Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions server/src/__tests__/agent-permissions-routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -694,6 +694,106 @@ describe.sequential("agent permission routes", () => {
);
}, 15_000);

it("supports status query parameter on the agent list route", async () => {
mockAgentService.list.mockResolvedValue([
baseAgent,
{
...baseAgent,
id: "33333333-3333-4333-8333-333333333333",
name: "Busy",
status: "running",
},
{
...baseAgent,
id: "44444444-4444-4444-8444-444444444444",
name: "Retired",
status: "terminated",
},
]);

const app = await createApp({
type: "board",
userId: "board-user",
source: "local_implicit",
isInstanceAdmin: true,
companyIds: [companyId],
});

const res = await request(app)
.get(`/api/companies/${companyId}/agents`)
.query({ status: "idle,running" });

expect(res.status).toBe(200);
expect(mockAgentService.list).toHaveBeenCalledWith(companyId, { includeTerminated: false });
expect(res.body).toHaveLength(2);
expect(res.body.map((agent: { status: string }) => agent.status).sort()).toEqual(["idle", "running"]);
});

it("includes terminated rows when status filter requests terminated", async () => {
mockAgentService.list.mockResolvedValue([
{ ...baseAgent, status: "idle" },
{
...baseAgent,
id: "44444444-4444-4444-8444-444444444444",
name: "Retired",
status: "terminated",
},
]);

const app = await createApp({
type: "board",
userId: "board-user",
source: "local_implicit",
isInstanceAdmin: true,
companyIds: [companyId],
});

const res = await request(app)
.get(`/api/companies/${companyId}/agents`)
.query({ status: "terminated" });

expect(res.status).toBe(200);
expect(mockAgentService.list).toHaveBeenCalledWith(companyId, { includeTerminated: true });
expect(res.body).toHaveLength(1);
expect(res.body[0].status).toBe("terminated");
});

it("rejects invalid status values on the agent list route", async () => {
const app = await createApp({
type: "board",
userId: "board-user",
source: "local_implicit",
isInstanceAdmin: true,
companyIds: [companyId],
});

const res = await request(app)
.get(`/api/companies/${companyId}/agents`)
.query({ status: "idle,banana" });

expect(res.status).toBe(400);
expect(res.body.error).toContain("banana");
expect(mockAgentService.list).not.toHaveBeenCalled();
});

it("rejects empty status filter values on the agent list route", async () => {
const app = await createApp({
type: "board",
userId: "board-user",
source: "local_implicit",
isInstanceAdmin: true,
companyIds: [companyId],
});

const res = await request(app)
.get(`/api/companies/${companyId}/agents`)
.query({ status: "" });

expect(res.status).toBe(400);
expect(res.body.error).toContain("comma-separated statuses");
expect(mockAgentService.list).not.toHaveBeenCalled();
});

it("rejects unsupported query parameters on the agent list route", async () => {
const app = await createApp({
type: "board",
Expand Down
51 changes: 47 additions & 4 deletions server/src/routes/agents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { Db } from "@paperclipai/db";
import { agents as agentsTable, companies, heartbeatRuns, issues as issuesTable } from "@paperclipai/db";
import { and, desc, eq, inArray, not, sql } from "drizzle-orm";
import {
AGENT_STATUSES,
agentSkillSyncSchema,
agentMineInboxQuerySchema,
AGENT_DEFAULT_MAX_CONCURRENT_RUNS,
Expand All @@ -16,6 +17,7 @@ import {
resetAgentSessionSchema,
testAdapterEnvironmentSchema,
type AgentSkillSnapshot,
type AgentStatus,
type InstanceSchedulerHeartbeatAgent,
upsertAgentInstructionsFileSchema,
updateAgentInstructionsBundleSchema,
Expand Down Expand Up @@ -1114,20 +1116,61 @@ export function agentRoutes(
router.get("/companies/:companyId/agents", async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
const unsupportedQueryParams = Object.keys(req.query).sort();

const supportedQueryParams = new Set(["status"]);
const unsupportedQueryParams = Object.keys(req.query)
.filter((key) => !supportedQueryParams.has(key))
.sort();
if (unsupportedQueryParams.length > 0) {
res.status(400).json({
error: `Unsupported query parameter${unsupportedQueryParams.length === 1 ? "" : "s"}: ${unsupportedQueryParams.join(", ")}`,
});
return;
}
const result = await svc.list(companyId);

const requestedStatuses: AgentStatus[] = [];
const rawStatusQuery = req.query.status;
const statusQueryProvided = rawStatusQuery !== undefined;
const statusEntries = Array.isArray(rawStatusQuery) ? rawStatusQuery : rawStatusQuery ? [rawStatusQuery] : [];
for (const entry of statusEntries) {
if (typeof entry !== "string") continue;
for (const value of entry.split(",")) {
const trimmed = value.trim();
if (trimmed.length > 0) {
requestedStatuses.push(trimmed as AgentStatus);
}
}
}

if (statusQueryProvided && requestedStatuses.length === 0) {
res.status(400).json({
error: "Invalid status query parameter value: expected one or more comma-separated statuses",
});
return;
}

const invalidStatuses = requestedStatuses.filter((status) => !AGENT_STATUSES.includes(status));
if (invalidStatuses.length > 0) {
res.status(400).json({
error: `Invalid status query parameter value${invalidStatuses.length === 1 ? "" : "s"}: ${invalidStatuses.join(", ")}. Allowed: ${AGENT_STATUSES.join(", ")}`,
});
return;
}

const statusFilter = new Set(requestedStatuses);
const includeTerminated = statusFilter.has("terminated");
const result = await svc.list(companyId, { includeTerminated });
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 includeTerminated always passed even with no status filter

The original call was svc.list(companyId) (no second argument). Now every request — including ones with no status param — calls svc.list(companyId, { includeTerminated: false }). If the service method's default behaviour when the option is omitted differs from { includeTerminated: false } (e.g. it previously returned terminated agents by default), this silently changes the unfiltered list response for all existing callers. Worth a quick verification against the AgentService.list signature to confirm includeTerminated defaults to false.

Prompt To Fix With AI
This is a comment left during a code review.
Path: server/src/routes/agents.ts
Line: 1162

Comment:
**`includeTerminated` always passed even with no status filter**

The original call was `svc.list(companyId)` (no second argument). Now every request — including ones with no `status` param — calls `svc.list(companyId, { includeTerminated: false })`. If the service method's default behaviour when the option is omitted differs from `{ includeTerminated: false }` (e.g. it previously returned terminated agents by default), this silently changes the unfiltered list response for all existing callers. Worth a quick verification against the `AgentService.list` signature to confirm `includeTerminated` defaults to `false`.

How can I resolve this? If you propose a fix, please make it concise.

const filtered =
statusFilter.size > 0
? result.filter((agent) => statusFilter.has(agent.status as AgentStatus))
: result;

const canReadConfigs = await actorCanReadConfigurationsForCompany(req, companyId);
if (canReadConfigs) {
res.json(result);
res.json(filtered);
return;
}
res.json(result.map((agent) => redactForRestrictedAgentView(agent)));
res.json(filtered.map((agent) => redactForRestrictedAgentView(agent)));
});

router.get("/instance/scheduler-heartbeats", async (req, res) => {
Expand Down
Loading