diff --git a/apps/backend/internal/office/agents/service.go b/apps/backend/internal/office/agents/service.go index 1dbb5e8ea3..fd7d802679 100644 --- a/apps/backend/internal/office/agents/service.go +++ b/apps/backend/internal/office/agents/service.go @@ -39,8 +39,10 @@ var ( ErrAgentNameRequired = errors.New("agent name is required") ErrAgentRoleInvalid = errors.New("invalid agent role") ErrAgentCEOAlreadyExists = errors.New("workspace already has a CEO agent") + ErrAgentCEOReportsTo = errors.New("CEO agent must be the workspace root") ErrAgentReportsToInvalid = errors.New("reports_to agent does not exist in this workspace") ErrAgentReportsToSelf = errors.New("agent cannot report to itself") + ErrAgentReportsToCycle = errors.New("agent reporting structure cannot contain a cycle") ErrAgentStatusTransition = errors.New("invalid status transition") ) @@ -756,6 +758,9 @@ func (s *AgentService) validateAgentCreate(ctx context.Context, agent *models.Ag return ErrAgentRoleInvalid } if agent.Role == models.AgentRoleCEO { + if agent.ReportsTo != "" { + return ErrAgentCEOReportsTo + } if s.countAgentsByRoleInWorkspace(ctx, models.AgentRoleCEO, agent.WorkspaceID, "") > 0 { return ErrAgentCEOAlreadyExists } @@ -764,7 +769,7 @@ func (s *AgentService) validateAgentCreate(ctx context.Context, agent *models.Ag return err } if agent.ReportsTo != "" { - return s.validateReportsTo(ctx, agent.ReportsTo, "") + return s.validateReportsTo(ctx, agent.ReportsTo, "", agent.WorkspaceID) } return nil } @@ -778,12 +783,15 @@ func (s *AgentService) validateAgentUpdate(ctx context.Context, agent *models.Ag return ErrAgentRoleInvalid } if agent.Role == models.AgentRoleCEO { + if agent.ReportsTo != "" { + return ErrAgentCEOReportsTo + } if s.countAgentsByRoleInWorkspace(ctx, models.AgentRoleCEO, agent.WorkspaceID, agent.ID) > 0 { return ErrAgentCEOAlreadyExists } } if agent.ReportsTo != "" { - return s.validateReportsTo(ctx, agent.ReportsTo, agent.ID) + return s.validateReportsTo(ctx, agent.ReportsTo, agent.ID, agent.WorkspaceID) } return nil } @@ -812,15 +820,62 @@ func (s *AgentService) validateAgentNameUnique(ctx context.Context, name, worksp return nil } -// validateReportsTo ensures the target agent exists. -func (s *AgentService) validateReportsTo(ctx context.Context, reportsTo, selfID string) error { +// validateReportsTo ensures the target agent exists in the same workspace and +// that changing the edge does not create a cycle in the reporting tree. +func (s *AgentService) validateReportsTo( + ctx context.Context, reportsTo, selfID, workspaceID string, +) error { if selfID != "" && reportsTo == selfID { return ErrAgentReportsToSelf } - _, err := s.GetAgentFromConfig(ctx, reportsTo) + target, err := s.GetAgentFromConfig(ctx, reportsTo) if err != nil { return ErrAgentReportsToInvalid } + if target.WorkspaceID != workspaceID { + return ErrAgentReportsToInvalid + } + if selfID == "" { + return nil + } + + agents, err := s.ListAgentsFromConfig(ctx, workspaceID) + if err != nil { + return ErrAgentReportsToInvalid + } + parentByID := make(map[string]string, len(agents)) + idByReference := make(map[string]string, len(agents)*2) + for _, agent := range agents { + parentByID[agent.ID] = agent.ReportsTo + idByReference[agent.ID] = agent.ID + if agent.Name != "" { + idByReference[agent.Name] = agent.ID + } + } + // Validate the proposed edge, not the stale value currently stored for the + // agent being updated. + parentByID[selfID] = reportsTo + + currentID := target.ID + visited := make(map[string]struct{}, len(agents)) + for currentID != "" { + if currentID == selfID { + return ErrAgentReportsToCycle + } + if _, seen := visited[currentID]; seen { + return ErrAgentReportsToCycle + } + visited[currentID] = struct{}{} + parentReference := parentByID[currentID] + if parentReference == "" { + return nil + } + nextID, ok := idByReference[parentReference] + if !ok { + return nil + } + currentID = nextID + } return nil } diff --git a/apps/backend/internal/office/agents/service_test.go b/apps/backend/internal/office/agents/service_test.go index bba402b269..1db2b23dd7 100644 --- a/apps/backend/internal/office/agents/service_test.go +++ b/apps/backend/internal/office/agents/service_test.go @@ -156,6 +156,86 @@ func TestCreateAgentInstance_PreservesExplicitSystemSkills(t *testing.T) { assertSkillSlugMembership(t, stored.DesiredSkills, "kandev-projects", false) } +func TestCreateAgentInstance_RejectsCEOWithManager(t *testing.T) { + svc, repo := newTestAgentService(t) + manager := createAndGetAgent(t, svc, repo, &models.AgentInstance{ + WorkspaceID: "ws-1", + Name: "Manager", + Role: models.AgentRoleWorker, + }) + + err := svc.CreateAgentInstance(context.Background(), &models.AgentInstance{ + WorkspaceID: "ws-1", + Name: "CEO", + Role: models.AgentRoleCEO, + ReportsTo: manager.ID, + }) + if !errors.Is(err, ErrAgentCEOReportsTo) { + t.Fatalf("CreateAgentInstance error = %v, want %v", err, ErrAgentCEOReportsTo) + } +} + +func TestUpdateAgentInstance_RejectsCEOWithManager(t *testing.T) { + svc, repo := newTestAgentService(t) + ceo := createAndGetAgent(t, svc, repo, &models.AgentInstance{ + WorkspaceID: "ws-1", + Name: "CEO", + Role: models.AgentRoleCEO, + }) + ceo.ReportsTo = "manager-id" + + err := svc.UpdateAgentInstance(context.Background(), ceo) + if !errors.Is(err, ErrAgentCEOReportsTo) { + t.Fatalf("UpdateAgentInstance error = %v, want %v", err, ErrAgentCEOReportsTo) + } +} + +func TestCreateAgentInstance_RejectsCrossWorkspaceManager(t *testing.T) { + svc, repo := newTestAgentService(t) + foreign := createAndGetAgent(t, svc, repo, &models.AgentInstance{ + WorkspaceID: "ws-other", + Name: "Foreign manager", + Role: models.AgentRoleWorker, + }) + + err := svc.CreateAgentInstance(context.Background(), &models.AgentInstance{ + WorkspaceID: "ws-1", + Name: "Worker", + Role: models.AgentRoleWorker, + ReportsTo: foreign.ID, + }) + if !errors.Is(err, ErrAgentReportsToInvalid) { + t.Fatalf("CreateAgentInstance error = %v, want %v", err, ErrAgentReportsToInvalid) + } +} + +func TestUpdateAgentInstance_RejectsReportingCycle(t *testing.T) { + svc, repo := newTestAgentService(t) + ceo := createAndGetAgent(t, svc, repo, &models.AgentInstance{ + WorkspaceID: "ws-1", + Name: "CEO", + Role: models.AgentRoleCEO, + }) + manager := createAndGetAgent(t, svc, repo, &models.AgentInstance{ + WorkspaceID: "ws-1", + Name: "Manager", + Role: models.AgentRoleWorker, + ReportsTo: ceo.ID, + }) + worker := createAndGetAgent(t, svc, repo, &models.AgentInstance{ + WorkspaceID: "ws-1", + Name: "Worker", + Role: models.AgentRoleWorker, + ReportsTo: manager.ID, + }) + manager.ReportsTo = worker.ID + + err := svc.UpdateAgentInstance(context.Background(), manager) + if !errors.Is(err, ErrAgentReportsToCycle) { + t.Fatalf("UpdateAgentInstance error = %v, want %v", err, ErrAgentReportsToCycle) + } +} + func createAndGetAgent( t *testing.T, svc *AgentService, diff --git a/apps/web/app/office/agents/[id]/components/agent-configuration-tab.test.tsx b/apps/web/app/office/agents/[id]/components/agent-configuration-tab.test.tsx index bfcc9d4776..8a78bfe131 100644 --- a/apps/web/app/office/agents/[id]/components/agent-configuration-tab.test.tsx +++ b/apps/web/app/office/agents/[id]/components/agent-configuration-tab.test.tsx @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import { StateProvider } from "@/components/state-provider"; import { updateAgentProfile } from "@/lib/api/domains/office-api"; import type { AgentProfile } from "@/lib/state/slices/office/types"; @@ -27,10 +27,15 @@ afterEach(() => { const AGENT_TIMESTAMP = "2026-05-04T00:00:00Z"; const CLAUDE_AGENT_ID = "claude-code"; +const WORKSPACE_ID = "ws-1"; +const WORKER_ID = "agent-worker"; +const MANAGER_ID = "agent-manager"; +const SAVE_BUTTON = "Save Configuration"; +const REPORTS_TO_COMBOBOX = "Reports to"; const baseAgent = { id: "agent-ceo", - workspaceId: "ws-1", + workspaceId: WORKSPACE_ID, name: "CEO", role: "ceo", status: "idle", @@ -51,51 +56,44 @@ const PROFILE_OPTION = { cli_passthrough: false, }; -describe("AgentConfigurationTab", () => { +function renderConfigTab(agents: AgentProfile[], agent: AgentProfile) { + return render( + + + , + ); +} + +describe("AgentConfigurationTab save", () => { it("reconciles the form with the canonical profile returned by the backend", async () => { vi.mocked(updateAgentProfile).mockResolvedValueOnce({ ...baseAgent, agentProfileId: toAgentProfileId(baseAgent.id), name: "Canonical CEO", }); - render( - - - , - ); + renderConfigTab([baseAgent], baseAgent); fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Local edit" } }); - fireEvent.click(screen.getByRole("button", { name: "Save Configuration" })); + fireEvent.click(screen.getByRole("button", { name: SAVE_BUTTON })); await waitFor(() => { expect((screen.getByLabelText("Name") as HTMLInputElement).value).toBe("Canonical CEO"); }); }); +}); +describe("AgentConfigurationTab capabilities", () => { it("shows create-agent capability for CEO agents", () => { - render( - - - , - ); + renderConfigTab([baseAgent], baseAgent); expect(screen.getByTestId("agent-capability-preview").textContent).toContain("Create agent"); }); @@ -103,27 +101,216 @@ describe("AgentConfigurationTab", () => { it("omits create-agent capability for default worker agents", () => { const worker = { ...baseAgent, - id: toAgentProfileId("agent-worker"), + id: toAgentProfileId(WORKER_ID), name: "Worker", role: "worker" as const, }; - render( - - - , - ); + renderConfigTab([worker], worker); expect(screen.getByTestId("agent-capability-preview").textContent).not.toContain( "Create agent", ); }); }); + +describe("AgentConfigurationTab reports-to selection", () => { + it("PATCHes reportsTo when a new manager is selected", async () => { + const manager = { ...baseAgent, id: MANAGER_ID, name: "Manager" } as AgentProfile; + const worker = { + ...baseAgent, + id: WORKER_ID, + name: "Worker", + role: "worker" as const, + reportsTo: undefined, + } as AgentProfile; + renderConfigTab([manager, worker], worker); + + fireEvent.click(screen.getByRole("combobox", { name: REPORTS_TO_COMBOBOX })); + const listbox = await screen.findByRole("listbox"); + fireEvent.click(within(listbox).getByRole("option", { name: "Manager" })); + fireEvent.click(screen.getByRole("button", { name: SAVE_BUTTON })); + + await waitFor(() => { + expect(updateAgentProfile).toHaveBeenCalledWith( + WORKER_ID, + expect.objectContaining({ reportsTo: MANAGER_ID }), + ); + }); + }); + + it("PATCHes reportsTo as an empty string when cleared to None", async () => { + const worker = { + ...baseAgent, + id: WORKER_ID, + name: "Worker", + role: "worker" as const, + reportsTo: "agent-ceo", + } as AgentProfile; + renderConfigTab([baseAgent, worker], worker); + + fireEvent.click(screen.getByRole("combobox", { name: REPORTS_TO_COMBOBOX })); + const listbox = await screen.findByRole("listbox"); + fireEvent.click(within(listbox).getByRole("option", { name: "None" })); + fireEvent.click(screen.getByRole("button", { name: SAVE_BUTTON })); + + await waitFor(() => { + expect(updateAgentProfile).toHaveBeenCalledWith( + WORKER_ID, + expect.objectContaining({ reportsTo: "" }), + ); + }); + }); + + it("does not offer the agent itself as a reports-to option", async () => { + const manager = { + ...baseAgent, + id: MANAGER_ID, + name: "Manager", + role: "worker", + } as AgentProfile; + renderConfigTab([manager], manager); + + fireEvent.click(screen.getByRole("combobox", { name: REPORTS_TO_COMBOBOX })); + const listbox = await screen.findByRole("listbox"); + await waitFor(() => { + expect(within(listbox).queryByRole("option", { name: "Manager" })).toBeNull(); + }); + }); + + it("does not offer a descendant as a reports-to option", async () => { + const manager = { + ...baseAgent, + id: MANAGER_ID, + name: "Manager", + role: "worker", + } as AgentProfile; + const worker = { + ...baseAgent, + id: WORKER_ID, + name: "Worker", + role: "worker" as const, + reportsTo: MANAGER_ID, + } as AgentProfile; + renderConfigTab([manager, worker], manager); + + fireEvent.click(screen.getByRole("combobox", { name: REPORTS_TO_COMBOBOX })); + const listbox = await screen.findByRole("listbox"); + await waitFor(() => { + expect(within(listbox).queryByRole("option", { name: "Worker" })).toBeNull(); + }); + }); +}); + +describe("AgentConfigurationTab save errors", () => { + it("keeps the form dirty when saving fails", async () => { + vi.mocked(updateAgentProfile).mockRejectedValueOnce(new Error("network error")); + renderConfigTab([baseAgent], baseAgent); + + fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Retry CEO" } }); + fireEvent.click(screen.getByRole("button", { name: SAVE_BUTTON })); + + await waitFor(() => { + expect(screen.queryByRole("button", { name: SAVE_BUTTON })).not.toBeNull(); + }); + }); +}); + +describe("AgentConfigurationTab draft navigation", () => { + it("resets a draft when navigation changes to another agent", async () => { + const manager = { + ...baseAgent, + id: MANAGER_ID, + name: "Manager", + role: "worker", + } as AgentProfile; + const worker = { + ...baseAgent, + id: WORKER_ID, + name: "Worker", + role: "worker" as const, + reportsTo: MANAGER_ID, + } as AgentProfile; + const view = renderConfigTab([manager, worker], worker); + + fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Draft worker" } }); + view.rerender( + + + , + ); + + await waitFor(() => { + expect((screen.getByLabelText("Name") as HTMLInputElement).value).toBe("Manager"); + }); + expect(screen.queryByRole("button", { name: SAVE_BUTTON })).toBeNull(); + }); +}); + +describe("AgentConfigurationTab concurrent save", () => { + it("uses a concurrent manager update when the manager field was untouched", async () => { + const manager = { + ...baseAgent, + id: MANAGER_ID, + name: "Manager", + role: "worker", + } as AgentProfile; + const worker = { + ...baseAgent, + id: WORKER_ID, + name: "Worker", + role: "worker" as const, + reportsTo: undefined, + } as AgentProfile; + const updatedWorker = { ...worker, reportsTo: MANAGER_ID }; + vi.mocked(updateAgentProfile).mockResolvedValueOnce(updatedWorker); + const view = renderConfigTab([manager, worker], worker); + + fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Renamed worker" } }); + view.rerender( + + + , + ); + + fireEvent.click(screen.getByRole("button", { name: SAVE_BUTTON })); + await waitFor(() => { + expect(updateAgentProfile).toHaveBeenCalledWith( + WORKER_ID, + expect.objectContaining({ name: "Renamed worker", reportsTo: MANAGER_ID }), + ); + }); + }); +}); + +describe("AgentConfigurationTab CEO hierarchy", () => { + it("keeps the CEO at the top of the hierarchy", () => { + const manager = { + ...baseAgent, + id: MANAGER_ID, + name: "Manager", + role: "worker", + } as AgentProfile; + renderConfigTab([baseAgent, manager], baseAgent); + + const reportsTo = screen.getByRole("combobox", { name: REPORTS_TO_COMBOBOX }); + expect((reportsTo as HTMLButtonElement).disabled).toBe(true); + }); +}); diff --git a/apps/web/app/office/agents/[id]/components/agent-configuration-tab.tsx b/apps/web/app/office/agents/[id]/components/agent-configuration-tab.tsx index 29cfed8b2b..1ebe2df6b3 100644 --- a/apps/web/app/office/agents/[id]/components/agent-configuration-tab.tsx +++ b/apps/web/app/office/agents/[id]/components/agent-configuration-tab.tsx @@ -1,6 +1,6 @@ "use client"; -import { useState, useCallback, useMemo } from "react"; +import { useState, useCallback, useEffect, useMemo, useRef } from "react"; import { Card, CardContent, CardHeader, CardTitle } from "@kandev/ui/card"; import { Input } from "@kandev/ui/input"; import { Label } from "@kandev/ui/label"; @@ -13,6 +13,7 @@ import { selectOfficeAgentProfiles } from "@/lib/state/slices/office/selectors"; import { updateAgentProfile } from "@/lib/api/domains/office-api"; import type { AgentProfile, AgentRole } from "@/lib/state/slices/office/types"; import { AgentRoutingCard } from "./agent-routing-card"; +import { reportsToOptions } from "./reports-to-options"; import { useTranslation } from "react-i18next"; type AgentConfigurationTabProps = { @@ -54,15 +55,28 @@ const CAPABILITY_LABEL_KEYS: Record = { type FormState = { name: string; role: AgentRole; + reportsTo: string; budgetMonthlyCents: number; maxConcurrentSessions: number; executorType: string; }; +type FormField = keyof FormState; + +const FORM_FIELDS: FormField[] = [ + "name", + "role", + "reportsTo", + "budgetMonthlyCents", + "maxConcurrentSessions", + "executorType", +]; + function initialForm(agent: AgentProfile): FormState { return { name: agent.name, role: agent.role, + reportsTo: agent.role === "ceo" ? "" : (agent.reportsTo ?? ""), budgetMonthlyCents: agent.budgetMonthlyCents, maxConcurrentSessions: agent.maxConcurrentSessions, executorType: agent.executorPreference?.type ?? "", @@ -72,7 +86,6 @@ function initialForm(agent: AgentProfile): FormState { export function AgentConfigurationTab({ agent }: AgentConfigurationTabProps) { const { t } = useTranslation(); const meta = useAppStore((s) => s.office.meta); - const updateStore = useAppStore((s) => s.updateOfficeAgentProfile); const allOfficeAgents = useAppStore(selectOfficeAgentProfiles); const roles = @@ -82,51 +95,24 @@ export function AgentConfigurationTab({ agent }: AgentConfigurationTabProps) { meta?.executorTypes.map((e) => ({ id: e.id, label: e.label })) ?? FALLBACK_EXECUTOR_TYPES.map((e) => ({ id: e.id, label: t(e.labelKey) })); - const [form, setForm] = useState(() => initialForm(agent)); - const [saving, setSaving] = useState(false); - const [dirty, setDirty] = useState(false); + const { form, saving, dirty, patch, handleSave } = useAgentConfigurationForm(agent); - const patch = useCallback((p: Partial) => { - setForm((prev) => ({ ...prev, ...p })); - setDirty(true); - }, []); - - const reportsToAgent = useMemo( - () => allOfficeAgents.find((a) => a.id === agent.reportsTo), - [allOfficeAgents, agent.reportsTo], + const reportsToChoices = useMemo( + () => (form.role === "ceo" ? [] : reportsToOptions(allOfficeAgents, agent.id)), + [allOfficeAgents, agent.id, form.role], ); - const handleSave = useCallback(async () => { - setSaving(true); - try { - const update: Partial = { - name: form.name, - role: form.role, - budgetMonthlyCents: form.budgetMonthlyCents, - maxConcurrentSessions: form.maxConcurrentSessions, - executorPreference: form.executorType ? { type: form.executorType } : undefined, - }; - const saved = await updateAgentProfile(agent.id, update); - updateStore(agent.workspaceId, agent.id, saved); - setForm(initialForm(saved)); - setDirty(false); - toast.success(t("office:agentConfigurationUpdated")); - } catch (err) { - toast.error(err instanceof Error ? err.message : t("office:failedToUpdateAgent")); - } finally { - setSaving(false); - } - }, [agent.id, agent.workspaceId, form, updateStore]); - return (
patch({ name: v })} - onRoleChange={(v) => patch({ role: v })} + onRoleChange={(v) => patch(v === "ceo" ? { role: v, reportsTo: "" } : { role: v })} + onReportsToChange={(v) => patch({ reportsTo: v })} /> , +): FormState { + const reconciled = { ...previousForm }; + for (const field of FORM_FIELDS) { + if (!dirtyFields.has(field)) { + Object.assign(reconciled, { [field]: nextForm[field] }); + } + } + return reconciled; +} + +function buildAgentUpdate( + form: FormState, + canonical: FormState, + dirtyFields: Set, +): Partial { + function valueFor(field: T): FormState[T] { + return dirtyFields.has(field) ? form[field] : canonical[field]; + } + + const executorType = valueFor("executorType"); + return { + name: valueFor("name"), + role: valueFor("role"), + reportsTo: valueFor("reportsTo"), + budgetMonthlyCents: valueFor("budgetMonthlyCents"), + maxConcurrentSessions: valueFor("maxConcurrentSessions"), + executorPreference: executorType ? { type: executorType } : undefined, + }; +} + +function useAgentConfigurationForm(agent: AgentProfile) { + const { t } = useTranslation(); + const updateStore = useAppStore((s) => s.updateOfficeAgentProfile); + const [form, setForm] = useState(() => initialForm(agent)); + const [saving, setSaving] = useState(false); + const [dirty, setDirty] = useState(false); + const dirtyFieldsRef = useRef>(new Set()); + const previousAgentRef = useRef(agent); + const activeAgentIdRef = useRef(agent.id); + const saveRequestRef = useRef(0); + const editGenerationRef = useRef(0); + + activeAgentIdRef.current = agent.id; + + useEffect(() => { + const previousAgent = previousAgentRef.current; + previousAgentRef.current = agent; + const nextForm = initialForm(agent); + + if (previousAgent.id !== agent.id) { + dirtyFieldsRef.current.clear(); + setForm(nextForm); + setDirty(false); + setSaving(false); + return; + } + + if (dirtyFieldsRef.current.size === 0) { + setForm(nextForm); + return; + } + + setForm((previousForm) => reconcileForm(previousForm, nextForm, dirtyFieldsRef.current)); + }, [agent]); + + const patch = useCallback((p: Partial) => { + editGenerationRef.current += 1; + for (const field of Object.keys(p) as FormField[]) { + dirtyFieldsRef.current.add(field); + } + setForm((prev) => ({ ...prev, ...p })); + setDirty(true); + }, []); + + const handleSave = useCallback(async () => { + const targetAgentId = agent.id; + const requestId = saveRequestRef.current + 1; + saveRequestRef.current = requestId; + const canonical = initialForm(agent); + const dirtyFields = dirtyFieldsRef.current; + const editGeneration = editGenerationRef.current; + + setSaving(true); + try { + const update = buildAgentUpdate(form, canonical, dirtyFields); + const saved = await updateAgentProfile(targetAgentId, update); + updateStore(agent.workspaceId, targetAgentId, saved); + if ( + activeAgentIdRef.current !== targetAgentId || + saveRequestRef.current !== requestId || + editGenerationRef.current !== editGeneration + ) { + return; + } + dirtyFieldsRef.current.clear(); + setForm(initialForm(saved)); + setDirty(false); + toast.success(t("office:agentConfigurationUpdated")); + } catch (err) { + toast.error(err instanceof Error ? err.message : t("office:failedToUpdateAgent")); + } finally { + if (activeAgentIdRef.current === targetAgentId && saveRequestRef.current === requestId) { + setSaving(false); + } + } + }, [agent, form, t, updateStore]); + + return { form, saving, dirty, patch, handleSave }; +} + function CapabilityPreviewCard({ agent, role }: { agent: AgentProfile; role: AgentRole }) { const { t } = useTranslation(); const capabilities = effectiveCapabilities(agent, role); @@ -193,20 +293,66 @@ function effectiveCapabilities(agent: AgentProfile, role: AgentRole): string[] { return Object.keys(CAPABILITY_LABEL_KEYS).filter((key) => allowed.has(key)); } +function ReportsToField({ + reportsTo, + choices, + disabled, + onChange, +}: { + reportsTo: string; + choices: Array<{ id: string; name: string }>; + disabled: boolean; + onChange: (v: string) => void; +}) { + const { t } = useTranslation(); + return ( +
+ + +

{t("office:whichAgentManagesThisOne")}

+
+ ); +} + function IdentityCard({ name, role, roles, - reportsToName, + reportsTo, + reportsToChoices, onNameChange, onRoleChange, + onReportsToChange, }: { name: string; role: AgentRole; roles: Array<{ id: string; label: string }>; - reportsToName: string; + reportsTo: string; + reportsToChoices: Array<{ id: string; name: string }>; onNameChange: (v: string) => void; onRoleChange: (v: AgentRole) => void; + onReportsToChange: (v: string) => void; }) { const { t } = useTranslation(); return ( @@ -227,11 +373,11 @@ function IdentityCard({ className="mt-1" />
-
+
-
- - -

- {t("office:editOrgChartFromTheAgents")} -

-
+
diff --git a/apps/web/app/office/agents/[id]/components/agent-overview-tab.tsx b/apps/web/app/office/agents/[id]/components/agent-overview-tab.tsx deleted file mode 100644 index d054453161..0000000000 --- a/apps/web/app/office/agents/[id]/components/agent-overview-tab.tsx +++ /dev/null @@ -1,323 +0,0 @@ -"use client"; - -import { useState, useCallback } from "react"; -import { Card, CardContent, CardHeader, CardTitle } from "@kandev/ui/card"; -import { Input } from "@kandev/ui/input"; -import { Label } from "@kandev/ui/label"; -import { Button } from "@kandev/ui/button"; -import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select"; -import { IconRefresh } from "@tabler/icons-react"; -import { toast } from "@/lib/toast/sonner"; -import { useAppStore } from "@/components/state-provider"; -import { selectOfficeAgentProfiles } from "@/lib/state/slices/office/selectors"; -import { updateAgentProfile, getAgentUtilization } from "@/lib/api/domains/office-api"; -import type { AgentProfile, AgentRole, ProviderUsage } from "@/lib/state/slices/office/types"; -import { UtilizationBars } from "@/app/office/components/utilization-bars"; -import { useTranslation } from "react-i18next"; - -type AgentOverviewTabProps = { - agent: AgentProfile; -}; - -function IdentityCard({ - name, - role, - reportsToName, - roles, - onNameChange, - onRoleChange, -}: { - name: string; - role: AgentRole; - reportsToName: string; - roles: Array<{ id: string; label: string }>; - onNameChange: (v: string) => void; - onRoleChange: (v: AgentRole) => void; -}) { - const { t } = useTranslation(); - return ( - - - {t("office:identity")} -

- {t("office:nameRoleAndReportingStructureFor")} -

-
- -
- - onNameChange(e.target.value)} className="mt-1" /> -
-
-
- - -
-
- - -
-
-
-
- ); -} - -function ConfigurationCard({ - budget, - maxConcurrent, - executorType, - executorTypes, - onBudgetChange, - onMaxConcurrentChange, - onExecutorTypeChange, -}: { - budget: number; - maxConcurrent: number; - executorType: string; - executorTypes: Array<{ id: string; label: string }>; - onBudgetChange: (v: number) => void; - onMaxConcurrentChange: (v: number) => void; - onExecutorTypeChange: (v: string) => void; -}) { - const { t } = useTranslation(); - return ( - - - {t("office:configuration")} -

- {t("office:budgetLimitsConcurrencyAndExecutionEnvironment")} -

-
- -
-
- - onBudgetChange(Number(e.target.value))} - className="mt-1" - /> -
-
- - onMaxConcurrentChange(Number(e.target.value))} - className="mt-1" - /> -
-
-
- - -
-
-
- ); -} - -function QuotaCard({ - agentId, - initialUsage, -}: { - agentId: string; - initialUsage: ProviderUsage | null | undefined; -}) { - const { t } = useTranslation(); - const [usage, setUsage] = useState(initialUsage ?? null); - const [refreshing, setRefreshing] = useState(false); - - const handleRefresh = useCallback(async () => { - setRefreshing(true); - try { - const result = await getAgentUtilization(agentId); - setUsage(result.utilization); - } catch { - toast.error(t("office:failedToRefreshUtilization")); - } finally { - setRefreshing(false); - } - }, [agentId]); - - return ( - - -
-
- {t("office:subscriptionQuota")} -

- {t("office:currentUtilizationOfSubscriptionRateLimit")} -

-
- -
-
- - {usage ? ( - - ) : ( -

- {t("office:noUtilizationDataClickRefreshTo")} -

- )} -
-
- ); -} - -// Catalog keys, not copy — module scope freezes a `t()` at the boot locale. -// The `id`s are the wire role / executor-type values. -const FALLBACK_ROLES = [ - { id: "ceo", labelKey: "office:roleCeo" }, - { id: "worker", labelKey: "office:roleWorker" }, - { id: "specialist", labelKey: "office:roleSpecialist" }, - { id: "assistant", labelKey: "office:roleAssistant" }, -]; - -const FALLBACK_EXECUTOR_TYPES = [ - { id: "local_pc", labelKey: "office:localStandalone" }, - { id: "local_docker", labelKey: "office:localDocker" }, - { id: "sprites", labelKey: "office:spritesRemoteSandbox" }, -]; - -export function AgentOverviewTab({ agent }: AgentOverviewTabProps) { - const { t } = useTranslation(); - const agents = useAppStore(selectOfficeAgentProfiles); - const meta = useAppStore((s) => s.office.meta); - const updateStore = useAppStore((s) => s.updateOfficeAgentProfile); - - const roles = - meta?.roles.map((r) => ({ id: r.id, label: r.label })) ?? - FALLBACK_ROLES.map((r) => ({ id: r.id, label: t(r.labelKey) })); - const executorTypes = - meta?.executorTypes.map((e) => ({ id: e.id, label: e.label })) ?? - FALLBACK_EXECUTOR_TYPES.map((e) => ({ id: e.id, label: t(e.labelKey) })); - - const [name, setName] = useState(agent.name); - const [role, setRole] = useState(agent.role); - const [budget, setBudget] = useState(agent.budgetMonthlyCents / 100); - const [maxConcurrent, setMaxConcurrent] = useState(agent.maxConcurrentSessions); - const [executorType, setExecutorType] = useState(agent.executorPreference?.type ?? ""); - const [saving, setSaving] = useState(false); - const [dirty, setDirty] = useState(false); - - const markDirty = useCallback(() => setDirty(true), []); - - const handleSave = useCallback(async () => { - setSaving(true); - try { - await updateAgentProfile(agent.id, { - name, - role, - budgetMonthlyCents: Math.round(budget * 100), - maxConcurrentSessions: maxConcurrent, - executorPreference: executorType ? { type: executorType } : undefined, - } as Partial); - updateStore(agent.workspaceId, agent.id, { - name, - role, - budgetMonthlyCents: Math.round(budget * 100), - maxConcurrentSessions: maxConcurrent, - executorPreference: executorType ? { type: executorType } : undefined, - }); - setDirty(false); - toast.success(t("office:agentUpdated")); - } catch (err) { - toast.error(err instanceof Error ? err.message : t("office:failedToUpdateAgent")); - } finally { - setSaving(false); - } - }, [agent.id, agent.workspaceId, name, role, budget, maxConcurrent, executorType, updateStore]); - - const reportsToAgent = agents.find((a) => a.id === agent.reportsTo); - - const isSubscription = agent.billingType === "subscription"; - - return ( -
- { - setName(v); - markDirty(); - }} - onRoleChange={(v) => { - setRole(v); - markDirty(); - }} - /> - { - setBudget(v); - markDirty(); - }} - onMaxConcurrentChange={(v) => { - setMaxConcurrent(v); - markDirty(); - }} - onExecutorTypeChange={(v) => { - setExecutorType(v); - markDirty(); - }} - /> - {isSubscription && } - {dirty && ( -
- -
- )} -
- ); -} diff --git a/apps/web/app/office/agents/[id]/components/reports-to-options.test.ts b/apps/web/app/office/agents/[id]/components/reports-to-options.test.ts new file mode 100644 index 0000000000..060ff195d0 --- /dev/null +++ b/apps/web/app/office/agents/[id]/components/reports-to-options.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from "vitest"; +import type { AgentProfile } from "@/lib/state/slices/office/types"; +import { collectDescendantIds, reportsToOptions } from "./reports-to-options"; + +function agent(id: string, reportsTo?: string): AgentProfile { + return { id, name: id, reportsTo } as AgentProfile; +} + +describe("collectDescendantIds", () => { + it("returns the direct child of the root", () => { + const agents = [agent("ceo"), agent("manager", "ceo")]; + expect(collectDescendantIds(agents, "ceo")).toEqual(new Set(["manager"])); + }); + + it("returns a grandchild transitively", () => { + const agents = [agent("ceo"), agent("manager", "ceo"), agent("worker", "manager")]; + expect(collectDescendantIds(agents, "ceo")).toEqual(new Set(["manager", "worker"])); + }); + + it("excludes unrelated agents", () => { + const agents = [agent("ceo"), agent("manager", "ceo"), agent("other")]; + expect(collectDescendantIds(agents, "ceo")).toEqual(new Set(["manager"])); + }); + + it("does not loop on a chain with a missing parent", () => { + const agents = [agent("orphan", "does-not-exist")]; + expect(collectDescendantIds(agents, "orphan")).toEqual(new Set()); + }); + + it("returns an empty set for a leaf agent", () => { + const agents = [agent("ceo"), agent("worker", "ceo")]; + expect(collectDescendantIds(agents, "worker")).toEqual(new Set()); + }); +}); + +describe("reportsToOptions", () => { + it("excludes the agent itself", () => { + const agents = [agent("ceo"), agent("worker", "ceo")]; + const options = reportsToOptions(agents, "worker"); + expect(options.map((o) => o.id)).not.toContain("worker"); + }); + + it("excludes a direct child", () => { + const agents = [agent("ceo"), agent("manager", "ceo"), agent("worker", "manager")]; + const options = reportsToOptions(agents, "ceo"); + expect(options.map((o) => o.id)).not.toContain("manager"); + }); + + it("excludes a grandchild", () => { + const agents = [agent("ceo"), agent("manager", "ceo"), agent("worker", "manager")]; + const options = reportsToOptions(agents, "ceo"); + expect(options.map((o) => o.id)).not.toContain("worker"); + }); + + it("keeps an unrelated agent", () => { + const agents = [agent("ceo"), agent("manager", "ceo"), agent("other")]; + const options = reportsToOptions(agents, "manager"); + expect(options.map((o) => o.id)).toContain("other"); + }); + + it("keeps an unrelated agent when a chain has a missing parent", () => { + const agents = [agent("orphan", "does-not-exist"), agent("other")]; + const options = reportsToOptions(agents, "orphan"); + expect(options.map((o) => o.id)).toEqual(["other"]); + }); +}); diff --git a/apps/web/app/office/agents/[id]/components/reports-to-options.ts b/apps/web/app/office/agents/[id]/components/reports-to-options.ts new file mode 100644 index 0000000000..a6f47ebaa1 --- /dev/null +++ b/apps/web/app/office/agents/[id]/components/reports-to-options.ts @@ -0,0 +1,37 @@ +import type { AgentProfile } from "@/lib/state/slices/office/types"; + +/** + * Every agent transitively managed by `rootId`, walking the `reportsTo` edges + * forward. Re-parenting `rootId` under one of its own descendants would form + * a cycle: `buildForest` (org-tree-layout.ts) treats a cyclic agent's parent + * as unresolved and drops the whole cycle from the org chart with no error. + */ +export function collectDescendantIds(agents: AgentProfile[], rootId: string): Set { + const childrenByParent = new Map(); + for (const agent of agents) { + if (!agent.reportsTo) continue; + const siblings = childrenByParent.get(agent.reportsTo) ?? []; + siblings.push(agent.id); + childrenByParent.set(agent.reportsTo, siblings); + } + + const descendants = new Set(); + const queue = [...(childrenByParent.get(rootId) ?? [])]; + while (queue.length > 0) { + const id = queue.pop()!; + if (descendants.has(id)) continue; + descendants.add(id); + queue.push(...(childrenByParent.get(id) ?? [])); + } + return descendants; +} + +/** Agents eligible as a manager for `agentId`: everyone except itself and its own descendants. */ +export function reportsToOptions( + agents: AgentProfile[], + agentId: string, +): Array<{ id: string; name: string }> { + const excluded = collectDescendantIds(agents, agentId); + excluded.add(agentId); + return agents.filter((a) => !excluded.has(a.id)).map((a) => ({ id: a.id, name: a.name })); +} diff --git a/apps/web/app/office/workspace/org/org-node-card.tsx b/apps/web/app/office/workspace/org/org-node-card.tsx index 2d85a9e59e..6c42afe1f5 100644 --- a/apps/web/app/office/workspace/org/org-node-card.tsx +++ b/apps/web/app/office/workspace/org/org-node-card.tsx @@ -47,6 +47,7 @@ export function OrgNodeCard({ node }: OrgNodeCardProps) { return ( diff --git a/apps/web/e2e/tests/office/mobile-office-reparent.spec.ts b/apps/web/e2e/tests/office/mobile-office-reparent.spec.ts new file mode 100644 index 0000000000..620b7bc8e1 --- /dev/null +++ b/apps/web/e2e/tests/office/mobile-office-reparent.spec.ts @@ -0,0 +1,45 @@ +import { expect, test } from "../../fixtures/office-fixture"; +import { waitForHttp } from "../../helpers/causal-waits"; + +test.describe("Office manager reassignment on mobile", () => { + test("saves a manager change and renders the new parent-child link", async ({ + testPage, + officeApi, + officeSeed, + }) => { + const worker = await officeApi.createAgent(officeSeed.workspaceId, { + name: "Mobile Org Chart Reparent Target", + role: "worker", + }); + const workerId = worker.id as string; + + await testPage.goto(`/office/agents/${workerId}/configuration`); + const reportsTo = testPage.getByRole("combobox", { name: "Reports to" }); + await expect(reportsTo).toBeVisible(); + const reportsToBox = await reportsTo.boundingBox(); + expect(reportsToBox).not.toBeNull(); + expect(reportsToBox!.height).toBeGreaterThanOrEqual(44); + + await reportsTo.click(); + const listbox = testPage.getByRole("listbox"); + await expect(listbox).toBeVisible(); + await listbox.getByRole("option", { name: "CEO" }).click(); + + const saved = waitForHttp(testPage, "PATCH", new RegExp(`/api/v1/office/agents/${workerId}$`)); + await testPage.getByRole("button", { name: "Save Configuration" }).click(); + await saved; + + await testPage.getByTestId("app-nav-trigger").click(); + await testPage + .getByTestId("app-nav-sheet") + .getByRole("link", { name: /Org chart/i }) + .click(); + await expect(testPage).toHaveURL(/\/office\/workspace\/org$/); + await expect(testPage.getByRole("heading", { name: /Org/i }).first()).toBeVisible({ + timeout: 10_000, + }); + await expect( + testPage.getByRole("link", { name: "Mobile Org Chart Reparent Target" }), + ).toHaveAttribute("data-reports-to", officeSeed.agentId); + }); +}); diff --git a/apps/web/e2e/tests/office/org-chart.spec.ts b/apps/web/e2e/tests/office/org-chart.spec.ts index 1f8db69008..5163710fdd 100644 --- a/apps/web/e2e/tests/office/org-chart.spec.ts +++ b/apps/web/e2e/tests/office/org-chart.spec.ts @@ -1,4 +1,5 @@ import { test, expect } from "../../fixtures/office-fixture"; +import { waitForHttp } from "../../helpers/causal-waits"; test.describe("Org chart", () => { test("org chart shows CEO agent node", async ({ testPage, officeSeed: _ }) => { @@ -9,4 +10,45 @@ test.describe("Org chart", () => { // CEO agent from onboarding should appear as a node await expect(testPage.getByText("CEO").first()).toBeVisible({ timeout: 15_000 }); }); + + test("changing an agent's manager on the configuration tab re-parents it on the org chart", async ({ + testPage, + officeApi, + officeSeed, + }) => { + const worker = await officeApi.createAgent(officeSeed.workspaceId, { + name: "Org Chart Reparent Target", + role: "worker", + }); + const workerId = worker.id as string; + + await testPage.goto("/office/workspace/org"); + await expect(testPage.getByRole("heading", { name: /Org/i }).first()).toBeVisible({ + timeout: 10_000, + }); + const edgesBefore = await testPage.getByTestId("org-edge").count(); + + await testPage.goto(`/office/agents/${workerId}/configuration`); + await testPage.getByRole("combobox", { name: "Reports to" }).click(); + const listbox = testPage.getByRole("listbox"); + await expect(listbox).toBeVisible(); + await listbox.getByRole("option", { name: "CEO" }).click(); + + const saved = waitForHttp(testPage, "PATCH", new RegExp(`/api/v1/office/agents/${workerId}$`)); + await testPage.getByRole("button", { name: "Save Configuration" }).click(); + await saved; + + await testPage.getByRole("link", { name: /Agent topology/i }).click(); + await expect(testPage.getByRole("heading", { name: /Org/i }).first()).toBeVisible({ + timeout: 10_000, + }); + const orgChart = testPage.getByTestId("org-chart-edges").locator(".."); + await expect(orgChart.getByRole("link", { name: /Org Chart Reparent Target/ })).toHaveAttribute( + "data-reports-to", + officeSeed.agentId, + ); + await expect(testPage.getByTestId("org-edge")).toHaveCount(edgesBefore + 1, { + timeout: 15_000, + }); + }); }); diff --git a/apps/web/src/locales/en/office.json b/apps/web/src/locales/en/office.json index a91d3b1044..ac902a3595 100644 --- a/apps/web/src/locales/en/office.json +++ b/apps/web/src/locales/en/office.json @@ -238,7 +238,6 @@ "dockerImageWithExample": "Docker image (e.g. node:20-slim)", "duration": "Duration", "editable": "Editable", - "editOrgChartFromTheAgents": "Edit org chart from the agents list.", "editRoutine": "Edit routine", "effectiveActionsThisAgentCanRequest": "Effective actions this agent can request during Office runs.", "eGCodeReview": "e.g. code-review", diff --git a/apps/web/src/locales/pseudo/office.json b/apps/web/src/locales/pseudo/office.json index ceae002d19..87fec4aa96 100644 --- a/apps/web/src/locales/pseudo/office.json +++ b/apps/web/src/locales/pseudo/office.json @@ -238,7 +238,6 @@ "dockerImageWithExample": "Ďōćķēŕ ĩḿàĝē (ē.ĝ. ńōďē:20-śĺĩḿ)", "duration": "Ďũŕàţĩōń", "editable": "Ēďĩţàƀĺē", - "editOrgChartFromTheAgents": "Ēďĩţ ōŕĝ ćĥàŕţ ƒŕōḿ ţĥē àĝēńţś ĺĩśţ.", "editRoutine": "Ēďĩţ ŕōũţĩńē", "effectiveActionsThisAgentCanRequest": "Ēƒƒēćţĩvē àćţĩōńś ţĥĩś àĝēńţ ćàń ŕēqũēśţ ďũŕĩńĝ Ōƒƒĩćē ŕũńś.", "eGCodeReview": "ē.ĝ. ćōďē-ŕēvĩēŵ", diff --git a/apps/web/src/locales/pt-pt/office.json b/apps/web/src/locales/pt-pt/office.json index aefcf44bb7..809721a97f 100644 --- a/apps/web/src/locales/pt-pt/office.json +++ b/apps/web/src/locales/pt-pt/office.json @@ -238,7 +238,6 @@ "dockerImageWithExample": "Imagem Docker (por exemplo, node:20-slim)", "duration": "Duração", "editable": "Editável", - "editOrgChartFromTheAgents": "Edite o organograma a partir da lista de agentes.", "editRoutine": "Editar rotina", "effectiveActionsThisAgentCanRequest": "Ações efetivas que este agente pode pedir durante as execuções do Office.", "eGCodeReview": "por exemplo, code-review", diff --git a/apps/web/src/locales/zh-cn/office.json b/apps/web/src/locales/zh-cn/office.json index 0119049a95..895d8bc83c 100644 --- a/apps/web/src/locales/zh-cn/office.json +++ b/apps/web/src/locales/zh-cn/office.json @@ -238,7 +238,6 @@ "dockerImageWithExample": "Docker 镜像(例如 node:20-slim)", "duration": "时长", "editable": "可编辑", - "editOrgChartFromTheAgents": "从智能体列表编辑组织图。", "editRoutine": "编辑例行程序", "effectiveActionsThisAgentCanRequest": "此智能体在办公室运行期间可请求的有效操作。", "eGCodeReview": "例如 code-review", diff --git a/apps/web/src/locales/zh-hk/office.json b/apps/web/src/locales/zh-hk/office.json index 002fc31414..f945a0ab25 100644 --- a/apps/web/src/locales/zh-hk/office.json +++ b/apps/web/src/locales/zh-hk/office.json @@ -238,7 +238,6 @@ "dockerImageWithExample": "Docker 鏡像(例如 node:20-slim)", "duration": "時長", "editable": "可編輯", - "editOrgChartFromTheAgents": "從代理程式列表編輯組織圖。", "editRoutine": "編輯例行程序", "effectiveActionsThisAgentCanRequest": "此代理程式在辦公室執行期間可請求的有效操作。", "eGCodeReview": "例如 code-review", diff --git a/apps/web/src/locales/zh-tw/office.json b/apps/web/src/locales/zh-tw/office.json index 2020857924..c65a385dd3 100644 --- a/apps/web/src/locales/zh-tw/office.json +++ b/apps/web/src/locales/zh-tw/office.json @@ -238,7 +238,6 @@ "dockerImageWithExample": "Docker 映象(例如 node:20-slim)", "duration": "時長", "editable": "可編輯", - "editOrgChartFromTheAgents": "從代理程式清單編輯組織圖。", "editRoutine": "編輯例行程式", "effectiveActionsThisAgentCanRequest": "此代理程式在辦公室執行期間可請求的有效操作。", "eGCodeReview": "例如 code-review",