🌄 fix: Show Skill Pills When a Turn Starts (#18036)

Co-authored-by: Lia <lia@librechat.ai>
This commit is contained in:
lia-by-librechat[bot] 2026-11-11 12:49:50 -05:00 • committed by GitHub
parent 6c479ef244
commit 1ef7d244b5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 211 additions and 52 deletions

View file

@ -40,6 +40,7 @@ const {
rejectPrivateTextAdmission,
bindPrivateTextPersistenceAbort,
persistedReasoningOverrideFields,
skillMessageFields,
isTemporaryTurn,
loadHistoryRows,
} = require('@librechat/api');
@ -620,6 +621,13 @@ class BaseClient {
Object.assign(
userMessage,
skillMessageFields({
manualSkills: this.options.req?.body?.manualSkills,
alwaysApplySkillPrimes: this.options.agent?.alwaysApplySkillPrimes,
isEdited: opts.isEdited,
isCompaction: opts.isCompaction,
skipSaveUserMessage: this.skipSaveUserMessage,
}),
persistedReasoningOverrideFields({
rawReasoningOverride: this.options.req?.body?.reasoningOverride,
isEdited: opts.isEdited,
@ -897,39 +905,6 @@ class BaseClient {
}
delete userMessage.image_urls;
}
/**
* Persist the user's manual skill picks onto the user message so the
* frontend `SkillPills` component can render them in history
* after reload. UI-only metadata — the runtime skill resolution
* pipeline reads the top-level `req.body.manualSkills` separately.
* Filter is defense-in-depth on top of Mongoose schema validation:
* keeps the DB row free of empty/non-string entries even if a
* crafted payload slips past schema checks upstream.
*/
const rawManualSkills = this.options.req?.body?.manualSkills;
if (Array.isArray(rawManualSkills) && rawManualSkills.length > 0) {
const skills = rawManualSkills.filter((s) => typeof s === 'string' && s.length > 0);
if (skills.length > 0) {
userMessage.manualSkills = skills;
}
}
/**
* Persist the names of skills auto-primed this turn via `always-apply`
* frontmatter so `SkillPills` can render pinned-variant badges
* on the user bubble that survive reload and history render. Frozen
* at turn time (not reconstructed from `Skill.alwaysApply` at render
* time) because the flag is mutable — historical turns must keep
* their audit trail even if an admin flips `alwaysApply` off later.
*/
const alwaysApplySkillPrimes = this.options.agent?.alwaysApplySkillPrimes;
if (Array.isArray(alwaysApplySkillPrimes) && alwaysApplySkillPrimes.length > 0) {
const names = alwaysApplySkillPrimes
.map((p) => p?.name)
.filter((n) => typeof n === 'string' && n.length > 0);
if (names.length > 0) {
userMessage.alwaysAppliedSkills = names;
}
}
const startUserMessagePersistence = () => {
this.savedMessageIds.add(userMessage.messageId);
return this.saveMessageToDatabase(userMessage, saveOptions, user).catch((err) => {

View file

@ -3813,6 +3813,83 @@ describe('BaseClient', () => {
});
});
describe('sendMessage skill metadata', () => {
test.each([
[
'manual',
{ manualSkills: ['manual-skill', '', 42] },
{},
{ manualSkills: ['manual-skill'] },
],
[
'always-applied',
{ alwaysAppliedSkills: ['untrusted-skill'] },
{ alwaysApplySkillPrimes: [{ name: 'always-skill' }, { name: '' }, {}] },
{ alwaysAppliedSkills: ['always-skill'] },
],
[
'combined',
{ manualSkills: ['manual-skill'] },
{ alwaysApplySkillPrimes: [{ name: 'always-skill' }] },
{ manualSkills: ['manual-skill'], alwaysAppliedSkills: ['always-skill'] },
],
])(
'attaches %s skills before start callbacks and preserves them on save',
async (_label, body, agent, expected) => {
TestClient.options = { ...TestClient.options, req: { body }, agent };
TestClient.saveMessageToDatabase = jest.fn().mockResolvedValue({ message: {} });
const starts = [];
const capture = (message) =>
starts.push({
manualSkills: message.manualSkills,
alwaysAppliedSkills: message.alwaysAppliedSkills,
});
await TestClient.sendMessage('Hello with skills', {
getReqData: ({ userMessage: message }) => {
if (message) capture(message);
},
onStart: capture,
});
expect(starts.length).toBeGreaterThanOrEqual(2);
for (const start of starts) {
expect(start).toMatchObject(expected);
}
const userSave = TestClient.saveMessageToDatabase.mock.calls.find(
([message]) => message.isCreatedByUser,
);
expect(userSave[0]).toMatchObject(expected);
},
);
test('preserves historical skill metadata on a rerun', async () => {
const historical = [
...messageHistory.map((message) => ({ ...message })),
{ role: 'assistant', messageId: 'response-0', parentMessageId: '3', text: 'Previous' },
];
historical[2].manualSkills = ['original-manual'];
historical[2].alwaysAppliedSkills = ['original-always'];
const client = initializeFakeClient(apiKey, options, historical);
client.options = {
...client.options,
req: { body: { manualSkills: ['new-manual'] } },
agent: { alwaysApplySkillPrimes: [{ name: 'new-always' }] },
};
const result = await client.handleStartMethods('Rerun', {
conversationId: 'conversation-1',
parentMessageId: '3',
responseMessageId: 'response-0',
isEdited: true,
isContinued: true,
});
expect(result.userMessage.manualSkills).toEqual(['original-manual']);
expect(result.userMessage.alwaysAppliedSkills).toEqual(['original-always']);
});
});
describe('sendMessage quote references', () => {
// The blockquote merge itself lives in AgentClient.buildMessages / prependQuotes
// (covered by packages/api specs). BaseClient's job is to attach the normalized

View file

@ -4384,6 +4384,55 @@ describe('ResumableAgentController resume metadata', () => {
expect(mockGenerationJobManager.completeJob).toHaveBeenCalledTimes(3);
});
it('announces resolved skills at turn start and preserves them in resume metadata', async () => {
const skills = {
manualSkills: ['manual-skill'],
alwaysAppliedSkills: ['resolved-always-skill'],
};
const client = {
options: {},
sendMessage: jest.fn(async (_text, options) => {
options.onStart(
{
messageId: 'server-user',
conversationId,
text: 'Hello with skills',
isCreatedByUser: true,
...skills,
},
'server-response',
);
throw new Error('stopped after start');
}),
};
await AgentController(
createFailedRequest({
manualSkills: ['unvalidated-manual'],
alwaysAppliedSkills: ['untrusted-always'],
}),
createResumableResponse(),
jest.fn(),
jest.fn().mockResolvedValue({ client }),
null,
);
await flushBackgroundGeneration();
expect(mockGenerationJobManager.emitChunk).toHaveBeenCalledWith(
conversationId,
expect.objectContaining({ created: true, message: expect.objectContaining(skills) }),
expect.any(Object),
);
expect(mockGenerationJobManager.updateMetadata).toHaveBeenCalledWith(
conversationId,
expect.objectContaining({
responseMessageId: 'server-response',
userMessage: expect.objectContaining(skills),
}),
1000,
);
});
it('uses the live user identity after generation starts', async () => {
const serverUserMessage = {
messageId: 'server-user',

View file

@ -2429,15 +2429,8 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit
// paused turn's files.
...(Array.isArray(req.body?.files) &&
req.body.files.length > 0 && { files: req.body.files }),
// Skill selections aren't on `userMsg` yet at onStart (BaseClient adds them
// later), so source them from the request — otherwise this update overwrites
// the preliminary metadata and a HITL-resumed turn loses its skill pills.
...(Array.isArray(req.body?.manualSkills) &&
req.body.manualSkills.length > 0 && { manualSkills: req.body.manualSkills }),
...(Array.isArray(req.body?.alwaysAppliedSkills) &&
req.body.alwaysAppliedSkills.length > 0 && {
alwaysAppliedSkills: req.body.alwaysAppliedSkills,
}),
manualSkills: userMsg.manualSkills,
alwaysAppliedSkills: userMsg.alwaysAppliedSkills,
},
},
jobCreatedAt,
@ -2449,22 +2442,12 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit
streamId,
{
created: true,
// Skill selections aren't on `userMessage` yet at onStart (BaseClient adds
// them later), so attach them from the request — this is the message
// `trackUserMessage` persists as the authoritative job.metadata.userMessage,
// and it's what the live client renders the user bubble from.
message: {
...userMessage,
// Carry files so trackUserMessage (the authoritative writer) persists them on
// job.metadata.userMessage for a HITL resume (see the updateMetadata above).
...(Array.isArray(req.body?.files) &&
req.body.files.length > 0 && { files: req.body.files }),
...(Array.isArray(req.body?.manualSkills) &&
req.body.manualSkills.length > 0 && { manualSkills: req.body.manualSkills }),
...(Array.isArray(req.body?.alwaysAppliedSkills) &&
req.body.alwaysAppliedSkills.length > 0 && {
alwaysAppliedSkills: req.body.alwaysAppliedSkills,
}),
},
streamId,
},

View file

@ -2,3 +2,4 @@ export * from './parts';
export * from './previews';
export * from './page';
export * from './history';
export * from './skills';

View file

@ -0,0 +1,32 @@
import { skillMessageFields } from './skills';
describe('skillMessageFields', () => {
it('returns manual and server-resolved always-applied skill names', () => {
expect(
skillMessageFields({
manualSkills: ['manual', '', 42, null],
alwaysApplySkillPrimes: [{ name: 'always' }, { name: '' }],
}),
).toEqual({ manualSkills: ['manual'], alwaysAppliedSkills: ['always'] });
});
it.each([undefined, null, [], [''], [42], 'manual'])(
'omits empty or malformed metadata: %p',
(manualSkills) => {
expect(skillMessageFields({ manualSkills, alwaysApplySkillPrimes: [] })).toEqual({});
},
);
it.each(['isEdited', 'isCompaction', 'skipSaveUserMessage'] as const)(
'leaves existing message fields alone for %s',
(flag) => {
expect(
skillMessageFields({
[flag]: true,
manualSkills: ['new-manual'],
alwaysApplySkillPrimes: [{ name: 'new-always' }],
}),
).toEqual({});
},
);
});

View file

@ -0,0 +1,42 @@
import type { TMessage } from 'librechat-data-provider';
import type { ResolvedSkillPrime } from '~/agents/skills';
interface SkillMessageInput {
manualSkills?: unknown;
alwaysApplySkillPrimes?: readonly Pick<ResolvedSkillPrime, 'name'>[];
isEdited?: boolean;
isCompaction?: boolean;
skipSaveUserMessage?: boolean;
}
/** Freeze skill badges before the turn is announced, preserving historical turns. */
export function skillMessageFields({
manualSkills,
alwaysApplySkillPrimes,
isEdited,
isCompaction,
skipSaveUserMessage,
}: SkillMessageInput): Pick<TMessage, 'manualSkills' | 'alwaysAppliedSkills'> {
if (isEdited || isCompaction || skipSaveUserMessage) {
return {};
}
const fields: Pick<TMessage, 'manualSkills' | 'alwaysAppliedSkills'> = {};
if (Array.isArray(manualSkills)) {
const names = manualSkills.filter(
(name): name is string => typeof name === 'string' && name.length > 0,
);
if (names.length > 0) {
fields.manualSkills = names;
}
}
if (Array.isArray(alwaysApplySkillPrimes)) {
const names = alwaysApplySkillPrimes
.map((prime) => prime?.name)
.filter((name): name is string => typeof name === 'string' && name.length > 0);
if (names.length > 0) {
fields.alwaysAppliedSkills = names;
}
}
return fields;
}