⭐️⭐️⭐️ 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.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
import { useEffect, useRef, useState } from 'react';
import { Sparkles, Wrench } from 'lucide-react';
import type { AiAgent } from '@/lib/api/endpoints/agents';
import { teamSectionPath } from '@/utils/paths';
import {
useCreateAiAgent,
useUpdateAiAgent,
useAgentToolsQuery,
} from '@/services/aiAgents.service';
import {
useIntegrationCatalogQuery,
useIntegrationModelsQuery,
useIntegrationOptionsQuery,
} from '@/services/integrations.service';
import {
useTeam,
useTeamProjectDefaultsQuery,
useTeamProjectOptionsQuery,
useTeamQuery,
useUpdateTeamProjectDefaults,
} from '@/services/teams.service';
import {
useSkillOptionsQuery,
useAgentSkillsQuery,
useSetAgentSkills,
} from '@/services/agentSkills.service';
import {
useConfiguredToolOptionsQuery,
useAgentToolLinksQuery,
useSetAgentTools,
} from '@/services/customTools.service';
import { Button } from '@/components/ui/button';
import { useAgentCan, useAgentSection } from '../../context/agentSection';
import { AgentCapabilityList } from './AgentCapabilityList';
import { AgentEmptyNotice } from './AgentEmptyNotice';
import TeamAiAgentFields, { AGENT_EXPANDED_WIDTH } from './TeamAiAgentFields';
import {
initialAgentValue,
isAgentFormValid,
suggestUsername,
toCreateInput,
toUpdatePatch,
type AgentFormValue,
} from '../../utils/agentForm';
import { integrationLabel } from '@/utils/integrationLabels';
import { useTranslations } from 'next-intl';
// The Edit tab of the agent sheet, used for both create and edit. With no agent it
// creates one; once created (onCreated lifts it to the sheet) the same form switches
// to editing that agent without remounting, so the entered values stay. The kind can
// be chosen on create but not changed after. A new external agent's key is revealed
// once in the API key section. An internal agent's enabled skills are managed once
// the agent exists (they are linked through a separate endpoint).
export function AgentSheetForm({
agent,
expanded = false,
onCreated,
}: {
agent: AiAgent | null;
// The project a new agent starts attached to, set when the sheet is opened from
// inside one. An agent reaches nothing until it works in a project, so creating it
// there means creating it for that project.
expanded?: boolean;
onCreated: (agent: AiAgent) => void;
}) {
const t = useTranslations('teams.agents');
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);
// While creating, the username is derived from the name until the user edits it.
// Clearing the username field resumes auto-generation.
const [usernameEdited, setUsernameEdited] = useState(false);
// Skills are a separate permission; when the user can't manage them, the Skills
// section is hidden and its queries and save are skipped (the backend enforces it
// too). Providers are their own resource — the model select just stays empty when
// the user can't read them.
const { teamId } = useAgentSection();
const team = useTeamQuery(teamId).data;
const canManageSkills = team?.permissions.agent_skills.edit ?? false;
const canManageTools = team?.permissions.agent_tools.edit ?? false;
const projects = useTeamProjectOptionsQuery(teamId).data ?? [];
const teamRole = useTeam(teamId)?.role;
const canEditDefaults = teamRole != null && teamRole !== 'member';
const defaultIds = useTeamProjectDefaultsQuery(canEditDefaults ? teamId : null).data
?.defaultAgentIds;
const updateDefaults = useUpdateTeamProjectDefaults(teamId);
const toolsQuery = useAgentToolsQuery(teamId);
const catalogQuery = useIntegrationCatalogQuery(teamId);
const catalog = catalogQuery.data ?? [];
const llmCredentials = useIntegrationOptionsQuery(teamId, 'llm').data ?? [];
const selectedProvider =
llmCredentials.find((c) => c.id === value.modelCredentialId)?.integrationKey ?? null;
const providerModelsQuery = useIntegrationModelsQuery(
teamId,
value.kind === 'internal' ? selectedProvider : null,
);
const skillsLibraryQuery = useSkillOptionsQuery(
value.kind === 'internal' && canManageSkills ? teamId : null,
);
const agentSkillsQuery = useAgentSkillsQuery(
teamId,
agent && agent.kind === 'internal' && canManageSkills ? agent.id : null,
);
const toolsLibraryQuery = useConfiguredToolOptionsQuery(
value.kind === 'internal' && canManageTools ? teamId : null,
);
const agentToolsQuery = useAgentToolLinksQuery(
teamId,
agent && agent.kind === 'internal' && canManageTools ? agent.id : null,
);
const createAgent = useCreateAiAgent(teamId);
const updateAgent = useUpdateAiAgent(teamId);
const setAgentSkills = useSetAgentSkills(teamId);
const setAgentTools = useSetAgentTools(teamId);
const saving =
createAgent.isPending ||
updateAgent.isPending ||
setAgentSkills.isPending ||
setAgentTools.isPending ||
updateDefaults.isPending;
// A new agent starts with every action granted. Seed the tool set once the action
// catalog loads, only while creating and only if the user has not changed it yet.
const toolsSeeded = useRef(false);
useEffect(() => {
const actions = toolsQuery.data;
if (isCreate && !toolsSeeded.current && actions && actions.length > 0) {
toolsSeeded.current = true;
setValue((v) => ({ ...v, tools: actions.map((t) => t.key) }));
}
}, [isCreate, toolsQuery.data]);
// The agent's enabled skills, seeded from the server once loaded (edit mode only).
const [skillIds, setSkillIds] = useState<number[] | null>(null);
useEffect(() => {
if (agentSkillsQuery.data && skillIds === null) {
setSkillIds(agentSkillsQuery.data.map((s) => s.id));
}
}, [agentSkillsQuery.data, skillIds]);
const selectedSkills = skillIds ?? [];
// The agent's enabled custom tools, seeded from the server once loaded (edit only).
const [toolIds, setToolIds] = useState<number[] | null>(null);
useEffect(() => {
if (agentToolsQuery.data && toolIds === null) {
setToolIds(agentToolsQuery.data.map((t) => t.id));
}
}, [agentToolsQuery.data, toolIds]);
const selectedTools = toolIds ?? [];
// Whether the agent joins new projects, seeded from the team's defaults once they load.
const [joinsNewProjects, setJoinsNewProjects] = useState<boolean | null>(isCreate ? false : null);
useEffect(() => {
if (agent && defaultIds && joinsNewProjects === null) {
setJoinsNewProjects(defaultIds.includes(agent.id));
}
}, [agent, defaultIds, joinsNewProjects]);
async function saveJoinsNewProjects(agentId: number) {
if (!defaultIds || joinsNewProjects === null) return;
if (joinsNewProjects === defaultIds.includes(agentId)) return;
await updateDefaults.mutateAsync(
joinsNewProjects ? [...defaultIds, agentId] : defaultIds.filter((id) => id !== agentId),
);
}
function merge(patch: Partial<AgentFormValue>) {
setValue((prev) => {
const next = { ...prev, ...patch };
if (isCreate && 'name' in patch && !usernameEdited) {
next.username = suggestUsername(next.name);
}
return next;
});
if ('username' in patch) setUsernameEdited((patch.username ?? '').trim() !== '');
}
function toggleSkill(id: number, on: boolean) {
setSkillIds((prev) => {
const base = prev ?? [];
return on ? [...new Set([...base, id])] : base.filter((x) => x !== id);
});
}
function toggleTool(id: number, on: boolean) {
setToolIds((prev) => {
const base = prev ?? [];
return on ? [...new Set([...base, id])] : base.filter((x) => x !== id);
});
}
async function submit() {
if (!isAgentFormValid(value) || saving) return;
if (isCreate) {
const res = await createAgent.mutateAsync(toCreateInput(value));
// Link the picked skills/tools against the freshly created agent id (the join
// tables need an id, which only exists after the create returns).
if (res.agent.kind === 'internal' && canManageSkills && skillIds && skillIds.length > 0) {
await setAgentSkills.mutateAsync({ agentId: res.agent.id, skillIds });
}
if (res.agent.kind === 'internal' && canManageTools && toolIds && toolIds.length > 0) {
await setAgentTools.mutateAsync({ agentId: res.agent.id, agentToolIds: toolIds });
}
await saveJoinsNewProjects(res.agent.id);
setRevealedKey(res.apiKey);
onCreated(res.agent);
} else {
await updateAgent.mutateAsync({ id: agent.id, patch: toUpdatePatch(value) });
if (agent.kind === 'internal' && canManageSkills && skillIds !== null) {
await setAgentSkills.mutateAsync({ agentId: agent.id, skillIds });
}
if (agent.kind === 'internal' && canManageTools && toolIds !== null) {
await setAgentTools.mutateAsync({ agentId: agent.id, agentToolIds: toolIds });
}
await saveJoinsNewProjects(agent.id);
}
}
const skillsLibrary = skillsLibraryQuery.data ?? [];
const showSkills = value.kind === 'internal' && canManageSkills;
// The Skills section body (the fields layout wraps it in a section). The configured
// skill library the agent may load.
const skillsContent = showSkills ? (
skillsLibrary.length === 0 ? (
<AgentEmptyNotice
icon={Sparkles}
title={t('noSkills')}
hint={t('noSkillsHint')}
href={teamSectionPath(team?.ref ?? String(teamId), 'agent-skills')}
linkLabel={t('goToSkills')}
/>
) : (
<AgentCapabilityList
searchPlaceholder={t('searchSkills')}
onToggle={toggleSkill}
items={skillsLibrary.map((skill) => ({
id: skill.id,
checked: selectedSkills.includes(skill.id),
title: skill.name,
subtitle: skill.description || t('noDescription'),
search: `${skill.name} ${skill.description ?? ''}`.toLowerCase(),
}))}
/>
)
) : null;
const toolsLibrary = toolsLibraryQuery.data ?? [];
const showTools = value.kind === 'internal' && canManageTools;
// The Tools section body: the configured custom tools the agent may call.
const toolsContent = showTools ? (
toolsLibrary.length === 0 ? (
<AgentEmptyNotice
icon={Wrench}
title={t('noTools')}
hint={t('noToolsHint')}
href={teamSectionPath(team?.ref ?? String(teamId), 'agent-tools')}
linkLabel={t('goToTools')}
/>
) : (
<AgentCapabilityList
searchPlaceholder={t('searchTools')}
onToggle={toggleTool}
items={toolsLibrary.map((tool) => {
const toolLabel =
catalog.flatMap((i) => i.tools).find((t) => t.key === tool.toolKey)?.label ??
tool.toolKey;
const integration = integrationLabel(catalog, tool.integrationKey);
return {
id: tool.id,
checked: selectedTools.includes(tool.id),
title: toolLabel,
subtitle: tool.credentialLabel ?? undefined,
group: integration,
search: `${toolLabel} ${integration} ${tool.credentialLabel ?? ''}`.toLowerCase(),
};
})}
/>
)
) : null;
// "enabled / available" over each capability library, shown in the section header
// and its nav entry. Nothing to count while the library is empty.
const countBadge = (selected: number, total: number) =>
total > 0 ? `${selected} / ${total}` : undefined;
// In the sheet the form owns its scroll container: it holds the section nav, whose
// scroll spy needs that root. The compact side panel stacks in a single column here.
const contentWidth = expanded ? AGENT_EXPANDED_WIDTH : '';
const fields = (
<TeamAiAgentFields
value={value}
onChange={merge}
projects={projects}
tools={toolsQuery.data ?? []}
toolsLoading={toolsQuery.isLoading}
kindLocked={!isCreate}
expanded={expanded}
credentials={llmCredentials}
catalog={catalog}
models={providerModelsQuery.data ?? []}
modelsLoading={providerModelsQuery.isLoading}
agent={agent}
skillsContent={skillsContent}
skillsBadge={countBadge(selectedSkills.length, skillsLibrary.length)}
toolsContent={toolsContent}
toolsBadge={countBadge(selectedTools.length, toolsLibrary.length)}
revealedKey={revealedKey}
onRevealedKey={setRevealedKey}
joinsNewProjects={joinsNewProjects ?? false}
onJoinsNewProjectsChange={canEditDefaults ? setJoinsNewProjects : undefined}
/>
);
return (
<form
className="flex h-full min-h-0 flex-col"
onSubmit={(e) => {
e.preventDefault();
if (canSave) void submit();
}}
>
{expanded ? (
fields
) : (
<div className="min-h-0 flex-1 overflow-y-auto px-4 pt-5 pb-6 sm:px-6">
<div className={`mx-auto w-full space-y-6 ${contentWidth}`}>{fields}</div>
</div>
)}
{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>
)}
</form>
);
}