Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

Merge commit from fork

Pasqual Troncone4888447bbd49
diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.md
index 8cfd5b3d..24d28784 100644
--- a/apps/api/AGENTS.md
+++ b/apps/api/AGENTS.md
@@ -226,9 +226,13 @@ Two decisions a reader would otherwise propose again:
flag on the user. An agent is reachable through its team or not at all.
- **The `ai_agents` permissions are administrative.** A role granting `create` or `edit`
can make an agent, attach it to the projects the caller sees, and read its key — so
- granting either is granting everything an agent of those projects can reach. What the
- agents spent is a resource of its own, `agent_usage`, read only, so reading it
- administers nothing.
+ granting either is granting everything an agent of those projects can reach. Rotating
+ the key, editing or deleting the agent, setting its tools or skills, and reading,
+ rotating or testing its invocation secret act on it in every project it works in, so
+ they also take running the team or being a member of all of them
+ (`assertFullAgentAccess`). The agent's `canManage` reports the same rule to the caller,
+ so the web hides what the api would refuse. What the agents spent is a resource of its own,
+ `agent_usage`, read only, so reading it administers nothing.
- **An agent's role is its `project_member` row**, per project, set from the project's
member list like a person's. Attaching an agent joins it on the team's default role;
`members/` refuses to make it an owner, since an owner bypasses the matrix.
diff --git a/apps/api/src/modules/agents/core/__tests__/integration/agent-key-access.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/agent-key-access.test.ts
new file mode 100644
index 00000000..6c973135
--- /dev/null
+++ b/apps/api/src/modules/agents/core/__tests__/integration/agent-key-access.test.ts
@@ -0,0 +1,177 @@
+import { beforeEach, describe, expect, it } from 'bun:test';
+import { authedApi, createProject, type Api } from '#tests/helpers/app';
+import { createRole } from '#tests/helpers/roles';
+import { addProjectMember } from '#tests/helpers/members';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { createAgent, projectIdOf } from '#tests/helpers/agents';
+
+// Regenerating an agent's key, or editing the agent, acts on it across every project
+// it works in: the rotated key authenticates as the bot in all of them. The visibility
+// check needs only one shared project, so a member who shares just one must not reach
+// an agent that also works in a project they are not in.
+const agents = (api: Api, teamId: number) => api.teams({ teamId })['ai-agents'];
+
+async function setup() {
+ const owner = await signUpTestUser({ name: 'Owner' });
+ const asOwner = authedApi(owner.cookie);
+ const project = await createProject(asOwner, { key: 'MKT', name: 'Marketing' });
+ return { asOwner, teamId: project.data!.teamId };
+}
+
+async function handlerRole(asOwner: Api, projectKey: string): Promise<number> {
+ const role = await createRole(asOwner, projectKey, {
+ name: 'Agent handler',
+ permissions: {
+ ai_agents: { read: true, create: true, edit: true, delete: true },
+ agent_skills: { read: true, edit: true },
+ agent_tools: { read: true, edit: true },
+ },
+ });
+ return role.data!.id;
+}
+
+describe('agent key / edit requires access to all the agent projects', () => {
+ beforeEach(resetDb);
+
+ it('refuses regenerate-key to a member who shares only one of the agent projects', async () => {
+ const { asOwner, teamId } = await setup();
+ const ops = await asOwner.teams({ teamId }).projects.post({ key: 'OPS', name: 'Operations' });
+ const mkt = await projectIdOf(asOwner, 'MKT');
+ const created = await createAgent(asOwner, 'MKT', {
+ name: 'Bot',
+ username: 'bot',
+ kind: 'external',
+ projectIds: [mkt, ops.data!.id],
+ });
+ const agentId = created.data!.agent.id;
+ const asMember = await addProjectMember(asOwner, 'MKT', await handlerRole(asOwner, 'MKT'));
+
+ expect((await agents(asMember, teamId)({ agentId })['regenerate-key'].post()).status).toBe(403);
+ expect((await agents(asMember, teamId)({ agentId }).patch({ name: 'Renamed' })).status).toBe(
+ 403,
+ );
+ // Its tools, its skills and the agent itself reach the other projects too.
+ expect(
+ (await agents(asMember, teamId)({ agentId })['tool-configs'].put({ agentToolIds: [] }))
+ .status,
+ ).toBe(403);
+ expect((await agents(asMember, teamId)({ agentId }).skills.put({ skillIds: [] })).status).toBe(
+ 403,
+ );
+ expect((await agents(asMember, teamId)({ agentId }).delete()).status).toBe(403);
+ });
+
+ it('refuses the invocation secret to a member who shares only one of the agent projects', async () => {
+ const { asOwner, teamId } = await setup();
+ const ops = await asOwner.teams({ teamId }).projects.post({ key: 'OPS', name: 'Operations' });
+ const mkt = await projectIdOf(asOwner, 'MKT');
+ const created = await createAgent(asOwner, 'MKT', {
+ name: 'Bot',
+ username: 'bot',
+ kind: 'external',
+ projectIds: [mkt, ops.data!.id],
+ });
+ const agentId = created.data!.agent.id;
+ const asMember = await addProjectMember(asOwner, 'MKT', await handlerRole(asOwner, 'MKT'));
+ const agent = agents(asMember, teamId)({ agentId });
+
+ // The secret signs the work the agent runs in every project it works in.
+ expect((await agent['invocation-secret'].get()).status).toBe(403);
+ expect((await agent['invocation-secret'].post()).status).toBe(403);
+ expect((await agent['invocation-test'].post()).status).toBe(403);
+ expect((await agents(asOwner, teamId)({ agentId })['invocation-secret'].get()).status).toBe(
+ 200,
+ );
+ });
+
+ it('allows the team owner to regenerate the key', async () => {
+ const { asOwner, teamId } = await setup();
+ const ops = await asOwner.teams({ teamId }).projects.post({ key: 'OPS', name: 'Operations' });
+ const mkt = await projectIdOf(asOwner, 'MKT');
+ const created = await createAgent(asOwner, 'MKT', {
+ name: 'Bot',
+ username: 'bot',
+ kind: 'external',
+ projectIds: [mkt, ops.data!.id],
+ });
+
+ const res = await agents(
+ asOwner,
+ teamId,
+ )({ agentId: created.data!.agent.id })['regenerate-key'].post();
+ expect(res.status).toBe(200);
+ });
+
+ it('allows a member who is in every project the agent works in', async () => {
+ const { asOwner, teamId } = await setup();
+ const created = await createAgent(asOwner, 'MKT', {
+ name: 'Bot',
+ username: 'bot',
+ kind: 'external',
+ });
+ const asMember = await addProjectMember(asOwner, 'MKT', await handlerRole(asOwner, 'MKT'));
+ const agent = agents(asMember, teamId)({ agentId: created.data!.agent.id });
+
+ expect((await agent['regenerate-key'].post()).status).toBe(200);
+ expect((await agent.patch({ name: 'Renamed' })).status).toBe(200);
+ expect((await agent['tool-configs'].put({ agentToolIds: [] })).status).toBe(200);
+ expect((await agent.skills.put({ skillIds: [] })).status).toBe(200);
+ expect((await agent['invocation-secret'].get()).status).toBe(200);
+ expect((await agent.delete()).status).toBe(204);
+ });
+
+ it('allows a team manager who is in none of the agent projects', async () => {
+ const { asOwner, teamId } = await setup();
+ const ops = await asOwner.teams({ teamId }).projects.post({ key: 'OPS', name: 'Operations' });
+ const mkt = await projectIdOf(asOwner, 'MKT');
+ const created = await createAgent(asOwner, 'MKT', {
+ name: 'Bot',
+ username: 'bot',
+ kind: 'external',
+ projectIds: [mkt, ops.data!.id],
+ });
+ const manager = await signUpTestUser();
+ const invite = await asOwner
+ .teams({ teamId })
+ .invites.post({ email: manager.email, role: 'manager' });
+ const asManager = authedApi(manager.cookie);
+ await asManager.invites({ token: invite.data!.token }).accept.post();
+
+ const res = await agents(
+ asManager,
+ teamId,
+ )({ agentId: created.data!.agent.id })['regenerate-key'].post();
+ expect(res.status).toBe(200);
+ });
+
+ it('tells each caller whether they may act on the agent as a whole', async () => {
+ const { asOwner, teamId } = await setup();
+ const ops = await asOwner.teams({ teamId }).projects.post({ key: 'OPS', name: 'Operations' });
+ const mkt = await projectIdOf(asOwner, 'MKT');
+ const created = await createAgent(asOwner, 'MKT', {
+ name: 'Bot',
+ username: 'bot',
+ kind: 'external',
+ projectIds: [mkt, ops.data!.id],
+ });
+ const agentId = created.data!.agent.id;
+ expect(created.data!.agent.canManage).toBe(true);
+ const asPartial = await addProjectMember(asOwner, 'MKT', await handlerRole(asOwner, 'MKT'));
+
+ expect((await agents(asPartial, teamId)({ agentId }).get()).data).toMatchObject({
+ canManage: false,
+ });
+ expect((await agents(asPartial, teamId).get({ query: {} })).data).toEqual([
+ expect.objectContaining({ id: agentId, canManage: false }),
+ ]);
+ expect((await agents(asOwner, teamId)({ agentId }).get()).data).toMatchObject({
+ canManage: true,
+ });
+ const set = await agents(asOwner, teamId)({ agentId }).projects.put({ projectIds: [mkt] });
+ expect(set.data).toMatchObject({ canManage: true });
+ expect((await agents(asPartial, teamId)({ agentId }).get()).data).toMatchObject({
+ canManage: true,
+ });
+ });
+});
diff --git a/apps/api/src/modules/agents/core/index.ts b/apps/api/src/modules/agents/core/index.ts
index 1e251950..e9340414 100644
--- a/apps/api/src/modules/agents/core/index.ts
+++ b/apps/api/src/modules/agents/core/index.ts
@@ -20,6 +20,8 @@ import {
getAgentInProject,
agentScopeOf,
memberProjectIds,
+ assertFullAgentAccess,
+ withCanManage,
type AgentKind,
} from './service';
import {
@@ -195,8 +197,11 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
.use(guards)
.get(
'/teams/:teamId/ai-agents',
- ({ membership, query }) =>
- listAgents(membership.teamId, query.projectId, agentScopeOf(membership)),
+ async ({ membership, query }) =>
+ withCanManage(
+ membership,
+ await listAgents(membership.teamId, query.projectId, agentScopeOf(membership)),
+ ),
{
params: teamParams,
query: agentListQuery,
@@ -214,7 +219,12 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
.get(
'/teams/:teamId/ai-agents/:agentId',
- ({ params, membership }) => requireVisibleAgent(params.agentId, membership),
+ async ({ params, membership }) => {
+ const [agent] = await withCanManage(membership, [
+ await requireVisibleAgent(params.agentId, membership),
+ ]);
+ return agent;
+ },
{
params: agentParams,
teamPermission: ['ai_agents', 'read'],
@@ -235,11 +245,13 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
async ({ membership, body, set, user }) => {
const projectIds = await resolveAgentProjects(membership, body.projectIds, []);
set.status = 201;
- return createAgent(membership.teamId, {
+ const created = await createAgent(membership.teamId, {
...body,
projectIds,
ownerUserId: requireUser(user).id,
});
+ const [agent] = await withCanManage(membership, [created.agent]);
+ return { ...created, agent };
},
{
params: teamParams,
@@ -260,6 +272,7 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
'/teams/:teamId/ai-agents/:agentId',
async ({ params, membership, body, user }) => {
const current = await requireVisibleAgent(params.agentId, membership);
+ await assertFullAgentAccess(membership, params.agentId);
const projectIds = await resolveAgentProjects(membership, body.projectIds, current.projects);
const agent = await updateAgent(
params.agentId,
@@ -268,7 +281,8 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
requireUser(user).id,
);
if (!agent) throw new HttpError(404, 'Agent not found');
- return agent;
+ const [withAccess] = await withCanManage(membership, [agent]);
+ return withAccess;
},
{
body: updateAgentBody,
@@ -297,7 +311,8 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
requireUser(user).id,
);
if (!agent) throw new HttpError(404, 'Agent not found');
- return agent;
+ const [withAccess] = await withCanManage(membership, [agent]);
+ return withAccess;
},
{
body: setAgentProjectsBody,
@@ -321,6 +336,7 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
'/teams/:teamId/ai-agents/:agentId/regenerate-key',
async ({ params, membership }) => {
const agent = await requireVisibleAgent(params.agentId, membership);
+ await assertFullAgentAccess(membership, params.agentId);
if (agent.kind !== 'external')
throw new HttpError(400, 'Internal agents do not use an API key');
const apiKey = await regenerateKey(params.agentId, membership.teamId);
@@ -480,6 +496,7 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
'/teams/:teamId/ai-agents/:agentId',
async ({ params, membership }) => {
await requireVisibleAgent(params.agentId, membership);
+ await assertFullAgentAccess(membership, params.agentId);
const ok = await deleteAgent(params.agentId, membership.teamId);
if (!ok) throw new HttpError(404, 'Agent not found');
return noContent();
diff --git a/apps/api/src/modules/agents/core/model.ts b/apps/api/src/modules/agents/core/model.ts
index fd12b739..f61402aa 100644
--- a/apps/api/src/modules/agents/core/model.ts
+++ b/apps/api/src/modules/agents/core/model.ts
@@ -173,6 +173,13 @@ export const AiAgentResponse = t.Object({
actionCount: t.Number(),
skillCount: t.Number(),
toolCount: t.Number(),
+ canManage: t.Boolean({
+ description:
+ 'Whether you may act on the agent as a whole: rotate its key, edit or delete it, set its ' +
+ 'tools or skills, and read, rotate or test its invocation secret. Takes running the team ' +
+ 'or being a member of every project the agent works in; each action also needs its role ' +
+ 'permission.',
+ }),
});
// createAgent's result: the agent plus its one-time API key secret (null for an
diff --git a/apps/api/src/modules/agents/core/service.ts b/apps/api/src/modules/agents/core/service.ts
index dabe3043..f12c9e77 100644
--- a/apps/api/src/modules/agents/core/service.ts
+++ b/apps/api/src/modules/agents/core/service.ts
@@ -24,6 +24,7 @@ import { normalizeToolKeys, ALWAYS_ON_ACTIONS } from './runtime/tools/catalog';
import { deleteThreadsWhere } from './runtime/memory';
import { listAgentMemberFieldIds } from '#modules/custom-fields/service';
import { runsTeam, type TeamStanding } from '#modules/teams/service';
+import type { TeamMembership } from '#shared/access';
import { projectRefSql } from '#modules/teams/ref';
import { getDefaultRoleId } from '#modules/roles/service';
import { deleteAccount } from '#shared/account-deletion';
@@ -287,6 +288,42 @@ export async function memberProjectIds(teamId: number, userId: string): Promise<
return rows.map((row) => row.id);
}
+// The agents, each with whether the caller may act on it as a whole, by the rule
+// assertFullAgentAccess applies, so a screen can hide what the caller would be refused.
+export async function withCanManage<T extends { projects: { id: number }[] }>(
+ membership: TeamMembership,
+ agents: T[],
+): Promise<(T & { canManage: boolean })[]> {
+ const runs = runsTeam(membership.role);
+ const mine = new Set(runs ? [] : await memberProjectIds(membership.teamId, membership.userId));
+ return agents.map((agent) => ({
+ ...agent,
+ canManage: runs || agent.projects.every((p) => mine.has(p.id)),
+ }));
+}
+
+// Regenerating the key, editing the agent, changing its tools or skills, deleting it, or
+// reading its invocation secret acts on the agent in every project it works in — the key
+// authenticates as the bot in all of them, and the secret signs the work it runs there.
+// The visibility check only needs one shared project, so a caller who shares just one
+// must not reach the others: these require running the team or being a member of every
+// project the agent is in.
+export async function assertFullAgentAccess(
+ membership: TeamMembership,
+ agentId: number,
+): Promise<void> {
+ if (runsTeam(membership.role)) return;
+ const agent = await getAgentById(agentId, membership.teamId);
+ if (!agent) throw new HttpError(404, 'Agent not found');
+ const [{ canManage }] = await withCanManage(membership, [agent]);
+ if (!canManage) {
+ throw new HttpError(
+ 403,
+ 'Only a team owner or manager, or a member of every project the agent works in, can do this',
+ );
+ }
+}
+
// Whether the agent works in a project the user is a member of, as a condition on a
// query over ai_agent. Both sides are project_member rows: the agent's bot user and
// the user themselves.
diff --git a/apps/api/src/modules/agents/invocation/index.ts b/apps/api/src/modules/agents/invocation/index.ts
index abd59fa1..17bb4517 100644
--- a/apps/api/src/modules/agents/invocation/index.ts
+++ b/apps/api/src/modules/agents/invocation/index.ts
@@ -5,7 +5,7 @@ import type { TeamMembership } from '#shared/access';
import { HttpError } from '#shared/lib';
import { commonErrors } from '#shared/responses';
import { mcpTool } from '#mcp/generate';
-import { agentScopeOf, getAgentById } from '../core/service';
+import { agentScopeOf, assertFullAgentAccess, getAgentById } from '../core/service';
import {
agentParams,
InvocationSecretResponse,
@@ -19,6 +19,7 @@ import { testInvocation } from './service';
async function requireExternalAgent(agentId: number, membership: TeamMembership) {
const agent = await getAgentById(agentId, membership.teamId, agentScopeOf(membership));
if (!agent) throw new HttpError(404, 'Agent not found');
+ await assertFullAgentAccess(membership, agentId);
if (agent.kind !== 'external') {
throw new HttpError(400, 'Only an external agent is sent its work');
}
@@ -26,8 +27,9 @@ async function requireExternalAgent(agentId: number, membership: TeamMembership)
}
// What is needed to set up the endpoint at an external agent's invocation URL. Each
-// route requires `edit` on the agents: the secret lets its holder sign work for the
-// agent, and whoever may edit the agent can already point its URL anywhere.
+// route requires `edit` on the agents and the access editing the agent takes: the secret
+// lets its holder sign work the agent runs in every project it works in, and whoever may
+// edit the agent can already point its URL anywhere.
export const agentInvocationRoutes = new Elysia({
name: 'agent-invocation',
detail: { tags: ['AI Agents'] },
diff --git a/apps/api/src/modules/agents/skills/index.ts b/apps/api/src/modules/agents/skills/index.ts
index 8d2c96c0..7116bacc 100644
--- a/apps/api/src/modules/agents/skills/index.ts
+++ b/apps/api/src/modules/agents/skills/index.ts
@@ -42,7 +42,7 @@ import {
listAgentSkills,
setAgentSkills,
} from './service';
-import { agentInTeam, agentScopeOf } from '../core/service';
+import { agentInTeam, agentScopeOf, assertFullAgentAccess } from '../core/service';
// Reference-file bytes are capped like the skill markdown.
const MAX_REF_BYTES = MAX_SKILL_BYTES;
@@ -371,6 +371,7 @@ export const agentSkillRoutes = new Elysia({
if (!(await agentInTeam(params.agentId, membership.teamId, agentScopeOf(membership)))) {
throw new HttpError(404, 'Agent not found');
}
+ await assertFullAgentAccess(membership, params.agentId);
await setAgentSkills(params.agentId, membership.teamId, body.skillIds);
return listAgentSkills(params.agentId);
},
diff --git a/apps/api/src/modules/agents/tools/index.ts b/apps/api/src/modules/agents/tools/index.ts
index 835d2b24..a81ff250 100644
--- a/apps/api/src/modules/agents/tools/index.ts
+++ b/apps/api/src/modules/agents/tools/index.ts
@@ -7,7 +7,7 @@ import { accessErrors, commonErrors, errors } from '#shared/responses';
import { mcpTool } from '#mcp/generate';
import { paginate } from '#shared/pagination';
import { teamParams } from '#modules/teams/model';
-import { agentInTeam, agentScopeOf } from '../core/service';
+import { agentInTeam, agentScopeOf, assertFullAgentAccess } from '../core/service';
import { actionCatalog } from '../core/runtime/tools/route-tools';
import {
AgentToolListResponse,
@@ -157,6 +157,7 @@ export const agentToolRoutes = new Elysia({
if (!(await agentInTeam(params.agentId, membership.teamId, agentScopeOf(membership)))) {
throw new HttpError(404, 'Agent not found');
}
+ await assertFullAgentAccess(membership, params.agentId);
await setAgentTools(params.agentId, membership.teamId, body.agentToolIds);
return listAgentToolLinks(params.agentId);
},
diff --git a/apps/web/src/features/teams/components/ai-agents/AgentInvocationPanel.tsx b/apps/web/src/features/teams/components/ai-agents/AgentInvocationPanel.tsx
index bdc300c0..db7bf8c2 100644
--- a/apps/web/src/features/teams/components/ai-agents/AgentInvocationPanel.tsx
+++ b/apps/web/src/features/teams/components/ai-agents/AgentInvocationPanel.tsx
@@ -48,7 +48,8 @@ export default function AgentInvocationPanel({
{!agent || !saved ? (
<p className="text-xs text-muted-foreground">{t('invocationSecretOnSave')}</p>
) : (
- can('edit') && (
+ can('edit') &&
+ agent.canManage && (
<>
<AgentInvocationSecret agent={agent} />
<AgentInvocationTest agentId={agent.id} />
diff --git a/apps/web/src/features/teams/components/ai-agents/AgentSheetForm.test.tsx b/apps/web/src/features/teams/components/ai-agents/AgentSheetForm.test.tsx
new file mode 100644
index 00000000..ebce4a90
--- /dev/null
+++ b/apps/web/src/features/teams/components/ai-agents/AgentSheetForm.test.tsx
@@ -0,0 +1,162 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { act } from 'react';
+import type { Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { JSDOM } from 'jsdom';
+import type { AiAgent } from '@/lib/api/endpoints/agents';
+import teams from '../../../../../messages/en/teams.json';
+import common from '../../../../../messages/en/common.json';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { AgentSectionProvider } from '../../context/agentSection';
+
+// The sheet also opens for the test chat. It offers saving only to a viewer who may
+// change the agent: a role that edits agents, on an agent whose projects they all share.
+const replacedGlobals = [
+ 'window',
+ 'document',
+ 'navigator',
+ 'Node',
+ 'NodeFilter',
+ 'DocumentFragment',
+ 'Element',
+ 'HTMLElement',
+ 'HTMLButtonElement',
+ 'SVGElement',
+ 'ShadowRoot',
+ 'Event',
+ 'CustomEvent',
+ 'MouseEvent',
+ 'KeyboardEvent',
+ 'MutationObserver',
+ 'getComputedStyle',
+ 'requestAnimationFrame',
+ 'cancelAnimationFrame',
+ 'IS_REACT_ACT_ENVIRONMENT',
+ 'fetch',
+] as const;
+
+let dom: JSDOM;
+let root: Root;
+let originals: Map<string, PropertyDescriptor | undefined>;
+
+const agent = (canManage: boolean): AiAgent => ({
+ id: 4,
+ teamId: 1,
+ projects: [{ id: 1, key: 'MKT', ref: 'MKT', name: 'Marketing' }],
+ userId: 'bot',
+ name: 'Bot',
+ username: 'bot',
+ kind: 'internal',
+ modelCredentialId: null,
+ model: null,
+ instructions: null,
+ tools: [],
+ temperature: null,
+ reasoningEffort: null,
+ maxSteps: null,
+ runTimeoutSec: null,
+ memoryEnabled: false,
+ memoryLastMessages: null,
+ triggerOnMention: false,
+ triggerOnAssign: false,
+ fieldTriggers: [],
+ delegationDelaySec: 0,
+ ownerUserId: null,
+ runnerScope: 'team',
+ lastSeenAt: null,
+ invocationUrl: null,
+ createdAt: new Date(0).toISOString(),
+ apiKeyStart: null,
+ modelProvider: null,
+ actionCount: 0,
+ skillCount: 0,
+ toolCount: 0,
+ canManage,
+});
+
+async function render(row: AiAgent, edit = true) {
+ const { AgentSheetForm } = await import('./AgentSheetForm');
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ await act(async () =>
+ root.render(
+ <QueryClientProvider client={client}>
+ <NextIntlClientProvider locale="en" messages={{ teams, common }} timeZone="UTC">
+ <AgentSectionProvider
+ teamId={1}
+ permissions={{ read: true, create: true, edit, delete: true }}
+ >
+ <AgentSheetForm agent={row} onCreated={() => {}} />
+ </AgentSectionProvider>
+ </NextIntlClientProvider>
+ </QueryClientProvider>,
+ ),
+ );
+}
+
+const saveButton = () =>
+ [...document.querySelectorAll('button[type="submit"]')].find((b) =>
+ b.textContent?.includes(teams.agents.save),
+ );
+
+beforeEach(async () => {
+ originals = new Map(
+ replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),
+ );
+ dom = new JSDOM('<!doctype html><div id="root"></div>', {
+ url: 'https://example.test/',
+ pretendToBeVisual: true,
+ });
+ Object.assign(dom.window, {
+ __ITSAPLAN_ENV__: { apiUrl: 'http://api.test', privacyUrl: '', termsUrl: '' },
+ });
+ for (const name of replacedGlobals) {
+ if (name in dom.window) {
+ Object.defineProperty(globalThis, name, {
+ configurable: true,
+ value: dom.window[name as keyof typeof dom.window],
+ });
+ }
+ }
+ Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
+ configurable: true,
+ value: true,
+ });
+ Object.defineProperty(globalThis, 'fetch', {
+ configurable: true,
+ value: async () => Response.json({ error: 'Access denied' }, { status: 403 }),
+ });
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(document.querySelector('#root')!);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ // The instructions editor tears down after the unmount; let it run while the page exists.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ dom.window.close();
+ for (const [name, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+describe('AgentSheetForm', () => {
+ it('offers saving an agent the viewer may change', async () => {
+ await render(agent(true));
+
+ assert.ok(saveButton());
+ });
+
+ it('offers no saving on an agent the viewer may not manage', async () => {
+ await render(agent(false));
+
+ assert.equal(saveButton(), undefined);
+ });
+
+ it('offers no saving to a role that does not edit agents', async () => {
+ await render(agent(true), false);
+
+ assert.equal(saveButton(), undefined);
+ });
+});
diff --git a/apps/web/src/features/teams/components/ai-agents/AgentSheetForm.tsx b/apps/web/src/features/teams/components/ai-agents/AgentSheetForm.tsx
index 91fb31cd..683de2e8 100644
--- a/apps/web/src/features/teams/components/ai-agents/AgentSheetForm.tsx
+++ b/apps/web/src/features/teams/components/ai-agents/AgentSheetForm.tsx
@@ -30,7 +30,7 @@ import {
useSetAgentTools,
} from '@/services/customTools.service';
import { Button } from '@/components/ui/button';
-import { useAgentSection } from '../../context/agentSection';
+import { useAgentCan, useAgentSection } from '../../context/agentSection';
import { AgentCapabilityList } from './AgentCapabilityList';
import { AgentEmptyNotice } from './AgentEmptyNotice';
import TeamAiAgentFields, { AGENT_EXPANDED_WIDTH } from './TeamAiAgentFields';
@@ -67,6 +67,9 @@ export function AgentSheetForm({
const tCommon = useTranslations('common');
const [value, setValue] = useState<AgentFormValue>(() => initialAgentValue(agent ?? undefined));
const isCreate = agent == null;
+ // The sheet also opens for the test chat, to a viewer who may not change the agent.
+ const can = useAgentCan();
+ const canSave = isCreate || (can('edit') && agent.canManage);
// The plaintext key issued in this sheet, by the create or by a regenerate. It is
// shown once in the API key section and cannot be read back from the server.
const [revealedKey, setRevealedKey] = useState<string | null>(null);
@@ -325,7 +328,7 @@ export function AgentSheetForm({
className="flex h-full min-h-0 flex-col"
onSubmit={(e) => {
e.preventDefault();
- void submit();
+ if (canSave) void submit();
}}
>
{expanded ? (
@@ -335,17 +338,19 @@ export function AgentSheetForm({
<div className={`mx-auto w-full space-y-6 ${contentWidth}`}>{fields}</div>
</div>
)}
- <div className="border-t border-border/60 px-4 py-3 sm:px-6">
- <div className={`mx-auto flex w-full ${contentWidth} ${expanded ? 'justify-end' : ''}`}>
- <Button
- type="submit"
- className={expanded ? 'min-w-40' : 'w-full'}
- disabled={!isAgentFormValid(value) || saving}
- >
- {saving ? tCommon('saving') : isCreate ? t('create') : t('save')}
- </Button>
+ {canSave && (
+ <div className="border-t border-border/60 px-4 py-3 sm:px-6">
+ <div className={`mx-auto flex w-full ${contentWidth} ${expanded ? 'justify-end' : ''}`}>
+ <Button
+ type="submit"
+ className={expanded ? 'min-w-40' : 'w-full'}
+ disabled={!isAgentFormValid(value) || saving}
+ >
+ {saving ? tCommon('saving') : isCreate ? t('create') : t('save')}
+ </Button>
+ </div>
</div>
- </div>
+ )}
</form>
);
}
diff --git a/apps/web/src/features/teams/components/ai-agents/AgentTokenSection.tsx b/apps/web/src/features/teams/components/ai-agents/AgentTokenSection.tsx
index 41a25191..c79c1589 100644
--- a/apps/web/src/features/teams/components/ai-agents/AgentTokenSection.tsx
+++ b/apps/web/src/features/teams/components/ai-agents/AgentTokenSection.tsx
@@ -80,7 +80,7 @@ export default function AgentTokenSection({
{agent.apiKeyStart ?? '—'}
<span className="text-muted-foreground">••••••••</span>
</code>
- {can('edit') && (
+ {can('edit') && agent.canManage && (
<Button
type="button"
variant="outline"
diff --git a/apps/web/src/features/teams/components/ai-agents/TeamAiAgentRow.test.tsx b/apps/web/src/features/teams/components/ai-agents/TeamAiAgentRow.test.tsx
new file mode 100644
index 00000000..a94d4200
--- /dev/null
+++ b/apps/web/src/features/teams/components/ai-agents/TeamAiAgentRow.test.tsx
@@ -0,0 +1,169 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { act } from 'react';
+import type { Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { JSDOM } from 'jsdom';
+import type { AiAgent } from '@/lib/api/endpoints/agents';
+import teams from '../../../../../messages/en/teams.json';
+import common from '../../../../../messages/en/common.json';
+import { AgentSectionProvider } from '../../context/agentSection';
+
+// Editing or deleting an agent acts on it in every project it works in, so a member who
+// shares only some of them is offered neither, although their role may edit agents.
+const replacedGlobals = [
+ 'window',
+ 'document',
+ 'navigator',
+ 'Node',
+ 'NodeFilter',
+ 'DocumentFragment',
+ 'Element',
+ 'HTMLElement',
+ 'HTMLButtonElement',
+ 'SVGElement',
+ 'ShadowRoot',
+ 'Event',
+ 'CustomEvent',
+ 'MouseEvent',
+ 'KeyboardEvent',
+ 'MutationObserver',
+ 'getComputedStyle',
+ 'requestAnimationFrame',
+ 'cancelAnimationFrame',
+ 'IS_REACT_ACT_ENVIRONMENT',
+] as const;
+
+let dom: JSDOM;
+let root: Root;
+let originals: Map<string, PropertyDescriptor | undefined>;
+let edited = 0;
+
+const agent = (canManage: boolean): AiAgent => ({
+ id: 4,
+ teamId: 1,
+ projects: [{ id: 1, key: 'MKT', ref: 'MKT', name: 'Marketing' }],
+ userId: 'bot',
+ name: 'Bot',
+ username: 'bot',
+ kind: 'internal',
+ modelCredentialId: null,
+ model: null,
+ instructions: null,
+ tools: [],
+ temperature: null,
+ reasoningEffort: null,
+ maxSteps: null,
+ runTimeoutSec: null,
+ memoryEnabled: false,
+ memoryLastMessages: null,
+ triggerOnMention: false,
+ triggerOnAssign: false,
+ fieldTriggers: [],
+ delegationDelaySec: 0,
+ ownerUserId: null,
+ runnerScope: 'team',
+ lastSeenAt: null,
+ invocationUrl: null,
+ createdAt: new Date(0).toISOString(),
+ apiKeyStart: null,
+ modelProvider: null,
+ actionCount: 0,
+ skillCount: 0,
+ toolCount: 0,
+ canManage,
+});
+
+async function render(row: AiAgent) {
+ const { TeamAiAgentRow } = await import('./TeamAiAgentRow');
+ await act(async () =>
+ root.render(
+ <NextIntlClientProvider locale="en" messages={{ teams, common }} timeZone="UTC">
+ <AgentSectionProvider
+ teamId={1}
+ permissions={{ read: true, create: true, edit: true, delete: true }}
+ >
+ <table>
+ <tbody>
+ <TeamAiAgentRow
+ agent={row}
+ providerLabel={(key) => key}
+ onChat={() => {}}
+ onRuns={() => {}}
+ onEdit={() => {
+ edited += 1;
+ }}
+ onDelete={() => {}}
+ joinsNewProjects={false}
+ joinsNewProjectsPending={false}
+ />
+ </tbody>
+ </table>
+ </AgentSectionProvider>
+ </NextIntlClientProvider>,
+ ),
+ );
+}
+
+// The items of the row's menu, once it is open.
+async function menuItems(): Promise<string[]> {
+ const trigger = document.querySelector('button[aria-haspopup="menu"]')!;
+ await act(async () => {
+ trigger.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
+ });
+ return [...document.querySelectorAll('[role="menuitem"]')].map((i) => i.textContent ?? '');
+}
+
+beforeEach(async () => {
+ originals = new Map(
+ replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),
+ );
+ dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'https://example.test/' });
+ for (const name of replacedGlobals) {
+ if (name in dom.window) {
+ Object.defineProperty(globalThis, name, {
+ configurable: true,
+ value: dom.window[name as keyof typeof dom.window],
+ });
+ }
+ }
+ Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
+ configurable: true,
+ value: true,
+ });
+ edited = 0;
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(document.querySelector('#root')!);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ dom.window.close();
+ for (const [name, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+describe('TeamAiAgentRow', () => {
+ it('opens the editor and offers deleting an agent the viewer may manage', async () => {
+ await render(agent(true));
+
+ await act(async () => (document.querySelector('tr') as HTMLElement).click());
+ assert.equal(edited, 1);
+ const items = await menuItems();
+ assert.ok(items.some((i) => i.includes(common.edit)));
+ assert.ok(items.some((i) => i.includes(common.delete)));
+ });
+
+ it('offers neither editing nor deleting an agent the viewer may not manage', async () => {
+ await render(agent(false));
+
+ await act(async () => (document.querySelector('tr') as HTMLElement).click());
+ assert.equal(edited, 0);
+ const items = await menuItems();
+ assert.ok(items.some((i) => i.includes(teams.agents.runHistory)));
+ assert.ok(!items.some((i) => i.includes(common.edit)));
+ assert.ok(!items.some((i) => i.includes(common.delete)));
+ });
+});
diff --git a/apps/web/src/features/teams/components/ai-agents/TeamAiAgentRow.tsx b/apps/web/src/features/teams/components/ai-agents/TeamAiAgentRow.tsx
index ce3364e5..e8191d90 100644
--- a/apps/web/src/features/teams/components/ai-agents/TeamAiAgentRow.tsx
+++ b/apps/web/src/features/teams/components/ai-agents/TeamAiAgentRow.tsx
@@ -51,8 +51,9 @@ export function TeamAiAgentRow({
const can = useAgentCan();
const canHistory = can('read');
const KindIcon = AGENT_KIND_ICON[agent.kind];
- const canEdit = can('edit');
- const hasMenu = canEdit || canHistory || can('delete');
+ const canEdit = can('edit') && agent.canManage;
+ const canDelete = can('delete') && agent.canManage;
+ const hasMenu = canEdit || canHistory || canDelete;
return (
<TableRow
@@ -150,8 +151,8 @@ export function TeamAiAgentRow({
{t('testChat')}
</DropdownMenuItem>
)}
- {can('delete') && (canEdit || canHistory) && <DropdownMenuSeparator />}
- {can('delete') && (
+ {canDelete && (canEdit || canHistory) && <DropdownMenuSeparator />}
+ {canDelete && (
<DropdownMenuItem
className="min-h-11 sm:min-h-8"
variant="destructive"
diff --git a/apps/web/src/lib/api/endpoints/agents.ts b/apps/web/src/lib/api/endpoints/agents.ts
index 315da1a9..38ff0cf6 100644
--- a/apps/web/src/lib/api/endpoints/agents.ts
+++ b/apps/web/src/lib/api/endpoints/agents.ts
@@ -78,6 +78,10 @@ export interface AiAgent {
actionCount: number;
skillCount: number;
toolCount: number;
+ // Whether the viewer may act on the agent as a whole (edit, delete, rotate its key,
+ // use its invocation secret): the api refuses a member who shares only some of its
+ // projects.
+ canManage: boolean;
}
// A run waits as 'pending' until a worker or a runner takes it; 'canceled' is a