mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-18 15:39:47 +02:00
feat: add attention queue and Decisions surface (#9380)
## Thinking Path > - Paperclip is the control plane for autonomous AI companies, where operators need a reliable way to find and act on work awaiting their input. > - The attention and issue-thread interaction subsystems expose those decision points across server APIs and the board UI. > - The previous navigation and interaction presentation left these actions fragmented and did not offer a controlled rollout for the Decisions surface. > - This branch adds the attention feed, richer interaction cards, grouping, dismiss/snooze behavior, and a gated Decisions sidebar entry. > - It also keeps experimental settings and API contracts synchronized, with an idempotent migration for the new dismissal state. > - This pull request delivers the complete, tested attention/Decisions experience as one reviewable unit. ## Linked Issues or Issue Description - Adds an operator-focused attention queue and Decisions experience: grouped decision cards, semantic interaction actions, dismiss/snooze handling, resilient interaction states, and an experimental flag to control the Decisions navigation entry. ## Feature Context ### Problem or Motivation Operators currently have to hunt across approvals, interactions, failed runs, and budget alerts to find decisions that need their action. ### Proposed Solution Provide a gated Decisions attention queue that groups actionable items, supports direct resolution, and preserves operator control through dismiss and snooze actions. ### Alternatives Considered Keep separate, source-specific views only; this leaves cross-cutting operator decisions fragmented and harder to prioritize. ### Roadmap Alignment This improves the V1 control-plane operator workflow by making pending governed actions discoverable in one company-scoped surface. ## What Changed - Added server attention-feed services, routes, interaction handling, dismiss/snooze support, and an idempotent `0145` inbox-dismissal migration. - Added shared attention, inbox-dismissal, and experimental-settings contracts. - Added Decisions/attention UI, interaction-card states, sidebar badge/navigation integration, grouping, keyboard support, and Storybook coverage. - Added tests for attention behavior, thread interactions, settings normalization, dismissals, and API behavior. - Removed generated screenshots from the final PR diff and rebased the branch onto current `master`. ## Verification - `pnpm check:token-gates` — passed. - `pnpm exec vitest run packages/shared/src/issue-thread-interactions.test.ts server/src/__tests__/attention-service.test.ts server/src/__tests__/inbox-dismissals.test.ts server/src/__tests__/issue-thread-interactions-service.test.ts server/src/__tests__/issue-thread-interaction-routes.test.ts ui/src/lib/attention.test.ts ui/src/components/AttentionQueueRow.test.tsx ui/src/components/IssueThreadInteractionCard.test.tsx ui/src/pages/InstanceExperimentalSettings.test.tsx` — passed: 158 tests across 9 focused files. - GitHub Actions for `ad636f560`: build and typecheck/release-registry have passed; remaining general-server and Greptile checks are in progress. ## Risks - Moderate: this is a cross-layer attention/interaction feature with a new migration and navigation behavior. - The `enableDecisions` experimental setting defaults to off, limiting rollout impact. - Existing dismissal data is backfilled to `dismiss`; the migration is idempotent and uses guarded constraint creation. > ROADMAP.md was checked; no duplicate planned core feature was identified. Related open pull requests were searched before opening this PR. ## Model Used - OpenAI GPT-5.5 via Codex CLI, with tool use and local code execution. Context-window size unavailable in this environment. ## 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 public PR branch name describes the change and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally; focused tests pass and the remaining unrelated AWS test failure is documented above - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
70 files changed
+9067
-90
No files matched your search
@@ -0,0 +1,961 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import {
|
||||
activityLog,
|
||||
agents,
|
||||
approvals,
|
||||
assets,
|
||||
budgetIncidents,
|
||||
budgetPolicies,
|
||||
companies,
|
||||
createDb,
|
||||
documents,
|
||||
heartbeatRunEvents,
|
||||
heartbeatRuns,
|
||||
inboxDismissals,
|
||||
invites,
|
||||
issueApprovals,
|
||||
issueAttachments,
|
||||
issueDocuments,
|
||||
issueRecoveryActions,
|
||||
issueRelations,
|
||||
issueThreadInteractions,
|
||||
issues,
|
||||
joinRequests,
|
||||
projects,
|
||||
projectWorkspaces,
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "./helpers/embedded-postgres.js";
|
||||
import { errorHandler } from "../middleware/index.js";
|
||||
import { attentionRoutes } from "../routes/attention.js";
|
||||
import { attentionService } from "../services/attention.js";
|
||||
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
|
||||
if (!embeddedPostgresSupport.supported) {
|
||||
console.warn(
|
||||
`Skipping embedded Postgres attention service tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
|
||||
);
|
||||
}
|
||||
|
||||
describeEmbeddedPostgres("attention service", () => {
|
||||
let db!: ReturnType<typeof createDb>;
|
||||
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
|
||||
beforeAll(async () => {
|
||||
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-attention-service-");
|
||||
db = createDb(tempDb.connectionString);
|
||||
}, 30_000);
|
||||
|
||||
afterEach(async () => {
|
||||
await db.delete(inboxDismissals);
|
||||
await db.delete(issueThreadInteractions);
|
||||
await db.delete(issueApprovals);
|
||||
await db.delete(issueAttachments);
|
||||
await db.delete(issueDocuments);
|
||||
await db.delete(heartbeatRunEvents);
|
||||
await db.delete(heartbeatRuns);
|
||||
await db.delete(budgetIncidents);
|
||||
await db.delete(budgetPolicies);
|
||||
await db.delete(joinRequests);
|
||||
await db.delete(invites);
|
||||
await db.delete(issueRecoveryActions);
|
||||
await db.delete(issueRelations);
|
||||
await db.delete(activityLog);
|
||||
await db.delete(approvals);
|
||||
await db.delete(issues);
|
||||
await db.delete(assets);
|
||||
await db.delete(documents);
|
||||
await db.delete(projectWorkspaces);
|
||||
await db.delete(projects);
|
||||
await db.delete(agents);
|
||||
await db.delete(companies);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await tempDb?.cleanup();
|
||||
});
|
||||
|
||||
async function seedCompany(prefix = "ATN") {
|
||||
const companyId = randomUUID();
|
||||
const workerId = randomUUID();
|
||||
const reviewerId = randomUUID();
|
||||
const errorAgentId = randomUUID();
|
||||
|
||||
await db.insert(companies).values({
|
||||
id: companyId,
|
||||
name: `${prefix} Co`,
|
||||
issuePrefix: prefix,
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
});
|
||||
await db.insert(agents).values([
|
||||
{
|
||||
id: workerId,
|
||||
companyId,
|
||||
name: "Worker",
|
||||
role: "engineer",
|
||||
status: "idle",
|
||||
adapterType: "codex_local",
|
||||
adapterConfig: {},
|
||||
runtimeConfig: {},
|
||||
permissions: {},
|
||||
},
|
||||
{
|
||||
id: reviewerId,
|
||||
companyId,
|
||||
name: "Reviewer",
|
||||
role: "qa",
|
||||
status: "idle",
|
||||
adapterType: "codex_local",
|
||||
adapterConfig: {},
|
||||
runtimeConfig: {},
|
||||
permissions: {},
|
||||
},
|
||||
{
|
||||
id: errorAgentId,
|
||||
companyId,
|
||||
name: "Broken Agent",
|
||||
role: "engineer",
|
||||
status: "error",
|
||||
errorReason: "adapter config missing",
|
||||
adapterType: "codex_local",
|
||||
adapterConfig: {},
|
||||
runtimeConfig: {},
|
||||
permissions: {},
|
||||
},
|
||||
]);
|
||||
|
||||
return { companyId, workerId, reviewerId, errorAgentId, prefix };
|
||||
}
|
||||
|
||||
async function insertIssue(input: {
|
||||
companyId: string;
|
||||
id?: string;
|
||||
identifier: string;
|
||||
title: string;
|
||||
status: string;
|
||||
priority?: string;
|
||||
parentId?: string | null;
|
||||
assigneeAgentId?: string | null;
|
||||
assigneeUserId?: string | null;
|
||||
originKind?: string;
|
||||
originId?: string | null;
|
||||
originFingerprint?: string;
|
||||
projectId?: string | null;
|
||||
projectWorkspaceId?: string | null;
|
||||
executionState?: Record<string, unknown> | null;
|
||||
updatedAt?: Date;
|
||||
createdAt?: Date;
|
||||
}) {
|
||||
const id = input.id ?? randomUUID();
|
||||
await db.insert(issues).values({
|
||||
id,
|
||||
companyId: input.companyId,
|
||||
identifier: input.identifier,
|
||||
title: input.title,
|
||||
status: input.status,
|
||||
priority: input.priority ?? "medium",
|
||||
parentId: input.parentId ?? null,
|
||||
projectId: input.projectId ?? null,
|
||||
projectWorkspaceId: input.projectWorkspaceId ?? null,
|
||||
assigneeAgentId: input.assigneeAgentId ?? null,
|
||||
assigneeUserId: input.assigneeUserId ?? null,
|
||||
originKind: input.originKind ?? "manual",
|
||||
originId: input.originId ?? null,
|
||||
originFingerprint: input.originFingerprint ?? "default",
|
||||
executionState: input.executionState ?? null,
|
||||
createdAt: input.createdAt,
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
return id;
|
||||
}
|
||||
|
||||
function pendingUserExecutionState(userId = "board-user") {
|
||||
return {
|
||||
status: "pending",
|
||||
currentStageId: null,
|
||||
currentStageIndex: null,
|
||||
currentStageType: "review",
|
||||
currentParticipant: { type: "user", userId },
|
||||
returnAssignee: null,
|
||||
reviewRequest: null,
|
||||
completedStageIds: [],
|
||||
lastDecisionId: null,
|
||||
lastDecisionOutcome: null,
|
||||
monitor: null,
|
||||
};
|
||||
}
|
||||
|
||||
function pendingAgentExecutionState(agentId: string) {
|
||||
return {
|
||||
...pendingUserExecutionState(),
|
||||
currentParticipant: { type: "agent", agentId },
|
||||
};
|
||||
}
|
||||
|
||||
it("returns ranked decision-only items for every active source and excludes non-human or transient rows", async () => {
|
||||
const { companyId, workerId, reviewerId } = await seedCompany("ATN");
|
||||
const baseTime = new Date("2026-07-09T12:00:00.000Z");
|
||||
const interactionIssueId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATN-1",
|
||||
title: "Needs interaction",
|
||||
status: "in_progress",
|
||||
assigneeAgentId: workerId,
|
||||
updatedAt: baseTime,
|
||||
});
|
||||
const recoverySourceIssueId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATN-2",
|
||||
title: "Needs recovery",
|
||||
status: "in_progress",
|
||||
assigneeAgentId: workerId,
|
||||
updatedAt: baseTime,
|
||||
});
|
||||
const agentRecoverySourceIssueId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATN-21",
|
||||
title: "Agent-owned recovery source",
|
||||
status: "in_progress",
|
||||
assigneeAgentId: workerId,
|
||||
updatedAt: baseTime,
|
||||
});
|
||||
const productivitySourceIssueId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATN-3",
|
||||
title: "Needs productivity review source",
|
||||
status: "in_progress",
|
||||
assigneeAgentId: workerId,
|
||||
updatedAt: baseTime,
|
||||
});
|
||||
const agentProductivitySourceIssueId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATN-31",
|
||||
title: "Agent productivity review source",
|
||||
status: "in_progress",
|
||||
assigneeAgentId: workerId,
|
||||
updatedAt: baseTime,
|
||||
});
|
||||
const blockerParentId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATN-4",
|
||||
title: "Blocked parent",
|
||||
status: "blocked",
|
||||
updatedAt: new Date("2026-07-09T12:04:00.000Z"),
|
||||
});
|
||||
const blockerLeafId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATN-5",
|
||||
title: "Stalled review blocker",
|
||||
status: "in_review",
|
||||
assigneeAgentId: reviewerId,
|
||||
updatedAt: new Date("2026-07-09T12:05:00.000Z"),
|
||||
});
|
||||
await db.insert(issueRelations).values({
|
||||
companyId,
|
||||
issueId: blockerLeafId,
|
||||
relatedIssueId: blockerParentId,
|
||||
type: "blocks",
|
||||
});
|
||||
const reviewUserIssueId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATN-6",
|
||||
title: "Human review",
|
||||
status: "in_review",
|
||||
executionState: pendingUserExecutionState(),
|
||||
updatedAt: new Date("2026-07-09T12:06:00.000Z"),
|
||||
});
|
||||
await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATN-7",
|
||||
title: "Agent review excluded",
|
||||
status: "in_review",
|
||||
executionState: pendingAgentExecutionState(reviewerId),
|
||||
updatedAt: new Date("2026-07-09T12:07:00.000Z"),
|
||||
});
|
||||
|
||||
const pendingApprovalId = randomUUID();
|
||||
await db.insert(approvals).values([
|
||||
{
|
||||
id: pendingApprovalId,
|
||||
companyId,
|
||||
type: "hire_agent",
|
||||
status: "pending",
|
||||
payload: { title: "Hire Designer" },
|
||||
createdAt: new Date("2026-07-09T12:01:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:01:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: randomUUID(),
|
||||
companyId,
|
||||
type: "hire_agent",
|
||||
status: "revision_requested",
|
||||
payload: { title: "Revision requested" },
|
||||
createdAt: new Date("2026-07-09T12:02:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:02:00.000Z"),
|
||||
},
|
||||
]);
|
||||
|
||||
await db.insert(issueThreadInteractions).values([
|
||||
{
|
||||
id: randomUUID(),
|
||||
companyId,
|
||||
issueId: interactionIssueId,
|
||||
kind: "ask_user_questions",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
title: "Pick a launch date",
|
||||
payload: { version: 1, questions: [] },
|
||||
createdAt: new Date("2026-07-09T12:03:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:03:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: randomUUID(),
|
||||
companyId,
|
||||
issueId: interactionIssueId,
|
||||
kind: "request_confirmation",
|
||||
status: "accepted",
|
||||
continuationPolicy: "wake_assignee",
|
||||
title: "Already accepted",
|
||||
payload: { version: 1, prompt: "Already done" },
|
||||
createdAt: new Date("2026-07-09T12:03:30.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:03:30.000Z"),
|
||||
},
|
||||
]);
|
||||
|
||||
const inviteId = randomUUID();
|
||||
await db.insert(invites).values({
|
||||
id: inviteId,
|
||||
companyId,
|
||||
tokenHash: `hash-${inviteId}`,
|
||||
allowedJoinTypes: "both",
|
||||
expiresAt: new Date("2026-07-10T00:00:00.000Z"),
|
||||
});
|
||||
await db.insert(joinRequests).values({
|
||||
id: randomUUID(),
|
||||
inviteId,
|
||||
companyId,
|
||||
requestType: "human",
|
||||
status: "pending_approval",
|
||||
requestIp: "127.0.0.1",
|
||||
requestEmailSnapshot: "new@paperclip.test",
|
||||
createdAt: new Date("2026-07-09T12:04:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:04:00.000Z"),
|
||||
});
|
||||
|
||||
await db.insert(issueRecoveryActions).values([
|
||||
{
|
||||
id: randomUUID(),
|
||||
companyId,
|
||||
sourceIssueId: recoverySourceIssueId,
|
||||
kind: "missing_disposition",
|
||||
status: "escalated",
|
||||
ownerType: "board",
|
||||
ownerAgentId: null,
|
||||
ownerUserId: null,
|
||||
cause: "missing_disposition",
|
||||
fingerprint: "human-recovery",
|
||||
evidence: {},
|
||||
nextAction: "Choose the final disposition.",
|
||||
createdAt: new Date("2026-07-09T12:05:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:05:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: randomUUID(),
|
||||
companyId,
|
||||
sourceIssueId: agentRecoverySourceIssueId,
|
||||
kind: "stranded_assigned_issue",
|
||||
status: "active",
|
||||
ownerType: "agent",
|
||||
ownerAgentId: workerId,
|
||||
ownerUserId: null,
|
||||
cause: "stranded",
|
||||
fingerprint: "agent-recovery",
|
||||
evidence: {},
|
||||
nextAction: "Agent should self-heal.",
|
||||
createdAt: new Date("2026-07-09T12:05:30.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:05:30.000Z"),
|
||||
},
|
||||
]);
|
||||
|
||||
await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATN-8",
|
||||
title: "Human productivity review",
|
||||
status: "todo",
|
||||
priority: "high",
|
||||
parentId: productivitySourceIssueId,
|
||||
assigneeUserId: "board-user",
|
||||
originKind: "issue_productivity_review",
|
||||
originId: productivitySourceIssueId,
|
||||
originFingerprint: `productivity-review:${productivitySourceIssueId}`,
|
||||
updatedAt: new Date("2026-07-09T12:08:00.000Z"),
|
||||
});
|
||||
await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATN-9",
|
||||
title: "Agent productivity review excluded",
|
||||
status: "todo",
|
||||
priority: "high",
|
||||
parentId: agentProductivitySourceIssueId,
|
||||
assigneeAgentId: workerId,
|
||||
originKind: "issue_productivity_review",
|
||||
originId: agentProductivitySourceIssueId,
|
||||
originFingerprint: `productivity-review-agent:${agentProductivitySourceIssueId}`,
|
||||
updatedAt: new Date("2026-07-09T12:08:30.000Z"),
|
||||
});
|
||||
|
||||
const exhaustedRunId = randomUUID();
|
||||
const transientRunId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values([
|
||||
{
|
||||
id: exhaustedRunId,
|
||||
companyId,
|
||||
agentId: workerId,
|
||||
invocationSource: "automation",
|
||||
status: "failed",
|
||||
error: "adapter failed",
|
||||
errorCode: "adapter_failed",
|
||||
contextSnapshot: { issueId: reviewUserIssueId },
|
||||
scheduledRetryAttempt: 4,
|
||||
scheduledRetryReason: "transient_failure",
|
||||
createdAt: new Date("2026-07-09T12:09:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:09:00.000Z"),
|
||||
finishedAt: new Date("2026-07-09T12:09:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: transientRunId,
|
||||
companyId,
|
||||
agentId: reviewerId,
|
||||
invocationSource: "automation",
|
||||
status: "failed",
|
||||
error: "will retry",
|
||||
errorCode: "provider_quota",
|
||||
contextSnapshot: { issueId: interactionIssueId },
|
||||
createdAt: new Date("2026-07-09T12:09:30.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:09:30.000Z"),
|
||||
finishedAt: new Date("2026-07-09T12:09:30.000Z"),
|
||||
},
|
||||
]);
|
||||
await db.insert(heartbeatRunEvents).values({
|
||||
companyId,
|
||||
runId: exhaustedRunId,
|
||||
agentId: workerId,
|
||||
seq: 1,
|
||||
eventType: "lifecycle",
|
||||
message: "Bounded retry exhausted after 4 scheduled attempts; no further automatic retry will be queued",
|
||||
payload: { retryReason: "transient_failure", maxAttempts: 4 },
|
||||
createdAt: new Date("2026-07-09T12:09:01.000Z"),
|
||||
});
|
||||
|
||||
const softPolicy85Id = randomUUID();
|
||||
const softPolicy84Id = randomUUID();
|
||||
const hardPolicyId = randomUUID();
|
||||
await db.insert(budgetPolicies).values([
|
||||
{
|
||||
id: softPolicy85Id,
|
||||
companyId,
|
||||
scopeType: "company",
|
||||
scopeId: companyId,
|
||||
metric: "billed_cents",
|
||||
windowKind: "calendar_month_utc",
|
||||
amount: 100,
|
||||
},
|
||||
{
|
||||
id: softPolicy84Id,
|
||||
companyId,
|
||||
scopeType: "company",
|
||||
scopeId: companyId,
|
||||
metric: "billed_cents",
|
||||
windowKind: "lifetime",
|
||||
amount: 100,
|
||||
},
|
||||
{
|
||||
id: hardPolicyId,
|
||||
companyId,
|
||||
scopeType: "agent",
|
||||
scopeId: workerId,
|
||||
metric: "billed_cents",
|
||||
windowKind: "calendar_month_utc",
|
||||
amount: 100,
|
||||
},
|
||||
]);
|
||||
await db.insert(budgetIncidents).values([
|
||||
{
|
||||
companyId,
|
||||
policyId: softPolicy85Id,
|
||||
scopeType: "company",
|
||||
scopeId: companyId,
|
||||
metric: "billed_cents",
|
||||
windowKind: "calendar_month_utc",
|
||||
windowStart: new Date("2026-07-01T00:00:00.000Z"),
|
||||
windowEnd: new Date("2026-08-01T00:00:00.000Z"),
|
||||
thresholdType: "soft",
|
||||
amountLimit: 100,
|
||||
amountObserved: 85,
|
||||
status: "open",
|
||||
createdAt: new Date("2026-07-09T12:10:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:10:00.000Z"),
|
||||
},
|
||||
{
|
||||
companyId,
|
||||
policyId: softPolicy84Id,
|
||||
scopeType: "company",
|
||||
scopeId: companyId,
|
||||
metric: "billed_cents",
|
||||
windowKind: "lifetime",
|
||||
windowStart: new Date("1970-01-01T00:00:00.000Z"),
|
||||
windowEnd: new Date("9999-01-01T00:00:00.000Z"),
|
||||
thresholdType: "soft",
|
||||
amountLimit: 100,
|
||||
amountObserved: 84,
|
||||
status: "open",
|
||||
createdAt: new Date("2026-07-09T12:10:30.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:10:30.000Z"),
|
||||
},
|
||||
{
|
||||
companyId,
|
||||
policyId: hardPolicyId,
|
||||
scopeType: "agent",
|
||||
scopeId: workerId,
|
||||
metric: "billed_cents",
|
||||
windowKind: "calendar_month_utc",
|
||||
windowStart: new Date("2026-07-01T00:00:00.000Z"),
|
||||
windowEnd: new Date("2026-08-01T00:00:00.000Z"),
|
||||
thresholdType: "hard",
|
||||
amountLimit: 100,
|
||||
amountObserved: 100,
|
||||
status: "open",
|
||||
createdAt: new Date("2026-07-09T12:11:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:11:00.000Z"),
|
||||
},
|
||||
]);
|
||||
|
||||
const feed = await attentionService(db).list(companyId, { userId: "board-user" });
|
||||
|
||||
expect(feed.totalCount).toBe(11);
|
||||
expect(feed.countsBySourceKind).toMatchObject({
|
||||
approval: 1,
|
||||
issue_thread_interaction: 1,
|
||||
join_request: 1,
|
||||
recovery_action: 1,
|
||||
productivity_review: 1,
|
||||
blocker_attention: 1,
|
||||
review: 1,
|
||||
failed_run: 1,
|
||||
budget_alert: 2,
|
||||
agent_error_alert: 1,
|
||||
});
|
||||
expect(feed.items.map((item) => item.sourceKind)).toEqual(expect.arrayContaining([
|
||||
"approval",
|
||||
"issue_thread_interaction",
|
||||
"join_request",
|
||||
"recovery_action",
|
||||
"productivity_review",
|
||||
"blocker_attention",
|
||||
"review",
|
||||
"failed_run",
|
||||
"budget_alert",
|
||||
"agent_error_alert",
|
||||
]));
|
||||
for (const item of feed.items) {
|
||||
expect(item.dedupKey).toBeTruthy();
|
||||
expect(item.dismissalKey).toBe(`attention:${item.dedupKey}`);
|
||||
expect(item.whyNow).toBeTruthy();
|
||||
expect(item.entryRule).toBeTruthy();
|
||||
expect(item.exitRule).toBeTruthy();
|
||||
expect(item.decisionVerbs.length).toBeGreaterThan(0);
|
||||
expect(item.rank).toBeGreaterThan(0);
|
||||
}
|
||||
expect(feed.items.some((item) => item.subject.title === "Revision requested")).toBe(false);
|
||||
expect(feed.items.some((item) => item.subject.title === "Agent productivity review excluded")).toBe(false);
|
||||
expect(feed.items.some((item) => item.subject.title === "Agent review excluded")).toBe(false);
|
||||
expect(feed.items.some((item) =>
|
||||
item.sourceKind === "failed_run" && item.subject.metadata?.errorCode === "provider_quota"
|
||||
)).toBe(false);
|
||||
expect(feed.items.find((item) => item.sourceKind === "approval")?.detail).toMatchObject({
|
||||
kind: "approval",
|
||||
approvalType: "hire_agent",
|
||||
summaryExcerpt: "Hire Designer",
|
||||
});
|
||||
expect(feed.items.find((item) => item.sourceKind === "issue_thread_interaction")?.detail).toMatchObject({
|
||||
kind: "questions",
|
||||
questionCount: 0,
|
||||
});
|
||||
expect(feed.items.find((item) => item.sourceKind === "blocker_attention")?.detail).toMatchObject({
|
||||
kind: "blocker",
|
||||
blockingIssue: { identifier: "ATN-5", title: "Stalled review blocker" },
|
||||
});
|
||||
expect(feed.items.find((item) => item.sourceKind === "failed_run")?.detail).toMatchObject({
|
||||
kind: "failed_run",
|
||||
agentName: "Worker",
|
||||
failureReasonExcerpt: "adapter failed",
|
||||
});
|
||||
expect(feed.items.find((item) =>
|
||||
item.sourceKind === "budget_alert" && item.detail?.kind === "budget" && item.detail.observedPercent === 100
|
||||
)).toBeTruthy();
|
||||
expect(feed.items.find((item) => item.sourceKind === "agent_error_alert")?.detail).toMatchObject({
|
||||
kind: "agent_error",
|
||||
agentName: "Broken Agent",
|
||||
failureReasonExcerpt: "adapter config missing",
|
||||
});
|
||||
});
|
||||
|
||||
it("suppresses failed-run attention after a newer run for the same issue", async () => {
|
||||
const { companyId, workerId } = await seedCompany("ATN");
|
||||
const issueId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATN-1",
|
||||
title: "Recoverable task",
|
||||
status: "in_progress",
|
||||
});
|
||||
const failedRunId = randomUUID();
|
||||
const failedAt = new Date("2026-07-09T12:00:00.000Z");
|
||||
|
||||
await db.insert(heartbeatRuns).values([
|
||||
{
|
||||
id: failedRunId,
|
||||
companyId,
|
||||
agentId: workerId,
|
||||
invocationSource: "automation",
|
||||
status: "failed",
|
||||
error: "adapter failed",
|
||||
contextSnapshot: { issueId },
|
||||
createdAt: failedAt,
|
||||
updatedAt: failedAt,
|
||||
finishedAt: failedAt,
|
||||
},
|
||||
{
|
||||
id: randomUUID(),
|
||||
companyId,
|
||||
agentId: workerId,
|
||||
invocationSource: "automation",
|
||||
status: "succeeded",
|
||||
contextSnapshot: { issueId },
|
||||
createdAt: new Date("2026-07-09T12:01:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:01:00.000Z"),
|
||||
finishedAt: new Date("2026-07-09T12:01:00.000Z"),
|
||||
},
|
||||
]);
|
||||
await db.insert(heartbeatRunEvents).values({
|
||||
companyId,
|
||||
runId: failedRunId,
|
||||
agentId: workerId,
|
||||
seq: 1,
|
||||
eventType: "lifecycle",
|
||||
message: "Bounded retry exhausted after 4 scheduled attempts; no further automatic retry will be queued",
|
||||
createdAt: new Date("2026-07-09T12:00:01.000Z"),
|
||||
});
|
||||
|
||||
const feed = await attentionService(db).list(companyId, { userId: "board-user" });
|
||||
|
||||
expect(feed.items.filter((item) => item.sourceKind === "failed_run")).toEqual([]);
|
||||
});
|
||||
|
||||
it("enriches interaction details with project, workspace, plan metadata, and images", async () => {
|
||||
const { companyId, workerId } = await seedCompany("ATE");
|
||||
const projectId = randomUUID();
|
||||
const workspaceId = randomUUID();
|
||||
const issueId = randomUUID();
|
||||
const planDocumentId = randomUUID();
|
||||
const planRevisionId = randomUUID();
|
||||
const imageAssetIds = [randomUUID(), randomUUID(), randomUUID(), randomUUID()];
|
||||
|
||||
await db.insert(projects).values({
|
||||
id: projectId,
|
||||
companyId,
|
||||
name: "Attention Project",
|
||||
status: "in_progress",
|
||||
color: "#0f766e",
|
||||
icon: "rocket",
|
||||
});
|
||||
await db.insert(projectWorkspaces).values({
|
||||
id: workspaceId,
|
||||
companyId,
|
||||
projectId,
|
||||
name: "Preview workspace",
|
||||
sourceType: "local_path",
|
||||
isPrimary: true,
|
||||
});
|
||||
await insertIssue({
|
||||
id: issueId,
|
||||
companyId,
|
||||
identifier: "ATE-1",
|
||||
title: "Approve launch plan",
|
||||
status: "in_progress",
|
||||
assigneeAgentId: workerId,
|
||||
projectId,
|
||||
projectWorkspaceId: workspaceId,
|
||||
updatedAt: new Date("2026-07-09T12:00:00.000Z"),
|
||||
});
|
||||
await db.insert(documents).values({
|
||||
id: planDocumentId,
|
||||
companyId,
|
||||
title: "Launch Plan",
|
||||
format: "markdown",
|
||||
latestBody: "# Summary\n\nThis plan explains the launch checklist, rollout owner, QA gates, and risk controls for the homepage release.",
|
||||
latestRevisionId: planRevisionId,
|
||||
latestRevisionNumber: 2,
|
||||
});
|
||||
await db.insert(issueDocuments).values({
|
||||
companyId,
|
||||
issueId,
|
||||
documentId: planDocumentId,
|
||||
key: "plan",
|
||||
});
|
||||
await db.insert(assets).values([
|
||||
{ id: imageAssetIds[0], companyId, provider: "local_disk", objectKey: "img-1", contentType: "image/png", byteSize: 10, sha256: "a".repeat(64), originalFilename: "one.png" },
|
||||
{ id: imageAssetIds[1], companyId, provider: "local_disk", objectKey: "img-2", contentType: "image/jpeg", byteSize: 10, sha256: "b".repeat(64), originalFilename: "two.jpg" },
|
||||
{ id: imageAssetIds[2], companyId, provider: "local_disk", objectKey: "img-3", contentType: "image/gif", byteSize: 10, sha256: "c".repeat(64), originalFilename: "three.gif" },
|
||||
{ id: imageAssetIds[3], companyId, provider: "local_disk", objectKey: "img-4", contentType: "image/png", byteSize: 10, sha256: "d".repeat(64), originalFilename: "four.png" },
|
||||
]);
|
||||
await db.insert(issueAttachments).values(imageAssetIds.map((assetId, index) => ({
|
||||
companyId,
|
||||
issueId,
|
||||
assetId,
|
||||
createdAt: new Date(`2026-07-09T12:0${index}:30.000Z`),
|
||||
updatedAt: new Date(`2026-07-09T12:0${index}:30.000Z`),
|
||||
})));
|
||||
|
||||
const planInteractionId = randomUUID();
|
||||
const questionsInteractionId = randomUUID();
|
||||
const tasksInteractionId = randomUUID();
|
||||
const checkboxInteractionId = randomUUID();
|
||||
const verdictInteractionId = randomUUID();
|
||||
await db.insert(issueThreadInteractions).values([
|
||||
{
|
||||
id: planInteractionId,
|
||||
companyId,
|
||||
issueId,
|
||||
kind: "request_confirmation",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
title: "Approve the plan",
|
||||
payload: {
|
||||
version: 1,
|
||||
prompt: "Approve plan?",
|
||||
acceptLabel: "Approve plan",
|
||||
rejectLabel: "Request changes",
|
||||
target: { type: "issue_document", issueId, key: "plan", revisionId: planRevisionId },
|
||||
},
|
||||
createdAt: new Date("2026-07-09T12:01:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:01:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: questionsInteractionId,
|
||||
companyId,
|
||||
issueId,
|
||||
kind: "ask_user_questions",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
title: "Questions",
|
||||
payload: {
|
||||
version: 1,
|
||||
questions: [
|
||||
{ id: "q1", prompt: "Which auth provider should we use?", selectionMode: "single", options: [] },
|
||||
{ id: "q2", prompt: "Should we add a fallback?", selectionMode: "single", options: [] },
|
||||
],
|
||||
},
|
||||
createdAt: new Date("2026-07-09T12:02:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:02:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: tasksInteractionId,
|
||||
companyId,
|
||||
issueId,
|
||||
kind: "suggest_tasks",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
title: "Tasks",
|
||||
payload: { version: 1, tasks: [{ clientKey: "t1", title: "Build API" }, { clientKey: "t2", title: "Wire UI" }] },
|
||||
createdAt: new Date("2026-07-09T12:03:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:03:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: checkboxInteractionId,
|
||||
companyId,
|
||||
issueId,
|
||||
kind: "request_checkbox_confirmation",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
title: "Checkbox",
|
||||
payload: { version: 1, prompt: "Select rollout regions", options: [{ id: "us", label: "US" }, { id: "eu", label: "EU" }] },
|
||||
createdAt: new Date("2026-07-09T12:04:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:04:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: verdictInteractionId,
|
||||
companyId,
|
||||
issueId,
|
||||
kind: "request_item_verdicts",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
title: "Verdicts",
|
||||
payload: { version: 1, prompt: "Approve these screenshots", items: [{ id: "one", label: "One" }, { id: "two", label: "Two" }] },
|
||||
createdAt: new Date("2026-07-09T12:05:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:05:00.000Z"),
|
||||
},
|
||||
]);
|
||||
|
||||
const feed = await attentionService(db).list(companyId, { userId: "board-user" });
|
||||
const interactionItems = feed.items.filter((item) => item.sourceKind === "issue_thread_interaction");
|
||||
const detailsByKind = new Map(interactionItems.map((item) => [item.detail?.kind, item]));
|
||||
|
||||
const planItem = detailsByKind.get("plan_approval");
|
||||
expect(planItem?.subject.title).toBe("Plan approval - Approve launch plan");
|
||||
expect(planItem?.subject.metadata).toMatchObject({ isPlanTarget: true, targetDocumentKey: "plan" });
|
||||
expect(planItem?.decisionVerbs).toEqual([
|
||||
expect.objectContaining({ id: "accept", label: "Approve plan" }),
|
||||
expect.objectContaining({ id: "reject", label: "Request changes" }),
|
||||
]);
|
||||
expect(planItem?.project).toMatchObject({
|
||||
id: projectId,
|
||||
name: "Attention Project",
|
||||
color: "#0f766e",
|
||||
icon: "rocket",
|
||||
});
|
||||
expect(planItem?.project?.urlKey).toEqual(expect.any(String));
|
||||
expect(planItem?.workspace).toEqual({ id: workspaceId, name: "Preview workspace" });
|
||||
expect(planItem?.detail).toMatchObject({
|
||||
kind: "plan_approval",
|
||||
issueTitle: "Approve launch plan",
|
||||
planTitle: "Launch Plan",
|
||||
summaryExcerpt: expect.stringContaining("launch checklist"),
|
||||
images: imageAssetIds.slice(0, 3).map((assetId) => ({ assetId, alt: expect.any(String) })),
|
||||
});
|
||||
expect(detailsByKind.get("questions")?.detail).toMatchObject({
|
||||
kind: "questions",
|
||||
questionCount: 2,
|
||||
firstQuestionText: "Which auth provider should we use?",
|
||||
});
|
||||
expect(detailsByKind.get("suggested_tasks")?.detail).toMatchObject({
|
||||
kind: "suggested_tasks",
|
||||
taskCount: 2,
|
||||
firstTaskTitle: "Build API",
|
||||
});
|
||||
expect(detailsByKind.get("checkbox_confirmation")?.detail).toMatchObject({
|
||||
kind: "checkbox_confirmation",
|
||||
optionCount: 2,
|
||||
promptExcerpt: "Select rollout regions",
|
||||
});
|
||||
expect(detailsByKind.get("item_verdicts")?.detail).toMatchObject({
|
||||
kind: "item_verdicts",
|
||||
itemCount: 2,
|
||||
promptExcerpt: "Approve these screenshots",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses inbox_dismissals with attention-prefixed dedup keys and resurfaces newer activity", async () => {
|
||||
const { companyId } = await seedCompany("ATD");
|
||||
const approvalId = randomUUID();
|
||||
await db.insert(approvals).values({
|
||||
id: approvalId,
|
||||
companyId,
|
||||
type: "hire_agent",
|
||||
status: "pending",
|
||||
payload: { title: "Hire Writer" },
|
||||
createdAt: new Date("2026-07-09T12:00:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:00:00.000Z"),
|
||||
});
|
||||
await db.insert(inboxDismissals).values({
|
||||
companyId,
|
||||
userId: "board-user",
|
||||
itemKey: `attention:approval:${approvalId}`,
|
||||
dismissedAt: new Date("2026-07-09T13:00:00.000Z"),
|
||||
});
|
||||
|
||||
await expect(attentionService(db).list(companyId, { userId: "board-user" }))
|
||||
.resolves.toMatchObject({ totalCount: 1 }); // agent_error_alert from seed
|
||||
const includeDismissedFeed = await attentionService(db).list(companyId, { userId: "board-user", includeDismissed: true });
|
||||
expect(includeDismissedFeed.totalCount).toBe(2);
|
||||
expect(includeDismissedFeed.items.find((item) => item.dedupKey === `approval:${approvalId}`)?.dismissal)
|
||||
.toMatchObject({ kind: "dismiss", isActive: true, snoozedUntil: null });
|
||||
|
||||
await db
|
||||
.update(approvals)
|
||||
.set({ updatedAt: new Date("2026-07-09T14:00:00.000Z") })
|
||||
.where(eq(approvals.id, approvalId));
|
||||
|
||||
const feed = await attentionService(db).list(companyId, { userId: "board-user" });
|
||||
expect(feed.items.some((item) => item.dedupKey === `approval:${approvalId}`)).toBe(true);
|
||||
});
|
||||
|
||||
it("hides snoozed attention rows until snoozedUntil passes, then returns them unconditionally", async () => {
|
||||
const { companyId } = await seedCompany("ATS");
|
||||
const approvalId = randomUUID();
|
||||
await db.insert(approvals).values({
|
||||
id: approvalId,
|
||||
companyId,
|
||||
type: "hire_agent",
|
||||
status: "pending",
|
||||
payload: { title: "Hire Researcher" },
|
||||
createdAt: new Date("2026-07-09T12:00:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:00:00.000Z"),
|
||||
});
|
||||
await db.insert(inboxDismissals).values({
|
||||
companyId,
|
||||
userId: "board-user",
|
||||
itemKey: `attention:approval:${approvalId}`,
|
||||
kind: "snooze",
|
||||
dismissedAt: new Date("2099-01-01T00:00:00.000Z"),
|
||||
snoozedUntil: new Date("2099-01-02T00:00:00.000Z"),
|
||||
});
|
||||
|
||||
await expect(attentionService(db).list(companyId, { userId: "board-user" }))
|
||||
.resolves.toMatchObject({ totalCount: 1 }); // agent_error_alert from seed
|
||||
const hiddenFeed = await attentionService(db).list(companyId, { userId: "board-user", includeDismissed: true });
|
||||
expect(hiddenFeed.items.find((item) => item.dedupKey === `approval:${approvalId}`)?.dismissal)
|
||||
.toMatchObject({ kind: "snooze", isActive: true, snoozedUntil: "2099-01-02T00:00:00.000Z" });
|
||||
|
||||
await db
|
||||
.update(inboxDismissals)
|
||||
.set({ snoozedUntil: new Date("2020-01-01T00:00:00.000Z") })
|
||||
.where(eq(inboxDismissals.itemKey, `attention:approval:${approvalId}`));
|
||||
|
||||
const visibleFeed = await attentionService(db).list(companyId, { userId: "board-user" });
|
||||
const visibleApproval = visibleFeed.items.find((item) => item.dedupKey === `approval:${approvalId}`);
|
||||
expect(visibleApproval?.dismissal).toMatchObject({ kind: "snooze", isActive: false });
|
||||
expect(visibleApproval).toBeTruthy();
|
||||
});
|
||||
|
||||
it("serves the route for board users and rejects agent callers", async () => {
|
||||
const { companyId } = await seedCompany("ATR");
|
||||
|
||||
function app(actor: Record<string, unknown>) {
|
||||
const testApp = express();
|
||||
testApp.use(express.json());
|
||||
testApp.use((req, _res, next) => {
|
||||
(req as any).actor = actor;
|
||||
next();
|
||||
});
|
||||
testApp.use("/api", attentionRoutes(db));
|
||||
testApp.use(errorHandler);
|
||||
return testApp;
|
||||
}
|
||||
|
||||
const board = {
|
||||
type: "board",
|
||||
source: "local_implicit",
|
||||
userId: "board-user",
|
||||
companyIds: [companyId],
|
||||
isInstanceAdmin: false,
|
||||
};
|
||||
const agent = {
|
||||
type: "agent",
|
||||
source: "agent_key",
|
||||
companyId,
|
||||
agentId: randomUUID(),
|
||||
runId: null,
|
||||
};
|
||||
|
||||
await request(app(board)).get(`/api/companies/${companyId}/attention`).expect(200);
|
||||
await request(app(agent)).get(`/api/companies/${companyId}/attention`).expect(403);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,9 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import {
|
||||
activityLog,
|
||||
agents,
|
||||
approvals,
|
||||
companies,
|
||||
@@ -14,6 +17,8 @@ import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "./helpers/embedded-postgres.js";
|
||||
import { errorHandler } from "../middleware/index.js";
|
||||
import { inboxDismissalRoutes } from "../routes/inbox-dismissals.js";
|
||||
import { inboxDismissalService } from "../services/inbox-dismissals.ts";
|
||||
import { sidebarBadgeService } from "../services/sidebar-badges.ts";
|
||||
|
||||
@@ -43,6 +48,7 @@ describeEmbeddedPostgres("inbox dismissals", () => {
|
||||
await db.delete(inboxDismissals);
|
||||
await db.delete(joinRequests);
|
||||
await db.delete(invites);
|
||||
await db.delete(activityLog);
|
||||
await db.delete(heartbeatRuns);
|
||||
await db.delete(approvals);
|
||||
await db.delete(agents);
|
||||
@@ -73,9 +79,63 @@ describeEmbeddedPostgres("inbox dismissals", () => {
|
||||
|
||||
expect(dismissals).toHaveLength(1);
|
||||
expect(dismissals[0]?.itemKey).toBe("approval:approval-1");
|
||||
expect(dismissals[0]?.kind).toBe("dismiss");
|
||||
expect(dismissals[0]?.snoozedUntil).toBeNull();
|
||||
expect(new Date(dismissals[0]?.dismissedAt ?? 0).toISOString()).toBe(secondDismissedAt.toISOString());
|
||||
});
|
||||
|
||||
it("snoozes and restores dismissal records through the route", async () => {
|
||||
const companyId = randomUUID();
|
||||
const userId = "board-user";
|
||||
|
||||
await db.insert(companies).values({
|
||||
id: companyId,
|
||||
name: "Paperclip",
|
||||
issuePrefix: "PAP",
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
});
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
(req as any).actor = {
|
||||
type: "board",
|
||||
source: "local_implicit",
|
||||
userId,
|
||||
companyIds: [companyId],
|
||||
isInstanceAdmin: false,
|
||||
};
|
||||
next();
|
||||
});
|
||||
app.use("/api", inboxDismissalRoutes(db));
|
||||
app.use(errorHandler);
|
||||
|
||||
await request(app)
|
||||
.post(`/api/companies/${companyId}/inbox-dismissals`)
|
||||
.send({ itemKey: "attention:approval:old", kind: "snooze", snoozedUntil: "2020-01-01T00:00:00.000Z" })
|
||||
.expect(400);
|
||||
|
||||
const snoozedUntil = "2099-01-01T00:00:00.000Z";
|
||||
const createRes = await request(app)
|
||||
.post(`/api/companies/${companyId}/inbox-dismissals`)
|
||||
.send({ itemKey: "attention:approval:approval-1", kind: "snooze", snoozedUntil })
|
||||
.expect(201);
|
||||
|
||||
expect(createRes.body).toMatchObject({
|
||||
companyId,
|
||||
userId,
|
||||
itemKey: "attention:approval:approval-1",
|
||||
kind: "snooze",
|
||||
snoozedUntil,
|
||||
});
|
||||
|
||||
await request(app)
|
||||
.delete(`/api/companies/${companyId}/inbox-dismissals/${encodeURIComponent("attention:approval:approval-1")}`)
|
||||
.expect(204);
|
||||
|
||||
await expect(dismissalsSvc.list(companyId, userId)).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
it("honors dismissal timestamps and resurfaces approvals with newer activity", async () => {
|
||||
const companyId = randomUUID();
|
||||
const userId = "board-user";
|
||||
|
||||
@@ -37,6 +37,7 @@ describe("instance settings service", () => {
|
||||
enableTaskWatchdogs: true,
|
||||
enableCloudSync: true,
|
||||
enableBuiltInAgents: true,
|
||||
enableDecisions: false,
|
||||
enableGoalsSidebarLink: true,
|
||||
enableServerInfoDebugView: true,
|
||||
autoRestartDevServerWhenIdle: true,
|
||||
@@ -83,6 +84,14 @@ describe("instance settings service", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("defaults enableDecisions to false for empty and legacy stored settings", () => {
|
||||
expect(normalizeExperimentalSettings(undefined).enableDecisions).toBe(false);
|
||||
expect(normalizeExperimentalSettings({}).enableDecisions).toBe(false);
|
||||
expect(
|
||||
normalizeExperimentalSettings({ enableStreamlinedLeftNavigation: true }).enableDecisions,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("defaults workspace branch repair settings to true for empty and legacy stored settings", () => {
|
||||
expect(normalizeExperimentalSettings(undefined).enableWorkspaceBranchReconcileForward).toBe(true);
|
||||
expect(normalizeExperimentalSettings({}).enableWorkspaceBranchReconcileForward).toBe(true);
|
||||
|
||||
@@ -18,6 +18,7 @@ const mockInteractionService = vi.hoisted(() => ({
|
||||
rejectSuggestedTasks: vi.fn(),
|
||||
expireRequestConfirmationsSupersededByHistoricalComments: vi.fn(),
|
||||
answerQuestions: vi.fn(),
|
||||
submitItemVerdicts: vi.fn(),
|
||||
cancelQuestions: vi.fn(),
|
||||
}));
|
||||
|
||||
@@ -284,6 +285,48 @@ describe.sequential("issue thread interaction routes", () => {
|
||||
updatedAt: "2026-04-20T12:06:00.000Z",
|
||||
resolvedAt: "2026-04-20T12:06:00.000Z",
|
||||
});
|
||||
mockInteractionService.submitItemVerdicts.mockResolvedValue({
|
||||
interaction: {
|
||||
id: "interaction-verdicts",
|
||||
companyId: "company-1",
|
||||
issueId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
|
||||
kind: "request_item_verdicts",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
idempotencyKey: null,
|
||||
sourceCommentId: "comment-verdicts",
|
||||
sourceRunId: "run-verdicts",
|
||||
payload: {
|
||||
version: 1,
|
||||
prompt: "Review generated artifacts.",
|
||||
items: [
|
||||
{ id: "api", label: "API route" },
|
||||
{ id: "docs", label: "Docs" },
|
||||
],
|
||||
verdicts: ["approve", "reject"],
|
||||
requireReasonOn: ["reject"],
|
||||
allowBulkApprove: true,
|
||||
},
|
||||
result: {
|
||||
version: 1,
|
||||
outcome: "resolved",
|
||||
complete: false,
|
||||
items: [
|
||||
{
|
||||
id: "docs",
|
||||
verdict: "reject",
|
||||
reason: "Missing examples",
|
||||
resolvedByUserId: "local-board",
|
||||
resolvedAt: "2026-04-20T12:06:00.000Z",
|
||||
},
|
||||
],
|
||||
},
|
||||
createdAt: "2026-04-20T12:00:00.000Z",
|
||||
updatedAt: "2026-04-20T12:06:00.000Z",
|
||||
resolvedAt: null,
|
||||
},
|
||||
newlyResolvedItemIds: ["docs"],
|
||||
});
|
||||
mockInteractionService.cancelQuestions.mockResolvedValue({
|
||||
id: "interaction-2",
|
||||
companyId: "company-1",
|
||||
@@ -469,6 +512,68 @@ describe.sequential("issue thread interaction routes", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("submits item verdicts and emits one continuation wake with resolved item ids", async () => {
|
||||
const app = await createApp();
|
||||
|
||||
const res = await request(app)
|
||||
.post("/api/issues/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/interactions/interaction-verdicts/verdicts")
|
||||
.send({
|
||||
verdicts: [{ id: "docs", verdict: "reject", reason: "Missing examples" }],
|
||||
});
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockInteractionService.submitItemVerdicts).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa" }),
|
||||
"interaction-verdicts",
|
||||
{ verdicts: [{ id: "docs", verdict: "reject", reason: "Missing examples" }] },
|
||||
expect.objectContaining({ userId: "local-board" }),
|
||||
);
|
||||
expect(mockHeartbeatService.wakeup).toHaveBeenCalledTimes(1);
|
||||
expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith(
|
||||
ASSIGNEE_AGENT_ID,
|
||||
expect.objectContaining({
|
||||
reason: "issue_commented",
|
||||
idempotencyKey: expect.stringMatching(
|
||||
/^request_item_verdicts:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa:interaction-verdicts:/,
|
||||
),
|
||||
payload: expect.objectContaining({
|
||||
interactionId: "interaction-verdicts",
|
||||
interactionKind: "request_item_verdicts",
|
||||
interactionStatus: "pending",
|
||||
sourceCommentId: "comment-verdicts",
|
||||
sourceRunId: "run-verdicts",
|
||||
newlyResolvedItemIds: ["docs"],
|
||||
itemVerdicts: {
|
||||
newlyResolvedItemIds: ["docs"],
|
||||
coalesceWindowMs: 2000,
|
||||
},
|
||||
}),
|
||||
contextSnapshot: expect.objectContaining({
|
||||
interactionId: "interaction-verdicts",
|
||||
interactionKind: "request_item_verdicts",
|
||||
interactionStatus: "pending",
|
||||
newlyResolvedItemIds: ["docs"],
|
||||
itemVerdicts: {
|
||||
newlyResolvedItemIds: ["docs"],
|
||||
coalesceWindowMs: 2000,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(mockLogActivity).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
action: "issue.thread_interaction_item_verdicts_submitted",
|
||||
details: expect.objectContaining({
|
||||
interactionKind: "request_item_verdicts",
|
||||
newlyResolvedItemCount: 1,
|
||||
newlyResolvedItemIds: ["docs"],
|
||||
complete: false,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("cancels question interactions and emits a continuation wake", async () => {
|
||||
const app = await createApp();
|
||||
|
||||
|
||||
@@ -1140,6 +1140,243 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("submits request_item_verdicts partially and completes when all items are resolved", async () => {
|
||||
const { companyId, issueId } = await seedConfirmationIssue("Item verdict partial submit");
|
||||
|
||||
const created = await interactionsSvc.create({
|
||||
id: issueId,
|
||||
companyId,
|
||||
}, {
|
||||
kind: "request_item_verdicts",
|
||||
payload: {
|
||||
version: 1,
|
||||
prompt: "Review generated artifacts.",
|
||||
items: [
|
||||
{ id: "api", label: "API route" },
|
||||
{ id: "docs", label: "Docs" },
|
||||
{ id: "tests", label: "Tests" },
|
||||
],
|
||||
},
|
||||
}, {
|
||||
userId: "local-board",
|
||||
});
|
||||
|
||||
expect(created).toMatchObject({
|
||||
kind: "request_item_verdicts",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
payload: {
|
||||
verdicts: ["approve", "reject"],
|
||||
requireReasonOn: ["reject"],
|
||||
allowBulkApprove: true,
|
||||
supersedeOnUserComment: true,
|
||||
},
|
||||
});
|
||||
|
||||
const first = await interactionsSvc.submitItemVerdicts({
|
||||
id: issueId,
|
||||
companyId,
|
||||
}, created.id, {
|
||||
verdicts: [{ id: "docs", verdict: "reject", reason: "Missing examples" }],
|
||||
}, {
|
||||
userId: "local-board",
|
||||
});
|
||||
|
||||
expect(first.newlyResolvedItemIds).toEqual(["docs"]);
|
||||
expect(first.interaction).toMatchObject({
|
||||
kind: "request_item_verdicts",
|
||||
status: "pending",
|
||||
result: {
|
||||
version: 1,
|
||||
outcome: "resolved",
|
||||
complete: false,
|
||||
items: [
|
||||
{
|
||||
id: "docs",
|
||||
verdict: "reject",
|
||||
reason: "Missing examples",
|
||||
resolvedByUserId: "local-board",
|
||||
},
|
||||
],
|
||||
},
|
||||
resolvedAt: null,
|
||||
});
|
||||
|
||||
const duplicate = await interactionsSvc.submitItemVerdicts({
|
||||
id: issueId,
|
||||
companyId,
|
||||
}, created.id, {
|
||||
verdicts: [{ id: "docs", verdict: "reject" }],
|
||||
}, {
|
||||
userId: "local-board",
|
||||
});
|
||||
|
||||
expect(duplicate.newlyResolvedItemIds).toEqual([]);
|
||||
expect(duplicate.interaction).toMatchObject({
|
||||
status: "pending",
|
||||
result: {
|
||||
complete: false,
|
||||
items: [
|
||||
{
|
||||
id: "docs",
|
||||
verdict: "reject",
|
||||
reason: "Missing examples",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const completed = await interactionsSvc.submitItemVerdicts({
|
||||
id: issueId,
|
||||
companyId,
|
||||
}, created.id, {
|
||||
verdicts: [
|
||||
{ id: "api", verdict: "approve" },
|
||||
{ id: "tests", verdict: "reject", reason: "No route coverage" },
|
||||
],
|
||||
}, {
|
||||
userId: "local-board",
|
||||
});
|
||||
|
||||
expect(completed.newlyResolvedItemIds).toEqual(["api", "tests"]);
|
||||
expect(completed.interaction).toMatchObject({
|
||||
kind: "request_item_verdicts",
|
||||
status: "answered",
|
||||
result: {
|
||||
version: 1,
|
||||
outcome: "resolved",
|
||||
complete: true,
|
||||
items: [
|
||||
{ id: "api", verdict: "approve" },
|
||||
{ id: "docs", verdict: "reject", reason: "Missing examples" },
|
||||
{ id: "tests", verdict: "reject", reason: "No route coverage" },
|
||||
],
|
||||
},
|
||||
resolvedByUserId: "local-board",
|
||||
});
|
||||
|
||||
const duplicateAfterComplete = await interactionsSvc.submitItemVerdicts({
|
||||
id: issueId,
|
||||
companyId,
|
||||
}, created.id, {
|
||||
verdicts: [{ id: "api", verdict: "approve" }],
|
||||
}, {
|
||||
userId: "local-board",
|
||||
});
|
||||
expect(duplicateAfterComplete.newlyResolvedItemIds).toEqual([]);
|
||||
expect(duplicateAfterComplete.interaction.status).toBe("answered");
|
||||
});
|
||||
|
||||
it("enforces request_item_verdicts ids, enabled verdicts, and required reasons", async () => {
|
||||
const { companyId, issueId } = await seedConfirmationIssue("Item verdict validation");
|
||||
|
||||
const created = await interactionsSvc.create({
|
||||
id: issueId,
|
||||
companyId,
|
||||
}, {
|
||||
kind: "request_item_verdicts",
|
||||
payload: {
|
||||
version: 1,
|
||||
prompt: "Review generated artifacts.",
|
||||
items: [
|
||||
{ id: "api", label: "API route" },
|
||||
{ id: "docs", label: "Docs" },
|
||||
],
|
||||
},
|
||||
}, {
|
||||
userId: "local-board",
|
||||
});
|
||||
|
||||
await expect(interactionsSvc.submitItemVerdicts({
|
||||
id: issueId,
|
||||
companyId,
|
||||
}, created.id, {
|
||||
verdicts: [{ id: "missing", verdict: "approve" }],
|
||||
}, {
|
||||
userId: "local-board",
|
||||
})).rejects.toThrow("Unknown item verdict id: missing");
|
||||
|
||||
await expect(interactionsSvc.submitItemVerdicts({
|
||||
id: issueId,
|
||||
companyId,
|
||||
}, created.id, {
|
||||
verdicts: [{ id: "api", verdict: "defer" }],
|
||||
}, {
|
||||
userId: "local-board",
|
||||
})).rejects.toThrow("Verdict defer is not enabled");
|
||||
|
||||
await expect(interactionsSvc.submitItemVerdicts({
|
||||
id: issueId,
|
||||
companyId,
|
||||
}, created.id, {
|
||||
verdicts: [{ id: "docs", verdict: "reject" }],
|
||||
}, {
|
||||
userId: "local-board",
|
||||
})).rejects.toThrow("A reason is required when verdict is reject");
|
||||
});
|
||||
|
||||
it("preserves resolved request_item_verdicts items when a later user comment supersedes the pending remainder", async () => {
|
||||
const { companyId, issueId } = await seedConfirmationIssue("Item verdict supersede");
|
||||
const commentId = randomUUID();
|
||||
|
||||
const created = await interactionsSvc.create({
|
||||
id: issueId,
|
||||
companyId,
|
||||
}, {
|
||||
kind: "request_item_verdicts",
|
||||
payload: {
|
||||
version: 1,
|
||||
prompt: "Review generated artifacts.",
|
||||
items: [
|
||||
{ id: "api", label: "API route" },
|
||||
{ id: "docs", label: "Docs" },
|
||||
],
|
||||
},
|
||||
}, {
|
||||
userId: "local-board",
|
||||
});
|
||||
|
||||
await interactionsSvc.submitItemVerdicts({
|
||||
id: issueId,
|
||||
companyId,
|
||||
}, created.id, {
|
||||
verdicts: [{ id: "api", verdict: "approve" }],
|
||||
}, {
|
||||
userId: "local-board",
|
||||
});
|
||||
|
||||
const expired = await interactionsSvc.expireRequestConfirmationsSupersededByComment({
|
||||
id: issueId,
|
||||
companyId,
|
||||
}, {
|
||||
id: commentId,
|
||||
createdAt: new Date(new Date(created.createdAt).getTime() + 1_000),
|
||||
authorUserId: "local-board",
|
||||
}, {
|
||||
userId: "local-board",
|
||||
});
|
||||
|
||||
expect(expired).toHaveLength(1);
|
||||
expect(expired[0]).toMatchObject({
|
||||
id: created.id,
|
||||
kind: "request_item_verdicts",
|
||||
status: "expired",
|
||||
result: {
|
||||
version: 1,
|
||||
outcome: "superseded_by_comment",
|
||||
complete: false,
|
||||
commentId,
|
||||
items: [
|
||||
{
|
||||
id: "api",
|
||||
verdict: "approve",
|
||||
resolvedByUserId: "local-board",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("returns agent-authored request confirmations to the creating agent when a board user accepts", async () => {
|
||||
const companyId = randomUUID();
|
||||
const goalId = randomUUID();
|
||||
@@ -1580,6 +1817,152 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves resolved request_item_verdicts items when the watched issue document revision changes", async () => {
|
||||
const companyId = randomUUID();
|
||||
const goalId = randomUUID();
|
||||
const issueId = randomUUID();
|
||||
const documentId = randomUUID();
|
||||
const revisionId = randomUUID();
|
||||
const nextRevisionId = randomUUID();
|
||||
|
||||
await db.insert(companies).values({
|
||||
id: companyId,
|
||||
name: "Paperclip",
|
||||
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
});
|
||||
await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: false });
|
||||
await db.insert(goals).values({
|
||||
id: goalId,
|
||||
companyId,
|
||||
title: "Document target verdicts",
|
||||
level: "task",
|
||||
status: "active",
|
||||
});
|
||||
await db.insert(issues).values({
|
||||
id: issueId,
|
||||
companyId,
|
||||
goalId,
|
||||
title: "Parent issue",
|
||||
status: "in_progress",
|
||||
priority: "medium",
|
||||
});
|
||||
await db.insert(documents).values({
|
||||
id: documentId,
|
||||
companyId,
|
||||
title: "Plan",
|
||||
format: "markdown",
|
||||
latestBody: "v1",
|
||||
latestRevisionId: revisionId,
|
||||
latestRevisionNumber: 1,
|
||||
});
|
||||
await db.insert(issueDocuments).values({
|
||||
companyId,
|
||||
issueId,
|
||||
documentId,
|
||||
key: "plan",
|
||||
});
|
||||
await db.insert(documentRevisions).values({
|
||||
id: revisionId,
|
||||
companyId,
|
||||
documentId,
|
||||
revisionNumber: 1,
|
||||
title: "Plan",
|
||||
format: "markdown",
|
||||
body: "v1",
|
||||
});
|
||||
|
||||
const created = await interactionsSvc.create({
|
||||
id: issueId,
|
||||
companyId,
|
||||
}, {
|
||||
kind: "request_item_verdicts",
|
||||
continuationPolicy: "wake_assignee",
|
||||
payload: {
|
||||
version: 1,
|
||||
prompt: "Review generated artifacts.",
|
||||
items: [
|
||||
{ id: "api", label: "API route" },
|
||||
{ id: "docs", label: "Docs" },
|
||||
],
|
||||
target: {
|
||||
type: "issue_document",
|
||||
issueId,
|
||||
documentId,
|
||||
key: "plan",
|
||||
revisionId,
|
||||
revisionNumber: 1,
|
||||
},
|
||||
},
|
||||
}, {
|
||||
userId: "local-board",
|
||||
});
|
||||
|
||||
await interactionsSvc.submitItemVerdicts({
|
||||
id: issueId,
|
||||
companyId,
|
||||
}, created.id, {
|
||||
verdicts: [{ id: "api", verdict: "approve" }],
|
||||
}, {
|
||||
userId: "local-board",
|
||||
});
|
||||
|
||||
await db.insert(documentRevisions).values({
|
||||
id: nextRevisionId,
|
||||
companyId,
|
||||
documentId,
|
||||
revisionNumber: 2,
|
||||
title: "Plan",
|
||||
format: "markdown",
|
||||
body: "v2",
|
||||
});
|
||||
await db.update(documents).set({
|
||||
latestBody: "v2",
|
||||
latestRevisionId: nextRevisionId,
|
||||
latestRevisionNumber: 2,
|
||||
});
|
||||
|
||||
const stale = await interactionsSvc.submitItemVerdicts({
|
||||
id: issueId,
|
||||
companyId,
|
||||
}, created.id, {
|
||||
verdicts: [{ id: "docs", verdict: "approve" }],
|
||||
}, {
|
||||
userId: "local-board",
|
||||
});
|
||||
|
||||
expect(stale.newlyResolvedItemIds).toEqual([]);
|
||||
expect(stale.interaction).toMatchObject({
|
||||
id: created.id,
|
||||
status: "expired",
|
||||
payload: {
|
||||
target: {
|
||||
type: "issue_document",
|
||||
key: "plan",
|
||||
revisionId: nextRevisionId,
|
||||
revisionNumber: 2,
|
||||
},
|
||||
},
|
||||
result: {
|
||||
version: 1,
|
||||
outcome: "stale_target",
|
||||
complete: false,
|
||||
staleTarget: {
|
||||
type: "issue_document",
|
||||
key: "plan",
|
||||
revisionId,
|
||||
},
|
||||
items: [
|
||||
{
|
||||
id: "api",
|
||||
verdict: "approve",
|
||||
resolvedByUserId: "local-board",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
describe("workspace_finalize accept gate", () => {
|
||||
type AcceptGateInteractionKind = "request_confirmation" | "request_checkbox_confirmation";
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"activity.ts": "/api",
|
||||
"adapters.ts": "/api",
|
||||
"agents.ts": "/api",
|
||||
"attention.ts": "/api",
|
||||
"approvals.ts": "/api",
|
||||
"assets.ts": "/api",
|
||||
"auth.ts": "/api/auth",
|
||||
|
||||
@@ -33,6 +33,7 @@ import { secretRoutes } from "./routes/secrets.js";
|
||||
import { costRoutes } from "./routes/costs.js";
|
||||
import { activityRoutes } from "./routes/activity.js";
|
||||
import { dashboardRoutes } from "./routes/dashboard.js";
|
||||
import { attentionRoutes } from "./routes/attention.js";
|
||||
import { userProfileRoutes } from "./routes/user-profiles.js";
|
||||
import { sidebarBadgeRoutes } from "./routes/sidebar-badges.js";
|
||||
import { sidebarPreferenceRoutes } from "./routes/sidebar-preferences.js";
|
||||
@@ -253,6 +254,7 @@ export async function createApp(
|
||||
api.use(costRoutes(db, { pluginWorkerManager: workerManager }));
|
||||
api.use(activityRoutes(db));
|
||||
api.use(dashboardRoutes(db));
|
||||
api.use(attentionRoutes(db));
|
||||
api.use(userProfileRoutes(db));
|
||||
api.use(sidebarBadgeRoutes(db));
|
||||
api.use(sidebarPreferenceRoutes(db));
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Router } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { attentionService } from "../services/attention.js";
|
||||
import { assertBoard, assertCompanyAccess } from "./authz.js";
|
||||
|
||||
export function attentionRoutes(db: Db) {
|
||||
const router = Router();
|
||||
const svc = attentionService(db);
|
||||
|
||||
router.get("/companies/:companyId/attention", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
assertBoard(req);
|
||||
if (!req.actor.userId) {
|
||||
res.status(403).json({ error: "Board user context required" });
|
||||
return;
|
||||
}
|
||||
|
||||
const includeDismissed = req.query.includeDismissed === "true";
|
||||
const feed = await svc.list(companyId, {
|
||||
userId: req.actor.userId,
|
||||
includeDismissed,
|
||||
});
|
||||
res.json(feed);
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -1,14 +1,50 @@
|
||||
import { Router } from "express";
|
||||
import { Router, type Request, type Response } from "express";
|
||||
import { z } from "zod";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { validate } from "../middleware/validate.js";
|
||||
import { assertCompanyAccess, getActorInfo } from "./authz.js";
|
||||
import { inboxDismissalService, logActivity } from "../services/index.js";
|
||||
|
||||
const ITEM_KEY_RE = /^(approval|join|run|attention):.+$/;
|
||||
|
||||
const inboxDismissalSchema = z.object({
|
||||
itemKey: z.string().trim().min(1).regex(/^(approval|join|run):.+$/, "Unsupported inbox item key"),
|
||||
itemKey: z.string().trim().min(1).regex(ITEM_KEY_RE, "Unsupported inbox item key"),
|
||||
kind: z.enum(["dismiss", "snooze"]).default("dismiss"),
|
||||
snoozedUntil: z.string().trim().optional(),
|
||||
}).superRefine((value, ctx) => {
|
||||
if (value.kind === "dismiss") {
|
||||
if (value.snoozedUntil != null) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["snoozedUntil"], message: "Dismissals must not include snoozedUntil" });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!value.snoozedUntil) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["snoozedUntil"], message: "Snooze requires snoozedUntil" });
|
||||
return;
|
||||
}
|
||||
const timestamp = new Date(value.snoozedUntil).getTime();
|
||||
if (!Number.isFinite(timestamp)) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["snoozedUntil"], message: "snoozedUntil must be an ISO timestamp" });
|
||||
return;
|
||||
}
|
||||
if (timestamp <= Date.now()) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["snoozedUntil"], message: "snoozedUntil must be in the future" });
|
||||
}
|
||||
});
|
||||
|
||||
function requireBoardUser(req: Request, res: Response) {
|
||||
if (req.actor.type !== "board") {
|
||||
res.status(403).json({ error: "Board authentication required" });
|
||||
return null;
|
||||
}
|
||||
if (!req.actor.userId) {
|
||||
res.status(403).json({ error: "Board user context required" });
|
||||
return null;
|
||||
}
|
||||
return req.actor.userId;
|
||||
}
|
||||
|
||||
export function inboxDismissalRoutes(db: Db) {
|
||||
const router = Router();
|
||||
const svc = inboxDismissalService(db);
|
||||
@@ -16,15 +52,10 @@ export function inboxDismissalRoutes(db: Db) {
|
||||
router.get("/companies/:companyId/inbox-dismissals", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
if (req.actor.type !== "board") {
|
||||
res.status(403).json({ error: "Board authentication required" });
|
||||
return;
|
||||
}
|
||||
if (!req.actor.userId) {
|
||||
res.status(403).json({ error: "Board user context required" });
|
||||
return;
|
||||
}
|
||||
const dismissals = await svc.list(companyId, req.actor.userId);
|
||||
const userId = requireBoardUser(req, res);
|
||||
if (!userId) return;
|
||||
|
||||
const dismissals = await svc.list(companyId, userId);
|
||||
res.json(dismissals);
|
||||
});
|
||||
|
||||
@@ -34,16 +65,12 @@ export function inboxDismissalRoutes(db: Db) {
|
||||
async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
if (req.actor.type !== "board") {
|
||||
res.status(403).json({ error: "Board authentication required" });
|
||||
return;
|
||||
}
|
||||
if (!req.actor.userId) {
|
||||
res.status(403).json({ error: "Board user context required" });
|
||||
return;
|
||||
}
|
||||
const userId = requireBoardUser(req, res);
|
||||
if (!userId) return;
|
||||
|
||||
const dismissal = await svc.dismiss(companyId, req.actor.userId, req.body.itemKey, new Date());
|
||||
const dismissal = req.body.kind === "snooze"
|
||||
? await svc.snooze(companyId, userId, req.body.itemKey, new Date(req.body.snoozedUntil))
|
||||
: await svc.dismiss(companyId, userId, req.body.itemKey, new Date());
|
||||
const actor = getActorInfo(req);
|
||||
await logActivity(db, {
|
||||
companyId,
|
||||
@@ -51,13 +78,15 @@ export function inboxDismissalRoutes(db: Db) {
|
||||
actorId: actor.actorId,
|
||||
agentId: actor.agentId,
|
||||
runId: actor.runId,
|
||||
action: "inbox.dismissed",
|
||||
action: dismissal.kind === "snooze" ? "inbox.snoozed" : "inbox.dismissed",
|
||||
entityType: "company",
|
||||
entityId: companyId,
|
||||
details: {
|
||||
userId: req.actor.userId,
|
||||
userId,
|
||||
itemKey: dismissal.itemKey,
|
||||
kind: dismissal.kind,
|
||||
dismissedAt: dismissal.dismissedAt,
|
||||
snoozedUntil: dismissal.snoozedUntil,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -65,5 +94,42 @@ export function inboxDismissalRoutes(db: Db) {
|
||||
},
|
||||
);
|
||||
|
||||
router.delete("/companies/:companyId/inbox-dismissals/:itemKey", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
const userId = requireBoardUser(req, res);
|
||||
if (!userId) return;
|
||||
|
||||
const itemKey = req.params.itemKey as string;
|
||||
if (!ITEM_KEY_RE.test(itemKey)) {
|
||||
res.status(400).json({ error: "Unsupported inbox item key" });
|
||||
return;
|
||||
}
|
||||
|
||||
const restored = await svc.restore(companyId, userId, itemKey);
|
||||
if (restored) {
|
||||
const actor = getActorInfo(req);
|
||||
await logActivity(db, {
|
||||
companyId,
|
||||
actorType: actor.actorType,
|
||||
actorId: actor.actorId,
|
||||
agentId: actor.agentId,
|
||||
runId: actor.runId,
|
||||
action: "inbox.restored",
|
||||
entityType: "company",
|
||||
entityId: companyId,
|
||||
details: {
|
||||
userId,
|
||||
itemKey: restored.itemKey,
|
||||
kind: restored.kind,
|
||||
dismissedAt: restored.dismissedAt,
|
||||
snoozedUntil: restored.snoozedUntil,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
res.status(204).send();
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -15,6 +15,7 @@ export { secretRoutes } from "./secrets.js";
|
||||
export { costRoutes } from "./costs.js";
|
||||
export { activityRoutes } from "./activity.js";
|
||||
export { dashboardRoutes } from "./dashboard.js";
|
||||
export { attentionRoutes } from "./attention.js";
|
||||
export { sidebarBadgeRoutes } from "./sidebar-badges.js";
|
||||
export { sidebarPreferenceRoutes } from "./sidebar-preferences.js";
|
||||
export { resourceMembershipRoutes } from "./resource-memberships.js";
|
||||
|
||||
@@ -53,6 +53,7 @@ import {
|
||||
rejectIssueThreadInteractionSchema,
|
||||
restoreIssueDocumentRevisionSchema,
|
||||
respondIssueThreadInteractionSchema,
|
||||
submitIssueThreadInteractionVerdictsSchema,
|
||||
updateIssueWorkProductSchema,
|
||||
updateDocumentAnnotationThreadSchema,
|
||||
upsertIssueDocumentSchema,
|
||||
@@ -1766,6 +1767,18 @@ function isAssigneeSelfCommentOnTerminalIssue(input: {
|
||||
return input.actorId === input.assigneeAgentId;
|
||||
}
|
||||
|
||||
const REQUEST_ITEM_VERDICTS_WAKE_COALESCE_WINDOW_MS = 2_000;
|
||||
|
||||
function buildRequestItemVerdictsWakeIdempotencyKey(args: {
|
||||
issueId: string;
|
||||
interactionId: string;
|
||||
at?: Date;
|
||||
}) {
|
||||
const now = args.at ?? new Date();
|
||||
const bucket = Math.floor(now.getTime() / REQUEST_ITEM_VERDICTS_WAKE_COALESCE_WINDOW_MS);
|
||||
return `request_item_verdicts:${args.issueId}:${args.interactionId}:${bucket}`;
|
||||
}
|
||||
|
||||
function queueResolvedInteractionContinuationWakeup(input: {
|
||||
heartbeat: ReturnType<typeof heartbeatService>;
|
||||
issue: { id: string; assigneeAgentId: string | null; status: string };
|
||||
@@ -1783,6 +1796,8 @@ function queueResolvedInteractionContinuationWakeup(input: {
|
||||
source: string;
|
||||
forceFreshSession?: boolean;
|
||||
workspaceRefreshReason?: string | null;
|
||||
newlyResolvedItemIds?: string[];
|
||||
idempotencyKey?: string | null;
|
||||
}) {
|
||||
if (
|
||||
input.interaction.continuationPolicy !== "wake_assignee"
|
||||
@@ -1800,6 +1815,13 @@ function queueResolvedInteractionContinuationWakeup(input: {
|
||||
const planTarget = readPlanConfirmationTargetForIssue(input.interaction.payload, input.issue.id);
|
||||
const interactionResult = readConfirmationResultForWake(input.interaction.result);
|
||||
const checkboxSelection = readCheckboxSelectionForWake(input.interaction);
|
||||
const newlyResolvedItemIds = input.newlyResolvedItemIds?.filter((value) => value.length > 0) ?? [];
|
||||
const itemVerdicts = newlyResolvedItemIds.length > 0
|
||||
? {
|
||||
newlyResolvedItemIds,
|
||||
coalesceWindowMs: REQUEST_ITEM_VERDICTS_WAKE_COALESCE_WINDOW_MS,
|
||||
}
|
||||
: null;
|
||||
const planReviewInteraction =
|
||||
planTarget && input.interaction.kind === "request_confirmation"
|
||||
? {
|
||||
@@ -1824,8 +1846,10 @@ function queueResolvedInteractionContinuationWakeup(input: {
|
||||
sourceRunId: input.interaction.sourceRunId ?? null,
|
||||
...(planReviewInteraction ? { planReviewInteraction } : {}),
|
||||
...(checkboxSelection ? { checkboxSelection } : {}),
|
||||
...(itemVerdicts ? { itemVerdicts, newlyResolvedItemIds } : {}),
|
||||
mutation: "interaction",
|
||||
},
|
||||
idempotencyKey: input.idempotencyKey ?? null,
|
||||
requestedByActorType: input.actor.actorType,
|
||||
requestedByActorId: input.actor.actorId,
|
||||
contextSnapshot: {
|
||||
@@ -1838,6 +1862,7 @@ function queueResolvedInteractionContinuationWakeup(input: {
|
||||
sourceRunId: input.interaction.sourceRunId ?? null,
|
||||
...(planReviewInteraction ? { planReviewInteraction } : {}),
|
||||
...(checkboxSelection ? { checkboxSelection } : {}),
|
||||
...(itemVerdicts ? { itemVerdicts, newlyResolvedItemIds } : {}),
|
||||
wakeReason: "issue_commented",
|
||||
source: input.source,
|
||||
...(forceFreshSession ? { forceFreshSession: true } : {}),
|
||||
@@ -9181,6 +9206,76 @@ export function issueRoutes(
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/issues/:id/interactions/:interactionId/verdicts",
|
||||
validate(submitIssueThreadInteractionVerdictsSchema),
|
||||
async (req, res) => {
|
||||
const id = req.params.id as string;
|
||||
const interactionId = req.params.interactionId as string;
|
||||
const issue = await svc.getById(id);
|
||||
if (!issue) {
|
||||
res.status(404).json({ error: "Issue not found" });
|
||||
return;
|
||||
}
|
||||
assertCompanyAccess(req, issue.companyId);
|
||||
if (await rejectAgentIssueThreadInteractionResolution(req, res, issue)) return;
|
||||
assertBoard(req);
|
||||
|
||||
const actor = getActorInfo(req);
|
||||
const { interaction, newlyResolvedItemIds } = await issueThreadInteractionService(db).submitItemVerdicts(
|
||||
issue,
|
||||
interactionId,
|
||||
req.body,
|
||||
{
|
||||
agentId: actor.agentId,
|
||||
userId: actor.actorType === "user" ? actor.actorId : null,
|
||||
},
|
||||
);
|
||||
|
||||
await logActivity(db, {
|
||||
companyId: issue.companyId,
|
||||
actorType: actor.actorType,
|
||||
actorId: actor.actorId,
|
||||
agentId: actor.agentId,
|
||||
runId: actor.runId,
|
||||
action: interaction.status === "expired"
|
||||
? "issue.thread_interaction_expired"
|
||||
: "issue.thread_interaction_item_verdicts_submitted",
|
||||
entityType: "issue",
|
||||
entityId: issue.id,
|
||||
details: {
|
||||
interactionId: interaction.id,
|
||||
interactionKind: interaction.kind,
|
||||
interactionStatus: interaction.status,
|
||||
submittedVerdictCount: Array.isArray(req.body?.verdicts) ? req.body.verdicts.length : 0,
|
||||
newlyResolvedItemCount: newlyResolvedItemIds.length,
|
||||
newlyResolvedItemIds,
|
||||
complete:
|
||||
interaction.kind === "request_item_verdicts"
|
||||
? (interaction.result?.complete ?? false)
|
||||
: false,
|
||||
},
|
||||
});
|
||||
|
||||
if (newlyResolvedItemIds.length > 0) {
|
||||
queueResolvedInteractionContinuationWakeup({
|
||||
heartbeat,
|
||||
issue,
|
||||
interaction,
|
||||
actor,
|
||||
source: "issue.interaction.verdicts",
|
||||
newlyResolvedItemIds,
|
||||
idempotencyKey: buildRequestItemVerdictsWakeIdempotencyKey({
|
||||
issueId: issue.id,
|
||||
interactionId: interaction.id,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
res.json(interaction);
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/issues/:id/interactions/:interactionId/cancel",
|
||||
validate(cancelIssueThreadInteractionSchema),
|
||||
|
||||
@@ -111,6 +111,7 @@ import {
|
||||
acceptIssueThreadInteractionSchema,
|
||||
rejectIssueThreadInteractionSchema,
|
||||
respondIssueThreadInteractionSchema,
|
||||
submitIssueThreadInteractionVerdictsSchema,
|
||||
// Auth / profile
|
||||
updateCurrentUserProfileSchema,
|
||||
// Company portability (legacy routes)
|
||||
@@ -2813,6 +2814,15 @@ registry.registerPath({
|
||||
responses: { 200: r.ok(), 401: r.unauthorized },
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/companies/{companyId}/attention",
|
||||
tags: ["inbox"],
|
||||
summary: "List decision-only attention feed items",
|
||||
request: { params: z.object({ companyId: z.string() }) },
|
||||
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden },
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/sidebar-preferences/me",
|
||||
@@ -2866,14 +2876,25 @@ registry.registerPath({
|
||||
method: "post",
|
||||
path: "/api/companies/{companyId}/inbox-dismissals",
|
||||
tags: ["inbox"],
|
||||
summary: "Create an inbox dismissal",
|
||||
summary: "Create an inbox dismissal or snooze",
|
||||
request: {
|
||||
params: z.object({ companyId: z.string() }),
|
||||
body: jsonBody(z.object({
|
||||
itemKey: z.string().trim().min(1).regex(/^(approval|join|run):.+$/, "Unsupported inbox item key"),
|
||||
itemKey: z.string().trim().min(1).regex(/^(approval|join|run|attention):.+$/, "Unsupported inbox item key"),
|
||||
kind: z.enum(["dismiss", "snooze"]).optional(),
|
||||
snoozedUntil: z.string().datetime().optional(),
|
||||
})),
|
||||
},
|
||||
responses: { 200: r.ok(), 401: r.unauthorized },
|
||||
responses: { 201: r.ok(), 400: r.badRequest, 401: r.unauthorized },
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "delete",
|
||||
path: "/api/companies/{companyId}/inbox-dismissals/{itemKey}",
|
||||
tags: ["inbox"],
|
||||
summary: "Restore an inbox dismissal or snooze",
|
||||
request: { params: z.object({ companyId: z.string(), itemKey: z.string() }) },
|
||||
responses: { 204: r.ok(), 400: r.badRequest, 401: r.unauthorized },
|
||||
});
|
||||
|
||||
// ─── Instance settings ────────────────────────────────────────────────────────
|
||||
@@ -3433,6 +3454,18 @@ registry.registerPath({
|
||||
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 404: r.notFound },
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/api/issues/{id}/interactions/{interactionId}/verdicts",
|
||||
tags: ["issues"],
|
||||
summary: "Submit item verdicts on an issue thread interaction",
|
||||
request: {
|
||||
params: z.object({ id: z.string(), interactionId: z.string() }),
|
||||
body: jsonBody(submitIssueThreadInteractionVerdictsSchema),
|
||||
},
|
||||
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 404: r.notFound },
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/api/issues/{id}/children",
|
||||
|
||||
@@ -9,11 +9,19 @@ import { collapseDuplicatePendingHumanJoinRequests } from "../lib/join-request-d
|
||||
import { assertCompanyAccess } from "./authz.js";
|
||||
|
||||
function buildDismissedAtByKey(
|
||||
dismissals: Array<{ itemKey: string; dismissedAt: Date | string }>,
|
||||
dismissals: Array<{ itemKey: string; kind: string; dismissedAt: Date | string; snoozedUntil: Date | string | null }>,
|
||||
): Map<string, number> {
|
||||
return new Map(
|
||||
dismissals.map((dismissal) => [dismissal.itemKey, new Date(dismissal.dismissedAt).getTime()]),
|
||||
);
|
||||
const now = Date.now();
|
||||
const entries: Array<[string, number]> = [];
|
||||
for (const dismissal of dismissals) {
|
||||
if (dismissal.kind === "snooze") {
|
||||
const snoozedUntil = dismissal.snoozedUntil ? new Date(dismissal.snoozedUntil).getTime() : 0;
|
||||
if (Number.isFinite(snoozedUntil) && snoozedUntil > now) entries.push([dismissal.itemKey, Number.MAX_SAFE_INTEGER]);
|
||||
continue;
|
||||
}
|
||||
entries.push([dismissal.itemKey, new Date(dismissal.dismissedAt).getTime()]);
|
||||
}
|
||||
return new Map(entries);
|
||||
}
|
||||
|
||||
export function sidebarBadgeRoutes(db: Db) {
|
||||
@@ -59,7 +67,12 @@ export function sidebarBadgeRoutes(db: Db) {
|
||||
const dismissedAtByKey =
|
||||
req.actor.type === "board" && req.actor.userId
|
||||
? await db
|
||||
.select({ itemKey: inboxDismissals.itemKey, dismissedAt: inboxDismissals.dismissedAt })
|
||||
.select({
|
||||
itemKey: inboxDismissals.itemKey,
|
||||
kind: inboxDismissals.kind,
|
||||
dismissedAt: inboxDismissals.dismissedAt,
|
||||
snoozedUntil: inboxDismissals.snoozedUntil,
|
||||
})
|
||||
.from(inboxDismissals)
|
||||
.where(and(eq(inboxDismissals.companyId, companyId), eq(inboxDismissals.userId, req.actor.userId)))
|
||||
.then(buildDismissedAtByKey)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3951,6 +3951,8 @@ const INTERACTION_CONTINUATION_CONTEXT_KEYS = [
|
||||
"interactionStatus",
|
||||
"continuationPolicy",
|
||||
"checkboxSelection",
|
||||
"itemVerdicts",
|
||||
"newlyResolvedItemIds",
|
||||
] as const;
|
||||
|
||||
function isInteractionResolutionWakePayload(payload: Record<string, unknown> | null | undefined) {
|
||||
|
||||
@@ -1,8 +1,42 @@
|
||||
import { and, desc, eq } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { inboxDismissals } from "@paperclipai/db";
|
||||
import type { InboxDismissalKind } from "@paperclipai/shared";
|
||||
|
||||
export function inboxDismissalService(db: Db) {
|
||||
async function upsert(
|
||||
companyId: string,
|
||||
userId: string,
|
||||
itemKey: string,
|
||||
input: { kind: InboxDismissalKind; dismissedAt?: Date; snoozedUntil?: Date | null },
|
||||
) {
|
||||
const now = new Date();
|
||||
const dismissedAt = input.dismissedAt ?? now;
|
||||
const snoozedUntil = input.kind === "snooze" ? input.snoozedUntil ?? null : null;
|
||||
const [row] = await db
|
||||
.insert(inboxDismissals)
|
||||
.values({
|
||||
companyId,
|
||||
userId,
|
||||
itemKey,
|
||||
kind: input.kind,
|
||||
dismissedAt,
|
||||
snoozedUntil,
|
||||
updatedAt: now,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [inboxDismissals.companyId, inboxDismissals.userId, inboxDismissals.itemKey],
|
||||
set: {
|
||||
kind: input.kind,
|
||||
dismissedAt,
|
||||
snoozedUntil,
|
||||
updatedAt: now,
|
||||
},
|
||||
})
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
return {
|
||||
list: async (companyId: string, userId: string) =>
|
||||
db
|
||||
@@ -16,26 +50,26 @@ export function inboxDismissalService(db: Db) {
|
||||
userId: string,
|
||||
itemKey: string,
|
||||
dismissedAt: Date = new Date(),
|
||||
) => {
|
||||
const now = new Date();
|
||||
) => upsert(companyId, userId, itemKey, { kind: "dismiss", dismissedAt }),
|
||||
|
||||
snooze: async (
|
||||
companyId: string,
|
||||
userId: string,
|
||||
itemKey: string,
|
||||
snoozedUntil: Date,
|
||||
dismissedAt: Date = new Date(),
|
||||
) => upsert(companyId, userId, itemKey, { kind: "snooze", dismissedAt, snoozedUntil }),
|
||||
|
||||
restore: async (companyId: string, userId: string, itemKey: string) => {
|
||||
const [row] = await db
|
||||
.insert(inboxDismissals)
|
||||
.values({
|
||||
companyId,
|
||||
userId,
|
||||
itemKey,
|
||||
dismissedAt,
|
||||
updatedAt: now,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [inboxDismissals.companyId, inboxDismissals.userId, inboxDismissals.itemKey],
|
||||
set: {
|
||||
dismissedAt,
|
||||
updatedAt: now,
|
||||
},
|
||||
})
|
||||
.delete(inboxDismissals)
|
||||
.where(and(
|
||||
eq(inboxDismissals.companyId, companyId),
|
||||
eq(inboxDismissals.userId, userId),
|
||||
eq(inboxDismissals.itemKey, itemKey),
|
||||
))
|
||||
.returning();
|
||||
return row;
|
||||
return row ?? null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -58,6 +58,7 @@ export {
|
||||
export { goalService } from "./goals.js";
|
||||
export { activityService, type ActivityFilters } from "./activity.js";
|
||||
export { workTimelineService, normalizeTimelineWindow } from "./work-timeline.js";
|
||||
export { attentionService } from "./attention.js";
|
||||
export type {
|
||||
WorkTimelineActor,
|
||||
WorkTimelineEdge,
|
||||
|
||||
@@ -214,6 +214,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
|
||||
enableCloudSync: parsed.data.enableCloudSync ?? false,
|
||||
enableExternalObjects: parsed.data.enableExternalObjects ?? false,
|
||||
enableBuiltInAgents: parsed.data.enableBuiltInAgents ?? false,
|
||||
enableDecisions: parsed.data.enableDecisions ?? false,
|
||||
enableGoalsSidebarLink: parsed.data.enableGoalsSidebarLink ?? false,
|
||||
enableServerInfoDebugView: parsed.data.enableServerInfoDebugView ?? false,
|
||||
autoRestartDevServerWhenIdle: parsed.data.autoRestartDevServerWhenIdle ?? false,
|
||||
@@ -242,6 +243,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
|
||||
enableCloudSync: false,
|
||||
enableExternalObjects: false,
|
||||
enableBuiltInAgents: false,
|
||||
enableDecisions: false,
|
||||
enableGoalsSidebarLink: false,
|
||||
enableServerInfoDebugView: false,
|
||||
autoRestartDevServerWhenIdle: false,
|
||||
|
||||
@@ -21,10 +21,14 @@ import type {
|
||||
RequestCheckboxConfirmationInteraction,
|
||||
RequestConfirmationInteraction,
|
||||
RequestConfirmationTarget,
|
||||
RequestItemVerdictsInteraction,
|
||||
RequestItemVerdictsResult,
|
||||
RequestItemVerdictsResultItem,
|
||||
RejectIssueThreadInteraction,
|
||||
RespondIssueThreadInteraction,
|
||||
SuggestTasksInteraction,
|
||||
SuggestTasksResultCreatedTask,
|
||||
SubmitIssueThreadInteractionVerdicts,
|
||||
} from "@paperclipai/shared";
|
||||
import {
|
||||
acceptIssueThreadInteractionSchema,
|
||||
@@ -37,8 +41,11 @@ import {
|
||||
requestCheckboxConfirmationResultSchema,
|
||||
requestConfirmationPayloadSchema,
|
||||
requestConfirmationResultSchema,
|
||||
requestItemVerdictsPayloadSchema,
|
||||
requestItemVerdictsResultSchema,
|
||||
suggestTasksPayloadSchema,
|
||||
suggestTasksResultSchema,
|
||||
submitIssueThreadInteractionVerdictsSchema,
|
||||
} from "@paperclipai/shared";
|
||||
import { conflict, notFound, unprocessable } from "../errors.js";
|
||||
import { getTelemetryClient } from "../telemetry.js";
|
||||
@@ -85,19 +92,32 @@ type RequestConfirmationLikeInteraction =
|
||||
| RequestConfirmationInteraction
|
||||
| RequestCheckboxConfirmationInteraction;
|
||||
|
||||
const USER_COMMENT_SUPERSEDABLE_INTERACTION_KINDS = [
|
||||
const TARGET_BOUND_INTERACTION_KINDS = [
|
||||
...REQUEST_CONFIRMATION_INTERACTION_KINDS,
|
||||
"request_item_verdicts",
|
||||
] as const;
|
||||
type TargetBoundInteractionKind = (typeof TARGET_BOUND_INTERACTION_KINDS)[number];
|
||||
type TargetBoundInteraction =
|
||||
| RequestConfirmationLikeInteraction
|
||||
| RequestItemVerdictsInteraction;
|
||||
|
||||
const USER_COMMENT_SUPERSEDABLE_INTERACTION_KINDS = [
|
||||
...TARGET_BOUND_INTERACTION_KINDS,
|
||||
"ask_user_questions",
|
||||
] as const;
|
||||
type UserCommentSupersedableKind = (typeof USER_COMMENT_SUPERSEDABLE_INTERACTION_KINDS)[number];
|
||||
type UserCommentSupersedableInteraction =
|
||||
| RequestConfirmationLikeInteraction
|
||||
| TargetBoundInteraction
|
||||
| AskUserQuestionsInteraction;
|
||||
|
||||
function isRequestConfirmationLikeKind(kind: string): kind is RequestConfirmationLikeKind {
|
||||
return (REQUEST_CONFIRMATION_INTERACTION_KINDS as readonly string[]).includes(kind);
|
||||
}
|
||||
|
||||
function isTargetBoundInteractionKind(kind: string): kind is TargetBoundInteractionKind {
|
||||
return (TARGET_BOUND_INTERACTION_KINDS as readonly string[]).includes(kind);
|
||||
}
|
||||
|
||||
function isUserCommentSupersedableKind(kind: string): kind is UserCommentSupersedableKind {
|
||||
return (USER_COMMENT_SUPERSEDABLE_INTERACTION_KINDS as readonly string[]).includes(kind);
|
||||
}
|
||||
@@ -167,6 +187,13 @@ function hydrateInteraction(
|
||||
payload: requestCheckboxConfirmationPayloadSchema.parse(row.payload),
|
||||
result: row.result ? requestCheckboxConfirmationResultSchema.parse(row.result) : null,
|
||||
} satisfies RequestCheckboxConfirmationInteraction;
|
||||
case "request_item_verdicts":
|
||||
return {
|
||||
...base,
|
||||
kind: "request_item_verdicts",
|
||||
payload: requestItemVerdictsPayloadSchema.parse(row.payload),
|
||||
result: row.result ? requestItemVerdictsResultSchema.parse(row.result) : null,
|
||||
} satisfies RequestItemVerdictsInteraction;
|
||||
default:
|
||||
throw unprocessable(`Unknown interaction kind: ${row.kind}`);
|
||||
}
|
||||
@@ -227,6 +254,14 @@ function normalizeCreateInteractionInput(input: CreateIssueThreadInteraction): C
|
||||
supersedeOnUserComment: input.payload.supersedeOnUserComment ?? true,
|
||||
},
|
||||
};
|
||||
case "request_item_verdicts":
|
||||
return {
|
||||
...input,
|
||||
payload: {
|
||||
...input.payload,
|
||||
supersedeOnUserComment: input.payload.supersedeOnUserComment ?? true,
|
||||
},
|
||||
};
|
||||
default:
|
||||
return input;
|
||||
}
|
||||
@@ -243,6 +278,17 @@ function buildSupersededByCommentResult(row: IssueThreadInteractionRow, commentI
|
||||
} as const;
|
||||
}
|
||||
|
||||
if (row.kind === "request_item_verdicts") {
|
||||
const interaction = hydrateInteraction(row) as RequestItemVerdictsInteraction;
|
||||
return {
|
||||
version: 1,
|
||||
outcome: "superseded_by_comment",
|
||||
complete: false,
|
||||
items: interaction.result?.items ?? [],
|
||||
commentId,
|
||||
} satisfies RequestItemVerdictsResult;
|
||||
}
|
||||
|
||||
return {
|
||||
version: 1,
|
||||
outcome: "superseded_by_comment",
|
||||
@@ -250,6 +296,28 @@ function buildSupersededByCommentResult(row: IssueThreadInteractionRow, commentI
|
||||
} as const;
|
||||
}
|
||||
|
||||
function buildStaleTargetResult(
|
||||
row: IssueThreadInteractionRow,
|
||||
staleTarget: RequestConfirmationTarget | null,
|
||||
) {
|
||||
if (row.kind === "request_item_verdicts") {
|
||||
const interaction = hydrateInteraction(row) as RequestItemVerdictsInteraction;
|
||||
return {
|
||||
version: 1,
|
||||
outcome: "stale_target",
|
||||
complete: false,
|
||||
items: interaction.result?.items ?? [],
|
||||
staleTarget,
|
||||
} satisfies RequestItemVerdictsResult;
|
||||
}
|
||||
|
||||
return {
|
||||
version: 1,
|
||||
outcome: "stale_target",
|
||||
staleTarget,
|
||||
} as const;
|
||||
}
|
||||
|
||||
function resolveActorKind(interaction: Pick<IssueThreadInteraction, "resolvedByAgentId" | "resolvedByUserId">) {
|
||||
if (interaction.resolvedByAgentId) return "agent";
|
||||
if (interaction.resolvedByUserId) return "user";
|
||||
@@ -263,10 +331,14 @@ function resolveCreatorKind(interaction: Pick<IssueThreadInteraction, "createdBy
|
||||
}
|
||||
|
||||
function deriveTargetType(interaction: IssueThreadInteraction) {
|
||||
if (interaction.kind !== "request_confirmation" && interaction.kind !== "request_checkbox_confirmation") {
|
||||
return "none";
|
||||
switch (interaction.kind) {
|
||||
case "request_confirmation":
|
||||
case "request_checkbox_confirmation":
|
||||
case "request_item_verdicts":
|
||||
return interaction.payload.target?.type ?? "none";
|
||||
default:
|
||||
return "none";
|
||||
}
|
||||
return interaction.payload.target?.type ?? "none";
|
||||
}
|
||||
|
||||
function deriveResolutionReason(interaction: IssueThreadInteraction) {
|
||||
@@ -284,8 +356,17 @@ function deriveResolutionReason(interaction: IssueThreadInteraction) {
|
||||
if (interaction.kind === "request_confirmation" || interaction.kind === "request_checkbox_confirmation") {
|
||||
return interaction.result?.outcome ?? "expired";
|
||||
}
|
||||
if (interaction.kind === "request_item_verdicts") {
|
||||
return interaction.result?.outcome ?? "expired";
|
||||
}
|
||||
return "expired";
|
||||
}
|
||||
case "answered": {
|
||||
if (interaction.kind === "request_item_verdicts") {
|
||||
return interaction.result?.outcome ?? "answered";
|
||||
}
|
||||
return "answered";
|
||||
}
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
@@ -315,6 +396,11 @@ function buildInteractionResolvedCounts(interaction: IssueThreadInteraction, arg
|
||||
questionCount: nonNegativeInteger(interaction.payload.questions.length),
|
||||
answeredQuestionCount: nonNegativeInteger(interaction.result?.answers?.length ?? 0),
|
||||
};
|
||||
case "request_item_verdicts":
|
||||
return {
|
||||
itemCount: nonNegativeInteger(interaction.payload.items.length),
|
||||
resolvedItemCount: nonNegativeInteger(interaction.result?.items?.length ?? 0),
|
||||
};
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
@@ -507,6 +593,68 @@ function resolveSelectedCheckboxConfirmationOptions(args: {
|
||||
.map((option) => option.id);
|
||||
}
|
||||
|
||||
function resolveRequestItemVerdictSubmissions(args: {
|
||||
interaction: RequestItemVerdictsInteraction;
|
||||
input: SubmitIssueThreadInteractionVerdicts;
|
||||
actor: InteractionActor;
|
||||
now: Date;
|
||||
}) {
|
||||
if (!args.actor.userId) {
|
||||
throw unprocessable("request_item_verdicts submissions require a user actor");
|
||||
}
|
||||
|
||||
const existingItems = args.interaction.result?.items ?? [];
|
||||
const existingById = new Map(existingItems.map((item) => [item.id, item] as const));
|
||||
const payloadItemIds = new Set(args.interaction.payload.items.map((item) => item.id));
|
||||
const enabledVerdicts = new Set(args.interaction.payload.verdicts ?? ["approve", "reject"]);
|
||||
const requireReasonOn = new Set(args.interaction.payload.requireReasonOn ?? ["reject"]);
|
||||
const newlyResolvedById = new Map<string, RequestItemVerdictsResultItem>();
|
||||
const newlyResolvedItemIds: string[] = [];
|
||||
|
||||
for (const submitted of args.input.verdicts) {
|
||||
if (!payloadItemIds.has(submitted.id)) {
|
||||
throw unprocessable(`Unknown item verdict id: ${submitted.id}`);
|
||||
}
|
||||
if (existingById.has(submitted.id)) {
|
||||
continue;
|
||||
}
|
||||
if (!enabledVerdicts.has(submitted.verdict)) {
|
||||
throw unprocessable(`Verdict ${submitted.verdict} is not enabled for this item verdict request`);
|
||||
}
|
||||
|
||||
const reason = submitted.reason?.trim() ?? "";
|
||||
if (requireReasonOn.has(submitted.verdict) && reason.length === 0) {
|
||||
throw unprocessable(`A reason is required when verdict is ${submitted.verdict}`);
|
||||
}
|
||||
|
||||
if (newlyResolvedById.has(submitted.id)) {
|
||||
continue;
|
||||
}
|
||||
newlyResolvedById.set(submitted.id, {
|
||||
id: submitted.id,
|
||||
verdict: submitted.verdict,
|
||||
...(reason ? { reason } : {}),
|
||||
resolvedByUserId: args.actor.userId,
|
||||
resolvedAt: args.now,
|
||||
});
|
||||
newlyResolvedItemIds.push(submitted.id);
|
||||
}
|
||||
|
||||
const nextById = new Map<string, RequestItemVerdictsResultItem>(existingItems.map((item) => [item.id, item]));
|
||||
for (const [id, item] of newlyResolvedById) {
|
||||
nextById.set(id, item);
|
||||
}
|
||||
const items = args.interaction.payload.items
|
||||
.map((item) => nextById.get(item.id))
|
||||
.filter((item): item is RequestItemVerdictsResultItem => Boolean(item));
|
||||
|
||||
return {
|
||||
items,
|
||||
complete: items.length === args.interaction.payload.items.length,
|
||||
newlyResolvedItemIds,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeQuestionAnswers(args: {
|
||||
questions: AskUserQuestionsInteraction["payload"]["questions"];
|
||||
answers: RespondIssueThreadInteraction["answers"];
|
||||
@@ -653,8 +801,8 @@ async function expireStaleRequestConfirmationTarget(db: Db | any, args: {
|
||||
row: IssueThreadInteractionRow;
|
||||
actor: InteractionActor;
|
||||
}): Promise<IssueThreadInteraction | null> {
|
||||
if (!isRequestConfirmationLikeKind(args.row.kind) || args.row.status !== "pending") return null;
|
||||
const interaction = hydrateInteraction(args.row) as RequestConfirmationLikeInteraction;
|
||||
if (!isTargetBoundInteractionKind(args.row.kind) || args.row.status !== "pending") return null;
|
||||
const interaction = hydrateInteraction(args.row) as TargetBoundInteraction;
|
||||
const target = interaction.payload.target ?? null;
|
||||
if (!target) return null;
|
||||
if (target.type !== "issue_document") return null;
|
||||
@@ -686,9 +834,7 @@ async function expireStaleRequestConfirmationTarget(db: Db | any, args: {
|
||||
}
|
||||
: interaction.payload,
|
||||
result: {
|
||||
version: 1,
|
||||
outcome: "stale_target",
|
||||
staleTarget: target,
|
||||
...buildStaleTargetResult(args.row, target),
|
||||
},
|
||||
resolvedByAgentId: args.actor.agentId ?? null,
|
||||
resolvedByUserId: args.actor.userId ?? null,
|
||||
@@ -1002,7 +1148,11 @@ export function issueThreadInteractionService(db: Db) {
|
||||
}
|
||||
}
|
||||
|
||||
if (data.kind === "request_confirmation" || data.kind === "request_checkbox_confirmation") {
|
||||
if (
|
||||
data.kind === "request_confirmation"
|
||||
|| data.kind === "request_checkbox_confirmation"
|
||||
|| data.kind === "request_item_verdicts"
|
||||
) {
|
||||
await assertRequestConfirmationTargetIsCurrent(db, {
|
||||
companyId: issue.companyId,
|
||||
issueId: issue.id,
|
||||
@@ -1274,6 +1424,106 @@ export function issueThreadInteractionService(db: Db) {
|
||||
}
|
||||
},
|
||||
|
||||
submitItemVerdicts: async (
|
||||
issue: { id: string; companyId: string },
|
||||
interactionId: string,
|
||||
input: SubmitIssueThreadInteractionVerdicts,
|
||||
actor: InteractionActor,
|
||||
): Promise<{ interaction: IssueThreadInteraction; newlyResolvedItemIds: string[] }> => {
|
||||
const data = submitIssueThreadInteractionVerdictsSchema.parse(input);
|
||||
const submission = await db.transaction(async (tx) => {
|
||||
const current = await tx
|
||||
.select()
|
||||
.from(issueThreadInteractions)
|
||||
.where(eq(issueThreadInteractions.id, interactionId))
|
||||
.for("update")
|
||||
.then((rows) => rows[0] ?? null);
|
||||
|
||||
if (!current) throw notFound("Interaction not found");
|
||||
if (current.companyId !== issue.companyId || current.issueId !== issue.id) {
|
||||
throw notFound("Interaction not found");
|
||||
}
|
||||
if (current.kind !== "request_item_verdicts") {
|
||||
throw unprocessable("Only request_item_verdicts interactions can receive item verdicts");
|
||||
}
|
||||
|
||||
const interaction = hydrateInteraction(current) as RequestItemVerdictsInteraction;
|
||||
if (current.status !== "pending") {
|
||||
if (current.status === "answered") {
|
||||
const resolvedIds = new Set(interaction.result?.items.map((item) => item.id) ?? []);
|
||||
const payloadIds = new Set(interaction.payload.items.map((item) => item.id));
|
||||
for (const submitted of data.verdicts) {
|
||||
if (!payloadIds.has(submitted.id)) {
|
||||
throw unprocessable(`Unknown item verdict id: ${submitted.id}`);
|
||||
}
|
||||
if (!resolvedIds.has(submitted.id)) {
|
||||
throw conflict("Interaction has already been resolved");
|
||||
}
|
||||
}
|
||||
return { interaction, newlyResolvedItemIds: [], resolved: false };
|
||||
}
|
||||
throw conflict("Interaction has already been resolved");
|
||||
}
|
||||
|
||||
const expired = await expireStaleRequestConfirmationTarget(tx, {
|
||||
row: current,
|
||||
actor,
|
||||
});
|
||||
if (expired) {
|
||||
return { interaction: expired, newlyResolvedItemIds: [], resolved: false };
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const { items, complete, newlyResolvedItemIds } = resolveRequestItemVerdictSubmissions({
|
||||
interaction,
|
||||
input: data,
|
||||
actor,
|
||||
now,
|
||||
});
|
||||
if (newlyResolvedItemIds.length === 0) {
|
||||
return { interaction, newlyResolvedItemIds: [], resolved: false };
|
||||
}
|
||||
|
||||
const result = {
|
||||
version: 1,
|
||||
outcome: "resolved",
|
||||
complete,
|
||||
items,
|
||||
} satisfies RequestItemVerdictsResult;
|
||||
const [updated] = await tx
|
||||
.update(issueThreadInteractions)
|
||||
.set({
|
||||
status: complete ? "answered" : "pending",
|
||||
result,
|
||||
resolvedByAgentId: complete ? actor.agentId ?? null : null,
|
||||
resolvedByUserId: complete ? actor.userId ?? null : null,
|
||||
resolvedAt: complete ? now : null,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(and(
|
||||
eq(issueThreadInteractions.id, interactionId),
|
||||
eq(issueThreadInteractions.status, "pending"),
|
||||
))
|
||||
.returning();
|
||||
|
||||
if (!updated) {
|
||||
throw conflict("Interaction has already been resolved");
|
||||
}
|
||||
|
||||
await touchIssue(tx, issue.id);
|
||||
return {
|
||||
interaction: hydrateInteraction(updated),
|
||||
newlyResolvedItemIds,
|
||||
resolved: complete,
|
||||
};
|
||||
});
|
||||
|
||||
if (submission.resolved) {
|
||||
await emitInteractionResolvedTelemetry(db, submission.interaction);
|
||||
}
|
||||
return submission;
|
||||
},
|
||||
|
||||
rejectSuggestedTasks: async (
|
||||
issue: { id: string; companyId: string },
|
||||
interactionId: string,
|
||||
@@ -1447,6 +1697,8 @@ export function issueThreadInteractionService(db: Db) {
|
||||
const confirmationRowIds = commentRows
|
||||
.filter((row) => isRequestConfirmationLikeKind(row.kind))
|
||||
.map((row) => row.id);
|
||||
const itemVerdictRows = commentRows
|
||||
.filter((row) => row.kind === "request_item_verdicts");
|
||||
|
||||
if (questionRowIds.length > 0) {
|
||||
const sampleQuestionRow = commentRows.find((row) => row.kind === "ask_user_questions");
|
||||
@@ -1489,6 +1741,25 @@ export function issueThreadInteractionService(db: Db) {
|
||||
.returning();
|
||||
expired.push(...updatedRows.map(hydrateInteraction));
|
||||
}
|
||||
|
||||
for (const row of itemVerdictRows) {
|
||||
const [updated] = await db
|
||||
.update(issueThreadInteractions)
|
||||
.set({
|
||||
status: "expired",
|
||||
result: buildSupersededByCommentResult(row, comment.id),
|
||||
resolvedByAgentId: null,
|
||||
resolvedByUserId: comment.authorUserId,
|
||||
resolvedAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(and(
|
||||
eq(issueThreadInteractions.id, row.id),
|
||||
eq(issueThreadInteractions.status, "pending"),
|
||||
))
|
||||
.returning();
|
||||
if (updated) expired.push(hydrateInteraction(updated));
|
||||
}
|
||||
}
|
||||
|
||||
if (expired.length > 0) {
|
||||
@@ -1509,12 +1780,12 @@ export function issueThreadInteractionService(db: Db) {
|
||||
.where(and(
|
||||
eq(issueThreadInteractions.companyId, issue.companyId),
|
||||
eq(issueThreadInteractions.issueId, issue.id),
|
||||
inArray(issueThreadInteractions.kind, [...REQUEST_CONFIRMATION_INTERACTION_KINDS]),
|
||||
inArray(issueThreadInteractions.kind, [...TARGET_BOUND_INTERACTION_KINDS]),
|
||||
eq(issueThreadInteractions.status, "pending"),
|
||||
));
|
||||
|
||||
const staleRows = rows.filter((row) => {
|
||||
const interaction = hydrateInteraction(row) as RequestConfirmationLikeInteraction;
|
||||
const interaction = hydrateInteraction(row) as TargetBoundInteraction;
|
||||
const target = interaction.payload.target;
|
||||
if (!target || target.type !== "issue_document") return false;
|
||||
const targetIssueId = target.issueId ?? issue.id;
|
||||
@@ -1533,7 +1804,7 @@ export function issueThreadInteractionService(db: Db) {
|
||||
const now = new Date();
|
||||
const expired: IssueThreadInteraction[] = [];
|
||||
for (const row of staleRows) {
|
||||
const interaction = hydrateInteraction(row) as RequestConfirmationLikeInteraction;
|
||||
const interaction = hydrateInteraction(row) as TargetBoundInteraction;
|
||||
const target = interaction.payload.target ?? null;
|
||||
const currentTarget = buildIssueDocumentTargetFromDocument({
|
||||
issueId: issue.id,
|
||||
@@ -1549,11 +1820,7 @@ export function issueThreadInteractionService(db: Db) {
|
||||
target: currentTarget,
|
||||
}
|
||||
: interaction.payload,
|
||||
result: {
|
||||
version: 1,
|
||||
outcome: "stale_target",
|
||||
staleTarget: target,
|
||||
},
|
||||
result: buildStaleTargetResult(row, target),
|
||||
resolvedByAgentId: actor.agentId ?? null,
|
||||
resolvedByUserId: actor.userId ?? null,
|
||||
resolvedAt: now,
|
||||
|
||||
Reference in new issue
Block a user