Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🏷️ feat: Activity Groups With Fast-Model Headers (#14391)

Danny Avila7b6900d5562a
diff --git a/api/app/clients/BaseClient.js b/api/app/clients/BaseClient.js
index 5f426a56c9..c97dbb25b6 100644
--- a/api/app/clients/BaseClient.js
+++ b/api/app/clients/BaseClient.js
@@ -1171,6 +1171,8 @@ class BaseClient {
!item.type ||
item.type === ContentTypes.THINK ||
item.type === ContentTypes.ERROR ||
+ // UI-only progress headers — never model input, never billed output
+ item.type === ContentTypes.ACTIVITY_LABEL ||
item.type === ContentTypes.IMAGE_URL
) {
continue;
diff --git a/api/app/clients/prompts/formatMessages.js b/api/app/clients/prompts/formatMessages.js
index 29d4841b4c..24af946ff7 100644
--- a/api/app/clients/prompts/formatMessages.js
+++ b/api/app/clients/prompts/formatMessages.js
@@ -271,7 +271,12 @@ const formatAgentMessages = (payload) => {
* attaching to the pre-steer one would emit its ToolMessage after
* the HumanMessage while the call sat before it (invalid order). */
lastAIMessage = null;
- } else if (part.type === ContentTypes.ERROR || part.type === ContentTypes.AGENT_UPDATE) {
+ } else if (
+ part.type === ContentTypes.ERROR ||
+ part.type === ContentTypes.AGENT_UPDATE ||
+ part.type === ContentTypes.ACTIVITY_LABEL
+ ) {
+ // ACTIVITY_LABEL parts are UI-only progress notes — never model input.
continue;
} else {
currentContent.push(part);
diff --git a/api/server/controllers/agents/__tests__/openai.spec.js b/api/server/controllers/agents/__tests__/openai.spec.js
index 8b6910fe35..57df19ef82 100644
--- a/api/server/controllers/agents/__tests__/openai.spec.js
+++ b/api/server/controllers/agents/__tests__/openai.spec.js
@@ -78,6 +78,10 @@ jest.mock('@librechat/agents', () => ({
}));
jest.mock('@librechat/api', () => ({
+ /** Pass-through: the controller strips UI-only activity-label parts
+ * before SDK formatting; the mock must expose it like any other used
+ * export or the call throws before the assertions run. */
+ stripActivityLabelParts: jest.fn((payload) => payload),
writeSSE: jest.fn(),
createRun: jest.fn().mockResolvedValue({
processStream: mockProcessStream,
diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.js
index 4bc6d19e7e..424c9d742d 100644
--- a/api/server/controllers/agents/__tests__/responses.unit.spec.js
+++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js
@@ -84,6 +84,10 @@ jest.mock('@librechat/agents', () => ({
}));
jest.mock('@librechat/api', () => ({
+ /** Pass-through: the controller strips UI-only activity-label parts
+ * before SDK formatting; the mock must expose it like any other used
+ * export or the call throws before the assertions run. */
+ stripActivityLabelParts: jest.fn((payload) => payload),
createRun: jest.fn().mockResolvedValue({
processStream: jest.fn().mockResolvedValue(undefined),
}),
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index f1cb8c783a..c450884165 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -51,6 +51,13 @@ const {
isSteeringSupported,
buildSteerMedia,
stampSteerPartMedia,
+ createActivityLabelWiring,
+ resolveActivityConfig,
+ getCustomEndpointConfig,
+ mapCollectedMetadataToUsage,
+ resolveActivityLabelModel,
+ settlePendingLabelFills,
+ stripActivityLabelParts,
getRequestMemories,
getMemoryAgentId,
createMemoryProcessor,
@@ -79,6 +86,7 @@ const {
maybePrewarmCodeSandbox,
} = require('@librechat/api');
const {
+ Run,
Callback,
Providers,
TitleMethod,
@@ -89,6 +97,7 @@ const {
const {
Constants,
SteerEvents,
+ ActivityLabelEvents,
UsageEvents,
Permissions,
VisionModes,
@@ -341,6 +350,571 @@ class AgentClient extends BaseClient {
setOptions(_options) {}
+ /**
+ * Resolve provider + client options for the
+ * tool-batch summary model. Same resolution path as titleConvo minus the
+ * title-specific branches. Model precedence: the endpoint's
+ * `activityModel` > its `titleModel` > the agent's own model, on the
+ * endpoint named by `activityEndpoint` (default: the agent's).
+ */
+ async resolveActivityLabelLLM() {
+ /** Memoized per response: resolution reads provider config and can hit the
+ * database for user keys, and nothing it depends on changes between
+ * batches of the same run — so re-resolving on every batch (twice, with
+ * usage accounting) is repeated credential work for an identical result.
+ * The promise is cached rather than the value so concurrent batches share
+ * one in-flight resolution. */
+ this.activityLabelLLMPromise =
+ this.activityLabelLLMPromise ??
+ resolveActivityLabelModel({
+ req: this.options.req,
+ agent: this.options.agent,
+ /** Same public-endpoint-first field resolution as the wiring gate. */
+ publicEndpoint: this.options.endpoint,
+ ids: {
+ messageId: this.responseMessageId,
+ conversationId: this.conversationId,
+ parentMessageId: this.parentMessageId,
+ },
+ db: { getUserKey: db.getUserKey, getUserKeyValues: db.getUserKeyValues },
+ }).catch((error) => {
+ /** Never cache a rejection: a transient credential read failure would
+ * otherwise disable labels for the rest of the response. */
+ this.activityLabelLLMPromise = null;
+ throw error;
+ });
+ return this.activityLabelLLMPromise;
+ }
+
+ /**
+ * Bills the label call and folds its usage into the response rollup with
+ * an `activity-label` tag (subagent precedent) so `metadata.usage` and the
+ * live cost gauge reflect it. Tagged, so it is not a PRIMARY usage event
+ * and cannot disturb the context-snapshot pairing in buildResponseMetadata.
+ */
+ async recordActivityLabelUsage(
+ collectedMetadata,
+ model,
+ endpointTokenConfig,
+ sameEndpoint,
+ /** Optional suppression gate, defaulting open. The hook-driven paths
+ * deliberately pass nothing: they invoke accounting ONLY for a
+ * COMMITTED fill, and a committed (visible) label must bill even when
+ * its scope closed during the durable emit — the commit flag, not the
+ * scope, is the billing authority. */
+ scopeOpen = () => true,
+ /** The LABEL endpoint's provider — cost math needs it to know whether
+ * cache tokens are folded into `input_tokens` (additive providers like
+ * Bedrock keep them separate). */
+ provider = undefined,
+ /** Lazy `() => ({ promptText, completionText })` fallback. When the
+ * provider omits usage metadata entirely, labels bill by ESTIMATE —
+ * the title convention — from locally counted text rather than going
+ * unbilled. Invoked only when no entry carries a real token count. */
+ estimate = undefined,
+ ) {
+ const appConfig = this.options.req?.config;
+ /** Provider ON EVERY ENTRY, not just the streamed event: `splitUsage`
+ * keys additive-vs-subset cache math on `usage.provider`, and an
+ * unknown provider takes the additive branch — for Anthropic/OpenAI
+ * (cache already inside `input_tokens`) that re-adds cache_read and
+ * cache_creation on top, double-charging the balance while the
+ * streamed cost (which carries the provider) disagrees. */
+ let collectedUsage = mapCollectedMetadataToUsage(collectedMetadata).map((usage) =>
+ provider != null ? { ...usage, provider } : usage,
+ );
+ const hasRealUsage = collectedUsage.some(
+ (usage) => usage.input_tokens != null || usage.output_tokens != null,
+ );
+ if (!hasRealUsage && typeof estimate === 'function') {
+ try {
+ const { promptText = '', completionText = '' } = estimate() ?? {};
+ const [input_tokens, output_tokens] = await Promise.all([
+ countTokens(promptText),
+ countTokens(completionText),
+ ]);
+ collectedUsage = [
+ provider != null
+ ? { input_tokens, output_tokens, provider }
+ : { input_tokens, output_tokens },
+ ];
+ } catch (err) {
+ logger.warn(
+ `[AgentClient] Failed to estimate activity-label usage: ${err?.message ?? err}`,
+ );
+ }
+ }
+ if (
+ collectedUsage.length === 0 ||
+ !collectedUsage.some((usage) => usage.input_tokens != null || usage.output_tokens != null)
+ ) {
+ return;
+ }
+ if (!scopeOpen()) {
+ return;
+ }
+ const streamId = this.options.req?._resumableStreamId || null;
+ const includeCost = this.options.req?.config?.interfaceConfig?.contextCost === true;
+ /** Cross-endpoint labels (`activityEndpoint`) price with THEIR endpoint's
+ * rates. `undefined` is a MEANINGFUL result for a built-in label endpoint
+ * (built-ins price from the shared table, not a per-endpoint map), so it
+ * must not fall through to the agent's custom rates — a custom primary
+ * pointing `activityEndpoint` at a built-in would bill the label at its
+ * own rates. Only inherit when the label actually runs on the agent's
+ * endpoint. */
+ const labelTokenConfig = sameEndpoint
+ ? (endpointTokenConfig ?? this.options.endpointTokenConfig)
+ : endpointTokenConfig;
+ for (const usage of collectedUsage) {
+ /** `seq` is normally a position in `collectedUsage` (each emitter
+ * pushes, then emits with the new length). Label usage is billed
+ * separately and never appended there, so it has no position: any
+ * positive value eventually collides with a real one, and the client
+ * dedupes on `runId:seq`. Labels therefore occupy a NEGATIVE seq
+ * namespace that positional sequences can never reach. The key is
+ * only used for Set membership, so the sign is inert. */
+ this.activityLabelUsageSeq = (this.activityLabelUsageSeq ?? 0) + 1;
+ const data = {
+ input_tokens: usage.input_tokens,
+ output_tokens: usage.output_tokens,
+ /** Cache tokens ride along (subagent-event shape) so display and
+ * aggregation price cached label calls at cache rates. */
+ ...(usage.input_token_details != null && {
+ input_token_details: usage.input_token_details,
+ }),
+ ...(provider != null && { provider }),
+ model,
+ usage_type: 'activity-label',
+ /**
+ * Scoped to the GENERATION, not just the response. Editing one
+ * assistant response reuses its `responseMessageId` while each fresh
+ * server generation restarts `activityLabelUsageSeq`, so a second
+ * edit re-emitted `<responseId>:-1` and the client — which dedupes on
+ * exactly `runId:seq` — discarded the newer usage even though its
+ * balance transaction was still written. `jobCreatedAt` is the run's
+ * own epoch: stable across reconnects and HITL resumes of one
+ * generation, distinct between generations.
+ */
+ runId:
+ this.jobCreatedAt != null
+ ? `${this.responseMessageId}:${this.jobCreatedAt}`
+ : this.responseMessageId,
+ seq: -this.activityLabelUsageSeq,
+ /** Cost coverage is all-or-nothing in `aggregateEmittedUsage`: an
+ * event without `cost` suppresses the whole response's cost when
+ * `interface.contextCost` is on. */
+ cost: includeCost
+ ? computeUsageCostUSD(
+ { ...usage, model, provider },
+ { getMultiplier: db.getMultiplier, getCacheMultiplier: db.getCacheMultiplier },
+ labelTokenConfig,
+ )
+ : undefined,
+ };
+ /** Fold into the response rollup synchronously, then stream it like
+ * primary/subagent usage so the live session gauge stays honest.
+ * Retained and flushed with the subagent emits so job cleanup cannot
+ * race the persist. */
+ this.usageEmitSink?.push(data);
+ if (streamId) {
+ const emit = GenerationJobManager.emitChunk(
+ streamId,
+ {
+ event: UsageEvents.ON_TOKEN_USAGE,
+ data,
+ },
+ /** Same epoch scoping as the label event: this usage is recorded
+ * from a detached generation and must not bill against whichever
+ * generation replaced it. */
+ { expectedCreatedAt: this.jobCreatedAt },
+ ).catch((err) => {
+ logger.warn(`[AgentClient] Failed to emit activity-label usage: ${err?.message ?? err}`);
+ });
+ this.pendingSubagentEmits.push(emit);
+ }
+ }
+ await this.recordCollectedUsage({
+ collectedUsage,
+ context: 'activity-label',
+ model,
+ endpointTokenConfig: labelTokenConfig,
+ /** The label ran elsewhere, so its config governs even when undefined. */
+ crossEndpoint: sameEndpoint === false,
+ balance: getBalanceConfig(appConfig),
+ transactions: getTransactionsConfig(appConfig),
+ messageId: this.responseMessageId,
+ /** Billed, but NOT the response's stream usage — see the parameter. */
+ updateStreamUsage: false,
+ }).catch((err) => {
+ logger.error(
+ '[api/server/controllers/agents/client.js #recordActivityLabelUsage] Error recording usage',
+ err,
+ );
+ });
+ }
+
+ /**
+ * Bridges label generation to the SDK's `run.generateActivityLabel()` so
+ * the fast-model call is Langfuse-traced under the conversation's session
+ * (thread_id) with its own tags — never as an orphan trace. Returns null
+ * when the label could not be generated.
+ */
+ async generateActivityLabelViaRun({
+ entries,
+ context,
+ previousLabels,
+ traceSeed,
+ signal,
+ charLimit,
+ prompt,
+ executingAgentId,
+ deferUsage,
+ }) {
+ /** Version gating happens at wiring time via the `sdkCapable` prototype
+ * probe, so this only catches a run that is missing or not yet built.
+ * Resolve `undefined` (not `null`) so the hook reads it as "this path
+ * cannot serve the request" and falls back to the direct model call;
+ * `null` would mean "ran, produced no label" and would leave the slot
+ * permanently empty. */
+ if (typeof this.run?.generateActivityLabel !== 'function') {
+ return undefined;
+ }
+ const { provider, clientOptions, endpointTokenConfig, sameEndpoint } =
+ await this.resolveActivityLabelLLM();
+ const { handleLLMEnd, collected: collectedMetadata } = createMetadataAggregator();
+ /**
+ * NO scope gate here: the hook invokes this ONLY for a COMMITTED fill,
+ * and the commit flag is the single billing authority. A scope that
+ * closes while the fill's durable emit is in flight does not un-commit
+ * the label — it is persisted and visible — so gating on the scope here
+ * turned that race into a completed provider call escaping both the
+ * label charge and the primary abort accounting. The reverse direction
+ * (billed but never shown) is enforced by the commit gate itself: a
+ * dropped fill never reaches this callback.
+ */
+ /**
+ * The PROMPT THE SDK ACTUALLY SENT, captured at chain start. The hook's
+ * estimate thunk carries this module's locally built prompt — same
+ * entries and instruction but different framing — so estimated billing
+ * on this path would count a prompt that was never sent. When capture
+ * succeeded, it replaces the thunk's promptText.
+ */
+ let sdkPromptText;
+ const capturePrompt = {
+ handleLLMStart: (_llm, prompts) => {
+ sdkPromptText = Array.isArray(prompts) ? prompts.join('\n') : undefined;
+ },
+ handleChatModelStart: (_llm, messages) => {
+ try {
+ sdkPromptText = (messages ?? [])
+ .flat()
+ .map((message) =>
+ typeof message?.content === 'string'
+ ? message.content
+ : JSON.stringify(message?.content ?? ''),
+ )
+ .join('\n');
+ } catch {
+ /** Estimation falls back to the local approximation. */
+ }
+ },
+ };
+ const recordUsage = async (estimate) => {
+ const refined =
+ typeof estimate === 'function'
+ ? () => {
+ const base = estimate() ?? {};
+ return sdkPromptText != null && sdkPromptText.length > 0
+ ? { ...base, promptText: sdkPromptText }
+ : base;
+ }
+ : estimate;
+ await this.recordActivityLabelUsage(
+ collectedMetadata,
+ clientOptions.model,
+ endpointTokenConfig,
+ sameEndpoint,
+ undefined,
+ provider,
+ refined,
+ );
+ };
+ /**
+ * Accounting is DEFERRED to the hook, which runs it only after the slot
+ * commit settles. Awaiting it here (pre-fill) let the settlement window
+ * expire during the balance write: the charge landed, then the fill was
+ * dropped as out-of-scope — billed, never shown. Registered before the
+ * call so a mid-call throw still bills whatever metadata the provider
+ * returned, exactly like the old `finally` did.
+ */
+ let usageDeferred = false;
+ if (typeof deferUsage === 'function') {
+ usageDeferred = true;
+ deferUsage(recordUsage);
+ }
+ try {
+ const { label } = await this.run.generateActivityLabel({
+ provider,
+ clientOptions,
+ entries: entries.map(({ toolName, toolInput, toolOutput, error, status }) => ({
+ toolName,
+ toolInput,
+ toolOutput,
+ error,
+ status,
+ })),
+ thinkingExcerpts: context.thinkingExcerpts,
+ lastAssistantText: context.lastAssistantText,
+ ...(previousLabels != null && { previousLabels }),
+ traceSeed,
+ charLimit,
+ /** Selects the EXECUTING agent's Langfuse metadata and, more
+ * importantly, its tool-output redaction policy. Omitting it lets a
+ * handoff's activity be traced and redacted under the default
+ * agent's configuration, bypassing a stricter per-agent policy. */
+ ...(executingAgentId != null && { agentId: executingAgentId }),
+ /** The wiring always supplies one (the yaml `activityPrompt` when
+ * set, else this repo's instruction). Falling through to the SDK's
+ * built-in prompt would silently use a different register. */
+ ...((prompt ?? this.activityLabelPrompt) != null && {
+ prompt: prompt ?? this.activityLabelPrompt,
+ }),
+ chainOptions: {
+ signal,
+ callbacks: [{ handleLLMEnd, ...capturePrompt }],
+ configurable: {
+ thread_id: this.conversationId,
+ user_id: this.user ?? this.options.req?.user?.id,
+ },
+ },
+ });
+ return label ?? null;
+ } finally {
+ /** Safety net for a caller that did not defer (none in-tree): the old
+ * inline accounting, still scope-gated. */
+ if (!usageDeferred) {
+ await recordUsage();
+ }
+ }
+ }
+
+ /** Bounded settle for in-flight label fills before finalization. On
+ * timeout the label scope is closed and its abort controller fired, so a
+ * straggler cannot mutate the saved response or emit into a dead job. */
+ async settleActivityLabels(timeoutMs = 3000) {
+ /** Detached even when nothing settled: the wiring attaches its abort
+ * listener at BUILD time, and a segment can end without a single claim
+ * (text-only, or handoff batches, which skip labels) — the early
+ * return below would otherwise leave that listener accumulating across
+ * HITL approval cycles on the shared job signal. Idempotent. */
+ const detachScopeListeners = () => {
+ for (const scope of this.activityLabelScopes ?? []) {
+ scope.detach?.();
+ }
+ };
+ const pending = this.pendingActivityLabelFills;
+ if (!pending || pending.length === 0) {
+ detachScopeListeners();
+ return;
+ }
+ this.pendingActivityLabelFills = [];
+ await settlePendingLabelFills(pending, timeoutMs, () => {
+ /** Close EVERY generation's scope: a pre-pause wiring's straggler must
+ * stay closed even though a resume built a newer one. */
+ for (const scope of this.activityLabelScopes ?? []) {
+ scope.closed = true;
+ scope.abort.abort();
+ }
+ });
+ detachScopeListeners();
+ }
+
+ /**
+ * Activity-label wiring. At each batch boundary the hook synchronously
+ * claims a live content slot (steering's index-offset pattern: push
+ * placeholder with deterministic counts, bump the shared offset so
+ * subsequent SDK indices land past it) and fills it when the fast-model
+ * label resolves. Both states reach the live client via the dedicated
+ * `on_activity_label` event; failures leave the counts-only part.
+ * @param {string | undefined} streamId
+ */
+ buildActivityLabelWiring(streamId, abortSignal) {
+ if (!streamId) {
+ return undefined;
+ }
+ /** Per-endpoint opt-in via `activityLabel: true` in librechat.yaml,
+ * resolved the same way the title options are (endpoints.all > named
+ * endpoint > custom endpoint config). Custom endpoints live in the
+ * `endpoints.custom` ARRAY, so their settings are only visible through
+ * the matched entry — without it every custom endpoint reads as
+ * disabled. */
+ const agentEndpoint = this.options.agent?.endpoint ?? '';
+ const appConfigForActivity = this.options.req?.config;
+ let customEndpointConfig;
+ try {
+ customEndpointConfig = getCustomEndpointConfig({
+ endpoint: agentEndpoint,
+ appConfig: appConfigForActivity,
+ });
+ } catch {
+ customEndpointConfig = undefined;
+ }
+ const activityConfig = resolveActivityConfig(
+ appConfigForActivity,
+ agentEndpoint,
+ customEndpointConfig,
+ /** The PUBLIC endpoint (`agents`): `initializeAgent` rewrites
+ * `agent.endpoint` to the backing provider, so without this an
+ * admin's `endpoints.agents.activityLabel: true` reads the
+ * provider's block instead and the feature stays off. */
+ this.options.endpoint,
+ );
+ if (!activityConfig.enabled) {
+ return undefined;
+ }
+ this.activityLabelPrompt = activityConfig.prompt;
+ /**
+ * Mark the job so a resume can reconcile label gaps without probing
+ * content. Retried rather than fire-and-forget: this flag GATES that
+ * reconciliation, and it is a separate write from the durable label
+ * append — so a single lost write silently drops a label that the label
+ * content itself recorded perfectly well. One retry costs nothing at run
+ * setup and removes the only realistic way the gate goes stale.
+ */
+ /** Retained (not fire-and-forget): the RUN START awaits this persist
+ * (chatCompletion/resumeCompletion, before processStream/resume), so
+ * the flag is durable before any batch can claim a label — closing the
+ * immediate-reconnect race WITHOUT delaying the claim-time reservation
+ * emit, whose ordering against shifted SDK indices is load-bearing.
+ * The chain settles on failure (warned retry), so a lost write can
+ * never wedge run startup. */
+ this.activityLabelsMarkedPromise = GenerationJobManager.markActivityLabels(streamId).catch(() =>
+ GenerationJobManager.markActivityLabels(streamId).catch(() => {
+ logger.warn(
+ `[AgentClient] Could not flag activity labels for ${streamId}; a label resolving during a resume gap may not be reconciled.`,
+ );
+ }),
+ );
+ /** SDK support probe (steering-style): the Run method and the formatter
+ * replay skip ship together, so method presence is the capability. */
+ const sdkCapable = typeof Run?.prototype?.generateActivityLabel === 'function';
+ /** Label-scoped abort: fired when settle times out so a straggling
+ * generation stops burning provider time for a finalized response.
+ * Chained to the run signal so a user abort still cancels labels. */
+ /** Close state is PER WIRING, not per client: a HITL resume rebuilds the
+ * wiring, and resetting a shared instance flag would re-open closures
+ * from the pre-pause segment whose provider call ignored the abort.
+ * Scopes are retained so settle closes every generation, past included. */
+ const labelScope = { closed: false, abort: new AbortController() };
+ this.activityLabelScopes = this.activityLabelScopes ?? [];
+ this.activityLabelScopes.push(labelScope);
+ /** Seed the usage sequence past the labels already on this response.
+ * `runId` is the response message id, so a HITL resume — which builds a
+ * NEW client for the SAME response — would otherwise restart at -1 and
+ * the client's `runId:seq` deduper would discard the post-approval
+ * label's usage as already counted. Each label generation is a single
+ * non-streaming invoke, so one existing label part == one consumed seq. */
+ this.activityLabelUsageSeq =
+ this.activityLabelUsageSeq ??
+ (this.contentParts ?? []).filter((part) => part?.type === ContentTypes.ACTIVITY_LABEL).length;
+ this.activityLabelAbort = labelScope.abort;
+ /** An abort CLOSES the scope, not just cancels the call. The rejected
+ * generation still runs its catch and calls `fill(null)`; with the scope
+ * merely aborted that fill would emit — and by then the next generation
+ * may already own the stream, so the event would land an index from the
+ * abandoned response onto the new one. */
+ const closeOnAbort = () => {
+ labelScope.closed = true;
+ labelScope.abort.abort();
+ };
+ if (abortSignal != null) {
+ if (abortSignal.aborted) {
+ closeOnAbort();
+ } else {
+ abortSignal.addEventListener('abort', closeOnAbort, { once: true });
+ /** Detached once this segment settles: HITL runs rebuild a wiring
+ * per approval cycle on the SAME job signal, and `once` only
+ * removes the listener if an abort actually fires — long
+ * multi-approval runs would otherwise accumulate obsolete
+ * closures toward the listener-limit warning. */
+ labelScope.detach = () => abortSignal.removeEventListener('abort', closeOnAbort);
+ }
+ }
+ /** Thin wrapper: slot claiming, lane stamping, emit ordering, and settle
+ * tracking live in `createActivityLabelWiring` (packages/api, TS). */
+ return createActivityLabelWiring({
+ maxPerRun: activityConfig.maxPerRun,
+ charLimit: activityConfig.charLimit,
+ prompt: activityConfig.prompt,
+ abortSignal: labelScope.abort.signal,
+ isClosed: () => labelScope.closed,
+ getContentParts: () => this.contentParts,
+ bumpIndexOffset: () => {
+ this.steerOffsetState.offset += 1;
+ },
+ /** Emits IMMEDIATELY — never sequenced behind the flag persist. The
+ * claim has already bumped the shared index offset, so delaying the
+ * reservation while shifted SDK chunks persist would let a
+ * cross-instance reconnect reconstruct a hole, compact it, and have
+ * the late label event overwrite the part that moved into its index.
+ * Flag ordering is guaranteed upstream instead: run start awaits the
+ * persist, so the flag is durable before any batch can claim. */
+ emitLabelEvent: (index, part) =>
+ GenerationJobManager.emitChunk(
+ streamId,
+ {
+ event: ActivityLabelEvents.ON_ACTIVITY_LABEL,
+ data: {
+ index,
+ part,
+ responseMessageId: this.responseMessageId,
+ conversationId: this.conversationId,
+ },
+ },
+ /** Label generation is detached and can outlive its generation, so
+ * the emit is scoped to the epoch that claimed the index. Without
+ * it a straggler from a replaced generation lands its old index on
+ * the new response — invisibly, since an empty label renders
+ * nothing — overwriting whatever occupies that slot. */
+ { durable: true, expectedCreatedAt: this.jobCreatedAt },
+ ),
+ trackPendingFill: (fillDone) => {
+ this.pendingActivityLabelFills = this.pendingActivityLabelFills ?? [];
+ this.pendingActivityLabelFills.push(fillDone);
+ },
+ resolveLLM: () => this.resolveActivityLabelLLM(),
+ /** Per-generation usage accounting for the direct fallback path;
+ * the SDK bridge records its own via chainOptions callbacks. */
+ getInvokeCallbacks: () => {
+ const { handleLLMEnd, collected } = createMetadataAggregator();
+ return {
+ callbacks: [{ handleLLMEnd }],
+ collect: async (estimate) => {
+ const { provider, clientOptions, endpointTokenConfig, sameEndpoint } =
+ await this.resolveActivityLabelLLM();
+ await this.recordActivityLabelUsage(
+ collected,
+ clientOptions.model,
+ endpointTokenConfig,
+ sameEndpoint,
+ /** No scope gate — the hook invokes collect ONLY for a
+ * COMMITTED fill (the billing authority), and a scope that
+ * closes during the fill's durable emit must not let a
+ * visible label escape its charge. Dropped fills never
+ * reach this callback. */
+ undefined,
+ provider,
+ estimate,
+ );
+ },
+ };
+ },
+ ...(sdkCapable && {
+ generateLabel: (payload) => this.generateActivityLabelViaRun(payload),
+ }),
+ });
+ }
+
/**
* `AgentClient` is not opinionated about vision requests, so we don't do anything here
* @param {MongoFile[]} attachments
@@ -1254,7 +1828,41 @@ class AgentClient extends BaseClient {
transactions,
context = 'message',
collectedUsage = this.collectedUsage,
+ /**
+ * Rates for usage that did NOT run on the agent's endpoint — currently
+ * activity labels pointed at a different `activityEndpoint`. Without it
+ * the caller's config was dropped here and the balance transaction was
+ * written at the primary agent's rates while the UI cost was computed at
+ * the label's, so the two disagreed. `undefined` keeps the agent default.
+ */
+ endpointTokenConfig,
+ /**
+ * True when this usage ran on a DIFFERENT endpoint than the agent, making
+ * `endpointTokenConfig` authoritative even when it is `undefined` (a
+ * built-in endpoint prices from the shared table). Presence of the value
+ * cannot express that, which is why the caller states it outright.
+ */
+ crossEndpoint = false,
+ /**
+ * Whether this recording owns `getStreamUsage()`. Only the PRIMARY
+ * generation does. Secondary usage (activity labels) must still be
+ * billed, but writing it here would hand `BaseClient` the label's token
+ * counts as the assistant response's authoritative total — and because
+ * the primary call returns early when it collected nothing, the wrong
+ * value would never be replaced, suppressing the text-based token
+ * fallback and leaving the real generation unbilled.
+ */
+ updateStreamUsage = true,
}) {
+ /** Per-agent resolution keys off the AGENT's config map, which cannot
+ * describe a label running on a different endpoint — so an explicit
+ * config wins outright rather than being second-guessed per usage row.
+ *
+ * Keyed on the caller's discriminator, NOT on `endpointTokenConfig !==
+ * undefined`: a built-in label endpoint prices from the shared table, so
+ * `undefined` is its meaningful value. Reading that as "no override" is
+ * what silently restored the primary's custom rates. */
+ const overrideTokenConfig = crossEndpoint === true;
const result = await recordCollectedUsage(
{
spendTokens: db.spendTokens,
@@ -1271,12 +1879,16 @@ class AgentClient extends BaseClient {
messageId: this.responseMessageId,
balance,
transactions,
- endpointTokenConfig: this.options.endpointTokenConfig,
- resolveEndpointTokenConfig: (usage) => this.resolveAgentEndpointTokenConfig(usage),
+ endpointTokenConfig: overrideTokenConfig
+ ? endpointTokenConfig
+ : this.options.endpointTokenConfig,
+ ...(overrideTokenConfig
+ ? {}
+ : { resolveEndpointTokenConfig: (usage) => this.resolveAgentEndpointTokenConfig(usage) }),
},
);
- if (result) {
+ if (result && updateStreamUsage) {
this.usage = result;
}
}
@@ -1402,6 +2014,9 @@ class AgentClient extends BaseClient {
// Steer parts are user speech, not intermediate agent output — dropping
// one would erase the user's words from the persisted turn.
part.type === ContentTypes.STEER ||
+ // Activity labels summarize the hidden intermediate outputs — exactly
+ // the affordance hide_sequential_outputs wants to keep visible.
+ part.type === ContentTypes.ACTIVITY_LABEL ||
part.tool_call_ids,
);
}
@@ -1673,7 +2288,7 @@ class AgentClient extends BaseClient {
summary: initialSummary,
boundaryTokenAdjustment,
} = formatAgentMessages(
- payload,
+ stripActivityLabelParts(payload),
this.indexTokenCountMap,
toolSet,
skillPrimeResult?.skills,
@@ -1747,7 +2362,7 @@ class AgentClient extends BaseClient {
const memoryMessages =
this.processMemory && this.memoryPayload
? formatAgentMessages(
- this.memoryPayload,
+ stripActivityLabelParts(this.memoryPayload),
undefined,
toolSet,
skillPrimeResult?.skills,
@@ -1847,6 +2462,7 @@ class AgentClient extends BaseClient {
// boundary and inject them into graph state. The offset wrapper
// shifts SDK content indices past any spliced steer parts.
steering: this.buildSteerWiring(streamId),
+ activityLabel: this.buildActivityLabelWiring(streamId, abortController.signal),
indexTokenCountMap,
initialSummary,
initialSessions,
@@ -1912,6 +2528,13 @@ class AgentClient extends BaseClient {
config.configurable.last_agent_id = agents[agents.length - 1].id;
this.options.startupTelemetry?.mark('stream_processing_started');
+ /** Flag durable BEFORE the run can claim a label: gap reconciliation
+ * is gated on it, and ordering it here (one settled-on-failure
+ * await) keeps the claim-time reservation emit immediate — see
+ * `emitLabelEvent` in buildActivityLabelWiring. */
+ if (this.activityLabelsMarkedPromise != null) {
+ await this.activityLabelsMarkedPromise;
+ }
await run.processStream({ messages }, config, {
callbacks: {
[Callback.TOOL_ERROR]: logToolError,
@@ -1959,6 +2582,18 @@ class AgentClient extends BaseClient {
* below the reply on finalize. Post-run unshift keeps the final
* responseMessage.content in the right order.
*/
+ /**
+ * Settle in-flight label fills BEFORE the content is reshaped below.
+ * A fill emits its claim-time index; the skill-card unshift and the
+ * hide-sequential filter both shift positions, so a fill landing after
+ * either would emit a stale index — and a client that already synced
+ * the reshaped array applies it onto the wrong part. A paused turn
+ * never gets a final event to repair that. Costs nothing extra: these
+ * are the same promises the finalization settle would wait on, and
+ * that later call then sees an empty pending list.
+ */
+ await this.settleActivityLabels();
+
const manualPrimed = this.options.agent?.manualSkillPrimes ?? [];
if (manualPrimed.length > 0) {
const runId = this.responseMessageId ?? 'skill-prime';
@@ -2004,6 +2639,7 @@ class AgentClient extends BaseClient {
}
this.finalizeSubagentContent();
+ await this.settleActivityLabels();
/** Flush subagent usage emits the sink fired without awaiting, so their
* persist/publish completes before we return and the job is cleaned up
@@ -2183,6 +2819,9 @@ class AgentClient extends BaseClient {
// Steering stays live across a pause/resume cycle: steers queued while
// the resumed segment runs drain at its tool-batch boundaries.
steering: this.buildSteerWiring(streamId),
+ // Activity labels likewise survive pause/resume: post-resume tool
+ // batches keep claiming slots and generating group headers.
+ activityLabel: this.buildActivityLabelWiring(streamId, abortController.signal),
// Replay deferred tools discovered before the pause. With `messages: []` the
// discovery scan finds nothing, so a deferred tool the paused call targets
// would be absent from the rebuilt toolMap; these names (captured at pause)
@@ -2247,6 +2886,10 @@ class AgentClient extends BaseClient {
/** @deprecated Agent Chain */
config.configurable.last_agent_id = agents[agents.length - 1].id;
+ /** Same flag-before-run ordering as chatCompletion's processStream. */
+ if (this.activityLabelsMarkedPromise != null) {
+ await this.activityLabelsMarkedPromise;
+ }
await run.resume(
resumeValue,
config,
@@ -2260,7 +2903,11 @@ class AgentClient extends BaseClient {
// question). Re-arm the same interrupt gate so the cycle can repeat.
await this.handleRunInterrupt(run, streamId);
- // Mirror chatCompletion: strip hidden intermediate sequential-agent content
+ // Mirror chatCompletion: settle label fills before the filter below can
+ // shift part positions out from under an in-flight fill's claimed index.
+ await this.settleActivityLabels();
+
+ // Strip hidden intermediate sequential-agent content
// before resume finalize/re-pause persistence reads `this.contentParts`, so a
// resumed sequential chain doesn't persist/emit outputs hide_sequential_outputs
// is meant to hide.
@@ -2297,6 +2944,7 @@ class AgentClient extends BaseClient {
}
this.finalizeSubagentContent();
+ await this.settleActivityLabels();
if (this.pendingSubagentEmits.length > 0) {
await Promise.allSettled(this.pendingSubagentEmits);
diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.js
index 6c9eb0a0ff..848d995502 100644
--- a/api/server/controllers/agents/openai.js
+++ b/api/server/controllers/agents/openai.js
@@ -35,6 +35,7 @@ const {
resolveAgentScopedSkillIds,
createOpenAIContentAggregator,
isChatCompletionValidationFailure,
+ stripActivityLabelParts,
} = require('@librechat/api');
const {
buildSummarizationHandlers,
@@ -524,7 +525,7 @@ const OpenAIChatCompletionController = async (req, res) => {
const openaiMessages = convertMessages(request.messages);
const toolSet = buildToolSet(primaryConfig);
- const formatted = formatAgentMessages(openaiMessages, {}, toolSet);
+ const formatted = formatAgentMessages(stripActivityLabelParts(openaiMessages), {}, toolSet);
const formattedMessages = formatted.messages;
const initialSummary = formatted.summary;
let indexTokenCountMap = formatted.indexTokenCountMap;
diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.js
index a9551ff66d..2ef58e9cda 100644
--- a/api/server/controllers/agents/responses.js
+++ b/api/server/controllers/agents/responses.js
@@ -46,6 +46,7 @@ const {
sendResponsesErrorResponse,
createResponsesEventHandlers,
createAggregatorEventHandlers,
+ stripActivityLabelParts,
} = require('@librechat/api');
const {
createResponsesToolEndCallback,
@@ -629,7 +630,7 @@ const createResponse = async (req, res) => {
const allMessages = [...previousMessages, ...inputMessages];
const toolSet = buildToolSet(primaryConfig);
- const formatted = formatAgentMessages(allMessages, {}, toolSet);
+ const formatted = formatAgentMessages(stripActivityLabelParts(allMessages), {}, toolSet);
const formattedMessages = formatted.messages;
const initialSummary = formatted.summary;
let indexTokenCountMap = formatted.indexTokenCountMap;
diff --git a/client/src/components/Chat/Messages/Content/ContentParts.tsx b/client/src/components/Chat/Messages/Content/ContentParts.tsx
index d017778585..116f51f379 100644
--- a/client/src/components/Chat/Messages/Content/ContentParts.tsx
+++ b/client/src/components/Chat/Messages/Content/ContentParts.tsx
@@ -11,6 +11,7 @@ import type { ToolCallGroupExpansionState } from './ToolCallGroup';
import { mapAttachments, filterAttachmentsForPart, groupSequentialToolCalls } from '~/utils';
import { ParallelContentRenderer, type PartWithIndex } from './ParallelContent';
import { EditTextPart, EmptyText, AgentUpdate } from './Parts';
+import { lastVisibleContentIdx } from '~/utils/activityLabels';
import { MessageContext, SearchContext } from '~/Providers';
import PendingSkillCall from './Parts/PendingSkillCall';
import ApprovalProvider from './ApprovalContext';
@@ -31,11 +32,24 @@ const getToolGroupId = (parts: PartWithIndex[], fallbackScope: number): string =
if (!firstPart) {
return 'empty';
}
- const toolCallId = getToolCallId(firstPart.part);
- if (toolCallId) {
- return `tool:${toolCallId}`;
+ /** Keyed on the first TOOL CALL, not the first part. An activity label
+ * absorbs the block's leading THINK part when its text lands, so keying on
+ * `parts[0]` would flip the key mid-run — remounting the group and losing
+ * whatever the user had expanded. The tool calls themselves do not move. */
+ let firstToolIdx: number | undefined;
+ for (const { part, idx } of parts) {
+ const toolCallId = getToolCallId(part);
+ if (toolCallId) {
+ return `tool:${toolCallId}`;
+ }
+ if (firstToolIdx === undefined && part?.type === ContentTypes.TOOL_CALL) {
+ firstToolIdx = idx;
+ }
}
- return `fallback:${fallbackScope}:${firstPart.idx}`;
+ /** Same reasoning for id-less tool calls: anchor to the first TOOL entry's
+ * index rather than the block's first part, which shifts when reasoning is
+ * absorbed. Only a block with no tool call at all falls back to `parts[0]`. */
+ return `fallback:${fallbackScope}:${firstToolIdx ?? firstPart.idx}`;
};
type PartWithContextProps = {
@@ -422,7 +436,10 @@ const ContentParts = memo(function ContentParts({
const safeContent = content ?? [];
const showEmptyCursor = safeContent.length === 0 && effectiveIsSubmitting;
- const lastContentIdx = safeContent.length - 1;
+ /** Skips trailing BLANK label reservations — they render nothing, and
+ * counting one as last would strip the streaming cursor from the last
+ * VISIBLE part until the next delta. */
+ const lastContentIdx = lastVisibleContentIdx(safeContent);
// Parallel content: use dedicated renderer with columns (TMessageContentParts includes ContentMetadata)
const hasParallelContent = safeContent.some((part) => part?.groupId != null);
@@ -474,12 +491,20 @@ const ContentParts = memo(function ContentParts({
key={`tool-group-${groupId}`}
parts={group.parts}
isSubmitting={effectiveIsSubmitting}
- isLast={group.parts.some((p) => p.idx === lastContentIdx)}
+ /** The label part is CONSUMED into the header, not listed in
+ * `parts` — a filled label at the content tail must still
+ * mark its group as last or nothing holds the streaming
+ * cursor until the next delta. */
+ isLast={
+ group.parts.some((p) => p.idx === lastContentIdx) ||
+ group.labelPart?.idx === lastContentIdx
+ }
renderPart={renderGroupedPart}
lastContentIdx={lastContentIdx}
groupAttachments={group.groupAttachments}
initialExpansionState={toolGroupExpansionRef.current.get(groupId)}
onExpansionChange={(state) => handleGroupExpansionChange(groupId, state)}
+ labelPart={group.labelPart}
/>,
);
return nodes;
diff --git a/client/src/components/Chat/Messages/Content/ParallelContent.tsx b/client/src/components/Chat/Messages/Content/ParallelContent.tsx
index ea1805737a..0da7fc0dd0 100644
--- a/client/src/components/Chat/Messages/Content/ParallelContent.tsx
+++ b/client/src/components/Chat/Messages/Content/ParallelContent.tsx
@@ -1,5 +1,11 @@
import { memo, useMemo } from 'react';
+import { ContentTypes } from 'librechat-data-provider';
import type { TMessageContentParts, SearchResultData, TAttachment } from 'librechat-data-provider';
+import {
+ getActivityLabelPart,
+ getActivityLabelText,
+ lastVisibleContentIdx,
+} from '~/utils/activityLabels';
import MemoryArtifacts from './MemoryArtifacts';
import Sources from '~/components/Web/Sources';
import { SearchContext } from '~/Providers';
@@ -159,7 +165,17 @@ export const ParallelColumns = memo(function ParallelColumns({
}: ParallelColumnsProps) {
return (
<div className={cn('flex w-full flex-col gap-3 md:flex-row', 'sibling-content-group')}>
- {columns.map(({ agentId, parts: columnParts }, colIdx) => {
+ {columns.map(({ agentId, parts: allColumnParts }, colIdx) => {
+ /** Lanes render raw parts, so an activity label cannot become a
+ * collapsible header here (tracked separately). An UNFILLED one has
+ * nothing to render at all, and every batch now publishes its
+ * reservation immediately — so drop empty labels rather than emit a
+ * blank line into the column while generation is pending. */
+ const columnParts = allColumnParts.filter(
+ ({ part }) =>
+ part?.type !== ContentTypes.ACTIVITY_LABEL ||
+ getActivityLabelText(getActivityLabelPart(part)).length > 0,
+ );
// Show loading cursor if column has no content parts yet (empty array from placeholder)
const showLoadingCursor = isSubmitting && columnParts.length === 0;
@@ -231,7 +247,10 @@ export const ParallelContentRenderer = memo(function ParallelContentRenderer({
[content],
);
- const lastContentIdx = (content?.length ?? 0) - 1;
+ /** Same walk-back as `ContentParts`: a trailing BLANK label reservation is
+ * filtered out of every lane, so counting it as last would leave NO
+ * rendered part with the last-part cursor until the label fills. */
+ const lastContentIdx = lastVisibleContentIdx(content);
// Split sequential parts into before/after parallel sections
const { before, after } = useMemo(() => {
diff --git a/client/src/components/Chat/Messages/Content/Part.tsx b/client/src/components/Chat/Messages/Content/Part.tsx
index ef286c44ee..13c9f9d4da 100644
--- a/client/src/components/Chat/Messages/Content/Part.tsx
+++ b/client/src/components/Chat/Messages/Content/Part.tsx
@@ -23,13 +23,13 @@ import {
SubagentCall,
SteerPart,
} from './Parts';
+import { getCachedPreview, getActivityLabelPart, getActivityLabelText } from '~/utils';
import { getAskUserQuestionPart } from '~/utils/approval';
import AskUserQuestionCall from './AskUserQuestionCall';
import { isBashProgrammaticToolCall } from './routing';
import { ErrorMessage } from './MessageContent';
import AskUserQuestion from './AskUserQuestion';
import RetrievalCall from './RetrievalCall';
-import { getCachedPreview } from '~/utils';
import ToolApproval from './ToolApproval';
import AgentHandoff from './AgentHandoff';
import CodeAnalyze from './CodeAnalyze';
@@ -153,6 +153,22 @@ const Part = memo(function Part({
summarizing={part.summarizing}
/>
);
+ } else if (part.type === ContentTypes.ACTIVITY_LABEL) {
+ /** Orphan label (its block's parts were filtered/hidden): renders as a
+ * standalone line. Labeled blocks normally render via ToolCallGroup,
+ * which consumes the label part as the group header instead. */
+ const display = getActivityLabelText(getActivityLabelPart(part));
+ if (!display) {
+ return null;
+ }
+ const failed = part.status === 'failed' || part.status === 'partial';
+ return (
+ <div
+ className={`my-1 pl-1 text-sm italic ${failed ? 'text-amber-600 dark:text-amber-400' : 'text-text-secondary'}`}
+ >
+ {display}
+ </div>
+ );
} else if (part.type === ContentTypes.TOOL_CALL) {
const toolCall = part[ContentTypes.TOOL_CALL];
diff --git a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
index 5c386cc06d..cc43f3a924 100644
--- a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
@@ -10,10 +10,10 @@ import type {
} from 'librechat-data-provider';
import type { PartWithIndex } from './ParallelContent';
import { useLocalize, useExpandCollapse, scheduleMessageContentLayoutReconcile } from '~/hooks';
+import { cn, getToolDisplayLabel, getActivityLabelPart, getActivityLabelText } from '~/utils';
import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';
import { isBashProgrammaticToolCall } from './routing';
import { ASK_USER_QUESTION } from '~/utils/approval';
-import { cn, getToolDisplayLabel } from '~/utils';
import { StackedToolIcons } from './ToolOutput';
import { AttachmentGroup } from './Parts';
import store from '~/store';
@@ -107,6 +107,9 @@ interface ToolCallGroupProps {
groupAttachments?: TAttachment[];
initialExpansionState?: ToolCallGroupExpansionState;
onExpansionChange?: (state: ToolCallGroupExpansionState) => void;
+ /** Activity-label part terminating this block; when it carries generated
+ * text the header shows that text instead of the default tool summary. */
+ labelPart?: PartWithIndex;
}
export type ToolCallGroupExpansionState = {
@@ -123,6 +126,7 @@ export default function ToolCallGroup({
groupAttachments,
initialExpansionState,
onExpansionChange,
+ labelPart,
}: ToolCallGroupProps) {
const localize = useLocalize();
const mcpIconMap = useMCPIconMap();
@@ -130,19 +134,39 @@ export default function ToolCallGroup({
const rootRef = useRef<HTMLDivElement | null>(null);
const cancelLayoutReconcileRef = useRef<(() => void) | null>(null);
const retainedForPendingApprovalRef = useRef(false);
- const count = parts.length;
- const toolMetadata = useMemo(() => parts.map((p) => getToolMeta(p.part)), [parts]);
+ /** Labeled activity blocks also contain THINK parts, which yield null
+ * metadata. Narrow to tool entries once: they alone drive the count, the
+ * completion check, and the icon strip — passing a null-derived empty
+ * name to StackedToolIcons would render a phantom generic tool icon. */
+ const toolMetadata = useMemo(
+ () => parts.map((p) => getToolMeta(p.part)).filter((m): m is ToolMeta => m != null),
+ [parts],
+ );
+ const count = toolMetadata.length;
+ /** Approval state is read from the RAW parts, not `toolMetadata`: a pending
+ * call can be nested inside a subagent's content, which never surfaces as
+ * a tool entry here. */
const hasPendingApproval = useMemo(
() => parts.some(({ part }) => hasPendingApprovalInPart(part)),
[parts],
);
+ const activityLabel = getActivityLabelPart(labelPart?.part);
+ const activityLabelText = getActivityLabelText(activityLabel);
+ const activityFailed = activityLabel?.status === 'failed' || activityLabel?.status === 'partial';
+ /** A settled, filled label is itself a completion proof: the PostToolBatch
+ * claim only happens after every output in the batch returned. Without
+ * it, a tool that legitimately returns an empty string reads as
+ * `hasOutput: false` forever and its labeled group never auto-collapses. */
+ const labelSettled =
+ activityLabelText.length > 0 &&
+ (labelPart?.part as { pending?: boolean } | undefined)?.pending !== true;
const allCompleted = useMemo(
- () => toolMetadata.every((m) => m?.hasOutput === true),
- [toolMetadata],
+ () => labelSettled || toolMetadata.every((m) => m.hasOutput === true),
+ [toolMetadata, labelSettled],
);
- const toolNames = useMemo(() => toolMetadata.map((m) => m?.name ?? ''), [toolMetadata]);
- const iconToolNames = useMemo(() => toolMetadata.map((m) => m?.iconName ?? ''), [toolMetadata]);
+ const toolNames = useMemo(() => toolMetadata.map((m) => m.name), [toolMetadata]);
+ const iconToolNames = useMemo(() => toolMetadata.map((m) => m.iconName), [toolMetadata]);
/** Subagent tool calls get their own label verb ("Running/Ran N agents")
* since "Used N tools" reads oddly when the "tools" are actually child
@@ -193,7 +217,10 @@ export default function ToolCallGroup({
}, [toolNames, localize, mcpServerNames]);
const autoExpand = useRecoilValue(store.autoExpandTools);
- const autoCollapse = !autoExpand && count >= 2 && allCompleted;
+ /** A labeled activity block is summarized by its header, so it collapses
+ * even at a single tool call — agent runs are full of one-call batches,
+ * and leaving those expanded defeats the grouping. */
+ const autoCollapse = !autoExpand && allCompleted && (count >= 2 || activityLabelText.length > 0);
const initialState = initialExpansionState?.userOverride === true ? initialExpansionState : null;
const [isExpanded, setIsExpanded] = useState(
initialState?.isExpanded ?? (autoExpand || !autoCollapse),
@@ -296,7 +323,10 @@ export default function ToolCallGroup({
}
return localize('com_ui_used_n_tools', { 0: String(count) });
};
- const groupLabel = resolveGroupLabel();
+ /** The generated line wins over the generic category verb — but only once
+ * it exists. An unfilled label part leaves the block rendering exactly as
+ * it would without the feature. */
+ const groupLabel = activityLabelText.length > 0 ? activityLabelText : resolveGroupLabel();
/** Single category glyph for homogeneous groups (else StackedToolIcons). */
const CategoryIcon = allSubagents ? Users : MessageCircleQuestion;
@@ -344,7 +374,15 @@ export default function ToolCallGroup({
isAnimating={!allCompleted && isSubmitting}
/>
)}
- <span className="tool-status-text font-medium">{groupLabel}</span>
+ <span
+ className={cn(
+ 'tool-status-text font-medium',
+ activityFailed && 'text-amber-600 dark:text-amber-400',
+ )}
+ role="status"
+ >
+ {groupLabel}
+ </span>
{/** Hide the tool-name summary for pure-category groups (subagents /
* questions) — every entry deduplicates to the same token, which
* adds noise without info. Mixed groups keep the summary. */}
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
index 2328d916f5..f05631f0f6 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
@@ -63,6 +63,10 @@ jest.mock('~/utils', () => ({
['execute_code', 'bash_tool', 'run_tools_with_code', 'run_tools_with_bash'].includes(name)
? 'Code'
: name,
+ /** Real implementations: the group header resolves its text through these,
+ * so stubbing them out would hide the header logic under test. */
+ getActivityLabelPart: jest.requireActual('~/utils/activityLabels').getActivityLabelPart,
+ getActivityLabelText: jest.requireActual('~/utils/activityLabels').getActivityLabelText,
}));
jest.mock('../Parts', () => ({
@@ -199,6 +203,55 @@ describe('ToolCallGroup image hoisting', () => {
expect(mockScheduleMessageContentLayoutReconcile).not.toHaveBeenCalled();
});
+ /** A settled label proves the batch finished — a void tool's legitimate
+ * empty output must not keep its labeled group expanded forever. */
+ it('auto-collapses a labeled group whose only tool returned an empty output', () => {
+ const voidToolParts = [{ part: makePart('t1', '', 'update_settings'), idx: 0 }];
+ const labelPart = {
+ part: {
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: 'Updated the notification settings',
+ pending: false,
+ } as unknown as TMessageContentParts,
+ idx: 1,
+ };
+
+ renderGroup({
+ ...baseProps,
+ parts: voidToolParts,
+ lastContentIdx: 1,
+ labelPart,
+ });
+
+ expect(
+ screen.getByRole('button', { name: 'Updated the notification settings' }),
+ ).toBeInTheDocument();
+ /** Collapsed: bodies not mounted. */
+ expect(screen.queryByTestId('inner-0')).not.toBeInTheDocument();
+ });
+
+ it('keeps a pending-label group expanded while its tool has no output', () => {
+ const voidToolParts = [{ part: makePart('t1', '', 'update_settings'), idx: 0 }];
+ const labelPart = {
+ part: {
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: '',
+ pending: true,
+ } as unknown as TMessageContentParts,
+ idx: 1,
+ };
+
+ renderGroup({
+ ...baseProps,
+ parts: voidToolParts,
+ lastContentIdx: 1,
+ labelPart,
+ isSubmitting: true,
+ });
+
+ expect(screen.getByTestId('inner-0')).toBeInTheDocument();
+ });
+
it('does not render tool bodies for an initially collapsed large completed group', () => {
const largeParts = Array.from({ length: 59 }, (_, idx) => ({
part: makePart(`t${idx}`),
diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.ts
index 8419f5d767..885a35d226 100644
--- a/client/src/hooks/Chat/useChatFunctions.ts
+++ b/client/src/hooks/Chat/useChatFunctions.ts
@@ -560,6 +560,8 @@ export default function useChatFunctions({
)
: null) ??
null;
+ /** Set only for edited resubmissions; see `TSubmission.editPrefixLength`. */
+ let editPrefixLength: number | undefined;
const initialResponseId =
responseMessageId ?? `${isRegenerate ? messageId : intermediateId}`.replace(/_+$/, '') + '_';
@@ -607,6 +609,10 @@ export default function useChatFunctions({
if (editedContent && latestMessage?.content) {
initialResponse.content = cloneDeep(latestMessage.content);
+ /** Captured now, while it is still the retained prefix: a later resume
+ * sync replaces this array with the server's completion-local
+ * snapshot, after which its length no longer describes the offset. */
+ editPrefixLength = initialResponse.content.length;
const { index, type, ...part } = editedContent;
if (initialResponse.content && index >= 0 && index < initialResponse.content.length) {
const contentPart = initialResponse.content[index];
@@ -667,6 +673,7 @@ export default function useChatFunctions({
isTemporary,
ephemeralAgent,
editedContent,
+ editPrefixLength,
addedConvo,
manualSkills: manualSkills.length > 0 ? manualSkills : undefined,
clientRequestId,
diff --git a/client/src/hooks/Conversations/__tests__/format.test.ts b/client/src/hooks/Conversations/__tests__/format.test.ts
index 5f2dd75d15..0f66fd034d 100644
--- a/client/src/hooks/Conversations/__tests__/format.test.ts
+++ b/client/src/hooks/Conversations/__tests__/format.test.ts
@@ -12,6 +12,7 @@ const translations: Record<string, string> = {
com_ui_export_image: 'Image',
com_ui_export_retrieval: 'Retrieval',
com_ui_export_steer: 'You (steered)',
+ com_ui_export_activity_label: 'Activity',
com_ui_export_summary: 'Summary',
com_ui_export_tool: 'Tool',
com_ui_export_video: 'Video',
@@ -88,6 +89,12 @@ const contentByType: Record<ContentTypes, ExportableContentPart> = {
steer: 'Focus on the tests',
steerId: 'steer-1',
},
+ [ContentTypes.ACTIVITY_LABEL]: {
+ type: ContentTypes.ACTIVITY_LABEL,
+ activity_label: 'Searched runtime release notes',
+ tool_call_ids: ['tool-1'],
+ status: 'ok',
+ },
[ContentTypes.ERROR]: {
type: ContentTypes.ERROR,
error: 'Something failed',
@@ -109,6 +116,7 @@ const expectedMarkdownByType: Record<ContentTypes, MessageContentExport> = {
[ContentTypes.AGENT_UPDATE]: ['Agent Update', '{"index":0,"runId":"run-1","agentId":"agent-1"}'],
[ContentTypes.SUMMARY]: ['Summary', 'Summary text'],
[ContentTypes.STEER]: ['You (steered)', 'Focus on the tests'],
+ [ContentTypes.ACTIVITY_LABEL]: ['Activity', 'Searched runtime release notes'],
[ContentTypes.ERROR]: ['Assistant', 'Something failed'],
};
diff --git a/client/src/hooks/Conversations/format.ts b/client/src/hooks/Conversations/format.ts
index be42392453..0603950c2f 100644
--- a/client/src/hooks/Conversations/format.ts
+++ b/client/src/hooks/Conversations/format.ts
@@ -2,6 +2,7 @@ import { ContentTypes, ToolCallTypes } from 'librechat-data-provider';
import type { TMessage, TMessageContentParts } from 'librechat-data-provider';
import type { LocalizeFunction } from '~/common';
+import { getActivityLabelPart, getActivityLabelText } from '~/utils/activityLabels';
export type ExportFormat = 'text' | 'md';
export type MessageContentExport = [] | [sender: string, text: string];
@@ -35,6 +36,7 @@ export const handledExportContentTypes = [
ContentTypes.AGENT_UPDATE,
ContentTypes.SUMMARY,
ContentTypes.STEER,
+ ContentTypes.ACTIVITY_LABEL,
ContentTypes.ERROR,
] satisfies readonly ContentTypes[];
@@ -60,6 +62,7 @@ const exportLabelKeys = {
retrieval: 'com_ui_export_retrieval',
fileSearch: 'com_ui_export_file_search',
agentUpdate: 'com_ui_export_agent_update',
+ activityLabel: 'com_ui_export_activity_label',
} satisfies Record<string, Parameters<LocalizeFunction>[0]>;
const stripThinkTags = (reasoning: string): string =>
@@ -198,6 +201,14 @@ export function formatMessageContent({
return [localize(exportLabelKeys.steer), text];
}
+ if (content.type === ContentTypes.ACTIVITY_LABEL) {
+ const text = getActivityLabelText(getActivityLabelPart(content as TMessageContentParts));
+ if (text.trim().length === 0) {
+ return [];
+ }
+ return [localize(exportLabelKeys.activityLabel), text];
+ }
+
return [sender, stringify(content)];
}
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index 83ef206943..b0cebbd71d 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -11,6 +11,7 @@ import {
StepEvents,
apiBaseUrl,
SteerEvents,
+ ActivityLabelEvents,
UsageEvents,
createPayload,
ApprovalEvents,
@@ -26,6 +27,7 @@ import type {
TPendingSteer,
EventSubmission,
TSteerAppliedEvent,
+ TActivityLabelEvent,
} from 'librechat-data-provider';
import type { EventHandlerParams } from './useEventHandlers';
import type { ActiveJobsResponse } from '~/data-provider';
@@ -38,6 +40,8 @@ import {
carriedSteerContext,
resolveRunEndTarget,
findSteerMessageIndex,
+ applyActivityLabelPart,
+ findActivityLabelMessageIndex,
appendAppliedSteerIds,
removeConvoFromAllQueries,
upsertConvoInAllQueries,
@@ -545,6 +549,25 @@ export default function useResumableSSE(
* bounded next-frame retry as pending actions, on its own handle so the
* two retries can't cancel each other. */
const steerRetryRef = useRef<number | null>(null);
+ /** EVERY outstanding label-retry frame, not a single handle: labels fire
+ * two events per slot (reservation, then fill), so concurrent retry
+ * chains are the norm — a single ref would let cleanup cancel only the
+ * newest chain while the others kept running for up to 120 frames and
+ * could apply a stale label to a replacement generation that reuses the
+ * same response id (edits do). */
+ const activityLabelRetryFramesRef = useRef<Set<number>>(new Set());
+ /**
+ * Set once a SYNC has replaced the response with the server's
+ * completion-local snapshot, which discards the prefix an edited
+ * resubmission retained. From that point incoming indices are absolute and
+ * `editPrefixLength` must no longer be applied — by run steps or labels.
+ */
+ const editPrefixClearedRef = useRef(false);
+ /** Generation the cleared-prefix state above belongs to, so it is dropped
+ * when a new generation starts rather than when a subscribe happens to be
+ * live. Keyed by response message id — the stream id is the conversation
+ * id and is therefore shared by every generation within it. */
+ const prefixStateGenerationIdRef = useRef<string | null>(null);
/** Removes the pending chip once its steer is injected (the inline content
* part becomes the durable record), and records the id so a 202 ACK that
@@ -620,7 +643,7 @@ export default function useResumableSSE(
const setRunEnd = useSetRecoilState(store.runEndByIndex(runIndex));
const {
- stepHandler,
+ stepHandler: rawStepHandler,
finalHandler,
errorHandler,
clearStepMaps,
@@ -643,6 +666,11 @@ export default function useResumableSSE(
setShowStopButton,
});
+ /** Run steps dispatch straight through: their index math is upstream's and
+ * is deliberately left untouched by this feature. Only the activity-label
+ * handler applies the resume-aware prefix offset. */
+ const stepHandler = rawStepHandler;
+
const { data: startupConfig } = useGetStartupConfig();
const balanceQuery = useGetUserBalance({
enabled: !!isAuthenticated && startupConfig?.balance?.enabled,
@@ -665,6 +693,35 @@ export default function useResumableSSE(
*/
const subscribeToStream = useCallback(
(currentStreamId: string, currentSubmission: TSubmission, isResume = false) => {
+ /**
+ * A NEW generation starts with its retained prefix intact, so the
+ * cleared-prefix state from a previous one must not carry over — the
+ * hook outlives any single submission, and a later edited resubmission
+ * would otherwise dispatch with no offset and overwrite the content it
+ * kept.
+ *
+ * Keyed on `clientRequestId`, the per-submission uuid. Each of the
+ * narrower keys tried before it crossed a real boundary:
+ * - `isResume` — a submission whose POST succeeded but lost its
+ * response retries and returns `resumed: true`, so a NEW generation
+ * arrives in resume mode and skipped the reset.
+ * - the stream id — `request.js` sets `streamId = conversationId`, so
+ * every generation in a conversation shares it.
+ * - the response message id — editing an assistant response reuses
+ * that same id (`editedMessageId`), so re-editing one response
+ * produced the same key twice.
+ * `clientRequestId` is minted per submission and forwarded unchanged on
+ * retries, which is exactly "new per edit attempt, stable across
+ * reconnects".
+ */
+ const generationId =
+ currentSubmission.clientRequestId ??
+ (currentSubmission.initialResponse as TMessage | undefined)?.messageId ??
+ currentStreamId;
+ if (prefixStateGenerationIdRef.current !== generationId) {
+ prefixStateGenerationIdRef.current = generationId;
+ editPrefixClearedRef.current = false;
+ }
let { userMessage } = currentSubmission;
let textIndex: number | null = null;
let finalReceived = false;
@@ -774,6 +831,66 @@ export default function useResumableSSE(
resolveSteerChip(chipConvoId, event.steerId);
};
+ /**
+ * Places an activity-label part at its claimed content index on the
+ * in-flight response message. Fires twice per block (the empty
+ * reservation at batch end, the generated label on resolve);
+ * `applyActivityLabelPart` is referentially stable on duplicate replays
+ * and refuses to overwrite filled text with a stale placeholder. Same
+ * bounded next-frame retry as steers for the inject-before-render race.
+ */
+ const applyActivityLabelToMessages = (event: TActivityLabelEvent, attempt = 0) => {
+ const retryNextFrame = () => {
+ if (attempt < PENDING_ACTION_MAX_RETRY_FRAMES) {
+ const frameId = requestAnimationFrame(() => {
+ activityLabelRetryFramesRef.current.delete(frameId);
+ applyActivityLabelToMessages(event, attempt + 1);
+ });
+ activityLabelRetryFramesRef.current.add(frameId);
+ }
+ };
+ /** Same boundary as pending actions and steers: land queued deltas
+ * before the label part is placed and synced, or the later flush
+ * would clobber it (and `syncStepMessage` would sync a pre-delta
+ * copy back into the step handler's authoritative map). */
+ flushPendingDeltas();
+ const messages = getMessages() ?? [];
+ const index = findActivityLabelMessageIndex(messages, event);
+ if (index < 0) {
+ retryNextFrame();
+ return;
+ }
+ /** Edit-and-resubmit replays the kept prefix into the response before
+ * the run starts, and the server indexes only the NEW content — so
+ * run steps offset by that prefix (`useStepHandler`). The label index
+ * is claimed in the same server-side space and needs the identical
+ * shift, or it lands inside the prefix and overwrites kept content.
+ *
+ * Uses `editPrefixLength`, captured when the submission was built,
+ * for the same reason `useStepHandler` does: a resume sync replaces
+ * `initialResponse.content` with the server's completion-local
+ * snapshot, so its length no longer describes the retained prefix.
+ * Tool cards and the label heading them must land in one index
+ * space — a label shifting differently from its tools would overwrite
+ * another part, and a gap fill would miss its own reservation and
+ * leave the placeholder pending forever. */
+ const prefixLength =
+ currentSubmission.editedContent != null && !editPrefixClearedRef.current
+ ? (currentSubmission.editPrefixLength ??
+ (currentSubmission.initialResponse as TMessage | undefined)?.content?.length ??
+ 0)
+ : 0;
+ const offsetEvent =
+ prefixLength > 0 ? { ...event, index: event.index + prefixLength } : event;
+ const updated = applyActivityLabelPart(messages[index], offsetEvent);
+ if (updated !== messages[index]) {
+ const nextMessages = [...messages];
+ nextMessages[index] = updated;
+ setMessages(nextMessages);
+ syncStepMessage(updated);
+ }
+ };
+
const baseUrl = `${apiBaseUrl()}/api/agents/chat/stream/${encodeURIComponent(currentStreamId)}`;
const url = isResume ? `${baseUrl}?resume=true` : baseUrl;
logger.log('ResumableSSE', 'Subscribing to stream:', url, { isResume });
@@ -932,6 +1049,11 @@ export default function useResumableSSE(
return;
}
+ if (data.event === ActivityLabelEvents.ON_ACTIVITY_LABEL) {
+ applyActivityLabelToMessages(data.data as TActivityLabelEvent);
+ return;
+ }
+
if (data.event != null) {
if (
data.event === StepEvents.ON_MESSAGE_DELTA ||
@@ -1045,6 +1167,19 @@ export default function useResumableSSE(
matchedByResponseId &&
Array.isArray(oldContent) &&
oldContent.length > 0;
+ /**
+ * Replacing the response with `aggregatedContent` drops the
+ * prefix an edited resubmission had retained: the snapshot is
+ * completion-local, indexed from zero. Every later event must
+ * therefore stop offsetting, or it writes past the end of the
+ * shorter array — for an activity label that means the fill
+ * misses its own reservation and the placeholder never
+ * resolves. Preserving `oldContent` keeps the prefix, and with
+ * it the offset. Run steps and labels both read this.
+ */
+ if (!preserveLoadedContent) {
+ editPrefixClearedRef.current = true;
+ }
const responseMessage = {
...messages[responseIdx],
content: preserveLoadedContent ? oldContent : data.resumeState.aggregatedContent,
@@ -1067,6 +1202,13 @@ export default function useResumableSSE(
syncStepMessage(responseMessage);
logger.log('ResumableSSE', 'SYNC complete, handlers synced');
} else {
+ /** Same reasoning as the matched branch above: this row is
+ * built straight from the server's completion-local
+ * `aggregatedContent`, so it holds no retained prefix and
+ * later steps and labels must stop offsetting. Setting it
+ * only in the matched branch left this path adding an offset
+ * to indices that were already absolute. */
+ editPrefixClearedRef.current = true;
const responseId = serverResponseId ?? `${userMsgId}_`;
const newMessage = {
messageId: responseId,
@@ -1127,6 +1269,8 @@ export default function useResumableSSE(
applyPendingActionToMessages(replayEvent.data as Agents.PendingAction);
} else if (replayEvent.event === SteerEvents.ON_STEER_APPLIED) {
applySteerToMessages(replayEvent.data as TSteerAppliedEvent);
+ } else if (replayEvent.event === ActivityLabelEvents.ON_ACTIVITY_LABEL) {
+ applyActivityLabelToMessages(replayEvent.data as TActivityLabelEvent);
} else if (replayEvent.event != null) {
if (
replayEvent.event === StepEvents.ON_MESSAGE_DELTA ||
@@ -1156,6 +1300,8 @@ export default function useResumableSSE(
applyPendingActionToMessages(pendingEvent.data as Agents.PendingAction);
} else if (pendingEvent.event === SteerEvents.ON_STEER_APPLIED) {
applySteerToMessages(pendingEvent.data as TSteerAppliedEvent);
+ } else if (pendingEvent.event === ActivityLabelEvents.ON_ACTIVITY_LABEL) {
+ applyActivityLabelToMessages(pendingEvent.data as TActivityLabelEvent);
} else if (pendingEvent.event != null) {
if (
pendingEvent.event === StepEvents.ON_MESSAGE_DELTA ||
@@ -1736,6 +1882,10 @@ export default function useResumableSSE(
initStream();
+ /** The Set object itself is never reassigned, so this alias reads the
+ * LIVE frame ids at cleanup time (satisfies react-hooks/exhaustive-deps
+ * without changing behavior). */
+ const activityLabelRetryFrames = activityLabelRetryFramesRef.current;
return () => {
logger.log('ResumableSSE', 'Cleanup - closing SSE, resetting UI state');
startController.abort();
@@ -1750,6 +1900,10 @@ export default function useResumableSSE(
cancelAnimationFrame(pendingActionRetryRef.current);
pendingActionRetryRef.current = null;
}
+ for (const frameId of activityLabelRetryFrames) {
+ cancelAnimationFrame(frameId);
+ }
+ activityLabelRetryFrames.clear();
if (steerRetryRef.current != null) {
cancelAnimationFrame(steerRetryRef.current);
steerRetryRef.current = null;
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index ac8f407851..9234370159 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -1190,6 +1190,7 @@
"com_ui_export_file_search": "File Search",
"com_ui_export_image": "Image",
"com_ui_export_retrieval": "Retrieval",
+ "com_ui_export_activity_label": "Activity",
"com_ui_export_steer": "You (steered)",
"com_ui_export_summary": "Summary",
"com_ui_export_tool": "Tool",
diff --git a/client/src/utils/__tests__/activityLabels.spec.ts b/client/src/utils/__tests__/activityLabels.spec.ts
new file mode 100644
index 0000000000..5adda8aa93
--- /dev/null
+++ b/client/src/utils/__tests__/activityLabels.spec.ts
@@ -0,0 +1,78 @@
+import { ContentTypes } from 'librechat-data-provider';
+import type { TActivityLabelEvent, TMessage, TMessageContentParts } from 'librechat-data-provider';
+import { applyActivityLabelPart, lastVisibleContentIdx } from '../activityLabels';
+
+const buildMessage = (content: TMessage['content']): TMessage =>
+ ({ messageId: 'm1', isCreatedByUser: false, content }) as TMessage;
+
+const labelPart = (
+ overrides: Partial<TActivityLabelEvent['part']> = {},
+): TActivityLabelEvent['part'] => ({
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: '',
+ pending: true,
+ ...overrides,
+});
+
+describe('applyActivityLabelPart', () => {
+ it('writes the part at its claimed index', () => {
+ const message = buildMessage([]);
+ const updated = applyActivityLabelPart(message, { index: 2, part: labelPart() });
+ expect(updated).not.toBe(message);
+ expect((updated.content as unknown[])[2]).toMatchObject({
+ type: ContentTypes.ACTIVITY_LABEL,
+ pending: true,
+ });
+ });
+
+ it('returns the same reference on duplicate replay', () => {
+ const part = labelPart({ activity_label: 'Searched docs', pending: false });
+ const message = buildMessage([undefined as never, part as never]);
+ const updated = applyActivityLabelPart(message, { index: 1, part });
+ expect(updated).toBe(message);
+ });
+
+ it('never lets a stale pending placeholder overwrite a resolved label', () => {
+ const resolved = labelPart({
+ activity_label: 'Searched runtime release notes',
+ pending: false,
+ });
+ const message = buildMessage([resolved as never]);
+ const updated = applyActivityLabelPart(message, {
+ index: 0,
+ part: labelPart({ pending: true }),
+ });
+ expect(updated).toBe(message);
+ expect((updated.content as unknown[])[0]).toMatchObject({
+ activity_label: 'Searched runtime release notes',
+ pending: false,
+ });
+ });
+});
+
+describe('lastVisibleContentIdx', () => {
+ const text = { type: ContentTypes.TEXT, text: 'hello' } as unknown as TMessageContentParts;
+ const tool = {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 't1', name: 'web_search', args: '{}', output: 'ok' },
+ } as unknown as TMessageContentParts;
+
+ it('skips a trailing blank label reservation', () => {
+ expect(lastVisibleContentIdx([text, tool, labelPart() as never])).toBe(1);
+ });
+
+ it('skips consecutive trailing blank labels', () => {
+ expect(lastVisibleContentIdx([tool, labelPart() as never, tool, labelPart() as never])).toBe(2);
+ });
+
+ it('counts a filled label as visible', () => {
+ const filled = labelPart({ activity_label: 'Fetched the docs', pending: false });
+ expect(lastVisibleContentIdx([tool, filled as never])).toBe(1);
+ });
+
+ it('falls back to the raw last index without labels', () => {
+ expect(lastVisibleContentIdx([text, tool])).toBe(1);
+ expect(lastVisibleContentIdx([])).toBe(-1);
+ expect(lastVisibleContentIdx(undefined)).toBe(-1);
+ });
+});
diff --git a/client/src/utils/__tests__/groupToolCalls.test.ts b/client/src/utils/__tests__/groupToolCalls.test.ts
new file mode 100644
index 0000000000..a785836849
--- /dev/null
+++ b/client/src/utils/__tests__/groupToolCalls.test.ts
@@ -0,0 +1,177 @@
+import { ContentTypes } from 'librechat-data-provider';
+import type { TMessageContentParts } from 'librechat-data-provider';
+import type { PartWithIndex } from '~/components/Chat/Messages/Content/ParallelContent';
+import { groupSequentialToolCalls } from '../groupToolCalls';
+
+const toolCall = (id: string): TMessageContentParts =>
+ ({
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id, name: 'web_search', args: '{}', output: 'ok' },
+ }) as unknown as TMessageContentParts;
+
+const think = (text: string): TMessageContentParts =>
+ ({ type: ContentTypes.THINK, [ContentTypes.THINK]: text }) as unknown as TMessageContentParts;
+
+const label = (text: string): TMessageContentParts =>
+ ({
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: text,
+ pending: text.length === 0,
+ }) as unknown as TMessageContentParts;
+
+const withIndex = (parts: TMessageContentParts[]): PartWithIndex[] =>
+ parts.map((part, idx) => ({ part, idx }));
+
+describe('groupSequentialToolCalls with activity labels', () => {
+ /**
+ * Every batch publishes its reservation the moment the batch ends, so an
+ * empty label is the NORMAL state while generation is in flight. It must
+ * render exactly as the feature-off path does: a lone tool call stays a
+ * single (no group wrapper) and THINK parts stay standalone.
+ */
+ it('leaves a single tool call and its reasoning untouched while the label is empty', () => {
+ const grouped = groupSequentialToolCalls(
+ withIndex([think('deciding what to search'), toolCall('t1'), label('')]),
+ );
+
+ expect(grouped).toHaveLength(2);
+ expect(grouped[0]).toMatchObject({ type: 'single' });
+ expect(grouped[1]).toMatchObject({ type: 'single' });
+ /** No labelPart anywhere, and crucially no 'tool-group' wrapper. */
+ expect(grouped.some((entry) => entry.type === 'tool-group')).toBe(false);
+ });
+
+ /** A blank/failed fill is permanent, and must stay equally invisible. */
+ it('keeps legacy splitting for two tool calls when the label never fills', () => {
+ const grouped = groupSequentialToolCalls(
+ withIndex([toolCall('t1'), toolCall('t2'), label('')]),
+ );
+
+ /** Two adjacent tool calls group even without the feature. */
+ expect(grouped).toHaveLength(1);
+ expect(grouped[0]).toMatchObject({ type: 'tool-group' });
+ expect((grouped[0] as { labelPart?: PartWithIndex }).labelPart).toBeUndefined();
+ });
+
+ /** Once real text lands the block becomes one labeled group, THINK included. */
+ it('absorbs reasoning into a labeled group once the label has text', () => {
+ const grouped = groupSequentialToolCalls(
+ withIndex([
+ think('deciding what to search'),
+ toolCall('t1'),
+ label('Found the failing spec'),
+ ]),
+ );
+
+ expect(grouped).toHaveLength(1);
+ expect(grouped[0].type).toBe('tool-group');
+ const group = grouped[0] as { parts: PartWithIndex[]; labelPart?: PartWithIndex };
+ expect(group.parts).toHaveLength(2);
+ expect(group.labelPart?.part).toMatchObject({
+ [ContentTypes.ACTIVITY_LABEL]: 'Found the failing spec',
+ });
+ });
+
+ /** An empty orphan label has nothing to render and no block to delimit. */
+ it('drops an empty orphan label entirely', () => {
+ expect(groupSequentialToolCalls(withIndex([label('')]))).toEqual([]);
+ });
+
+ /**
+ * Two consecutive single-call batches whose labels stay blank: with the
+ * feature off these adjacent calls merge into one legacy group, so the
+ * invisible blank slots must not split them into standalone cards.
+ */
+ it('merges adjacent single-call batches across blank labels like the feature-off path', () => {
+ const grouped = groupSequentialToolCalls(
+ withIndex([toolCall('t1'), label(''), toolCall('t2'), label('')]),
+ );
+
+ expect(grouped).toHaveLength(1);
+ expect(grouped[0]).toMatchObject({ type: 'tool-group' });
+ const group = grouped[0] as { parts: PartWithIndex[]; labelPart?: PartWithIndex };
+ expect(group.parts.map((p) => p.idx)).toEqual([0, 2]);
+ expect(group.labelPart).toBeUndefined();
+ });
+
+ /** A pure-handoff batch's label has nothing to head: the transfer card
+ * names the destination, transfers are never groupable, and the label
+ * would render as a stray line after the card. */
+ it('drops an orphan label whose batch was only transfer calls', () => {
+ const transfer = {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'x1', name: 'lc_transfer_to_billing', args: '{}' },
+ } as unknown as TMessageContentParts;
+ const transferLabel = {
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: 'Handed off to billing',
+ tool_call_ids: ['x1'],
+ pending: false,
+ } as unknown as TMessageContentParts;
+
+ const grouped = groupSequentialToolCalls(withIndex([transfer, transferLabel]));
+
+ expect(grouped).toHaveLength(1);
+ expect(grouped[0]).toMatchObject({ type: 'single' });
+ expect((grouped[0] as { part: PartWithIndex }).part.idx).toBe(0);
+ });
+
+ /** Mixed legacy content: an orphan label covering a transfer AND real
+ * calls is equally headless once the block flushed at the transfer. */
+ it('drops an orphan label whose batch mixed a transfer with real calls', () => {
+ const realTool = {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 't1', name: 'web_search', args: '{}', output: 'ok' },
+ } as unknown as TMessageContentParts;
+ const transfer = {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'x1', name: 'lc_transfer_to_billing', args: '{}' },
+ } as unknown as TMessageContentParts;
+ const mixedLabel = {
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: 'Looked up the refund policy',
+ tool_call_ids: ['t1', 'x1'],
+ pending: false,
+ } as unknown as TMessageContentParts;
+
+ const grouped = groupSequentialToolCalls(withIndex([realTool, transfer, mixedLabel]));
+
+ /** Tool card + handoff card render; the headless label is dropped. */
+ expect(grouped).toHaveLength(2);
+ expect(grouped.every((entry) => entry.type === 'single')).toBe(true);
+ });
+
+ it('keeps rendering an orphan label whose batch had real tool calls', () => {
+ const orphanLabel = {
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: 'Searched the docs',
+ tool_call_ids: ['t9'],
+ pending: false,
+ } as unknown as TMessageContentParts;
+
+ const grouped = groupSequentialToolCalls(withIndex([orphanLabel]));
+
+ expect(grouped).toHaveLength(1);
+ expect((grouped[0] as { part: PartWithIndex }).part.part).toMatchObject({
+ [ContentTypes.ACTIVITY_LABEL]: 'Searched the docs',
+ });
+ });
+
+ /** A filled label claims only its own batch — never one behind a blank slot. */
+ it('stops a filled label from claiming a batch behind a blank label', () => {
+ const grouped = groupSequentialToolCalls(
+ withIndex([toolCall('t1'), label(''), toolCall('t2'), label('Fetched the docs')]),
+ );
+
+ expect(grouped).toHaveLength(2);
+ /** The blank-labeled batch renders legacy-style, before the labeled group. */
+ expect(grouped[0]).toMatchObject({ type: 'single' });
+ expect((grouped[0] as { part: PartWithIndex }).part.idx).toBe(0);
+ expect(grouped[1].type).toBe('tool-group');
+ const group = grouped[1] as { parts: PartWithIndex[]; labelPart?: PartWithIndex };
+ expect(group.parts.map((p) => p.idx)).toEqual([2]);
+ expect(group.labelPart?.part).toMatchObject({
+ [ContentTypes.ACTIVITY_LABEL]: 'Fetched the docs',
+ });
+ });
+});
diff --git a/client/src/utils/activityLabels.ts b/client/src/utils/activityLabels.ts
new file mode 100644
index 0000000000..5cf1eca87d
--- /dev/null
+++ b/client/src/utils/activityLabels.ts
@@ -0,0 +1,117 @@
+import { ContentTypes } from 'librechat-data-provider';
+import type { TMessage, TActivityLabelEvent, TMessageContentParts } from 'librechat-data-provider';
+
+type ActivityLabelPart = Extract<TMessageContentParts, { type: ContentTypes.ACTIVITY_LABEL }>;
+
+/** Returns the activity-label content part when `part` is one, else undefined. */
+export function getActivityLabelPart(
+ part: TMessageContentParts | undefined,
+): ActivityLabelPart | undefined {
+ return part?.type === ContentTypes.ACTIVITY_LABEL ? (part as ActivityLabelPart) : undefined;
+}
+
+/**
+ * The generated description, or empty when none exists yet.
+ *
+ * There is deliberately NO fallback string. A templated stand-in
+ * ("ran 1 command") only restates the tool card rendered directly beneath
+ * it, and showing one changes the UI before anything worth reading exists.
+ * Callers render nothing until this returns text.
+ */
+export function getActivityLabelText(part: ActivityLabelPart | undefined): string {
+ if (!part) {
+ return '';
+ }
+ const label = part[ContentTypes.ACTIVITY_LABEL];
+ return typeof label === 'string' ? label.trim() : '';
+}
+
+/**
+ * Last content index that actually renders something. Trailing BLANK label
+ * reservations are invisible (every batch publishes one at batch end), so
+ * counting one as the last part would suppress the streaming cursor and
+ * other last-item affordances on the last VISIBLE part for the whole
+ * interval until the label fills or the next delta arrives. Used by both
+ * the sequential and parallel content renderers so they stay in lockstep.
+ */
+export function lastVisibleContentIdx(
+ content: ReadonlyArray<TMessageContentParts | undefined> | undefined,
+): number {
+ const parts = content ?? [];
+ let last = parts.length - 1;
+ while (last > 0) {
+ const tail = parts[last];
+ if (
+ tail?.type === ContentTypes.ACTIVITY_LABEL &&
+ getActivityLabelText(getActivityLabelPart(tail)).length === 0
+ ) {
+ last -= 1;
+ } else {
+ break;
+ }
+ }
+ return last;
+}
+
+/**
+ * Resolves the assistant response message an activity-label event targets.
+ * Exact-id assistant match when `responseMessageId` is present (a miss
+ * returns -1 so the caller retries next frame); best-effort last assistant
+ * otherwise. Mirrors `findSteerMessageIndex`.
+ */
+export function findActivityLabelMessageIndex(
+ messages: TMessage[],
+ event: TActivityLabelEvent,
+): number {
+ const isAssistant = (message: TMessage | undefined) => message?.isCreatedByUser === false;
+ const { responseMessageId } = event;
+ if (responseMessageId) {
+ return messages.findIndex(
+ (message) => message.messageId === responseMessageId && isAssistant(message),
+ );
+ }
+ for (let i = messages.length - 1; i >= 0; i--) {
+ if (isAssistant(messages[i])) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+/**
+ * Places an activity-label part at its absolute content index on the target
+ * response message. The server claimed that slot (subsequent SDK events were
+ * emitted with already-shifted indices), so the write never collides with
+ * streamed parts. Pure with a referential-stability contract: returns the
+ * SAME message reference when the write would be a no-op — including when a
+ * stale pending placeholder arrives AFTER the resolved label (out-of-order
+ * publish), which must never overwrite the filled text.
+ */
+export function applyActivityLabelPart(message: TMessage, event: TActivityLabelEvent): TMessage {
+ const { index, part } = event;
+ if (typeof index !== 'number' || index < 0 || part == null) {
+ return message;
+ }
+ const content = Array.isArray(message.content) ? message.content : [];
+ const existing = getActivityLabelPart(content[index] as TMessageContentParts | undefined);
+ if (
+ existing != null &&
+ existing[ContentTypes.ACTIVITY_LABEL] === part[ContentTypes.ACTIVITY_LABEL] &&
+ existing.pending === part.pending
+ ) {
+ return message;
+ }
+ const existingText = existing?.[ContentTypes.ACTIVITY_LABEL];
+ if (
+ existing != null &&
+ existing.pending !== true &&
+ typeof existingText === 'string' &&
+ existingText.length > 0 &&
+ part.pending === true
+ ) {
+ return message;
+ }
+ const nextContent = [...content] as TMessageContentParts[];
+ nextContent[index] = part as TMessageContentParts;
+ return { ...message, content: nextContent };
+}
diff --git a/client/src/utils/groupToolCalls.ts b/client/src/utils/groupToolCalls.ts
index 406b686aad..7f4b365731 100644
--- a/client/src/utils/groupToolCalls.ts
+++ b/client/src/utils/groupToolCalls.ts
@@ -1,10 +1,11 @@
import { Constants, ContentTypes, ToolCallTypes } from 'librechat-data-provider';
import type { TMessageContentParts, Agents } from 'librechat-data-provider';
import type { PartWithIndex } from '~/components/Chat/Messages/Content/ParallelContent';
+import { getActivityLabelPart, getActivityLabelText } from '~/utils/activityLabels';
export type GroupedPart =
| { type: 'single'; part: PartWithIndex }
- | { type: 'tool-group'; parts: PartWithIndex[] };
+ | { type: 'tool-group'; parts: PartWithIndex[]; labelPart?: PartWithIndex };
function isGroupableToolCall(part: TMessageContentParts): boolean {
if (part.type !== ContentTypes.TOOL_CALL) {
@@ -22,30 +23,116 @@ function isGroupableToolCall(part: TMessageContentParts): boolean {
return true;
}
+/**
+ * True when the label covers ANY `transfer_to_*` handoff call. Transfer
+ * parts are never groupable, so the flush at the handoff card leaves such a
+ * label with nothing to head — it can only orphan into a stray line after
+ * cards that already show everything (the handoff card names the
+ * destination; mixed batches keep their tool cards). Content persisted
+ * before the server stopped claiming labels for handoff batches still
+ * carries these; they are dropped at render.
+ */
+function coversTransferCall(labelPart: TMessageContentParts, allParts: PartWithIndex[]): boolean {
+ const ids = (labelPart as { tool_call_ids?: unknown }).tool_call_ids;
+ if (!Array.isArray(ids) || ids.length === 0) {
+ return false;
+ }
+ return ids.some((id) =>
+ allParts.some(({ part }) => {
+ if (part?.type !== ContentTypes.TOOL_CALL) {
+ return false;
+ }
+ const toolCall = part[ContentTypes.TOOL_CALL] as Agents.ToolCall | undefined;
+ return toolCall?.id === id && toolCall?.name?.startsWith(Constants.LC_TRANSFER_TO_) === true;
+ }),
+ );
+}
+
+/**
+ * Groups message content for rendering.
+ *
+ * Activity blocks: reasoning (THINK) parts are absorbed tentatively; when an
+ * ACTIVITY_LABEL part terminates the run, the whole block (thinking + tool
+ * calls) becomes one labeled group — the claude.ai-style hierarchy. Any
+ * other part type breaks the block.
+ *
+ * Legacy behavior is preserved exactly when no ACTIVITY_LABEL part arrives
+ * (feature off, older conversations): the tentative block is re-split so
+ * THINK parts render standalone in their original positions and only runs
+ * of >= 2 tool calls group.
+ */
export function groupSequentialToolCalls(parts: PartWithIndex[]): GroupedPart[] {
const result: GroupedPart[] = [];
- let currentGroup: PartWithIndex[] = [];
+ let currentBlock: PartWithIndex[] = [];
+ /** Position in `currentBlock` just past the most recent BLANK label. A
+ * filled label may only claim parts after it (its own batch); everything
+ * before it belongs to earlier batches whose labels stayed empty. */
+ let claimStart = 0;
- const flushGroup = () => {
- if (currentGroup.length >= 2) {
- result.push({ type: 'tool-group', parts: [...currentGroup] });
- } else {
- for (const p of currentGroup) {
+ const flushWithoutLabel = () => {
+ let toolRun: PartWithIndex[] = [];
+ const flushToolRun = () => {
+ if (toolRun.length >= 2) {
+ result.push({ type: 'tool-group', parts: [...toolRun] });
+ } else {
+ for (const p of toolRun) {
+ result.push({ type: 'single', part: p });
+ }
+ }
+ toolRun = [];
+ };
+ for (const p of currentBlock) {
+ if (isGroupableToolCall(p.part)) {
+ toolRun.push(p);
+ } else {
+ flushToolRun();
result.push({ type: 'single', part: p });
}
}
- currentGroup = [];
+ flushToolRun();
+ currentBlock = [];
+ claimStart = 0;
};
for (const item of parts) {
- if (isGroupableToolCall(item.part)) {
- currentGroup.push(item);
- } else {
- flushGroup();
- result.push({ type: 'single', part: item });
+ if (isGroupableToolCall(item.part) || item.part.type === ContentTypes.THINK) {
+ currentBlock.push(item);
+ continue;
+ }
+ if (item.part.type === ContentTypes.ACTIVITY_LABEL) {
+ const hasText = getActivityLabelText(getActivityLabelPart(item.part)).length > 0;
+ if (!hasText) {
+ /** A reserved-but-unfilled slot (and a failed/blank fill) must be
+ * INVISIBLE. Every batch now publishes its reservation immediately,
+ * so forming a group here would wrap even a single tool call and pull
+ * THINK parts inside it while generation is still pending. It cannot
+ * flush either: two consecutive single-call batches would then render
+ * as two standalone cards where the feature-off path merges them into
+ * one legacy group. It only marks the claim boundary, so the block
+ * keeps accumulating for legacy merging while a later filled label
+ * still cannot reach back into this batch. */
+ claimStart = currentBlock.length;
+ continue;
+ }
+ const claimed = currentBlock.slice(claimStart);
+ /** Earlier blank-labeled batches render legacy-style, in order, before
+ * this label's group. */
+ currentBlock = currentBlock.slice(0, claimStart);
+ flushWithoutLabel();
+ if (claimed.length > 0) {
+ result.push({ type: 'tool-group', parts: claimed, labelPart: item });
+ } else if (!coversTransferCall(item.part, parts)) {
+ /** Orphan label (block parts hidden/filtered): renders standalone —
+ * UNLESS its batch contained a handoff call, where the cards
+ * already say everything and the label would be a stray line. */
+ result.push({ type: 'single', part: item });
+ }
+ continue;
}
+ flushWithoutLabel();
+ result.push({ type: 'single', part: item });
}
- flushGroup();
+ flushWithoutLabel();
return result;
}
diff --git a/client/src/utils/index.ts b/client/src/utils/index.ts
index 4b54dfa0d5..0078d1666a 100644
--- a/client/src/utils/index.ts
+++ b/client/src/utils/index.ts
@@ -42,6 +42,7 @@ export * from './toolLabels';
export * from './favoritesError';
export * from './approval';
export * from './steer';
+export * from './activityLabels';
export * from './numbers';
export { default as cn } from './cn';
export { default as logger } from './logger';
diff --git a/e2e/config/librechat.e2e.yaml b/e2e/config/librechat.e2e.yaml
index 07062dce7d..b8ebab2851 100644
--- a/e2e/config/librechat.e2e.yaml
+++ b/e2e/config/librechat.e2e.yaml
@@ -119,6 +119,26 @@ endpoints:
titleConvo: false
modelDisplayLabel: 'Mock Provider D'
+ # Activity labels are enabled ONLY here. They get a dedicated endpoint
+ # because a label collapses its tool group (a labeled block auto-collapses
+ # even at one call), which hides the tool cards other specs assert on —
+ # enabling this on a shared endpoint broke steering.spec.ts. Provider D is
+ # the unlabeled control. The label call is the one request that leaves the
+ # process (e2e/setup/fake-label-server.js serves the baseURL below), and
+ # `activityModel` differs from the chat model so a spec can prove the label
+ # ran on the configured model rather than the agent's.
+ - name: 'Mock Provider E'
+ apiKey: 'e2e-mock-key-e'
+ baseURL: 'http://127.0.0.1:8889/v1'
+ models:
+ default:
+ - 'mock-model-e'
+ fetch: false
+ titleConvo: false
+ modelDisplayLabel: 'Mock Provider E'
+ activityLabel: true
+ activityModel: 'mock-label-model'
+
modelSpecs:
prioritize: true
# Enforcement would reject sends from the non-spec paths addedEndpoints
@@ -129,6 +149,7 @@ modelSpecs:
addedEndpoints:
- 'Mock Provider C'
- 'Mock Provider D'
+ - 'Mock Provider E'
- 'agents'
list:
- name: 'e2e-mock-provider-a'
diff --git a/e2e/playwright.config.mock.ts b/e2e/playwright.config.mock.ts
index 606a5e0625..758f1e6726 100644
--- a/e2e/playwright.config.mock.ts
+++ b/e2e/playwright.config.mock.ts
@@ -8,6 +8,10 @@ const serverPath = path.resolve(rootPath, 'e2e/setup/start-server.js');
const mcpHttpServerPath = path.resolve(rootPath, 'e2e/setup/fake-mcp-http-server.js');
/** Must match the `e2e-http` server URL in e2e/config/librechat.e2e.yaml. */
const MCP_HTTP_PORT = process.env.E2E_MCP_HTTP_PORT || '8765';
+const labelServerPath = path.resolve(rootPath, 'e2e/setup/fake-label-server.js');
+/** The template's custom-endpoint `baseURL`s hard-code 8889;
+ * `writeRuntimeMockConfig` substitutes any override into the generated copy. */
+const LABEL_PORT = process.env.E2E_LABEL_PORT || '8889';
const fakeModelHookPath = path.resolve(rootPath, 'e2e/setup/fake-model.js');
const configTemplatePath = path.resolve(rootPath, 'e2e/config/librechat.e2e.yaml');
const configPath = path.resolve(rootPath, 'e2e/.generated/librechat.e2e.yaml');
@@ -50,16 +54,27 @@ const preservedCredentialEnvKeys = new Set([
]);
/**
- * The custom endpoints in the template point at an unreachable baseURL; the fake
- * model injected via `LIBRECHAT_TEST_RUN_HOOK` overrides the run before any
- * request is made, so no real (or mock HTTP) provider is contacted.
+ * The custom endpoints in the template point their `baseURL` at the local fake
+ * label server; the fake model injected via `LIBRECHAT_TEST_RUN_HOOK` overrides
+ * the GRAPH before any request is made, so no real provider is contacted.
+ *
+ * Activity labels are the one exception: `run.generateActivityLabel()` bypasses
+ * the graph override and calls the endpoint's resolved client options, so that
+ * request does go out over HTTP — to `fake-label-server.js` on 127.0.0.1.
*/
function writeRuntimeMockConfig() {
const template = fs.readFileSync(configTemplatePath, 'utf8');
- const config =
+ let config =
process.env.E2E_MODEL_SPECS_ENFORCE === 'true'
? template.replace('\n enforce: false\n', '\n enforce: true\n')
: template;
+ /** Keep the generated config in lockstep with the overridable label-server
+ * port: the template hard-codes 8889, so an `E2E_LABEL_PORT` override that
+ * moved only the server and its health check would report ready while
+ * every activity-label request went to the wrong port. */
+ if (LABEL_PORT !== '8889') {
+ config = config.split('127.0.0.1:8889').join(`127.0.0.1:${LABEL_PORT}`);
+ }
fs.mkdirSync(path.dirname(configPath), { recursive: true });
fs.writeFileSync(configPath, config);
}
@@ -151,5 +166,15 @@ export default defineConfig({
timeout: 60_000,
reuseExistingServer: false,
},
+ {
+ // Serves the activity-label model call (the custom endpoints' baseURL).
+ command: `node ${labelServerPath}`,
+ cwd: rootPath,
+ env: { ...process.env, E2E_LABEL_PORT: LABEL_PORT },
+ url: `http://127.0.0.1:${LABEL_PORT}/`,
+ stdout: 'pipe',
+ timeout: 60_000,
+ reuseExistingServer: false,
+ },
],
});
diff --git a/e2e/setup/fake-label-server.js b/e2e/setup/fake-label-server.js
new file mode 100644
index 0000000000..ad2e590b27
--- /dev/null
+++ b/e2e/setup/fake-label-server.js
@@ -0,0 +1,180 @@
+/**
+ * OpenAI-compatible HTTP fixture for activity-label e2e tests.
+ *
+ * Activity labels are the one model call in a mock run that is NOT served by
+ * `e2e/setup/fake-model.js`: that hook swaps the GRAPH's model via
+ * `run.Graph.overrideTestModel(...)`, while the label call goes out through
+ * `run.generateActivityLabel()` against client options resolved from the
+ * endpoint config. Those options carry the template's `baseURL`
+ * (http://127.0.0.1:8889/v1), so a real server on that port serves label
+ * calls — and only label calls — with no production seam. Every mock endpoint
+ * sets `titleConvo: false`, so nothing else lands here.
+ *
+ * Beyond returning a label it RECORDS each request, which is what lets a spec
+ * assert the prompt contract (that the register and the tool OUTPUTS actually
+ * reached the model) rather than just that some text rendered.
+ */
+const http = require('http');
+
+const PORT = Number(process.env.E2E_LABEL_PORT) || 8889;
+
+/** Recorded label requests, newest last. */
+const requests = [];
+/** Test-controlled response behavior; `reset` restores these defaults. */
+const DEFAULT_BEHAVIOR = { mode: 'ok', label: null, delayMs: 0 };
+let behavior = { ...DEFAULT_BEHAVIOR };
+let labelCount = 0;
+
+function readBody(req) {
+ return new Promise((resolve) => {
+ let raw = '';
+ req.on('data', (chunk) => {
+ raw += chunk;
+ });
+ req.on('end', () => {
+ try {
+ resolve(raw ? JSON.parse(raw) : {});
+ } catch {
+ resolve({});
+ }
+ });
+ });
+}
+
+function sendJson(res, status, payload) {
+ const body = JSON.stringify(payload);
+ res.writeHead(status, {
+ 'Content-Type': 'application/json',
+ 'Content-Length': Buffer.byteLength(body),
+ });
+ res.end(body);
+}
+
+function messageText(content) {
+ if (typeof content === 'string') {
+ return content;
+ }
+ if (!Array.isArray(content)) {
+ return '';
+ }
+ return content.map((part) => (typeof part === 'string' ? part : (part?.text ?? ''))).join('\n');
+}
+
+/** Flattened prompt text so specs can assert on the register and tool outputs. */
+function flattenPrompt(messages) {
+ return (messages ?? []).map((message) => messageText(message?.content)).join('\n\n');
+}
+
+/** Non-streaming OpenAI chat completion. */
+function completionPayload(model, label) {
+ return {
+ id: `chatcmpl-e2e-${labelCount}`,
+ object: 'chat.completion',
+ created: 0,
+ model: model ?? 'mock-label-model',
+ choices: [
+ {
+ index: 0,
+ message: { role: 'assistant', content: label },
+ finish_reason: 'stop',
+ },
+ ],
+ usage: { prompt_tokens: 42, completion_tokens: 7, total_tokens: 49 },
+ };
+}
+
+/**
+ * SSE form of the same completion. The label call inherits the endpoint's
+ * client options, which may leave streaming on, so both shapes are served.
+ */
+function sendStream(res, model, label) {
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ Connection: 'keep-alive',
+ });
+ const base = {
+ id: `chatcmpl-e2e-${labelCount}`,
+ object: 'chat.completion.chunk',
+ created: 0,
+ model,
+ };
+ res.write(
+ `data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta: { role: 'assistant', content: label }, finish_reason: null }] })}\n\n`,
+ );
+ res.write(
+ `data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage: { prompt_tokens: 42, completion_tokens: 7, total_tokens: 49 } })}\n\n`,
+ );
+ res.write('data: [DONE]\n\n');
+ res.end();
+}
+
+const server = http.createServer(async (req, res) => {
+ const url = new URL(req.url, `http://127.0.0.1:${PORT}`);
+
+ /** Playwright's webServer readiness probe. */
+ if (req.method === 'GET' && url.pathname === '/') {
+ sendJson(res, 200, { ok: true, service: 'fake-label-server' });
+ return;
+ }
+
+ if (req.method === 'GET' && url.pathname === '/__e2e/requests') {
+ sendJson(res, 200, { count: requests.length, requests });
+ return;
+ }
+
+ /** Specs reset between cases so counts and prompts stay per-test. */
+ if (req.method === 'POST' && url.pathname === '/__e2e/reset') {
+ requests.length = 0;
+ labelCount = 0;
+ behavior = { ...DEFAULT_BEHAVIOR };
+ sendJson(res, 200, { ok: true });
+ return;
+ }
+
+ if (req.method === 'POST' && url.pathname === '/__e2e/behavior') {
+ const body = await readBody(req);
+ behavior = { ...DEFAULT_BEHAVIOR, ...body };
+ sendJson(res, 200, { ok: true, behavior });
+ return;
+ }
+
+ if (req.method === 'POST' && url.pathname === '/v1/chat/completions') {
+ const body = await readBody(req);
+ labelCount += 1;
+ const prompt = flattenPrompt(body.messages);
+ requests.push({
+ model: body.model,
+ stream: body.stream === true,
+ prompt,
+ messages: body.messages ?? [],
+ });
+
+ if (behavior.delayMs > 0) {
+ await new Promise((resolve) => setTimeout(resolve, behavior.delayMs));
+ }
+
+ /** Generation failure: the run must finish cleanly with no header. */
+ if (behavior.mode === 'error') {
+ sendJson(res, 500, { error: { message: 'E2E forced label failure' } });
+ return;
+ }
+
+ /** Whitespace-only output must fill null, leaving the block unlabeled. */
+ const label =
+ behavior.mode === 'blank' ? ' ' : (behavior.label ?? `E2E activity label ${labelCount}`);
+
+ if (body.stream === true) {
+ sendStream(res, body.model, label);
+ return;
+ }
+ sendJson(res, 200, completionPayload(body.model, label));
+ return;
+ }
+
+ sendJson(res, 404, { error: { message: `Unhandled ${req.method} ${url.pathname}` } });
+});
+
+server.listen(PORT, '127.0.0.1', () => {
+ console.log(`[e2e] fake label server listening on http://127.0.0.1:${PORT}`);
+});
diff --git a/e2e/setup/fake-model.js b/e2e/setup/fake-model.js
index b365937a7d..b7e5993c63 100644
--- a/e2e/setup/fake-model.js
+++ b/e2e/setup/fake-model.js
@@ -31,6 +31,7 @@ const SLOW_COUNTED_REPLY_MARKER = 'E2E_SLOW_COUNTED_REPLY:';
const STEER_TOOL_REPLY_MARKER = 'E2E_STEER_TOOL_REPLY:';
const STEER_SPLIT_REPLY_MARKER = 'E2E_STEER_SPLIT_REPLY:';
const STEER_LATE_REPLY_MARKER = 'E2E_STEER_LATE_REPLY:';
+const ACTIVITY_REPLY_MARKER = 'E2E_ACTIVITY_REPLY:';
const RESUME_ICON_REPLY_MARKER = 'E2E_RESUME_ICON_REPLY:';
const FORCED_ERROR_MARKER = 'E2E_FORCED_ERROR:';
const MARKDOWN_REPLY_MARKER = 'E2E_MARKDOWN_REPLY';
@@ -53,6 +54,7 @@ const QUOTE_ASSERTION_FINAL_TEXT = 'E2E quote assertion passed';
const STEER_TOOL_FINAL_TEXT = 'E2E steer tool reply done';
const STEER_SPLIT_FINAL_TEXT = 'E2E steer split reply done';
const STEER_LATE_FINAL_TEXT = 'E2E steer late reply done';
+const ACTIVITY_FINAL_TEXT = 'E2E activity reply done';
const STEER_TOOL_NAME_PREFIX = 'remember_fact';
const SLOW_CHUNK_DELAY_MS = Number(process.env.MOCK_LLM_SLOW_CHUNK_DELAY_MS) || 35;
const SLOW_REPLY_CHUNKS = 160;
@@ -999,6 +1001,40 @@ function steerLateReplyResponses(label, toolNames) {
};
}
+/**
+ * Two-turn run with a real tool boundary for the activity-label e2e: turn 1
+ * emits TWO parallel `remember_fact` calls (one `PostToolBatch` -> one label),
+ * turn 2 streams the final text. The args are distinct and the MCP fixture
+ * echoes them back prefixed, so a spec can tell an OUTPUT ("E2E MCP memory
+ * noted: ...") from an INPUT in the recorded label prompt — which is the whole
+ * point of labeling after the batch rather than before it.
+ */
+function activityReplyResponses(label, toolNames) {
+ const toolName = Array.from(toolNames).find((name) => name.startsWith(STEER_TOOL_NAME_PREFIX));
+ if (!toolName) {
+ return {
+ responses: [`E2E activity reply unavailable: no ${STEER_TOOL_NAME_PREFIX} tool advertised.`],
+ };
+ }
+ return {
+ responses: ['', `${ACTIVITY_FINAL_TEXT} ${label}`],
+ toolCalls: [
+ {
+ id: `call_e2e_activity_alpha_${label}`,
+ name: toolName,
+ args: { fact: `activity alpha ${label}` },
+ type: 'tool_call',
+ },
+ {
+ id: `call_e2e_activity_beta_${label}`,
+ name: toolName,
+ args: { fact: `activity beta ${label}` },
+ type: 'tool_call',
+ },
+ ],
+ };
+}
+
function findLastToolMessageText(messages, requiredToken) {
for (let index = (messages ?? []).length - 1; index >= 0; index--) {
const message = messages[index];
@@ -1568,6 +1604,11 @@ function resolveResponses({ graph, messages, text, toolNames }) {
return steerLateReplyResponses(steerLateLabel, toolNames);
}
+ const activityLabel = getMarkerValue(text, ACTIVITY_REPLY_MARKER);
+ if (activityLabel) {
+ return activityReplyResponses(activityLabel, toolNames);
+ }
+
if (text.includes(ASSERT_AGENT_CONTEXT_MARKER)) {
return {
responses: [MOCK_REPLY],
diff --git a/e2e/specs/mock/activity-labels.spec.ts b/e2e/specs/mock/activity-labels.spec.ts
new file mode 100644
index 0000000000..d139762cb9
--- /dev/null
+++ b/e2e/specs/mock/activity-labels.spec.ts
@@ -0,0 +1,222 @@
+import { expect, test } from '@playwright/test';
+import type { APIRequestContext, Page } from '@playwright/test';
+import { NEW_CHAT_PATH, messagesView, selectMockEndpoint, sendMessage } from './helpers';
+
+/** The only endpoint with `activityLabel` in e2e/config/librechat.e2e.yaml. It
+ * is dedicated to this spec: a label auto-collapses its tool group, hiding the
+ * tool cards other specs assert on. Both are non-spec `addedEndpoints`, the
+ * path the ephemeral MCP dropdown rides (mirroring steering.spec.ts) — a
+ * spec-backed endpoint would not surface the selector at all. */
+const LABELED_ENDPOINT = { label: 'Mock Provider E', model: 'mock-model-e' };
+/** Same path, no `activityLabel`: the control proving the config gates it. */
+const UNLABELED_ENDPOINT = { label: 'Mock Provider D', model: 'mock-model-d' };
+/** Distinct from the chat model, so a label request proves `activityModel` won. */
+const LABEL_MODEL = 'mock-label-model';
+const MCP_SERVER_TITLE = 'E2E Memory';
+const LABEL_SERVER = `http://127.0.0.1:${process.env.E2E_LABEL_PORT || '8889'}`;
+
+type LabelRequest = { model?: string; stream: boolean; prompt: string };
+
+const uniqueLabel = (prefix: string) =>
+ `${prefix}-${Date.now()}-${Math.floor(Math.random() * 1e4)}`;
+
+async function resetLabelServer(request: APIRequestContext) {
+ const response = await request.post(`${LABEL_SERVER}/__e2e/reset`);
+ expect(response.ok()).toBeTruthy();
+}
+
+async function setLabelBehavior(
+ request: APIRequestContext,
+ behavior: { mode?: 'ok' | 'blank' | 'error'; label?: string; delayMs?: number },
+) {
+ const response = await request.post(`${LABEL_SERVER}/__e2e/behavior`, { data: behavior });
+ expect(response.ok()).toBeTruthy();
+}
+
+async function getLabelRequests(request: APIRequestContext): Promise<LabelRequest[]> {
+ const response = await request.get(`${LABEL_SERVER}/__e2e/requests`);
+ expect(response.ok()).toBeTruthy();
+ return (await response.json()).requests as LabelRequest[];
+}
+
+/**
+ * Label requests carrying THIS test's token, which reaches the server inside
+ * the recorded tool arguments. Counting every request instead would be racy:
+ * a 5xx label response is retried by the provider client, and a retry can land
+ * after the next test has already reset the server.
+ */
+async function getLabelRequestsFor(
+ request: APIRequestContext,
+ token: string,
+): Promise<LabelRequest[]> {
+ return (await getLabelRequests(request)).filter((entry) => entry.prompt.includes(token));
+}
+
+/** Select the MCP server whose `remember_fact` tool creates the batch boundary. */
+async function selectEphemeralMCP(page: Page) {
+ await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
+ const serverItem = page.getByRole('menuitemcheckbox', { name: new RegExp(MCP_SERVER_TITLE) });
+ await expect(serverItem).toBeVisible();
+ await serverItem.click();
+ await expect(serverItem).toHaveAttribute('aria-checked', 'true');
+ await page.keyboard.press('Escape');
+ await expect(page.getByRole('button', { name: new RegExp(MCP_SERVER_TITLE) })).toBeVisible();
+}
+
+/** Run one labeled turn: two parallel tool calls => exactly one PostToolBatch. */
+async function runLabeledTurn(page: Page, label: string) {
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, LABELED_ENDPOINT);
+ await selectEphemeralMCP(page);
+ const run = await sendMessage(page, `E2E_ACTIVITY_REPLY:${label}`);
+ expect(run.ok()).toBeTruthy();
+ await expect(messagesView(page).getByText(`E2E activity reply done ${label}`)).toBeVisible({
+ timeout: 60000,
+ });
+}
+
+test.describe('activity labels', () => {
+ test.beforeEach(async ({ request }) => {
+ await resetLabelServer(request);
+ });
+
+ /**
+ * The header is the feature: once a label lands it REPLACES the generic
+ * "Used N tools" verb above the same tool cards.
+ */
+ test('renders the generated label as the tool-group header', async ({ page, request }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel('activity');
+ await setLabelBehavior(request, { label: 'Stored two facts in memory' });
+
+ await runLabeledTurn(page, label);
+
+ await expect(
+ messagesView(page).getByRole('button', { name: 'Stored two facts in memory' }),
+ ).toBeVisible({ timeout: 30000 });
+ await expect(messagesView(page).getByRole('button', { name: 'Used 2 tools' })).toHaveCount(0);
+ });
+
+ /**
+ * Regression for the bug that made real output "abysmal": the wiring passed a
+ * prompt ONLY when `activityPrompt` was configured, so a default install ran
+ * the SDK's own generic prompt and this repo's register never reached the
+ * model. Asserting on the request the model actually received is the only way
+ * to catch that — rendered text looks identical either way.
+ *
+ * Also pins the two things that make the header worth a row: it runs on the
+ * configured `activityModel`, and it sees the tool OUTPUTS (only available
+ * because the hook fires AFTER the batch), not just the arguments.
+ */
+ test('sends the register, the tool outputs, and the configured model', async ({
+ page,
+ request,
+ }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel('prompt');
+
+ await runLabeledTurn(page, label);
+
+ await expect
+ .poll(async () => (await getLabelRequestsFor(request, label)).length, { timeout: 30000 })
+ .toBe(1);
+ const [labelRequest] = await getLabelRequestsFor(request, label);
+
+ /** `activityModel` beat the agent's own model. */
+ expect(labelRequest.model).toBe(LABEL_MODEL);
+
+ /** This repo's register reached the model, not the SDK's built-in prompt. */
+ expect(labelRequest.prompt).toMatch(/never name the tools/i);
+ expect(labelRequest.prompt).toMatch(/outcome, not the attempt/i);
+ /** Deliberately NOT asserted: the "do not restate these" entry framing
+ * lives in `buildPrompt`, which only the direct fallback path uses. The
+ * SDK path builds the entry list with its own `buildActivityLabelPrompt`,
+ * so the two paths agree on the register (above) but not on that framing.
+ * Asserting it here would encode a divergence the SDK owns. */
+
+ /** Tool OUTPUTS, not just inputs — the reason this runs post-batch. */
+ expect(labelRequest.prompt).toContain(`E2E MCP memory noted: activity alpha ${label}`);
+ expect(labelRequest.prompt).toContain(`E2E MCP memory noted: activity beta ${label}`);
+ });
+
+ /**
+ * A whitespace-only label must fill null. There is deliberately no templated
+ * stand-in ("ran 2 tools" only restates the cards), so the block renders
+ * exactly as it would without the feature.
+ */
+ test('leaves the generic header when the model returns a blank label', async ({
+ page,
+ request,
+ }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel('blank');
+ await setLabelBehavior(request, { mode: 'blank' });
+
+ await runLabeledTurn(page, label);
+
+ await expect(messagesView(page).getByRole('button', { name: 'Used 2 tools' })).toBeVisible({
+ timeout: 30000,
+ });
+ });
+
+ /** Label generation is best-effort: a failing label must not fail the run. */
+ test('completes the run cleanly when label generation errors', async ({ page, request }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel('failure');
+ await setLabelBehavior(request, { mode: 'error' });
+
+ await runLabeledTurn(page, label);
+
+ /** The turn still finished (asserted in runLabeledTurn) and the block kept
+ * its generic header rather than rendering an empty row. */
+ await expect(messagesView(page).getByRole('button', { name: 'Used 2 tools' })).toBeVisible({
+ timeout: 30000,
+ });
+ /** At least one attempt was made and failed; the client may retry a 5xx,
+ * so the exact count is not part of the contract. */
+ expect((await getLabelRequestsFor(request, label)).length).toBeGreaterThanOrEqual(1);
+ });
+
+ /** `activityLabel` is per-endpoint: an endpoint without it must not call out. */
+ test('makes no label request on an endpoint without activityLabel', async ({ page, request }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel('disabled');
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, UNLABELED_ENDPOINT);
+ await selectEphemeralMCP(page);
+ const run = await sendMessage(page, `E2E_ACTIVITY_REPLY:${label}`);
+ expect(run.ok()).toBeTruthy();
+ await expect(messagesView(page).getByText(`E2E activity reply done ${label}`)).toBeVisible({
+ timeout: 60000,
+ });
+
+ await expect(messagesView(page).getByRole('button', { name: 'Used 2 tools' })).toBeVisible();
+ expect(await getLabelRequestsFor(request, label)).toHaveLength(0);
+ });
+
+ /**
+ * The label is a persisted content part at a claimed index, not a live-only
+ * decoration: it must survive a reload at the same position.
+ */
+ test('persists the label across a page reload', async ({ page, request }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel('persist');
+ await setLabelBehavior(request, { label: 'Recorded both facts for later' });
+
+ await runLabeledTurn(page, label);
+ const header = messagesView(page).getByRole('button', {
+ name: 'Recorded both facts for later',
+ });
+ await expect(header).toBeVisible({ timeout: 30000 });
+
+ await expect(page).toHaveURL(/\/c\/[0-9a-fA-F-]{36}$/, { timeout: 15000 });
+ await page.reload();
+
+ await expect(
+ messagesView(page).getByRole('button', { name: 'Recorded both facts for later' }),
+ ).toBeVisible({ timeout: 30000 });
+ /** Reload replays persisted content; it must not trigger a new generation. */
+ expect(await getLabelRequestsFor(request, label)).toHaveLength(1);
+ });
+});
diff --git a/librechat.example.yaml b/librechat.example.yaml
index aa49b4875b..51b09950f8 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -545,6 +545,14 @@ endpoints:
fetch: false
titleConvo: true
titleModel: 'claude-sonnet-4-5'
+ # Agent activity groups: collapse each block of reasoning + tool calls
+ # under a generated one-line header. Same shape as the title options.
+ activityLabel: true
+ activityModel: 'claude-3-5-haiku'
+ # activityEndpoint: 'anthropic' # run labels on another endpoint's credentials
+ # activityPrompt: 'Write a 5-9 word past-tense label...'
+ # activityMaxPerRun: 20 # cost cap per response
+ # activityCharLimit: 600 # per-entry prompt truncation
modelDisplayLabel: 'Claude (Compatible)'
# Groq Example
diff --git a/packages/api/src/agents/activityLabels/__tests__/host.spec.ts b/packages/api/src/agents/activityLabels/__tests__/host.spec.ts
new file mode 100644
index 0000000000..5de40f7428
--- /dev/null
+++ b/packages/api/src/agents/activityLabels/__tests__/host.spec.ts
@@ -0,0 +1,291 @@
+import type { AppConfig } from '@librechat/data-schemas';
+import type { EndpointDbMethods, ServerRequest } from '~/types';
+import {
+ mapCollectedMetadataToUsage,
+ resolveActivityConfig,
+ resolveActivityLabelModel,
+} from '../host';
+
+const mockGetOptions = jest.fn(async (_params: unknown) => ({
+ llmConfig: { model: 'resolved' },
+}));
+jest.mock('~/endpoints/config/providers', () => ({
+ getProviderConfig: jest.fn(() => ({
+ getOptions: (params: unknown) => mockGetOptions(params),
+ customEndpointConfig: undefined,
+ })),
+}));
+jest.mock('~/utils/headers', () => ({ resolveConfigHeaders: jest.fn() }));
+jest.mock('~/utils/env', () => ({ createSafeUser: jest.fn(() => undefined) }));
+
+const appConfig = (endpoints: Record<string, unknown>): AppConfig =>
+ ({ endpoints }) as unknown as AppConfig;
+
+describe('resolveActivityConfig', () => {
+ it('is disabled when nothing is configured', () => {
+ expect(resolveActivityConfig(undefined, 'openAI').enabled).toBe(false);
+ expect(resolveActivityConfig(appConfig({}), 'openAI').enabled).toBe(false);
+ });
+
+ it('reads the named endpoint block', () => {
+ const config = resolveActivityConfig(
+ appConfig({
+ openAI: {
+ activityLabel: true,
+ activityModel: 'gpt-4o-mini',
+ activityPrompt: 'custom',
+ activityMaxPerRun: 5,
+ activityCharLimit: 200,
+ },
+ }),
+ 'openAI',
+ );
+ expect(config).toMatchObject({
+ enabled: true,
+ model: 'gpt-4o-mini',
+ prompt: 'custom',
+ maxPerRun: 5,
+ charLimit: 200,
+ });
+ });
+
+ it('lets endpoints.all win over the named endpoint, like the title options', () => {
+ const config = resolveActivityConfig(
+ appConfig({
+ all: { activityLabel: true, activityModel: 'shared-model' },
+ openAI: { activityLabel: false, activityModel: 'ignored' },
+ }),
+ 'openAI',
+ );
+ expect(config.enabled).toBe(true);
+ expect(config.model).toBe('shared-model');
+ });
+
+ it('falls back to a custom endpoint config when the name is absent', () => {
+ const config = resolveActivityConfig(appConfig({}), 'MyProxy', {
+ activityLabel: true,
+ activityModel: 'proxy-mini',
+ });
+ expect(config.enabled).toBe(true);
+ expect(config.model).toBe('proxy-mini');
+ });
+
+ it('treats a missing activityLabel flag as opt-out even with other fields set', () => {
+ const config = resolveActivityConfig(
+ appConfig({ openAI: { activityModel: 'gpt-4o-mini' } }),
+ 'openAI',
+ );
+ expect(config.enabled).toBe(false);
+ expect(config.model).toBe('gpt-4o-mini');
+ });
+
+ /** `initializeAgent` rewrites `agent.endpoint` to the backing provider, so
+ * the PUBLIC endpoint's block (`endpoints.agents`) must still be honored
+ * — it inherits every activity field via `agentsEndpointSchema`. */
+ it('honors the public agents endpoint when the agent endpoint was rewritten', () => {
+ const config = resolveActivityConfig(
+ appConfig({ agents: { activityLabel: true, activityModel: 'agents-mini' } }),
+ 'openAI',
+ undefined,
+ 'agents',
+ );
+ expect(config.enabled).toBe(true);
+ expect(config.model).toBe('agents-mini');
+ });
+
+ it('lets the public endpoint win per field over the backing provider', () => {
+ const config = resolveActivityConfig(
+ appConfig({
+ agents: { activityModel: 'agents-mini' },
+ openAI: { activityLabel: true, activityModel: 'provider-mini', activityMaxPerRun: 3 },
+ }),
+ 'openAI',
+ undefined,
+ 'agents',
+ );
+ /** Field-wise: model from `agents`, the rest falls through to `openAI`. */
+ expect(config.enabled).toBe(true);
+ expect(config.model).toBe('agents-mini');
+ expect(config.maxPerRun).toBe(3);
+ });
+
+ it('keeps endpoints.all above the public endpoint', () => {
+ const config = resolveActivityConfig(
+ appConfig({
+ all: { activityModel: 'shared-model' },
+ agents: { activityLabel: true, activityModel: 'agents-mini' },
+ }),
+ 'openAI',
+ undefined,
+ 'agents',
+ );
+ expect(config.model).toBe('shared-model');
+ });
+});
+
+describe('resolveActivityLabelModel model precedence', () => {
+ const db = {} as EndpointDbMethods;
+ const resolve = (endpointConfig: Record<string, unknown>) =>
+ resolveActivityLabelModel({
+ req: { config: appConfig({ openAI: endpointConfig }) } as unknown as ServerRequest,
+ agent: { endpoint: 'openAI', model_parameters: { model: 'run-model' } },
+ ids: {},
+ db,
+ });
+
+ beforeEach(() => {
+ mockGetOptions.mockClear();
+ });
+
+ /** An EXPLICIT `activityModel: current_model` names the run model — a
+ * configured `titleModel` must not shadow it via the fallback chain. */
+ it('resolves an explicit current_model sentinel to the run model over titleModel', async () => {
+ await resolve({ activityLabel: true, activityModel: 'current_model', titleModel: 'haiku' });
+ expect(mockGetOptions).toHaveBeenCalledWith(
+ expect.objectContaining({ model_parameters: { model: 'run-model' } }),
+ );
+ });
+
+ it('falls back to titleModel only when activityModel is absent', async () => {
+ await resolve({ activityLabel: true, titleModel: 'haiku' });
+ expect(mockGetOptions).toHaveBeenCalledWith(
+ expect.objectContaining({ model_parameters: { model: 'haiku' } }),
+ );
+ });
+
+ it('prefers an explicit activityModel over everything', async () => {
+ await resolve({ activityLabel: true, activityModel: 'label-model', titleModel: 'haiku' });
+ expect(mockGetOptions).toHaveBeenCalledWith(
+ expect.objectContaining({ model_parameters: { model: 'label-model' } }),
+ );
+ });
+
+ /** The label often runs a cheaper model than the primary generation, so
+ * primary-only options (thinking, output caps) must be stripped exactly
+ * like the title path — while proxy headers survive. */
+ it('strips primary-generation options but keeps the Anthropic header carrier', async () => {
+ mockGetOptions.mockResolvedValueOnce({
+ llmConfig: {
+ model: 'resolved',
+ thinking: { type: 'enabled', budget_tokens: 4096 },
+ maxOutputTokens: 8192,
+ streaming: true,
+ modelKwargs: { max_output_tokens: 8192, service_tier: 'flex' },
+ clientOptions: { defaultHeaders: { 'x-proxy-key': 'abc' } },
+ },
+ } as never);
+ const resolved = await resolve({ activityLabel: true, activityModel: 'label-model' });
+ const clientOptions = resolved.clientOptions as Record<string, unknown>;
+ expect(clientOptions.thinking).toBeUndefined();
+ expect(clientOptions.maxOutputTokens).toBeUndefined();
+ expect(clientOptions.streaming).toBeUndefined();
+ expect(clientOptions.modelKwargs).toEqual({ service_tier: 'flex' });
+ expect(clientOptions.clientOptions).toEqual({
+ defaultHeaders: { 'x-proxy-key': 'abc' },
+ });
+ });
+
+ /** The primary cap is not merely stripped — it is REPLACED with a small
+ * label-specific one, so a model ignoring the 4–9-word instruction (or
+ * steered by injected tool output) cannot generate and bill its
+ * provider-default output for a header. */
+ it('replaces the primary maxTokens with the small label cap', async () => {
+ mockGetOptions.mockResolvedValueOnce({
+ llmConfig: { model: 'resolved', maxTokens: 64_000 },
+ } as never);
+ const resolved = await resolve({ activityLabel: true, activityModel: 'label-model' });
+ expect((resolved.clientOptions as Record<string, unknown>).maxTokens).toBe(256);
+ });
+
+ /** GPT-5+ rejects `max_tokens`: the label cap must ride in modelKwargs
+ * exactly as the OpenAI builder routes primary caps. */
+ it('routes the label cap into modelKwargs for GPT-5-family models', async () => {
+ mockGetOptions.mockResolvedValueOnce({
+ llmConfig: { model: 'gpt-5.2' },
+ } as never);
+ const resolved = await resolve({ activityLabel: true, activityModel: 'gpt-5.2' });
+ const clientOptions = resolved.clientOptions as Record<string, unknown>;
+ expect(clientOptions.maxTokens).toBeUndefined();
+ expect(clientOptions.modelKwargs).toEqual({ max_completion_tokens: 256 });
+ });
+
+ /** o-series models reject `max_tokens` and get NO cap — title parity;
+ * the 200-char persistence bound still applies. */
+ it('sets no cap at all for o-series reasoning models', async () => {
+ mockGetOptions.mockResolvedValueOnce({
+ llmConfig: { model: 'o3-mini' },
+ } as never);
+ const resolved = await resolve({ activityLabel: true, activityModel: 'o3-mini' });
+ const clientOptions = resolved.clientOptions as Record<string, unknown>;
+ expect(clientOptions.maxTokens).toBeUndefined();
+ expect(clientOptions.modelKwargs).toBeUndefined();
+ expect(clientOptions.maxOutputTokens).toBeUndefined();
+ });
+
+ /** The Anthropic carrier holds client CONSTRUCTION options — for
+ * user-provided base URLs that includes the SSRF-safe fetch dispatcher —
+ * so it must survive the strip even with no custom headers, and by the
+ * SAME reference. */
+ it('preserves the SSRF-safe carrier even without defaultHeaders', async () => {
+ const carrier = { fetchOptions: { dispatcher: { kind: 'guarded' }, redirect: 'error' } };
+ mockGetOptions.mockResolvedValueOnce({
+ llmConfig: { model: 'resolved', thinking: { type: 'enabled' }, clientOptions: carrier },
+ } as never);
+ const resolved = await resolve({ activityLabel: true, activityModel: 'label-model' });
+ expect((resolved.clientOptions as Record<string, unknown>).clientOptions).toBe(carrier);
+ });
+});
+
+describe('mapCollectedMetadataToUsage cache tokens', () => {
+ it('carries Anthropic raw cache fields as normalized details', () => {
+ const [usage] = mapCollectedMetadataToUsage([
+ {
+ usage: {
+ input_tokens: 100,
+ output_tokens: 9,
+ cache_read_input_tokens: 80,
+ cache_creation_input_tokens: 10,
+ },
+ },
+ ]);
+ expect(usage).toEqual({
+ input_tokens: 100,
+ output_tokens: 9,
+ input_token_details: { cache_read: 80, cache_creation: 10 },
+ });
+ });
+
+ it('maps OpenAI cached_tokens to cache_read', () => {
+ const [usage] = mapCollectedMetadataToUsage([
+ {
+ usage: {
+ prompt_tokens: 50,
+ completion_tokens: 7,
+ prompt_tokens_details: { cached_tokens: 40 },
+ },
+ },
+ ]);
+ expect(usage.input_token_details).toEqual({ cache_read: 40, cache_creation: undefined });
+ });
+
+ it('passes through LangChain-standard input_token_details', () => {
+ const [usage] = mapCollectedMetadataToUsage([
+ {
+ usage_metadata: {
+ input_tokens: 30,
+ output_tokens: 5,
+ input_token_details: { cache_read: 20, cache_creation: 4 },
+ },
+ },
+ ]);
+ expect(usage.input_token_details).toEqual({ cache_read: 20, cache_creation: 4 });
+ });
+
+ it('omits the details object entirely when no cache tokens are reported', () => {
+ const [usage] = mapCollectedMetadataToUsage([
+ { usage: { input_tokens: 10, output_tokens: 2 } },
+ ]);
+ expect(usage).toEqual({ input_tokens: 10, output_tokens: 2 });
+ expect('input_token_details' in usage).toBe(false);
+ });
+});
diff --git a/packages/api/src/agents/activityLabels/__tests__/runtime.spec.ts b/packages/api/src/agents/activityLabels/__tests__/runtime.spec.ts
new file mode 100644
index 0000000000..ac48f31463
--- /dev/null
+++ b/packages/api/src/agents/activityLabels/__tests__/runtime.spec.ts
@@ -0,0 +1,696 @@
+import { Providers } from '@librechat/agents';
+import type { PostToolBatchHookInput } from '@librechat/agents';
+
+const mockInvoke = jest.fn();
+const mockInitializeModel = jest.fn(() => ({ invoke: mockInvoke }));
+
+jest.mock('@librechat/agents', () => ({
+ ...jest.requireActual('@librechat/agents'),
+ initializeModel: (...args: unknown[]) => mockInitializeModel(...(args as [])),
+}));
+
+import {
+ ACTIVITY_INSTRUCTION,
+ buildPrompt,
+ classifyBatch,
+ createActivityLabelHook,
+} from '../runtime';
+import type { ActivityLabelBatchMeta, ActivityLabelSlot, GenerateLabelPayload } from '../runtime';
+
+/** Flushes the hook's detached generation chain. */
+async function flushDetached(): Promise<void> {
+ for (let i = 0; i < 4; i += 1) {
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+}
+
+function batchInput(overrides: Partial<PostToolBatchHookInput> = {}): PostToolBatchHookInput {
+ return {
+ hook_event_name: 'PostToolBatch',
+ runId: 'run-1',
+ entries: [
+ {
+ toolName: 'web_search',
+ toolInput: { query: 'librechat' },
+ toolUseId: 'tool-1',
+ status: 'success',
+ toolOutput: 'ten results about librechat',
+ },
+ ],
+ ...overrides,
+ } as PostToolBatchHookInput;
+}
+
+describe('classifyBatch', () => {
+ it('collects the covered tool calls and derives batch status', () => {
+ const meta = classifyBatch([
+ { toolName: 'web_search', toolInput: {}, toolUseId: 'a', status: 'success', toolOutput: '' },
+ { toolName: 'read_file', toolInput: {}, toolUseId: 'b', status: 'success', toolOutput: '' },
+ { toolName: 'edit_file', toolInput: {}, toolUseId: 'c', status: 'error', error: 'denied' },
+ ]);
+ expect(meta.toolCallIds).toEqual(['a', 'b', 'c']);
+ expect(meta.status).toBe('partial');
+ });
+
+ it('reports failed when every tool errors', () => {
+ const meta = classifyBatch([
+ { toolName: 'bash_tool', toolInput: {}, toolUseId: 'x', status: 'error', error: 'boom' },
+ ]);
+ expect(meta.status).toBe('failed');
+ });
+
+ /** A tool-type tally could only echo the cards under the header, so the
+ * metadata deliberately has no place to put one. */
+ it('carries no tool-type tally', () => {
+ const meta = classifyBatch([
+ { toolName: 'bash_tool', toolInput: {}, toolUseId: 'x', status: 'success', toolOutput: '' },
+ ]);
+ expect(Object.keys(meta).sort()).toEqual(['status', 'toolCallIds']);
+ });
+});
+
+describe('ACTIVITY_INSTRUCTION', () => {
+ it('forbids restating what the tool cards already show', () => {
+ expect(ACTIVITY_INSTRUCTION).toMatch(/never name the tools/i);
+ expect(ACTIVITY_INSTRUCTION).toMatch(/never count them/i);
+ expect(ACTIVITY_INSTRUCTION).toMatch(/never echo the arguments/i);
+ });
+
+ it('asks for a past-tense outcome, not the attempt', () => {
+ expect(ACTIVITY_INSTRUCTION).toMatch(/past tense/i);
+ expect(ACTIVITY_INSTRUCTION).toMatch(/outcome, not the attempt/i);
+ });
+});
+
+describe('buildPrompt', () => {
+ it('carries intent and marks the calls as reference material', () => {
+ const prompt = buildPrompt(
+ [
+ {
+ toolName: 'bash_tool',
+ toolInput: { command: 'ls /mnt/data' },
+ toolUseId: 'a',
+ status: 'success',
+ toolOutput: 'empty',
+ },
+ ],
+ 600,
+ {
+ lastAssistantText: 'Let me check what is actually in /mnt/data',
+ thinkingExcerpts: ['The filesystem seems to reset between calls'],
+ },
+ );
+ expect(prompt).toContain('Let me check what is actually in /mnt/data');
+ expect(prompt).toContain('The filesystem seems to reset between calls');
+ expect(prompt).toContain('do not restate these');
+ /** Outputs are the whole reason this runs after the batch. */
+ expect(prompt).toContain('empty');
+ });
+
+ it('uses the caller instruction verbatim when one is supplied', () => {
+ const prompt = buildPrompt([], 600, undefined, 'CUSTOM RULE');
+ expect(prompt.startsWith('CUSTOM RULE')).toBe(true);
+ expect(prompt).not.toContain('git commit subject');
+ });
+
+ it('renders previous headers ahead of block context, oldest dropped at the cap', () => {
+ const prompt = buildPrompt(
+ batchInput().entries,
+ 600,
+ { lastAssistantText: 'Now verifying persistence.' },
+ undefined,
+ ['One header', 'Two header', 'Three header', 'Four header'],
+ );
+ expect(prompt).toContain('Previous headers in this run (most recent last):');
+ expect(prompt).not.toContain('- One header');
+ expect(prompt.indexOf('- Two header')).toBeLessThan(prompt.indexOf('- Three header'));
+ expect(prompt.indexOf('- Four header')).toBeLessThan(prompt.indexOf('Intent'));
+ });
+
+ it('omits the previous-headers section when the list is empty', () => {
+ /** The instruction itself references "Previous headers", so the absence
+ * check must target the section heading, not the phrase. */
+ const prompt = buildPrompt(batchInput().entries, 600, undefined, undefined, []);
+ expect(prompt).not.toContain('Previous headers in this run');
+ });
+
+ /**
+ * Serialization is bounded: a multi-megabyte tool result must not be fully
+ * materialized just to keep a few hundred characters, and what IS kept must
+ * truncate exactly as the unbounded path did.
+ */
+ it('truncates giant outputs with the ellipsis without serializing them whole', () => {
+ const giant = 'x'.repeat(5_000_000);
+ const prompt = buildPrompt(
+ [
+ {
+ toolName: 'reader',
+ toolInput: { rows: Array.from({ length: 100_000 }, (_, i) => ({ i, giant })) },
+ toolUseId: 'a',
+ status: 'success',
+ toolOutput: giant,
+ },
+ ],
+ 600,
+ );
+ const line = prompt.split('\n').find((l) => l.startsWith('- reader')) ?? '';
+ /** Instruction + intent + one entry line: nothing retains the megabytes. */
+ expect(prompt.length).toBeLessThan(3_000);
+ expect(line).toContain('…');
+ expect(line).toContain('x'.repeat(100));
+ });
+
+ /** `activityCharLimit` is documented as the per-entry limit for tool input
+ * AND output — a hard-coded input cap would make the setting unable to
+ * reach a distinguishing path or query past the first 200 characters. */
+ it('applies the configured charLimit to tool inputs, not a hard-coded cap', () => {
+ const longQuery = 'q'.repeat(400);
+ const prompt = buildPrompt(
+ [
+ {
+ toolName: 'search',
+ toolInput: { query: longQuery },
+ toolUseId: 'a',
+ status: 'success',
+ toolOutput: 'ok',
+ },
+ ],
+ 450,
+ );
+ /** 400-char argument survives intact under a 450 limit (the old 200-char
+ * cap would have cut it), while a tighter limit still truncates. */
+ expect(prompt).toContain(longQuery);
+ const tight = buildPrompt(
+ [
+ {
+ toolName: 'search',
+ toolInput: { query: longQuery },
+ toolUseId: 'a',
+ status: 'success',
+ toolOutput: 'ok',
+ },
+ ],
+ 50,
+ );
+ expect(tight).not.toContain('q'.repeat(60));
+ expect(tight).toContain('…');
+ });
+
+ /** Per-entry truncation alone leaves the batch dimension unbounded: a
+ * parallel batch of hundreds of calls must not build a prompt past the
+ * fast model's window. */
+ it('bounds the total entries section for giant parallel batches', () => {
+ const entries = Array.from({ length: 200 }, (_, i) => ({
+ toolName: `tool_${i}`,
+ toolInput: { i },
+ toolUseId: `t${i}`,
+ status: 'success' as const,
+ toolOutput: 'y'.repeat(500),
+ }));
+ const prompt = buildPrompt(entries, 600);
+ expect(prompt.length).toBeLessThan(15_000);
+ expect(prompt).toMatch(/\(\+\d+ more tool calls not shown\)/);
+ /** Prefix semantics: the first entry is always present in full. */
+ expect(prompt).toContain('- tool_0(');
+ expect(prompt).not.toContain('- tool_199(');
+ });
+
+ it('shows every entry when the batch fits the budget', () => {
+ const entries = Array.from({ length: 3 }, (_, i) => ({
+ toolName: `tool_${i}`,
+ toolInput: { i },
+ toolUseId: `t${i}`,
+ status: 'success' as const,
+ toolOutput: 'ok',
+ }));
+ const prompt = buildPrompt(entries, 600);
+ expect(prompt).toContain('- tool_2(');
+ expect(prompt).not.toContain('more tool calls not shown');
+ });
+
+ it('serializes small structured values exactly like JSON.stringify', () => {
+ const toolInput = { q: 'docs', filters: { lang: 'en', page: 2 }, ids: [1, 2] };
+ const prompt = buildPrompt(
+ [{ toolName: 'search', toolInput, toolUseId: 'a', status: 'success', toolOutput: 'ok' }],
+ 600,
+ );
+ expect(prompt).toContain(`search(${JSON.stringify(toolInput)})`);
+ });
+});
+
+describe('createActivityLabelHook', () => {
+ let slots: Array<{ index: number; filled: Array<string | null> }>;
+ let claimSlot: () => ActivityLabelSlot;
+ const resolveLLM = jest.fn(async () => ({
+ provider: Providers.OPENAI,
+ clientOptions: { model: 'small-model' },
+ }));
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ slots = [];
+ claimSlot = () => {
+ const record = { index: slots.length, filled: [] as Array<string | null> };
+ slots.push(record);
+ return {
+ index: record.index,
+ fill: (text) => {
+ record.filled.push(text);
+ return true;
+ },
+ };
+ };
+ mockInvoke.mockResolvedValue({ content: ' Searched the web for LibreChat docs. ' });
+ });
+
+ it('returns {} synchronously and fills the claimed slot when the model resolves', async () => {
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM });
+ const result = await hook(batchInput(), new AbortController().signal);
+ expect(result).toEqual({});
+ expect(slots).toHaveLength(1);
+ expect(slots[0].filled).toHaveLength(0);
+
+ await flushDetached();
+ expect(slots[0].filled).toEqual(['Searched the web for LibreChat docs.']);
+ expect(mockInitializeModel).toHaveBeenCalledWith(
+ expect.objectContaining({
+ provider: Providers.OPENAI,
+ clientOptions: expect.objectContaining({ model: 'small-model', streaming: false }),
+ }),
+ );
+ });
+
+ it('claims no slot for an empty batch', async () => {
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM });
+ await hook(batchInput({ entries: [] }), new AbortController().signal);
+ await flushDetached();
+ expect(slots).toHaveLength(0);
+ expect(mockInvoke).not.toHaveBeenCalled();
+ });
+
+ it('fills null when generation fails, without rejecting', async () => {
+ mockInvoke.mockRejectedValue(new Error('provider down'));
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM });
+ await expect(hook(batchInput(), new AbortController().signal)).resolves.toEqual({});
+ await flushDetached();
+ expect(slots[0].filled).toEqual([null]);
+ });
+
+ it('fills null for blank model output', async () => {
+ mockInvoke.mockResolvedValue({ content: ' ' });
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ expect(slots[0].filled).toEqual([null]);
+ });
+
+ /** A pure-handoff batch gets no label: the transfer card already names
+ * the destination, and the client renders transfers standalone, so a
+ * label could only orphan. Must not consume `maxPerRun` either. */
+ it('claims nothing for a batch of only transfer calls', async () => {
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM });
+ await hook(
+ batchInput({
+ entries: [
+ {
+ toolName: 'lc_transfer_to_billing_agent',
+ toolInput: {},
+ toolUseId: 'x1',
+ status: 'success',
+ toolOutput: '',
+ },
+ ],
+ }),
+ new AbortController().signal,
+ );
+ await flushDetached();
+ expect(slots).toHaveLength(0);
+ expect(mockInvoke).not.toHaveBeenCalled();
+ });
+
+ /** Mixed batches skip too: the client flushes the block at the transfer
+ * card, so the label would orphan even when real tools ran alongside. */
+ it('claims nothing for a mixed batch containing a transfer call', async () => {
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM });
+ await hook(
+ batchInput({
+ entries: [
+ {
+ toolName: 'lc_transfer_to_billing_agent',
+ toolInput: {},
+ toolUseId: 'x1',
+ status: 'success',
+ toolOutput: '',
+ },
+ {
+ toolName: 'web_search',
+ toolInput: { query: 'refund policy' },
+ toolUseId: 'x2',
+ status: 'success',
+ toolOutput: 'found it',
+ },
+ ],
+ }),
+ new AbortController().signal,
+ );
+ await flushDetached();
+ expect(slots).toHaveLength(0);
+ expect(mockInvoke).not.toHaveBeenCalled();
+ });
+
+ it('skips subagent scopes entirely', async () => {
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM });
+ await hook(batchInput({ agentId: 'subagent-1' }), new AbortController().signal);
+ await flushDetached();
+ expect(slots).toHaveLength(0);
+ expect(mockInvoke).not.toHaveBeenCalled();
+ });
+
+ it('passes executingAgentId through to the claimed slot metadata', async () => {
+ const captured: ActivityLabelBatchMeta[] = [];
+ const hook = createActivityLabelHook({
+ claimSlot: (meta) => {
+ captured.push(meta);
+ return { index: 0, fill: () => true };
+ },
+ resolveLLM,
+ });
+ await hook(batchInput({ executingAgentId: 'agent-a' }), new AbortController().signal);
+ await flushDetached();
+ expect(captured[0].executingAgentId).toBe('agent-a');
+ expect(captured[0].status).toBe('ok');
+ });
+
+ it('prefers the SDK-backed generateLabel path with a per-slot trace seed', async () => {
+ const generateLabel = jest.fn(async () => 'Searched runtime release notes');
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM, generateLabel });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ expect(generateLabel).toHaveBeenCalledWith(
+ expect.objectContaining({
+ traceSeed: 'run-1-activity-0',
+ charLimit: 600,
+ entries: expect.any(Array),
+ context: expect.any(Object),
+ signal: expect.any(AbortSignal),
+ }),
+ );
+ expect(mockInitializeModel).not.toHaveBeenCalled();
+ expect(slots[0].filled).toEqual(['Searched runtime release notes']);
+ });
+
+ describe('continuity', () => {
+ it('threads committed labels into later payloads, oldest dropped at the cap', async () => {
+ const payloads: GenerateLabelPayload[] = [];
+ let seq = 0;
+ const generateLabel = jest.fn(async (payload: GenerateLabelPayload) => {
+ payloads.push(payload);
+ seq += 1;
+ return `Header ${seq}`;
+ });
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM, generateLabel });
+ for (let i = 0; i < 5; i += 1) {
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ }
+ expect(payloads[0].previousLabels).toBeUndefined();
+ expect(payloads[1].previousLabels).toEqual(['Header 1']);
+ expect(payloads[3].previousLabels).toEqual(['Header 1', 'Header 2', 'Header 3']);
+ expect(payloads[4].previousLabels).toEqual(['Header 2', 'Header 3', 'Header 4']);
+ });
+
+ it('excludes uncommitted fills from continuity', async () => {
+ const payloads: GenerateLabelPayload[] = [];
+ const generateLabel = jest.fn(async (payload: GenerateLabelPayload) => {
+ payloads.push(payload);
+ return 'Dropped header';
+ });
+ let claims = 0;
+ const hook = createActivityLabelHook({
+ claimSlot: () => ({ index: claims++, fill: () => false }),
+ resolveLLM,
+ generateLabel,
+ });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ expect(payloads[1].previousLabels).toBeUndefined();
+ });
+
+ it('seeds continuity from resumed labels, in index order', async () => {
+ const payloads: GenerateLabelPayload[] = [];
+ const generateLabel = jest.fn(async (payload: GenerateLabelPayload) => {
+ payloads.push(payload);
+ return 'Fresh header';
+ });
+ let claims = 0;
+ const hook = createActivityLabelHook({
+ claimSlot: () => ({ index: 10 + claims++, fill: () => true }),
+ resolveLLM,
+ generateLabel,
+ initialGeneratedCount: 2,
+ initialLabels: [
+ { index: 7, text: 'Resumed late header' },
+ { index: 4, text: 'Resumed early header' },
+ ],
+ });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ expect(payloads[0].previousLabels).toEqual(['Resumed early header', 'Resumed late header']);
+ });
+
+ it('renders previous headers on the fallback path', async () => {
+ mockInvoke
+ .mockResolvedValueOnce({ content: 'Wrote the marker file' })
+ .mockResolvedValueOnce({ content: 'Confirmed the marker persists' });
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ const secondPrompt = mockInvoke.mock.calls[1][0] as string;
+ expect(secondPrompt).toContain(
+ 'Previous headers in this run (most recent last):\n- Wrote the marker file',
+ );
+ });
+ });
+
+ it('claims nothing when the host abort signal is already aborted', async () => {
+ const controller = new AbortController();
+ controller.abort();
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM, signal: controller.signal });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ expect(slots).toHaveLength(0);
+ expect(mockInvoke).not.toHaveBeenCalled();
+ });
+
+ it('runs per-generation invoke callbacks and collects usage on the fallback path', async () => {
+ const collect = jest.fn();
+ const handleLLMEnd = jest.fn();
+ const getInvokeCallbacks = jest.fn(() => ({ callbacks: [{ handleLLMEnd }], collect }));
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM, getInvokeCallbacks });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ expect(getInvokeCallbacks).toHaveBeenCalledTimes(1);
+ expect(mockInvoke).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ callbacks: [{ handleLLMEnd }] }),
+ );
+ expect(collect).toHaveBeenCalledTimes(1);
+ });
+
+ /**
+ * Billing runs only AFTER the visible label commits. Billing first let the
+ * settlement deadline expire during the balance write, after which the fill
+ * was dropped as out-of-scope: charged, never shown.
+ */
+ it('collects usage after the fill commits, in that order', async () => {
+ const order: string[] = [];
+ const collect = jest.fn(() => void order.push('collect'));
+ const getInvokeCallbacks = jest.fn(() => ({ callbacks: [], collect }));
+ const hook = createActivityLabelHook({
+ claimSlot: () => ({
+ index: 0,
+ fill: () => {
+ order.push('fill');
+ return true;
+ },
+ }),
+ resolveLLM,
+ getInvokeCallbacks,
+ });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ expect(order).toEqual(['fill', 'collect']);
+ });
+
+ /**
+ * The settle must cover billing, not just the fill: deferred usage runs
+ * after `fill` resolves, so a settle keyed on fills alone would let
+ * finalization flush the usage sink while billing was still in flight.
+ */
+ it('reports a detached task that resolves only after usage collection', async () => {
+ let releaseCollect: () => void = () => undefined;
+ const collect = jest.fn(() => new Promise<void>((resolve) => (releaseCollect = resolve)));
+ const tracked: Array<Promise<void>> = [];
+ const hook = createActivityLabelHook({
+ claimSlot: () => ({ index: 0, fill: () => true }),
+ resolveLLM,
+ getInvokeCallbacks: () => ({ callbacks: [], collect }),
+ trackTask: (task) => void tracked.push(task),
+ });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ expect(tracked).toHaveLength(1);
+ let settled = false;
+ void tracked[0].then(() => (settled = true));
+ await flushDetached();
+ /** Collection is still pending, so the task must be too. */
+ expect(collect).toHaveBeenCalledTimes(1);
+ expect(settled).toBe(false);
+ releaseCollect();
+ await flushDetached();
+ expect(settled).toBe(true);
+ });
+
+ it('suppresses usage collection when the host drops the fill', async () => {
+ const collect = jest.fn();
+ const getInvokeCallbacks = jest.fn(() => ({ callbacks: [], collect }));
+ const hook = createActivityLabelHook({
+ /** `false` = the response finalized and the label never surfaced. */
+ claimSlot: () => ({ index: 0, fill: () => false }),
+ resolveLLM,
+ getInvokeCallbacks,
+ });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ expect(collect).not.toHaveBeenCalled();
+ });
+
+ it('runs usage accounting the SDK path deferred, after the commit', async () => {
+ const order: string[] = [];
+ const recordUsage = jest.fn(() => void order.push('usage'));
+ const generateLabel = jest.fn(
+ async ({ deferUsage }: { deferUsage: (fn: () => void) => void }) => {
+ deferUsage(recordUsage);
+ return 'Traced the failing request';
+ },
+ );
+ const hook = createActivityLabelHook({
+ claimSlot: () => ({
+ index: 0,
+ fill: () => {
+ order.push('fill');
+ return true;
+ },
+ }),
+ resolveLLM,
+ generateLabel,
+ });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ expect(order).toEqual(['fill', 'usage']);
+ });
+
+ /** Title-convention estimated billing: when the provider omits usage
+ * metadata, the biller falls back to counting text — so the hook must
+ * hand it the EXACT prompt the direct path sent plus the final label. */
+ it('passes a lazy usage estimate carrying the exact prompt and raw completion', async () => {
+ /** Multi-line reply: only line one persists as the label, but the model
+ * GENERATED (and the provider would bill) the whole thing — the
+ * estimate must count the raw output, not the normalized 200-char cap. */
+ mockInvoke.mockResolvedValue({
+ content: 'Searched the web for LibreChat docs.\nExtra verbose reasoning the model emitted.',
+ });
+ const collect = jest.fn();
+ const getInvokeCallbacks = jest.fn(() => ({ callbacks: [], collect }));
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM, getInvokeCallbacks });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ expect(slots[0].filled).toEqual(['Searched the web for LibreChat docs.']);
+ expect(collect).toHaveBeenCalledTimes(1);
+ const estimateThunk = collect.mock.calls[0][0] as () => {
+ promptText: string;
+ completionText: string;
+ };
+ expect(typeof estimateThunk).toBe('function');
+ const estimate = estimateThunk();
+ expect(estimate.promptText).toBe(mockInvoke.mock.calls[0][0]);
+ expect(estimate.completionText).toContain('Extra verbose reasoning the model emitted.');
+ });
+
+ it('passes no estimate when generation threw before a label', async () => {
+ const recordUsage = jest.fn();
+ const generateLabel = jest.fn(
+ async ({ deferUsage }: { deferUsage: (fn: (estimate?: unknown) => void) => void }) => {
+ deferUsage(recordUsage);
+ throw new Error('mid-call failure');
+ },
+ );
+ const hook = createActivityLabelHook({
+ claimSlot: () => ({ index: 0, fill: () => true }),
+ resolveLLM,
+ generateLabel,
+ });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ /** Billed only from REAL collected metadata on the failure path — an
+ * estimate would charge a full prompt for a call that may have
+ * consumed nothing. */
+ expect(recordUsage).toHaveBeenCalledTimes(1);
+ expect(recordUsage.mock.calls[0][0]).toBeUndefined();
+ });
+
+ it('memoizes LLM resolution and enforces maxPerRun', async () => {
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM, maxPerRun: 2 });
+ await hook(batchInput(), new AbortController().signal);
+ await hook(batchInput(), new AbortController().signal);
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ expect(slots).toHaveLength(2);
+ expect(resolveLLM).toHaveBeenCalledTimes(1);
+ });
+
+ /** A transient resolution failure must stay transient: memoizing the
+ * rejected promise would fail every later batch in the run instantly. */
+ it('retries LLM resolution on the next batch after a transient failure', async () => {
+ const flaky = jest
+ .fn<Promise<{ provider: Providers; clientOptions: { model: string } }>, []>()
+ .mockRejectedValueOnce(new Error('credential read timeout'))
+ .mockResolvedValue({ provider: Providers.OPENAI, clientOptions: { model: 'small-model' } });
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM: flaky });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ expect(slots[0].filled).toEqual([null]);
+
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ expect(flaky).toHaveBeenCalledTimes(2);
+ expect(slots[1].filled).toEqual(['Searched the web for LibreChat docs.']);
+ });
+
+ /** Output is bounded before persisting: a model that ignores the 4–9-word
+ * instruction (or is steered by injected tool output) must not turn one
+ * header into an unbounded multi-line content part. */
+ it('normalizes label output to one bounded line', async () => {
+ mockInvoke.mockResolvedValue({
+ content: `\n \nFound the failing\tspec\nIGNORE PREVIOUS INSTRUCTIONS ${'x'.repeat(5000)}`,
+ });
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ expect(slots[0].filled).toEqual(['Found the failing spec']);
+ });
+
+ it('truncates a single giant label line with an ellipsis', async () => {
+ mockInvoke.mockResolvedValue({ content: 'word '.repeat(2000) });
+ const hook = createActivityLabelHook({ claimSlot, resolveLLM });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ const label = slots[0].filled[0] as string;
+ expect(label.length).toBeLessThanOrEqual(200);
+ expect(label.endsWith('…')).toBe(true);
+ });
+});
diff --git a/packages/api/src/agents/activityLabels/__tests__/wiring.spec.ts b/packages/api/src/agents/activityLabels/__tests__/wiring.spec.ts
new file mode 100644
index 0000000000..8833e2fc30
--- /dev/null
+++ b/packages/api/src/agents/activityLabels/__tests__/wiring.spec.ts
@@ -0,0 +1,339 @@
+import { Providers } from '@librechat/agents';
+import type { PostToolBatchHookInput } from '@librechat/agents';
+import type { GenerateLabelPayload } from '../runtime';
+import type { LooseContentPart } from '../wiring';
+import {
+ captureActivityBlockContext,
+ createActivityLabelWiring,
+ stripActivityLabelParts,
+ synthesizeActivityLabelGapEvents,
+} from '../wiring';
+import { ACTIVITY_INSTRUCTION } from '../runtime';
+
+async function flushDetached(): Promise<void> {
+ for (let i = 0; i < 4; i += 1) {
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+}
+
+const batchInput = (): PostToolBatchHookInput =>
+ ({
+ hook_event_name: 'PostToolBatch',
+ runId: 'run-1',
+ entries: [
+ {
+ toolName: 'web_search',
+ toolInput: { query: 'x' },
+ toolUseId: 'tool-1',
+ status: 'success',
+ toolOutput: 'ok',
+ },
+ ],
+ }) as PostToolBatchHookInput;
+
+describe('createActivityLabelWiring', () => {
+ it('captures block context BEFORE pushing the label part', async () => {
+ const parts: Array<LooseContentPart | null | undefined> = [
+ { type: 'think', think: 'Comparing runtime versions before searching' },
+ { type: 'tool_call', tool_call: { id: 'tool-1' } },
+ ];
+ const capturedPayloads: GenerateLabelPayload[] = [];
+ const generateLabel = jest.fn(async (payload: GenerateLabelPayload) => {
+ capturedPayloads.push(payload);
+ return 'Searched runtime versions';
+ });
+ const { hook } = createActivityLabelWiring({
+ getContentParts: () => parts,
+ bumpIndexOffset: jest.fn(),
+ emitLabelEvent: jest.fn(async () => undefined),
+ trackPendingFill: jest.fn(),
+ resolveLLM: jest.fn(async () => ({
+ provider: Providers.OPENAI,
+ clientOptions: { model: 'm' },
+ })),
+ generateLabel,
+ });
+
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+
+ expect(generateLabel).toHaveBeenCalledTimes(1);
+ expect(capturedPayloads[0]?.context.thinkingExcerpts).toEqual([
+ 'Comparing runtime versions before searching',
+ ]);
+ /** And the label part landed at the tail with the claimed index. */
+ expect(parts[2]).toMatchObject({ type: 'activity_label', pending: false });
+ });
+
+ it('threads committed labels across batches and seeds from resumed parts', async () => {
+ const parts: Array<LooseContentPart | null | undefined> = [
+ { type: 'activity_label', activity_label: 'Resumed header', pending: false },
+ { type: 'activity_label', activity_label: '', pending: true },
+ { type: 'tool_call', tool_call: { id: 'tool-1' } },
+ ];
+ const payloads: GenerateLabelPayload[] = [];
+ let seq = 0;
+ const generateLabel = jest.fn(async (payload: GenerateLabelPayload) => {
+ payloads.push(payload);
+ seq += 1;
+ return `Fresh header ${seq}`;
+ });
+ const { hook } = createActivityLabelWiring({
+ getContentParts: () => parts,
+ bumpIndexOffset: jest.fn(),
+ emitLabelEvent: jest.fn(async () => undefined),
+ trackPendingFill: jest.fn(),
+ resolveLLM: jest.fn(async () => ({
+ provider: Providers.OPENAI,
+ clientOptions: { model: 'm' },
+ })),
+ generateLabel,
+ });
+
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+
+ /** The unfilled pending reservation is excluded from the seed; the
+ * committed resumed text and the first fresh commit both thread. */
+ expect(payloads[0]?.previousLabels).toEqual(['Resumed header']);
+ expect(payloads[1]?.previousLabels).toEqual(['Resumed header', 'Fresh header 1']);
+ });
+});
+
+describe('captureActivityBlockContext', () => {
+ it('stops reasoning collection at a prior label but keeps intent', () => {
+ const parts: LooseContentPart[] = [
+ { type: 'text', text: 'Let me verify each runtime.' },
+ { type: 'think', think: 'Earlier batch reasoning' },
+ { type: 'activity_label', activity_label: 'Searched Node versions' },
+ { type: 'think', think: 'Current batch reasoning' },
+ ];
+ const context = captureActivityBlockContext(parts);
+ expect(context.thinkingExcerpts).toEqual(['Current batch reasoning']);
+ expect(context.lastAssistantText).toBe('Let me verify each runtime.');
+ });
+
+ it('filters reasoning by executing agent in multi-agent runs', () => {
+ const parts: LooseContentPart[] = [
+ { type: 'think', think: 'Agent B reasoning', agentId: 'agent-b' },
+ { type: 'think', think: 'Agent A reasoning', agentId: 'agent-a' },
+ ];
+ const context = captureActivityBlockContext(parts, 'agent-a');
+ expect(context.thinkingExcerpts).toEqual(['Agent A reasoning']);
+ });
+});
+
+describe('stripActivityLabelParts', () => {
+ it('removes label parts and keeps the reference when none exist', () => {
+ const withLabel = [{ content: [{ type: 'text', text: 'hi' }, { type: 'activity_label' }] }];
+ const stripped = stripActivityLabelParts(withLabel);
+ expect(stripped[0].content).toHaveLength(1);
+
+ const clean = [{ content: [{ type: 'text', text: 'hi' }] }];
+ expect(stripActivityLabelParts(clean)).toBe(clean);
+ });
+});
+
+describe('captureActivityBlockContext intent filtering', () => {
+ it("skips another agent's tail text when resolving intent", () => {
+ const parts: LooseContentPart[] = [
+ { type: 'text', text: 'Agent A plan for this batch', agentId: 'agent-a' },
+ { type: 'text', text: 'Agent B unrelated narration', agentId: 'agent-b' },
+ ];
+ const context = captureActivityBlockContext(parts, 'agent-a');
+ expect(context.lastAssistantText).toBe('Agent A plan for this batch');
+ });
+});
+
+describe('synthesizeActivityLabelGapEvents', () => {
+ const meta = { conversationId: 'c1', responseMessageId: 'm1' };
+
+ it('re-emits a label filled during the snapshot gap', () => {
+ const snapshot: LooseContentPart[] = [
+ { type: 'tool_call', tool_call: { id: 't1' } },
+ { type: 'activity_label', activity_label: '', pending: true },
+ ];
+ const fresh: LooseContentPart[] = [
+ { type: 'tool_call', tool_call: { id: 't1' } },
+ { type: 'activity_label', activity_label: 'Searched release notes', pending: false },
+ ];
+ const events = synthesizeActivityLabelGapEvents(snapshot, fresh, meta);
+ expect(events).toHaveLength(1);
+ expect(events[0].event).toBe('on_activity_label');
+ expect(events[0].data).toMatchObject({ index: 1, conversationId: 'c1' });
+ });
+
+ it('re-emits a label claimed entirely within the gap', () => {
+ const fresh: LooseContentPart[] = [
+ { type: 'tool_call', tool_call: { id: 't1' } },
+ { type: 'activity_label', activity_label: '', pending: true },
+ ];
+ expect(synthesizeActivityLabelGapEvents([fresh[0]], fresh, meta)).toHaveLength(1);
+ });
+
+ it('emits nothing when the snapshot already matches', () => {
+ const parts: LooseContentPart[] = [
+ { type: 'activity_label', activity_label: 'Same label', pending: false },
+ ];
+ expect(synthesizeActivityLabelGapEvents(parts, parts, meta)).toEqual([]);
+ });
+});
+
+describe('createActivityLabelWiring close gate', () => {
+ it('drops a late fill once the response has finalized', async () => {
+ const parts: Array<LooseContentPart | null | undefined> = [
+ { type: 'tool_call', tool_call: { id: 'tool-1' } },
+ ];
+ const emitLabelEvent = jest.fn(async () => undefined);
+ let closed = false;
+ let releaseLabel: (value: string) => void = () => undefined;
+ const generateLabel = jest.fn(
+ () =>
+ new Promise<string>((resolve) => {
+ releaseLabel = resolve;
+ }),
+ );
+ const { hook } = createActivityLabelWiring({
+ getContentParts: () => parts,
+ bumpIndexOffset: jest.fn(),
+ emitLabelEvent,
+ trackPendingFill: jest.fn(),
+ isClosed: () => closed,
+ resolveLLM: jest.fn(async () => ({
+ provider: Providers.OPENAI,
+ clientOptions: { model: 'm' },
+ })),
+ generateLabel,
+ });
+
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ /** Claiming publishes the reservation so replay cannot compact the index
+ * away — empty and pending, which renders nothing. */
+ expect(emitLabelEvent).toHaveBeenCalledTimes(1);
+ expect(emitLabelEvent).toHaveBeenCalledWith(
+ 1,
+ expect.objectContaining({ activity_label: '', pending: true }),
+ );
+
+ /** Settle timed out: the scope closes, then the straggler resolves. */
+ closed = true;
+ releaseLabel('Late label that must not land');
+ await flushDetached();
+
+ /** No SECOND emit: the late fill neither mutates nor publishes. */
+ expect(emitLabelEvent).toHaveBeenCalledTimes(1);
+ const labelPart = parts[1] as LooseContentPart;
+ expect(labelPart.activity_label).toBe('');
+ expect(labelPart.pending).toBe(true);
+ });
+});
+
+describe('createActivityLabelWiring reservation', () => {
+ /**
+ * Without a claim-time event the slot exists only in server memory, so a
+ * cross-instance replay rebuilds [tool, <hole>, laterText], compacts the
+ * hole, and the fill for the reserved index then overwrites `laterText`.
+ * Publishing the empty part keeps the index real for every consumer.
+ */
+ it('publishes the reserved index before any label exists', async () => {
+ const parts: Array<LooseContentPart | null | undefined> = [
+ { type: 'tool_call', tool_call: { id: 'tool-1' } },
+ ];
+ const emitted: Array<{ index: number; label: unknown; pending?: boolean }> = [];
+ const emitLabelEvent = jest.fn(async (index: number, part: LooseContentPart) => {
+ emitted.push({ index, label: part.activity_label, pending: part.pending });
+ return undefined;
+ });
+ const { hook } = createActivityLabelWiring({
+ getContentParts: () => parts,
+ bumpIndexOffset: jest.fn(),
+ emitLabelEvent,
+ trackPendingFill: jest.fn(),
+ resolveLLM: jest.fn(async () => ({
+ provider: Providers.OPENAI,
+ clientOptions: { model: 'm' },
+ })),
+ generateLabel: jest.fn(async () => 'Stored the release notes'),
+ });
+
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+
+ /** Reservation first (empty, pending), then the fill at the SAME index. */
+ expect(emitted).toEqual([
+ { index: 1, label: '', pending: true },
+ { index: 1, label: 'Stored the release notes', pending: false },
+ ]);
+ });
+
+ /** A blank result must still settle the slot, or the client stays pending. */
+ it('publishes a settled empty part when generation yields nothing', async () => {
+ const parts: Array<LooseContentPart | null | undefined> = [
+ { type: 'tool_call', tool_call: { id: 'tool-1' } },
+ ];
+ const emitLabelEvent = jest.fn(async () => undefined);
+ const { hook } = createActivityLabelWiring({
+ getContentParts: () => parts,
+ bumpIndexOffset: jest.fn(),
+ emitLabelEvent,
+ trackPendingFill: jest.fn(),
+ resolveLLM: jest.fn(async () => ({
+ provider: Providers.OPENAI,
+ clientOptions: { model: 'm' },
+ })),
+ generateLabel: jest.fn(async () => null),
+ });
+
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+
+ expect(emitLabelEvent).toHaveBeenCalledTimes(2);
+ expect(emitLabelEvent).toHaveBeenLastCalledWith(
+ 1,
+ expect.objectContaining({ activity_label: '', pending: false }),
+ );
+ });
+});
+
+describe('createActivityLabelWiring instruction', () => {
+ const runWith = async (prompt?: string) => {
+ const parts: Array<LooseContentPart | null | undefined> = [
+ { type: 'tool_call', tool_call: { id: 'tool-1' } },
+ ];
+ const generateLabel = jest.fn(async () => 'Confirmed the sandbox resets');
+ const { hook } = createActivityLabelWiring({
+ getContentParts: () => parts,
+ bumpIndexOffset: jest.fn(),
+ emitLabelEvent: jest.fn(async () => undefined),
+ trackPendingFill: jest.fn(),
+ resolveLLM: jest.fn(async () => ({
+ provider: Providers.OPENAI,
+ clientOptions: { model: 'm' },
+ })),
+ generateLabel,
+ ...(prompt != null && { prompt }),
+ });
+ await hook(batchInput(), new AbortController().signal);
+ await flushDetached();
+ return generateLabel;
+ };
+
+ /** Without this the SDK path silently uses the published package's own
+ * generic prompt, and only the fallback path gets this repo's register. */
+ it('always forwards an instruction to the SDK path', async () => {
+ const generateLabel = await runWith();
+ expect(generateLabel).toHaveBeenCalledWith(
+ expect.objectContaining({ prompt: ACTIVITY_INSTRUCTION }),
+ );
+ });
+
+ it('prefers the configured activityPrompt when one is set', async () => {
+ const generateLabel = await runWith('House style, please');
+ expect(generateLabel).toHaveBeenCalledWith(
+ expect.objectContaining({ prompt: 'House style, please' }),
+ );
+ });
+});
diff --git a/packages/api/src/agents/activityLabels/host.ts b/packages/api/src/agents/activityLabels/host.ts
new file mode 100644
index 0000000000..e4f937bfc7
--- /dev/null
+++ b/packages/api/src/agents/activityLabels/host.ts
@@ -0,0 +1,419 @@
+import { Providers } from '@librechat/agents';
+import { logger } from '@librechat/data-schemas';
+import { Constants, EModelEndpoint } from 'librechat-data-provider';
+import type { AppConfig, IUser } from '@librechat/data-schemas';
+import type { TEndpoint } from 'librechat-data-provider';
+import type { ClientOptions } from '@librechat/agents';
+import type { EndpointDbMethods, OpenAIConfiguration, ServerRequest } from '~/types';
+import type { ActivityLabelLLM } from './runtime';
+import { getProviderConfig } from '~/endpoints/config/providers';
+import { resolveConfigHeaders } from '~/utils/headers';
+import { omitTitleOptions } from '~/agents/client';
+import { createSafeUser } from '~/utils/env';
+
+/** Cache-token details in the LangChain-standard normalized shape. */
+interface CacheTokenDetails {
+ cache_read?: number;
+ cache_creation?: number;
+}
+
+/** Aggregated LLM metadata entries (shape varies by provider SDK). */
+export interface CollectedMetadataEntry {
+ usage?: {
+ prompt_tokens?: number;
+ input_tokens?: number;
+ inputTokens?: number;
+ completion_tokens?: number;
+ output_tokens?: number;
+ outputTokens?: number;
+ /** Anthropic raw usage. */
+ cache_creation_input_tokens?: number;
+ cache_read_input_tokens?: number;
+ /** OpenAI raw usage. */
+ prompt_tokens_details?: { cached_tokens?: number };
+ };
+ tokenUsage?: { promptTokens?: number; completionTokens?: number };
+ usage_metadata?: {
+ input_tokens?: number;
+ output_tokens?: number;
+ input_token_details?: CacheTokenDetails;
+ };
+}
+
+export interface ActivityLabelUsage {
+ input_tokens?: number;
+ output_tokens?: number;
+ /** Normalized cache tokens — `computeUsageCostUSD` and the transaction
+ * path read this shape first, so carrying it prices cached label calls
+ * at cache rates instead of the ordinary input rate (or not at all). */
+ input_token_details?: CacheTokenDetails;
+}
+
+/**
+ * Normalizes provider-specific aggregated metadata into the usage shape
+ * `recordCollectedUsage` expects, cache-token details included — dropping
+ * them made Anthropic cache tokens vanish from billing and charged OpenAI
+ * cache reads at the full input rate. Mirrors the title path's inline
+ * mapping otherwise.
+ */
+export function mapCollectedMetadataToUsage(
+ collected: CollectedMetadataEntry[],
+): ActivityLabelUsage[] {
+ return collected.map((item) => {
+ let input_tokens: number | undefined;
+ let output_tokens: number | undefined;
+ let cache_read: number | undefined;
+ let cache_creation: number | undefined;
+ if (item.usage) {
+ input_tokens = item.usage.prompt_tokens ?? item.usage.input_tokens ?? item.usage.inputTokens;
+ output_tokens =
+ item.usage.completion_tokens ?? item.usage.output_tokens ?? item.usage.outputTokens;
+ cache_read =
+ item.usage.cache_read_input_tokens ?? item.usage.prompt_tokens_details?.cached_tokens;
+ cache_creation = item.usage.cache_creation_input_tokens;
+ } else if (item.tokenUsage) {
+ input_tokens = item.tokenUsage.promptTokens;
+ output_tokens = item.tokenUsage.completionTokens;
+ } else if (item.usage_metadata) {
+ input_tokens = item.usage_metadata.input_tokens;
+ output_tokens = item.usage_metadata.output_tokens;
+ cache_read = item.usage_metadata.input_token_details?.cache_read;
+ cache_creation = item.usage_metadata.input_token_details?.cache_creation;
+ }
+ return {
+ input_tokens,
+ output_tokens,
+ ...(cache_read != null || cache_creation != null
+ ? { input_token_details: { cache_read, cache_creation } }
+ : {}),
+ };
+ });
+}
+
+/** The agent fields the label model resolution needs. */
+export interface ActivityLabelAgent {
+ endpoint?: string;
+ provider?: string;
+ model?: string;
+ model_parameters?: { model?: string };
+}
+
+export interface ResolveActivityLabelModelParams {
+ req: ServerRequest;
+ agent: ActivityLabelAgent;
+ /** The PUBLIC endpoint the request came in on (e.g. `agents`) when it
+ * differs from the agent's rewritten provider endpoint — its config block
+ * wins per field over the provider's. */
+ publicEndpoint?: string;
+ /** Request-scoped ids for header placeholder resolution. */
+ ids: { messageId?: string; conversationId?: string; parentMessageId?: string };
+ db: EndpointDbMethods;
+}
+
+/** Azure resolution reads an instance name that only some configs carry. */
+type MaybeAzureConfig = ClientOptions & {
+ azureOpenAIApiInstanceName?: string;
+ configuration?: OpenAIConfiguration;
+};
+
+/** Generation cap for label calls — ~25x the largest legitimate 4–9 word
+ * header, so truncation can never clip a real label. Replaces the stripped
+ * primary caps: with NO cap, a model that ignores the instruction (or is
+ * steered by injection in untrusted tool output) generates and BILLS its
+ * provider-default output on every batch; `normalizeLabelOutput` bounds
+ * only what persists, not what the provider generates. */
+const LABEL_MAX_OUTPUT_TOKENS = 256;
+
+/** Effective activity-label settings for one endpoint. */
+export interface ResolvedActivityConfig {
+ enabled: boolean;
+ model?: string;
+ endpoint?: string;
+ prompt?: string;
+ maxPerRun?: number;
+ charLimit?: number;
+}
+
+/**
+ * Reads the per-endpoint `activity*` settings, mirroring how titles resolve
+ * theirs: an `endpoints.all` block wins over the named endpoint, which wins
+ * over a custom endpoint's own config.
+ */
+/**
+ * Reads ONE endpoint setting, global-then-named, rather than picking a whole
+ * config object.
+ *
+ * Selecting wholesale means any `endpoints.all` block — even one carrying
+ * nothing but `headers` — shadows the named/custom endpoint entirely, so a
+ * single unrelated global setting silently hides every activity field AND the
+ * `titleModel` fallback. Global still wins per field, so a real
+ * `all.activityLabel` keeps overriding the endpoint.
+ */
+function pickEndpointField<K extends keyof TEndpoint>(
+ appConfig: AppConfig | undefined,
+ endpoint: string,
+ customEndpointConfig: Partial<TEndpoint> | undefined,
+ key: K,
+ publicEndpoint?: string,
+): TEndpoint[K] | undefined {
+ const endpoints = appConfig?.endpoints as
+ | (Record<string, TEndpoint | undefined> & { all?: TEndpoint })
+ | undefined;
+ const all = endpoints?.all as Partial<TEndpoint> | undefined;
+ /** The PUBLIC endpoint the request came in on, when it differs from the
+ * backing provider. `initializeAgent` rewrites `agent.endpoint` to the
+ * provider (an agents-endpoint run backed by OpenAI reads `openAI`), so
+ * without this an admin's `endpoints.agents.activityLabel: true` — valid
+ * config, since `agentsEndpointSchema` inherits every activity field —
+ * is silently ignored. Public wins per field over the backing provider,
+ * mirroring how request-path options resolve. */
+ const publicBlock =
+ publicEndpoint != null && publicEndpoint !== endpoint
+ ? (endpoints?.[publicEndpoint] as Partial<TEndpoint> | undefined)
+ : undefined;
+ const named = (endpoints?.[endpoint] ?? customEndpointConfig) as Partial<TEndpoint> | undefined;
+ return all?.[key] ?? publicBlock?.[key] ?? named?.[key];
+}
+
+export function resolveActivityConfig(
+ appConfig: AppConfig | undefined,
+ endpoint: string,
+ customEndpointConfig?: Partial<TEndpoint>,
+ publicEndpoint?: string,
+): ResolvedActivityConfig {
+ const pick = <K extends keyof TEndpoint>(key: K): TEndpoint[K] | undefined =>
+ pickEndpointField(appConfig, endpoint, customEndpointConfig, key, publicEndpoint);
+ return {
+ enabled: pick('activityLabel') === true,
+ model: pick('activityModel'),
+ endpoint: pick('activityEndpoint'),
+ prompt: pick('activityPrompt'),
+ maxPerRun: pick('activityMaxPerRun'),
+ charLimit: pick('activityCharLimit'),
+ /** `titleModel` is the documented fallback below, not a field here. */
+ };
+}
+
+/**
+ * Resolves provider + client options for the label model, mirroring
+ * `titleConvo`'s resolution. Model precedence: the endpoint's
+ * `activityModel` > its `titleModel` > the agent's own model. When
+ * `activityEndpoint` names a different endpoint, the label runs on THAT
+ * endpoint's credentials (title parity); an unknown name falls back to the
+ * agent's endpoint with a warning rather than failing the run.
+ */
+export async function resolveActivityLabelModel({
+ req,
+ agent,
+ publicEndpoint,
+ ids,
+ db,
+}: ResolveActivityLabelModelParams): Promise<ActivityLabelLLM> {
+ const appConfig = req.config as AppConfig | undefined;
+ const agentEndpoint = agent.endpoint ?? '';
+ let providerConfig = getProviderConfig({ provider: agentEndpoint, appConfig });
+ const activity = resolveActivityConfig(
+ appConfig,
+ agentEndpoint,
+ providerConfig.customEndpointConfig,
+ publicEndpoint,
+ );
+
+ /**
+ * Captured from the ORIGINATING endpoint, before any `activityEndpoint`
+ * switch — matching how `titleConvo` reads its config. The documented
+ * fallback is "this endpoint's `titleModel`", so reading it from the
+ * destination instead would let an OpenAI endpoint configured with
+ * `titleModel: claude-haiku` and `activityEndpoint: anthropic` fall through
+ * to the OpenAI run model and send that name to Anthropic, failing every
+ * label. The destination supplies credentials, not the model choice.
+ */
+ const originatingTitleModel = pickEndpointField(
+ appConfig,
+ agentEndpoint,
+ providerConfig.customEndpointConfig,
+ 'titleModel',
+ publicEndpoint,
+ );
+ let endpoint = agentEndpoint;
+ if (activity.endpoint != null && activity.endpoint !== agentEndpoint) {
+ try {
+ providerConfig = getProviderConfig({ provider: activity.endpoint, appConfig });
+ endpoint = activity.endpoint;
+ } catch (error) {
+ logger.warn(
+ `[activityLabels] Unknown activityEndpoint "${activity.endpoint}", falling back to "${agentEndpoint}"`,
+ error,
+ );
+ providerConfig = getProviderConfig({ provider: agentEndpoint, appConfig });
+ endpoint = agentEndpoint;
+ }
+ }
+
+ /** ONLY the originating endpoint's value. The documented precedence is
+ * `activityModel` → this endpoint's `titleModel` → the run model, so
+ * falling back to the DESTINATION's `titleModel` would make changing just
+ * the credential target silently change the model and its cost. The
+ * destination supplies credentials, never the model choice. */
+ const titleModel = originatingTitleModel;
+ /** `model_parameters.model` FIRST: `initializeAgent` merges the request's
+ * `endpointOption` override into it and the run itself gives it precedence,
+ * so the saved `agent.model` can be a stale or entirely different model.
+ * Reading it first is what makes "current model" mean the model the
+ * conversation is actually running on. */
+ const runModel = agent.model_parameters?.model ?? agent.model;
+ /** `current_model` means "the agent's model" for BOTH overrides — passing
+ * the literal through would send `model: "current_model"` to the provider
+ * and fail every label. An EXPLICIT `activityModel: current_model` resolves
+ * straight to the run model: the admin asked for it by name, so letting a
+ * configured `titleModel` win instead would route labels to an unintended
+ * model with different behavior and cost. The title fallback applies only
+ * when `activityModel` is absent. */
+ let model: string | undefined;
+ if (activity.model === Constants.CURRENT_MODEL) {
+ model = runModel;
+ } else if (activity.model != null) {
+ model = activity.model;
+ } else if (titleModel != null && titleModel !== Constants.CURRENT_MODEL) {
+ model = titleModel;
+ } else {
+ model = runModel;
+ }
+ const options = await providerConfig.getOptions({
+ req,
+ endpoint,
+ model_parameters: { model },
+ db,
+ });
+ const llmConfig = options.llmConfig as MaybeAzureConfig | undefined;
+ let provider = (options.provider ??
+ providerConfig.overrideProvider ??
+ agent.provider) as Providers;
+ if (endpoint === EModelEndpoint.azureOpenAI && llmConfig?.azureOpenAIApiInstanceName == null) {
+ provider = Providers.OPENAI;
+ } else if (
+ endpoint === EModelEndpoint.azureOpenAI &&
+ llmConfig?.azureOpenAIApiInstanceName != null &&
+ provider !== Providers.AZURE
+ ) {
+ provider = Providers.AZURE;
+ }
+ /** Sanitized copy, exactly like the title path: the label often runs a
+ * DIFFERENT (cheaper) model than the primary generation, so
+ * primary-generation options must not ride along. `omitTitleOptions`
+ * drops thinking/streaming/output-cap keys that can make the label
+ * request fail outright on the substitute model — or spend extended
+ * thinking on a 4–9 word header and blow the settlement window. The
+ * `modelKwargs` output caps go for the same reason (copied, not mutated:
+ * `llmConfig` is shared with the memoized provider resolution). */
+ const rawOptions = { ...(llmConfig ?? {}) } as MaybeAzureConfig & {
+ maxTokens?: number;
+ modelKwargs?: Record<string, unknown>;
+ clientOptions?: { defaultHeaders?: unknown };
+ };
+ /** Top-level `maxTokens` too, exactly like the title path — it is not in
+ * `omitTitleOptions`, and a primary cap sized for the agent's model can
+ * be unsupported or absurd on the substitute label model. */
+ delete rawOptions.maxTokens;
+ if (rawOptions.modelKwargs != null) {
+ const modelKwargs = { ...rawOptions.modelKwargs };
+ delete modelKwargs.max_completion_tokens;
+ delete modelKwargs.max_output_tokens;
+ rawOptions.modelKwargs = modelKwargs;
+ }
+ /** The filter drops the Anthropic `clientOptions` carrier, so restore it
+ * WHENEVER it exists — by the SAME reference. It holds client
+ * CONSTRUCTION options, not generation parameters: proxy
+ * `defaultHeaders`, and for user-provided base URLs the SSRF-safe
+ * `fetchOptions` (guarded Undici dispatcher, `redirect: 'error'`).
+ * Restoring only when headers were present silently stripped those
+ * guards from label calls to user-controlled URLs, re-opening DNS
+ * rebinding/redirect paths the endpoint validation exists to block; the
+ * same-reference restore also lets `resolveConfigHeaders` mutate the
+ * object the client is actually built from. */
+ const anthropicCarrier = rawOptions.clientOptions;
+ const clientOptions = Object.fromEntries(
+ Object.entries(rawOptions).filter(([key]) => !omitTitleOptions.has(key)),
+ ) as MaybeAzureConfig & {
+ clientOptions?: { defaultHeaders?: unknown };
+ modelKwargs?: Record<string, unknown>;
+ };
+ if (anthropicCarrier != null && clientOptions.clientOptions == null) {
+ clientOptions.clientOptions = anthropicCarrier;
+ }
+ /** Replace the stripped primary caps with a SMALL one — see
+ * {@link LABEL_MAX_OUTPUT_TOKENS} — routed with the SAME model/API
+ * conversion as the OpenAI builder (endpoints/openai/llm.ts): GPT-5+
+ * rejects `max_tokens`, so its cap goes to `modelKwargs`
+ * (responses-API aware); o-series reasoning models get NO cap at all,
+ * matching the title path, since they reject `max_tokens` and have no
+ * stable kwargs cap across API surfaces (the 200-char persistence bound
+ * still applies); Google-family wrappers read `maxOutputTokens`. */
+ const isGpt5Plus = model != null && /\bgpt-[5-9](?:\.\d+)?\b/i.test(model);
+ const isOSeries = model != null && /\bo[1-9](?:[-.]|\b)/i.test(model);
+ if (provider === Providers.GOOGLE || provider === Providers.VERTEXAI) {
+ (clientOptions as { maxOutputTokens?: number }).maxOutputTokens = LABEL_MAX_OUTPUT_TOKENS;
+ } else if (isGpt5Plus) {
+ const paramName =
+ (rawOptions as { useResponsesApi?: boolean }).useResponsesApi === true
+ ? 'max_output_tokens'
+ : 'max_completion_tokens';
+ clientOptions.modelKwargs = {
+ ...(clientOptions.modelKwargs ?? {}),
+ [paramName]: LABEL_MAX_OUTPUT_TOKENS,
+ };
+ } else if (!isOSeries) {
+ (clientOptions as { maxTokens?: number }).maxTokens = LABEL_MAX_OUTPUT_TOKENS;
+ }
+ if (options.configOptions) {
+ clientOptions.configuration = options.configOptions;
+ }
+ /** Resolve request-based header placeholders across provider-specific
+ * header locations, mirroring titleConvo — proxies that key on
+ * conversation/user metadata need them on label calls too. */
+ resolveConfigHeaders({
+ llmConfig: clientOptions,
+ user: createSafeUser(req.user as IUser | undefined),
+ body: ids,
+ });
+ return {
+ provider,
+ clientOptions: clientOptions as ClientOptions,
+ /** Priced with the LABEL endpoint's rates, not the agent's. */
+ endpointTokenConfig: options.endpointTokenConfig,
+ sameEndpoint: endpoint === agentEndpoint,
+ };
+}
+
+/**
+ * Bounded wait for in-flight label fills so a label resolving during the
+ * final batch still reaches the durable log and the saved message before the
+ * job completes. Never delays finalization past the bound; fills that lose
+ * the race leave the counts-only placeholder, which renders fine.
+ */
+export async function settlePendingLabelFills(
+ pending: Array<Promise<void>>,
+ timeoutMs = 3000,
+ onTimeout?: () => void,
+): Promise<void> {
+ if (pending.length === 0) {
+ return;
+ }
+ let timerId: ReturnType<typeof setTimeout> | undefined;
+ let timedOut = false;
+ const timeout = new Promise<void>((resolve) => {
+ timerId = setTimeout(() => {
+ timedOut = true;
+ resolve();
+ }, timeoutMs);
+ });
+ await Promise.race([Promise.allSettled(pending), timeout]);
+ if (timerId != null) {
+ clearTimeout(timerId);
+ }
+ if (timedOut) {
+ /** Stragglers must not mutate or emit for a response that is already
+ * finalizing: the caller aborts them and closes the slot gate. */
+ onTimeout?.();
+ }
+}
diff --git a/packages/api/src/agents/activityLabels/index.ts b/packages/api/src/agents/activityLabels/index.ts
new file mode 100644
index 0000000000..f40c4b0c44
--- /dev/null
+++ b/packages/api/src/agents/activityLabels/index.ts
@@ -0,0 +1,35 @@
+export {
+ ACTIVITY_INSTRUCTION,
+ buildPrompt,
+ classifyBatch,
+ createActivityLabelHook,
+} from './runtime';
+export type {
+ ActivityLabelBatchMeta,
+ ActivityLabelBlockContext,
+ ActivityLabelHookOptions,
+ ActivityLabelLLM,
+ ActivityLabelSlot,
+ ActivityLabelInvokeCallbacks,
+ GenerateLabelPayload,
+} from './runtime';
+export {
+ captureActivityBlockContext,
+ createActivityLabelWiring,
+ stripActivityLabelParts,
+ synthesizeActivityLabelGapEvents,
+} from './wiring';
+export type { ActivityLabelHostDeps, LooseContentPart } from './wiring';
+export {
+ mapCollectedMetadataToUsage,
+ resolveActivityConfig,
+ resolveActivityLabelModel,
+ settlePendingLabelFills,
+} from './host';
+export type {
+ ActivityLabelAgent,
+ ResolvedActivityConfig,
+ ActivityLabelUsage,
+ CollectedMetadataEntry,
+ ResolveActivityLabelModelParams,
+} from './host';
diff --git a/packages/api/src/agents/activityLabels/runtime.ts b/packages/api/src/agents/activityLabels/runtime.ts
new file mode 100644
index 0000000000..21e9de5451
--- /dev/null
+++ b/packages/api/src/agents/activityLabels/runtime.ts
@@ -0,0 +1,687 @@
+import { logger } from '@librechat/data-schemas';
+import { Constants } from 'librechat-data-provider';
+import { initializeModel } from '@librechat/agents';
+import type { ClientOptions, HookCallback, HookInputByEvent, Providers } from '@librechat/agents';
+
+type PostToolBatchInput = HookInputByEvent['PostToolBatch'];
+type BatchEntry = PostToolBatchInput['entries'][number];
+
+/** Resolved provider + client options for the label model call. */
+export interface ActivityLabelLLM {
+ provider: Providers;
+ clientOptions: ClientOptions;
+ /**
+ * Token config of the endpoint the LABEL runs on, which differs from the
+ * agent's whenever `activityEndpoint` is set. Pricing must use this or a
+ * cross-endpoint label is costed at the wrong rates.
+ */
+ endpointTokenConfig?: unknown;
+ /**
+ * True when the label resolved to the agent's OWN endpoint. Callers need
+ * this to read an undefined `endpointTokenConfig` correctly: for a built-in
+ * label endpoint undefined means "price from the shared table", so
+ * inheriting the agent's custom rates there would misprice the label.
+ */
+ sameEndpoint?: boolean;
+}
+
+/**
+ * Batch metadata handed to the host at slot-claim time (all deterministic).
+ *
+ * Deliberately carries no tool-type tally. A tally can only restate the tool
+ * cards rendered directly beneath the header ("ran 1 command"), so it has no
+ * place in either the prompt or the UI; the header earns its row solely by
+ * saying something the cards cannot.
+ */
+export interface ActivityLabelBatchMeta {
+ toolCallIds: string[];
+ /** ok = all succeeded, failed = all failed, partial = mixed. */
+ status: 'ok' | 'partial' | 'failed';
+ /** Owning agent in multi-agent graphs — lets the host stamp the part for lane grouping. */
+ executingAgentId?: string;
+}
+
+/**
+ * Block context captured host-side at claim time (before more parts stream
+ * in): reasoning excerpts from the block and the assistant's preceding text.
+ * Never contains human messages.
+ */
+export interface ActivityLabelBlockContext {
+ thinkingExcerpts?: string[];
+ lastAssistantText?: string;
+}
+
+/**
+ * A content slot claimed synchronously at the batch boundary. `fill` is
+ * called later (or with `null` on failure) once the label resolves.
+ */
+export interface ActivityLabelSlot {
+ index: number;
+ /**
+ * Resolves `true` when the fill COMMITTED (mutated content + emitted) and
+ * `false` when the host dropped it because the response already finalized.
+ * Usage accounting keys on this: a dropped label must not be billed.
+ */
+ fill: (text: string | null) => boolean | Promise<boolean>;
+ /** Snapshot of block context, captured synchronously at claim time. */
+ context?: ActivityLabelBlockContext;
+}
+
+/** Payload handed to the host's `generateLabel` (SDK-backed) implementation. */
+export interface GenerateLabelPayload {
+ entries: BatchEntry[];
+ context: ActivityLabelBlockContext;
+ /**
+ * Committed headers from earlier batches in this run (run order, most
+ * recent last, max {@link MAX_PREVIOUS_LABELS}) — continuity context so
+ * consecutive same-activity batches extend the story instead of restating
+ * it. Present only when at least one earlier label committed. An SDK
+ * without the field ignores it harmlessly; the fallback path renders it
+ * regardless.
+ */
+ previousLabels?: string[];
+ /** Deterministic Langfuse trace seed, unique per slot. */
+ traceSeed: string;
+ signal: AbortSignal;
+ /** Effective per-entry truncation, forwarded so host and SDK prompts agree. */
+ charLimit: number;
+ /**
+ * Instruction for the label model. Always sent: left unset, the SDK falls
+ * back to its own generic past-tense prompt and the register defined here
+ * never reaches the preferred path.
+ */
+ prompt?: string;
+ /**
+ * Owning agent of the batch. Selects that agent's tracing metadata AND its
+ * tool-output redaction policy on the SDK path, so a handoff is not traced
+ * or redacted under the default agent's configuration.
+ */
+ executingAgentId?: string;
+ /**
+ * Defers usage accounting until AFTER the slot commits. A generator that
+ * bills inline consumes the settlement window with its balance write, so
+ * the deadline can expire mid-write — the charge lands but the fill is
+ * then dropped as out-of-scope: billed, never shown. Registering the
+ * accounting here instead lets the hook commit the visible label first and
+ * only then run it, and only for a committed fill. The hook passes a lazy
+ * {@link LabelUsageEstimate} on the success path so the biller can fall
+ * back to title-style estimated billing when the provider omits usage.
+ */
+ deferUsage: (collect: (estimate?: () => LabelUsageEstimate) => void | Promise<void>) => void;
+}
+
+/**
+ * Text the biller can count locally when the provider omits usage metadata,
+ * following the title convention of estimate-based billing. Produced lazily —
+ * tokenizing costs CPU, so the thunk runs only when real usage is absent.
+ */
+export interface LabelUsageEstimate {
+ promptText: string;
+ completionText: string;
+}
+
+/** Per-generation LLM callbacks for usage accounting on the fallback path. */
+export interface ActivityLabelInvokeCallbacks {
+ callbacks: Array<Record<string, unknown>>;
+ collect: (estimate?: () => LabelUsageEstimate) => void | Promise<void>;
+}
+
+export interface ActivityLabelHookOptions {
+ /**
+ * Synchronously claims the next live content index on the host (push
+ * placeholder part + bump the shared index offset, exactly like steering's
+ * `applySteerPart`). Receives deterministic batch metadata so the
+ * placeholder is informative before the LLM label lands. Must be cheap
+ * — it runs inside the awaited hook.
+ */
+ claimSlot: (meta: ActivityLabelBatchMeta) => ActivityLabelSlot;
+ /**
+ * Preferred generation path: host bridges to the SDK's
+ * `run.generateActivityLabel()` (session-grouped Langfuse tracing).
+ *
+ * Resolve `undefined` to decline — the SDK lacks the API — and the hook
+ * falls back to a direct, untraced model call via `resolveLLM`. `null`
+ * means the opposite: this path ran and produced no label, so the slot
+ * fills empty. Hosts wire this bridge unconditionally (the run does not
+ * exist yet at construction time), which is why declining has to be
+ * expressible at call time rather than by omitting the option.
+ */
+ generateLabel?: (payload: GenerateLabelPayload) => Promise<string | null | undefined>;
+ /**
+ * Fallback model resolution for the direct-call path. Memoized here so
+ * hosts can pass a fresh thunk without caching concerns.
+ */
+ resolveLLM: () => Promise<ActivityLabelLLM>;
+ /** Run abort signal; in-flight label calls are also bounded by a timeout. */
+ signal?: AbortSignal;
+ /**
+ * Factory for per-generation LLM callbacks (fallback path only): fresh
+ * aggregator per call, `collect()` invoked after a successful response so
+ * label calls participate in usage accounting like titles do.
+ */
+ getInvokeCallbacks?: () => ActivityLabelInvokeCallbacks;
+ /** Cap on labels per run (cost guard). Default 20. */
+ maxPerRun?: number;
+ /** Per-entry output truncation for the prompt. Default 600 chars. */
+ charLimit?: number;
+ /**
+ * `activityPrompt` override. Applies to BOTH paths: the SDK bridge passes
+ * it through, and the direct fallback seeds `buildPrompt` with it instead
+ * of the built-in instruction.
+ */
+ prompt?: string;
+ /**
+ * Labels already present on the response (HITL resume rebuilds the hook
+ * with pre-pause content), so the per-response cap counts them instead of
+ * restarting at zero after every approval.
+ */
+ initialGeneratedCount?: number;
+ /**
+ * Committed label texts already on the response, keyed by content index —
+ * the continuity seed for a HITL resume, so post-approval batches still
+ * see the pre-pause headers. Unfilled reservations are excluded by the
+ * host; only text the user is actually reading belongs here.
+ */
+ initialLabels?: ReadonlyArray<{ index: number; text: string }>;
+ /**
+ * Receives the whole detached task (generate → fill → deferred usage) so
+ * the host's bounded settle covers the accounting too. Deferring usage
+ * until after the commit moved it PAST the fill's resolution, so a settle
+ * keyed on fills alone could let finalization flush the usage sink and
+ * snapshot metadata while the label's billing was still in flight. The
+ * task never rejects.
+ */
+ trackTask?: (task: Promise<void>) => void;
+}
+
+const DEFAULT_MAX_PER_RUN = 20;
+const DEFAULT_CHAR_LIMIT = 600;
+/** Continuity window: matching the SDK prompt builder's own cap, and small
+ * because the point is avoiding a restatement of what is on screen NEAR the
+ * new header — a 20-label history would only dilute the batch content. */
+const MAX_PREVIOUS_LABELS = 3;
+/** Intent-line truncation only. Tool inputs and outputs both truncate at the
+ * configured `activityCharLimit` — the schema documents it as the per-entry
+ * limit for BOTH, so a hard-coded input cap would make the setting unable to
+ * reach a distinguishing path or query past the first 200 characters. */
+const INTENT_CHAR_LIMIT = 200;
+const SUMMARY_TIMEOUT_MS = 12_000;
+/** Total budget for the entries section. Per-entry truncation alone leaves
+ * the batch dimension unbounded — a parallel batch of hundreds of calls
+ * would build a prompt past the fast model's window and bill input tokens
+ * far beyond what a one-line header justifies. Scales with the configured
+ * per-entry limit so a raised `activityCharLimit` still fits several
+ * entries; entries past the budget are skipped WITHOUT serializing them. */
+const ENTRIES_CHAR_BUDGET = 8_000;
+/** Hard bound on the PERSISTED label. The instruction asks for 4–9 words, but
+ * a model that ignores it — or is steered by injection through untrusted
+ * tool output — could otherwise turn one header into thousands of tokens
+ * duplicated through SSE, the durable chunk log, persistence, and the UI. */
+const LABEL_OUTPUT_CHAR_LIMIT = 200;
+
+/**
+ * Normalizes raw model output into a header: the first non-empty line,
+ * whitespace collapsed, hard-capped at {@link LABEL_OUTPUT_CHAR_LIMIT}. A
+ * header renders as one line, so everything past the first line break is
+ * noise at best and injected payload at worst.
+ */
+export function normalizeLabelOutput(text: string | null | undefined): string {
+ if (text == null) {
+ return '';
+ }
+ const firstLine = text.split(/\r?\n/).find((line) => line.trim().length > 0) ?? '';
+ const collapsed = firstLine.replace(/\s+/g, ' ').trim();
+ return collapsed.length > LABEL_OUTPUT_CHAR_LIMIT
+ ? `${collapsed.slice(0, LABEL_OUTPUT_CHAR_LIMIT - 1)}…`
+ : collapsed;
+}
+
+function truncate(value: string, limit: number): string {
+ return value.length > limit ? `${value.slice(0, limit)}…` : value;
+}
+
+/**
+ * Serializes at most `limit + 1` characters of an arbitrary value. Tool
+ * outputs are unbounded — a multi-megabyte result would otherwise be fully
+ * materialized by `JSON.stringify` on EVERY detached label task just to keep
+ * a few hundred characters, blocking the event loop for prompt fodder that
+ * is immediately discarded. Traversal stops the moment the budget is spent
+ * (the overshoot marks that `truncate` must append its ellipsis), which also
+ * bounds cyclic structures: every level emits before recursing, so depth can
+ * never exceed the budget. Output is JSON-shaped, not guaranteed JSON.
+ */
+function stringifyBounded(value: unknown, limit: number): string {
+ const out: string[] = [];
+ let length = 0;
+ const push = (chunk: string): boolean => {
+ out.push(chunk);
+ length += chunk.length;
+ return length <= limit;
+ };
+ const walk = (val: unknown): boolean => {
+ if (typeof val === 'string') {
+ /** Slice BEFORE quoting — quoting is what materializes the copy. */
+ return push(JSON.stringify(val.length > limit + 1 ? val.slice(0, limit + 1) : val));
+ }
+ if (val == null || typeof val === 'number' || typeof val === 'boolean') {
+ return push(String(val));
+ }
+ if (Array.isArray(val)) {
+ if (!push('[')) {
+ return false;
+ }
+ for (let i = 0; i < val.length; i++) {
+ if ((i > 0 && !push(',')) || !walk(val[i])) {
+ return false;
+ }
+ }
+ return push(']');
+ }
+ if (typeof val === 'object') {
+ const toJSON = (val as { toJSON?: () => unknown }).toJSON;
+ if (typeof toJSON === 'function') {
+ try {
+ return walk(toJSON.call(val));
+ } catch {
+ return push(String(val).slice(0, limit + 1));
+ }
+ }
+ if (!push('{')) {
+ return false;
+ }
+ let first = true;
+ /** for-in, not Object.keys: enumeration stops at the budget instead of
+ * materializing a key array for a million-property object first. The
+ * own-property guard replaces what Object.keys implied. */
+ for (const key in val) {
+ if (!Object.prototype.hasOwnProperty.call(val, key)) {
+ continue;
+ }
+ const entry = (val as Record<string, unknown>)[key];
+ if (entry === undefined || typeof entry === 'function') {
+ continue;
+ }
+ /** Keys are untrusted too: slice BEFORE quoting, exactly like string
+ * values — quoting is what materializes the copy. */
+ const boundedKey = key.length > limit + 1 ? key.slice(0, limit + 1) : key;
+ if ((!first && !push(',')) || !push(`${JSON.stringify(boundedKey)}:`) || !walk(entry)) {
+ return false;
+ }
+ first = false;
+ }
+ return push('}');
+ }
+ return push(String(val).slice(0, limit + 1));
+ };
+ walk(value);
+ return out.join('').slice(0, limit + 1);
+}
+
+function stringifyUnknown(value: unknown, limit: number): string {
+ if (value == null) {
+ return '';
+ }
+ if (typeof value === 'string') {
+ return value.length > limit + 1 ? value.slice(0, limit + 1) : value;
+ }
+ try {
+ return stringifyBounded(value, limit);
+ } catch {
+ return String(value).slice(0, limit + 1);
+ }
+}
+
+/**
+ * Deterministic batch facts: which tool calls the label covers (for lane
+ * stamping) and whether they succeeded (for failure tinting). No tool-type
+ * tally — see {@link ActivityLabelBatchMeta}.
+ */
+export function classifyBatch(entries: BatchEntry[]): ActivityLabelBatchMeta {
+ const toolCallIds: string[] = [];
+ let failures = 0;
+ for (const entry of entries) {
+ toolCallIds.push(entry.toolUseId);
+ if (entry.status === 'error') {
+ failures += 1;
+ }
+ }
+ let status: ActivityLabelBatchMeta['status'] = 'partial';
+ if (failures === 0) {
+ status = 'ok';
+ } else if (failures === entries.length) {
+ status = 'failed';
+ }
+ return { toolCallIds, status };
+}
+
+/**
+ * The header sits directly above the tool cards it summarizes, so anything
+ * the cards already display — tool names, how many ran, the arguments — is
+ * noise when repeated. What the cards cannot show is the point of the batch
+ * and how it came out, and that is the only thing worth a row of screen.
+ *
+ * Because this fires after the batch, the tool OUTPUTS are available: prefer
+ * the answer the calls produced over a restatement of what was attempted.
+ *
+ * Sentence ORDER is deliberate, not stylistic: content rules first and
+ * format rules last measurably improves both format adherence and opening-
+ * verb diversity on small label models (eval corpus:
+ * scripts/activity-labels/), so a reshuffle here regresses real output.
+ */
+export const ACTIVITY_INSTRUCTION: string = [
+ 'You write the one-line header above a group of tool calls an AI agent just made.',
+ 'Say what the calls established or produced — the outcome, not the attempt. If they answered a question, the answer is the line.',
+ 'Write it like a git commit subject: past tense, verb first, leading with the most distinctive file, name, or finding.',
+ 'Good: "Confirmed /mnt/data resets between calls". "Traced the leak to formatAgentMessages". "Found 3 failing auth tests".',
+ 'Bad: "Ran 1 command". "Used bash_tool twice". "Executed ls /mnt/data". "Searched the codebase".',
+ 'If every call failed, say what failed and why, plainly.',
+ 'A "Previous headers" list may precede the batch: never restate one — if this batch continues that activity, say only what is new.',
+ 'Never name the tools, never count them, never echo the arguments: the cards below the header already show all three.',
+ 'Write 4 to 9 words, sentence case, no trailing punctuation, no quotes or markdown.',
+ 'Output only the line.',
+].join(' ');
+
+export function buildPrompt(
+ entries: BatchEntry[],
+ charLimit: number,
+ context?: ActivityLabelBlockContext,
+ instruction?: string,
+ previousLabels?: string[],
+): string {
+ const sections: string[] = [instruction ?? ACTIVITY_INSTRUCTION];
+ if (previousLabels != null && previousLabels.length > 0) {
+ sections.push(
+ 'Previous headers in this run (most recent last):\n' +
+ previousLabels
+ .slice(-MAX_PREVIOUS_LABELS)
+ .map((label) => `- ${label}`)
+ .join('\n'),
+ );
+ }
+ if (context?.lastAssistantText) {
+ sections.push(
+ `Intent (assistant's last message): ${truncate(context.lastAssistantText, INTENT_CHAR_LIMIT)}`,
+ );
+ }
+ if (context?.thinkingExcerpts?.length) {
+ sections.push(
+ 'Reasoning excerpts:\n' +
+ context.thinkingExcerpts
+ .slice(0, 4)
+ .map((excerpt) => `- ${truncate(excerpt, charLimit)}`)
+ .join('\n'),
+ );
+ }
+ const budget = Math.max(ENTRIES_CHAR_BUDGET, charLimit * 4);
+ const lines: string[] = [];
+ let used = 0;
+ let omitted = 0;
+ for (const entry of entries) {
+ /** Prefix cut, never a mid-list sample: once the budget is spent the
+ * remaining entries are skipped unserialized (a giant batch must not
+ * even pay the stringify cost for lines that will be dropped). The
+ * first entry always fits, and the line that crosses the budget is
+ * kept, so at least one complete call is always shown. */
+ if (lines.length > 0 && used >= budget) {
+ omitted += 1;
+ continue;
+ }
+ const input = truncate(stringifyUnknown(entry.toolInput, charLimit), charLimit);
+ const outcome =
+ entry.status === 'error'
+ ? `ERROR: ${truncate(entry.error ?? 'unknown error', charLimit)}`
+ : truncate(stringifyUnknown(entry.toolOutput, charLimit), charLimit);
+ const line = `- ${entry.toolName}(${input}) → ${outcome}`;
+ lines.push(line);
+ used += line.length;
+ }
+ if (omitted > 0) {
+ lines.push(`- (+${omitted} more tool calls not shown)`);
+ }
+ /** Flagged as reference material: without this the model tends to read the
+ * list as the thing to summarize and hands back a transcription of it. */
+ sections.push(`What it called, and what came back (do not restate these):\n${lines.join('\n')}`);
+ sections.push('Header:');
+ return sections.join('\n\n');
+}
+
+function extractText(content: unknown): string {
+ if (typeof content === 'string') {
+ return content.trim();
+ }
+ if (Array.isArray(content)) {
+ return content
+ .map((block) =>
+ typeof block === 'string' ? block : ((block as { text?: string })?.text ?? ''),
+ )
+ .join('')
+ .trim();
+ }
+ return '';
+}
+
+function buildSignal(runSignal?: AbortSignal, hookSignal?: AbortSignal): AbortSignal {
+ const timeout = AbortSignal.timeout(SUMMARY_TIMEOUT_MS);
+ const signals = [runSignal, hookSignal].filter((signal): signal is AbortSignal => signal != null);
+ if (signals.length > 0 && typeof AbortSignal.any === 'function') {
+ return AbortSignal.any([...signals, timeout]);
+ }
+ return timeout;
+}
+
+/**
+ * PoC PostToolBatch hook: claims a content slot synchronously, then generates
+ * a one-line batch summary on a cheap model as a DETACHED promise — the hook
+ * returns immediately so the next model call is never delayed. Failures fill
+ * the slot with `null` (host renders nothing for empty summaries).
+ */
+export function createActivityLabelHook(
+ opts: ActivityLabelHookOptions,
+): HookCallback<'PostToolBatch'> {
+ const maxPerRun = opts.maxPerRun ?? DEFAULT_MAX_PER_RUN;
+ const charLimit = opts.charLimit ?? DEFAULT_CHAR_LIMIT;
+ let generated = opts.initialGeneratedCount ?? 0;
+ let llmPromise: Promise<ActivityLabelLLM> | null = null;
+ /** Committed label text by content index. A Map because fills land in
+ * COMPLETION order, not run order — batch N+1's label can commit before
+ * batch N's — so continuity reads must re-sort by index rather than
+ * trusting insertion order. */
+ const committedLabels = new Map<number, string>();
+ for (const seed of opts.initialLabels ?? []) {
+ committedLabels.set(seed.index, seed.text);
+ }
+ const recentLabels = (beforeIndex: number): string[] => {
+ const prior: Array<[number, string]> = [];
+ for (const entry of committedLabels) {
+ if (entry[0] < beforeIndex) {
+ prior.push(entry);
+ }
+ }
+ return prior
+ .sort((a, b) => a[0] - b[0])
+ .slice(-MAX_PREVIOUS_LABELS)
+ .map(([, text]) => text);
+ };
+
+ const getLLM = (): Promise<ActivityLabelLLM> => {
+ llmPromise =
+ llmPromise ??
+ opts.resolveLLM().catch((error) => {
+ /** Never cache a rejection: memoizing it would fail every later
+ * batch in the run instantly — and silently defeat the host
+ * resolver's own rejected-cache eviction, which exists precisely so
+ * a transient credential read failure stays transient. */
+ llmPromise = null;
+ throw error;
+ });
+ return llmPromise;
+ };
+
+ return async (input: PostToolBatchInput, hookSignal?: AbortSignal) => {
+ /** Subagent scopes are skipped (`input.agentId` set), mirroring the steer
+ * drain: subagent content is buffered per spawning tool call, so a slot
+ * claimed here would land in the WRONG transcript (the main message). */
+ if (input.agentId != null) {
+ return {};
+ }
+ if (
+ generated >= maxPerRun ||
+ input.entries.length === 0 ||
+ opts.signal?.aborted === true ||
+ hookSignal?.aborted === true
+ ) {
+ return {};
+ }
+ /** A batch containing ANY handoff call gets no label — mixed batches
+ * included. Transfer parts are never groupable on the client, so the
+ * flush at the transfer card leaves the label with nothing to head and
+ * it could only orphan into a stray line after the cards; the handoff
+ * card already names the destination and the tool cards still show the
+ * work. Skipped BEFORE the quota so handoffs never consume
+ * `maxPerRun`. */
+ if (
+ input.entries.some((entry) => entry.toolName?.startsWith(Constants.LC_TRANSFER_TO_) === true)
+ ) {
+ return {};
+ }
+ generated += 1;
+ const slot = opts.claimSlot({
+ ...classifyBatch(input.entries),
+ executingAgentId: input.executingAgentId,
+ });
+
+ const task = (async () => {
+ /**
+ * Usage accounting registered by whichever generation path ran, invoked
+ * only after `slot.fill` settles. Billing BEFORE the commit let the
+ * settlement deadline expire during the accounting's balance write —
+ * the charge landed, then the fill was dropped as out-of-scope: billed,
+ * never shown. Committing first makes the charge conditional on the
+ * label actually surfacing.
+ */
+ let deferredUsage:
+ | ((estimate?: () => LabelUsageEstimate) => void | Promise<void>)
+ | undefined;
+ const collectDeferredUsage = async (
+ committed: boolean,
+ estimate?: () => LabelUsageEstimate,
+ ) => {
+ if (!committed || deferredUsage == null) {
+ return;
+ }
+ try {
+ await deferredUsage(estimate);
+ } catch (error) {
+ logger.warn(
+ `[activityLabel] usage accounting failed (slot ${slot.index}): ${(error as Error)?.message ?? error}`,
+ );
+ }
+ };
+ try {
+ /** Host run-abort signal AND the dispatch signal both cancel the
+ * label call — a user abort must not keep paying for generation
+ * until the timeout. */
+ const signal = buildSignal(opts.signal, hookSignal);
+ /** Read at request-build time, not claim time: earlier batches'
+ * fills usually land in the gap between batch boundaries, so this
+ * captures labels a claim-time snapshot would miss — exactly the
+ * rapid consecutive batches where continuity matters most. */
+ const previousLabels = recentLabels(slot.index);
+ /** Direct, untraced call: the fallback when no SDK bridge is wired or
+ * when the bridge declines because the package is too old. */
+ let directPromptText: string | undefined;
+ const generateDirect = async (): Promise<string | null> => {
+ const { provider, clientOptions } = await getLLM();
+ const model = initializeModel({
+ provider,
+ clientOptions: { ...clientOptions, streaming: false } as ClientOptions,
+ });
+ const invokeCallbacks = opts.getInvokeCallbacks?.();
+ directPromptText = buildPrompt(
+ input.entries,
+ charLimit,
+ slot.context,
+ opts.prompt,
+ previousLabels,
+ );
+ const response = await (
+ model as { invoke: (input: string, config?: object) => Promise<{ content?: unknown }> }
+ ).invoke(directPromptText, {
+ signal,
+ ...(invokeCallbacks && { callbacks: invokeCallbacks.callbacks }),
+ });
+ const direct = extractText(response?.content);
+ deferredUsage = invokeCallbacks?.collect;
+ return direct;
+ };
+
+ let text: string | null = null;
+ if (opts.generateLabel != null) {
+ /** SDK-backed path: session-grouped Langfuse tracing via
+ * `run.generateActivityLabel()` (host bridges the call). */
+ const bridged = await opts.generateLabel({
+ entries: input.entries,
+ context: slot.context ?? {},
+ ...(previousLabels.length > 0 && { previousLabels }),
+ traceSeed: `${input.runId}-activity-${slot.index}`,
+ signal,
+ charLimit,
+ deferUsage: (collect) => {
+ deferredUsage = collect;
+ },
+ ...(opts.prompt != null && { prompt: opts.prompt }),
+ ...(input.executingAgentId != null && { executingAgentId: input.executingAgentId }),
+ });
+ /** Declined (no SDK support) — not the same as "no label". */
+ text = bridged === undefined ? await generateDirect() : bridged;
+ } else {
+ text = await generateDirect();
+ }
+ /** Normalize centrally — BOTH paths: single line, bounded length,
+ * whitespace-only becomes null so the UI keeps the deterministic
+ * counts fallback. */
+ const normalized = normalizeLabelOutput(text);
+ const committed = (await slot.fill(normalized.length > 0 ? normalized : null)) === true;
+ /** Continuity records only what actually surfaced: a dropped fill
+ * never reached the user, so later headers must not write around
+ * a line that is not on screen. */
+ if (committed && normalized.length > 0) {
+ committedLabels.set(slot.index, normalized);
+ }
+ /** Estimate for providers that omit usage metadata — title-style
+ * billing from locally counted text. LAZY: the thunk runs only when
+ * real usage is absent. The direct path counts the EXACT prompt it
+ * sent; the SDK path counts the locally built equivalent (same
+ * entries, context, instruction, and truncation contract). The
+ * completion counts the RAW model output, not the normalized label —
+ * a verbose multi-line reply consumed tokens up to the generation
+ * cap even though only its bounded first line persists. Success
+ * path only: a throw before a response consumed nothing billable
+ * beyond what real metadata already captured. */
+ await collectDeferredUsage(committed, () => ({
+ promptText:
+ directPromptText ??
+ buildPrompt(input.entries, charLimit, slot.context, opts.prompt, previousLabels),
+ completionText: text ?? '',
+ }));
+ } catch (error) {
+ logger.warn(
+ `[activityLabel] label generation failed (slot ${slot.index}): ${(error as Error)?.message ?? error}`,
+ );
+ let committed = false;
+ try {
+ committed = (await slot.fill(null)) === true;
+ } catch {
+ /* host fill must never throw into the void chain */
+ }
+ /** A throw after the provider responded still consumed tokens; bill
+ * them when the empty fill committed, on the same shown-iff-billed
+ * rule (collect itself never throws past its own catch). */
+ await collectDeferredUsage(committed);
+ }
+ })();
+ opts.trackTask?.(task);
+
+ return {};
+ };
+}
diff --git a/packages/api/src/agents/activityLabels/wiring.ts b/packages/api/src/agents/activityLabels/wiring.ts
new file mode 100644
index 0000000000..ee36b1c7ef
--- /dev/null
+++ b/packages/api/src/agents/activityLabels/wiring.ts
@@ -0,0 +1,346 @@
+import { ContentTypes } from 'librechat-data-provider';
+import type { HookCallback } from '@librechat/agents';
+import type {
+ ActivityLabelBlockContext,
+ ActivityLabelInvokeCallbacks,
+ ActivityLabelLLM,
+ GenerateLabelPayload,
+} from './runtime';
+import { ACTIVITY_INSTRUCTION, createActivityLabelHook } from './runtime';
+
+/** Structural view of a content part; hosts pass their live parts array. */
+export interface LooseContentPart {
+ type?: string;
+ text?: unknown;
+ think?: unknown;
+ agentId?: unknown;
+ groupId?: unknown;
+ tool_call?: { id?: unknown };
+ pending?: boolean;
+ [key: string]: unknown;
+}
+
+const MAX_EXCERPTS = 4;
+const EXCERPT_CHARS = 300;
+const INTENT_CHARS = 200;
+
+function textValue(value: unknown): string {
+ if (typeof value === 'string') {
+ return value;
+ }
+ const nested = (value as { value?: unknown } | null | undefined)?.value;
+ return typeof nested === 'string' ? nested : '';
+}
+
+/**
+ * Captures the current activity block's context for the label payload:
+ * reasoning excerpts since the last text part, plus the assistant's last
+ * text (~200 chars) as intent. Deliberately NO human messages. Reasoning
+ * collection stops at the previous block's label part — labels delimit
+ * blocks, so scanning past one would bleed another batch's reasoning into
+ * this payload — and filters by executing agent in multi-agent runs.
+ * Intent keeps scanning past labels: with consecutive batches and no
+ * interleaved text, the assistant's last words remain the current intent.
+ */
+export function captureActivityBlockContext(
+ parts: ReadonlyArray<LooseContentPart | null | undefined>,
+ executingAgentId?: string,
+): ActivityLabelBlockContext {
+ const thinkingExcerpts: string[] = [];
+ let lastAssistantText: string | undefined;
+ let collectThinking = true;
+ for (let i = parts.length - 1; i >= 0; i--) {
+ const part = parts[i];
+ if (part == null) {
+ continue;
+ }
+ if (part.type === ContentTypes.ACTIVITY_LABEL) {
+ collectThinking = false;
+ continue;
+ }
+ if (part.type === ContentTypes.TEXT) {
+ /** Parallel/added-agent runs interleave text parts from several
+ * agents; another agent's text at the tail is not this batch's
+ * intent, so skip it rather than stopping the scan there. */
+ if (executingAgentId != null && part.agentId != null && part.agentId !== executingAgentId) {
+ continue;
+ }
+ const text = textValue(part.text).trim();
+ if (text.length > 0) {
+ lastAssistantText = text.slice(-INTENT_CHARS);
+ break;
+ }
+ continue;
+ }
+ if (
+ collectThinking &&
+ part.type === ContentTypes.THINK &&
+ thinkingExcerpts.length < MAX_EXCERPTS &&
+ (executingAgentId == null || part.agentId == null || part.agentId === executingAgentId)
+ ) {
+ const think = textValue(part.think).trim();
+ if (think.length > 0) {
+ thinkingExcerpts.unshift(think.slice(0, EXCERPT_CHARS));
+ }
+ }
+ }
+ return { thinkingExcerpts, lastAssistantText };
+}
+
+/**
+ * Removes UI-only activity-label parts from a message payload before any
+ * `formatAgentMessages` call. Published SDK versions without the formatter
+ * skip would otherwise fold the label text into provider-facing content via
+ * the formatter's catch-all. Non-mutating; returns the same reference when
+ * nothing needed stripping.
+ */
+export function stripActivityLabelParts<T extends { content?: unknown }>(payload: T[]): T[] {
+ if (!Array.isArray(payload)) {
+ return payload;
+ }
+ let changed = false;
+ const result = payload.map((message) => {
+ const content = message?.content;
+ if (!Array.isArray(content)) {
+ return message;
+ }
+ const filtered = content.filter(
+ (part) => (part as LooseContentPart | null | undefined)?.type !== ContentTypes.ACTIVITY_LABEL,
+ );
+ if (filtered.length === content.length) {
+ return message;
+ }
+ changed = true;
+ return { ...message, content: filtered };
+ });
+ return changed ? result : payload;
+}
+
+/** Minimal SSE shape for synthesized gap events. */
+interface ActivityLabelGapEvent {
+ event: string;
+ data: Record<string, unknown>;
+}
+
+/**
+ * Synthesizes `on_activity_label` events for labels that appeared OR were
+ * filled between a resume snapshot and subscriber attach. In Redis mode the
+ * label publish is fire-and-forget and the sync payload carries only the
+ * snapshot, so a label claimed or resolved in that window would otherwise
+ * never reach the reconnecting client. Compares by index: a fresh label part
+ * whose text or pending state differs from the snapshot's (or that has no
+ * snapshot counterpart) is re-emitted. Idempotent - the client applier
+ * ignores duplicates and refuses stale pending placeholders.
+ */
+export function synthesizeActivityLabelGapEvents(
+ snapshotContent: ReadonlyArray<LooseContentPart | null | undefined>,
+ freshContent: ReadonlyArray<LooseContentPart | null | undefined>,
+ meta: { conversationId: string; responseMessageId?: string },
+): ActivityLabelGapEvent[] {
+ const events: ActivityLabelGapEvent[] = [];
+ for (let i = 0; i < freshContent.length; i++) {
+ const part = freshContent[i];
+ if (part?.type !== ContentTypes.ACTIVITY_LABEL) {
+ continue;
+ }
+ const snapshot = snapshotContent[i];
+ const isSameLabel =
+ snapshot?.type === ContentTypes.ACTIVITY_LABEL &&
+ snapshot[ContentTypes.ACTIVITY_LABEL] === part[ContentTypes.ACTIVITY_LABEL] &&
+ snapshot.pending === part.pending;
+ if (isSameLabel) {
+ continue;
+ }
+ events.push({
+ event: 'on_activity_label',
+ data: {
+ index: i,
+ part,
+ conversationId: meta.conversationId,
+ ...(meta.responseMessageId != null && { responseMessageId: meta.responseMessageId }),
+ },
+ });
+ }
+ return events;
+}
+
+/** Host closures the wiring needs; each is a thin bridge into the caller. */
+export interface ActivityLabelHostDeps {
+ /** Cost cap from `activityMaxPerRun`; falls back to the hook default. */
+ maxPerRun?: number;
+ /** Prompt truncation from `activityCharLimit`; falls back to the hook default. */
+ charLimit?: number;
+ /** `activityPrompt` override, applied on both generation paths. */
+ prompt?: string;
+ abortSignal?: AbortSignal;
+ /** Returns the LIVE host content array (same instance the SDK writes into). */
+ getContentParts: () => Array<LooseContentPart | null | undefined>;
+ /** Bumps the shared index offset so subsequent SDK indices skip the slot. */
+ bumpIndexOffset: () => void;
+ /** Emits the on_activity_label SSE/chunk event for a slot state. */
+ emitLabelEvent: (index: number, part: LooseContentPart) => Promise<unknown>;
+ /** Registers a promise the bounded settle must await at finalization:
+ * per-slot fill completion AND the hook's whole detached task (fill plus
+ * the usage accounting deferred until after the commit). */
+ trackPendingFill: (fillDone: Promise<void>) => void;
+ /**
+ * True once the response has finalized (settle timed out). A late fill
+ * must then neither mutate persisted content nor emit chunks for a job
+ * whose runtime is gone.
+ */
+ isClosed?: () => boolean;
+ resolveLLM: () => Promise<ActivityLabelLLM>;
+ /**
+ * Resolve `undefined` to DECLINE — this bridge cannot serve the request, so
+ * the hook falls back to the direct model call. `null` means it ran and
+ * produced no label. The distinction is the contract the hook keys on, so it
+ * belongs in the exported type.
+ */
+ generateLabel?: (payload: GenerateLabelPayload) => Promise<string | null | undefined>;
+ getInvokeCallbacks?: () => ActivityLabelInvokeCallbacks;
+}
+
+/**
+ * Builds the run wiring for activity labels: slot claiming at each batch
+ * boundary (steering's index-offset pattern), fill-time label emit,
+ * groupId/agentId lane stamping, and settle tracking. Implementation lives
+ * here (TS) so the JS controller stays a thin wrapper.
+ */
+export function createActivityLabelWiring(deps: ActivityLabelHostDeps): {
+ hook: HookCallback<'PostToolBatch'>;
+} {
+ /** One pass over resumed content for BOTH seeds: the quota counts every
+ * label part (filled or not, so a HITL resume cannot mint a fresh quota
+ * after every approval) while continuity keeps only committed text,
+ * keyed by content index so run order survives out-of-order fills. */
+ const resumedParts = deps.getContentParts();
+ let initialGeneratedCount = 0;
+ const initialLabels: Array<{ index: number; text: string }> = [];
+ for (let i = 0; i < resumedParts.length; i++) {
+ const part = resumedParts[i];
+ if (part?.type !== ContentTypes.ACTIVITY_LABEL) {
+ continue;
+ }
+ initialGeneratedCount += 1;
+ const text = part[ContentTypes.ACTIVITY_LABEL];
+ if (typeof text === 'string' && text.length > 0 && part.pending !== true) {
+ initialLabels.push({ index: i, text });
+ }
+ }
+ return {
+ hook: createActivityLabelHook({
+ resolveLLM: deps.resolveLLM,
+ ...(deps.maxPerRun != null && { maxPerRun: deps.maxPerRun }),
+ ...(deps.charLimit != null && { charLimit: deps.charLimit }),
+ /** Always send an instruction. With none, the SDK path falls back to
+ * the published package's own generic prompt, so the register this
+ * module defines would apply to the fallback path only. */
+ prompt: deps.prompt ?? ACTIVITY_INSTRUCTION,
+ initialGeneratedCount,
+ initialLabels,
+ /** The settle must cover the whole detached task: deferred usage runs
+ * AFTER the fill resolves, so tracking fills alone would let
+ * finalization flush the usage sink mid-billing. */
+ trackTask: deps.trackPendingFill,
+ signal: deps.abortSignal,
+ getInvokeCallbacks: deps.getInvokeCallbacks,
+ ...(deps.generateLabel && { generateLabel: deps.generateLabel }),
+ claimSlot: (meta) => {
+ const parts = deps.getContentParts();
+ const index = parts.length;
+ /** Parallel-column runs: carry the batch's groupId onto the label
+ * part so ParallelContentRenderer places it inside its group
+ * instead of filtering it out as an unplaced sequential part. */
+ let groupId: unknown;
+ for (let i = parts.length - 1; i >= 0 && groupId == null; i--) {
+ const prior = parts[i];
+ if (
+ prior?.type === ContentTypes.TOOL_CALL &&
+ prior.groupId != null &&
+ typeof prior.tool_call?.id === 'string' &&
+ meta.toolCallIds.includes(prior.tool_call.id)
+ ) {
+ groupId = prior.groupId;
+ }
+ }
+ /** Context is captured BEFORE the label part is pushed — the scan
+ * stops at ACTIVITY_LABEL parts, so capturing after the push would
+ * hit the just-inserted label at the tail and collect nothing. */
+ const context = captureActivityBlockContext(parts, meta.executingAgentId);
+ const part: LooseContentPart = {
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: '',
+ tool_call_ids: meta.toolCallIds,
+ status: meta.status,
+ ...(meta.executingAgentId != null && { agentId: meta.executingAgentId }),
+ ...(groupId != null && { groupId }),
+ pending: true,
+ };
+ parts.push(part);
+ deps.bumpIndexOffset();
+ /**
+ * Publish the reservation immediately, empty and pending.
+ *
+ * Reserving the index server-side is not enough on its own: with no
+ * event for this slot, a cross-instance replay rebuilds content as
+ * [tool, <hole>, laterText] and compacts the hole away, so the fill
+ * that later arrives for this index lands on `laterText` and
+ * overwrites it. Publishing the empty part keeps the slot real
+ * everywhere the content is reconstructed.
+ *
+ * It stays invisible: `groupSequentialToolCalls` lets an empty label
+ * delimit its batch without becoming the header, so the block renders
+ * exactly as it does with the feature off until `fill` lands.
+ */
+ void Promise.resolve(deps.emitLabelEvent(index, part)).catch(() => {
+ /** Best-effort: a dropped reservation degrades to the pre-fix
+ * behavior, and must never break the batch that triggered it. */
+ });
+ let resolveFill: () => void = () => undefined;
+ const fillDone = new Promise<void>((resolve) => {
+ resolveFill = resolve;
+ });
+ deps.trackPendingFill(fillDone);
+ return {
+ index,
+ context,
+ fill: async (text) => {
+ try {
+ /** Finalization already passed: drop the result rather than
+ * mutating a saved response or emitting into a closed job.
+ * `false` tells the hook the label never surfaced, so its
+ * usage must not be billed. A scope that closes AFTER this
+ * check — while the durable emit below is in flight — does
+ * NOT un-commit: the emit was already dispatched and the
+ * mutation lands with it, so the fill still resolves `true`
+ * and the committed label bills. */
+ if (deps.isClosed?.() === true) {
+ return false;
+ }
+ /** Staged on a COPY; the shared part mutates only AFTER the
+ * durable emit succeeds. Mutating first let a FAILED emit
+ * leave the text on `contentParts` anyway — persistence could
+ * then save and display a label that no client ever received
+ * and that billing (keyed on the commit flag) never charged.
+ * Emitted even when generation produced nothing: the claim
+ * already published a PENDING part, so staying silent would
+ * leave the client pinned at pending forever. */
+ const next: LooseContentPart = { ...part, pending: false };
+ if (text != null && text.length > 0) {
+ next[ContentTypes.ACTIVITY_LABEL] = text;
+ }
+ await deps.emitLabelEvent(index, next);
+ part.pending = false;
+ if (text != null && text.length > 0) {
+ part[ContentTypes.ACTIVITY_LABEL] = text;
+ }
+ return true;
+ } finally {
+ resolveFill();
+ }
+ },
+ };
+ },
+ }),
+ };
+}
diff --git a/packages/api/src/agents/client.ts b/packages/api/src/agents/client.ts
index e3cb6ff280..df846bf8eb 100644
--- a/packages/api/src/agents/client.ts
+++ b/packages/api/src/agents/client.ts
@@ -285,7 +285,12 @@ export function countFormattedMessageTokens(
continue;
}
- if (type === ContentTypes.THINK || type === ContentTypes.ERROR) {
+ if (
+ type === ContentTypes.THINK ||
+ type === ContentTypes.ERROR ||
+ // UI-only progress headers — never model input, never billed output
+ type === ContentTypes.ACTIVITY_LABEL
+ ) {
continue;
}
diff --git a/packages/api/src/agents/index.ts b/packages/api/src/agents/index.ts
index 115525fd25..749e2e6dbe 100644
--- a/packages/api/src/agents/index.ts
+++ b/packages/api/src/agents/index.ts
@@ -37,4 +37,5 @@ export * from './added';
export * from './load';
export * from './hitl';
export * from './steering';
+export * from './activityLabels';
export * from './toolValidation';
diff --git a/packages/api/src/agents/run.ts b/packages/api/src/agents/run.ts
index 1ffe249b2d..cab948492e 100644
--- a/packages/api/src/agents/run.ts
+++ b/packages/api/src/agents/run.ts
@@ -1037,6 +1037,7 @@ export async function createRun({
appConfig,
subagentUsageSink,
steering,
+ activityLabel,
hitlCapable = false,
toolInputValidationErrors,
streaming = true,
@@ -1095,6 +1096,12 @@ export async function createRun({
* OpenAI-compatible and Responses controllers have no job/SSE surface.
*/
steering?: { hook: HookCallback<'PostToolBatch'> };
+ /**
+ * Run-scoped tool-batch summary hook (PostToolBatch). Like steering, it
+ * registers independently of the approval policy and needs no checkpointer;
+ * the hook returns immediately and generates off the critical path.
+ */
+ activityLabel?: { hook: HookCallback<'PostToolBatch'> };
/**
* Whether the caller implements the HITL pause/resume lifecycle (inspects
* `run.getInterrupt()`, persists a pending action, exposes a resume route). Gates the
@@ -1454,6 +1461,16 @@ export async function createRun({
* this guard is defense in depth).
*/
let hooks = hitl?.hooks;
+ /** Activity labels register BEFORE the steer drain: the label must claim
+ * its slot while the batch's tool parts are still the content tail. If a
+ * steer drained first, its injected part would flush the tool block in
+ * sequential rendering and orphan the label outside its group. With the
+ * label claimed first, parts order as [tools…, label, steer] — the label
+ * terminates the group and the steer renders after it. */
+ if (activityLabel != null) {
+ hooks = hooks ?? new HookRegistry();
+ hooks.register('PostToolBatch', { hooks: [activityLabel.hook] });
+ }
if (steering != null && isSteeringSupported()) {
hooks = hooks ?? new HookRegistry();
hooks.register('PostToolBatch', { hooks: [steering.hook] });
diff --git a/packages/api/src/stream/GenerationJobManager.ts b/packages/api/src/stream/GenerationJobManager.ts
index 262ec93f95..d97318debb 100644
--- a/packages/api/src/stream/GenerationJobManager.ts
+++ b/packages/api/src/stream/GenerationJobManager.ts
@@ -38,6 +38,7 @@ import {
synthesizeAppliedSteerEvents,
} from './SteeringLifecycle';
import { isPendingActionStale, isPendingActionExpired } from './interfaces/IJobStore';
+import { synthesizeActivityLabelGapEvents } from '~/agents/activityLabels/wiring';
import { InMemoryEventTransport } from './implementations/InMemoryEventTransport';
import { InMemoryJobStore } from './implementations/InMemoryJobStore';
import { normalizeResumeRunStepIndices } from '~/agents/hitl/resume';
@@ -2258,6 +2259,20 @@ class GenerationJobManagerClass {
// the queue shows gap activity, and synthesis sources from the FRESH
// content view so an applied steer with no snapshot id still surfaces.
const jobActive = liveJob?.status === 'running' || liveJob?.status === 'requires_action';
+ /** Shared by the steer and activity-label gap passes below: whichever
+ * needs the fresh content view first pays for it, the other reuses it.
+ * Both reconcile the same snapshot→subscribe window, so re-reading per
+ * feature would bill two round trips for one question. */
+ let freshContent: t.ServerSentEvent[] | undefined;
+ let freshContentRead = false;
+ const readFreshContent = async (): Promise<unknown[] | undefined> => {
+ if (!freshContentRead) {
+ freshContentRead = true;
+ const contentResult = await this.jobStore.getContentParts(streamId, liveJob?.createdAt);
+ freshContent = contentResult?.content as t.ServerSentEvent[] | undefined;
+ }
+ return freshContent as unknown[] | undefined;
+ };
if (resumeState != null && jobActive) {
const snapshotSteers = resumeState.pendingSteers ?? [];
const liveQueue = await this.jobStore.peekSteers(streamId, liveJob.createdAt);
@@ -2273,14 +2288,14 @@ class GenerationJobManagerClass {
resumeState.pendingSteers = livePending.length > 0 ? livePending : undefined;
}
if (queueChanged || liveQueue.length > 0) {
- const contentResult = await this.jobStore.getContentParts(streamId, liveJob.createdAt);
+ const content = await readFreshContent();
if (options?.signal?.aborted || this.detachSubscriptionDuringShutdown(subscription)) {
return cancelResumeSubscription();
}
const gapEvents = synthesizeAppliedSteerEvents(
(resumeState.aggregatedContent ?? []) as SteerContentView,
liveQueue,
- (contentResult?.content ?? []) as SteerContentView,
+ (content ?? []) as SteerContentView,
{ conversationId: streamId, responseMessageId: resumeState.responseMessageId },
);
if (gapEvents.length > 0) {
@@ -2289,6 +2304,55 @@ class GenerationJobManagerClass {
}
}
+ /**
+ * Same snapshot→subscribe race for activity labels: the label publish is
+ * fire-and-forget, so a slot claimed (or filled) in the window is in
+ * neither the snapshot nor the chunk replay the client already applied.
+ * Compare the snapshot content view against a fresh read and re-emit any
+ * label whose text/pending state moved; the client applier is idempotent
+ * and refuses stale pending placeholders.
+ *
+ * Gated on the run's own flag, falling back to the snapshot when the
+ * flag is absent. Reconciling unconditionally would be simpler and would
+ * also close the residual window below, but it bills a content read to
+ * every resume of every run — including deployments with the feature
+ * off — which the steer pass deliberately avoids ("an unchanged empty
+ * queue skips the content re-read").
+ *
+ * The residual: if `markActivityLabels` lost its write AND the first
+ * label is claimed inside the gap, this is skipped. The flag is a
+ * SEPARATE write from the durable label append, so that is genuinely
+ * possible rather than implying a broken store — which is why the mark
+ * is retried at run setup instead of being fire-and-forget. When the
+ * steer pass above already fetched content, this check is free.
+ */
+ const snapshotHasActivityLabels =
+ resumeState?.aggregatedContent?.some(
+ (part) => (part as { type?: string } | null)?.type === 'activity_label',
+ ) === true;
+ if (
+ resumeState != null &&
+ jobActive &&
+ (liveJob?.activityLabels === true || snapshotHasActivityLabels)
+ ) {
+ const labelContent = await readFreshContent();
+ if (options?.signal?.aborted || this.detachSubscriptionDuringShutdown(subscription)) {
+ return cancelResumeSubscription();
+ }
+ if (labelContent != null) {
+ const labelGapEvents = synthesizeActivityLabelGapEvents(
+ (resumeState.aggregatedContent ?? []) as Parameters<
+ typeof synthesizeActivityLabelGapEvents
+ >[0],
+ labelContent as Parameters<typeof synthesizeActivityLabelGapEvents>[1],
+ { conversationId: streamId, responseMessageId: resumeState.responseMessageId },
+ );
+ if (labelGapEvents.length > 0) {
+ pendingEvents.push(...(labelGapEvents as t.ServerSentEvent[]));
+ }
+ }
+ }
+
// Reconciliation is complete. Events that arrive after this point already belong to the
// paused transport subscription and must remain there for activation rather than being
// appended to a pending-events array the caller may already be serializing.
@@ -2349,6 +2413,21 @@ class GenerationJobManagerClass {
* cross-replica reconnect can reconstruct content without them. The default
* stays fire-and-forget — no added latency on the per-delta hot path.
*/
+ /**
+ * Flags a run as producing activity labels. Read back on resume so label
+ * gap-reconciliation can be skipped for runs without the feature WITHOUT
+ * inspecting content — the first label can be claimed inside the
+ * snapshot->subscribe window, so content is not a reliable signal.
+ * Best-effort: the flag is an optimization hint, never correctness.
+ */
+ async markActivityLabels(streamId: string): Promise<void> {
+ /** Deliberately REJECTS on failure. This flag gates resume gap
+ * reconciliation, so the caller retries it; swallowing the error here
+ * resolved successfully and made that retry unreachable, leaving the
+ * flag absent after a transient write failure. */
+ await this.jobStore.updateJob(streamId, { activityLabels: true });
+ }
+
async emitChunk(
streamId: string,
event: t.ServerSentEvent,
@@ -2362,7 +2441,6 @@ class GenerationJobManagerClass {
) {
return;
}
-
const sequence = ++runtime.emissionSequence;
let signalSnapshotReady!: () => void;
const snapshotReady = new Promise<void>((resolve) => {
diff --git a/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts b/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts
index 3019268d51..2dabfb47d7 100644
--- a/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts
+++ b/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts
@@ -2855,6 +2855,94 @@ describe('RedisJobStore Integration Tests', () => {
await store.destroy();
});
+
+ test('getContentParts reconstructs the LAST on_activity_label chunk per index', async () => {
+ if (!ioredisClient) {
+ return;
+ }
+
+ const { RedisJobStore } = await import('../implementations/RedisJobStore');
+ const store = new RedisJobStore(ioredisClient);
+ await store.initialize();
+
+ const streamId = `activity-recon-${Date.now()}`;
+ await store.createJob(streamId, 'label-user', streamId);
+
+ const chunks = [
+ {
+ event: 'on_run_step',
+ data: {
+ id: 'step-1',
+ index: 0,
+ stepDetails: { type: 'tool_calls', tool_calls: [] },
+ },
+ },
+ /** Claim-time placeholder (counts only) at index 1 … */
+ {
+ event: 'on_activity_label',
+ data: {
+ index: 1,
+ part: {
+ type: 'activity_label',
+ activity_label: '',
+ counts: { searches: 1, reads: 0, writes: 0, commands: 0, other: 0 },
+ status: 'ok',
+ pending: true,
+ },
+ },
+ },
+ /** … then the resolved label for the same slot: last write wins. */
+ {
+ event: 'on_activity_label',
+ data: {
+ index: 1,
+ part: {
+ type: 'activity_label',
+ activity_label: 'Searched runtime release notes',
+ counts: { searches: 1, reads: 0, writes: 0, commands: 0, other: 0 },
+ status: 'ok',
+ pending: false,
+ },
+ },
+ },
+ {
+ event: 'on_run_step',
+ data: {
+ id: 'step-2',
+ // Emitted with the already-shifted index (offset wrapper)
+ index: 2,
+ stepDetails: { type: 'message_creation', message_creation: {} },
+ },
+ },
+ {
+ event: 'on_message_delta',
+ data: { id: 'step-2', delta: { content: { type: 'text', text: 'After batch.' } } },
+ },
+ ];
+ for (const chunk of chunks) {
+ await store.appendChunk(streamId, chunk);
+ }
+
+ const result = await store.getContentParts(streamId);
+ expect(result).not.toBeNull();
+ const parts = result!.content as Array<{
+ type?: string;
+ activity_label?: string;
+ pending?: boolean;
+ }>;
+ /** Position-independent: the placeholder and the filled event share a
+ * slot, so exactly ONE label part must survive and it must carry the
+ * resolved text (last write wins). */
+ const labels = parts.filter((part) => part?.type === 'activity_label');
+ expect(labels).toHaveLength(1);
+ expect(labels[0]).toMatchObject({
+ activity_label: 'Searched runtime release notes',
+ pending: false,
+ });
+ expect(parts.some((part) => part?.type === 'text')).toBe(true);
+
+ await store.destroy();
+ });
});
describe('Idempotency claims (#14339 duplicate-billing guard)', () => {
diff --git a/packages/api/src/stream/implementations/RedisJobStore.ts b/packages/api/src/stream/implementations/RedisJobStore.ts
index 32ff26f030..7f22304e49 100644
--- a/packages/api/src/stream/implementations/RedisJobStore.ts
+++ b/packages/api/src/stream/implementations/RedisJobStore.ts
@@ -1472,9 +1472,12 @@ export class RedisJobStore implements IJobStore {
});
}
- /** Splice-inserts host-authored steer parts (from `on_steer_applied`
- * chunks) into an SDK-graph content view, ascending by recorded index so
- * each host-view position lands exactly where live clients saw it. */
+ /** Splice-inserts host-authored parts (steers from `on_steer_applied`,
+ * activity labels from `on_activity_label` chunks) into an SDK-graph
+ * content view, ascending by recorded index so each host-view position
+ * lands exactly where live clients saw it. Label events fire twice per
+ * slot (placeholder, then filled); chronological last-wins keeps the
+ * resolved label. */
private async overlayHostSteerParts(
streamId: string,
parts: Agents.MessageContentComplex[],
@@ -1485,23 +1488,34 @@ export class RedisJobStore implements IJobStore {
return parts;
}
const steers: Array<{ index: number; part: Agents.MessageContentComplex }> = [];
+ const labelsByIndex = new Map<number, Agents.MessageContentComplex>();
for (const chunk of chunks) {
const event = chunk as { event?: string; data?: unknown };
- if (event.event !== 'on_steer_applied') {
+ if (event.event === 'on_steer_applied') {
+ const steerData = event.data as { index?: number; part?: Agents.MessageContentComplex };
+ if (typeof steerData.index === 'number' && steerData.part != null) {
+ steers.push({ index: steerData.index, part: steerData.part });
+ }
continue;
}
- const steerData = event.data as { index?: number; part?: Agents.MessageContentComplex };
- if (typeof steerData.index === 'number' && steerData.part != null) {
- steers.push({ index: steerData.index, part: steerData.part });
+ if (event.event === 'on_activity_label') {
+ const labelData = event.data as { index?: number; part?: Agents.MessageContentComplex };
+ if (typeof labelData.index === 'number' && labelData.part != null) {
+ labelsByIndex.set(labelData.index, labelData.part);
+ }
}
}
- if (steers.length === 0) {
+ if (steers.length === 0 && labelsByIndex.size === 0) {
return parts;
}
- steers.sort((a, b) => a.index - b.index);
+ const inserts = [
+ ...steers,
+ ...[...labelsByIndex.entries()].map(([index, part]) => ({ index, part })),
+ ];
+ inserts.sort((a, b) => a.index - b.index);
const merged = [...parts];
- for (const steer of steers) {
- merged.splice(Math.min(steer.index, merged.length), 0, steer.part);
+ for (const insert of inserts) {
+ merged.splice(Math.min(insert.index, merged.length), 0, insert.part);
}
return merged;
}
@@ -1667,6 +1681,17 @@ export class RedisJobStore implements IJobStore {
continue;
}
+ // Activity-label parts are host-authored like steers and claimed at a
+ // fixed index. The event fires twice per slot (counts placeholder,
+ // then resolved label); chronological replay makes the last write win.
+ if (event.event === 'on_activity_label') {
+ const labelData = event.data as { index?: number; part?: Agents.MessageContentComplex };
+ if (typeof labelData.index === 'number' && labelData.part != null) {
+ contentParts[labelData.index] = labelData.part;
+ }
+ continue;
+ }
+
if (!validEvents.has(event.event)) {
continue;
}
@@ -2219,6 +2244,11 @@ export class RedisJobStore implements IJobStore {
pendingAction: this.parsePendingAction(data.pendingAction),
pendingActionId: data.pendingActionId || undefined,
lastActiveAt: data.lastActiveAt ? parseInt(data.lastActiveAt, 10) : undefined,
+ /** `markActivityLabels` persists this, so it has to be read back:
+ * without it every Redis reload leaves the flag undefined and resume
+ * skips activity-label gap reconciliation, silently dropping a label
+ * that resolved between the snapshot and subscriber attach. */
+ activityLabels: data.activityLabels != null ? data.activityLabels === '1' : undefined,
};
}
diff --git a/packages/api/src/stream/interfaces/IJobStore.ts b/packages/api/src/stream/interfaces/IJobStore.ts
index 2c2952aa73..4d1f023685 100644
--- a/packages/api/src/stream/interfaces/IJobStore.ts
+++ b/packages/api/src/stream/interfaces/IJobStore.ts
@@ -43,6 +43,15 @@ export interface SerializableJobData {
/** Response message ID for reconnection */
responseMessageId?: string;
+ /**
+ * Whether this run has activity labels enabled (per-endpoint
+ * `activityLabel: true`). Set once at run start so the resume path can
+ * decide whether to reconcile label gaps WITHOUT reading content — the
+ * first label of a run can be claimed inside the snapshot->subscribe
+ * window, so the snapshot itself is not a reliable signal.
+ */
+ activityLabels?: boolean;
+
/**
* Deferred-tool names discovered (via `tool_search`) before a HITL pause, captured
* so a resume can replay them into `createRun` — the rebuilt graph uses `messages: []`
diff --git a/packages/api/src/utils/headers.ts b/packages/api/src/utils/headers.ts
index 37ddd571ce..cb84449dfd 100644
--- a/packages/api/src/utils/headers.ts
+++ b/packages/api/src/utils/headers.ts
@@ -96,7 +96,11 @@ export function resolveConfigHeaders({
body,
customUserVars,
}: {
- llmConfig?: RunLLMConfig | null;
+ /** Partial: this only reads the three provider header carriers, so
+ * callers with a bare ClientOptions (e.g. auxiliary generations like
+ * titles/activity labels) can resolve headers without assembling a
+ * full run config. */
+ llmConfig?: Partial<RunLLMConfig> | null;
user?: Partial<IUser> | { id: string };
body?: RequestBody;
customUserVars?: Record<string, string>;
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 29e8b6abb0..428c32b4da 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -613,6 +613,27 @@ export const baseEndpointSchema = z.object({
* completes (legacy behavior).
*/
titleTiming: z.union([z.literal('immediate'), z.literal('final')]).optional(),
+ /**
+ * Agent activity groups: collapse each contiguous block of reasoning and
+ * tool calls under a generated one-line header. Mirrors the title options
+ * above — `activityLabel` enables it (like `titleConvo`), the rest tune
+ * the fast model that writes the label.
+ *
+ * NOTE: fields added here reach `endpoints.all` automatically (that schema
+ * is `baseEndpointSchema.omit({ baseURL })`), but NOT Azure — see the
+ * enumerated `.pick()` in `azureEndpointSchema` below.
+ */
+ activityLabel: z.boolean().optional(),
+ /** Model used to write activity labels. Defaults to `titleModel`, then the agent's model. */
+ activityModel: z.string().optional(),
+ /** Endpoint whose credentials the label model runs on. Defaults to the agent's endpoint. */
+ activityEndpoint: z.string().optional(),
+ /** Overrides the system prompt used to write activity labels. */
+ activityPrompt: z.string().optional(),
+ /** Cost cap: maximum labels generated per run. Default 20. */
+ activityMaxPerRun: z.number().int().positive().optional(),
+ /** Per-entry truncation of tool input/output in the label prompt. Default 600. */
+ activityCharLimit: z.number().int().positive().optional(),
/** Maximum characters allowed in a single tool result before truncation. */
maxToolResultChars: z.number().positive().optional(),
});
@@ -1024,6 +1045,13 @@ export const azureEndpointSchema = z
assistants: z.boolean().optional(),
})
.and(
+ /**
+ * Azure carries only the base-endpoint fields enumerated here. This is a
+ * `.pick()`, NOT an omit, so a field added to `baseEndpointSchema` is
+ * silently unavailable on Azure endpoints until it is listed below —
+ * unlike `endpoints.all`, which omits and therefore inherits new fields
+ * automatically. Keep this list in sync when adding endpoint options.
+ */
endpointSchema
.pick({
streamRate: true,
@@ -1033,6 +1061,12 @@ export const azureEndpointSchema = z
titlePrompt: true,
titleTiming: true,
titlePromptTemplate: true,
+ activityLabel: true,
+ activityModel: true,
+ activityEndpoint: true,
+ activityPrompt: true,
+ activityMaxPerRun: true,
+ activityCharLimit: true,
})
.partial(),
);
@@ -1934,6 +1968,13 @@ export const configSchema = z.object({
endpoints: z
.object({
allowedAddresses: allowedAddressesSchema,
+ /**
+ * Defaults applied to every endpoint. Omit-based, so options added to
+ * `baseEndpointSchema` are inherited here automatically — no list to
+ * maintain (contrast `azureEndpointSchema`, which enumerates via
+ * `.pick()`). Resolution order at read sites is `all` > the named
+ * endpoint > a custom endpoint's own config.
+ */
all: baseEndpointSchema.omit({ baseURL: true }).optional(),
[EModelEndpoint.openAI]: baseEndpointSchema.optional(),
[EModelEndpoint.google]: baseEndpointSchema.optional(),
diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.ts
index 7316d2b33e..7b00aeee59 100644
--- a/packages/data-provider/src/types.ts
+++ b/packages/data-provider/src/types.ts
@@ -175,6 +175,18 @@ export type TSubmission = {
clientTimestamp?: string;
ephemeralAgent?: TEphemeralAgent | null;
editedContent?: TEditedContent | null;
+ /**
+ * Length of the retained content prefix for an edited resubmission, captured
+ * when the submission is built.
+ *
+ * The server indexes only NEW content, so the client offsets incoming
+ * indices by the prefix it kept. `initialResponse.content` cannot be used
+ * for that after a reconnect: the resume sync overwrites it with the
+ * server's completion-local snapshot, whose length is unrelated to the
+ * prefix. Recording the length up front keeps the offset stable across
+ * resumes for run steps and activity labels alike.
+ */
+ editPrefixLength?: number;
/** Added conversation for multi-convo feature */
addedConvo?: TConversation;
/** Skills the user invoked via the `$` popover for this submission. */
diff --git a/packages/data-provider/src/types/assistants.ts b/packages/data-provider/src/types/assistants.ts
index 2b03a5b4ee..c19c42c051 100644
--- a/packages/data-provider/src/types/assistants.ts
+++ b/packages/data-provider/src/types/assistants.ts
@@ -628,6 +628,16 @@ export type TMessageContentParts =
} & ContentMetadata)
| ({ type: ContentTypes.IMAGE_FILE; image_file: ImageFile & PartMetadata } & ContentMetadata)
| (SummaryContentPart & ContentMetadata)
+ | ({
+ /** One-line LLM-generated note describing a completed tool batch. UI-only:
+ * never sent to the model (stripped before payload formatting). */
+ type: ContentTypes.ACTIVITY_LABEL;
+ activity_label?: string;
+ tool_call_ids?: string[];
+ /** ok = all tools succeeded, failed = all failed, partial = mixed. */
+ status?: 'ok' | 'partial' | 'failed';
+ pending?: boolean;
+ } & ContentMetadata)
| (Agents.AgentUpdate & ContentMetadata)
| (Agents.MessageContentImageUrl & ContentMetadata)
| (Agents.MessageContentVideoUrl & ContentMetadata)
diff --git a/packages/data-provider/src/types/runs.spec.ts b/packages/data-provider/src/types/runs.spec.ts
index f4058d1c7b..d2090b9e94 100644
--- a/packages/data-provider/src/types/runs.spec.ts
+++ b/packages/data-provider/src/types/runs.spec.ts
@@ -33,6 +33,19 @@ describe('promptTokensFromUsage', () => {
expect(promptTokensFromUsage({ provider: 'anthropic' })).toBe(0);
});
+ it('accepts the activity-label usage bucket emitted on the wire', () => {
+ /** Type-level pin: the backend emits this literal for fast-model header
+ * calls, so the union must be able to represent the actual payload. */
+ const event: TTokenUsageEvent = {
+ input_tokens: 120,
+ output_tokens: 9,
+ usage_type: 'activity-label',
+ runId: 'msg-1:1700000000000',
+ seq: -1,
+ };
+ expect(promptTokensFromUsage(event)).toBe(120);
+ });
+
it('uses the magnitude heuristic when the provider is absent (cache ≤ input ⇒ included)', () => {
/** OpenAI-compatible/custom payload with no provider: cache already folded
* into input_tokens, so it must NOT be re-added. */
diff --git a/packages/data-provider/src/types/runs.ts b/packages/data-provider/src/types/runs.ts
index fdf1ca5eef..47362c94db 100644
--- a/packages/data-provider/src/types/runs.ts
+++ b/packages/data-provider/src/types/runs.ts
@@ -12,6 +12,7 @@ export enum ContentTypes {
INPUT_AUDIO = 'input_audio',
AGENT_UPDATE = 'agent_update',
SUMMARY = 'summary',
+ ACTIVITY_LABEL = 'activity_label',
STEER = 'steer',
ERROR = 'error',
}
@@ -78,6 +79,39 @@ export enum SteerEvents {
ON_STEER_APPLIED = 'on_steer_applied',
}
+/**
+ * Activity-label event names. `on_activity_label` streams to live clients
+ * when a tool-batch label part is claimed (deterministic counts) and again
+ * when the fast-model label resolves; reconnecting clients recover applied
+ * labels from `aggregatedContent` like any other content part.
+ */
+export enum ActivityLabelEvents {
+ ON_ACTIVITY_LABEL = 'on_activity_label',
+}
+
+/** Payload of the `on_activity_label` SSE event. */
+export type TActivityLabelEvent = {
+ /** Absolute content index the label part occupies. */
+ index: number;
+ part: {
+ type: ContentTypes.ACTIVITY_LABEL;
+ [ContentTypes.ACTIVITY_LABEL]: string;
+ tool_call_ids?: string[];
+ counts?: {
+ searches: number;
+ reads: number;
+ writes: number;
+ commands: number;
+ other: number;
+ };
+ status?: 'ok' | 'partial' | 'failed';
+ agentId?: string;
+ pending?: boolean;
+ };
+ responseMessageId?: string;
+ conversationId?: string;
+};
+
/** A steer message queued server-side but not yet injected into the run. */
export type TPendingSteer = {
steerId: string;
@@ -171,8 +205,9 @@ export type TTokenUsageEvent = {
provider?: string;
/** Non-primary buckets fold into session cost/totals but not the live
* context gauge: hidden sequential-agent calls (`sequential`), summary
- * passes (`summarization`), and isolated subagent runs (`subagent`) */
- usage_type?: 'summarization' | 'subagent' | 'sequential';
+ * passes (`summarization`), isolated subagent runs (`subagent`), and
+ * fast-model activity headers (`activity-label`) */
+ usage_type?: 'summarization' | 'subagent' | 'sequential' | 'activity-label';
runId?: string;
/** Per-run emission sequence; keeps identical payloads from distinct model calls unique */
seq?: number;