Files
PaperClipAI/server/src/__tests__/dashboard-service.test.ts
DottaandPaperclip efc2e6810e fix: show each task once in dashboard agent cards (#14847)
## Thinking Path

> - Paperclip helps people manage AI agents and their tasks.
> - The dashboard shows recent agent activity in compact cards.
> - Those cards use run records, so two runs for one task can create
duplicate task cards.
> - An operator needs to see each task once when scanning the dashboard.
> - This pull request selects one run per linked task before it applies
the card limit.
> - The live runs page still shows each run for run inspection.

## Linked Issues or Issue Description

**What happened?**

The dashboard showed the same task in two agent cards when that task had
both an active run and a completed run.

**Expected behavior**

The dashboard should show a linked task at most once. It should keep the
active run card when one is present.

**Steps to reproduce**

1. Start an agent run for a task that already has a completed run.
2. Open the company dashboard.
3. Observe two cards linked to the same task.

**Paperclip version or commit**

Reproduced on the pre-change master at `8b4aa0692`.

**Deployment mode**

Local dev, built from source. The bug is in the core dashboard UI and
does not depend on an agent adapter or database mode.

## What Changed

- Select distinct linked tasks from capped active and recent run samples
before applying the dashboard card limit.
- Keep separate cards for runs without a linked task.
- Preserve the dashboard's count of additional distinct cards behind the
live-runs link.
- Add UI and embedded Postgres regression tests for duplicate runs and
document the dashboard rule.
- Give the existing multi-request cross-tenant authorization test enough
time on loaded CI runners.

## Verification

- `pnpm --filter @paperclipai/ui exec vitest run
src/components/ActiveAgentsPanel.test.tsx`
- `pnpm --filter @paperclipai/ui exec vitest run
src/api/heartbeats.test.ts`
- `pnpm exec vitest run server/src/__tests__/dashboard-service.test.ts
server/src/__tests__/agent-live-run-routes.test.ts`
- `pnpm exec vitest run
server/src/__tests__/agent-cross-tenant-authz-routes.test.ts`
- `pnpm --filter @paperclipai/ui typecheck`
- `pnpm --filter @paperclipai/server typecheck`
- `pnpm --filter @paperclipai/ui build`
- `pnpm -r typecheck`
- `pnpm build`
- `pnpm check:token-gates`
- Review the dashboard with an active and a completed run on the same
task. Confirm that it shows one card. Open Live agent runs to inspect
both run records.

## Risks

- A very high volume of recent runs for one task can fill the capped
sample and leave older tasks off the dashboard. The Live runs page
remains available for full run inspection.
- The dashboard may fetch up to 50 distinct run representatives to
preserve its overflow count. The default run API response and persisted
data are unchanged.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI Codex, GPT-6. The runtime does not expose the exact model ID or
context window size to this task. The model used reasoning, tool calls,
and code execution.

## 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)
- [x] 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
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-01 12:18:35 -05:00

278 lines
9.4 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { agents, companies, createDb, heartbeatRuns } from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { dashboardService, getUtcMonthStart } from "../services/dashboard.ts";
import { selectDashboardRunIds } from "../services/dashboard-run-selection.ts";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
if (!embeddedPostgresSupport.supported) {
console.warn(
`Skipping embedded Postgres dashboard service tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
);
}
function utcDay(offsetDays: number): Date {
const now = new Date();
const day = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + offsetDays, 12);
return new Date(day);
}
function utcDateKey(date: Date): string {
return date.toISOString().slice(0, 10);
}
describe("getUtcMonthStart", () => {
it("anchors the monthly spend window to UTC month boundaries", () => {
expect(getUtcMonthStart(new Date("2026-03-31T20:30:00.000-05:00")).toISOString()).toBe(
"2026-04-01T00:00:00.000Z",
);
expect(getUtcMonthStart(new Date("2026-04-01T00:30:00.000+14:00")).toISOString()).toBe(
"2026-03-01T00:00:00.000Z",
);
});
});
describeEmbeddedPostgres("dashboard service", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-dashboard-service-");
db = createDb(tempDb.connectionString);
}, 20_000);
afterEach(async () => {
await db.delete(heartbeatRuns);
await db.delete(agents);
await db.delete(companies);
});
afterAll(async () => {
await tempDb?.cleanup();
});
it("selects distinct task cards before limiting and keeps taskless runs separate", async () => {
const companyId = randomUUID();
const otherCompanyId = randomUUID();
const agentId = randomUUID();
const otherAgentId = randomUUID();
const repeatedIssueId = randomUUID();
const otherIssueId = randomUUID();
const activeRunId = randomUUID();
const otherTaskRunId = randomUUID();
const tasklessRunId = randomUUID();
await db.insert(companies).values([
{ id: companyId, name: "Dashboard cards", issuePrefix: "CARDS" },
{ id: otherCompanyId, name: "Other company", issuePrefix: "OTHER" },
]);
await db.insert(agents).values([
{ id: agentId, companyId, name: "Builder", role: "engineer", adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {}, permissions: {} },
{ id: otherAgentId, companyId: otherCompanyId, name: "Other", role: "engineer", adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {}, permissions: {} },
]);
await db.insert(heartbeatRuns).values([
...Array.from({ length: 6 }, (_, index) => ({
id: randomUUID(), companyId, agentId, status: "succeeded",
contextSnapshot: { issueId: repeatedIssueId },
createdAt: new Date(`2026-04-10T10:0${index}:00.000Z`),
})),
{ id: activeRunId, companyId, agentId, status: "running", contextSnapshot: { issueId: repeatedIssueId }, createdAt: new Date("2026-04-10T08:00:00.000Z") },
{ id: otherTaskRunId, companyId, agentId, status: "succeeded", contextSnapshot: { issueId: otherIssueId }, createdAt: new Date("2026-04-10T09:04:00.000Z") },
{ id: tasklessRunId, companyId, agentId, status: "succeeded", createdAt: new Date("2026-04-10T09:03:00.000Z") },
{ id: randomUUID(), companyId: otherCompanyId, agentId: otherAgentId, status: "running", contextSnapshot: { issueId: otherIssueId }, createdAt: new Date("2026-04-10T11:00:00.000Z") },
]);
expect(await selectDashboardRunIds(db, companyId, 3)).toEqual([
activeRunId, otherTaskRunId, tasklessRunId,
]);
});
it("aggregates the full 14-day run activity window without recent-run truncation", async () => {
const companyId = randomUUID();
const otherCompanyId = randomUUID();
const agentId = randomUUID();
const otherAgentId = randomUUID();
const today = utcDay(0);
const weekAgo = utcDay(-7);
await db.insert(companies).values([
{
id: companyId,
name: "Paperclip",
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
requireBoardApprovalForNewAgents: false,
},
{
id: otherCompanyId,
name: "Other",
issuePrefix: `T${otherCompanyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
requireBoardApprovalForNewAgents: false,
},
]);
await db.insert(agents).values([
{
id: agentId,
companyId,
name: "CodexCoder",
role: "engineer",
status: "running",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
},
{
id: otherAgentId,
companyId: otherCompanyId,
name: "OtherAgent",
role: "engineer",
status: "running",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
},
]);
await db.insert(heartbeatRuns).values([
...Array.from({ length: 105 }, () => ({
id: randomUUID(),
companyId,
agentId,
invocationSource: "assignment",
status: "succeeded",
createdAt: today,
})),
{
id: randomUUID(),
companyId,
agentId,
invocationSource: "assignment",
status: "failed",
createdAt: weekAgo,
},
{
id: randomUUID(),
companyId,
agentId,
invocationSource: "assignment",
status: "timed_out",
createdAt: weekAgo,
},
{
id: randomUUID(),
companyId,
agentId,
invocationSource: "assignment",
status: "cancelled",
createdAt: weekAgo,
},
{
id: randomUUID(),
companyId: otherCompanyId,
agentId: otherAgentId,
invocationSource: "assignment",
status: "succeeded",
createdAt: weekAgo,
},
]);
const summary = await dashboardService(db).summary(companyId);
expect(summary.runActivity).toHaveLength(14);
const todayBucket = summary.runActivity.find((bucket) => bucket.date === utcDateKey(today));
const weekAgoBucket = summary.runActivity.find((bucket) => bucket.date === utcDateKey(weekAgo));
expect(todayBucket).toMatchObject({
succeeded: 105,
failed: 0,
recovered: 0,
other: 0,
total: 105,
failedByErrorCode: {},
});
expect(weekAgoBucket).toMatchObject({
succeeded: 0,
failed: 2,
recovered: 0,
other: 1,
total: 3,
// failed + timed_out with no error code both bucket under "unknown"
failedByErrorCode: { unknown: 2 },
});
});
it("separates recovered restart kills from true failures and breaks failures down by error code", async () => {
const companyId = randomUUID();
const agentId = randomUUID();
const day = utcDay(-2);
await db.insert(companies).values({
id: companyId,
name: "Paperclip",
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values({
id: agentId,
companyId,
name: "CodexCoder",
role: "engineer",
status: "running",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
});
const base = {
companyId,
agentId,
invocationSource: "assignment",
createdAt: day,
};
// Direct recovery: a process-loss kill whose retry succeeded.
const original = randomUUID();
const retry = randomUUID();
// Chained recovery: kill -> failed retry -> succeeded retry (both kills recovered).
const chainedOriginal = randomUUID();
const chainedRetry = randomUUID();
const chainedRetrySuccess = randomUUID();
// A genuine, unrecovered failure that should remain in the failed count.
const trueFailure = randomUUID();
await db.insert(heartbeatRuns).values([
{ ...base, id: original, status: "failed", errorCode: "process_lost" },
{ ...base, id: retry, status: "succeeded", retryOfRunId: original },
{ ...base, id: chainedOriginal, status: "failed", errorCode: "process_lost" },
{ ...base, id: chainedRetry, status: "failed", errorCode: "process_lost", retryOfRunId: chainedOriginal },
{ ...base, id: chainedRetrySuccess, status: "succeeded", retryOfRunId: chainedRetry },
{ ...base, id: trueFailure, status: "failed", errorCode: "provider_quota" },
]);
const summary = await dashboardService(db).summary(companyId);
const bucket = summary.runActivity.find((b) => b.date === utcDateKey(day));
expect(bucket).toMatchObject({
succeeded: 2,
// original + chainedOriginal + chainedRetry all recovered via a later success
recovered: 3,
failed: 1,
other: 0,
total: 6,
failedByErrorCode: { provider_quota: 1 },
});
// process_lost kills that recovered must not leak into the failed breakdown.
expect(bucket?.failedByErrorCode.process_lost).toBeUndefined();
});
});