From 762d680daf3563d42a0c4c280761c233b21713c7 Mon Sep 17 00:00:00 2001
From: Dotta <34892728+cryppadotta@users.noreply.github.com>
Date: Mon, 12 Oct 2026 08:11:31 -0500
Subject: [PATCH 1/3] feat(ui): upload files directly in task artifacts
(#15964)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
## Thinking Path
> - Paperclip helps people manage agent work and retain its context.
> - Task documents and attachments keep that context with the task.
> - The Artifacts panel showed output but could not accept a new file.
> - Uploading through a message can require resuming a paused task.
> - Existing document and attachment APIs can save files directly.
> - This PR adds direct uploads and a drop target to the task panel.
> - People can add context while keeping work paused and unassigned.
## Linked Issues or Issue Description
**What existing behavior does this improve?**
The task Artifacts panel and its existing document and attachment APIs.
**Subsystem affected**
ui/ — React board UI. No server, schema, or API changes.
**Current behavior**
The Artifacts panel cannot upload a file. It also excludes files
uploaded by people. The message composer can require a task to resume
before it submits attachments.
**Proposed behavior**
Use the upload icon or drop files anywhere in the open Artifacts panel.
The target includes the header, padding, and existing cards. Files save
directly to the task without a message or a pause change.
**Reason and benefit**
People can prepare a handoff on a paused, unassigned task without
starting agent work. Markdown becomes a task document. Other supported
files use attachment storage.
**Breaking changes**
Files from people now appear in Artifacts alongside agent output.
Promoted attachments still appear once. A repeated Markdown filename
creates a separate document instead of replacing an existing revision.
Existing APIs and limits stay the same.
**Additional context**
Related upload API work: Refs #7472 and Refs #7248. This PR adds the
missing task-panel entry point. ROADMAP.md lists Artifacts and Work
Products as available; this is a scoped UI improvement.
## What Changed
- Add an upload icon with no visible label or background.
- Accept file drops across the full task panel, including the desktop
portal header and mobile tabs.
- Show per-file progress and inline Retry and Dismiss actions.
- Import Markdown under a new document key and retain existing
revisions.
- Include files from people in Artifacts and dedupe promoted
attachments.
- Add component and task-journey stories for empty, populated, loading,
error, mobile, and drag-over states.
- Add real browser tests for persistence, pause preservation, duplicate
document names, full-panel drops, and partial failure recovery.
## Verification
- Five Playwright tests passed against an isolated instance started by
the source `test-drive` command. The document API, attachment storage,
pause holds, downloads, and task UI were real. Only the explicit upload
failure was injected.
- The browser tests verified desktop and mobile uploads, document
reading, persistence after reload, no task comments or runs, header
drops, preservation of original and hidden internal documents, reserved
filename handling, and upload retry.
- 163 focused UI tests passed.
- `pnpm -r typecheck` passed.
- `pnpm build` passed.
- `pnpm check:token-gates` passed.
- The full Vitest suite is running after repair of an exhausted local
PostgreSQL shared-memory pool. The initial run failed to initialize
PostgreSQL. Six unattached segments had no living creator or last-user
process; removing them restored free slots.
- CI and the current-head Greptile review are pending.
## Risks
- Artifacts now includes user files, so existing tasks can show more
cards.
- Uploads retain the server's authorization, file-type, size, and
revision checks. No migration is needed.
- Binary attachment uploads use the existing API. A transport failure
with an unknown save outcome can retain the existing API's retry
ambiguity.
## Model Used
OpenAI GPT-6 through Codex. The exact runtime snapshot ID and
context-window size were not exposed to this session. The model used
repository inspection, code editing, shell tools, and browser
automation.
## 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
- [ ] 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
---------
Co-authored-by: Paperclip
---
doc/AGENT-ARTIFACTS.md | 14 ++
tests/e2e/artifact-uploads.spec.ts | 149 ++++++++++++++++++
.../components/artifacts/ArtifactDropzone.tsx | 75 +++++++++
.../artifacts/ArtifactUploadArea.tsx | 22 +++
.../artifacts/ArtifactUploadControls.tsx | 66 ++++++++
.../issue-properties/IssueProperties.tsx | 7 +-
.../IssuePropertiesArtifactsTab.tsx | 30 ++--
...ssuePropertiesMarkdownWorkProduct.test.tsx | 8 +-
.../components/side-panel/SidePanelFrame.tsx | 2 +-
.../task-side-panel/TaskSidePanel.tsx | 15 +-
ui/src/hooks/useIssueArtifactUploads.ts | 65 ++++++++
ui/src/lib/issue-artifact-upload.test.ts | 23 +++
ui/src/lib/issue-artifact-upload.ts | 15 ++
ui/src/lib/issue-artifacts.test.ts | 11 ++
ui/src/lib/issue-artifacts.ts | 9 ++
.../artifact-upload/01-components.stories.tsx | 22 +++
.../02-task-journey.stories.tsx | 59 +++++++
.../stories/artifact-upload/UploadPreview.tsx | 105 ++++++++++++
.../stories/artifact-upload/fixtures.ts | 129 +++++++++++++++
19 files changed, 802 insertions(+), 24 deletions(-)
create mode 100644 tests/e2e/artifact-uploads.spec.ts
create mode 100644 ui/src/components/artifacts/ArtifactDropzone.tsx
create mode 100644 ui/src/components/artifacts/ArtifactUploadArea.tsx
create mode 100644 ui/src/components/artifacts/ArtifactUploadControls.tsx
create mode 100644 ui/src/hooks/useIssueArtifactUploads.ts
create mode 100644 ui/src/lib/issue-artifact-upload.test.ts
create mode 100644 ui/src/lib/issue-artifact-upload.ts
create mode 100644 ui/storybook/stories/artifact-upload/01-components.stories.tsx
create mode 100644 ui/storybook/stories/artifact-upload/02-task-journey.stories.tsx
create mode 100644 ui/storybook/stories/artifact-upload/UploadPreview.tsx
create mode 100644 ui/storybook/stories/artifact-upload/fixtures.ts
diff --git a/doc/AGENT-ARTIFACTS.md b/doc/AGENT-ARTIFACTS.md
index 1d97ee4ae8c..e17d623d6a5 100644
--- a/doc/AGENT-ARTIFACTS.md
+++ b/doc/AGENT-ARTIFACTS.md
@@ -5,6 +5,20 @@ must be attached to the Paperclip issue before the agent chooses a final
disposition. A local workspace path is not enough, because cloud users and
reviewers often cannot access the agent's disk.
+## Upload files from a task
+
+People can open the task's Artifacts tab and use the upload icon, or drop files
+anywhere in the panel, including its header and existing artifact cards. Uploads
+save directly to the task. They do not send a message, assign an agent, or
+release a pause hold. Files from people and agents appear together in Artifacts.
+
+Markdown imports create task documents. Repeated filenames get a new document
+key instead of replacing an existing revision.
+Hidden system keys and artifact-review prefixes are reserved; imports with
+those filenames receive a visible upload document key. Other supported files use
+the existing attachment API and its type and size limits. Failed uploads show
+an inline Retry action while successful files remain available.
+
## Native runner
When `register_deliverable` is available, use it for files in the bound local or
diff --git a/tests/e2e/artifact-uploads.spec.ts b/tests/e2e/artifact-uploads.spec.ts
new file mode 100644
index 00000000000..8dc63aa6fb5
--- /dev/null
+++ b/tests/e2e/artifact-uploads.spec.ts
@@ -0,0 +1,149 @@
+import { randomUUID } from "node:crypto";
+import { expect, test, type APIRequestContext, type APIResponse, type Locator, type Page } from "@playwright/test";
+import { expectTaskPanelTab } from "./helpers/task-panel-tabs";
+
+// Real task UI, document revisions, attachment storage and pause holds.
+// Only the explicit failed-upload response in the recovery test is injected.
+async function json(response: APIResponse) {
+ expect(response.ok(), `${response.status()}: ${await response.text()}`).toBe(true);
+ return response.json();
+}
+
+async function setup(page: Page, request: APIRequestContext, mobile = false) {
+ await page.setViewportSize(mobile ? { width: 390, height: 844 } : { width: 1440, height: 960 });
+ await page.addInitScript(() => localStorage.setItem("paperclip:panel-visible", "true"));
+ const companies = await json(await request.get("/api/companies"));
+ const company = companies.find((row: { name: string }) => row.name === "Artifact Upload Review") ?? await json(await request.post("/api/companies", { data: { name: `Artifact uploads ${randomUUID()}` } }));
+ const issue = await json(await request.post(`/api/companies/${company.id}/issues`, {
+ data: { title: `Upload handoff files ${randomUUID().slice(0, 8)}`, status: "backlog", assigneeAgentId: null, assigneeUserId: null },
+ }));
+ await json(await request.post(`/api/issues/${issue.id}/tree-holds`, { data: { mode: "pause" } }));
+ await page.goto(`/${company.issuePrefix}/issues/${issue.identifier}${mobile ? "?from=inbox&fromHref=%2Finbox%2Fmine" : ""}`);
+ await expect(page.getByRole("heading", { name: issue.title, exact: true })).toBeVisible();
+ if (mobile) {
+ await page.getByRole("button", { name: "More actions", exact: true }).click();
+ await page.getByRole("button", { name: "Properties", exact: true }).click();
+ }
+ const panel = mobile ? page.getByTestId("mobile-task-side-panel") : page.locator("aside").filter({ has: page.getByRole("button", { name: "Open a new tab", exact: true }) });
+ await panel.getByRole("button", { name: "Open a new tab", exact: true }).click();
+ await page.getByRole("option", { name: "Artifacts", exact: true }).click();
+ await expectTaskPanelTab(panel, mobile, "Artifacts");
+ await expect(panel.getByRole("button", { name: "Upload files", exact: true })).toBeVisible();
+ return { company, issue, panel };
+}
+
+async function chooseFiles(page: Page, panel: Locator, files: { name: string; mimeType: string; buffer: Buffer }[]) {
+ const chooser = page.waitForEvent("filechooser");
+ await panel.getByRole("button", { name: "Upload files", exact: true }).click();
+ await (await chooser).setFiles(files);
+}
+
+async function assertStillPaused(request: APIRequestContext, issueId: string) {
+ const issue = await json(await request.get(`/api/issues/${issueId}`));
+ expect(issue.status).toBe("backlog");
+ expect(issue.assigneeAgentId).toBeNull();
+ expect(issue.assigneeUserId).toBeNull();
+ const state = await json(await request.get(`/api/issues/${issueId}/tree-control/state`));
+ expect(state.activePauseHold).not.toBeNull();
+ expect(await json(await request.get(`/api/issues/${issueId}/comments`))).toEqual([]);
+ expect(await json(await request.get(`/api/issues/${issueId}/runs`))).toEqual([]);
+}
+
+for (const mobile of [false, true]) {
+ test(`upload documents and files while a task remains paused (mobile=${mobile})`, async ({ page, request }, testInfo) => {
+ const { issue, panel } = await setup(page, request, mobile);
+ await chooseFiles(page, panel, [
+ { name: "core-handoff.md", mimeType: "text/markdown", buffer: Buffer.from("# Engineering handoff\n\nStart with the loop inventory and preserve current task ownership.") },
+ { name: "loop-inventory.csv", mimeType: "text/csv", buffer: Buffer.from("path,pattern\ndelivery,event-driven\nroutines,clock-driven") },
+ ]);
+ await expect(panel.getByRole("button", { name: "Read document", exact: true })).toBeVisible();
+ await expect(panel.getByRole("link", { name: "Download file", exact: true })).toBeVisible();
+ await expectTaskPanelTab(panel, mobile, "Artifacts");
+ const download = page.waitForEvent("download");
+ await panel.getByRole("link", { name: "Download file", exact: true }).click();
+ expect((await download).suggestedFilename()).toBe("loop-inventory.csv");
+ await panel.getByRole("button", { name: "Read document", exact: true }).click();
+ await expect(panel.getByText("Start with the loop inventory and preserve current task ownership.", { exact: true })).toBeVisible();
+ await assertStillPaused(request, issue.id);
+ await page.reload();
+ await expect(page.getByRole("heading", { name: issue.title, exact: true })).toBeVisible();
+ const documents = await json(await request.get(`/api/issues/${issue.id}/documents`));
+ const attachments = await json(await request.get(`/api/issues/${issue.id}/attachments`));
+ expect(documents).toHaveLength(1);
+ expect(documents[0].key).toBe("core-handoff");
+ expect(attachments).toHaveLength(1);
+ expect(attachments[0].originalFilename).toBe("loop-inventory.csv");
+ await assertStillPaused(request, issue.id);
+ await page.screenshot({ path: testInfo.outputPath("uploaded-handoff-persisted.png"), fullPage: true });
+ });
+}
+
+test("the entire populated panel accepts a drop and preserves an existing document", async ({ page, request }, testInfo) => {
+ const { issue, panel } = await setup(page, request);
+ await chooseFiles(page, panel, [{ name: "handoff.md", mimeType: "text/markdown", buffer: Buffer.from("# Original handoff\n\nPreserve this version.") }]);
+ await expect(panel.getByRole("button", { name: "Read document", exact: true })).toBeVisible();
+ const transfer = await page.evaluateHandle(() => {
+ const data = new DataTransfer();
+ data.items.add(new File(["# Additional handoff\n\nNew reference, separate document."], "handoff.md", { type: "text/markdown" }));
+ data.items.add(new File(["Check saved deadlines before enabling instance sleep."], "verification.txt", { type: "text/plain" }));
+ return data;
+ });
+ const header = panel.locator("[data-presentation] > header");
+ await header.dispatchEvent("dragenter", { dataTransfer: transfer });
+ const overlay = panel.locator("[data-artifact-drop-overlay]");
+ await expect(overlay).toBeVisible();
+ const frameBounds = await panel.locator("[data-presentation]").boundingBox();
+ const overlayBounds = await overlay.boundingBox();
+ expect(overlayBounds).toEqual(frameBounds);
+ await page.screenshot({ path: testInfo.outputPath("entire-panel-dropzone.png"), fullPage: true });
+ await header.dispatchEvent("dragleave", { dataTransfer: transfer });
+ await expect(overlay).toBeHidden();
+ await header.dispatchEvent("dragenter", { dataTransfer: transfer });
+ await panel.locator("article").first().dispatchEvent("drop", { dataTransfer: transfer });
+ await expect(panel.getByRole("button", { name: "Read document", exact: true })).toHaveCount(2);
+ await expect(panel.getByText("verification.txt", { exact: true }).first()).toBeVisible();
+ const documents = await json(await request.get(`/api/issues/${issue.id}/documents`));
+ expect(documents.map((row: { key: string }) => row.key).sort()).toEqual(["handoff", "handoff-2"]);
+ expect(documents.find((row: { key: string }) => row.key === "handoff").body).toContain("Preserve this version.");
+ await assertStillPaused(request, issue.id);
+});
+
+test("a failed upload stays local and retry preserves the successful files", async ({ page, request }) => {
+ const { issue, panel } = await setup(page, request);
+ let fail = true;
+ await page.route(`**/api/companies/*/issues/${issue.id}/attachments`, async route => {
+ if (fail) { fail = false; await route.fulfill({ status: 422, contentType: "application/json", body: JSON.stringify({ error: "Upload failed. Try again." }) }); }
+ else await route.continue();
+ });
+ await chooseFiles(page, panel, [
+ { name: "failed-reference.txt", mimeType: "text/plain", buffer: Buffer.from("Reference restored after retry.") },
+ { name: "saved-reference.txt", mimeType: "text/plain", buffer: Buffer.from("Keep this successful file.") },
+ ]);
+ await expect(panel.getByRole("button", { name: "Retry", exact: true })).toBeVisible();
+ await expect.poll(async () => (await json(await request.get(`/api/issues/${issue.id}/attachments`))).length).toBe(1);
+ await panel.getByRole("button", { name: "Retry", exact: true }).click();
+ await expect(panel.getByRole("button", { name: "Retry", exact: true })).toBeHidden();
+ await expect.poll(async () => (await json(await request.get(`/api/issues/${issue.id}/attachments`))).map((row: { originalFilename: string }) => row.originalFilename).sort()).toEqual(["failed-reference.txt", "saved-reference.txt"]);
+ await assertStillPaused(request, issue.id);
+});
+
+test("reserved filenames create visible documents without replacing internal revisions", async ({ page, request }) => {
+ const { issue, panel } = await setup(page, request);
+ const reserved = ["artifact-review-notes", "continuation-summary", "pipeline-case-body"];
+ const originals = new Map();
+ for (const key of reserved) {
+ const document = await json(await request.put(`/api/issues/${issue.id}/documents/${key}`, {
+ data: { title: "Internal context", format: "markdown", body: `Preserve the internal ${key} document.`, baseRevisionId: null },
+ }));
+ originals.set(key, document.latestRevisionId);
+ }
+ await chooseFiles(page, panel, reserved.map(key => ({ name: `${key}.md`, mimeType: "text/markdown", buffer: Buffer.from(`# Uploaded ${key}\n\nThis reference must stay visible.`) })));
+ await expect(panel.getByRole("button", { name: "Read document", exact: true })).toHaveCount(3);
+ const documents = await json(await request.get(`/api/issues/${issue.id}/documents`));
+ expect(documents.filter((row: { key: string }) => row.key.startsWith("upload-")).map((row: { key: string }) => row.key).sort()).toEqual(reserved.map(key => `upload-${key}`).sort());
+ for (const key of reserved) {
+ const document = await json(await request.get(`/api/issues/${issue.id}/documents/${key}`));
+ expect(document.latestRevisionId).toBe(originals.get(key));
+ }
+ await assertStillPaused(request, issue.id);
+});
diff --git a/ui/src/components/artifacts/ArtifactDropzone.tsx b/ui/src/components/artifacts/ArtifactDropzone.tsx
new file mode 100644
index 00000000000..7830ac1bc0a
--- /dev/null
+++ b/ui/src/components/artifacts/ArtifactDropzone.tsx
@@ -0,0 +1,75 @@
+import { useEffect, useRef, useState, type ReactNode } from "react";
+import { createPortal } from "react-dom";
+import { Upload } from "lucide-react";
+
+/** The target can be the host frame when its tab header is rendered by a portal. */
+export function ArtifactDropzone({ children, onUpload, enabled = true, target }: {
+ children: ReactNode;
+ onUpload: (files: File[]) => void;
+ enabled?: boolean;
+ target?: HTMLElement | null;
+}) {
+ const rootRef = useRef(null);
+ const uploadRef = useRef(onUpload);
+ uploadRef.current = onUpload;
+ const [dragging, setDragging] = useState(false);
+
+ useEffect(() => {
+ const element = target ?? rootRef.current;
+ setDragging(false);
+ if (!enabled || !element) return;
+ let depth = 0;
+ const hasFiles = (event: DragEvent) => Array.from(event.dataTransfer?.types ?? []).includes("Files");
+ const enter = (event: DragEvent) => {
+ if (!hasFiles(event)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ depth += 1;
+ setDragging(true);
+ };
+ const over = (event: DragEvent) => {
+ if (!hasFiles(event)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
+ };
+ const leave = (event: DragEvent) => {
+ if (!hasFiles(event)) return;
+ event.stopPropagation();
+ depth = Math.max(0, depth - 1);
+ if (depth === 0) setDragging(false);
+ };
+ const drop = (event: DragEvent) => {
+ if (!hasFiles(event)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ depth = 0;
+ setDragging(false);
+ const files = Array.from(event.dataTransfer?.files ?? []);
+ if (files.length) uploadRef.current(files);
+ };
+ element.addEventListener("dragenter", enter);
+ element.addEventListener("dragover", over);
+ element.addEventListener("dragleave", leave);
+ element.addEventListener("drop", drop);
+ return () => {
+ element.removeEventListener("dragenter", enter);
+ element.removeEventListener("dragover", over);
+ element.removeEventListener("dragleave", leave);
+ element.removeEventListener("drop", drop);
+ };
+ }, [enabled, target]);
+
+ const overlay = dragging ? (
+
+
+
Drop files to add them to this task
+
+ ) : null;
+ return (
+
+ {children}
+ {target && overlay ? createPortal(overlay, target) : overlay}
+
+ );
+}
diff --git a/ui/src/components/artifacts/ArtifactUploadArea.tsx b/ui/src/components/artifacts/ArtifactUploadArea.tsx
new file mode 100644
index 00000000000..5b36c005c25
--- /dev/null
+++ b/ui/src/components/artifacts/ArtifactUploadArea.tsx
@@ -0,0 +1,22 @@
+import type { ReactNode } from "react";
+import { SidePanelFrame } from "@/components/side-panel/SidePanelFrame";
+import { ArtifactDropzone } from "./ArtifactDropzone";
+import { ArtifactUploadButton, ArtifactUploadContent, type ArtifactUploadEntry } from "./ArtifactUploadControls";
+export type { ArtifactUploadEntry } from "./ArtifactUploadControls";
+
+/** Standalone composition of the same controls used by task panel hosts. */
+export function ArtifactUploadArea({ children, header, empty = false, entries = [], onUpload, onRetry, onDismiss }: {
+ children?: ReactNode;
+ header?: ReactNode;
+ empty?: boolean;
+ entries?: ArtifactUploadEntry[];
+ onUpload: (files: File[]) => void;
+ onRetry?: (id: string) => void;
+ onDismiss?: (id: string) => void;
+}) {
+ return
+ }>
+ {children}
+
+ ;
+}
diff --git a/ui/src/components/artifacts/ArtifactUploadControls.tsx b/ui/src/components/artifacts/ArtifactUploadControls.tsx
new file mode 100644
index 00000000000..ae86a645890
--- /dev/null
+++ b/ui/src/components/artifacts/ArtifactUploadControls.tsx
@@ -0,0 +1,66 @@
+import { useRef, type ReactNode } from "react";
+import { FileUp, Loader2, Upload, X } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+
+export interface ArtifactUploadEntry {
+ id: string;
+ filename: string;
+ status: "uploading" | "error";
+ error?: string;
+}
+
+export function ArtifactUploadButton({ onUpload }: { onUpload: (files: File[]) => void }) {
+ const inputRef = useRef(null);
+ return <>
+ {
+ const files = Array.from(event.target.files ?? []);
+ event.target.value = "";
+ if (files.length) onUpload(files);
+ }} />
+
+
+
+
+ Upload files
+
+ >;
+}
+
+export function ArtifactUploadContent({ children, empty = false, entries = [], onRetry, onDismiss }: {
+ children?: ReactNode;
+ empty?: boolean;
+ entries?: ArtifactUploadEntry[];
+ onRetry?: (id: string) => void;
+ onDismiss?: (id: string) => void;
+}) {
+ return
+ {entries.length > 0 ?
+ {entries.map((entry) => -
+ {entry.status === "uploading"
+ ?
+ : }
+
+ {entry.filename}
+
+ {entry.status === "uploading" ? "Uploading…" : entry.error ?? "Upload failed. Try again."}
+
+
+ {entry.status === "error" ?
+ {onRetry ? : null}
+ {onDismiss ? : null}
+
: null}
+ )}
+
: null}
+ {empty ?
+
+
+
Add files to this task
+
Drop files anywhere in this panel or use the upload icon.
+
+
: children}
+
;
+}
diff --git a/ui/src/components/issue-properties/IssueProperties.tsx b/ui/src/components/issue-properties/IssueProperties.tsx
index 2b00c76abae..2eb00aa6503 100644
--- a/ui/src/components/issue-properties/IssueProperties.tsx
+++ b/ui/src/components/issue-properties/IssueProperties.tsx
@@ -29,7 +29,7 @@ import { issuesApi } from "../../api/issues";
import { useIssuePlanDocument } from "@/hooks/useIssuePlanDocument";
import { useIssueDocuments } from "@/hooks/useIssueDocuments";
import { useStreamlinedUiEnabled } from "@/hooks/useStreamlinedUiEnabled";
-import { selectAgentArtifactAttachments } from "@/lib/issue-artifacts";
+import { selectArtifactAttachments } from "@/lib/issue-artifacts";
import { projectsApi } from "../../api/projects";
import { useCompany } from "../../context/CompanyContext";
import { useSidebar } from "../../context/SidebarContext";
@@ -321,12 +321,11 @@ export function IssueProperties({
|| paneTabStandaloneDocuments.length > 0;
// Artifacts covers the same three sources the tab body composes: work
// products, documents (redundant with the Plan tab, intentionally), and
- // agent-created attachments. User comment uploads stay thread-only and
- // no longer summon the tab.
+ // attachments from agents and people.
const hasArtifactsTab =
(paneTabWorkProducts?.length ?? 0) > 0
|| paneTabStandaloneDocuments.length > 0
- || selectAgentArtifactAttachments(paneTabAttachments, paneTabWorkProducts).length > 0;
+ || selectArtifactAttachments(paneTabAttachments, paneTabWorkProducts).length > 0;
const [paneTab, setPaneTab] = useState("properties");
const [closedPaneTabs, setClosedPaneTabs] = useState>(() => new Set());
// Once a plan document exists, surface it: switch the pane to the Plan tab so
diff --git a/ui/src/components/issue-properties/IssuePropertiesArtifactsTab.tsx b/ui/src/components/issue-properties/IssuePropertiesArtifactsTab.tsx
index 17d1bd1cffc..bc573fba519 100644
--- a/ui/src/components/issue-properties/IssuePropertiesArtifactsTab.tsx
+++ b/ui/src/components/issue-properties/IssuePropertiesArtifactsTab.tsx
@@ -1,5 +1,6 @@
import { TextAttachmentContext } from "@/context/TextAttachmentContext";
-import { useContext, useEffect, useMemo, useRef, useState } from "react";
+import { useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { ArtifactUploadContent, type ArtifactUploadEntry } from "@/components/artifacts/ArtifactUploadControls";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type {
AttachmentArtifactWorkProductMetadata,
@@ -23,7 +24,7 @@ import { useIssueDocuments } from "@/hooks/useIssueDocuments";
import { useIssueWorkProducts } from "@/hooks/useIssueWorkProducts";
import {
documentDisplayTitle,
- selectAgentArtifactAttachments,
+ selectArtifactAttachments,
} from "@/lib/issue-artifacts";
import { DocumentCard } from "@/components/artifacts/RichArtifactCards";
import {
@@ -44,6 +45,7 @@ import { useLocation } from "@/lib/router";
interface IssuePropertiesArtifactsTabProps {
issue: Issue;
+ uploadState?: { entries: ArtifactUploadEntry[]; retry: (id: string) => void; dismiss: (id: string) => void };
onOpenDocument?: (document: IssueDocument) => void;
documentDeepLink?: {
requestId: number;
@@ -355,17 +357,16 @@ function DocumentRow({
/**
* Artifacts tab of the properties pane (PAP-491).
*
- * A read-only "what did this task produce" view composed from three sources:
+ * Task files and output composed from three sources:
* work products, issue documents (also readable in the Plan tab — the
- * redundancy is intentional), and agent-created attachments. Attachments
- * already promoted to attachment-backed work products are deduped out, and
- * user uploads are excluded — those stay first-class in the conversation
- * thread.
+ * redundancy is intentional), and attachments from agents and people.
+ * Attachments already promoted to work products are deduped out.
*/
export function IssuePropertiesArtifactsTab({
issue,
documentDeepLink,
onOpenDocument,
+ uploadState,
}: IssuePropertiesArtifactsTabProps) {
const {
data: attachments,
@@ -406,7 +407,7 @@ export function IssuePropertiesArtifactsTab({
const reviewDocsByKey = new Map(
(documents ?? []).map((doc) => [doc.key, doc]),
);
- const fileRows = selectAgentArtifactAttachments(attachments, workProducts);
+ const fileRows = selectArtifactAttachments(attachments, workProducts);
const runsById = useMemo(
() => new Map((runs ?? []).map((run) => [run.runId, run])),
[runs],
@@ -513,21 +514,26 @@ export function IssuePropertiesArtifactsTab({
) : null;
+ const withUploads = (content: ReactNode, empty = false) => uploadState ? (
+ {content}
+ ) : content;
+
if (
workProductRows.length === 0 &&
documentRows.length === 0 &&
fileRows.length === 0
) {
- if (feedback) return feedback;
- return (
+ if (feedback) return withUploads(feedback);
+ return withUploads(
No artifacts yet. Work products, documents, and agent-produced files
will appear here.
-
+ ,
+ true,
);
}
- return (
+ return withUploads(
{feedback}
{groupedRows.map((group) => {
diff --git a/ui/src/components/issue-properties/IssuePropertiesMarkdownWorkProduct.test.tsx b/ui/src/components/issue-properties/IssuePropertiesMarkdownWorkProduct.test.tsx
index 0b52378d5e4..d2fc25f5ffc 100644
--- a/ui/src/components/issue-properties/IssuePropertiesMarkdownWorkProduct.test.tsx
+++ b/ui/src/components/issue-properties/IssuePropertiesMarkdownWorkProduct.test.tsx
@@ -415,7 +415,7 @@ describe("markdown work product review row", () => {
expect(container.querySelector("button[aria-expanded]")).toBeNull();
});
- it.each(["image/png", "application/octet-stream"])("renders %s media tiles without duplicates or user uploads", async (contentType) => {
+ it.each(["image/png", "application/octet-stream"])("renders %s media tiles with user uploads and without promoted duplicates", async (contentType) => {
const image = { ...makeMarkdownAttachment(), contentType, originalFilename: "cover.png" };
const looseImage = { ...image, id: "loose-image", contentPath: "/api/attachments/loose-image/content" };
const video = { ...makeMarkdownAttachment(), id: "loose-video", contentType: "application/octet-stream", originalFilename: "clip.mp4", contentPath: "/api/attachments/loose-video/content" };
@@ -427,11 +427,11 @@ describe("markdown work product review row", () => {
await renderTab({}, "Cover artwork");
await waitForAssertion(() => {
const buttons = container.querySelectorAll('button[aria-label^="View image:"], button[aria-label^="Open video:"]');
- expect(buttons).toHaveLength(3);
+ expect(buttons).toHaveLength(4);
expect(container.querySelectorAll("img")).toHaveLength(2);
- expect(container.querySelectorAll("article")).toHaveLength(3);
+ expect(container.querySelectorAll("article")).toHaveLength(4);
expect(container.querySelector("video")?.getAttribute("src")).toBe(video.contentPath);
- expect(container.querySelectorAll("video")).toHaveLength(1);
+ expect(container.querySelectorAll("video")).toHaveLength(2);
});
});
diff --git a/ui/src/components/side-panel/SidePanelFrame.tsx b/ui/src/components/side-panel/SidePanelFrame.tsx
index 614455e81b4..320c9cde4ff 100644
--- a/ui/src/components/side-panel/SidePanelFrame.tsx
+++ b/ui/src/components/side-panel/SidePanelFrame.tsx
@@ -49,7 +49,7 @@ export function SidePanelFrame({
data-maximized={maximized ? "true" : "false"}
data-resizing={resizing ? "true" : "false"}
className={cn(
- "flex min-h-0 min-w-0 flex-col overflow-hidden bg-(--side-panel-bg) text-(--side-panel-fg)",
+ "relative flex min-h-0 min-w-0 flex-col overflow-hidden bg-(--side-panel-bg) text-(--side-panel-fg)",
presentation === "docked" && "h-full border-l border-border",
presentation === "sheet" && "h-full w-full",
presentation === "embedded" && "h-full rounded-xl border border-border",
diff --git a/ui/src/components/task-side-panel/TaskSidePanel.tsx b/ui/src/components/task-side-panel/TaskSidePanel.tsx
index 3e1e5e754f0..ee28cab900d 100644
--- a/ui/src/components/task-side-panel/TaskSidePanel.tsx
+++ b/ui/src/components/task-side-panel/TaskSidePanel.tsx
@@ -37,6 +37,9 @@ import { WorkspaceFileBrowser } from "@/components/WorkspaceFileBrowser";
import { AgentArtifactsPanel, AgentTasksPanel } from "@/components/chat/AgentWorkPanels";
import { useAgentChatEnabled } from "@/hooks/useAgentChatEnabled";
import { IssuePropertiesArtifactsTab } from "@/components/issue-properties/IssuePropertiesArtifactsTab";
+import { ArtifactDropzone } from "@/components/artifacts/ArtifactDropzone";
+import { ArtifactUploadButton } from "@/components/artifacts/ArtifactUploadControls";
+import { useIssueArtifactUploads } from "@/hooks/useIssueArtifactUploads";
import { IssuePropertiesPlansTab } from "@/components/issue-properties/IssuePropertiesPlansTab";
import { TaskDetailSubtasksPanel } from "@/components/task-detail/TaskDetailRelationsPanel";
import {
@@ -274,6 +277,7 @@ export function TaskSidePanel({
const conversationAgentId = agentChatEnabled ? issue.conversationAgentId ?? null : null;
const showRelatedTasks = showSubtasksTab && !conversationAgentId;
const viewer = useTaskSidePanelFileRouting();
+ const artifactUploads = useIssueArtifactUploads(issue);
const { data: documentsData } = useIssueDocuments(issue.id);
const documents = documentsData ?? EMPTY_ISSUE_DOCUMENTS;
const { data: planDocument } = useIssuePlanDocument(issue.id);
@@ -353,6 +357,7 @@ export function TaskSidePanel({
}
}, [openBrowserId, controller.activeTabId, onBrowserOpened, accountScope, issue.companyId, issue.id, fileTabsEnabled]);
const activeTab = controller.tabs.find((tab) => tab.id === controller.activeTabId) ?? null;
+ const canUploadArtifacts = activeTab?.payload.kind === "artifacts" && !conversationAgentId && !issue.id.startsWith("chat:");
const subtasksAvailable = showRelatedTasks && (taskCount > 0 || tasksTab?.hasError === true);
const hasSubtasksTab = controller.tabs.some((tab) => tab.id === "subtasks");
@@ -760,7 +765,7 @@ export function TaskSidePanel({
markInteracted();
controller.openTab(taskPanelAttachmentTab(id, title));
if (viewer.state || viewer.browse) viewer.close();
- }}>
;
+ }}>
;
} else if (activeTab.payload.kind === "issue-document") {
content = activeTab.payload.documentKey === "plan" ? (
@@ -815,11 +820,14 @@ export function TaskSidePanel({
}
const contentMode = activeTab?.contentMode ?? "full-bleed";
+ const header = <>{tabStrip}{canUploadArtifacts ?
: null}>;
return (
+
("[data-presentation]")} onUpload={artifactUploads.upload}>
- {paneHeaderSlot ? createPortal(tabStrip, paneHeaderSlot) : (
+
{artifactUploads.announcement}
+ {paneHeaderSlot ? createPortal(header, paneHeaderSlot) : (
- {tabStrip}
+ {header}
{onRequestClose ? (
mobile ? (
+
);
}
diff --git a/ui/src/hooks/useIssueArtifactUploads.ts b/ui/src/hooks/useIssueArtifactUploads.ts
new file mode 100644
index 00000000000..bc058b77fc4
--- /dev/null
+++ b/ui/src/hooks/useIssueArtifactUploads.ts
@@ -0,0 +1,65 @@
+import { useCallback, useRef, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import type { Issue, IssueAttachment, IssueDocument } from "@paperclipai/shared";
+import { issuesApi } from "@/api/issues";
+import { queryKeys } from "@/lib/queryKeys";
+import { uploadedDocumentKey } from "@/lib/issue-artifact-upload";
+import type { ArtifactUploadEntry } from "@/components/artifacts/ArtifactUploadControls";
+
+export function useIssueArtifactUploads(issue: Pick
) {
+ const client = useQueryClient();
+ const [entries, setEntries] = useState([]);
+ const [announcement, setAnnouncement] = useState("");
+ const files = useRef(new Map());
+ const queue = useRef>(Promise.resolve());
+
+ const enqueue = useCallback((batch: { id: string; file: File }[]) => {
+ for (const { id, file } of batch) files.current.set(id, file);
+ setEntries(current => [
+ ...current.filter(entry => !batch.some(file => file.id === entry.id)),
+ ...batch.map(({ id, file }): ArtifactUploadEntry => ({ id, filename: file.name, status: "uploading" })),
+ ]);
+ // Serialize imports so repeated filenames in successive selections get
+ // distinct keys. The server still rejects concurrent document creates.
+ queue.current = queue.current.then(async () => {
+ for (const { id, file } of batch) {
+ try {
+ if (/\.(md|markdown)$/i.test(file.name) || file.type === "text/markdown") {
+ const body = await file.text();
+ const documents = await issuesApi.listDocuments(issue.id);
+ const basename = file.name.replace(/\.[^.]+$/, "");
+ const key = uploadedDocumentKey(file.name, documents.map(document => document.key));
+ const document = await issuesApi.upsertDocument(issue.id, key, {
+ title: basename.replace(/[-_]+/g, " ").slice(0, 200), format: "markdown", body, baseRevisionId: null,
+ });
+ client.setQueryData([...queryKeys.issues.documents(issue.id), "list"], current => [document, ...(current ?? []).filter(row => row.id !== document.id)]);
+ void client.invalidateQueries({ queryKey: queryKeys.issues.documents(issue.id) });
+ } else {
+ const attachment = await issuesApi.uploadAttachment(issue.companyId, issue.id, file);
+ client.setQueryData(queryKeys.issues.attachments(issue.id), current => [attachment, ...(current ?? []).filter(row => row.id !== attachment.id)]);
+ void client.invalidateQueries({ queryKey: queryKeys.issues.attachments(issue.id) });
+ }
+ void client.invalidateQueries({ queryKey: queryKeys.issues.detail(issue.id) });
+ files.current.delete(id);
+ setEntries(current => current.filter(entry => entry.id !== id));
+ setAnnouncement(`${file.name} added to this task.`);
+ } catch (error) {
+ setEntries(current => current.map(entry => entry.id === id ? {
+ ...entry, status: "error", error: error instanceof Error ? error.message : "Upload failed. Try again.",
+ } : entry));
+ }
+ }
+ });
+ }, [client, issue.companyId, issue.id]);
+
+ const upload = useCallback((picked: File[]) => enqueue(picked.map(file => ({ id: crypto.randomUUID(), file }))), [enqueue]);
+ const retry = useCallback((id: string) => {
+ const file = files.current.get(id);
+ if (file) enqueue([{ id, file }]);
+ }, [enqueue]);
+ const dismiss = useCallback((id: string) => {
+ files.current.delete(id);
+ setEntries(current => current.filter(entry => entry.id !== id));
+ }, []);
+ return { entries, announcement, upload, retry, dismiss };
+}
diff --git a/ui/src/lib/issue-artifact-upload.test.ts b/ui/src/lib/issue-artifact-upload.test.ts
new file mode 100644
index 00000000000..d4cfb1d58c8
--- /dev/null
+++ b/ui/src/lib/issue-artifact-upload.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vitest";
+import { isArtifactReviewDocumentKey, isSystemIssueDocumentKey, issueDocumentKeySchema } from "@paperclipai/shared";
+import { uploadedDocumentKey } from "./issue-artifact-upload";
+
+describe("uploadedDocumentKey", () => {
+ it.each(["artifact-review-notes", "continuation-summary", "pipeline-case-body"])("keeps %s uploads visible and separate from internal documents", (reserved) => {
+ const key = uploadedDocumentKey(`${reserved}.md`, [reserved]);
+ expect(key).toBe(`upload-${reserved}`);
+ expect(isArtifactReviewDocumentKey(key)).toBe(false);
+ expect(isSystemIssueDocumentKey(key)).toBe(false);
+ expect(uploadedDocumentKey(`${reserved}.md`, [key])).toBe(`${key}-2`);
+ });
+
+ it("preserves existing filename-derived documents and bounds long keys", () => {
+ expect(uploadedDocumentKey("Core handoff.md", ["core-handoff", "core-handoff-2"])).toBe("core-handoff-3");
+ const filename = `artifact-review-${"notes-".repeat(30)}.md`;
+ const first = uploadedDocumentKey(filename, []);
+ const repeated = uploadedDocumentKey(filename, [first]);
+ expect(issueDocumentKeySchema.safeParse(repeated).success).toBe(true);
+ expect(isArtifactReviewDocumentKey(repeated)).toBe(false);
+ expect(repeated).not.toBe(first);
+ });
+});
diff --git a/ui/src/lib/issue-artifact-upload.ts b/ui/src/lib/issue-artifact-upload.ts
new file mode 100644
index 00000000000..61355412d50
--- /dev/null
+++ b/ui/src/lib/issue-artifact-upload.ts
@@ -0,0 +1,15 @@
+import { isArtifactReviewDocumentKey, isSystemIssueDocumentKey } from "@paperclipai/shared";
+
+/** Uploaded filenames must never select a hidden or internal document key. */
+export function uploadedDocumentKey(filename: string, existingKeys: Iterable): string {
+ const slug = filename.replace(/\.[^.]+$/, "").toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "document";
+ const visibleSlug = isSystemIssueDocumentKey(slug) || isArtifactReviewDocumentKey(slug)
+ ? `upload-${slug}` : slug;
+ const base = visibleSlug.slice(0, 54);
+ const keys = new Set(existingKeys);
+ let key = base;
+ let suffix = 2;
+ while (keys.has(key)) key = `${base}-${suffix++}`;
+ return key;
+}
diff --git a/ui/src/lib/issue-artifacts.test.ts b/ui/src/lib/issue-artifacts.test.ts
index 42dc6d3ee8b..1326c06a778 100644
--- a/ui/src/lib/issue-artifacts.test.ts
+++ b/ui/src/lib/issue-artifacts.test.ts
@@ -5,6 +5,7 @@ import {
getAttachmentBackedWorkProductAttachmentIds,
isAgentAttachment,
selectAgentArtifactAttachments,
+ selectArtifactAttachments,
workProductHref,
} from "./issue-artifacts";
@@ -134,6 +135,16 @@ describe("selectAgentArtifactAttachments", () => {
});
});
+describe("selectArtifactAttachments", () => {
+ it("includes files from people while deduping promoted files", () => {
+ const promotedId = "00000000-0000-4000-8000-000000000001";
+ const user = makeAttachment({ id: "user-file", createdByUserId: "user-1", issueCommentId: "comment-1" });
+ const agent = makeAttachment({ id: "agent-file", createdByAgentId: "agent-1" });
+ const promoted = makeAttachment({ id: promotedId, createdByUserId: "user-1" });
+ expect(selectArtifactAttachments([user, agent, promoted], [makePromotingWorkProduct(promotedId)])).toEqual([user, agent]);
+ });
+});
+
describe("getAttachmentBackedWorkProductAttachmentIds", () => {
it("collects attachment ids across content types", () => {
const imageId = "00000000-0000-4000-8000-000000000001";
diff --git a/ui/src/lib/issue-artifacts.ts b/ui/src/lib/issue-artifacts.ts
index f3f3d8a6d1f..e7af1582bbb 100644
--- a/ui/src/lib/issue-artifacts.ts
+++ b/ui/src/lib/issue-artifacts.ts
@@ -51,6 +51,15 @@ export function selectAgentArtifactAttachments(
);
}
+/** All task files, regardless of author, with promoted work products deduped. */
+export function selectArtifactAttachments(
+ attachments: IssueAttachment[] | null | undefined,
+ workProducts: IssueWorkProduct[] | null | undefined,
+): IssueAttachment[] {
+ const promoted = getAttachmentBackedWorkProductAttachmentIds(workProducts);
+ return (attachments ?? []).filter(attachment => !promoted.has(attachment.id));
+}
+
/**
* Where a work-product row should link. Many rows carry `url: null` with the
* usable link only in metadata — `openPath` for attachment-backed artifacts
diff --git a/ui/storybook/stories/artifact-upload/01-components.stories.tsx b/ui/storybook/stories/artifact-upload/01-components.stories.tsx
new file mode 100644
index 00000000000..2e33e82d78b
--- /dev/null
+++ b/ui/storybook/stories/artifact-upload/01-components.stories.tsx
@@ -0,0 +1,22 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { UploadPreview } from "./UploadPreview";
+import { showFileDrag } from "./fixtures";
+
+const meta = {
+ title: "Artifact upload/01 Artifacts pane", component: UploadPreview,
+ parameters: { layout: "fullscreen", docs: { description: { component: "The upload icon sits in the tab header without text or a background. The entire Artifacts panel, including its header, padding, existing cards and empty space, accepts files. Drag-over stories enter through the actual header drag handler and highlight the complete visible panel, including after scrolling. Use the upload icon for one or several files. Markdown becomes a document; other files use artifact cards. Uploads are simulated in memory and reset when the story reloads. The Uploading story holds its example pending; Retry completes the sample CSV upload. No task or execution state changes." }, story: { inline: false } } },
+ argTypes: { state: { control: "select", options: ["empty", "populated", "uploading", "error", "long"] } },
+ render: (args, context) =>
,
+} satisfies Meta;
+export default meta;
+type Story = StoryObj;
+export const Empty: Story = { args: { state: "empty" } };
+export const Populated: Story = { args: { state: "populated" } };
+export const Uploading: Story = { args: { state: "uploading" } };
+export const RetryUpload: Story = { args: { state: "error" } };
+export const LongReference: Story = { args: { state: "long" } };
+export const DragOverEmptyPanel: Story = { args: { state: "empty" }, play: ({ canvasElement }) => showFileDrag(canvasElement) };
+export const DragOverExistingArtifacts: Story = { args: { state: "populated" }, play: ({ canvasElement }) => showFileDrag(canvasElement) };
+export const DragOverScrolledArtifacts: Story = { args: { state: "long" }, play: ({ canvasElement }) => showFileDrag(canvasElement, true) };
+export const Mobile: Story = { args: { state: "populated" }, globals: { viewport: { value: "mobile", isRotated: false } } };
+export const MobileError: Story = { args: { state: "error" }, globals: { viewport: { value: "mobile", isRotated: false } } };
diff --git a/ui/storybook/stories/artifact-upload/02-task-journey.stories.tsx b/ui/storybook/stories/artifact-upload/02-task-journey.stories.tsx
new file mode 100644
index 00000000000..6068e2d1848
--- /dev/null
+++ b/ui/storybook/stories/artifact-upload/02-task-journey.stories.tsx
@@ -0,0 +1,59 @@
+import { useEffect, useState } from "react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { Route, Routes } from "@/lib/router";
+import { Layout } from "@/components/Layout";
+import { TaskChatBubble } from "@/components/task-chat/TaskChatBubble";
+import { TaskChatPausedTakeover } from "@/components/task-chat/TaskChatPausedTakeover";
+import { StatusBadge } from "@/components/StatusBadge";
+import { Button } from "@/components/ui/button";
+import { ArrowLeft, Box, X } from "lucide-react";
+import { PluginLauncherProvider } from "@/plugins/launchers";
+import { useBreadcrumbs } from "@/context/BreadcrumbContext";
+import { useSidebar } from "@/context/SidebarContext";
+import { UploadPreview } from "./UploadPreview";
+import { issue, showFileDrag, type PreviewState } from "./fixtures";
+
+function TaskPage({ state = "empty", panelOpenInitially = false }: { state?: PreviewState; panelOpenInitially?: boolean }) {
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const { isMobile: mobile } = useSidebar();
+ const [open, setOpen] = useState(panelOpenInitially);
+ useEffect(() => { setBreadcrumbs([{ label: "Tasks", href: "/PAP/issues" }, { label: issue.title, identifier: issue.identifier ?? undefined }]); }, [setBreadcrumbs]);
+ return
+
+
+
+
+
PAP-214Unassigned
+ {mobile ?
: null}
+
+ {issue.title}
+
+
+
+
+
+
+
+
;
+}
+
+function Journey(props: { state?: PreviewState; panelOpenInitially?: boolean }) {
+ return }>} />;
+}
+
+const meta = {
+ title: "Artifact upload/02 Paused task journey", component: Journey,
+ parameters: { layout: "fullscreen", initialEntries: ["/PAP/issues/PAP-214"], docs: { description: { component: "Start on the paused, unassigned PAP-214 placeholder in the production app shell. Upload or drop files in Artifacts, open a document in another tab, then return to Artifacts. On mobile, open Artifacts from the task header. Uses production chat bubbles, paused takeover, panel frame, desktop/mobile tabs, artifact list and document viewer. The story composes these components for review; upload persistence is simulated. No live issue is modified or resumed." }, story: { inline: false } } },
+ render: (args, context) => ,
+} satisfies Meta;
+export default meta;
+type Story = StoryObj;
+export const AddToPlaceholder: Story = { args: { state: "empty" } };
+export const HandoffAttached: Story = { args: { state: "populated" } };
+export const DragOverArtifacts: Story = { args: { state: "populated" }, play: ({ canvasElement }) => showFileDrag(canvasElement) };
+export const RecoverAnUpload: Story = { args: { state: "error" } };
+export const MobileFromTask: Story = { args: { state: "empty" }, globals: { viewport: { value: "mobile", isRotated: false } } };
+export const MobileArtifacts: Story = { args: { state: "populated", panelOpenInitially: true }, globals: { viewport: { value: "mobile", isRotated: false } } };
diff --git a/ui/storybook/stories/artifact-upload/UploadPreview.tsx b/ui/storybook/stories/artifact-upload/UploadPreview.tsx
new file mode 100644
index 00000000000..556346f750b
--- /dev/null
+++ b/ui/storybook/stories/artifact-upload/UploadPreview.tsx
@@ -0,0 +1,105 @@
+import { useLayoutEffect, useRef, useState, type MouseEvent } from "react";
+import { QueryClientProvider, useQuery } from "@tanstack/react-query";
+import type { IssueDocument } from "@paperclipai/shared";
+import { ArtifactUploadArea, type ArtifactUploadEntry } from "@/components/artifacts/ArtifactUploadArea";
+import { IssuePropertiesArtifactsTab } from "@/components/issue-properties/IssuePropertiesArtifactsTab";
+import { TaskDocumentPanel } from "@/components/task-side-panel/TaskDocumentPanel";
+import { SidePanelFrame } from "@/components/side-panel/SidePanelFrame";
+import { SidePanelTabs } from "@/components/side-panel/SidePanelTabs";
+import { SidePanelMobileTabs } from "@/components/side-panel/SidePanelMobileTabs";
+import type { SidePanelTabItem } from "@/components/side-panel/types";
+import { queryKeys } from "@/lib/queryKeys";
+import { useSidebar } from "@/context/SidebarContext";
+import { addPreviewFile, createPreviewClient, installPreviewApi, issue, type PreviewState } from "./fixtures";
+
+export function UploadPreview({ state = "empty" }: { state?: PreviewState }) {
+ const [client] = useState(() => createPreviewClient(state));
+ const [entries, setEntries] = useState(() => state === "error" ? [{ id: "failed-upload", filename: "remaining-work.csv", status: "error", error: "Connection lost. Your file hasn’t been added." }] : state === "uploading" ? [{ id: "pending-upload", filename: "remaining-work.csv", status: "uploading" }] : []);
+ const files = useRef(new Map());
+ const alive = useRef(true);
+ const [announcement, setAnnouncement] = useState("");
+ const [tabs, setTabs] = useState([{ id: "artifacts", type: "view", label: "Artifacts", closable: false }]);
+ const [activeTab, setActiveTab] = useState("artifacts");
+ const [selectedDocuments, setSelectedDocuments] = useState>({});
+ const { isMobile: mobile } = useSidebar();
+ const docQuery = useQuery({ queryKey: [...queryKeys.issues.documents(issue.id), "list"], queryFn: async () => [] as IssueDocument[], initialData: client.getQueryData([...queryKeys.issues.documents(issue.id), "list"]), staleTime: Infinity }, client);
+ const productQuery = useQuery({ queryKey: queryKeys.issues.workProducts(issue.id), queryFn: async () => [], initialData: client.getQueryData(queryKeys.issues.workProducts(issue.id)), staleTime: Infinity }, client);
+
+ useLayoutEffect(() => {
+ alive.current = true;
+ files.current.set("failed-upload", new File(["path,pattern\ndelivery,event-driven\nroutines,clock-driven"], "remaining-work.csv", { type: "text/csv" }));
+ const restore = installPreviewApi(client);
+ return () => { alive.current = false; restore(); };
+ }, [client]);
+
+ async function upload(batch: { id: string; file: File }[]) {
+ for (const { id, file } of batch) {
+ files.current.set(id, file);
+ setEntries(current => [...current.filter(entry => entry.id !== id), { id, filename: file.name, status: "uploading" }]);
+ }
+ await Promise.all(batch.map(async ({ id, file }) => {
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ if (!alive.current) return;
+ try {
+ await addPreviewFile(client, file, id);
+ setEntries(current => current.filter(entry => entry.id !== id));
+ setAnnouncement(`${file.name} added to this task.`);
+ files.current.delete(id);
+ } catch {
+ setEntries(current => current.map(entry => entry.id === id ? { ...entry, status: "error", error: "This file couldn’t be read. Try again." } : entry));
+ }
+ }));
+ }
+
+ function openDocument(document: IssueDocument) {
+ setSelectedDocuments(current => ({ ...current, [document.key]: document }));
+ setTabs(current => current.some(tab => tab.id === document.key) ? current : [...current, { id: document.key, type: "document", label: document.title ?? document.key, closable: true }]);
+ setActiveTab(document.key);
+ }
+
+ function closeTab(id: string) {
+ if (id === "artifacts") return;
+ setTabs(current => current.filter(tab => tab.id !== id));
+ if (activeTab === id) setActiveTab("artifacts");
+ }
+
+ function handlePreviewLink(event: MouseEvent) {
+ const link = (event.target as HTMLElement).closest("a");
+ if (!link) return;
+ const url = new URL(link.href, window.location.origin);
+ const key = url.searchParams.get("doc");
+ if (key) {
+ const document = docQuery.data?.find(doc => doc.key === key);
+ if (document) { event.preventDefault(); openDocument(document); }
+ return;
+ }
+ const attachmentMatch = url.pathname.match(/^\/api\/attachments\/([^/]+)\/content$/);
+ const file = attachmentMatch && client.getQueryData(["storybook-upload-file", attachmentMatch[1]]);
+ if (!file) return;
+ event.preventDefault();
+ // Browser navigations bypass the in-memory fetch fixture. Supply the
+ // preview's bytes locally for the production card's open/download links.
+ const href = URL.createObjectURL(file);
+ if (url.searchParams.has("download")) {
+ const download = window.document.createElement("a");
+ download.href = href;
+ download.download = file.name;
+ download.click();
+ } else window.open(href, "_blank", "noopener,noreferrer");
+ window.setTimeout(() => URL.revokeObjectURL(href), 60_000);
+ }
+
+ const tabProps = { tabs, activeTabId: activeTab, onActiveTabChange: setActiveTab, onCloseTab: closeTab };
+ const header = mobile ? : ;
+ return
+
+
{announcement}
+ {activeTab === "artifacts" ?
void upload(picked.map(file => ({ id: crypto.randomUUID(), file })))}
+ onRetry={id => { const file = files.current.get(id); if (file) void upload([{ id, file }]); }}
+ onDismiss={id => { files.current.delete(id); setEntries(current => current.filter(entry => entry.id !== id)); }}>
+
+ :
}
+
+ ;
+}
diff --git a/ui/storybook/stories/artifact-upload/fixtures.ts b/ui/storybook/stories/artifact-upload/fixtures.ts
new file mode 100644
index 00000000000..0bf665ff862
--- /dev/null
+++ b/ui/storybook/stories/artifact-upload/fixtures.ts
@@ -0,0 +1,129 @@
+import type { IssueDocument, IssueWorkProduct } from "@paperclipai/shared";
+import { queryKeys } from "@/lib/queryKeys";
+import { uploadedDocumentKey } from "@/lib/issue-artifact-upload";
+import { QueryClient } from "@tanstack/react-query";
+import { createIssue, storybookAgents } from "../../fixtures/paperclipData";
+
+export const issue = createIssue({
+ id: "artifact-upload-placeholder", identifier: "PAP-214", issueNumber: 214,
+ title: "Instance sleep — engineering handoff", status: "backlog",
+ assigneeAgentId: null, assigneeUserId: null, executionRunId: null,
+ checkoutRunId: null, executionLockedAt: null, currentExecutionWorkspace: null,
+ executionWorkspaceId: null, documentSummaries: [], workProducts: [],
+});
+
+export const handoffBody = `# Instance sleep: engineering handoff
+
+Paperclip should release idle database connections and let inactive instances sleep without losing scheduled work, incoming events, accounting, or recovery.
+
+## Start here
+
+The inventory records the remaining work. The implementation notes explain the patterns already in use. Quiet delivery queues alone do not establish whole-instance sleep.
+
+## References
+
+- [Loop inventory](?doc=loop-inventory)
+- [Implementation notes](?doc=implementation-notes)
+
+## Current direction
+
+Work caused by a committed change should run from that event. Work caused by the passage of time belongs in one instance-wide scheduler.
+
+## What comes next
+
+1. Migrate the remaining clock-driven work to the scheduler.
+2. Prove the full writer-admission and idle/resume boundary.
+3. Verify actual app and database sleep with the hosting providers.
+`;
+
+export function makeDocument(key: string, title: string, body: string): IssueDocument {
+ return {
+ id: `document-${key}`, issueId: issue.id, companyId: issue.companyId,
+ key, title, format: "markdown", body, latestRevisionId: `revision-${key}`,
+ latestRevisionNumber: 1, createdByAgentId: null, updatedByAgentId: null,
+ createdByUserId: "user-board", updatedByUserId: "user-board",
+ lockedAt: null, lockedByAgentId: null, lockedByUserId: null,
+ createdAt: new Date("2026-10-12T15:00:00Z"), updatedAt: new Date("2026-10-12T15:00:00Z"),
+ };
+}
+
+export const documents = [
+ makeDocument("core-handoff", "Instance sleep: engineering handoff", handoffBody),
+ makeDocument("loop-inventory", "Loop inventory", "# Loop inventory\n\n| Path | Pattern | Next action |\n| --- | --- | --- |\n| Durable delivery queues | Wake after commit | Verify idle boundary |\n| Routine schedules | Saved deadline | Register with scheduler |\n| Browser live events | Visibility-aware connection | Verify disconnect on hide |\n\n## Completion evidence\n\nRecord the source, change and verification result for each item."),
+ makeDocument("implementation-notes", "Implementation notes", "# Implementation notes\n\nDurable queue rows remain authoritative. A producer registers intent before its write; the database owner defers delivery wakes until the outer transaction settles.\n\n## Recovery\n\nKeep startup scans and saved retry deadlines. Empty, settled queues need no recurring scan.\n\n## Boundary\n\nSignals are process-local to one database owner and its dedicated child pools. Cross-process handoff needs separate fencing."),
+];
+
+export type PreviewState = "empty" | "populated" | "uploading" | "error" | "long";
+
+/** Enter through the real DOM drag handler so stories show the actual state. */
+export function showFileDrag(canvas: HTMLElement, scroll = false) {
+ const panel = canvas.querySelector('[aria-label="Artifact uploads"]');
+ if (!panel) throw new Error("Artifacts drop target is missing");
+ if (scroll) {
+ const viewport = panel.querySelector("[data-side-panel-content-viewport]");
+ if (viewport) viewport.scrollTop = viewport.scrollHeight;
+ }
+ const transfer = new DataTransfer();
+ transfer.items.add(new File(["# New reference\n\nAdded through the Artifacts panel."], "new-reference.md", { type: "text/markdown" }));
+ // Include the tab header in the target rather than only the inner file list.
+ const target = panel.querySelector("header") ?? panel;
+ target.dispatchEvent(new DragEvent("dragenter", { bubbles: true, cancelable: true, dataTransfer: transfer }));
+}
+
+export function createPreviewClient(state: PreviewState) {
+ const client = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } });
+ client.setQueryData([...queryKeys.issues.documents(issue.id), "list"], state === "empty" ? [] : state === "long" ? [...documents, makeDocument("long-reference", "Database transaction recovery and instance sleep: detailed engineering reference with verification evidence", Array.from({ length: 20 }, (_, index) => `## Investigation ${index + 1}\n\nCheck the transaction outcome before retrying uncertain writes. Preserve the durable receipt and current task state.`).join("\n\n"))] : documents);
+ client.setQueryData(queryKeys.issues.attachments(issue.id), []);
+ client.setQueryData(queryKeys.issues.workProducts(issue.id), []);
+ client.setQueryData(queryKeys.issues.runs(issue.id), []);
+ client.setQueryData(queryKeys.agents.list(issue.companyId), storybookAgents);
+ return client;
+}
+
+// File bytes and mutations stay in this preview's memory. No live task changes.
+export async function addPreviewFile(client: QueryClient, file: File, id: string) {
+ if (/\.(md|markdown)$/i.test(file.name) || file.type === "text/markdown") {
+ const body = await file.text();
+ const current = client.getQueryData([...queryKeys.issues.documents(issue.id), "list"]) ?? [];
+ const title = file.name.replace(/\.[^.]+$/, "").replace(/[-_]/g, " ");
+ const key = uploadedDocumentKey(file.name, current.map(document => document.key));
+ client.setQueryData([...queryKeys.issues.documents(issue.id), "list"], [makeDocument(key, title, body), ...current]);
+ return;
+ }
+ client.setQueryData(["storybook-upload-file", id], file);
+ const contentPath = `/api/attachments/${id}/content`;
+ const product: IssueWorkProduct = {
+ id, companyId: issue.companyId, issueId: issue.id, projectId: issue.projectId,
+ executionWorkspaceId: null, runtimeServiceId: null, type: "artifact", provider: "paperclip",
+ externalId: null, title: file.name, url: null, status: "active", reviewState: "none",
+ isPrimary: false, healthStatus: "healthy", summary: null, createdByRunId: null,
+ metadata: { attachmentId: id, contentType: file.type || "application/octet-stream", byteSize: file.size, contentPath, openPath: contentPath, downloadPath: `${contentPath}?download=1`, originalFilename: file.name },
+ createdAt: new Date("2026-10-12T15:01:00Z"), updatedAt: new Date("2026-10-12T15:01:00Z"),
+ };
+ client.setQueryData(queryKeys.issues.workProducts(issue.id), (current = []) => [product, ...current]);
+}
+
+export function installPreviewApi(client: QueryClient) {
+ const originalFetch = window.fetch;
+ const fixtureFetch: typeof window.fetch = async (input, init) => {
+ const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url, window.location.origin);
+ const base = `/api/issues/${issue.id}`;
+ const attachmentMatch = url.pathname.match(/^\/api\/attachments\/([^/]+)\/content$/);
+ if (attachmentMatch) {
+ const file = client.getQueryData(["storybook-upload-file", attachmentMatch[1]]);
+ if (file) return new Response(file, { headers: { "Content-Type": file.type || "application/octet-stream" } });
+ }
+ if (url.pathname === `${base}/work-products`) return Response.json(client.getQueryData(queryKeys.issues.workProducts(issue.id)) ?? []);
+ if (url.pathname === `${base}/attachments`) return Response.json([]);
+ if (url.pathname === `${base}/documents`) return Response.json(client.getQueryData([...queryKeys.issues.documents(issue.id), "list"]) ?? []);
+ if (url.pathname.startsWith(`${base}/documents/`)) {
+ if (url.pathname.endsWith("/annotations")) return Response.json([]);
+ const key = decodeURIComponent(url.pathname.split("/").at(-1)!);
+ const document = (client.getQueryData([...queryKeys.issues.documents(issue.id), "list"]) ?? []).find((doc) => doc.key === key);
+ return document ? Response.json(document) : Response.json({ error: "Document not found" }, { status: 404 });
+ }
+ return originalFetch(input, init);
+ };
+ window.fetch = fixtureFetch;
+ return () => { if (window.fetch === fixtureFetch) window.fetch = originalFetch; };
+}
From ce15fe7c73e7a60ee05c13e74f93b140424b9bb7 Mon Sep 17 00:00:00 2001
From: Dotta <34892728+cryppadotta@users.noreply.github.com>
Date: Mon, 12 Oct 2026 08:15:21 -0500
Subject: [PATCH 2/3] refactor(heartbeat): extract task context preparation
(#15872)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Heartbeat execution prepares task context before it selects an
environment and starts an adapter.
> - This preparation still occupied 319 lines inside the executor after
the earlier extractions.
> - It combines continuation summaries, comments, prompt variants,
communication guidance, and redaction.
> - This pull request moves that responsibility into one typed module
under `services/heartbeat/`.
> - The executor keeps admission, resource ownership, dispatch, and
cleanup ordering together.
> - The result makes the preparation phase easier to find and test
without changing execution behavior.
## Linked Issues or Issue Description
Refs #15825, #15807. This continues the incremental heartbeat extraction
series. A search found no duplicate task-context extraction.
**What existing behavior does this improve?**
Maintenance and review of heartbeat task context preparation.
**Current behavior**
The executor assembles prompts and trust-filtered context inline. This
hides its execution phases among preparation details.
**Proposed behavior**
Call `prepareHeartbeatTaskContext` at the same point in execution.
Preserve statement order, prompt contents, public exports, and the
shared run context object.
## What Changed
- Move task context assembly to
`server/src/services/heartbeat/task-context.ts`. Inputs group task
state, policy, and two existing service methods. Results preserve the
continuation and wake values used by later runtime selection and
dispatch.
- Keep company-scoped loading, quarantined-content filtering, secret
redaction, and revision hashing in their original order. Add no
execution resource acquisition.
- Add four public-path integration tests before the move. Cover prompt
variants and redacted revisions, quarantined summaries/comments, a
mixed-company wake batch, and stale caller fields.
- Extend the real process worker in the opt-in browser suite to check
persisted prompt variants and the description revision before it
completes its task.
- Update the module map and acceptance-test documentation.
- Reduce `heartbeat.ts` from 5,314 lines / 220,784 bytes to 4,989 lines
/ 206,650 bytes. The new module has 376 lines / 15,912 bytes.
## Verification
- Before the move: 11 existing prompt tests and all four new
characterization tests passed against the inline implementation.
- Normalized syntax comparison passed for all 319 moved lines and the
remaining orchestrator, including public exports. Imports and the typed
boundary were reviewed separately.
- `pnpm -r typecheck` passed.
- `pnpm build` passed.
- The clean post-move focused run passed all 26 tests in five files,
with no skips: task-context characterization, task-markdown, Slack
invitation, accepted-plan workspace refresh, and run-preparation.
- The local `pnpm test:run` attempt was interrupted after database
failures while the Mac exhausted its shared-memory slots. All 15
affected native warm-ownership database cases passed in an isolated
rerun after the browser instance stopped; the other 666 cases in that
file were excluded by the test-name filter. The interrupted command is
not a full-suite pass. Full CI passed on
`6bf86cfdc07e7fe34015f7b719218639f4232510`: 55 successful checks and two
optional Storybook checks skipped. Greptile reviewed the latest commit
at 5/5; its one earlier worker-test finding is fixed and resolved.
- Browser E2E passed both scenarios on the final code: persistent
timeouts stop after three runs and survive reload; one timeout recovers
without manual Retry, verifies task-context prompt variants/revision and
preserved workspace files in a real process, then completes through the
run-scoped API. The first recovery attempt exposed an incorrect new test
assertion because the fixture title equals its description. The worker
now checks the description section specifically; the corrected recovery
scenario passed in 55.9 seconds. The original failure trace was
preserved. These tests use a deterministic process adapter and make no
live model calls.
## Risks
This is a behavior-preserving extraction. The main risks are changed
closure bindings, missing return values, or changed preparation order.
Typed inputs, public-path tests, and syntax comparison cover those
risks. The run context is still the same mutable object. The helper
acquires no leases or processes. It introduces no schema, API, or prompt
policy changes.
The first post-move database run skipped cases due to host resource
exhaustion. All 26 focused cases passed on the subsequent clean run.
Browser E2E passed after the worker assertion fix. The full local suite
remains incomplete. All 15 native warm-ownership database cases passed
on their isolated rerun; The full CI test suite passed on the final
commit.
## Model Used
OpenAI Codex, based on GPT-6, with reasoning, repository inspection,
code execution, and test tools. The host does not expose the exact
deployment model ID or context-window size.
## 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
---
doc/DEVELOPING.md | 13 +-
.../__tests__/heartbeat-task-context.test.ts | 177 +++++++++
server/src/services/heartbeat.ts | 343 +---------------
server/src/services/heartbeat/task-context.ts | 376 ++++++++++++++++++
tests/e2e/workspace-bootstrap/README.md | 4 +-
tests/e2e/workspace-bootstrap/worker.mjs | 12 +
6 files changed, 589 insertions(+), 336 deletions(-)
create mode 100644 server/src/__tests__/heartbeat-task-context.test.ts
create mode 100644 server/src/services/heartbeat/task-context.ts
diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md
index ae811577a16..79d71fb4012 100644
--- a/doc/DEVELOPING.md
+++ b/doc/DEVELOPING.md
@@ -1279,9 +1279,20 @@ When a workspace service runs Paperclip for browser OAuth QA, configure its `exp
Keep relevant heartbeat extractions and their focused tests in `server/src/services/heartbeat/`.
Task assignment Markdown is rendered by `server/src/services/heartbeat/task-markdown.ts`.
-`heartbeat.ts` calls the renderer and re-exports it for existing callers. Keep prompt
+`heartbeat.ts` re-exports it for existing callers. Keep prompt
formatting changes in the renderer and its tests, separate from run orchestration.
+Task context assembly is in `server/src/services/heartbeat/task-context.ts`.
+`prepareHeartbeatTaskContext` rebuilds prompt fields on the current run context:
+continuation summaries, wake comments, task plans, communication guidance, and
+full/compact assignment Markdown. It preserves quarantine and secret redaction
+before computing turn-context revisions. The executor supplies the already-loaded
+issue, session, and trust policy, and retains admission, resource ownership, and
+cleanup. Public-path characterization tests are in
+`server/src/__tests__/heartbeat-task-context.test.ts`; the workspace-bootstrap
+browser fixture also checks the persisted prompt variants and description revision
+from a real process adapter before completing its task.
+
Run-log formatting is in `server/src/services/heartbeat/run-log.ts`. It bounds
stored event payloads, redacts and shortens log chunks, and caps stdout/stderr
excerpts. `heartbeat.ts` keeps event writes, current-user redaction, and live
diff --git a/server/src/__tests__/heartbeat-task-context.test.ts b/server/src/__tests__/heartbeat-task-context.test.ts
new file mode 100644
index 00000000000..bca00d2a403
--- /dev/null
+++ b/server/src/__tests__/heartbeat-task-context.test.ts
@@ -0,0 +1,177 @@
+import { createHash, randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { agents, companies, createDb, heartbeatRuns, issueComments, issues } from "@paperclipai/db";
+import { FAST_RESPONSE_AGENT_GUIDANCE } from "@paperclipai/shared";
+import { registerServerAdapter, unregisterServerAdapter, type AdapterExecutionContext } from "../adapters/index.js";
+import { heartbeatService } from "../services/heartbeat.js";
+import { documentService } from "../services/documents.js";
+import { ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY } from "../services/issue-continuation-summary.js";
+import { createRunSecretRedactionRegistry } from "../services/run-secret-redaction.js";
+import { buildLowTrustSourceTrust, LOW_TRUST_QUARANTINED_BODY } from "../services/source-trust.js";
+import { REDACTED_EVENT_VALUE } from "../redaction.js";
+import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
+
+const support = await getEmbeddedPostgresTestSupport();
+const describePostgres = support.supported ? describe : describe.skip;
+if (!support.supported) console.warn(`Skipping heartbeat task context tests: ${support.reason}`);
+
+describePostgres("heartbeat task context delivered to an adapter", () => {
+ const adapterType = "task_context_test";
+ const captured = new Map();
+ let temporary: Awaited>;
+ let db: ReturnType;
+ let heartbeat: ReturnType;
+
+ beforeAll(async () => {
+ temporary = await startEmbeddedPostgresTestDatabase("heartbeat-task-context-");
+ db = createDb(temporary.connectionString);
+ heartbeat = heartbeatService(db);
+ registerServerAdapter({
+ type: adapterType,
+ supportsLocalAgentJwt: false,
+ execute: async (input) => {
+ captured.set(input.runId, input);
+ return { exitCode: 0, signal: null, timedOut: false, sessionId: "context-session", resultJson: {} };
+ },
+ testEnvironment: async () => ({ adapterType, status: "pass", checks: [], testedAt: new Date().toISOString() }),
+ });
+ }, 30_000);
+
+ afterAll(async () => {
+ await heartbeat?.drainActiveRunExecutions();
+ unregisterServerAdapter(adapterType);
+ await db?.$client.end({ timeout: 0 });
+ await temporary?.cleanup();
+ });
+
+ async function seed() {
+ const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: "Task context fixture", issuePrefix: `T${companyId.slice(0, 6)}` });
+ await db.insert(agents).values({ id: agentId, companyId, name: "Context reader", adapterType, status: "idle" });
+ await db.insert(issues).values({
+ id: issueId, companyId, title: "Task context fixture", description: "Assignment description canary",
+ status: "todo", assigneeAgentId: agentId, responsibleUserId: "context-user", issueNumber: 1,
+ });
+ return { companyId, agentId, issueId };
+ }
+
+ async function execute(f: Awaited>, context: Record) {
+ const run = await heartbeat.wakeup(f.agentId, {
+ source: "on_demand", triggerDetail: "manual", reason: "issue_assigned",
+ payload: { issueId: f.issueId }, contextSnapshot: { issueId: f.issueId, ...context },
+ });
+ expect(run).not.toBeNull();
+ await heartbeat.drainActiveRunExecutions();
+ const finished = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run!.id)).then(rows => rows[0]);
+ expect(finished?.status, finished?.error ?? undefined).toBe("succeeded");
+ expect(captured.has(run!.id)).toBe(true);
+ return captured.get(run!.id)!;
+ }
+
+ it("keeps assignment, wake, compact, and revision context aligned after secret redaction", async () => {
+ const f = await seed();
+ const secret = "task-context-secret-canary";
+ const description = `Assignment description canary ${secret}`;
+ await db.update(issues).set({ description }).where(eq(issues.id, f.issueId));
+ const previousRunId = randomUUID();
+ await db.insert(heartbeatRuns).values({
+ id: previousRunId, companyId: f.companyId, agentId: f.agentId,
+ invocationSource: "on_demand", status: "succeeded", contextSnapshot: { issueId: f.issueId },
+ });
+ await createRunSecretRedactionRegistry(db).register(f.companyId, previousRunId, secret);
+ const commentId = randomUUID();
+ await db.insert(issueComments).values({
+ id: commentId, companyId: f.companyId, issueId: f.issueId, authorType: "user", authorUserId: "context-user",
+ body: `Wake comment canary ${secret}`,
+ });
+ const { context } = await execute(f, {
+ wakeCommentId: commentId, wakeCommentIds: [commentId],
+ paperclipTaskCommunicationGuidance: "FORGED caller guidance", paperclipSkillTest: { directive: "FORGED skill" },
+ paperclipContinuationSummary: { body: "FORGED summary" },
+ });
+ expect(context.paperclipTaskMarkdown).toContain("Assignment description canary");
+ expect(context.paperclipTaskMarkdown).toContain("Wake comment canary");
+ expect(context.paperclipTaskMarkdownAssignment).toContain("Assignment description canary");
+ expect(context.paperclipTaskMarkdownAssignment).not.toContain("Wake comment canary");
+ expect(context.paperclipTaskMarkdownCompact).not.toContain("Assignment description canary");
+ expect(context.paperclipTaskMarkdownCompact).toContain("Wake comment canary");
+ expect(context.paperclipTaskMarkdownAssignmentCompact).not.toContain("Assignment description canary");
+ expect(context.paperclipTaskMarkdownAssignmentCompact).not.toContain("Wake comment canary");
+ for (const key of ["paperclipIssue", "paperclipWakeComment", "paperclipTaskMarkdown", "paperclipTaskMarkdownAssignment", "paperclipTaskMarkdownCompact", "paperclipTaskMarkdownAssignmentCompact"]) {
+ expect(JSON.stringify(context[key])).not.toContain(secret);
+ }
+ expect(context.paperclipTaskCommunicationGuidance).toBe(FAST_RESPONSE_AGENT_GUIDANCE);
+ expect(context.paperclipSkillTest).toBeUndefined();
+ expect(context.paperclipContinuationSummary).toBeUndefined();
+ const digest = (value: string) => createHash("sha256").update(value).digest("hex");
+ expect(context.paperclipTurnContext).toMatchObject({
+ version: 1,
+ assignment: { owner: "task_markdown", description: { id: f.issueId, revision: digest(`Assignment description canary ${REDACTED_EVENT_VALUE}`) } },
+ events: { owner: "wake_prompt", comments: [{ id: commentId, revision: digest(`Wake comment canary ${REDACTED_EVENT_VALUE}`) }] },
+ });
+ });
+
+ it("quarantines low-trust summaries and comments before preparing higher-trust prompts", async () => {
+ const f = await seed();
+ const sourceTrust = buildLowTrustSourceTrust({ issueId: f.issueId });
+ await documentService(db).upsertIssueDocument({
+ issueId: f.issueId, key: ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY, format: "markdown",
+ body: "QUARANTINED summary canary", sourceTrust,
+ });
+ const commentId = randomUUID();
+ await db.insert(issueComments).values({
+ id: commentId, companyId: f.companyId, issueId: f.issueId, authorType: "user", authorUserId: "context-user",
+ body: "QUARANTINED comment canary", sourceTrust,
+ });
+ const { context } = await execute(f, { wakeCommentId: commentId, wakeCommentIds: [commentId] });
+ expect(context.paperclipContinuationSummary).toMatchObject({ body: LOW_TRUST_QUARANTINED_BODY });
+ expect(context.paperclipWakeComment).toMatchObject({ body: LOW_TRUST_QUARANTINED_BODY, presentation: null, metadata: null });
+ expect(context.paperclipTaskMarkdown).toContain(LOW_TRUST_QUARANTINED_BODY);
+ for (const key of ["paperclipContinuationSummary", "executionContinuation", "paperclipWakeComment", "paperclipTaskMarkdown", "paperclipTaskMarkdownCompact", "paperclipWakePayload"]) {
+ expect(JSON.stringify(context[key]) ?? "").not.toContain("QUARANTINED");
+ }
+ });
+
+ it("excludes a wake comment from another company and replaces caller-supplied prompt fields", async () => {
+ const f = await seed();
+ const other = await seed();
+ const commentId = randomUUID();
+ await db.insert(issueComments).values({
+ id: commentId, companyId: other.companyId, issueId: other.issueId, authorType: "user", authorUserId: "other-user",
+ body: "OTHER COMPANY private comment",
+ });
+ const ownCommentId = randomUUID();
+ await db.insert(issueComments).values({
+ id: ownCommentId, companyId: f.companyId, issueId: f.issueId, authorType: "user", authorUserId: "context-user",
+ body: "Authorized wake comment",
+ });
+ const { context } = await execute(f, {
+ wakeCommentId: ownCommentId, wakeCommentIds: [ownCommentId, commentId],
+ paperclipWakeComment: { body: "FORGED comment" }, paperclipTaskMarkdown: "FORGED prompt",
+ paperclipTaskMarkdownAssignment: "FORGED assignment", paperclipTaskMarkdownCompact: "FORGED compact",
+ paperclipTaskMarkdownAssignmentCompact: "FORGED compact assignment",
+ });
+ expect(context.paperclipWakeComment).toMatchObject({ id: ownCommentId, body: "Authorized wake comment" });
+ expect(context.paperclipTaskMarkdown).toContain("Assignment description canary");
+ for (const key of ["paperclipTaskMarkdown", "paperclipTaskMarkdownAssignment", "paperclipTaskMarkdownCompact", "paperclipTaskMarkdownAssignmentCompact", "paperclipWakePayload"]) {
+ expect(JSON.stringify(context[key]) ?? "").not.toContain("FORGED");
+ expect(JSON.stringify(context[key]) ?? "").not.toContain("OTHER COMPANY");
+ }
+ expect(context.paperclipTurnContext).toMatchObject({ events: { comments: [{ id: ownCommentId }] } });
+ });
+
+ it("clears stale wake comments and continuation data when the task has none", async () => {
+ const f = await seed();
+ const { context } = await execute(f, {
+ paperclipWakeComment: { body: "FORGED comment" },
+ paperclipContinuationSummary: { body: "FORGED summary" },
+ paperclipSkillTest: { directive: "FORGED skill" },
+ paperclipTurnContext: { events: { comments: [{ id: "FORGED comment" }] } },
+ });
+ expect(context.paperclipWakeComment).toBeUndefined();
+ expect(context.paperclipContinuationSummary).toBeUndefined();
+ expect(context.paperclipSkillTest).toBeUndefined();
+ expect(context.paperclipTurnContext).toMatchObject({ events: { comments: [] } });
+ });
+});
diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts
index 4c2cd3da028..bcbcdb0a648 100644
--- a/server/src/services/heartbeat.ts
+++ b/server/src/services/heartbeat.ts
@@ -1,3 +1,4 @@
+import { prepareHeartbeatTaskContext } from "./heartbeat/task-context.js";
import { selectHeartbeatEnvironment } from "./heartbeat/environment-selection.js";
import { prepareHeartbeatWorkspace } from "./heartbeat/workspace-preparation.js";
import { executeHeartbeatRuntime, NativeSessionResumeScheduledError, NativeWorkspaceFinalizeScheduledError } from "./heartbeat/runtime-execution.js";
@@ -13,7 +14,6 @@ import {
createHeartbeatScheduling,
formatIssueIdentifierLink,
} from "./heartbeat/scheduling.js";
-import { FAST_RESPONSE_AGENT_GUIDANCE, fastResponseHistoryBody } from "@paperclipai/shared";
import { agentExecutionsHaveStopped } from "./agent-execution-stop.js";
import {
cancelHeartbeatNativeRun,
@@ -115,7 +115,6 @@ import {
attestReviewedExternalChatRun,
resolveAcceptedPlanWakeRoutingDecision,
clearInteractionContinuationWakeContext,
- buildPaperclipWakePayload,
PAPERCLIP_WAKE_PAYLOAD_KEY,
resolveRunScopedMentionedSkillKeys,
resolveExecutionRunAdapterConfig,
@@ -220,7 +219,6 @@ export {
boundHeartbeatRunEventPayloadForStorage,
compactRunLogChunk,
} from "./heartbeat/run-log.js";
-import { buildPaperclipTaskMarkdown } from "./heartbeat/task-markdown.js";
export { buildPaperclipTaskMarkdown } from "./heartbeat/task-markdown.js";
import { decisionModelService } from "./decision-models.js";
@@ -236,12 +234,9 @@ import {
} from "./native-runtime/native-cancellation-request.js";
import {
prepareChatCompletionTurn,
- chatCompletionInstruction,
} from "./chat-completion-delivery.js";
import { AgentDirectoryReuseInvalidatedError, isAgentDirectoryCopy } from "./agent-directory-working-copies.js";
-import type { PaperclipTurnContext } from "@paperclipai/adapter-utils/server-utils";
-
import {
NativeWorkspaceFinalizationBusyError,
NativeWorkspaceFinalizationOwnershipLostError,
@@ -251,7 +246,6 @@ import { reserveRunBudget } from "./budget-reservations.js";
import { accountRunCost, createCostAccountingReconciler } from "./run-cost-accounting.js";
import { toolActionDeliveryService } from "./tool-action-delivery.js";
-import { liveVoiceExecutionGuidance } from "./voice/voice-execution-guidance.js";
import { githubBotConnectionIdsForRun } from "./chat-github-tools.js";
import {
@@ -260,7 +254,6 @@ import {
settleConversationTurn,
} from "./agent-conversations.js";
import { withAdapterExecutionPhase } from "@paperclipai/adapter-utils/execution-phase";
-import { getConversationConfirmationContext } from "./conversation-confirmation-context.js";
import {
recordNativeLocalProcessStop,
} from "./native-local-process-stop.js";
@@ -300,7 +293,7 @@ import {
import { executionFailureRetryCount } from "./execution-recovery-attempt.js";
import { buildHeartbeatRunStatusLiveEventPayload } from "./heartbeat-run-status-payload.js";
export { buildHeartbeatRunStatusLiveEventPayload } from "./heartbeat-run-status-payload.js";
-import { buildExecutionContinuation, StaleExecutionContinuationError } from "./execution-continuation.js";
+import { StaleExecutionContinuationError } from "./execution-continuation.js";
import { renderPaperclipWakePrompt } from "@paperclipai/adapter-utils/server-utils";
import {
@@ -370,8 +363,6 @@ import {
queuedCommentIdsFromRunContext,
} from "./issue-queued-comment-queue.js";
-import { getTaskPlanContext } from "./task-plan-context.js";
-
import {
claimWarmNativeInstructionCopy,
nativeSessionWorkspaceScope,
@@ -471,7 +462,6 @@ import {
} from "./issue-tree-control.js";
import {
continuationSummaryParksExecutor,
- getIssueContinuationSummaryDocument,
} from "./issue-continuation-summary.js";
import {
@@ -543,10 +533,6 @@ import {
DIRECT_NON_INVOKABLE_STATUSES,
} from "./agent-invokability.js";
-import {
- redactQuarantinedBodyForHigherTrust,
- sanitizeQuarantinedCommentForHigherTrust,
-} from "./source-trust.js";
import {
redactCurrentUserText,
} from "../log-redaction.js";
@@ -2701,325 +2687,14 @@ export function heartbeatService(
await db.update(heartbeatRuns).set({
usageJson: sql`coalesce(${heartbeatRuns.usageJson}, '{}'::jsonb) || ${JSON.stringify({ ledgerScope: runLedgerScope })}::jsonb`,
}).where(eq(heartbeatRuns.id, run.id));
- const continuationSummary = issueRef && !isConversation(issueContext)
- ? await getIssueContinuationSummaryDocument(db, issueRef.id)
- : null;
- const exposeLowTrustRaw = trustPreset.kind === "low_trust_review";
- const safeContinuationSummary =
- continuationSummary && !exposeLowTrustRaw
- ? redactQuarantinedBodyForHigherTrust(continuationSummary)
- : continuationSummary;
- const safeWakeCommentContext =
- wakeCommentContext && !exposeLowTrustRaw
- ? sanitizeQuarantinedCommentForHigherTrust(wakeCommentContext)
- : wakeCommentContext;
- const issueAncestors = issueRef
- ? await issuesSvc.getAncestors(issueRef.id)
- : [];
- if (continuationSummary) {
- context.paperclipContinuationSummary = {
- key: safeContinuationSummary!.key,
- title: safeContinuationSummary!.title,
- body: safeContinuationSummary!.body,
- sourceTrust: safeContinuationSummary!.sourceTrust ?? null,
- updatedAt: safeContinuationSummary!.updatedAt.toISOString(),
- };
- } else {
- delete context.paperclipContinuationSummary;
- }
- const pinnedSkillTestContext =
- issueRef?.workMode === "skill_test"
- ? await getPinnedSkillTestContext(agent.companyId, issueRef.id)
- : null;
- if (pinnedSkillTestContext) {
- context.paperclipSkillTest = {
- ...pinnedSkillTestContext,
- directive:
- "Use this pinned file inventory as the exact skill revision under test, regardless of synced runtime skills.",
- };
- } else {
- delete context.paperclipSkillTest;
- }
- const executionContinuation =
- issueRef && !isConversation(issueContext) && issueContext?.assigneeAgentId === agent.id
- ? await buildExecutionContinuation({
- db,
- companyId: agent.companyId,
- issueId: issueRef.id,
- agentId: agent.id,
- runId: run.id,
- context,
- previousContextRunId: taskSession?.lastRunId,
- summary: safeContinuationSummary?.body ?? null,
- exposeLowTrustRaw,
- })
- : null;
- context.executionContinuation = executionContinuation;
- const paperclipWakePayload = await buildPaperclipWakePayload({
- db,
- companyId: agent.companyId,
- agentId: agent.id,
- runId: run.id,
- contextSnapshot: context,
- continuationSummary,
- issueSummary: issueRef
- ? {
- id: issueRef.id,
- identifier: issueRef.identifier,
- title: issueRef.title,
- description: issueContext?.description ?? null,
- status: issueRef.status,
- priority: issueRef.priority,
- workMode: issueRef.workMode,
- projectId: issueRef.projectId,
- executionPolicy: issueContext?.executionPolicy ?? null,
- }
- : null,
- exposeLowTrustRaw,
- simplifiedEnglishInteractions:
- experimentalInstanceSettings.enableSimplifiedEnglishInteractions ===
- true,
+ const {
+ continuationSummary, executionContinuation, paperclipWakePayload, safeWakeComments, safeWakeCommentContext,
+ } = await prepareHeartbeatTaskContext(db, {
+ run, agent,
+ task: { issueRef, issueContext, wakeCommentContext, context, taskSession },
+ policy: { trustPreset, experimentalInstanceSettings },
+ services: { issuesSvc, getPinnedSkillTestContext },
});
- if (paperclipWakePayload) {
- context[PAPERCLIP_WAKE_PAYLOAD_KEY] = paperclipWakePayload;
- } else {
- delete context[PAPERCLIP_WAKE_PAYLOAD_KEY];
- }
- const safeWakeComments = (paperclipWakePayload?.comments ?? []).flatMap(
- (comment) =>
- typeof comment.id === "string" && typeof comment.body === "string"
- ? [
- {
- id: comment.id,
- body: fastResponseHistoryBody({ body: comment.body, origin: typeof comment.origin === "string" ? comment.origin : null }),
- attachments: Array.isArray(comment.attachments)
- ? comment.attachments.flatMap((attachment) => {
- const descriptor = parseObject(attachment);
- const id = readNonEmptyString(descriptor.id);
- const filename = readNonEmptyString(
- descriptor.filename,
- );
- const contentType = readNonEmptyString(
- descriptor.contentType,
- );
- const contentPath = readNonEmptyString(
- descriptor.contentPath,
- );
- const byteSize = descriptor.byteSize;
- return id &&
- filename &&
- contentType &&
- contentPath &&
- typeof byteSize === "number"
- ? [
- {
- id,
- filename,
- contentType,
- byteSize,
- contentPath,
- },
- ]
- : [];
- })
- : [],
- },
- ]
- : [],
- );
- // Always replace caller-supplied context with the immutable, company-scoped
- // conversation snapshot. It belongs only to the endpoint's assigned agent.
- const liveVoiceGuidance = issueContext?.chatAssignedAgentId === agent.id && issueContext.chatProvider === "speko"
- ? await liveVoiceExecutionGuidance(db, { companyId: agent.companyId, issueId: issueContext.id, agentId: agent.id })
- : null;
- context.paperclipTaskCommunicationGuidance =
- issueContext?.chatAssignedAgentId === agent.id
- ? issueContext.chatCommunicationGuidance
- : null;
- const taskMarkdownInput = {
- conversationConfirmations: issueRef && isConversation(issueContext)
- ? await getConversationConfirmationContext({ db, companyId: agent.companyId, issueId: issueRef.id, agentId: agent.id })
- : null,
- issue: issueRef
- ? {
- id: issueRef.id,
- identifier: issueRef.identifier,
- title: issueRef.title,
- titleNeedsGeneration: issueContext?.titleNeedsGeneration,
- workMode: issueRef.workMode,
- conversationAgentId: issueContext?.conversationAgentId,
- description: issueRef.description,
- }
- : null,
- ancestors: issueAncestors,
- wakeComment: safeWakeCommentContext,
- wakeComments: safeWakeComments,
- attachmentOmissions: paperclipWakePayload?.attachmentOmissions,
- externalChatProvider: paperclipWakePayload?.externalChatProvider,
- slackCommand: issueContext?.chatAssignedAgentId === agent.id
- ? issueContext.chatSlackCommand
- : null,
- nativeRunner: agent.adapterType === "paperclip_runner",
- interaction: {
- kind: readNonEmptyString(context.interactionKind),
- status: readNonEmptyString(context.interactionStatus),
- },
- planReview: paperclipWakePayload?.planReviewContext?.interaction
- ? {
- status: paperclipWakePayload.planReviewContext.interaction.status,
- reason: paperclipWakePayload.planReviewContext.interaction.result?.reason,
- }
- : null,
- acceptedPlanContinuation:
- readNonEmptyString(context.workspaceRefreshReason) ===
- "accepted_plan_confirmation" &&
- Object.keys(parseObject(context.acceptedPlanWakeRouting)).length ===
- 0,
- acceptedPlan: (() => {
- const accepted = parseObject(
- parseObject(context.planReviewInteraction).acceptedTargetRevision,
- );
- const revisionId = readNonEmptyString(accepted.revisionId);
- if (!revisionId) return null;
- return {
- documentId: readNonEmptyString(accepted.documentId),
- revisionId,
- revisionNumber:
- typeof accepted.revisionNumber === "number"
- ? accepted.revisionNumber
- : null,
- };
- })(),
- };
- const taskPlan = issueRef && !isConversation(issueContext)
- ? await getTaskPlanContext({
- db,
- companyId: agent.companyId,
- issueId: issueRef.id,
- approvedRevisionId: taskMarkdownInput.acceptedPlan?.revisionId,
- exposeLowTrustRaw,
- })
- : null;
- // Unlike the frozen initial communication preferences, live-call context
- // must also reach resumed turns. Rebuild it from server records each wake.
- const liveVoiceTaskPrefix = liveVoiceGuidance ? `${liveVoiceGuidance}\n\n` : "";
- let taskMarkdown = liveVoiceTaskPrefix + buildPaperclipTaskMarkdown({ ...taskMarkdownInput, taskPlan }) + chatCompletionInstruction(context);
- let taskMarkdownAssignment = liveVoiceTaskPrefix + buildPaperclipTaskMarkdown({
- ...taskMarkdownInput,
- taskPlan,
- includeWakeComments: false,
- }) + chatCompletionInstruction(context);
- const taskMarkdownCompact = liveVoiceTaskPrefix + buildPaperclipTaskMarkdown({
- ...taskMarkdownInput,
- taskPlan,
- includeDescription: false,
- }) + chatCompletionInstruction(context);
- const taskMarkdownAssignmentCompact = liveVoiceTaskPrefix + buildPaperclipTaskMarkdown({
- ...taskMarkdownInput,
- taskPlan,
- includeDescription: false,
- includeWakeComments: false,
- }) + chatCompletionInstruction(context);
- if (issueRef) {
- context.paperclipIssue = {
- id: issueRef.id,
- identifier: issueRef.identifier,
- title: issueRef.title,
- description: isConversation(issueContext) ? null : issueRef.description,
- workMode: issueRef.workMode,
- };
- } else {
- delete context.paperclipIssue;
- }
- if (wakeCommentContext) {
- context.paperclipWakeComment = safeWakeCommentContext;
- } else {
- delete context.paperclipWakeComment;
- }
- if (taskMarkdown) {
- context.paperclipTaskMarkdown = taskMarkdown;
- } else {
- delete context.paperclipTaskMarkdown;
- }
- if (taskMarkdownAssignment) {
- context.paperclipTaskMarkdownAssignment = taskMarkdownAssignment;
- } else {
- delete context.paperclipTaskMarkdownAssignment;
- }
- if (taskMarkdownCompact && taskMarkdownCompact !== taskMarkdown) {
- context.paperclipTaskMarkdownCompact = taskMarkdownCompact;
- } else {
- delete context.paperclipTaskMarkdownCompact;
- }
- if (taskMarkdownAssignmentCompact && taskMarkdownAssignmentCompact !== taskMarkdownAssignment) {
- context.paperclipTaskMarkdownAssignmentCompact = taskMarkdownAssignmentCompact;
- } else {
- delete context.paperclipTaskMarkdownAssignmentCompact;
- }
- context.paperclipTaskCommunicationGuidance = [context.paperclipTaskCommunicationGuidance, FAST_RESPONSE_AGENT_GUIDANCE].filter(Boolean).join("\n\n");
- if (issueRef) {
- const redactedWakeContext = await createRunSecretRedactionRegistry(
- db,
- ).redactForIssue(agent.companyId, issueRef.id, {
- paperclipIssue: context.paperclipIssue,
- paperclipWakeComment: context.paperclipWakeComment,
- paperclipTaskCommunicationGuidance: context.paperclipTaskCommunicationGuidance,
- paperclipTaskMarkdown: context.paperclipTaskMarkdown,
- paperclipTaskMarkdownCompact: context.paperclipTaskMarkdownCompact,
- paperclipTaskMarkdownAssignment: context.paperclipTaskMarkdownAssignment,
- paperclipTaskMarkdownAssignmentCompact: context.paperclipTaskMarkdownAssignmentCompact,
- });
- context.paperclipIssue = redactedWakeContext.paperclipIssue;
- context.paperclipTaskCommunicationGuidance = redactedWakeContext.paperclipTaskCommunicationGuidance;
- if (redactedWakeContext.paperclipWakeComment) {
- context.paperclipWakeComment =
- redactedWakeContext.paperclipWakeComment;
- }
- if (redactedWakeContext.paperclipTaskMarkdown) {
- context.paperclipTaskMarkdown =
- redactedWakeContext.paperclipTaskMarkdown;
- }
- if (redactedWakeContext.paperclipTaskMarkdownCompact) {
- context.paperclipTaskMarkdownCompact =
- redactedWakeContext.paperclipTaskMarkdownCompact;
- }
- if (redactedWakeContext.paperclipTaskMarkdownAssignment) {
- context.paperclipTaskMarkdownAssignment =
- redactedWakeContext.paperclipTaskMarkdownAssignment;
- }
- if (redactedWakeContext.paperclipTaskMarkdownAssignmentCompact) {
- context.paperclipTaskMarkdownAssignmentCompact =
- redactedWakeContext.paperclipTaskMarkdownAssignmentCompact;
- }
- }
- if (issueRef) {
- const digest = (value: string | null | undefined) =>
- value?.trim()
- ? createHash("sha256")
- .update(value.trim().replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ""))
- .digest("hex")
- : null;
- const redactedIssue = parseObject(context.paperclipIssue);
- context.paperclipTurnContext = {
- version: 1,
- assignment: {
- owner: "task_markdown",
- description: {
- id: issueRef.id,
- revision: digest(readNonEmptyString(redactedIssue.description)),
- },
- },
- events: {
- owner: "wake_prompt",
- comments: safeWakeComments.map((comment) => ({
- id: comment.id,
- revision: digest(comment.body),
- })),
- },
- } satisfies PaperclipTurnContext;
- } else {
- delete context.paperclipTurnContext;
- }
const {
persistedRunnerProfile,
persistedNativeExecutionInput,
diff --git a/server/src/services/heartbeat/task-context.ts b/server/src/services/heartbeat/task-context.ts
new file mode 100644
index 00000000000..56210bd00e1
--- /dev/null
+++ b/server/src/services/heartbeat/task-context.ts
@@ -0,0 +1,376 @@
+import { createHash } from "node:crypto";
+import type { Db, agents, agentTaskSessions, heartbeatRuns, issueComments } from "@paperclipai/db";
+import { FAST_RESPONSE_AGENT_GUIDANCE, fastResponseHistoryBody } from "@paperclipai/shared";
+import type { PaperclipTurnContext } from "@paperclipai/adapter-utils/server-utils";
+import { parseObject } from "../../adapters/utils.js";
+import { isConversation } from "../agent-conversations.js";
+import { chatCompletionInstruction } from "../chat-completion-delivery.js";
+import { getConversationConfirmationContext } from "../conversation-confirmation-context.js";
+import { buildExecutionContinuation } from "../execution-continuation.js";
+import { getIssueContinuationSummaryDocument } from "../issue-continuation-summary.js";
+import type { issueService } from "../issues.js";
+import { createRunSecretRedactionRegistry } from "../run-secret-redaction.js";
+import { redactQuarantinedBodyForHigherTrust, sanitizeQuarantinedCommentForHigherTrust } from "../source-trust.js";
+import { getTaskPlanContext } from "../task-plan-context.js";
+import type { TrustPresetResolution } from "../trust-preset-resolver.js";
+import { liveVoiceExecutionGuidance } from "../voice/voice-execution-guidance.js";
+import { buildPaperclipWakePayload, PAPERCLIP_WAKE_PAYLOAD_KEY, type createHeartbeatRunPreparation } from "./run-preparation.js";
+import { buildPaperclipTaskMarkdown } from "./task-markdown.js";
+
+type RunPreparation = ReturnType;
+type IssueContext = NonNullable>>;
+
+export interface HeartbeatTaskContextInput {
+ run: Pick;
+ agent: Pick;
+ task: {
+ issueRef: Pick | null;
+ issueContext: IssueContext | null;
+ wakeCommentContext: Pick | null;
+ context: Record;
+ taskSession: Pick | null;
+ };
+ policy: {
+ trustPreset: Pick;
+ experimentalInstanceSettings: { enableSimplifiedEnglishInteractions?: boolean };
+ };
+ services: {
+ issuesSvc: Pick, "getAncestors">;
+ getPinnedSkillTestContext: RunPreparation["getPinnedSkillTestContext"];
+ };
+}
+
+function readNonEmptyString(value: unknown): string | null {
+ return typeof value === "string" && value.trim().length > 0 ? value : null;
+}
+
+/** Rebuilds task prompt fields on the run's context; acquires no execution resources. */
+export async function prepareHeartbeatTaskContext(db: Db, input: HeartbeatTaskContextInput) {
+ const { run, agent } = input;
+ const { issueRef, issueContext, wakeCommentContext, context, taskSession } = input.task;
+ const { trustPreset, experimentalInstanceSettings } = input.policy;
+ const { issuesSvc, getPinnedSkillTestContext } = input.services;
+ const continuationSummary = issueRef && !isConversation(issueContext)
+ ? await getIssueContinuationSummaryDocument(db, issueRef.id)
+ : null;
+ const exposeLowTrustRaw = trustPreset.kind === "low_trust_review";
+ const safeContinuationSummary =
+ continuationSummary && !exposeLowTrustRaw
+ ? redactQuarantinedBodyForHigherTrust(continuationSummary)
+ : continuationSummary;
+ const safeWakeCommentContext =
+ wakeCommentContext && !exposeLowTrustRaw
+ ? sanitizeQuarantinedCommentForHigherTrust(wakeCommentContext)
+ : wakeCommentContext;
+ const issueAncestors = issueRef
+ ? await issuesSvc.getAncestors(issueRef.id)
+ : [];
+ if (continuationSummary) {
+ context.paperclipContinuationSummary = {
+ key: safeContinuationSummary!.key,
+ title: safeContinuationSummary!.title,
+ body: safeContinuationSummary!.body,
+ sourceTrust: safeContinuationSummary!.sourceTrust ?? null,
+ updatedAt: safeContinuationSummary!.updatedAt.toISOString(),
+ };
+ } else {
+ delete context.paperclipContinuationSummary;
+ }
+ const pinnedSkillTestContext =
+ issueRef?.workMode === "skill_test"
+ ? await getPinnedSkillTestContext(agent.companyId, issueRef.id)
+ : null;
+ if (pinnedSkillTestContext) {
+ context.paperclipSkillTest = {
+ ...pinnedSkillTestContext,
+ directive:
+ "Use this pinned file inventory as the exact skill revision under test, regardless of synced runtime skills.",
+ };
+ } else {
+ delete context.paperclipSkillTest;
+ }
+ const executionContinuation =
+ issueRef && !isConversation(issueContext) && issueContext?.assigneeAgentId === agent.id
+ ? await buildExecutionContinuation({
+ db,
+ companyId: agent.companyId,
+ issueId: issueRef.id,
+ agentId: agent.id,
+ runId: run.id,
+ context,
+ previousContextRunId: taskSession?.lastRunId,
+ summary: safeContinuationSummary?.body ?? null,
+ exposeLowTrustRaw,
+ })
+ : null;
+ context.executionContinuation = executionContinuation;
+ const paperclipWakePayload = await buildPaperclipWakePayload({
+ db,
+ companyId: agent.companyId,
+ agentId: agent.id,
+ runId: run.id,
+ contextSnapshot: context,
+ continuationSummary,
+ issueSummary: issueRef
+ ? {
+ id: issueRef.id,
+ identifier: issueRef.identifier,
+ title: issueRef.title,
+ description: issueContext?.description ?? null,
+ status: issueRef.status,
+ priority: issueRef.priority,
+ workMode: issueRef.workMode,
+ projectId: issueRef.projectId,
+ executionPolicy: issueContext?.executionPolicy ?? null,
+ }
+ : null,
+ exposeLowTrustRaw,
+ simplifiedEnglishInteractions:
+ experimentalInstanceSettings.enableSimplifiedEnglishInteractions ===
+ true,
+ });
+ if (paperclipWakePayload) {
+ context[PAPERCLIP_WAKE_PAYLOAD_KEY] = paperclipWakePayload;
+ } else {
+ delete context[PAPERCLIP_WAKE_PAYLOAD_KEY];
+ }
+ const safeWakeComments = (paperclipWakePayload?.comments ?? []).flatMap(
+ (comment) =>
+ typeof comment.id === "string" && typeof comment.body === "string"
+ ? [
+ {
+ id: comment.id,
+ body: fastResponseHistoryBody({ body: comment.body, origin: typeof comment.origin === "string" ? comment.origin : null }),
+ attachments: Array.isArray(comment.attachments)
+ ? comment.attachments.flatMap((attachment) => {
+ const descriptor = parseObject(attachment);
+ const id = readNonEmptyString(descriptor.id);
+ const filename = readNonEmptyString(
+ descriptor.filename,
+ );
+ const contentType = readNonEmptyString(
+ descriptor.contentType,
+ );
+ const contentPath = readNonEmptyString(
+ descriptor.contentPath,
+ );
+ const byteSize = descriptor.byteSize;
+ return id &&
+ filename &&
+ contentType &&
+ contentPath &&
+ typeof byteSize === "number"
+ ? [
+ {
+ id,
+ filename,
+ contentType,
+ byteSize,
+ contentPath,
+ },
+ ]
+ : [];
+ })
+ : [],
+ },
+ ]
+ : [],
+ );
+ // Always replace caller-supplied context with the immutable, company-scoped
+ // conversation snapshot. It belongs only to the endpoint's assigned agent.
+ const liveVoiceGuidance = issueContext?.chatAssignedAgentId === agent.id && issueContext.chatProvider === "speko"
+ ? await liveVoiceExecutionGuidance(db, { companyId: agent.companyId, issueId: issueContext.id, agentId: agent.id })
+ : null;
+ context.paperclipTaskCommunicationGuidance =
+ issueContext?.chatAssignedAgentId === agent.id
+ ? issueContext.chatCommunicationGuidance
+ : null;
+ const taskMarkdownInput = {
+ conversationConfirmations: issueRef && isConversation(issueContext)
+ ? await getConversationConfirmationContext({ db, companyId: agent.companyId, issueId: issueRef.id, agentId: agent.id })
+ : null,
+ issue: issueRef
+ ? {
+ id: issueRef.id,
+ identifier: issueRef.identifier,
+ title: issueRef.title,
+ titleNeedsGeneration: issueContext?.titleNeedsGeneration,
+ workMode: issueRef.workMode,
+ conversationAgentId: issueContext?.conversationAgentId,
+ description: issueRef.description,
+ }
+ : null,
+ ancestors: issueAncestors,
+ wakeComment: safeWakeCommentContext,
+ wakeComments: safeWakeComments,
+ attachmentOmissions: paperclipWakePayload?.attachmentOmissions,
+ externalChatProvider: paperclipWakePayload?.externalChatProvider,
+ slackCommand: issueContext?.chatAssignedAgentId === agent.id
+ ? issueContext.chatSlackCommand
+ : null,
+ nativeRunner: agent.adapterType === "paperclip_runner",
+ interaction: {
+ kind: readNonEmptyString(context.interactionKind),
+ status: readNonEmptyString(context.interactionStatus),
+ },
+ planReview: paperclipWakePayload?.planReviewContext?.interaction
+ ? {
+ status: paperclipWakePayload.planReviewContext.interaction.status,
+ reason: paperclipWakePayload.planReviewContext.interaction.result?.reason,
+ }
+ : null,
+ acceptedPlanContinuation:
+ readNonEmptyString(context.workspaceRefreshReason) ===
+ "accepted_plan_confirmation" &&
+ Object.keys(parseObject(context.acceptedPlanWakeRouting)).length ===
+ 0,
+ acceptedPlan: (() => {
+ const accepted = parseObject(
+ parseObject(context.planReviewInteraction).acceptedTargetRevision,
+ );
+ const revisionId = readNonEmptyString(accepted.revisionId);
+ if (!revisionId) return null;
+ return {
+ documentId: readNonEmptyString(accepted.documentId),
+ revisionId,
+ revisionNumber:
+ typeof accepted.revisionNumber === "number"
+ ? accepted.revisionNumber
+ : null,
+ };
+ })(),
+ };
+ const taskPlan = issueRef && !isConversation(issueContext)
+ ? await getTaskPlanContext({
+ db,
+ companyId: agent.companyId,
+ issueId: issueRef.id,
+ approvedRevisionId: taskMarkdownInput.acceptedPlan?.revisionId,
+ exposeLowTrustRaw,
+ })
+ : null;
+ // Unlike the frozen initial communication preferences, live-call context
+ // must also reach resumed turns. Rebuild it from server records each wake.
+ const liveVoiceTaskPrefix = liveVoiceGuidance ? `${liveVoiceGuidance}\n\n` : "";
+ let taskMarkdown = liveVoiceTaskPrefix + buildPaperclipTaskMarkdown({ ...taskMarkdownInput, taskPlan }) + chatCompletionInstruction(context);
+ let taskMarkdownAssignment = liveVoiceTaskPrefix + buildPaperclipTaskMarkdown({
+ ...taskMarkdownInput,
+ taskPlan,
+ includeWakeComments: false,
+ }) + chatCompletionInstruction(context);
+ const taskMarkdownCompact = liveVoiceTaskPrefix + buildPaperclipTaskMarkdown({
+ ...taskMarkdownInput,
+ taskPlan,
+ includeDescription: false,
+ }) + chatCompletionInstruction(context);
+ const taskMarkdownAssignmentCompact = liveVoiceTaskPrefix + buildPaperclipTaskMarkdown({
+ ...taskMarkdownInput,
+ taskPlan,
+ includeDescription: false,
+ includeWakeComments: false,
+ }) + chatCompletionInstruction(context);
+ if (issueRef) {
+ context.paperclipIssue = {
+ id: issueRef.id,
+ identifier: issueRef.identifier,
+ title: issueRef.title,
+ description: isConversation(issueContext) ? null : issueRef.description,
+ workMode: issueRef.workMode,
+ };
+ } else {
+ delete context.paperclipIssue;
+ }
+ if (wakeCommentContext) {
+ context.paperclipWakeComment = safeWakeCommentContext;
+ } else {
+ delete context.paperclipWakeComment;
+ }
+ if (taskMarkdown) {
+ context.paperclipTaskMarkdown = taskMarkdown;
+ } else {
+ delete context.paperclipTaskMarkdown;
+ }
+ if (taskMarkdownAssignment) {
+ context.paperclipTaskMarkdownAssignment = taskMarkdownAssignment;
+ } else {
+ delete context.paperclipTaskMarkdownAssignment;
+ }
+ if (taskMarkdownCompact && taskMarkdownCompact !== taskMarkdown) {
+ context.paperclipTaskMarkdownCompact = taskMarkdownCompact;
+ } else {
+ delete context.paperclipTaskMarkdownCompact;
+ }
+ if (taskMarkdownAssignmentCompact && taskMarkdownAssignmentCompact !== taskMarkdownAssignment) {
+ context.paperclipTaskMarkdownAssignmentCompact = taskMarkdownAssignmentCompact;
+ } else {
+ delete context.paperclipTaskMarkdownAssignmentCompact;
+ }
+ context.paperclipTaskCommunicationGuidance = [context.paperclipTaskCommunicationGuidance, FAST_RESPONSE_AGENT_GUIDANCE].filter(Boolean).join("\n\n");
+ if (issueRef) {
+ const redactedWakeContext = await createRunSecretRedactionRegistry(
+ db,
+ ).redactForIssue(agent.companyId, issueRef.id, {
+ paperclipIssue: context.paperclipIssue,
+ paperclipWakeComment: context.paperclipWakeComment,
+ paperclipTaskCommunicationGuidance: context.paperclipTaskCommunicationGuidance,
+ paperclipTaskMarkdown: context.paperclipTaskMarkdown,
+ paperclipTaskMarkdownCompact: context.paperclipTaskMarkdownCompact,
+ paperclipTaskMarkdownAssignment: context.paperclipTaskMarkdownAssignment,
+ paperclipTaskMarkdownAssignmentCompact: context.paperclipTaskMarkdownAssignmentCompact,
+ });
+ context.paperclipIssue = redactedWakeContext.paperclipIssue;
+ context.paperclipTaskCommunicationGuidance = redactedWakeContext.paperclipTaskCommunicationGuidance;
+ if (redactedWakeContext.paperclipWakeComment) {
+ context.paperclipWakeComment =
+ redactedWakeContext.paperclipWakeComment;
+ }
+ if (redactedWakeContext.paperclipTaskMarkdown) {
+ context.paperclipTaskMarkdown =
+ redactedWakeContext.paperclipTaskMarkdown;
+ }
+ if (redactedWakeContext.paperclipTaskMarkdownCompact) {
+ context.paperclipTaskMarkdownCompact =
+ redactedWakeContext.paperclipTaskMarkdownCompact;
+ }
+ if (redactedWakeContext.paperclipTaskMarkdownAssignment) {
+ context.paperclipTaskMarkdownAssignment =
+ redactedWakeContext.paperclipTaskMarkdownAssignment;
+ }
+ if (redactedWakeContext.paperclipTaskMarkdownAssignmentCompact) {
+ context.paperclipTaskMarkdownAssignmentCompact =
+ redactedWakeContext.paperclipTaskMarkdownAssignmentCompact;
+ }
+ }
+ if (issueRef) {
+ const digest = (value: string | null | undefined) =>
+ value?.trim()
+ ? createHash("sha256")
+ .update(value.trim().replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ""))
+ .digest("hex")
+ : null;
+ const redactedIssue = parseObject(context.paperclipIssue);
+ context.paperclipTurnContext = {
+ version: 1,
+ assignment: {
+ owner: "task_markdown",
+ description: {
+ id: issueRef.id,
+ revision: digest(readNonEmptyString(redactedIssue.description)),
+ },
+ },
+ events: {
+ owner: "wake_prompt",
+ comments: safeWakeComments.map((comment) => ({
+ id: comment.id,
+ revision: digest(comment.body),
+ })),
+ },
+ } satisfies PaperclipTurnContext;
+ } else {
+ delete context.paperclipTurnContext;
+ }
+ return { continuationSummary, executionContinuation, paperclipWakePayload, safeWakeComments, safeWakeCommentContext };
+}
diff --git a/tests/e2e/workspace-bootstrap/README.md b/tests/e2e/workspace-bootstrap/README.md
index 3bf25b641e7..2d16539cf5e 100644
--- a/tests/e2e/workspace-bootstrap/README.md
+++ b/tests/e2e/workspace-bootstrap/README.md
@@ -31,5 +31,7 @@ pnpm exec playwright test --config tests/e2e/workspace-bootstrap/playwright.conf
The tests prove that one timeout schedules a retry and completes without manual
Retry, that persistent timeouts stop after three total runs, and that the final
state survives reload. Source edits remain intact and ignored private files are
-not copied. Screenshots and failure traces go to `test-results/workspace-bootstrap`.
+not copied. The worker also verifies that persisted task context contains the
+assignment, the full and compact prompt variants, and the description revision.
+Screenshots and failure traces go to `test-results/workspace-bootstrap`.
Stop test-drive with Ctrl-C. Its disposable data directory remains for inspection.
diff --git a/tests/e2e/workspace-bootstrap/worker.mjs b/tests/e2e/workspace-bootstrap/worker.mjs
index 07222bfb2bc..b94d0c150c6 100644
--- a/tests/e2e/workspace-bootstrap/worker.mjs
+++ b/tests/e2e/workspace-bootstrap/worker.mjs
@@ -3,6 +3,7 @@
import { readFile, readdir, writeFile, access } from "node:fs/promises";
import path from "node:path";
import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
const env = process.env;
const headers = { Authorization: `Bearer ${env.PAPERCLIP_API_KEY}`, "X-Paperclip-Run-Id": env.PAPERCLIP_RUN_ID, "Content-Type": "application/json" };
@@ -14,6 +15,17 @@ const api = async (route, method = "GET", body) => {
const run = await api(`/heartbeat-runs/${env.PAPERCLIP_RUN_ID}`);
assert.equal(run.contextSnapshot.paperclipEnvironment.driver, "local");
const issueId = run.contextSnapshot.issueId;
+const issue = await api(`/issues/${issueId}`);
+assert.equal(run.contextSnapshot.paperclipIssue.id, issue.id);
+assert.equal(run.contextSnapshot.paperclipIssue.description, issue.description);
+// The fixture's title equals its description; compact prompts keep the title.
+const descriptionSection = `\nIssue description:\n\`\`\`text\n${issue.description}\n\`\`\``;
+assert(run.contextSnapshot.paperclipTaskMarkdown.includes(descriptionSection));
+assert(run.contextSnapshot.paperclipTaskMarkdownAssignment.includes(descriptionSection));
+assert(!run.contextSnapshot.paperclipTaskMarkdownCompact.includes(descriptionSection));
+assert(!run.contextSnapshot.paperclipTaskMarkdownAssignmentCompact.includes(descriptionSection));
+assert.equal(run.contextSnapshot.paperclipTurnContext.assignment.description.revision,
+ createHash("sha256").update(issue.description.trim()).digest("hex"));
const repositories = await readdir(path.join(process.cwd(), ".paperclip-repositories"));
const repo = path.join(process.cwd(), ".paperclip-repositories", repositories.find((name) => !name.includes(".clone-")));
assert.equal(await readFile(path.join(repo, "README.md"), "utf8"), "Existing uncommitted work\n");
From fb21a3f30ac16f8dd281299f29b077285cb5f130 Mon Sep 17 00:00:00 2001
From: Dotta <34892728+cryppadotta@users.noreply.github.com>
Date: Mon, 12 Oct 2026 08:21:46 -0500
Subject: [PATCH 3/3] refactor(chat): extract provider message normalization
(#15823)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
## Thinking Path
> - Paperclip manages AI agents and keeps their work attached to company
tasks.
> - Chat providers deliver messages and corrections into those tasks.
> - The chat channel service has grown to 39,155 lines.
> - Provider message normalization has no database or worker ownership
of its own.
> - This pull request moves that responsibility into one module while
preserving the service body.
> - Reviewers can now find provider identities, timestamps, and edit
revisions together.
## Linked Issues or Issue Description
**What existing behavior does this improve?**
Maintenance of inbound chat message normalization in the server.
**Subsystem affected**
Server chat channels.
**Current behavior**
Provider message parsers and identity rules share a 39,155-line file
with credentials, runtime ownership, database admission, and publication
workers.
**Proposed behavior**
Move provider message normalization into
`chat-channels/provider-messages.ts`. Keep service exports and runtime
behavior unchanged.
**Reason and benefit**
This creates a clear first boundary for an incremental refactor. A dated
plan ranks the next four larger extractions. No duplicate chat refactor
was found in the GitHub title search.
**Breaking changes**
None intended. No schema, endpoint, transport, or public service API
changes.
Stack order: #15823 (provider messages) → #15834 (resource
reconciliation) → #15836 (identity links) → #15844 (publication
replacement) → #15845 (failed-run retries). Merge in this order;
retarget each child after its predecessor lands.
## What Changed
- Move provider message parsing into
`chat-channels/telegram/messages.ts`, `slack/messages.ts`,
`discord/messages.ts`, `microsoft-teams/messages.ts` and
`github/messages.ts`.
- Keep shared actor normalization, actor data and the inbound text limit
in `chat-channels/message-lifecycle.ts`. These six modules total 566
lines / 19,534 bytes.
- Import provider modules directly. Follow this provider-folder
convention for future extractions.
- Preserve exact actor IDs, edit hashes, timestamp provenance, and
Telegram message identity rules.
- Narrow two input types to the Teams parser method and the retained
delivery fields actually read.
- Reduce `chat-channels.ts` from 39,155 lines / 1,509,090 bytes to
38,643 lines / 1,491,703 bytes.
- Record five ranked extraction candidates and verification evidence in
the dated plan.
## Verification
- The original extraction passed complete CI and 5/5 review at
`cbba30a526`. Those results are historical; the updated head is
`90ac517e6c310c8cf194dbbd668006f740e58f3a`.
- Structural comparison: all 21 moved declarations match the base after
normalizing exports and two type-only changes. All remaining non-import
declarations, including the complete service body, match the base.
- Provider-folder update: the same 48 public service integration cases
passed locally before and after the move on PR #15823. They cover
Slack/Discord revision identity, Teams edits, GitHub edits, Telegram
rich messages and provider chronology.
- All 22 message declarations retain identical bodies; the service
changes imports only. The four dependent extractions rebased without
conflicts.
- Final-stack workspace `pnpm -r typecheck` passed. Module-boundary and
whitespace checks passed.
- Final-stack `pnpm build` passed. The fresh `pnpm test:run` was
interrupted after PostgreSQL startup failures recurred. An isolated
`native-status-arbiter-corpus.test.ts` run failed during database
initialization after five attempts; all 45 tests skipped. All 32 host
shared-memory slots were occupied. The full local gate remains
unverified; only the task-owned run was stopped.
- Greptile rated updated head `90ac517e6c310c8cf194dbbd668006f740e58f3a`
5/5 with no inline review threads.
- Updated-head CI passed: 53 successful checks and two skipped checks,
including all chat integration shards, typecheck, build and browser
suites.
- Tests use disposable databases and fixture provider transports. No
live third-party execution is claimed.
## Risks
- A wrong module import or changed revision identity could affect
message admission. Existing service-path tests and the declaration
comparison cover those risks.
- Authentication, company-scoped transactions, leases, background
workers, and shutdown remain in the original service.
- The service closure remains large. Resource reconciliation is the
recommended next extraction.
## Model Used
OpenAI Codex, GPT-6 family, with reasoning, local code execution, and
repository tools. The exact runtime model ID and context-window size are
not exposed in this session. No separate planning or review agent was
used.
## 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
- [ ] 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
---
.../2026-10-10-chat-channels-refactor.md | 127 ++++
server/src/services/chat-channels.ts | 574 +-----------------
.../chat-channels/discord/messages.ts | 30 +
.../services/chat-channels/github/messages.ts | 132 ++++
.../chat-channels/message-lifecycle.ts | 39 ++
.../chat-channels/microsoft-teams/messages.ts | 99 +++
.../services/chat-channels/slack/messages.ts | 43 ++
.../chat-channels/telegram/messages.ts | 223 +++++++
8 files changed, 724 insertions(+), 543 deletions(-)
create mode 100644 doc/plans/2026-10-10-chat-channels-refactor.md
create mode 100644 server/src/services/chat-channels/discord/messages.ts
create mode 100644 server/src/services/chat-channels/github/messages.ts
create mode 100644 server/src/services/chat-channels/message-lifecycle.ts
create mode 100644 server/src/services/chat-channels/microsoft-teams/messages.ts
create mode 100644 server/src/services/chat-channels/slack/messages.ts
create mode 100644 server/src/services/chat-channels/telegram/messages.ts
diff --git a/doc/plans/2026-10-10-chat-channels-refactor.md b/doc/plans/2026-10-10-chat-channels-refactor.md
new file mode 100644
index 00000000000..711c6e6b125
--- /dev/null
+++ b/doc/plans/2026-10-10-chat-channels-refactor.md
@@ -0,0 +1,127 @@
+# Chat channel service extraction sequence
+
+## Scope and finish line
+
+Apply the refactor-large-file workflow to `server/src/services/chat-channels.ts`.
+Map five responsibilities, then extract and verify one at a time. This slice
+extracts provider message normalization without changing provider behavior,
+public service exports, database contracts, authentication, or worker ownership.
+Subsequent slices require reassessment against the preceding result. No merge or
+deployment is part of this slice.
+
+## Baseline
+
+- Base: `1100682261` on a clean, detached task worktree.
+- File: 39,132 lines / 1,502,701 bytes; imports occupy 421 lines.
+- `chatChannelService`: 36,152 lines, including nested functions and wiring.
+ This is not a measurement of orchestration alone. The first slice removes
+ top-level normalization; it does not simplify that closure yet.
+- Largest nested functions: `processMessage` (2,164 lines), `handleAction`
+ (1,074), `applyProviderLifecycleEffect` (895), `configureWithCredentialLease`
+ (868), `processSelectedPublication` (728), `handleModalSubmit` (708),
+ `handleWebhook` (684), `failedChatRetrySource` (677), and
+ `processLifecycleDelivery` (657).
+- Existing siblings already own SDK runtimes/state, provider inventory reads,
+ resource lifecycle parsing, GitHub app management, registration, publication
+ projection/streaming, Teams transfers, Telegram media, and interaction forms.
+ Extend those boundaries where appropriate instead of duplicating them.
+- Callers include application assembly, chat routes, issue/agent routes, and
+ existing unit/integration tests. Keep their imports and service API stable.
+
+## Ranked extraction candidates
+
+Estimates are source lines moved / net reduction after wiring. Later estimates
+are provisional: explicit dependency contracts must precede each extraction.
+New paths below are relative to `server/src/services/`.
+
+| Rank / responsibility | Destination | Approx. move / net | Inputs and outputs | State and effects owned | Risk and verification |
+| --- | --- | --- | --- | --- | --- |
+| 1. Provider message normalization | `chat-channels/provider-messages.ts` | 540 / 520 | Provider payload, author, Request, Teams parser, or retained delivery → actor, lifecycle event, message ID, revision digest, timestamp | No mutable service state or DB writes; consumes the supplied GitHub Request body | Preserve exact revision hashes, limits, native IDs, malformed-input handling, and raw clock provenance. Existing public service integration tests cover all four providers. |
+| 2. Resource inventory reconciliation and availability | `chat-channels/resource-reconciliation.ts`, alongside `chat-provider-inventory.ts` and `chat-provider-lifecycle.ts` | 1,300–1,500 / 1,200–1,400 | Endpoint, inventory/lifecycle effect, credential lease, DB and explicit runtime callbacks → reconciled resources and availability | Company-scoped resource/conversation transactions; GitHub stable repository identity and provider-order checks | Keep advisory locks, lease checks and the complete availability transaction together. Verify repository rename, removal/reinstall, resource auditing, Telegram migration and stale callbacks. |
+| 3. Identity linking | `chat-channels/identity-links.ts` | 430–600 / 390–550 | DB, endpoint lookup, live public URL getter, principal, token, authenticated user → link preview/confirmation/revocation | Token hashes/expiry, membership checks, join requests and transactional audit records | No cached authority or URL snapshot. Preserve endpoint/company binding, replay behavior and revoked/conflicting links; run identity route and DB integration tests. |
+| 4. Publication replacement and supersession | `chat-channels/publication-replacement.ts` (the existing reconciliation module owns wake signals, a separate responsibility) | 1,000–1,150 / 950–1,100 | DB, publication, current endpoint/conversation/run → replacement candidate or suppression reason | Scoped reads and existing issue/run authorization snapshots; no transport or queue ownership | Preserve exact outbound link ownership, interaction precedence, terminal failure replacement, and issue→run lock order. Run publication reconciliation, progress and integration fixtures. |
+| 5. Failed chat run retry coordination | `chat-channels/failed-run-retry.ts` | 1,600–1,900 / 1,400–1,700 | DB, source/action IDs, explicit admission/heartbeat/publication hooks → authorized retry, claim and completion | Per-service in-flight retry promises and authority registration/cleanup, persisted source evidence | Higher risk: preserve single retry ownership, no replay of provider calls, live source revalidation and shutdown ordering. Run reconstructed-service, edited-source, revocation and concurrent retry integration fixtures. |
+
+Start with candidate 1: it establishes a domain folder and removes an independent
+responsibility without introducing a mutable context object. It is deliberately
+smaller than the later stateful slices. Resource lifecycle effects remain in the
+existing parser; message edits/deletes are a different normalization contract.
+
+Do not move runtime leases, webhook authentication, conversation admission,
+delivery transactions, transport attempts, or shutdown piecemeal. The service
+must continue to show who admits work and who releases resources. Candidate 2
+needs a narrow callback contract; candidate 5 must preserve the same service
+lifetime for registration and in-flight promises. Candidates are sequential,
+not independent concurrent changes to this file.
+
+## Provider folder convention (2026-10-11)
+
+Provider-specific code belongs under `chat-channels//`, using the
+existing provider identifiers. The normalization extraction now lives in
+`telegram/messages.ts`, `slack/messages.ts`, `discord/messages.ts`,
+`microsoft-teams/messages.ts` and `github/messages.ts`. Shared actor normalization,
+actor data and the inbound text limit live in `message-lifecycle.ts`. The service
+imports the provider modules directly. Future extractions should follow this
+layout; move older flat provider modules when their responsibility is touched.
+
+All 22 declarations retain their exact bodies. The service changes imports only.
+The same 48 provider integration cases passed before and after this move, and
+server typecheck and module boundaries pass. The historical extraction sizes
+below predate this folder change: direct imports add 10 service lines / 281 bytes.
+The six message modules now total 566 lines / 19,534 bytes, including imports.
+
+## Verification and progress
+
+Before the production move, run existing service integration cases for message
+lifecycle, file revision identity, provider timestamps, Telegram zero-message
+handling and rich content. These use disposable PostgreSQL and fixture provider
+transports, not live third-party execution. Keep those tests at their existing
+public entry points. Add characterization only if inspection exposes a gap.
+
+After the move, repeat that selection, compare extracted declarations and the
+remaining file mechanically against the base, then run the relevant adjacent
+suites and repository typecheck, full test and build gates. Record blockers and
+unverified checks explicitly; do not treat skipped integration tests as passes.
+
+- Dependencies: installed with the repository-pinned pnpm 9.15.4. The host's
+ newer pnpm ignored legacy patch settings, so verification uses the pinned tool.
+- Original-base integration selection: 48 passed before and 48 passed after
+ extraction. Existing tests cover the boundary; no new test-only exports or
+ mock-only characterization were needed.
+- Rebased onto `b1ebe3de3c` after master added fast-response acknowledgements
+ and action queue notifications. The only conflict was the import block;
+ retain upstream imports and add the normalization import. All 21 extracted
+ declarations match the new base, ignoring added exports and two narrowed
+ input types. Every remaining non-import declaration, including the entire
+ service body, matches the new base exactly.
+- Current size: 39,155 lines / 1,509,090 bytes before extraction; 38,633 lines /
+ 1,491,422 bytes after. Net reduction: 522 lines / 17,668 bytes. Destination:
+ 552 lines / 19,028 bytes, including imports and the shared text-limit constant.
+- On the rebased source, the service spans 36,175 lines: 287 direct nested
+ function declarations occupy 35,324 lines; 51 other statements occupy 504
+ lines of state, wiring, registration callbacks and the public API. The rest
+ is comments, whitespace and delimiters. Those counts remain unchanged by
+ this slice; they make the remaining orchestration work explicit.
+- The module takes only the Teams parser method and the two delivery fields it
+ reads, rather than requiring an entire runtime or database row. These are
+ type-only changes. It imports sibling implementations directly, never the
+ service entry point. Public service exports remain unchanged.
+- Initial full-test/typecheck runs were interrupted to rebase and are not
+ passes. Rebased integration selection: 48 passed (the other 1,185 cases were
+ excluded by the test-name filter). Module-boundary and whitespace checks pass.
+ Workspace `pnpm -r typecheck` and `pnpm build`: passed. The full suite and
+ remote checks were still running at PR opening; final results belong in the
+ PR's Verification section below.
+
+Reproduce the focused service-path check with the repository-pinned pnpm:
+
+```sh
+pnpm exec vitest run server/src/__tests__/chat-channels.integration.test.ts \
+ -t 'records message edits and deletes durably|redacts lifecycle edits|Telegram edit|Teams edit, soft-delete|verified Telegram edited_message|verified GitHub comment edit|provider timestamp provenance|Telegram retained zero-message admission|Telegram current rich inbound compatibility|deduplicates Slack file-only revisions|preserves exact Discord source authority'
+```
+
+Branch: `codex/chat-channel-provider-messages`. The user authorized publishing
+this slice to `paperclipai/paperclip`; subsequent extractions are not part of
+this PR.
+
+Review and final verification: [PR #15823](https://github.com/paperclipai/paperclip/pull/15823).
diff --git a/server/src/services/chat-channels.ts b/server/src/services/chat-channels.ts
index 12bff8621d9..9716073c91f 100644
--- a/server/src/services/chat-channels.ts
+++ b/server/src/services/chat-channels.ts
@@ -1,3 +1,34 @@
+import {
+ MAX_INBOUND_TEXT,
+ stableExternalPrincipalId,
+ type LifecycleActor,
+ lifecycleActorFromAuthor,
+} from "./chat-channels/message-lifecycle.js";
+import {
+ telegramLifecycleEventFromPayload,
+ isTelegramEditedMessageRaw,
+ isTelegramMigrationRaw,
+ telegramMessageSequence,
+ telegramMessageId,
+ telegramZeroMessageId,
+ telegramDeliveryHasZeroMessageId,
+ telegramMessageSentAt,
+} from "./chat-channels/telegram/messages.js";
+import {
+ slackLifecycleFilesDigest,
+ slackMessageSentAt,
+} from "./chat-channels/slack/messages.js";
+import {
+ discordLifecycleFilesDigest,
+} from "./chat-channels/discord/messages.js";
+import {
+ microsoftTeamsLifecycleEventFromPayload,
+ teamsActivitySentAt,
+} from "./chat-channels/microsoft-teams/messages.js";
+import {
+ type GitHubLifecycleEvent,
+ githubLifecycleEventFromRequest,
+} from "./chat-channels/github/messages.js";
import { dueChatAction, nextChatActionAt, SLACK_COMMAND_POST_STALE_MS, SLACK_COMMAND_EXPLICIT_RETRY_STALE_MS, SLACK_COMMAND_ADMISSION_STALE_MS, PROVIDER_EFFECT_STALE_MS } from "./chat-action-work.js";
import type { ScheduledChatAction } from "./chat-work-notifications.js";
import { notifyChatDeliveryWork, notifyChatPublicationWork, notifyChatEndpointWork, notifyChatActionWork, notifyChatVerificationWork } from "./chat-work-notifications.js";
@@ -381,7 +412,6 @@ import {
} from "./chat-inbound-wakeup-publications.js";
import {
normalizeMicrosoftTeamsCredentialIds,
- normalizeMicrosoftTeamsExternalPrincipalId,
} from "./chat-teams-credentials.js";
import {
isTeamsInlineImageContentType,
@@ -847,7 +877,6 @@ const SUPPLIED_CREDENTIAL_KEYS: Record = {
telegram: ["botToken"],
};
-const MAX_INBOUND_TEXT = 100_000;
const MAX_ERROR_TEXT = 2_000;
const DELIVERY_PROCESSING_STALE_MS = 60_000;
// Reactions can beat the transaction that persists a just-sent provider
@@ -1737,19 +1766,6 @@ function telegramGuidanceCommand(
return "unknown";
}
-function stableExternalPrincipalId(
- provider: ChatProvider,
- author: Author,
- raw?: unknown,
-): string {
- if (provider !== "microsoft-teams" || !raw || typeof raw !== "object")
- return author.userId;
- const from = (raw as { from?: unknown }).from;
- if (!from || typeof from !== "object") return author.userId;
- const aadObjectId = (from as { aadObjectId?: unknown }).aadObjectId;
- return normalizeMicrosoftTeamsExternalPrincipalId(aadObjectId, author.userId);
-}
-
function safeTitle(text: string, fallback: string): string {
const line = text
.replace(/<@[A-Z0-9]+>/gi, "")
@@ -2037,534 +2053,6 @@ function isSupportedTelegramWebhookBaseUrl(value: string | null): boolean {
}
}
-type GitHubLifecycleEvent = {
- actor?: LifecycleActor;
- isBotMessage?: true;
- eventKind: "message_updated" | "message_deleted";
- messageId: string;
- providerEventId?: string;
- providerMessageSequence: number | null;
- providerSentAt: string | null;
- revision: string;
- text: string;
- threadId: string;
-};
-
-type TelegramLifecycleEvent = {
- actor: LifecycleActor;
- eventKind: "message_updated";
- messageId: string;
- providerEventId?: string;
- providerMessageSequence: number;
- providerSentAt: string;
- providerUpdateId: number | null;
- revision: string;
- text: string;
- threadId: string;
-};
-
-type LifecycleActor = {
- displayName: string;
- externalId: string;
- handle: string;
-};
-
-type MicrosoftTeamsLifecycleEvent = {
- actor?: LifecycleActor;
- eventKind: "message_updated" | "message_deleted" | "message_restored";
- messageId: string;
- providerSentAt: string | null;
- raw?: unknown;
- revision: string;
- text: string;
- threadId: string;
-};
-
-function lifecycleActorFromAuthor(
- provider: ChatProvider,
- author: Author,
- raw?: unknown,
-): LifecycleActor {
- return {
- externalId: stableExternalPrincipalId(provider, author, raw),
- displayName: author.fullName,
- handle: author.userName,
- };
-}
-
-function slackLifecycleFilesDigest(raw: unknown): string {
- const files =
- raw && typeof raw === "object" && !Array.isArray(raw)
- ? (raw as Record).files
- : undefined;
- // Match the pinned Slack adapter's content-change projection. Transport
- // locators/unfurls are not content identity and must never enter durable keys.
- const projection = Array.isArray(files)
- ? files.map((file) => {
- const row =
- file && typeof file === "object" && !Array.isArray(file)
- ? (file as Record)
- : {};
- return [
- ...["id", "name", "mimetype"].map((key) =>
- typeof row[key] === "string" ? row[key] : null,
- ),
- ...["size", "original_w", "original_h"].map((key) =>
- typeof row[key] === "number" && Number.isFinite(row[key])
- ? row[key]
- : null,
- ),
- ];
- })
- : [];
- return createHash("sha256").update(JSON.stringify(projection)).digest("hex");
-}
-
-function discordLifecycleFilesDigest(raw: unknown): string {
- const attachments =
- raw && typeof raw === "object" && !Array.isArray(raw)
- ? (raw as Record).attachments
- : undefined;
- // Match the pinned Gateway adapter's flattened, ordered file projection.
- // Rotating CDN URLs are transport authority, never source revision identity.
- const projection = Array.isArray(attachments)
- ? attachments.map((attachment) => {
- const row =
- attachment &&
- typeof attachment === "object" &&
- !Array.isArray(attachment)
- ? (attachment as Record)
- : {};
- return [
- ...["id", "filename", "content_type"].map((key) =>
- typeof row[key] === "string" ? row[key] : null,
- ),
- typeof row.size === "number" && Number.isFinite(row.size)
- ? row.size
- : null,
- ];
- })
- : [];
- return createHash("sha256").update(JSON.stringify(projection)).digest("hex");
-}
-
-function telegramLifecycleActor(message: {
- from?: unknown;
- sender_chat?: unknown;
-}): LifecycleActor | null {
- const candidate =
- message.from &&
- typeof message.from === "object" &&
- !Array.isArray(message.from)
- ? (message.from as Record)
- : message.sender_chat &&
- typeof message.sender_chat === "object" &&
- !Array.isArray(message.sender_chat)
- ? (message.sender_chat as Record)
- : null;
- if (!candidate) return null;
- const id = candidate.id;
- if (typeof id !== "string" && typeof id !== "number") return null;
- const handle =
- typeof candidate.username === "string" ? candidate.username : "";
- const displayName =
- [candidate.first_name, candidate.last_name]
- .filter(
- (value): value is string => typeof value === "string" && Boolean(value),
- )
- .join(" ") ||
- (typeof candidate.title === "string" ? candidate.title : "") ||
- handle ||
- String(id);
- return { externalId: String(id), displayName, handle };
-}
-
-function microsoftTeamsLifecycleEventFromPayload(
- payload: unknown,
- endpointRuntime: ChatEndpointRuntime,
-): MicrosoftTeamsLifecycleEvent | null {
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
- return null;
- const activity = payload as {
- channelData?: { eventType?: unknown };
- timestamp?: unknown;
- type?: unknown;
- };
- const eventType = activity.channelData?.eventType;
- const isEdit =
- activity.type === "messageUpdate" && eventType === "editMessage";
- const isRestore =
- activity.type === "messageUpdate" && eventType === "undeleteMessage";
- const isDelete =
- activity.type === "messageDelete" && eventType === "softDeleteMessage";
- if (!isEdit && !isRestore && !isDelete) return null;
- const message = endpointRuntime.parseMicrosoftTeamsMessage(payload);
- if (!message?.id || !message.threadId) return null;
- const body = message.text.slice(0, MAX_INBOUND_TEXT);
- const providerSentAt =
- typeof activity.timestamp === "string" &&
- Number.isFinite(Date.parse(activity.timestamp))
- ? new Date(activity.timestamp).toISOString()
- : null;
- const bodyHash = createHash("sha256").update(body).digest("hex");
- const revision = providerSentAt ? `${providerSentAt}:${bodyHash}` : bodyHash;
- return {
- ...(!isDelete
- ? {
- actor: lifecycleActorFromAuthor(
- "microsoft-teams",
- message.author,
- message.raw,
- ),
- }
- : {}),
- eventKind: isDelete
- ? "message_deleted"
- : isRestore
- ? "message_restored"
- : "message_updated",
- messageId: message.id,
- providerSentAt,
- raw: message.raw,
- revision,
- text: isDelete
- ? "An external message in this conversation was deleted."
- : isRestore
- ? `An external message was restored:\n\n${body}`
- : `An external message was edited:\n\n${body}`,
- threadId: message.threadId,
- };
-}
-
-function telegramLifecycleEventFromPayload(
- payload: unknown,
-): TelegramLifecycleEvent | null {
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
- return null;
- const update = payload as {
- edited_message?: unknown;
- update_id?: unknown;
- };
- const edited = update.edited_message;
- if (!edited || typeof edited !== "object" || Array.isArray(edited))
- return null;
- const message = edited as {
- caption?: unknown;
- chat?: { id?: unknown };
- edit_date?: unknown;
- from?: unknown;
- message_id?: unknown;
- message_thread_id?: unknown;
- sender_chat?: unknown;
- text?: unknown;
- rich_message?: unknown;
- };
- const chatId = message.chat?.id;
- const messageId = message.message_id;
- const editDate = message.edit_date;
- if (
- (typeof chatId !== "string" && typeof chatId !== "number") ||
- typeof messageId !== "number" ||
- !Number.isSafeInteger(messageId) ||
- messageId < 0 ||
- typeof editDate !== "number" ||
- !Number.isSafeInteger(editDate) ||
- editDate <= 0
- )
- return null;
- const topicId = message.message_thread_id;
- if (topicId !== undefined && typeof topicId !== "number") return null;
- const rich = normalizeTelegramRichMessage(message);
- const body =
- rich?.text ??
- (typeof message.text === "string"
- ? message.text
- : typeof message.caption === "string"
- ? message.caption
- : "");
- const chat = String(chatId);
- const providerUpdateId =
- typeof update.update_id === "number" &&
- Number.isSafeInteger(update.update_id) &&
- update.update_id >= 0
- ? update.update_id
- : null;
- const bodyHash = createHash("sha256").update(body).digest("hex");
- const actor = telegramLifecycleActor(message);
- if (!actor) return null;
- return {
- actor,
- eventKind: "message_updated",
- messageId: `${chat}:${messageId}`,
- ...(providerUpdateId === null
- ? {}
- : { providerEventId: `telegram:update:${providerUpdateId}` }),
- providerMessageSequence: messageId,
- providerSentAt: new Date(editDate * 1_000).toISOString(),
- providerUpdateId,
- // Bot API timestamps have one-second resolution. The update id is the
- // authoritative identity when present; retaining a content hash keeps the
- // fallback path from collapsing two distinct edits in that same second.
- revision: `${editDate}:${bodyHash}${rich ? `:${rich.mediaDigest}` : ""}`,
- text: `An external message was edited:\n\n${body.slice(0, MAX_INBOUND_TEXT)}`,
- threadId:
- topicId === undefined
- ? `telegram:${chat}`
- : `telegram:${chat}:${topicId}`,
- };
-}
-
-function isTelegramEditedMessageRaw(raw: unknown): boolean {
- return (
- !!raw &&
- typeof raw === "object" &&
- !Array.isArray(raw) &&
- typeof (raw as { edit_date?: unknown }).edit_date === "number"
- );
-}
-
-function isTelegramMigrationRaw(raw: unknown): boolean {
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
- const value = raw as {
- migrate_from_chat_id?: unknown;
- migrate_to_chat_id?: unknown;
- };
- return (
- value.migrate_from_chat_id !== undefined ||
- value.migrate_to_chat_id !== undefined
- );
-}
-
-function telegramMessageSequence(raw: unknown): number | null {
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
- const value = (raw as { message_id?: unknown }).message_id;
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0
- ? value
- : null;
-}
-
-function telegramMessageId(raw: unknown): string | null {
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
- const value = raw as {
- chat?: { id?: unknown };
- message_id?: unknown;
- };
- const messageId = value.message_id;
- const chatId = value.chat?.id;
- if (
- typeof messageId !== "number" ||
- !Number.isSafeInteger(messageId) ||
- messageId <= 0
- )
- return null;
- const normalizedChatId =
- typeof chatId === "number" && Number.isSafeInteger(chatId)
- ? String(chatId)
- : typeof chatId === "string" && /^-?\d+$/.test(chatId)
- ? chatId
- : null;
- return normalizedChatId ? `${normalizedChatId}:${messageId}` : null;
-}
-
-function telegramZeroMessageId(value: unknown): boolean {
- // The pinned adapter qualifies native message IDs with the numeric chat ID.
- // Keep legacy synthetic/non-numeric IDs compatible; zero is specifically
- // the provider's non-ordinary message identity, never an admitted source.
- return typeof value === "string" && /^(?:-?\d+:)?0$/.test(value);
-}
-
-function telegramDeliveryHasZeroMessageId(
- delivery: DeliveryRow,
- provider: ChatProvider,
-): boolean {
- if (provider !== "telegram") return false;
- const normalized = delivery.normalizedEvent as {
- message?: {
- providerMessageId?: unknown;
- providerMessageSequence?: unknown;
- };
- conversation?: { externalThreadId?: unknown };
- };
- if (
- telegramZeroMessageId(normalized.message?.providerMessageId) ||
- normalized.message?.providerMessageSequence === 0
- )
- return true;
- const threadId = normalized.conversation?.externalThreadId;
- // Check the independently retained event key only inside its exact thread
- // namespace, not arbitrary IDs ending in ':0' from synthetic commands.
- return (
- typeof threadId === "string" &&
- delivery.providerEventId.startsWith(`${threadId}:`) &&
- telegramZeroMessageId(delivery.providerEventId.slice(threadId.length + 1))
- );
-}
-
-function telegramMessageSentAt(raw: unknown): Date | null {
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
- const value = (raw as { date?: unknown }).date;
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0)
- return null;
- const sentAt = new Date(value * 1_000);
- return Number.isFinite(sentAt.getTime()) ? sentAt : null;
-}
-
-function slackMessageSentAt(raw: unknown, messageId: string): Date | null {
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
- const ts = (raw as { ts?: unknown }).ts;
- if (
- ts !== messageId ||
- typeof ts !== "string" ||
- !/^[1-9][0-9]{0,12}\.[0-9]{6}$/.test(ts)
- )
- return null;
- const date = new Date(Number(ts) * 1_000);
- return Number.isFinite(date.getTime()) ? date : null;
-}
-
-function teamsActivitySentAt(raw: unknown): Date | null {
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
- const value = (raw as { timestamp?: unknown }).timestamp;
- // The SDK may supply a Date, but its missing-timestamp display fallback is
- // only on Message.metadata. Never use that fallback as provider chronology.
- if (value instanceof Date)
- return Number.isFinite(value.getTime()) ? new Date(value.getTime()) : null;
- if (
- typeof value !== "string" ||
- value.length > 64 ||
- !/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,7})?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(
- value,
- )
- )
- return null;
- // Date.parse otherwise normalizes nonexistent dates such as February 30.
- const day = value.slice(0, 10);
- const calendar = new Date(`${day}T00:00:00.000Z`);
- if (
- !Number.isFinite(calendar.getTime()) ||
- calendar.toISOString().slice(0, 10) !== day
- )
- return null;
- const sentAt = new Date(value);
- return Number.isFinite(sentAt.getTime()) ? sentAt : null;
-}
-
-async function githubLifecycleEventFromRequest(
- request: Request,
-): Promise {
- const eventType = request.headers.get("x-github-event");
- const deliveryId = request.headers.get("x-github-delivery")?.trim() || null;
- if (
- eventType !== "issue_comment" &&
- eventType !== "pull_request_review_comment"
- )
- return null;
- const payload = (await request.json()) as {
- action?: unknown;
- comment?: {
- id?: unknown;
- in_reply_to_id?: unknown;
- body?: unknown;
- updated_at?: unknown;
- user?: { type?: unknown };
- };
- issue?: { number?: unknown; pull_request?: unknown };
- pull_request?: { number?: unknown };
- repository?: { name?: unknown; owner?: { login?: unknown } };
- sender?: { id?: unknown; login?: unknown; type?: unknown };
- };
- if (payload.action !== "edited" && payload.action !== "deleted") return null;
- const owner = payload.repository?.owner?.login;
- const repo = payload.repository?.name;
- const messageId = payload.comment?.id;
- if (
- typeof owner !== "string" ||
- typeof repo !== "string" ||
- (typeof messageId !== "string" && typeof messageId !== "number")
- )
- return null;
- let threadId: string;
- if (eventType === "issue_comment") {
- const number = payload.issue?.number;
- if (typeof number !== "number") return null;
- threadId = payload.issue?.pull_request
- ? `github:${owner}/${repo}:${number}`
- : `github:${owner}/${repo}:issue:${number}`;
- } else {
- const number = payload.pull_request?.number;
- const rootCommentId =
- payload.comment?.in_reply_to_id ?? payload.comment?.id;
- if (
- typeof number !== "number" ||
- (typeof rootCommentId !== "string" && typeof rootCommentId !== "number")
- )
- return null;
- threadId = `github:${owner}/${repo}:${number}:rc:${rootCommentId}`;
- }
- const eventKind =
- payload.action === "edited" ? "message_updated" : "message_deleted";
- const body =
- typeof payload.comment?.body === "string"
- ? payload.comment.body.slice(0, MAX_INBOUND_TEXT)
- : "";
- const providerRevision =
- typeof payload.comment?.updated_at === "string"
- ? payload.comment.updated_at
- : payload.action;
- const parsedProviderSentAt = new Date(providerRevision);
- const providerSentAt = Number.isFinite(parsedProviderSentAt.getTime())
- ? parsedProviderSentAt.toISOString()
- : null;
- const numericMessageId =
- typeof messageId === "number"
- ? messageId
- : typeof messageId === "string" && /^\d+$/.test(messageId)
- ? Number(messageId)
- : null;
- const providerMessageSequence =
- numericMessageId !== null &&
- Number.isSafeInteger(numericMessageId) &&
- numericMessageId >= 0
- ? numericMessageId
- : null;
- const senderId = payload.sender?.id;
- const senderLogin = payload.sender?.login;
- const actor =
- (typeof senderId === "string" || typeof senderId === "number") &&
- typeof senderLogin === "string" &&
- senderLogin.length > 0
- ? {
- externalId: String(senderId),
- displayName: senderLogin,
- handle: senderLogin,
- }
- : undefined;
- return {
- ...(actor ? { actor } : {}),
- ...(payload.comment?.user?.type === "Bot" || payload.sender?.type === "Bot"
- ? { isBotMessage: true as const }
- : {}),
- eventKind,
- messageId: String(messageId),
- ...(deliveryId ? { providerEventId: `github:delivery:${deliveryId}` } : {}),
- providerMessageSequence,
- providerSentAt,
- // GitHub's updated_at value can have coarser resolution than a quick
- // sequence of edits. Include the normalized body so distinct edits at the
- // same timestamp remain durable while an exact webhook redelivery still
- // deduplicates.
- revision:
- eventKind === "message_updated"
- ? `${providerRevision}:${createHash("sha256").update(body).digest("hex")}`
- : providerRevision,
- text:
- eventKind === "message_updated"
- ? `An external message was edited:\n\n${body}`
- : "An external message in this conversation was deleted.",
- threadId,
- };
-}
-
function githubRepositoryInventoryItemFromPayload(
payload: unknown,
): ChatProviderResourceInventoryItem | null {
diff --git a/server/src/services/chat-channels/discord/messages.ts b/server/src/services/chat-channels/discord/messages.ts
new file mode 100644
index 00000000000..f61b2a2e8ef
--- /dev/null
+++ b/server/src/services/chat-channels/discord/messages.ts
@@ -0,0 +1,30 @@
+import { createHash } from "node:crypto";
+
+
+export function discordLifecycleFilesDigest(raw: unknown): string {
+ const attachments =
+ raw && typeof raw === "object" && !Array.isArray(raw)
+ ? (raw as Record).attachments
+ : undefined;
+ // Match the pinned Gateway adapter's flattened, ordered file projection.
+ // Rotating CDN URLs are transport authority, never source revision identity.
+ const projection = Array.isArray(attachments)
+ ? attachments.map((attachment) => {
+ const row =
+ attachment &&
+ typeof attachment === "object" &&
+ !Array.isArray(attachment)
+ ? (attachment as Record)
+ : {};
+ return [
+ ...["id", "filename", "content_type"].map((key) =>
+ typeof row[key] === "string" ? row[key] : null,
+ ),
+ typeof row.size === "number" && Number.isFinite(row.size)
+ ? row.size
+ : null,
+ ];
+ })
+ : [];
+ return createHash("sha256").update(JSON.stringify(projection)).digest("hex");
+}
diff --git a/server/src/services/chat-channels/github/messages.ts b/server/src/services/chat-channels/github/messages.ts
new file mode 100644
index 00000000000..800d806d263
--- /dev/null
+++ b/server/src/services/chat-channels/github/messages.ts
@@ -0,0 +1,132 @@
+import { createHash } from "node:crypto";
+import { MAX_INBOUND_TEXT, type LifecycleActor } from "../message-lifecycle.js";
+
+
+export type GitHubLifecycleEvent = {
+ actor?: LifecycleActor;
+ isBotMessage?: true;
+ eventKind: "message_updated" | "message_deleted";
+ messageId: string;
+ providerEventId?: string;
+ providerMessageSequence: number | null;
+ providerSentAt: string | null;
+ revision: string;
+ text: string;
+ threadId: string;
+};
+
+export async function githubLifecycleEventFromRequest(
+ request: Request,
+): Promise {
+ const eventType = request.headers.get("x-github-event");
+ const deliveryId = request.headers.get("x-github-delivery")?.trim() || null;
+ if (
+ eventType !== "issue_comment" &&
+ eventType !== "pull_request_review_comment"
+ )
+ return null;
+ const payload = (await request.json()) as {
+ action?: unknown;
+ comment?: {
+ id?: unknown;
+ in_reply_to_id?: unknown;
+ body?: unknown;
+ updated_at?: unknown;
+ user?: { type?: unknown };
+ };
+ issue?: { number?: unknown; pull_request?: unknown };
+ pull_request?: { number?: unknown };
+ repository?: { name?: unknown; owner?: { login?: unknown } };
+ sender?: { id?: unknown; login?: unknown; type?: unknown };
+ };
+ if (payload.action !== "edited" && payload.action !== "deleted") return null;
+ const owner = payload.repository?.owner?.login;
+ const repo = payload.repository?.name;
+ const messageId = payload.comment?.id;
+ if (
+ typeof owner !== "string" ||
+ typeof repo !== "string" ||
+ (typeof messageId !== "string" && typeof messageId !== "number")
+ )
+ return null;
+ let threadId: string;
+ if (eventType === "issue_comment") {
+ const number = payload.issue?.number;
+ if (typeof number !== "number") return null;
+ threadId = payload.issue?.pull_request
+ ? `github:${owner}/${repo}:${number}`
+ : `github:${owner}/${repo}:issue:${number}`;
+ } else {
+ const number = payload.pull_request?.number;
+ const rootCommentId =
+ payload.comment?.in_reply_to_id ?? payload.comment?.id;
+ if (
+ typeof number !== "number" ||
+ (typeof rootCommentId !== "string" && typeof rootCommentId !== "number")
+ )
+ return null;
+ threadId = `github:${owner}/${repo}:${number}:rc:${rootCommentId}`;
+ }
+ const eventKind =
+ payload.action === "edited" ? "message_updated" : "message_deleted";
+ const body =
+ typeof payload.comment?.body === "string"
+ ? payload.comment.body.slice(0, MAX_INBOUND_TEXT)
+ : "";
+ const providerRevision =
+ typeof payload.comment?.updated_at === "string"
+ ? payload.comment.updated_at
+ : payload.action;
+ const parsedProviderSentAt = new Date(providerRevision);
+ const providerSentAt = Number.isFinite(parsedProviderSentAt.getTime())
+ ? parsedProviderSentAt.toISOString()
+ : null;
+ const numericMessageId =
+ typeof messageId === "number"
+ ? messageId
+ : typeof messageId === "string" && /^\d+$/.test(messageId)
+ ? Number(messageId)
+ : null;
+ const providerMessageSequence =
+ numericMessageId !== null &&
+ Number.isSafeInteger(numericMessageId) &&
+ numericMessageId >= 0
+ ? numericMessageId
+ : null;
+ const senderId = payload.sender?.id;
+ const senderLogin = payload.sender?.login;
+ const actor =
+ (typeof senderId === "string" || typeof senderId === "number") &&
+ typeof senderLogin === "string" &&
+ senderLogin.length > 0
+ ? {
+ externalId: String(senderId),
+ displayName: senderLogin,
+ handle: senderLogin,
+ }
+ : undefined;
+ return {
+ ...(actor ? { actor } : {}),
+ ...(payload.comment?.user?.type === "Bot" || payload.sender?.type === "Bot"
+ ? { isBotMessage: true as const }
+ : {}),
+ eventKind,
+ messageId: String(messageId),
+ ...(deliveryId ? { providerEventId: `github:delivery:${deliveryId}` } : {}),
+ providerMessageSequence,
+ providerSentAt,
+ // GitHub's updated_at value can have coarser resolution than a quick
+ // sequence of edits. Include the normalized body so distinct edits at the
+ // same timestamp remain durable while an exact webhook redelivery still
+ // deduplicates.
+ revision:
+ eventKind === "message_updated"
+ ? `${providerRevision}:${createHash("sha256").update(body).digest("hex")}`
+ : providerRevision,
+ text:
+ eventKind === "message_updated"
+ ? `An external message was edited:\n\n${body}`
+ : "An external message in this conversation was deleted.",
+ threadId,
+ };
+}
diff --git a/server/src/services/chat-channels/message-lifecycle.ts b/server/src/services/chat-channels/message-lifecycle.ts
new file mode 100644
index 00000000000..00084d9169c
--- /dev/null
+++ b/server/src/services/chat-channels/message-lifecycle.ts
@@ -0,0 +1,39 @@
+import type { ChatProvider } from "@paperclipai/shared";
+import type { Author } from "chat";
+import { normalizeMicrosoftTeamsExternalPrincipalId } from "../chat-teams-credentials.js";
+
+
+// Provider message identity and chronology only. Callers retain authentication,
+// authorization, durable admission, and delivery ownership.
+export const MAX_INBOUND_TEXT = 100_000;
+
+export function stableExternalPrincipalId(
+ provider: ChatProvider,
+ author: Author,
+ raw?: unknown,
+): string {
+ if (provider !== "microsoft-teams" || !raw || typeof raw !== "object")
+ return author.userId;
+ const from = (raw as { from?: unknown }).from;
+ if (!from || typeof from !== "object") return author.userId;
+ const aadObjectId = (from as { aadObjectId?: unknown }).aadObjectId;
+ return normalizeMicrosoftTeamsExternalPrincipalId(aadObjectId, author.userId);
+}
+
+export type LifecycleActor = {
+ displayName: string;
+ externalId: string;
+ handle: string;
+};
+
+export function lifecycleActorFromAuthor(
+ provider: ChatProvider,
+ author: Author,
+ raw?: unknown,
+): LifecycleActor {
+ return {
+ externalId: stableExternalPrincipalId(provider, author, raw),
+ displayName: author.fullName,
+ handle: author.userName,
+ };
+}
diff --git a/server/src/services/chat-channels/microsoft-teams/messages.ts b/server/src/services/chat-channels/microsoft-teams/messages.ts
new file mode 100644
index 00000000000..c5ed87cebf9
--- /dev/null
+++ b/server/src/services/chat-channels/microsoft-teams/messages.ts
@@ -0,0 +1,99 @@
+import { createHash } from "node:crypto";
+import type { ChatEndpointRuntime } from "../../voice/voice-runtime.js";
+import { MAX_INBOUND_TEXT, lifecycleActorFromAuthor, type LifecycleActor } from "../message-lifecycle.js";
+
+
+type MicrosoftTeamsLifecycleEvent = {
+ actor?: LifecycleActor;
+ eventKind: "message_updated" | "message_deleted" | "message_restored";
+ messageId: string;
+ providerSentAt: string | null;
+ raw?: unknown;
+ revision: string;
+ text: string;
+ threadId: string;
+};
+
+export function microsoftTeamsLifecycleEventFromPayload(
+ payload: unknown,
+ endpointRuntime: Pick,
+): MicrosoftTeamsLifecycleEvent | null {
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
+ return null;
+ const activity = payload as {
+ channelData?: { eventType?: unknown };
+ timestamp?: unknown;
+ type?: unknown;
+ };
+ const eventType = activity.channelData?.eventType;
+ const isEdit =
+ activity.type === "messageUpdate" && eventType === "editMessage";
+ const isRestore =
+ activity.type === "messageUpdate" && eventType === "undeleteMessage";
+ const isDelete =
+ activity.type === "messageDelete" && eventType === "softDeleteMessage";
+ if (!isEdit && !isRestore && !isDelete) return null;
+ const message = endpointRuntime.parseMicrosoftTeamsMessage(payload);
+ if (!message?.id || !message.threadId) return null;
+ const body = message.text.slice(0, MAX_INBOUND_TEXT);
+ const providerSentAt =
+ typeof activity.timestamp === "string" &&
+ Number.isFinite(Date.parse(activity.timestamp))
+ ? new Date(activity.timestamp).toISOString()
+ : null;
+ const bodyHash = createHash("sha256").update(body).digest("hex");
+ const revision = providerSentAt ? `${providerSentAt}:${bodyHash}` : bodyHash;
+ return {
+ ...(!isDelete
+ ? {
+ actor: lifecycleActorFromAuthor(
+ "microsoft-teams",
+ message.author,
+ message.raw,
+ ),
+ }
+ : {}),
+ eventKind: isDelete
+ ? "message_deleted"
+ : isRestore
+ ? "message_restored"
+ : "message_updated",
+ messageId: message.id,
+ providerSentAt,
+ raw: message.raw,
+ revision,
+ text: isDelete
+ ? "An external message in this conversation was deleted."
+ : isRestore
+ ? `An external message was restored:\n\n${body}`
+ : `An external message was edited:\n\n${body}`,
+ threadId: message.threadId,
+ };
+}
+
+export function teamsActivitySentAt(raw: unknown): Date | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const value = (raw as { timestamp?: unknown }).timestamp;
+ // The SDK may supply a Date, but its missing-timestamp display fallback is
+ // only on Message.metadata. Never use that fallback as provider chronology.
+ if (value instanceof Date)
+ return Number.isFinite(value.getTime()) ? new Date(value.getTime()) : null;
+ if (
+ typeof value !== "string" ||
+ value.length > 64 ||
+ !/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,7})?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(
+ value,
+ )
+ )
+ return null;
+ // Date.parse otherwise normalizes nonexistent dates such as February 30.
+ const day = value.slice(0, 10);
+ const calendar = new Date(`${day}T00:00:00.000Z`);
+ if (
+ !Number.isFinite(calendar.getTime()) ||
+ calendar.toISOString().slice(0, 10) !== day
+ )
+ return null;
+ const sentAt = new Date(value);
+ return Number.isFinite(sentAt.getTime()) ? sentAt : null;
+}
diff --git a/server/src/services/chat-channels/slack/messages.ts b/server/src/services/chat-channels/slack/messages.ts
new file mode 100644
index 00000000000..eba1e833f2f
--- /dev/null
+++ b/server/src/services/chat-channels/slack/messages.ts
@@ -0,0 +1,43 @@
+import { createHash } from "node:crypto";
+
+
+export function slackLifecycleFilesDigest(raw: unknown): string {
+ const files =
+ raw && typeof raw === "object" && !Array.isArray(raw)
+ ? (raw as Record).files
+ : undefined;
+ // Match the pinned Slack adapter's content-change projection. Transport
+ // locators/unfurls are not content identity and must never enter durable keys.
+ const projection = Array.isArray(files)
+ ? files.map((file) => {
+ const row =
+ file && typeof file === "object" && !Array.isArray(file)
+ ? (file as Record)
+ : {};
+ return [
+ ...["id", "name", "mimetype"].map((key) =>
+ typeof row[key] === "string" ? row[key] : null,
+ ),
+ ...["size", "original_w", "original_h"].map((key) =>
+ typeof row[key] === "number" && Number.isFinite(row[key])
+ ? row[key]
+ : null,
+ ),
+ ];
+ })
+ : [];
+ return createHash("sha256").update(JSON.stringify(projection)).digest("hex");
+}
+
+export function slackMessageSentAt(raw: unknown, messageId: string): Date | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const ts = (raw as { ts?: unknown }).ts;
+ if (
+ ts !== messageId ||
+ typeof ts !== "string" ||
+ !/^[1-9][0-9]{0,12}\.[0-9]{6}$/.test(ts)
+ )
+ return null;
+ const date = new Date(Number(ts) * 1_000);
+ return Number.isFinite(date.getTime()) ? date : null;
+}
diff --git a/server/src/services/chat-channels/telegram/messages.ts b/server/src/services/chat-channels/telegram/messages.ts
new file mode 100644
index 00000000000..152b6478533
--- /dev/null
+++ b/server/src/services/chat-channels/telegram/messages.ts
@@ -0,0 +1,223 @@
+import { createHash } from "node:crypto";
+import type { chatDeliveries } from "@paperclipai/db";
+import type { ChatProvider } from "@paperclipai/shared";
+import { normalizeTelegramRichMessage } from "../../chat-telegram-rich-intake.js";
+import { MAX_INBOUND_TEXT, type LifecycleActor } from "../message-lifecycle.js";
+
+
+type TelegramLifecycleEvent = {
+ actor: LifecycleActor;
+ eventKind: "message_updated";
+ messageId: string;
+ providerEventId?: string;
+ providerMessageSequence: number;
+ providerSentAt: string;
+ providerUpdateId: number | null;
+ revision: string;
+ text: string;
+ threadId: string;
+};
+
+function telegramLifecycleActor(message: {
+ from?: unknown;
+ sender_chat?: unknown;
+}): LifecycleActor | null {
+ const candidate =
+ message.from &&
+ typeof message.from === "object" &&
+ !Array.isArray(message.from)
+ ? (message.from as Record)
+ : message.sender_chat &&
+ typeof message.sender_chat === "object" &&
+ !Array.isArray(message.sender_chat)
+ ? (message.sender_chat as Record)
+ : null;
+ if (!candidate) return null;
+ const id = candidate.id;
+ if (typeof id !== "string" && typeof id !== "number") return null;
+ const handle =
+ typeof candidate.username === "string" ? candidate.username : "";
+ const displayName =
+ [candidate.first_name, candidate.last_name]
+ .filter(
+ (value): value is string => typeof value === "string" && Boolean(value),
+ )
+ .join(" ") ||
+ (typeof candidate.title === "string" ? candidate.title : "") ||
+ handle ||
+ String(id);
+ return { externalId: String(id), displayName, handle };
+}
+
+export function telegramLifecycleEventFromPayload(
+ payload: unknown,
+): TelegramLifecycleEvent | null {
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
+ return null;
+ const update = payload as {
+ edited_message?: unknown;
+ update_id?: unknown;
+ };
+ const edited = update.edited_message;
+ if (!edited || typeof edited !== "object" || Array.isArray(edited))
+ return null;
+ const message = edited as {
+ caption?: unknown;
+ chat?: { id?: unknown };
+ edit_date?: unknown;
+ from?: unknown;
+ message_id?: unknown;
+ message_thread_id?: unknown;
+ sender_chat?: unknown;
+ text?: unknown;
+ rich_message?: unknown;
+ };
+ const chatId = message.chat?.id;
+ const messageId = message.message_id;
+ const editDate = message.edit_date;
+ if (
+ (typeof chatId !== "string" && typeof chatId !== "number") ||
+ typeof messageId !== "number" ||
+ !Number.isSafeInteger(messageId) ||
+ messageId < 0 ||
+ typeof editDate !== "number" ||
+ !Number.isSafeInteger(editDate) ||
+ editDate <= 0
+ )
+ return null;
+ const topicId = message.message_thread_id;
+ if (topicId !== undefined && typeof topicId !== "number") return null;
+ const rich = normalizeTelegramRichMessage(message);
+ const body =
+ rich?.text ??
+ (typeof message.text === "string"
+ ? message.text
+ : typeof message.caption === "string"
+ ? message.caption
+ : "");
+ const chat = String(chatId);
+ const providerUpdateId =
+ typeof update.update_id === "number" &&
+ Number.isSafeInteger(update.update_id) &&
+ update.update_id >= 0
+ ? update.update_id
+ : null;
+ const bodyHash = createHash("sha256").update(body).digest("hex");
+ const actor = telegramLifecycleActor(message);
+ if (!actor) return null;
+ return {
+ actor,
+ eventKind: "message_updated",
+ messageId: `${chat}:${messageId}`,
+ ...(providerUpdateId === null
+ ? {}
+ : { providerEventId: `telegram:update:${providerUpdateId}` }),
+ providerMessageSequence: messageId,
+ providerSentAt: new Date(editDate * 1_000).toISOString(),
+ providerUpdateId,
+ // Bot API timestamps have one-second resolution. The update id is the
+ // authoritative identity when present; retaining a content hash keeps the
+ // fallback path from collapsing two distinct edits in that same second.
+ revision: `${editDate}:${bodyHash}${rich ? `:${rich.mediaDigest}` : ""}`,
+ text: `An external message was edited:\n\n${body.slice(0, MAX_INBOUND_TEXT)}`,
+ threadId:
+ topicId === undefined
+ ? `telegram:${chat}`
+ : `telegram:${chat}:${topicId}`,
+ };
+}
+
+export function isTelegramEditedMessageRaw(raw: unknown): boolean {
+ return (
+ !!raw &&
+ typeof raw === "object" &&
+ !Array.isArray(raw) &&
+ typeof (raw as { edit_date?: unknown }).edit_date === "number"
+ );
+}
+
+export function isTelegramMigrationRaw(raw: unknown): boolean {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
+ const value = raw as {
+ migrate_from_chat_id?: unknown;
+ migrate_to_chat_id?: unknown;
+ };
+ return (
+ value.migrate_from_chat_id !== undefined ||
+ value.migrate_to_chat_id !== undefined
+ );
+}
+
+export function telegramMessageSequence(raw: unknown): number | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const value = (raw as { message_id?: unknown }).message_id;
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0
+ ? value
+ : null;
+}
+
+export function telegramMessageId(raw: unknown): string | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const value = raw as {
+ chat?: { id?: unknown };
+ message_id?: unknown;
+ };
+ const messageId = value.message_id;
+ const chatId = value.chat?.id;
+ if (
+ typeof messageId !== "number" ||
+ !Number.isSafeInteger(messageId) ||
+ messageId <= 0
+ )
+ return null;
+ const normalizedChatId =
+ typeof chatId === "number" && Number.isSafeInteger(chatId)
+ ? String(chatId)
+ : typeof chatId === "string" && /^-?\d+$/.test(chatId)
+ ? chatId
+ : null;
+ return normalizedChatId ? `${normalizedChatId}:${messageId}` : null;
+}
+
+export function telegramZeroMessageId(value: unknown): boolean {
+ // The pinned adapter qualifies native message IDs with the numeric chat ID.
+ // Keep legacy synthetic/non-numeric IDs compatible; zero is specifically
+ // the provider's non-ordinary message identity, never an admitted source.
+ return typeof value === "string" && /^(?:-?\d+:)?0$/.test(value);
+}
+
+export function telegramDeliveryHasZeroMessageId(
+ delivery: Pick,
+ provider: ChatProvider,
+): boolean {
+ if (provider !== "telegram") return false;
+ const normalized = delivery.normalizedEvent as {
+ message?: {
+ providerMessageId?: unknown;
+ providerMessageSequence?: unknown;
+ };
+ conversation?: { externalThreadId?: unknown };
+ };
+ if (
+ telegramZeroMessageId(normalized.message?.providerMessageId) ||
+ normalized.message?.providerMessageSequence === 0
+ )
+ return true;
+ const threadId = normalized.conversation?.externalThreadId;
+ // Check the independently retained event key only inside its exact thread
+ // namespace, not arbitrary IDs ending in ':0' from synthetic commands.
+ return (
+ typeof threadId === "string" &&
+ delivery.providerEventId.startsWith(`${threadId}:`) &&
+ telegramZeroMessageId(delivery.providerEventId.slice(threadId.length + 1))
+ );
+}
+
+export function telegramMessageSentAt(raw: unknown): Date | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const value = (raw as { date?: unknown }).date;
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0)
+ return null;
+ const sentAt = new Date(value * 1_000);
+ return Number.isFinite(sentAt.getTime()) ? sentAt : null;
+}