feat(ui): keep writes durable through temporary disconnects (#17960)

<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/123/changes/paperclip/123
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - People save tasks, write documents, make decisions and send board
messages.
> - A disconnect can hide a response after the server accepts a write.
> - Recovery must keep the original account, task and request key.
> - The merged connection foundation in #15754 handles reads and shared
outage state.
> - This change adds bounded write recovery and explicit actions when
recovery stops.

## Linked Issues or Issue Description

**What happened?**

Temporary failures could lose edits, report accepted writes as failures,
or require people to copy and send input again. A retry could target a
newly selected task or account. Restoring attachments could create a
second task.

**Expected behavior**

Keep the draft, its owner and its target. Retry only operations with a
server contract that prevents duplicate writes. Verify uncertain
results. Show conflicts and permanent failures, with an explicit resend
or cancel action.

**Steps to reproduce**

1. Save a task title during an outage, then open another task before
recovery.
2. Restore a task creation that needs files, selecting those files in
another order.
3. Lose a document or decision response, then interrupt the verification
read.
4. Switch accounts while a create, upload or connected-channel
publication is pending.
5. Type and erase a new-task draft before the first account lookup
completes, then reopen it.

This PR carries the write layer from #15769 and its review fixes. It
targets master after #15754 merged. Related test cleanup #16952 already
covers the unchanged copy-link toast test; this PR does not duplicate
that work.

## What Changed

- Add bounded autosave and submit jobs for supported writes, with
pending, conflict and manual retry states. Retain admitted autosaves
after navigation and preserve newer task revisions.
- Keep each job with its original account, task and operation. First
account resolution adopts admitted startup work; a later account change
cancels old work. Remount inline and document editors when their owner
or document subject changes.
- Preserve task-creation keys and immutable request snapshots through
file reattachment. Restore generated document keys before comparing
reselected files. Reject changed requests instead of creating a second
task.
- Check the original account scope before creates and each upload. Save
successful upload receipts before stopping on an account change.
Identify attachments by content digest and metadata.
- Verify uncertain document and decision results. Replay only plain,
keyed comments automatically; combined reassignment, reopen and
run-setting changes require receipt reconciliation or cancel. Settle
each request once when a receipt races its retry.
- Scope drafts and connected-channel publication reads to their owner.
Keep unowned older records unread and unreplayed, with an explicit
confirmed discard action after Activity inspection. Preserve typing
through the first session lookup, keep erased text erased, and report
browser persistence only when storage succeeds.
- Wait for the first account lookup before sending startup status
changes or decisions. Retry failed required lookups with a fixed limit
and surface exhaustion to the original action. Preserve uncertain
comment keys on account cancellation. Check the account generation
before a comment retry calls its sender and again immediately before
POST after asynchronous preparation. Retire only that request’s
optimistic echo on completion.
- Return an ordinary comment’s accepted same-company, same-task,
same-user receipt before workspace reopening, task status changes or
wakeups. Reused keys with changed text still conflict. Complete
reference and activity records through the same finalizer for initial
sends and accepted retries. It locks the task before its comment,
matching task and company deletion, comment removal and tombstoning,
rejects removed or tombstoned comments, repairs references and inserts a
missing activity record in one transaction, and publishes after commit.
- Remove reader-only record and comment-body size caps so accepted
browser writes remain readable, including JSON-escaped comment requests
in local and session storage. Update four existing Storybook fixtures to
use owned draft keys.
- Document the write contracts and add regression and real browser
recovery coverage.

- Add the exact reviewed-save recovery regression for both composer
implementations and reloads. Align receipt completion, both comment
deletion methods and company deletion with task deletion by locking
tasks first. Cover real task and company deletion races.

## Verification

- The exact reviewed-unknown-save regression fails in all four cases on
original commit `1ed0af4186`. It passes with this PR for both composers,
before and after reload. Cancel keeps the text and uploaded receipt. The
retained draft sends, and the next message also sends. Run `pnpm exec
vitest run --project @paperclipai/ui
ui/src/components/composer-recovery.test.tsx`.
- The new real PostgreSQL task-deletion race fails with SQLSTATE `40P01`
on parent commit `f3253a00c4`. The company-deletion race also fails with
`40P01` on `e8cf0e02dd`. All six receipt tests pass after the final
lock-order fixes. They cover company deletion, task deletion, comment
removal, tombstoning, concurrent cross-task references and interrupted
reference repair. Run `pnpm exec vitest run --project
@paperclipai/server
server/src/__tests__/issue-comment-receipt-postgres.test.ts`.
- The full UI run passed 9,656 of 9,659 tests across 816 files. Three
cases failed under that run: two large-tree timeouts and one
plugin-panel assertion. All 67 tests in those two files passed in an
isolated rerun. These failures remain recorded; this does not claim a
clean full UI run.
- `pnpm -r typecheck`, `pnpm build`, token gates and map checks pass on
the final change. The local full repository test command was started,
then stopped when the delivery moved to this existing PR. Fresh PR CI
must provide the full-suite gate.
- A local Storybook walkthrough used the real rich editor. Cancel kept
the restored text, Send cleared it after the simulated save, and a new
draft enabled Send again. Storybook simulates submission; it is not
staging acceptance.
- Earlier verification on `f3253a00c4` recorded five browser journeys
for title saves, cached-task offline recovery, startup recovery,
accepted comment replay and session lookup failure. Those results remain
prior-head evidence. No new staging deployment is claimed.

- On `e8cf0e02dd`, all CI checks passed after one browser-shard rerun.
Its first failure copied page text instead of YAML in an unrelated
agent-configuration test. On final commit `35131d4380`, Greptile is 5/5
with no unresolved review threads. The first CI attempt has two failures
outside this diff: runner close-attachment suspension and
scheduled-retry teardown. The scheduled-retry file passes all 14 tests
in isolation; the isolated runner test still fails locally. The single
standard CI rerun passed both jobs, and the aggregate verification gate
passed. All CI checks are green on `35131d4380`; Apex is 5/5 on that
same commit with no unresolved findings.

## Risks

- Automatic replay requires server duplicate prevention or result
verification. Uncertain combined mutations require receipt observation
or cancel and a fresh intentional send.
- Old unowned form drafts remain stored but are not assigned to an
account. Unowned channel records can be retired after Activity
inspection; this never cancels an accepted remote update.
- Browser storage and hashing can be unavailable. Storage failure is
reported honestly. Without a digest, replay can duplicate an upload
rather than silently drop a selected file.
- Detached autosaves remain bounded and check account ownership on each
attempt. Conflicts or exhaustion retain the draft for explicit recovery.
- No schema, credential or agent permission change is included. This PR
does not claim staging deployment or original-task acceptance.

## Model Used

Anthropic Claude Opus 5.5 (`claude-opus-5-5`) produced the original
implementation with tool use. OpenAI Codex, GPT-6 family, assisted with
restoration, integration, verification and review fixes. This Codex
session does not expose its exact serving 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: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Amy (Opus) <claude@users.noreply.github.com>
Co-authored-by: Dotta <bippadotta@protonmail.com>
This commit is contained in:
authored and GitHub committed 2026-10-28 10:52:06 -07:00
1 parent a2fbce9305
commit d30c8f42b8
62 files changed
+6486 -733

No files matched your search

@@ -0,0 +1,232 @@
import { randomUUID } from "node:crypto";
import { and, eq, sql } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { activityLog, companies, createDb, issueComments, issueReferenceMentions, issues } from "@paperclipai/db";
import { completeIssueCommentReceipt } from "../services/issue-comment-receipt.js";
import { issueReferenceService } from "../services/issue-references.js";
import { issueService } from "../services/issues.js";
import { deleteCompany } from "../services/company-deletion.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
const support = await getEmbeddedPostgresTestSupport();
const describePostgres = support.supported ? describe : describe.skip;
describePostgres("accepted comment finalization", () => {
let db: ReturnType<typeof createDb>;
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("paperclip-comment-receipt-");
db = createDb(database.connectionString);
}, 30_000);
afterAll(async () => {
await db?.$client.end({ timeout: 5 });
await database?.cleanup();
});
it("rolls back partial references and repairs them once across concurrent retries", async () => {
const companyId = randomUUID(), issueId = randomUUID(), targetId = randomUUID(), commentId = randomUUID();
const prefix = `RCP${companyId.slice(0, 6).toUpperCase()}`;
await db.insert(companies).values({ id: companyId, name: "Comment receipt recovery", issuePrefix: prefix });
await db.insert(issues).values([
{ id: issueId, companyId, title: "Completed task", status: "done", identifier: `${prefix}-1`, issueNumber: 1 },
{ id: targetId, companyId, title: "Referenced task", identifier: `${prefix}-2`, issueNumber: 2 },
]);
await db.insert(issueComments).values({
id: commentId, companyId, issueId, authorType: "user", authorUserId: "local-board",
clientRequestId: randomUUID(), body: `See ${prefix}-2`,
});
const refs = issueReferenceService(db);
let fail = true;
const interrupted = {
...refs,
syncComment: async (...args: Parameters<typeof refs.syncComment>) => {
await refs.syncComment(...args);
if (fail) throw new Error("Reference write interrupted before activity");
},
};
const input = {
companyId, issueId, commentId,
activity: () => ({ companyId, actorType: "user" as const, actorId: "local-board", action: "issue.comment_added",
entityType: "issue", entityId: issueId, details: { commentId } }),
};
await expect(completeIssueCommentReceipt(db, interrupted, input)).rejects.toThrow("Reference write interrupted");
expect(await db.select().from(issueReferenceMentions).where(eq(issueReferenceMentions.sourceRecordId, commentId))).toHaveLength(0);
expect(await db.select().from(activityLog).where(eq(activityLog.companyId, companyId))).toHaveLength(0);
fail = false;
await Promise.all(Array.from({ length: 3 }, () => completeIssueCommentReceipt(db, interrupted, input)));
expect(await db.select().from(issueReferenceMentions).where(and(
eq(issueReferenceMentions.sourceRecordId, commentId), eq(issueReferenceMentions.targetIssueId, targetId),
))).toHaveLength(1);
expect(await db.select().from(activityLog).where(eq(activityLog.companyId, companyId))).toHaveLength(1);
await db.delete(issueReferenceMentions).where(eq(issueReferenceMentions.sourceRecordId, commentId));
await completeIssueCommentReceipt(db, refs, input);
expect(await db.select().from(issueReferenceMentions).where(eq(issueReferenceMentions.sourceRecordId, commentId))).toHaveLength(1);
expect(await db.select().from(activityLog).where(eq(activityLog.companyId, companyId))).toHaveLength(1);
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0].status).toBe("done");
await expect(completeIssueCommentReceipt(db, refs, { ...input, companyId: randomUUID() })).rejects.toMatchObject({ status: 404 });
expect(await db.select().from(activityLog).where(eq(activityLog.companyId, companyId))).toHaveLength(1);
}, 30_000);
it("completes concurrent cross-task references without a deadlock", async () => {
const companyId = randomUUID(), firstId = randomUUID(), secondId = randomUUID();
const firstCommentId = randomUUID(), secondCommentId = randomUUID();
const prefix = `RCP${companyId.slice(0, 6).toUpperCase()}`;
await db.insert(companies).values({ id: companyId, name: "Cross-task comment recovery", issuePrefix: prefix });
await db.insert(issues).values([
{ id: firstId, companyId, title: "First task", status: "done", identifier: `${prefix}-1`, issueNumber: 1 },
{ id: secondId, companyId, title: "Second task", status: "done", identifier: `${prefix}-2`, issueNumber: 2 },
]);
await db.insert(issueComments).values([
{ id: firstCommentId, companyId, issueId: firstId, authorUserId: "local-board", body: `See ${prefix}-2` },
{ id: secondCommentId, companyId, issueId: secondId, authorUserId: "local-board", body: `See ${prefix}-1` },
]);
const refs = issueReferenceService(db);
let arrived = 0;
let release!: () => void;
const bothLocked = new Promise<void>(resolve => { release = resolve; });
const synchronized = {
...refs,
syncComment: async (...args: Parameters<typeof refs.syncComment>) => {
if (++arrived === 2) release();
await bothLocked;
await refs.syncComment(...args);
},
};
const results = await Promise.allSettled([[firstId, firstCommentId], [secondId, secondCommentId]].map(([issueId, commentId]) =>
completeIssueCommentReceipt(db, synchronized, { companyId, issueId, commentId,
activity: () => ({ companyId, actorType: "user", actorId: "local-board", action: "issue.comment_added",
entityType: "issue", entityId: issueId, details: { commentId } }),
})));
expect(results.map(result => result.status)).toEqual(["fulfilled", "fulfilled"]);
expect(await db.select().from(issueReferenceMentions).where(eq(issueReferenceMentions.companyId, companyId))).toHaveLength(2);
expect(await db.select().from(activityLog).where(eq(activityLog.companyId, companyId))).toHaveLength(2);
expect((await db.select().from(issues).where(eq(issues.companyId, companyId))).every(issue => issue.status === "done")).toBe(true);
}, 30_000);
it.each(["remove", "tombstone"] as const)("serializes completion with a real %s without a deadlock", async (kind) => {
const companyId = randomUUID(), issueId = randomUUID(), commentId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Comment deletion race", issuePrefix: `RCP${companyId.slice(0, 6).toUpperCase()}` });
await db.insert(issues).values({ id: issueId, companyId, title: "Completed task", status: "done" });
await db.insert(issueComments).values({ id: commentId, companyId, issueId, authorUserId: "local-board", body: "Saved comment" });
await issueService(db).removeComment(randomUUID());
const monitored = (started: (pid: number) => void) => new Proxy(db, {
get(target, property) {
if (property === "transaction") return (callback: (tx: any) => Promise<unknown>) => target.transaction(async tx => {
const [row] = await tx.execute(sql`select pg_backend_pid() as pid`);
started(Number(row.pid));
return callback(tx);
});
const value = Reflect.get(target, property, target);
return typeof value === "function" ? value.bind(target) : value;
},
});
const waitForLock = async (pid: number) => vi.waitFor(async () => {
const [state] = await db.execute(sql`select wait_event_type from pg_stat_activity where pid=${pid}`);
expect(state?.wait_event_type).toBe("Lock");
}, { timeout: 5_000, interval: 10 });
let release!: () => void, held!: () => void;
const gate = new Promise<void>(resolve => { release = resolve; });
const ready = new Promise<void>(resolve => { held = resolve; });
const holding = db.transaction(async tx => {
await tx.select().from(issueComments).where(eq(issueComments.id, commentId)).for("update");
held();
await gate;
});
const operations: Promise<unknown>[] = [holding];
try {
await ready;
let deleteStarted!: (pid: number) => void;
const deletePid = new Promise<number>(resolve => { deleteStarted = resolve; });
const deletingService = issueService(monitored(deleteStarted));
const deleting = (kind === "remove" ? deletingService.removeComment(commentId)
: deletingService.tombstoneComment(commentId, { actorType: "user", userId: "local-board" })).catch(error => error);
operations.push(deleting);
await waitForLock(await deletePid);
let completeStarted!: (pid: number) => void;
const completePid = new Promise<number>(resolve => { completeStarted = resolve; });
const completing = completeIssueCommentReceipt(monitored(completeStarted), issueReferenceService(db), {
companyId, issueId, commentId,
activity: () => ({ companyId, actorType: "user", actorId: "local-board", action: "issue.comment_added",
entityType: "issue", entityId: issueId, details: { commentId } }),
}).catch(error => error);
operations.push(completing);
await waitForLock(await completePid);
release();
await holding;
expect(await deleting).toMatchObject({ id: commentId });
expect(await completing).toMatchObject({ status: 404 });
expect(await db.select().from(activityLog).where(eq(activityLog.companyId, companyId))).toHaveLength(0);
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0].status).toBe("done");
} finally {
release();
await Promise.allSettled(operations);
}
}, 30_000);
it.each(["task", "company"] as const)("serializes receipt completion with actual %s deletion", async kind => {
const companyId = randomUUID(), issueId = randomUUID(), commentId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Task deletion race", issuePrefix: `RCP${companyId.slice(0, 6).toUpperCase()}` });
await db.insert(issues).values({ id: issueId, companyId, title: "Completed task", status: "done" });
await db.insert(issueComments).values({ id: commentId, companyId, issueId, authorUserId: "local-board", body: "Saved comment" });
let release!: () => void, held!: () => void, receiptStarted!: (pid: number) => void;
const gate = new Promise<void>(resolve => { release = resolve; });
const ready = new Promise<void>(resolve => { held = resolve; });
const receiptPid = new Promise<number>(resolve => { receiptStarted = resolve; });
const wrap = (deleting: boolean) => new Proxy(db, {
get(target, property) {
if (property === "transaction") return (callback: (tx: any) => Promise<unknown>) => target.transaction(async tx => {
if (!deleting) {
const [row] = await tx.execute(sql`select pg_backend_pid() as pid`);
receiptStarted(Number(row.pid));
}
return callback(new Proxy(tx, {
get(transaction, method) {
// Delay the real task DELETE, preserving each service's normal
// earlier locks (including company deletion's child-row locks).
if (deleting && method === "delete") return (table: unknown) => {
const builder = transaction.delete(table as typeof issues);
if (table !== issues) return builder;
return { where: (...args: Parameters<typeof builder.where>) => {
const query = builder.where(...args);
const wait = async () => { held(); await gate; };
return kind === "task"
? { returning: async () => { await wait(); return query.returning(); } }
: (async () => { await wait(); return query; })();
} };
};
const value = Reflect.get(transaction, method, transaction);
return typeof value === "function" ? value.bind(transaction) : value;
},
}));
});
const value = Reflect.get(target, property, target);
return typeof value === "function" ? value.bind(target) : value;
},
});
const deleting = (kind === "task" ? issueService(wrap(true)).remove(issueId)
: deleteCompany(wrap(true), companyId)).catch(error => error);
let completing: Promise<unknown> | undefined;
try {
await ready;
completing = completeIssueCommentReceipt(wrap(false), issueReferenceService(db), {
companyId, issueId, commentId,
activity: () => ({ companyId, actorType: "user", actorId: "local-board", action: "issue.comment_added",
entityType: "issue", entityId: issueId, details: { commentId } }),
}).catch(error => error);
const pid = await receiptPid;
await vi.waitFor(async () => {
const [state] = await db.execute(sql`select wait_event_type from pg_stat_activity where pid=${pid}`);
expect(state?.wait_event_type).toBe("Lock");
}, { timeout: 5_000, interval: 10 });
release();
expect(await deleting).toMatchObject({ id: kind === "task" ? issueId : companyId });
expect(await completing).toMatchObject({ status: 404 });
expect(await db.select().from(issues).where(eq(issues.id, issueId))).toHaveLength(0);
expect(await db.select().from(issueComments).where(eq(issueComments.id, commentId))).toHaveLength(0);
expect(await db.select().from(activityLog).where(eq(activityLog.companyId, companyId))).toHaveLength(0);
if (kind === "company") expect(await db.select().from(companies).where(eq(companies.id, companyId))).toHaveLength(0);
} finally {
release();
await Promise.allSettled([deleting, completing]);
}
}, 30_000);
});
@@ -49,17 +49,20 @@ const mockAgentService = vi.hoisted(() => ({
}));
const mockLogActivity = vi.hoisted(() => vi.fn(async () => undefined));
const mockSyncCommentReferences = vi.hoisted(() => vi.fn(async () => undefined));
const mockTxInsertValues = vi.hoisted(() => vi.fn(async () => undefined));
const mockTxInsert = vi.hoisted(() =>
vi.fn(() => ({ values: mockTxInsertValues })),
);
const mockTx = vi.hoisted(() => ({
select: () => mockDbSelect(),
insert: mockTxInsert,
}));
const mockDbSelectOrderBy = vi.hoisted(() => vi.fn(async () => []));
const mockDbSelectWhere = vi.hoisted(() =>
vi.fn(() => ({
orderBy: mockDbSelectOrderBy,
for: async () => [{ id: "comment-1" }],
then: (
onFulfilled: (rows: unknown[]) => unknown,
onRejected?: (reason: unknown) => unknown,
@@ -203,7 +206,7 @@ vi.mock("../services/index.js", () => ({
}),
emptySummary: () => ({ outbound: [], inbound: [] }),
listIssueReferenceSummary: async () => ({ outbound: [], inbound: [] }),
syncComment: async () => undefined,
syncComment: mockSyncCommentReferences,
syncDocument: async () => undefined,
syncIssue: async () => undefined,
}),
@@ -397,6 +400,7 @@ describe("issue comment reopen routes", () => {
mockAgentService.list.mockReset();
mockAgentService.resolveByReference.mockReset();
mockLogActivity.mockReset();
mockSyncCommentReferences.mockReset().mockResolvedValue(undefined);
mockFeedbackService.listIssueVotesForUser.mockReset();
mockFeedbackService.saveIssueVote.mockReset();
mockInstanceSettingsService.get.mockReset();
@@ -422,6 +426,7 @@ describe("issue comment reopen routes", () => {
mockDbSelectOrderBy.mockResolvedValue([]);
mockDbSelectWhere.mockImplementation(() => ({
orderBy: mockDbSelectOrderBy,
for: async () => [{ id: "comment-1" }],
then: (
onFulfilled: (rows: unknown[]) => unknown,
onRejected?: (reason: unknown) => unknown,
@@ -573,6 +578,41 @@ describe("issue comment reopen routes", () => {
);
});
it("finishes missing reference and activity writes for an accepted comment", async () => {
const issue = makeIssue("done");
mockIssueService.getById.mockResolvedValue(issue);
const selectFrom = mockDbSelectFrom.getMockImplementation()!;
mockDbSelectFrom.mockImplementation((table) => getTableName(table as Parameters<typeof getTableName>[0]) === "issue_comments"
? { where: vi.fn(() => Object.assign(Promise.resolve([{ id: "comment-1" }]), { for: async () => [{ id: "comment-1" }] })) } as any : selectFrom(table));
const response = await request(await installActor(createApp())).post(`/api/issues/${issue.id}/comments`)
.send({ body: "hello", clientRequestId: "77777777-7777-4777-8777-777777777777" });
expect(response.status).toBe(201);
expect(mockSyncCommentReferences).toHaveBeenCalledWith("comment-1", expect.anything());
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
action: "issue.comment_added", details: expect.objectContaining({ commentId: "comment-1" }),
}), expect.anything());
expect(mockIssueService.update).not.toHaveBeenCalled();
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
});
it.each([false, true])("returns a retained comment before reopening completed work (changed body=%s)", async (changed) => {
const issue = makeIssue("done");
const requestId = "77777777-7777-4777-8777-777777777777";
mockIssueService.getById.mockResolvedValue(issue);
const selectFrom = mockDbSelectFrom.getMockImplementation()!;
mockDbSelectFrom.mockImplementation((table) => getTableName(table as Parameters<typeof getTableName>[0]) === "issue_comments"
? { where: vi.fn(() => Object.assign(Promise.resolve([{ id: "comment-1" }]), { for: async () => [{ id: "comment-1" }] })) } as any : getTableName(table as Parameters<typeof getTableName>[0]) === "activity_log"
? { where: async () => [{ id: "activity-1" }] } as any : selectFrom(table));
if (changed) mockIssueService.addComment.mockRejectedValue(new HttpError(409, "Message request ID was already used for different content"));
const response = await request(await installActor(createApp())).post(`/api/issues/${issue.id}/comments`)
.send({ body: changed ? "Changed body" : "hello", clientRequestId: requestId });
expect(response.status).toBe(changed ? 409 : 201);
if (!changed) expect(response.body.id).toBe("comment-1");
expect(mockIssueService.update).not.toHaveBeenCalled();
expect(mockLogActivity).not.toHaveBeenCalled();
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
});
it("treats reopen=true as a no-op when the issue is already open", async () => {
mockIssueService.getById.mockResolvedValue(makeIssue("todo"));
mockIssueService.update.mockImplementation(
@@ -2,6 +2,11 @@ import express from "express";
import request from "supertest";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../services/activity-log.js", () => ({
logActivity: vi.fn(async () => undefined),
publishActivity: vi.fn(),
}));
vi.mock("../services/fast-responses.js", () => ({
enqueueFastResponse: vi.fn(async () => undefined),
}));
@@ -222,7 +227,7 @@ async function loadAppModules() {
}
async function createApp(transaction: (callback: (tx: Record<string, never>) => Promise<unknown>) => Promise<unknown> =
async (callback) => callback({})) {
async (callback) => callback({ select: () => ({ from: () => ({ where: () => Object.assign(Promise.resolve([]), { for: async () => [{ id: "comment-3" }] }) }) }) } as any)) {
const [{ errorHandler }, { issueRoutes }] = await loadAppModules();
const app = express();
app.use(express.json());
@@ -239,6 +244,7 @@ async function createApp(transaction: (callback: (tx: Record<string, never>) =>
});
app.use("/api", issueRoutes({
transaction,
select: () => ({ from: () => ({ where: async () => [] }) }),
} as any, {} as any));
app.use(errorHandler);
return app;
+111 -67
View File
@@ -1,3 +1,4 @@
import { completeIssueCommentReceipt } from "../services/issue-comment-receipt.js";
import { taskInterruptionPresentation, taskInterruptionPresentations } from "../services/task-interruption-presentation.js";
import { parseObject } from "../adapters/utils.js";
import { prepareRestrictedWorkspaceRetry } from "../services/restricted-workspace-retry.js";
@@ -18468,7 +18469,6 @@ export function issueRoutes(
issue,
);
if (!commentAccessDecision) return;
if (!(await assertBoardCommentNotPaused(req, res, issue))) return;
const commentAuthorizationReason = issueWriteAuthorizationReason(
req,
commentAccessDecision,
@@ -18480,6 +18480,42 @@ export function issueRoutes(
})
)
return;
if (req.actor.type === "board" && req.actor.userId && req.body.clientRequestId) {
const [accepted] = await db.select({ id: issueComments.id }).from(issueComments).where(and(
eq(issueComments.companyId, issue.companyId), eq(issueComments.issueId, issue.id),
eq(issueComments.authorUserId, req.actor.userId), eq(issueComments.clientRequestId, req.body.clientRequestId),
));
if (accepted) {
const receipt = await svc.addComment(issue.id, req.body.body, { userId: req.actor.userId }, {
clientRequestId: req.body.clientRequestId, attachmentIds: req.body.attachmentIds,
authorType: "user",
});
const userId = req.actor.userId;
await completeIssueCommentReceipt(db, issueReferencesSvc, {
companyId: issue.companyId, issueId: issue.id, commentId: receipt.id,
activity: diff => ({
companyId: issue.companyId, actorType: "user", actorId: userId,
runId: receipt.createdByRunId,
responsibleUserIdOverride: receipt.onBehalfOfUserId ?? userId,
action: "issue.comment_added", entityType: "issue", entityId: issue.id,
details: {
commentId: receipt.id, bodySnippet: receipt.body.slice(0, 120),
identifier: issue.identifier, issueTitle: issue.title,
authorizationReason: commentAuthorizationReason, source: "comment_receipt_recovery",
...summarizeIssueReferenceActivityDetails({
addedReferencedIssues: diff.addedReferencedIssues.map(summarizeIssueRelationForActivity),
removedReferencedIssues: diff.removedReferencedIssues.map(summarizeIssueRelationForActivity),
currentReferencedIssues: diff.currentReferencedIssues.map(summarizeIssueRelationForActivity),
}),
},
}),
});
await externalObjectsSvc.syncCommentSafely(receipt.id);
res.status(201).json(receipt);
return;
}
}
if (!(await assertBoardCommentNotPaused(req, res, issue))) return;
const closedExecutionWorkspace =
await getClosedIssueExecutionWorkspace(issue);
@@ -18969,72 +19005,8 @@ export function issueRoutes(
.catch(() => logger.warn({ issueId: currentIssue.id }, "fast response admission unavailable"));
}
await issueReferencesSvc.syncComment(comment.id);
await externalObjectsSvc.syncCommentSafely(comment.id);
if (
currentIssue.assigneeAgentId &&
// Slack-linked messages need the normal attributed wake boundary so
// the accepted requester and return-thread receipt travel with the run.
!currentIssue.externalConversationState &&
!(
actor.actorType === "agent" &&
actor.actorId === currentIssue.assigneeAgentId
)
) {
const goalProjection = await runnerGoals.projection(
currentIssue.companyId,
currentIssue.id,
currentIssue.assigneeAgentId,
);
if (
goalProjection?.goal?.status === "active" &&
goalProjection.workingNow
) {
const steer = queueLiveRunnerPrpCommand({
companyId: currentIssue.companyId,
issueId: currentIssue.id,
agentId: currentIssue.assigneeAgentId,
type: "turn.steer",
payload: { text: comment.body },
commandId: `goal_comment_${comment.id}`,
});
if (steer) {
try {
await steer.completion;
goalCommentSteered = true;
} catch (err) {
logger.warn(
{
err,
issueId: currentIssue.id,
commentId: comment.id,
runId: steer.runId,
},
"failed to steer an active session goal; falling back to a boundary wake",
);
}
}
}
}
const commentReferenceSummaryAfter =
await issueReferencesSvc.listIssueReferenceSummary(currentIssue.id);
const commentReferenceDiff = issueReferencesSvc.diffIssueReferenceSummary(
commentReferenceSummaryBefore,
commentReferenceSummaryAfter,
);
if (actor.runId) {
await heartbeat
.reportRunActivity(actor.runId)
.catch((err) =>
logger.warn(
{ err, runId: actor.runId },
"failed to clear detached run warning after issue comment",
),
);
}
await logActivity(db, {
const keyedComment = req.actor.type === "board" && Boolean(req.actor.userId && req.body.clientRequestId);
const buildCommentActivity = (commentReferenceDiff: ReturnType<typeof issueReferencesSvc.diffIssueReferenceSummary>) => ({
companyId: currentIssue.companyId,
actorType: actor.actorType,
actorId: actor.actorId,
@@ -19091,6 +19063,78 @@ export function issueRoutes(
}),
},
});
if (keyedComment) await completeIssueCommentReceipt(db, issueReferencesSvc, {
companyId: currentIssue.companyId, issueId: currentIssue.id, commentId: comment.id,
referenceSummaryBefore: commentReferenceSummaryBefore, activity: buildCommentActivity,
});
else await issueReferencesSvc.syncComment(comment.id);
await externalObjectsSvc.syncCommentSafely(comment.id);
if (
currentIssue.assigneeAgentId &&
// Slack-linked messages need the normal attributed wake boundary so
// the accepted requester and return-thread receipt travel with the run.
!currentIssue.externalConversationState &&
!(
actor.actorType === "agent" &&
actor.actorId === currentIssue.assigneeAgentId
)
) {
const goalProjection = await runnerGoals.projection(
currentIssue.companyId,
currentIssue.id,
currentIssue.assigneeAgentId,
);
if (
goalProjection?.goal?.status === "active" &&
goalProjection.workingNow
) {
const steer = queueLiveRunnerPrpCommand({
companyId: currentIssue.companyId,
issueId: currentIssue.id,
agentId: currentIssue.assigneeAgentId,
type: "turn.steer",
payload: { text: comment.body },
commandId: `goal_comment_${comment.id}`,
});
if (steer) {
try {
await steer.completion;
goalCommentSteered = true;
} catch (err) {
logger.warn(
{
err,
issueId: currentIssue.id,
commentId: comment.id,
runId: steer.runId,
},
"failed to steer an active session goal; falling back to a boundary wake",
);
}
}
}
}
if (actor.runId) {
await heartbeat
.reportRunActivity(actor.runId)
.catch((err) =>
logger.warn(
{ err, runId: actor.runId },
"failed to clear detached run warning after issue comment",
),
);
}
if (!keyedComment) {
const commentReferenceSummaryAfter =
await issueReferencesSvc.listIssueReferenceSummary(currentIssue.id);
const commentReferenceDiff = issueReferencesSvc.diffIssueReferenceSummary(
commentReferenceSummaryBefore,
commentReferenceSummaryAfter,
);
await logActivity(db, buildCommentActivity(commentReferenceDiff));
}
const expiredInteractions = await issueThreadInteractionService(
db,
+3
View File
@@ -100,6 +100,9 @@ export async function deleteCompany(db: Db, id: string) {
await tx.delete(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, id));
await tx.delete(agentApiKeys).where(eq(agentApiKeys.companyId, id));
await tx.delete(agentRuntimeState).where(eq(agentRuntimeState.companyId, id));
// Match receipt completion and comment deletion: task before comment.
await tx.select({ id: issues.id }).from(issues)
.where(eq(issues.companyId, id)).orderBy(issues.id).for("no key update");
await tx.delete(issueComments).where(eq(issueComments.companyId, id));
await tx.delete(approvalComments).where(eq(approvalComments.companyId, id));
await notifyCompanyRetentionWork(tx, id);
@@ -0,0 +1,52 @@
import { and, eq, sql } from "drizzle-orm";
import { activityLog, issueComments, issues, type Db } from "@paperclipai/db";
import type { IssueRelatedWorkSummary } from "@paperclipai/shared";
import { notFound } from "../errors.js";
import { logActivity, publishActivity, type ActivityPublication, type LogActivityInput } from "./activity-log.js";
import type { issueReferenceService } from "./issue-references.js";
type CommentReferences = Pick<ReturnType<typeof issueReferenceService>,
"syncComment" | "listIssueReferenceSummary" | "diffIssueReferenceSummary">;
type ReferenceDiff = ReturnType<CommentReferences["diffIssueReferenceSummary"]>;
export async function completeIssueCommentReceipt(db: Db, references: CommentReferences, input: {
companyId: string;
issueId: string;
commentId: string;
referenceSummaryBefore?: IssueRelatedWorkSummary;
activity: (diff: ReferenceDiff) => LogActivityInput;
}) {
const publications: ActivityPublication[] = [];
await db.transaction(async tx => {
const connection = tx as unknown as Db;
// Match task deletion and comment mutation: lock the task before its
// comment. NO KEY UPDATE still permits references from other tasks.
const [issue] = await tx.select({ id: issues.id }).from(issues).where(and(
eq(issues.id, input.issueId), eq(issues.companyId, input.companyId),
)).for("no key update");
if (!issue) throw notFound("Issue not found");
const [comment] = await tx.select({ id: issueComments.id, deletedAt: issueComments.deletedAt }).from(issueComments).where(and(
eq(issueComments.id, input.commentId), eq(issueComments.companyId, input.companyId),
eq(issueComments.issueId, input.issueId),
)).for("update");
if (!comment || comment.deletedAt) throw notFound("Issue comment not found");
const before = input.referenceSummaryBefore ?? await references.listIssueReferenceSummary(input.issueId, connection);
await references.syncComment(input.commentId, connection);
const after = await references.listIssueReferenceSummary(input.issueId, connection);
const diff = references.diffIssueReferenceSummary(before, after);
const [existing] = await tx.select({ id: activityLog.id }).from(activityLog).where(and(
eq(activityLog.companyId, input.companyId), eq(activityLog.entityType, "issue"),
eq(activityLog.entityId, input.issueId), eq(activityLog.action, "issue.comment_added"),
sql`${activityLog.details}->>'commentId' = ${input.commentId}`,
));
if (!existing) {
const activity = input.activity(diff);
await logActivity(connection, {
...activity, companyId: input.companyId, action: "issue.comment_added",
entityType: "issue", entityId: input.issueId,
details: { ...activity.details, commentId: input.commentId },
}, publications);
}
});
for (const publication of publications) publishActivity(publication);
}
+13
View File
@@ -6750,6 +6750,17 @@ export async function readIssueCommentRunLogText(run: {
return content;
}
/** Share task-before-comment lock order with receipt completion and task deletion. */
async function lockIssueForCommentMutation(tx: DbTransaction, commentId: string) {
const [comment] = await tx.select({ issueId: issueComments.issueId, companyId: issueComments.companyId })
.from(issueComments).where(eq(issueComments.id, commentId));
if (!comment) return false;
const [issue] = await tx.select({ id: issues.id }).from(issues).where(and(
eq(issues.id, comment.issueId), eq(issues.companyId, comment.companyId),
)).for("no key update");
return Boolean(issue);
}
export function issueService(db: Db) {
const instanceSettings = instanceSettingsService(db);
const treeControlSvc = issueTreeControlService(db);
@@ -12569,6 +12580,7 @@ export function issueService(db: Db) {
};
return db.transaction(async (tx) => {
if (!(await lockIssueForCommentMutation(tx, commentId))) return null;
const [comment] = await tx
.delete(issueComments)
.where(eq(issueComments.id, commentId))
@@ -12602,6 +12614,7 @@ export function issueService(db: Db) {
};
return db.transaction(async (tx) => {
if (!(await lockIssueForCommentMutation(tx, commentId))) return null;
const now = new Date();
const [comment] = await tx
.update(issueComments)