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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🔗 feat: use LibreChat prompt groups as agent instructions (#16686)
Atef Bellaaj3c90cde7d8de
diff --git a/api/cache/getLogStores.js b/api/cache/getLogStores.jsindex 53d73125df..a9916f3b4b 100644--- a/api/cache/getLogStores.js+++ b/api/cache/getLogStores.js@@ -74,6 +74,10 @@ const namespaces = {Time.THIRTY_SECONDS,),[CacheKeys.PASSKEY_CHALLENGE]: standardCache(CacheKeys.PASSKEY_CHALLENGE, Time.FIVE_MINUTES),+ [CacheKeys.AGENT_LINKED_INSTRUCTIONS]: standardCache(+ CacheKeys.AGENT_LINKED_INSTRUCTIONS,+ Time.FIVE_MINUTES,+ ),};/**diff --git a/api/server/controllers/agents/__tests__/openai.spec.js b/api/server/controllers/agents/__tests__/openai.spec.jsindex 7ca66410c9..d7511dba92 100644--- a/api/server/controllers/agents/__tests__/openai.spec.js+++ b/api/server/controllers/agents/__tests__/openai.spec.js@@ -412,6 +412,11 @@ jest.mock('~/server/services/Endpoints/agents/skillDeps', () => ({enrichLoadedToolsWithAgentContext: mockEnrichLoadedToolsWithAgentContext,}));+const mockResolveLinkedInstructions = jest.fn();+jest.mock('~/server/services/Endpoints/agents/linkedInstructions', () => ({+ getLinkedInstructionsResolver: jest.fn(() => mockResolveLinkedInstructions),+}));+jest.mock('~/cache', () => ({logViolation: jest.fn(),}));diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.jsindex aa079c64b4..6be7ee74d5 100644--- a/api/server/controllers/agents/__tests__/responses.unit.spec.js+++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js@@ -525,6 +525,11 @@ jest.mock('~/server/services/Endpoints/agents/skillDeps', () => ({enrichLoadedToolsWithAgentContext: mockEnrichLoadedToolsWithAgentContext,}));+const mockResolveLinkedInstructions = jest.fn();+jest.mock('~/server/services/Endpoints/agents/linkedInstructions', () => ({+ getLinkedInstructionsResolver: jest.fn(() => mockResolveLinkedInstructions),+}));+jest.mock('~/cache', () => ({logViolation: jest.fn(),}));diff --git a/api/server/controllers/agents/__tests__/resume.spec.js b/api/server/controllers/agents/__tests__/resume.spec.jsindex c702c35ca9..b5baf0c4a7 100644--- a/api/server/controllers/agents/__tests__/resume.spec.js+++ b/api/server/controllers/agents/__tests__/resume.spec.js@@ -1608,6 +1608,18 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {expect(mockInitializeClient).toHaveBeenCalledTimes(1);});+ it('passes isResume: true into initializeClient so recorded prompt-link usage is not doubled', async () => {+ mockGenerationJobManager.getJob.mockResolvedValue(makeToolApprovalJob());++ const res = await post(approveBody());+ expect(res.status).toBe(200);+ await settled;+ await flush();++ expect(mockInitializeClient).toHaveBeenCalledTimes(1);+ expect(mockInitializeClient.mock.calls[0][0]).toMatchObject({ isResume: true });+ });+it('does not read the checkpoint for a source unrelated to resume content', async () => {requestConfigOverrides = {filters: {diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.jsindex 7d0108bb2f..3e233348bc 100644--- a/api/server/controllers/agents/client.js+++ b/api/server/controllers/agents/client.js@@ -237,6 +237,9 @@ const {const { filterFilesByAgentAccess } = require('~/server/services/Files/permissions');const { encodeAndFormat } = require('~/server/services/Files/images/encode');const { createContextHandlers } = require('~/app/clients/prompts');+const {+ getLinkedInstructionsResolver,+} = require('~/server/services/Endpoints/agents/linkedInstructions');const { resolveConfigServers, getAccessibleMcpServerNames } = require('~/server/services/MCP');const { getMCPServerTools } = require('~/server/services/Config');const { getAccessibleMCPServers } = require('~/server/services/MCP');@@ -3392,6 +3395,13 @@ class AgentClient extends BaseClient {codeEnvAvailable: memoryCodeEnabled && memoryToolGrants?.runCode === true,statefulSessionsAvailable: memoryCapabilities.has(AgentCapabilities.stateful_code_sessions),useChatProjectContext: false,+ /** A saved memory agent may itself link its instructions to a native+ * prompt group; without a resolver `initializeAgent` falls back to+ * empty instructions for it. This path never counts a generation —+ * it primes memory extraction, not a model-facing turn the user+ * asked for. */+ resolveLinkedInstructions: getLinkedInstructionsResolver(),+ recordLinkedPromptUsage: false,},{getProjectFiles: db.getProjectFiles,diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.jsindex 4784ca4964..2491cb2281 100644--- a/api/server/controllers/agents/client.test.js+++ b/api/server/controllers/agents/client.test.js@@ -1963,6 +1963,11 @@ jest.mock('~/server/services/MCP', () => ({resolveConfigServers: jest.fn().mockResolvedValue({}),}));+const mockLinkedInstructionsResolver = jest.fn();+jest.mock('~/server/services/Endpoints/agents/linkedInstructions', () => ({+ getLinkedInstructionsResolver: jest.fn(() => mockLinkedInstructionsResolver),+}));+jest.mock('~/models', () => ({bulkInsertTransactions: jest.fn(),getCacheMultiplier: jest.fn(),@@ -8941,6 +8946,29 @@ describe('AgentClient - titleConvo', () => {);});+ it('passes the shared linked-instructions resolver, without recording usage, so a linked memory agent still resolves its instructions', async () => {+ mockCheckAccess.mockResolvedValue(true);+ mockInitializeAgent.mockResolvedValue({+ ...mockAgent,+ provider: EModelEndpoint.openAI,+ });+ mockCreateMemoryProcessor.mockResolvedValue([undefined, jest.fn()]);++ client = new AgentClient(mockOptions);+ client.conversationId = 'convo-123';+ client.responseMessageId = 'response-123';++ await client.useMemory();++ expect(mockInitializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ resolveLinkedInstructions: mockLinkedInstructionsResolver,+ recordLinkedPromptUsage: false,+ }),+ expect.any(Object),+ );+ });+it('should bind memory processing to the current generation epoch', async () => {mockReq._resumableStreamId = 'convo-123';mockCheckAccess.mockResolvedValue(true);diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.jsindex 28f996d0d2..817723c29d 100644--- a/api/server/controllers/agents/openai.js+++ b/api/server/controllers/agents/openai.js@@ -103,6 +103,9 @@ const {} = require('~/server/services/Endpoints/agents/skillDeps');const { createProvisionFilesCallback } = require('~/server/services/Files/provisionCallback');const { checkSessionsAlive, loadCodeApiKey } = require('~/server/services/Files/provision');+const {+ getLinkedInstructionsResolver,+} = require('~/server/services/Endpoints/agents/linkedInstructions');const { getModelsConfig } = require('~/server/controllers/ModelController');const { filterFilesByAgentAccess } = require('~/server/services/Files/permissions');const { resolveConfigServers } = require('~/server/services/MCP');@@ -585,6 +588,9 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {* request instead of issuing its own read. */const resolveWebSearchGrant = async () =>(await resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName })).webSearch;+ /** Resolves any agent's `instructionsPrompt` link this run encounters — primary+ * or handoff. No default resolution path, unlike `resolveWebSearchGrant`. */+ const resolveLinkedInstructions = getLinkedInstructionsResolver();const skillsCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.skills);const ephemeralSkillsToggle = request.ephemeralAgent?.skills === true;const accessibleSkillIds = skillsCapabilityEnabled@@ -653,6 +659,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {codeEnvAvailable,fileSearchAvailable,resolveWebSearchGrant,+ resolveLinkedInstructions,backgroundToolsAvailable: enabledCapabilities.has(AgentCapabilities.run_in_background),toolIntentsAvailable: enabledCapabilities.has(AgentCapabilities.tool_intents),statefulSessionsAvailable: enabledCapabilities.has(@@ -737,6 +744,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {codeEnvAvailable,fileSearchAvailable,resolveWebSearchGrant,+ resolveLinkedInstructions,backgroundToolsAvailable: enabledCapabilities.has(AgentCapabilities.run_in_background),toolIntentsAvailable: enabledCapabilities.has(AgentCapabilities.tool_intents),statefulSessionsAvailable: enabledCapabilities.has(diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.jsindex 7daf8478b8..d0a4eeb495 100644--- a/api/server/controllers/agents/responses.js+++ b/api/server/controllers/agents/responses.js@@ -119,6 +119,9 @@ const {} = require('~/server/services/Endpoints/agents/skillDeps');const { createProvisionFilesCallback } = require('~/server/services/Files/provisionCallback');const { checkSessionsAlive, loadCodeApiKey } = require('~/server/services/Files/provision');+const {+ getLinkedInstructionsResolver,+} = require('~/server/services/Endpoints/agents/linkedInstructions');const { getModelsConfig } = require('~/server/controllers/ModelController');const { filterFilesByAgentAccess } = require('~/server/services/Files/permissions');const { resolveConfigServers, getAccessibleMcpServerNames } = require('~/server/services/MCP');@@ -838,6 +841,9 @@ const executeResponse = async (envelope, { req, res }) => {* request instead of issuing its own read. */const resolveWebSearchGrant = async () =>(await resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName })).webSearch;+ /** Resolves any agent's `instructionsPrompt` link this run encounters — primary+ * or handoff. No default resolution path, unlike `resolveWebSearchGrant`. */+ const resolveLinkedInstructions = getLinkedInstructionsResolver();const skillsCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.skills);const ephemeralSkillsToggle = request.ephemeralAgent?.skills === true;const accessibleSkillIds = skillsCapabilityEnabled@@ -906,6 +912,7 @@ const executeResponse = async (envelope, { req, res }) => {codeEnvAvailable,fileSearchAvailable,resolveWebSearchGrant,+ resolveLinkedInstructions,backgroundToolsAvailable: enabledCapabilities.has(AgentCapabilities.run_in_background),toolIntentsAvailable: enabledCapabilities.has(AgentCapabilities.tool_intents),statefulSessionsAvailable: enabledCapabilities.has(@@ -990,6 +997,7 @@ const executeResponse = async (envelope, { req, res }) => {codeEnvAvailable,fileSearchAvailable,resolveWebSearchGrant,+ resolveLinkedInstructions,backgroundToolsAvailable: enabledCapabilities.has(AgentCapabilities.run_in_background),toolIntentsAvailable: enabledCapabilities.has(AgentCapabilities.tool_intents),statefulSessionsAvailable: enabledCapabilities.has(diff --git a/api/server/controllers/agents/resume.js b/api/server/controllers/agents/resume.jsindex 290d3ccea1..19155a606b 100644--- a/api/server/controllers/agents/resume.js+++ b/api/server/controllers/agents/resume.js@@ -1957,6 +1957,10 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle)foregroundRunId: mcpRequestBody.messageId,requestBody: mcpRequestBody,toolTimingReplayEvents: resumeState?.replayEvents,+ // This turn's generation was already counted when it first ran; resuming+ // replays it rather than repeating it, so linked-prompt usage is not+ // recorded again. Resolution itself still runs, cache-first.+ isResume: true,});client = result.client;diff --git a/api/server/controllers/agents/v1.js b/api/server/controllers/agents/v1.jsindex e2a246529c..5aad55ad35 100644--- a/api/server/controllers/agents/v1.js+++ b/api/server/controllers/agents/v1.js@@ -49,6 +49,9 @@ const {marketplaceMineFilter,resolveMarketplaceListQuery,mapMarketplaceListError,+ checkInstructionsPromptWrite,+ applyInstructionsPromptUnset,+ instructionsContentForScan,} = require('@librechat/api');const {Time,@@ -91,6 +94,7 @@ const {} = require('~/server/services/MCP');const { hasCapability } = require('~/server/middleware/roles/capabilities');const { attachOwnerContacts } = require('~/server/services/Agents/ownerContact');+const { instructionsPromptAccess } = require('~/server/services/Agents/instructionsPrompt');const { getMCPServersRegistry } = require('~/config');const { getLogStores } = require('~/cache');const db = require('~/models');@@ -774,7 +778,13 @@ const createAgentHandler = async (req, res) => {});}- if (await blockFilteredAgentContent(req, res, agentData)) {+ if (+ await blockFilteredAgentContent(+ req,+ res,+ instructionsContentForScan('create', { data: agentData }),+ )+ ) {return;}@@ -822,6 +832,20 @@ const createAgentHandler = async (req, res) => {return res.status(subagentReferenceError.status).json(subagentReferenceError.body);}+ const instructionsPromptError = await checkInstructionsPromptWrite({+ access: instructionsPromptAccess,+ operation: 'create',+ user: req.user,+ previous: undefined,+ next: agentData.instructionsPrompt,+ filters: req.config?.filters,+ logger,+ req,+ });+ if (instructionsPromptError) {+ return res.status(instructionsPromptError.status).json(instructionsPromptError.body);+ }+agentData.author = userId;agentData.tools = [];@@ -976,7 +1000,11 @@ const getAgentHandler = async (req, res, expandProperties = false) => {}// EDIT permission: Full agent details including sensitive configuration- return res.status(200).json(agent);+ const presentedAgent = await instructionsPromptAccess.presentForEditor({+ user: req.user,+ agent,+ });+ return res.status(200).json(presentedAgent);} catch (error) {logger.error('[/Agents/:id] Error retrieving agent', error);res.status(500).json({ error: error.message });@@ -996,13 +1024,25 @@ const getAgentHandler = async (req, res, expandProperties = false) => {const getAgentVersionsHandler = async (req, res) => {try {const id = req.params.id;- const versions = await db.getAgentVersions({ id });+ // Independent reads: the version history and the agent's own current link (used+ // only to flag a redacted version as `matchesCurrent`, never to render it).+ const [versions, currentAgent] = await Promise.all([+ db.getAgentVersions({ id }),+ db.getAgent({ id }, { instructionsPrompt: 1, _id: 0 }),+ ]);if (versions == null) {return res.status(404).json({ error: 'Agent not found' });}- return res.status(200).json(versions);+ // Each snapshot carries its own independently-authorized instructionsPrompt link.+ const presentedVersions = await instructionsPromptAccess.presentVersionsForEditor({+ user: req.user,+ versions,+ currentLink: currentAgent?.instructionsPrompt ?? null,+ });++ return res.status(200).json(presentedVersions);} catch (error) {logger.error('[/Agents/:id/versions] Error retrieving agent versions', error);res.status(500).json({ error: error.message });@@ -1032,6 +1072,8 @@ const updateAgentHandler = async (req, res) => {avatar: avatarField,code_environment_id: codeEnvironmentIdField,git_identity: gitIdentityField,+ // Preserve explicit `null` (link removal); `removeNullishValues` would drop it.+ instructionsPrompt: instructionsPromptField,_id,...rest} = validatedData;@@ -1042,6 +1084,9 @@ const updateAgentHandler = async (req, res) => {if (gitIdentityField !== undefined) {updateData.git_identity = gitIdentityField;}+ if (instructionsPromptField !== undefined) {+ updateData.instructionsPrompt = instructionsPromptField;+ }let existingAgent;const includesStatefulConfiguration =@@ -1192,6 +1237,20 @@ const updateAgentHandler = async (req, res) => {return res.status(404).json({ error: 'Agent not found' });}+ const instructionsPromptError = await checkInstructionsPromptWrite({+ access: instructionsPromptAccess,+ operation: 'update',+ user: req.user,+ previous: existingAgent.instructionsPrompt,+ next: instructionsPromptField,+ filters: req.config?.filters,+ logger,+ req,+ });+ if (instructionsPromptError) {+ return res.status(instructionsPromptError.status).json(instructionsPromptError.body);+ }+// Convert legacy OCR tool resource to context format in existing agentconst ocrConversion = mergeAgentOcrConversion(existingAgent, updateData);if (ocrConversion.tool_resources) {@@ -1210,7 +1269,17 @@ const updateAgentHandler = async (req, res) => {});}- if (await blockFilteredAgentContent(req, res, updateData)) {+ if (+ await blockFilteredAgentContent(+ req,+ res,+ instructionsContentForScan('update', {+ data: updateData,+ existing: existingAgent,+ nextLink: instructionsPromptField,+ }),+ )+ ) {return;}@@ -1312,6 +1381,7 @@ const updateAgentHandler = async (req, res) => {delete updateData.git_identity;updateData.$unset = { ...updateData.$unset, git_identity: 1 };}+ updateData = applyInstructionsPromptUnset(updateData);let updatedAgent =Object.keys(updateData).length > 0@@ -1333,7 +1403,13 @@ const updateAgentHandler = async (req, res) => {delete updatedAgent.author;}- return res.json(updatedAgent);+ // Same EDIT-scoped restricted-stub treatment as the GET handler.+ const presentedAgent = await instructionsPromptAccess.presentForEditor({+ user: req.user,+ agent: updatedAgent,+ });++ return res.json(presentedAgent);} catch (error) {if (error instanceof z.ZodError) {logger.error('[/Agents/:id] Validation error', error.errors);@@ -1375,6 +1451,8 @@ const duplicateAgentHandler = async (req, res) => {});}+ // The duplicate carries the source agent's link verbatim: no ACL VIEW, PROMPTS+ // USE, or resolvability check.const {id: _id,_id: __id,@@ -1539,7 +1617,11 @@ const duplicateAgentHandler = async (req, res) => {}if (- (await blockFilteredAgentContent(req, res, newAgentData)) ||+ (await blockFilteredAgentContent(+ req,+ res,+ instructionsContentForScan('duplicate', { data: newAgentData }),+ )) ||blockFilteredActionContent(req, res, sanitizedActions)) {return;@@ -1621,8 +1703,14 @@ const duplicateAgentHandler = async (req, res) => {);}- return res.status(201).json({+ // The link copies verbatim; same EDIT-scoped restricted-stub treatment as GET and update.+ const presentedAgent = await instructionsPromptAccess.presentForEditor({+ user: req.user,agent: newAgent,+ });++ return res.status(201).json({+ agent: presentedAgent,actions: newActionsList,});} catch (error) {@@ -1918,7 +2006,13 @@ const uploadAgentAvatarHandler = async (req, res) => {logger.error('[/:agent_id/avatar] Error invalidating avatar refresh cache', cacheErr);}- res.status(201).json(updatedAgent);+ // Same EDIT-scoped restricted-stub treatment as the other write handlers.+ const presentedAgent = await instructionsPromptAccess.presentForEditor({+ user: req.user,+ agent: updatedAgent,+ });++ res.status(201).json(presentedAgent);} catch (error) {const message = 'An error occurred while updating the Agent Avatar';logger.error(@@ -1952,6 +2046,7 @@ const uploadAgentAvatarHandler = async (req, res) => {* @throws {Error} 400 - If version_index is missing* @throws {Error} 403 - If user doesn't have permission to modify the agent* @throws {Error} 404 - If agent not found+ * @throws {Error} 404 - If version not found* @throws {Error} 500 - If there's an internal server error during the reversion process*/const revertAgentVersionHandler = async (req, res) => {@@ -1970,15 +2065,17 @@ const revertAgentVersionHandler = async (req, res) => {}const revertVersion = existingAgent.versions?.[version_index];- if (!validateAgentCodeEnvironmentAllowlist(req, res, revertVersion?.code_environment_ids)) {+ if (!revertVersion) {+ return res.status(404).json({ error: `Version ${version_index} not found` });+ }+ if (!validateAgentCodeEnvironmentAllowlist(req, res, revertVersion.code_environment_ids)) {return;}- const restoredWorkspaceConfiguration = revertVersion- ? resolveAgentWorkspaceRestoreConfiguration({- version: revertVersion,- current: existingAgent,- })- : undefined;++ const restoredWorkspaceConfiguration = resolveAgentWorkspaceRestoreConfiguration({+ version: revertVersion,+ current: existingAgent,+ });if (isActiveAgentWorkspaceConfiguration(restoredWorkspaceConfiguration) &&!validateStatefulCodeEnvironment(@@ -1993,7 +2090,7 @@ const revertAgentVersionHandler = async (req, res) => {) {return;}- const storedRevertEdges = Array.isArray(revertVersion?.edges) ? revertVersion.edges : [];+ const storedRevertEdges = Array.isArray(revertVersion.edges) ? revertVersion.edges : [];const revertEdges = replaceEdgeSourceId(storedRevertEdges, '', id);const hasLegacyEdgeSource = storedRevertEdges.some((edge) =>Array.isArray(edge.from) ? edge.from.includes('') : edge.from === '',@@ -2018,14 +2115,14 @@ const revertAgentVersionHandler = async (req, res) => {}}- const subagentReferenceError = await getSubagentReferenceError(revertVersion?.subagents, req);+ const subagentReferenceError = await getSubagentReferenceError(revertVersion.subagents, req);if (subagentReferenceError) {return res.status(subagentReferenceError.status).json(subagentReferenceError.body);}// Permissions are enforced via route middleware (ACL EDIT)- const actionIds = (revertVersion?.actions ?? [])+ const actionIds = (revertVersion.actions ?? []).map((action) => (typeof action === 'string' ? action.split(actionDelimiter)[1] : undefined)).filter(Boolean);const actions =@@ -2034,7 +2131,11 @@ const revertAgentVersionHandler = async (req, res) => {: [];if (- (await blockFilteredAgentContent(req, res, revertVersion)) ||+ (await blockFilteredAgentContent(+ req,+ res,+ instructionsContentForScan('revert', { data: revertVersion, existing: existingAgent }),+ )) ||blockFilteredActionContent(req, res, actions)) {return;@@ -2043,8 +2144,8 @@ const revertAgentVersionHandler = async (req, res) => {let updatedAgent = await db.revertAgentVersion({ id }, version_index);const revertUpdates = {};if (- revertVersion &&- (hasLegacyEdgeSource || (!Array.isArray(revertVersion.edges) && updatedAgent.edges?.length))+ hasLegacyEdgeSource ||+ (!Array.isArray(revertVersion.edges) && updatedAgent.edges?.length)) {revertUpdates.edges = revertEdges;}@@ -2112,7 +2213,13 @@ const revertAgentVersionHandler = async (req, res) => {delete updatedAgent.author;}- return res.json(updatedAgent);+ // Same EDIT-scoped restricted-stub treatment as GET and update.+ const presentedAgent = await instructionsPromptAccess.presentForEditor({+ user: req.user,+ agent: updatedAgent,+ });++ return res.json(presentedAgent);} catch (error) {logger.error('[/agents/:id/revert] Error reverting Agent version', error);if (error?.statusCode === 409) {diff --git a/api/server/controllers/agents/v1.spec.js b/api/server/controllers/agents/v1.spec.jsindex effe06002f..68824ce624 100644--- a/api/server/controllers/agents/v1.spec.js+++ b/api/server/controllers/agents/v1.spec.js@@ -1,3 +1,6 @@+const fs = require('fs');+const os = require('os');+const path = require('path');const mongoose = require('mongoose');const express = require('express');const request = require('supertest');@@ -20,6 +23,7 @@ const {PrincipalType,ResourceType,actionDelimiter,+ InstructionsPromptErrorCode,} = require('librechat-data-provider');const { MongoMemoryServer } = require('mongodb-memory-server');@@ -97,6 +101,7 @@ const {revertAgentVersion: revertAgentVersionHandler,updateAgent: updateAgentHandler,getListAgents: getListAgentsHandler,+ uploadAgentAvatar: uploadAgentAvatarHandler,} = require('./v1');const {@@ -117,6 +122,8 @@ const {} = require('@librechat/api');const { grantPermission } = require('~/server/services/PermissionService');const { hasCapability } = require('~/server/middleware/roles/capabilities');+const { getStrategyFunctions } = require('~/server/services/Files/strategies');+const { resizeAvatar } = require('~/server/services/Files/images/avatar');const db = require('~/models');/**@@ -5394,4 +5401,2106 @@ describe('Agent Controllers - Mass Assignment Protection', () => {expect(persisted.name).toBe('Current Router');});});++ describe('instructionsPrompt access control', () => {+ /** Grants PROMPTGROUP VIEW for every id in `visibleGroupIds`; every other id (and+ * every other resource type) resolves with no permission, matching the file's+ * default `getResourcePermissionsMap` behavior. */+ const mockGroupVisibility = (visibleGroupIds) => {+ getResourcePermissionsMap.mockImplementation(async ({ resourceIds }) => {+ const map = new Map();+ for (const id of resourceIds) {+ if (visibleGroupIds.has(id.toString())) {+ map.set(id.toString(), PermissionBits.VIEW);+ }+ }+ return map;+ });+ };++ const createPromptGroupFixture = async (name = 'Fixture Group') => {+ const { group, prompt } = await db.createPromptGroup({+ prompt: { prompt: 'You are a helpful assistant.', type: 'text' },+ group: { name },+ author: mockReq.user.id,+ authorName: 'Fixture Author',+ });+ return { groupId: group._id.toString(), promptId: prompt._id.toString() };+ };++ afterEach(() => {+ getResourcePermissionsMap.mockReset().mockResolvedValue(new Map());+ });++ describe('prompt-management capability', () => {+ test.each(['ADMIN', 'PROMPT_MANAGER_TEST'])(+ 'allows %s to link, revise, and view prompts without group ACLs',+ async (role) => {+ mockReq.user.role = role;+ mockReq.user.idOnTheSource = null;+ await db.grantCapability({+ principalType: PrincipalType.ROLE,+ principalId: role,+ capability: SystemCapabilities.MANAGE_PROMPTS,+ });+ if (role !== 'ADMIN') {+ await mongoose.models.Role.findOneAndUpdate(+ { name: role },+ { $set: { [`permissions.${PermissionTypes.PROMPTS}.${Permissions.USE}`]: true } },+ { upsert: true },+ );+ }+ const { groupId, promptId } = await createPromptGroupFixture();+ const productionLink = { source: 'native', groupId, selection: { type: 'production' } };+ mockReq.body = {+ name: 'Manager Linked Agent',+ provider: 'openai',+ model: 'gpt-4',+ instructionsPrompt: productionLink,+ };+ await createAgentHandler(mockReq, mockRes);+ expect(mockRes.status).toHaveBeenCalledWith(201);+ const created = mockRes.json.mock.calls[0][0];+ expect(created.instructionsPrompt).toEqual(productionLink);+ mockRes.json.mockClear();+ mockRes.status.mockClear();+ mockReq.params = { id: created.id };+ const exactLink = { source: 'native', groupId, selection: { type: 'exact', promptId } };+ mockReq.body = { instructionsPrompt: exactLink };+ await updateAgentHandler(mockReq, mockRes);+ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ const updated = mockRes.json.mock.calls[0][0];+ expect(updated.instructionsPrompt).toEqual(exactLink);+ expect(+ updated.versions.every((version) => version.instructionsPrompt?.restricted !== true),+ ).toBe(true);+ mockRes.json.mockClear();+ await getAgentVersionsHandler(mockReq, mockRes);+ const versions = mockRes.json.mock.calls[0][0];+ expect(versions.some((version) => version.instructionsPrompt?.groupId === groupId)).toBe(+ true,+ );+ expect(versions.every((version) => version.instructionsPrompt?.restricted !== true)).toBe(+ true,+ );+ expect(getResourcePermissionsMap).not.toHaveBeenCalled();+ },+ );+ });++ describe('createAgentHandler', () => {+ test('persists the agent when the linked prompt group is viewable', async () => {+ const { groupId } = await createPromptGroupFixture();+ mockGroupVisibility(new Set([groupId]));+ const instructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ };++ mockReq.body = {+ name: 'Prompt-Linked Agent',+ provider: 'openai',+ model: 'gpt-4',+ instructionsPrompt,+ };++ await createAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(201);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.instructionsPrompt).toEqual(instructionsPrompt);+ const persisted = await Agent.findOne({ id: response.id }).lean();+ expect(persisted.instructionsPrompt).toEqual(instructionsPrompt);+ });++ test('returns 403 instructions_prompt_forbidden for a group the creator cannot VIEW', async () => {+ const groupId = new mongoose.Types.ObjectId().toString();+ mockReq.body = {+ name: 'Attacker Prompt Agent',+ provider: 'openai',+ model: 'gpt-4',+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ };++ await createAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(403);+ expect(mockRes.json).toHaveBeenCalledWith({+ error: expect.any(String),+ code: InstructionsPromptErrorCode.FORBIDDEN,+ });+ expect(await Agent.countDocuments()).toBe(0);+ });++ test('returns 400 instructions_prompt_unavailable for a selection that does not resolve', async () => {+ const groupId = new mongoose.Types.ObjectId().toString();+ mockGroupVisibility(new Set([groupId]));+ mockReq.body = {+ name: 'Dangling Prompt Agent',+ provider: 'openai',+ model: 'gpt-4',+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ };++ await createAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(400);+ expect(mockRes.json).toHaveBeenCalledWith({+ error: expect.any(String),+ code: InstructionsPromptErrorCode.UNAVAILABLE,+ });+ expect(await Agent.countDocuments()).toBe(0);+ });++ test('returns 400 instructions_prompt_unavailable when the linked content violates the agent-instructions content policy (but not the prompts policy)', async () => {+ const { group } = await db.createPromptGroup({+ prompt: { prompt: 'Use sk-private-token for requests', type: 'text' },+ group: { name: 'Sensitive Content Group' },+ author: mockReq.user.id,+ authorName: 'Fixture Author',+ });+ const groupId = group._id.toString();+ mockGroupVisibility(new Set([groupId]));+ // Only the agent-instructions policy is active; the prompts-library policy is+ // not, so `resolvePrompt` itself must succeed before this gate applies.+ mockReq.config = {+ filters: {+ agentInstructions: {+ pii: {+ starterPatterns: ['sk_prefix'],+ },+ },+ },+ };+ mockReq.body = {+ name: 'Blocked Prompt Agent',+ provider: 'openai',+ model: 'gpt-4',+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ };++ await createAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(400);+ expect(mockRes.json).toHaveBeenCalledWith({+ error: expect.any(String),+ code: InstructionsPromptErrorCode.UNAVAILABLE,+ });+ expect(await Agent.countDocuments()).toBe(0);+ });++ test('excludes the submitted (now-dead) inline instructions from the save-time scan when a safe link is set', async () => {+ const { groupId } = await createPromptGroupFixture('Create Scan Safe Group');+ mockGroupVisibility(new Set([groupId]));+ mockReq.config = {+ filters: { agentInstructions: { pii: { starterPatterns: ['sk_prefix'] } } },+ };+ mockReq.body = {+ name: 'Linked At Creation',+ provider: 'openai',+ model: 'gpt-4',+ instructions: 'Use sk-private-token for requests',+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ };++ await createAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(201);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.instructionsPrompt.groupId).toBe(groupId);+ });+ });++ describe('updateAgentHandler', () => {+ test('preserves a link the editor cannot VIEW when the edit is unrelated', async () => {+ const { groupId } = await createPromptGroupFixture();+ const instructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ };+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Renamable Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt,+ });+ // No VIEW grant for `groupId`: the editor cannot see the linked group.++ mockReq.params = { id: agent.id };+ mockReq.body = { name: 'Renamed Agent' };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.name).toBe('Renamed Agent');+ expect(persisted.instructionsPrompt).toEqual(instructionsPrompt);+ });++ test("changes to a new link the editor can VIEW, regardless of the previous link's visibility", async () => {+ const { groupId: restrictedGroupId } = await createPromptGroupFixture('Restricted Group');+ const { groupId: nextGroupId } = await createPromptGroupFixture('Next Group');+ mockGroupVisibility(new Set([nextGroupId]));+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Restricted Link Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId: restrictedGroupId,+ selection: { type: 'production' },+ },+ });++ mockReq.params = { id: agent.id };+ mockReq.body = {+ instructionsPrompt: {+ source: 'native',+ groupId: nextGroupId,+ selection: { type: 'production' },+ },+ };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.instructionsPrompt.groupId).toBe(nextGroupId);+ });++ test('removes the link (via $unset) when the update sets it to null', async () => {+ const { groupId } = await createPromptGroupFixture();+ mockGroupVisibility(new Set([groupId]));+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Removable Link Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ });++ mockReq.params = { id: agent.id };+ mockReq.body = { instructionsPrompt: null };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.instructionsPrompt).toBeUndefined();+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.instructionsPrompt).toBeUndefined();+ });++ test('removes the link (via $unset) when the update sets it to null, even without VIEW', async () => {+ const { groupId } = await createPromptGroupFixture();+ mockGroupVisibility(new Set());+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Removable Link Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ });++ mockReq.params = { id: agent.id };+ mockReq.body = { instructionsPrompt: null };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.instructionsPrompt).toBeUndefined();+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.instructionsPrompt).toBeUndefined();+ });++ test('returns 400 instructions_prompt_unavailable for a selection that does not resolve', async () => {+ const groupId = new mongoose.Types.ObjectId().toString();+ mockGroupVisibility(new Set([groupId]));+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'No Link Yet Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ });++ mockReq.params = { id: agent.id };+ mockReq.body = {+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(400);+ expect(mockRes.json).toHaveBeenCalledWith({+ error: expect.any(String),+ code: InstructionsPromptErrorCode.UNAVAILABLE,+ });+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.instructionsPrompt).toBeUndefined();+ });++ describe('a linked group that has been deleted', () => {+ test('allows the owner to remove a link to a deleted group (update null) even without VIEW', async () => {+ const { groupId } = await createPromptGroupFixture('Doomed Group');+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Agent With Deleted Link',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ });+ // The group is deleted (its ACL entries go with it): the owner no+ // longer has VIEW on it. `mockGroupVisibility` is never called with+ // `groupId`, so it stays out of visibility either way.+ await db.deletePromptGroup({ _id: groupId });++ mockReq.params = { id: agent.id };+ mockReq.body = { instructionsPrompt: null };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.instructionsPrompt).toBeUndefined();+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.instructionsPrompt).toBeUndefined();+ });++ test('allows the owner to replace a link to a deleted group with an accessible one', async () => {+ const { groupId: deletedGroupId } = await createPromptGroupFixture('Doomed Group 2');+ const { groupId: nextGroupId } = await createPromptGroupFixture('Replacement Group');+ mockGroupVisibility(new Set([nextGroupId]));+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Agent With Deleted Link',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId: deletedGroupId,+ selection: { type: 'production' },+ },+ });+ await db.deletePromptGroup({ _id: deletedGroupId });++ mockReq.params = { id: agent.id };+ mockReq.body = {+ instructionsPrompt: {+ source: 'native',+ groupId: nextGroupId,+ selection: { type: 'production' },+ },+ };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.instructionsPrompt.groupId).toBe(nextGroupId);+ });+ });++ test('redacts an inaccessible link inside versions[] in the PATCH response, without touching the persisted snapshot', async () => {+ const { groupId: restrictedGroupId } = await createPromptGroupFixture(+ 'Restricted History Group',+ );+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Agent With History',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ versions: [+ {+ name: 'Old Linked Name',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId: restrictedGroupId,+ selection: { type: 'production' },+ },+ },+ ],+ });+ // No VIEW grant for `restrictedGroupId`.++ mockReq.params = { id: agent.id };+ mockReq.body = { name: 'Agent With History Renamed' };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ const response = mockRes.json.mock.calls[0][0];+ // The agent carries no current link at all, so the redacted snapshot's link+ // cannot match it.+ expect(response.versions[0].instructionsPrompt).toEqual({+ source: 'native',+ restricted: true,+ matchesCurrent: false,+ });+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.versions[0].instructionsPrompt.groupId).toBe(restrictedGroupId);+ });++ test('keeps a viewable link inside versions[] intact in the PATCH response', async () => {+ const { groupId } = await createPromptGroupFixture('Visible History Group');+ mockGroupVisibility(new Set([groupId]));+ const versionInstructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ };+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Agent With Visible History',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ versions: [+ {+ name: 'Old Linked Name',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: versionInstructionsPrompt,+ },+ ],+ });++ mockReq.params = { id: agent.id };+ mockReq.body = { name: 'Agent With Visible History Renamed' };++ await updateAgentHandler(mockReq, mockRes);++ const response = mockRes.json.mock.calls[0][0];+ expect(response.versions[0].instructionsPrompt).toEqual(versionInstructionsPrompt);+ });++ describe('save-time content scan when a link governs the agent', () => {+ const blockedInstructions = 'Use sk-private-token for requests';+ const blockedFilters = {+ agentInstructions: { pii: { starterPatterns: ['sk_prefix'] } },+ };++ test('excludes the stored (now-dead) inline instructions from the scan when switching to a safe link', async () => {+ const { groupId } = await createPromptGroupFixture('Scan Safe Group');+ mockGroupVisibility(new Set([groupId]));+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Switching Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructions: blockedInstructions,+ });++ mockReq.config = { filters: blockedFilters };+ mockReq.params = { id: agent.id };+ mockReq.body = {+ instructions: blockedInstructions,+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.instructionsPrompt.groupId).toBe(groupId);+ // The inline text is stored as submitted; only the scan ignored it.+ expect(persisted.instructions).toBe(blockedInstructions);+ });++ test('still rejects switching back to Inline while the stored inline text is blocked', async () => {+ const { groupId } = await createPromptGroupFixture('Scan Safe Group Two');+ mockGroupVisibility(new Set([groupId]));+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Switching Back Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructions: blockedInstructions,+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ });++ mockReq.config = { filters: blockedFilters };+ mockReq.params = { id: agent.id };+ mockReq.body = { instructions: blockedInstructions, instructionsPrompt: null };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(400);+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.instructionsPrompt.groupId).toBe(groupId);+ expect(persisted.instructions).toBe(blockedInstructions);+ });++ test('still rejects blocked inline text on an agent with no link at all', async () => {+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Unlinked Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ });++ mockReq.config = { filters: blockedFilters };+ mockReq.params = { id: agent.id };+ mockReq.body = { instructions: blockedInstructions };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(400);+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.instructions).toBeUndefined();+ });++ test('allows a safe partial edit of an unlinked agent even when its stored instructions would fail content policy (regression guard)', async () => {+ // An agent that was never linked has no `previous` link to remove, so an+ // unrelated edit must scan only what the payload sends — never fall back+ // to stored `instructions` the write doesn't touch. Mirrors+ // e2e/specs/mock/content-filters.persisted.spec.ts's "safe partial edits+ // work" scenario.+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Unlinked Agent With Stored Blocked Text',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructions: blockedInstructions,+ });++ mockReq.config = { filters: blockedFilters };+ mockReq.params = { id: agent.id };+ mockReq.body = { name: 'Renamed Unlinked Agent' };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.name).toBe('Renamed Unlinked Agent');+ expect(persisted.instructions).toBe(blockedInstructions);+ });++ test('rejects removing a link over stored disallowed inline text the update never resends', async () => {+ const { groupId } = await createPromptGroupFixture('Removal Scan Blocked Group');+ mockGroupVisibility(new Set([groupId]));+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Linked With Dead Text',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructions: blockedInstructions,+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ });++ mockReq.config = { filters: blockedFilters };+ mockReq.params = { id: agent.id };+ // Only the link is touched; `instructions` is not resent, so the stored+ // text — never scanned while the link stayed valid — must fall in.+ mockReq.body = { instructionsPrompt: null };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(400);+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ // The write never applied: the link and stored text are untouched.+ expect(persisted.instructionsPrompt.groupId).toBe(groupId);+ expect(persisted.instructions).toBe(blockedInstructions);+ });++ test('allows removing a link over stored allowed inline text', async () => {+ const { groupId } = await createPromptGroupFixture('Removal Scan Allowed Group');+ mockGroupVisibility(new Set([groupId]));+ const allowedInstructions = 'Be helpful and concise.';+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Linked With Allowed Text',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructions: allowedInstructions,+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ });++ mockReq.config = { filters: blockedFilters };+ mockReq.params = { id: agent.id };+ mockReq.body = { instructionsPrompt: null };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.instructionsPrompt).toBeUndefined();+ expect(persisted.instructions).toBe(allowedInstructions);+ });++ test('allows removing a link while sending new allowed instructions over stored disallowed text', async () => {+ const { groupId } = await createPromptGroupFixture('Removal Scan Replace Group');+ mockGroupVisibility(new Set([groupId]));+ const newInstructions = 'Be helpful and concise.';+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Linked, Replacing Dead Text',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructions: blockedInstructions,+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ });++ mockReq.config = { filters: blockedFilters };+ mockReq.params = { id: agent.id };+ mockReq.body = { instructions: newInstructions, instructionsPrompt: null };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.instructionsPrompt).toBeUndefined();+ expect(persisted.instructions).toBe(newInstructions);+ });+ });+ });++ describe('getAgentHandler', () => {+ test('EDIT branch presents a restricted stub for a link the editor cannot VIEW', async () => {+ const { groupId } = await createPromptGroupFixture();+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Restricted View Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ });+ // No VIEW grant for `groupId`.++ mockReq.params = { id: agent.id };++ await getAgentHandler(mockReq, mockRes, true);++ expect(mockRes.status).toHaveBeenCalledWith(200);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.instructionsPrompt).toEqual({ source: 'native', restricted: true });+ });++ test('EDIT branch keeps a visible link intact', async () => {+ const { groupId } = await createPromptGroupFixture();+ mockGroupVisibility(new Set([groupId]));+ const instructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ };+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Visible Link Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt,+ });++ mockReq.params = { id: agent.id };++ await getAgentHandler(mockReq, mockRes, true);++ const response = mockRes.json.mock.calls[0][0];+ expect(response.instructionsPrompt).toEqual(instructionsPrompt);+ });++ test('VIEW-only branch never includes instructionsPrompt', async () => {+ const { groupId } = await createPromptGroupFixture();+ mockGroupVisibility(new Set([groupId]));+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'View Only Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ });++ mockReq.params = { id: agent.id };++ await getAgentHandler(mockReq, mockRes);++ const response = mockRes.json.mock.calls[0][0];+ expect(response).not.toHaveProperty('instructionsPrompt');+ });+ });++ describe('duplicateAgentHandler', () => {+ test('copies the link verbatim, with no extra ACL check on the write', async () => {+ const { groupId } = await createPromptGroupFixture();+ // No VIEW grant: duplication must succeed regardless.+ const instructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ };+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Source Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt,+ });++ mockReq.params = { id: agent.id };++ await duplicateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(201);+ const newAgentId = mockRes.json.mock.calls[0][0].agent.id;+ const persisted = await Agent.findOne({ id: newAgentId }).lean();+ expect(persisted.instructionsPrompt).toEqual(instructionsPrompt);+ });++ test("presents a restricted stub in the response when the duplicator can't VIEW the group", async () => {+ const { groupId } = await createPromptGroupFixture();+ const instructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ };+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Source Agent Two',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt,+ });++ mockReq.params = { id: agent.id };++ await duplicateAgentHandler(mockReq, mockRes);++ const response = mockRes.json.mock.calls[0][0];+ expect(response.agent.instructionsPrompt).toEqual({ source: 'native', restricted: true });+ const newAgentId = response.agent.id;+ const persisted = await Agent.findOne({ id: newAgentId }).lean();+ expect(persisted.instructionsPrompt).toEqual(instructionsPrompt);+ });++ test('fails closed (201 with a restricted stub, never a 500) when the post-duplicate ACL lookup fails, and creates exactly one duplicate', async () => {+ const { groupId } = await createPromptGroupFixture();+ const instructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ };+ await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Source Agent Three',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt,+ });+ expect(await Agent.countDocuments({})).toBe(1);++ // The duplicate has already been persisted (with its cloned actions and+ // grants) by the time `presentForEditor` runs; a failure here must not+ // surface as a 500 — a client retry on that 500 would create another+ // duplicate against a write that already succeeded.+ getResourcePermissionsMap.mockImplementation(async () => {+ throw new Error('acl outage');+ });++ mockReq.params = { id: (await Agent.findOne({ name: 'Source Agent Three' })).id };++ await duplicateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(201);+ expect(mockRes.status).not.toHaveBeenCalledWith(500);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.agent.instructionsPrompt).toEqual({ source: 'native', restricted: true });+ expect(await Agent.countDocuments({})).toBe(2);+ });++ describe('save-time content scan when a link governs the source agent', () => {+ const blockedInstructions = 'Use sk-private-token for requests';+ const blockedFilters = {+ agentInstructions: { pii: { starterPatterns: ['sk_prefix'] } },+ };++ test('excludes the copied (dead) inline instructions from the scan when the source is linked', async () => {+ const { groupId } = await createPromptGroupFixture('Duplicate Scan Safe Group');+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Linked Source With Dead Text',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructions: blockedInstructions,+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ });++ mockReq.config = { filters: blockedFilters };+ mockReq.params = { id: agent.id };++ await duplicateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(201);+ const newAgentId = mockRes.json.mock.calls[0][0].agent.id;+ const persisted = await Agent.findOne({ id: newAgentId }).lean();+ expect(persisted.instructionsPrompt.groupId).toBe(groupId);+ expect(persisted.instructions).toBe(blockedInstructions);+ });++ test('still rejects duplicating an unlinked agent whose inline text is blocked', async () => {+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Unlinked Source With Blocked Text',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructions: blockedInstructions,+ });++ mockReq.config = { filters: blockedFilters };+ mockReq.params = { id: agent.id };++ await duplicateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(400);+ expect(await Agent.countDocuments({})).toBe(1);+ });+ });++ describe('no PROMPTS USE or VIEW check on a duplicate', () => {+ /** `getRoleByName` auto-creates a missing system role from defaults (which+ * grant PROMPTS USE), so a role document must already exist to override it.+ * Reset after each test so later tests see the auto-created default again. */+ const setPromptsUse = (allowed) =>+ mongoose.models.Role.findOneAndUpdate(+ { name: 'USER' },+ {+ $set: {+ name: 'USER',+ [`permissions.${PermissionTypes.PROMPTS}.${Permissions.USE}`]: allowed,+ },+ },+ { upsert: true },+ );++ afterEach(async () => {+ await mongoose.models.Role.deleteMany({ name: 'USER' });+ });++ test('copies the link when the duplicator lacks PROMPTS USE', async () => {+ const { groupId } = await createPromptGroupFixture('Duplicate Gate Group');+ const instructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ };+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Source Agent For Gated Duplicate',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt,+ });+ await setPromptsUse(false);++ mockReq.params = { id: agent.id };++ await duplicateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(201);+ const newAgentId = mockRes.json.mock.calls[0][0].agent.id;+ const persisted = await Agent.findOne({ id: newAgentId }).lean();+ expect(persisted.instructionsPrompt).toEqual(instructionsPrompt);+ });++ test('allows duplicating an unlinked agent without PROMPTS USE', async () => {+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Unlinked Source For Gated Duplicate',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ });+ await setPromptsUse(false);++ mockReq.params = { id: agent.id };++ await duplicateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(201);+ expect(await Agent.countDocuments({})).toBe(2);+ });++ test('presents a restricted stub (201) when the duplicator has no VIEW on the group', async () => {+ const { groupId } = await createPromptGroupFixture('Duplicate Gate Use Only Group');+ const instructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ };+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Source Agent For Use-Only Duplicate',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt,+ });+ // Default role grants PROMPTS USE; no VIEW grant for `groupId`.++ mockReq.params = { id: agent.id };++ await duplicateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(201);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.agent.instructionsPrompt).toEqual({ source: 'native', restricted: true });+ const persisted = await Agent.findOne({ id: response.agent.id }).lean();+ expect(persisted.instructionsPrompt).toEqual(instructionsPrompt);+ });+ });+ });++ describe('revertAgentVersionHandler', () => {+ test('removes the link when reverting to a version that predates it and the editor can VIEW the current link', async () => {+ const { groupId } = await createPromptGroupFixture();+ mockGroupVisibility(new Set([groupId]));+ const agentId = `agent_${nanoid()}`;+ await Agent.create({+ id: agentId,+ author: mockReq.user.id,+ name: 'Current Prompt-Linked Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ versions: [+ {+ name: 'Pre-Link Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ },+ ],+ });++ mockReq.params = { id: agentId };+ mockReq.body = { version_index: 0 };++ await revertAgentVersionHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.name).toBe('Pre-Link Agent');+ expect(response.instructionsPrompt).toBeUndefined();+ const persisted = await Agent.findOne({ id: agentId }).lean();+ expect(persisted.instructionsPrompt).toBeUndefined();+ });++ test('returns 404 for an out-of-range version_index on a linked agent instead of a 500', async () => {+ const { groupId } = await createPromptGroupFixture();+ const agentId = `agent_${nanoid()}`;+ await Agent.create({+ id: agentId,+ author: mockReq.user.id,+ name: 'Current Prompt-Linked Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ versions: [+ {+ name: 'Pre-Link Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ },+ ],+ });++ mockReq.params = { id: agentId };+ mockReq.body = { version_index: 99 };++ await revertAgentVersionHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(404);+ expect(mockRes.json).toHaveBeenCalledWith({ error: 'Version 99 not found' });+ const persisted = await Agent.findOne({ id: agentId }).lean();+ expect(persisted.instructionsPrompt).toEqual({+ source: 'native',+ groupId,+ selection: { type: 'production' },+ });+ });++ test('removes the current link via revert even though the editor cannot VIEW it (no VIEW check on a revert)', async () => {+ const { groupId } = await createPromptGroupFixture();+ // No VIEW grant for `groupId`: the editor cannot see the currently linked group.+ const agentId = `agent_${nanoid()}`;+ await Agent.create({+ id: agentId,+ author: mockReq.user.id,+ name: 'Current Prompt-Linked Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ versions: [+ {+ name: 'Pre-Link Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ },+ ],+ });++ mockReq.params = { id: agentId };+ mockReq.body = { version_index: 0 };++ await revertAgentVersionHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ const persisted = await Agent.findOne({ id: agentId }).lean();+ expect(persisted.name).toBe('Pre-Link Agent');+ expect(persisted.instructionsPrompt).toBeUndefined();+ });++ test('sets a snapshot link to a group the editor cannot VIEW via revert, with no VIEW or USE check', async () => {+ const { groupId } = await createPromptGroupFixture();+ // No VIEW grant for `groupId`, and no PROMPTS USE check runs for a revert either.+ const agentId = `agent_${nanoid()}`;+ await Agent.create({+ id: agentId,+ author: mockReq.user.id,+ name: 'Current Unlinked Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ versions: [+ {+ name: 'Pre-Link Snapshot',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ },+ ],+ });++ mockReq.params = { id: agentId };+ mockReq.body = { version_index: 0 };++ await revertAgentVersionHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.name).toBe('Pre-Link Snapshot');+ // Not visible, so presented as a restricted stub in the response.+ expect(response.instructionsPrompt).toEqual({ source: 'native', restricted: true });+ const persisted = await Agent.findOne({ id: agentId }).lean();+ expect(persisted.instructionsPrompt.groupId).toBe(groupId);+ });++ test('reverts successfully when the snapshot link is accessible, even though it no longer resolves', async () => {+ const groupId = new mongoose.Types.ObjectId().toString();+ mockGroupVisibility(new Set([groupId]));+ // No prompt group document exists for `groupId`: the snapshot's selection cannot+ // resolve. A revert still applies — a stale revision continues without+ // instructions at runtime rather than rejecting the write.+ const agentId = `agent_${nanoid()}`;+ await Agent.create({+ id: agentId,+ author: mockReq.user.id,+ name: 'Current Unlinked Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ versions: [+ {+ name: 'Dangling Snapshot',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ },+ ],+ });++ mockReq.params = { id: agentId };+ mockReq.body = { version_index: 0 };++ await revertAgentVersionHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.name).toBe('Dangling Snapshot');+ expect(response.instructionsPrompt).toEqual({+ source: 'native',+ groupId,+ selection: { type: 'production' },+ });+ const persisted = await Agent.findOne({ id: agentId }).lean();+ expect(persisted.instructionsPrompt.groupId).toBe(groupId);+ });++ test('reverts successfully when the snapshot link equals the current link, even without VIEW', async () => {+ const { groupId } = await createPromptGroupFixture();+ // No VIEW grant for `groupId`, but the snapshot's link is identical to the+ // current one, so this is not a change the access check needs to gate.+ const agentId = `agent_${nanoid()}`;+ const instructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ };+ await Agent.create({+ id: agentId,+ author: mockReq.user.id,+ name: 'Current Prompt-Linked Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt,+ versions: [+ {+ name: 'Same-Link Snapshot',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt,+ },+ ],+ });++ mockReq.params = { id: agentId };+ mockReq.body = { version_index: 0 };++ await revertAgentVersionHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.name).toBe('Same-Link Snapshot');+ // Not visible, so still presented as a restricted stub in the response.+ expect(response.instructionsPrompt).toEqual({ source: 'native', restricted: true });+ const persisted = await Agent.findOne({ id: agentId }).lean();+ expect(persisted.instructionsPrompt).toEqual(instructionsPrompt);+ });++ describe('a linked group that has been deleted', () => {+ test('allows a revert that moves away from a deleted-group link, even without VIEW', async () => {+ const { groupId } = await createPromptGroupFixture('Doomed Current Link');+ const agentId = `agent_${nanoid()}`;+ await Agent.create({+ id: agentId,+ author: mockReq.user.id,+ name: 'Current Deleted-Link Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ versions: [+ {+ name: 'Pre-Link Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ },+ ],+ });+ await db.deletePromptGroup({ _id: groupId });++ mockReq.params = { id: agentId };+ mockReq.body = { version_index: 0 };++ await revertAgentVersionHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.name).toBe('Pre-Link Agent');+ expect(response.instructionsPrompt).toBeUndefined();+ const persisted = await Agent.findOne({ id: agentId }).lean();+ expect(persisted.instructionsPrompt).toBeUndefined();+ });++ test('allows a revert onto a version linking a deleted group', async () => {+ const { groupId } = await createPromptGroupFixture('Doomed Snapshot Link');+ const agentId = `agent_${nanoid()}`;+ await Agent.create({+ id: agentId,+ author: mockReq.user.id,+ name: 'Current Unlinked Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ versions: [+ {+ name: 'Deleted-Link Snapshot',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ },+ ],+ });+ await db.deletePromptGroup({ _id: groupId });++ mockReq.params = { id: agentId };+ mockReq.body = { version_index: 0 };++ await revertAgentVersionHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.name).toBe('Deleted-Link Snapshot');+ // The group's ACL entries went with it, so it reads as not-visible and is+ // stubbed the same as any other hidden group — redaction has no separate+ // existence check.+ expect(response.instructionsPrompt).toEqual({ source: 'native', restricted: true });+ const persisted = await Agent.findOne({ id: agentId }).lean();+ expect(persisted.instructionsPrompt.groupId).toBe(groupId);+ });+ });++ test("excludes the reverted snapshot's dead inline instructions from the scan when the snapshot's own link is valid", async () => {+ const { groupId } = await createPromptGroupFixture('Revert Scan Safe Group');+ mockGroupVisibility(new Set([groupId]));+ const blockedInstructions = 'Use sk-private-token for requests';+ const agentId = `agent_${nanoid()}`;+ await Agent.create({+ id: agentId,+ author: mockReq.user.id,+ name: 'Current Unlinked Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ versions: [+ {+ name: 'Linked Snapshot',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructions: blockedInstructions,+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ },+ ],+ });++ mockReq.config = {+ filters: { agentInstructions: { pii: { starterPatterns: ['sk_prefix'] } } },+ };+ mockReq.params = { id: agentId };+ mockReq.body = { version_index: 0 };++ await revertAgentVersionHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ const persisted = await Agent.findOne({ id: agentId }).lean();+ expect(persisted.instructionsPrompt.groupId).toBe(groupId);+ expect(persisted.instructions).toBe(blockedInstructions);+ });++ test('rejects a revert that removes the current link, landing on a snapshot whose own stored inline text is blocked', async () => {+ const { groupId } = await createPromptGroupFixture('Revert Removal Scan Group');+ mockGroupVisibility(new Set([groupId]));+ const blockedInstructions = 'Use sk-private-token for requests';+ const agentId = `agent_${nanoid()}`;+ await Agent.create({+ id: agentId,+ author: mockReq.user.id,+ name: 'Currently Linked Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ versions: [+ {+ name: 'Pre-Link Snapshot With Dead Text',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructions: blockedInstructions,+ },+ ],+ });++ mockReq.config = {+ filters: { agentInstructions: { pii: { starterPatterns: ['sk_prefix'] } } },+ };+ mockReq.params = { id: agentId };+ mockReq.body = { version_index: 0 };++ await revertAgentVersionHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(400);+ const persisted = await Agent.findOne({ id: agentId }).lean();+ // The revert never applied: the current link and the snapshot are untouched.+ expect(persisted.instructionsPrompt.groupId).toBe(groupId);+ expect(persisted.versions[0].instructions).toBe(blockedInstructions);+ });++ test("rejects a revert that removes the current link, landing on a snapshot that omits instructions, by scanning the agent's current stored text", async () => {+ const { groupId } = await createPromptGroupFixture('Revert Fallback Scan Group');+ mockGroupVisibility(new Set([groupId]));+ const blockedInstructions = 'Use sk-private-token for requests';+ const agentId = `agent_${nanoid()}`;+ await Agent.create({+ id: agentId,+ author: mockReq.user.id,+ name: 'Currently Linked Agent With Dead Text',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructions: blockedInstructions,+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ versions: [+ {+ name: 'Unlinked Snapshot Without Instructions',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ },+ ],+ });++ mockReq.config = {+ filters: { agentInstructions: { pii: { starterPatterns: ['sk_prefix'] } } },+ };+ mockReq.params = { id: agentId };+ mockReq.body = { version_index: 0 };++ await revertAgentVersionHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(400);+ const response = mockRes.json.mock.calls[0][0];+ expect(response).toEqual(+ expect.objectContaining({+ error: 'content_filter_block',+ source: 'agent_instruction',+ field: 'instructions',+ }),+ );+ const persisted = await Agent.findOne({ id: agentId }).lean();+ // The revert never applied: the current link and stored text are untouched.+ expect(persisted.instructionsPrompt.groupId).toBe(groupId);+ expect(persisted.instructions).toBe(blockedInstructions);+ });++ test("allows a revert that removes the current link, landing on a snapshot that omits instructions, when the agent's current stored text is allowed", async () => {+ const { groupId } = await createPromptGroupFixture('Revert Fallback Allowed Group');+ mockGroupVisibility(new Set([groupId]));+ const allowedInstructions = 'Current allowed instructions';+ const agentId = `agent_${nanoid()}`;+ await Agent.create({+ id: agentId,+ author: mockReq.user.id,+ name: 'Currently Linked Agent With Allowed Text',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructions: allowedInstructions,+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ versions: [+ {+ name: 'Unlinked Snapshot Without Instructions',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ },+ ],+ });++ mockReq.config = {+ filters: { agentInstructions: { pii: { starterPatterns: ['sk_prefix'] } } },+ };+ mockReq.params = { id: agentId };+ mockReq.body = { version_index: 0 };++ await revertAgentVersionHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ const persisted = await Agent.findOne({ id: agentId }).lean();+ expect(persisted.instructionsPrompt).toBeUndefined();+ expect(persisted.instructions).toBe(allowedInstructions);+ });++ test('leaves a never-linked revert unaffected by the fallback: no link to remove, so the base behavior (scan only what the snapshot sends) still applies', async () => {+ const blockedInstructions = 'Use sk-private-token for requests';+ const agentId = `agent_${nanoid()}`;+ await Agent.create({+ id: agentId,+ author: mockReq.user.id,+ name: 'Never-Linked Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructions: blockedInstructions,+ versions: [+ {+ name: 'Snapshot Without Instructions',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ },+ ],+ });++ mockReq.config = {+ filters: { agentInstructions: { pii: { starterPatterns: ['sk_prefix'] } } },+ };+ mockReq.params = { id: agentId };+ mockReq.body = { version_index: 0 };++ await revertAgentVersionHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ const persisted = await Agent.findOne({ id: agentId }).lean();+ // Unaffected by the fallback: no link to remove, so the stored text was+ // never a candidate for the scan.+ expect(persisted.instructions).toBe(blockedInstructions);+ });+ });++ describe('getAgentVersionsHandler', () => {+ test('redacts an inaccessible link in a version snapshot', async () => {+ const { groupId } = await createPromptGroupFixture('Versions Endpoint Restricted Group');+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Versioned Prompt Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ versions: [+ {+ name: 'Old Linked Name',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ },+ ],+ });+ // No VIEW grant for `groupId`.++ mockReq.params = { id: agent.id };++ await getAgentVersionsHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(200);+ const versions = mockRes.json.mock.calls[0][0];+ // The agent carries no current link at all, so the redacted snapshot's link+ // cannot match it.+ expect(versions[0].instructionsPrompt).toEqual({+ source: 'native',+ restricted: true,+ matchesCurrent: false,+ });+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.versions[0].instructionsPrompt.groupId).toBe(groupId);+ });++ test('keeps a viewable link in a version snapshot intact', async () => {+ const { groupId } = await createPromptGroupFixture('Versions Endpoint Visible Group');+ mockGroupVisibility(new Set([groupId]));+ const versionInstructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ };+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Versioned Prompt Agent Visible',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ versions: [+ {+ name: 'Old Linked Name',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: versionInstructionsPrompt,+ },+ ],+ });++ mockReq.params = { id: agent.id };++ await getAgentVersionsHandler(mockReq, mockRes);++ const versions = mockRes.json.mock.calls[0][0];+ expect(versions[0].instructionsPrompt).toEqual(versionInstructionsPrompt);+ });++ test("flags a redacted version stub as matchesCurrent against the agent's own hidden current link", async () => {+ const { groupId } = await createPromptGroupFixture('Hidden Current Group');+ const { groupId: otherGroupId } = await createPromptGroupFixture('Hidden Other Group');+ const currentInstructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ };+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Hidden Current Link Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: currentInstructionsPrompt,+ versions: [+ {+ name: 'Same Link Version',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: { ...currentInstructionsPrompt },+ },+ {+ name: 'Different Link Version',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId: otherGroupId,+ selection: { type: 'production' },+ },+ },+ ],+ });+ // No VIEW grant for either `groupId` or `otherGroupId`: both the current link+ // and every version's link are hidden from this editor.++ mockReq.params = { id: agent.id };++ await getAgentVersionsHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(200);+ const versions = mockRes.json.mock.calls[0][0];+ expect(versions[0].instructionsPrompt).toEqual({+ source: 'native',+ restricted: true,+ matchesCurrent: true,+ });+ expect(versions[1].instructionsPrompt).toEqual({+ source: 'native',+ restricted: true,+ matchesCurrent: false,+ });+ });+ });++ describe('uploadAgentAvatarHandler', () => {+ const createTempAvatarFile = () => {+ const filePath = path.join(os.tmpdir(), `avatar-${nanoid()}.png`);+ fs.writeFileSync(filePath, 'fake-image-bytes');+ return filePath;+ };++ beforeEach(() => {+ mockReq.config = {};+ getStrategyFunctions.mockReturnValue({+ processAvatar: jest.fn().mockResolvedValue('https://cdn.example/avatar.png'),+ deleteFile: jest.fn(),+ });+ resizeAvatar.mockResolvedValue(Buffer.from('resized'));+ });++ test('redacts an inaccessible link inside versions[] in the avatar-upload response', async () => {+ const { groupId } = await createPromptGroupFixture('Avatar History Restricted Group');+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Avatar Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ versions: [+ {+ name: 'Old Linked Name',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ },+ },+ ],+ });+ // No VIEW grant for `groupId`.++ mockReq.params = { agent_id: agent.id };+ mockReq.file = { path: createTempAvatarFile(), originalname: 'avatar.png' };++ await uploadAgentAvatarHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(201);+ const response = mockRes.json.mock.calls[0][0];+ // The agent carries no current link at all, so the redacted snapshot's link+ // cannot match it.+ expect(response.versions[0].instructionsPrompt).toEqual({+ source: 'native',+ restricted: true,+ matchesCurrent: false,+ });+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.versions[0].instructionsPrompt.groupId).toBe(groupId);+ });++ test('keeps a viewable top-level link intact in the avatar-upload response', async () => {+ const { groupId } = await createPromptGroupFixture('Avatar Visible Group');+ mockGroupVisibility(new Set([groupId]));+ const instructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+ };+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Avatar Agent Visible',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt,+ });++ mockReq.params = { agent_id: agent.id };+ mockReq.file = { path: createTempAvatarFile(), originalname: 'avatar.png' };++ await uploadAgentAvatarHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(201);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.instructionsPrompt).toEqual(instructionsPrompt);+ });+ });++ describe('role gate (PROMPTS USE)', () => {+ /** `getRoleByName` auto-creates a missing system role from defaults (which grant+ * PROMPTS USE), so a role document must already exist to override it. Resets+ * after each test so later tests see the auto-created default again. */+ const setPromptsUse = (allowed) =>+ mongoose.models.Role.findOneAndUpdate(+ { name: 'USER' },+ {+ $set: {+ name: 'USER',+ [`permissions.${PermissionTypes.PROMPTS}.${Permissions.USE}`]: allowed,+ },+ },+ { upsert: true },+ );++ afterEach(async () => {+ await mongoose.models.Role.deleteMany({ name: 'USER' });+ });++ test('returns 403 instructions_prompt_forbidden for a new link when the role lacks PROMPTS USE', async () => {+ const { groupId } = await createPromptGroupFixture('Role Gate New Link Group');+ mockGroupVisibility(new Set([groupId]));+ await setPromptsUse(false);++ mockReq.body = {+ name: 'No Prompts Permission Agent',+ provider: 'openai',+ model: 'gpt-4',+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ };++ await createAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(403);+ expect(mockRes.json).toHaveBeenCalledWith({+ error: expect.any(String),+ code: InstructionsPromptErrorCode.FORBIDDEN,+ });+ expect(await Agent.countDocuments()).toBe(0);+ });++ test('returns 403 instructions_prompt_forbidden when changing to a different link and the role lacks PROMPTS USE', async () => {+ const { groupId: currentGroupId } =+ await createPromptGroupFixture('Role Gate Current Group');+ const { groupId: nextGroupId } = await createPromptGroupFixture('Role Gate Next Group');+ mockGroupVisibility(new Set([currentGroupId, nextGroupId]));+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Currently Linked Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId: currentGroupId,+ selection: { type: 'production' },+ },+ });+ await setPromptsUse(false);++ mockReq.params = { id: agent.id };+ mockReq.body = {+ instructionsPrompt: {+ source: 'native',+ groupId: nextGroupId,+ selection: { type: 'production' },+ },+ };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(403);+ expect(mockRes.json).toHaveBeenCalledWith({+ error: expect.any(String),+ code: InstructionsPromptErrorCode.FORBIDDEN,+ });+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.instructionsPrompt.groupId).toBe(currentGroupId);+ });++ test('still allows removing a link when the role lacks PROMPTS USE', async () => {+ const { groupId } = await createPromptGroupFixture('Role Gate Removal Group');+ mockGroupVisibility(new Set([groupId]));+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Linked Agent For Removal',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ });+ await setPromptsUse(false);++ mockReq.params = { id: agent.id };+ mockReq.body = { instructionsPrompt: null };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.instructionsPrompt).toBeUndefined();+ });++ test('still allows an unrelated edit that leaves an inaccessible-role link untouched', async () => {+ const { groupId } = await createPromptGroupFixture('Role Gate Unrelated Edit Group');+ mockGroupVisibility(new Set([groupId]));+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Linked Agent For Unrelated Edit',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ });+ await setPromptsUse(false);++ mockReq.params = { id: agent.id };+ mockReq.body = { name: 'Renamed Without Prompts Permission' };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.name).toBe('Renamed Without Prompts Permission');+ expect(persisted.instructionsPrompt.groupId).toBe(groupId);+ });+ });++ describe('unexpected validation failures (500)', () => {+ /** Every case below forces the ACL lookup `checkInstructionsPromptWrite` calls+ * (via `validateLinkWrite`, for create/update) to throw, and asserts the+ * handler sends only the fixed, safe body: never the thrown message, and+ * nothing is created or persisted. Duplicate and revert never call+ * `validateLinkWrite` — they restore/copy the link as-is — so there is no+ * equivalent 500 case for them here; `presentForEditor`'s own fail-closed+ * behavior (stub, never 500) is covered under `duplicateAgentHandler` above. */+ const outageMessage = 'outage detail that must never reach the client';++ test('createAgentHandler returns the fixed 500 when the ACL lookup throws and creates nothing', async () => {+ const groupId = new mongoose.Types.ObjectId().toString();+ getResourcePermissionsMap.mockImplementation(async () => {+ throw new Error(outageMessage);+ });++ mockReq.body = {+ name: 'Validation Failure Agent',+ provider: 'openai',+ model: 'gpt-4',+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ };++ await createAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(500);+ expect(mockRes.json).toHaveBeenCalledWith({+ error: 'Unable to validate the linked prompt',+ code: InstructionsPromptErrorCode.VALIDATION_FAILED,+ });+ expect(mockRes.json).not.toHaveBeenCalledWith(+ expect.objectContaining({ error: expect.stringContaining(outageMessage) }),+ );+ expect(await Agent.countDocuments({})).toBe(0);+ });++ test('updateAgentHandler returns the fixed 500 when the ACL lookup throws and persists nothing', async () => {+ const { groupId: currentGroupId } = await createPromptGroupFixture(+ 'Validation Failure Current Group',+ );+ const { groupId: nextGroupId } = await createPromptGroupFixture(+ 'Validation Failure Next Group',+ );+ mockGroupVisibility(new Set([currentGroupId, nextGroupId]));+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Agent Pending Validation Failure',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: {+ source: 'native',+ groupId: currentGroupId,+ selection: { type: 'production' },+ },+ });++ getResourcePermissionsMap.mockImplementation(async () => {+ throw new Error(outageMessage);+ });++ mockReq.params = { id: agent.id };+ mockReq.body = {+ instructionsPrompt: {+ source: 'native',+ groupId: nextGroupId,+ selection: { type: 'production' },+ },+ };++ await updateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(500);+ expect(mockRes.json).toHaveBeenCalledWith({+ error: 'Unable to validate the linked prompt',+ code: InstructionsPromptErrorCode.VALIDATION_FAILED,+ });+ expect(mockRes.json).not.toHaveBeenCalledWith(+ expect.objectContaining({ error: expect.stringContaining(outageMessage) }),+ );+ const persisted = await Agent.findOne({ id: agent.id }).lean();+ expect(persisted.instructionsPrompt.groupId).toBe(currentGroupId);+ });++ test('revert restores the snapshot link when the ACL lookup fails and presents it fail-closed', async () => {+ const { groupId } = await createPromptGroupFixture('Validation Failure Revert Group');+ const agentId = `agent_${nanoid()}`;+ await Agent.create({+ id: agentId,+ author: mockReq.user.id,+ name: 'Current Unlinked Agent For Validation Failure',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ versions: [+ {+ name: 'Pre-Link Snapshot',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ },+ ],+ });++ getResourcePermissionsMap.mockImplementation(async () => {+ throw new Error(outageMessage);+ });++ mockReq.params = { id: agentId };+ mockReq.body = { version_index: 0 };++ await revertAgentVersionHandler(mockReq, mockRes);++ // The thrown ACL lookup surfaces only in `presentForEditor`'s own+ // fail-closed stubbing, not as a 500 — the revert itself proceeds and+ // persists the snapshot's link, which the response presents as restricted.+ expect(mockRes.status).not.toHaveBeenCalledWith(500);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.instructionsPrompt).toEqual({ source: 'native', restricted: true });+ const persisted = await Agent.findOne({ id: agentId }).lean();+ expect(persisted.name).toBe('Pre-Link Snapshot');+ expect(persisted.instructionsPrompt.groupId).toBe(groupId);+ });++ test('duplicateAgentHandler never calls getRoleByName for the link (no PROMPTS USE check on a duplicate)', async () => {+ const { groupId } = await createPromptGroupFixture('Validation Failure Duplicate Group');+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Source Agent For Validation Failure',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ });++ const getRoleByNameSpy = jest.spyOn(db, 'getRoleByName');++ mockReq.params = { id: agent.id };++ await duplicateAgentHandler(mockReq, mockRes);++ // Nothing calls the role lookup for a duplicate.+ expect(getRoleByNameSpy).not.toHaveBeenCalled();+ expect(mockRes.status).toHaveBeenCalledWith(201);+ expect(await Agent.countDocuments({})).toBe(2);++ getRoleByNameSpy.mockRestore();+ });+ });+ });});diff --git a/api/server/routes/agents/actions.js b/api/server/routes/agents/actions.jsindex 9846a2b899..ea7f3f42d3 100644--- a/api/server/routes/agents/actions.js+++ b/api/server/routes/agents/actions.js@@ -28,6 +28,7 @@ const {} = require('~/server/services/ActionService');const { findAccessibleResources } = require('~/server/services/PermissionService');const { attachOwnerContacts } = require('~/server/services/Agents/ownerContact');+const { instructionsPromptAccess } = require('~/server/services/Agents/instructionsPrompt');const db = require('~/models');const { canAccessAgentResource } = require('~/server/middleware');@@ -263,7 +264,16 @@ router.post(}}- res.json([updatedAgent, updatedAction]);+ /** `updatedAgent` is the same EDIT-scoped, `versions[]`-carrying shape returned by+ * `controllers/agents/v1.js`'s write handlers, and the client writes this response+ * into the expanded agent cache — an unrelated action edit must not leak a link the+ * caller cannot VIEW. */+ const presentedAgent = await instructionsPromptAccess.presentForEditor({+ user: req.user,+ agent: updatedAgent,+ });++ res.json([presentedAgent, updatedAction]);} catch (error) {const message = 'Trouble updating the Agent Action';logger.error(message, error);diff --git a/api/server/routes/agents/actions.spec.js b/api/server/routes/agents/actions.spec.jsnew file mode 100644index 0000000000..426cdcdece--- /dev/null+++ b/api/server/routes/agents/actions.spec.js@@ -0,0 +1,157 @@+const express = require('express');+const request = require('supertest');+const { PermissionBits } = require('librechat-data-provider');++const mockEncryptMetadata = jest.fn();+const mockDecryptMetadata = jest.fn();+const mockDomainParser = jest.fn();+const mockGetResourcePermissionsMap = jest.fn().mockResolvedValue(new Map());++jest.mock('@librechat/api', () => ({+ ...jest.requireActual('@librechat/api'),+ generateCheckAccess: jest.fn(() => (_req, _res, next) => next()),+ isActionDomainAllowed: jest.fn().mockResolvedValue(true),+}));+jest.mock('~/server/services/ActionService', () => ({+ decryptMetadata: mockDecryptMetadata,+ encryptMetadata: mockEncryptMetadata,+ domainParser: mockDomainParser,+}));+jest.mock('~/server/services/PermissionService', () => ({+ findAccessibleResources: jest.fn(),+ getResourcePermissionsMap: mockGetResourcePermissionsMap,+ grantPermission: jest.fn(),+}));+jest.mock('~/server/services/Agents/ownerContact', () => ({+ attachOwnerContacts: jest.fn(async (agents) => agents),+}));+jest.mock('~/models', () => ({+ getRoleByName: jest.fn(),+ getUserPrincipals: jest.fn().mockResolvedValue([]),+ hasCapabilityForPrincipals: jest.fn().mockResolvedValue(false),+ deleteTokens: jest.fn(),+ getListAgentsByAccess: jest.fn(),+ getActions: jest.fn(),+ getAgent: jest.fn(),+ // `instructionsPromptAccess` (below) reads this to tell an inaccessible-but-+ // existing link (redact) apart from one whose group has been deleted (show+ // as-is). The tests here exercise permission-only redaction, so the group+ // always exists.+ getPromptGroup: jest.fn().mockResolvedValue({+ _id: '507f1f77bcf86cd799439011',+ name: 'Fixture Group',+ author: 'owner-id',+ authorName: 'Owner',+ }),+ updateAgent: jest.fn(),+ updateAction: jest.fn(),+ deleteAction: jest.fn(),+}));+jest.mock('~/server/middleware', () => ({+ canAccessAgentResource: jest.fn(() => (_req, _res, next) => next()),+}));++const router = require('./actions');+const db = require('~/models');++function createApp() {+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.config = { filters: {} };+ req.user = { id: 'user-id', role: 'USER' };+ next();+ });+ app.use(router);+ return app;+}++const groupId = '507f1f77bcf86cd799439011';++const linkedInstructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+};++describe('POST /actions/:agent_id instructionsPrompt presentation', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockEncryptMetadata.mockImplementation(async (metadata) => metadata);+ mockDecryptMetadata.mockImplementation(async (metadata) => metadata);+ mockDomainParser.mockResolvedValue('encoded');+ mockGetResourcePermissionsMap.mockResolvedValue(new Map());+ db.getAgent.mockResolvedValue({+ id: 'agent-id',+ actions: [],+ tools: [],+ author: 'owner-id',+ });+ db.updateAction.mockResolvedValue({ metadata: { domain: 'example.test' } });+ });++ const postAction = (app) =>+ request(app)+ .post('/agent-id')+ .send({+ functions: [+ {+ type: 'function',+ function: { name: 'lookup', description: 'Lookup', parameters: { type: 'object' } },+ },+ ],+ metadata: { domain: 'example.test' },+ });++ it('redacts an updatedAgent.instructionsPrompt link the caller cannot VIEW', async () => {+ db.updateAgent.mockResolvedValue({+ id: 'agent-id',+ instructionsPrompt: linkedInstructionsPrompt,+ });++ const response = await postAction(createApp());++ expect(response.status).toBe(200);+ expect(response.body[0].instructionsPrompt).toEqual({ source: 'native', restricted: true });+ });++ it('keeps a visible updatedAgent.instructionsPrompt link intact', async () => {+ mockGetResourcePermissionsMap.mockResolvedValue(new Map([[groupId, PermissionBits.VIEW]]));+ db.updateAgent.mockResolvedValue({+ id: 'agent-id',+ instructionsPrompt: linkedInstructionsPrompt,+ });++ const response = await postAction(createApp());++ expect(response.status).toBe(200);+ expect(response.body[0].instructionsPrompt).toEqual(linkedInstructionsPrompt);+ });++ it('redacts an inaccessible link inside updatedAgent.versions[] as well', async () => {+ db.updateAgent.mockResolvedValue({+ id: 'agent-id',+ versions: [{ name: 'v1', instructionsPrompt: linkedInstructionsPrompt }],+ });++ const response = await postAction(createApp());++ expect(response.status).toBe(200);+ expect(response.body[0].versions).toEqual([+ {+ name: 'v1',+ instructionsPrompt: { source: 'native', restricted: true, matchesCurrent: false },+ },+ ]);+ });++ it('leaves the response unchanged when the updated agent carries no link', async () => {+ db.updateAgent.mockResolvedValue({ id: 'agent-id' });++ const response = await postAction(createApp());++ expect(response.status).toBe(200);+ expect(response.body[0]).not.toHaveProperty('instructionsPrompt');+ expect(mockGetResourcePermissionsMap).not.toHaveBeenCalled();+ });+});diff --git a/api/server/routes/prompts.js b/api/server/routes/prompts.jsindex e2d7a947cd..27438f4913 100644--- a/api/server/routes/prompts.js+++ b/api/server/routes/prompts.js@@ -3,8 +3,14 @@ const {generateCheckAccess,createPromptService,createPromptHandlers,+ invalidateLinkedPrompt,} = require('@librechat/api');-const { Permissions, PermissionBits, PermissionTypes } = require('librechat-data-provider');+const {+ CacheKeys,+ Permissions,+ PermissionBits,+ PermissionTypes,+} = require('librechat-data-provider');const {canAccessPromptGroupResource,canAccessPromptViaGroup,@@ -13,15 +19,20 @@ const {configMiddleware,} = require('~/server/middleware');const { getEffectivePermissions, grantPermission } = require('~/server/services/PermissionService');+const { getLogStores } = require('~/cache');const db = require('~/models');const { getRoleByName } = db;const router = express.Router();+const linkedInstructionsCache = getLogStores(CacheKeys.AGENT_LINKED_INSTRUCTIONS);+const handlers = createPromptHandlers({service: createPromptService({ db, grantPermission }),getPromptGroupAccessContext: db.getPromptGroupAccessContext,getEffectivePermissions,+ invalidateLinkedPrompt: (groupId, promptIds) =>+ invalidateLinkedPrompt(linkedInstructionsCache, groupId, promptIds),});const checkPromptAccess = generateCheckAccess({@@ -92,12 +103,14 @@ router.delete(requiredPermission: PermissionBits.DELETE,resourceIdParam: 'promptId',}),+ configMiddleware,handlers.deletePrompt,);router.delete('/groups/:groupId',checkPromptCreate,canAccessPromptGroupResource({ requiredPermission: PermissionBits.DELETE }),+ configMiddleware,handlers.deletePromptGroup,);diff --git a/api/server/routes/prompts.test.js b/api/server/routes/prompts.test.jsindex 41040cf2f6..57b89b57c6 100644--- a/api/server/routes/prompts.test.js+++ b/api/server/routes/prompts.test.js@@ -38,16 +38,18 @@ jest.mock('~/models', () => {jest.mock('~/server/middleware', () => ({requireJwtAuth: (req, res, next) => next(),- configMiddleware: (req, res, next) => {+ configMiddleware: jest.fn((req, res, next) => {req.config = mockAppConfig;next();- },+ }),promptUsageLimiter: (req, res, next) => next(),canAccessPromptViaGroup: jest.requireActual('~/server/middleware').canAccessPromptViaGroup,canAccessPromptGroupResource:jest.requireActual('~/server/middleware').canAccessPromptGroupResource,}));+const { configMiddleware } = require('~/server/middleware');+let app;let mongoServer;let promptRoutes;@@ -736,6 +738,54 @@ describe('Prompt Routes - ACL Permissions', () => {const prompt = await Prompt.findById(authorPrompt._id);expect(prompt).toBeTruthy();});++ it('should run configMiddleware so the handler receives the configured value', async () => {+ configMiddleware.mockClear();++ await request(app)+ .delete(`/api/prompts/${testPrompt._id}`)+ .query({ groupId: testGroup._id.toString() })+ .expect(200);++ expect(configMiddleware).toHaveBeenCalledTimes(1);+ });+ });++ describe('DELETE /api/prompts/groups/:groupId - Delete Prompt Group', () => {+ let testGroup;++ beforeEach(async () => {+ testGroup = await PromptGroup.create({+ name: 'Delete Group Test Group',+ category: 'testing',+ author: testUsers.owner._id,+ authorName: testUsers.owner.name,+ productionId: new ObjectId(),+ });++ await grantPermission({+ principalType: PrincipalType.USER,+ principalId: testUsers.owner._id,+ resourceType: ResourceType.PROMPTGROUP,+ resourceId: testGroup._id,+ accessRoleId: AccessRoleIds.PROMPTGROUP_OWNER,+ grantedBy: testUsers.owner._id,+ });+ });++ afterEach(async () => {+ await Prompt.deleteMany({});+ await PromptGroup.deleteMany({});+ await AclEntry.deleteMany({});+ });++ it('should run configMiddleware so the handler receives the configured value', async () => {+ configMiddleware.mockClear();++ await request(app).delete(`/api/prompts/groups/${testGroup._id}`).expect(200);++ expect(configMiddleware).toHaveBeenCalledTimes(1);+ });});describe('PATCH /api/prompts/:promptId/tags/production - Make Production', () => {diff --git a/api/server/services/Agents/instructionsPrompt.js b/api/server/services/Agents/instructionsPrompt.jsnew file mode 100644index 0000000000..6da3a40aff--- /dev/null+++ b/api/server/services/Agents/instructionsPrompt.js@@ -0,0 +1,37 @@+const { logger, SystemCapabilities } = require('@librechat/data-schemas');+const {+ checkAccess,+ createPromptService,+ assertModelBoundContent,+ createInstructionsPromptAccess,+} = require('@librechat/api');+const { Permissions, PermissionTypes } = require('librechat-data-provider');+const {+ grantPermission,+ getResourcePermissionsMap,+} = require('~/server/services/PermissionService');+const { hasCapability } = require('~/server/middleware/roles/capabilities');+const db = require('~/models');++/** Wiring only: the write/present decision logic lives in `@librechat/api` (`createInstructionsPromptAccess`, `checkInstructionsPromptWrite`). */+const instructionsPromptAccess = createInstructionsPromptAccess({+ getResourcePermissionsMap,+ canManagePrompts: (user) => hasCapability(user, SystemCapabilities.MANAGE_PROMPTS),+ promptService: createPromptService({ db, grantPermission }),+ assertAgentInstructionsContent: ({ instructions, filters }) =>+ assertModelBoundContent({ filters, agents: [{ instructions }] }),+ /** The same role-level gate `checkPromptAccess` applies to every `/prompts` route+ * (`PermissionTypes.PROMPTS`, `Permissions.USE`). Only `.role` is read, so the+ * `{ id, role }` identity `validateLinkWrite` carries is enough. */+ canUsePrompts: (user, req) =>+ checkAccess({+ req,+ user,+ permissionType: PermissionTypes.PROMPTS,+ permissions: [Permissions.USE],+ getRoleByName: db.getRoleByName,+ }),+ logger,+});++module.exports = { instructionsPromptAccess };diff --git a/api/server/services/Endpoints/agents/addedConvo.js b/api/server/services/Endpoints/agents/addedConvo.jsindex b22c3b5b0b..e598fe46c4 100644--- a/api/server/services/Endpoints/agents/addedConvo.js+++ b/api/server/services/Endpoints/agents/addedConvo.js@@ -66,6 +66,10 @@ const loadAddedAgent = (params) =>* `codeEnvAvailable`. @see InitializeAgentParams.fileSearchAvailable.* @param {boolean} [params.statefulSessionsAvailable] - `stateful_code_sessions`* capability flag; forwarded verbatim alongside `codeEnvAvailable`.+ * @param {import('@librechat/api').ResolveLinkedInstructions} [params.resolveLinkedInstructions] -+ * Resolver for the added agent's own `instructionsPrompt` link, forwarded verbatim.+ * @param {boolean} [params.recordLinkedPromptUsage] - Forwarded to `initializeAgent`;+ * defaults to `true` there when omitted.* @param {AbortSignal} [params.signal] - Owning run cancellation signal.* @returns {Promise<{userMCPAuthMap: Object|undefined}>} The updated userMCPAuthMap*/@@ -94,6 +98,8 @@ const processAddedConvo = async ({defaultActiveOnShare,codeEnvAvailable,fileSearchAvailable,+ resolveLinkedInstructions,+ recordLinkedPromptUsage,backgroundToolsAvailable,toolIntentsAvailable,statefulSessionsAvailable,@@ -196,6 +202,8 @@ const processAddedConvo = async ({}),codeEnvAvailable,fileSearchAvailable,+ resolveLinkedInstructions,+ recordLinkedPromptUsage,backgroundToolsAvailable,toolIntentsAvailable,statefulSessionsAvailable,diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.jsindex 904853685f..01269a99b9 100644--- a/api/server/services/Endpoints/agents/initialize.js+++ b/api/server/services/Endpoints/agents/initialize.js@@ -98,6 +98,7 @@ const { getModelsConfig } = require('~/server/controllers/ModelController');const { checkPermission, findAccessibleResources } = require('~/server/services/PermissionService');const AgentClient = require('~/server/controllers/agents/client');const { processAddedConvo } = require('./addedConvo');+const { getLinkedInstructionsResolver } = require('./linkedInstructions');const subagentThreadTaskStore = require('./subagentThreadStore');const {preregisterBackgroundToolCompletion,@@ -201,6 +202,10 @@ function createToolLoader(* @param {import('@librechat/api').MCPRuntimeRequestBody} [params.requestBody]* @param {import('@librechat/api').UpstreamTokenProvider} [params.upstreamTokenProvider]* @param {import('@librechat/api').UpstreamTokenProviderResolver} [params.upstreamTokenProviderResolver]+ * @param {boolean} [params.isResume] Whether this initialization is replaying an+ * already-in-flight turn (a resumed stream), rather than starting a new one.+ * Resolution of every agent's `instructionsPrompt` link still runs, cache-first,+ * but usage is not recorded again for the same turn.*/const initializeClientWithProvider = async ({req,@@ -214,6 +219,7 @@ const initializeClientWithProvider = async ({toolTimingReplayEvents,upstreamTokenProvider,upstreamTokenProviderResolver,+ isResume,}) => {if (!endpointOption) {throw new Error('Endpoint option not provided');@@ -292,6 +298,12 @@ const initializeClientWithProvider = async ({: null;const backgroundToolsAvailable = enabledCapabilities.has(AgentCapabilities.run_in_background);const toolIntentsAvailable = enabledCapabilities.has(AgentCapabilities.tool_intents);+ /** Resolves any agent's `instructionsPrompt` link this run encounters — primary,+ * handoff, subagent, or added-conversation agent. A resumed turn records no+ * usage at all, including for a lazy subagent spawned for the first time+ * during that resumed turn: only a fresh turn records usage. */+ const resolveLinkedInstructions = getLinkedInstructionsResolver();+ const recordLinkedPromptUsage = !isResume;const deferredToolsAvailable = enabledCapabilities.has(AgentCapabilities.deferred_tools);const programmaticToolsAvailable = enabledCapabilities.has(AgentCapabilities.programmatic_tools);const statefulSessionsAvailable = enabledCapabilities.has(@@ -759,6 +771,8 @@ const initializeClientWithProvider = async ({skillAuthoringAvailable: primarySkillAuthoringAvailable,codeEnvAvailable,fileSearchAvailable,+ resolveLinkedInstructions,+ recordLinkedPromptUsage,backgroundToolsAvailable,toolIntentsAvailable,statefulSessionsAvailable,@@ -852,6 +866,8 @@ const initializeClientWithProvider = async ({defaultActiveOnShare,codeEnvAvailable,fileSearchAvailable,+ resolveLinkedInstructions,+ recordLinkedPromptUsage,backgroundToolsAvailable,toolIntentsAvailable,statefulSessionsAvailable,@@ -939,6 +955,8 @@ const initializeClientWithProvider = async ({defaultActiveOnShare,codeEnvAvailable,fileSearchAvailable,+ resolveLinkedInstructions,+ recordLinkedPromptUsage,backgroundToolsAvailable,toolIntentsAvailable,statefulSessionsAvailable,@@ -1354,6 +1372,8 @@ const initializeClientWithProvider = async ({}),codeEnvAvailable,fileSearchAvailable,+ resolveLinkedInstructions,+ recordLinkedPromptUsage,backgroundToolsAvailable,toolIntentsAvailable,statefulSessionsAvailable,diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.jsindex 1771bf2fca..777188ba10 100644--- a/api/server/services/Endpoints/agents/initialize.spec.js+++ b/api/server/services/Endpoints/agents/initialize.spec.js@@ -89,6 +89,11 @@ jest.mock('./addedConvo', () => ({processAddedConvo: jest.fn().mockResolvedValue({ userMCPAuthMap: undefined }),}));+const mockResolveLinkedInstructions = jest.fn();+jest.mock('./linkedInstructions', () => ({+ getLinkedInstructionsResolver: jest.fn(() => mockResolveLinkedInstructions),+}));+jest.mock('~/cache', () => ({logViolation: jest.fn(),}));@@ -358,6 +363,45 @@ describe('initializeClient — processAgent ACL gate', () => {expect(resolveUpstreamTokenProvider).not.toHaveBeenCalled();});+ it('forwards the linked-instructions resolver and records usage by default', async () => {+ mockInitializeAgent.mockResolvedValue(makePrimaryConfig([]));++ await initializeClient({+ req: makeReq(),+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });++ expect(mockInitializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ resolveLinkedInstructions: mockResolveLinkedInstructions,+ recordLinkedPromptUsage: true,+ }),+ expect.anything(),+ );+ });++ it('forwards recordLinkedPromptUsage: false for every agent initialized on the resume path', async () => {+ mockInitializeAgent.mockResolvedValue(makePrimaryConfig([]));++ await initializeClient({+ req: makeReq(),+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ isResume: true,+ });++ expect(mockInitializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ resolveLinkedInstructions: mockResolveLinkedInstructions,+ recordLinkedPromptUsage: false,+ }),+ expect.anything(),+ );+ });+it('replaces untrusted artifact route metadata with the executing agent context', async () => {mockInitializeAgent.mockResolvedValue(makePrimaryConfig([]));diff --git a/api/server/services/Endpoints/agents/linkedInstructions.js b/api/server/services/Endpoints/agents/linkedInstructions.jsnew file mode 100644index 0000000000..a105867fdf--- /dev/null+++ b/api/server/services/Endpoints/agents/linkedInstructions.js@@ -0,0 +1,25 @@+const { logger } = require('@librechat/data-schemas');+const { CacheKeys } = require('librechat-data-provider');+const { createPromptService, createLinkedInstructionsResolver } = require('@librechat/api');+const { grantPermission } = require('~/server/services/PermissionService');+const { getLogStores } = require('~/cache');+const db = require('~/models');++/**+ * Shared resolver for an agent's `instructionsPrompt` link. Resolve and cache+ * logic lives in `@librechat/api` (`createLinkedInstructionsResolver`); this+ * module wires in the LibreChat prompt service and the+ * `AGENT_LINKED_INSTRUCTIONS` cache namespace (`~/cache/getLogStores.js`).+ */+const linkedInstructionsResolver = createLinkedInstructionsResolver({+ promptService: createPromptService({ db, grantPermission }),+ cache: getLogStores(CacheKeys.AGENT_LINKED_INSTRUCTIONS),+ logger,+});++/** @returns {import('@librechat/api').ResolveLinkedInstructions} */+function getLinkedInstructionsResolver() {+ return linkedInstructionsResolver;+}++module.exports = { getLinkedInstructionsResolver };diff --git a/client/src/common/agents-types.ts b/client/src/common/agents-types.tsindex caa3d95c3c..02f11a2bd4 100644--- a/client/src/common/agents-types.ts+++ b/client/src/common/agents-types.ts@@ -10,6 +10,8 @@ import type {StatefulCodeEnvironment,GraphEdge,Agent,+ AgentInstructionsPrompt,+ RestrictedAgentInstructionsPrompt,} from 'librechat-data-provider';import type { OptionWithIcon, ExtendedFile } from './types';@@ -37,6 +39,10 @@ export type AgentForm = {name: string | null;description: string | null;instructions: string | null;+ /** Whether instructions come from the inline editor or a linked native prompt group. */+ instructionsSource: 'inline' | 'prompt';+ /** The linked prompt group revision, or the restricted stub when the editor cannot view it. */+ instructionsPrompt: AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null;model: string | null;model_parameters: AgentModelParameters;tools?: string[];diff --git a/client/src/components/SidePanel/Agents/AgentConfig.tsx b/client/src/components/SidePanel/Agents/AgentConfig.tsxindex 4e091d513d..ce6b96fd85 100644--- a/client/src/components/SidePanel/Agents/AgentConfig.tsx+++ b/client/src/components/SidePanel/Agents/AgentConfig.tsx@@ -1,5 +1,6 @@import { Input, Label } from '@librechat/client';import { Controller, useWatch, useFormContext } from 'react-hook-form';+import type { InstructionsPromptStatus } from './Instructions';import type { AgentForm } from '~/common';import { ResolvedProviderIcon } from '~/components/Endpoints/ResolvedProviderIcon';import AgentCategorySelector from './AgentCategorySelector';@@ -17,7 +18,13 @@ import { Panel } from '~/common';const fieldClass = 'h-9';-export default function AgentConfig() {+export default function AgentConfig({+ instructionsPromptStatus,+ onRetryInstructionsPrompt,+}: {+ instructionsPromptStatus?: InstructionsPromptStatus;+ onRetryInstructionsPrompt?: () => void;+}) {const localize = useLocalize();const methods = useFormContext<AgentForm>();const { setActivePanel, endpointsConfig, agentsConfig } = useAgentPanelContext();@@ -144,7 +151,10 @@ export default function AgentConfig() {</div>{/* INSTRUCTIONS */}- <Instructions />+ <Instructions+ promptStatus={instructionsPromptStatus}+ onRetryLoad={onRetryInstructionsPrompt}+ />{/* TOOLS — unified built-ins / tools / actions / mcp / skills */}<ToolsSection agentId={agent_id} />diff --git a/client/src/components/SidePanel/Agents/AgentPanel.test.tsx b/client/src/components/SidePanel/Agents/AgentPanel.test.tsxindex 44c778331d..cd5c775b2b 100644--- a/client/src/components/SidePanel/Agents/AgentPanel.test.tsx+++ b/client/src/components/SidePanel/Agents/AgentPanel.test.tsx@@ -7,6 +7,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import type { UseFormReturn } from 'react-hook-form';import type { Agent } from 'librechat-data-provider';import type { AgentForm, AgentModelPanelProps } from '~/common';+import type { InstructionsPromptStatus } from './Instructions';// Mock toast context - define this after all mockslet mockShowToast: jest.Mock;@@ -21,6 +22,10 @@ let mockModelPanelProps: Pick<'models' | 'modelsError' | 'modelsReady'> | null = null;let mockFormDefaults: Partial<AgentForm> = {};+let mockAgentConfigStatus: InstructionsPromptStatus | undefined;+let mockAgentSelectAgentQueryData: Agent | undefined;+let mockUserRole = 'USER';+let mockHasPermission = true;let mockAgentPanelContext = {activePanel: 'builder',agentsConfig: { allowedProviders: [] as string[] },@@ -121,12 +126,12 @@ jest.mock('~/utils', () => ({jest.mock('~/hooks', () => ({useSelectAgent: () => ({ onSelect: jest.fn() }),useLocalize: () => (key: string) => key,- useAuthContext: () => ({ user: { id: 'user-123', role: 'USER' } }),+ useAuthContext: () => ({ user: { id: 'user-123', role: mockUserRole } }),}));jest.mock('~/hooks/useResourcePermissions', () => ({useResourcePermissions: () => ({- hasPermission: jest.fn(() => true),+ hasPermission: jest.fn(() => mockHasPermission),isLoading: false,}),}));@@ -159,12 +164,18 @@ jest.mock('./Advanced/AdvancedPanel', () => ({jest.mock('./AgentConfig', () => ({__esModule: true,- default: () => <div>{`Agent Config`}</div>,+ default: (props: { instructionsPromptStatus?: InstructionsPromptStatus }) => {+ mockAgentConfigStatus = props.instructionsPromptStatus;+ return <div>{`Agent Config - ${props.instructionsPromptStatus ?? 'ready'}`}</div>;+ },}));jest.mock('./AgentSelect', () => ({__esModule: true,- default: () => <div>{`Agent Select`}</div>,+ default: (props: { agentQuery: { data?: Agent } }) => {+ mockAgentSelectAgentQueryData = props.agentQuery?.data;+ return <div>{`Agent Select`}</div>;+ },}));jest.mock('./ModelPanel', () => ({@@ -319,6 +330,10 @@ describe('AgentPanel - Update Agent Toast Messages', () => {mockFormSubmitHandler = null;capturedFormMethods = null;mockModelPanelProps = null;+ mockAgentConfigStatus = undefined;+ mockAgentSelectAgentQueryData = undefined;+ mockUserRole = 'USER';+ mockHasPermission = true;mockFormDefaults = {};mockModelsQuery = {data: { openai: ['gpt-4'] },@@ -442,6 +457,45 @@ describe('AgentPanel - Update Agent Toast Messages', () => {expect(mockModelPanelProps?.modelsError).toBe(true);});+ it('keeps instructions controls loading for an admin without ACL EDIT until the expanded agent arrives', async () => {+ const { mockUseGetAgentByIdQuery } = setupMocks();+ mockUserRole = 'ADMIN';+ mockHasPermission = false;++ mockUseGetAgentByIdQuery.mockReturnValue({+ data: createMockAgent(),+ isInitialLoading: false,+ } as any);+ const mockUseGetExpandedAgentByIdQuery = useGetExpandedAgentByIdQuery as jest.MockedFunction<+ typeof useGetExpandedAgentByIdQuery+ >;+ mockUseGetExpandedAgentByIdQuery.mockReturnValue({+ data: undefined,+ isError: false,+ refetch: jest.fn(),+ } as any);++ const Wrapper = createWrapper();+ const { rerender } = render(<AgentPanel />, { wrapper: Wrapper });++ await waitFor(() => expect(mockAgentConfigStatus).toBe('loading'));++ const link = {+ source: 'native' as const,+ groupId: '507f1f77bcf86cd799439011',+ selection: { type: 'production' as const },+ };+ mockUseGetExpandedAgentByIdQuery.mockReturnValue({+ data: createMockAgent({ instructionsPrompt: link }),+ isError: false,+ refetch: jest.fn(),+ } as any);+ rerender(<AgentPanel />);++ await waitFor(() => expect(mockAgentConfigStatus).toBe('ready'));+ expect(mockAgentSelectAgentQueryData?.instructionsPrompt).toEqual(link);+ });+it("preserves an existing agent's configured model", async () => {const { mockUseGetAgentByIdQuery } = setupMocks();mockAgentQuery(mockUseGetAgentByIdQuery, {});@@ -759,5 +813,518 @@ describe('AgentPanel - Update Agent Toast Messages', () => {});});});++ describe('instructionsPromptChanged', () => {+ const link = {+ source: 'native' as const,+ groupId: 'group_1',+ selection: { type: 'production' as const },+ };++ it('omits instructionsPrompt from a later unrelated save after a prompt link was saved', async () => {+ /** `AgentSelect`'s post-save `reset(..., { keepDirtyValues: true })` can leave+ * `dirtyFields.instructionsPrompt` true even once the field's value matches what+ * was just persisted. This harness never calls that `reset` at all (`AgentSelect`+ * is mocked out above), which reproduces the same end state by construction: once+ * `setValue(..., { shouldDirty: true })` marks the field dirty, nothing clears it+ * between the two submits below. A fix that still read `dirtyFields` here would+ * resend the link on the second, unrelated save. */+ const { mockUseGetAgentByIdQuery, mockUpdateAgent } = setupMocks();++ mockAgentQuery(mockUseGetAgentByIdQuery, {+ name: 'Test Agent',+ version: 2,+ instructionsPrompt: null,+ });+ mockFormDefaults = { instructionsSource: 'inline', instructionsPrompt: null };++ mockUpdateAgent.mockResolvedValueOnce(+ createMockAgent({ name: 'Test Agent', version: 2, instructionsPrompt: link }),+ );++ const Wrapper = createWrapper();+ const { container } = render(<AgentPanel />, { wrapper: Wrapper });++ act(() => {+ capturedFormMethods!.setValue('instructionsSource', 'prompt', { shouldDirty: true });+ capturedFormMethods!.setValue('instructionsPrompt', link, { shouldDirty: true });+ });++ fireEvent.submit(container.querySelector('form')!);+ await act(async () => {+ mockFormSubmitHandler?.();+ });++ await waitFor(() => expect(mockUpdateAgent).toHaveBeenCalledTimes(1));+ expect(mockUpdateAgent.mock.calls[0][0].data).toHaveProperty('instructionsPrompt', link);++ /** Mirrors what the real cache write in `mutations.ts` produces after the save: the+ * query the panel reads now reflects the link that was just persisted. The mock+ * hook only returns this on its next call, which the `setValue` below triggers. */+ mockAgentQuery(mockUseGetAgentByIdQuery, {+ name: 'Test Agent',+ version: 2,+ instructionsPrompt: link,+ });++ mockUpdateAgent.mockResolvedValueOnce(+ createMockAgent({ name: 'Renamed Agent', version: 2, instructionsPrompt: link }),+ );++ act(() => {+ capturedFormMethods!.setValue('name', 'Renamed Agent', { shouldDirty: true });+ });++ fireEvent.submit(container.querySelector('form')!);+ await act(async () => {+ mockFormSubmitHandler?.();+ });++ await waitFor(() => expect(mockUpdateAgent).toHaveBeenCalledTimes(2));+ expect(mockUpdateAgent.mock.calls[1][0].data).not.toHaveProperty('instructionsPrompt');+ });++ it('applies a restored prompt after saving a different link in the same session', async () => {+ const { mockUseGetAgentByIdQuery, mockUpdateAgent } = setupMocks();+ mockAgentQuery(mockUseGetAgentByIdQuery, { instructionsPrompt: null });+ mockFormDefaults = { instructionsSource: 'inline', instructionsPrompt: null };+ mockUpdateAgent.mockResolvedValueOnce(createMockAgent({ instructionsPrompt: link }));+ const { container, rerender } = render(<AgentPanel />, { wrapper: createWrapper() });+ act(() => {+ capturedFormMethods!.register('instructionsSource');+ capturedFormMethods!.register('instructionsPrompt');+ capturedFormMethods!.setValue('instructionsSource', 'prompt', { shouldDirty: true });+ capturedFormMethods!.setValue('instructionsPrompt', link, { shouldDirty: true });+ });+ fireEvent.submit(container.querySelector('form')!);+ await act(async () => {+ mockFormSubmitHandler?.();+ });+ await waitFor(() => expect(mockShowToast).toHaveBeenCalled());+ const restored = { ...link, groupId: 'restored-group' };+ mockAgentQuery(mockUseGetAgentByIdQuery, { instructionsPrompt: restored });+ act(() => {+ capturedFormMethods!.reset(+ { ...capturedFormMethods!.getValues(), instructionsPrompt: restored },+ { keepDirtyValues: true },+ );+ });+ rerender(<AgentPanel />);+ expect(capturedFormMethods!.getValues('instructionsPrompt')).toEqual(restored);+ mockUpdateAgent.mockResolvedValueOnce(createMockAgent({ instructionsPrompt: restored }));+ act(() => {+ capturedFormMethods!.setValue('name', 'Renamed', { shouldDirty: true });+ });+ fireEvent.submit(container.querySelector('form')!);+ await act(async () => {+ mockFormSubmitHandler?.();+ });+ await waitFor(() => expect(mockUpdateAgent).toHaveBeenCalledTimes(2));+ expect(mockUpdateAgent.mock.calls[1][0].data).not.toHaveProperty('instructionsPrompt');+ });++ it('keeps prompt edits made while a save is in flight', async () => {+ const { mockUseGetAgentByIdQuery, mockUpdateAgent } = setupMocks();+ mockAgentQuery(mockUseGetAgentByIdQuery, { instructionsPrompt: null });+ mockFormDefaults = { instructionsSource: 'inline', instructionsPrompt: null };+ let finish!: (saved: Agent) => void;+ mockUpdateAgent.mockReturnValueOnce(+ new Promise<Agent>((resolve) => {+ finish = resolve;+ }),+ );+ const { container } = render(<AgentPanel />, { wrapper: createWrapper() });+ act(() => {+ capturedFormMethods!.register('instructionsSource');+ capturedFormMethods!.register('instructionsPrompt');+ capturedFormMethods!.setValue('instructionsSource', 'prompt', { shouldDirty: true });+ capturedFormMethods!.setValue('instructionsPrompt', link, { shouldDirty: true });+ });+ fireEvent.submit(container.querySelector('form')!);+ await act(async () => {+ mockFormSubmitHandler?.();+ });+ await waitFor(() => expect(mockUpdateAgent).toHaveBeenCalledTimes(1));+ const next = { ...link, groupId: 'newer-edit' };+ act(() => {+ capturedFormMethods!.setValue('instructionsPrompt', next, { shouldDirty: true });+ });+ await act(async () => {+ finish(createMockAgent({ instructionsPrompt: link }));+ });+ expect(capturedFormMethods!.getValues('instructionsPrompt')).toEqual(next);+ expect(capturedFormMethods!.getFieldState('instructionsPrompt').isDirty).toBe(true);+ });++ it('sends the link on create after "create new" follows a linked agent picking the same group', async () => {+ /** Regression for the ref that remembers the last-loaded link: it used to update+ * only while `agentQuery.data` was truthy, so it stayed pinned to agent A's link+ * after "create new" cleared the selection (`agentQuery.data` goes back to+ * `undefined` and never becomes truthy again for "no agent"). Picking Prompt mode+ * and the same group on the new agent then read as "unchanged" against the stale+ * ref, and the create payload silently omitted the link. */+ const { mockUseGetAgentByIdQuery } = setupMocks();++ // Agent A is open, linked to group_1.+ mockAgentPanelContext = { ...mockAgentPanelContext, agent_id: 'agent-A' };+ mockAgentQuery(mockUseGetAgentByIdQuery, {+ id: 'agent-A',+ name: 'Agent A',+ version: 2,+ instructionsPrompt: link,+ });+ mockFormDefaults = {+ id: 'agent-A',+ instructionsSource: 'prompt',+ instructionsPrompt: link,+ };+ (dataService.createAgent as jest.Mock).mockResolvedValue(+ createMockAgent({ id: 'agent-new' }),+ );++ const Wrapper = createWrapper();+ const { container, rerender } = render(<AgentPanel />, { wrapper: Wrapper });++ // "Create new": no agent selected, and its query has nothing to return.+ mockAgentPanelContext = { ...mockAgentPanelContext, agent_id: undefined };+ mockUseGetAgentByIdQuery.mockReturnValue({+ data: undefined,+ isInitialLoading: false,+ } as any);+ (+ useGetExpandedAgentByIdQuery as jest.MockedFunction<typeof useGetExpandedAgentByIdQuery>+ ).mockReturnValue({ data: undefined, isInitialLoading: false } as any);+ rerender(<AgentPanel />);++ // The user fills out the new agent, picking Prompt mode and group_1 again.+ act(() => {+ capturedFormMethods!.setValue('id', '', { shouldDirty: true });+ capturedFormMethods!.setValue('name', 'New Agent', { shouldDirty: true });+ capturedFormMethods!.setValue('provider', 'openai', { shouldDirty: true });+ capturedFormMethods!.setValue('model', 'gpt-4', { shouldDirty: true });+ capturedFormMethods!.setValue('instructionsSource', 'prompt', { shouldDirty: true });+ capturedFormMethods!.setValue('instructionsPrompt', link, { shouldDirty: true });+ });++ fireEvent.submit(container.querySelector('form')!);+ await act(async () => {+ mockFormSubmitHandler?.();+ });++ await waitFor(() => expect(dataService.createAgent).toHaveBeenCalledTimes(1));+ expect((dataService.createAgent as jest.Mock).mock.calls[0][0]).toHaveProperty(+ 'instructionsPrompt',+ link,+ );+ });++ it('computes the changed flag against the newly selected agent when switching agents', async () => {+ const { mockUseGetAgentByIdQuery, mockUpdateAgent } = setupMocks();++ // Agent A is open, linked to group_1.+ mockAgentPanelContext = { ...mockAgentPanelContext, agent_id: 'agent-A' };+ mockAgentQuery(mockUseGetAgentByIdQuery, {+ id: 'agent-A',+ name: 'Agent A',+ version: 2,+ instructionsPrompt: link,+ });+ mockFormDefaults = {+ id: 'agent-A',+ instructionsSource: 'prompt',+ instructionsPrompt: link,+ };++ const Wrapper = createWrapper();+ const { container, rerender } = render(<AgentPanel />, { wrapper: Wrapper });++ // Switch to agent B, which has no link at all.+ mockAgentPanelContext = { ...mockAgentPanelContext, agent_id: 'agent-B' };+ mockAgentQuery(mockUseGetAgentByIdQuery, {+ id: 'agent-B',+ name: 'Agent B',+ version: 1,+ instructionsPrompt: null,+ });+ rerender(<AgentPanel />);++ // Mirrors what `AgentSelect`'s `resetAgentForm` does for the newly loaded agent.+ act(() => {+ capturedFormMethods!.setValue('id', 'agent-B', { shouldDirty: false });+ capturedFormMethods!.setValue('instructionsSource', 'inline', { shouldDirty: false });+ capturedFormMethods!.setValue('instructionsPrompt', null, { shouldDirty: false });+ capturedFormMethods!.setValue('name', 'Renamed B', { shouldDirty: true });+ });++ mockUpdateAgent.mockResolvedValueOnce(+ createMockAgent({+ id: 'agent-B',+ name: 'Renamed B',+ version: 1,+ instructionsPrompt: null,+ }),+ );++ fireEvent.submit(container.querySelector('form')!);+ await act(async () => {+ mockFormSubmitHandler?.();+ });++ await waitFor(() => expect(mockUpdateAgent).toHaveBeenCalledTimes(1));+ expect(mockUpdateAgent.mock.calls[0][0].agent_id).toBe('agent-B');+ expect(mockUpdateAgent.mock.calls[0][0].data).not.toHaveProperty('instructionsPrompt');+ });++ it("withholds instructionsPrompt from a save made while the newly selected agent's expanded query is still loading", async () => {+ /** Regression: `AgentSelect`'s `instructionsPromptReady` false branch keeps the+ * form's prior link instead of clearing it, so switching to agent B while its+ * expanded query is still pending leaves the form holding agent A's link. Saving+ * any other field before that query resolves must not patch the stale link onto+ * agent B. */+ const { mockUseGetAgentByIdQuery, mockUpdateAgent } = setupMocks();+ const mockUseGetExpandedAgentByIdQuery =+ useGetExpandedAgentByIdQuery as jest.MockedFunction<typeof useGetExpandedAgentByIdQuery>;++ // Agent A is open, linked to group_1.+ mockAgentPanelContext = { ...mockAgentPanelContext, agent_id: 'agent-A' };+ mockAgentQuery(mockUseGetAgentByIdQuery, {+ id: 'agent-A',+ name: 'Agent A',+ version: 2,+ instructionsPrompt: link,+ });+ mockFormDefaults = {+ id: 'agent-A',+ instructionsSource: 'prompt',+ instructionsPrompt: link,+ };++ const Wrapper = createWrapper();+ const { container, rerender } = render(<AgentPanel />, { wrapper: Wrapper });++ // Switch to agent B: its basic query resolves but the expanded query is still pending.+ mockAgentPanelContext = { ...mockAgentPanelContext, agent_id: 'agent-B' };+ mockUseGetAgentByIdQuery.mockReturnValue({+ data: createMockAgent({ id: 'agent-B', name: 'Agent B', version: 1 }),+ isInitialLoading: false,+ } as any);+ mockUseGetExpandedAgentByIdQuery.mockReturnValue({+ data: undefined,+ isError: false,+ refetch: jest.fn(),+ } as any);+ rerender(<AgentPanel />);++ await waitFor(() => expect(mockAgentConfigStatus).toBe('loading'));++ // The form keeps agent A's link; the user edits an unrelated field and saves.+ act(() => {+ capturedFormMethods!.setValue('id', 'agent-B', { shouldDirty: false });+ capturedFormMethods!.setValue('name', 'Renamed B', { shouldDirty: true });+ });++ mockUpdateAgent.mockResolvedValueOnce(+ createMockAgent({ id: 'agent-B', name: 'Renamed B', version: 1 }),+ );++ fireEvent.submit(container.querySelector('form')!);+ await act(async () => {+ mockFormSubmitHandler?.();+ });++ await waitFor(() => expect(mockUpdateAgent).toHaveBeenCalledTimes(1));+ expect(mockUpdateAgent.mock.calls[0][0].agent_id).toBe('agent-B');+ expect(mockUpdateAgent.mock.calls[0][0].data).not.toHaveProperty('instructionsPrompt');+ });++ it("withholds instructionsPrompt from a save made while the newly selected agent's expanded query errored", async () => {+ const { mockUseGetAgentByIdQuery, mockUpdateAgent } = setupMocks();+ const mockUseGetExpandedAgentByIdQuery =+ useGetExpandedAgentByIdQuery as jest.MockedFunction<typeof useGetExpandedAgentByIdQuery>;++ // Agent A is open, linked to group_1.+ mockAgentPanelContext = { ...mockAgentPanelContext, agent_id: 'agent-A' };+ mockAgentQuery(mockUseGetAgentByIdQuery, {+ id: 'agent-A',+ name: 'Agent A',+ version: 2,+ instructionsPrompt: link,+ });+ mockFormDefaults = {+ id: 'agent-A',+ instructionsSource: 'prompt',+ instructionsPrompt: link,+ };++ const Wrapper = createWrapper();+ const { container, rerender } = render(<AgentPanel />, { wrapper: Wrapper });++ // Switch to agent B: its expanded query fails outright.+ mockAgentPanelContext = { ...mockAgentPanelContext, agent_id: 'agent-B' };+ mockUseGetAgentByIdQuery.mockReturnValue({+ data: createMockAgent({ id: 'agent-B', name: 'Agent B', version: 1 }),+ isInitialLoading: false,+ } as any);+ mockUseGetExpandedAgentByIdQuery.mockReturnValue({+ data: undefined,+ isError: true,+ refetch: jest.fn(),+ } as any);+ rerender(<AgentPanel />);++ await waitFor(() => expect(mockAgentConfigStatus).toBe('error'));++ act(() => {+ capturedFormMethods!.setValue('id', 'agent-B', { shouldDirty: false });+ capturedFormMethods!.setValue('name', 'Renamed B', { shouldDirty: true });+ });++ mockUpdateAgent.mockResolvedValueOnce(+ createMockAgent({ id: 'agent-B', name: 'Renamed B', version: 1 }),+ );++ fireEvent.submit(container.querySelector('form')!);+ await act(async () => {+ mockFormSubmitHandler?.();+ });++ await waitFor(() => expect(mockUpdateAgent).toHaveBeenCalledTimes(1));+ expect(mockUpdateAgent.mock.calls[0][0].agent_id).toBe('agent-B');+ expect(mockUpdateAgent.mock.calls[0][0].data).not.toHaveProperty('instructionsPrompt');+ });++ it('sends instructionsPrompt once the expanded query is ready and the link actually changed', async () => {+ const { mockUseGetAgentByIdQuery, mockUpdateAgent } = setupMocks();++ mockAgentQuery(mockUseGetAgentByIdQuery, {+ name: 'Test Agent',+ version: 2,+ instructionsPrompt: null,+ });+ mockFormDefaults = { instructionsSource: 'inline', instructionsPrompt: null };++ mockUpdateAgent.mockResolvedValueOnce(+ createMockAgent({ name: 'Test Agent', version: 2, instructionsPrompt: link }),+ );++ const Wrapper = createWrapper();+ const { container } = render(<AgentPanel />, { wrapper: Wrapper });++ await waitFor(() => expect(mockAgentConfigStatus).toBe('ready'));++ act(() => {+ capturedFormMethods!.setValue('instructionsSource', 'prompt', { shouldDirty: true });+ capturedFormMethods!.setValue('instructionsPrompt', link, { shouldDirty: true });+ });++ fireEvent.submit(container.querySelector('form')!);+ await act(async () => {+ mockFormSubmitHandler?.();+ });++ await waitFor(() => expect(mockUpdateAgent).toHaveBeenCalledTimes(1));+ expect(mockUpdateAgent.mock.calls[0][0].data).toHaveProperty('instructionsPrompt', link);+ });++ describe('a restricted stub the editor cannot VIEW', () => {+ const stub = { source: 'native' as const, restricted: true as const };++ it('sends instructionsPrompt: null when switched to Inline', async () => {+ const { mockUseGetAgentByIdQuery, mockUpdateAgent } = setupMocks();++ mockAgentQuery(mockUseGetAgentByIdQuery, {+ name: 'Test Agent',+ version: 2,+ instructionsPrompt: stub,+ });+ mockFormDefaults = { instructionsSource: 'prompt', instructionsPrompt: stub };++ mockUpdateAgent.mockResolvedValueOnce(+ createMockAgent({ name: 'Test Agent', version: 2, instructionsPrompt: null }),+ );++ const Wrapper = createWrapper();+ const { container } = render(<AgentPanel />, { wrapper: Wrapper });++ await waitFor(() => expect(mockAgentConfigStatus).toBe('ready'));++ act(() => {+ capturedFormMethods!.setValue('instructionsSource', 'inline', { shouldDirty: true });+ });++ fireEvent.submit(container.querySelector('form')!);+ await act(async () => {+ mockFormSubmitHandler?.();+ });++ await waitFor(() => expect(mockUpdateAgent).toHaveBeenCalledTimes(1));+ expect(mockUpdateAgent.mock.calls[0][0].data).toHaveProperty('instructionsPrompt', null);+ });++ it('omits instructionsPrompt when kept and an unrelated field is edited', async () => {+ const { mockUseGetAgentByIdQuery, mockUpdateAgent } = setupMocks();++ mockAgentQuery(mockUseGetAgentByIdQuery, {+ name: 'Test Agent',+ version: 2,+ instructionsPrompt: stub,+ });+ mockFormDefaults = { instructionsSource: 'prompt', instructionsPrompt: stub };++ mockUpdateAgent.mockResolvedValueOnce(+ createMockAgent({ name: 'Renamed Agent', version: 2, instructionsPrompt: stub }),+ );++ const Wrapper = createWrapper();+ const { container } = render(<AgentPanel />, { wrapper: Wrapper });++ await waitFor(() => expect(mockAgentConfigStatus).toBe('ready'));++ act(() => {+ capturedFormMethods!.setValue('name', 'Renamed Agent', { shouldDirty: true });+ });++ fireEvent.submit(container.querySelector('form')!);+ await act(async () => {+ mockFormSubmitHandler?.();+ });++ await waitFor(() => expect(mockUpdateAgent).toHaveBeenCalledTimes(1));+ expect(mockUpdateAgent.mock.calls[0][0].data).not.toHaveProperty('instructionsPrompt');+ });++ it('sends the new link when replaced with a different group', async () => {+ const { mockUseGetAgentByIdQuery, mockUpdateAgent } = setupMocks();++ mockAgentQuery(mockUseGetAgentByIdQuery, {+ name: 'Test Agent',+ version: 2,+ instructionsPrompt: stub,+ });+ mockFormDefaults = { instructionsSource: 'prompt', instructionsPrompt: stub };++ mockUpdateAgent.mockResolvedValueOnce(+ createMockAgent({ name: 'Test Agent', version: 2, instructionsPrompt: link }),+ );++ const Wrapper = createWrapper();+ const { container } = render(<AgentPanel />, { wrapper: Wrapper });++ await waitFor(() => expect(mockAgentConfigStatus).toBe('ready'));++ act(() => {+ capturedFormMethods!.setValue('instructionsPrompt', link, { shouldDirty: true });+ });++ fireEvent.submit(container.querySelector('form')!);+ await act(async () => {+ mockFormSubmitHandler?.();+ });++ await waitFor(() => expect(mockUpdateAgent).toHaveBeenCalledTimes(1));+ expect(mockUpdateAgent.mock.calls[0][0].data).toHaveProperty('instructionsPrompt', link);+ });+ });+ });});});diff --git a/client/src/components/SidePanel/Agents/AgentPanel.tsx b/client/src/components/SidePanel/Agents/AgentPanel.tsxindex 95223c5332..2ff258593c 100644--- a/client/src/components/SidePanel/Agents/AgentPanel.tsx+++ b/client/src/components/SidePanel/Agents/AgentPanel.tsx@@ -18,6 +18,7 @@ import {} from 'librechat-data-provider';import type { Agent, AgentUpdateParams } from 'librechat-data-provider';import type { FieldNamesMarkedBoolean } from 'react-hook-form';+import type { InstructionsPromptStatus } from './Instructions';import type { TranslationKeys } from '~/hooks/useLocalize';import type { AgentParameterConfig } from './parameters';import type { AgentForm, StringOption } from '~/common';@@ -28,6 +29,11 @@ import {useGetExpandedAgentByIdQuery,useUploadAgentAvatarMutation,} from '~/data-provider';+import {+ isRestrictedInstructionsPrompt,+ getInstructionsPromptErrorCode,+ instructionsPromptErrorKeys,+} from './instructionsPromptUtils';import {createProviderOption,getAvailableAgentSelection,@@ -120,18 +126,28 @@ export function isSavedAgentOption(* Handles avatar reset requests for persistent agents independently of avatar uploads.* @param {AgentForm} data - Form data from the agent configuration form.* @param {string | null} [agent_id] - Agent identifier, if the agent already exists.+ * @param {AgentParameterConfig} [parameterConfig] - Model parameter schema context.+ * @param {{ instructionsPromptChanged: boolean }} flags - Whether the linked-prompt+ * selection changed, so an update sends the field only on an actual edit. Required,+ * with no default, so a caller can never silently overwrite a stored link. A create+ * (no `agent_id`) always sends the resolved link regardless of this flag: there is no+ * stored value to diff against, and the new agent must not end up unlinked just+ * because the selection happens to match whatever agent was last open in the panel.* @returns {{ payload: Partial<AgentForm>; provider: string; model: string }} Payload metadata.*/export function composeAgentUpdatePayload(data: AgentForm,- agent_id?: string | null,- parameterConfig?: AgentParameterConfig,+ agent_id: string | null | undefined,+ parameterConfig: AgentParameterConfig | undefined,+ flags: { instructionsPromptChanged: boolean },) {const {name,artifacts,description,instructions,+ instructionsSource,+ instructionsPrompt,model: _model,model_parameters: currentModelParameters,provider: _provider,@@ -160,6 +176,16 @@ export function composeAgentUpdatePayload(avatar_action: avatarActionState,} = data;+ /** Never re-sends the restricted stub; a real link only exists in `'prompt'` mode. */+ const resolvedInstructionsPrompt =+ instructionsSource === 'prompt' && !isRestrictedInstructionsPrompt(instructionsPrompt)+ ? (instructionsPrompt ?? null)+ : null;+ /** A create has no stored link to diff against, so it always carries the resolved+ * value; an update sends it only when `flags.instructionsPromptChanged` says the+ * selection actually moved. */+ const sendInstructionsPrompt = !agent_id || flags.instructionsPromptChanged;+/* stateful_code_sessions requires Code Interpreter; force it off on save when* execute_code is disabled so a stale opt-in can't silently reactivate later. */const normalizedStatefulCodeSessions =@@ -206,6 +232,7 @@ export function composeAgentUpdatePayload(artifacts,description,instructions,+ ...(sendInstructionsPrompt ? { instructionsPrompt: resolvedInstructionsPrompt } : {}),model,provider,model_parameters,@@ -248,6 +275,49 @@ export function composeAgentUpdatePayload(} as const;}+/**+ * Resolves the linked-prompt value a submission would actually send: `null` in+ * inline mode or for a restricted stub, otherwise the link. Mirrors+ * `resolvedInstructionsPrompt` in `composeAgentUpdatePayload`, so callers on both+ * sides of an equality check agree on what "no editable link" means.+ */+const resolveInstructionsPromptLink = (+ source: AgentForm['instructionsSource'],+ prompt: AgentForm['instructionsPrompt'],+): AgentForm['instructionsPrompt'] =>+ source === 'prompt' && !isRestrictedInstructionsPrompt(prompt) ? (prompt ?? null) : null;++/**+ * Whether the form's linked-prompt selection differs from the agent last loaded from+ * the server, so a save sends `instructionsPrompt` only on an actual edit. Compares+ * resolved links rather than `dirtyFields.instructionsPrompt`: a post-save+ * `reset(..., { keepDirtyValues: true })` can leave that field dirty even though its+ * value already matches what was just persisted, which would resend the link on the+ * next unrelated save and risk overwriting a concurrent change to it.+ */+export function computeInstructionsPromptChanged(+ formSource: AgentForm['instructionsSource'],+ formPrompt: AgentForm['instructionsPrompt'],+ lastLoadedPrompt: AgentForm['instructionsPrompt'] | null | undefined,+): boolean {+ /** `resolveInstructionsPromptLink` collapses both a restricted stub and inline mode+ * to `null`, so diffing resolved values can't tell "still the stub" apart from+ * "switched to Inline" when the loaded link was a stub — both resolve to `null` on+ * the current side. Settle that case directly: it's changed when the form switched+ * to Inline (the removal must still reach the save) or now holds a real link. */+ if (isRestrictedInstructionsPrompt(lastLoadedPrompt)) {+ return (+ formSource === 'inline' || (formPrompt != null && !isRestrictedInstructionsPrompt(formPrompt))+ );+ }+ const current = resolveInstructionsPromptLink(formSource, formPrompt);+ const stored = resolveInstructionsPromptLink(+ lastLoadedPrompt != null ? 'prompt' : 'inline',+ lastLoadedPrompt ?? null,+ );+ return !isEqual(current, stored);+}+type UploadAvatarFn = (variables: { agent_id: string; formData: FormData }) => Promise<Agent>;export interface PersistAvatarChangesParams {@@ -422,12 +492,28 @@ export default function AgentPanel() {);const canEdit = hasPermission(PermissionBits.EDIT);+ /** Same editor-visibility bypass `canEditAgent` grants admins below: an admin can open+ * the editor for a linked agent even without ACL EDIT on it. */+ const hasEditorAccess = canEdit || user?.role === SystemRoles.ADMIN;const expandedAgentQuery = useGetExpandedAgentByIdQuery(current_agent_id ?? '', {- enabled: !isEphemeralAgent(current_agent_id) && canEdit && !permissionsLoading,+ enabled: !isEphemeralAgent(current_agent_id) && hasEditorAccess && !permissionsLoading,});- const agentQuery = canEdit && expandedAgentQuery.data ? expandedAgentQuery : basicAgentQuery;+ const agentQuery =+ hasEditorAccess && expandedAgentQuery.data ? expandedAgentQuery : basicAgentQuery;++ const isPersistedAgent = Boolean(current_agent_id) && !isEphemeralAgent(current_agent_id);+ /** `instructionsPrompt` only ever arrives on the expanded query. A persisted,+ * editable agent stays in a disabled loading (or error) state here until that+ * query resolves, instead of briefly reading a linked agent as unlinked. */+ let instructionsPromptStatus: InstructionsPromptStatus = 'ready';+ if (isPersistedAgent && hasEditorAccess && !expandedAgentQuery.data) {+ instructionsPromptStatus = expandedAgentQuery.isError ? 'error' : 'loading';+ }+ const retryInstructionsPrompt = useCallback(() => {+ expandedAgentQuery.refetch();+ }, [expandedAgentQuery]);const modelsReady = modelsQuery.isFetchedAfterMount && !modelsQuery.isFetching;const modelsError = modelsQuery.isFetchedAfterMount && !modelsQuery.isSuccess;@@ -453,6 +539,34 @@ export default function AgentPanel() {formState: { dirtyFields },} = methods;const submittedStartersRef = useRef<SubmittedStarters | null>(null);+ const submittedInstructionsRef = useRef<{+ agentId: string;+ source: AgentForm['instructionsSource'];+ link: AgentForm['instructionsPrompt'];+ } | null>(null);+ const syncSavedInstructions = useCallback(+ (saved: Agent) => {+ const submitted = submittedInstructionsRef.current;+ submittedInstructionsRef.current = null;+ if (!submitted) {+ return;+ }+ const currentId = getValues('id') ?? '';+ const sameAgent =+ currentId === submitted.agentId || (!submitted.agentId && currentId === saved.id);+ if (+ !sameAgent ||+ getValues('instructionsSource') !== submitted.source ||+ !isEqual(getValues('instructionsPrompt') ?? null, submitted.link ?? null)+ ) {+ return;+ }+ const link = saved.instructionsPrompt ?? null;+ resetField('instructionsPrompt', { defaultValue: link });+ resetField('instructionsSource', { defaultValue: link == null ? 'inline' : 'prompt' });+ },+ [getValues, resetField],+ );/** The save may trim or drop starters; show what was stored, not what was typed. */const syncSavedStarters = useCallback((saved: Agent) => {@@ -518,6 +632,32 @@ export default function AgentPanel() {const previousVersionRef = useRef<number | undefined>();const submittedDirtyRef = useRef(false);const submittedRef = useRef<{ payload?: AgentUpdateParams; previous?: Agent }>({});+ /** The linked-prompt selection last seen from the server, compared against the form's+ * current value to decide whether a save carries an actual edit (see+ * `computeInstructionsPromptChanged`). `AgentSelect`'s post-save `reset(..., {+ * keepDirtyValues: true })` can leave `dirtyFields.instructionsPrompt` true even after+ * the field's value again matches what was just persisted, so `dirtyFields` alone+ * cannot answer "did this save change the link" without risking a stale resend that+ * overwrites a concurrent edit. */+ const lastLoadedInstructionsPromptRef = useRef<AgentForm['instructionsPrompt']>(null);+ /** Clears the remembered link the moment the selected agent changes, including a+ * switch to "create new" (`current_agent_id` becomes `undefined`). Without this, a+ * stale ref from the previously open agent survives the switch, `agentQuery.data`+ * never turns truthy again for the id that's gone, and the effect below never gets a+ * chance to correct it, so a new agent linked to the same group as the old one reads+ * as "unchanged" and the link is dropped from the create payload. */+ useEffect(() => {+ lastLoadedInstructionsPromptRef.current = null;+ }, [current_agent_id]);+ useEffect(() => {+ /** Only a 'ready' status carries data that can speak to the link: the expanded+ * query resolved, or editor access doesn't apply and the basic query is all+ * there is. A pending or failed expanded query must not overwrite the ref with+ * the basic projection's `undefined`. */+ if (instructionsPromptStatus === 'ready' && agentQuery.data) {+ lastLoadedInstructionsPromptRef.current = agentQuery.data.instructionsPrompt ?? null;+ }+ }, [agentQuery.data, instructionsPromptStatus]);const allowedProviders = useMemo(() => new Set(agentsConfig?.allowedProviders),@@ -620,6 +760,7 @@ export default function AgentPanel() {showToast({ message: toastMessage, status: noVersionChange ? 'info' : undefined });}+ syncSavedInstructions(data);syncSavedStarters(data);const agentOption = getValues('agent');@@ -649,6 +790,14 @@ export default function AgentPanel() {submittedRef.current = {};},onError: (err) => {+ const instructionsPromptErrorCode = getInstructionsPromptErrorCode(err);+ if (instructionsPromptErrorCode) {+ showToast({+ message: localize(instructionsPromptErrorKeys[instructionsPromptErrorCode]),+ status: 'error',+ });+ return;+ }const error = err as Error;showToast({message: `${localize('com_agents_update_error')}${@@ -661,6 +810,7 @@ export default function AgentPanel() {const create = useCreateAgentMutation({onSuccess: async (data) => {+ syncSavedInstructions(data);syncSavedStarters(data);setCurrentAgentId(data.id);showToast({@@ -680,6 +830,14 @@ export default function AgentPanel() {}},onError: (err) => {+ const instructionsPromptErrorCode = getInstructionsPromptErrorCode(err);+ if (instructionsPromptErrorCode) {+ showToast({+ message: localize(instructionsPromptErrorKeys[instructionsPromptErrorCode]),+ status: 'error',+ });+ return;+ }const error = err as Error;showToast({message: `${localize('com_agents_create_error')}${@@ -694,14 +852,28 @@ export default function AgentPanel() {async (data: AgentForm) => {const tools = Array.from(new Set([...(data.tools ?? []), ...resolveCapabilityTools(data)]));+ /** A persisted agent whose expanded query hasn't resolved (or failed) carries no+ * trustworthy link to diff against: the form may still hold the previously+ * selected agent's link (see `AgentSelect`). Force the flag false so the save+ * cannot patch that stale link onto this agent; other fields still save. */+ const instructionsPromptChanged =+ agent_id && instructionsPromptStatus !== 'ready'+ ? false+ : computeInstructionsPromptChanged(+ data.instructionsSource,+ data.instructionsPrompt,+ lastLoadedInstructionsPromptRef.current,+ );const {payload: basePayload,provider,model,- } = composeAgentUpdatePayload(data, agent_id, {- endpointsConfig,- startupConfig,- });+ } = composeAgentUpdatePayload(+ data,+ agent_id,+ { endpointsConfig, startupConfig },+ { instructionsPromptChanged },+ );if (agent_id) {if (data.avatar_action === 'upload' && isAvatarUploadOnlyDirty(dirtyFields)) {@@ -722,6 +894,10 @@ export default function AgentPanel() {}return;}+ submittedInstructionsRef.current =+ 'instructionsPrompt' in basePayload+ ? { agentId: agent_id, source: data.instructionsSource, link: data.instructionsPrompt }+ : null;submittedStartersRef.current = { agentId: agent_id, starters: data.conversation_starters };update.mutate({ agent_id, data: { ...basePayload, tools } });return;@@ -752,6 +928,11 @@ export default function AgentPanel() {});}+ submittedInstructionsRef.current = {+ agentId: '',+ source: data.instructionsSource,+ link: data.instructionsPrompt,+ };submittedStartersRef.current = { agentId: '', starters: data.conversation_starters };create.mutate({...basePayload,@@ -768,6 +949,7 @@ export default function AgentPanel() {dirtyFields,endpointsConfig,handleAvatarUpload,+ instructionsPromptStatus,models,modelsError,modelsReady,@@ -789,12 +971,8 @@ export default function AgentPanel() {return true;}- if (user?.role === SystemRoles.ADMIN) {- return true;- }-- return canEdit;- }, [agentQuery.data?.id, user?.role, canEdit]);+ return hasEditorAccess;+ }, [agentQuery.data?.id, hasEditorAccess]);return (<FormProvider {...methods}>@@ -812,6 +990,7 @@ export default function AgentPanel() {setCurrentAgentId={setCurrentAgentId}selectedAgentId={agentQuery.isInitialLoading ? null : (current_agent_id ?? null)}defaultStatefulCodeEnvironment={defaultStatefulCodeEnvironment}+ instructionsPromptReady={instructionsPromptStatus === 'ready'}/></div>{agent_id && (@@ -866,7 +1045,10 @@ export default function AgentPanel() {/>)}{canEditAgent && !agentQuery.isInitialLoading && activePanel === Panel.builder && (- <AgentConfig />+ <AgentConfig+ instructionsPromptStatus={instructionsPromptStatus}+ onRetryInstructionsPrompt={retryInstructionsPrompt}+ />)}{canEditAgent && !agentQuery.isInitialLoading && activePanel === Panel.advanced && (<AdvancedPanel />diff --git a/client/src/components/SidePanel/Agents/AgentSelect.tsx b/client/src/components/SidePanel/Agents/AgentSelect.tsxindex 4081cf40b0..5bb58798bb 100644--- a/client/src/components/SidePanel/Agents/AgentSelect.tsx+++ b/client/src/components/SidePanel/Agents/AgentSelect.tsx@@ -28,12 +28,18 @@ function AgentSelect({setCurrentAgentId,createMutation,defaultStatefulCodeEnvironment,+ instructionsPromptReady = true,}: {selectedAgentId: string | null;agentQuery: QueryObserverResult<Agent>;setCurrentAgentId: React.Dispatch<React.SetStateAction<string | undefined>>;createMutation: UseMutationResult<Agent, Error, AgentCreateParams>;defaultStatefulCodeEnvironment: StatefulCodeEnvironment;+ /** Whether `agentQuery.data` is the expanded agent (the only source of+ * `instructionsPrompt`) rather than the basic projection, which never carries it.+ * `false` keeps the form's existing instructions-source/-prompt values instead of+ * reading a linked agent as unlinked while the expanded query is still loading. */+ instructionsPromptReady?: boolean;}) {const localize = useLocalize();const lastSelectedAgent = useRef<string | null>(null);@@ -98,6 +104,19 @@ function AgentSelect({agentTools.push(tool);});+ /** The basic projection never carries `instructionsPrompt`, so deriving from it+ * here would read a linked agent as unlinked until the expanded query resolves.+ * Keep whatever the form already has until then. */+ let resolvedInstructionsPrompt: AgentForm['instructionsPrompt'];+ let resolvedInstructionsSource: AgentForm['instructionsSource'];+ if (instructionsPromptReady) {+ resolvedInstructionsPrompt = fullAgent.instructionsPrompt ?? null;+ resolvedInstructionsSource = resolvedInstructionsPrompt != null ? 'prompt' : 'inline';+ } else {+ resolvedInstructionsPrompt = getValues('instructionsPrompt');+ resolvedInstructionsSource = getValues('instructionsSource');+ }+const formValues: Partial<AgentForm & TAgentCapabilities> = {...capabilities,agent: update,@@ -118,6 +137,8 @@ function AgentSelect({repositoryInstructions: fullAgent.repositoryInstructions,code_workspace_id: fullAgent.code_workspace_id,git_identity: fullAgent.git_identity,+ instructionsSource: resolvedInstructionsSource,+ instructionsPrompt: resolvedInstructionsPrompt,};Object.entries(fullAgent).forEach(([name, value]) => {@@ -212,7 +233,7 @@ function AgentSelect({setValue('tools', mergedDirtyTools, { shouldDirty: true });}},- [getValues, reset, setValue],+ [getValues, reset, setValue, instructionsPromptReady],);const onSelect = useCallback(@@ -323,7 +344,8 @@ const MemoizedAgentSelect = memo(prevProps.agentQuery.data === nextProps.agentQuery.data &&prevProps.agentQuery.isSuccess === nextProps.agentQuery.isSuccess &&prevProps.createMutation.data?.id === nextProps.createMutation.data?.id &&- prevProps.createMutation.isLoading === nextProps.createMutation.isLoading,+ prevProps.createMutation.isLoading === nextProps.createMutation.isLoading &&+ prevProps.instructionsPromptReady === nextProps.instructionsPromptReady,);MemoizedAgentSelect.displayName = 'AgentSelect';diff --git a/client/src/components/SidePanel/Agents/Instructions.tsx b/client/src/components/SidePanel/Agents/Instructions.tsxindex 40646863b9..cb1d84c82d 100644--- a/client/src/components/SidePanel/Agents/Instructions.tsx+++ b/client/src/components/SidePanel/Agents/Instructions.tsx@@ -1,42 +1,137 @@-import { Controller, useFormContext } from 'react-hook-form';+import { Button, Label } from '@librechat/client';+import { Controller, useWatch, useFormContext } from 'react-hook-form';import type { AgentForm } from '~/common';+import InstructionsPromptFields, { fieldWrapperClass, LoadError } from './InstructionsPromptFields';+import { isRestrictedInstructionsPrompt } from './instructionsPromptUtils';+import RestrictedInstructionsPrompt from './RestrictedInstructionsPrompt';import { VariableEditor } from '~/components/Variables';import { useLocalize } from '~/hooks';+import { cn } from '~/utils';-export default function Instructions() {+/** Status of the expanded agent query that `instructionsPrompt` arrives on. A+ * persisted agent's basic projection never carries `instructionsPrompt`, so this+ * section stays in a disabled loading (or error) state until the expanded query+ * resolves, rather than briefly reading the link as absent. */+export type InstructionsPromptStatus = 'ready' | 'loading' | 'error';++/** Two-way segmented toggle between the inline editor and a linked prompt group. */+function SourceToggle({ disabled = false }: { disabled?: boolean }) {const localize = useLocalize();const { control } = useFormContext<AgentForm>();return (<Controller- name="instructions"+ name="instructionsSource"control={control}- render={({ field, fieldState: { error } }) => (- <div className="mb-3 flex flex-col">- <VariableEditor- id="instructions"- label={localize('com_ui_instructions')}- value={field.value ?? ''}- onChange={field.onChange}- onBlur={field.onBlur}- inputRef={field.ref}- placeholder={localize('com_agents_instructions_placeholder')}- className="min-h-[5.5rem] resize-y"- labelClassName="block text-[11px] font-medium uppercase tracking-wide text-text-secondary"- rows={3}- required={true}- invalid={error != null}- />- {error && (- <span- className="text-text-destructive mt-1 text-xs transition duration-300 ease-in-out"- role="alert"- >- {localize('com_ui_field_required')}- </span>- )}+ render={({ field }) => (+ <div+ role="group"+ aria-label={localize('com_agents_instructions_source_toggle_aria')}+ className="border-border-light bg-surface-primary inline-flex w-fit gap-1 rounded-lg border p-0.5"+ >+ <Button+ type="button"+ variant={field.value === 'inline' ? 'secondary' : 'ghost'}+ size="sm"+ aria-pressed={field.value === 'inline'}+ disabled={disabled}+ onClick={() => field.onChange('inline')}+ >+ {localize('com_agents_instructions_source_inline')}+ </Button>+ <Button+ type="button"+ variant={field.value === 'prompt' ? 'secondary' : 'ghost'}+ size="sm"+ aria-pressed={field.value === 'prompt'}+ disabled={disabled}+ onClick={() => field.onChange('prompt')}+ >+ {localize('com_agents_instructions_source_prompt')}+ </Button></div>)}/>);}++export default function Instructions({+ promptStatus = 'ready',+ onRetryLoad,+}: {+ promptStatus?: InstructionsPromptStatus;+ onRetryLoad?: () => void;+}) {+ const localize = useLocalize();+ const { control } = useFormContext<AgentForm>();+ const instructionsSource = useWatch({ control, name: 'instructionsSource' });+ const instructionsPrompt = useWatch({ control, name: 'instructionsPrompt' });+ const restricted = isRestrictedInstructionsPrompt(instructionsPrompt);+ const isPromptMode = instructionsSource === 'prompt';+ const isReady = promptStatus === 'ready';++ return (+ <div className="mb-3 flex flex-col gap-2">+ <div className="flex items-center justify-between gap-3">+ <Label variant="section" data-testid="instructions-heading">+ {localize('com_ui_instructions')}+ </Label>+ <SourceToggle disabled={!isReady} />+ </div>++ {/* The expanded agent query (the only source of `instructionsPrompt`) has not+ * resolved yet: nothing here is derived from the basic projection, which would+ * otherwise read a linked agent as unlinked. The toggle stays disabled above so+ * a save cannot carry an instructions change until the real link is known. */}+ {!isReady && promptStatus === 'error' && (+ <LoadError forbidden={false} onRetry={onRetryLoad ?? (() => {})} />+ )}+ {!isReady && promptStatus !== 'error' && (+ <div className={fieldWrapperClass}>{localize('com_ui_loading')}</div>+ )}++ {isReady && isPromptMode && (+ <>+ <InstructionsPromptFields />+ {restricted && <RestrictedInstructionsPrompt />}+ </>+ )}++ {isReady && (+ <Controller+ name="instructions"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <div+ data-testid="instructions-inline-panel"+ className={cn('flex flex-col', isPromptMode && 'hidden')}+ >+ <VariableEditor+ id="instructions"+ label={localize('com_ui_instructions')}+ value={field.value ?? ''}+ onChange={field.onChange}+ onBlur={field.onBlur}+ inputRef={field.ref}+ placeholder={localize('com_agents_instructions_placeholder')}+ className="min-h-[5.5rem] resize-y"+ labelClassName="sr-only"+ rows={3}+ required={!isPromptMode}+ invalid={error != null}+ />+ {error && (+ <span+ className="text-text-destructive mt-1 text-xs transition duration-300 ease-in-out"+ role="alert"+ >+ {localize('com_ui_field_required')}+ </span>+ )}+ </div>+ )}+ />+ )}+ </div>+ );+}diff --git a/client/src/components/SidePanel/Agents/InstructionsPromptFields.tsx b/client/src/components/SidePanel/Agents/InstructionsPromptFields.tsxnew file mode 100644index 0000000000..cb2c66d226--- /dev/null+++ b/client/src/components/SidePanel/Agents/InstructionsPromptFields.tsx@@ -0,0 +1,253 @@+import { useMemo } from 'react';+import { Controller, useFormContext } from 'react-hook-form';+import { Button, Label, ControlCombobox } from '@librechat/client';+import type { AgentInstructionsPromptSelection } from 'librechat-data-provider';+import type { ReactNode } from 'react';+import type { AgentForm } from '~/common';+import {+ buildPromptVersionOptions,+ isRestrictedInstructionsPrompt,+ getHttpStatus,+} from './instructionsPromptUtils';+import { useGetAllPromptGroups, useGetPrompts } from '~/data-provider';+import { useLocalize } from '~/hooks';++export const fieldWrapperClass =+ 'flex h-9 items-center rounded-lg border border-border-light bg-surface-secondary px-3 text-sm text-text-secondary';++export function LoadError({ forbidden, onRetry }: { forbidden: boolean; onRetry: () => void }) {+ const localize = useLocalize();+ return (+ <div className="border-border-light bg-surface-secondary text-text-secondary flex flex-col gap-1.5 rounded-lg border px-3 py-2 text-sm">+ <span role="alert">+ {forbidden+ ? localize('com_agents_instructions_prompt_forbidden')+ : localize('com_agents_instructions_prompt_load_error')}+ </span>+ {!forbidden && (+ <Button type="button" variant="outline" size="sm" className="w-fit" onClick={onRetry}>+ {localize('com_ui_retry')}+ </Button>+ )}+ </div>+ );+}++function VersionSelect({+ groupId,+ productionId,+ selection,+ onSelect,+}: {+ groupId: string;+ productionId?: string | null;+ selection?: AgentInstructionsPromptSelection;+ onSelect: (selection: AgentInstructionsPromptSelection) => void;+}) {+ const localize = useLocalize();+ const promptsQuery = useGetPrompts({ groupId }, { enabled: groupId !== '' });+ const promptsData = promptsQuery.data;+ const prompts = useMemo(() => (Array.isArray(promptsData) ? promptsData : []), [promptsData]);+ const options = useMemo(+ () => buildPromptVersionOptions(prompts, productionId, localize),+ [prompts, productionId, localize],+ );+ const selectedValue = selection?.type === 'exact' ? selection.promptId : 'production';+ const selectedOption = options.find((option) => option.value === selectedValue);++ let content: ReactNode;+ if (groupId === '') {+ content = (+ <div className={fieldWrapperClass}>+ {localize('com_agents_instructions_prompt_version_placeholder')}+ </div>+ );+ } else if (promptsQuery.isLoading) {+ content = <div className={fieldWrapperClass}>{localize('com_ui_loading')}</div>;+ } else if (promptsQuery.isError || !Array.isArray(promptsQuery.data)) {+ content = (+ <LoadError+ forbidden={getHttpStatus(promptsQuery.error) === 403}+ onRetry={() => promptsQuery.refetch()}+ />+ );+ } else if (prompts.length === 0) {+ content = (+ <div className={fieldWrapperClass}>{localize('com_agents_instructions_prompt_empty')}</div>+ );+ } else {+ content = (+ <ControlCombobox+ selectId="instructions-prompt-version"+ selectedValue={selectedValue}+ displayValue={selectedOption?.label ?? ''}+ selectPlaceholder={localize('com_agents_instructions_prompt_version_select_placeholder')}+ setValue={(value) => {+ const option = options.find((item) => item.value === value);+ if (option) {+ onSelect(option.selection);+ }+ }}+ items={options}+ ariaLabel={localize('com_agents_instructions_prompt_version_label')}+ isCollapsed={false}+ showCarat={true}+ variant="field"+ />+ );+ }++ return (+ <div className="flex min-w-0 flex-col">+ <Label id="instructions-prompt-version-label" variant="section" className="mb-1 block">+ {localize('com_agents_instructions_prompt_version_label')}+ </Label>+ {/* `aria-labelledby`, not `htmlFor`, because the loading/error/empty states+ * render a plain `div`, not the combobox `id` a `for` would need to target. */}+ <div role="group" aria-labelledby="instructions-prompt-version-label">+ {content}+ </div>+ </div>+ );+}++/**+ * Prompt + Version dropdown row shown in "Prompt" instructions mode. Reads and+ * writes the whole `instructionsPrompt` link through a single Controller, since+ * the two dropdowns jointly determine one value.+ */+export default function InstructionsPromptFields() {+ const localize = useLocalize();+ const { control } = useFormContext<AgentForm>();+ const groupsQuery = useGetAllPromptGroups();+ /** The endpoint can answer a 200 with `{ message }` instead of an array (for example, on+ * a permission failure that does not reach `isError`); treat that the same as a load+ * failure rather than an empty prompt library. */+ const groupsData = groupsQuery.data;+ const groupsFailed = groupsQuery.isError || !Array.isArray(groupsData);+ const groups = Array.isArray(groupsData) ? groupsData : [];++ return (+ <Controller+ name="instructionsPrompt"+ control={control}+ rules={{+ validate: (value, formValues) => {+ if (formValues.instructionsSource !== 'prompt') {+ return true;+ }+ if (isRestrictedInstructionsPrompt(value)) {+ return true;+ }+ return Boolean(value?.groupId) || localize('com_agents_instructions_prompt_required');+ },+ }}+ render={({ field, fieldState: { error } }) => {+ const link =+ field.value != null && !isRestrictedInstructionsPrompt(field.value) ? field.value : null;+ const groupId = link?.groupId ?? '';+ const selectedGroup = groups.find((group) => group._id === groupId);+ /** A link that survived loading but matches no listed group: the group was+ * deleted, or the editor's share access to it was revoked. */+ const linkedGroupMissing = groupId !== '' && !groupsFailed && selectedGroup == null;+ /** The stub carries no `groupId`, so the dropdown's current value comes from+ * this label, never from a group name: nothing here reads identity off it. */+ const groupDisplayValue = isRestrictedInstructionsPrompt(field.value)+ ? localize('com_agents_instructions_prompt_restricted_title')+ : (selectedGroup?.name ?? '');++ const handleGroupChange = (nextGroupId: string) => {+ if (nextGroupId === '') {+ field.onChange(null);+ return;+ }+ field.onChange({+ source: 'native',+ groupId: nextGroupId,+ selection: { type: 'production' },+ });+ };++ let groupField: ReactNode;+ if (groupsQuery.isLoading) {+ groupField = <div className={fieldWrapperClass}>{localize('com_ui_loading')}</div>;+ } else if (groupsFailed) {+ groupField = (+ <LoadError+ forbidden={getHttpStatus(groupsQuery.error) === 403}+ onRetry={() => groupsQuery.refetch()}+ />+ );+ } else if (groups.length === 0) {+ groupField = (+ <div className={fieldWrapperClass}>+ {localize('com_agents_instructions_prompt_empty')}+ </div>+ );+ } else {+ /** A missing link still gets the combobox, not just the hint below it: the+ * backend allows removing or replacing a link to a deleted group, so the user+ * needs a way to pick a replacement (or switch to Inline) rather than being+ * stuck with prose and no control. */+ groupField = (+ <ControlCombobox+ selectId="instructions-prompt-group"+ selectedValue={groupId}+ displayValue={groupDisplayValue}+ selectPlaceholder={localize('com_agents_instructions_prompt_select_placeholder')}+ searchPlaceholder={localize('com_agents_instructions_prompt_search_placeholder')}+ setValue={handleGroupChange}+ items={groups.map((group) => ({ label: group.name, value: group._id ?? '' }))}+ ariaLabel={localize('com_ui_prompt')}+ isCollapsed={false}+ showCarat={true}+ variant="field"+ />+ );+ }++ return (+ <div className="grid grid-cols-2 gap-2">+ <div className="flex min-w-0 flex-col">+ <Label id="instructions-prompt-group-label" variant="section" className="mb-1 block">+ {localize('com_ui_prompt')}+ </Label>+ {/* `aria-labelledby`, not `htmlFor`: the loading/error/empty+ * states render a plain `div`, not the combobox `id` a `for` would need. */}+ <div role="group" aria-labelledby="instructions-prompt-group-label">+ {groupField}+ </div>+ {linkedGroupMissing && (+ <span+ className="text-text-secondary mt-1 text-xs transition duration-300 ease-in-out"+ role="note"+ >+ {localize('com_agents_instructions_prompt_not_found')}+ </span>+ )}+ {error && (+ <span+ className="text-text-destructive mt-1 text-xs transition duration-300 ease-in-out"+ role="alert"+ >+ {error.message}+ </span>+ )}+ </div>+ <VersionSelect+ groupId={groupId}+ productionId={selectedGroup?.productionId}+ selection={link?.selection}+ onSelect={(selection) => {+ if (groupId === '') {+ return;+ }+ field.onChange({ source: 'native', groupId, selection });+ }}+ />+ </div>+ );+ }}+ />+ );+}diff --git a/client/src/components/SidePanel/Agents/RestrictedInstructionsPrompt.tsx b/client/src/components/SidePanel/Agents/RestrictedInstructionsPrompt.tsxnew file mode 100644index 0000000000..daa4f0d8dd--- /dev/null+++ b/client/src/components/SidePanel/Agents/RestrictedInstructionsPrompt.tsx@@ -0,0 +1,28 @@+import { Lock } from 'lucide-react';+import { useLocalize } from '~/hooks';++/**+ * Note shown alongside the Prompt picker when the linked group is a restricted+ * stub the current editor cannot VIEW. The server strips the group identity and+ * content before it reaches this component (`{ source: 'native', restricted: true+ * }`), so nothing here can name or preview the linked prompt; the picker next to+ * it still lets the editor replace the link or switch to inline instructions.+ */+export default function RestrictedInstructionsPrompt() {+ const localize = useLocalize();++ return (+ <div+ className="border-border-light bg-surface-secondary text-text-secondary flex items-center gap-2 rounded-lg border px-3 py-2 text-sm"+ role="note"+ >+ <Lock className="h-4 w-4 flex-shrink-0" aria-hidden="true" />+ <div className="flex flex-col">+ <span className="text-text-primary font-medium">+ {localize('com_agents_instructions_prompt_restricted_title')}+ </span>+ <span>{localize('com_agents_instructions_prompt_restricted_description')}</span>+ </div>+ </div>+ );+}diff --git a/client/src/components/SidePanel/Agents/Version/VersionPanel.tsx b/client/src/components/SidePanel/Agents/Version/VersionPanel.tsxindex fc5db0ebea..d1ea7be8f7 100644--- a/client/src/components/SidePanel/Agents/Version/VersionPanel.tsx+++ b/client/src/components/SidePanel/Agents/Version/VersionPanel.tsx@@ -54,6 +54,7 @@ export default function VersionPanel() {name: agentWithVersions.name,description: agentWithVersions.description,instructions: agentWithVersions.instructions,+ instructionsPrompt: agentWithVersions.instructionsPrompt,artifacts: agentWithVersions.artifacts,capabilities: agentWithVersions.capabilities,tools: agentWithVersions.tools,diff --git a/client/src/components/SidePanel/Agents/Version/__tests__/VersionPanel.spec.tsx b/client/src/components/SidePanel/Agents/Version/__tests__/VersionPanel.spec.tsxindex 8a0c20d421..2433b0d343 100644--- a/client/src/components/SidePanel/Agents/Version/__tests__/VersionPanel.spec.tsx+++ b/client/src/components/SidePanel/Agents/Version/__tests__/VersionPanel.spec.tsx@@ -247,4 +247,155 @@ describe('VersionPanel', () => {expect.anything(),);});++ test('treats versions as different when only the linked prompt differs', () => {+ const linkA = {+ source: 'native',+ groupId: 'group-a',+ selection: { type: 'production' },+ };+ const linkB = {+ source: 'native',+ groupId: 'group-b',+ selection: { type: 'production' },+ };+ const baseVersion = {+ name: mockAgentData.name,+ description: mockAgentData.description,+ instructions: mockAgentData.instructions,+ tools: mockAgentData.tools,+ capabilities: mockAgentData.capabilities,+ edges: mockAgentData.edges,+ };++ mockUseGetExpandedAgentByIdQuery.mockReturnValueOnce({+ data: { ...mockAgentData, instructionsPrompt: linkA },+ isLoading: false,+ error: null,+ refetch: jest.fn(),+ });+ mockUseGetAgentVersionsQuery.mockReturnValueOnce({+ data: [+ { ...baseVersion, instructionsPrompt: linkA, updatedAt: '2023-01-02T00:00:00Z' },+ { ...baseVersion, instructionsPrompt: linkB, updatedAt: '2023-01-01T00:00:00Z' },+ ],+ isLoading: false,+ error: null,+ refetch: jest.fn(),+ });++ render(<VersionPanel />);+ expect(VersionContent).toHaveBeenCalledWith(+ expect.objectContaining({+ versionContext: expect.objectContaining({+ activeVersion: expect.objectContaining({ instructionsPrompt: linkA }),+ versionIds: [+ expect.objectContaining({ isActive: true }),+ expect.objectContaining({ isActive: false }),+ ],+ }),+ }),+ expect.anything(),+ );+ });++ test('shows the Current badge on whichever restricted version the server flags as matchesCurrent, even the older one after a revert', () => {+ const restrictedStub = { source: 'native', restricted: true };+ const baseVersion = {+ name: mockAgentData.name,+ description: mockAgentData.description,+ instructions: mockAgentData.instructions,+ tools: mockAgentData.tools,+ capabilities: mockAgentData.capabilities,+ edges: mockAgentData.edges,+ };++ mockUseGetExpandedAgentByIdQuery.mockReturnValueOnce({+ data: { ...mockAgentData, instructionsPrompt: { ...restrictedStub } },+ isLoading: false,+ error: null,+ refetch: jest.fn(),+ });+ mockUseGetAgentVersionsQuery.mockReturnValueOnce({+ // Raw, append order. `revertAgentVersion` `$set`s the document without+ // appending a version, so the current link can equal the *older*, not+ // latest-appended, entry — the server reflects that via `matchesCurrent`+ // on each stub rather than position.+ data: [+ {+ ...baseVersion,+ instructionsPrompt: { ...restrictedStub, matchesCurrent: true },+ updatedAt: '2023-01-01T00:00:00Z',+ },+ {+ ...baseVersion,+ instructionsPrompt: { ...restrictedStub, matchesCurrent: false },+ updatedAt: '2023-01-02T00:00:00Z',+ },+ ],+ isLoading: false,+ error: null,+ refetch: jest.fn(),+ });++ render(<VersionPanel />);+ expect(VersionContent).toHaveBeenCalledWith(+ expect.objectContaining({+ versionContext: expect.objectContaining({+ activeVersion: expect.objectContaining({+ instructionsPrompt: { ...restrictedStub, matchesCurrent: true },+ updatedAt: '2023-01-01T00:00:00Z',+ }),+ // Display order is newest-first; the older (matching) entry is second.+ versionIds: [+ expect.objectContaining({ isActive: false }),+ expect.objectContaining({ isActive: true }),+ ],+ }),+ }),+ expect.anything(),+ );+ });++ test('treats versions with identical linked prompts as active', () => {+ const link = {+ source: 'native',+ groupId: 'group-a',+ selection: { type: 'production' },+ };+ const baseVersion = {+ name: mockAgentData.name,+ description: mockAgentData.description,+ instructions: mockAgentData.instructions,+ tools: mockAgentData.tools,+ capabilities: mockAgentData.capabilities,+ edges: mockAgentData.edges,+ };++ mockUseGetExpandedAgentByIdQuery.mockReturnValueOnce({+ data: { ...mockAgentData, instructionsPrompt: link },+ isLoading: false,+ error: null,+ refetch: jest.fn(),+ });+ mockUseGetAgentVersionsQuery.mockReturnValueOnce({+ data: [+ { ...baseVersion, instructionsPrompt: { ...link }, updatedAt: '2023-01-01T00:00:00Z' },+ ],+ isLoading: false,+ error: null,+ refetch: jest.fn(),+ });++ render(<VersionPanel />);+ expect(VersionContent).toHaveBeenCalledWith(+ expect.objectContaining({+ versionContext: expect.objectContaining({+ activeVersion: expect.objectContaining({ instructionsPrompt: link }),+ versionIds: [expect.objectContaining({ isActive: true })],+ }),+ }),+ expect.anything(),+ );+ });});diff --git a/client/src/components/SidePanel/Agents/Version/__tests__/isActiveVersion.spec.ts b/client/src/components/SidePanel/Agents/Version/__tests__/isActiveVersion.spec.tsindex fe3adc07b9..1531c9205e 100644--- a/client/src/components/SidePanel/Agents/Version/__tests__/isActiveVersion.spec.ts+++ b/client/src/components/SidePanel/Agents/Version/__tests__/isActiveVersion.spec.ts@@ -273,4 +273,128 @@ describe('isActiveVersion', () => {expect(isActiveVersion(version, currentAgent, versions)).toBe(true);});});++ describe('restricted instructions-prompt links', () => {+ const restrictedStub = { source: 'native', restricted: true };+ const visibleLink = {+ source: 'native',+ groupId: 'group-a',+ selection: { type: 'production' },+ };++ test('a restricted stub with matchesCurrent true matches an equally restricted current link', () => {+ const version = createVersion({+ instructionsPrompt: { ...restrictedStub, matchesCurrent: true },+ });+ const currentAgent = createAgentState({+ instructionsPrompt: { ...restrictedStub },+ });+ const versions = [version];++ expect(isActiveVersion(version, currentAgent, versions)).toBe(true);+ });++ test('a restricted stub with matchesCurrent false does not match, even on the latest/only version', () => {+ const version = createVersion({+ instructionsPrompt: { ...restrictedStub, matchesCurrent: false },+ });+ const currentAgent = createAgentState({+ instructionsPrompt: { ...restrictedStub },+ });+ const versions = [version];++ expect(isActiveVersion(version, currentAgent, versions)).toBe(false);+ });++ test('a restricted stub with no matchesCurrent flag does not match', () => {+ const version = createVersion({+ instructionsPrompt: { ...restrictedStub },+ });+ const currentAgent = createAgentState({+ instructionsPrompt: { ...restrictedStub },+ });+ const versions = [version];++ expect(isActiveVersion(version, currentAgent, versions)).toBe(false);+ });++ test('an older version with matchesCurrent true matches, even though a later snapshot does not', () => {+ // A revert `$set`s the document without appending a version, so the current+ // link can equal an older entry while the latest-appended one does not.+ const olderVersion = createVersion({+ name: 'Older Version',+ instructionsPrompt: { ...restrictedStub, matchesCurrent: true },+ });+ const latestVersion = createVersion({+ name: 'Latest Version',+ instructionsPrompt: { ...restrictedStub, matchesCurrent: false },+ });+ const currentAgent = createAgentState({+ name: 'Older Version',+ instructionsPrompt: { ...restrictedStub },+ });+ const versions = [olderVersion, latestVersion];++ expect(isActiveVersion(olderVersion, currentAgent, versions)).toBe(true);+ expect(isActiveVersion(latestVersion, currentAgent, versions)).toBe(false);+ });++ test('a restricted stub on only the version side is not active, even with matchesCurrent true', () => {+ const version = createVersion({+ instructionsPrompt: { ...restrictedStub, matchesCurrent: true },+ });+ const currentAgent = createAgentState({ instructionsPrompt: { ...visibleLink } });+ const versions = [version];++ expect(isActiveVersion(version, currentAgent, versions)).toBe(false);+ });++ test('a restricted stub on only the current-agent side is not active', () => {+ const version = createVersion({ instructionsPrompt: { ...visibleLink } });+ const currentAgent = createAgentState({ instructionsPrompt: { ...restrictedStub } });+ const versions = [version];++ expect(isActiveVersion(version, currentAgent, versions)).toBe(false);+ });++ test('visible, equal links still match', () => {+ const version = createVersion({ instructionsPrompt: { ...visibleLink } });+ const currentAgent = createAgentState({ instructionsPrompt: { ...visibleLink } });+ const versions = [version];++ expect(isActiveVersion(version, currentAgent, versions)).toBe(true);+ });++ test('visible links with different groups do not match', () => {+ const version = createVersion({ instructionsPrompt: { ...visibleLink } });+ const currentAgent = createAgentState({+ instructionsPrompt: { ...visibleLink, groupId: 'group-b' },+ });+ const versions = [version];++ expect(isActiveVersion(version, currentAgent, versions)).toBe(false);+ });++ test('with currentAgent null, restricted stubs never match each other, even index 0 against itself', () => {+ // There is no currentAgent here to resolve `matchesCurrent` against, so comparing+ // one version's restricted stub to another's must not trust either side's flag —+ // that flag only describes a comparison against the current agent. Base semantics+ // (never match a restricted stub against anything, including itself) apply, so+ // neither entry is reported active, matching how index 0 behaved before the+ // `matchesCurrent`-trusting server flag existed.+ const versions = [+ createVersion({+ name: 'Same Name',+ instructionsPrompt: { ...restrictedStub, matchesCurrent: true },+ }),+ createVersion({+ name: 'Same Name',+ instructionsPrompt: { ...restrictedStub, matchesCurrent: false },+ }),+ ];++ expect(isActiveVersion(versions[0], null, versions)).toBe(false);+ expect(isActiveVersion(versions[1], null, versions)).toBe(false);+ });+ });});diff --git a/client/src/components/SidePanel/Agents/Version/isActiveVersion.ts b/client/src/components/SidePanel/Agents/Version/isActiveVersion.tsindex 9ef22c685e..4c909472a3 100644--- a/client/src/components/SidePanel/Agents/Version/isActiveVersion.ts+++ b/client/src/components/SidePanel/Agents/Version/isActiveVersion.ts@@ -1,10 +1,57 @@import isEqual from 'lodash/isEqual';-import type { GraphEdge } from 'librechat-data-provider';+import type {+ GraphEdge,+ AgentInstructionsPrompt,+ RestrictedAgentInstructionsPrompt,+} from 'librechat-data-provider';import type { AgentState, VersionRecord } from './types';+import { isRestrictedInstructionsPrompt } from '../instructionsPromptUtils';const edgesMatch = (versionEdges?: GraphEdge[], currentEdges?: GraphEdge[]): boolean =>isEqual(versionEdges ?? [], currentEdges ?? []);+/** Compares the linked-prompt field: source, `groupId`, and `selection`. A restricted+ * stub hides the linked group from this editor, so the client cannot deep-compare its+ * shape against the other side. Instead it trusts the server-computed `matchesCurrent`+ * flag the stub carries (set by comparing the raw, unredacted links server-side — see+ * `presentForEditor`/`presentVersionsForEditor`): a restricted stub matches only+ * another restricted stub whose `matchesCurrent` is `true`, and never matches a+ * visible link on either side, because a visible link's group is unknown to the+ * restricted side. Two visible links still compare by value. */+const instructionsPromptMatch = (+ versionPrompt: AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null | undefined,+ currentPrompt: AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null | undefined,+): boolean => {+ if (isRestrictedInstructionsPrompt(versionPrompt)) {+ return isRestrictedInstructionsPrompt(currentPrompt) && versionPrompt.matchesCurrent === true;+ }+ if (isRestrictedInstructionsPrompt(currentPrompt)) {+ return false;+ }+ return isEqual(versionPrompt ?? null, currentPrompt ?? null);+};++/** Compares two versions' linked-prompt fields directly, with no `currentAgent` to+ * resolve `matchesCurrent` against. A restricted stub on either side hides its group,+ * so two stubs never match here even if their `matchesCurrent` flags happen to agree —+ * that flag only says how each one compares to the current agent, not to each other. */+const instructionsPromptMatchStrict = (+ versionPrompt: AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null | undefined,+ otherVersionPrompt:+ | AgentInstructionsPrompt+ | RestrictedAgentInstructionsPrompt+ | null+ | undefined,+): boolean => {+ if (+ isRestrictedInstructionsPrompt(versionPrompt) ||+ isRestrictedInstructionsPrompt(otherVersionPrompt)+ ) {+ return false;+ }+ return isEqual(versionPrompt ?? null, otherVersionPrompt ?? null);+};+export const isActiveVersion = (version: VersionRecord,currentAgent: AgentState,@@ -19,7 +66,8 @@ export const isActiveVersion = ((v) =>v.name === version.name &&v.instructions === version.instructions &&- v.artifacts === version.artifacts,+ v.artifacts === version.artifacts &&+ instructionsPromptMatchStrict(v.instructionsPrompt, version.instructionsPrompt),);return versionIndex === 0;}@@ -27,6 +75,10 @@ export const isActiveVersion = (const matchesName = version.name === currentAgent.name;const matchesDescription = version.description === currentAgent.description;const matchesInstructions = version.instructions === currentAgent.instructions;+ const matchesInstructionsPrompt = instructionsPromptMatch(+ version.instructionsPrompt,+ currentAgent.instructionsPrompt,+ );const matchesArtifacts = version.artifacts === currentAgent.artifacts;const matchesEdges = edgesMatch(version.edges, currentAgent.edges);@@ -58,6 +110,7 @@ export const isActiveVersion = (matchesName &&matchesDescription &&matchesInstructions &&+ matchesInstructionsPrompt &&matchesArtifacts &&matchesEdges &&toolsMatch() &&diff --git a/client/src/components/SidePanel/Agents/Version/types.ts b/client/src/components/SidePanel/Agents/Version/types.tsindex 1e5345c6cf..b159d5847e 100644--- a/client/src/components/SidePanel/Agents/Version/types.ts+++ b/client/src/components/SidePanel/Agents/Version/types.ts@@ -1,4 +1,8 @@-import type { GraphEdge } from 'librechat-data-provider';+import type {+ GraphEdge,+ AgentInstructionsPrompt,+ RestrictedAgentInstructionsPrompt,+} from 'librechat-data-provider';export type VersionRecord = Record<string, any>;@@ -6,6 +10,10 @@ export type AgentState = {name: string | null;description: string | null;instructions: string | null;+ /** Linked prompt group revision, or the restricted stub, backing `instructions`.+ * Two versions that differ only by this field must not compare as the same+ * state — see `isActiveVersion`. */+ instructionsPrompt?: AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null;artifacts?: string | null;capabilities?: string[];tools?: string[];@@ -31,6 +39,7 @@ export interface AgentWithVersions {name: string;description: string | null;instructions: string | null;+ instructionsPrompt?: AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null;artifacts?: string | null;capabilities?: string[];tools?: string[];diff --git a/client/src/components/SidePanel/Agents/__tests__/AgentAvatar.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/AgentAvatar.spec.tsxindex 0bee0e00bc..e689a3afb1 100644--- a/client/src/components/SidePanel/Agents/__tests__/AgentAvatar.spec.tsx+++ b/client/src/components/SidePanel/Agents/__tests__/AgentAvatar.spec.tsx@@ -39,6 +39,8 @@ const defaultFormValues: AgentForm = {name: 'Agent',description: null,instructions: null,+ instructionsSource: 'inline',+ instructionsPrompt: null,model: 'gpt-4',model_parameters: {temperature: 1,diff --git a/client/src/components/SidePanel/Agents/__tests__/AgentPanel.helpers.spec.ts b/client/src/components/SidePanel/Agents/__tests__/AgentPanel.helpers.spec.tsindex c308e196d7..b8782d405e 100644--- a/client/src/components/SidePanel/Agents/__tests__/AgentPanel.helpers.spec.ts+++ b/client/src/components/SidePanel/Agents/__tests__/AgentPanel.helpers.spec.ts@@ -17,6 +17,7 @@ import {mayHavePersistedChange,shouldSyncSavedStarters,isSavedAgentOption,+ computeInstructionsPromptChanged,} from '../AgentPanel';test('the create identity contract excludes the update-only clear sentinel', () => {@@ -32,6 +33,8 @@ const createForm = (): AgentForm => ({name: 'Agent',description: null,instructions: null,+ instructionsSource: 'inline',+ instructionsPrompt: null,model: 'gpt-4',model_parameters: {temperature: 1,@@ -64,12 +67,17 @@ describe('composeAgentUpdatePayload', () => {it('preserves a legacy chain on unrelated saves and sends explicit removal', () => {const form = createForm();form.agent_ids = ['first', 'second'];- expect(composeAgentUpdatePayload(form, 'agent_123').payload.agent_ids).toEqual([- 'first',- 'second',- ]);+ expect(+ composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ }).payload.agent_ids,+ ).toEqual(['first', 'second']);form.agent_ids = [];- expect(composeAgentUpdatePayload(form, 'agent_123').payload.agent_ids).toEqual([]);+ expect(+ composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ }).payload.agent_ids,+ ).toEqual([]);});it('omits unchanged unavailable machine choices but submits an explicit removal', () => {const form = createForm();@@ -79,16 +87,24 @@ describe('composeAgentUpdatePayload', () => {};form.code_environment_ids = ['missing'];expect(- composeAgentUpdatePayload(form, 'agent_123').payload.code_environment_ids,+ composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ }).payload.code_environment_ids,).toBeUndefined();form.code_environment_ids = [];- expect(composeAgentUpdatePayload(form, 'agent_123').payload.code_environment_ids).toEqual([]);+ expect(+ composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ }).payload.code_environment_ids,+ ).toEqual([]);});it('includes avatar: null when resetting a persistent agent', () => {const form = createForm();form.avatar_action = 'reset';- const { payload } = composeAgentUpdatePayload(form, 'agent_123');+ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.avatar).toBeNull();});@@ -97,7 +113,9 @@ describe('composeAgentUpdatePayload', () => {const form = createForm();form.avatar_action = 'reset';- const { payload } = composeAgentUpdatePayload(form, Constants.EPHEMERAL_AGENT_ID);+ const { payload } = composeAgentUpdatePayload(form, Constants.EPHEMERAL_AGENT_ID, undefined, {+ instructionsPromptChanged: false,+ });expect(payload.avatar).toBeUndefined();});@@ -106,7 +124,9 @@ describe('composeAgentUpdatePayload', () => {const form = createForm();form.avatar_action = 'upload';- const { payload } = composeAgentUpdatePayload(form, 'agent_123');+ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.avatar).toBeUndefined();});@@ -116,7 +136,9 @@ describe('composeAgentUpdatePayload', () => {form.execute_code = false;form.stateful_code_sessions = true;- const { payload } = composeAgentUpdatePayload(form, 'agent_123');+ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.stateful_code_sessions).toBe(false);});@@ -128,7 +150,9 @@ describe('composeAgentUpdatePayload', () => {search: { allowed_callers: ['code_execution'], defer_loading: true },};- const { payload } = composeAgentUpdatePayload(form, 'agent_123');+ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.tool_options).toEqual({ search: { defer_loading: true } });});@@ -140,7 +164,9 @@ describe('composeAgentUpdatePayload', () => {search: { allowed_callers: ['code_execution'] },};- const { payload } = composeAgentUpdatePayload(form, 'agent_123');+ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.tool_options).toEqual({search: { allowed_callers: ['code_execution'] },@@ -152,7 +178,9 @@ describe('composeAgentUpdatePayload', () => {form.execute_code = true;form.stateful_code_sessions = true;- const { payload } = composeAgentUpdatePayload(form, 'agent_123');+ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.stateful_code_sessions).toBe(true);});@@ -162,7 +190,9 @@ describe('composeAgentUpdatePayload', () => {form.execute_code = true;form.stateful_code_sessions = true;- const { payload } = composeAgentUpdatePayload(form, 'agent_123');+ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.stateful_code_environment).toBe('user');});@@ -173,7 +203,9 @@ describe('composeAgentUpdatePayload', () => {form.stateful_code_sessions = true;form.stateful_code_environment = 'agent-user';- const { payload } = composeAgentUpdatePayload(form, 'agent_123');+ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.stateful_code_environment).toBe('agent-user');});@@ -182,7 +214,9 @@ describe('composeAgentUpdatePayload', () => {const form = createForm();form.code_environment_id = null;- const { payload } = composeAgentUpdatePayload(form, 'agent_123');+ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.code_environment_id).toBeNull();});@@ -191,7 +225,9 @@ describe('composeAgentUpdatePayload', () => {const form = createForm();form.code_environment_id = null;- const { payload } = composeAgentUpdatePayload(form);+ const { payload } = composeAgentUpdatePayload(form, undefined, undefined, {+ instructionsPromptChanged: false,+ });expect(payload.code_environment_id).toBeUndefined();});@@ -200,7 +236,9 @@ describe('composeAgentUpdatePayload', () => {const form = createForm();form.git_identity = { name: ' Coding Agent ', email: ' [email protected] ' };- const { payload } = composeAgentUpdatePayload(form, 'agent_123');+ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.git_identity).toEqual({name: 'Coding Agent',@@ -212,7 +250,9 @@ describe('composeAgentUpdatePayload', () => {const form = createForm();form.git_identity = { name: '', email: '' };- const { payload } = composeAgentUpdatePayload(form, 'agent_123');+ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.git_identity).toBeNull();});@@ -221,7 +261,9 @@ describe('composeAgentUpdatePayload', () => {const form = createForm();form.git_identity = { name: 'Coding Agent', email: '' };- const { payload } = composeAgentUpdatePayload(form, 'agent_123');+ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.git_identity).toEqual({ name: 'Coding Agent', email: '' });});@@ -230,7 +272,9 @@ describe('composeAgentUpdatePayload', () => {const form = createForm();form.git_identity = { name: '', email: '' };- const { payload } = composeAgentUpdatePayload(form);+ const { payload } = composeAgentUpdatePayload(form, undefined, undefined, {+ instructionsPromptChanged: false,+ });expect(payload.git_identity).toBeUndefined();});@@ -241,7 +285,9 @@ describe('composeAgentUpdatePayload', () => {form.skills_enabled = false;form.skill_authoring_enabled = true;- const { payload } = composeAgentUpdatePayload(form, 'agent_123');+ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.skills_enabled).toBe(false);expect(payload.skill_authoring_enabled).toBe(true);@@ -270,10 +316,12 @@ describe('composeAgentUpdatePayload', () => {topK: 40,};form.model_parameters = stored;- const { payload } = composeAgentUpdatePayload(form, 'agent_123', {- endpointsConfig: {},- startupConfig: {},- });+ const { payload } = composeAgentUpdatePayload(+ form,+ 'agent_123',+ { endpointsConfig: {}, startupConfig: {} },+ { instructionsPromptChanged: false },+ );expect(payload.model_parameters).toEqual(form.model_parameters);expect(JSON.parse(JSON.stringify(payload)).model_parameters).toEqual(form.model_parameters);},@@ -284,12 +332,17 @@ describe('composeAgentUpdatePayload', () => {form.provider = EModelEndpoint.openAI;form.model_parameters.model = 'deployment-override';- const { payload } = composeAgentUpdatePayload(form, 'agent_123', {- endpointsConfig: {},- startupConfig: {- endpointsDropParamsMap: { [EModelEndpoint.openAI]: ['topP'] },+ const { payload } = composeAgentUpdatePayload(+ form,+ 'agent_123',+ {+ endpointsConfig: {},+ startupConfig: {+ endpointsDropParamsMap: { [EModelEndpoint.openAI]: ['topP'] },+ },},- });+ { instructionsPromptChanged: false },+ );expect(payload.model_parameters?.temperature).toBe(1);expect(payload.model_parameters?.top_p).toBeUndefined();@@ -300,10 +353,12 @@ describe('composeAgentUpdatePayload', () => {const form = createForm();form.provider = 'removed-provider';- const { payload } = composeAgentUpdatePayload(form, 'agent_123', {- endpointsConfig: {},- startupConfig: {},- });+ const { payload } = composeAgentUpdatePayload(+ form,+ 'agent_123',+ { endpointsConfig: {}, startupConfig: {} },+ { instructionsPromptChanged: false },+ );expect(payload.model_parameters).toEqual(form.model_parameters);});@@ -313,7 +368,9 @@ describe('composeAgentUpdatePayload', () => {form.agent = { conversation_starters: ['Plan my week'] } as AgentForm['agent'];form.conversation_starters = [' Plan my week ', '', ' ', 'Summarize'];- const { payload } = composeAgentUpdatePayload(form, 'agent_123');+ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.conversation_starters).toEqual(['Plan my week', 'Summarize']);});@@ -323,7 +380,9 @@ describe('composeAgentUpdatePayload', () => {form.agent = { conversation_starters: ['Plan my week'] } as AgentForm['agent'];form.conversation_starters = [];- const { payload } = composeAgentUpdatePayload(form, 'agent_123');+ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.conversation_starters).toEqual([]);});@@ -335,18 +394,163 @@ describe('composeAgentUpdatePayload', () => {form.conversation_starters = [...stored];form.name = 'Renamed';- const { payload } = composeAgentUpdatePayload(form, 'agent_123');+ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.conversation_starters).toBeUndefined();});it('omits starters when the form never loaded them', () => {- const { payload } = composeAgentUpdatePayload(createForm(), 'agent_123');+ const { payload } = composeAgentUpdatePayload(createForm(), 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });expect(payload.conversation_starters).toBeUndefined();});});+describe('composeAgentUpdatePayload instructionsPrompt', () => {+ it('omits instructionsPrompt for an unlinked agent left in the default inline mode', () => {+ const form = createForm();++ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });++ expect(payload).not.toHaveProperty('instructionsPrompt');+ });++ it('omits instructionsPrompt when the link did not change', () => {+ const form = createForm();+ form.instructionsSource = 'prompt';+ form.instructionsPrompt = {+ source: 'native',+ groupId: 'group_1',+ selection: { type: 'production' },+ };++ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: false,+ });++ expect(payload).not.toHaveProperty('instructionsPrompt');+ });++ it('sends the link with a Production selection when changed', () => {+ const form = createForm();+ form.instructionsSource = 'prompt';+ form.instructionsPrompt = {+ source: 'native',+ groupId: 'group_1',+ selection: { type: 'production' },+ };++ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: true,+ });++ expect(payload.instructionsPrompt).toEqual({+ source: 'native',+ groupId: 'group_1',+ selection: { type: 'production' },+ });+ });++ it('sends the link with an exact selection when a specific version is chosen', () => {+ const form = createForm();+ form.instructionsSource = 'prompt';+ form.instructionsPrompt = {+ source: 'native',+ groupId: 'group_1',+ selection: { type: 'exact', promptId: 'prompt_7' },+ };++ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: true,+ });++ expect(payload.instructionsPrompt).toEqual({+ source: 'native',+ groupId: 'group_1',+ selection: { type: 'exact', promptId: 'prompt_7' },+ });+ });++ it('sends null when switching a linked agent back to inline', () => {+ const form = createForm();+ form.instructionsSource = 'inline';+ form.instructionsPrompt = {+ source: 'native',+ groupId: 'group_1',+ selection: { type: 'production' },+ };++ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: true,+ });++ expect(payload.instructionsPrompt).toBeNull();+ });++ it('never re-sends the restricted stub, even if a caller marks it changed', () => {+ const form = createForm();+ form.instructionsSource = 'prompt';+ form.instructionsPrompt = { source: 'native', restricted: true };++ const { payload } = composeAgentUpdatePayload(form, 'agent_123', undefined, {+ instructionsPromptChanged: true,+ });++ expect(payload.instructionsPrompt).toBeNull();+ });++ it('always sends the link on create, even when the changed flag is false', () => {+ /** A create has no `agent_id` and no stored value to diff against. Gating on the+ * caller's changed flag here is how a new agent linked to the same group as+ * whatever agent was last open in the panel ends up created with no link at all. */+ const form = createForm();+ form.instructionsSource = 'prompt';+ form.instructionsPrompt = {+ source: 'native',+ groupId: 'group_1',+ selection: { type: 'production' },+ };++ const { payload } = composeAgentUpdatePayload(form, undefined, undefined, {+ instructionsPromptChanged: false,+ });++ expect(payload.instructionsPrompt).toEqual({+ source: 'native',+ groupId: 'group_1',+ selection: { type: 'production' },+ });+ });++ it('sends null on create for the default inline mode, even when the changed flag is false', () => {+ const form = createForm();++ const { payload } = composeAgentUpdatePayload(form, undefined, undefined, {+ instructionsPromptChanged: false,+ });++ expect(payload).toHaveProperty('instructionsPrompt', null);+ });++ it('never sends the restricted stub on create either', () => {+ const form = createForm();+ form.instructionsSource = 'prompt';+ form.instructionsPrompt = { source: 'native', restricted: true };++ const { payload } = composeAgentUpdatePayload(form, undefined, undefined, {+ instructionsPromptChanged: false,+ });++ expect(payload.instructionsPrompt).toBeNull();+ });+});+describe('persistAvatarChanges', () => {it('returns false for ephemeral agents', async () => {const uploadAvatar = jest.fn();@@ -590,3 +794,59 @@ describe('isSavedAgentOption', () => {expect(isSavedAgentOption(undefined, 'agent_a')).toBe(false);});});++describe('computeInstructionsPromptChanged', () => {+ const link = {+ source: 'native' as const,+ groupId: 'group_1',+ selection: { type: 'production' as const },+ };+ const otherLink = {+ source: 'native' as const,+ groupId: 'group_2',+ selection: { type: 'production' as const },+ };+ const stub = { source: 'native' as const, restricted: true as const };++ it('is unchanged for an unlinked form matching an unlinked agent', () => {+ expect(computeInstructionsPromptChanged('inline', null, null)).toBe(false);+ expect(computeInstructionsPromptChanged('inline', null, undefined)).toBe(false);+ });++ it('is changed when switching from inline to a selected link', () => {+ expect(computeInstructionsPromptChanged('prompt', link, null)).toBe(true);+ });++ it('is changed when switching a linked agent back to inline', () => {+ expect(computeInstructionsPromptChanged('inline', null, link)).toBe(true);+ });++ it('is changed when picking a different link than the one loaded', () => {+ expect(computeInstructionsPromptChanged('prompt', otherLink, link)).toBe(true);+ });++ it('is unchanged when the form still carries the link exactly as loaded', () => {+ /** This is the case a stale `dirtyFields.instructionsPrompt` gets wrong: the field+ * was dirtied by the save that set this link, but the value now matches what the+ * server has, so nothing here warrants resending it. */+ expect(computeInstructionsPromptChanged('prompt', link, link)).toBe(false);+ expect(computeInstructionsPromptChanged('prompt', { ...link }, link)).toBe(false);+ });++ it('is unchanged for a restricted stub the editor cannot see, in either direction', () => {+ expect(computeInstructionsPromptChanged('prompt', stub, stub)).toBe(false);+ expect(computeInstructionsPromptChanged('prompt', stub, null)).toBe(false);+ });++ it('is changed when an editor with access replaces a restricted stub with a real link', () => {+ expect(computeInstructionsPromptChanged('prompt', link, stub)).toBe(true);+ });++ it('is changed when a restricted stub is switched to Inline, so the removal is sent', () => {+ /** Both sides resolve to `null` here (inline mode and the stub both do), so a diff+ * of resolved values alone can't tell this apart from "still the stub, unchanged"+ * above — the stub-aware branch has to settle it directly. */+ expect(computeInstructionsPromptChanged('inline', null, stub)).toBe(true);+ expect(computeInstructionsPromptChanged('inline', stub, stub)).toBe(true);+ });+});diff --git a/client/src/components/SidePanel/Agents/__tests__/AgentSelect.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/AgentSelect.spec.tsxnew file mode 100644index 0000000000..ad1cce2108--- /dev/null+++ b/client/src/components/SidePanel/Agents/__tests__/AgentSelect.spec.tsx@@ -0,0 +1,150 @@+import React from 'react';+import { useForm, FormProvider } from 'react-hook-form';+import { render, waitFor } from '@testing-library/react';+import type { UseMutationResult, QueryObserverResult } from '@tanstack/react-query';+import type { Agent, AgentCreateParams } from 'librechat-data-provider';+import type { UseFormReturn } from 'react-hook-form';+import type { AgentForm } from '~/common';+import AgentSelect from '../AgentSelect';++jest.mock('~/data-provider', () => ({+ useListAgentsQuery: () => ({ data: [] }),+ useGetStartupConfig: () => ({ data: undefined }),+}));++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+ useAgentDefaultPermissionLevel: () => 1,+}));++jest.mock('@librechat/client', () => ({+ ControlCombobox: () => <div data-testid="agent-select-combobox" />,+}));++/**+ * Renders `AgentSelect` with an already-successful `agentQuery`, which drives its+ * `resetAgentForm` load effect the same way selecting an agent (or a background+ * refetch) does. `resetAgentForm` is a closure, not exported, so this is the+ * narrowest seam that observes its instructions-source/instructions-prompt mapping.+ */+function Harness({+ agent,+ onMethods,+ instructionsPromptReady,+ defaultValues,+}: {+ agent: Agent;+ onMethods: (methods: UseFormReturn<AgentForm>) => void;+ instructionsPromptReady?: boolean;+ defaultValues?: Partial<AgentForm>;+}) {+ const methods = useForm<AgentForm>({ defaultValues });+ onMethods(methods);++ return (+ <FormProvider {...methods}>+ <AgentSelect+ agentQuery={{ data: agent, isSuccess: true } as unknown as QueryObserverResult<Agent>}+ /** `null`, not `agent.id`: a non-null value with no matching row in the (empty,+ * mocked) agent list schedules `onSelect`'s "not found" timer, which would reset+ * the whole form back to defaults out from under this test. The load effect this+ * test targets keys off `agentQuery.data` alone. */+ selectedAgentId={null}+ setCurrentAgentId={jest.fn()}+ createMutation={+ { reset: jest.fn() } as unknown as UseMutationResult<Agent, Error, AgentCreateParams>+ }+ defaultStatefulCodeEnvironment="user"+ instructionsPromptReady={instructionsPromptReady}+ />+ </FormProvider>+ );+}++const createAgent = (overrides: Partial<Agent> = {}): Agent =>+ ({+ id: 'agent_1',+ name: 'Agent',+ provider: 'openai',+ model: 'gpt-4',+ ...overrides,+ }) as Agent;++describe('AgentSelect resetAgentForm', () => {+ it('maps a linked agent to Prompt mode with the link copied verbatim', async () => {+ const link = {+ source: 'native' as const,+ groupId: 'group_1',+ selection: { type: 'production' as const },+ };+ let methods: UseFormReturn<AgentForm> | undefined;++ render(+ <Harness+ agent={createAgent({ instructionsPrompt: link })}+ onMethods={(m) => (methods = m)}+ />,+ );++ await waitFor(() => expect(methods?.getValues('instructionsSource')).toBe('prompt'));+ expect(methods?.getValues('instructionsPrompt')).toEqual(link);+ });++ it('maps a restricted stub to Prompt mode with the stub preserved', async () => {+ const stub = { source: 'native' as const, restricted: true as const };+ let methods: UseFormReturn<AgentForm> | undefined;++ render(+ <Harness+ agent={createAgent({ instructionsPrompt: stub })}+ onMethods={(m) => (methods = m)}+ />,+ );++ await waitFor(() => expect(methods?.getValues('instructionsSource')).toBe('prompt'));+ expect(methods?.getValues('instructionsPrompt')).toEqual(stub);+ });++ it('maps an agent with no link to Inline mode with a null prompt', async () => {+ let methods: UseFormReturn<AgentForm> | undefined;++ render(+ <Harness+ agent={createAgent({ instructionsPrompt: null })}+ onMethods={(m) => (methods = m)}+ />,+ );++ await waitFor(() => expect(methods?.getValues('instructionsSource')).toBe('inline'));+ expect(methods?.getValues('instructionsPrompt')).toBeNull();+ });++ it('keeps the form instructions-source/prompt untouched when the data is the basic projection', async () => {+ let methods: UseFormReturn<AgentForm> | undefined;++ render(+ <Harness+ /** No `instructionsPrompt` key at all, as the basic agent projection sends it. */+ agent={createAgent()}+ instructionsPromptReady={false}+ defaultValues={{+ instructionsSource: 'prompt',+ instructionsPrompt: {+ source: 'native',+ groupId: 'group_1',+ selection: { type: 'production' },+ },+ }}+ onMethods={(m) => (methods = m)}+ />,+ );++ await waitFor(() => expect(methods?.getValues('name')).toBe('Agent'));+ expect(methods?.getValues('instructionsSource')).toBe('prompt');+ expect(methods?.getValues('instructionsPrompt')).toEqual({+ source: 'native',+ groupId: 'group_1',+ selection: { type: 'production' },+ });+ });+});diff --git a/client/src/components/SidePanel/Agents/__tests__/Instructions.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/Instructions.spec.tsxindex b2ff3fab9b..488ce9afbb 100644--- a/client/src/components/SidePanel/Agents/__tests__/Instructions.spec.tsx+++ b/client/src/components/SidePanel/Agents/__tests__/Instructions.spec.tsx@@ -1,20 +1,47 @@import { ToastProvider } from '@librechat/client';import userEvent from '@testing-library/user-event';-import { render, screen } from '@testing-library/react';import { FormProvider, useForm } from 'react-hook-form';+import { render, screen, fireEvent } from '@testing-library/react';import type { AgentForm } from '~/common';-import Instructions from '../Instructions';+import Instructions, { type InstructionsPromptStatus } from '../Instructions';jest.mock('~/hooks', () => ({useLocalize: () => (key: string) => key,}));-function InstructionsHarness() {- const methods = useForm<AgentForm>({ defaultValues: { instructions: '' } });+jest.mock('../InstructionsPromptFields', () => {+ /** Keeps the real `fieldWrapperClass`/`LoadError` exports Instructions.tsx reuses+ * for its own loading/error states; only the heavy field body is stubbed. */+ const actual = jest.requireActual('../InstructionsPromptFields');+ return {+ __esModule: true,+ ...actual,+ default: () => <div data-testid="instructions-prompt-fields" />,+ };+});++jest.mock('../RestrictedInstructionsPrompt', () => () => (+ <div data-testid="restricted-instructions-prompt" />+));++function InstructionsHarness({+ instructionsSource = 'inline',+ instructionsPrompt = null,+ promptStatus,+ onRetryLoad,+}: {+ instructionsSource?: AgentForm['instructionsSource'];+ instructionsPrompt?: AgentForm['instructionsPrompt'];+ promptStatus?: InstructionsPromptStatus;+ onRetryLoad?: () => void;+}) {+ const methods = useForm<AgentForm>({+ defaultValues: { instructions: '', instructionsSource, instructionsPrompt },+ });return (<ToastProvider><FormProvider {...methods}>- <Instructions />+ <Instructions promptStatus={promptStatus} onRetryLoad={onRetryLoad} /></FormProvider></ToastProvider>);@@ -30,4 +57,232 @@ describe('Agent Instructions', () => {await screen.findByRole('menuitem', { name: 'com_ui_special_var_current_date' }),).toBeInTheDocument();});++ it('defaults to inline mode and keeps the inline editor visible', () => {+ render(<InstructionsHarness />);++ expect(screen.getByLabelText('com_ui_instructions')).toBeInTheDocument();+ expect(screen.getByTestId('instructions-inline-panel')).not.toHaveClass('hidden');+ expect(screen.queryByTestId('instructions-prompt-fields')).not.toBeInTheDocument();+ });++ it('switching to Prompt mode hides the inline editor without unmounting it', () => {+ render(<InstructionsHarness />);++ fireEvent.click(screen.getByRole('button', { name: 'com_agents_instructions_source_prompt' }));++ expect(screen.getByTestId('instructions-prompt-fields')).toBeInTheDocument();+ expect(screen.getByTestId('instructions-inline-panel')).toHaveClass('hidden');+ });++ it('shows Prompt/Version controls in Prompt mode for an unrestricted link', () => {+ render(+ <InstructionsHarness+ instructionsSource="prompt"+ instructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ }}+ />,+ );++ expect(screen.getByTestId('instructions-prompt-fields')).toBeInTheDocument();+ expect(screen.queryByTestId('restricted-instructions-prompt')).not.toBeInTheDocument();+ });++ it('shows the Prompt picker alongside the restricted note, with the toggle enabled, for a restricted link', () => {+ render(+ <InstructionsHarness+ instructionsSource="prompt"+ instructionsPrompt={{ source: 'native', restricted: true }}+ />,+ );++ expect(screen.getByTestId('restricted-instructions-prompt')).toBeInTheDocument();+ expect(screen.getByTestId('instructions-prompt-fields')).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: 'com_agents_instructions_source_inline' }),+ ).not.toBeDisabled();+ expect(+ screen.getByRole('button', { name: 'com_agents_instructions_source_prompt' }),+ ).not.toBeDisabled();+ });++ it('lets a restricted stub be switched to Inline, hiding the picker and showing the inline editor', () => {+ render(+ <InstructionsHarness+ instructionsSource="prompt"+ instructionsPrompt={{ source: 'native', restricted: true }}+ />,+ );++ fireEvent.click(screen.getByRole('button', { name: 'com_agents_instructions_source_inline' }));++ expect(screen.queryByTestId('instructions-prompt-fields')).not.toBeInTheDocument();+ expect(screen.queryByTestId('restricted-instructions-prompt')).not.toBeInTheDocument();+ expect(screen.getByTestId('instructions-inline-panel')).not.toHaveClass('hidden');+ });++ it('reverts to the stored value when toggling back without saving', () => {+ render(+ <InstructionsHarness+ instructionsSource="inline"+ instructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ }}+ />,+ );++ const promptButton = screen.getByRole('button', {+ name: 'com_agents_instructions_source_prompt',+ });+ const inlineButton = screen.getByRole('button', {+ name: 'com_agents_instructions_source_inline',+ });++ fireEvent.click(promptButton);+ expect(screen.getByTestId('instructions-prompt-fields')).toBeInTheDocument();++ fireEvent.click(inlineButton);+ expect(screen.queryByTestId('instructions-prompt-fields')).not.toBeInTheDocument();+ expect(screen.getByTestId('instructions-inline-panel')).not.toHaveClass('hidden');+ });++ it('renders a disabled loading state while the expanded agent query is pending', () => {+ render(+ <InstructionsHarness+ instructionsSource="prompt"+ instructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ }}+ promptStatus="loading"+ />,+ );++ expect(screen.getByText('com_ui_loading')).toBeInTheDocument();+ expect(screen.queryByTestId('instructions-prompt-fields')).not.toBeInTheDocument();+ expect(screen.queryByTestId('instructions-inline-panel')).not.toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: 'com_agents_instructions_source_inline' }),+ ).toBeDisabled();+ expect(+ screen.getByRole('button', { name: 'com_agents_instructions_source_prompt' }),+ ).toBeDisabled();+ });++ it('renders Prompt mode with the link once the expanded query resolves', () => {+ render(+ <InstructionsHarness+ instructionsSource="prompt"+ instructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ }}+ promptStatus="ready"+ />,+ );++ expect(screen.getByTestId('instructions-prompt-fields')).toBeInTheDocument();+ expect(screen.queryByText('com_ui_loading')).not.toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: 'com_agents_instructions_source_prompt' }),+ ).not.toBeDisabled();+ });++ it('renders the load-error state with Retry and keeps controls disabled when the expanded query errors', async () => {+ const user = userEvent.setup();+ const onRetryLoad = jest.fn();+ render(+ <InstructionsHarness+ instructionsSource="prompt"+ instructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ }}+ promptStatus="error"+ onRetryLoad={onRetryLoad}+ />,+ );++ expect(screen.getByRole('alert')).toHaveTextContent(+ 'com_agents_instructions_prompt_load_error',+ );+ expect(+ screen.getByRole('button', { name: 'com_agents_instructions_source_inline' }),+ ).toBeDisabled();+ expect(+ screen.getByRole('button', { name: 'com_agents_instructions_source_prompt' }),+ ).toBeDisabled();++ await user.click(screen.getByRole('button', { name: 'com_ui_retry' }));+ expect(onRetryLoad).toHaveBeenCalledTimes(1);+ });++ describe('heading', () => {+ it('is visible in inline mode, beside the source toggle', () => {+ render(<InstructionsHarness instructionsSource="inline" />);++ expect(screen.getByTestId('instructions-heading')).toHaveTextContent('com_ui_instructions');+ expect(+ screen.getByRole('group', { name: 'com_agents_instructions_source_toggle_aria' }),+ ).toBeInTheDocument();+ });++ it('is visible in Prompt mode', () => {+ render(+ <InstructionsHarness+ instructionsSource="prompt"+ instructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ }}+ />,+ );++ expect(screen.getByTestId('instructions-heading')).toHaveTextContent('com_ui_instructions');+ });++ it('is visible for a restricted link', () => {+ render(+ <InstructionsHarness+ instructionsSource="prompt"+ instructionsPrompt={{ source: 'native', restricted: true }}+ />,+ );++ expect(screen.getByTestId('instructions-heading')).toHaveTextContent('com_ui_instructions');+ });++ it('is visible while the expanded agent query is loading', () => {+ render(<InstructionsHarness promptStatus="loading" />);++ expect(screen.getByTestId('instructions-heading')).toHaveTextContent('com_ui_instructions');+ });++ it('is visible when the expanded agent query errors', () => {+ render(<InstructionsHarness promptStatus="error" onRetryLoad={jest.fn()} />);++ expect(screen.getByTestId('instructions-heading')).toHaveTextContent('com_ui_instructions');+ });++ it('does not duplicate the visible "Instructions" text next to the inline editor', () => {+ render(<InstructionsHarness instructionsSource="inline" />);++ // The heading carries the one visible "Instructions" label; the inline+ // editor's own label stays in the accessibility tree only.+ expect(screen.getAllByText('com_ui_instructions')).toHaveLength(2);+ const textbox = screen.getByRole('textbox', { name: 'com_ui_instructions' });+ expect(textbox).toBeInTheDocument();+ const editorLabel = document.querySelector('label[for="instructions"]');+ expect(editorLabel).toHaveClass('sr-only');+ });+ });});diff --git a/client/src/components/SidePanel/Agents/__tests__/InstructionsPromptFields.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/InstructionsPromptFields.spec.tsxnew file mode 100644index 0000000000..e3491ef7e9--- /dev/null+++ b/client/src/components/SidePanel/Agents/__tests__/InstructionsPromptFields.spec.tsx@@ -0,0 +1,580 @@+import React from 'react';+import { useForm, FormProvider } from 'react-hook-form';+import { render, screen, fireEvent, act } from '@testing-library/react';+import type { TPromptGroup, TPrompt } from 'librechat-data-provider';+import type { UseFormReturn } from 'react-hook-form';+import type { AgentForm } from '~/common';+import InstructionsPromptFields from '../InstructionsPromptFields';++let mockGroupsQuery: {+ data?: unknown;+ isLoading: boolean;+ isError: boolean;+ error?: unknown;+ refetch: jest.Mock;+};+let mockPromptsQuery: {+ data?: unknown;+ isLoading: boolean;+ isError: boolean;+ error?: unknown;+ refetch: jest.Mock;+};++jest.mock('~/data-provider', () => ({+ useGetAllPromptGroups: () => mockGroupsQuery,+ useGetPrompts: () => mockPromptsQuery,+}));++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string, vars?: Record<string, unknown>) =>+ vars ? `${key}:${JSON.stringify(vars)}` : key,+}));++jest.mock('@librechat/client', () => ({+ Button: ({+ children,+ variant: _variant,+ size: _size,+ ...props+ }: React.ComponentProps<'button'> & { variant?: string; size?: string }) => (+ <button {...props}>{children}</button>+ ),+ Label: ({ children, ...props }: React.ComponentProps<'label'>) => (+ <label {...props}>{children}</label>+ ),+ ControlCombobox: ({+ ariaLabel,+ selectId,+ items,+ selectedValue,+ displayValue,+ setValue,+ }: {+ ariaLabel: string;+ selectId?: string;+ items: Array<{ value: string; label: string }>;+ selectedValue: string;+ displayValue?: string;+ setValue: (value: string) => void;+ }) => (+ <div>+ {/* Mirrors the real combobox's current-value text for the Prompt dropdown only,+ * which `displayValue` drives independently of `selectedValue`/`items` (the stub+ * shows a label with no matching option). Scoped to this one dropdown so it+ * doesn't duplicate the Version dropdown's option text in other assertions. */}+ {selectId === 'instructions-prompt-group' && (+ <span data-testid={`${selectId}-display-value`}>{displayValue}</span>+ )}+ <select+ aria-label={ariaLabel}+ id={selectId}+ value={selectedValue}+ onChange={(event) => setValue(event.target.value)}+ >+ {items.map((item) => (+ <option key={item.value} value={item.value}>+ {item.label}+ </option>+ ))}+ </select>+ </div>+ ),+}));++const group = (overrides: Partial<TPromptGroup> = {}): TPromptGroup => ({+ name: 'Support triage',+ author: 'user1',+ authorName: 'User One',+ _id: 'group1',+ ...overrides,+});++const prompt = (overrides: Partial<TPrompt> = {}): TPrompt => ({+ groupId: 'group1',+ author: 'user1',+ prompt: 'text',+ type: 'text',+ createdAt: '',+ updatedAt: '',+ ...overrides,+});++function Harness({+ defaultInstructionsPrompt = null,+ defaultInstructionsSource = 'prompt',+ onMethods,+}: {+ defaultInstructionsPrompt?: unknown;+ defaultInstructionsSource?: AgentForm['instructionsSource'];+ onMethods?: (methods: UseFormReturn<AgentForm>) => void;+}) {+ const methods = useForm<AgentForm>({+ defaultValues: {+ instructionsSource: defaultInstructionsSource,+ instructionsPrompt: defaultInstructionsPrompt,+ } as Partial<AgentForm>,+ });+ onMethods?.(methods);+ return (+ <FormProvider {...methods}>+ <InstructionsPromptFields />+ </FormProvider>+ );+}++beforeEach(() => {+ mockGroupsQuery = {+ data: [],+ isLoading: false,+ isError: false,+ error: undefined,+ refetch: jest.fn(),+ };+ mockPromptsQuery = {+ data: [],+ isLoading: false,+ isError: false,+ error: undefined,+ refetch: jest.fn(),+ };+});++describe('InstructionsPromptFields', () => {+ it('shows a loading state for the Prompt dropdown', () => {+ mockGroupsQuery.isLoading = true;+ render(<Harness />);++ expect(screen.getByText('com_ui_loading')).toBeInTheDocument();+ });++ it('shows an empty state when there are no prompt groups', () => {+ mockGroupsQuery.data = [];+ render(<Harness />);++ expect(screen.getByText('com_agents_instructions_prompt_empty')).toBeInTheDocument();+ });++ it('shows an error with Retry, and retries on click', () => {+ mockGroupsQuery.isError = true;+ mockGroupsQuery.error = new Error('network down');+ render(<Harness />);++ expect(screen.getByText('com_agents_instructions_prompt_load_error')).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_retry' }));+ expect(mockGroupsQuery.refetch).toHaveBeenCalledTimes(1);+ });++ it('shows a distinct message for a 403 and offers no retry', () => {+ mockGroupsQuery.isError = true;+ mockGroupsQuery.error = { isAxiosError: true, response: { status: 403, data: {} } };+ render(<Harness />);++ expect(screen.getByText('com_agents_instructions_prompt_forbidden')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'com_ui_retry' })).not.toBeInTheDocument();+ });++ it('selecting a prompt group defaults the selection to Production', () => {+ mockGroupsQuery.data = [group()];+ let methods: UseFormReturn<AgentForm> | undefined;+ render(<Harness onMethods={(m) => (methods = m)} />);++ fireEvent.change(screen.getByRole('combobox', { name: 'com_ui_prompt' }), {+ target: { value: 'group1' },+ });++ expect(methods?.getValues('instructionsPrompt')).toEqual({+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ });+ });++ it('lists Production first, then versions newest to oldest', () => {+ mockGroupsQuery.data = [group({ productionId: 'p2' })];+ mockPromptsQuery.data = [prompt({ _id: 'p3' }), prompt({ _id: 'p2' }), prompt({ _id: 'p1' })];+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ }}+ />,+ );++ const versionSelect = screen.getByRole('combobox', {+ name: 'com_agents_instructions_prompt_version_label',+ });+ const optionValues = Array.from(versionSelect.querySelectorAll('option')).map(+ (option) => (option as HTMLOptionElement).value,+ );+ expect(optionValues).toEqual(['production', 'p3', 'p2', 'p1']);+ expect(+ screen.getByText('com_agents_instructions_prompt_production_version:{"0":"2"}'),+ ).toBeInTheDocument();+ });++ it('selecting a version produces an exact selection', () => {+ mockGroupsQuery.data = [group()];+ mockPromptsQuery.data = [prompt({ _id: 'p2' }), prompt({ _id: 'p1' })];+ let methods: UseFormReturn<AgentForm> | undefined;+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ }}+ onMethods={(m) => (methods = m)}+ />,+ );++ fireEvent.change(+ screen.getByRole('combobox', { name: 'com_agents_instructions_prompt_version_label' }),+ { target: { value: 'p1' } },+ );++ expect(methods?.getValues('instructionsPrompt')).toEqual({+ source: 'native',+ groupId: 'group1',+ selection: { type: 'exact', promptId: 'p1' },+ });+ });++ it('disables the Version dropdown until a prompt group is selected', () => {+ mockGroupsQuery.data = [group()];+ render(<Harness />);++ expect(+ screen.getByText('com_agents_instructions_prompt_version_placeholder'),+ ).toBeInTheDocument();+ });++ it('surfaces a 403 for the Version dropdown separately from the Prompt dropdown', () => {+ mockGroupsQuery.data = [group()];+ mockPromptsQuery.isError = true;+ mockPromptsQuery.error = { isAxiosError: true, response: { status: 403, data: {} } };+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ }}+ />,+ );++ expect(screen.getByText('com_agents_instructions_prompt_forbidden')).toBeInTheDocument();+ });++ it('guards a 200 {message} version response as a load failure, not a crash', () => {+ mockGroupsQuery.data = [group()];+ mockPromptsQuery.data = { message: 'not allowed' };+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ }}+ />,+ );++ expect(screen.getByText('com_agents_instructions_prompt_load_error')).toBeInTheDocument();+ });++ it('guards a 200 {message} group response as a load failure, not an empty library', () => {+ mockGroupsQuery.data = { message: 'not allowed' };+ render(<Harness />);++ expect(screen.getByText('com_agents_instructions_prompt_load_error')).toBeInTheDocument();+ expect(screen.queryByText('com_agents_instructions_prompt_empty')).not.toBeInTheDocument();+ });++ describe('required validation', () => {+ it('blocks the save with a localized error when Prompt mode has no group selected', async () => {+ let methods: UseFormReturn<AgentForm> | undefined;+ mockGroupsQuery.data = [group()];+ render(+ <Harness+ defaultInstructionsSource="prompt"+ defaultInstructionsPrompt={null}+ onMethods={(m) => (methods = m)}+ />,+ );++ let isValid = true;+ await act(async () => {+ isValid = await methods!.trigger('instructionsPrompt');+ });++ expect(isValid).toBe(false);+ expect(screen.getByText('com_agents_instructions_prompt_required')).toBeInTheDocument();+ });++ it('passes validation once a group is selected', async () => {+ let methods: UseFormReturn<AgentForm> | undefined;+ mockGroupsQuery.data = [group()];+ render(+ <Harness+ defaultInstructionsSource="prompt"+ defaultInstructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ }}+ onMethods={(m) => (methods = m)}+ />,+ );++ let isValid = false;+ await act(async () => {+ isValid = await methods!.trigger('instructionsPrompt');+ });++ expect(isValid).toBe(true);+ });++ it('never blocks the save on a restricted stub', async () => {+ let methods: UseFormReturn<AgentForm> | undefined;+ render(+ <Harness+ defaultInstructionsSource="prompt"+ defaultInstructionsPrompt={{ source: 'native', restricted: true }}+ onMethods={(m) => (methods = m)}+ />,+ );++ let isValid = false;+ await act(async () => {+ isValid = await methods!.trigger('instructionsPrompt');+ });++ expect(isValid).toBe(true);+ });++ it('does not validate the link while Inline mode is selected', async () => {+ let methods: UseFormReturn<AgentForm> | undefined;+ render(+ <Harness+ defaultInstructionsSource="inline"+ defaultInstructionsPrompt={null}+ onMethods={(m) => (methods = m)}+ />,+ );++ let isValid = false;+ await act(async () => {+ isValid = await methods!.trigger('instructionsPrompt');+ });++ expect(isValid).toBe(true);+ });+ });++ describe('a restricted stub the editor cannot VIEW', () => {+ const stub = { source: 'native' as const, restricted: true as const };++ it('shows the localized "Restricted prompt" label as the current value, never a group name', () => {+ mockGroupsQuery.data = [group()];+ render(<Harness defaultInstructionsPrompt={stub} />);++ /** The listed group ("Support triage") is still a selectable option below, so this+ * checks the dropdown's current-value text specifically, not the whole document. */+ expect(screen.getByTestId('instructions-prompt-group-display-value')).toHaveTextContent(+ 'com_agents_instructions_prompt_restricted_title',+ );+ });++ it('leaves the Prompt dropdown enabled so a replacement can be picked', () => {+ mockGroupsQuery.data = [group()];+ render(<Harness defaultInstructionsPrompt={stub} />);++ expect(screen.getByRole('combobox', { name: 'com_ui_prompt' })).toBeInTheDocument();+ });++ it('disables the Version dropdown until a real group is picked', () => {+ mockGroupsQuery.data = [group()];+ render(<Harness defaultInstructionsPrompt={stub} />);++ expect(+ screen.getByText('com_agents_instructions_prompt_version_placeholder'),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole('combobox', { name: 'com_agents_instructions_prompt_version_label' }),+ ).not.toBeInTheDocument();+ });++ it('replaces the stub with a picked group through the existing handleGroupChange', () => {+ mockGroupsQuery.data = [group()];+ let methods: UseFormReturn<AgentForm> | undefined;+ render(<Harness defaultInstructionsPrompt={stub} onMethods={(m) => (methods = m)} />);++ fireEvent.change(screen.getByRole('combobox', { name: 'com_ui_prompt' }), {+ target: { value: 'group1' },+ });++ expect(methods?.getValues('instructionsPrompt')).toEqual({+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ });+ });++ it('does not show the "Prompt not found" hint for a stub, which carries no groupId', () => {+ mockGroupsQuery.data = [group()];+ render(<Harness defaultInstructionsPrompt={stub} />);++ expect(+ screen.queryByText('com_agents_instructions_prompt_not_found'),+ ).not.toBeInTheDocument();+ });+ });++ describe('a linked group missing from the listing', () => {+ it('shows a "Prompt not found" hint instead of a blank Prompt display', () => {+ mockGroupsQuery.data = [group({ _id: 'group_other', name: 'Other prompt' })];+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'native',+ groupId: 'group_missing',+ selection: { type: 'production' },+ }}+ />,+ );++ expect(screen.getByText('com_agents_instructions_prompt_not_found')).toBeInTheDocument();+ });++ it('keeps the Version dropdown usable for switching away from the missing group', () => {+ mockGroupsQuery.data = [group({ _id: 'group_other', name: 'Other prompt' })];+ mockPromptsQuery.data = [prompt({ _id: 'p2' }), prompt({ _id: 'p1' })];+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'native',+ groupId: 'group_missing',+ selection: { type: 'production' },+ }}+ />,+ );++ expect(+ screen.getByRole('combobox', { name: 'com_agents_instructions_prompt_version_label' }),+ ).toBeInTheDocument();+ });++ it('still renders the Prompt combobox so the user can pick a replacement group', () => {+ /** The backend allows removing or replacing a link to a deleted group, so the hint+ * must not replace the combobox — the user needs a control to act on it. */+ mockGroupsQuery.data = [group({ _id: 'group_other', name: 'Other prompt' })];+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'native',+ groupId: 'group_missing',+ selection: { type: 'production' },+ }}+ />,+ );++ expect(screen.getByText('com_agents_instructions_prompt_not_found')).toBeInTheDocument();+ expect(screen.getByRole('combobox', { name: 'com_ui_prompt' })).toBeInTheDocument();+ });++ it('lets the user pick a listed group to replace the missing one', () => {+ mockGroupsQuery.data = [group({ _id: 'group_other', name: 'Other prompt' })];+ let methods: UseFormReturn<AgentForm> | undefined;+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'native',+ groupId: 'group_missing',+ selection: { type: 'production' },+ }}+ onMethods={(m) => (methods = m)}+ />,+ );++ fireEvent.change(screen.getByRole('combobox', { name: 'com_ui_prompt' }), {+ target: { value: 'group_other' },+ });++ expect(methods?.getValues('instructionsPrompt')).toEqual({+ source: 'native',+ groupId: 'group_other',+ selection: { type: 'production' },+ });+ });+ });++ describe('accessible names across every render state', () => {+ const versionLabel = 'com_agents_instructions_prompt_version_label';++ it('names the Prompt field while loading', () => {+ mockGroupsQuery.isLoading = true;+ render(<Harness />);++ expect(screen.getByRole('group', { name: 'com_ui_prompt' })).toBeInTheDocument();+ });++ it('names the Prompt field on a load error', () => {+ mockGroupsQuery.isError = true;+ render(<Harness />);++ expect(screen.getByRole('group', { name: 'com_ui_prompt' })).toBeInTheDocument();+ });++ it('names the Prompt field when the library is empty', () => {+ mockGroupsQuery.data = [];+ render(<Harness />);++ expect(screen.getByRole('group', { name: 'com_ui_prompt' })).toBeInTheDocument();+ });++ it('names the Prompt field once prompts load', () => {+ mockGroupsQuery.data = [group()];+ render(<Harness />);++ expect(screen.getByRole('group', { name: 'com_ui_prompt' })).toBeInTheDocument();+ expect(screen.getByRole('combobox', { name: 'com_ui_prompt' })).toBeInTheDocument();+ });++ it('names the Prompt field when the linked group is missing', () => {+ mockGroupsQuery.data = [group({ _id: 'group_other' })];+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'native',+ groupId: 'group_missing',+ selection: { type: 'production' },+ }}+ />,+ );++ expect(screen.getByRole('group', { name: 'com_ui_prompt' })).toBeInTheDocument();+ });++ it('names the Version field before and after a group is selected', async () => {+ mockGroupsQuery.data = [group()];+ mockPromptsQuery.data = [prompt()];+ let methods: UseFormReturn<AgentForm> | undefined;+ render(<Harness onMethods={(m) => (methods = m)} />);++ expect(screen.getByRole('group', { name: versionLabel })).toBeInTheDocument();++ await act(async () => {+ methods!.setValue('instructionsPrompt', {+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ });+ });++ expect(screen.getByRole('group', { name: versionLabel })).toBeInTheDocument();+ expect(screen.getByRole('combobox', { name: versionLabel })).toBeInTheDocument();+ });+ });+});diff --git a/client/src/components/SidePanel/Agents/__tests__/RestrictedInstructionsPrompt.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/RestrictedInstructionsPrompt.spec.tsxnew file mode 100644index 0000000000..9ce9a109eb--- /dev/null+++ b/client/src/components/SidePanel/Agents/__tests__/RestrictedInstructionsPrompt.spec.tsx@@ -0,0 +1,18 @@+import { render, screen } from '@testing-library/react';+import RestrictedInstructionsPrompt from '../RestrictedInstructionsPrompt';++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++describe('RestrictedInstructionsPrompt', () => {+ it('renders a read-only notice with no group name or content', () => {+ render(<RestrictedInstructionsPrompt />);++ expect(screen.getByText('com_agents_instructions_prompt_restricted_title')).toBeInTheDocument();+ expect(+ screen.getByText('com_agents_instructions_prompt_restricted_description'),+ ).toBeInTheDocument();+ expect(screen.getByRole('note')).toBeInTheDocument();+ });+});diff --git a/client/src/components/SidePanel/Agents/__tests__/instructionsPromptUtils.spec.ts b/client/src/components/SidePanel/Agents/__tests__/instructionsPromptUtils.spec.tsnew file mode 100644index 0000000000..151b679d21--- /dev/null+++ b/client/src/components/SidePanel/Agents/__tests__/instructionsPromptUtils.spec.ts@@ -0,0 +1,138 @@+/**+ * @jest-environment jsdom+ */+import type { TPrompt } from 'librechat-data-provider';+import {+ isRestrictedInstructionsPrompt,+ buildPromptVersionOptions,+ getInstructionsPromptErrorCode,+ getHttpStatus,+} from '../instructionsPromptUtils';++const localize = (key: string, vars?: Record<string, unknown>) =>+ vars ? `${key}:${JSON.stringify(vars)}` : key;++const axiosError = (status: number, code?: string) => ({+ isAxiosError: true,+ response: { status, data: code ? { code } : {} },+});++describe('isRestrictedInstructionsPrompt', () => {+ it('returns false for null and undefined', () => {+ expect(isRestrictedInstructionsPrompt(null)).toBe(false);+ expect(isRestrictedInstructionsPrompt(undefined)).toBe(false);+ });++ it('returns false for a real link', () => {+ expect(+ isRestrictedInstructionsPrompt({+ source: 'native',+ groupId: 'g1',+ selection: { type: 'production' },+ }),+ ).toBe(false);+ });++ it('returns true for the restricted stub', () => {+ expect(isRestrictedInstructionsPrompt({ source: 'native', restricted: true })).toBe(true);+ });+});++describe('buildPromptVersionOptions', () => {+ const prompts: TPrompt[] = [+ {+ _id: 'p3',+ groupId: 'g1',+ author: 'a',+ prompt: 'newest',+ type: 'text',+ createdAt: '',+ updatedAt: '',+ },+ {+ _id: 'p2',+ groupId: 'g1',+ author: 'a',+ prompt: 'middle',+ type: 'text',+ createdAt: '',+ updatedAt: '',+ },+ {+ _id: 'p1',+ groupId: 'g1',+ author: 'a',+ prompt: 'oldest',+ type: 'text',+ createdAt: '',+ updatedAt: '',+ },+ ];++ it('lists Production first, then versions newest to oldest', () => {+ const options = buildPromptVersionOptions(prompts, undefined, localize);++ expect(options.map((option) => option.value)).toEqual(['production', 'p3', 'p2', 'p1']);+ expect(options[0].selection).toEqual({ type: 'production' });+ expect(options[1]).toEqual({+ value: 'p3',+ label: 'com_ui_version_var:{"0":"3"}',+ selection: { type: 'exact', promptId: 'p3' },+ });+ expect(options[3]).toEqual({+ value: 'p1',+ label: 'com_ui_version_var:{"0":"1"}',+ selection: { type: 'exact', promptId: 'p1' },+ });+ });++ it('labels Production with its display number when the revision is known', () => {+ const options = buildPromptVersionOptions(prompts, 'p2', localize);++ expect(options[0].label).toBe('com_agents_instructions_prompt_production_version:{"0":"2"}');+ });++ it('falls back to a plain Production label when the revision is unknown', () => {+ const options = buildPromptVersionOptions(prompts, 'not-in-group', localize);++ expect(options[0].label).toBe('com_ui_production');+ });++ it('falls back to a plain Production label when no production id is given', () => {+ const options = buildPromptVersionOptions(prompts, null, localize);++ expect(options[0].label).toBe('com_ui_production');+ });+});++describe('getHttpStatus', () => {+ it('reads the status off an axios-shaped error', () => {+ expect(getHttpStatus(axiosError(403))).toBe(403);+ });++ it('returns undefined for a non-HTTP error', () => {+ expect(getHttpStatus(new Error('network down'))).toBeUndefined();+ });+});++describe('getInstructionsPromptErrorCode', () => {+ it('reads a known error code off the response body', () => {+ expect(getInstructionsPromptErrorCode(axiosError(403, 'instructions_prompt_forbidden'))).toBe(+ 'instructions_prompt_forbidden',+ );+ expect(getInstructionsPromptErrorCode(axiosError(400, 'instructions_prompt_unavailable'))).toBe(+ 'instructions_prompt_unavailable',+ );+ expect(+ getInstructionsPromptErrorCode(axiosError(500, 'instructions_prompt_validation_failed')),+ ).toBe('instructions_prompt_validation_failed');+ });++ it('returns undefined for an unrecognized code', () => {+ expect(getInstructionsPromptErrorCode(axiosError(400, 'some_other_code'))).toBeUndefined();+ });++ it('returns undefined for a non-HTTP error', () => {+ expect(getInstructionsPromptErrorCode(new Error('offline'))).toBeUndefined();+ });+});diff --git a/client/src/components/SidePanel/Agents/instructionsPromptUtils.ts b/client/src/components/SidePanel/Agents/instructionsPromptUtils.tsnew file mode 100644index 0000000000..be78d53b79--- /dev/null+++ b/client/src/components/SidePanel/Agents/instructionsPromptUtils.ts@@ -0,0 +1,83 @@+import axios from 'axios';+import { InstructionsPromptErrorCode } from 'librechat-data-provider';+import type {+ TPrompt,+ AgentInstructionsPrompt,+ RestrictedAgentInstructionsPrompt,+ AgentInstructionsPromptSelection,+} from 'librechat-data-provider';+import type { TranslationKeys } from '~/hooks';++/** Narrows a link field to the restricted stub the server returns when the editor+ * cannot VIEW the linked group. The stub carries no `groupId`, so callers must+ * branch on this before reading group identity off the value. */+export const isRestrictedInstructionsPrompt = (+ value: AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null | undefined,+): value is RestrictedAgentInstructionsPrompt =>+ value != null && (value as RestrictedAgentInstructionsPrompt).restricted === true;++export type PromptVersionOption = {+ value: string;+ label: string;+ selection: AgentInstructionsPromptSelection;+};++/**+ * Builds the Version dropdown options for a prompt group's revisions.+ * "Production" is always first, labelled with the current production revision's+ * display number when it can be matched by `_id` against `productionId`. The+ * revisions that follow are labelled "Version N", newest to oldest, matching the+ * display ordinal used in `client/src/components/Prompts/display/PromptVersions.tsx`.+ */+export function buildPromptVersionOptions(+ prompts: TPrompt[],+ productionId: string | null | undefined,+ localize: (key: TranslationKeys, vars?: Record<string, unknown>) => string,+): PromptVersionOption[] {+ const total = prompts.length;+ const productionIndex =+ productionId != null ? prompts.findIndex((prompt) => prompt._id === productionId) : -1;+ const productionLabel =+ productionIndex >= 0+ ? localize('com_agents_instructions_prompt_production_version', {+ 0: String(total - productionIndex),+ })+ : localize('com_ui_production');++ const versionOptions: PromptVersionOption[] = prompts.map((prompt, index) => ({+ value: prompt._id ?? '',+ label: localize('com_ui_version_var', { 0: String(total - index) }),+ selection: { type: 'exact', promptId: prompt._id ?? '' },+ }));++ return [+ { value: 'production', label: productionLabel, selection: { type: 'production' } },+ ...versionOptions,+ ];+}++/** Stable, machine-readable codes mapped to a localized copy key each. */+export const instructionsPromptErrorKeys: Record<InstructionsPromptErrorCode, TranslationKeys> = {+ [InstructionsPromptErrorCode.UNAVAILABLE]: 'com_agents_instructions_prompt_error_unavailable',+ [InstructionsPromptErrorCode.FORBIDDEN]: 'com_agents_instructions_prompt_error_forbidden',+ [InstructionsPromptErrorCode.VALIDATION_FAILED]:+ 'com_agents_instructions_prompt_error_validation_failed',+};++/** Reads the stable error code an agent-write failure carried, when the server sent one. */+export function getInstructionsPromptErrorCode(+ error: unknown,+): InstructionsPromptErrorCode | undefined {+ if (!axios.isAxiosError(error)) {+ return undefined;+ }+ const code: unknown = error.response?.data?.code;+ return typeof code === 'string' && code in instructionsPromptErrorKeys+ ? (code as InstructionsPromptErrorCode)+ : undefined;+}++/** Returns the HTTP response status of an error, or `undefined` for a non-HTTP failure. */+export function getHttpStatus(error: unknown): number | undefined {+ return axios.isAxiosError(error) ? error.response?.status : undefined;+}diff --git a/client/src/data-provider/Agents/__tests__/mutations.test.ts b/client/src/data-provider/Agents/__tests__/mutations.test.tsindex 0cf839de97..f79a405d93 100644--- a/client/src/data-provider/Agents/__tests__/mutations.test.ts+++ b/client/src/data-provider/Agents/__tests__/mutations.test.ts@@ -177,6 +177,45 @@ describe('useUpdateAgentMutation', () => {isEditable: false,});});++ it('writes the server response straight into the expanded cache, redaction included', async () => {+ /** Every full-agent response is now redacted server-side (PATCH, duplicate, revert,+ * avatar, versions, actions), so the client no longer guards the cache against a+ * write response that carries an unredacted link: it trusts and stores whatever+ * `instructionsPrompt` the server returns, restricted stub or real link alike. */+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const agentId = 'agent_relinked';+ const expandedKey = [QueryKeys.agent, agentId, 'expanded'];+ const stub = { source: 'native' as const, restricted: true as const };+ queryClient.setQueryData<Agent>(expandedKey, {+ ...createAgent(agentId),+ instructionsPrompt: stub,+ });++ const newLink = {+ source: 'native' as const,+ groupId: 'group_2',+ selection: { type: 'production' as const },+ };+ const response = createAgent(agentId);+ response.instructionsPrompt = newLink;+ jest.mocked(dataService.updateAgent).mockResolvedValue(response);++ const { result } = renderHook(() => useUpdateAgentMutation(), {+ wrapper: createWrapper(queryClient),+ });++ await act(async () => {+ await result.current.mutateAsync({+ agent_id: agentId,+ data: { instructionsPrompt: newLink },+ });+ });++ expect(queryClient.getQueryData<Agent>(expandedKey)?.instructionsPrompt).toEqual(newLink);+ });});describe('useDuplicateAgentMutation', () => {diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex eac4b19b2f..b2e873d112 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -223,6 +223,25 @@"com_agents_filter_mine": "Only Agents I created","com_agents_grid_announcement": "Showing {{count}} agents in {{category}} category","com_agents_instructions_placeholder": "The system instructions that the agent uses",+ "com_agents_instructions_prompt_empty": "No prompts available",+ "com_agents_instructions_prompt_error_forbidden": "You don't have permission to link this prompt.",+ "com_agents_instructions_prompt_error_unavailable": "This prompt selection isn't available right now.",+ "com_agents_instructions_prompt_error_validation_failed": "Couldn't validate the linked prompt. Please try again.",+ "com_agents_instructions_prompt_forbidden": "You don't have access to the prompt library.",+ "com_agents_instructions_prompt_load_error": "Couldn't load prompts.",+ "com_agents_instructions_prompt_not_found": "Prompt not found",+ "com_agents_instructions_prompt_production_version": "Production (Version {{0}})",+ "com_agents_instructions_prompt_required": "Select a prompt to use as the agent's instructions.",+ "com_agents_instructions_prompt_restricted_description": "You don't have access to view this linked prompt. You can replace it or switch to inline instructions.",+ "com_agents_instructions_prompt_restricted_title": "Restricted prompt",+ "com_agents_instructions_prompt_search_placeholder": "Search prompts by name",+ "com_agents_instructions_prompt_select_placeholder": "Select a prompt",+ "com_agents_instructions_prompt_version_label": "Version",+ "com_agents_instructions_prompt_version_placeholder": "Select a prompt first",+ "com_agents_instructions_prompt_version_select_placeholder": "Select a version",+ "com_agents_instructions_source_inline": "Inline",+ "com_agents_instructions_source_prompt": "Prompt",+ "com_agents_instructions_source_toggle_aria": "Instructions source","com_agents_link_copied": "Link copied","com_agents_link_copy_failed": "Failed to copy link","com_agents_load_more_label": "Load more agents from {{category}} category",diff --git a/client/src/utils/forms.tsx b/client/src/utils/forms.tsxindex 11d481adf8..5b8e845acb 100644--- a/client/src/utils/forms.tsx+++ b/client/src/utils/forms.tsx@@ -53,6 +53,8 @@ export const getDefaultAgentFormValues = (avatar_preview: '',avatar_action: null,conversation_starter_draft: '',+ instructionsSource: 'inline' as const,+ instructionsPrompt: null,});export const processAgentOption = ({diff --git a/e2e/specs/mock/agent-handoffs.spec.ts b/e2e/specs/mock/agent-handoffs.spec.tsindex a4c13f83f8..a0e1b427f7 100644--- a/e2e/specs/mock/agent-handoffs.spec.ts+++ b/e2e/specs/mock/agent-handoffs.spec.ts@@ -116,7 +116,7 @@ async function configureNewAgent(page: Page, name: string): Promise<Locator> {let form = await startNewAgent(page);await form.getByLabel('Agent name').fill(name);await form.getByLabel('Agent description').fill(DESCRIPTION);- await form.getByLabel('Instructions').fill(INSTRUCTIONS);+ await form.getByRole('textbox', { name: 'Instructions', exact: true }).fill(INSTRUCTIONS);await selectMockModel(page, true);form = page.getByRole('form', { name: 'Agent configuration form' });return form;diff --git a/e2e/specs/mock/agent-skills.spec.ts b/e2e/specs/mock/agent-skills.spec.tsindex f5811b1c51..89c3209603 100644--- a/e2e/specs/mock/agent-skills.spec.ts+++ b/e2e/specs/mock/agent-skills.spec.ts@@ -692,7 +692,7 @@ test.describe('Agent Builder skills', () => {await createSkillDialog.getByLabel('Name').fill(skillName);await createSkillDialog.getByLabel('Description').fill(INLINE_SKILL_DESCRIPTION);await createSkillDialog- .getByLabel('Instructions')+ .getByRole('textbox', { name: 'Instructions', exact: true }).fill(`# ${skillName}\n\nCreated inline from Agent Builder.`);const skillResponsePromise = page.waitForResponse(diff --git a/e2e/specs/mock/agents.spec.ts b/e2e/specs/mock/agents.spec.tsindex 96b129e13f..424e5aa645 100644--- a/e2e/specs/mock/agents.spec.ts+++ b/e2e/specs/mock/agents.spec.ts@@ -133,7 +133,7 @@ test.describe('agent builder', () => {await form.getByLabel('Agent name').fill(agentName);await form.getByLabel('Agent description').fill(DESCRIPTION);- await form.getByLabel('Instructions').fill(INSTRUCTIONS);+ await form.getByRole('textbox', { name: 'Instructions', exact: true }).fill(INSTRUCTIONS);await selectMockModel(page);await fillAnthropicStyleModelParameters(page);@@ -180,7 +180,9 @@ test.describe('agent builder', () => {await expect(form.getByLabel('Agent name')).toHaveValue(agentName);await expect(form.getByLabel('Agent description')).toHaveValue(DESCRIPTION);- await expect(form.getByLabel('Instructions')).toHaveValue(INSTRUCTIONS);+ await expect(form.getByRole('textbox', { name: 'Instructions', exact: true })).toHaveValue(+ INSTRUCTIONS,+ );await form.locator('label[for="provider"] + button').click();await expectAnthropicStyleModelParameters(page);diff --git a/e2e/specs/mock/mcp.spec.ts b/e2e/specs/mock/mcp.spec.tsindex 5aebaf14b8..bdce5b151b 100644--- a/e2e/specs/mock/mcp.spec.ts+++ b/e2e/specs/mock/mcp.spec.ts@@ -93,7 +93,7 @@ test.describe('agent builder MCP tools', () => {await form.getByLabel('Agent name').fill(agentName);await form.getByLabel('Agent description').fill(DESCRIPTION);- await form.getByLabel('Instructions').fill(INSTRUCTIONS);+ await form.getByRole('textbox', { name: 'Instructions', exact: true }).fill(INSTRUCTIONS);await selectMockModel(page, true);await addMCPServerTools(page, form);@@ -136,7 +136,9 @@ test.describe('agent builder MCP tools', () => {await expect(reopenedForm.getByLabel('Agent name')).toHaveValue(agentName);await expect(reopenedForm.getByLabel('Agent description')).toHaveValue(DESCRIPTION);- await expect(reopenedForm.getByLabel('Instructions')).toHaveValue(INSTRUCTIONS);+ await expect(+ reopenedForm.getByRole('textbox', { name: 'Instructions', exact: true }),+ ).toHaveValue(INSTRUCTIONS);await expectSelectedMCPServerTools(reopenedForm);await reopenedForm.getByRole('button', { name: 'Select Agent' }).click();diff --git a/e2e/specs/mock/scenarios/agent-conversation-starters.spec.ts b/e2e/specs/mock/scenarios/agent-conversation-starters.spec.tsindex e166609edf..b3ff1c4221 100644--- a/e2e/specs/mock/scenarios/agent-conversation-starters.spec.ts+++ b/e2e/specs/mock/scenarios/agent-conversation-starters.spec.ts@@ -95,7 +95,9 @@ test.describe('agent conversation starters', () => {}form = builderForm(page);await form.getByLabel('Agent name').fill(name);- await form.getByLabel('Instructions').fill('Answer with the mock model.');+ await form+ .getByRole('textbox', { name: 'Instructions', exact: true })+ .fill('Answer with the mock model.');await selectMockModel(page, true);form = builderForm(page);diff --git a/eslint-suppressions.json b/eslint-suppressions.jsonindex daa7384f8b..deb401503a 100644--- a/eslint-suppressions.json+++ b/eslint-suppressions.json@@ -1583,14 +1583,6 @@"count": 3}},- "client/src/components/SidePanel/Agents/Instructions.tsx": {- "shadcn/no-arbitrary-values": {- "count": 1- },- "shadcn/no-restyle": {- "count": 5- }- },"client/src/components/SidePanel/Agents/MCPIcon.tsx": {"shadcn/no-inline-styles": {"count": 1diff --git a/packages/api/src/agents/__tests__/initialize.test.ts b/packages/api/src/agents/__tests__/initialize.test.tsindex 8953ad2f42..eb0042ebc8 100644--- a/packages/api/src/agents/__tests__/initialize.test.ts+++ b/packages/api/src/agents/__tests__/initialize.test.ts@@ -50,8 +50,9 @@ import {configSchema,} from 'librechat-data-provider';import type { IMongoFile } from '@librechat/data-schemas';-import type { Agent, TFile, FiltersConfig } from 'librechat-data-provider';+import type { Agent, TFile, FiltersConfig, AgentInstructionsPrompt } from 'librechat-data-provider';import type { ServerRequest, InitializeResultBase, EndpointTokenConfig } from '~/types';+import type { ResolveLinkedInstructions } from '../instructions/linked';import type { InitializeAgentDbMethods } from '../initialize';import type { CodeExecutionContext } from '../execution';import type { GraphSubagentHostConfig } from '../discovery';@@ -5469,6 +5470,368 @@ describe('initializeAgent — provider-native web search role gate', () => {});});+describe('initializeAgent — linked instructions', () => {+ const link: AgentInstructionsPrompt = {+ source: 'native',+ groupId: 'group-1',+ selection: { type: 'production' },+ };++ const flush = () => new Promise((resolve) => setImmediate(resolve));++ /** `ResolveLinkedInstructions` is a callable that also carries a `recordUse`+ * method (see `../instructions/linked`); a bare `jest.fn()` has no such+ * property, so tests build the mock the same shape the real resolver has. */+ type ResolveLinkedInstructionsMock = jest.Mock<+ ReturnType<ResolveLinkedInstructions>,+ Parameters<ResolveLinkedInstructions>+ > & { recordUse: jest.Mock };+ function makeResolveLinkedInstructions(): ResolveLinkedInstructionsMock {+ const resolve = jest.fn() as unknown as ResolveLinkedInstructionsMock;+ return Object.assign(resolve, { recordUse: jest.fn() });+ }++ const run = async ({+ agentOverrides,+ reqOverrides,+ params = {},+ loadToolsOverride,+ }: {+ agentOverrides?: Partial<Agent>;+ reqOverrides?: Partial<ServerRequest>;+ params?: Partial<Parameters<typeof initializeAgent>[0]>;+ loadToolsOverride?: (loadTools: ReturnType<typeof createMocks>['loadTools']) => void;+ }) => {+ const { agent, req, res, loadTools, db } = createMocks({});+ Object.assign(agent, agentOverrides);+ Object.assign(req, reqOverrides);+ loadToolsOverride?.(loadTools);+ return initializeAgent(+ {+ req,+ res,+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ isInitialAgent: true,+ ...params,+ },+ db,+ );+ };++ beforeEach(() => {+ (logger.warn as jest.Mock).mockClear?.();+ });++ it('resolves a linked agent, still applies special-vars substitution, and records exactly one usage', async () => {+ const resolveLinkedInstructions = makeResolveLinkedInstructions();+ resolveLinkedInstructions.mockResolvedValue({+ status: 'resolved',+ prompt: 'Hello {{current_user}}, be concise.',+ facts: { source: 'native', groupId: 'group-1', promptId: 'prompt-1' },+ });++ const result = await run({+ agentOverrides: { instructionsPrompt: link },+ reqOverrides: { user: { id: 'user-1', name: 'Ada' } as never },+ params: { resolveLinkedInstructions },+ });+ await flush();++ expect(resolveLinkedInstructions).toHaveBeenCalledWith(expect.objectContaining({ link }));+ expect(result.instructions).toBe('Hello Ada, be concise.');+ expect(result.instructionsPromptFacts).toEqual({+ source: 'native',+ groupId: 'group-1',+ promptId: 'prompt-1',+ });+ expect(resolveLinkedInstructions.recordUse).toHaveBeenCalledTimes(1);+ expect(resolveLinkedInstructions.recordUse).toHaveBeenCalledWith({+ source: 'native',+ groupId: 'group-1',+ promptId: 'prompt-1',+ });+ });++ it('falls back to empty instructions with a warning, and records no usage, when the link is unavailable', async () => {+ const resolveLinkedInstructions = makeResolveLinkedInstructions();+ resolveLinkedInstructions.mockResolvedValue({ status: 'unavailable', reason: 'timeout' });++ const result = await run({+ agentOverrides: { instructionsPrompt: link, instructions: 'stale inline text' },+ params: { resolveLinkedInstructions },+ });+ await flush();++ expect(result.instructions).toBe('');+ expect(result.instructionsPromptFacts).toBeUndefined();+ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('group-1'));+ expect(resolveLinkedInstructions.recordUse).not.toHaveBeenCalled();+ });++ it('falls back to empty instructions with a warning when no resolver is provided', async () => {+ const result = await run({+ agentOverrides: { instructionsPrompt: link, instructions: 'stale inline text' },+ });++ expect(result.instructions).toBe('');+ expect(result.instructionsPromptFacts).toBeUndefined();+ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('group-1'));+ });++ it('leaves an unlinked agent unchanged, never calls the resolver, and records no usage', async () => {+ const resolveLinkedInstructions = makeResolveLinkedInstructions();++ const result = await run({+ agentOverrides: { instructions: 'Be helpful.' },+ params: { resolveLinkedInstructions },+ });+ await flush();++ expect(resolveLinkedInstructions).not.toHaveBeenCalled();+ expect(result.instructions).toBe('Be helpful.');+ expect(result.instructionsPromptFacts).toBeUndefined();+ expect(resolveLinkedInstructions.recordUse).not.toHaveBeenCalled();+ });++ it('resolves and initializes normally, but records no usage, when recordLinkedPromptUsage is false', async () => {+ const resolveLinkedInstructions = makeResolveLinkedInstructions();+ resolveLinkedInstructions.mockResolvedValue({+ status: 'resolved',+ prompt: 'Fixed instructions.',+ facts: { source: 'native', groupId: 'group-1', promptId: 'prompt-1' },+ });++ const result = await run({+ agentOverrides: { instructionsPrompt: link },+ params: { resolveLinkedInstructions, recordLinkedPromptUsage: false },+ });+ await flush();++ expect(result.instructions).toBe('Fixed instructions.');+ expect(resolveLinkedInstructions).toHaveBeenCalledWith(expect.objectContaining({ link }));+ expect(resolveLinkedInstructions.recordUse).not.toHaveBeenCalled();+ });++ it('records no usage when initializeAgent throws after a successful resolution', async () => {+ const resolveLinkedInstructions = makeResolveLinkedInstructions();+ resolveLinkedInstructions.mockResolvedValue({+ status: 'resolved',+ prompt: 'Fixed instructions.',+ facts: { source: 'native', groupId: 'group-1', promptId: 'prompt-1' },+ });+ const failure = new Error('boom after resolution');++ await expect(+ run({+ agentOverrides: { instructionsPrompt: link },+ params: { resolveLinkedInstructions },+ loadToolsOverride: (loadTools) =>+ loadTools.mockResolvedValue({+ tools: [],+ toolContextMap: {},+ dynamicToolContextMap: {},+ toolDefinitions: [],+ hasDeferredTools: false,+ // Rejects well after the instructions block has resolved and set+ // `agent.instructions`, so the throw happens on the way OUT.+ repositoryInstructionSource: { load: jest.fn().mockRejectedValue(failure) },+ }),+ }),+ ).rejects.toBe(failure);+ await flush();++ expect(resolveLinkedInstructions.recordUse).not.toHaveBeenCalled();+ });++ it('does not throw when the resolver is a plain function with no recordUse (a successful init still returns normally)', async () => {+ // `resolveLinkedInstructions` is typed as a plain callable in+ // `InitializeAgentParams`; a caller-supplied function that matches the+ // type but not the real resolver's `Object.assign(resolve, { recordUse })`+ // shape must not throw after initialization has already succeeded.+ const resolveLinkedInstructions: ResolveLinkedInstructions = jest.fn().mockResolvedValue({+ status: 'resolved',+ prompt: 'Fixed instructions.',+ facts: { source: 'native', groupId: 'group-1', promptId: 'prompt-1' },+ }) as unknown as ResolveLinkedInstructions;++ const result = await run({+ agentOverrides: { instructionsPrompt: link },+ params: { resolveLinkedInstructions },+ });+ await flush();++ expect(result.instructions).toBe('Fixed instructions.');+ });++ it('does not produce an unhandled rejection when the resolution rejects before it is awaited', async () => {+ const unhandled: unknown[] = [];+ const onUnhandledRejection = (reason: unknown): void => {+ unhandled.push(reason);+ };+ process.on('unhandledRejection', onUnhandledRejection);+ try {+ const rejection = new Error('rejected before the instructions block awaits it');+ const resolveLinkedInstructions = makeResolveLinkedInstructions();+ // Rejects on the same tick it's called — well before `initializeAgent`+ // reaches the instructions block, since that only happens after tool+ // loading (delayed below) and several other steps.+ resolveLinkedInstructions.mockImplementation(() => Promise.reject(rejection));++ await expect(+ run({+ agentOverrides: { instructionsPrompt: link },+ params: { resolveLinkedInstructions },+ loadToolsOverride: (loadTools) =>+ loadTools.mockImplementation(+ () =>+ new Promise((resolve) => {+ setTimeout(+ () =>+ resolve({+ tools: [],+ toolContextMap: {},+ dynamicToolContextMap: {},+ toolDefinitions: [],+ hasDeferredTools: false,+ }),+ 10,+ );+ }),+ ),+ }),+ ).rejects.toBe(rejection);++ // Give the process a turn to report an unhandled rejection, if any occurred.+ await flush();+ } finally {+ process.off('unhandledRejection', onUnhandledRejection);+ }+ expect(unhandled).toEqual([]);+ });+});++describe('initializeAgent — linked instructions and the agent-definition content policy', () => {+ const link: AgentInstructionsPrompt = {+ source: 'native',+ groupId: 'group-1',+ selection: { type: 'production' },+ };+ const blockingAgentInstructionsFilters: FiltersConfig = {+ agentInstructions: {+ pii: {+ starterPatterns: [],+ customPatterns: [{ id: 'secret', label: 'secret value', regex: 'SECRET-[A-Z]+' }],+ fields: ['instructions'],+ },+ },+ };++ it('blocks a stored inline instructions field that trips the policy when there is no link', async () => {+ const { agent, req, res, loadTools, db } = createMocks({});+ agent.instructions = 'Contains SECRET-VALUE marker';+ Object.assign(req, { config: { filters: blockingAgentInstructionsFilters } });++ await expect(+ initializeAgent(+ {+ req,+ res,+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ isInitialAgent: true,+ },+ db,+ ),+ ).rejects.toThrow();+ });++ it('excludes the stored inline instructions from that scan when the agent has a valid link', async () => {+ const { agent, req, res, loadTools, db } = createMocks({});+ Object.assign(agent, {+ instructionsPrompt: link,+ instructions: 'Contains SECRET-VALUE marker',+ });+ Object.assign(req, { config: { filters: blockingAgentInstructionsFilters } });+ const resolveLinkedInstructions = jest.fn().mockResolvedValue({+ status: 'resolved',+ prompt: 'Safe resolved prompt.',+ facts: { source: 'native', groupId: 'group-1', promptId: 'prompt-1' },+ });+ Object.assign(resolveLinkedInstructions, { recordUse: jest.fn() });++ const result = await initializeAgent(+ {+ req,+ res,+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ isInitialAgent: true,+ resolveLinkedInstructions:+ resolveLinkedInstructions as unknown as ResolveLinkedInstructions,+ },+ db,+ );++ expect(result.instructions).toBe('Safe resolved prompt.');+ });++ it('never calls the resolver when the definition-content check rejects a field other than instructions', async () => {+ const { agent, req, res, loadTools, db } = createMocks({});+ Object.assign(agent, {+ instructionsPrompt: link,+ // The stored inline `instructions` are excluded from the scan by the+ // link (see the test above), but `description` is not — the check+ // must still run, and reject, before the resolver is ever started.+ description: 'Contains SECRET-VALUE marker',+ });+ Object.assign(req, {+ config: {+ filters: {+ agentInstructions: {+ pii: {+ starterPatterns: [],+ customPatterns: [{ id: 'secret', label: 'secret value', regex: 'SECRET-[A-Z]+' }],+ fields: ['description'],+ },+ },+ },+ },+ });+ const resolveLinkedInstructions = jest.fn().mockResolvedValue({+ status: 'resolved',+ prompt: 'Safe resolved prompt.',+ facts: { source: 'native', groupId: 'group-1', promptId: 'prompt-1' },+ });+ Object.assign(resolveLinkedInstructions, { recordUse: jest.fn() });++ await expect(+ initializeAgent(+ {+ req,+ res,+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ isInitialAgent: true,+ resolveLinkedInstructions:+ resolveLinkedInstructions as unknown as ResolveLinkedInstructions,+ },+ db,+ ),+ ).rejects.toThrow();++ expect(resolveLinkedInstructions).not.toHaveBeenCalled();+ });+});+describe('initializeAgent tool-routed text fallback', () => {beforeEach(() => {jest.clearAllMocks();diff --git a/packages/api/src/agents/discovery.spec.ts b/packages/api/src/agents/discovery.spec.tsindex 16a19f5f4a..a7fbb6e36c 100644--- a/packages/api/src/agents/discovery.spec.ts+++ b/packages/api/src/agents/discovery.spec.ts@@ -339,6 +339,41 @@ describe('discoverConnectedAgents', () => {);});+ /** Unlike `resolveWebSearchGrant`, there is no default DB-backed resolution path+ * for a linked agent — dropping the resolver here silently loses its instructions+ * one hop into a handoff. */+ it('forwards resolveLinkedInstructions and recordLinkedPromptUsage to every handoff initializeAgent call', async () => {+ const primaryConfig = makeConfig('A', [{ from: 'A', to: 'B', edgeType: 'handoff' }]);+ const getAgent = jest.fn(async () => makeAgent('B', []));+ // `ResolveLinkedInstructions` also carries a `recordUse` method (see+ // `./instructions/linked`); a bare `jest.fn()` lacks it.+ const resolveLinkedInstructions = Object.assign(jest.fn(), { recordUse: jest.fn() });++ await discoverConnectedAgents(+ {+ req: makeReq(),+ res: makeRes(),+ primaryConfig,+ allowedProviders: new Set(),+ modelsConfig: { openai: ['gpt-4o'] },+ loadTools: jest.fn(),+ resolveLinkedInstructions,+ recordLinkedPromptUsage: false,+ },+ {+ getAgent,+ checkPermission: jest.fn().mockResolvedValue(true),+ logViolation: jest.fn(),+ db: {} as never,+ },+ );++ expect(mockInitializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ resolveLinkedInstructions, recordLinkedPromptUsage: false }),+ expect.anything(),+ );+ });+it('forwards normalized request metadata to every handoff initializeAgent call', async () => {const primaryConfig = makeConfig('A', [{ from: 'A', to: 'B', edgeType: 'handoff' }]);const getAgent = jest.fn(async () => makeAgent('B', []));diff --git a/packages/api/src/agents/discovery.ts b/packages/api/src/agents/discovery.tsindex bbe5f85def..18b9cb4f77 100644--- a/packages/api/src/agents/discovery.ts+++ b/packages/api/src/agents/discovery.ts@@ -121,6 +121,15 @@ export interface DiscoverConnectedAgentsParams {* request-memoized read as its parent.*/resolveWebSearchGrant?: InitializeAgentParams['resolveWebSearchGrant'];+ /**+ * Resolves a handoff/subagent's own `instructionsPrompt` link, forwarded so+ * every discovered agent honors its link the same way the primary does.+ * There is no default resolution path, unlike `resolveWebSearchGrant` —+ * omitting it leaves a linked handoff agent with empty instructions.+ */+ resolveLinkedInstructions?: InitializeAgentParams['resolveLinkedInstructions'];+ /** Forwarded verbatim; the resume path sets this `false` for every discovered agent. */+ recordLinkedPromptUsage?: InitializeAgentParams['recordLinkedPromptUsage'];/** Sibling of `codeEnvAvailable` — the `stateful_code_sessions` capability flag, forwarded to every handoff `initializeAgent`. */statefulSessionsAvailable?: InitializeAgentParams['statefulSessionsAvailable'];/** Deployment policy for stateful workspace scopes, forwarded unchanged to every referenced agent. */@@ -271,6 +280,8 @@ async function initializeReferencedAgent(codeEnvAvailable: params.codeEnvAvailable,fileSearchAvailable: params.fileSearchAvailable,resolveWebSearchGrant: params.resolveWebSearchGrant,+ resolveLinkedInstructions: params.resolveLinkedInstructions,+ recordLinkedPromptUsage: params.recordLinkedPromptUsage,backgroundToolsAvailable: params.backgroundToolsAvailable,toolIntentsAvailable: params.toolIntentsAvailable,statefulSessionsAvailable: params.statefulSessionsAvailable,diff --git a/packages/api/src/agents/hitl/protection.spec.ts b/packages/api/src/agents/hitl/protection.spec.tsindex 26c877cdc9..86f0220a26 100644--- a/packages/api/src/agents/hitl/protection.spec.ts+++ b/packages/api/src/agents/hitl/protection.spec.ts@@ -717,4 +717,114 @@ describe('assertResumeRuntimeContentAllowed', () => {expect(dependencies.getUserMemories).not.toHaveBeenCalled();expect(dependencies.decryptMetadata).not.toHaveBeenCalled();});++ describe('linked agent instructions', () => {+ const basePolicyDependencies = (): ResumeContentProtectionDependencies => ({+ ...createDependencies(),+ checkAccess: jest.fn().mockResolvedValue(false),+ getAgent: jest.fn(),+ getActions: jest.fn().mockResolvedValue([]),+ getUserMemories: jest.fn().mockResolvedValue([]),+ getRoleByName: jest.fn(),+ decryptMetadata: jest.fn(),+ canAccessAgent: jest.fn().mockResolvedValue(true),+ });+ const agentInstructionsPolicy = {+ filters: {+ agentInstructions: {+ pii: {+ starterPatterns: [],+ customPatterns: [{ id: 'private', label: 'private', regex: 'PRIVATE-[A-Z]+' }],+ },+ },+ },+ };++ it('rejects a stored inline instructions field that trips the policy when there is no link', async () => {+ const input = {+ appConfig: agentInstructionsPolicy,+ endpointOption: {+ agent: Promise.resolve({+ id: 'agent-1',+ provider: 'openai',+ model: 'test-model',+ instructions: 'Contains PRIVATE-INSTRUCTION marker',+ }),+ },+ conversationId: 'conversation-1',+ targetMessageId: null,+ user,+ storedMessages: [],+ seedContent: [],+ liveFiles: [],+ isTemporary: true,+ } as unknown as Parameters<typeof assertResumeContentAllowed>[0];++ await expect(+ assertResumeContentAllowed(input, basePolicyDependencies()),+ ).rejects.toMatchObject({+ code: 'content_filter_block',+ body: { source: 'agent_instruction', field: 'instructions' },+ });+ });++ it('excludes the stored inline instructions from the same scan when the agent has a valid instructionsPrompt link', async () => {+ const input = {+ appConfig: agentInstructionsPolicy,+ endpointOption: {+ agent: Promise.resolve({+ id: 'agent-1',+ provider: 'openai',+ model: 'test-model',+ instructions: 'Contains PRIVATE-INSTRUCTION marker',+ instructionsPrompt: {+ source: 'native',+ groupId: 'group-1',+ selection: { type: 'production' },+ },+ }),+ },+ conversationId: 'conversation-1',+ targetMessageId: null,+ user,+ storedMessages: [],+ seedContent: [],+ liveFiles: [],+ isTemporary: true,+ } as unknown as Parameters<typeof assertResumeContentAllowed>[0];++ await expect(+ assertResumeContentAllowed(input, basePolicyDependencies()),+ ).resolves.toBeUndefined();+ });++ it('still inspects a restricted-stub link as no link — the stub carries no groupId to trust', async () => {+ const input = {+ appConfig: agentInstructionsPolicy,+ endpointOption: {+ agent: Promise.resolve({+ id: 'agent-1',+ provider: 'openai',+ model: 'test-model',+ instructions: 'Contains PRIVATE-INSTRUCTION marker',+ instructionsPrompt: { source: 'native', restricted: true },+ }),+ },+ conversationId: 'conversation-1',+ targetMessageId: null,+ user,+ storedMessages: [],+ seedContent: [],+ liveFiles: [],+ isTemporary: true,+ } as unknown as Parameters<typeof assertResumeContentAllowed>[0];++ await expect(+ assertResumeContentAllowed(input, basePolicyDependencies()),+ ).rejects.toMatchObject({+ code: 'content_filter_block',+ body: { source: 'agent_instruction', field: 'instructions' },+ });+ });+ });});diff --git a/packages/api/src/agents/hitl/protection.ts b/packages/api/src/agents/hitl/protection.tsindex 7ba81fed60..88d2720034 100644--- a/packages/api/src/agents/hitl/protection.ts+++ b/packages/api/src/agents/hitl/protection.ts@@ -54,6 +54,7 @@ import {import { getResumeAgentSnapshot, getResumeContentInspection } from './inspection';import { extractStoredMessageContent } from '~/protection/adapters/submissions';import { agentHasInlineMemoryTools, getMemoryAgentId } from '../memory';+import { isValidInstructionsPromptLink } from '../instructions/linked';import { LIBRECHAT_CHECKPOINT_NAMESPACE_KEY } from '../checkpointer';import { AttachmentObjectNotFoundError } from '~/files/encode/utils';import { ASK_USER_QUESTION_TOOL_NAME } from './askUserQuestionTool';@@ -546,12 +547,21 @@ function assertResumeToolContentAllowed(}}+/**+ * Projects a resume snapshot agent's definition fields for the content-policy+ * scan. Excludes the stored inline `instructions` when the agent has a valid+ * `instructionsPrompt` link — matching `initializeAgent`'s init-time content+ * check, which excludes the same field for the same reason: a linked agent's+ * stored inline text is dead, unused text, superseded by the resolved prompt+ * at runtime, so it must not block a resume this scan gates.+ */function projectResumeAgentDefinition(agent: ResumeSnapshotAgent): AgentContentInput {+ const hasValidLink = isValidInstructionsPromptLink(agent.instructionsPrompt);return {name: agent.name,category: agent.category,description: agent.description,- instructions: agent.instructions,+ instructions: hasValidLink ? undefined : agent.instructions,additional_instructions: agent.additional_instructions,conversation_starters: agent.conversation_starters,edges: agent.edges?.map((edge) => ({diff --git a/packages/api/src/agents/index.ts b/packages/api/src/agents/index.tsindex d06793bc35..b8c34f34ab 100644--- a/packages/api/src/agents/index.ts+++ b/packages/api/src/agents/index.ts@@ -28,6 +28,7 @@ export * from './backgroundCompletion';export * from './backgroundClaims';export * from './backgroundCompletionWakeup';export * from './initialize';+export * from './instructions';export * from './legacy';export * from './listing';export * from './listingAvatars';diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.tsindex 2088e588b2..0e2be4a4be 100644--- a/packages/api/src/agents/initialize.ts+++ b/packages/api/src/agents/initialize.ts@@ -54,6 +54,7 @@ import type {EndpointTokenConfig,InitializeResultBase,} from '~/types';+import type { ResolveLinkedInstructions, LinkedInstructionsFacts } from './instructions/linked';import type { LCAvailableTools, RequestScopedMCPConnectionStore } from '../mcp/types';import type { ContentTraversalLimitError } from '../protection/adapters/nested';import type { SkillContentInput } from '../protection/adapters/submissions';@@ -128,6 +129,7 @@ import { createConfiguredContentInspector, inspectContent } from '../protection/import { assertAgentAttachmentLimits, isModelBoundAttachmentFile } from './attachments';import { assertModelBoundContent } from '../middleware/modelBoundContent';import { resolveAttachedWorkspaceReadFileLines } from '~/code/workspace';+import { isValidInstructionsPromptLink } from './instructions/linked';import { isImplicitStatefulCodeRouteAvailable } from '../code/config';import { PARTIAL_RESOLVED_CONVERSATION } from './conversationSymbols';import { registerMemoryTools, memoryToolUsageGuard } from './memory';@@ -886,6 +888,12 @@ export type InitializedAgent = Agent & {provisionWarnings?: string[];/** State for deferred file provisioning — actual uploads happen at tool invocation time */provisionState?: ProvisionState;+ /**+ * Facts about a resolved `instructionsPrompt` link (source, groupId,+ * resolved promptId), surfaced for AI-2158. Never persisted — omitted for+ * an agent with no link, an unresolved link, or a missing resolver.+ */+ instructionsPromptFacts?: LinkedInstructionsFacts;};export const DEFAULT_MAX_CONTEXT_TOKENS = 32000;@@ -1008,6 +1016,22 @@ export interface InitializeAgentParams {* from `db.getRoleByName`.*/resolveWebSearchGrant?: () => Promise<boolean>;+ /**+ * Resolves an agent's `instructionsPrompt` link (a linked native prompt+ * group) into instruction text. Called only when `agent.instructionsPrompt`+ * carries a resolvable `native` link. Absent, a linked agent falls back to+ * empty instructions with a warning — there is no default DB-backed+ * resolution path, unlike `resolveWebSearchGrant`, so every caller that+ * wants linked instructions honored must supply one.+ */+ resolveLinkedInstructions?: ResolveLinkedInstructions;+ /**+ * Whether resolving `agent.instructionsPrompt` should record a usage+ * generation on the linked prompt group. Defaults to `true`. Callers on the+ * resume path set this to `false` because the turn that already counted the+ * generation is being replayed, not repeated.+ */+ recordLinkedPromptUsage?: boolean;/*** Whether the `run_in_background` capability is enabled for this run. When* true, tools the agent opted in via `tool_options[name].run_in_background`@@ -1207,6 +1231,17 @@ export async function initializeAgent(throw new Error('initializeAgent requires db methods to be passed');}+ /**+ * Computed up front, before the definition-content check below, because+ * that check needs it: a valid link means the stored inline `instructions`+ * is dead text — it is overwritten below with the resolved prompt, or with+ * `''` when the link can't resolve — so it is excluded from the scan+ * rather than inspected and then discarded.+ */+ const instructionsPromptLink = isValidInstructionsPromptLink(agent.instructionsPrompt)+ ? agent.instructionsPrompt+ : undefined;+/*** Reject the stored agent definition before initialization performs usage* accounting, resource priming, tool/MCP loading, or provider setup. Inspect@@ -1215,10 +1250,11 @@ export async function initializeAgent(*/let agentFragments: readonly TextContentFragment[] = [];let agentTraversalError: ContentTraversalLimitError | null = null;+ const agentDefinitionInput = (instructionsPromptLink+ ? { ...agent, instructions: undefined }+ : agent) as unknown as Parameters<typeof extractAgentContent>[0];try {- agentFragments = extractAgentContent(- agent as unknown as Parameters<typeof extractAgentContent>[0],- );+ agentFragments = extractAgentContent(agentDefinitionInput);} catch (error) {if (!isContentTraversalLimitError(error)) {throw error;@@ -1242,6 +1278,33 @@ export async function initializeAgent(throw agentTraversalError;}+ /**+ * Independent of every other step below (tool loading, resource priming,+ * provider setup), so it starts as soon as the definition-content check+ * above has passed — rather than waiting until the instructions block,+ * well below, is reached — but never before that check: a rejected agent+ * definition must never trigger an external prompt-service call. A valid+ * link with no resolver never calls out, matching the "no resolver"+ * fallback this same shape has always had.+ */+ const linkedInstructionsPromise =+ instructionsPromptLink && params.resolveLinkedInstructions+ ? params.resolveLinkedInstructions({+ link: instructionsPromptLink,+ signal: params.signal,+ filters: appConfig?.filters,+ config: appConfig?.endpoints?.agents?.linkedInstructions,+ })+ : undefined;+ /**+ * Started well before its result is needed at the instructions block below.+ * An abort (or any other rejection) that lands before that await must not+ * surface as an unhandled rejection; this no-op handler only silences that+ * warning — the promise itself, awaited later, still carries the real+ * outcome, rejection included.+ */+ linkedInstructionsPromise?.catch(() => {});+/*** Heal legacy MCP tool keys ONCE, before anything reads them: model-facing* keys embed the normalized server name (cache keys, definition names,@@ -2463,6 +2526,36 @@ export async function initializeAgent((agent.model_parameters as Record<string, unknown>).configuration = options.configOptions;}+ /**+ * Resolves an `instructionsPrompt` link before special-vars substitution, so+ * a linked prompt's `{{current_date}}`-style placeholders are replaced the+ * same way inline instructions are. A link without a resolver, or one that+ * resolves to `unavailable`, continues the turn with empty instructions+ * rather than failing initialization — the inline-text fallback is AI-2150.+ * The resolution itself started well above, in parallel with everything+ * between; this only awaits it.+ */+ let instructionsPromptFacts: LinkedInstructionsFacts | undefined;+ if (instructionsPromptLink) {+ if (linkedInstructionsPromise) {+ const linkedResult = await linkedInstructionsPromise;+ if (linkedResult.status === 'resolved') {+ agent.instructions = linkedResult.prompt;+ instructionsPromptFacts = linkedResult.facts;+ } else {+ agent.instructions = '';+ logger.warn(+ `[initializeAgent] Linked instructions unavailable for agent ${agent.id} (group ${instructionsPromptLink.groupId}): ${linkedResult.reason}`,+ );+ }+ } else {+ agent.instructions = '';+ logger.warn(+ `[initializeAgent] Agent ${agent.id} links instructions to group ${instructionsPromptLink.groupId} but no resolver was provided; continuing with empty instructions`,+ );+ }+ }+if (agent.instructions && agent.instructions !== '') {const resolvedInstructions = replaceSpecialVars({text: agent.instructions,@@ -2753,6 +2846,7 @@ export async function initializeAgent(: Math.max(1024, Math.round(baseContextTokens * (1 - DEFAULT_RESERVE_RATIO))),primedCodeFiles,endpointTokenConfig: options.endpointTokenConfig,+ instructionsPromptFacts,};prepareQueuedCodeFileContext(initializedAgent, [initializedAgent], user?.id);@@ -2763,5 +2857,29 @@ export async function initializeAgent(files: [{ content: queuedFileContext }],});}++ /**+ * Usage is recorded only once initialization has fully succeeded — every+ * step above (tool loading, resource priming, provider setup, the queued+ * code file content check just above) has already run without throwing. A+ * resolved link with no `instructionsPromptFacts` never reaches here; an+ * initialization that throws after resolution never reaches here either,+ * so it records no use. Fire-and-forget: the turn does not wait on the+ * increment, and `recordUse` itself catches and logs its own errors. The+ * `typeof` guard is load-bearing, not defensive noise: `resolveLinkedInstructions`+ * is typed as a plain callable in `InitializeAgentParams`, so a+ * caller-supplied plain function (matching the type but not the resolver's+ * `Object.assign(resolve, { recordUse })` shape) would otherwise throw here+ * — after initialization has already fully succeeded — rather than+ * silently recording no usage.+ */+ if (+ instructionsPromptFacts &&+ (params.recordLinkedPromptUsage ?? true) &&+ typeof params.resolveLinkedInstructions?.recordUse === 'function'+ ) {+ params.resolveLinkedInstructions.recordUse(instructionsPromptFacts);+ }+return initializedAgent;}diff --git a/packages/api/src/agents/instructions/access.spec.ts b/packages/api/src/agents/instructions/access.spec.tsnew file mode 100644index 0000000000..4e5328ee20--- /dev/null+++ b/packages/api/src/agents/instructions/access.spec.ts@@ -0,0 +1,960 @@+import { InstructionsPromptErrorCode, PermissionBits, ResourceType } from 'librechat-data-provider';+import type { AgentInstructionsPrompt } from 'librechat-data-provider';+import { ContentTraversalLimitError } from '~/protection/adapters/nested';+import { createInstructionsPromptAccess } from './access';++const groupId = '507f1f77bcf86cd799439011';+const otherGroupId = '507f1f77bcf86cd799439022';+const thirdGroupId = '507f1f77bcf86cd799439033';+const promptId = '507f191e810c19729de860ea';++const user = { id: 'user-1', role: 'USER' };++const productionLink: AgentInstructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+};++const exactLink: AgentInstructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'exact', promptId },+};++const otherGroupLink: AgentInstructionsPrompt = {+ source: 'native',+ groupId: otherGroupId,+ selection: { type: 'production' },+};++const thirdGroupLink: AgentInstructionsPrompt = {+ source: 'native',+ groupId: thirdGroupId,+ selection: { type: 'production' },+};++function buildAccess({+ visibleGroupIds = new Set<string>(),+ resolvePromptOk = true,+ canUsePromptsResult = true,+ getResourcePermissionsMap,+ resolvePrompt,+ assertAgentInstructionsContent,+ canUsePrompts,+ canManagePrompts,+}: {+ visibleGroupIds?: Set<string>;+ resolvePromptOk?: boolean;+ /** Default result for the injected `canUsePrompts` mock when the caller doesn't supply+ * its own — most tests here are about the group-specific ACL, not the role gate. */+ canUsePromptsResult?: boolean;+ getResourcePermissionsMap?: jest.Mock;+ resolvePrompt?: jest.Mock;+ assertAgentInstructionsContent?: jest.Mock;+ canUsePrompts?: jest.Mock;+ canManagePrompts?: jest.Mock;+} = {}) {+ const logger = { warn: jest.fn(), error: jest.fn() };+ const map = jest.fn(async ({ resourceIds }: { resourceIds: string[] }) => {+ const result = new Map<string, number>();+ for (const id of resourceIds) {+ if (visibleGroupIds.has(id)) {+ result.set(id, PermissionBits.VIEW);+ }+ }+ return result;+ });+ const resolve = jest.fn(async () =>+ resolvePromptOk+ ? { ok: true as const, value: { groupId, promptId, prompt: 'hi', type: 'text' as const } }+ : {+ ok: false as const,+ error: { type: 'unavailable_selection' as const, reason: 'production' as const },+ },+ );+ const assertContent = assertAgentInstructionsContent ?? jest.fn();+ const canUse = canUsePrompts ?? jest.fn(async () => canUsePromptsResult);+ const access = createInstructionsPromptAccess({+ getResourcePermissionsMap: getResourcePermissionsMap ?? map,+ promptService: { resolvePrompt: resolvePrompt ?? resolve },+ assertAgentInstructionsContent: assertContent,+ canUsePrompts: canUse,+ canManagePrompts: canManagePrompts ?? jest.fn().mockResolvedValue(false),+ logger,+ });+ return {+ access,+ map: getResourcePermissionsMap ?? map,+ resolve: resolvePrompt ?? resolve,+ assertContent,+ canUse,+ logger,+ };+}++describe('createInstructionsPromptAccess', () => {+ describe('canViewGroup', () => {+ it('returns true when the VIEW bit is set', async () => {+ const { access } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ await expect(+ access.canViewGroup({ userId: user.id, role: user.role, groupId }),+ ).resolves.toBe(true);+ });++ it('returns false when the bit map has no entry for the group', async () => {+ const { access } = buildAccess();+ await expect(+ access.canViewGroup({ userId: user.id, role: user.role, groupId }),+ ).resolves.toBe(false);+ });++ it('returns false when other bits are set but not VIEW', async () => {+ const { access } = buildAccess({+ getResourcePermissionsMap: jest.fn(async () => new Map([[groupId, PermissionBits.EDIT]])),+ });+ await expect(+ access.canViewGroup({ userId: user.id, role: user.role, groupId }),+ ).resolves.toBe(false);+ });++ it('queries PROMPTGROUP resources', async () => {+ const { access, map } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ await access.canViewGroup({ userId: user.id, role: user.role, groupId });+ expect(map).toHaveBeenCalledWith({+ userId: user.id,+ role: user.role,+ resourceType: ResourceType.PROMPTGROUP,+ resourceIds: [groupId],+ });+ });++ it('propagates a thrown permission-service error', async () => {+ const { access } = buildAccess({+ getResourcePermissionsMap: jest.fn(async () => {+ throw new Error('db down');+ }),+ });+ await expect(+ access.canViewGroup({ userId: user.id, role: user.role, groupId }),+ ).rejects.toThrow('db down');+ });+ });++ describe('prompt-management capability', () => {+ const manager = { ...user, tenantId: 'tenant-1', idOnTheSource: 'external-1' };+ const canManagePrompts = jest.fn().mockResolvedValue(true);++ it('allows VIEW without an ACL and preserves capability identity', async () => {+ const { access, map } = buildAccess({ canManagePrompts });+ await expect(+ access.canViewGroup({+ userId: manager.id,+ role: manager.role,+ tenantId: manager.tenantId,+ idOnTheSource: manager.idOnTheSource,+ groupId,+ }),+ ).resolves.toBe(true);+ expect(canManagePrompts).toHaveBeenCalledWith(manager);+ expect(map).not.toHaveBeenCalled();+ });++ it.each([productionLink, exactLink])(+ 'allows selecting $selection.type without an ACL',+ async (next) => {+ const { access, map } = buildAccess({ canManagePrompts });+ await expect(+ access.validateLinkWrite({ user: manager, previous: null, next }),+ ).resolves.toEqual({ ok: true });+ expect(canManagePrompts).toHaveBeenCalledWith(manager);+ expect(map).not.toHaveBeenCalled();+ },+ );++ it('still requires PROMPTS USE', async () => {+ const { access } = buildAccess({ canManagePrompts, canUsePromptsResult: false });+ await expect(+ access.validateLinkWrite({ user: manager, previous: null, next: productionLink }),+ ).resolves.toEqual({+ ok: false,+ status: 403,+ code: InstructionsPromptErrorCode.FORBIDDEN,+ });+ });++ it('preserves links in the agent and every version without ACL lookups', async () => {+ const { access, map } = buildAccess({ canManagePrompts });+ const agent = {+ instructionsPrompt: productionLink,+ versions: [{ instructionsPrompt: otherGroupLink }],+ };+ await expect(access.presentForEditor({ user: manager, agent })).resolves.toBe(agent);+ await expect(+ access.presentVersionsForEditor({ user: manager, versions: agent.versions }),+ ).resolves.toEqual(agent.versions);+ expect(map).not.toHaveBeenCalled();+ });++ it('fails closed when capability lookup fails', async () => {+ const { access, map } = buildAccess({+ canManagePrompts: jest.fn().mockRejectedValue(new Error('capability outage')),+ });+ await expect(+ access.validateLinkWrite({ user: manager, previous: null, next: productionLink }),+ ).rejects.toThrow('capability outage');+ await expect(+ access.presentForEditor({ user: manager, agent: { instructionsPrompt: productionLink } }),+ ).resolves.toEqual({ instructionsPrompt: { source: 'native', restricted: true } });+ expect(map).not.toHaveBeenCalled();+ });+ });++ describe('validateLinkWrite', () => {+ it('is ok when the field is absent (no change)', async () => {+ const { access } = buildAccess();+ const result = await access.validateLinkWrite({+ user,+ previous: otherGroupLink,+ next: undefined,+ });+ expect(result).toEqual({ ok: true });+ });++ it('is ok when there was no previous link and none is requested', async () => {+ const { access } = buildAccess();+ const result = await access.validateLinkWrite({ user, previous: null, next: null });+ expect(result).toEqual({ ok: true });+ });++ it('allows re-selecting the same value even when the group is inaccessible', async () => {+ const { access, map } = buildAccess();+ const result = await access.validateLinkWrite({+ user,+ previous: otherGroupLink,+ next: { ...otherGroupLink },+ });+ expect(result).toEqual({ ok: true });+ expect(map).not.toHaveBeenCalled();+ });++ it('allows re-submitting the same removal (no previous, next null)', async () => {+ const { access, map } = buildAccess();+ const result = await access.validateLinkWrite({ user, previous: undefined, next: null });+ expect(result).toEqual({ ok: true });+ expect(map).not.toHaveBeenCalled();+ });++ describe('keep, remove, or replace an existing link — agent EDIT only', () => {+ it('allows changing away from a link to a group the editor cannot VIEW', async () => {+ // `previous` (otherGroupLink) is never checked at all — only `next`'s group+ // (groupId) needs to be viewable and resolvable.+ const { access } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ const result = await access.validateLinkWrite({+ user,+ previous: otherGroupLink,+ next: productionLink,+ });+ expect(result).toEqual({ ok: true });+ });++ it('allows removing a link to a group the editor cannot VIEW', async () => {+ const { access, map } = buildAccess();+ const result = await access.validateLinkWrite({+ user,+ previous: otherGroupLink,+ next: null,+ });+ expect(result).toEqual({ ok: true });+ // No VIEW check on `previous` at all — the lookup never runs for a removal.+ expect(map).not.toHaveBeenCalled();+ });++ it('accepts removing a link the editor can also VIEW', async () => {+ const { access } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ const result = await access.validateLinkWrite({+ user,+ previous: productionLink,+ next: null,+ });+ expect(result).toEqual({ ok: true });+ });+ });++ it('rejects a new link to a group the editor cannot VIEW (forbidden) — never checks whether it exists', async () => {+ // This module has no way to tell a hidden-but-existing group from a+ // nonexistent one: both come back absent from the permissions map, and+ // both are rejected the same way.+ const { access } = buildAccess();+ const result = await access.validateLinkWrite({+ user,+ previous: null,+ next: productionLink,+ });+ expect(result).toEqual({+ ok: false,+ status: 403,+ code: InstructionsPromptErrorCode.FORBIDDEN,+ });+ });++ it('rejects a selection that does not resolve (unavailable)', async () => {+ const { access } = buildAccess({+ visibleGroupIds: new Set([groupId]),+ resolvePromptOk: false,+ });+ const result = await access.validateLinkWrite({ user, previous: null, next: exactLink });+ expect(result).toEqual({+ ok: false,+ status: 400,+ code: InstructionsPromptErrorCode.UNAVAILABLE,+ });+ });++ it('accepts a viewable, resolvable new link (happy path)', async () => {+ const { access, resolve } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ const result = await access.validateLinkWrite({ user, previous: null, next: exactLink });+ expect(result).toEqual({ ok: true });+ expect(resolve).toHaveBeenCalledWith({+ groupId,+ selection: exactLink.selection,+ filters: undefined,+ });+ });++ it('accepts changing between two viewable, resolvable links', async () => {+ const { access } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ const result = await access.validateLinkWrite({+ user,+ previous: productionLink,+ next: exactLink,+ });+ expect(result).toEqual({ ok: true });+ });++ it('forwards filters to resolvePrompt', async () => {+ const { access, resolve } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ const filters = { pii: {} } as never;+ await access.validateLinkWrite({ user, previous: null, next: productionLink, filters });+ expect(resolve).toHaveBeenCalledWith({+ groupId,+ selection: productionLink.selection,+ filters,+ });+ });++ it('propagates a thrown permission-service error', async () => {+ const { access } = buildAccess({+ getResourcePermissionsMap: jest.fn(async () => {+ throw new Error('acl outage');+ }),+ });+ await expect(+ access.validateLinkWrite({ user, previous: null, next: productionLink }),+ ).rejects.toThrow('acl outage');+ });++ it('propagates a thrown prompt-service error', async () => {+ const { access } = buildAccess({+ visibleGroupIds: new Set([groupId]),+ resolvePrompt: jest.fn(async () => {+ throw new Error('prompt store outage');+ }),+ });+ await expect(+ access.validateLinkWrite({ user, previous: null, next: productionLink }),+ ).rejects.toThrow('prompt store outage');+ });++ describe('content-policy check after a successful resolve', () => {+ it('rejects a resolvable link whose content the agent-instructions policy blocks', async () => {+ const { access, assertContent } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ assertContent.mockImplementation(() => {+ throw new ContentTraversalLimitError();+ });+ const result = await access.validateLinkWrite({+ user,+ previous: null,+ next: productionLink,+ });+ expect(result).toEqual({+ ok: false,+ status: 400,+ code: InstructionsPromptErrorCode.UNAVAILABLE,+ });+ expect(assertContent).toHaveBeenCalledWith({ instructions: 'hi', filters: undefined });+ });++ it('forwards filters to the content-policy check', async () => {+ const { access, assertContent } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ const filters = { agentInstructions: { pii: { types: ['EMAIL'] } } } as never;+ await access.validateLinkWrite({ user, previous: null, next: productionLink, filters });+ expect(assertContent).toHaveBeenCalledWith({ instructions: 'hi', filters });+ });++ it('propagates an assertion error the content-filter helper does not recognize', async () => {+ const { access, assertContent } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ assertContent.mockImplementation(() => {+ throw new Error('unexpected');+ });+ await expect(+ access.validateLinkWrite({ user, previous: null, next: productionLink }),+ ).rejects.toThrow('unexpected');+ });+ });++ describe('role gate (PROMPTS USE)', () => {+ it('rejects a new link when the role lacks PROMPTS USE, regardless of the group ACL result', async () => {+ // The role check and the group ACL lookup now start together; the ACL+ // lookup's own result is irrelevant here because the role failure+ // takes precedence in the returned code.+ const { access, map, canUse } = buildAccess({+ visibleGroupIds: new Set([groupId]),+ canUsePromptsResult: false,+ });+ const result = await access.validateLinkWrite({+ user,+ previous: null,+ next: productionLink,+ });+ expect(result).toEqual({+ ok: false,+ status: 403,+ code: InstructionsPromptErrorCode.FORBIDDEN,+ });+ expect(canUse).toHaveBeenCalledWith(user, undefined);+ expect(map).toHaveBeenCalledTimes(1);+ });++ it('rejects changing between two links when the role lacks PROMPTS USE', async () => {+ const { access, canUse } = buildAccess({+ visibleGroupIds: new Set([groupId]),+ canUsePromptsResult: false,+ });+ const result = await access.validateLinkWrite({+ user,+ previous: productionLink,+ next: exactLink,+ });+ expect(result).toEqual({+ ok: false,+ status: 403,+ code: InstructionsPromptErrorCode.FORBIDDEN,+ });+ expect(canUse).toHaveBeenCalledWith(user, undefined);+ });++ it('never checks the role for an unrelated edit (field absent)', async () => {+ const { access, canUse } = buildAccess({ canUsePromptsResult: false });+ const result = await access.validateLinkWrite({+ user,+ previous: otherGroupLink,+ next: undefined,+ });+ expect(result).toEqual({ ok: true });+ expect(canUse).not.toHaveBeenCalled();+ });++ it('never checks the role for removing a link', async () => {+ const { access, canUse } = buildAccess({ canUsePromptsResult: false });+ const result = await access.validateLinkWrite({+ user,+ previous: productionLink,+ next: null,+ });+ expect(result).toEqual({ ok: true });+ expect(canUse).not.toHaveBeenCalled();+ });++ it('never checks the role for re-selecting the unchanged value', async () => {+ const { access, canUse } = buildAccess({ canUsePromptsResult: false });+ const result = await access.validateLinkWrite({+ user,+ previous: otherGroupLink,+ next: { ...otherGroupLink },+ });+ expect(result).toEqual({ ok: true });+ expect(canUse).not.toHaveBeenCalled();+ });++ it('accepts a new link when the role has PROMPTS USE and the group is viewable', async () => {+ const { access, canUse } = buildAccess({+ visibleGroupIds: new Set([groupId]),+ canUsePromptsResult: true,+ });+ const result = await access.validateLinkWrite({+ user,+ previous: null,+ next: productionLink,+ });+ expect(result).toEqual({ ok: true });+ expect(canUse).toHaveBeenCalledWith(user, undefined);+ });++ it('forwards the opaque req to canUsePrompts so its role lookup can share the caller cache', async () => {+ const { access, canUse } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ const req = { marker: 'request-handle' };+ await access.validateLinkWrite({ user, previous: null, next: productionLink, req });+ expect(canUse).toHaveBeenCalledWith(user, req);+ });++ it('starts the role check and the next-group VIEW check concurrently', async () => {+ /** Deferred promises let the test observe that both lookups are already+ * in flight before either has resolved — proof the role check no longer+ * gates the start of the VIEW lookup. */+ let resolveCanUse!: (value: boolean) => void;+ const canUsePending = new Promise<boolean>((resolve) => {+ resolveCanUse = resolve;+ });+ let resolveMap!: (value: Map<string, number>) => void;+ const mapPending = new Promise<Map<string, number>>((resolve) => {+ resolveMap = resolve;+ });+ const canUse = jest.fn(() => canUsePending);+ const map = jest.fn(() => mapPending);+ const { access } = buildAccess({ canUsePrompts: canUse, getResourcePermissionsMap: map });++ const pending = access.validateLinkWrite({ user, previous: null, next: productionLink });++ await Promise.resolve(); // Let the capability check fall through to ACLs.++ // Both lookups must already have been called — neither awaited the other.+ expect(canUse).toHaveBeenCalledTimes(1);+ expect(map).toHaveBeenCalledTimes(1);++ resolveCanUse(true);+ resolveMap(new Map([[groupId, PermissionBits.VIEW]]));+ await expect(pending).resolves.toEqual({ ok: true });+ });++ it('keeps the role failure taking precedence over a VIEW failure, even when VIEW resolves first', async () => {+ // The VIEW lookup resolves (to a passing result) well before the role+ // check does; the returned code must still be the role-failure code.+ let resolveCanUse!: (value: boolean) => void;+ const canUsePending = new Promise<boolean>((resolve) => {+ resolveCanUse = resolve;+ });+ const canUse = jest.fn(() => canUsePending);+ const { access } = buildAccess({+ visibleGroupIds: new Set([groupId]),+ canUsePrompts: canUse,+ });++ const pending = access.validateLinkWrite({ user, previous: null, next: productionLink });+ await Promise.resolve(); // let the VIEW lookup (a resolved mock) settle first+ resolveCanUse(false);++ await expect(pending).resolves.toEqual({+ ok: false,+ status: 403,+ code: InstructionsPromptErrorCode.FORBIDDEN,+ });+ });+ });+ });++ describe('presentForEditor', () => {+ it('leaves the agent untouched when there is no link', async () => {+ const { access } = buildAccess();+ const agent = { id: 'a1', instructionsPrompt: null };+ await expect(access.presentForEditor({ user, agent })).resolves.toBe(agent);+ });++ it('leaves a visible link untouched', async () => {+ const { access } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ const agent = { id: 'a1', instructionsPrompt: productionLink };+ await expect(access.presentForEditor({ user, agent })).resolves.toBe(agent);+ });++ it('replaces an inaccessible link with a restricted stub', async () => {+ const { access } = buildAccess();+ const agent = { id: 'a1', name: 'Agent', instructionsPrompt: otherGroupLink };+ const result = await access.presentForEditor({ user, agent });+ expect(result).toEqual({+ id: 'a1',+ name: 'Agent',+ instructionsPrompt: { source: 'native', restricted: true },+ });+ });++ it('stubs a link to a deleted group the same as a hidden one, with no group-existence read', async () => {+ // A deleted group has no ACL entries, so it comes back not-visible —+ // same as any other hidden group. There is no separate existence check+ // (`getPromptGroup`) that could distinguish the two.+ const { access } = buildAccess();+ const agent = { id: 'a1', name: 'Agent', instructionsPrompt: otherGroupLink };+ const result = await access.presentForEditor({ user, agent });+ expect(result).toEqual({+ id: 'a1',+ name: 'Agent',+ instructionsPrompt: { source: 'native', restricted: true },+ });+ });++ it('is idempotent on an already-restricted stub', async () => {+ const { access, map } = buildAccess();+ const agent = {+ id: 'a1',+ instructionsPrompt: { source: 'native' as const, restricted: true as const },+ };+ const result = await access.presentForEditor({ user, agent });+ expect(result).toBe(agent);+ expect(map).not.toHaveBeenCalled();+ });++ it('fails closed on a thrown permission-service error: stubs the link and logs, never throws', async () => {+ const { access, logger } = buildAccess({+ getResourcePermissionsMap: jest.fn(async () => {+ throw new Error('acl outage');+ }),+ });+ const agent = { id: 'a1', name: 'Agent', instructionsPrompt: otherGroupLink };+ const result = await access.presentForEditor({ user, agent });+ expect(result).toEqual({+ id: 'a1',+ name: 'Agent',+ instructionsPrompt: { source: 'native', restricted: true },+ });+ expect(logger.error).toHaveBeenCalledTimes(1);+ const [message, meta] = logger.error.mock.calls[0];+ expect(message).toContain('[createInstructionsPromptAccess]');+ expect(JSON.stringify(meta)).not.toContain('acl outage');+ });++ it('fails closed across both the top-level link and every version snapshot', async () => {+ const { access } = buildAccess({+ getResourcePermissionsMap: jest.fn(async () => {+ throw new Error('acl outage');+ }),+ });+ const agent = {+ id: 'a1',+ instructionsPrompt: productionLink,+ versions: [+ { name: 'v1', instructionsPrompt: otherGroupLink },+ { name: 'v2', instructionsPrompt: null },+ ],+ };+ const result = await access.presentForEditor({ user, agent });+ expect(result).toEqual({+ id: 'a1',+ instructionsPrompt: { source: 'native', restricted: true },+ versions: [+ { name: 'v1', instructionsPrompt: { source: 'native', restricted: true } },+ { name: 'v2', instructionsPrompt: null },+ ],+ });+ });++ describe('versions[] redaction', () => {+ it('leaves an agent with no links (top-level or versioned) untouched', async () => {+ const { access, map } = buildAccess();+ const agent = {+ id: 'a1',+ instructionsPrompt: null,+ versions: [{ name: 'v1', instructionsPrompt: null }],+ };+ const result = await access.presentForEditor({ user, agent });+ expect(result).toBe(agent);+ expect(map).not.toHaveBeenCalled();+ });++ it('redacts an inaccessible link inside a version snapshot, leaving a visible top-level link intact', async () => {+ const { access } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ const agent = {+ id: 'a1',+ instructionsPrompt: productionLink,+ versions: [+ { name: 'v1', instructionsPrompt: otherGroupLink },+ { name: 'v2', instructionsPrompt: productionLink },+ ],+ };+ const result = await access.presentForEditor({ user, agent });+ expect(result).toEqual({+ id: 'a1',+ instructionsPrompt: productionLink,+ versions: [+ {+ name: 'v1',+ instructionsPrompt: { source: 'native', restricted: true, matchesCurrent: false },+ },+ { name: 'v2', instructionsPrompt: productionLink },+ ],+ });+ });++ it('redacts the top-level link while leaving an accessible version snapshot intact', async () => {+ const { access } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ const agent = {+ id: 'a1',+ instructionsPrompt: otherGroupLink,+ versions: [{ name: 'v1', instructionsPrompt: productionLink }],+ };+ const result = await access.presentForEditor({ user, agent });+ expect(result).toEqual({+ id: 'a1',+ instructionsPrompt: { source: 'native', restricted: true },+ versions: [{ name: 'v1', instructionsPrompt: productionLink }],+ });+ });++ it('leaves an already-restricted version snapshot untouched', async () => {+ const { access } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ const agent = {+ id: 'a1',+ instructionsPrompt: productionLink,+ versions: [+ {+ name: 'v1',+ instructionsPrompt: { source: 'native' as const, restricted: true as const },+ },+ ],+ };+ const result = await access.presentForEditor({ user, agent });+ expect(result).toBe(agent);+ });++ it('batches every distinct groupId (top-level and versioned) into one permission lookup', async () => {+ const { access, map } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ const agent = {+ id: 'a1',+ instructionsPrompt: productionLink,+ versions: [+ { name: 'v1', instructionsPrompt: otherGroupLink },+ { name: 'v2', instructionsPrompt: thirdGroupLink },+ { name: 'v3', instructionsPrompt: otherGroupLink },+ ],+ };+ await access.presentForEditor({ user, agent });+ expect(map).toHaveBeenCalledTimes(1);+ const [{ resourceIds }] = map.mock.calls[0];+ expect(new Set(resourceIds)).toEqual(new Set([groupId, otherGroupId, thirdGroupId]));+ });++ it('redacts a version snapshot whose group has been deleted, the same as a hidden one', async () => {+ const { access } = buildAccess();+ const agent = {+ id: 'a1',+ instructionsPrompt: null,+ versions: [+ { name: 'v1', instructionsPrompt: otherGroupLink },+ { name: 'v2', instructionsPrompt: thirdGroupLink },+ ],+ };+ const result = await access.presentForEditor({ user, agent });+ expect(result).toEqual({+ id: 'a1',+ instructionsPrompt: null,+ versions: [+ {+ name: 'v1',+ instructionsPrompt: { source: 'native', restricted: true, matchesCurrent: false },+ },+ {+ name: 'v2',+ instructionsPrompt: { source: 'native', restricted: true, matchesCurrent: false },+ },+ ],+ });+ });+ });++ describe('matchesCurrent on a redacted version stub', () => {+ it('flags a redacted version as matching the current link (same group, same selection)', async () => {+ const { access } = buildAccess();+ const agent = {+ id: 'a1',+ instructionsPrompt: otherGroupLink,+ versions: [{ name: 'v1', instructionsPrompt: otherGroupLink }],+ };+ const result = await access.presentForEditor({ user, agent });+ expect(result).toEqual({+ id: 'a1',+ instructionsPrompt: { source: 'native', restricted: true },+ versions: [+ {+ name: 'v1',+ instructionsPrompt: { source: 'native', restricted: true, matchesCurrent: true },+ },+ ],+ });+ });++ it('flags a redacted version as not matching when its group differs from the current link', async () => {+ const { access } = buildAccess();+ const agent = {+ id: 'a1',+ instructionsPrompt: otherGroupLink,+ versions: [{ name: 'v1', instructionsPrompt: thirdGroupLink }],+ };+ const result = await access.presentForEditor({ user, agent });+ expect(result).toEqual({+ id: 'a1',+ instructionsPrompt: { source: 'native', restricted: true },+ versions: [+ {+ name: 'v1',+ instructionsPrompt: { source: 'native', restricted: true, matchesCurrent: false },+ },+ ],+ });+ });++ it('flags a redacted version as not matching when only the selection differs within the same group', async () => {+ const { access } = buildAccess();+ const agent = {+ id: 'a1',+ instructionsPrompt: productionLink,+ versions: [{ name: 'v1', instructionsPrompt: exactLink }],+ };+ const result = await access.presentForEditor({ user, agent });+ expect(result).toEqual({+ id: 'a1',+ instructionsPrompt: { source: 'native', restricted: true },+ versions: [+ {+ name: 'v1',+ instructionsPrompt: { source: 'native', restricted: true, matchesCurrent: false },+ },+ ],+ });+ });++ it('flags an older version as matching current after a revert, even though a later snapshot does not', async () => {+ // `revertAgentVersion` `$set`s the document without appending a new version,+ // so after a revert the current link can equal an *older* entry while the+ // latest-appended entry (still the pre-revert link) does not.+ const { access } = buildAccess();+ const agent = {+ id: 'a1',+ instructionsPrompt: otherGroupLink,+ versions: [+ { name: 'older', instructionsPrompt: otherGroupLink },+ { name: 'latest', instructionsPrompt: thirdGroupLink },+ ],+ };+ const result = await access.presentForEditor({ user, agent });+ expect(result).toEqual({+ id: 'a1',+ instructionsPrompt: { source: 'native', restricted: true },+ versions: [+ {+ name: 'older',+ instructionsPrompt: { source: 'native', restricted: true, matchesCurrent: true },+ },+ {+ name: 'latest',+ instructionsPrompt: { source: 'native', restricted: true, matchesCurrent: false },+ },+ ],+ });+ });+ });+ });++ describe('presentVersionsForEditor', () => {+ it('returns the versions unchanged when none carry a link', async () => {+ const { access, map } = buildAccess();+ const versions = [{ name: 'v1', instructionsPrompt: null }, { name: 'v2' }];+ const result = await access.presentVersionsForEditor({ user, versions });+ expect(result).toEqual(versions);+ expect(map).not.toHaveBeenCalled();+ });++ it('redacts only the snapshots whose link the editor cannot VIEW', async () => {+ const { access, map } = buildAccess({ visibleGroupIds: new Set([groupId]) });+ const versions = [+ { name: 'v1', instructionsPrompt: productionLink },+ { name: 'v2', instructionsPrompt: otherGroupLink },+ ];+ const result = await access.presentVersionsForEditor({ user, versions });+ expect(result).toEqual([+ { name: 'v1', instructionsPrompt: productionLink },+ { name: 'v2', instructionsPrompt: { source: 'native', restricted: true } },+ ]);+ expect(map).toHaveBeenCalledTimes(1);+ });++ it('leaves an already-restricted snapshot untouched', async () => {+ const { access } = buildAccess();+ const versions = [+ {+ name: 'v1',+ instructionsPrompt: { source: 'native' as const, restricted: true as const },+ },+ ];+ const result = await access.presentVersionsForEditor({ user, versions });+ expect(result[0]).toBe(versions[0]);+ });++ it('redacts a snapshot whose group has been deleted, the same as a hidden one', async () => {+ const { access } = buildAccess();+ const versions = [{ name: 'v1', instructionsPrompt: otherGroupLink }];+ const result = await access.presentVersionsForEditor({ user, versions });+ expect(result).toEqual([+ { name: 'v1', instructionsPrompt: { source: 'native', restricted: true } },+ ]);+ });++ it('fails closed on a thrown permission-service error: stubs every link and logs, never throws', async () => {+ const { access, logger } = buildAccess({+ getResourcePermissionsMap: jest.fn(async () => {+ throw new Error('acl outage');+ }),+ });+ const versions = [+ { name: 'v1', instructionsPrompt: otherGroupLink },+ { name: 'v2', instructionsPrompt: null },+ ];+ const result = await access.presentVersionsForEditor({ user, versions });+ expect(result).toEqual([+ { name: 'v1', instructionsPrompt: { source: 'native', restricted: true } },+ { name: 'v2', instructionsPrompt: null },+ ]);+ expect(logger.error).toHaveBeenCalledTimes(1);+ });++ describe('matchesCurrent', () => {+ it('flags a redacted snapshot that matches the given current link', async () => {+ const { access } = buildAccess();+ const versions = [{ name: 'v1', instructionsPrompt: otherGroupLink }];+ const result = await access.presentVersionsForEditor({+ user,+ versions,+ currentLink: otherGroupLink,+ });+ expect(result).toEqual([+ {+ name: 'v1',+ instructionsPrompt: { source: 'native', restricted: true, matchesCurrent: true },+ },+ ]);+ });++ it('flags a redacted snapshot that does not match the given current link', async () => {+ const { access } = buildAccess();+ const versions = [{ name: 'v1', instructionsPrompt: otherGroupLink }];+ const result = await access.presentVersionsForEditor({+ user,+ versions,+ currentLink: thirdGroupLink,+ });+ expect(result).toEqual([+ {+ name: 'v1',+ instructionsPrompt: { source: 'native', restricted: true, matchesCurrent: false },+ },+ ]);+ });++ it('omits the flag entirely when the caller passes no current link to compare against', async () => {+ const { access } = buildAccess();+ const versions = [{ name: 'v1', instructionsPrompt: otherGroupLink }];+ const result = await access.presentVersionsForEditor({ user, versions });+ expect(result).toEqual([+ { name: 'v1', instructionsPrompt: { source: 'native', restricted: true } },+ ]);+ });+ });+ });+});diff --git a/packages/api/src/agents/instructions/access.ts b/packages/api/src/agents/instructions/access.tsnew file mode 100644index 0000000000..a7ab0968d2--- /dev/null+++ b/packages/api/src/agents/instructions/access.ts@@ -0,0 +1,449 @@+import { InstructionsPromptErrorCode, PermissionBits, ResourceType } from 'librechat-data-provider';+import type {+ FiltersConfig,+ AgentInstructionsPrompt,+ RestrictedAgentInstructionsPrompt,+} from 'librechat-data-provider';+import type { PromptService } from '~/prompts';+import { isContentFilterError } from '~/middleware/contentFilter';+import { getSafeErrorMetadata } from '~/utils/errors';++/** Matches the `logger` shape injected elsewhere in this module family+ * (`createLinkedInstructionsResolver`). */+export interface InstructionsPromptAccessLogger {+ warn(message: string, meta?: object): void;+ error(message: string, meta?: object): void;+}++/** The write-path identity a link permission check runs as. */+export interface InstructionsPromptAccessUser {+ readonly id: string;+ readonly role: string;+ readonly tenantId?: string;+ readonly idOnTheSource?: string | null;+}++/** Matches `PermissionService.getResourcePermissionsMap`, injected rather than imported. */+export type GetResourcePermissionsMap = (input: {+ userId: string;+ role: string;+ resourceType: ResourceType;+ resourceIds: string[];+}) => Promise<Map<string, number>>;++/** Matches `assertModelBoundContent({ filters, agents: [{ instructions }] })`, injected so+ * this module never depends on the wider agent-content shape it inspects. Throws the same+ * content-policy errors as the save-time and runtime checks on inline instructions. */+export type AssertAgentInstructionsContent = (input: {+ instructions: string;+ filters?: FiltersConfig;+}) => void;++/** Opaque handle to the inbound request, forwarded to `canUsePrompts` only so its+ * role lookup (`checkAccess` → `getRoleForAccess`) can reuse the caller's per-request+ * role cache instead of re-reading the role document. This module never reads or+ * branches on it — kept as `unknown` so it stays decoupled from Express. */+export type InstructionsPromptAccessRequest = unknown;++/** Whether `user`'s role grants the role-level PROMPTS/USE permission — the same gate+ * `checkPromptAccess` applies to every `/prompts` route. Injected so this module stays+ * decoupled from `checkAccess`/`IUser`/`getRoleByName`, the way every other dependency+ * here is. A PROMPTGROUP VIEW grant on a specific group (`canViewGroup`) says nothing+ * about this broader, role-level capability — a user can be granted VIEW on one group+ * by its owner while their role still lacks PROMPTS USE entirely. */+export type CanUsePrompts = (+ user: InstructionsPromptAccessUser,+ req?: InstructionsPromptAccessRequest,+) => Promise<boolean>;++export type InstructionsPromptWriteResult =+ | { readonly ok: true }+ | { readonly ok: false; readonly status: 400 | 403; readonly code: InstructionsPromptErrorCode };++/** Any object carrying an agent's presented (possibly restricted) instructions-prompt link. */+export type AgentInstructionsPromptCarrier = {+ instructionsPrompt?: AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null;+};++/** An agent (or update/revert response) carrying its own link plus version snapshots that+ * each carry their own, independently-authorized link. */+export type AgentWithVersionsCarrier = AgentInstructionsPromptCarrier & {+ versions?: readonly AgentInstructionsPromptCarrier[];+};++export interface InstructionsPromptAccess {+ /** Effective PROMPTGROUP VIEW, including the management-capability bypass. */+ canViewGroup(+ input: Omit<InstructionsPromptAccessUser, 'id'> & { userId: string; groupId: string },+ ): Promise<boolean>;+ /**+ * Validates a create/update write of `instructionsPrompt` against the stored link.+ * `next === undefined` means the field is absent from the payload (no change+ * requested) — ok. Keeping, removing (`next === null`), or re-submitting the+ * unchanged link (`isSameLink`) is always ok: agent EDIT already authorizes all+ * three, and none of them reveals anything about `previous`'s group that EDIT+ * doesn't already know.+ *+ * A genuinely new or changed `next` requires the role-level PROMPTS `USE`+ * permission (`canUsePrompts`) and PROMPTGROUP `VIEW` on `next.groupId`+ * (`canViewGroup`), `FORBIDDEN` otherwise — a PROMPTGROUP `VIEW` grant on one group+ * says nothing about whether the role may link prompts at all, and `next` not+ * existing is indistinguishable from `next` existing but hidden, so group+ * existence is never revealed through it. The two checks are independent, so both+ * run concurrently instead of one gating the start of the other. Once both pass,+ * the selection must still resolve and pass content policy (`UNAVAILABLE`+ * otherwise).+ */+ validateLinkWrite(input: {+ user: InstructionsPromptAccessUser;+ previous: AgentInstructionsPrompt | null | undefined;+ next: AgentInstructionsPrompt | null | undefined;+ filters?: FiltersConfig;+ /** Forwarded unexamined to `canUsePrompts` so its role lookup can reuse the+ * caller's per-request role cache. */+ req?: InstructionsPromptAccessRequest;+ }): Promise<InstructionsPromptWriteResult>;+ /** Replaces every link the editor cannot VIEW — on the agent itself and inside every+ * `versions[i]` snapshot — with a restricted stub before an EDIT-scoped response.+ * Batches every distinct linked group into a single permission lookup. A deleted+ * group stubs the same as a hidden one: there is no group record left to check+ * existence against, so this redacts on VIEW alone.+ *+ * Fails closed: this runs after the write it is presenting has already been+ * persisted, so an ACL-lookup failure here must never surface as a 500 (a client+ * retry on that 500 would create another duplicate/etc. against the write that+ * already succeeded). On such a failure this logs a safe message and returns+ * every link — top-level and every version snapshot — as the restricted stub+ * instead of throwing. */+ presentForEditor<T extends AgentWithVersionsCarrier>(input: {+ user: InstructionsPromptAccessUser;+ agent: T;+ }): Promise<T>;+ /** Same redaction as `presentForEditor`, including the same fail-closed behavior,+ * for a response that returns a version-history array directly+ * (`GET /agents/:id/versions`) rather than a wrapping agent document.+ *+ * `currentLink` is the agent document's own raw (unredacted) link, used only to+ * set `matchesCurrent` on a redacted version's stub — see `redactIfHidden`. Omit+ * it when the caller has no current link to compare against. */+ presentVersionsForEditor<T extends AgentInstructionsPromptCarrier>(input: {+ user: InstructionsPromptAccessUser;+ versions: readonly T[];+ currentLink?: AgentInstructionsPrompt | null;+ }): Promise<T[]>;+}++/** Structural equality for the small, plain-JSON link shape. `null` and `undefined` are equal. */+function isSameLink(+ a: AgentInstructionsPrompt | null | undefined,+ b: AgentInstructionsPrompt | null | undefined,+): boolean {+ const left = a ?? null;+ const right = b ?? null;+ if (left === right) {+ return true;+ }+ if (left == null || right == null) {+ return false;+ }+ if (left.source !== right.source || left.groupId !== right.groupId) {+ return false;+ }+ if (left.selection.type !== right.selection.type) {+ return false;+ }+ if (left.selection.type === 'exact' && right.selection.type === 'exact') {+ return left.selection.promptId === right.selection.promptId;+ }+ return true;+}++function isRestrictedStub(+ link: AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt,+): link is RestrictedAgentInstructionsPrompt {+ return (link as RestrictedAgentInstructionsPrompt).restricted === true;+}++const RESTRICTED_STUB: RestrictedAgentInstructionsPrompt = { source: 'native', restricted: true };++/** Every distinct, non-restricted-stub `groupId` referenced by the given links. */+function collectLinkGroupIds(+ links: Iterable<AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null | undefined>,+): string[] {+ const ids = new Set<string>();+ for (const link of links) {+ if (link != null && !isRestrictedStub(link)) {+ ids.add(link.groupId);+ }+ }+ return [...ids];+}++/**+ * Builds the permission checks that gate reading and writing an agent's linked+ * instructions prompt. Callers (the `/api` write and read handlers) own the HTTP+ * boundary; this module only decides ok/forbidden/unavailable.+ * `validateLinkWrite` throws on an unexpected permission or prompt-service failure+ * rather than swallowing it — that check runs before the write lands, so failing it+ * is safe. The caller, `checkInstructionsPromptWrite` (`./writes`), is the one that turns such a+ * throw into a sanitized `500` rather than letting a raw `error.message` reach the+ * client; this module's job stops at ok/forbidden/unavailable or throwing.+ * `presentForEditor` and `presentVersionsForEditor` run after the write has already+ * been persisted and fail closed instead: see their own docs below.+ */+export function createInstructionsPromptAccess(deps: {+ getResourcePermissionsMap: GetResourcePermissionsMap;+ promptService: Pick<PromptService, 'resolvePrompt'>;+ assertAgentInstructionsContent: AssertAgentInstructionsContent;+ canUsePrompts: CanUsePrompts;+ canManagePrompts: (user: InstructionsPromptAccessUser) => Promise<boolean>;+ logger: InstructionsPromptAccessLogger;+}): InstructionsPromptAccess {+ const {+ getResourcePermissionsMap,+ promptService,+ assertAgentInstructionsContent,+ canUsePrompts,+ canManagePrompts,+ logger,+ } = deps;++ async function canViewGroup({+ userId,+ groupId,+ ...identity+ }: Omit<InstructionsPromptAccessUser, 'id'> & {+ userId: string;+ groupId: string;+ }): Promise<boolean> {+ if (await canManagePrompts({ id: userId, ...identity })) {+ return true;+ }+ const permissionsMap = await getResourcePermissionsMap({+ userId,+ role: identity.role,+ resourceType: ResourceType.PROMPTGROUP,+ resourceIds: [groupId],+ });+ const bits = permissionsMap.get(groupId) ?? 0;+ return (bits & PermissionBits.VIEW) === PermissionBits.VIEW;+ }++ /**+ * One batched permission lookup for every distinct `groupId` among the given links.+ * Returns the subset the editor cannot VIEW — the groups that must be redacted+ * before an EDIT-scoped response. A deleted group has no ACL entries left, so it+ * comes back not-visible and is redacted the same as a hidden one.+ */+ async function buildRedactionSet(+ user: InstructionsPromptAccessUser,+ groupIds: readonly string[],+ ): Promise<ReadonlySet<string>> {+ if (groupIds.length === 0 || (await canManagePrompts(user))) {+ return new Set();+ }+ const permissionsMap = await getResourcePermissionsMap({+ userId: user.id,+ role: user.role,+ resourceType: ResourceType.PROMPTGROUP,+ resourceIds: [...groupIds],+ });+ const notVisible = groupIds.filter((groupId) => {+ const bits = permissionsMap.get(groupId) ?? 0;+ return (bits & PermissionBits.VIEW) !== PermissionBits.VIEW;+ });+ return new Set(notVisible);+ }++ /** `currentLink` is the agent's current raw link, used only to set `matchesCurrent`+ * on the stub (never on the current agent's own stub — that caller never passes+ * it). Left `undefined` when the caller has no current link to compare against,+ * in which case the stub carries no `matchesCurrent` at all. */+ function redactIfHidden<T extends AgentInstructionsPromptCarrier>(+ carrier: T,+ redactGroupIds: ReadonlySet<string>,+ currentLink?: AgentInstructionsPrompt | null,+ ): T {+ const link = carrier.instructionsPrompt;+ if (link == null || isRestrictedStub(link) || !redactGroupIds.has(link.groupId)) {+ return carrier;+ }+ const stub: RestrictedAgentInstructionsPrompt =+ currentLink === undefined+ ? RESTRICTED_STUB+ : { ...RESTRICTED_STUB, matchesCurrent: isSameLink(link, currentLink) };+ return { ...carrier, instructionsPrompt: stub };+ }++ /** Unconditional stub, used only on the fail-closed path below: every link is+ * hidden because whether it may be shown could not be determined. */+ function stubLink<T extends AgentInstructionsPromptCarrier>(carrier: T): T {+ return carrier.instructionsPrompt == null+ ? carrier+ : { ...carrier, instructionsPrompt: RESTRICTED_STUB };+ }++ /** Content-free failure log shared by every fail-closed path below. */+ function logAuthorizationFailure(error: unknown): void {+ logger.error(+ '[createInstructionsPromptAccess] Failed to authorize a linked instructions prompt for an EDIT-scoped response; presenting every link as restricted',+ getSafeErrorMetadata(error),+ );+ }++ /** Logs and reports back with no group identity — every top-level and+ * versioned link on `agent` becomes the restricted stub. */+ function failClosed<T extends AgentWithVersionsCarrier>(error: unknown, agent: T): T {+ logAuthorizationFailure(error);+ const versions = agent.versions;+ return {+ ...stubLink(agent),+ ...(versions == null ? {} : { versions: versions.map((version) => stubLink(version)) }),+ };+ }++ async function validateLinkWrite({+ user,+ previous,+ next,+ filters,+ req,+ }: {+ user: InstructionsPromptAccessUser;+ previous: AgentInstructionsPrompt | null | undefined;+ next: AgentInstructionsPrompt | null | undefined;+ filters?: FiltersConfig;+ req?: InstructionsPromptAccessRequest;+ }): Promise<InstructionsPromptWriteResult> {+ if (next === undefined) {+ // Field absent from the payload: an unrelated edit keeps an inaccessible link.+ return { ok: true };+ }+ if (isSameLink(previous, next)) {+ // Re-selecting (or re-submitting the removal of) the unchanged value is always ok,+ // even when the editor cannot VIEW the group.+ return { ok: true };+ }+ if (next == null) {+ // Removing a link, regardless of whether the editor could VIEW the previous+ // group, is always allowed — agent EDIT is the only authority this needs.+ return { ok: true };+ }+ // A genuinely new or changed link (never a removal, and never a re-selection of the+ // unchanged value — both returned above): the role must grant PROMPTS USE, and the+ // next group must be VIEWable. The two checks are independent and run concurrently;+ // a role failure takes precedence over a VIEW failure.+ const [usable, nextVisible] = await Promise.all([+ canUsePrompts(user, req),+ canViewGroup({+ userId: user.id,+ role: user.role,+ tenantId: user.tenantId,+ idOnTheSource: user.idOnTheSource,+ groupId: next.groupId,+ }),+ ]);+ if (!usable) {+ return { ok: false, status: 403, code: InstructionsPromptErrorCode.FORBIDDEN };+ }+ if (!nextVisible) {+ // FORBIDDEN regardless of whether the group exists, so group existence is never+ // revealed through a new link.+ return { ok: false, status: 403, code: InstructionsPromptErrorCode.FORBIDDEN };+ }+ const resolved = await promptService.resolvePrompt({+ groupId: next.groupId,+ selection: next.selection,+ filters,+ });+ if (!resolved.ok) {+ return { ok: false, status: 400, code: InstructionsPromptErrorCode.UNAVAILABLE };+ }+ try {+ assertAgentInstructionsContent({ instructions: resolved.value.prompt, filters });+ } catch (error) {+ if (isContentFilterError(error)) {+ return { ok: false, status: 400, code: InstructionsPromptErrorCode.UNAVAILABLE };+ }+ throw error;+ }+ return { ok: true };+ }++ async function presentForEditor<T extends AgentWithVersionsCarrier>({+ user,+ agent,+ }: {+ user: InstructionsPromptAccessUser;+ agent: T;+ }): Promise<T> {+ const versions = agent.versions;+ const groupIds = collectLinkGroupIds([+ agent.instructionsPrompt,+ ...(versions ?? []).map((version) => version.instructionsPrompt),+ ]);+ if (groupIds.length === 0) {+ return agent;+ }+ let redact: ReadonlySet<string>;+ try {+ redact = await buildRedactionSet(user, groupIds);+ } catch (error) {+ return failClosed(error, agent);+ }+ const topLevelLink = agent.instructionsPrompt;+ const topLevelRedacted =+ topLevelLink != null && !isRestrictedStub(topLevelLink) && redact.has(topLevelLink.groupId);+ const versionsUnchanged =+ versions == null ||+ versions.every((version) => {+ const link = version.instructionsPrompt;+ return link == null || isRestrictedStub(link) || !redact.has(link.groupId);+ });+ if (!topLevelRedacted && versionsUnchanged) {+ return agent;+ }+ // The agent's own raw link, used to flag a redacted version snapshot as+ // `matchesCurrent` — never a restricted stub here since this function is the+ // one that applies that redaction.+ const currentRawLink =+ topLevelLink != null && !isRestrictedStub(topLevelLink) ? topLevelLink : null;+ return {+ ...agent,+ ...(topLevelRedacted ? { instructionsPrompt: RESTRICTED_STUB } : {}),+ ...(versions == null+ ? {}+ : { versions: versions.map((version) => redactIfHidden(version, redact, currentRawLink)) }),+ };+ }++ async function presentVersionsForEditor<T extends AgentInstructionsPromptCarrier>({+ user,+ versions,+ currentLink,+ }: {+ user: InstructionsPromptAccessUser;+ versions: readonly T[];+ currentLink?: AgentInstructionsPrompt | null;+ }): Promise<T[]> {+ const groupIds = collectLinkGroupIds(versions.map((version) => version.instructionsPrompt));+ if (groupIds.length === 0) {+ return versions as T[];+ }+ let redact: ReadonlySet<string>;+ try {+ redact = await buildRedactionSet(user, groupIds);+ } catch (error) {+ logAuthorizationFailure(error);+ return versions.map((version) => stubLink(version));+ }+ return versions.map((version) => redactIfHidden(version, redact, currentLink));+ }++ return {+ canViewGroup,+ validateLinkWrite,+ presentForEditor,+ presentVersionsForEditor,+ };+}diff --git a/packages/api/src/agents/instructions/errors.ts b/packages/api/src/agents/instructions/errors.tsnew file mode 100644index 0000000000..ca3d6589e2--- /dev/null+++ b/packages/api/src/agents/instructions/errors.ts@@ -0,0 +1,70 @@+import { InstructionsPromptErrorCode } from 'librechat-data-provider';+import type { AgentInstructionsPrompt, FiltersConfig } from 'librechat-data-provider';+import type {+ InstructionsPromptAccess,+ InstructionsPromptAccessUser,+ InstructionsPromptAccessRequest,+} from './access';++/** User-safe copy for each stable `instructionsPrompt` write-rejection code. */+const INSTRUCTIONS_PROMPT_ERROR_MESSAGES: Record<InstructionsPromptErrorCode, string> = {+ [InstructionsPromptErrorCode.UNAVAILABLE]: 'The selected prompt is not available.',+ [InstructionsPromptErrorCode.FORBIDDEN]: 'You do not have access to the selected prompt.',+ [InstructionsPromptErrorCode.VALIDATION_FAILED]: 'Unable to validate the linked prompt',+};++export interface InstructionsPromptLinkErrorResponse {+ readonly status: 400 | 403 | 500;+ readonly body: { readonly error: string; readonly code: InstructionsPromptErrorCode };+}++/**+ * Builds the HTTP-shaped `{ status, body }` response for a stable `instructionsPrompt`+ * error code, pairing it with its one approved, user-safe message. Shared by every+ * caller that maps a stable code to a response, so the same code always carries the+ * same copy: the per-operation rejection below, and `checkInstructionsPromptWrite`'s+ * own unexpected-failure (VALIDATION_FAILED) case.+ */+export function buildInstructionsPromptError(+ status: InstructionsPromptLinkErrorResponse['status'],+ code: InstructionsPromptErrorCode,+): InstructionsPromptLinkErrorResponse {+ return { status, body: { error: INSTRUCTIONS_PROMPT_ERROR_MESSAGES[code], code } };+}++/**+ * Validates a create/update write of `instructionsPrompt` against the agent's stored+ * link, before any write lands, and maps a rejection to the HTTP boundary's+ * `{ status, body }` shape. Returns `null` when the write may proceed. The caller+ * (`/api`) owns only the HTTP call; every ok/forbidden/unavailable decision lives in+ * `access.validateLinkWrite`.+ */+export async function getInstructionsPromptLinkError({+ access,+ user,+ previous,+ next,+ filters,+ req,+}: {+ access: Pick<InstructionsPromptAccess, 'validateLinkWrite'>;+ user: InstructionsPromptAccessUser;+ previous: AgentInstructionsPrompt | null | undefined;+ next: AgentInstructionsPrompt | null | undefined;+ filters?: FiltersConfig;+ /** Forwarded unexamined to `validateLinkWrite` so its role lookup can reuse the+ * caller's per-request role cache. */+ req?: InstructionsPromptAccessRequest;+}): Promise<InstructionsPromptLinkErrorResponse | null> {+ const result = await access.validateLinkWrite({+ user,+ previous,+ next,+ filters,+ req,+ });+ if (result.ok) {+ return null;+ }+ return buildInstructionsPromptError(result.status, result.code);+}diff --git a/packages/api/src/agents/instructions/index.ts b/packages/api/src/agents/instructions/index.tsnew file mode 100644index 0000000000..6fedb02333--- /dev/null+++ b/packages/api/src/agents/instructions/index.ts@@ -0,0 +1,4 @@+export * from './linked';+export * from './access';+export * from './errors';+export * from './writes';diff --git a/packages/api/src/agents/instructions/linked.spec.ts b/packages/api/src/agents/instructions/linked.spec.tsnew file mode 100644index 0000000000..eb6b5cdb91--- /dev/null+++ b/packages/api/src/agents/instructions/linked.spec.ts@@ -0,0 +1,705 @@+import type { FiltersConfig, AgentInstructionsPrompt } from 'librechat-data-provider';+import type { LinkedInstructionsCache, LinkedInstructionsLogger } from './linked';+import type { PromptService, ResolvedPrompt } from '~/prompts';+import { createLinkedInstructionsResolver, invalidateLinkedPrompt } from './linked';+import { ContentTraversalLimitError } from '~/protection/adapters/nested';+import { assertModelBoundContent } from '~/middleware/modelBoundContent';++jest.mock('~/middleware/modelBoundContent', () => ({+ ...jest.requireActual('~/middleware/modelBoundContent'),+ assertModelBoundContent: jest.fn(),+}));++const mockAssertModelBoundContent = assertModelBoundContent as jest.MockedFunction<+ typeof assertModelBoundContent+>;+const actualAssertModelBoundContent = jest.requireActual('~/middleware/modelBoundContent')+ .assertModelBoundContent as typeof assertModelBoundContent;++/** Map-based cache with real per-entry TTL, matching the Keyv contract the resolver relies on. */+class FakeCache implements LinkedInstructionsCache {+ private store = new Map<string, { value: unknown; expiresAt?: number }>();++ async get(key: string): Promise<unknown> {+ const entry = this.store.get(key);+ if (!entry) {+ return undefined;+ }+ if (entry.expiresAt != null && entry.expiresAt <= Date.now()) {+ this.store.delete(key);+ return undefined;+ }+ return entry.value;+ }++ async set(key: string, value: unknown, ttl?: number): Promise<boolean> {+ this.store.set(key, { value, expiresAt: ttl ? Date.now() + ttl : undefined });+ return true;+ }++ async delete(key: string): Promise<boolean> {+ return this.store.delete(key);+ }++ get size(): number {+ return this.store.size;+ }++ keys(): string[] {+ return [...this.store.keys()];+ }+}++const blockingFilters: FiltersConfig = {+ prompts: {+ pii: {+ starterPatterns: [],+ customPatterns: [{ id: 'private', label: 'private value', regex: 'PRIVATE-[A-Z]+' }],+ fields: ['text'],+ },+ },+};++/** Blocks only via the agent-instructions policy — `prompts.pii` is untouched — so a+ * finding here can only come from the `assertModelBoundContent({ agents: [...] })`+ * check, never from `inspectPromptContent`. */+const agentInstructionsBlockingFilters: FiltersConfig = {+ agentInstructions: {+ pii: {+ starterPatterns: [],+ customPatterns: [{ id: 'secret', label: 'secret value', regex: 'SECRET-[A-Z]+' }],+ fields: ['instructions'],+ },+ },+};++const groupId = '507f1f77bcf86cd799439011';+const promptId = '507f1f77bcf86cd799439012';++const productionLink: AgentInstructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+};++const exactLink: AgentInstructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'exact', promptId },+};++function makeResolvedPrompt(overrides: Partial<ResolvedPrompt> = {}): ResolvedPrompt {+ return {+ groupId,+ promptId,+ prompt: 'You are a helpful assistant.',+ type: 'text',+ ...overrides,+ };+}++function makeLogger(): LinkedInstructionsLogger & { warn: jest.Mock; error: jest.Mock } {+ return { warn: jest.fn(), error: jest.fn() };+}++function makePromptService(+ overrides: Partial<Pick<PromptService, 'resolvePrompt' | 'incrementPromptGroupUsage'>> = {},+): Pick<PromptService, 'resolvePrompt' | 'incrementPromptGroupUsage'> {+ return {+ resolvePrompt: jest.fn().mockResolvedValue({ ok: true, value: makeResolvedPrompt() }),+ incrementPromptGroupUsage: jest.fn().mockResolvedValue({ numberOfGenerations: 1 }),+ ...overrides,+ };+}++/** Flushes pending microtasks (used to let fire-and-forget calls settle). */+const flush = () => new Promise((resolve) => setImmediate(resolve));++describe('createLinkedInstructionsResolver', () => {+ beforeEach(() => {+ mockAssertModelBoundContent.mockImplementation(actualAssertModelBoundContent);+ });++ it('resolves the production selection on a cache miss and caches the result', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const result = await resolver({ link: productionLink });++ expect(result).toEqual({+ status: 'resolved',+ prompt: 'You are a helpful assistant.',+ facts: { source: 'native', groupId, promptId },+ });+ expect(promptService.resolvePrompt).toHaveBeenCalledWith({+ groupId,+ selection: { type: 'production' },+ filters: undefined,+ });+ await expect(cache.get(`native:${groupId}:production`)).resolves.toMatchObject({+ groupId,+ promptId,+ prompt: 'You are a helpful assistant.',+ });+ });++ it('resolves an exact revision selection and caches it under the exact key', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const result = await resolver({ link: exactLink });++ expect(result.status).toBe('resolved');+ expect(promptService.resolvePrompt).toHaveBeenCalledWith({+ groupId,+ selection: { type: 'exact', promptId },+ filters: undefined,+ });+ await expect(cache.get(`native:${groupId}:exact:${promptId}`)).resolves.toBeDefined();+ });++ it('serves a cache hit without calling resolvePrompt', async () => {+ const cache = new FakeCache();+ await cache.set(`native:${groupId}:production`, {+ groupId,+ promptId,+ prompt: 'Cached instructions',+ type: 'text',+ });+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const result = await resolver({ link: productionLink });++ expect(result).toEqual({+ status: 'resolved',+ prompt: 'Cached instructions',+ facts: { source: 'native', groupId, promptId },+ });+ expect(promptService.resolvePrompt).not.toHaveBeenCalled();+ });++ it('re-inspects a cache hit and blocks it when current prompt filters now block the content', async () => {+ const cache = new FakeCache();+ await cache.set(`native:${groupId}:production`, {+ groupId,+ promptId,+ prompt: 'Contains PRIVATE-SECRET marker',+ type: 'text',+ });+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const result = await resolver({ link: productionLink, filters: blockingFilters });++ expect(result).toEqual({ status: 'unavailable', reason: 'blocked_content' });+ expect(promptService.resolvePrompt).not.toHaveBeenCalled();+ });++ it('blocks a cache hit under the agent-instructions policy alone (prompts.pii is untouched)', async () => {+ const cache = new FakeCache();+ await cache.set(`native:${groupId}:production`, {+ groupId,+ promptId,+ prompt: 'Contains SECRET-VALUE marker',+ type: 'text',+ });+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const result = await resolver({+ link: productionLink,+ filters: agentInstructionsBlockingFilters,+ });++ expect(result).toEqual({ status: 'unavailable', reason: 'blocked_content' });+ expect(promptService.resolvePrompt).not.toHaveBeenCalled();+ });++ it('blocks a fresh resolution under the agent-instructions policy alone (prompts.pii is untouched)', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService({+ resolvePrompt: jest.fn().mockResolvedValue({+ ok: true,+ value: makeResolvedPrompt({ prompt: 'Contains SECRET-VALUE marker' }),+ }),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const result = await resolver({+ link: productionLink,+ filters: agentInstructionsBlockingFilters,+ });++ expect(result).toEqual({ status: 'unavailable', reason: 'blocked_content' });+ // Blocked before the cache write: a violation is never cached.+ await expect(cache.get(`native:${groupId}:production`)).resolves.toBeUndefined();+ });++ it('does not re-run the prompt-library policy on a fresh resolution, leaving it to resolvePrompt', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService({+ resolvePrompt: jest.fn().mockResolvedValue({+ ok: true,+ value: makeResolvedPrompt({ prompt: 'Contains PRIVATE-SECRET marker' }),+ }),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const result = await resolver({ link: productionLink, filters: blockingFilters });++ expect(result.status).toBe('resolved');+ });++ it('maps any content-policy error the content check throws to blocked_content, not just ContentFilterError', async () => {+ // A traversal-limit error is a content-policy error `isContentFilterError`+ // recognizes, but not an `instanceof ContentFilterError` — this is exactly+ // the gap `isContentFilterError` closes over the old `instanceof` check.+ mockAssertModelBoundContent.mockImplementation(() => {+ throw new ContentTraversalLimitError();+ });+ const cache = new FakeCache();+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const result = await resolver({ link: productionLink });++ expect(result).toEqual({ status: 'unavailable', reason: 'blocked_content' });+ });++ it('maps an error the content-policy check does not recognize to reason "error" instead of rejecting', async () => {+ mockAssertModelBoundContent.mockImplementation(() => {+ throw new Error('unexpected content-policy failure');+ });+ const cache = new FakeCache();+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ await expect(resolver({ link: productionLink })).resolves.toEqual({+ status: 'unavailable',+ reason: 'error',+ });+ expect(logger.error).toHaveBeenCalledWith(+ '[linkedInstructions] Content-policy check failed',+ expect.objectContaining({ groupId, errorName: 'Error' }),+ );+ });++ it('fetches fresh content after the cached entry expires', async () => {+ jest.useFakeTimers();+ try {+ const cache = new FakeCache();+ const promptService = makePromptService({+ resolvePrompt: jest+ .fn()+ .mockResolvedValueOnce({ ok: true, value: makeResolvedPrompt({ prompt: 'first' }) })+ .mockResolvedValueOnce({ ok: true, value: makeResolvedPrompt({ prompt: 'second' }) }),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const first = await resolver({+ link: productionLink,+ config: { native: { cacheTtlMs: 1000 } },+ });+ expect(first).toMatchObject({ status: 'resolved', prompt: 'first' });++ jest.advanceTimersByTime(1001);++ const second = await resolver({+ link: productionLink,+ config: { native: { cacheTtlMs: 1000 } },+ });+ expect(second).toMatchObject({ status: 'resolved', prompt: 'second' });+ expect(promptService.resolvePrompt).toHaveBeenCalledTimes(2);+ } finally {+ jest.useRealTimers();+ }+ });++ it('does not read or write the cache when cacheTtlMs is 0', async () => {+ const cache = new FakeCache();+ const getSpy = jest.spyOn(cache, 'get');+ const setSpy = jest.spyOn(cache, 'set');+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const result = await resolver({+ link: productionLink,+ config: { native: { cacheTtlMs: 0 } },+ });++ expect(result.status).toBe('resolved');+ expect(getSpy).not.toHaveBeenCalled();+ expect(setSpy).not.toHaveBeenCalled();+ });++ it('falls through to resolvePrompt and still resolves when the cache read errors', async () => {+ const cache = new FakeCache();+ const getSpy = jest.spyOn(cache, 'get').mockRejectedValue(new Error('cache unavailable'));+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const result = await resolver({ link: productionLink });++ expect(getSpy).toHaveBeenCalledTimes(1);+ expect(promptService.resolvePrompt).toHaveBeenCalledTimes(1);+ expect(result).toEqual({+ status: 'resolved',+ prompt: 'You are a helpful assistant.',+ facts: { source: 'native', groupId, promptId },+ });+ expect(logger.warn).toHaveBeenCalledWith(+ '[linkedInstructions] Cache read failed; resolving without cache',+ expect.objectContaining({ groupId, errorName: 'Error' }),+ );+ });++ it('bounds the cache-read phase so a hung cache read still leaves resolvePrompt room to answer from the database', async () => {+ jest.useFakeTimers();+ try {+ const cache = new FakeCache();+ jest.spyOn(cache, 'get').mockReturnValue(new Promise(() => {})); // never settles+ const promptService = makePromptService(); // resolvePrompt settles immediately+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const pending = resolver({ link: productionLink, config: { timeoutMs: 200 } });+ // The cache-read phase is capped at min(250ms, timeoutMs / 4) = 50ms here, well+ // under the 200ms deadline — advancing past just that cap (not the full+ // deadline) is enough for the hung cache read to time out, fall through to+ // resolvePrompt, and settle from the database with ~150ms of budget to spare.+ await jest.advanceTimersByTimeAsync(50);++ await expect(pending).resolves.toEqual({+ status: 'resolved',+ prompt: 'You are a helpful assistant.',+ facts: { source: 'native', groupId, promptId },+ });+ expect(promptService.resolvePrompt).toHaveBeenCalledTimes(1);+ expect(logger.warn).toHaveBeenCalledWith(+ '[linkedInstructions] Cache read failed; resolving without cache',+ expect.objectContaining({ groupId, errorName: 'LinkedInstructionsTimeoutError' }),+ );+ } finally {+ jest.useRealTimers();+ }+ });++ it('still bounds total latency to ~timeoutMs when both the cache read and resolvePrompt hang', async () => {+ jest.useFakeTimers();+ try {+ const cache = new FakeCache();+ jest.spyOn(cache, 'get').mockReturnValue(new Promise(() => {}));+ const promptService = makePromptService({+ // Also hangs, so this call can only settle via the shared-deadline timeout,+ // not because the mock happened to resolve fast.+ resolvePrompt: jest.fn().mockReturnValue(new Promise(() => {})),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const pending = resolver({ link: productionLink, config: { timeoutMs: 50 } });+ // The capped cache-read phase (min(250ms, 50/4) = 12.5ms) times out first;+ // the remaining ~37.5ms of the shared deadline is left for resolvePrompt,+ // which also hangs and times out in turn.+ await jest.advanceTimersByTimeAsync(50);++ await expect(pending).resolves.toEqual({ status: 'unavailable', reason: 'timeout' });+ } finally {+ jest.useRealTimers();+ }+ });++ it('returns unavailable "timeout" when resolvePrompt does not settle in time', async () => {+ jest.useFakeTimers();+ try {+ const cache = new FakeCache();+ const promptService = makePromptService({+ resolvePrompt: jest.fn().mockImplementation(+ () =>+ new Promise((resolve) => {+ setTimeout(() => resolve({ ok: true, value: makeResolvedPrompt() }), 200);+ }),+ ),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const pending = resolver({+ link: productionLink,+ config: { timeoutMs: 10 },+ });+ await jest.advanceTimersByTimeAsync(11);++ await expect(pending).resolves.toEqual({ status: 'unavailable', reason: 'timeout' });+ // Let the still-pending mock's own timer fire and resolve harmlessly.+ await jest.advanceTimersByTimeAsync(200);+ } finally {+ jest.useRealTimers();+ }+ });++ it('returns unavailable "error" when resolvePrompt throws', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService({+ resolvePrompt: jest.fn().mockRejectedValue(new Error('adapter exploded')),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const result = await resolver({ link: productionLink });++ expect(result).toEqual({ status: 'unavailable', reason: 'error' });+ expect(logger.error).toHaveBeenCalledWith(+ '[linkedInstructions] resolvePrompt failed',+ expect.objectContaining({ groupId, errorName: 'Error' }),+ );+ });++ it('maps unavailable_selection and blocked_content service errors', async () => {+ const cache = new FakeCache();+ const logger = makeLogger();++ const unavailableService = makePromptService({+ resolvePrompt: jest.fn().mockResolvedValue({+ ok: false,+ error: { type: 'unavailable_selection', reason: 'production' },+ }),+ });+ const unavailableResolver = createLinkedInstructionsResolver({+ promptService: unavailableService,+ cache,+ logger,+ });+ await expect(unavailableResolver({ link: productionLink })).resolves.toEqual({+ status: 'unavailable',+ reason: 'unavailable_selection',+ });++ const blockedService = makePromptService({+ resolvePrompt: jest.fn().mockResolvedValue({+ ok: false,+ error: { type: 'blocked_content', finding: { source: 'prompt' } },+ }),+ });+ const blockedResolver = createLinkedInstructionsResolver({+ promptService: blockedService,+ cache: new FakeCache(),+ logger,+ });+ await expect(blockedResolver({ link: productionLink })).resolves.toEqual({+ status: 'unavailable',+ reason: 'blocked_content',+ });+ });++ it('throws the abort reason when already aborted before any work starts', async () => {+ const cache = new FakeCache();+ const getSpy = jest.spyOn(cache, 'get');+ const setSpy = jest.spyOn(cache, 'set');+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const controller = new AbortController();+ controller.abort();++ await expect(resolver({ link: productionLink, signal: controller.signal })).rejects.toBe(+ controller.signal.reason,+ );+ expect(getSpy).not.toHaveBeenCalled();+ expect(setSpy).not.toHaveBeenCalled();+ expect(promptService.resolvePrompt).not.toHaveBeenCalled();+ });++ it('throws the abort reason when aborted mid-flight and never writes the cache', async () => {+ const cache = new FakeCache();+ const setSpy = jest.spyOn(cache, 'set');+ jest.spyOn(cache, 'get').mockReturnValue(new Promise(() => {}));+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const controller = new AbortController();+ const pending = resolver({+ link: productionLink,+ signal: controller.signal,+ });+ controller.abort();++ await expect(pending).rejects.toBe(controller.signal.reason);+ expect(setSpy).not.toHaveBeenCalled();+ });++ it('never logs prompt text', async () => {+ const secretMarker = 'DO-NOT-LOG-THIS-PROMPT-BODY';+ const cache = new FakeCache();+ jest.spyOn(cache, 'set').mockRejectedValue(new Error(secretMarker));+ const promptService = makePromptService({+ resolvePrompt: jest.fn().mockResolvedValue({+ ok: true,+ value: makeResolvedPrompt({ prompt: secretMarker }),+ }),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ await resolver({ link: productionLink });+ await flush();++ const allLogCalls = [...logger.warn.mock.calls, ...logger.error.mock.calls];+ for (const call of allLogCalls) {+ expect(JSON.stringify(call)).not.toContain(secretMarker);+ }+ });++ describe('tenant scoping', () => {+ it('scopes the cache key by tenant so two tenants never share an entry', async () => {+ const { tenantStorage } = await import('@librechat/data-schemas');+ const cache = new FakeCache();+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ await tenantStorage.run({ tenantId: 'tenant-a' }, () => resolver({ link: productionLink }));+ await tenantStorage.run({ tenantId: 'tenant-b' }, () => resolver({ link: productionLink }));++ const keys = cache.keys();+ expect(keys).toContain(`native:${groupId}:production:tenant-a`);+ expect(keys).toContain(`native:${groupId}:production:tenant-b`);+ expect(keys).not.toContain(`native:${groupId}:production`);+ // Neither tenant's cached entry satisfied the other's read.+ expect(promptService.resolvePrompt).toHaveBeenCalledTimes(2);+ });++ it('reuses the same key across calls within one tenant', async () => {+ const { tenantStorage } = await import('@librechat/data-schemas');+ const cache = new FakeCache();+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ await tenantStorage.run({ tenantId: 'tenant-a' }, async () => {+ await resolver({ link: productionLink });+ await resolver({ link: productionLink });+ });++ expect(promptService.resolvePrompt).toHaveBeenCalledTimes(1);+ });+ });++ describe('recordUse', () => {+ it('does not record usage on its own when resolve succeeds', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const result = await resolver({ link: productionLink });+ await flush();++ expect(result.status).toBe('resolved');+ expect(promptService.incrementPromptGroupUsage).not.toHaveBeenCalled();+ });++ it('records a usage generation for the given facts, fire-and-forget', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ resolver.recordUse({ source: 'native', groupId, promptId });+ await flush();++ expect(promptService.incrementPromptGroupUsage).toHaveBeenCalledTimes(1);+ expect(promptService.incrementPromptGroupUsage).toHaveBeenCalledWith(groupId);+ });++ it('logs but does not throw when incrementPromptGroupUsage fails', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService({+ incrementPromptGroupUsage: jest.fn().mockRejectedValue(new Error('usage boom')),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ expect(() => resolver.recordUse({ source: 'native', groupId, promptId })).not.toThrow();+ await flush();++ expect(logger.warn).toHaveBeenCalledWith(+ '[linkedInstructions] Failed to record prompt group usage',+ expect.objectContaining({ groupId, errorName: 'Error' }),+ );+ });+ });++ describe('invalidateLinkedPrompt', () => {+ it('clears only the production key when no promptIds are given', async () => {+ const cache = new FakeCache();+ await cache.set(`native:${groupId}:production`, 'cached');+ await cache.set(`native:${groupId}:exact:${promptId}`, 'cached');++ await invalidateLinkedPrompt(cache, groupId, []);++ await expect(cache.get(`native:${groupId}:production`)).resolves.toBeUndefined();+ await expect(cache.get(`native:${groupId}:exact:${promptId}`)).resolves.toBe('cached');+ });++ it('clears the production key plus one exact key per promptId', async () => {+ const otherPromptId = '507f1f77bcf86cd799439013';+ const cache = new FakeCache();+ await cache.set(`native:${groupId}:production`, 'cached');+ await cache.set(`native:${groupId}:exact:${promptId}`, 'cached');+ await cache.set(`native:${groupId}:exact:${otherPromptId}`, 'cached');++ await invalidateLinkedPrompt(cache, groupId, [promptId, otherPromptId]);++ expect(cache.keys()).toEqual([]);+ });++ it('does not disturb another group sharing the same cache', async () => {+ const otherGroupId = '507f1f77bcf86cd799439099';+ const cache = new FakeCache();+ await cache.set(`native:${groupId}:production`, 'cached');+ await cache.set(`native:${otherGroupId}:production`, 'cached');++ await invalidateLinkedPrompt(cache, groupId, []);++ await expect(cache.get(`native:${groupId}:production`)).resolves.toBeUndefined();+ await expect(cache.get(`native:${otherGroupId}:production`)).resolves.toBe('cached');+ });++ describe('tenant scoping', () => {+ it('clears only the calling tenant entry when two tenants cached the same group', async () => {+ const { tenantStorage } = await import('@librechat/data-schemas');+ const cache = new FakeCache();+ await tenantStorage.run({ tenantId: 'tenant-a' }, () =>+ cache.set(`native:${groupId}:production:tenant-a`, 'cached'),+ );+ await tenantStorage.run({ tenantId: 'tenant-b' }, () =>+ cache.set(`native:${groupId}:production:tenant-b`, 'cached'),+ );++ await tenantStorage.run({ tenantId: 'tenant-a' }, () =>+ invalidateLinkedPrompt(cache, groupId, []),+ );++ expect(cache.keys()).toEqual([`native:${groupId}:production:tenant-b`]);+ });+ });+ });+});diff --git a/packages/api/src/agents/instructions/linked.ts b/packages/api/src/agents/instructions/linked.tsnew file mode 100644index 0000000000..2d68ba09a7--- /dev/null+++ b/packages/api/src/agents/instructions/linked.ts@@ -0,0 +1,450 @@+import { scopedCacheKey } from '@librechat/data-schemas';+import type {+ FiltersConfig,+ AgentInstructionsPrompt,+ AgentInstructionsPromptSelection,+ RestrictedAgentInstructionsPrompt,+} from 'librechat-data-provider';+import type { PromptService } from '~/prompts/service';+import type { ResolvedPrompt } from '~/prompts/types';+import { assertModelBoundContent } from '~/middleware/modelBoundContent';+import { isContentFilterError } from '~/middleware/contentFilter';+import { inspectPromptContent } from '~/prompts/protection';++/**+ * Narrows `link` to a resolvable `native` link — the same test+ * `initializeAgent` uses to decide whether an agent's stored inline+ * `instructions` are live text or dead text superseded by a link. A+ * `RestrictedAgentInstructionsPrompt` stub (`{ source: 'native', restricted:+ * true }`, no `groupId`) is never valid: it never reaches `initializeAgent`+ * (that shape exists only for an editor without VIEW on the linked group),+ * so it must not be treated as a link that suppresses inline text elsewhere+ * either — most importantly in the HITL resume preflight, which inspects a+ * stored agent snapshot rather than a live `Agent`.+ */+export function isValidInstructionsPromptLink(+ link: AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null | undefined,+): link is AgentInstructionsPrompt {+ return link != null && link.source === 'native' && 'groupId' in link;+}++/** Facts about a resolved link, retained on the initialized agent. Never persisted. */+export type LinkedInstructionsFacts = {+ source: 'native';+ groupId: string;+ promptId: string;+};++export type LinkedInstructionsUnavailableReason =+ | 'unavailable_selection'+ | 'blocked_content'+ | 'timeout'+ | 'error';++export type LinkedInstructionsResult =+ | { status: 'resolved'; prompt: string; facts: LinkedInstructionsFacts }+ | { status: 'unavailable'; reason: LinkedInstructionsUnavailableReason };++/**+ * Resolves an agent's linked native prompt-group instructions. Usage is no+ * longer recorded here — call `.recordUse(facts)` (below) once the caller's+ * own initialization that used a `resolved` result has itself succeeded.+ */+export type ResolveLinkedInstructions = ((input: {+ link: AgentInstructionsPrompt;+ signal?: AbortSignal;+ filters?: FiltersConfig;+ config?: { timeoutMs?: number; native?: { cacheTtlMs?: number } };+}) => Promise<LinkedInstructionsResult>) & {+ /**+ * Records a usage generation for a resolved link's prompt group. The+ * resolver never calls this itself: `resolve` only reads and caches+ * content, so a caller that never calls `recordUse` records no usage at+ * all. Fire-and-forget — errors are caught and logged, never thrown, and+ * this returns before the increment settles.+ */+ recordUse(facts: LinkedInstructionsFacts): void;+};++/**+ * Minimal cache contract this module needs — `resolve` reads and writes, and+ * `invalidateLinkedPrompt` (below) deletes; a Keyv instance already satisfies this shape.+ */+export interface LinkedInstructionsCache {+ get(key: string): Promise<unknown>;+ set(key: string, value: unknown, ttl?: number): Promise<unknown>;+ delete(key: string): Promise<unknown>;+}++export interface LinkedInstructionsLogger {+ warn(msg: string, meta?: object): void;+ error(msg: string, meta?: object): void;+}++export interface CreateLinkedInstructionsResolverDeps {+ promptService: Pick<PromptService, 'resolvePrompt' | 'incrementPromptGroupUsage'>;+ cache: LinkedInstructionsCache;+ logger: LinkedInstructionsLogger;+}++/**+ * Mirrors the `linkedInstructions` block defaults in the data-provider agents+ * endpoint schema (`packages/data-provider/src/config.ts`). Those defaults+ * are inline zod literals, not exported constants, so this is the one place+ * that carries the runtime copy — nothing else in the resolver hardcodes+ * either number.+ */+const DEFAULT_TIMEOUT_MS = 2000;+const DEFAULT_CACHE_TTL_MS = 300_000;++/** The shape written to and read from the content cache. */+interface CachedLinkedPrompt {+ readonly groupId: string;+ readonly promptId: string;+ readonly prompt: string;+ readonly type: ResolvedPrompt['type'];+}++class LinkedInstructionsTimeoutError extends Error {+ constructor() {+ super('Linked instructions resolution timed out');+ this.name = 'LinkedInstructionsTimeoutError';+ }+}++function buildCacheKey(groupId: string, selection: AgentInstructionsPromptSelection): string {+ const selectionKey =+ selection.type === 'production' ? 'production' : `exact:${selection.promptId}`;+ return `native:${groupId}:${selectionKey}`;+}++/**+ * Clears a native prompt group's cached linked-instructions entries so a promote or+ * delete reaches a linked agent on the next request instead of after the cache's TTL.+ * Always clears the production selection; `promptIds` adds one exact selection per+ * revision ID the caller passes — a promote clears only production (empty+ * `promptIds`), a revision delete passes that revision's ID, and a group delete+ * passes every revision's ID. Keys are built with `buildCacheKey`, the same function+ * `resolve` uses, so both stay in agreement on the key format.+ */+export async function invalidateLinkedPrompt(+ cache: LinkedInstructionsCache,+ groupId: string,+ promptIds: readonly string[],+): Promise<void> {+ const selections: AgentInstructionsPromptSelection[] = [+ { type: 'production' },+ ...promptIds.map((promptId) => ({ type: 'exact' as const, promptId })),+ ];+ await Promise.all(+ selections.map((selection) => cache.delete(scopedCacheKey(buildCacheKey(groupId, selection)))),+ );+}++function isCachedLinkedPrompt(value: unknown): value is CachedLinkedPrompt {+ if (value == null || typeof value !== 'object') {+ return false;+ }+ const candidate = value as Partial<CachedLinkedPrompt>;+ return (+ typeof candidate.groupId === 'string' &&+ typeof candidate.promptId === 'string' &&+ typeof candidate.prompt === 'string'+ );+}++function errorName(error: unknown): string {+ return error instanceof Error ? error.name : typeof error;+}++function mapServiceErrorReason(+ type: 'invalid_input' | 'blocked_content' | 'unavailable_selection' | 'unsupported',+): LinkedInstructionsUnavailableReason {+ return type === 'blocked_content' || type === 'unavailable_selection' ? type : 'error';+}++/**+ * Whether `prompt` is blocked under the agent-instructions policy+ * (`filters.agentInstructions.pii`, via `assertModelBoundContent`'s `agents`+ * field — the same check inline agent instructions and repository+ * instructions get at init).+ *+ * Uses `isContentFilterError` — the same helper `access.ts` uses to recognize+ * a content-policy rejection — rather than an `instanceof ContentFilterError`+ * check, so every content-policy error `assertModelBoundContent` can throw+ * (including a traversal-limit or uninspectable-file error) maps to a block+ * consistently. An unrecognized error still throws (the caller,+ * `checkPromptBlocked` below, catches it and maps it to the resolver's+ * generic `'error'` reason rather than rejecting the resolution).+ */+function isBlockedAsAgentInstructions(prompt: string, filters: FiltersConfig | undefined): boolean {+ try {+ assertModelBoundContent({ filters, agents: [{ instructions: prompt }] });+ return false;+ } catch (error) {+ if (isContentFilterError(error)) {+ return true;+ }+ throw error;+ }+}++/**+ * Whether `prompt` is blocked under either policy a linked prompt is subject+ * to: the prompt-library policy (`filters.prompts.pii`, via+ * `inspectPromptContent` — the same check `resolvePrompt` runs on a fresh+ * fetch) or the agent-instructions policy (`isBlockedAsAgentInstructions`).+ */+function isPromptBlocked(prompt: string, filters: FiltersConfig | undefined): boolean {+ return (+ inspectPromptContent({ prompt }, filters) != null ||+ isBlockedAsAgentInstructions(prompt, filters)+ );+}++/**+ * Bounds `operation` by `timeoutMs` and cancels the wait immediately when+ * `signal` aborts — clearing the timeout timer right away rather than leaving+ * it to fire later. The underlying `operation` itself is not cancelled, only+ * this wait is, so a cache/adapter call already in flight cannot outlive its+ * caller's abort handling. Exported so other cache-bound call sites (for+ * example, the prompt handlers' cache clear) share this instead of a copy.+ */+export function runBounded<T>(+ operation: Promise<T>,+ timeoutMs: number,+ signal?: AbortSignal,+): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ let settled = false;+ const cleanup = (): void => {+ clearTimeout(timer);+ signal?.removeEventListener('abort', onAbort);+ };+ const settle = (run: () => void): void => {+ if (settled) {+ return;+ }+ settled = true;+ cleanup();+ run();+ };+ const onAbort = (): void => settle(() => reject(signal?.reason));+ const timer = setTimeout(+ () => settle(() => reject(new LinkedInstructionsTimeoutError())),+ timeoutMs,+ );+ signal?.addEventListener('abort', onAbort);+ operation.then(+ (value) => settle(() => resolve(value)),+ (error) => settle(() => reject(error)),+ );+ });+}++/** Milliseconds left until `deadline`, floored at 0. Never negative, so a+ * spent budget still schedules a real (if immediate) bounded call rather+ * than one with no timeout at all. */+function remainingMs(deadline: number): number {+ return Math.max(0, deadline - Date.now());+}++/** Caps the cache-read phase so a hung cache can never consume the whole+ * resolution deadline: at most 250ms, or a quarter of `timeoutMs` when that+ * is smaller. Whatever remains of `timeoutMs` after this phase — at least+ * three quarters of it — is left for `resolvePrompt`. */+function cacheReadBudgetMs(timeoutMs: number): number {+ return Math.min(250, timeoutMs / 4);+}++/**+ * Builds the runtime resolver for an agent's linked native prompt-group+ * instructions.+ *+ * Cache-first: a hit is checked under both policies — prompt-library and+ * agent-instructions — with the caller's *current* filters (so a policy+ * change blocks a previously-cached prompt) before being returned. A miss+ * calls `resolvePrompt`, which already applies the prompt-library policy+ * with the same filters, so the miss path checks only the+ * agent-instructions policy and writes the cache only on success, while+ * unaborted, and only when `cacheTtlMs > 0`. `cacheTtlMs === 0` skips the+ * cache read entirely (and never writes).+ *+ * Latency is bounded by one shared deadline (`config.timeoutMs` from the+ * moment `resolve` is called), not by re-arming a fresh timeout per phase —+ * a slow or failed cache read spends part of that budget, and only what+ * remains is left for `resolvePrompt`, so the worst case stays ~`timeoutMs`+ * overall instead of doubling. The cache-read phase itself is additionally+ * capped at `cacheReadBudgetMs` (at most 250ms, or a quarter of `timeoutMs`+ * when that is smaller) so a *hung* cache read — one that never settles —+ * cannot consume the entire deadline and starve `resolvePrompt` of its own+ * chance to run; a cache read failure or timeout is logged and treated as a+ * miss (falls through to `resolvePrompt`) rather than failing the turn — a+ * cache outage must not drop instructions. The cache write itself never+ * blocks the caller: it is fire-and-forget (errors caught and logged),+ * issued only when unaborted.+ *+ * Abort is checked before work starts and after every await and always+ * throws the signal's abort reason — it is never mapped to an `unavailable`+ * result, and a cancelled call never writes the cache. Failures (timeout on+ * the `resolvePrompt` phase, a thrown adapter error, or an unrecognized error+ * from the content-policy check) resolve to `{ status: 'unavailable', reason+ * }` — the resolution is never rejected by anything other than an abort.+ * Logs never include prompt text — only the reason, groupId, and the error's+ * name.+ *+ * The returned function never records prompt-group usage itself; call its+ * `.recordUse(facts)` once the caller's own initialization succeeds.+ */+export function createLinkedInstructionsResolver(+ deps: CreateLinkedInstructionsResolverDeps,+): ResolveLinkedInstructions {+ const { promptService, cache, logger } = deps;++ const resolve = async function resolveLinkedInstructions({+ link,+ signal,+ filters,+ config,+ }: {+ link: AgentInstructionsPrompt;+ signal?: AbortSignal;+ filters?: FiltersConfig;+ config?: { timeoutMs?: number; native?: { cacheTtlMs?: number } };+ }): Promise<LinkedInstructionsResult> {+ signal?.throwIfAborted();++ const timeoutMs = config?.timeoutMs ?? DEFAULT_TIMEOUT_MS;+ const cacheTtlMs = config?.native?.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;+ const key = scopedCacheKey(buildCacheKey(link.groupId, link.selection));+ const deadline = Date.now() + timeoutMs;++ let cached: CachedLinkedPrompt | undefined;+ if (cacheTtlMs > 0) {+ try {+ const cacheBudget = Math.min(remainingMs(deadline), cacheReadBudgetMs(timeoutMs));+ const raw = await runBounded(cache.get(key), cacheBudget, signal);+ cached = isCachedLinkedPrompt(raw) ? raw : undefined;+ } catch (error) {+ /* An abort must still surface as the abort reason, not be swallowed into+ * the "fall through to resolvePrompt" handling below. */+ signal?.throwIfAborted();+ logger.warn('[linkedInstructions] Cache read failed; resolving without cache', {+ groupId: link.groupId,+ errorName: errorName(error),+ });+ }+ }+ signal?.throwIfAborted();++ /** Neither content-policy check ever rejects the resolution: a recognized+ * content-policy error maps to `blocked_content`, and anything else — an+ * unexpected throw from `assertModelBoundContent` — is logged and mapped+ * to the generic `'error'` reason instead of propagating. `isBlocked` is+ * `isPromptBlocked` for a cache hit (both policies) or+ * `isBlockedAsAgentInstructions` for a fresh `resolvePrompt` result+ * (agent-instructions policy only, since `resolvePrompt` already applied+ * the prompt-library policy with the same filters). */+ const checkPromptBlocked = (+ prompt: string,+ isBlocked: (prompt: string, filters: FiltersConfig | undefined) => boolean,+ ): 'ok' | 'blocked' | 'error' => {+ try {+ return isBlocked(prompt, filters) ? 'blocked' : 'ok';+ } catch (error) {+ logger.error('[linkedInstructions] Content-policy check failed', {+ groupId: link.groupId,+ errorName: errorName(error),+ });+ return 'error';+ }+ };++ if (cached) {+ const blockCheck = checkPromptBlocked(cached.prompt, isPromptBlocked);+ if (blockCheck !== 'ok') {+ return {+ status: 'unavailable',+ reason: blockCheck === 'blocked' ? 'blocked_content' : 'error',+ };+ }+ return {+ status: 'resolved',+ prompt: cached.prompt,+ facts: { source: 'native', groupId: cached.groupId, promptId: cached.promptId },+ };+ }++ let fetched: ResolvedPrompt;+ try {+ const result = await runBounded(+ promptService.resolvePrompt({ groupId: link.groupId, selection: link.selection, filters }),+ remainingMs(deadline),+ signal,+ );+ signal?.throwIfAborted();+ if (!result.ok) {+ return { status: 'unavailable', reason: mapServiceErrorReason(result.error.type) };+ }+ fetched = result.value;+ } catch (error) {+ signal?.throwIfAborted();+ if (error instanceof LinkedInstructionsTimeoutError) {+ return { status: 'unavailable', reason: 'timeout' };+ }+ logger.error('[linkedInstructions] resolvePrompt failed', {+ groupId: link.groupId,+ errorName: errorName(error),+ });+ return { status: 'unavailable', reason: 'error' };+ }++ const fetchedBlockCheck = checkPromptBlocked(fetched.prompt, isBlockedAsAgentInstructions);+ if (fetchedBlockCheck !== 'ok') {+ return {+ status: 'unavailable',+ reason: fetchedBlockCheck === 'blocked' ? 'blocked_content' : 'error',+ };+ }++ if (cacheTtlMs > 0 && !signal?.aborted) {+ /* Fire-and-forget: the turn must not wait on the cache write, and a+ * write failure is a cache-warmth loss, not a resolution failure. */+ cache+ .set(+ key,+ {+ groupId: fetched.groupId,+ promptId: fetched.promptId,+ prompt: fetched.prompt,+ type: fetched.type,+ },+ cacheTtlMs,+ )+ .catch((error: unknown) => {+ logger.warn('[linkedInstructions] Cache write failed', {+ groupId: fetched.groupId,+ errorName: errorName(error),+ });+ });+ }+ signal?.throwIfAborted();++ return {+ status: 'resolved',+ prompt: fetched.prompt,+ facts: { source: 'native', groupId: fetched.groupId, promptId: fetched.promptId },+ };+ };++ const recordUse = (facts: LinkedInstructionsFacts): void => {+ promptService.incrementPromptGroupUsage(facts.groupId).catch((error: unknown) => {+ logger.warn('[linkedInstructions] Failed to record prompt group usage', {+ groupId: facts.groupId,+ errorName: errorName(error),+ });+ });+ };++ return Object.assign(resolve, { recordUse });+}diff --git a/packages/api/src/agents/instructions/writes.spec.ts b/packages/api/src/agents/instructions/writes.spec.tsnew file mode 100644index 0000000000..9b6b96da7c--- /dev/null+++ b/packages/api/src/agents/instructions/writes.spec.ts@@ -0,0 +1,415 @@+import { InstructionsPromptErrorCode } from 'librechat-data-provider';+import type { AgentInstructionsPrompt } from 'librechat-data-provider';+import {+ checkInstructionsPromptWrite,+ applyInstructionsPromptUnset,+ effectiveInstructionsPromptLink,+ excludeInstructionsWhenLinked,+ instructionsContentForScan,+} from './writes';+import { ContentTraversalLimitError } from '~/protection/adapters/nested';++const groupId = '507f1f77bcf86cd799439011';+const otherGroupId = '507f1f77bcf86cd799439022';++const user = { id: 'user-1', role: 'USER' };++const link: AgentInstructionsPrompt = {+ source: 'native',+ groupId,+ selection: { type: 'production' },+};++const otherLink: AgentInstructionsPrompt = {+ source: 'native',+ groupId: otherGroupId,+ selection: { type: 'production' },+};++const restrictedStub = { source: 'native' as const, restricted: true as const };++/** No-op logger satisfying `InstructionsPromptAccessLogger`; tests that care about+ * logging build their own and pass it instead. */+const logger = { warn: jest.fn(), error: jest.fn() };++describe('checkInstructionsPromptWrite', () => {+ it('returns null without calling access when the field is absent', async () => {+ const validateLinkWrite = jest.fn();+ const result = await checkInstructionsPromptWrite({+ access: { validateLinkWrite },+ operation: 'update',+ user,+ previous: link,+ next: undefined,+ logger,+ });+ expect(result).toBeNull();+ expect(validateLinkWrite).not.toHaveBeenCalled();+ });++ it('validates the link on create', async () => {+ const validateLinkWrite = jest.fn(async () => ({ ok: true as const }));+ await checkInstructionsPromptWrite({+ access: { validateLinkWrite },+ operation: 'create',+ user,+ previous: undefined,+ next: link,+ logger,+ });+ expect(validateLinkWrite).toHaveBeenCalledWith(+ expect.objectContaining({ previous: null, next: link }),+ );+ });++ it('validates the link on update', async () => {+ const validateLinkWrite = jest.fn(async () => ({ ok: true as const }));+ await checkInstructionsPromptWrite({+ access: { validateLinkWrite },+ operation: 'update',+ user,+ previous: otherLink,+ next: link,+ logger,+ });+ expect(validateLinkWrite).toHaveBeenCalledWith(+ expect.objectContaining({ previous: otherLink, next: link }),+ );+ });++ it('maps a rejection to the HTTP-shaped error response', async () => {+ const validateLinkWrite = jest.fn(async () => ({+ ok: false as const,+ status: 403 as const,+ code: InstructionsPromptErrorCode.FORBIDDEN,+ }));+ const result = await checkInstructionsPromptWrite({+ access: { validateLinkWrite },+ operation: 'create',+ user,+ previous: undefined,+ next: link,+ logger,+ });+ expect(result).toEqual({+ status: 403,+ body: { error: expect.any(String), code: InstructionsPromptErrorCode.FORBIDDEN },+ });+ });++ it('forwards filters', async () => {+ const validateLinkWrite = jest.fn(async () => ({ ok: true as const }));+ const filters = { pii: {} } as never;+ await checkInstructionsPromptWrite({+ access: { validateLinkWrite },+ operation: 'create',+ user,+ previous: undefined,+ next: link,+ filters,+ logger,+ });+ expect(validateLinkWrite).toHaveBeenCalledWith(expect.objectContaining({ filters }));+ });++ it('forwards req to validateLinkWrite for create/update so its role lookup can share the caller cache', async () => {+ const validateLinkWrite = jest.fn(async () => ({ ok: true as const }));+ const req = { marker: 'request-handle' };+ await checkInstructionsPromptWrite({+ access: { validateLinkWrite },+ operation: 'update',+ user,+ previous: otherLink,+ next: link,+ logger,+ req,+ });+ expect(validateLinkWrite).toHaveBeenCalledWith(expect.objectContaining({ req }));+ });++ describe('an unexpected check failure', () => {+ it.each(['create', 'update'] as const)(+ 'returns the fixed 500 and logs safely when validateLinkWrite throws on %s',+ async (operation) => {+ const log = { warn: jest.fn(), error: jest.fn() };+ const access = {+ validateLinkWrite: jest.fn(async () => {+ throw new Error('acl outage: secret-detail');+ }),+ };+ const result = await checkInstructionsPromptWrite({+ access,+ operation,+ user,+ previous: otherLink,+ next: link,+ logger: log,+ });+ expect(result).toEqual({+ status: 500,+ body: {+ error: 'Unable to validate the linked prompt',+ code: InstructionsPromptErrorCode.VALIDATION_FAILED,+ },+ });+ expect(log.error).toHaveBeenCalledTimes(1);+ const [, metadata] = log.error.mock.calls[0];+ expect(JSON.stringify(metadata)).not.toContain('secret-detail');+ },+ );++ it('rethrows a recognized content-filter error instead of masking it as a 500', async () => {+ const access = {+ validateLinkWrite: jest.fn(async () => {+ throw new ContentTraversalLimitError();+ }),+ };+ await expect(+ checkInstructionsPromptWrite({+ access,+ operation: 'create',+ user,+ previous: undefined,+ next: link,+ logger,+ }),+ ).rejects.toBeInstanceOf(ContentTraversalLimitError);+ });+ });+});++describe('applyInstructionsPromptUnset', () => {+ it('leaves the update untouched when the field is a link', () => {+ const updateData = { name: 'Agent', instructionsPrompt: link };+ expect(applyInstructionsPromptUnset(updateData)).toBe(updateData);+ });++ it('leaves the update untouched when the field is absent', () => {+ const updateData = { name: 'Agent' };+ expect(applyInstructionsPromptUnset(updateData)).toBe(updateData);+ });++ it('converts an explicit null into $unset and drops the field', () => {+ const updateData = { name: 'Agent', instructionsPrompt: null as null };+ const result = applyInstructionsPromptUnset(updateData);+ expect(result).toEqual({ name: 'Agent', $unset: { instructionsPrompt: 1 } });+ expect(result).not.toHaveProperty('instructionsPrompt');+ });++ it('merges with an existing $unset rather than replacing it', () => {+ const updateData = {+ name: 'Agent',+ instructionsPrompt: null as null,+ $unset: { git_identity: 1 },+ };+ const result = applyInstructionsPromptUnset(updateData);+ expect(result).toEqual({+ name: 'Agent',+ $unset: { git_identity: 1, instructionsPrompt: 1 },+ });+ });+});++describe('effectiveInstructionsPromptLink', () => {+ it('uses next when the payload carries the field', () => {+ expect(effectiveInstructionsPromptLink(link, otherLink)).toBe(link);+ });++ it('uses next when it is an explicit removal, even with a stored previous', () => {+ expect(effectiveInstructionsPromptLink(null, otherLink)).toBeNull();+ });++ it('falls back to previous when the field is absent from the payload', () => {+ expect(effectiveInstructionsPromptLink(undefined, otherLink)).toBe(otherLink);+ });++ it('is undefined when neither is set (create with no stored link)', () => {+ expect(effectiveInstructionsPromptLink(undefined, undefined)).toBeUndefined();+ });+});++describe('excludeInstructionsWhenLinked', () => {+ it('excludes instructions when the effective link is a real link', () => {+ const data = { instructions: 'blocked text', name: 'Agent' };+ const result = excludeInstructionsWhenLinked(data, { previous: undefined, effective: link });+ expect(result).toEqual({ instructions: undefined, name: 'Agent' });+ });++ it('leaves instructions untouched when there is no effective link', () => {+ const data = { instructions: 'inline text', name: 'Agent' };+ expect(excludeInstructionsWhenLinked(data, { previous: undefined, effective: null })).toBe(+ data,+ );+ expect(excludeInstructionsWhenLinked(data, { previous: undefined, effective: undefined })).toBe(+ data,+ );+ });++ it('leaves instructions untouched for a restricted stub (never valid on its own)', () => {+ const data = { instructions: 'inline text' };+ expect(+ excludeInstructionsWhenLinked(data, { previous: undefined, effective: restrictedStub }),+ ).toBe(data);+ });++ it('falls back to the stored instructions when the payload sends none and a previously valid link was removed', () => {+ const data = { instructions: undefined, name: 'Agent' };+ const result = excludeInstructionsWhenLinked(data, {+ previous: link,+ effective: null,+ fallbackInstructions: 'stored inline text',+ });+ expect(result).toEqual({ instructions: 'stored inline text', name: 'Agent' });+ });++ it('does NOT fall back for an ordinary unlinked agent (no previous link to remove) — regression guard', () => {+ // An unrelated partial edit of an agent that was never linked must scan only+ // what the payload sends, never stored text the write doesn't touch — even+ // when a fallback is supplied, as the update handler always does.+ const data = { instructions: undefined, name: 'Renamed' };+ const result = excludeInstructionsWhenLinked(data, {+ previous: null,+ effective: null,+ fallbackInstructions: 'stored text that would fail content policy',+ });+ expect(result).toBe(data);+ });++ it('does NOT fall back when previous was already the restricted stub (never a real link)', () => {+ const data = { instructions: undefined, name: 'Agent' };+ const result = excludeInstructionsWhenLinked(data, {+ previous: restrictedStub,+ effective: null,+ fallbackInstructions: 'stored inline text',+ });+ expect(result).toBe(data);+ });++ it('prefers the payload instructions over the fallback when both are present', () => {+ const data = { instructions: 'new inline text', name: 'Agent' };+ const result = excludeInstructionsWhenLinked(data, {+ previous: link,+ effective: null,+ fallbackInstructions: 'stored inline text',+ });+ expect(result).toBe(data);+ });++ it('leaves instructions untouched when there is no fallback and none in the payload', () => {+ const data = { instructions: undefined, name: 'Agent' };+ expect(excludeInstructionsWhenLinked(data, { previous: link, effective: null })).toBe(data);+ expect(excludeInstructionsWhenLinked(data, { previous: null, effective: undefined })).toBe(+ data,+ );+ });++ it('never falls back when the effective link is a real link (linked -> linked)', () => {+ const data = { instructions: undefined, name: 'Agent' };+ const result = excludeInstructionsWhenLinked(data, {+ previous: otherLink,+ effective: link,+ fallbackInstructions: 'stored inline text',+ });+ expect(result).toEqual({ instructions: undefined, name: 'Agent' });+ });+});++describe('instructionsContentForScan', () => {+ describe('create', () => {+ it('excludes instructions when the payload links on create', () => {+ const data = { instructions: 'blocked text', instructionsPrompt: link, name: 'Agent' };+ const result = instructionsContentForScan('create', { data });+ expect(result).toEqual({ instructions: undefined, instructionsPrompt: link, name: 'Agent' });+ });++ it('leaves instructions untouched when the payload has no link', () => {+ const data = { instructions: 'inline text', name: 'Agent' };+ expect(instructionsContentForScan('create', { data })).toBe(data);+ });+ });++ describe('duplicate', () => {+ it('excludes instructions when the source agent is linked', () => {+ const data = { instructions: 'blocked text', instructionsPrompt: link, name: 'Agent copy' };+ const result = instructionsContentForScan('duplicate', { data });+ expect(result).toEqual({+ instructions: undefined,+ instructionsPrompt: link,+ name: 'Agent copy',+ });+ });++ it('leaves instructions untouched when the source agent is unlinked', () => {+ const data = { instructions: 'inline text', name: 'Agent copy' };+ expect(instructionsContentForScan('duplicate', { data })).toBe(data);+ });+ });++ describe('update', () => {+ it('none -> valid: excludes instructions once the update links the agent', () => {+ const data = { instructions: 'blocked text', name: 'Agent' };+ const existing = { instructionsPrompt: null, instructions: 'stored text' };+ const result = instructionsContentForScan('update', { data, existing, nextLink: link });+ expect(result).toEqual({ instructions: undefined, name: 'Agent' });+ });++ it('valid -> null with no payload instructions: falls back to the stored instructions', () => {+ const data = { instructions: undefined, name: 'Agent' };+ const existing = { instructionsPrompt: link, instructions: 'stored inline text' };+ const result = instructionsContentForScan('update', { data, existing, nextLink: null });+ expect(result).toEqual({ name: 'Agent', instructions: 'stored inline text' });+ });++ it('valid -> valid: excludes instructions and ignores any fallback', () => {+ const data = { instructions: undefined, name: 'Agent' };+ const existing = { instructionsPrompt: link, instructions: 'stored inline text' };+ const result = instructionsContentForScan('update', { data, existing, nextLink: otherLink });+ expect(result).toEqual({ name: 'Agent', instructions: undefined });+ });++ it('unrelated partial edit on an unlinked agent has no fallback', () => {+ const data = { instructions: undefined, name: 'Renamed' };+ const existing = { instructionsPrompt: null, instructions: 'stored text that would fail' };+ const result = instructionsContentForScan('update', { data, existing, nextLink: undefined });+ expect(result).toBe(data);+ });+ });++ describe('revert', () => {+ it('none -> valid: excludes instructions once the snapshot carries a link', () => {+ const data = { instructions: 'blocked text', instructionsPrompt: link, name: 'Agent' };+ const existing = { instructionsPrompt: null, instructions: 'stored text' };+ const result = instructionsContentForScan('revert', { data, existing });+ expect(result).toEqual({ instructions: undefined, instructionsPrompt: link, name: 'Agent' });+ });++ it('valid -> null with no payload instructions: falls back to the current stored instructions', () => {+ const data = { instructions: undefined, instructionsPrompt: null, name: 'Agent' };+ const existing = { instructionsPrompt: link, instructions: 'stored inline text' };+ const result = instructionsContentForScan('revert', { data, existing });+ expect(result).toEqual({+ instructions: 'stored inline text',+ instructionsPrompt: null,+ name: 'Agent',+ });+ });++ it('valid -> valid: excludes instructions and ignores any fallback', () => {+ const data = { instructions: undefined, instructionsPrompt: otherLink, name: 'Agent' };+ const existing = { instructionsPrompt: link, instructions: 'stored inline text' };+ const result = instructionsContentForScan('revert', { data, existing });+ expect(result).toEqual({+ instructions: undefined,+ instructionsPrompt: otherLink,+ name: 'Agent',+ });+ });++ it('unrelated partial edit on an unlinked agent has no fallback', () => {+ const data = { instructions: undefined, instructionsPrompt: null, name: 'Renamed' };+ const existing = { instructionsPrompt: null, instructions: 'stored text that would fail' };+ const result = instructionsContentForScan('revert', { data, existing });+ expect(result).toBe(data);+ });+ });+});diff --git a/packages/api/src/agents/instructions/writes.ts b/packages/api/src/agents/instructions/writes.tsnew file mode 100644index 0000000000..62b22b842e--- /dev/null+++ b/packages/api/src/agents/instructions/writes.ts@@ -0,0 +1,252 @@+import { InstructionsPromptErrorCode } from 'librechat-data-provider';+import type {+ FiltersConfig,+ AgentInstructionsPrompt,+ RestrictedAgentInstructionsPrompt,+} from 'librechat-data-provider';+import type {+ InstructionsPromptAccess,+ InstructionsPromptAccessUser,+ InstructionsPromptAccessLogger,+ InstructionsPromptAccessRequest,+} from './access';+import type { InstructionsPromptLinkErrorResponse } from './errors';+import { getInstructionsPromptLinkError, buildInstructionsPromptError } from './errors';+import { isContentFilterError } from '~/middleware/contentFilter';+import { isValidInstructionsPromptLink } from './linked';+import { getSafeErrorMetadata } from '~/utils/errors';++export type InstructionsPromptWriteOperation = 'create' | 'update';++/**+ * Returned whenever the role, ACL, or prompt-store lookup backing a write check throws+ * unexpectedly (never for a recognized content-policy rejection, which `validateLinkWrite`+ * already turns into its own `ok: false` result). One fixed, pre-built response — no+ * detail about the failure is disclosed, and the caller logs the real cause separately+ * via `getSafeErrorMetadata`.+ */+const VALIDATION_FAILED_ERROR = buildInstructionsPromptError(+ 500,+ InstructionsPromptErrorCode.VALIDATION_FAILED,+);++/**+ * Validates one create or update write of `instructionsPrompt`, owning every branch+ * the write handler would otherwise carry: whether the field changed at all+ * (`next === undefined` short-circuits before any permission or prompt lookup) and+ * the permission/resolvability checks in `access.validateLinkWrite`. Returns `null`+ * when the write may proceed; the caller only needs to map a non-null result to its+ * HTTP response.+ *+ * Covers `'create'` and `'update'` only. A duplicate or revert carries its source+ * link (the duplicated agent's, or a version snapshot's) as-is and never calls this+ * function; Agent EDIT is the only authority either needs.+ *+ * Every branch runs inside one try/catch: an unexpected throw from the role, ACL, or+ * prompt-store lookups behind `validateLinkWrite` is logged here with+ * `getSafeErrorMetadata` and mapped to `VALIDATION_FAILED_ERROR` instead of reaching+ * the caller, where it would otherwise surface as a raw `error.message` on the+ * handler's catch-all. A recognized content-policy error is rethrown unchanged —+ * `validateLinkWrite` already maps that case to its own `ok: false` result, so one+ * reaching here would be an unrecognized caller bug, not a failure this function+ * should mask.+ */+export async function checkInstructionsPromptWrite({+ access,+ operation: _operation,+ user,+ previous,+ next,+ filters,+ logger,+ req,+}: {+ access: Pick<InstructionsPromptAccess, 'validateLinkWrite'>;+ operation: InstructionsPromptWriteOperation;+ user: InstructionsPromptAccessUser;+ previous: AgentInstructionsPrompt | null | undefined;+ next: AgentInstructionsPrompt | null | undefined;+ filters?: FiltersConfig;+ logger: InstructionsPromptAccessLogger;+ /** Forwarded unexamined to `access.validateLinkWrite` so its role lookup can reuse+ * the caller's per-request role cache. */+ req?: InstructionsPromptAccessRequest;+}): Promise<InstructionsPromptLinkErrorResponse | null> {+ if (next === undefined) {+ return null;+ }+ try {+ return await getInstructionsPromptLinkError({+ access,+ user,+ previous: previous ?? null,+ next,+ filters,+ req,+ });+ } catch (error) {+ if (isContentFilterError(error)) {+ throw error;+ }+ logger.error(+ '[checkInstructionsPromptWrite] Failed to validate a linked instructions-prompt write',+ getSafeErrorMetadata(error),+ );+ return VALIDATION_FAILED_ERROR;+ }+}++/**+ * Applies the create/update convention that a `null` `instructionsPrompt` in+ * the update payload means "remove the link" — expressed as `$unset` because+ * `removeNullishValues` drops a bare `null` before it would reach the database+ * driver. Leaves `updateData` untouched when the field isn't `null` (absent,+ * or a link to set). Any existing `$unset` entries on `updateData` are kept.+ * Takes and returns a plain record — the `/api` update payload it operates on+ * is assembled dynamically and has no single static shape.+ */+export function applyInstructionsPromptUnset(+ updateData: Record<string, unknown>,+): Record<string, unknown> {+ if (updateData.instructionsPrompt !== null) {+ return updateData;+ }+ const { instructionsPrompt: _removed, $unset, ...rest } = updateData;+ return {+ ...rest,+ $unset: { ...(($unset as Record<string, unknown> | undefined) ?? {}), instructionsPrompt: 1 },+ };+}++/**+ * The link that will govern the agent's instructions after this write: `next`+ * when the payload carries the field at all (including an explicit `null`+ * removal), otherwise whatever is already stored (`previous`). A create has+ * no stored link, so callers pass `undefined` for `previous` there.+ */+export function effectiveInstructionsPromptLink(+ next: AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null | undefined,+ previous: AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null | undefined,+): AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null | undefined {+ return next !== undefined ? next : previous;+}++/**+ * Resolves what a save-time content scan should see for `instructions`, given the+ * link that governed the agent before this write (`previous`) and the one that will+ * govern it after (`effective`).+ *+ * Excludes `instructions` when `effective` is a real link (`isValidInstructionsPromptLink`+ * — the same shape test `initializeAgent` uses): that text is dead once a link governs+ * the agent, so it must not block a write that is otherwise switching to safe, linked+ * content.+ *+ * Otherwise the agent's inline `instructions` are live text, and the payload's own+ * `instructions` is scanned as-is when present. `fallbackInstructions` only fills in+ * for a payload that sends none, and only when `previous` was a real link: that is+ * the one case where text that was never scanned while the link stayed valid+ * (`existingAgent.instructions` for an update, the reverted snapshot's own+ * `instructions` for a revert) is about to go live and must be scanned before it does.+ * An ordinary unlinked agent — `previous` was never a real link — keeps the base+ * behavior of scanning only what the payload actually submits; `fallbackInstructions`+ * is ignored for it even when supplied, so a safe partial edit that omits+ * `instructions` is never rejected over stored text nothing in this write touches.+ * Every other field of `data` is returned unchanged.+ */+export function excludeInstructionsWhenLinked<T extends { instructions?: unknown }>(+ data: T,+ {+ previous,+ effective,+ fallbackInstructions,+ }: {+ previous: AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null | undefined;+ effective: AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null | undefined;+ fallbackInstructions?: unknown;+ },+): T {+ if (isValidInstructionsPromptLink(effective)) {+ return { ...data, instructions: undefined };+ }+ const linkRemoved = isValidInstructionsPromptLink(previous);+ if (linkRemoved && data.instructions === undefined && fallbackInstructions !== undefined) {+ return { ...data, instructions: fallbackInstructions };+ }+ return data;+}++type InstructionsPromptLinkValue =+ | AgentInstructionsPrompt+ | RestrictedAgentInstructionsPrompt+ | null+ | undefined;++export type InstructionsContentScanOperation = 'create' | 'update' | 'duplicate' | 'revert';++/**+ * Resolves what a save-time content scan should see for `instructions` on one+ * agent write, dispatching `excludeInstructionsWhenLinked` with the `previous`/+ * `effective`/`fallbackInstructions` a given `operation` carries:+ *+ * - `'create'` and `'duplicate'`: there is no stored link to remove, so `previous`+ * is always `undefined` and `effective` is `data.instructionsPrompt` as submitted+ * (copied verbatim from the source agent on a duplicate). No fallback applies.+ * - `'update'`: `previous` is `existing.instructionsPrompt`; `effective` is+ * `nextLink` when the payload carries the field at all (including an explicit+ * `null` removal), otherwise `previous`. `fallbackInstructions` is+ * `existing.instructions` — the text never scanned while the link stayed valid —+ * so it goes live once a previously valid link is removed and the payload sends+ * no `instructions` of its own.+ * - `'revert'`: the snapshot's own `instructionsPrompt` restores as-is, so+ * `effective` is `data.instructionsPrompt ?? null` with no permission or+ * resolvability check. `previous` is `existing.instructionsPrompt ?? null`, and+ * `fallbackInstructions` is `existing.instructions` — a reverted snapshot never+ * unsets `instructions` for a missing field, so the agent's current stored text+ * stays active and must be scanned when a valid link is being removed.+ *+ * Every case excludes `instructions` entirely once `effective` is a real link+ * (`isValidInstructionsPromptLink`): that text is dead once a link governs the+ * agent, so it must not block a write that is otherwise switching to safe, linked+ * content. See `excludeInstructionsWhenLinked` for the shared exclusion/fallback+ * rule this applies.+ */+export function instructionsContentForScan<+ T extends { instructions?: unknown; instructionsPrompt?: unknown },+>(+ operation: InstructionsContentScanOperation,+ {+ data,+ existing,+ nextLink,+ }: {+ data: T;+ existing?: { instructions?: unknown; instructionsPrompt?: unknown } | null;+ nextLink?: unknown;+ },+): T {+ switch (operation) {+ case 'create':+ case 'duplicate':+ return excludeInstructionsWhenLinked(data, {+ previous: undefined,+ effective: data.instructionsPrompt as InstructionsPromptLinkValue,+ });+ case 'update': {+ const previous = existing?.instructionsPrompt as InstructionsPromptLinkValue;+ return excludeInstructionsWhenLinked(data, {+ previous,+ effective: effectiveInstructionsPromptLink(+ nextLink as InstructionsPromptLinkValue,+ previous,+ ),+ fallbackInstructions: existing?.instructions,+ });+ }+ case 'revert':+ return excludeInstructionsWhenLinked(data, {+ previous: (existing?.instructionsPrompt ?? null) as InstructionsPromptLinkValue,+ effective: (data.instructionsPrompt ?? null) as InstructionsPromptLinkValue,+ fallbackInstructions: existing?.instructions,+ });+ }+}diff --git a/packages/api/src/agents/lazySubagents.spec.ts b/packages/api/src/agents/lazySubagents.spec.tsindex 320a0235fb..a21aad6981 100644--- a/packages/api/src/agents/lazySubagents.spec.ts+++ b/packages/api/src/agents/lazySubagents.spec.ts@@ -75,6 +75,36 @@ describe('getLazySubagentConfigId', () => {);});+ it('changes when the linked instructions prompt changes, even at the same version', () => {+ const linkedA = {+ ...agent,+ instructionsPrompt: {+ source: 'native' as const,+ groupId: 'group-a',+ selection: { type: 'production' as const },+ },+ };+ const linkedB = {+ ...agent,+ instructionsPrompt: {+ source: 'native' as const,+ groupId: 'group-b',+ selection: { type: 'production' as const },+ },+ };++ // Same `version` on both sides reproduces a revert that restores an older link+ // without bumping the version number.+ expect(getLazySubagentConfigId(linkedA)).not.toBe(getLazySubagentConfigId(linkedB));+ });++ it('leaves the descriptor identity unchanged for an agent with no linked prompt', () => {+ const withoutLink = getLazySubagentConfigId(agent);+ const explicitlyUnset = getLazySubagentConfigId({ ...agent, instructionsPrompt: undefined });++ expect(explicitlyUnset).toBe(withoutLink);+ });+it('changes when the persisted skill catalog scope changes', () => {expect(getLazySubagentConfigId({diff --git a/packages/api/src/agents/lazySubagents.ts b/packages/api/src/agents/lazySubagents.tsindex 50e1ac20e7..ff1f2e356f 100644--- a/packages/api/src/agents/lazySubagents.ts+++ b/packages/api/src/agents/lazySubagents.ts@@ -33,6 +33,7 @@ type VersionedAgent = Pick<| 'hide_sequential_outputs'| 'subagents'| 'memory_scope'+ | 'instructionsPrompt'> & {version?: number;actions?: string[];@@ -82,6 +83,7 @@ export function selectLazySubagentConfig(agent: VersionedAgent): Omit<VersionedAdescription,instructions,additional_instructions,+ instructionsPrompt,endpoint,provider,model,@@ -116,6 +118,7 @@ export function selectLazySubagentConfig(agent: VersionedAgent): Omit<VersionedAdescription,instructions,additional_instructions,+ instructionsPrompt,endpoint,provider,model,diff --git a/packages/api/src/agents/management.spec.ts b/packages/api/src/agents/management.spec.tsindex 01939c853e..bb6535b982 100644--- a/packages/api/src/agents/management.spec.ts+++ b/packages/api/src/agents/management.spec.ts@@ -113,6 +113,25 @@ describe('Agent Management contract', () => {},);+ it.each([agentManagementCreateSchema, agentManagementUpdateSchema])(+ 'rejects instructionsPrompt — the Builder-only prompt-group link is not a Management API field',+ (schema) => {+ const base =+ schema === agentManagementCreateSchema ? { provider: 'openAI', model: 'gpt-5' } : {};+ expect(+ schema.safeParse({+ ...base,+ instructionsPrompt: {+ source: 'native',+ groupId: '64da00000000000000000001',+ selection: { type: 'production' },+ },+ }).success,+ ).toBe(false);+ expect(schema.safeParse({ ...base, instructionsPrompt: null }).success).toBe(false);+ },+ );+it('rejects a null model before Agent creation reaches persistence', () => {expect(agentManagementCreateSchema.safeParse({ provider: 'openAI', model: null }).success,@@ -237,6 +256,29 @@ describe('Agent Management contract', () => {expect(response).not.toHaveProperty('is_promoted');});+ it('never returns instructionsPrompt — the Builder-only prompt-group link is not a Management API field', () => {+ // The projection source type has no `instructionsPrompt` field (see the note above+ // `agentManagementCreateSchema`); the cast simulates a stored document that still+ // carries the Builder's own link, to prove the allowlist drops it regardless.+ const response = projectAgentManagementResponse({+ ...persistedAgent,+ instructionsPrompt: {+ source: 'native',+ groupId: '64da00000000000000000001',+ selection: { type: 'production' },+ },+ } as Record<string, unknown> as typeof persistedAgent);++ expect(response).not.toHaveProperty('instructionsPrompt');+ expect(agentManagementResponseSchema.parse(response)).toEqual(response);+ expect(+ agentManagementResponseSchema.safeParse({+ ...response,+ instructionsPrompt: { source: 'native', restricted: true },+ }).success,+ ).toBe(false);+ });+it('omits legacy string avatars that are not part of the management contract', () => {const response = projectAgentManagementResponse({...persistedAgent,diff --git a/packages/api/src/agents/management.ts b/packages/api/src/agents/management.tsindex 306b17aa79..d7275ca809 100644--- a/packages/api/src/agents/management.ts+++ b/packages/api/src/agents/management.ts@@ -10,15 +10,28 @@ const MAX_LIST_LIMIT = 100;const DEFAULT_LIST_LIMIT = 20;const MAX_CURSOR_LENGTH = 512;-export type AgentManagementCreate = Omit<z.output<typeof agentCreateSchema>, 'model'> & {+/**+ * `instructionsPrompt` (the Builder's link to a native prompt group) is a Builder-only+ * feature in this slice: the Management API never accepts or returns it, so every+ * Management type and schema below omits the field entirely, the same way an unknown+ * top-level field is rejected rather than silently stripped (see the note above+ * `agentManagementCreateSchema`).+ */+export type AgentManagementCreate = Omit<+ z.output<typeof agentCreateSchema>,+ 'model' | 'instructionsPrompt'+> & {model: string;};-type AgentManagementCreateInput = Omit<z.input<typeof agentCreateSchema>, 'model'> & {+type AgentManagementCreateInput = Omit<+ z.input<typeof agentCreateSchema>,+ 'model' | 'instructionsPrompt'+> & {model: string;};export type AgentManagementUpdate = Omit<z.output<typeof agentUpdateSchema>,- 'name' | 'description' | 'instructions' | 'model' | 'avatar'+ 'name' | 'description' | 'instructions' | 'model' | 'avatar' | 'instructionsPrompt'> & {name?: string;description?: string;@@ -32,7 +45,7 @@ export type AgentManagementList = {};export type AgentManagementResponse = Omit<z.output<typeof agentUpdateSchema>,- 'provider' | 'model'+ 'provider' | 'model' | 'instructionsPrompt'> & {id: string;provider: string;@@ -95,8 +108,9 @@ export const agentManagementCreateSchema: z.ZodType<AgentManagementCreate,z.ZodTypeDef,AgentManagementCreateInput-> = agentCreateSchema.extend({ model: z.string() }).strict();+> = agentCreateSchema.omit({ instructionsPrompt: true }).extend({ model: z.string() }).strict();export const agentManagementUpdateSchema: z.ZodType<AgentManagementUpdate> = agentUpdateSchema+ .omit({ instructionsPrompt: true }).extend({name: z.string().optional(),description: z.string().optional(),@@ -168,8 +182,10 @@ const agentManagementSubagentsResponseSchema: z.ZodType<AgentSubagentsConfig | u.strict().optional();-/** The externally supported Agent shape. Persistence and ownership fields are intentionally absent. */+/** The externally supported Agent shape. Persistence and ownership fields are intentionally+ * absent, and so is `instructionsPrompt` — see the note above `agentManagementCreateSchema`. */export const agentManagementResponseSchema: z.ZodType<AgentManagementResponse> = agentUpdateSchema+ .omit({ instructionsPrompt: true }).extend({id: z.string().min(1),provider: z.string(),diff --git a/packages/api/src/agents/openai/service.spec.ts b/packages/api/src/agents/openai/service.spec.tsindex 852e1418aa..3eff802d34 100644--- a/packages/api/src/agents/openai/service.spec.ts+++ b/packages/api/src/agents/openai/service.spec.ts@@ -612,6 +612,21 @@ describe('createAgentChatCompletion - MCP permission user propagation', () => {);});+ /** Unlike `resolveWebSearchGrant`, there is no default DB-backed resolution path+ * for a linked agent — the embedder's resolver (and usage-recording flag) must+ * reach `initializeAgent` verbatim or a linked agent silently loses its instructions. */+ it('forwards resolveLinkedInstructions and recordLinkedPromptUsage verbatim to initializeAgent', async () => {+ const resolveLinkedInstructions = jest.fn();+ deps.resolveLinkedInstructions = resolveLinkedInstructions as never;+ deps.recordLinkedPromptUsage = false;++ await createAgentChatCompletion(createMockReq({ id: 'user-123' }), createMockRes(), deps);++ expect(deps.initializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ resolveLinkedInstructions, recordLinkedPromptUsage: false }),+ );+ });+it('preserves stateful scope policy status and code in an initialization error response', async () => {const policyError = Object.assign(new Error('Stateful code environment is not allowed by this deployment: conversation'),diff --git a/packages/api/src/agents/openai/service.ts b/packages/api/src/agents/openai/service.tsindex 71a061b2cf..0b4d8a7ad6 100644--- a/packages/api/src/agents/openai/service.ts+++ b/packages/api/src/agents/openai/service.ts@@ -132,6 +132,15 @@ export interface ChatCompletionDependencies {getRoleByName?: Parameters<typeof resolveToolRoleGrants>[0]['getRoleByName'];/** Tool execute options for event-driven tool execution */toolExecuteOptions?: ToolExecuteOptions;+ /**+ * Resolves an agent's `instructionsPrompt` link. Unlike `getRoleByName`,+ * this has no default resolution path — the embedder must build it (a+ * prompt service, cache, and logger) and supply it here for a linked agent+ * to receive resolved instructions instead of falling back to empty.+ */+ resolveLinkedInstructions?: CoreInitializeAgentParams['resolveLinkedInstructions'];+ /** Forwarded to `initializeAgent`; defaults to `true` when omitted. */+ recordLinkedPromptUsage?: CoreInitializeAgentParams['recordLinkedPromptUsage'];}/**@@ -221,6 +230,15 @@ interface InitializeAgentParams {* search when it resolves `false`.*/resolveWebSearchGrant?: () => Promise<boolean>;+ /**+ * Resolves this agent's `instructionsPrompt` link (a linked native prompt+ * group). `initializeAgent` calls it only when the agent carries a+ * resolvable link; absent, a linked agent falls back to empty instructions+ * with a warning, since there is no default resolution path.+ */+ resolveLinkedInstructions?: CoreInitializeAgentParams['resolveLinkedInstructions'];+ /** Forwarded to `initializeAgent`; defaults to `true` when omitted. */+ recordLinkedPromptUsage?: CoreInitializeAgentParams['recordLinkedPromptUsage'];/*** Whether the admin-level `stateful_code_sessions` capability is enabled.* Threaded to `initializeAgent` alongside `codeEnvAvailable` so this@@ -779,6 +797,8 @@ export async function createAgentChatCompletion(codeEnvAvailable,fileSearchAvailable,resolveWebSearchGrant,+ resolveLinkedInstructions: deps.resolveLinkedInstructions,+ recordLinkedPromptUsage: deps.recordLinkedPromptUsage,statefulSessionsAvailable,allowedStatefulCodeEnvironments,backgroundToolsAvailable,diff --git a/packages/api/src/agents/validation.spec.ts b/packages/api/src/agents/validation.spec.tsindex 66f6ea4806..d2b4266b40 100644--- a/packages/api/src/agents/validation.spec.ts+++ b/packages/api/src/agents/validation.spec.ts@@ -15,6 +15,9 @@ import {validateAgentModel,} from './validation';+const validGroupId = '507f1f77bcf86cd799439011';+const validPromptId = '507f191e810c19729de860ea';+describe('agent Git identity validation', () => {const base = { provider: 'openAI', model: 'gpt-4o-mini', tools: [] };@@ -51,6 +54,132 @@ describe('agent Git identity validation', () => {});});+describe('agent instructions-prompt link validation', () => {+ const base = { provider: 'openAI', model: 'gpt-4o-mini', tools: [] };++ it('accepts a production selection on create and update', () => {+ const instructionsPrompt = {+ source: 'native' as const,+ groupId: validGroupId,+ selection: { type: 'production' as const },+ };+ expect(agentCreateSchema.parse({ ...base, instructionsPrompt }).instructionsPrompt).toEqual(+ instructionsPrompt,+ );+ expect(agentUpdateSchema.parse({ instructionsPrompt }).instructionsPrompt).toEqual(+ instructionsPrompt,+ );+ });++ it('accepts an exact selection with a valid promptId', () => {+ const instructionsPrompt = {+ source: 'native' as const,+ groupId: validGroupId,+ selection: { type: 'exact' as const, promptId: validPromptId },+ };+ expect(agentCreateSchema.parse({ ...base, instructionsPrompt }).instructionsPrompt).toEqual(+ instructionsPrompt,+ );+ });++ it('accepts null on create and update to keep or remove the link', () => {+ expect(+ agentCreateSchema.parse({ ...base, instructionsPrompt: null }).instructionsPrompt,+ ).toBeNull();+ expect(agentUpdateSchema.parse({ instructionsPrompt: null }).instructionsPrompt).toBeNull();+ });++ it('rejects a malformed groupId', () => {+ expect(+ agentCreateSchema.safeParse({+ ...base,+ instructionsPrompt: {+ source: 'native',+ groupId: 'not-an-object-id',+ selection: { type: 'production' },+ },+ }).success,+ ).toBe(false);+ });++ it('rejects a malformed promptId on an exact selection', () => {+ expect(+ agentCreateSchema.safeParse({+ ...base,+ instructionsPrompt: {+ source: 'native',+ groupId: validGroupId,+ selection: { type: 'exact', promptId: 'not-an-object-id' },+ },+ }).success,+ ).toBe(false);+ });++ it('rejects an unknown source', () => {+ expect(+ agentCreateSchema.safeParse({+ ...base,+ instructionsPrompt: {+ source: 'langfuse',+ groupId: validGroupId,+ selection: { type: 'production' },+ },+ }).success,+ ).toBe(false);+ });++ it('rejects an unknown selection type', () => {+ expect(+ agentCreateSchema.safeParse({+ ...base,+ instructionsPrompt: {+ source: 'native',+ groupId: validGroupId,+ selection: { type: 'staging' },+ },+ }).success,+ ).toBe(false);+ });++ it('rejects extra keys on the link and on the selection', () => {+ expect(+ agentCreateSchema.safeParse({+ ...base,+ instructionsPrompt: {+ source: 'native',+ groupId: validGroupId,+ selection: { type: 'production' },+ extra: true,+ },+ }).success,+ ).toBe(false);+ expect(+ agentCreateSchema.safeParse({+ ...base,+ instructionsPrompt: {+ source: 'native',+ groupId: validGroupId,+ selection: { type: 'production', extra: true },+ },+ }).success,+ ).toBe(false);+ });++ it('keeps the field on both create and update schemas instead of stripping it', () => {+ const instructionsPrompt = {+ source: 'native' as const,+ groupId: validGroupId,+ selection: { type: 'production' as const },+ };+ expect(agentCreateSchema.parse({ ...base, instructionsPrompt })).toMatchObject({+ instructionsPrompt,+ });+ expect(agentUpdateSchema.parse({ instructionsPrompt })).toMatchObject({+ instructionsPrompt,+ });+ });+});+describe('agentSubagentsSchema', () => {const graph = {type: 'research_team',diff --git a/packages/api/src/agents/validation.ts b/packages/api/src/agents/validation.tsindex abc4ba1778..cde6c1fb98 100644--- a/packages/api/src/agents/validation.ts+++ b/packages/api/src/agents/validation.ts@@ -1,4 +1,5 @@import { z } from 'zod';+import { isValidObjectIdString } from '@librechat/data-schemas';import {CODE_WORKSPACE_ID_PATTERN,MAX_AGENT_CODE_ENVIRONMENT_CHOICES,@@ -17,6 +18,7 @@ import type {AgentGitIdentity,TModelsConfig,AgentSubagentsConfig,+ AgentInstructionsPrompt,} from 'librechat-data-provider';import type { Request, Response } from 'express';@@ -402,11 +404,35 @@ const agentCodeEnvironmentIdsSchema: z.ZodArray<z.ZodString> = zconst agentGitIdentityUpdateSchema: z.ZodType<AgentGitIdentity | null | undefined> =agentGitIdentitySchema.nullable();+/** A 24-character hexadecimal Mongo ObjectId string. */+const objectIdStringSchema = z.string().refine(isValidObjectIdString);++/** Selects which revision of a linked prompt group an agent's instructions follow. */+const instructionsPromptSelectionSchema = z.discriminatedUnion('type', [+ z.object({ type: z.literal('production') }).strict(),+ z.object({ type: z.literal('exact'), promptId: objectIdStringSchema }).strict(),+]);++/** Links an agent's instructions to a native LibreChat prompt group revision. */+export const agentInstructionsPromptSchema: z.ZodType<AgentInstructionsPrompt> = z+ .object({+ source: z.literal('native'),+ groupId: objectIdStringSchema,+ selection: instructionsPromptSelectionSchema,+ })+ .strict();++/** Shared field schema: `.nullable().optional()` per contract, `null` removes the link. */+const agentInstructionsPromptFieldSchema: z.ZodOptional<+ z.ZodNullable<typeof agentInstructionsPromptSchema>+> = agentInstructionsPromptSchema.nullable().optional();+export const agentBaseSchema: z.ZodObject<{name: z.ZodOptional<z.ZodNullable<z.ZodString>>;description: z.ZodOptional<z.ZodNullable<z.ZodString>>;instructions: z.ZodOptional<z.ZodNullable<z.ZodString>>;+ instructionsPrompt: z.ZodOptional<z.ZodNullable<typeof agentInstructionsPromptSchema>>;avatar: z.ZodOptional<z.ZodNullable<z.ZodObject<@@ -554,6 +580,7 @@ export const agentBaseSchema: z.ZodObject<name: z.string().nullable().optional(),description: z.string().nullable().optional(),instructions: z.string().nullable().optional(),+ instructionsPrompt: agentInstructionsPromptFieldSchema,avatar: agentAvatarSchema.nullable().optional(),model_parameters: z.record(z.unknown()).optional(),tools: z.array(z.string()).optional(),@@ -590,6 +617,7 @@ export const agentCreateSchema: z.ZodObject<name: z.ZodOptional<z.ZodNullable<z.ZodString>>;description: z.ZodOptional<z.ZodNullable<z.ZodString>>;instructions: z.ZodOptional<z.ZodNullable<z.ZodString>>;+ instructionsPrompt: z.ZodOptional<z.ZodNullable<typeof agentInstructionsPromptSchema>>;avatar: z.ZodOptional<z.ZodNullable<z.ZodObject<@@ -747,6 +775,7 @@ export const agentUpdateSchema: z.ZodObject<name: z.ZodOptional<z.ZodNullable<z.ZodString>>;description: z.ZodOptional<z.ZodNullable<z.ZodString>>;instructions: z.ZodOptional<z.ZodNullable<z.ZodString>>;+ instructionsPrompt: z.ZodOptional<z.ZodNullable<typeof agentInstructionsPromptSchema>>;model_parameters: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;tools: z.ZodOptional<z.ZodArray<z.ZodString, 'many'>>;skills: z.ZodOptional<z.ZodArray<z.ZodString, 'many'>>;diff --git a/packages/api/src/openapi/agents.ts b/packages/api/src/openapi/agents.tsindex 18aea24bf4..c7e271b620 100644--- a/packages/api/src/openapi/agents.ts+++ b/packages/api/src/openapi/agents.ts@@ -47,6 +47,13 @@ function withDocumentedEdges(schema: ZodTypeAny): ZodTypeAny {});}+/**+ * `instructionsPrompt` (the Builder's link to a native prompt group) is Builder-only: the+ * Management API's create/update/response schemas omit it entirely (see+ * `packages/api/src/agents/management.ts`), so this document never carries the field —+ * neither the full link shape a request could send nor the restricted stub a Builder+ * response can carry (`packages/api/src/agents/instructions/access.ts`).+ */const agentCreateRequestSchema = withDocumentedEdges(agentManagementCreateSchema);const agentUpdateRequestSchema = withDocumentedEdges(agentManagementUpdateSchema);const agentResponseSchema = withDocumentedEdges(agentManagementResponseSchema);diff --git a/packages/api/src/prompts/handlers.spec.ts b/packages/api/src/prompts/handlers.spec.tsnew file mode 100644index 0000000000..ee11e5e770--- /dev/null+++ b/packages/api/src/prompts/handlers.spec.ts@@ -0,0 +1,447 @@+import { logger } from '@librechat/data-schemas';+import type { Response } from 'express';+import type { PromptRequest, PromptHandlersDeps } from './handlers';+import type { PromptService } from './service';+import { createPromptHandlers } from './handlers';++function mockReq(overrides: Record<string, unknown> = {}): PromptRequest {+ return {+ user: { id: 'u1' },+ params: {},+ query: {},+ body: {},+ ...overrides,+ } as unknown as PromptRequest;+}++interface MockRes {+ statusCode: number;+ body: unknown;+ status: jest.Mock;+ send: jest.Mock;+ json: jest.Mock;+}++function mockRes(): Response & MockRes {+ const res: MockRes = {+ statusCode: 200,+ body: undefined,+ status: jest.fn((code: number) => {+ res.statusCode = code;+ return res;+ }),+ send: jest.fn((data: unknown) => {+ res.body = data;+ return res;+ }),+ json: jest.fn((data: unknown) => {+ res.body = data;+ return res;+ }),+ };+ return res as unknown as Response & MockRes;+}++function makeService(overrides: Partial<PromptService> = {}): PromptService {+ return {+ resolvePrompt: jest.fn(),+ getListPromptGroupsByAccess: jest.fn(),+ getPrompts: jest.fn().mockResolvedValue([]),+ createPromptGroup: jest.fn(),+ savePrompt: jest.fn(),+ getPromptGroup: jest.fn(),+ getPrompt: jest.fn(),+ incrementPromptGroupUsage: jest.fn(),+ updatePromptGroup: jest.fn(),+ makePromptProduction: jest.fn(),+ deletePrompt: jest.fn(),+ deletePromptGroup: jest.fn(),+ ...overrides,+ } as unknown as PromptService;+}++function makeDeps(overrides: Partial<PromptHandlersDeps> = {}): PromptHandlersDeps {+ return {+ service: makeService(),+ getPromptGroupAccessContext: jest.fn(),+ getEffectivePermissions: jest.fn(),+ ...overrides,+ };+}++const groupId = '507f1f77bcf86cd799439011';+const promptId = '507f1f77bcf86cd799439012';++/** The shape `canAccessPromptViaGroup` stores on a non-bypass request. */+function withLoadedRevision(overrides: Record<string, unknown> = {}): PromptRequest {+ return mockReq({+ params: { promptId },+ resourceAccess: { resourceInfo: { _id: groupId, prompt: { _id: promptId, groupId } } },+ ...overrides,+ });+}++describe('createPromptHandlers linked-instructions cache clearing', () => {+ afterEach(() => {+ jest.restoreAllMocks();+ });++ describe('makePromptProduction', () => {+ it('clears the production key for the promoted revision’s group', async () => {+ const invalidateLinkedPrompt = jest.fn().mockResolvedValue(undefined);+ const service = makeService({+ makePromptProduction: jest.fn().mockResolvedValue({+ ok: true,+ value: { message: 'Prompt production made successfully' },+ groupId,+ }),+ });+ const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));+ const res = mockRes();++ await handlers.makePromptProduction(withLoadedRevision(), res);++ expect(invalidateLinkedPrompt).toHaveBeenCalledTimes(1);+ expect(invalidateLinkedPrompt).toHaveBeenCalledWith(groupId, []);+ expect(res.statusCode).toBe(200);+ });++ it('does not clear the cache when the promote is rejected', async () => {+ const invalidateLinkedPrompt = jest.fn();+ const service = makeService({+ makePromptProduction: jest+ .fn()+ .mockResolvedValue({ ok: false, error: { type: 'invalid_input', message: 'bad' } }),+ });+ const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));+ const res = mockRes();++ await handlers.makePromptProduction(withLoadedRevision(), res);++ expect(invalidateLinkedPrompt).not.toHaveBeenCalled();+ });++ it('clears the cache from the service result when no resourceInfo was loaded (capability bypass)', async () => {+ const invalidateLinkedPrompt = jest.fn().mockResolvedValue(undefined);+ const service = makeService({+ makePromptProduction: jest.fn().mockResolvedValue({+ ok: true,+ value: { message: 'Prompt production made successfully' },+ groupId,+ }),+ });+ const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));+ const res = mockRes();++ await handlers.makePromptProduction(mockReq({ params: { promptId } }), res);++ expect(invalidateLinkedPrompt).toHaveBeenCalledTimes(1);+ expect(invalidateLinkedPrompt).toHaveBeenCalledWith(groupId, []);+ expect(res.statusCode).toBe(200);+ });++ it('does not clear the cache when the promoted revision has no group id', async () => {+ const invalidateLinkedPrompt = jest.fn();+ const service = makeService({+ makePromptProduction: jest.fn().mockResolvedValue({+ ok: true,+ value: { message: 'Prompt production made successfully' },+ }),+ });+ const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));+ const res = mockRes();++ await handlers.makePromptProduction(withLoadedRevision(), res);++ expect(invalidateLinkedPrompt).not.toHaveBeenCalled();+ expect(res.statusCode).toBe(200);+ });+ });++ describe('deletePrompt', () => {+ it('clears the production key and an exact key for the deleted revision', async () => {+ const invalidateLinkedPrompt = jest.fn().mockResolvedValue(undefined);+ const service = makeService({+ deletePrompt: jest+ .fn()+ .mockResolvedValue({ ok: true, value: { prompt: 'Prompt deleted successfully' } }),+ });+ const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));+ const res = mockRes();++ await handlers.deletePrompt(mockReq({ params: { promptId }, query: { groupId } }), res);++ expect(invalidateLinkedPrompt).toHaveBeenCalledTimes(1);+ expect(invalidateLinkedPrompt).toHaveBeenCalledWith(groupId, [promptId]);+ });++ it('does not clear the cache when the delete is rejected', async () => {+ const invalidateLinkedPrompt = jest.fn();+ const service = makeService({+ deletePrompt: jest+ .fn()+ .mockResolvedValue({ ok: false, error: { type: 'invalid_input', message: 'bad' } }),+ });+ const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));+ const res = mockRes();++ await handlers.deletePrompt(mockReq({ params: { promptId }, query: { groupId } }), res);++ expect(invalidateLinkedPrompt).not.toHaveBeenCalled();+ });+ });++ describe('deletePromptGroup', () => {+ it('reads every revision before deleting and clears an exact key for each', async () => {+ const invalidateLinkedPrompt = jest.fn().mockResolvedValue(undefined);+ const callOrder: string[] = [];+ const service = makeService({+ getPrompts: jest.fn().mockImplementation(async () => {+ callOrder.push('getPrompts');+ return [{ _id: 'prompt-1' }, { _id: 'prompt-2' }];+ }),+ deletePromptGroup: jest.fn().mockImplementation(async () => {+ callOrder.push('deletePromptGroup');+ return { message: 'Prompt group deleted successfully' };+ }),+ });+ const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));+ const res = mockRes();++ await handlers.deletePromptGroup(mockReq({ params: { groupId } }), res);++ expect(service.getPrompts).toHaveBeenCalledWith({ groupId });+ expect(invalidateLinkedPrompt).toHaveBeenCalledTimes(1);+ expect(invalidateLinkedPrompt).toHaveBeenCalledWith(groupId, ['prompt-1', 'prompt-2']);+ // The revisions are read before the group (and its prompts) are deleted.+ expect(callOrder).toEqual(['getPrompts', 'deletePromptGroup']);+ });++ it('does not read revisions when no cache dependency is wired', async () => {+ const service = makeService({+ deletePromptGroup: jest+ .fn()+ .mockResolvedValue({ message: 'Prompt group deleted successfully' }),+ });+ const handlers = createPromptHandlers(makeDeps({ service }));+ const res = mockRes();++ await handlers.deletePromptGroup(mockReq({ params: { groupId } }), res);++ expect(service.getPrompts).not.toHaveBeenCalled();+ });++ it('still deletes the group and clears the cache with no ids when reading revisions rejects', async () => {+ const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => logger);+ const invalidateLinkedPrompt = jest.fn().mockResolvedValue(undefined);+ const service = makeService({+ getPrompts: jest.fn().mockRejectedValue(new Error('read failed')),+ deletePromptGroup: jest+ .fn()+ .mockResolvedValue({ message: 'Prompt group deleted successfully' }),+ });+ const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));+ const res = mockRes();++ await handlers.deletePromptGroup(mockReq({ params: { groupId } }), res);++ expect(service.deletePromptGroup).toHaveBeenCalledWith(groupId);+ expect(res.statusCode).toBe(200);+ expect(invalidateLinkedPrompt).toHaveBeenCalledWith(groupId, []);+ expect(errorSpy).toHaveBeenCalledWith(+ '[prompts] Failed to read revisions before deleting the group',+ {+ groupId,+ type: 'Error',+ },+ );+ });+ });++ describe('writes that do not change what a linked agent reads', () => {+ it('does not clear the cache after creating a prompt group', async () => {+ const invalidateLinkedPrompt = jest.fn();+ const service = makeService({+ createPromptGroup: jest.fn().mockResolvedValue({+ ok: true,+ value: { prompt: null, group: { _id: groupId, name: 'g' } },+ }),+ });+ const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));+ const res = mockRes();++ await handlers.createPromptGroup(+ mockReq({ body: { prompt: { prompt: 'x', type: 'text' }, group: { name: 'g' } } }),+ res,+ );++ expect(res.statusCode).toBe(200);+ expect(invalidateLinkedPrompt).not.toHaveBeenCalled();+ });++ it('does not clear the cache after adding a revision', async () => {+ const invalidateLinkedPrompt = jest.fn();+ const service = makeService({+ savePrompt: jest.fn().mockResolvedValue({ ok: true, value: { prompt: {} } }),+ });+ const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));+ const res = mockRes();++ await handlers.savePrompt(+ mockReq({ params: { groupId }, body: { prompt: { prompt: 'x', type: 'text' } } }),+ res,+ );++ expect(res.statusCode).toBe(200);+ expect(invalidateLinkedPrompt).not.toHaveBeenCalled();+ });+ });++ describe('cache clear failures', () => {+ it('logs a cache clear failure and still returns the write’s success response', async () => {+ const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => logger);+ const invalidateLinkedPrompt = jest.fn().mockRejectedValue(new Error('cache down'));+ const service = makeService({+ makePromptProduction: jest.fn().mockResolvedValue({+ ok: true,+ value: { message: 'Prompt production made successfully' },+ groupId,+ }),+ });+ const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));+ const res = mockRes();++ await handlers.makePromptProduction(withLoadedRevision(), res);++ expect(res.statusCode).toBe(200);+ expect(res.body).toEqual({ message: 'Prompt production made successfully' });+ expect(errorSpy).toHaveBeenCalledWith(+ '[prompts] Failed to clear the linked-instructions cache',+ {+ groupId,+ type: 'Error',+ },+ );+ });+ });++ describe('cache clear bound', () => {+ beforeEach(() => {+ jest.useFakeTimers();+ });++ afterEach(() => {+ jest.useRealTimers();+ });++ it('promote returns 200 and logs once after the limit when the clear never settles', async () => {+ const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => logger);+ const invalidateLinkedPrompt = jest.fn().mockReturnValue(new Promise(() => {}));+ const service = makeService({+ makePromptProduction: jest.fn().mockResolvedValue({+ ok: true,+ value: { message: 'Prompt production made successfully' },+ groupId,+ }),+ });+ const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));+ const res = mockRes();++ const pending = handlers.makePromptProduction(withLoadedRevision(), res);+ await jest.advanceTimersByTimeAsync(1000);+ await pending;++ expect(res.statusCode).toBe(200);+ expect(errorSpy).toHaveBeenCalledTimes(1);+ expect(errorSpy).toHaveBeenCalledWith(+ '[prompts] Failed to clear the linked-instructions cache',+ {+ groupId,+ type: 'Error',+ },+ );+ });++ it('promote honors a configured timeout shorter than the default', async () => {+ const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => logger);+ const invalidateLinkedPrompt = jest.fn().mockReturnValue(new Promise(() => {}));+ const service = makeService({+ makePromptProduction: jest.fn().mockResolvedValue({+ ok: true,+ value: { message: 'Prompt production made successfully' },+ groupId,+ }),+ });+ const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));+ const res = mockRes();+ const req = withLoadedRevision({+ config: {+ endpoints: { agents: { linkedInstructions: { native: { cacheClearTimeoutMs: 50 } } } },+ },+ });++ const pending = handlers.makePromptProduction(req, res);+ await jest.advanceTimersByTimeAsync(50);+ await pending;++ expect(res.statusCode).toBe(200);+ expect(errorSpy).toHaveBeenCalledTimes(1);+ });++ it('deletePrompt returns 200 and logs once after the limit when the clear never settles', async () => {+ const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => logger);+ const invalidateLinkedPrompt = jest.fn().mockReturnValue(new Promise(() => {}));+ const service = makeService({+ deletePrompt: jest+ .fn()+ .mockResolvedValue({ ok: true, value: { prompt: 'Prompt deleted successfully' } }),+ });+ const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));+ const res = mockRes();++ const pending = handlers.deletePrompt(+ mockReq({ params: { promptId }, query: { groupId } }),+ res,+ );+ await jest.advanceTimersByTimeAsync(1000);+ await pending;++ expect(res.statusCode).toBe(200);+ expect(errorSpy).toHaveBeenCalledTimes(1);+ expect(errorSpy).toHaveBeenCalledWith(+ '[prompts] Failed to clear the linked-instructions cache',+ {+ groupId,+ type: 'Error',+ },+ );+ });++ it('deletePromptGroup returns 200 and logs once after the limit when the clear never settles', async () => {+ const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => logger);+ const invalidateLinkedPrompt = jest.fn().mockReturnValue(new Promise(() => {}));+ const service = makeService({+ getPrompts: jest.fn().mockResolvedValue([{ _id: 'prompt-1' }]),+ deletePromptGroup: jest+ .fn()+ .mockResolvedValue({ message: 'Prompt group deleted successfully' }),+ });+ const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));+ const res = mockRes();++ const pending = handlers.deletePromptGroup(mockReq({ params: { groupId } }), res);+ await jest.advanceTimersByTimeAsync(1000);+ await pending;++ expect(res.statusCode).toBe(200);+ expect(errorSpy).toHaveBeenCalledTimes(1);+ expect(errorSpy).toHaveBeenCalledWith(+ '[prompts] Failed to clear the linked-instructions cache',+ {+ groupId,+ type: 'Error',+ },+ );+ });+ });+});diff --git a/packages/api/src/prompts/handlers.ts b/packages/api/src/prompts/handlers.tsindex ce55198d48..8369d8fc75 100644--- a/packages/api/src/prompts/handlers.ts+++ b/packages/api/src/prompts/handlers.ts@@ -1,12 +1,18 @@-import { PermissionBits, ResourceType } from 'librechat-data-provider';import { logger, isValidObjectIdString } from '@librechat/data-schemas';+import {+ PermissionBits,+ ResourceType,+ DEFAULT_CACHE_CLEAR_TIMEOUT_MS,+} from 'librechat-data-provider';import type { Response } from 'express';import type { PromptGroupRecord, PromptServiceError, StoredId } from './types';import type { PromptViaGroupResource } from './access';import type { PromptService } from './service';import type { ServerRequest } from '~/types';import { contentFilterBlockResponse } from '~/middleware/contentFilter';+import { runBounded } from '~/agents/instructions/linked';import { formatPromptGroupsResponse } from './format';+import { getSafeErrorMetadata } from '~/utils';import { isPromptStoreError } from './errors';/** A request after the prompt access middleware stored the resolved record. */@@ -29,6 +35,13 @@ export interface PromptHandlersDeps {resourceType: ResourceType;resourceId: string;}): Promise<number>;+ /**+ * Clears the linked-instructions cache for a native prompt group after a write that+ * can change what a linked agent reads next: promote, delete a revision, delete a+ * group. Omitted where no cache is wired. A clear failure is logged and never fails+ * the write that triggered it.+ */+ invalidateLinkedPrompt?(groupId: string, promptIds: readonly string[]): Promise<void>;}export interface PromptHandlers {@@ -83,6 +96,37 @@ function sendRejection(res: Response, error: PromptServiceError): Response {return res.status(400).send({ error: 'Prompt operation is not available' });}+/**+ * Clears the linked-instructions cache so a promote or delete reaches linked agents+ * on the next request instead of after the cache's TTL. A no-op when no cache is+ * wired. The write this follows has already succeeded; the clear waits at most+ * `endpoints.agents.linkedInstructions.native.cacheClearTimeoutMs` (default+ * `DEFAULT_CACHE_CLEAR_TIMEOUT_MS`) and lets the delete finish in the background past+ * that limit. A timeout and a rejection both log and continue rather than surface,+ * since either one only loses cache warmth.+ */+async function clearLinkedPromptCache(+ deps: PromptHandlersDeps,+ req: PromptRequest,+ groupId: string,+ promptIds: readonly string[],+): Promise<void> {+ if (!deps.invalidateLinkedPrompt) {+ return;+ }+ const cacheClearTimeoutMs =+ req.config?.endpoints?.agents?.linkedInstructions?.native?.cacheClearTimeoutMs ??+ DEFAULT_CACHE_CLEAR_TIMEOUT_MS;+ try {+ await runBounded(deps.invalidateLinkedPrompt(groupId, promptIds), cacheClearTimeoutMs);+ } catch (error) {+ logger.error('[prompts] Failed to clear the linked-instructions cache', {+ groupId,+ ...getSafeErrorMetadata(error),+ });+ }+}+async function loadAccessContext(deps: PromptHandlersDeps, req: PromptRequest) {const context = await deps.getPromptGroupAccessContext({userId: req.user?.id ?? '',@@ -278,6 +322,9 @@ export function createPromptHandlers(deps: PromptHandlersDeps): PromptHandlers {if (!result.ok) {return sendRejection(res, result.error);}+ if (result.groupId) {+ await clearLinkedPromptCache(deps, req, result.groupId, []);+ }return res.status(200).send(result.value);} catch (error) {logger.error(error);@@ -349,10 +396,12 @@ export function createPromptHandlers(deps: PromptHandlersDeps): PromptHandlers {if (!groupId || !isValidObjectIdString(groupId)) {return res.status(400).send({ error: 'Invalid or missing groupId' });}- const result = await service.deletePrompt({ groupId, promptId: param(req, 'promptId') });+ const promptId = param(req, 'promptId');+ const result = await service.deletePrompt({ groupId, promptId });if (!result.ok) {return sendRejection(res, result.error);}+ await clearLinkedPromptCache(deps, req, groupId, [promptId]);return res.status(200).send(result.value);} catch (error) {logger.error(error);@@ -362,7 +411,25 @@ export function createPromptHandlers(deps: PromptHandlersDeps): PromptHandlers {async deletePromptGroup(req, res) {try {- return res.send(await service.deletePromptGroup(param(req, 'groupId')));+ const groupId = param(req, 'groupId');+ /* Revisions are gone once the group is deleted, so their IDs are read first —+ * only when a cache is wired, since otherwise nothing is cleared. A read failure+ * leaves exact-revision cache entries to expire by TTL; it is logged and the+ * delete proceeds. */+ let promptIds: readonly string[] = [];+ if (deps.invalidateLinkedPrompt) {+ try {+ promptIds = (await service.getPrompts({ groupId })).map((revision) => revision._id);+ } catch (error) {+ logger.error('[prompts] Failed to read revisions before deleting the group', {+ groupId,+ ...getSafeErrorMetadata(error),+ });+ }+ }+ const value = await service.deletePromptGroup(groupId);+ await clearLinkedPromptCache(deps, req, groupId, promptIds);+ return res.send(value);} catch (error) {logger.error('Error deleting prompt group', error);return res.status(500).send({ message: 'Error deleting prompt group' });diff --git a/packages/api/src/prompts/service.spec.ts b/packages/api/src/prompts/service.spec.tsindex 47157d13e0..ff261120e2 100644--- a/packages/api/src/prompts/service.spec.ts+++ b/packages/api/src/prompts/service.spec.ts@@ -475,10 +475,26 @@ describe('createPromptService', () => {await expect(service.makePromptProduction({ promptId: draft._id, loadedRevision: draft }),- ).resolves.toEqual({ ok: true, value: { message: 'Prompt production made successfully' } });+ ).resolves.toEqual({+ ok: true,+ value: { message: 'Prompt production made successfully' },+ groupId: draft.groupId,+ });expect(read).not.toHaveBeenCalled();});+ it('reads the revision and surfaces its group id when no revision was loaded', async () => {+ const draft = await addRevision('Draft');+ const read = jest.spyOn(db, 'getPrompt');++ await expect(service.makePromptProduction({ promptId: draft._id })).resolves.toEqual({+ ok: true,+ value: { message: 'Prompt production made successfully' },+ groupId: draft.groupId,+ });+ expect(read).toHaveBeenCalledTimes(1);+ });+it('does not promote blocked content', async () => {const blocked = await addRevision('Contains PRIVATE-VALUE');const promote = jest.spyOn(db, 'makePromptProduction');@@ -506,6 +522,20 @@ describe('createPromptService', () => {cause: { message: 'Prompt not found' },});});++ it('promotes through the source and omits the group id when no revision is found', async () => {+ const promptId = missingId();+ jest.spyOn(db, 'getPrompt').mockResolvedValueOnce(null);+ const promote = jest+ .spyOn(db, 'makePromptProduction')+ .mockResolvedValueOnce({ message: 'Prompt production made successfully' });++ await expect(service.makePromptProduction({ promptId })).resolves.toEqual({+ ok: true,+ value: { message: 'Prompt production made successfully' },+ });+ expect(promote).toHaveBeenCalledWith(promptId);+ });});describe('usage and deletion', () => {diff --git a/packages/api/src/prompts/service.ts b/packages/api/src/prompts/service.tsindex 6bacd64c7c..89f1d66aa3 100644--- a/packages/api/src/prompts/service.ts+++ b/packages/api/src/prompts/service.ts@@ -1,10 +1,6 @@import { logger } from '@librechat/data-schemas';import { AccessRoleIds, PrincipalType, ResourceType } from 'librechat-data-provider';-import type {- FiltersConfig,- TDeletePromptResponse,- TMakePromptProductionResponse,-} from 'librechat-data-provider';+import type { FiltersConfig, TDeletePromptResponse } from 'librechat-data-provider';import type {PromptRecord,PromptDatabase,@@ -13,10 +9,12 @@ import type {PromptOperation,PromptGroupRecord,ResolvePromptInput,+ PromptServiceError,PromptServiceResult,PromptCreationResult,CreatePromptGroupInput,PromptServiceAdapters,+ MakePromptProductionResult,} from './types';import type { ProjectedStoredPrompt, ProjectedStoredPromptGroup } from './protection';import {@@ -95,7 +93,7 @@ export interface PromptService {readonly promptId: string;readonly loadedRevision?: PromptRecord | null;}>,- ): Promise<PromptServiceResult<TMakePromptProductionResponse>>;+ ): Promise<MakePromptProductionResult>;deletePrompt(input: {readonly groupId: string;readonly promptId: string;@@ -107,14 +105,17 @@ function invalidInput<T>(message: string, details?: unknown): PromptServiceResulreturn { ok: false, error: { type: 'invalid_input', message, details } };}-function unsupported<T>(operation: PromptOperation): PromptServiceResult<T> {+function unsupported(operation: PromptOperation): {+ readonly ok: false;+ readonly error: PromptServiceError;+} {return { ok: false, error: { type: 'unsupported', operation } };}-function inspect<T>(+function inspect(input: Parameters<typeof inspectPromptContent>[0],filters: FiltersConfig | undefined,-): PromptServiceResult<T> | null {+): { readonly ok: false; readonly error: PromptServiceError } | null {const finding = inspectPromptContent(input, filters);return finding == null ? null : { ok: false, error: { type: 'blocked_content', finding } };}@@ -182,10 +183,7 @@ export function createPromptServiceFromAdapters(adapters: PromptServiceAdapters)if (!validation.success) {return invalidInput(validation.error.issues[0]?.message ?? 'Invalid prompt');}- const rejection = inspect<PromptCreationResult>(- { prompt: validation.data, group: input.group },- filters,- );+ const rejection = inspect({ prompt: validation.data, group: input.group }, filters);if (rejection != null) {return rejection;}@@ -215,7 +213,7 @@ export function createPromptServiceFromAdapters(adapters: PromptServiceAdapters)if (!validation.success) {return invalidInput(validation.error.issues[0]?.message ?? 'Invalid prompt');}- const rejection = inspect<{ prompt: PromptRecord }>({ prompt: validation.data }, filters);+ const rejection = inspect({ prompt: validation.data }, filters);if (rejection != null) {return rejection;}@@ -235,7 +233,7 @@ export function createPromptServiceFromAdapters(adapters: PromptServiceAdapters)return null;}return (- inspect<ProjectedGroup | null>({ group }, filters) ?? {+ inspect({ group }, filters) ?? {ok: true,value: projectStoredPromptGroup(group, filters),}@@ -247,7 +245,7 @@ export function createPromptServiceFromAdapters(adapters: PromptServiceAdapters)if (revision == null) {return null;}- return inspect<PromptRecord>({ prompt: revision }, filters) ?? { ok: true, value: revision };+ return inspect({ prompt: revision }, filters) ?? { ok: true, value: revision };},incrementPromptGroupUsage: (groupId) => catalog.incrementPromptGroupUsage(groupId),@@ -257,7 +255,7 @@ export function createPromptServiceFromAdapters(adapters: PromptServiceAdapters)if (!validation.success) {return invalidInput('Invalid request body', validation.error.errors);}- const rejection = inspect<PromptGroupRecord>({ group: validation.data }, filters);+ const rejection = inspect({ group: validation.data }, filters);if (rejection != null) {return rejection;}@@ -272,16 +270,13 @@ export function createPromptServiceFromAdapters(adapters: PromptServiceAdapters)return unsupported('makePromptProduction');}const revision = await readPrompt(promptId, loadedRevision);- const rejection = inspect<TMakePromptProductionResponse>(- { prompt: revision ?? undefined },- filters,- );+ const rejection = inspect({ prompt: revision ?? undefined }, filters);if (rejection != null) {return rejection;}const promote = source.makePromptProduction;const value = await withPromptStage('write', () => promote(promptId));- return { ok: true, value };+ return { ok: true, value, groupId: revision?.groupId };},async deletePrompt(input) {diff --git a/packages/api/src/prompts/types.ts b/packages/api/src/prompts/types.tsindex 999909a39a..fb4cc58fac 100644--- a/packages/api/src/prompts/types.ts+++ b/packages/api/src/prompts/types.ts@@ -112,6 +112,15 @@ export type PromptServiceResult<T> =| { readonly ok: true; readonly value: T }| { readonly ok: false; readonly error: PromptServiceError };+/**+ * `makePromptProduction` carries `groupId` outside `value` so a caller can clear the+ * linked-instructions cache without changing `TMakePromptProductionResponse`, the HTTP body.+ * `groupId` is absent when the promoted revision does not exist.+ */+export type MakePromptProductionResult =+ | { readonly ok: true; readonly value: TMakePromptProductionResponse; readonly groupId?: string }+ | { readonly ok: false; readonly error: PromptServiceError };+export interface ResolvePromptInput {readonly groupId: string;readonly selection: PromptSelection;diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.tsindex 95c4aa3260..40e3b7564d 100644--- a/packages/data-provider/src/config.spec.ts+++ b/packages/data-provider/src/config.spec.ts@@ -215,6 +215,37 @@ describe('steer escalation confirmation timeout', () => {});});+describe('linked instructions configuration', () => {+ it('defaults optional reads and the native cache TTL, and bounds operator overrides', () => {+ expect(agentsEndpointSchema.parse({}).linkedInstructions).toBeUndefined();+ expect(agentsEndpointSchema.parse({ linkedInstructions: {} }).linkedInstructions).toEqual({+ timeoutMs: 2000,+ native: { cacheTtlMs: 300_000, cacheClearTimeoutMs: 1000 },+ });+ expect(+ agentsEndpointSchema.parse({+ linkedInstructions: { timeoutMs: 5000, native: { cacheTtlMs: 0 } },+ }).linkedInstructions,+ ).toEqual({ timeoutMs: 5000, native: { cacheTtlMs: 0, cacheClearTimeoutMs: 1000 } });+ for (const timeoutMs of [0, 99, 30_001, 1.5]) {+ expect(agentsEndpointSchema.safeParse({ linkedInstructions: { timeoutMs } }).success).toBe(+ false,+ );+ }+ for (const cacheTtlMs of [-1, 3_600_001, 1.5]) {+ expect(+ agentsEndpointSchema.safeParse({ linkedInstructions: { native: { cacheTtlMs } } }).success,+ ).toBe(false);+ }+ for (const cacheClearTimeoutMs of [0, 30_001, 1.5]) {+ expect(+ agentsEndpointSchema.safeParse({ linkedInstructions: { native: { cacheClearTimeoutMs } } })+ .success,+ ).toBe(false);+ }+ });+});+describe('ask user retained answers', () => {it('leaves the block unconfigured by default and accepts an operator budget', () => {expect(agentsEndpointSchema.parse({}).askUserQuestion).toBeUndefined();diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex b14aab8f8a..2388bcafb2 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -1455,6 +1455,7 @@ export const DEFAULT_AVATAR_REFRESH_COVERAGE_LIMIT = 1000;export const DEFAULT_MAX_PROVIDER_ERROR_CHARS = 2000;export const DEFAULT_AGENT_MODEL_RESPONSE_BODY_TIMEOUT_MS = 900_000;export const DEFAULT_AGENT_MODEL_RESPONSE_HEADERS_TIMEOUT_MS = 300_000;+export const DEFAULT_CACHE_CLEAR_TIMEOUT_MS = 1000;export const HOST_FILE_EDIT_HARD_MAX_COUNT = 100;@@ -1529,6 +1530,29 @@ export const agentsEndpointSchema = baseEndpointSchematimeoutMs: z.number().int().min(100).max(30_000).optional().default(2000),}).optional(),+ /** Budget and cache configuration for resolving an agent's linked prompt-group+ * instructions. Omitting the block applies the defaults below. */+ linkedInstructions: z+ .object({+ timeoutMs: z.number().int().min(100).max(30_000).optional().default(2000),+ native: z+ .object({+ /** Content cache TTL for a resolved native prompt link; `0` disables the cache. */+ cacheTtlMs: z.number().int().min(0).max(3_600_000).optional().default(300_000),+ /** Max wait for the cache clear a prompt write triggers before the write's+ * response continues without it. */+ cacheClearTimeoutMs: z+ .number()+ .int()+ .min(1)+ .max(30_000)+ .optional()+ .default(DEFAULT_CACHE_CLEAR_TIMEOUT_MS),+ })+ .optional()+ .default({}),+ })+ .optional(),maxRecursionLimit: z.number().optional(),/** Max cumulative bytes a single streamed tool call's arguments may reach before the run* aborts. Defaults to 64 KiB in the agents SDK; `0` disables the guard. */@@ -4395,6 +4419,10 @@ export enum CacheKeys {* Key for cached prompt group access ID sets (accessible, public, owned).*/PROMPT_GROUPS_ACCESS = 'PROMPT_GROUPS_ACCESS',+ /**+ * Key for cached resolved content of an agent's linked native prompt-group instructions.+ */+ AGENT_LINKED_INSTRUCTIONS = 'AGENT_LINKED_INSTRUCTIONS',/*** Key for per-conversation stateful code sandbox prewarm/warm state.*/diff --git a/packages/data-provider/src/types/agents.ts b/packages/data-provider/src/types/agents.tsindex 2b7738fa82..6b6ecf69c6 100644--- a/packages/data-provider/src/types/agents.ts+++ b/packages/data-provider/src/types/agents.ts@@ -1035,6 +1035,43 @@ export const agentGitIdentitySchema: z.ZodType<AgentGitIdentity | undefined> = z}).optional();+/** Selects which revision of a linked prompt group an agent's instructions follow. */+export type AgentInstructionsPromptSelection =+ | { type: 'production' }+ | { type: 'exact'; promptId: string };++/** A link from an agent to a native LibreChat prompt group used as its instructions. */+export type AgentInstructionsPrompt = {+ source: 'native';+ groupId: string;+ selection: AgentInstructionsPromptSelection;+};++/** Returned to an editor who lacks VIEW on the linked group. Hides the group identity.+ * `matchesCurrent` is set only on a version snapshot's stub (never on the current+ * agent's own stub): whether that version's raw link equals the agent's current raw+ * link (same `groupId` and selection), without revealing which group either is. */+export type RestrictedAgentInstructionsPrompt = {+ source: 'native';+ restricted: true;+ matchesCurrent?: boolean;+};++/** Stable, machine-readable error codes for agent-instructions-prompt link failures. */+export const InstructionsPromptErrorCode = {+ /** The selection does not resolve (missing group, missing Production, revision not in+ * group) or its content is blocked. */+ UNAVAILABLE: 'instructions_prompt_unavailable',+ /** The editor sets or changes a link to a group without PROMPTGROUP `VIEW`. */+ FORBIDDEN: 'instructions_prompt_forbidden',+ /** The role, ACL, or prompt-store lookup backing the write check failed unexpectedly+ * (not a content-policy rejection). No detail about the failure is disclosed. */+ VALIDATION_FAILED: 'instructions_prompt_validation_failed',+} as const;++export type InstructionsPromptErrorCode =+ (typeof InstructionsPromptErrorCode)[keyof typeof InstructionsPromptErrorCode];+export type Agent = {_id?: string;id: string;@@ -1048,6 +1085,8 @@ export type Agent = {avatar: AgentAvatar | null;instructions?: string | null;additional_instructions?: string | null;+ /** Links these instructions to a native prompt group revision instead of inline text. */+ instructionsPrompt?: AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null;tools?: string[];tool_kwargs?: Record<string, unknown>;metadata?: Record<string, unknown>;@@ -1123,6 +1162,8 @@ export type AgentCreateParams = {avatar?: AgentAvatar | null;file_ids?: string[];instructions?: string | null;+ /** Links these instructions to a native prompt group revision; `null` keeps inline text. */+ instructionsPrompt?: AgentInstructionsPrompt | null;tools?: Array<FunctionTool | string>;provider: AgentProvider;model: string | null;@@ -1159,6 +1200,8 @@ export type AgentUpdateParams = {avatar?: AgentAvatar | null;file_ids?: string[];instructions?: string | null;+ /** Links these instructions to a native prompt group revision; `null` removes the link. */+ instructionsPrompt?: AgentInstructionsPrompt | null;tools?: Array<FunctionTool | string>;tool_resources?: ToolResources;provider?: AgentProvider;diff --git a/packages/data-schemas/src/methods/agent.spec.ts b/packages/data-schemas/src/methods/agent.spec.tsindex aa27fd19e4..720562b32e 100644--- a/packages/data-schemas/src/methods/agent.spec.ts+++ b/packages/data-schemas/src/methods/agent.spec.ts@@ -552,6 +552,29 @@ describe('Agent Methods', () => {expect(retrievedAgent!.description).toBe('Test description');});+ test('should persist a linked native prompt-group instructions selection on create', async () => {+ const { agentId, authorId } = createTestIds();+ const instructionsPrompt = {+ source: 'native',+ groupId: new mongoose.Types.ObjectId().toString(),+ selection: { type: 'production' },+ };++ const newAgent = await createAgent({+ id: agentId,+ name: 'Linked Instructions Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ instructionsPrompt,+ });++ expect(newAgent.instructionsPrompt).toEqual(instructionsPrompt);++ const retrievedAgent = await getAgent({ id: agentId });+ expect(retrievedAgent!.instructionsPrompt).toEqual(instructionsPrompt);+ });+test('should derive mcpServerNames only from MCP tools on create', async () => {const { agentId, authorId } = createTestIds();const actionTool = `sync${Constants.mcp_delimiter}state${actionDelimiter}api---example---com`;@@ -2990,6 +3013,57 @@ describe('Agent Methods', () => {expect(revertedAgent.code_environment_id).toBeUndefined();});+ test('should unset a linked prompt-group instructions selection absent from the restored version', async () => {+ const agentId = `agent_${uuidv4()}`;+ const authorId = new mongoose.Types.ObjectId();++ await createAgent({+ id: agentId,+ name: 'Unlinked Instructions Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ });+ await updateAgent(+ { id: agentId },+ {+ instructionsPrompt: {+ source: 'native',+ groupId: new mongoose.Types.ObjectId().toString(),+ selection: { type: 'production' },+ },+ },+ );++ const revertedAgent = await revertAgentVersion({ id: agentId }, 0);++ expect(revertedAgent.instructionsPrompt).toBeUndefined();+ });++ test('should restore a linked prompt-group instructions selection present in the reverted version', async () => {+ const agentId = `agent_${uuidv4()}`;+ const authorId = new mongoose.Types.ObjectId();+ const instructionsPrompt = {+ source: 'native',+ groupId: new mongoose.Types.ObjectId().toString(),+ selection: { type: 'production' },+ };++ await createAgent({+ id: agentId,+ name: 'Linked Instructions Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ instructionsPrompt,+ });+ await updateAgent({ id: agentId }, { instructionsPrompt: null });++ const revertedAgent = await revertAgentVersion({ id: agentId }, 0);++ expect(revertedAgent.instructionsPrompt).toEqual(instructionsPrompt);+ });+test('should clear a Git identity absent from the restored version', async () => {const agentId = `agent_${uuidv4()}`;const authorId = new mongoose.Types.ObjectId();@@ -3500,6 +3574,39 @@ describe('Agent Methods', () => {expect(updatedAgent!.versions).toHaveLength(2);});+ test('should create a new version when the linked prompt-group selection changes', async () => {+ const agentId = `agent_${uuidv4()}`;+ const authorId = new mongoose.Types.ObjectId();+ const groupId = new mongoose.Types.ObjectId().toString();++ await createAgent({+ id: agentId,+ name: 'Test Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ });++ const updatedAgent = await updateAgent(+ { id: agentId },+ {+ instructionsPrompt: {+ source: 'native',+ groupId,+ selection: { type: 'exact', promptId: new mongoose.Types.ObjectId().toString() },+ },+ },+ );++ expect(updatedAgent!.versions).toHaveLength(2);+ expect(updatedAgent!.instructionsPrompt).toMatchObject({+ source: 'native',+ groupId,+ selection: { type: 'exact' },+ });+ });+test('should handle isDuplicateVersion with mixed primitive and object arrays', async () => {const agentId = `agent_${uuidv4()}`;const authorId = new mongoose.Types.ObjectId();diff --git a/packages/data-schemas/src/methods/agent.ts b/packages/data-schemas/src/methods/agent.tsindex b59a3f69d0..714f7c5339 100644--- a/packages/data-schemas/src/methods/agent.ts+++ b/packages/data-schemas/src/methods/agent.ts@@ -2662,6 +2662,7 @@ export function createAgentMethods('code_environment_ids','repositoryInstructions','git_identity',+ 'instructionsPrompt','skills_scope','skill_authoring_enabled',]) {diff --git a/packages/data-schemas/src/schema/agent.ts b/packages/data-schemas/src/schema/agent.tsindex 6d8ffc9230..762d5f3471 100644--- a/packages/data-schemas/src/schema/agent.ts+++ b/packages/data-schemas/src/schema/agent.ts@@ -97,6 +97,26 @@ const agentSchema: Schema<IAgent> = new Schema<IAgent>(code_workspace_id: { type: String },code_environment_ids: { type: [String], default: undefined },repositoryInstructions: { type: String, enum: ['prefer', 'defer', 'off'] },+ instructionsPrompt: {+ type: new Schema(+ {+ source: { type: String, enum: ['native'], required: true },+ groupId: { type: String, required: true },+ selection: {+ type: new Schema(+ {+ type: { type: String, enum: ['production', 'exact'], required: true },+ promptId: { type: String },+ },+ { _id: false },+ ),+ required: true,+ },+ },+ { _id: false },+ ),+ default: undefined,+ },git_identity: {type: new Schema({diff --git a/packages/data-schemas/src/types/agent.ts b/packages/data-schemas/src/types/agent.tsindex bf224f202c..e849fb8c2e 100644--- a/packages/data-schemas/src/types/agent.ts+++ b/packages/data-schemas/src/types/agent.ts@@ -7,6 +7,7 @@ import type {AgentToolResources,AgentSubagentsConfig,AgentGitIdentity,+ AgentInstructionsPrompt,} from 'librechat-data-provider';export interface ISupportContact {@@ -47,6 +48,8 @@ export interface IAgent extends Omit<Document, 'model'> {code_workspace_id?: string;repositoryInstructions?: 'prefer' | 'defer' | 'off';git_identity?: AgentGitIdentity | null;+ /** Links these instructions to a native prompt group revision instead of inline text. */+ instructionsPrompt?: AgentInstructionsPrompt | null;/** @deprecated Use edges instead */agent_ids?: string[];edges?: GraphEdge[];