mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-27 19:35:13 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Reviewers annotate plans and issue documents with inline comments, and assigned agents act on that feedback > - The server already builds a bounded review context from open plan annotations and includes it in agent wake payloads > - Non-plan issue documents did not get the same treatment: their open annotation threads never reached the agent, and the properties pane did not surface their annotations > - This pull request extends the review-context path and the properties-pane UI to issue documents, at parity with plans > - The benefit is that agent feedback on any issue document reaches the assigned agent, not only feedback on the plan ## Linked Issues or Issue Description **What existing behavior does this improve?** The review-context pipeline that delivers inline annotation feedback to assigned agents, and the properties pane that surfaces those annotations to reviewers. **Subsystem affected** The server review-context path (`server/src/services/plan-review-context.ts`, wake payload assembly in `server/src/services/heartbeat.ts`, `server/src/routes/issues.ts`), shared wake-payload types (`packages/shared`, `packages/adapter-utils`), and the issue properties pane (`ui/src/components/issue-properties/`). **Current behavior** A reviewer can annotate any issue document, not only the plan. The agent wake payload includes open annotation threads for the plan document only. Feedback left on other issue documents is invisible to the assigned agent. In the properties pane, the Artifacts tab also gives no way to see or open a document's annotations. **Proposed behavior** Add `buildDocumentReviewContext` beside the existing plan builder. It collects open annotation threads for all non-plan issue documents, applies the same thread, comment, and character budgets across documents, and reports truncation. Include the result as a new `documentReviewContext` field in agent wake payloads and in the issue wake-context route. Keep the plan context on its legacy builder and field so plan-only wakes stay byte-for-byte compatible. Render the new context in the adapter wake-payload text, and surface annotation counts and the annotation panel for documents in the properties pane's Plans and Artifacts tabs. **Reason and benefit** The floating annotation popover and persistent highlight UI landed earlier; this change completes the loop so agent feedback on any issue document reaches the assigned agent, not only feedback on the plan. **Breaking changes** None. The wake payload gains a new optional `documentReviewContext` field; the existing plan context field and its legacy builder are unchanged, so plan-only wakes stay byte-for-byte compatible. ## What Changed - Add `buildDocumentReviewContext` in `server/src/services/plan-review-context.ts`: bounded review context (shared thread/comment/character budgets, per-document legacy limits) over all non-plan issue documents - Include `documentReviewContext` in agent wake payloads (`server/src/services/heartbeat.ts`) and in the issue wake-context response (`server/src/routes/issues.ts`) - Add shared `DocumentReviewContext` / `DocumentReviewContextDocument` types in `packages/shared` - Normalize and render the new context in adapter wake-payload text (`packages/adapter-utils/src/server-utils.ts`), with tests - Show a `DocumentAnnotationsCountChip` and the annotation panel for documents in the properties pane Plans and Artifacts tabs, with tests - Extend server document-annotations service tests to cover the new context builder ## Verification - Run `npx vitest run packages/adapter-utils/src/server-utils.test.ts server/src/__tests__/document-annotations-service.test.ts` from the repo root — 104 tests pass - Run `TZ=UTC npx vitest run ui/src/components/issue-properties/IssuePropertiesDocumentAnnotations.test.tsx ui/src/components/IssueProperties.test.tsx ui/src/components/IssueDocumentAnnotations.test.tsx ui/src/components/DocumentAnnotationPopover.test.tsx` from the repo root — 75 tests pass (one pre-existing monitor-row case asserts UTC timestamps, so use `TZ=UTC` locally; CI runs in UTC) - `pnpm run typecheck` in `server/` passes - Manual: annotate a non-plan issue document, then wake the assigned agent with a comment — the wake payload lists the open document annotation threads; the Artifacts tab shows the annotation count chip and opens the panel ## Risks - The wake payload gains a new optional `documentReviewContext` field; consumers that ignore unknown fields are unaffected, and the plan context field is unchanged - The context is new input to agent wakes; shared budgets (same limits as the plan context) bound token cost across all documents - Low UI risk: the properties-pane changes reuse the existing annotation components > 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 - Claude (Anthropic), model ID `claude-fable-5` (Claude Fable 5), with extended thinking and agentic tool use (Claude Code harness) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip <noreply@paperclip.ing>
565 lines
22 KiB
TypeScript
565 lines
22 KiB
TypeScript
import { and, asc, desc, eq, inArray, sql } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import {
|
|
documentAnnotationComments,
|
|
documentAnnotationThreads,
|
|
documents,
|
|
issueDocuments,
|
|
issueThreadInteractions,
|
|
} from "@paperclipai/db";
|
|
import type {
|
|
DocumentReviewContext,
|
|
DocumentReviewContextDocument,
|
|
PlanReviewContext,
|
|
PlanReviewContextAuthor,
|
|
PlanReviewInteractionContext,
|
|
PlanReviewInteractionResultContext,
|
|
PlanReviewInteractionTargetContext,
|
|
} from "@paperclipai/shared";
|
|
import { parseObject } from "../adapters/utils.js";
|
|
|
|
export const PLAN_REVIEW_CONTEXT_LIMITS = {
|
|
maxThreads: 20,
|
|
maxComments: 80,
|
|
maxBodyChars: 1_200,
|
|
maxTotalBodyChars: 12_000,
|
|
maxAnchorTextChars: 500,
|
|
} as const;
|
|
|
|
type BuildPlanReviewContextInput = {
|
|
db: Db;
|
|
companyId: string;
|
|
issueId: string;
|
|
issueWorkMode?: string | null;
|
|
includeForIssueComment?: boolean;
|
|
includeForAnnotationDelta?: boolean;
|
|
interactionId?: string | null;
|
|
};
|
|
|
|
type BuildDocumentReviewContextInput = Omit<BuildPlanReviewContextInput, "issueWorkMode" | "interactionId">;
|
|
|
|
function nonEmptyString(value: unknown) {
|
|
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
|
}
|
|
|
|
function truncateText(value: string, maxChars: number) {
|
|
if (value.length <= maxChars) return { text: value, truncated: false };
|
|
return { text: value.slice(0, maxChars), truncated: true };
|
|
}
|
|
|
|
function authorFrom(row: {
|
|
authorType?: string | null;
|
|
authorAgentId?: string | null;
|
|
authorUserId?: string | null;
|
|
}): PlanReviewContextAuthor {
|
|
if (row.authorAgentId) return { type: "agent", id: row.authorAgentId };
|
|
if (row.authorUserId) return { type: "user", id: row.authorUserId };
|
|
return {
|
|
type: row.authorType === "agent" || row.authorType === "user" || row.authorType === "system"
|
|
? row.authorType
|
|
: "system",
|
|
id: null,
|
|
};
|
|
}
|
|
|
|
function readPlanTarget(value: unknown, issueId: string): PlanReviewInteractionTargetContext | null {
|
|
const target = parseObject(value);
|
|
if (target.type !== "issue_document") return null;
|
|
if (target.key !== "plan") return null;
|
|
if (nonEmptyString(target.issueId) !== issueId) return null;
|
|
return {
|
|
issueId,
|
|
documentId: nonEmptyString(target.documentId),
|
|
key: "plan",
|
|
revisionId: nonEmptyString(target.revisionId),
|
|
revisionNumber: typeof target.revisionNumber === "number" ? target.revisionNumber : null,
|
|
};
|
|
}
|
|
|
|
function readResult(value: unknown): PlanReviewInteractionResultContext | null {
|
|
const result = parseObject(value);
|
|
if (Object.keys(result).length === 0) return null;
|
|
return {
|
|
outcome: nonEmptyString(result.outcome),
|
|
reason: nonEmptyString(result.reason) ?? nonEmptyString(result.rejectionReason),
|
|
commentId: nonEmptyString(result.commentId),
|
|
};
|
|
}
|
|
|
|
async function getPlanInteractionContext(input: {
|
|
db: Db;
|
|
companyId: string;
|
|
issueId: string;
|
|
interactionId: string | null;
|
|
}): Promise<PlanReviewInteractionContext | null> {
|
|
if (!input.interactionId) return null;
|
|
|
|
const row = await input.db
|
|
.select({
|
|
id: issueThreadInteractions.id,
|
|
kind: issueThreadInteractions.kind,
|
|
status: issueThreadInteractions.status,
|
|
continuationPolicy: issueThreadInteractions.continuationPolicy,
|
|
sourceCommentId: issueThreadInteractions.sourceCommentId,
|
|
sourceRunId: issueThreadInteractions.sourceRunId,
|
|
payload: issueThreadInteractions.payload,
|
|
result: issueThreadInteractions.result,
|
|
resolvedAt: issueThreadInteractions.resolvedAt,
|
|
})
|
|
.from(issueThreadInteractions)
|
|
.where(and(
|
|
eq(issueThreadInteractions.id, input.interactionId),
|
|
eq(issueThreadInteractions.companyId, input.companyId),
|
|
eq(issueThreadInteractions.issueId, input.issueId),
|
|
))
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
if (!row) return null;
|
|
const payload = parseObject(row.payload);
|
|
const target = readPlanTarget(payload.target, input.issueId);
|
|
if (!target) return null;
|
|
const result = readResult(row.result);
|
|
|
|
return {
|
|
id: row.id,
|
|
kind: row.kind,
|
|
status: row.status,
|
|
continuationPolicy: row.continuationPolicy,
|
|
sourceCommentId: row.sourceCommentId ?? null,
|
|
sourceRunId: row.sourceRunId ?? null,
|
|
target,
|
|
acceptedTargetRevision: row.status === "accepted" ? target : null,
|
|
result,
|
|
resolvedAt: row.resolvedAt ? row.resolvedAt.toISOString() : null,
|
|
};
|
|
}
|
|
|
|
export async function buildPlanReviewContext(input: BuildPlanReviewContextInput): Promise<PlanReviewContext | null> {
|
|
const interaction = await getPlanInteractionContext({
|
|
db: input.db,
|
|
companyId: input.companyId,
|
|
issueId: input.issueId,
|
|
interactionId: nonEmptyString(input.interactionId),
|
|
});
|
|
const shouldInclude =
|
|
input.issueWorkMode === "planning" ||
|
|
input.includeForIssueComment === true ||
|
|
input.includeForAnnotationDelta === true ||
|
|
interaction !== null;
|
|
if (!shouldInclude) return null;
|
|
|
|
const planDocument = await input.db
|
|
.select({
|
|
documentId: documents.id,
|
|
latestRevisionId: documents.latestRevisionId,
|
|
latestRevisionNumber: documents.latestRevisionNumber,
|
|
})
|
|
.from(issueDocuments)
|
|
.innerJoin(documents, eq(issueDocuments.documentId, documents.id))
|
|
.where(and(
|
|
eq(issueDocuments.companyId, input.companyId),
|
|
eq(issueDocuments.issueId, input.issueId),
|
|
eq(issueDocuments.key, "plan"),
|
|
eq(documents.companyId, input.companyId),
|
|
))
|
|
.then((rows) => rows[0] ?? null);
|
|
if (!planDocument) return null;
|
|
|
|
const [{ count: openThreadCount }] = await input.db
|
|
.select({ count: sql<number>`count(*)::int` })
|
|
.from(documentAnnotationThreads)
|
|
.where(and(
|
|
eq(documentAnnotationThreads.companyId, input.companyId),
|
|
eq(documentAnnotationThreads.issueId, input.issueId),
|
|
eq(documentAnnotationThreads.documentId, planDocument.documentId),
|
|
eq(documentAnnotationThreads.documentKey, "plan"),
|
|
eq(documentAnnotationThreads.status, "open"),
|
|
));
|
|
|
|
const threadRows = await input.db
|
|
.select({
|
|
id: documentAnnotationThreads.id,
|
|
documentId: documentAnnotationThreads.documentId,
|
|
documentKey: documentAnnotationThreads.documentKey,
|
|
status: documentAnnotationThreads.status,
|
|
revisionId: documentAnnotationThreads.currentRevisionId,
|
|
revisionNumber: documentAnnotationThreads.currentRevisionNumber,
|
|
anchorState: documentAnnotationThreads.anchorState,
|
|
anchorConfidence: documentAnnotationThreads.anchorConfidence,
|
|
selectedText: documentAnnotationThreads.selectedText,
|
|
prefixText: documentAnnotationThreads.prefixText,
|
|
suffixText: documentAnnotationThreads.suffixText,
|
|
createdByAgentId: documentAnnotationThreads.createdByAgentId,
|
|
createdByUserId: documentAnnotationThreads.createdByUserId,
|
|
createdAt: documentAnnotationThreads.createdAt,
|
|
updatedAt: documentAnnotationThreads.updatedAt,
|
|
})
|
|
.from(documentAnnotationThreads)
|
|
.where(and(
|
|
eq(documentAnnotationThreads.companyId, input.companyId),
|
|
eq(documentAnnotationThreads.issueId, input.issueId),
|
|
eq(documentAnnotationThreads.documentId, planDocument.documentId),
|
|
eq(documentAnnotationThreads.documentKey, "plan"),
|
|
eq(documentAnnotationThreads.status, "open"),
|
|
))
|
|
.orderBy(desc(documentAnnotationThreads.updatedAt), desc(documentAnnotationThreads.id))
|
|
.limit(PLAN_REVIEW_CONTEXT_LIMITS.maxThreads);
|
|
|
|
const threadIds = threadRows.map((thread) => thread.id);
|
|
const commentRows = threadIds.length === 0
|
|
? []
|
|
: await input.db
|
|
.select({
|
|
id: documentAnnotationComments.id,
|
|
threadId: documentAnnotationComments.threadId,
|
|
body: documentAnnotationComments.body,
|
|
authorType: documentAnnotationComments.authorType,
|
|
authorAgentId: documentAnnotationComments.authorAgentId,
|
|
authorUserId: documentAnnotationComments.authorUserId,
|
|
createdAt: documentAnnotationComments.createdAt,
|
|
updatedAt: documentAnnotationComments.updatedAt,
|
|
})
|
|
.from(documentAnnotationComments)
|
|
.where(and(
|
|
eq(documentAnnotationComments.companyId, input.companyId),
|
|
eq(documentAnnotationComments.issueId, input.issueId),
|
|
eq(documentAnnotationComments.documentId, planDocument.documentId),
|
|
inArray(documentAnnotationComments.threadId, threadIds),
|
|
))
|
|
.orderBy(asc(documentAnnotationComments.createdAt), asc(documentAnnotationComments.id))
|
|
.limit(PLAN_REVIEW_CONTEXT_LIMITS.maxComments);
|
|
|
|
const [{ count: commentCount }] = await input.db
|
|
.select({ count: sql<number>`count(*)::int` })
|
|
.from(documentAnnotationComments)
|
|
.innerJoin(documentAnnotationThreads, eq(documentAnnotationComments.threadId, documentAnnotationThreads.id))
|
|
.where(and(
|
|
eq(documentAnnotationComments.companyId, input.companyId),
|
|
eq(documentAnnotationComments.issueId, input.issueId),
|
|
eq(documentAnnotationComments.documentId, planDocument.documentId),
|
|
eq(documentAnnotationThreads.companyId, input.companyId),
|
|
eq(documentAnnotationThreads.issueId, input.issueId),
|
|
eq(documentAnnotationThreads.documentId, planDocument.documentId),
|
|
eq(documentAnnotationThreads.documentKey, "plan"),
|
|
eq(documentAnnotationThreads.status, "open"),
|
|
));
|
|
|
|
const commentsByThread = new Map<string, typeof commentRows>();
|
|
for (const comment of commentRows) {
|
|
const existing = commentsByThread.get(comment.threadId) ?? [];
|
|
existing.push(comment);
|
|
commentsByThread.set(comment.threadId, existing);
|
|
}
|
|
|
|
let remainingBodyChars = PLAN_REVIEW_CONTEXT_LIMITS.maxTotalBodyChars;
|
|
let includedCommentCount = 0;
|
|
let truncated = openThreadCount > threadRows.length;
|
|
const threads = threadRows.map((thread) => {
|
|
const selectedText = truncateText(thread.selectedText, PLAN_REVIEW_CONTEXT_LIMITS.maxAnchorTextChars);
|
|
const prefixText = truncateText(thread.prefixText, PLAN_REVIEW_CONTEXT_LIMITS.maxAnchorTextChars);
|
|
const suffixText = truncateText(thread.suffixText, PLAN_REVIEW_CONTEXT_LIMITS.maxAnchorTextChars);
|
|
if (selectedText.truncated || prefixText.truncated || suffixText.truncated) truncated = true;
|
|
|
|
const threadComments = commentsByThread.get(thread.id) ?? [];
|
|
const comments = [];
|
|
for (const comment of threadComments) {
|
|
if (includedCommentCount >= PLAN_REVIEW_CONTEXT_LIMITS.maxComments || remainingBodyChars <= 0) {
|
|
truncated = true;
|
|
break;
|
|
}
|
|
const allowedChars = Math.min(PLAN_REVIEW_CONTEXT_LIMITS.maxBodyChars, remainingBodyChars);
|
|
const body = truncateText(comment.body, allowedChars);
|
|
if (body.truncated) truncated = true;
|
|
remainingBodyChars -= body.text.length;
|
|
includedCommentCount += 1;
|
|
comments.push({
|
|
id: comment.id,
|
|
threadId: comment.threadId,
|
|
body: body.text,
|
|
bodyTruncated: body.truncated,
|
|
author: authorFrom(comment),
|
|
createdAt: comment.createdAt.toISOString(),
|
|
updatedAt: comment.updatedAt.toISOString(),
|
|
});
|
|
}
|
|
|
|
const commentsTruncated = comments.length < threadComments.length;
|
|
if (commentsTruncated) truncated = true;
|
|
|
|
return {
|
|
id: thread.id,
|
|
documentKey: thread.documentKey,
|
|
documentId: thread.documentId,
|
|
status: thread.status,
|
|
revisionId: thread.revisionId,
|
|
revisionNumber: thread.revisionNumber,
|
|
anchorState: thread.anchorState,
|
|
anchorConfidence: thread.anchorConfidence,
|
|
selectedText: selectedText.text,
|
|
selectedTextTruncated: selectedText.truncated,
|
|
prefixText: prefixText.text,
|
|
prefixTextTruncated: prefixText.truncated,
|
|
suffixText: suffixText.text,
|
|
suffixTextTruncated: suffixText.truncated,
|
|
author: authorFrom({ authorAgentId: thread.createdByAgentId, authorUserId: thread.createdByUserId }),
|
|
commentCount: threadComments.length,
|
|
comments,
|
|
commentsTruncated,
|
|
createdAt: thread.createdAt.toISOString(),
|
|
updatedAt: thread.updatedAt.toISOString(),
|
|
};
|
|
});
|
|
|
|
const omittedCommentCount = Math.max(0, commentCount - includedCommentCount);
|
|
if (omittedCommentCount > 0) truncated = true;
|
|
|
|
return {
|
|
documentKey: "plan",
|
|
issueId: input.issueId,
|
|
latestRevisionId: planDocument.latestRevisionId,
|
|
latestRevisionNumber: planDocument.latestRevisionNumber,
|
|
threads,
|
|
interaction,
|
|
totals: {
|
|
openThreadCount,
|
|
includedThreadCount: threads.length,
|
|
omittedThreadCount: Math.max(0, openThreadCount - threads.length),
|
|
commentCount,
|
|
includedCommentCount,
|
|
omittedCommentCount,
|
|
},
|
|
limits: { ...PLAN_REVIEW_CONTEXT_LIMITS },
|
|
truncated,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Builds the non-plan half of issue-document review context. Plan context stays
|
|
* on its legacy builder and payload field so plan-only wakes remain byte-for-byte
|
|
* compatible. Budgets are shared across documents, while each document also
|
|
* observes the legacy per-document limits.
|
|
*/
|
|
export async function buildDocumentReviewContext(
|
|
input: BuildDocumentReviewContextInput,
|
|
): Promise<DocumentReviewContext | null> {
|
|
if (input.includeForIssueComment !== true && input.includeForAnnotationDelta !== true) return null;
|
|
|
|
const documentRows = await input.db
|
|
.select({
|
|
documentId: documents.id,
|
|
documentKey: issueDocuments.key,
|
|
title: documents.title,
|
|
latestRevisionId: documents.latestRevisionId,
|
|
latestRevisionNumber: documents.latestRevisionNumber,
|
|
updatedAt: issueDocuments.updatedAt,
|
|
})
|
|
.from(issueDocuments)
|
|
.innerJoin(documents, eq(issueDocuments.documentId, documents.id))
|
|
.where(and(
|
|
eq(issueDocuments.companyId, input.companyId),
|
|
eq(issueDocuments.issueId, input.issueId),
|
|
eq(documents.companyId, input.companyId),
|
|
sql`${issueDocuments.key} <> 'plan'`,
|
|
))
|
|
.orderBy(desc(issueDocuments.updatedAt), desc(issueDocuments.id));
|
|
if (documentRows.length === 0) return null;
|
|
|
|
let remainingThreads = PLAN_REVIEW_CONTEXT_LIMITS.maxThreads;
|
|
let remainingComments = PLAN_REVIEW_CONTEXT_LIMITS.maxComments;
|
|
let remainingBodyChars = PLAN_REVIEW_CONTEXT_LIMITS.maxTotalBodyChars;
|
|
let totalOpenThreads = 0;
|
|
let totalComments = 0;
|
|
let includedThreads = 0;
|
|
let includedComments = 0;
|
|
let truncated = false;
|
|
const groupedDocuments: DocumentReviewContextDocument[] = [];
|
|
|
|
for (const document of documentRows) {
|
|
const [{ count: openThreadCount }] = await input.db
|
|
.select({ count: sql<number>`count(*)::int` })
|
|
.from(documentAnnotationThreads)
|
|
.where(and(
|
|
eq(documentAnnotationThreads.companyId, input.companyId),
|
|
eq(documentAnnotationThreads.issueId, input.issueId),
|
|
eq(documentAnnotationThreads.documentId, document.documentId),
|
|
eq(documentAnnotationThreads.documentKey, document.documentKey),
|
|
eq(documentAnnotationThreads.status, "open"),
|
|
));
|
|
if (openThreadCount === 0) continue;
|
|
|
|
const perDocumentThreadLimit = Math.min(PLAN_REVIEW_CONTEXT_LIMITS.maxThreads, remainingThreads);
|
|
const threadRows = perDocumentThreadLimit === 0 ? [] : await input.db
|
|
.select({
|
|
id: documentAnnotationThreads.id,
|
|
documentId: documentAnnotationThreads.documentId,
|
|
documentKey: documentAnnotationThreads.documentKey,
|
|
status: documentAnnotationThreads.status,
|
|
revisionId: documentAnnotationThreads.currentRevisionId,
|
|
revisionNumber: documentAnnotationThreads.currentRevisionNumber,
|
|
anchorState: documentAnnotationThreads.anchorState,
|
|
anchorConfidence: documentAnnotationThreads.anchorConfidence,
|
|
selectedText: documentAnnotationThreads.selectedText,
|
|
prefixText: documentAnnotationThreads.prefixText,
|
|
suffixText: documentAnnotationThreads.suffixText,
|
|
createdByAgentId: documentAnnotationThreads.createdByAgentId,
|
|
createdByUserId: documentAnnotationThreads.createdByUserId,
|
|
createdAt: documentAnnotationThreads.createdAt,
|
|
updatedAt: documentAnnotationThreads.updatedAt,
|
|
})
|
|
.from(documentAnnotationThreads)
|
|
.where(and(
|
|
eq(documentAnnotationThreads.companyId, input.companyId),
|
|
eq(documentAnnotationThreads.issueId, input.issueId),
|
|
eq(documentAnnotationThreads.documentId, document.documentId),
|
|
eq(documentAnnotationThreads.documentKey, document.documentKey),
|
|
eq(documentAnnotationThreads.status, "open"),
|
|
))
|
|
.orderBy(desc(documentAnnotationThreads.updatedAt), desc(documentAnnotationThreads.id))
|
|
.limit(perDocumentThreadLimit);
|
|
|
|
const threadIds = threadRows.map((thread) => thread.id);
|
|
const perDocumentCommentLimit = Math.min(PLAN_REVIEW_CONTEXT_LIMITS.maxComments, remainingComments);
|
|
const commentRows = threadIds.length === 0 || perDocumentCommentLimit === 0 ? [] : await input.db
|
|
.select({
|
|
id: documentAnnotationComments.id,
|
|
threadId: documentAnnotationComments.threadId,
|
|
body: documentAnnotationComments.body,
|
|
authorType: documentAnnotationComments.authorType,
|
|
authorAgentId: documentAnnotationComments.authorAgentId,
|
|
authorUserId: documentAnnotationComments.authorUserId,
|
|
createdAt: documentAnnotationComments.createdAt,
|
|
updatedAt: documentAnnotationComments.updatedAt,
|
|
})
|
|
.from(documentAnnotationComments)
|
|
.where(and(
|
|
eq(documentAnnotationComments.companyId, input.companyId),
|
|
eq(documentAnnotationComments.issueId, input.issueId),
|
|
eq(documentAnnotationComments.documentId, document.documentId),
|
|
inArray(documentAnnotationComments.threadId, threadIds),
|
|
))
|
|
.orderBy(asc(documentAnnotationComments.createdAt), asc(documentAnnotationComments.id))
|
|
.limit(perDocumentCommentLimit);
|
|
|
|
const [{ count: commentCount }] = await input.db
|
|
.select({ count: sql<number>`count(*)::int` })
|
|
.from(documentAnnotationComments)
|
|
.innerJoin(documentAnnotationThreads, eq(documentAnnotationComments.threadId, documentAnnotationThreads.id))
|
|
.where(and(
|
|
eq(documentAnnotationComments.companyId, input.companyId),
|
|
eq(documentAnnotationComments.issueId, input.issueId),
|
|
eq(documentAnnotationComments.documentId, document.documentId),
|
|
eq(documentAnnotationThreads.companyId, input.companyId),
|
|
eq(documentAnnotationThreads.issueId, input.issueId),
|
|
eq(documentAnnotationThreads.documentId, document.documentId),
|
|
eq(documentAnnotationThreads.documentKey, document.documentKey),
|
|
eq(documentAnnotationThreads.status, "open"),
|
|
));
|
|
|
|
const commentsByThread = new Map<string, typeof commentRows>();
|
|
for (const comment of commentRows) {
|
|
const current = commentsByThread.get(comment.threadId) ?? [];
|
|
current.push(comment);
|
|
commentsByThread.set(comment.threadId, current);
|
|
}
|
|
|
|
let documentIncludedComments = 0;
|
|
let documentTruncated = openThreadCount > threadRows.length;
|
|
const threads = threadRows.map((thread) => {
|
|
const selectedText = truncateText(thread.selectedText, PLAN_REVIEW_CONTEXT_LIMITS.maxAnchorTextChars);
|
|
const prefixText = truncateText(thread.prefixText, PLAN_REVIEW_CONTEXT_LIMITS.maxAnchorTextChars);
|
|
const suffixText = truncateText(thread.suffixText, PLAN_REVIEW_CONTEXT_LIMITS.maxAnchorTextChars);
|
|
if (selectedText.truncated || prefixText.truncated || suffixText.truncated) documentTruncated = true;
|
|
const sourceComments = commentsByThread.get(thread.id) ?? [];
|
|
const comments = [];
|
|
for (const comment of sourceComments) {
|
|
if (remainingComments <= 0 || remainingBodyChars <= 0) {
|
|
documentTruncated = true;
|
|
break;
|
|
}
|
|
const body = truncateText(
|
|
comment.body,
|
|
Math.min(PLAN_REVIEW_CONTEXT_LIMITS.maxBodyChars, remainingBodyChars),
|
|
);
|
|
if (body.truncated) documentTruncated = true;
|
|
remainingBodyChars -= body.text.length;
|
|
remainingComments -= 1;
|
|
documentIncludedComments += 1;
|
|
includedComments += 1;
|
|
comments.push({
|
|
id: comment.id,
|
|
threadId: comment.threadId,
|
|
body: body.text,
|
|
bodyTruncated: body.truncated,
|
|
author: authorFrom(comment),
|
|
createdAt: comment.createdAt.toISOString(),
|
|
updatedAt: comment.updatedAt.toISOString(),
|
|
});
|
|
}
|
|
const commentsTruncated = comments.length < sourceComments.length;
|
|
if (commentsTruncated) documentTruncated = true;
|
|
return {
|
|
id: thread.id,
|
|
documentKey: thread.documentKey,
|
|
documentId: thread.documentId,
|
|
status: thread.status,
|
|
revisionId: thread.revisionId,
|
|
revisionNumber: thread.revisionNumber,
|
|
anchorState: thread.anchorState,
|
|
anchorConfidence: thread.anchorConfidence,
|
|
selectedText: selectedText.text,
|
|
selectedTextTruncated: selectedText.truncated,
|
|
prefixText: prefixText.text,
|
|
prefixTextTruncated: prefixText.truncated,
|
|
suffixText: suffixText.text,
|
|
suffixTextTruncated: suffixText.truncated,
|
|
author: authorFrom({ authorAgentId: thread.createdByAgentId, authorUserId: thread.createdByUserId }),
|
|
commentCount: sourceComments.length,
|
|
comments,
|
|
commentsTruncated,
|
|
createdAt: thread.createdAt.toISOString(),
|
|
updatedAt: thread.updatedAt.toISOString(),
|
|
};
|
|
});
|
|
|
|
remainingThreads -= threads.length;
|
|
totalOpenThreads += openThreadCount;
|
|
totalComments += commentCount;
|
|
includedThreads += threads.length;
|
|
if (commentCount > documentIncludedComments) documentTruncated = true;
|
|
if (documentTruncated) truncated = true;
|
|
groupedDocuments.push({
|
|
documentKey: document.documentKey,
|
|
documentId: document.documentId,
|
|
title: document.title,
|
|
latestRevisionId: document.latestRevisionId,
|
|
latestRevisionNumber: document.latestRevisionNumber,
|
|
threads,
|
|
totals: {
|
|
openThreadCount,
|
|
includedThreadCount: threads.length,
|
|
omittedThreadCount: Math.max(0, openThreadCount - threads.length),
|
|
commentCount,
|
|
includedCommentCount: documentIncludedComments,
|
|
omittedCommentCount: Math.max(0, commentCount - documentIncludedComments),
|
|
},
|
|
truncated: documentTruncated,
|
|
});
|
|
}
|
|
|
|
if (groupedDocuments.length === 0) return null;
|
|
return {
|
|
issueId: input.issueId,
|
|
documents: groupedDocuments,
|
|
totals: {
|
|
openThreadCount: totalOpenThreads,
|
|
includedThreadCount: includedThreads,
|
|
omittedThreadCount: Math.max(0, totalOpenThreads - includedThreads),
|
|
commentCount: totalComments,
|
|
includedCommentCount: includedComments,
|
|
omittedCommentCount: Math.max(0, totalComments - includedComments),
|
|
},
|
|
limits: { ...PLAN_REVIEW_CONTEXT_LIMITS },
|
|
truncated,
|
|
};
|
|
}
|