mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-19 14:33:38 +00:00
🏡 feat: Remember Agent Workspace Defaults (#15843)
* 🧭 feat: Remember Attached Workspace Choices
* Guard Workspace Defaults Across Navigation and Version Restore
* Order Workspace Preference Imports
* fix: Harden agent workspace defaults
* fix: Type workspace validation schema
* test: Cover safe execution projections
* fix: Bind workspace defaults to attached environments
* fix: Preserve unchanged workspace bindings
* fix: Scope workspace preferences to active agents
* fix: Preserve workspace selection state
* test: Target workspace discovery status
* fix: Keep workspace reset available
* fix: Resolve workspace defaults per environment
* fix: Collect per-environment workspace defaults
* fix: Reconcile Deleted Agent Graph Caches
* fix: Reject Stale Workspace Bindings
This commit is contained in:
parent
1ef4aa9f14
commit
1d45f5bd40
37 changed files with 1326 additions and 31 deletions
|
|
@ -38,6 +38,9 @@ const {
|
|||
isContentTraversalLimitError,
|
||||
resolveCanonicalFileReferences,
|
||||
reportLocatorTraversalFailure,
|
||||
reconcileAgentWorkspaceDefault,
|
||||
shouldValidateAgentWorkspaceDefaultBinding,
|
||||
validateAgentWorkspaceDefaultBinding,
|
||||
} = require('@librechat/api');
|
||||
const {
|
||||
Time,
|
||||
|
|
@ -480,13 +483,27 @@ const validateStatefulCodeEnvironment = (
|
|||
environment,
|
||||
environmentId,
|
||||
environmentIdSelected = false,
|
||||
workspaceId,
|
||||
currentWorkspaceId,
|
||||
currentEnvironmentId,
|
||||
) => {
|
||||
const configuredEnvironments =
|
||||
req.config?.endpoints?.[EModelEndpoint.agents]?.statefulCodeSessions?.environments ?? [];
|
||||
const workspaceValidation = validateAgentWorkspaceDefaultBinding({
|
||||
workspaceId,
|
||||
environmentId,
|
||||
currentWorkspaceId,
|
||||
currentEnvironmentId,
|
||||
environments: configuredEnvironments,
|
||||
});
|
||||
if (!workspaceValidation.valid) {
|
||||
res.status(400).json({ error: workspaceValidation.error });
|
||||
return false;
|
||||
}
|
||||
if (enabled !== true && !environmentIdSelected) {
|
||||
return true;
|
||||
}
|
||||
if (environmentId != null) {
|
||||
const configuredEnvironments =
|
||||
req.config?.endpoints?.[EModelEndpoint.agents]?.statefulCodeSessions?.environments ?? [];
|
||||
const configuredEnvironment = configuredEnvironments.find(
|
||||
(configured) => configured.id === environmentId,
|
||||
);
|
||||
|
|
@ -780,6 +797,7 @@ const createAgentHandler = async (req, res) => {
|
|||
agentData.stateful_code_environment,
|
||||
agentData.code_environment_id,
|
||||
agentData.code_environment_id != null,
|
||||
agentData.code_workspace_id,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
|
|
@ -1066,7 +1084,7 @@ const updateAgentHandler = async (req, res) => {
|
|||
_id,
|
||||
...rest
|
||||
} = validatedData;
|
||||
const updateData = removeNullishValues(rest);
|
||||
let updateData = removeNullishValues(rest);
|
||||
if (codeEnvironmentIdField !== undefined) {
|
||||
updateData.code_environment_id = codeEnvironmentIdField;
|
||||
}
|
||||
|
|
@ -1079,10 +1097,12 @@ const updateAgentHandler = async (req, res) => {
|
|||
updateData.stateful_code_sessions !== undefined ||
|
||||
updateData.stateful_code_environment !== undefined ||
|
||||
updateData.code_environment_id !== undefined;
|
||||
const includesWorkspaceConfiguration = updateData.code_workspace_id !== undefined;
|
||||
const includesToolsConfiguration = Array.isArray(updateData.tools);
|
||||
const includesToolOptionsConfiguration = updateData.tool_options !== undefined;
|
||||
if (
|
||||
includesStatefulConfiguration ||
|
||||
includesWorkspaceConfiguration ||
|
||||
includesToolsConfiguration ||
|
||||
includesToolOptionsConfiguration
|
||||
) {
|
||||
|
|
@ -1094,6 +1114,11 @@ const updateAgentHandler = async (req, res) => {
|
|||
const codeEnvironmentSelectionChanged =
|
||||
updateData.code_environment_id !== undefined &&
|
||||
updateData.code_environment_id !== existingAgent.code_environment_id;
|
||||
updateData = reconcileAgentWorkspaceDefault({
|
||||
update: updateData,
|
||||
request: validatedData,
|
||||
currentEnvironmentId: existingAgent.code_environment_id,
|
||||
});
|
||||
const statefulConfigurationChanged =
|
||||
(updateData.stateful_code_sessions !== undefined &&
|
||||
(updateData.stateful_code_sessions === true) !==
|
||||
|
|
@ -1106,7 +1131,20 @@ const updateAgentHandler = async (req, res) => {
|
|||
includesToolsConfiguration &&
|
||||
updateData.tools.includes(Tools.execute_code) &&
|
||||
existingAgent.tools?.includes(Tools.execute_code) !== true;
|
||||
if (statefulConfigurationChanged || activatesCodeExecution) {
|
||||
const effectiveCodeWorkspaceId =
|
||||
updateData.code_workspace_id ?? existingAgent.code_workspace_id;
|
||||
const selectsWorkspaceDefault =
|
||||
includesWorkspaceConfiguration &&
|
||||
shouldValidateAgentWorkspaceDefaultBinding({
|
||||
workspaceId: effectiveCodeWorkspaceId,
|
||||
environmentId:
|
||||
updateData.code_environment_id === null
|
||||
? undefined
|
||||
: (updateData.code_environment_id ?? existingAgent.code_environment_id),
|
||||
currentWorkspaceId: existingAgent.code_workspace_id,
|
||||
currentEnvironmentId: existingAgent.code_environment_id,
|
||||
});
|
||||
if (statefulConfigurationChanged || selectsWorkspaceDefault || activatesCodeExecution) {
|
||||
const effectiveStatefulSessions =
|
||||
updateData.stateful_code_sessions ?? existingAgent.stateful_code_sessions;
|
||||
const effectiveStatefulEnvironment =
|
||||
|
|
@ -1123,6 +1161,9 @@ const updateAgentHandler = async (req, res) => {
|
|||
effectiveStatefulEnvironment,
|
||||
effectiveCodeEnvironmentId,
|
||||
codeEnvironmentSelectionChanged,
|
||||
effectiveCodeWorkspaceId,
|
||||
existingAgent.code_workspace_id,
|
||||
existingAgent.code_environment_id,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
|
|
@ -1428,6 +1469,8 @@ const duplicateAgentHandler = async (req, res) => {
|
|||
newAgentData.stateful_code_sessions,
|
||||
newAgentData.stateful_code_environment,
|
||||
newAgentData.code_environment_id,
|
||||
false,
|
||||
newAgentData.code_workspace_id,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
|
|
@ -1829,6 +1872,7 @@ const getListAgentsHandler = async (req, res) => {
|
|||
limit,
|
||||
after: cursor,
|
||||
includeSkillConfig: true,
|
||||
includeExecutionConfig: true,
|
||||
});
|
||||
|
||||
const agents = data?.data ?? [];
|
||||
|
|
@ -2034,6 +2078,8 @@ const revertAgentVersionHandler = async (req, res) => {
|
|||
revertVersion.stateful_code_sessions,
|
||||
revertVersion.stateful_code_environment,
|
||||
revertVersion.code_environment_id,
|
||||
false,
|
||||
revertVersion.code_workspace_id,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -316,6 +316,76 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
|
|||
expect(await Agent.countDocuments()).toBe(0);
|
||||
});
|
||||
|
||||
test('rejects a workspace default without an explicit attached environment', async () => {
|
||||
mockReq.config = {
|
||||
endpoints: {
|
||||
agents: {
|
||||
statefulCodeSessions: {
|
||||
allowedEnvironments: ['user'],
|
||||
environments: [
|
||||
{
|
||||
id: 'default-vm',
|
||||
name: 'Default VM',
|
||||
type: 'attached',
|
||||
baseURL: 'https://code.example.com/v1',
|
||||
default: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
mockReq.body = {
|
||||
name: 'Unbound Workspace Agent',
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
code_workspace_id: 'project-a',
|
||||
};
|
||||
|
||||
await createAgentHandler(mockReq, mockRes);
|
||||
|
||||
expect(mockRes.status).toHaveBeenCalledWith(400);
|
||||
expect(mockRes.json).toHaveBeenCalledWith({
|
||||
error: 'Code workspace defaults require an explicit attached code environment',
|
||||
});
|
||||
expect(await Agent.countDocuments()).toBe(0);
|
||||
});
|
||||
|
||||
test('rejects a workspace default for a managed environment', async () => {
|
||||
mockReq.config = {
|
||||
endpoints: {
|
||||
agents: {
|
||||
statefulCodeSessions: {
|
||||
allowedEnvironments: ['user'],
|
||||
environments: [
|
||||
{
|
||||
id: 'managed-runtime',
|
||||
name: 'Managed Runtime',
|
||||
type: 'managed',
|
||||
baseURL: 'https://code.example.com/v1',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
mockReq.body = {
|
||||
name: 'Managed Workspace Agent',
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
code_environment_id: 'managed-runtime',
|
||||
code_workspace_id: 'project-a',
|
||||
};
|
||||
|
||||
await createAgentHandler(mockReq, mockRes);
|
||||
|
||||
expect(mockRes.status).toHaveBeenCalledWith(400);
|
||||
expect(mockRes.json).toHaveBeenCalledWith({
|
||||
error: 'Code workspace defaults require an explicit attached code environment',
|
||||
});
|
||||
expect(await Agent.countDocuments()).toBe(0);
|
||||
});
|
||||
|
||||
test('should block configured agent instruction content before persistence', async () => {
|
||||
mockReq.config = {
|
||||
filters: {
|
||||
|
|
@ -1605,12 +1675,74 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
|
|||
expect(agentInDb.code_environment_id).toBeUndefined();
|
||||
});
|
||||
|
||||
test('allows a workspace-only update for an existing attached environment', async () => {
|
||||
await Agent.updateOne({ id: existingAgentId }, { code_environment_id: 'attached-vm' });
|
||||
mockReq.user.id = existingAgentAuthorId.toString();
|
||||
mockReq.params.id = existingAgentId;
|
||||
mockReq.config = {
|
||||
endpoints: {
|
||||
agents: {
|
||||
statefulCodeSessions: {
|
||||
allowedEnvironments: ['user'],
|
||||
environments: [
|
||||
{
|
||||
id: 'attached-vm',
|
||||
name: 'Attached VM',
|
||||
type: 'attached',
|
||||
baseURL: 'https://bridge.example.com/v1',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
mockReq.body = { code_workspace_id: 'project-a' };
|
||||
|
||||
await updateAgentHandler(mockReq, mockRes);
|
||||
|
||||
expect(mockRes.status).not.toHaveBeenCalledWith(400);
|
||||
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
||||
expect(agentInDb.code_environment_id).toBe('attached-vm');
|
||||
expect(agentInDb.code_workspace_id).toBe('project-a');
|
||||
});
|
||||
|
||||
test('rejects a workspace-only update without an attached environment', async () => {
|
||||
mockReq.user.id = existingAgentAuthorId.toString();
|
||||
mockReq.params.id = existingAgentId;
|
||||
mockReq.config = {
|
||||
endpoints: {
|
||||
agents: {
|
||||
statefulCodeSessions: {
|
||||
allowedEnvironments: ['user'],
|
||||
environments: [
|
||||
{
|
||||
id: 'default-vm',
|
||||
name: 'Default VM',
|
||||
type: 'attached',
|
||||
baseURL: 'https://bridge.example.com/v1',
|
||||
default: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
mockReq.body = { code_workspace_id: 'project-a' };
|
||||
|
||||
await updateAgentHandler(mockReq, mockRes);
|
||||
|
||||
expect(mockRes.status).toHaveBeenCalledWith(400);
|
||||
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
||||
expect(agentInDb.code_workspace_id).toBeUndefined();
|
||||
});
|
||||
|
||||
test('allows disabling stateful sessions after the configured environment is removed', async () => {
|
||||
await Agent.updateOne(
|
||||
{ id: existingAgentId },
|
||||
{
|
||||
stateful_code_sessions: true,
|
||||
code_environment_id: 'removed-vm',
|
||||
code_workspace_id: 'project-a',
|
||||
},
|
||||
);
|
||||
mockReq.user.id = existingAgentAuthorId.toString();
|
||||
|
|
@ -1628,6 +1760,7 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
|
|||
mockReq.body = {
|
||||
stateful_code_sessions: false,
|
||||
code_environment_id: 'removed-vm',
|
||||
code_workspace_id: 'project-a',
|
||||
};
|
||||
|
||||
await updateAgentHandler(mockReq, mockRes);
|
||||
|
|
@ -1636,6 +1769,7 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
|
|||
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
||||
expect(agentInDb.stateful_code_sessions).toBe(false);
|
||||
expect(agentInDb.code_environment_id).toBe('removed-vm');
|
||||
expect(agentInDb.code_workspace_id).toBe('project-a');
|
||||
});
|
||||
|
||||
test('restores the deployment-default code environment', async () => {
|
||||
|
|
@ -1644,6 +1778,7 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
|
|||
{
|
||||
stateful_code_sessions: true,
|
||||
code_environment_id: 'attached-vm',
|
||||
code_workspace_id: 'project-a',
|
||||
},
|
||||
);
|
||||
mockReq.user.id = existingAgentAuthorId.toString();
|
||||
|
|
@ -1673,6 +1808,7 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
|
|||
expect(mockRes.status).not.toHaveBeenCalledWith(400);
|
||||
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
||||
expect(agentInDb.code_environment_id).toBeUndefined();
|
||||
expect(agentInDb.code_workspace_id).toBe('');
|
||||
});
|
||||
|
||||
test('clears a configured Git identity', async () => {
|
||||
|
|
@ -3332,16 +3468,20 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
|
|||
expect(Object.keys(agent).sort()).toEqual(
|
||||
[
|
||||
'_id',
|
||||
'agent_ids',
|
||||
'author',
|
||||
'avatar',
|
||||
'category',
|
||||
'conversation_starters',
|
||||
'description',
|
||||
'edges',
|
||||
'id',
|
||||
'isEditable',
|
||||
'is_promoted',
|
||||
'name',
|
||||
'subagents',
|
||||
'support_contact',
|
||||
'tools',
|
||||
'updatedAt',
|
||||
].sort(),
|
||||
);
|
||||
|
|
@ -3353,6 +3493,9 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
|
|||
author: userA.toString(),
|
||||
category: 'general',
|
||||
is_promoted: true,
|
||||
tools: ['execute_code'],
|
||||
edges: [{ from: agentA1.id, to: agentA2.id }],
|
||||
subagents: { enabled: true, agent_ids: [agentA2.id] },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -52,6 +52,7 @@ export type AgentForm = {
|
|||
stateful_code_environment?: StatefulCodeEnvironment;
|
||||
/** Operator-configured managed or attached execution environment. */
|
||||
code_environment_id?: string | null;
|
||||
code_workspace_id?: string;
|
||||
/** Git authorship applied to sandboxed commands for this agent. */
|
||||
git_identity?: Agent['git_identity'];
|
||||
provider?: AgentProvider | OptionWithIcon;
|
||||
|
|
|
|||
|
|
@ -31,22 +31,30 @@ export default function CodeWorkspaceMenu({
|
|||
const menuStore = Ariakit.useMenuStore({ focusLoop: true, placement: 'top-start' });
|
||||
const isOpen = menuStore.useState('open');
|
||||
|
||||
/** A single advertised root per reachable environment is an unambiguous
|
||||
* initial choice. Once a conversation owns any binding, even a partial or
|
||||
* stale set, only explicit user actions may replace or complete it. */
|
||||
/** Pin resolved defaults to this chat; later preference changes cannot move it. */
|
||||
useEffect(() => {
|
||||
if (conversation?.codeWorkspaces != null || workspace.selections == null) return;
|
||||
setConversation((current) =>
|
||||
current == null || current.codeWorkspaces != null
|
||||
current == null ||
|
||||
current.codeWorkspaces != null ||
|
||||
current.conversationId !== conversation?.conversationId ||
|
||||
current.agent_id !== conversation?.agent_id
|
||||
? current
|
||||
: { ...current, codeWorkspaces: workspace.selections },
|
||||
);
|
||||
}, [conversation?.codeWorkspaces, setConversation, workspace.selections]);
|
||||
}, [
|
||||
conversation?.codeWorkspaces,
|
||||
conversation?.conversationId,
|
||||
conversation?.agent_id,
|
||||
setConversation,
|
||||
workspace.selections,
|
||||
]);
|
||||
|
||||
if (!workspace.required) return null;
|
||||
|
||||
const environmentIds = new Set(workspace.environments.map(({ environment }) => environment.id));
|
||||
const selectWorkspace = (selection: CodeWorkspaceSelection) => {
|
||||
workspace.rememberSelection(selection);
|
||||
setConversation((current) => {
|
||||
if (current == null) return current;
|
||||
const retained = (current.codeWorkspaces ?? []).filter(
|
||||
|
|
|
|||
|
|
@ -52,6 +52,7 @@ function workspace(overrides: Partial<CodeWorkspaceResult> = {}): CodeWorkspaceR
|
|||
selections: [selected],
|
||||
resolveSelections: () => [selected],
|
||||
resolveSubmission: () => ({ codeWorkspaces: [selected] }),
|
||||
rememberSelection: jest.fn(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
|
@ -73,6 +74,10 @@ describe('CodeWorkspaceMenu', () => {
|
|||
...conversation,
|
||||
codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'project-a' }],
|
||||
});
|
||||
const navigated = { ...conversation, agent_id: 'different-agent' };
|
||||
expect(update(navigated)).toBe(navigated);
|
||||
const differentChat = { ...conversation, conversationId: 'different-chat' };
|
||||
expect(update(differentChat)).toBe(differentChat);
|
||||
expect(screen.getByTestId('code-workspace')).toHaveTextContent('Project A');
|
||||
});
|
||||
|
||||
|
|
@ -82,6 +87,7 @@ describe('CodeWorkspaceMenu', () => {
|
|||
codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'removed-project' }],
|
||||
};
|
||||
const setConversation = jest.fn();
|
||||
const rememberSelection = jest.fn();
|
||||
render(
|
||||
<CodeWorkspaceMenu
|
||||
conversation={savedConversation}
|
||||
|
|
@ -97,6 +103,7 @@ describe('CodeWorkspaceMenu', () => {
|
|||
selected: undefined,
|
||||
},
|
||||
],
|
||||
rememberSelection,
|
||||
})}
|
||||
disabled={false}
|
||||
/>,
|
||||
|
|
@ -107,6 +114,10 @@ describe('CodeWorkspaceMenu', () => {
|
|||
await userEvent.click(screen.getByTestId('code-workspace'));
|
||||
await userEvent.click(await screen.findByText('Project A'));
|
||||
|
||||
expect(rememberSelection).toHaveBeenCalledWith({
|
||||
environmentId: 'personal-vm',
|
||||
workspaceId: 'project-a',
|
||||
});
|
||||
const update = setConversation.mock.calls[0][0];
|
||||
expect(update(savedConversation)).toEqual({
|
||||
...savedConversation,
|
||||
|
|
|
|||
|
|
@ -91,6 +91,7 @@ export function composeAgentUpdatePayload(
|
|||
stateful_code_sessions,
|
||||
stateful_code_environment,
|
||||
code_environment_id,
|
||||
code_workspace_id,
|
||||
git_identity,
|
||||
recursion_limit,
|
||||
category,
|
||||
|
|
@ -152,6 +153,7 @@ export function composeAgentUpdatePayload(
|
|||
stateful_code_sessions: normalizedStatefulCodeSessions,
|
||||
stateful_code_environment: normalizedStatefulCodeEnvironment,
|
||||
code_environment_id: agent_id ? code_environment_id : (code_environment_id ?? undefined),
|
||||
code_workspace_id,
|
||||
git_identity: normalizedGitIdentity,
|
||||
recursion_limit,
|
||||
category,
|
||||
|
|
|
|||
|
|
@ -101,6 +101,7 @@ function AgentSelect({
|
|||
avatar_action: null,
|
||||
stateful_code_environment: fullAgent.stateful_code_environment ?? 'user',
|
||||
code_environment_id: fullAgent.code_environment_id,
|
||||
code_workspace_id: fullAgent.code_workspace_id,
|
||||
git_identity: fullAgent.git_identity,
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ import {
|
|||
import type { StatefulCodeEnvironment } from 'librechat-data-provider';
|
||||
import type { AgentForm } from '~/common';
|
||||
import { useAuthContext, useGetAgentsConfig, useLocalize } from '~/hooks';
|
||||
import { useCodeEnvironmentStatusQueries } from '~/data-provider';
|
||||
import { ESide } from '~/common';
|
||||
|
||||
const ENVIRONMENT_LABELS = {
|
||||
|
|
@ -33,6 +34,11 @@ const ENVIRONMENT_LABELS = {
|
|||
} as const;
|
||||
|
||||
const DEPLOYMENT_DEFAULT_ENVIRONMENT = '__deployment_default__';
|
||||
const WORKSPACE_STATUS_LABELS = {
|
||||
loading: 'com_ui_code_workspace_loading',
|
||||
unavailable: 'com_ui_code_workspace_unavailable',
|
||||
unsupported: 'com_ui_code_workspace_unsupported',
|
||||
} as const;
|
||||
|
||||
export default function CodeSettings() {
|
||||
const localize = useLocalize();
|
||||
|
|
@ -52,6 +58,7 @@ export default function CodeSettings() {
|
|||
const codeEnabled = watch(AgentCapabilities.execute_code);
|
||||
const environment = watch('stateful_code_environment') ?? 'user';
|
||||
const codeEnvironmentId = watch('code_environment_id');
|
||||
const workspaceId = watch('code_workspace_id') ?? '';
|
||||
const configuredEnvironments = agentsConfig?.statefulCodeSessions?.allowedEnvironments;
|
||||
const executionEnvironments = agentsConfig?.statefulCodeSessions?.environments ?? [];
|
||||
const statefulSessionsAvailable =
|
||||
|
|
@ -65,6 +72,30 @@ export default function CodeSettings() {
|
|||
codeEnabled &&
|
||||
enabled &&
|
||||
effectiveExecutionEnvironment?.type === 'attached';
|
||||
const workspaceStatuses = useCodeEnvironmentStatusQueries(
|
||||
effectiveExecutionEnvironment?.type === 'attached' ? [effectiveExecutionEnvironment.id] : [],
|
||||
showGitIdentity === true,
|
||||
);
|
||||
const workspaceStatusQuery = workspaceStatuses[0];
|
||||
const workspaceStatus = workspaceStatusQuery?.data;
|
||||
let workspaceDiscoveryState: 'loading' | 'unavailable' | 'unsupported' | 'ready' = 'ready';
|
||||
if (workspaceStatusQuery == null || workspaceStatusQuery.isLoading) {
|
||||
workspaceDiscoveryState = 'loading';
|
||||
} else if (
|
||||
workspaceStatusQuery.isError ||
|
||||
workspaceStatus?.status !== 'ready' ||
|
||||
workspaceStatus.environmentId !== effectiveExecutionEnvironment?.id
|
||||
) {
|
||||
workspaceDiscoveryState = 'unavailable';
|
||||
} else if (workspaceStatus.workspaces == null) {
|
||||
workspaceDiscoveryState = 'unsupported';
|
||||
}
|
||||
const workspaces =
|
||||
workspaceDiscoveryState === 'ready' &&
|
||||
workspaceStatus?.status === 'ready' &&
|
||||
workspaceStatus.environmentId === effectiveExecutionEnvironment?.id
|
||||
? (workspaceStatus.workspaces ?? [])
|
||||
: [];
|
||||
const releaseIdentity = useCallback(() => {
|
||||
const identity = getValues('git_identity');
|
||||
const empty = !identity?.name?.trim() && !identity?.email?.trim();
|
||||
|
|
@ -151,6 +182,7 @@ export default function CodeSettings() {
|
|||
<Select
|
||||
value={codeEnvironmentId ?? DEPLOYMENT_DEFAULT_ENVIRONMENT}
|
||||
onValueChange={(value) => {
|
||||
setValue('code_workspace_id', '', { shouldDirty: true });
|
||||
setValue(
|
||||
'code_environment_id',
|
||||
value === DEPLOYMENT_DEFAULT_ENVIRONMENT ? null : value,
|
||||
|
|
@ -215,6 +247,65 @@ export default function CodeSettings() {
|
|||
<p className="text-xs text-text-tertiary">
|
||||
{localize('com_nav_info_stateful_code_environment')}
|
||||
</p>
|
||||
{showGitIdentity && (
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="code-workspace-default"
|
||||
className="text-xs font-medium text-text-secondary"
|
||||
>
|
||||
{localize('com_ui_code_workspace_default')}
|
||||
</label>
|
||||
<Select
|
||||
value={workspaceId || '__automatic__'}
|
||||
onValueChange={(value) => {
|
||||
if (value !== '__automatic__' && !workspaces.some(({ id }) => id === value))
|
||||
return;
|
||||
setValue('code_workspace_id', value === '__automatic__' ? '' : value, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
if (value !== '__automatic__' && effectiveExecutionEnvironment) {
|
||||
setValue('code_environment_id', effectiveExecutionEnvironment.id, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger id="code-workspace-default">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__automatic__">
|
||||
{localize('com_ui_code_workspace_last_used')}
|
||||
</SelectItem>
|
||||
{workspaceId &&
|
||||
(workspaceDiscoveryState !== 'ready' ||
|
||||
!workspaces.some(({ id }) => id === workspaceId)) && (
|
||||
<SelectItem value={workspaceId} disabled>
|
||||
{workspaceId} —{' '}
|
||||
{localize(
|
||||
workspaceDiscoveryState === 'ready'
|
||||
? 'com_ui_code_workspace_missing'
|
||||
: WORKSPACE_STATUS_LABELS[workspaceDiscoveryState],
|
||||
)}
|
||||
</SelectItem>
|
||||
)}
|
||||
{workspaces.map(({ id, name }) => (
|
||||
<SelectItem key={id} value={id}>
|
||||
{name ?? id}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{workspaceDiscoveryState !== 'ready' && (
|
||||
<p className="text-xs text-text-tertiary" role="status">
|
||||
{localize(WORKSPACE_STATUS_LABELS[workspaceDiscoveryState])}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xs text-text-tertiary">
|
||||
{localize('com_ui_code_workspace_default_description')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{showGitIdentity && (
|
||||
<div className="space-y-2 border-t border-border-light pt-3">
|
||||
<div className="text-xs font-medium text-text-secondary">
|
||||
|
|
|
|||
|
|
@ -19,7 +19,10 @@ jest.mock('~/hooks', () => ({
|
|||
}),
|
||||
useAgentCapabilities: () => ({ backgroundToolsEnabled: false }),
|
||||
}));
|
||||
jest.mock('~/data-provider', () => ({ useVerifyAgentToolAuth: () => ({ data: undefined }) }));
|
||||
jest.mock('~/data-provider', () => ({
|
||||
useVerifyAgentToolAuth: () => ({ data: undefined }),
|
||||
useCodeEnvironmentStatusQueries: () => [],
|
||||
}));
|
||||
jest.mock('../../../Search/Action', () => ({ __esModule: true, default: () => <div /> }));
|
||||
jest.mock('../../../FileContext', () => ({ __esModule: true, default: () => <div /> }));
|
||||
jest.mock('../../../FileSearch', () => ({ __esModule: true, default: () => <div /> }));
|
||||
|
|
|
|||
|
|
@ -6,6 +6,10 @@ import { AgentCapabilities } from 'librechat-data-provider';
|
|||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import type { AgentForm } from '~/common';
|
||||
import CodeSettings from '../Code/Settings';
|
||||
const mockWorkspaceStatusQueries = jest.fn();
|
||||
jest.mock('~/data-provider', () => ({
|
||||
useCodeEnvironmentStatusQueries: () => mockWorkspaceStatusQueries(),
|
||||
}));
|
||||
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize: () => (key: string) => key,
|
||||
|
|
@ -20,7 +24,27 @@ jest.mock('~/hooks', () => ({
|
|||
}),
|
||||
}));
|
||||
|
||||
function IdentityForm({ savedIdentity }: { savedIdentity?: AgentForm['git_identity'] }) {
|
||||
beforeEach(() => {
|
||||
mockWorkspaceStatusQueries.mockReturnValue([
|
||||
{
|
||||
data: {
|
||||
status: 'ready',
|
||||
environmentId: 'byom',
|
||||
workspaces: [{ id: 'project-a', name: 'Project A' }],
|
||||
},
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
function IdentityForm({
|
||||
savedIdentity,
|
||||
savedWorkspace,
|
||||
}: {
|
||||
savedIdentity?: AgentForm['git_identity'];
|
||||
savedWorkspace?: string;
|
||||
}) {
|
||||
const [dialogOpen, setDialogOpen] = useState(true);
|
||||
const methods = useForm<AgentForm>({
|
||||
mode: 'onChange',
|
||||
|
|
@ -28,6 +52,7 @@ function IdentityForm({ savedIdentity }: { savedIdentity?: AgentForm['git_identi
|
|||
execute_code: true,
|
||||
stateful_code_sessions: true,
|
||||
git_identity: savedIdentity,
|
||||
code_workspace_id: savedWorkspace,
|
||||
},
|
||||
});
|
||||
return (
|
||||
|
|
@ -44,10 +69,55 @@ function IdentityForm({ savedIdentity }: { savedIdentity?: AgentForm['git_identi
|
|||
Disable sessions
|
||||
</button>
|
||||
<output data-testid="identity">{JSON.stringify(methods.watch('git_identity'))}</output>
|
||||
<output data-testid="workspace-default">{methods.watch('code_workspace_id')}</output>
|
||||
<output data-testid="machine-default">{methods.watch('code_environment_id')}</output>
|
||||
</FormProvider>
|
||||
);
|
||||
}
|
||||
|
||||
test('saves a workspace default bound to the selected machine and permits clearing it', async () => {
|
||||
HTMLElement.prototype.scrollIntoView = jest.fn();
|
||||
render(<IdentityForm />);
|
||||
fireEvent.click(screen.getByRole('combobox', { name: 'com_ui_code_workspace_default' }));
|
||||
fireEvent.click(await screen.findByRole('option', { name: 'Project A' }));
|
||||
expect(screen.getByTestId('workspace-default')).toHaveTextContent('project-a');
|
||||
expect(screen.getByTestId('machine-default')).toHaveTextContent('byom');
|
||||
fireEvent.click(screen.getByRole('combobox', { name: 'com_ui_code_workspace_default' }));
|
||||
fireEvent.click(await screen.findByRole('option', { name: 'com_ui_code_workspace_last_used' }));
|
||||
expect(screen.getByTestId('workspace-default')).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
test.each([
|
||||
[{ isLoading: true, isError: false }, 'com_ui_code_workspace_loading'],
|
||||
[{ isLoading: false, isError: true }, 'com_ui_code_workspace_unavailable'],
|
||||
[
|
||||
{
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
data: { status: 'ready', environmentId: 'byom', workspaces: undefined },
|
||||
},
|
||||
'com_ui_code_workspace_unsupported',
|
||||
],
|
||||
])('preserves a saved workspace while discovery reports %s', (query, expectedLabel) => {
|
||||
mockWorkspaceStatusQueries.mockReturnValue([query]);
|
||||
render(<IdentityForm savedWorkspace="project-a" />);
|
||||
|
||||
expect(screen.getByText(expectedLabel, { selector: 'p[role="status"]' })).toBeInTheDocument();
|
||||
expect(screen.getByTestId('workspace-default')).toHaveTextContent('project-a');
|
||||
expect(screen.queryByText(/com_ui_code_workspace_missing/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('permits clearing a saved workspace while discovery is unavailable', async () => {
|
||||
HTMLElement.prototype.scrollIntoView = jest.fn();
|
||||
mockWorkspaceStatusQueries.mockReturnValue([{ isLoading: false, isError: true }]);
|
||||
render(<IdentityForm savedWorkspace="project-a" />);
|
||||
|
||||
fireEvent.click(screen.getByRole('combobox', { name: 'com_ui_code_workspace_default' }));
|
||||
fireEvent.click(await screen.findByRole('option', { name: 'com_ui_code_workspace_last_used' }));
|
||||
|
||||
expect(screen.getByTestId('workspace-default')).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
test.each(['', 'not-an-email'])(
|
||||
'restores the saved identity when reopening an invalid draft: %s',
|
||||
async (email) => {
|
||||
|
|
|
|||
|
|
@ -65,6 +65,7 @@ describe('useDeleteAgentMutation', () => {
|
|||
const affectedQueryKey = [QueryKeys.agent, affectedId, 'expanded'];
|
||||
const affectedSourceQueryKey = [QueryKeys.agent, affectedSourceId, 'expanded'];
|
||||
const unrelatedQueryKey = [QueryKeys.agent, unrelatedId, 'expanded'];
|
||||
const viewListKey = [QueryKeys.agents, { requiredPermission: PermissionBits.VIEW }];
|
||||
const staleAffectedAgent = createAgent(affectedId, [
|
||||
{ from: affectedId, to: targetId, edgeType: 'handoff' },
|
||||
]);
|
||||
|
|
@ -79,6 +80,9 @@ describe('useDeleteAgentMutation', () => {
|
|||
const refreshedAffectedSourceAgent = createAgent(affectedSourceId, [
|
||||
{ from: 'agent_surviving_source', to: affectedSourceId, edgeType: 'handoff' },
|
||||
]);
|
||||
const locallyPrunedAffectedSourceAgent = createAgent(affectedSourceId, [
|
||||
{ from: ['agent_surviving_source'], to: affectedSourceId, edgeType: 'handoff' },
|
||||
]);
|
||||
const unrelatedAgent = createAgent(unrelatedId, [
|
||||
{ from: unrelatedId, to: 'agent_other', edgeType: 'handoff' },
|
||||
]);
|
||||
|
|
@ -95,6 +99,13 @@ describe('useDeleteAgentMutation', () => {
|
|||
await queryClient.prefetchQuery(affectedQueryKey, affectedFetch);
|
||||
await queryClient.prefetchQuery(affectedSourceQueryKey, affectedSourceFetch);
|
||||
await queryClient.prefetchQuery(unrelatedQueryKey, unrelatedFetch);
|
||||
queryClient.setQueryData<AgentListResponse>(viewListKey, {
|
||||
object: 'list',
|
||||
data: [staleAffectedAgent, staleAffectedSourceAgent, unrelatedAgent, createAgent(targetId)],
|
||||
first_id: affectedId,
|
||||
last_id: targetId,
|
||||
has_more: false,
|
||||
});
|
||||
queryClient.setQueryData([QueryKeys.agent, targetId], createAgent(targetId));
|
||||
queryClient.setQueryData([QueryKeys.agent, targetId, 'expanded'], createAgent(targetId));
|
||||
|
||||
|
|
@ -114,6 +125,11 @@ describe('useDeleteAgentMutation', () => {
|
|||
expect(queryClient.getQueryData(affectedSourceQueryKey)).toEqual(refreshedAffectedSourceAgent);
|
||||
expect(unrelatedFetch).toHaveBeenCalledTimes(1);
|
||||
expect(queryClient.getQueryData(unrelatedQueryKey)).toEqual(unrelatedAgent);
|
||||
expect(queryClient.getQueryData<AgentListResponse>(viewListKey)?.data).toEqual([
|
||||
refreshedAffectedAgent,
|
||||
locallyPrunedAffectedSourceAgent,
|
||||
unrelatedAgent,
|
||||
]);
|
||||
expect(queryClient.getQueryData([QueryKeys.agent, targetId])).toBeUndefined();
|
||||
expect(queryClient.getQueryData([QueryKeys.agent, targetId, 'expanded'])).toBeUndefined();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -30,6 +30,31 @@ const hasEdgeWithAgent = (data: unknown, agentId: string): boolean => {
|
|||
);
|
||||
};
|
||||
|
||||
const pruneEdgeEndpoint = (
|
||||
endpoint: t.GraphEdge['from'],
|
||||
agentId: string,
|
||||
): t.GraphEdge['from'] | null => {
|
||||
if (Array.isArray(endpoint)) {
|
||||
const retained = endpoint.filter((id) => id !== agentId);
|
||||
return retained.length > 0 ? retained : null;
|
||||
}
|
||||
return endpoint === agentId ? null : endpoint;
|
||||
};
|
||||
|
||||
/** Mirrors the server's deletion cleanup so cached execution graphs stop referencing the
|
||||
* deleted agent immediately, before the authoritative refetch completes. */
|
||||
const pruneAgentEdges = (agent: t.Agent, agentId: string): t.Agent => {
|
||||
if (!hasEdgeWithAgent(agent, agentId)) {
|
||||
return agent;
|
||||
}
|
||||
const edges = (agent.edges ?? []).flatMap((edge) => {
|
||||
const from = pruneEdgeEndpoint(edge.from, agentId);
|
||||
const to = pruneEdgeEndpoint(edge.to, agentId);
|
||||
return from == null || to == null ? [] : [{ ...edge, from, to }];
|
||||
});
|
||||
return { ...agent, edges };
|
||||
};
|
||||
|
||||
/**
|
||||
* Mutation responses omit list-only `isEditable`. When merging into a cached list
|
||||
* row, keep the ACL flag the list endpoint set rather than inferring it from
|
||||
|
|
@ -156,7 +181,9 @@ export const useDeleteAgentMutation = (
|
|||
return options?.onSuccess?.(_data, variables, context);
|
||||
}
|
||||
|
||||
data = listRes.data.filter((agent) => agent.id !== variables.agent_id);
|
||||
data = listRes.data
|
||||
.filter((agent) => agent.id !== variables.agent_id)
|
||||
.map((agent) => pruneAgentEdges(agent, variables.agent_id));
|
||||
|
||||
queryClient.setQueryData<t.AgentListResponse>([QueryKeys.agents, key], {
|
||||
...listRes,
|
||||
|
|
@ -168,15 +195,20 @@ export const useDeleteAgentMutation = (
|
|||
|
||||
queryClient.removeQueries([QueryKeys.agent, variables.agent_id]);
|
||||
queryClient.removeQueries([QueryKeys.agent, variables.agent_id, 'expanded']);
|
||||
/** Deletion removes the agent from every edge endpoint server-side. Expanded queries
|
||||
* opt out of refetch-on-mount, so refresh every cached graph known to reference it. */
|
||||
/** Deletion removes the agent from every edge endpoint server-side. Refresh every cached
|
||||
* graph known to reference it, then mirror that cleanup immediately while refetch runs. */
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: [QueryKeys.agent],
|
||||
predicate: (query) =>
|
||||
query.queryKey[2] === 'expanded' &&
|
||||
hasEdgeWithAgent(query.state.data, variables.agent_id),
|
||||
predicate: (query) => hasEdgeWithAgent(query.state.data, variables.agent_id),
|
||||
refetchType: 'all',
|
||||
});
|
||||
queryClient.setQueriesData<t.Agent>(
|
||||
{
|
||||
queryKey: [QueryKeys.agent],
|
||||
predicate: (query) => hasEdgeWithAgent(query.state.data, variables.agent_id),
|
||||
},
|
||||
(agent) => (agent ? pruneAgentEdges(agent, variables.agent_id) : agent),
|
||||
);
|
||||
invalidateAgentMarketplaceQueries(queryClient);
|
||||
|
||||
return options?.onSuccess?.(_data, variables, data);
|
||||
|
|
|
|||
|
|
@ -149,6 +149,33 @@ describe('useAgentToolPermissions', () => {
|
|||
expect(result.current.statefulCodeSessionsAllowedByAgent).toBe(true);
|
||||
});
|
||||
|
||||
it('preserves execution graph metadata omitted by the basic agent response', () => {
|
||||
const agentId = 'agent_test';
|
||||
mockUseAgentsMapContext.mockReturnValue({
|
||||
[agentId]: {
|
||||
id: agentId,
|
||||
tools: [Tools.execute_code],
|
||||
code_environment_id: 'attached-vm',
|
||||
code_workspace_id: 'project-a',
|
||||
stateful_code_sessions: true,
|
||||
agent_ids: ['agent-child'],
|
||||
},
|
||||
});
|
||||
mockUseGetAgentByIdQuery.mockReturnValue({
|
||||
data: { id: agentId, name: 'Safe agent response' },
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAgentToolPermissions(agentId));
|
||||
|
||||
expect(result.current.agent).toMatchObject({
|
||||
id: agentId,
|
||||
name: 'Safe agent response',
|
||||
code_environment_id: 'attached-vm',
|
||||
code_workspace_id: 'project-a',
|
||||
agent_ids: ['agent-child'],
|
||||
});
|
||||
});
|
||||
|
||||
it('should fallback to agent map data when API data is not available', () => {
|
||||
const agentId = 'agent_test';
|
||||
const agentMapData = {
|
||||
|
|
|
|||
|
|
@ -8,6 +8,11 @@ const mockAgentsConfig = jest.fn();
|
|||
const mockStatus = jest.fn();
|
||||
const mockAgentsMap = jest.fn();
|
||||
const mockAccess = jest.fn();
|
||||
const mockPreference = jest.fn();
|
||||
const mockRememberPreference = jest.fn();
|
||||
jest.mock('../workspacePreferences', () => ({
|
||||
useWorkspacePreferences: () => ({ get: mockPreference, remember: mockRememberPreference }),
|
||||
}));
|
||||
jest.mock('~/hooks/Roles/useHasAccess', () => () => mockAccess());
|
||||
|
||||
jest.mock(
|
||||
|
|
@ -32,6 +37,8 @@ const conversation = (codeWorkspaces?: TConversation['codeWorkspaces']): TConver
|
|||
|
||||
describe('useCodeWorkspace', () => {
|
||||
beforeEach(() => {
|
||||
mockPreference.mockReset();
|
||||
mockRememberPreference.mockReset();
|
||||
mockAccess.mockReturnValue(true);
|
||||
mockAgentPermissions.mockReturnValue({
|
||||
tools: [Tools.execute_code],
|
||||
|
|
@ -100,6 +107,177 @@ describe('useCodeWorkspace', () => {
|
|||
expect(mockStatus).toHaveBeenCalledWith(['personal-vm'], true);
|
||||
});
|
||||
|
||||
it('uses an agent default ahead of the last used workspace only for new chats', () => {
|
||||
mockStatus()[0].data.workspaces.push({ id: 'project-b', name: 'Project B' });
|
||||
mockAgentPermissions().agent.code_workspace_id = 'project-b';
|
||||
mockPreference.mockReturnValue('project-a');
|
||||
const { result, rerender } = renderHook(
|
||||
({ id }) => useCodeWorkspace({ ...conversation(), conversationId: id }),
|
||||
{
|
||||
initialProps: { id: 'new' },
|
||||
},
|
||||
);
|
||||
expect(result.current.selections?.[0].workspaceId).toBe('project-b');
|
||||
rerender({ id: 'existing' });
|
||||
expect(result.current.canSubmit).toBe(false);
|
||||
});
|
||||
|
||||
it('uses a valid last choice and preserves an explicit conversation binding', () => {
|
||||
mockStatus()[0].data.workspaces.push({ id: 'project-b', name: 'Project B' });
|
||||
mockPreference.mockReturnValue('project-b');
|
||||
const { result } = renderHook(() =>
|
||||
useCodeWorkspace({ ...conversation(), conversationId: 'new' }),
|
||||
);
|
||||
expect(result.current.selections?.[0].workspaceId).toBe('project-b');
|
||||
const saved = [{ environmentId: 'personal-vm', workspaceId: 'project-a' }];
|
||||
const existing = renderHook(() =>
|
||||
useCodeWorkspace({ ...conversation(saved), conversationId: 'new' }),
|
||||
);
|
||||
expect(existing.result.current.selections).toEqual(saved);
|
||||
});
|
||||
|
||||
it('reads and records preferences for the root that reaches each environment', () => {
|
||||
const primaryAgent = {
|
||||
id: 'agent_primary',
|
||||
stateful_code_sessions: true,
|
||||
code_environment_id: 'primary-vm',
|
||||
tools: [Tools.execute_code],
|
||||
};
|
||||
const addedAgent = {
|
||||
id: 'agent_added',
|
||||
stateful_code_sessions: true,
|
||||
code_environment_id: 'added-vm',
|
||||
tools: [Tools.execute_code],
|
||||
};
|
||||
mockAgentPermissions.mockImplementation((agentId) => ({
|
||||
tools: [Tools.execute_code],
|
||||
agent: agentId === 'agent_added' ? addedAgent : primaryAgent,
|
||||
}));
|
||||
mockAgentsConfig.mockReturnValue({
|
||||
agentsConfig: {
|
||||
capabilities: ['execute_code', 'stateful_code_sessions'],
|
||||
statefulCodeSessions: {
|
||||
environments: [
|
||||
{ id: 'primary-vm', name: 'Primary VM', type: 'attached' },
|
||||
{ id: 'added-vm', name: 'Added VM', type: 'attached' },
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
mockStatus.mockReturnValue(
|
||||
['added-vm', 'primary-vm'].map((environmentId) => ({
|
||||
data: {
|
||||
environmentId,
|
||||
status: 'ready',
|
||||
workspaces: [{ id: 'project-a' }, { id: 'project-b' }],
|
||||
},
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
})),
|
||||
);
|
||||
mockPreference.mockImplementation((environmentId, agentId) =>
|
||||
environmentId === 'added-vm' && agentId === 'agent_added' ? 'project-b' : 'project-a',
|
||||
);
|
||||
|
||||
const addedConversation = {
|
||||
...conversation(),
|
||||
conversationId: 'new',
|
||||
agent_id: 'agent_added',
|
||||
};
|
||||
const { result } = renderHook(() =>
|
||||
useCodeWorkspace({ ...conversation(), conversationId: 'new' }, addedConversation),
|
||||
);
|
||||
|
||||
expect(result.current.selections).toEqual([
|
||||
{ environmentId: 'added-vm', workspaceId: 'project-b' },
|
||||
{ environmentId: 'primary-vm', workspaceId: 'project-a' },
|
||||
]);
|
||||
result.current.rememberSelection({ environmentId: 'added-vm', workspaceId: 'project-a' });
|
||||
expect(mockRememberPreference).toHaveBeenCalledWith('added-vm', 'project-a', ['agent_added']);
|
||||
});
|
||||
|
||||
it('applies an added agent default after the primary workspace is already pinned', () => {
|
||||
const primaryAgent = {
|
||||
id: 'agent_primary',
|
||||
stateful_code_sessions: true,
|
||||
code_environment_id: 'primary-vm',
|
||||
code_workspace_id: 'primary-project',
|
||||
tools: [Tools.execute_code],
|
||||
};
|
||||
const addedAgent = {
|
||||
id: 'agent_added',
|
||||
stateful_code_sessions: true,
|
||||
code_environment_id: 'added-vm',
|
||||
code_workspace_id: 'added-project',
|
||||
tools: [Tools.execute_code],
|
||||
};
|
||||
mockAgentPermissions.mockImplementation((agentId) => ({
|
||||
tools: [Tools.execute_code],
|
||||
agent: agentId === 'agent_added' ? addedAgent : primaryAgent,
|
||||
}));
|
||||
mockAgentsConfig.mockReturnValue({
|
||||
agentsConfig: {
|
||||
capabilities: ['execute_code', 'stateful_code_sessions'],
|
||||
statefulCodeSessions: {
|
||||
environments: [
|
||||
{ id: 'primary-vm', type: 'attached' },
|
||||
{ id: 'added-vm', type: 'attached' },
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
mockStatus.mockImplementation((environmentIds: string[]) =>
|
||||
environmentIds.map((environmentId) => ({
|
||||
data: {
|
||||
environmentId,
|
||||
status: 'ready',
|
||||
workspaces: [
|
||||
{ id: environmentId === 'primary-vm' ? 'primary-project' : 'added-project' },
|
||||
],
|
||||
},
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
})),
|
||||
);
|
||||
const primarySelection = {
|
||||
environmentId: 'primary-vm',
|
||||
workspaceId: 'primary-project',
|
||||
};
|
||||
const addedConversation = {
|
||||
...conversation(),
|
||||
conversationId: 'new',
|
||||
agent_id: 'agent_added',
|
||||
};
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useCodeWorkspace(
|
||||
{ ...conversation([primarySelection]), conversationId: 'new' },
|
||||
addedConversation,
|
||||
),
|
||||
);
|
||||
|
||||
expect(result.current.selections).toEqual([
|
||||
{ environmentId: 'added-vm', workspaceId: 'added-project' },
|
||||
primarySelection,
|
||||
]);
|
||||
expect(result.current.canSubmit).toBe(true);
|
||||
});
|
||||
|
||||
it('ignores stale remembered choices but never silently replaces a missing agent default', () => {
|
||||
mockPreference.mockReturnValue('gone');
|
||||
const { result, rerender } = renderHook(() =>
|
||||
useCodeWorkspace({ ...conversation(), conversationId: 'new' }),
|
||||
);
|
||||
expect(result.current.selections?.[0].workspaceId).toBe('project-a');
|
||||
mockAgentPermissions.mockReturnValue({
|
||||
...mockAgentPermissions(),
|
||||
agent: { ...mockAgentPermissions().agent, code_workspace_id: 'gone' },
|
||||
});
|
||||
rerender();
|
||||
expect(result.current.state).toBe('missing');
|
||||
expect(result.current.canSubmit).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['ephemeral', 'openAI__gpt-4o'])('does not block ephemeral agent %s', (agent_id) => {
|
||||
mockAgentPermissions.mockReturnValue({});
|
||||
const { result } = renderHook(() => useCodeWorkspace({ ...conversation(), agent_id }));
|
||||
|
|
@ -351,6 +529,38 @@ describe('useCodeWorkspace', () => {
|
|||
expect(result.current.resolveSubmission()).toEqual({});
|
||||
});
|
||||
|
||||
it('requires an explicit choice when reachable agents disagree on one machine', () => {
|
||||
const primary = {
|
||||
...mockAgentPermissions().agent,
|
||||
code_workspace_id: 'project-a',
|
||||
subagents: { enabled: true, agent_ids: ['child'] },
|
||||
};
|
||||
mockAgentPermissions.mockImplementation((id?: string) => ({
|
||||
agent: id === 'agent_primary' ? primary : undefined,
|
||||
}));
|
||||
mockAgentsMap.mockReturnValue({
|
||||
child: {
|
||||
id: 'child',
|
||||
stateful_code_sessions: true,
|
||||
code_environment_id: 'personal-vm',
|
||||
code_workspace_id: 'project-b',
|
||||
tools: [Tools.execute_code],
|
||||
},
|
||||
});
|
||||
const { result } = renderHook(() =>
|
||||
useCodeWorkspace({ ...conversation(), conversationId: 'new' }),
|
||||
);
|
||||
expect(result.current.state).toBe('choose');
|
||||
expect(result.current.canSubmit).toBe(false);
|
||||
expect(
|
||||
result.current.resolveSubmission([
|
||||
{ environmentId: 'personal-vm', workspaceId: 'project-a' },
|
||||
]),
|
||||
).toEqual({
|
||||
codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'project-a' }],
|
||||
});
|
||||
});
|
||||
|
||||
it.each(['subagent', 'handoff'])('collects every attached environment through %s', (kind) => {
|
||||
const primary = {
|
||||
id: 'agent_primary',
|
||||
|
|
|
|||
|
|
@ -124,6 +124,48 @@ describe('useSelectAgent', () => {
|
|||
spec: null,
|
||||
iconURL: null,
|
||||
modelLabel: null,
|
||||
codeWorkspaces: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not carry a prior agent workspace binding into the selected agent', async () => {
|
||||
mockGetConversation.mockResolvedValue({
|
||||
endpoint: EModelEndpoint.agents,
|
||||
agent_id: 'agent-old',
|
||||
codeWorkspaces: [{ environmentId: 'machine-a', workspaceId: 'project-old' }],
|
||||
} as TConversation);
|
||||
mockFetchQuery.mockResolvedValue({ id: 'agent-1', name: 'Full Agent' });
|
||||
const { result } = renderHook(() => useSelectAgent());
|
||||
|
||||
await act(async () => {
|
||||
await result.current.onSelect('agent-1');
|
||||
});
|
||||
|
||||
expect(mockNewConversation.mock.calls[0][0].template.codeWorkspaces).toBeUndefined();
|
||||
expect(mockNewConversation.mock.calls[1][0].template.codeWorkspaces).toBeUndefined();
|
||||
expect(mockGetDefaultConversation.mock.calls[0][0].conversation.codeWorkspaces).toBeUndefined();
|
||||
});
|
||||
|
||||
it('preserves a workspace selected while the same agent is hydrating', async () => {
|
||||
const selectedWorkspace = [{ environmentId: 'machine-a', workspaceId: 'project-a' }];
|
||||
mockGetConversation
|
||||
.mockResolvedValueOnce({
|
||||
endpoint: EModelEndpoint.agents,
|
||||
agent_id: 'agent-old',
|
||||
} as TConversation)
|
||||
.mockResolvedValueOnce({
|
||||
endpoint: EModelEndpoint.agents,
|
||||
agent_id: 'agent-1',
|
||||
codeWorkspaces: selectedWorkspace,
|
||||
} as TConversation);
|
||||
mockFetchQuery.mockResolvedValue({ id: 'agent-1', name: 'Full Agent' });
|
||||
const { result } = renderHook(() => useSelectAgent());
|
||||
|
||||
await act(async () => {
|
||||
await result.current.onSelect('agent-1');
|
||||
});
|
||||
|
||||
expect(mockNewConversation.mock.calls[0][0].template.codeWorkspaces).toBeUndefined();
|
||||
expect(mockNewConversation.mock.calls[1][0].template.codeWorkspaces).toEqual(selectedWorkspace);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -0,0 +1,52 @@
|
|||
import { Provider } from 'jotai';
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { useWorkspacePreferences } from '../workspacePreferences';
|
||||
|
||||
const mockUser = { id: 'user-a', tenantId: 'tenant-a' };
|
||||
jest.mock('~/hooks/AuthContext', () => ({ useAuthContext: () => ({ user: mockUser }) }));
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
mockUser.id = 'user-a';
|
||||
mockUser.tenantId = 'tenant-a';
|
||||
});
|
||||
|
||||
test('persists choices across mounts and scopes them by user, tenant, agent and machine', () => {
|
||||
const first = renderHook(() => useWorkspacePreferences('agent-a'), { wrapper: Provider });
|
||||
act(() => first.result.current.remember('machine-a', 'project-a'));
|
||||
first.unmount();
|
||||
const { result, rerender } = renderHook(({ agent }) => useWorkspacePreferences(agent), {
|
||||
wrapper: Provider,
|
||||
initialProps: { agent: 'agent-a' },
|
||||
});
|
||||
expect(result.current.get('machine-a')).toBe('project-a');
|
||||
expect(result.current.get('machine-b')).toBeUndefined();
|
||||
rerender({ agent: 'agent-b' });
|
||||
expect(result.current.get('machine-a')).toBeUndefined();
|
||||
mockUser.id = 'user-b';
|
||||
rerender({ agent: 'agent-a' });
|
||||
expect(result.current.get('machine-a')).toBeUndefined();
|
||||
mockUser.id = 'user-a';
|
||||
mockUser.tenantId = 'tenant-b';
|
||||
rerender({ agent: 'agent-a' });
|
||||
expect(result.current.get('machine-a')).toBeUndefined();
|
||||
});
|
||||
|
||||
test('storage errors never prevent a manual choice', () => {
|
||||
const { result } = renderHook(() => useWorkspacePreferences('agent-a'), { wrapper: Provider });
|
||||
jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
|
||||
throw new Error('quota');
|
||||
});
|
||||
expect(() => act(() => result.current.remember('machine-a', 'project-a'))).not.toThrow();
|
||||
});
|
||||
|
||||
test('records a shared selection for every root agent that reaches the machine', () => {
|
||||
const first = renderHook(() => useWorkspacePreferences(), { wrapper: Provider });
|
||||
act(() => first.result.current.remember('machine-a', 'project-a', ['agent-a', 'agent-b']));
|
||||
first.unmount();
|
||||
|
||||
const { result } = renderHook(() => useWorkspacePreferences(), { wrapper: Provider });
|
||||
expect(result.current.get('machine-a', 'agent-a')).toBe('project-a');
|
||||
expect(result.current.get('machine-a', 'agent-b')).toBe('project-a');
|
||||
expect(result.current.get('machine-a', 'agent-c')).toBeUndefined();
|
||||
});
|
||||
|
|
@ -77,12 +77,18 @@ export default function useAgentToolPermissions(
|
|||
return tools?.includes(Tools.execute_code) ?? false;
|
||||
}, [agentId, selectedAgent, tools, ephemeralAgent]);
|
||||
|
||||
const agent = useMemo(() => {
|
||||
if (selectedAgent == null) return agentData;
|
||||
if (agentData == null) return selectedAgent;
|
||||
return { ...selectedAgent, ...agentData };
|
||||
}, [agentData, selectedAgent]);
|
||||
|
||||
return {
|
||||
fileSearchAllowedByAgent,
|
||||
codeAllowedByAgent,
|
||||
statefulCodeSessionsAllowedByAgent,
|
||||
codeEnvironmentId,
|
||||
agent: agentData ?? selectedAgent,
|
||||
agent,
|
||||
provider,
|
||||
tools,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import type {
|
|||
} from 'librechat-data-provider';
|
||||
import { collectReachableAgents, findExecutionEnvironment } from './useCodeApprovalMode';
|
||||
import { useCodeEnvironmentStatusQueries } from '~/data-provider';
|
||||
import { useWorkspacePreferences } from './workspacePreferences';
|
||||
import useAgentToolPermissions from './useAgentToolPermissions';
|
||||
import useHasAccess from '~/hooks/Roles/useHasAccess';
|
||||
import useGetAgentsConfig from './useGetAgentsConfig';
|
||||
|
|
@ -49,6 +50,7 @@ export interface CodeWorkspaceResult {
|
|||
resolveSubmission: (
|
||||
selections?: CodeWorkspaceSelection[],
|
||||
) => { codeWorkspaces?: CodeWorkspaceSelection[] } | undefined;
|
||||
rememberSelection: (selection: CodeWorkspaceSelection) => void;
|
||||
}
|
||||
|
||||
function aggregateState(
|
||||
|
|
@ -93,6 +95,7 @@ export default function useCodeWorkspace(
|
|||
conversation: TConversation | null,
|
||||
addedConversation?: TConversation | null,
|
||||
): CodeWorkspaceResult {
|
||||
const preferences = useWorkspacePreferences(conversation?.agent_id);
|
||||
const { agentsConfig, endpointsConfig } = useGetAgentsConfig();
|
||||
const canRunCode = useHasAccess({
|
||||
permissionType: PermissionTypes.RUN_CODE,
|
||||
|
|
@ -118,6 +121,8 @@ export default function useCodeWorkspace(
|
|||
);
|
||||
const workspaceMetadata = useMemo(() => {
|
||||
const unique = new Map<string, TPublicCodeEnvironment>();
|
||||
const defaults = new Map<string, Set<string>>();
|
||||
const preferenceAgentIds = new Map<string, Set<string>>();
|
||||
let complete = true;
|
||||
for (const agent of reachable.agents) {
|
||||
if (agent.stateful_code_sessions !== true || !agent.tools?.includes(Tools.execute_code)) {
|
||||
|
|
@ -125,13 +130,47 @@ export default function useCodeWorkspace(
|
|||
}
|
||||
const environment = findExecutionEnvironment(agent, statefulCodeSessions?.environments);
|
||||
if (agent.code_environment_id && environment == null) complete = false;
|
||||
if (environment?.type === 'attached') unique.set(environment.id, environment);
|
||||
if (environment?.type !== 'attached') continue;
|
||||
unique.set(environment.id, environment);
|
||||
if (agent.code_environment_id === environment.id && agent.code_workspace_id) {
|
||||
const choices = defaults.get(environment.id) ?? new Set<string>();
|
||||
choices.add(agent.code_workspace_id);
|
||||
defaults.set(environment.id, choices);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [rootAgent, rootAgentId] of [
|
||||
[primaryAgent, conversation?.agent_id],
|
||||
[addedAgent, addedConversation?.agent_id],
|
||||
] as const) {
|
||||
if (!rootAgent || !rootAgentId) continue;
|
||||
const rootReachable = collectReachableAgents([rootAgent], agentsMap, [rootAgentId]);
|
||||
for (const agent of rootReachable.agents) {
|
||||
if (agent.stateful_code_sessions !== true || !agent.tools?.includes(Tools.execute_code)) {
|
||||
continue;
|
||||
}
|
||||
const environment = findExecutionEnvironment(agent, statefulCodeSessions?.environments);
|
||||
if (environment?.type !== 'attached') continue;
|
||||
const owners = preferenceAgentIds.get(environment.id) ?? new Set<string>();
|
||||
owners.add(rootAgentId);
|
||||
preferenceAgentIds.set(environment.id, owners);
|
||||
}
|
||||
}
|
||||
return {
|
||||
complete,
|
||||
defaults,
|
||||
preferenceAgentIds,
|
||||
environments: [...unique.values()].sort((a, b) => a.id.localeCompare(b.id)),
|
||||
};
|
||||
}, [reachable.agents, statefulCodeSessions?.environments]);
|
||||
}, [
|
||||
addedAgent,
|
||||
addedConversation?.agent_id,
|
||||
agentsMap,
|
||||
conversation?.agent_id,
|
||||
primaryAgent,
|
||||
reachable.agents,
|
||||
statefulCodeSessions?.environments,
|
||||
]);
|
||||
const isAgentsConversation =
|
||||
(conversation?.endpointType ?? conversation?.endpoint) === EModelEndpoint.agents;
|
||||
const expectedRoot = conversation?.agent_id != null || addedConversation?.agent_id != null;
|
||||
|
|
@ -153,19 +192,42 @@ export default function useCodeWorkspace(
|
|||
required && selectionMetadataComplete,
|
||||
);
|
||||
const storedSelections = conversation?.codeWorkspaces;
|
||||
const attachedEnvironmentIds = new Set(attachedEnvironments.map(({ id }) => id));
|
||||
const hasForeignStoredSelection = storedSelections?.some(
|
||||
({ environmentId }) => !attachedEnvironmentIds.has(environmentId),
|
||||
);
|
||||
const isNewChat =
|
||||
conversation != null &&
|
||||
(conversation.conversationId == null || conversation.conversationId === 'new');
|
||||
const environmentResults = attachedEnvironments.map((environment, index) => {
|
||||
const status = statuses[index];
|
||||
const workspaces =
|
||||
status?.data?.status === 'ready' && Array.isArray(status.data.workspaces)
|
||||
? status.data.workspaces
|
||||
: [];
|
||||
const stored = storedSelections?.find(({ environmentId }) => environmentId === environment.id);
|
||||
let stored = storedSelections?.find(({ environmentId }) => environmentId === environment.id);
|
||||
let conflictingDefaults = false;
|
||||
if (stored == null && isNewChat && !hasForeignStoredSelection) {
|
||||
const defaults = workspaceMetadata.defaults.get(environment.id) ?? new Set<string>();
|
||||
let preferred: string | undefined;
|
||||
if (defaults.size === 1) preferred = [...defaults][0];
|
||||
else if (defaults.size === 0) {
|
||||
preferred = [...(workspaceMetadata.preferenceAgentIds.get(environment.id) ?? [])]
|
||||
.map((agentId) => preferences.get(environment.id, agentId))
|
||||
.find((workspaceId) => workspaces.some(({ id }) => id === workspaceId));
|
||||
}
|
||||
if (preferred && (defaults.size > 0 || workspaces.some(({ id }) => id === preferred))) {
|
||||
stored = { environmentId: environment.id, workspaceId: preferred };
|
||||
}
|
||||
conflictingDefaults = defaults.size > 1;
|
||||
}
|
||||
const selected = resolveEnvironmentSelection({
|
||||
environment,
|
||||
status: status?.data,
|
||||
workspaces,
|
||||
stored,
|
||||
hasStoredSelections: storedSelections != null,
|
||||
hasStoredSelections:
|
||||
stored != null || conflictingDefaults || hasForeignStoredSelection === true,
|
||||
});
|
||||
let state: CodeWorkspaceEnvironmentResult['state'] = 'choose';
|
||||
if (status == null || status.isLoading) state = 'loading';
|
||||
|
|
@ -204,11 +266,8 @@ export default function useCodeWorkspace(
|
|||
});
|
||||
continue;
|
||||
}
|
||||
if (selections == null && result.workspaces.length === 1 && result.state === 'ready') {
|
||||
resolved.push({
|
||||
environmentId: result.environment.id,
|
||||
workspaceId: result.workspaces[0].id,
|
||||
});
|
||||
if (requested == null && result.selected != null && result.state === 'ready') {
|
||||
resolved.push(result.selected);
|
||||
continue;
|
||||
}
|
||||
return undefined;
|
||||
|
|
@ -233,6 +292,14 @@ export default function useCodeWorkspace(
|
|||
[required, resolveSelections],
|
||||
);
|
||||
const canSubmit = resolveSubmission(storedSelections) != null;
|
||||
const rememberSelection = useCallback(
|
||||
(selection: CodeWorkspaceSelection) => {
|
||||
preferences.remember(selection.environmentId, selection.workspaceId, [
|
||||
...(workspaceMetadata.preferenceAgentIds.get(selection.environmentId) ?? []),
|
||||
]);
|
||||
},
|
||||
[preferences, workspaceMetadata.preferenceAgentIds],
|
||||
);
|
||||
return {
|
||||
required,
|
||||
state,
|
||||
|
|
@ -241,5 +308,6 @@ export default function useCodeWorkspace(
|
|||
selections,
|
||||
resolveSelections,
|
||||
resolveSubmission,
|
||||
rememberSelection,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,10 +39,20 @@ export default function useSelectAgent() {
|
|||
});
|
||||
return;
|
||||
}
|
||||
const currentConvo = getDefaultConversation({
|
||||
conversation: { ...(conversation ?? {}), agent_id: agent.id, ...specDisplayFieldReset },
|
||||
const switchesAgent = conversation?.agent_id !== agent.id;
|
||||
const resolvedConvo = getDefaultConversation({
|
||||
conversation: {
|
||||
...(conversation ?? {}),
|
||||
agent_id: agent.id,
|
||||
codeWorkspaces: switchesAgent ? undefined : conversation?.codeWorkspaces,
|
||||
...specDisplayFieldReset,
|
||||
},
|
||||
preset: template,
|
||||
});
|
||||
const currentConvo = {
|
||||
...resolvedConvo,
|
||||
codeWorkspaces: switchesAgent ? undefined : conversation?.codeWorkspaces,
|
||||
};
|
||||
newConversation({
|
||||
template: currentConvo,
|
||||
preset: template as Partial<TPreset>,
|
||||
|
|
@ -63,6 +73,7 @@ export default function useSelectAgent() {
|
|||
endpoint: EModelEndpoint.agents,
|
||||
agent_id: agent.id,
|
||||
conversationId: Constants.NEW_CONVO as string,
|
||||
codeWorkspaces: undefined,
|
||||
...specDisplayFieldReset,
|
||||
};
|
||||
|
||||
|
|
|
|||
51
client/src/hooks/Agents/workspacePreferences.ts
Normal file
51
client/src/hooks/Agents/workspacePreferences.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { useAtom } from 'jotai';
|
||||
import { createStorageAtom } from '~/store/jotai-utils';
|
||||
import { useAuthContext } from '~/hooks/AuthContext';
|
||||
|
||||
interface WorkspacePreference {
|
||||
key: string;
|
||||
workspaceId: string;
|
||||
}
|
||||
|
||||
const preferences = createStorageAtom<WorkspacePreference[]>('codeWorkspacePreferences', []);
|
||||
|
||||
function validEntries(saved: WorkspacePreference[]): WorkspacePreference[] {
|
||||
return Array.isArray(saved)
|
||||
? saved.filter(
|
||||
(entry) => entry && typeof entry.key === 'string' && typeof entry.workspaceId === 'string',
|
||||
)
|
||||
: [];
|
||||
}
|
||||
|
||||
/** Browser-local hints, never authorization or conversation bindings. */
|
||||
export function useWorkspacePreferences(agentId?: string | null) {
|
||||
const { user } = useAuthContext();
|
||||
const [saved, setSaved] = useAtom(preferences);
|
||||
const keyFor = (environmentId: string, ownerAgentId = agentId) =>
|
||||
JSON.stringify([user?.tenantId ?? '', user?.id, ownerAgentId, environmentId]);
|
||||
const entries = validEntries(saved);
|
||||
return {
|
||||
get: (environmentId: string, ownerAgentId = agentId) =>
|
||||
user?.id && ownerAgentId
|
||||
? entries.find((entry) => entry.key === keyFor(environmentId, ownerAgentId))?.workspaceId
|
||||
: undefined,
|
||||
remember: (environmentId: string, workspaceId: string, ownerAgentIds = [agentId]) => {
|
||||
if (!user?.id) return;
|
||||
const keys = ownerAgentIds
|
||||
.filter((ownerAgentId): ownerAgentId is string => Boolean(ownerAgentId))
|
||||
.map((ownerAgentId) => keyFor(environmentId, ownerAgentId));
|
||||
if (keys.length === 0) return;
|
||||
// Bound this browser's disposable MRU cache; evictions only restore the chooser.
|
||||
try {
|
||||
setSaved((current) =>
|
||||
[
|
||||
...keys.map((key) => ({ key, workspaceId })),
|
||||
...validEntries(current).filter((entry) => !keys.includes(entry.key)),
|
||||
].slice(0, 100),
|
||||
);
|
||||
} catch {
|
||||
// Disabled or full browser storage must not prevent explicit workspace selection.
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -25,6 +25,7 @@ const mockResolveCodeWorkspaceSubmission = jest.fn<
|
|||
>(() => ({}));
|
||||
const mockCodeWorkspace = {
|
||||
resolveSubmission: mockResolveCodeWorkspaceSubmission,
|
||||
rememberSelection: jest.fn(),
|
||||
};
|
||||
|
||||
jest.mock('react-router-dom', () => ({
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
import { renderHook, act } from '@testing-library/react';
|
||||
import { Constants, EModelEndpoint } from 'librechat-data-provider';
|
||||
import type { TConversation } from 'librechat-data-provider';
|
||||
|
||||
const mockDeleteFiles = jest.fn();
|
||||
const mockSetFiles = jest.fn();
|
||||
|
|
@ -113,7 +115,53 @@ jest.mock('~/store', () => ({
|
|||
},
|
||||
}));
|
||||
|
||||
import useNewConvo from '../useNewConvo';
|
||||
import useNewConvo, { clearInheritedAgentWorkspace } from '../useNewConvo';
|
||||
|
||||
describe('clearInheritedAgentWorkspace', () => {
|
||||
const workspaceBinding = [{ environmentId: 'machine-a', workspaceId: 'project-a' }];
|
||||
|
||||
it('clears a workspace inherited by a new chat when the agent changes', () => {
|
||||
expect(
|
||||
clearInheritedAgentWorkspace(
|
||||
{
|
||||
conversationId: Constants.NEW_CONVO,
|
||||
endpoint: EModelEndpoint.agents,
|
||||
agent_id: 'agent-b',
|
||||
codeWorkspaces: workspaceBinding,
|
||||
} as TConversation,
|
||||
{ agent_id: 'agent-a' } as TConversation,
|
||||
).codeWorkspaces,
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it('preserves an existing conversation workspace binding', () => {
|
||||
expect(
|
||||
clearInheritedAgentWorkspace(
|
||||
{
|
||||
conversationId: 'conversation-1',
|
||||
endpoint: EModelEndpoint.agents,
|
||||
agent_id: 'agent-b',
|
||||
codeWorkspaces: workspaceBinding,
|
||||
} as TConversation,
|
||||
{ agent_id: 'agent-a' } as TConversation,
|
||||
).codeWorkspaces,
|
||||
).toEqual(workspaceBinding);
|
||||
});
|
||||
|
||||
it('preserves a new-chat workspace binding when the agent is unchanged', () => {
|
||||
expect(
|
||||
clearInheritedAgentWorkspace(
|
||||
{
|
||||
conversationId: Constants.NEW_CONVO,
|
||||
endpoint: EModelEndpoint.agents,
|
||||
agent_id: 'agent-a',
|
||||
codeWorkspaces: workspaceBinding,
|
||||
} as TConversation,
|
||||
{ agent_id: 'agent-a' } as TConversation,
|
||||
).codeWorkspaces,
|
||||
).toEqual(workspaceBinding);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useNewConvo reset cleanup', () => {
|
||||
beforeEach(() => {
|
||||
|
|
|
|||
|
|
@ -58,6 +58,18 @@ import { usePauseGlobalAudio } from './Audio';
|
|||
import { useHasAccess } from '~/hooks';
|
||||
import store from '~/store';
|
||||
|
||||
export function clearInheritedAgentWorkspace(
|
||||
conversation: TConversation,
|
||||
previousConversation?: TConversation | null,
|
||||
): TConversation {
|
||||
const startsNewAgentConversation =
|
||||
conversation.conversationId === Constants.NEW_CONVO &&
|
||||
conversation.agent_id != null &&
|
||||
conversation.agent_id !== previousConversation?.agent_id;
|
||||
|
||||
return startsNewAgentConversation ? { ...conversation, codeWorkspaces: undefined } : conversation;
|
||||
}
|
||||
|
||||
const useNewConvo = (index = 0) => {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
|
|
@ -349,7 +361,7 @@ const useNewConvo = (index = 0) => {
|
|||
? { endpoint: _template.endpoint, chatProjectId: _template.chatProjectId }
|
||||
: _template;
|
||||
|
||||
const conversation = {
|
||||
let conversation = {
|
||||
conversationId: Constants.NEW_CONVO as string,
|
||||
title: 'New Chat',
|
||||
endpoint: null,
|
||||
|
|
@ -373,6 +385,7 @@ const useNewConvo = (index = 0) => {
|
|||
}
|
||||
|
||||
const prevConversation = getConversation();
|
||||
conversation = clearInheritedAgentWorkspace(conversation, prevConversation);
|
||||
applyModelSpecEffects({
|
||||
startupConfig,
|
||||
specName: preset?.spec,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
{
|
||||
"com_ui_code_workspace_default": "Default workspace for new chats",
|
||||
"com_ui_code_workspace_last_used": "Last used workspace",
|
||||
"com_ui_code_workspace_default_description": "New chats use this workspace. Without a default, reuse your last available choice for this agent and machine in this browser. Existing chats keep their workspace.",
|
||||
"com_ui_schedule_mcp_ready": "Ready for scheduled chats",
|
||||
"com_ui_schedule_mcp_reauth": "Reconnect this MCP server before enabling the schedule.",
|
||||
"com_ui_schedule_mcp_configuration": "Configure or remove this MCP server before enabling the schedule.",
|
||||
|
|
|
|||
|
|
@ -77,6 +77,7 @@ export * from './activityLabels';
|
|||
export * from './activityPhases';
|
||||
export * from './subagentDelivery';
|
||||
export * from './view';
|
||||
export * from './workspace';
|
||||
export * from './reasoningLabels';
|
||||
export * from './refusal';
|
||||
export * from './toolValidation';
|
||||
|
|
|
|||
|
|
@ -279,6 +279,7 @@ export function projectAgentManagementResponse(
|
|||
stateful_code_sessions: source.stateful_code_sessions,
|
||||
stateful_code_environment: source.stateful_code_environment,
|
||||
code_environment_id: source.code_environment_id,
|
||||
code_workspace_id: source.code_workspace_id,
|
||||
git_identity: source.git_identity,
|
||||
artifacts: source.artifacts,
|
||||
recursion_limit: source.recursion_limit,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
CODE_WORKSPACE_ID_PATTERN,
|
||||
MemoryScope,
|
||||
SkillsScope,
|
||||
getMaxSubagents,
|
||||
|
|
@ -25,6 +26,11 @@ import type { Request, Response } from 'express';
|
|||
*/
|
||||
type LooseRequest = Request<unknown, unknown, unknown>;
|
||||
|
||||
const agentCodeWorkspaceIdSchema: z.ZodUnion<[z.ZodLiteral<''>, z.ZodString]> = z.union([
|
||||
z.literal(''),
|
||||
z.string().regex(CODE_WORKSPACE_ID_PATTERN),
|
||||
]);
|
||||
|
||||
/** Avatar schema shared between create and update */
|
||||
export const agentAvatarSchema: z.ZodObject<
|
||||
{
|
||||
|
|
@ -500,6 +506,7 @@ export const agentBaseSchema: z.ZodObject<
|
|||
stateful_code_sessions: z.ZodOptional<z.ZodBoolean>;
|
||||
stateful_code_environment: z.ZodOptional<z.ZodEnum<['user', 'agent-user', 'conversation']>>;
|
||||
code_environment_id: z.ZodOptional<z.ZodString>;
|
||||
code_workspace_id: z.ZodOptional<typeof agentCodeWorkspaceIdSchema>;
|
||||
git_identity: typeof agentGitIdentitySchema;
|
||||
artifacts: z.ZodOptional<z.ZodString>;
|
||||
recursion_limit: z.ZodOptional<z.ZodNumber>;
|
||||
|
|
@ -576,6 +583,7 @@ export const agentBaseSchema: z.ZodObject<
|
|||
stateful_code_sessions: z.boolean().optional(),
|
||||
stateful_code_environment: z.enum(['user', 'agent-user', 'conversation']).optional(),
|
||||
code_environment_id: agentCodeEnvironmentIdSchema.optional(),
|
||||
code_workspace_id: agentCodeWorkspaceIdSchema.optional(),
|
||||
git_identity: agentGitIdentitySchema,
|
||||
artifacts: z.string().optional(),
|
||||
recursion_limit: z.number().optional(),
|
||||
|
|
@ -676,6 +684,7 @@ export const agentCreateSchema: z.ZodObject<
|
|||
stateful_code_environment: z.ZodOptional<z.ZodEnum<['user', 'agent-user', 'conversation']>>;
|
||||
code_environment_id: z.ZodOptional<z.ZodString>;
|
||||
git_identity: typeof agentGitIdentitySchema;
|
||||
code_workspace_id: z.ZodOptional<typeof agentCodeWorkspaceIdSchema>;
|
||||
artifacts: z.ZodOptional<z.ZodString>;
|
||||
recursion_limit: z.ZodOptional<z.ZodNumber>;
|
||||
conversation_starters: z.ZodOptional<z.ZodArray<z.ZodString, 'many'>>;
|
||||
|
|
@ -810,6 +819,7 @@ export const agentUpdateSchema: z.ZodObject<
|
|||
stateful_code_sessions: z.ZodOptional<z.ZodBoolean>;
|
||||
stateful_code_environment: z.ZodOptional<z.ZodEnum<['user', 'agent-user', 'conversation']>>;
|
||||
code_environment_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
||||
code_workspace_id: z.ZodOptional<typeof agentCodeWorkspaceIdSchema>;
|
||||
git_identity: typeof agentGitIdentityUpdateSchema;
|
||||
artifacts: z.ZodOptional<z.ZodString>;
|
||||
recursion_limit: z.ZodOptional<z.ZodNumber>;
|
||||
|
|
@ -895,6 +905,7 @@ export const agentUpdateSchema: z.ZodObject<
|
|||
> = agentBaseSchema.extend({
|
||||
avatar: z.union([agentAvatarSchema, z.null()]).optional(),
|
||||
code_environment_id: agentCodeEnvironmentIdSchema.nullable().optional(),
|
||||
code_workspace_id: agentCodeWorkspaceIdSchema.optional(),
|
||||
git_identity: agentGitIdentityUpdateSchema,
|
||||
provider: z.string().optional(),
|
||||
model: z.string().nullable().optional(),
|
||||
|
|
|
|||
18
packages/api/src/agents/workspace-default.spec.ts
Normal file
18
packages/api/src/agents/workspace-default.spec.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { agentUpdateSchema } from './validation';
|
||||
|
||||
describe('agent workspace default', () => {
|
||||
it('retains a default and an explicit reset through update validation', () => {
|
||||
expect(agentUpdateSchema.parse({ code_workspace_id: 'primary' }).code_workspace_id).toBe(
|
||||
'primary',
|
||||
);
|
||||
expect(agentUpdateSchema.parse({ code_workspace_id: '' }).code_workspace_id).toBe('');
|
||||
expect(agentUpdateSchema.parse({}).code_workspace_id).toBeUndefined();
|
||||
});
|
||||
|
||||
it('rejects malformed or non-string defaults', () => {
|
||||
expect(agentUpdateSchema.safeParse({ code_workspace_id: 'x'.repeat(129) }).success).toBe(false);
|
||||
expect(agentUpdateSchema.safeParse({ code_workspace_id: 'bad workspace' }).success).toBe(false);
|
||||
expect(agentUpdateSchema.safeParse({ code_workspace_id: '../escape' }).success).toBe(false);
|
||||
expect(agentUpdateSchema.safeParse({ code_workspace_id: {} }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
104
packages/api/src/agents/workspace.spec.ts
Normal file
104
packages/api/src/agents/workspace.spec.ts
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import {
|
||||
AGENT_WORKSPACE_ATTACHED_ENVIRONMENT_ERROR,
|
||||
reconcileAgentWorkspaceDefault,
|
||||
validateAgentWorkspaceDefaultBinding,
|
||||
} from './workspace';
|
||||
|
||||
describe('reconcileAgentWorkspaceDefault', () => {
|
||||
it('clears a stale default when the attached environment changes', () => {
|
||||
expect(
|
||||
reconcileAgentWorkspaceDefault({
|
||||
update: { code_environment_id: 'machine-b' },
|
||||
request: { code_environment_id: 'machine-b' },
|
||||
currentEnvironmentId: 'machine-a',
|
||||
}),
|
||||
).toEqual({ code_environment_id: 'machine-b', code_workspace_id: '' });
|
||||
});
|
||||
|
||||
it('preserves an explicit replacement default', () => {
|
||||
expect(
|
||||
reconcileAgentWorkspaceDefault({
|
||||
update: { code_environment_id: 'machine-b', code_workspace_id: 'project-b' },
|
||||
request: { code_environment_id: 'machine-b', code_workspace_id: 'project-b' },
|
||||
currentEnvironmentId: 'machine-a',
|
||||
}),
|
||||
).toEqual({ code_environment_id: 'machine-b', code_workspace_id: 'project-b' });
|
||||
});
|
||||
|
||||
it('does not clear the default when an unchanged environment is resubmitted', () => {
|
||||
expect(
|
||||
reconcileAgentWorkspaceDefault({
|
||||
update: { code_environment_id: 'machine-a' },
|
||||
request: { code_environment_id: 'machine-a' },
|
||||
currentEnvironmentId: 'machine-a',
|
||||
}),
|
||||
).toEqual({ code_environment_id: 'machine-a' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateAgentWorkspaceDefaultBinding', () => {
|
||||
const environments = [
|
||||
{ id: 'attached-vm', type: 'attached' },
|
||||
{ id: 'managed-runtime', type: 'managed' },
|
||||
];
|
||||
|
||||
it('accepts a new default bound to an explicit attached environment', () => {
|
||||
expect(
|
||||
validateAgentWorkspaceDefaultBinding({
|
||||
workspaceId: 'project-a',
|
||||
environmentId: 'attached-vm',
|
||||
environments,
|
||||
}),
|
||||
).toEqual({ valid: true });
|
||||
});
|
||||
|
||||
it.each([
|
||||
['an omitted environment', undefined],
|
||||
['a managed environment', 'managed-runtime'],
|
||||
['an unconfigured environment', 'missing-vm'],
|
||||
])('rejects a new default bound to %s', (_label, environmentId) => {
|
||||
expect(
|
||||
validateAgentWorkspaceDefaultBinding({
|
||||
workspaceId: 'project-a',
|
||||
environmentId,
|
||||
environments,
|
||||
}),
|
||||
).toEqual({ valid: false, error: AGENT_WORKSPACE_ATTACHED_ENVIRONMENT_ERROR });
|
||||
});
|
||||
|
||||
it('skips an unchanged binding after its environment is removed', () => {
|
||||
expect(
|
||||
validateAgentWorkspaceDefaultBinding({
|
||||
workspaceId: 'project-a',
|
||||
environmentId: 'removed-vm',
|
||||
currentWorkspaceId: 'project-a',
|
||||
currentEnvironmentId: 'removed-vm',
|
||||
environments,
|
||||
}),
|
||||
).toEqual({ valid: true });
|
||||
});
|
||||
|
||||
it('revalidates the same workspace when it is rebound to another environment', () => {
|
||||
expect(
|
||||
validateAgentWorkspaceDefaultBinding({
|
||||
workspaceId: 'project-a',
|
||||
environmentId: 'managed-runtime',
|
||||
currentWorkspaceId: 'project-a',
|
||||
currentEnvironmentId: 'attached-vm',
|
||||
environments,
|
||||
}),
|
||||
).toEqual({ valid: false, error: AGENT_WORKSPACE_ATTACHED_ENVIRONMENT_ERROR });
|
||||
});
|
||||
|
||||
it('allows clearing a stale default', () => {
|
||||
expect(
|
||||
validateAgentWorkspaceDefaultBinding({
|
||||
workspaceId: '',
|
||||
environmentId: 'removed-vm',
|
||||
currentWorkspaceId: 'project-a',
|
||||
currentEnvironmentId: 'removed-vm',
|
||||
environments,
|
||||
}),
|
||||
).toEqual({ valid: true });
|
||||
});
|
||||
});
|
||||
85
packages/api/src/agents/workspace.ts
Normal file
85
packages/api/src/agents/workspace.ts
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
interface AgentWorkspaceUpdate {
|
||||
code_environment_id?: string | null;
|
||||
code_workspace_id?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
interface AgentWorkspaceEnvironment {
|
||||
id: string;
|
||||
type?: string;
|
||||
}
|
||||
|
||||
export const AGENT_WORKSPACE_ATTACHED_ENVIRONMENT_ERROR =
|
||||
'Code workspace defaults require an explicit attached code environment';
|
||||
|
||||
export function shouldValidateAgentWorkspaceDefaultBinding({
|
||||
workspaceId,
|
||||
environmentId,
|
||||
currentWorkspaceId,
|
||||
currentEnvironmentId,
|
||||
}: {
|
||||
workspaceId?: string;
|
||||
environmentId?: string | null;
|
||||
currentWorkspaceId?: string;
|
||||
currentEnvironmentId?: string | null;
|
||||
}): boolean {
|
||||
return Boolean(
|
||||
workspaceId &&
|
||||
(workspaceId !== currentWorkspaceId ||
|
||||
(environmentId ?? undefined) !== (currentEnvironmentId ?? undefined)),
|
||||
);
|
||||
}
|
||||
|
||||
/** Validate only a newly selected or rebound machine-scoped workspace default. */
|
||||
export function validateAgentWorkspaceDefaultBinding({
|
||||
workspaceId,
|
||||
environmentId,
|
||||
currentWorkspaceId,
|
||||
currentEnvironmentId,
|
||||
environments,
|
||||
}: {
|
||||
workspaceId?: string;
|
||||
environmentId?: string | null;
|
||||
currentWorkspaceId?: string;
|
||||
currentEnvironmentId?: string | null;
|
||||
environments?: readonly AgentWorkspaceEnvironment[];
|
||||
}): { valid: true } | { valid: false; error: string } {
|
||||
if (
|
||||
!shouldValidateAgentWorkspaceDefaultBinding({
|
||||
workspaceId,
|
||||
environmentId,
|
||||
currentWorkspaceId,
|
||||
currentEnvironmentId,
|
||||
})
|
||||
) {
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
const configuredEnvironment = environments?.find(
|
||||
(environment) => environment.id === (environmentId ?? undefined),
|
||||
);
|
||||
if (configuredEnvironment?.type === 'attached') {
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
return { valid: false, error: AGENT_WORKSPACE_ATTACHED_ENVIRONMENT_ERROR };
|
||||
}
|
||||
|
||||
/** Clear a machine-scoped default when its environment changes without a replacement default. */
|
||||
export function reconcileAgentWorkspaceDefault<T extends AgentWorkspaceUpdate>({
|
||||
update,
|
||||
request,
|
||||
currentEnvironmentId,
|
||||
}: {
|
||||
update: T;
|
||||
request: AgentWorkspaceUpdate;
|
||||
currentEnvironmentId?: string | null;
|
||||
}): T {
|
||||
const changesEnvironment =
|
||||
Object.prototype.hasOwnProperty.call(request, 'code_environment_id') &&
|
||||
request.code_environment_id !== currentEnvironmentId;
|
||||
if (!changesEnvironment || Object.prototype.hasOwnProperty.call(request, 'code_workspace_id')) {
|
||||
return update;
|
||||
}
|
||||
return { ...update, code_workspace_id: '' };
|
||||
}
|
||||
|
|
@ -386,6 +386,7 @@ export const defaultAgentFormValues = {
|
|||
[Tools.memory]: false,
|
||||
stateful_code_environment: 'user' as const,
|
||||
code_environment_id: undefined as string | null | undefined,
|
||||
code_workspace_id: undefined as string | undefined,
|
||||
category: 'general',
|
||||
support_contact: {
|
||||
name: '',
|
||||
|
|
|
|||
|
|
@ -364,6 +364,8 @@ export type Agent = {
|
|||
stateful_code_environment?: StatefulCodeEnvironment;
|
||||
/** Operator-configured managed or attached stateful execution environment. */
|
||||
code_environment_id?: string | null;
|
||||
/** Default attached workspace for new chats; empty means no agent default. */
|
||||
code_workspace_id?: string;
|
||||
/** Non-secret Git authorship injected into this agent's sandboxed commands. */
|
||||
git_identity?: AgentGitIdentity | null;
|
||||
artifacts?: ArtifactModes;
|
||||
|
|
@ -427,6 +429,7 @@ export type AgentCreateParams = {
|
|||
| 'stateful_code_sessions'
|
||||
| 'stateful_code_environment'
|
||||
| 'code_environment_id'
|
||||
| 'code_workspace_id'
|
||||
| 'artifacts'
|
||||
| 'recursion_limit'
|
||||
| 'category'
|
||||
|
|
@ -461,6 +464,7 @@ export type AgentUpdateParams = {
|
|||
| 'stateful_code_environment'
|
||||
| 'code_environment_id'
|
||||
| 'git_identity'
|
||||
| 'code_workspace_id'
|
||||
| 'artifacts'
|
||||
| 'recursion_limit'
|
||||
| 'category'
|
||||
|
|
|
|||
|
|
@ -2440,6 +2440,22 @@ describe('Agent Methods', () => {
|
|||
expect(updated!.versions![1].code_environment_id).toBeUndefined();
|
||||
});
|
||||
|
||||
test('persists and restores the workspace default without retaining a later preference', async () => {
|
||||
const agentId = `agent_${uuidv4()}`;
|
||||
await createAgent({
|
||||
id: agentId,
|
||||
provider: 'test',
|
||||
model: 'test-model',
|
||||
author: new mongoose.Types.ObjectId(),
|
||||
});
|
||||
await updateAgent({ id: agentId }, { code_workspace_id: 'project-a' });
|
||||
expect((await getAgent({ id: agentId }))?.code_workspace_id).toBe('project-a');
|
||||
await updateAgent({ id: agentId }, { code_workspace_id: '' });
|
||||
expect((await getAgent({ id: agentId }))?.code_workspace_id).toBe('');
|
||||
expect((await revertAgentVersion({ id: agentId }, 1))?.code_workspace_id).toBe('project-a');
|
||||
expect((await revertAgentVersion({ id: agentId }, 0))?.code_workspace_id).toBeUndefined();
|
||||
});
|
||||
|
||||
test('should handle parameter objects correctly', async () => {
|
||||
const agentId = `agent_${uuidv4()}`;
|
||||
const authorId = new mongoose.Types.ObjectId();
|
||||
|
|
@ -5005,6 +5021,69 @@ describe('Support Contact Field', () => {
|
|||
expect(result.data[0].conversation_starters).toEqual(starters);
|
||||
});
|
||||
|
||||
test('should include workspace execution metadata only when explicitly requested', async () => {
|
||||
const scopedAgent = await createAgent({
|
||||
id: `agent_${uuidv4().slice(0, 12)}`,
|
||||
name: 'Workspace Agent',
|
||||
description: 'Agent with attached workspace defaults',
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
author: userA,
|
||||
tools: [EToolResources.execute_code, 'private_mcp_tool'],
|
||||
stateful_code_sessions: true,
|
||||
code_environment_id: 'machine-a',
|
||||
code_workspace_id: 'project-a',
|
||||
agent_ids: [agentA1.id],
|
||||
edges: [{ from: 'source', to: agentA1.id, prompt: 'Private routing prompt' }],
|
||||
subagents: {
|
||||
enabled: true,
|
||||
agent_ids: [agentA1.id],
|
||||
graphs: [
|
||||
{
|
||||
type: 'collapsed_team',
|
||||
name: 'Private graph name',
|
||||
agent_ids: [agentA1.id],
|
||||
edges: [],
|
||||
entry_agent_id: agentA1.id,
|
||||
result_agent_id: agentA1.id,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const defaultResult = await getListAgentsByAccess({
|
||||
accessibleIds: [scopedAgent._id] as mongoose.Types.ObjectId[],
|
||||
otherParams: {},
|
||||
});
|
||||
expect(defaultResult.data[0].tools).toBeUndefined();
|
||||
expect(defaultResult.data[0].code_workspace_id).toBeUndefined();
|
||||
expect(defaultResult.data[0].edges).toBeUndefined();
|
||||
|
||||
const result = await getListAgentsByAccess({
|
||||
accessibleIds: [scopedAgent._id] as mongoose.Types.ObjectId[],
|
||||
otherParams: {},
|
||||
includeExecutionConfig: true,
|
||||
});
|
||||
|
||||
expect(result.data[0]).toMatchObject({
|
||||
tools: [EToolResources.execute_code],
|
||||
stateful_code_sessions: true,
|
||||
code_environment_id: 'machine-a',
|
||||
code_workspace_id: 'project-a',
|
||||
agent_ids: [agentA1.id],
|
||||
edges: [{ from: 'source', to: agentA1.id }],
|
||||
subagents: {
|
||||
enabled: true,
|
||||
agent_ids: [agentA1.id],
|
||||
graphs: [{ agent_ids: [agentA1.id] }],
|
||||
},
|
||||
});
|
||||
expect(result.data[0].tools).not.toContain('private_mcp_tool');
|
||||
expect(result.data[0].edges).not.toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ prompt: expect.anything() })]),
|
||||
);
|
||||
});
|
||||
|
||||
test('should return multiple accessible agents when provided', async () => {
|
||||
// Give User B access to two of User A's agents
|
||||
const accessibleIds = [agentA1._id, agentA3._id] as mongoose.Types.ObjectId[];
|
||||
|
|
|
|||
|
|
@ -604,12 +604,14 @@ export function createAgentMethods(
|
|||
limit,
|
||||
after,
|
||||
includeSkillConfig,
|
||||
includeExecutionConfig,
|
||||
}: {
|
||||
accessibleIds?: Types.ObjectId[];
|
||||
otherParams?: Record<string, unknown>;
|
||||
limit?: number | null;
|
||||
after?: string | null;
|
||||
includeSkillConfig?: boolean;
|
||||
includeExecutionConfig?: boolean;
|
||||
}) => Promise<{
|
||||
object: string;
|
||||
data: Array<Record<string, unknown>>;
|
||||
|
|
@ -1352,12 +1354,14 @@ export function createAgentMethods(
|
|||
limit = 100,
|
||||
after = null,
|
||||
includeSkillConfig = false,
|
||||
includeExecutionConfig = false,
|
||||
}: {
|
||||
accessibleIds?: Types.ObjectId[];
|
||||
otherParams?: Record<string, unknown>;
|
||||
limit?: number | null;
|
||||
after?: string | null;
|
||||
includeSkillConfig?: boolean;
|
||||
includeExecutionConfig?: boolean;
|
||||
}): Promise<{
|
||||
object: string;
|
||||
data: Array<Record<string, unknown>>;
|
||||
|
|
@ -1425,6 +1429,18 @@ export function createAgentMethods(
|
|||
projection.skill_authoring_enabled = 1;
|
||||
projection.skills_scope = 1;
|
||||
}
|
||||
if (includeExecutionConfig) {
|
||||
projection.tools = 1;
|
||||
projection.stateful_code_sessions = 1;
|
||||
projection.code_environment_id = 1;
|
||||
projection.code_workspace_id = 1;
|
||||
projection.agent_ids = 1;
|
||||
projection['edges.from'] = 1;
|
||||
projection['edges.to'] = 1;
|
||||
projection['subagents.enabled'] = 1;
|
||||
projection['subagents.agent_ids'] = 1;
|
||||
projection['subagents.graphs.agent_ids'] = 1;
|
||||
}
|
||||
|
||||
let query = Agent.find(baseQuery, projection).sort({ updatedAt: -1, _id: 1 });
|
||||
|
||||
|
|
@ -1437,6 +1453,12 @@ export function createAgentMethods(
|
|||
const hasMore = isPaginated && normalizedLimit ? agents.length > normalizedLimit : false;
|
||||
const data = (isPaginated && normalizedLimit ? agents.slice(0, normalizedLimit) : agents).map(
|
||||
(agent) => {
|
||||
if (includeExecutionConfig) {
|
||||
agent.tools =
|
||||
Array.isArray(agent.tools) && agent.tools.includes(EToolResources.execute_code)
|
||||
? [EToolResources.execute_code]
|
||||
: [];
|
||||
}
|
||||
if (agent.author) {
|
||||
agent.author = (agent.author as Types.ObjectId).toString();
|
||||
}
|
||||
|
|
@ -1578,6 +1600,7 @@ export function createAgentMethods(
|
|||
const unsetOnRestore: Record<string, 1> = {};
|
||||
for (const field of [
|
||||
'code_environment_id',
|
||||
'code_workspace_id',
|
||||
'git_identity',
|
||||
'skills_scope',
|
||||
'skill_authoring_enabled',
|
||||
|
|
|
|||
|
|
@ -94,6 +94,7 @@ const agentSchema: Schema<IAgent> = new Schema<IAgent>(
|
|||
code_environment_id: {
|
||||
type: String,
|
||||
},
|
||||
code_workspace_id: { type: String },
|
||||
git_identity: {
|
||||
type: new Schema(
|
||||
{
|
||||
|
|
|
|||
10
packages/data-schemas/src/schema/agentWorkspace.spec.ts
Normal file
10
packages/data-schemas/src/schema/agentWorkspace.spec.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import { model, models } from 'mongoose';
|
||||
import agentSchema from './agent';
|
||||
|
||||
it('retains the agent workspace preference and explicit reset through serialization', () => {
|
||||
const Agent = models.WorkspaceDefaultAgent ?? model('WorkspaceDefaultAgent', agentSchema);
|
||||
const agent = new Agent({ code_environment_id: 'machine-a', code_workspace_id: 'project-a' });
|
||||
expect(new Agent(agent.toObject()).toObject().code_workspace_id).toBe('project-a');
|
||||
agent.code_workspace_id = '';
|
||||
expect(new Agent(agent.toObject()).toObject().code_workspace_id).toBe('');
|
||||
});
|
||||
|
|
@ -43,6 +43,7 @@ export interface IAgent extends Omit<Document, 'model'> {
|
|||
stateful_code_sessions?: boolean;
|
||||
stateful_code_environment?: 'user' | 'agent-user' | 'conversation';
|
||||
code_environment_id?: string;
|
||||
code_workspace_id?: string;
|
||||
git_identity?: AgentGitIdentity | null;
|
||||
/** @deprecated Use edges instead */
|
||||
agent_ids?: string[];
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue