Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
feat: page the enrichment queue (CMP-92) (#160)
github-actions[bot]8c1abb14f4a6
diff --git a/.github/workflows/pr-title.yml b/.github/workflows/pr-title.ymlindex 023627be..c289adbe 100644--- a/.github/workflows/pr-title.yml+++ b/.github/workflows/pr-title.yml@@ -61,10 +61,24 @@ jobs:body=$(printf '%s\n\n<!-- pr-title: %s -->\n' \"$(printf '%s\n' "$body" | grep -v '^<!-- pr-title: ' || true)" "$title")- gh pr edit "$NUMBER" --title "$title" --body "$body"- echo "written=true" >> "$GITHUB_OUTPUT"- echo "Retitled #$NUMBER to \`$title\`, because $reason." >> "$GITHUB_STEP_SUMMARY"+ if gh pr edit "$NUMBER" --title "$title" --body "$body"; then+ echo "written=true" >> "$GITHUB_OUTPUT"+ echo "Retitled #$NUMBER to \`$title\`, because $reason." >> "$GITHUB_STEP_SUMMARY"+ exit 0+ fi++ {+ echo "The title needs changing, because $reason, but this workflow"+ echo "could not write it. Set it by hand:"+ echo+ echo '```'+ echo "$title"+ echo '```'+ echo+ echo "A fork pull request grants a read-only token, which is the usual"+ echo "cause. Check the step log for what the API returned."+ } >> "$GITHUB_STEP_SUMMARY"- uses: amannn/action-semantic-pull-request@v6id: lintdiff --git a/apps/api/src/enrichment/enrichment.router.ts b/apps/api/src/enrichment/enrichment.router.tsindex 5276bef8..9d1e2fae 100644--- a/apps/api/src/enrichment/enrichment.router.ts+++ b/apps/api/src/enrichment/enrichment.router.ts@@ -1,5 +1,7 @@+import { enrichmentQueueInput } from "@crm/validation/enrichment-queue";import { Inject } from "@nestjs/common";-import { Query, Router, UseMiddlewares } from "nestjs-trpc";+import { Input, Query, Router, UseMiddlewares } from "nestjs-trpc";+import type { z } from "zod";import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";import { EnrichmentService } from "./enrichment.service";@@ -10,8 +12,8 @@ export class EnrichmentRouter {@Inject(EnrichmentService) private readonly enrichment: EnrichmentService,) {}- @Query()- async queue() {- return this.enrichment.queue();+ @Query({ input: enrichmentQueueInput })+ async queue(@Input() input: z.infer<typeof enrichmentQueueInput>) {+ return this.enrichment.queue(input.limit);}}diff --git a/apps/api/src/enrichment/enrichment.service.ts b/apps/api/src/enrichment/enrichment.service.tsindex ba51ae8b..65dc1af9 100644--- a/apps/api/src/enrichment/enrichment.service.ts+++ b/apps/api/src/enrichment/enrichment.service.ts@@ -1,4 +1,5 @@import type { Db, Prisma } from "@crm/db";+import { ENRICHMENT_PAGE, pageSize } from "@crm/validation/enrichment-queue";import { Injectable } from "@nestjs/common";import { InjectDatabase } from "../database/database.constants";import {@@ -8,10 +9,6 @@ import {enrichmentQueueState,} from "./enrichment-copy";-const QUEUE_ROWS = 20;--const SCHEDULED_ROWS = 20;-export type EnrichmentQueueSubject =| {kind: "contact";@@ -76,7 +73,8 @@ type QueuedTask = {export class EnrichmentService {constructor(@InjectDatabase() private readonly db: Db) {}- async queue(): Promise<EnrichmentQueue> {+ async queue(limit: number = ENRICHMENT_PAGE): Promise<EnrichmentQueue> {+ const take = pageSize(limit);const now = new Date();const named: Prisma.AgentTaskWhereInput = {@@ -98,14 +96,14 @@ export class EnrichmentService {this.db.agentTask.findMany({where: dueWhere,orderBy: [{ priority: "desc" }, { dueAt: "asc" }],- take: QUEUE_ROWS,+ take,select: TASK_SELECT,}),this.db.agentTask.count({ where: dueWhere }),this.db.agentTask.findMany({where: scheduledWhere,orderBy: [{ dueAt: "asc" }],- take: SCHEDULED_ROWS,+ take,select: TASK_SELECT,}),this.db.agentTask.count({ where: scheduledWhere }),diff --git a/apps/api/src/generated/server.ts b/apps/api/src/generated/server.tsindex 84a6eed8..e4369caf 100644--- a/apps/api/src/generated/server.ts+++ b/apps/api/src/generated/server.ts@@ -21,6 +21,7 @@ import { conversationListInput, builderResourceSearchInput, conversationIdInput,import { setReportingCurrencyInput, setManualRateInput, removeManualRateInput } from "../currency/currency.contracts";import { dashboardSummaryInput } from "../dashboard/dashboard.contracts";import { dealListInput, dealIdInput, dealCreateInput, dealUpdateArgs, setStageInput, dealContactsInput, dealAttachContactInput, dealDetachContactInput, dealContactRoleInput, dealBulkOwnerInput, dealBulkStageInput, dealBulkInput } from "../deals/deals.contracts";+import { enrichmentQueueInput } from "@crm/validation/enrichment-queue";import { fieldListInput, fieldByKeyInput, fieldIdInput, fieldCreateInput, fieldUpdateArgs, fieldReorderInput } from "../fields/fields.contracts";import { setAutoCreateInput, suppressDomainInput, threadInput, calendarEventInput } from "../google/google.contracts";import { setOutlookAutoCreateInput } from "../microsoft/microsoft.contracts";@@ -304,6 +305,7 @@ const appRouter = t.router({}),enrichment: t.router({queue: publicProcedure+ .input(enrichmentQueueInput).query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<EnrichmentRouter["queue"]>>)}),fields: t.router({diff --git a/apps/api/test/enrichment-queue.spec.ts b/apps/api/test/enrichment-queue.spec.tsindex 6e619157..dbece0ab 100644--- a/apps/api/test/enrichment-queue.spec.ts+++ b/apps/api/test/enrichment-queue.spec.ts@@ -1,5 +1,11 @@import { afterAll, beforeAll, describe, expect, it } from "bun:test";import { db } from "@crm/db";+import {+ ENRICHMENT_PAGE,+ ENRICHMENT_PAGE_MAX,+ enrichmentQueueInput,+ pageSize,+} from "@crm/validation/enrichment-queue";import { EnrichmentService } from "../src/enrichment/enrichment.service";const suffix = process.env.TEST_RUN_ID ?? "enrichment-queue-spec";@@ -11,6 +17,8 @@ const enrichment = new EnrichmentService(db);const DAY_MS = 86_400_000;+const EXTRA_ROWS = 8;+let contactId: string;let companyId: string;let dueId: string;@@ -19,6 +27,9 @@ let scheduledId: string;async function clean() {await db.agentTask.deleteMany({ where: { kind } });await db.contact.deleteMany({ where: { email } });+ await db.contact.deleteMany({+ where: { email: { endsWith: `-${suffix}@example.test` } },+ });await db.company.deleteMany({ where: { name } });}@@ -60,6 +71,27 @@ beforeAll(async () => {dueId = due.id;scheduledId = scheduled.id;++ for (let index = 0; index < EXTRA_ROWS; index++) {+ const extra = await db.contact.create({+ data: {+ firstName: "Queue",+ lastName: `Page ${index}`,+ email: `page-${index}-${suffix}@example.test`,+ },+ select: { id: true },+ });++ await db.agentTask.create({+ data: {+ kind,+ reason: "due now",+ dueAt: new Date(Date.now() - 60_000),+ budget: 4,+ contactId: extra.id,+ },+ });+ }});afterAll(clean);@@ -96,4 +128,62 @@ describe("what the enrichment widget reads", () => {expect(row?.subject.id).toBe(companyId);expect(row?.line).toBe("Waiting");});++ it("hands back exactly the number of rows asked for", async () => {+ const queue = await enrichment.queue(3);++ expect(queue.rows).toHaveLength(3);+ expect(queue.total).toBeGreaterThan(3);+ });++ it("counts every due task, not only the ones it returned", async () => {+ const page = await enrichment.queue(3);+ const all = await enrichment.queue(EXTRA_ROWS + 10);++ expect(page.total).toBe(all.total);+ expect(all.rows.length).toBeGreaterThan(page.rows.length);+ });++ it("treats a nonsense limit as one row, never as none", async () => {+ expect(await enrichment.queue(0)).toHaveProperty("rows.length", 1);+ expect(await enrichment.queue(-5)).toHaveProperty("rows.length", 1);+ });++ it("reads the whole page when asked for more than exists", async () => {+ const queue = await enrichment.queue(ENRICHMENT_PAGE_MAX);++ expect(queue.rows).toHaveLength(Math.min(queue.total, ENRICHMENT_PAGE_MAX));+ });+});++describe("the page size the queue will accept", () => {+ it("never returns nothing", () => {+ expect(pageSize(0)).toBe(1);+ expect(pageSize(-100)).toBe(1);+ });++ it("never reads past the maximum", () => {+ expect(pageSize(10_000)).toBe(ENRICHMENT_PAGE_MAX);+ expect(pageSize(ENRICHMENT_PAGE_MAX + 1)).toBe(ENRICHMENT_PAGE_MAX);+ });++ it("keeps a sane request as it is", () => {+ expect(pageSize(1)).toBe(1);+ expect(pageSize(20)).toBe(20);+ expect(pageSize(ENRICHMENT_PAGE_MAX)).toBe(ENRICHMENT_PAGE_MAX);+ });++ it("drops part rows and refuses a number that is not one", () => {+ expect(pageSize(7.9)).toBe(7);+ expect(pageSize(Number.NaN)).toBe(ENRICHMENT_PAGE);+ expect(pageSize(Number.POSITIVE_INFINITY)).toBe(ENRICHMENT_PAGE);+ });++ it("refuses a limit past the maximum at the boundary", () => {+ expect(enrichmentQueueInput.safeParse({ limit: 10_000 }).success).toBe(+ false,+ );+ expect(enrichmentQueueInput.safeParse({ limit: 0 }).success).toBe(false);+ expect(enrichmentQueueInput.parse({}).limit).toBe(ENRICHMENT_PAGE);+ });});diff --git a/apps/app/components/enrichment-queue.tsx b/apps/app/components/enrichment-queue.tsxindex a09f0962..8044ebe8 100644--- a/apps/app/components/enrichment-queue.tsx+++ b/apps/app/components/enrichment-queue.tsx@@ -22,10 +22,14 @@ import {type StatusTone,} from "@crm/ui/components/status-indicator";import { cn } from "@crm/ui/lib/utils";-import { useQuery } from "@tanstack/react-query";+import {+ ENRICHMENT_PAGE,+ ENRICHMENT_PAGE_MAX,+} from "@crm/validation/enrichment-queue";+import { keepPreviousData, useQuery } from "@tanstack/react-query";import { useState } from "react";import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";-import { elapsedLabel } from "@/lib/enrichment-queue";+import { elapsedLabel, queueFooter } from "@/lib/enrichment-queue";import {ENRICHMENT_IDLE_POLL_MS,ENRICHMENT_POLL_MS,@@ -51,9 +55,11 @@ export function EnrichmentQueue() {const openRecord = useOpenRecord();const [open, setOpen] = useState(false);const [expanded, setExpanded] = useState(false);+ const [limit, setLimit] = useState(ENRICHMENT_PAGE);const queue = useQuery({- ...trpc.enrichment.queue.queryOptions(),+ ...trpc.enrichment.queue.queryOptions({ limit }),+ placeholderData: keepPreviousData,refetchInterval: (query) =>(query.state.data?.total ?? 0) > 0? ENRICHMENT_POLL_MS@@ -65,21 +71,28 @@ export function EnrichmentQueue() {const scheduled = queue.data?.scheduled ?? [];const scheduledTotal = queue.data?.scheduledTotal ?? 0;const visible = expanded ? rows : rows.slice(0, VISIBLE_ROWS);- const hidden = rows.length - visible.length;- const more = total - visible.length;+ const footer = queueFooter({+ total,+ fetched: rows.length,+ shown: visible.length,+ limit,+ });- const openSubject = (subject: QueueSubject) => {+ const close = () => {setOpen(false);+ setExpanded(false);+ setLimit(ENRICHMENT_PAGE);+ };++ const openSubject = (subject: QueueSubject) => {+ close();openRecord({ kind: subject.kind, id: subject.id });};return (<Popoveropen={open}- onOpenChange={(next) => {- setOpen(next);- if (!next) setExpanded(false);- }}+ onOpenChange={(next) => (next ? setOpen(true) : close())}><PopoverTrigger asChild><Button variant="outline" size="sm">@@ -119,10 +132,12 @@ export function EnrichmentQueue() {/>)}- {more > 0 ? (+ {footer.more > 0 ? (<div className="flex items-center justify-between px-4 py-3 text-xs">- <span className="text-muted-foreground">{more} more queued</span>- {hidden > 0 ? (+ <span className="text-muted-foreground">+ {footer.more} more queued+ </span>+ {footer.action === "show-all" ? (<buttontype="button"className="cursor-pointer text-primary"@@ -131,6 +146,19 @@ export function EnrichmentQueue() {Show all</button>) : null}+ {footer.action === "load-more" ? (+ <button+ type="button"+ className="cursor-pointer text-primary"+ onClick={() =>+ setLimit((current) =>+ Math.min(current + ENRICHMENT_PAGE, ENRICHMENT_PAGE_MAX),+ )+ }+ >+ Load more+ </button>+ ) : null}</div>) : null}diff --git a/apps/app/lib/enrichment-queue.ts b/apps/app/lib/enrichment-queue.tsindex ebdf1619..26b81b75 100644--- a/apps/app/lib/enrichment-queue.ts+++ b/apps/app/lib/enrichment-queue.ts@@ -1,9 +1,33 @@+import { ENRICHMENT_PAGE_MAX } from "@crm/validation/enrichment-queue";+const SECOND_MS = 1_000;const MINUTE_S = 60;const HOUR_S = 60 * MINUTE_S;export const NO_ELAPSED = "—";+export type QueueFooter = {+ more: number;+ action: "show-all" | "load-more" | "none";+};++export function queueFooter(input: {+ total: number;+ fetched: number;+ shown: number;+ limit: number;+}): QueueFooter {+ const more = Math.max(0, input.total - input.shown);+ if (more === 0) return { more: 0, action: "none" };++ if (input.fetched > input.shown) return { more, action: "show-all" };++ return {+ more,+ action: input.limit < ENRICHMENT_PAGE_MAX ? "load-more" : "none",+ };+}+export function formatElapsed(seconds: number): string {const whole = Math.max(0, Math.floor(seconds));const minutes = Math.floor((whole % HOUR_S) / MINUTE_S);diff --git a/apps/app/test/enrichment-queue.spec.ts b/apps/app/test/enrichment-queue.spec.tsindex 70ca7f4b..8038a025 100644--- a/apps/app/test/enrichment-queue.spec.ts+++ b/apps/app/test/enrichment-queue.spec.ts@@ -3,6 +3,7 @@ import {elapsedLabel,formatElapsed,NO_ELAPSED,+ queueFooter,} from "../lib/enrichment-queue";describe("how long a lookup has been going", () => {@@ -57,3 +58,43 @@ describe("what the meta slot shows", () => {expect(elapsedLabel("running", "not a date", now)).toBe(NO_ELAPSED);});});++describe("what the queue footer offers", () => {+ it("says nothing when every row is on screen", () => {+ expect(queueFooter({ total: 3, fetched: 3, shown: 3, limit: 20 })).toEqual({+ more: 0,+ action: "none",+ });+ });++ it("offers to show the rows already fetched", () => {+ expect(+ queueFooter({ total: 12, fetched: 12, shown: 5, limit: 20 }),+ ).toEqual({ more: 7, action: "show-all" });+ });++ it("offers to fetch the rows the server held back", () => {+ expect(+ queueFooter({ total: 60, fetched: 20, shown: 20, limit: 20 }),+ ).toEqual({ more: 40, action: "load-more" });+ });++ it("shows the rows it has before fetching more", () => {+ expect(+ queueFooter({ total: 60, fetched: 20, shown: 5, limit: 20 }),+ ).toEqual({ more: 55, action: "show-all" });+ });++ it("stops offering once the page maximum is reached", () => {+ expect(+ queueFooter({ total: 500, fetched: 200, shown: 200, limit: 200 }),+ ).toEqual({ more: 300, action: "none" });+ });++ it("never promises a negative number of rows", () => {+ expect(queueFooter({ total: 0, fetched: 5, shown: 5, limit: 20 })).toEqual({+ more: 0,+ action: "none",+ });+ });+});diff --git a/packages/validation/package.json b/packages/validation/package.jsonindex 105f3b29..0ab67f1f 100644--- a/packages/validation/package.json+++ b/packages/validation/package.json@@ -9,6 +9,7 @@"./agent-events": "./src/agent-events.ts","./agent-manifest": "./src/agent-manifest.ts","./builder-question": "./src/builder-question.ts",+ "./enrichment-queue": "./src/enrichment-queue.ts","./eve-stream": "./src/eve-stream.ts","./eve-tool": "./src/eve-tool.ts"},diff --git a/packages/validation/src/enrichment-queue.ts b/packages/validation/src/enrichment-queue.tsnew file mode 100644index 00000000..d465c4e9--- /dev/null+++ b/packages/validation/src/enrichment-queue.ts@@ -0,0 +1,22 @@+import { z } from "zod";++export const ENRICHMENT_PAGE = 20;++export const ENRICHMENT_PAGE_MAX = 200;++export const enrichmentQueueInput = z.object({+ limit: z+ .number()+ .int()+ .min(1)+ .max(ENRICHMENT_PAGE_MAX)+ .default(ENRICHMENT_PAGE),+});++export type EnrichmentQueueInput = z.infer<typeof enrichmentQueueInput>;++export function pageSize(limit: number): number {+ if (!Number.isFinite(limit)) return ENRICHMENT_PAGE;++ return Math.min(Math.max(1, Math.trunc(limit)), ENRICHMENT_PAGE_MAX);+}