mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-29 12:59:13 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Product E2E tests verify tasks through the application and retain reports. > - A final screenshot cannot show the complete task conversation. > - Debugging a result requires the earlier requests, replies, and answers. > - This pull request captures task conversations before fixture cleanup and adds them to Test details. > - Reviewers can read each task thread without a running test instance. ## Linked Issues or Issue Description **What existing behavior does this improve?** The task evidence shown in Product E2E campaign reports. **Current behavior** Most task results show screenshots and checks. Screenshots show the final visible state. They omit earlier messages and long replies. Only the first-task suite has a conversation view. **Proposed behavior** Every standard runner attempt captures the saved conversation before cleanup. Test details show full task messages, requests, answers, and native agent progress. Related tasks have separate threads. Failed attempts also retain available history. Partial captures are labeled. **Reason and benefit** Readers can debug a task by reading its conversation. They do not need to reconstruct it from a screenshot or private run logs. GitHub searches found no duplicate PR or issue for this change. This is an improvement to test reporting and does not overlap a planned core feature in ROADMAP.md. **Breaking changes** None. The result adds an optional `taskChat` field. Old results still render. A result without a task has no chat section. Older reports need retained conversation evidence before they can gain this view. ## What Changed - Capture comments through all pages, task briefs, visible request copy, recorded answers, and native progress before fixture cleanup. - Include delegated tasks and standing chats. Preserve available history when a read fails. Report capture limits explicitly. - Add a closed, credential-redacted conversation format to normalized results. Exclude reasoning, raw tool payloads, and provider session metadata. - Render task conversations inside Test details. Retain them through report aggregation and dashboard regeneration. - Add capture, publication-format, regeneration, and browser tests. Update the evidence and security contracts. ## Verification - Report tests: `node node_modules/vitest/vitest.mjs run --config tests/runner-e2e/vitest.config.ts task-chat.test.ts first-task-report.test.ts report.test.ts history.test.ts` — 103 tests passed after review fixes. - Browser tests: `node node_modules/@playwright/test/cli.js test --config tests/runner-e2e/report-playwright.config.ts` — 6 tests passed after rebase. - Targeted TypeScript check of the new capture, renderer, validator, report, and browser-test files passed. - Tests cover a 1,105-message thread, a long final reply, event pagination, partial capture, company access, credential redaction, HTML escaping, and report regeneration. - Review regressions reproduced two failures before repair: the task-run API uses `runId`, and item reviews save verdicts in `result.items`. Capture now follows these contracts. Both regression tests pass. - Greptile reviewed commit `471236438e03e54cc4ad85de6653adf45835063c` at 5/5 with no new findings. The separate Paperclip review execution stopped without an assessment and ended neutral. Its cause is not established; this is not a completed Paperclip assessment. - Execution discovery passed for `core-compatibility.runner-codex.local.message-marker`. No paid provider run was started. - Full local commands were attempted. `pnpm -r typecheck` and `pnpm build` stop because the DB package cannot find `tsx`. `pnpm test:run` stops because the general-server lane cannot find `vitest`. These package dependency links are absent in this checkout. - [Remote CI on the final commit](https://github.com/paperclipai/paperclip/actions/runs/40728689517) passed: typecheck and release registry, all general and serialized test shards, Runner static/Rust/Vitest checks, build, canary dry run, all eight browser E2E shards, and final verification. Security and contributor checks also passed. - Open a new task-based result and expand **Test details**. Read **Task chat** and expand each related task thread. Results without tasks keep their existing layout. ## Risks - Published reports now include fixture conversation text. Capture retains only reviewed display fields and redacts credentials. Fixture authors must keep this text suitable for public reports. - Long threads increase report size. Collection has a 30-second request-admission budget and page limits. It labels incomplete evidence and does not change the workflow grade. - Old reports cannot recover conversation text from screenshots. New attempts must retain the evidence. ## Model Used OpenAI Codex (GPT-6). The exact serving snapshot and context-window size are not exposed in this session. Used reasoning, code execution, repository tools, and browser tests. ## 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>
190 lines
9.8 KiB
TypeScript
190 lines
9.8 KiB
TypeScript
import { sanitizeJson } from "./redaction.js";
|
|
import { questionReportAnswers } from "./interaction-report.js";
|
|
import { collectRunEvents } from "./run-observations.js";
|
|
import { taskChatProgress } from "./task-chat-progress.js";
|
|
|
|
type Row = Record<string, any>;
|
|
interface TaskChatRun {
|
|
runId: string;
|
|
agentId: string;
|
|
runtimeMode?: "legacy" | "native";
|
|
}
|
|
export interface TaskChatMessage {
|
|
id: string;
|
|
at: string | null;
|
|
role: "user" | "agent" | "system";
|
|
author: string;
|
|
kind: "description" | "comment" | "interaction" | "answer" | "progress";
|
|
body: string;
|
|
}
|
|
export interface TaskChatThread {
|
|
issueId: string;
|
|
identifier: string | null;
|
|
title: string;
|
|
status: "complete" | "partial";
|
|
messages: TaskChatMessage[];
|
|
}
|
|
export interface TaskChatEvidence {
|
|
schema: "paperclip.runner-e2e.task-chat/v1";
|
|
capturedAt: string;
|
|
status: "complete" | "partial" | "unavailable";
|
|
threads: TaskChatThread[];
|
|
/** Fixed diagnostic labels only; API errors may contain private response bodies. */
|
|
missing: string[];
|
|
}
|
|
|
|
const rows = (value: unknown): Row[] => {
|
|
if (!Array.isArray(value) || value.some(row => !row || typeof row !== "object" || Array.isArray(row))) {
|
|
throw new Error("Invalid task chat page");
|
|
}
|
|
return value;
|
|
};
|
|
const text = (value: unknown): string => typeof value === "string" ? value : "";
|
|
const at = (value: unknown): string | null => typeof value === "string" && Number.isFinite(Date.parse(value)) ? value : null;
|
|
const lines = (values: unknown[]) => values.filter(value => typeof value === "string" && value.length).join("\n\n");
|
|
|
|
/** Only visible card copy and recorded choices cross the public boundary.
|
|
* Tool arguments, credentials, provider envelopes and arbitrary metadata do not. */
|
|
function cardBody(row: Row): string {
|
|
const p = row.payload ?? {};
|
|
const questions = p.questionSet?.questions ?? p.questions ?? [];
|
|
return lines([row.title, p.title, p.prompt, p.detailsMarkdown, p.questionSet?.title, p.questionSet?.description,
|
|
...rows(questions).map(q => lines([q.prompt, q.helpText,
|
|
...rows(q.options ?? []).map(option => lines([option.label, option.description])),
|
|
])),
|
|
...rows(p.items ?? p.options ?? []).map(item => lines([item.label, item.title, item.description])),
|
|
p.acceptLabel, p.rejectLabel, `Status: ${text(row.status) || "unknown"}`]);
|
|
}
|
|
function answerBody(row: Row): string {
|
|
const questions = rows(row.payload?.questionSet?.questions ?? row.payload?.questions ?? []);
|
|
return lines([row.result?.outcome,
|
|
...questionReportAnswers({ ...row, id: text(row.id) }).map(answer => {
|
|
const q = questions.find(q => q.id === answer.questionId);
|
|
const selected = answer.optionIds ?? answer.selectedOptionIds ?? [];
|
|
return lines([q?.prompt, ...(Array.isArray(selected) ? selected.map(id =>
|
|
rows(q?.options ?? []).find(option => option.id === id)?.label ?? text(id)) : []),
|
|
answer.otherText ?? answer.customText ?? answer.text]);
|
|
}), row.result?.reason,
|
|
...(Array.isArray(row.result?.selectedOptionIds) ? row.result.selectedOptionIds.map((id: string) =>
|
|
rows(row.payload?.items ?? row.payload?.options ?? []).find(item => item.id === id)?.label ?? id) : []),
|
|
...rows(row.result?.items ?? []).map(result => lines([
|
|
rows(row.payload?.items ?? []).find(item => item.id === result.id)?.label ?? text(result.id),
|
|
result.verdict, result.reason,
|
|
])),
|
|
]);
|
|
}
|
|
|
|
export function projectTaskChatThread(issue: Row, comments: Row[], interactions: Row[], names: ReadonlyMap<string, string>): TaskChatThread {
|
|
const messages: TaskChatMessage[] = [];
|
|
if (text(issue.description)) messages.push({ id: `description:${issue.id}`, at: at(issue.createdAt),
|
|
role: "user", author: "Task brief", kind: "description", body: issue.description });
|
|
for (const c of comments) {
|
|
const role = c.authorAgentId || c.authorType === "agent" ? "agent" : c.authorType === "system" ? "system" : "user";
|
|
messages.push({ id: `comment:${c.id}`, at: at(c.createdAt), role,
|
|
author: role === "agent" ? names.get(c.authorAgentId) ?? "Agent" : role === "user" ? "You" : "System",
|
|
kind: "comment", body: text(c.body) });
|
|
}
|
|
for (const card of interactions) {
|
|
messages.push({ id: `interaction:${card.id}`, at: at(card.createdAt), role: "agent", author: "Request",
|
|
kind: "interaction", body: cardBody(card) });
|
|
if (card.result && card.resolvedAt) messages.push({ id: `answer:${card.id}`, at: at(card.resolvedAt),
|
|
role: card.resolvedByAgentId ? "agent" : "user",
|
|
author: card.resolvedByAgentId ? names.get(card.resolvedByAgentId) ?? "Agent" : "You",
|
|
kind: "answer", body: answerBody(card) || text(card.status) });
|
|
}
|
|
messages.sort((a, b) => (a.at ?? "").localeCompare(b.at ?? "") || a.id.localeCompare(b.id));
|
|
return { issueId: text(issue.id), identifier: text(issue.identifier) || null, title: text(issue.title), status: "complete", messages };
|
|
}
|
|
|
|
/** Called once after run retirement and before the disposable instance is removed.
|
|
* Discovery includes delegated tasks; explicit IDs retain standing chats even
|
|
* when the journey has restored the disabled Agent Chat setting. */
|
|
export async function captureTaskChat(input: {
|
|
get: <T>(route: string) => Promise<T>;
|
|
companyId: string;
|
|
issueIds?: readonly string[];
|
|
secrets: readonly string[];
|
|
}): Promise<TaskChatEvidence> {
|
|
const deadlineAt = Date.now() + 30_000;
|
|
const get = <T>(route: string): Promise<T> => {
|
|
if (Date.now() >= deadlineAt) return Promise.reject(new Error("Task chat collection deadline"));
|
|
return input.get<T>(route);
|
|
};
|
|
const evidence: TaskChatEvidence = { schema: "paperclip.runner-e2e.task-chat/v1", capturedAt: new Date().toISOString(),
|
|
status: "complete", threads: [], missing: [] };
|
|
const issues = new Map<string, Row>();
|
|
let names = new Map<string, string>();
|
|
try {
|
|
names = new Map(rows(await get(`/api/companies/${input.companyId}/agents`)).map(agent => [agent.id, text(agent.name) || "Agent"]));
|
|
} catch { evidence.missing.push("agent-names"); }
|
|
try {
|
|
let cursor = "";
|
|
for (let page = 0; ; page++) {
|
|
if (page === 100) throw new Error("Task discovery exceeded page bound");
|
|
const batch = rows(await get(`/api/companies/${input.companyId}/issues?includeAgentCreatedTasks=true&includeRoutineExecutions=true&includePluginOperations=true&sortField=id&sortDir=asc&limit=100${cursor ? `&afterId=${encodeURIComponent(cursor)}` : ""}`));
|
|
if (batch.length > 100) throw new Error("Oversized task discovery page");
|
|
for (const issue of batch) {
|
|
if (!text(issue.id) || issue.id <= cursor || issues.has(issue.id) || issue.companyId !== input.companyId) throw new Error("Invalid task discovery page");
|
|
issues.set(issue.id, issue);
|
|
cursor = issue.id;
|
|
}
|
|
if (batch.length < 100) break;
|
|
}
|
|
} catch { evidence.missing.push("task-discovery"); }
|
|
// Avoid a disabled-chat 404: the setting is often restored by the journey.
|
|
try {
|
|
const settings = await get<Row>("/api/instance/settings/experimental");
|
|
if (settings.enableAgentChat) for (const issue of rows(await get(`/api/companies/${input.companyId}/chats`))) {
|
|
if (issue.companyId !== input.companyId || !text(issue.id)) throw new Error("Foreign chat");
|
|
issues.set(issue.id, issue);
|
|
}
|
|
} catch { evidence.missing.push("chat-discovery"); }
|
|
for (const id of new Set(input.issueIds)) {
|
|
if (issues.has(id)) continue;
|
|
try {
|
|
const issue = await get<Row>(`/api/issues/${encodeURIComponent(id)}`);
|
|
if (issue.companyId !== input.companyId || issue.id !== id) throw new Error("Foreign task");
|
|
issues.set(id, issue);
|
|
} catch { evidence.missing.push("task-read"); }
|
|
}
|
|
for (const issue of issues.values()) {
|
|
const comments: Row[] = [];
|
|
let interactions: Row[] = [];
|
|
let complete = true;
|
|
try {
|
|
let cursor = "";
|
|
const seen = new Set<string>();
|
|
for (let page = 0; ; page++) {
|
|
if (page === 100) throw new Error("Comment capture exceeded page bound");
|
|
const batch = rows(await get(`/api/issues/${issue.id}/comments?order=asc&limit=100${cursor ? `&after=${encodeURIComponent(cursor)}` : ""}`));
|
|
if (batch.length > 100) throw new Error("Oversized comment page");
|
|
for (const comment of batch) {
|
|
if (!text(comment.id) || seen.has(comment.id)) throw new Error("Repeated comment page");
|
|
seen.add(comment.id); comments.push(comment); cursor = comment.id;
|
|
}
|
|
if (batch.length < 100) break;
|
|
}
|
|
} catch { complete = false; evidence.missing.push("comments"); }
|
|
try { interactions = rows(await get(`/api/issues/${issue.id}/interactions`)); }
|
|
catch { complete = false; evidence.missing.push("interactions"); }
|
|
try {
|
|
const thread = projectTaskChatThread(issue, comments, interactions, names);
|
|
try {
|
|
const runs = await get<TaskChatRun[]>(`/api/issues/${issue.id}/runs`);
|
|
rows(runs);
|
|
for (const run of runs.filter(run => run.runtimeMode === "native")) {
|
|
if (!text(run.runId)) throw new Error("Native task run has no runId");
|
|
const events = await collectRunEvents((afterSeq, limit) => get(`/api/heartbeat-runs/${encodeURIComponent(run.runId)}/events?afterSeq=${afterSeq}&limit=${limit}`));
|
|
thread.messages.push(...taskChatProgress(run.runId, events, names.get(run.agentId) ?? "Agent"));
|
|
}
|
|
thread.messages.sort((a, b) => (a.at ?? "").localeCompare(b.at ?? "") || a.id.localeCompare(b.id));
|
|
} catch { complete = false; evidence.missing.push("progress"); }
|
|
thread.status = complete ? "complete" : "partial";
|
|
evidence.threads.push(thread);
|
|
} catch { evidence.missing.push("thread-projection"); }
|
|
}
|
|
evidence.missing = [...new Set(evidence.missing)];
|
|
if (evidence.missing.length) evidence.status = evidence.threads.length ? "partial" : "unavailable";
|
|
return sanitizeJson(evidence, input.secrets) as TaskChatEvidence;
|
|
}
|