## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - People review agent artifacts (plans, documents, routine descriptions, and case documents) with inline annotation comments > - Today a person must type a full reply to say "done", "checked", "looks good", or "I have a question" > - This slows down quick review feedback, and a question inside a reply does not automatically bring the assignee back > - This pull request adds four one-tap reactions to each annotation comment: Done, Check, Thumbs up, and Question > - A person's first Question reaction on an open task saves a durable wake receipt and wakes the task's assignee in a dedicated follow-up run to reply in that comment's thread (respecting chat ownership and wake rate limits) > - The benefit is fast review feedback without extra typing, while agents can read and set the same reactions through the API ## Linked Issues or Issue Description Refs #21637 (supersedes on current `master` with renumbered Drizzle migration, OpenAPI/experimental route contracts, durable wake receipts, chat ownership and rate-limit hardening, and current UI test suite) Refs #9336 (agent wake notifications for document annotation threads) Refs #9674 (agents cannot read inline document review comments) **What problem does this solve?** A reviewer cannot quickly acknowledge or question an annotation comment on an artifact. A short answer requires a typed reply, and nothing tells the agent that a person has a question about a comment. **Proposed solution** Add four fixed reactions per annotation comment: `done`, `check`, `thumbs_up`, and `question`. One tap adds a reaction and a second tap removes it. Each person or agent can add each reaction once per comment. A person's first `question` reaction on an open task commits a durable wake receipt in the same transaction and wakes the assignee once in a dedicated follow-up turn, with the comment included in the wake context. **Alternatives considered** Free-form emoji reactions. Fixed named reactions keep the API contract stable for agents and avoid storing arbitrary emoji strings on the server. ## What Changed - `packages/db`: Added `document_annotation_comment_reactions` table (`company_id`, `comment_id`, `reaction`, `actor_type`, `actor_id`, `created_at`, `removed_at`) with check constraints, cascade delete on comment deletion, and unique `(comment_id, reaction, actor_type, actor_id)` index. Generated online-compatible migration `0510_clear_speedball.sql`, refreshed Drizzle snapshot `0510_snapshot.json`, and pruned `0505_snapshot.json`. - `packages/shared`: Added `DOCUMENT_ANNOTATION_COMMENT_REACTIONS`, `DocumentAnnotationCommentReactionName`, `DocumentAnnotationCommentReactionActor`, `DocumentAnnotationCommentReactionSummary`, optional `reactions` on `DocumentAnnotationComment`, and `documentAnnotationCommentReactionSchema`. - `server`: Added `setCommentReaction` in `document-annotations.ts` using soft-delete (`removed_at`) and upsert revival (`(xmax = 0)` for `firstAdd`), and attached reaction summaries (`count`, `actors`, `reactedByMe`) to thread/comment reads. - `server` routes & contracts: Added `PUT` and `DELETE .../annotations/:threadId/comments/:commentId/reactions/:reaction` for issues, routines, and cases, registered them in `openapi.ts`, `experimental-api-metadata.ts`, and `experimental-api-paths.ts`, and logged activity (`*.document_annotation_comment_reaction_added` / `_removed`) only when a row changes. - `server` durable wake, chat ownership, rate limits & `packages/adapter-utils`: - A person's first `question` reaction on an open assigned issue inserts a recoverable `deferred_issue_execution` receipt in `agent_wakeup_requests` in the same DB transaction (`annotation-question-reaction:<id>`), passes `executionWaitRequestId` to `heartbeat.wakeup` (`reason: "issue_commented"`, `allowRunCoalescing: false`), resumes via `resumeDeferredExecutionReceipts` if immediate wake fails, and defers behind busy turns without duplicating receipts. - Recognized human annotation question reactions (`isHumanAnnotationQuestionWake`) as an independent wake cause for idle waiting agent chats while strictly enforcing chat ownership (`!conversationAgentId || conversationUserId === actorId`) across service, route, wake preflight, locked admission, and recovery queries. - Bounded distinct-comment question wakes under `issues ... FOR UPDATE` to at most 1 pending/in-flight wake per `(companyId, issueId, agentId)` and at most 3 original question receipts (`idempotency_key LIKE 'annotation-question-reaction:%'`) per `(companyId, issueId, user)` in a rolling 10-minute window. - `renderPaperclipWakePrompt` instructs the agent to answer the question in the annotation thread. - `ui`: Added four one-tap reaction buttons (`✅`, `✔️`, `👍`, `❓`) under each non-optimistic annotation comment in `DocumentAnnotationPanel` / `DocumentAnnotationPopover`, with counts, `aria-pressed`, hover tooltips naming actors, optimistic updates, client-scoped write serialization across panel/popover remounts (`WeakMap<QueryClient, Map<string, TargetReactionState>>`), live-update refetch overlay preservation, deferred invalidation while writes are pending, and updated Storybook fixture. - `docs/api` & `tests/runner-e2e`: Documented the reaction endpoints and wake bounds in `docs/api/issues.md` and `docs/api/routines.md`, and refreshed `tests/runner-e2e/source-sdk-public-inputs.json`. ## Verification - `pnpm --filter @paperclipai/db run check:migrations` and `migration-compatibility.ts`: `0510_clear_speedball.sql` classified `online_compatible`. - `pnpm --filter @paperclipai/db exec vitest run src/migration-snapshot-drift.test.ts src/migration-compatibility.test.ts`: passed (117/117). - `pnpm --filter @paperclipai/adapter-utils exec vitest run src/server-utils.test.ts -t "question reaction"`: passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/document-annotations-service.test.ts` (20/20, embedded Postgres — covering durable wake recovery, idle waiting-chat wake, busy-turn deferral, non-owner chat wake denial, and rolling-window + pending-backlog wake bounds across full queue admission), `src/__tests__/document-annotation-routes.test.ts` (20/20), `src/__tests__/routine-document-annotation-routes.test.ts`, `src/modules/wake-queue/application/issue-wake-admission.test.ts` (15/15), and `src/modules/wake-queue/domain/policy.test.ts`: all passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/openapi-routes.test.ts`: passed (59/59). - `pnpm --filter @paperclipai/ui exec vitest run src/hooks/useDocumentAnnotationMutations.test.tsx`: passed (9/9, covering optimistic updates, serialized writes across remounts, live-update refetch preservation, deferred invalidation across comments, and rendered `ThreadCard` DOM buttons/toggles). - Package typechecks (`@paperclipai/shared`, `@paperclipai/db`, `@paperclipai/adapter-utils`, `@paperclipai/server` all 7 layers, `@paperclipai/ui` + Storybook catalog): all passed. - `pnpm check:token-gates`, `node scripts/check-module-boundaries.mjs`, and `node scripts/check-test-budget.mjs`: all passed. - `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD) --check`: in sync (`inputs: 579, changed: false`). - Full-stack Playwright verification against a throwaway local server + embedded PostgreSQL: created a task, `plan` document, and annotation thread; verified invalid reaction returns `400`; clicked `thumbs_up` and `question` in the real document viewer; reloaded to prove PostgreSQL persistence; toggled `thumbs_up` off and reloaded to verify removal persisted. - PR CI on `4d892c8067`: 83/83 executed checks passing (including `ci / verify`, `ci / e2e` + all 16 E2E shards, all General/Serialized server shards, `Build`, `Typecheck + Release Registry`, `Verify Paperclip Runner`, `Superagent Security Scan`, and `Greptile Review` 5/5 with 0 unresolved threads). ## Risks - Low risk. Migration `0510_clear_speedball.sql` only creates a new table and its indexes (`online_compatible`), so running releases are unaffected. - `reactions` is optional on `DocumentAnnotationComment`, preserving backward compatibility for existing clients. - Question wakes are bounded by soft-delete revival (`firstAdd`), chat ownership enforcement, single pending/in-flight wake per `(companyId, issueId, agentId)`, and at most 3 original question wakes per `(companyId, issueId, user)` per 10-minute window. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Google Gemini (`gemini-3-pro` / Antigravity agentic coding environment with shell execution, file editing, embedded PostgreSQL, and Playwright verification), rebasing and extending prior work originally authored with Claude Opus 5.5 in #21637. ## 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: lucktastic <13757243+lucktastic@users.noreply.github.com> Co-authored-by: Paperclip <noreply@paperclip.ing>
16 KiB
title, summary
| title | summary |
|---|---|
| Routines | Recurring task scheduling, triggers, and run history |
Routines are recurring tasks that fire on a schedule, webhook, or API call and create a heartbeat run for the assigned agent.
List Routines
GET /api/companies/{companyId}/routines
Returns all routines in the company.
Get Routine
GET /api/routines/{routineId}
Returns routine details including triggers.
Routine and trigger resource IDs must be complete UUIDs from the API response.
Short prefixes and malformed IDs return the same 404 as a missing resource.
UUID lookup accepts PostgreSQL's existing input forms, including uppercase,
compact and braced UUIDs; it does not trim whitespace or resolve prefixes.
Company access and routine-assignee permissions still apply. Public trigger
IDs in webhook URLs are separate opaque identifiers, not resource UUIDs.
Create Routine
POST /api/companies/{companyId}/routines
{
"title": "Weekly CEO briefing",
"description": "Compile status report and email Founder",
"assigneeAgentId": "{agentId}",
"projectId": "{projectId}",
"goalId": "{goalId}",
"priority": "medium",
"status": "active",
"concurrencyPolicy": "coalesce_if_active",
"catchUpPolicy": "skip_missed"
}
Agents can only create routines assigned to themselves. Board operators can assign to any agent.
Fields:
| Field | Required | Description |
|---|---|---|
title |
yes | Routine name |
description |
no | Human-readable description of the routine |
assigneeAgentId |
yes | Agent who receives each run |
projectId |
yes | Project this routine belongs to |
goalId |
no | Goal to link runs to |
parentIssueId |
no | Parent issue for created run issues |
priority |
no | critical, high, medium (default), low |
status |
no | active (default), paused, archived |
concurrencyPolicy |
no | Behaviour when a run fires while a previous one is still active |
catchUpPolicy |
no | Behaviour for missed scheduled runs |
Concurrency policies:
| Value | Behaviour |
|---|---|
coalesce_if_active (default) |
Incoming run is immediately finalised as coalesced and linked to the active run — no new issue is created |
skip_if_active |
Incoming run is immediately finalised as skipped and linked to the active run — no new issue is created |
always_enqueue |
Always create a new run regardless of active runs |
Catch-up policies:
| Value | Behaviour |
|---|---|
skip_missed (default) |
Missed scheduled runs are dropped |
enqueue_missed_with_cap |
Missed runs are enqueued up to an internal cap |
Update Routine
PATCH /api/routines/{routineId}
{
"status": "paused",
"baseRevisionId": "{latestRevisionId}"
}
All fields from create are updatable. baseRevisionId is optional for backward compatibility; when provided, stale values return 409 Conflict with the current revision id. Agents can only update routines assigned to themselves and cannot reassign a routine to another agent.
When env contains a variable that an active plugin environment sets on its
own tasks (protectedEnvironmentKeys), create and update still save it. The
response then includes configurationWarnings entries with code
protected_environment_variable, a field such as env.KEY, and a message
that names those environments.
List Revisions
GET /api/routines/{routineId}/revisions
Returns append-only routine definition revisions newest first. Snapshots include routine fields and safe trigger metadata only; webhook secret values and secretId are never returned.
Description Comment Reactions
PUT /api/routines/{routineId}/description/annotations/{threadId}/comments/{commentId}/reactions/{reaction}
DELETE /api/routines/{routineId}/description/annotations/{threadId}/comments/{commentId}/reactions/{reaction}
Adds or removes a done, check, thumbs_up or question reaction on a routine description annotation comment. See Comment Reactions for the response shape and rules. Routine reactions do not wake an agent.
Restore Revision
POST /api/routines/{routineId}/revisions/{revisionId}/restore
Restores a historical routine definition by creating a new latest revision copied from the selected revision. Historical revision rows, routine run history, and activity history are preserved. If restoring a deleted webhook trigger requires recreating it, the response can include one-time replacement secret material for that trigger.
Add Trigger
POST /api/routines/{routineId}/triggers
Three trigger kinds:
Schedule — fires on a cron expression:
{
"kind": "schedule",
"cronExpression": "0 9 * * 1",
"timezone": "Europe/Amsterdam"
}
Webhook — fires on an inbound HTTP POST to a generated URL:
{
"kind": "webhook",
"signingMode": "hmac_sha256",
"replayWindowSec": 300
}
Signing modes: bearer (default), hmac_sha256, github_hmac, and none.
The replay window applies to hmac_sha256 only: 30–86400 seconds (default 300).
Creating a webhook returns trigger and one-time secretMaterial containing
webhookUrl and webhookSecret. Save the secret before closing the dialog.
Routine details retain the URL; rotate the secret if its value is lost.
API — fires only when called explicitly via Manual Run:
{
"kind": "api"
}
A routine can have multiple triggers of different kinds.
Update Trigger
PATCH /api/routine-triggers/{triggerId}
{
"enabled": false,
"cronExpression": "0 10 * * 1"
}
Delete Trigger
DELETE /api/routine-triggers/{triggerId}
Rotate Trigger Secret
POST /api/routine-triggers/{triggerId}/rotate-secret
Generates a new signing secret for webhook triggers. The previous secret is immediately invalidated.
Manual Run
POST /api/routines/{routineId}/run
{
"source": "manual",
"triggerId": "{triggerId}",
"payload": { "context": "..." },
"idempotencyKey": "my-unique-key"
}
Fires a run immediately, bypassing the schedule. Concurrency policy still applies.
A run an agent starts through this endpoint is always recorded with source manual; the server ignores a source value an agent sends. Board callers may send manual or api.
triggerId is optional. When supplied, the server validates the trigger belongs to this routine (403) and is enabled (409), then records the run against that trigger and updates its lastFiredAt. Omit it for a generic manual run with no trigger attribution.
Fire Public Trigger
POST /api/routine-triggers/public/{publicId}/fire
Fires a webhook trigger from an external system without a Paperclip login. Send
Content-Type: application/json and a JSON object. The trigger authenticates the
request using its own secret; an agent or board API key is not a substitute.
| Mode | Headers and signature |
|---|---|
bearer |
Authorization: Bearer <webhookSecret> |
hmac_sha256 |
X-Paperclip-Timestamp (Unix seconds or milliseconds) and X-Paperclip-Signature: sha256=<hex>; HMAC-SHA256 over the timestamp string, a dot, and the exact body bytes |
github_hmac |
X-Hub-Signature-256: sha256=<hex>; HMAC-SHA256 over the exact body bytes, without a timestamp. X-Paperclip-Signature is also accepted. Configure GitHub to send JSON. |
none |
No signature. Anyone with the generated URL can fire the trigger; keep it private. |
For a bearer trigger:
curl --fail-with-body "$WEBHOOK_URL" \
-H "Authorization: Bearer $WEBHOOK_SECRET" \
-H 'Content-Type: application/json' \
-H 'Idempotency-Key: deployment-123' \
--data-binary '{"event":"deployment","variables":{"environment":"staging"}}'
For a timestamped HMAC trigger, sign and send the same bytes:
import { createHmac } from "node:crypto";
const body = JSON.stringify({ variables: { environment: "staging" } });
const timestamp = String(Math.floor(Date.now() / 1000));
const signature = createHmac("sha256", process.env.WEBHOOK_SECRET)
.update(`${timestamp}.`).update(body).digest("hex");
const response = await fetch(process.env.WEBHOOK_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Paperclip-Timestamp": timestamp,
"X-Paperclip-Signature": `sha256=${signature}`,
},
body,
});
console.log(response.status, await response.json());
202 returns the routine run, including its status and linked task. The task
runs asynchronously, so acceptance does not mean the agent has finished.
Concurrency policy can coalesce or skip a delivery while work is active.
Payload fields or a nested variables object supply declared routine variables;
nested values take precedence. The full payload is retained in run history.
For app-webhook triggers, the sender's JSON is also copied into the execution
task. Normal webhook intake does not apply a provider-specific field allowlist
or a general payload scrubber. Send only data suitable for company-readable
routine history; authentication and creation provenance do not certify the
payload's privacy. See the Sentry tutorial
for source-side scrubbing and setup checks.
For bearer, GitHub HMAC, and unsigned triggers, send a stable Idempotency-Key
when retrying a delivery to receive the original run without creating another
task. Timestamped HMAC rejects an identical signed delivery with 409, even
inside the replay window; stale timestamps and invalid secrets/signatures return
401. Disabled triggers and paused/archived routines return 409. Missing
required variables return 422; non-JSON media types return 415 and invalid
JSON objects return 400. Rotating a secret immediately invalidates the old one.
Cloud installations use their canonical public origin for generated URLs.
Self-hosted installations should set PAPERCLIP_PUBLIC_URL to their HTTPS
origin. The reverse proxy must forward this POST endpoint and its authorization,
signature, timestamp, and idempotency headers without requiring a browser login.
For local HTTPS testing, proxy an isolated test instance through Tailscale Serve;
use Funnel only if the sender is outside the tailnet. Existing routine and agent
execution controls still apply, including the isolated-worktree execution gate.
Verified creation provenance
The receiving routine and its run are recorded as the new task's direct origin.
Paperclip can also retain the run that invoked the routine. Authenticated agent
calls to the routine run API record a validated caller run. For an ordinary
public webhook, optionally send X-Paperclip-Source-Run-Token containing a
current, standard Paperclip run JWT from the same instance and company. The
trigger still authenticates with its own secret. Invalid, expired, foreign, or
stopped caller credentials return 401 before dispatch.
The source reference is stored as createdByRunId on the routine run, separate
from triggerPayload. Sender JSON and plain run-ID headers cannot establish
trusted caller ancestry. Without the source credential, a public webhook starts
a new external receiving-routine origin. This metadata grants no additional
execution or source-read authority. A source reference remains recorded after
run retention; unresolved ancestry is unknown, never assumed independent.
Routine-wide execution receipts
Send X-Paperclip-Idempotency-Scope: routine with a stable Idempotency-Key to
deduplicate execution receipts across webhook triggers on one routine. The
default is trigger. Keep the key and scope stable on retries. Routine scope
uses a deterministic receipt identity, so deleting the original trigger does
not let the same occurrence start another task. Scope does not change ordinary
concurrency, pause, company, permission, or budget controls.
Timestamped HMAC always uses trigger-scoped anti-replay receipts and rejects a
routine-scope request with 400. Setup checks create no routine runs; their
content-free test receipts remain associated with the setup trigger.
For a worked example that uses the normal webhook with Sentry, see Repair Failed Runs from Sentry.
List Runs
GET /api/routines/{routineId}/runs?limit=50
Returns recent run history for the routine. Defaults to 50 most recent runs.
Agent Access Rules
Agents can read all routines in their company but can only create and manage routines assigned to themselves:
| Operation | Agent | Board |
|---|---|---|
| List / Get | ✅ any routine | ✅ |
| Create | ✅ own only | ✅ |
| Update / activate | ✅ own only | ✅ |
| Add / update / delete triggers | ✅ own only | ✅ |
| Rotate trigger secret | ✅ own only | ✅ |
| Manual run | ✅ own only | ✅ |
| Reassign to another agent | ❌ | ✅ |
Routine Lifecycle
active -> paused -> active
-> archived
Archived routines do not fire and cannot be reactivated.
Routine detail navigation
The routine detail page keeps Runs and Activity in the routine sidebar. Runs lists the execution issues for that routine using the shared issue list, including issue status, priority, assignee, and search controls. Activity shows the routine, trigger, and run event timeline without leaving the routine page. The overview links to these same local tabs.
Webhook setup and connection checks
Create a webhook trigger with setupPending: true to configure it safely. While setup is pending, authenticated deliveries return 202 with { "status": "test_received", "test": true, "routineStarted": false, "linkedIssueId": null }. They never create a routine run, task, or agent wakeup. This state survives refreshes and server restarts, and connection checks also work while the routine is paused. Invalid authentication still returns 401.
Routine detail exposes setupPending and lastWebhookDelivery (status, receivedAt, and test) so the wizard can show live connection feedback. The secret is only returned at creation or rotation; it is never stored in browser draft storage or included in routine detail.
Finish setup with PATCH /api/routine-triggers/{id} and { "setupPending": false }. Future deliveries use normal routine dispatch and still respect the routine's enabled state. Test events are not dispatched on activation. Retries with the same Idempotency-Key, GitHub X-GitHub-Delivery, or timestamp-HMAC replay key remain test receipts after activation. Send a unique delivery ID per event so a sender's retries can be recognized. Requests without a delivery ID are new events after activation.
For compatibility, API-created triggers without setupPending: true are immediately live.
To test a live webhook again, send PATCH /api/routine-triggers/{id} with { "setupPending": true }. Only enabled, non-removed webhook triggers on a routine that is not archived can enter test mode: other trigger kinds return 422, and a disabled or removed webhook or an archived routine returns 409. While testing, every authenticated delivery, including real events from the sender, is recorded as a test and never starts the routine. Each test delivery's lastWebhookDelivery.previous holds the last real delivery from before testing (or null). Sending { "setupPending": false } returns the webhook to live and restores that last real delivery as lastWebhookDelivery. Events received while testing are not replayed, and retries of them with the same delivery ID stay test receipts.
Trigger cards support removal with Undo. PATCH with { "archived": true } excludes a trigger from routine detail and scheduling, and rejects its webhook deliveries. Setting archived back to false restores the same URL and credentials. DELETE remains the permanent deletion API.
The webhook wizard and saved trigger editor warn about localhost, private-network addresses, Tailscale hostnames, and HTTP URLs without blocking setup. HTTPS does not imply public access: Tailscale Serve is private, while Funnel can expose the same hostname publicly. These warnings inspect the URL only; they do not resolve DNS or test internet reachability. Use the HTTPS setup guide to configure public access when the sender is outside your network.