Files
PaperClipAI/cli/src/__tests__/run.test.ts
T
Josh CoxandReview a072b17067 fix(cli): warn when run list stops at the server page cap (#16533)
## Thinking Path
> - Bounding run history gave `GET
/api/companies/:companyId/heartbeat-runs` a default page of 200 runs and
a ceiling of 1,000, with no offset parameter and no truncation signal in
the response.
> - `paperclipai run list` sends `limit` only when `--limit` is passed,
makes one request, and the HTTP client returns only the parsed body. So
the command prints the newest 200 runs and stops, with no notice — and
`--limit 5000` silently stops at 1,000 the same way.
> - The issue's expected behavior is that the command either returns
every run or says that it did not.
> - Returning every run needs server work that is already scoped in open
issue #14958 (an `offset` parameter plus `X-Result-Truncated` /
`X-Total-Count` headers, and a client that surfaces headers). That is
not this PR.
> - What the CLI can do today: tell the truth. State the default and the
ceiling in the help text, and when a page comes back exactly full — the
only truncation sign the current route gives — say on stderr that more
runs may exist.

## Linked Issues

Fixes #16413

Refs #14958

## What Changed

- `cli/src/commands/client/run.ts`: the `run list` `--limit` help now
reads "Maximum runs to return (server default 200, max 1000)", using the
shared `HEARTBEAT_RUN_LIST_DEFAULT_LIMIT` /
`HEARTBEAT_RUN_LIST_MAX_LIMIT` constants so the text cannot drift from
the server values.
- Same file: after printing, when the returned row count reaches the
effective limit (the requested limit clamped to the server ceiling, or
the 200 default), the command prints a notice on stderr: how many runs
are shown, the cap that applied, that more runs may exist, and to raise
`--limit` to see more. stderr keeps `--json` output on stdout clean and
machine-readable.
- Tests in `cli/src/__tests__/run.test.ts`: a full 200-row default page
triggers exactly one stderr notice and sends no `limit` parameter; a
partial page under `--limit 25` stays quiet.

## Verification

- `vitest run src/__tests__/run.test.ts` — 5 of 5 pass, including the
pre-existing run command tests (request shapes unchanged: no `limit` is
sent unless `--limit` is passed).
- Disclosure: the CLI package typecheck did not complete in my sandbox
(the checker process is very slow against the shared package surface
here and was cut off); CI runs the CLI typecheck and is the arbiter. The
change uses two constants that are exported from `@paperclipai/shared`
today and already imported the same way elsewhere.

## Risks

- A company with exactly 200 (or exactly `--limit`) runs gets the notice
even though nothing was hidden. The wording says more runs *may* exist,
which is the strongest claim the current route supports; #14958's
headers will let a later change make it exact.
- This PR deliberately does not page or raise the default page size: the
server bound exists to keep run-history reads cheap, and silently
requesting 1,000 by default would change the command's cost profile for
every user. Full retrieval lands with #14958.

## Model Used

- **Provider / Model ID:** Meta, Muse Spark 1.3
- **Context window:** 1M+ tokens (exact limit not disclosed);
large-repository tasks with long tool transcripts
- **Capabilities:** agentic coding with tool use — file editing, shell
execution, test execution, browser and API access, multi-step planning

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [ ] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Signed-off-by: Josh Cox <joshuacox@users.noreply.github.com>
Co-authored-by: Review <review@local>
2026-12-04 23:43:38 -08:00

314 lines
12 KiB
TypeScript

import { Command } from "commander";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { registerAgentCommands } from "../commands/client/agent.js";
import { registerIssueCommands } from "../commands/client/issue.js";
import { registerRunCommands } from "../commands/client/run.js";
const COMPANY_ID = "22222222-2222-4222-8222-222222222222";
const AGENT_ID = "11111111-1111-4111-8111-111111111111";
const RUN_ID = "33333333-3333-4333-8333-333333333333";
const ISSUE_ID = "44444444-4444-4444-8444-444444444444";
function createProgram(): Command {
const program = new Command();
program.exitOverride();
program.configureOutput({
writeOut: () => {},
writeErr: () => {},
});
const run = program.command("run").action(() => {});
registerRunCommands(run);
registerAgentCommands(program);
registerIssueCommands(program);
return program;
}
describe("run inspection commands", () => {
beforeEach(() => {
vi.restoreAllMocks();
delete process.env.PAPERCLIP_API_KEY;
delete process.env.PAPERCLIP_API_URL;
});
afterEach(() => {
vi.restoreAllMocks();
});
it("lists and reads heartbeat runs through run subcommands", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response(JSON.stringify([
{ id: RUN_ID, companyId: COMPANY_ID, agentId: AGENT_ID, status: "running", invocationSource: "on_demand" },
]), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify({
id: RUN_ID,
companyId: COMPANY_ID,
agentId: AGENT_ID,
status: "running",
invocationSource: "on_demand",
}), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify({
text: "hello",
offset: 0,
nextOffset: 5,
}), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify({ id: RUN_ID, status: "cancelled" }), { status: 200 }));
vi.stubGlobal("fetch", fetchMock);
vi.spyOn(console, "log").mockImplementation(() => {});
vi.spyOn(process.stdout, "write").mockImplementation(() => true);
await createProgram().parseAsync([
"run", "list",
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
"--company-id", COMPANY_ID,
"--agent-id", AGENT_ID,
"--limit", "25",
], { from: "user" });
await createProgram().parseAsync([
"run", "get", RUN_ID,
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
], { from: "user" });
await createProgram().parseAsync([
"run", "log", RUN_ID,
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
"--offset", "4",
"--limit-bytes", "100",
"--text",
], { from: "user" });
await createProgram().parseAsync([
"run", "cancel", RUN_ID,
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
], { from: "user" });
expect(fetchMock.mock.calls[0]?.[0]).toBe(
`http://localhost:3100/api/companies/${COMPANY_ID}/heartbeat-runs?agentId=${AGENT_ID}&limit=25`,
);
expect(fetchMock.mock.calls[1]?.[0]).toBe(`http://localhost:3100/api/heartbeat-runs/${RUN_ID}`);
expect(fetchMock.mock.calls[2]?.[0]).toBe(
`http://localhost:3100/api/heartbeat-runs/${RUN_ID}/log?offset=4&limitBytes=100`,
);
expect(fetchMock.mock.calls[3]?.[0]).toBe(`http://localhost:3100/api/heartbeat-runs/${RUN_ID}/cancel`);
expect(fetchMock.mock.calls[3]?.[1]?.method).toBe("POST");
});
it("supports run events, issues, workspace operations, and watchdog decisions", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response(JSON.stringify([
{ id: 1, runId: RUN_ID, agentId: AGENT_ID, seq: 1, eventType: "output", message: "hi" },
]), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify([
{ id: ISSUE_ID, identifier: "PC-1", title: "Fix it", status: "in_progress", priority: "normal" },
]), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify([
{ id: "55555555-5555-4555-8555-555555555555", status: "succeeded", phase: "workspace_provision" },
]), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify({ text: "workspace" }), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify({ id: "decision-1", decision: "continue" }), { status: 200 }));
vi.stubGlobal("fetch", fetchMock);
vi.spyOn(console, "log").mockImplementation(() => {});
await createProgram().parseAsync([
"run", "events", RUN_ID,
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
"--after-seq", "7",
"--limit", "50",
], { from: "user" });
await createProgram().parseAsync([
"run", "issues", RUN_ID,
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
], { from: "user" });
await createProgram().parseAsync([
"run", "workspace-operations", RUN_ID,
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
], { from: "user" });
await createProgram().parseAsync([
"run", "workspace-log", "55555555-5555-4555-8555-555555555555",
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
], { from: "user" });
await createProgram().parseAsync([
"run", "watchdog-decision", RUN_ID,
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
"--decision", "continue",
"--reason", "operator reviewed",
], { from: "user" });
expect(fetchMock.mock.calls[0]?.[0]).toBe(
`http://localhost:3100/api/heartbeat-runs/${RUN_ID}/events?afterSeq=7&limit=50`,
);
expect(fetchMock.mock.calls[1]?.[0]).toBe(`http://localhost:3100/api/heartbeat-runs/${RUN_ID}/issues`);
expect(fetchMock.mock.calls[2]?.[0]).toBe(`http://localhost:3100/api/heartbeat-runs/${RUN_ID}/workspace-operations`);
expect(fetchMock.mock.calls[3]?.[0]).toBe(
"http://localhost:3100/api/workspace-operations/55555555-5555-4555-8555-555555555555/log?offset=0",
);
expect(fetchMock.mock.calls[4]?.[0]).toBe(`http://localhost:3100/api/heartbeat-runs/${RUN_ID}/watchdog-decisions`);
expect(JSON.parse(String(fetchMock.mock.calls[4]?.[1]?.body))).toMatchObject({
decision: "continue",
reason: "operator reviewed",
});
});
it("wakes agents and exposes issue run helpers", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response(JSON.stringify({
id: AGENT_ID,
name: "Builder",
companyId: COMPANY_ID,
urlKey: "builder",
}), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify({
id: RUN_ID,
companyId: COMPANY_ID,
agentId: AGENT_ID,
status: "queued",
}), { status: 202 }))
.mockResolvedValueOnce(new Response(JSON.stringify([{ id: RUN_ID, status: "succeeded" }]), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify([{ id: RUN_ID, status: "running" }]), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify({ id: RUN_ID, status: "running" }), { status: 200 }));
vi.stubGlobal("fetch", fetchMock);
vi.spyOn(console, "log").mockImplementation(() => {});
await createProgram().parseAsync([
"agent", "wake", "builder",
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
"--company-id", COMPANY_ID,
"--reason", "manual check",
"--payload", "{\"issueId\":\"PC-1\"}",
], { from: "user" });
await createProgram().parseAsync([
"issue", "runs", "PC-1",
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
], { from: "user" });
await createProgram().parseAsync([
"issue", "live-runs", "PC-1",
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
], { from: "user" });
await createProgram().parseAsync([
"issue", "active-run", "PC-1",
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
], { from: "user" });
expect(fetchMock.mock.calls[0]?.[0]).toBe(`http://localhost:3100/api/agents/builder?companyId=${COMPANY_ID}`);
expect(fetchMock.mock.calls[1]?.[0]).toBe(`http://localhost:3100/api/agents/${AGENT_ID}/wakeup`);
expect(JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body))).toMatchObject({
source: "on_demand",
triggerDetail: "manual",
reason: "manual check",
payload: { issueId: "PC-1" },
});
expect(fetchMock.mock.calls[2]?.[0]).toBe("http://localhost:3100/api/issues/PC-1/runs");
expect(fetchMock.mock.calls[3]?.[0]).toBe("http://localhost:3100/api/issues/PC-1/live-runs");
expect(fetchMock.mock.calls[4]?.[0]).toBe("http://localhost:3100/api/issues/PC-1/active-run");
});
it("warns on stderr when run list returns a full server-capped page", async () => {
const page = Array.from({ length: 200 }, (_, i) => ({
id: `33333333-3333-4333-8333-${String(i).padStart(12, "0")}`,
companyId: COMPANY_ID,
agentId: AGENT_ID,
status: "succeeded",
invocationSource: "on_demand",
}));
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify(page), { status: 200 }));
vi.stubGlobal("fetch", fetchMock);
vi.spyOn(console, "log").mockImplementation(() => {});
const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
await createProgram().parseAsync([
"run", "list",
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
"--company-id", COMPANY_ID,
], { from: "user" });
// No limit is sent by default, and the full 200-row page is flagged.
expect(fetchMock.mock.calls[0]?.[0]).toBe(
`http://localhost:3100/api/companies/${COMPANY_ID}/heartbeat-runs`,
);
expect(errSpy).toHaveBeenCalledTimes(1);
expect(errSpy.mock.calls[0]?.[0]).toContain("newest 200 runs");
expect(errSpy.mock.calls[0]?.[0]).toContain("1000 max");
});
it("warns when a negative limit makes the server return a single run", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify([
{ id: RUN_ID, companyId: COMPANY_ID, agentId: AGENT_ID, status: "succeeded", invocationSource: "on_demand" },
]), { status: 200 }));
vi.stubGlobal("fetch", fetchMock);
vi.spyOn(console, "log").mockImplementation(() => {});
const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
await createProgram().parseAsync([
"run", "list",
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
"--company-id", COMPANY_ID,
"--limit=-1",
], { from: "user" });
expect(errSpy).toHaveBeenCalledTimes(1);
expect(errSpy.mock.calls[0]?.[0]).toContain("newest 1 runs");
});
it("does not advise raising --limit when the page already hit the server ceiling", async () => {
const page = Array.from({ length: 1000 }, (_, i) => ({
id: `33333333-3333-4333-8333-${String(i).padStart(12, "0")}`,
companyId: COMPANY_ID,
agentId: AGENT_ID,
status: "succeeded",
invocationSource: "on_demand",
}));
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify(page), { status: 200 }));
vi.stubGlobal("fetch", fetchMock);
vi.spyOn(console, "log").mockImplementation(() => {});
const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
await createProgram().parseAsync([
"run", "list",
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
"--company-id", COMPANY_ID,
"--limit", "5000",
], { from: "user" });
expect(errSpy).toHaveBeenCalledTimes(1);
expect(errSpy.mock.calls[0]?.[0]).toContain("newest 1000 runs");
expect(errSpy.mock.calls[0]?.[0]).not.toContain("Raise --limit");
});
it("stays quiet when run list returns a partial page", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify([
{ id: RUN_ID, companyId: COMPANY_ID, agentId: AGENT_ID, status: "running", invocationSource: "on_demand" },
]), { status: 200 }));
vi.stubGlobal("fetch", fetchMock);
vi.spyOn(console, "log").mockImplementation(() => {});
const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
await createProgram().parseAsync([
"run", "list",
"--api-base", "http://localhost:3100",
"--api-key", "board-token",
"--company-id", COMPANY_ID,
"--limit", "25",
], { from: "user" });
expect(errSpy).not.toHaveBeenCalled();
});
});