fix(office): allow changing an agent's manager from the configuration tab (#2821)
Co-authored-by: nova28 <17953305+nova28@users.noreply.github.com> Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(
|
||||
<StateProvider
|
||||
initialState={{
|
||||
workspaces: { activeId: WORKSPACE_ID, items: [] },
|
||||
office: {
|
||||
...defaultOfficeState.office,
|
||||
agentProfilesByWorkspaceId: { [WORKSPACE_ID]: agents },
|
||||
},
|
||||
agentProfiles: { items: [PROFILE_OPTION], version: 0 },
|
||||
}}
|
||||
>
|
||||
<AgentConfigurationTab agent={agent} />
|
||||
</StateProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
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(
|
||||
<StateProvider
|
||||
initialState={{
|
||||
workspaces: { activeId: "ws-1", items: [] },
|
||||
office: {
|
||||
...defaultOfficeState.office,
|
||||
agentProfilesByWorkspaceId: { "ws-1": [baseAgent] },
|
||||
},
|
||||
agentProfiles: { items: [PROFILE_OPTION], version: 0 },
|
||||
}}
|
||||
>
|
||||
<AgentConfigurationTab agent={baseAgent} />
|
||||
</StateProvider>,
|
||||
);
|
||||
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(
|
||||
<StateProvider
|
||||
initialState={{
|
||||
workspaces: { activeId: "ws-1", items: [] },
|
||||
office: {
|
||||
...defaultOfficeState.office,
|
||||
agentProfilesByWorkspaceId: { "ws-1": [baseAgent] },
|
||||
},
|
||||
agentProfiles: { items: [PROFILE_OPTION], version: 0 },
|
||||
}}
|
||||
>
|
||||
<AgentConfigurationTab agent={baseAgent} />
|
||||
</StateProvider>,
|
||||
);
|
||||
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(
|
||||
<StateProvider
|
||||
initialState={{
|
||||
workspaces: { activeId: "ws-1", items: [] },
|
||||
office: {
|
||||
...defaultOfficeState.office,
|
||||
agentProfilesByWorkspaceId: { "ws-1": [worker] },
|
||||
},
|
||||
agentProfiles: { items: [PROFILE_OPTION], version: 0 },
|
||||
}}
|
||||
>
|
||||
<AgentConfigurationTab agent={worker} />
|
||||
</StateProvider>,
|
||||
);
|
||||
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(
|
||||
<StateProvider
|
||||
initialState={{
|
||||
workspaces: { activeId: WORKSPACE_ID, items: [] },
|
||||
office: {
|
||||
...defaultOfficeState.office,
|
||||
agentProfilesByWorkspaceId: { [WORKSPACE_ID]: [manager, worker] },
|
||||
},
|
||||
agentProfiles: { items: [PROFILE_OPTION], version: 0 },
|
||||
}}
|
||||
>
|
||||
<AgentConfigurationTab agent={manager} />
|
||||
</StateProvider>,
|
||||
);
|
||||
|
||||
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(
|
||||
<StateProvider
|
||||
initialState={{
|
||||
workspaces: { activeId: WORKSPACE_ID, items: [] },
|
||||
office: {
|
||||
...defaultOfficeState.office,
|
||||
agentProfilesByWorkspaceId: { [WORKSPACE_ID]: [manager, updatedWorker] },
|
||||
},
|
||||
agentProfiles: { items: [PROFILE_OPTION], version: 0 },
|
||||
}}
|
||||
>
|
||||
<AgentConfigurationTab agent={updatedWorker} />
|
||||
</StateProvider>,
|
||||
);
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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<string, string> = {
|
||||
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<FormState>(() => 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<FormState>) => {
|
||||
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<AgentProfile> = {
|
||||
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 (
|
||||
<div className="space-y-4 mt-4" data-testid="agent-configuration-tab">
|
||||
<IdentityCard
|
||||
name={form.name}
|
||||
role={form.role}
|
||||
roles={roles}
|
||||
reportsToName={reportsToAgent?.name ?? t("office:none")}
|
||||
reportsTo={form.reportsTo}
|
||||
reportsToChoices={reportsToChoices}
|
||||
onNameChange={(v) => patch({ name: v })}
|
||||
onRoleChange={(v) => patch({ role: v })}
|
||||
onRoleChange={(v) => patch(v === "ceo" ? { role: v, reportsTo: "" } : { role: v })}
|
||||
onReportsToChange={(v) => patch({ reportsTo: v })}
|
||||
/>
|
||||
<CapabilityPreviewCard agent={agent} role={form.role} />
|
||||
<OrchestrationCard
|
||||
@@ -150,6 +136,120 @@ export function AgentConfigurationTab({ agent }: AgentConfigurationTabProps) {
|
||||
);
|
||||
}
|
||||
|
||||
function reconcileForm(
|
||||
previousForm: FormState,
|
||||
nextForm: FormState,
|
||||
dirtyFields: Set<FormField>,
|
||||
): 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<FormField>,
|
||||
): Partial<AgentProfile> {
|
||||
function valueFor<T extends FormField>(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<FormState>(() => initialForm(agent));
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const dirtyFieldsRef = useRef<Set<FormField>>(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<FormState>) => {
|
||||
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 (
|
||||
<div className="flex-1">
|
||||
<Label htmlFor="cfg-reports-to">{t("office:reportsTo")}</Label>
|
||||
<Select
|
||||
value={reportsTo || "__none__"}
|
||||
disabled={disabled}
|
||||
onValueChange={(v) => onChange(v === "__none__" ? "" : v)}
|
||||
>
|
||||
<SelectTrigger
|
||||
id="cfg-reports-to"
|
||||
className="mt-1 min-h-11 w-full cursor-pointer md:min-h-7"
|
||||
>
|
||||
<SelectValue placeholder={t("office:noneTopLevel")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__none__" className="cursor-pointer">
|
||||
{t("office:none")}
|
||||
</SelectItem>
|
||||
{choices.map((c) => (
|
||||
<SelectItem key={c.id} value={c.id} className="cursor-pointer">
|
||||
{c.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground mt-1">{t("office:whichAgentManagesThisOne")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-4">
|
||||
<div className="flex flex-col gap-4 md:flex-row">
|
||||
<div className="flex-1">
|
||||
<Label>{t("office:role")}</Label>
|
||||
<Select value={role} onValueChange={(v) => onRoleChange(v as AgentRole)}>
|
||||
<SelectTrigger className="mt-1 cursor-pointer">
|
||||
<SelectTrigger className="mt-1 min-h-11 w-full cursor-pointer md:min-h-7">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -243,13 +389,12 @@ function IdentityCard({
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<Label>{t("office:reportsTo")}</Label>
|
||||
<Input value={reportsToName} disabled className="mt-1" />
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{t("office:editOrgChartFromTheAgents")}
|
||||
</p>
|
||||
</div>
|
||||
<ReportsToField
|
||||
reportsTo={reportsTo}
|
||||
choices={reportsToChoices}
|
||||
disabled={role === "ceo"}
|
||||
onChange={onReportsToChange}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -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 (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-sm">{t("office:identity")}</CardTitle>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("office:nameRoleAndReportingStructureFor")}
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div>
|
||||
<Label>{t("office:name")}</Label>
|
||||
<Input value={name} onChange={(e) => onNameChange(e.target.value)} className="mt-1" />
|
||||
</div>
|
||||
<div className="flex gap-4">
|
||||
<div className="flex-1">
|
||||
<Label>{t("office:role")}</Label>
|
||||
<Select value={role} onValueChange={(v) => onRoleChange(v as AgentRole)}>
|
||||
<SelectTrigger className="mt-1 cursor-pointer">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{roles.map((r) => (
|
||||
<SelectItem key={r.id} value={r.id} className="cursor-pointer">
|
||||
{r.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<Label>{t("office:reportsTo")}</Label>
|
||||
<Input value={reportsToName} disabled className="mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-sm">{t("office:configuration")}</CardTitle>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("office:budgetLimitsConcurrencyAndExecutionEnvironment")}
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex gap-4">
|
||||
<div className="flex-1">
|
||||
<Label>{t("office:monthlyBudget")}</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
value={budget}
|
||||
onChange={(e) => onBudgetChange(Number(e.target.value))}
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<Label>{t("office:maxConcurrentSessions")}</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={10}
|
||||
value={maxConcurrent}
|
||||
onChange={(e) => onMaxConcurrentChange(Number(e.target.value))}
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label>{t("office:executorPreference")}</Label>
|
||||
<Select
|
||||
value={executorType || "__inherit__"}
|
||||
onValueChange={(v) => onExecutorTypeChange(v === "__inherit__" ? "" : v)}
|
||||
>
|
||||
<SelectTrigger className="mt-1 cursor-pointer">
|
||||
<SelectValue placeholder={t("office:inheritFromProjectWorkspace")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__inherit__" className="cursor-pointer">
|
||||
{t("office:inherit")}
|
||||
</SelectItem>
|
||||
{executorTypes.map((et) => (
|
||||
<SelectItem key={et.id} value={et.id} className="cursor-pointer">
|
||||
{et.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function QuotaCard({
|
||||
agentId,
|
||||
initialUsage,
|
||||
}: {
|
||||
agentId: string;
|
||||
initialUsage: ProviderUsage | null | undefined;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [usage, setUsage] = useState<ProviderUsage | null>(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 (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle className="text-sm">{t("office:subscriptionQuota")}</CardTitle>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{t("office:currentUtilizationOfSubscriptionRateLimit")}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handleRefresh}
|
||||
disabled={refreshing}
|
||||
className="cursor-pointer h-7 w-7"
|
||||
title={t("office:refreshUtilization")}
|
||||
>
|
||||
<IconRefresh className={`h-4 w-4 ${refreshing ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{usage ? (
|
||||
<UtilizationBars usage={usage} />
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("office:noUtilizationDataClickRefreshTo")}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// 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<AgentRole>(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<AgentProfile>);
|
||||
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 (
|
||||
<div className="space-y-4 mt-4">
|
||||
<IdentityCard
|
||||
name={name}
|
||||
role={role}
|
||||
reportsToName={reportsToAgent?.name ?? t("office:none")}
|
||||
roles={roles}
|
||||
onNameChange={(v) => {
|
||||
setName(v);
|
||||
markDirty();
|
||||
}}
|
||||
onRoleChange={(v) => {
|
||||
setRole(v);
|
||||
markDirty();
|
||||
}}
|
||||
/>
|
||||
<ConfigurationCard
|
||||
budget={budget}
|
||||
maxConcurrent={maxConcurrent}
|
||||
executorType={executorType}
|
||||
executorTypes={executorTypes}
|
||||
onBudgetChange={(v) => {
|
||||
setBudget(v);
|
||||
markDirty();
|
||||
}}
|
||||
onMaxConcurrentChange={(v) => {
|
||||
setMaxConcurrent(v);
|
||||
markDirty();
|
||||
}}
|
||||
onExecutorTypeChange={(v) => {
|
||||
setExecutorType(v);
|
||||
markDirty();
|
||||
}}
|
||||
/>
|
||||
{isSubscription && <QuotaCard agentId={agent.id} initialUsage={agent.utilization} />}
|
||||
{dirty && (
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={handleSave} disabled={saving} className="cursor-pointer">
|
||||
{saving ? t("office:saving") : t("office:saveChanges")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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"]);
|
||||
});
|
||||
});
|
||||
@@ -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<string> {
|
||||
const childrenByParent = new Map<string, string[]>();
|
||||
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<string>();
|
||||
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 }));
|
||||
}
|
||||
@@ -47,6 +47,7 @@ export function OrgNodeCard({ node }: OrgNodeCardProps) {
|
||||
return (
|
||||
<Link
|
||||
href={`/office/agents/${agent.id}`}
|
||||
data-reports-to={agent.reportsTo ?? ""}
|
||||
className="absolute group rounded-xl border border-border bg-card p-3.5 shadow-sm hover:shadow-md hover:border-primary/50 hover:-translate-y-0.5 cursor-pointer transition-all"
|
||||
style={{ left: node.x, top: node.y, width: CARD_W }}
|
||||
>
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -238,7 +238,6 @@
|
||||
"dockerImageWithExample": "Ďōćķēŕ ĩḿàĝē (ē.ĝ. ńōďē:20-śĺĩḿ)",
|
||||
"duration": "Ďũŕàţĩōń",
|
||||
"editable": "Ēďĩţàƀĺē",
|
||||
"editOrgChartFromTheAgents": "Ēďĩţ ōŕĝ ćĥàŕţ ƒŕōḿ ţĥē àĝēńţś ĺĩśţ.",
|
||||
"editRoutine": "Ēďĩţ ŕōũţĩńē",
|
||||
"effectiveActionsThisAgentCanRequest": "Ēƒƒēćţĩvē àćţĩōńś ţĥĩś àĝēńţ ćàń ŕēqũēśţ ďũŕĩńĝ Ōƒƒĩćē ŕũńś.",
|
||||
"eGCodeReview": "ē.ĝ. ćōďē-ŕēvĩēŵ",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -238,7 +238,6 @@
|
||||
"dockerImageWithExample": "Docker 镜像(例如 node:20-slim)",
|
||||
"duration": "时长",
|
||||
"editable": "可编辑",
|
||||
"editOrgChartFromTheAgents": "从智能体列表编辑组织图。",
|
||||
"editRoutine": "编辑例行程序",
|
||||
"effectiveActionsThisAgentCanRequest": "此智能体在办公室运行期间可请求的有效操作。",
|
||||
"eGCodeReview": "例如 code-review",
|
||||
|
||||
@@ -238,7 +238,6 @@
|
||||
"dockerImageWithExample": "Docker 鏡像(例如 node:20-slim)",
|
||||
"duration": "時長",
|
||||
"editable": "可編輯",
|
||||
"editOrgChartFromTheAgents": "從代理程式列表編輯組織圖。",
|
||||
"editRoutine": "編輯例行程序",
|
||||
"effectiveActionsThisAgentCanRequest": "此代理程式在辦公室執行期間可請求的有效操作。",
|
||||
"eGCodeReview": "例如 code-review",
|
||||
|
||||
@@ -238,7 +238,6 @@
|
||||
"dockerImageWithExample": "Docker 映象(例如 node:20-slim)",
|
||||
"duration": "時長",
|
||||
"editable": "可編輯",
|
||||
"editOrgChartFromTheAgents": "從代理程式清單編輯組織圖。",
|
||||
"editRoutine": "編輯例行程式",
|
||||
"effectiveActionsThisAgentCanRequest": "此代理程式在辦公室執行期間可請求的有效操作。",
|
||||
"eGCodeReview": "例如 code-review",
|
||||
|
||||
Reference in New Issue
Block a user