Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

refactor(agent): enhance image handling and clean up code

Lewis Carhart29685995058e
diff --git a/.env.example b/.env.example
index 0fa8c177..1317408d 100644
--- a/.env.example
+++ b/.env.example
@@ -73,12 +73,26 @@ GOOGLE_CLIENT_SECRET=""
# Any classic token with no scopes will do.
# GITHUB_TOKEN=""
-# Vercel Blob — mirrors profile pictures so they survive the source going away.
-# Without it, avatars are linked rather than copied.
+# Vercel Blob — where every logo and profile picture in the CRM is kept.
+#
+# The URLs these arrive on are somebody else's: LinkedIn signs theirs with an
+# expiry a few weeks out, a brand CDN is a rate limit on a page that draws forty
+# logos, and a company's own favicon is served by a company with no idea we are
+# drawing it. So the bytes are copied once and the record points at our copy.
+#
+# Read by the agent, by the API — which writes a favicon and a signed-in user's
+# Google avatar — and by the seed. Not by the Next.js app, which only needs to
+# recognise one of our URLs to route it through the image optimizer.
+#
+# Without it, a contact's photograph is not stored at all, because a URL that
+# works today and 404s next month is worse than initials and nobody can tell
+# which it will be. Everything else — logos, favicons, avatars — keeps the
+# origin's URL and renders as an ordinary hotlinked image.
# BLOB_READ_WRITE_TOKEN=""
# The model the agent runs on is reached through the Vercel AI Gateway. On
# Vercel this is handled by OIDC and needs nothing; elsewhere, set a key.
+# Which model is a setting, not a variable — change it on the settings page.
# https://vercel.com/docs/ai-gateway
# AI_GATEWAY_API_KEY=""
diff --git a/apps/agent/agent/agent.ts b/apps/agent/agent/agent.ts
index 66ed610d..0f179305 100644
--- a/apps/agent/agent/agent.ts
+++ b/apps/agent/agent/agent.ts
@@ -1,30 +1,10 @@
import "@crm/env/load";
-import { defineAgent } from "eve";
+import { DEFAULT_AGENT_MODEL } from "@crm/db/settings";
+import { defineAgent, defineDynamic } from "eve";
import { capabilities } from "./lib/capabilities";
+import { selectedModel } from "./lib/model";
-/**
- * The people-research agent.
- *
- * Sonnet rather than a frontier model: the hard part here is not reasoning, it
- * is refusing to accept a plausible-looking wrong answer, and that is enforced
- * by the tools and the skill rather than by model strength. Revisit if the
- * identity-matching evals say otherwise.
- *
- * A plain model id routes through the Vercel AI Gateway, authenticated by
- * project OIDC — so on Vercel there is no provider key to manage. Elsewhere,
- * set `AI_GATEWAY_API_KEY`.
- */
-
-/**
- * Says which outside sources are on, once, at startup.
- *
- * Every one of them is optional and the agent is designed to run with none, so
- * the thing a self-hoster needs is not a warning — it is a plain statement of
- * what this install can see, printed where they are already looking. Silence
- * would leave "the agent found nothing" and "the agent had nowhere to look"
- * indistinguishable.
- */
for (const capability of capabilities()) {
console.log(
`[agent] ${capability.enabled ? "on " : "off"} ${capability.label} (${capability.env})`,
@@ -32,5 +12,8 @@ for (const capability of capabilities()) {
}
export default defineAgent({
- model: "anthropic/claude-sonnet-5",
+ model: defineDynamic({
+ fallback: DEFAULT_AGENT_MODEL.id,
+ events: { "session.started": () => selectedModel() },
+ }),
});
diff --git a/apps/agent/agent/channels/crm.ts b/apps/agent/agent/channels/crm.ts
index eeade9e4..27872f10 100644
--- a/apps/agent/agent/channels/crm.ts
+++ b/apps/agent/agent/channels/crm.ts
@@ -3,26 +3,10 @@ import { defineChannel, POST } from "eve/channels";
import { settle } from "../lib/enrichment";
import { completeTask, taskSubject } from "../lib/tasks";
-/**
- * The CRM itself, as a place work arrives from.
- *
- * The dispatcher needs a channel to hand a task to, and the built-in HTTP
- * channel is not one: it answers requests, it has no `receive` hook, and there
- * is nothing to deliver a reply *to*. This is the other shape — a channel whose
- * whole job is to start a durable session and let the tools do the writing.
- *
- * There is deliberately no delivery. A run that identifies somebody has already
- * succeeded by the time it would have something to say, because success is a
- * fact on a record rather than a message to a person. If this ever needs to
- * tell somebody something, the timeline is where it goes.
- */
-
-/** The token format this channel owns. eve namespaces it by file stem. */
function taskToken(taskId: string): string {
return `crm:task:${taskId}`;
}
-/** The task a session is working for, or null if it is not working for one. */
function taskFromToken(token: string | undefined): string | null {
if (!token) return null;
const prefix = "crm:task:";
@@ -30,24 +14,6 @@ function taskFromToken(token: string | undefined): string | null {
}
export default defineChannel({
- /**
- * Work reaches this channel by hand-off from the dispatcher, not by request
- * — the API queues a row, it does not call us. So this route is not an entry
- * point and refuses everything.
- *
- * It exists because eve builds its channel registry *from routes*: one
- * manifest entry per method/path pair. With `routes: []` the channel
- * compiles to nothing, never registers, and `receive(crm, …)` fails with
- * "the channel passed as the first argument is not registered in this
- * agent's channels/" — which reads like a bad import and is not one.
- * Nothing reports it: `resolveTargetByReference` matches on object
- * identity, its `createRouteFingerprint` fallback returns null for an empty
- * route set, and a channel contributing no routes is not a discovery error,
- * so `diagnostics` stays at zero while every dispatched task fails.
- *
- * Registering this way is what keeps the hand-off working; if eve gains a
- * way to register a routeless channel, this goes.
- */
routes: [
POST(
"/internal/crm/dispatch-only",
@@ -55,28 +21,12 @@ export default defineChannel({
),
],
- /**
- * A turn ending is what retires the row.
- *
- * The dispatcher cannot do it: `receive` returns a `Session` the moment the
- * message is accepted, so awaiting it says the work *started*, never that it
- * finished. Completing there would retire rows before the research ran; not
- * completing there — which is what the code did — meant nothing retired them
- * at all, the lease expired, and the row was dispatched again ten minutes
- * later, forever, resuming the same session and paying for another turn.
- *
- * `session.waiting` is the boundary that actually means "this turn is done
- * and the session is ready for the next message", so it is the one that
- * closes the task.
- */
events: {
async "session.waiting"(_data, channel) {
const taskId = taskFromToken(channel.continuationToken);
if (!taskId) return;
const subject = await completeTask(taskId, "ran");
- // Null means somebody already closed it — a later turn on the same
- // thread, or the retirement sweep. Not ours to settle.
if (subject) await settle(subject, EnrichmentStatus.COMPLETE);
},
@@ -89,11 +39,6 @@ export default defineChannel({
? String((data as { error: unknown }).error)
: "The research turn failed.";
- // The row is deliberately *not* closed. A failed turn is worth another
- // go, and leaving it open lets the lease expire and the attempt cap
- // decide when to stop — the same path a crashed run takes. Only the
- // record is updated, so the sheet stops claiming somebody is working
- // on it in the meantime; the next claim puts it back to RUNNING.
const subject = await taskSubject(taskId);
if (subject) await settle(subject, EnrichmentStatus.FAILED, reason);
},
@@ -103,11 +48,6 @@ export default defineChannel({
const taskId =
typeof input.target?.taskId === "string" ? input.target.taskId : null;
- // The token is the task, which gives retries the behaviour you want for
- // free: a lease that expired mid-run is re-dispatched and *continues* the
- // same durable session rather than starting the research over. A task
- // scheduled fortnightly gets a new id each time, so two runs a fortnight
- // apart correctly share nothing.
return send(input.message, {
auth: input.auth,
continuationToken: taskId
diff --git a/apps/agent/agent/channels/eve.ts b/apps/agent/agent/channels/eve.ts
index 31840673..10f91e5b 100644
--- a/apps/agent/agent/channels/eve.ts
+++ b/apps/agent/agent/channels/eve.ts
@@ -8,41 +8,9 @@ import {
} from "eve/channels/auth";
import { eveChannel } from "eve/channels/eve";
-/**
- * The HTTP surface, and who is allowed to reach it.
- *
- * Three callers, in the order they are tried:
- *
- * 1. **A rep, through the CRM** — see `repFromCrm` below.
- * 2. **Vercel-to-Vercel**, for callers inside the deployment boundary.
- * 3. **localhost**, for `eve dev` and the terminal UI.
- *
- * Auth fails closed. With `AGENT_BRIDGE_SECRET` unset, entry 1 is skipped
- * rather than opened: no shared signer, no way for the proxy to prove who it
- * is, so the panel stops working and nothing else changes.
- */
-
-/** Both halves must agree on these, so they are stated once and exported. */
export const BRIDGE_ISSUER = "crm-app";
export const BRIDGE_AUDIENCE = "crm-agent";
-/**
- * A signed-in rep, arriving through the CRM's proxy.
- *
- * The browser never talks to this agent directly. `apps/app` proxies
- * `/eve/v1/*` on its own origin, checks the Better Auth session, and mints a
- * two-minute HS256 token naming the person. That avoids CORS, avoids scoping a
- * session cookie to a third host, and — the part that matters — tells the agent
- * *which rep* is asking rather than merely that the app is.
- *
- * Wrapping `verifyJwtHmac` rather than using the `jwtHmac()` helper directly,
- * for one reason worth stating: the helper maps an HMAC token to
- * `principalType: "service"` with `principalId: "crm-app:<sub>"`, which is the
- * right default for a shared machine credential and wrong here. This is a
- * person. `lib/approval.ts` decides whether to pause for a human by reading
- * exactly these fields, so getting them right is the difference between a rep
- * being asked to confirm a job change and the agent quietly refusing.
- */
export function repFromCrm(secret: string): AuthFn<Request> {
return withAuthChallenges(
async (request: Request) => {
diff --git a/apps/agent/agent/hooks/audit.ts b/apps/agent/agent/hooks/audit.ts
index a0d12240..a574b0aa 100644
--- a/apps/agent/agent/hooks/audit.ts
+++ b/apps/agent/agent/hooks/audit.ts
@@ -2,34 +2,11 @@ import { db } from "@crm/db";
import { defineHook } from "eve/hooks";
import { currentFocus } from "../lib/focus";
-/**
- * Every runtime event, on the record it was about.
- *
- * This is what "show your work" reads. Without it the agent's reasoning exists
- * only in a log nobody can query, and the contact sheet can say *what* a field
- * is but never *how it got there* — which is the whole difference between this
- * and buying a record from a data vendor.
- *
- * `meta.id` is eve's own ULID, minted once when the event is written to the
- * durable stream and stable across reconnects, rewinds and replays. Using it as
- * the primary key with `skipDuplicates` is what makes ingestion idempotent: a
- * reconnect mid-turn re-delivers events we already have, and they land as
- * no-ops instead of duplicate rows. Leading with a timestamp keeps inserts
- * roughly append-ordered too.
- *
- * Hooks are observe-only and run after the event is durably recorded, so a
- * failure in here can never take a turn down with it — but it must not throw
- * either, which is why the write is wrapped.
- */
export default defineHook({
events: {
async "*"(event, ctx) {
const id = event.meta?.id;
- // Events written before eve stream version 20 carry no id. They cannot
- // be deduplicated, so they are not stored rather than risking a
- // duplicate history — the exposure ends with the sessions that predate
- // the upgrade.
if (!id) return;
try {
@@ -40,9 +17,6 @@ export default defineHook({
sessionId: ctx.session.id,
contactId: currentFocus().contactId,
type: event.type,
- // Not every event carries a payload — `session.completed`
- // is the whole event. The column is non-null, so those
- // store an empty object rather than being dropped.
data: ("data" in event ? (event.data ?? {}) : {}) as object,
emittedAt: event.meta?.at ? new Date(event.meta.at) : new Date(),
},
@@ -50,7 +24,6 @@ export default defineHook({
skipDuplicates: true,
});
} catch (error) {
- // Never let the audit trail break the work it is auditing.
console.warn("[audit] could not record event", {
type: event.type,
reason: error instanceof Error ? error.message : String(error),
diff --git a/apps/agent/agent/instructions/task.ts b/apps/agent/agent/instructions/task.ts
index 5f5f87ac..186ac5b3 100644
--- a/apps/agent/agent/instructions/task.ts
+++ b/apps/agent/agent/instructions/task.ts
@@ -2,24 +2,6 @@ import { defineDynamic, defineInstructions } from "eve/instructions";
import { focusOn, setBudget } from "../lib/focus";
import { sessionPreamble } from "../lib/preamble";
-/**
- * What this particular session is for.
- *
- * `instructions.md` is the agent's permanent identity and is the same every
- * time. This is the opposite: resolved once per session from whoever started
- * it, so a run dispatched for one contact opens already knowing who they are,
- * what the task is, and what it may spend — instead of spending its first two
- * tool calls finding out.
- *
- * Resolved at `session.started` rather than per turn. Prompt caches are keyed
- * on the prompt, so a preamble that changed every turn would re-ingest the
- * whole conversation at uncached prices for information that does not change.
- *
- * The prose itself lives in `lib/preamble.ts` — three records, three different
- * conversations, and a test that says so. This file is the one place that
- * decides *focus*, because seeding it is what lets the audit hook file every
- * event against the right record: a hook sees events, not arguments.
- */
export default defineDynamic({
events: {
"session.started": async (_event, ctx) => {
@@ -36,8 +18,6 @@ export default defineDynamic({
dealId: asString(attributes.dealId),
},
{
- // The dispatcher names a task; the panel never does. That is the
- // only signal available at session start, and it is a reliable one.
dispatched: Boolean(kind),
kind,
reason: asString(attributes.reason),
diff --git a/apps/agent/agent/lib/accounts.ts b/apps/agent/agent/lib/accounts.ts
index 031b2342..79ae965c 100644
--- a/apps/agent/agent/lib/accounts.ts
+++ b/apps/agent/agent/lib/accounts.ts
@@ -1,26 +1,10 @@
import { ActivityType, db, EmailDirection } from "@crm/db";
import { isDerivedName } from "./names";
-/**
- * The CRM's other two records: companies and deals.
- *
- * `crm.ts` reads a person. This reads what a person hangs off, and it exists
- * because the agent could not. A session opened on a company knew the count of
- * contacts there and not one of their ids, so asked the rep to paste one — the
- * CRM's own join, handed back to the human as homework. A deal was worse: the
- * agent could name the stage and had no way to see what had happened in it.
- *
- * Both reads are free — our own Postgres, no vendor, no budget — and both
- * **name the neighbouring records and give their ids**, because that is what
- * turns "I need an identifier" into a second tool call.
- */
-
-/** How much of a body to hand back. Enough to read a signature block. */
const BODY_LIMIT = 4000;
export type AccountThread = {
subject: string | null;
- /** Whose thread it is, so a company-wide read is still attributable. */
contact: { id: string; name: string } | null;
messageCount: number;
lastMessageAt: string;
@@ -56,7 +40,6 @@ export type CompanyPerson = {
lastActivityAt: string | null;
threads: number;
meetings: number;
- /** Still named after their email address — nobody has worked out who they are. */
needsIdentity: boolean;
};
@@ -101,14 +84,6 @@ export type CompanyHistory = {
};
};
-/**
- * Everything we know about an account: who works there, what is being sold to
- * them, and every word exchanged with any of them.
- *
- * The people list is the point. A company session that cannot name its own
- * contacts spends its first turn asking the rep for a cuid, and a rep who has
- * the record open on screen is being asked to do the join by hand.
- */
export async function readCompanyHistory(
companyId: string,
options: {
@@ -136,10 +111,6 @@ export async function readCompanyHistory(
if (!company) return null;
- // A thread or a meeting is stamped with the company when the sync can
- // resolve one, but it is only ever stamped with the contact when the
- // counterparty was already on file — so both paths are checked. Missing the
- // second reads as an account nobody has ever emailed.
const belongsToCompany = { OR: [{ companyId }, { contact: { companyId } }] };
const [people, deals, threads, meetings, notes, lastInbound, counts] =
@@ -319,7 +290,6 @@ export type DealHistory = {
email: string | null;
role: string | null;
}[];
- /** Every stage this deal has been through, oldest first. */
stageHistory: { from: string | null; to: string | null; at: string }[];
threads: AccountThread[];
meetings: AccountMeeting[];
@@ -331,18 +301,9 @@ export type DealHistory = {
nextMeetingAt: string | null;
daysSinceLastActivity: number | null;
};
- /** Why the correspondence here is the account's and not the deal's. */
note: string;
};
-/**
- * Where a deal actually stands, as opposed to what its stage field says.
- *
- * The two answers differ often enough to be the reason this exists: a deal
- * sitting in `CONTRACT_SENT` for six weeks with no inbound reply is not a
- * contract-sent deal, and the only way to know is to read the stage clock, the
- * last reply and the next meeting together.
- */
export async function readDealHistory(
dealId: string,
options: { threads?: number; messagesPerThread?: number } = {},
@@ -384,11 +345,6 @@ export async function readDealHistory(
const contactIds = deal.contacts.map(({ contact }) => contact.id);
- // Email and calendar are filed against a person and a company, never against
- // a deal — Google has no idea our deals exist. So the correspondence here is
- // the account's, narrowed to the people on the deal where there are any. The
- // return says so rather than letting the agent infer that every thread it is
- // reading was about this deal.
const relatedThreads =
contactIds.length > 0
? {
@@ -516,7 +472,6 @@ export async function readDealHistory(
};
}
-/** The stages that are still in play. */
function isOpen(stage: string): boolean {
return (
stage !== "CLOSED_WON" &&
@@ -525,13 +480,6 @@ function isOpen(stage: string): boolean {
);
}
-/**
- * Typed notes on the timeline, without the email and meeting projections.
- *
- * Every thread and every event already lands on the timeline as an `Activity`,
- * so including those types here would hand the same conversation back twice —
- * once as a note saying an email happened, and once as the email.
- */
async function recentNotes(
where: { companyId: string } | { dealId: string },
): Promise<AccountNote[]> {
diff --git a/apps/agent/agent/lib/approval.ts b/apps/agent/agent/lib/approval.ts
index 80937c99..4fb05c6a 100644
--- a/apps/agent/agent/lib/approval.ts
+++ b/apps/agent/agent/lib/approval.ts
@@ -1,26 +1,5 @@
import type { Approval } from "eve/tools";
-/**
- * Who is driving, and what that licenses.
- *
- * Two facts shape every approval decision in this agent:
- *
- * 1. eve's own guidance is that model behaviour must not be relied on to
- * prevent sensitive writes. A confidence rubric in a system prompt *is*
- * model behaviour.
- * 2. **A task-mode schedule cannot pause for a person.** "Ask a human when
- * unsure" is therefore not available to a cron run — asking would hang it.
- * The same tool has to behave differently depending on who called it.
- *
- * Note what is deliberately *not* gated: `record_fact`. Its band logic runs in
- * the same function that scores the evidence, so a weak claim cannot be written
- * however the model asks. An approval gate there could only reject calls the
- * tool already rejects, while breaking the thing that makes weak claims
- * useful — being stored as a suggestion. Gates go on writes whose blast radius
- * is bigger than one field.
- */
-
-/** eve's app principal, used by markdown schedules and the dispatcher. */
export function isAutomated(session: {
auth: {
current?: {
@@ -38,14 +17,6 @@ export function isAutomated(session: {
);
}
-/**
- * For writes that move a record rather than fill a field.
- *
- * Re-parenting a contact to a different company is the example: it changes
- * whose pipeline they are in and which timeline their history hangs off, and
- * getting it wrong is not a typo somebody spots. A person signs it off, or it
- * does not happen unattended.
- */
export function sensitiveWrite(instead: string): Approval {
return ({ session }) =>
isAutomated(session)
diff --git a/apps/agent/agent/lib/avatar.ts b/apps/agent/agent/lib/avatar.ts
deleted file mode 100644
index 5cc053ee..00000000
--- a/apps/agent/agent/lib/avatar.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import { put } from "@vercel/blob";
-
-/** Bigger than any avatar, small enough that a redirect to something huge stops here. */
-const MAX_BYTES = 3 * 1024 * 1024;
-const TIMEOUT_MS = 15_000;
-
-const ALLOWED = new Set(["image/jpeg", "image/png", "image/webp", "image/gif"]);
-
-/**
- * Mirrors a profile picture into Vercel Blob.
- *
- * LinkedIn's CDN URLs are signed and expire — the ones we fetched carried
- * `e=1787184000`, roughly three weeks out. Storing that URL would give every
- * contact an avatar that works today and is a broken image next month, which is
- * worse than no avatar because nobody would connect the two.
- *
- * So the bytes are copied once and the record points at our own copy.
- *
- * Moved here from the API with the rest of enrichment: whoever writes the URL
- * onto the record is who should own fetching the bytes, and that is now the
- * agent. Plain functions rather than a Nest provider, because there is no
- * container on this side.
- */
-export function avatarsEnabled(): boolean {
- return Boolean(process.env.BLOB_READ_WRITE_TOKEN);
-}
-
-/**
- * Fetches a remote image and stores it. Returns our URL, or null.
- *
- * Never throws: an avatar is decoration, and a contact whose photo could not be
- * fetched is still a contact worth having.
- */
-export async function mirrorAvatar(
- sourceUrl: string,
- contactId: string,
-): Promise<string | null> {
- if (!avatarsEnabled()) return null;
-
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
-
- try {
- const response = await fetch(sourceUrl, {
- signal: controller.signal,
- // LinkedIn's CDN rejects requests carrying our origin.
- referrerPolicy: "no-referrer",
- });
-
- if (!response.ok) return null;
-
- const type = response.headers.get("content-type")?.split(";")[0]?.trim();
- if (!type || !ALLOWED.has(type)) return null;
-
- const buffer = await response.arrayBuffer();
- if (buffer.byteLength === 0 || buffer.byteLength > MAX_BYTES) return null;
-
- // Keyed by contact, so re-running replaces the photo rather than
- // littering the store with orphans.
- const extension = type.split("/")[1] ?? "jpg";
- const blob = await put(
- `contacts/${contactId}.${extension}`,
- Buffer.from(buffer),
- {
- access: "public",
- contentType: type,
- addRandomSuffix: false,
- allowOverwrite: true,
- },
- );
-
- return blob.url;
- } catch {
- return null;
- } finally {
- clearTimeout(timer);
- }
-}
diff --git a/apps/agent/agent/lib/brand-images.ts b/apps/agent/agent/lib/brand-images.ts
new file mode 100644
index 00000000..f00f2fe5
--- /dev/null
+++ b/apps/agent/agent/lib/brand-images.ts
@@ -0,0 +1,31 @@
+import type { Prisma } from "@crm/db";
+import { blobEnabled, mirror } from "@crm/db/blob";
+import { COMPANY_IMAGE_FIELDS } from "@crm/db/images";
+
+export async function mirrorBrandImages(
+ companyId: string,
+ update: Prisma.CompanyUpdateInput,
+): Promise<{ update: Prisma.CompanyUpdateInput; mirrored: string[] }> {
+ if (!blobEnabled()) return { update, mirrored: [] };
+
+ const mirrored: string[] = [];
+
+ await Promise.all(
+ COMPANY_IMAGE_FIELDS.map(async (slot) => {
+ const source = plain(update[slot]);
+ if (!source) return;
+
+ const stored = await mirror(source, `companies/${companyId}/${slot}`);
+ if (!stored || stored === source) return;
+
+ update[slot] = stored;
+ mirrored.push(slot);
+ }),
+ );
+
+ return { update, mirrored };
+}
+
+function plain(value: unknown): string | null {
+ return typeof value === "string" && value.trim() ? value : null;
+}
diff --git a/apps/agent/agent/lib/brand-mapping.ts b/apps/agent/agent/lib/brand-mapping.ts
index 91812206..7c3f426c 100644
--- a/apps/agent/agent/lib/brand-mapping.ts
+++ b/apps/agent/agent/lib/brand-mapping.ts
@@ -1,23 +1,10 @@
import type { Prisma } from "@crm/db";
import type { Brand } from "./context-dev";
-/**
- * What the agent is allowed to change about a company.
- *
- * Every field Context.dev returns is nullable, and a human's typed-in value
- * always outranks a guess: this only ever *fills gaps*, which is why almost
- * every assignment goes through `fill`.
- *
- * The two exceptions are `name` and `iconUrl`, and both are exceptions for the
- * same reason — their existing value was written by us rather than by a person,
- * so there is nobody to overrule. Each is marked at the assignment.
- */
export type BrandUpdate = Prisma.CompanyUpdateInput;
-/** The current values, so we know which gaps there are to fill. */
export type CompanySnapshot = {
name: string;
- /** True when the record was created domain-first and never named by a human. */
nameIsPlaceholder: boolean;
description: string | null;
logoUrl: string | null;
@@ -41,12 +28,6 @@ export type CompanySnapshot = {
careersUrl: string | null;
};
-/**
- * Picks a logo by `mode` and `type` rather than taking `logos[0]`.
- *
- * The array is not ordered by usefulness: taking the first one is how you end
- * up with a dark-mode wordmark on a white table row.
- */
type LogoMode = "light" | "dark" | "has_opaque_background";
function pickEntry(
@@ -70,12 +51,6 @@ function pickLogo(
return pickEntry(logos, type, mode)?.url ?? null;
}
-/**
- * The icon to render, preferring one that carries its own background.
- *
- * `has_opaque_background` is Context.dev saying the artwork is already composed
- * on a tile, which is the only kind that needs no help from us in either theme.
- */
function pickIcon(logos: Brand["logos"]) {
return (
pickEntry(logos, "icon", "has_opaque_background") ??
@@ -84,14 +59,6 @@ function pickIcon(logos: Brand["logos"]) {
);
}
-/**
- * How the chosen icon behaves against a background.
- *
- * Most brands publish a light-mode logo and nothing else — of the companies
- * enriched so far, every one had colour data and only two had a dark icon — so
- * the artwork's own dominant colour, not a second URL, is what makes a black
- * wordmark visible in dark mode.
- */
function iconTone(logos: Brand["logos"]): string | null {
const icon = pickIcon(logos);
if (!icon) return null;
@@ -101,29 +68,17 @@ function iconTone(logos: Brand["logos"]): string | null {
const rgb = parseHex(icon.colors?.find((colour) => colour?.hex)?.hex);
if (!rgb) return null;
- // Only near-greyscale artwork is a candidate. The fix downstream is a CSS
- // invert, and inverting a coloured mark does not make it visible — it makes
- // it the wrong brand: Monzo's coral comes out teal. A saturated logo is left
- // alone even if it is dark, because a wrong-coloured logo is worse than a
- // dim one.
const [r, g, b] = rgb;
const saturation = (Math.max(r, g, b) - Math.min(r, g, b)) / 255;
if (saturation > 0.12) return null;
- // Rec. 601 weighting — enough to answer "is this light or dark", and cheaper
- // than the sRGB-linearised version nobody would notice here.
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
- // Deliberately not a split at the midpoint. Only artwork close to pure black
- // or pure white actually disappears against a theme background, and only
- // that artwork survives an invert unchanged. Everything in between keeps its
- // own colours.
if (luminance < 0.2) return "dark";
if (luminance > 0.8) return "light";
return null;
}
-/** `#rrggbb` to a channel triple. */
function parseHex(
hex: string | null | undefined,
): [number, number, number] | null {
@@ -143,13 +98,6 @@ function clean(value: string | null | undefined): string | null {
return trimmed ? trimmed : null;
}
-/**
- * Builds the Prisma update for a brand lookup.
- *
- * Returns the fields the lookup actually found that are currently empty — plus
- * the two the agent owns outright — so re-enriching a company a rep has been
- * editing does not undo their work.
- */
export function brandToUpdate(
brand: Brand,
current: CompanySnapshot,
@@ -165,8 +113,6 @@ export function brandToUpdate(
}
};
- // The one non-null field the agent may replace: a company created from a
- // domain alone is named after the domain until we know better.
const title = clean(brand.title);
if (title && current.nameIsPlaceholder) {
update.name = title;
@@ -177,20 +123,12 @@ export function brandToUpdate(
fill("logoUrl", pickLogo(brand.logos, "logo", "light"));
fill("logoDarkUrl", pickLogo(brand.logos, "logo", "dark"));
- // The second non-null field the agent may replace, and for the same reason
- // as the name: `iconUrl` has another writer. The API derives a favicon from
- // the domain so a new company is not a grey square while we work, and this
- // icon is the curated one — `fill` would see a non-null value and skip,
- // leaving the stand-in in place permanently. No human can set `iconUrl`
- // (it is not in `companyUpdateInput`), so there is nobody to overrule.
const icon = pickIcon(brand.logos)?.url ?? null;
if (icon) update.iconUrl = icon;
fill("iconDarkUrl", pickLogo(brand.logos, "icon", "dark"));
fill("iconTone", iconTone(brand.logos));
- // `colors[].name` is generated rather than the brand's own name for it, so
- // the hex is the only part worth storing.
fill("brandColor", clean(brand.colors?.[0]?.hex));
const eic = brand.industries?.eic?.[0];
@@ -218,7 +156,6 @@ export function brandToUpdate(
return update;
}
-/** Fields worth counting when logging what a lookup actually achieved. */
export function filledFields(update: BrandUpdate): string[] {
return Object.keys(update);
}
diff --git a/apps/agent/agent/lib/capabilities.ts b/apps/agent/agent/lib/capabilities.ts
index 5a7fe2e3..c5c7ed20 100644
--- a/apps/agent/agent/lib/capabilities.ts
+++ b/apps/agent/agent/lib/capabilities.ts
@@ -1,37 +1,12 @@
import "@crm/env/load";
-/**
- * What this install can actually do.
- *
- * Every outside source the agent can reach is optional, and most self-hosted
- * copies of this repo will have none of them. That has to be an ordinary
- * operating condition rather than a degraded one, because the best evidence
- * here was never bought: a reply from someone's own address, their signature
- * block, a meeting they turned up to. `read_crm_history` needs no key at all
- * and beats every vendor in this list.
- *
- * So a missing key is not an error anywhere. It removes a place to look, the
- * agent is told which places it has before it plans, and the tools that need
- * one say so plainly and cost nothing. The failure this design exists to
- * prevent is an agent that burns its budget rediscovering that a key is
- * absent, then writes a confident summary from the little it managed to read.
- */
-
export type Capability = {
- /** The variable to set to turn it on. */
readonly env: string;
readonly label: string;
- /** What it adds, in the agent's terms. */
readonly gives: string;
readonly enabled: boolean;
};
-/**
- * Read on every call rather than captured at import.
- *
- * These are cheap, and a value that was snapshotted at module load is a value
- * that lies in tests and in any process that configures itself late.
- */
export function capabilities(): readonly Capability[] {
const set = (key: string) => Boolean(process.env[key]?.trim());
@@ -56,23 +31,22 @@ export function capabilities(): readonly Capability[] {
gives: "a company's logo, industry, location and socials from its domain",
enabled: set("CONTEXT_DEV_API_KEY"),
},
+ {
+ env: "BLOB_READ_WRITE_TOKEN",
+ label: "Picture storage",
+ gives:
+ "somewhere to keep a logo or a profile photo. Without it a record has no picture at all, because the URLs these sources hand back expire and are never stored as they are",
+ enabled: set("BLOB_READ_WRITE_TOKEN"),
+ },
];
}
-/** Whether one source is available, by its variable name. */
export function enabled(env: string): boolean {
return capabilities().some(
(capability) => capability.env === env && capability.enabled,
);
}
-/**
- * The result a tool returns when its source is not configured.
- *
- * Deliberately shaped like every other "we could not find out" answer, and
- * deliberately explicit that retrying is pointless — an agent told only
- * "failed" will reasonably try again, and there is nothing on the other end.
- */
export function unavailable(env: string): {
ok: false;
configured: false;
@@ -87,13 +61,6 @@ export function unavailable(env: string): {
};
}
-/**
- * The capability list, as a section for the session instructions.
- *
- * Both halves are stated. An agent told only what it has will keep proposing
- * the tool it does not, and one told only what it lacks reads it as a fault to
- * work around.
- */
export function capabilitiesMarkdown(): string {
const all = capabilities();
const on = all.filter((capability) => capability.enabled);
diff --git a/apps/agent/agent/lib/context-dev.ts b/apps/agent/agent/lib/context-dev.ts
index 98e5ad35..42c0a214 100644
--- a/apps/agent/agent/lib/context-dev.ts
+++ b/apps/agent/agent/lib/context-dev.ts
@@ -1,16 +1,6 @@
import ContextDev from "context.dev";
import { APIError } from "context.dev/core/error";
-/**
- * Context.dev: brand data, web extraction and web search.
- *
- * Moved here from `apps/api/src/enrichment` unchanged in behaviour. It is the
- * same client with the Nest scaffolding taken off — the API is not allowed to
- * know this vendor exists, and a class that needs a DI container is awkward in
- * a runtime that does not have one.
- */
-
-/** The Context.dev `brand` object, narrowed to the parts we map. */
export type Brand = {
domain?: string | null;
title?: string | null;
@@ -22,10 +12,8 @@ export type Brand = {
logos?:
| {
url?: string | null;
- /** "light" | "dark" | "has_opaque_background". */
mode?: string | null;
type?: string | null;
- /** The artwork's own dominant colours — how a dark mark is detected. */
colors?: { hex?: string | null; name?: string | null }[] | null;
}[]
| null;
@@ -45,19 +33,11 @@ export type Brand = {
} | null;
};
-/**
- * Why a lookup did not produce a brand.
- *
- * `skipped` and `failed` are deliberately different: "there is nothing to find
- * for this domain" is a settled answer that should stop us retrying and cost
- * nothing, while "the call fell over" is worth another go.
- */
export type LookupResult =
| { outcome: "found"; brand: Brand; raw: unknown }
| { outcome: "skipped"; reason: string }
| { outcome: "failed"; reason: string; retryable: boolean };
-/** One web search result, narrowed to the parts a person lookup reads. */
export type SearchResult = {
url: string | null;
title: string | null;
@@ -65,13 +45,8 @@ export type SearchResult = {
markdown: string | null;
};
-/** Cold lookups are p50 ≈ 7s, p90 ≈ 18s — so this is generous on purpose. */
const TIMEOUT_MS = 60_000;
-/**
- * Resolved on first use rather than at import, because the agent's environment
- * is not necessarily populated at module-evaluation time.
- */
let client: ContextDev | null | undefined;
function contextDev(): ContextDev | null {
@@ -86,7 +61,6 @@ export function contextDevEnabled(): boolean {
return contextDev() !== null;
}
-/** `POST /brand/retrieve` by domain. 10 credits, only on a successful match. */
export async function brandByDomain(
domain: string,
maxAgeMs?: number,
@@ -99,35 +73,19 @@ export async function brandByDomain(
});
}
-/** `POST /brand/retrieve` by work email — the domain is extracted for us. */
export async function brandByEmail(email: string): Promise<LookupResult> {
return lookup({ type: "by_email", email, timeoutMS: TIMEOUT_MS });
}
-/**
- * Warms the cache so a later retrieve lands sub-second. Free, and
- * fire-and-forget: the response carries no brand data.
- *
- * Paid plans only. A 403 here is a plan limit rather than a bug, and either way
- * the caller falls through to a direct retrieve — so nothing is reported.
- */
export async function prefetch(domain: string): Promise<void> {
const api = contextDev();
if (!api) return;
try {
await api.utility.prefetch({ type: "brand", identifier: { domain } });
- } catch {
- // Deliberately silent; see above.
- }
+ } catch {}
}
-/**
- * `POST /web/extract` against a caller-defined JSON Schema.
- *
- * Used for a company brief, which is not a brand lookup — it is "read this
- * company's site and answer these questions".
- */
export async function extract(
url: string,
schema: Record<string, unknown>,
@@ -154,13 +112,6 @@ export async function extract(
}
}
-/**
- * `POST /web/search`.
- *
- * Accepts Google-style operators, which is what makes a person lookup *sourced*
- * rather than guessed: we search for evidence and read a name off a page,
- * instead of asking a model what "pmarchetti" probably stands for.
- */
export async function search(
query: string,
options: { limit?: number; excludeDomains?: string[] } = {},
@@ -176,11 +127,7 @@ export async function search(
try {
const response = await api.web.search({
query,
- // The API rejects anything under 10 — a smaller ask fails validation
- // rather than returning fewer results.
numResults: Math.max(options.limit ?? 10, 10),
- // Without this the results are titles and snippets only, and a name is
- // usually in the page rather than the snippet.
markdownOptions: { enabled: true },
...(options.excludeDomains
? { excludeDomains: options.excludeDomains }
@@ -191,8 +138,6 @@ export async function search(
url: result.url ?? null,
title: result.title ?? null,
description: result.description ?? null,
- // `code` is the per-result scrape outcome; anything but SUCCESS means
- // `markdown` is null and the snippet is all we have.
markdown:
result.markdown?.code === "SUCCESS"
? (result.markdown.markdown ?? null)
@@ -225,12 +170,6 @@ async function lookup(
}
}
-/**
- * Maps Context.dev's failures onto something the CRM can act on.
- *
- * The important distinction is which of these should leave a company retryable.
- * An unknown domain never becomes known by asking again; a timeout might.
- */
function classify(error: unknown): LookupResult {
if (!(error instanceof APIError)) {
return { outcome: "failed", reason: describe(error), retryable: true };
@@ -238,8 +177,6 @@ function classify(error: unknown): LookupResult {
const code = errorCode(error);
- // 400 covers both malformed input and "we looked, there is nothing there".
- // Neither is billed, and neither is worth retrying.
if (error.status === 400) {
if (code === "NOT_FOUND" || code === "WEBSITE_ACCESS_ERROR") {
return {
@@ -253,7 +190,6 @@ function classify(error: unknown): LookupResult {
return { outcome: "failed", reason: describe(error), retryable: false };
}
- // A personal or throwaway address says nothing about where someone works.
if (error.status === 422) {
return {
outcome: "skipped",
@@ -265,7 +201,6 @@ function classify(error: unknown): LookupResult {
return { outcome: "failed", reason: describe(error), retryable: false };
}
- // Cold-cache timeouts and rate limits are the retryable ones.
if (error.status === 408 || error.status === 429) {
return { outcome: "failed", reason: describe(error), retryable: true };
}
diff --git a/apps/agent/agent/lib/crm.ts b/apps/agent/agent/lib/crm.ts
index 45dc220d..7301cc0b 100644
--- a/apps/agent/agent/lib/crm.ts
+++ b/apps/agent/agent/lib/crm.ts
@@ -2,18 +2,6 @@ import { db, EnrichmentStatus } from "@crm/db";
import { domainOf, isDerivedName } from "./names";
import type { Person } from "./socials";
-/**
- * The CRM, as far as this agent is concerned.
- *
- * Straight to Postgres through the workspace package rather than through a new
- * internal HTTP API: `@crm/db` is already shared by the API and the app, and a
- * third caller does not justify inventing a service boundary.
- *
- * Everything that *writes a claim* lives in `facts.ts` instead. This file reads,
- * and does the two bookkeeping writes that are not claims about a person: the
- * "we looked" stamp and the enrichment status the sheet polls.
- */
-
export type WorkItem = {
id: string;
fullName: string;
@@ -22,7 +10,6 @@ export type WorkItem = {
companyName: string | null;
companyDomain: string | null;
linkedinUrl: string | null;
- /** What is missing, so the agent does not redo the parts that are done. */
needs: {
identity: boolean;
brief: boolean;
@@ -30,15 +17,6 @@ export type WorkItem = {
};
};
-/**
- * Everything the agent could usefully do to a contact right now.
- *
- * One query instead of the two "list contacts that need X" tools this replaced.
- * Those encoded the *order* of the work in their names, which is exactly the
- * decision the agent is supposed to be making: whether an unnamed contact on a
- * live deal matters more than a named one with no background is a judgement,
- * not a schedule.
- */
export async function contactsNeedingWork(limit: number): Promise<WorkItem[]> {
const rows = await db.contact.findMany({
where: {
@@ -80,14 +58,6 @@ export async function contactsNeedingWork(limit: number): Promise<WorkItem[]> {
}));
}
-/**
- * Who the CRM says this person is — the only input the verification checks are
- * allowed to measure a candidate against.
- *
- * Loaded here rather than taken from tool arguments: a check run against a name
- * and employer the model supplied is a check the model can pass by supplying
- * different ones.
- */
export async function personForVerification(
contactId: string,
): Promise<Person | null> {
@@ -116,7 +86,6 @@ export async function personForVerification(
};
}
-/** The LinkedIn slug on a contact, or null if they have no profile on file. */
export async function contactProfileSlug(
contactId: string,
): Promise<{ slug: string; profileUrl: string } | null> {
@@ -131,7 +100,6 @@ export async function contactProfileSlug(
: null;
}
-/** `https://www.linkedin.com/in/lewiscarhart/` → `lewiscarhart`. */
export function linkedinSlug(url: string | null): string | null {
if (!url) return null;
const match = /linkedin\.com\/in\/([A-Za-z0-9\-_%]+)/.exec(url);
@@ -144,14 +112,6 @@ export type CrmHistory = {
email: string | null;
title: string | null;
companyName: string | null;
- /**
- * The company **id**, not just its name.
- *
- * Its absence was a real dead end: every company tool takes an id, this
- * was the only place a contact session could have learned one, and it
- * returned a display string. So an agent sitting on a contact who plainly
- * works somewhere reported that it had no company to look at.
- */
company: {
id: string;
name: string;
@@ -159,7 +119,6 @@ export type CrmHistory = {
industry: string | null;
} | null;
};
- /** The deals this person is attached to — the other way out of a contact. */
deals: {
id: string;
name: string;
@@ -178,7 +137,6 @@ export type CrmHistory = {
from: string;
fromName: string | null;
sentAt: string;
- /** The whole message. See the note on this function. */
body: string | null;
}[];
}[];
@@ -198,21 +156,6 @@ export type CrmHistory = {
colleagues: { id: string; name: string; title: string | null }[];
};
-/**
- * Everything we already know about this person from our own mailbox and
- * calendar — **including full message bodies**.
- *
- * This is the single biggest advantage we have over a data vendor, and it is
- * not close. A reply on a thread is proof of identity nobody can sell us. A
- * signature block settles a job title outright, and it settles it more
- * reliably than LinkedIn, because people update their signature when they get
- * promoted and update LinkedIn when they change jobs.
- *
- * Bodies are included deliberately: this is a single-tenant internal tool and
- * the data is already ours. The boundary is egress, not access — see the
- * `data-boundaries` skill. Nothing returned here may be pasted into a web
- * search, written to the sandbox, or logged.
- */
export async function readCrmHistory(
contactId: string,
options: { threads?: number; messagesPerThread?: number } = {},
@@ -369,7 +312,6 @@ export async function readCrmHistory(
};
}
-/** Records that we went looking, so nobody looks again next hour. */
export async function stampSocialsChecked(contactId: string): Promise<void> {
await db.contact.update({
where: { id: contactId },
@@ -377,13 +319,6 @@ export async function stampSocialsChecked(contactId: string): Promise<void> {
});
}
-/**
- * The status the contact sheet polls on, mirroring `Company`.
- *
- * Background writes are not invalidations — no client action caused them — so
- * the browser can only find out by asking, and it only knows to stop asking
- * when this settles.
- */
export async function setEnrichmentStatus(
contactId: string,
status: EnrichmentStatus,
@@ -401,7 +336,6 @@ export async function setEnrichmentStatus(
});
}
-/** Writes a note onto the contact's timeline, stamped as agent-written. */
export async function writeTimelineNote(
contactId: string,
subject: string,
@@ -414,9 +348,6 @@ export async function writeTimelineNote(
});
if (!contact) return null;
- // Activity.createdById is required. Attribute to the contact's owner, or to
- // any user if the contact is unowned — the meta marks it as agent-written so
- // the UI never claims a person typed it.
const author =
contact.ownerId ??
(await db.user.findFirst({ select: { id: true } }))?.id ??
diff --git a/apps/agent/agent/lib/enrichment.ts b/apps/agent/agent/lib/enrichment.ts
index 44b8d3f0..a68b24dc 100644
--- a/apps/agent/agent/lib/enrichment.ts
+++ b/apps/agent/agent/lib/enrichment.ts
@@ -1,47 +1,10 @@
import { db, EnrichmentStatus } from "@crm/db";
import type { TaskSubject } from "./tasks";
-/**
- * The enrichment status on a record, driven by the task lifecycle.
- *
- * This exists because the previous arrangement asked the model to keep the
- * status honest and it could not. `enrich_company` writes RUNNING and COMPLETE
- * around its own vendor call, which is right as far as it goes — but a
- * `company-profile` session that answers without reaching for that tool leaves
- * the record saying PENDING with no work outstanding, and a contact had no
- * equivalent at all. `setEnrichmentStatus` was written for contacts and never
- * called from anywhere, so every contact in the database sat at PENDING from
- * the moment it was inserted, which the UI rendered as "Queued" forever.
- *
- * So the status follows the queue rather than the model's intentions: claimed
- * is RUNNING, parked is COMPLETE, given up on is FAILED. A tool that knows
- * something more specific still wins — see `UNSETTLED`.
- *
- * COMPLETE means *we looked and the run finished*, not *we found everything*.
- * That is already what `enrich_company` means by it: it settles COMPLETE even
- * when the vendor returned nothing new, with a note saying so.
- */
-
-/**
- * Somebody is working on this now.
- *
- * Unconditional, and it has to be: a retry after a failed attempt is genuinely
- * running again, so gating this on the previous status would strand a record
- * on FAILED while a session was actively researching it.
- */
export async function markRunning(subject: TaskSubject): Promise<void> {
await write(subject, EnrichmentStatus.RUNNING, null, false);
}
-/**
- * Nobody is working on this any more, and here is how it ended.
- *
- * Only from RUNNING, which is what lets a tool win. A tool that reached a
- * terminal answer knows more than the queue does — that a company has no domain
- * to look up (SKIPPED), or that the vendor refused (FAILED, with the reason) —
- * and settling the task must not flatten those into a bland COMPLETE and lose
- * the message the rep would have read.
- */
export async function settle(
subject: TaskSubject,
status: EnrichmentStatus,
@@ -66,9 +29,6 @@ async function write(
? { enrichmentStatus: EnrichmentStatus.RUNNING }
: {};
- // `updateMany` for the status guard, and because a row can be deleted
- // between the dispatch and the session parking — a `update` would throw on
- // a record the rep removed while the agent was still reading about it.
if (subject.contactId) {
await db.contact.updateMany({
where: { id: subject.contactId, ...guard },
diff --git a/apps/agent/agent/lib/evidence.ts b/apps/agent/agent/lib/evidence.ts
index 87966e3e..67bcb4d3 100644
--- a/apps/agent/agent/lib/evidence.ts
+++ b/apps/agent/agent/lib/evidence.ts
@@ -1,21 +1,5 @@
import { FactBand } from "@crm/db";
-/**
- * How sure we are, and why.
- *
- * The rule this exists to enforce is that a score is never asserted — not by
- * the model, not by a tool author. A score is *derived* from a list of things
- * that were actually observed, each of which names what it is and where it came
- * from. That makes two otherwise impossible things possible: telling a rep why
- * a field says what it says, and re-calibrating every band in the database
- * without re-running a single lookup.
- *
- * The weights below are starting values to be moved by evals, not truths. What
- * is *not* negotiable is the shape: a primary source is required before
- * anything is written automatically, and a contradiction is never averaged
- * away.
- */
-
export type EvidenceKind =
| "profile.email-match"
| "linkedin.employer-and-name"
@@ -31,16 +15,7 @@ export type EvidenceKind =
type Weighting = {
weight: number;
- /**
- * Whether this evidence can carry a fact on its own.
- *
- * Only sources that identify *this person* qualify. Three non-primary
- * signals multiply to a confident-looking number and remain three weak
- * signals, which is the arithmetic that would otherwise let "a handle that
- * looks like their name" become a written fact.
- */
primary: boolean;
- /** Shown to a rep in the provenance tooltip. Written for them, not for us. */
label: string;
};
@@ -55,8 +30,6 @@ export const WEIGHTS: Record<EvidenceKind, Weighting> = {
primary: true,
label: "LinkedIn: employer and name both match",
},
- // Ours, and near the top. A person replying on a thread is proof of identity
- // that no data vendor can sell us, because it happened in our own mailbox.
"crm.thread-reply": {
weight: 0.85,
primary: true,
@@ -97,7 +70,6 @@ export const WEIGHTS: Record<EvidenceKind, Weighting> = {
primary: false,
label: "the employer matches, the name does not",
},
- // Not evidence for anything — evidence that something is wrong.
contradiction: {
weight: 0,
primary: false,
@@ -107,7 +79,6 @@ export const WEIGHTS: Record<EvidenceKind, Weighting> = {
export type Evidence = {
kind: EvidenceKind;
- /** What was actually seen, in a rep's words. */
detail: string;
sourceUrl?: string;
};
@@ -116,25 +87,15 @@ export type Scored = {
score: number;
band: FactBand | null;
hasPrimary: boolean;
- /** Why it landed where it did — the sentence shown under a proposal. */
rationale: string;
};
-/** Nothing is certain, so nothing scores 1. */
const CEILING = 0.99;
-/** A contradiction cannot be outvoted, only investigated. */
const CONTRADICTED = 0.45;
export const BAND_FLOOR = { VERIFIED: 0.85, PROBABLE: 0.55, POSSIBLE: 0.3 };
-/**
- * Combines independent evidence.
- *
- * `1 − Π(1 − wᵢ)` — the probability that at least one of them is right, if they
- * were independent and calibrated. They are neither, which is why §9's evals
- * exist and why the number is rendered as a word.
- */
export function scoreEvidence(evidence: Evidence[]): Scored {
if (evidence.length === 0) {
return {
@@ -164,13 +125,6 @@ export function scoreEvidence(evidence: Evidence[]): Scored {
};
}
-/**
- * The band, which is the behaviour.
- *
- * `VERIFIED` needs a primary source *and* the score — a fact good enough to
- * write without asking is a fact somebody's own page, mailbox or profile
- * asserts.
- */
export function bandFor(score: number, hasPrimary: boolean): FactBand | null {
if (score >= BAND_FLOOR.VERIFIED && hasPrimary) return FactBand.VERIFIED;
if (score >= BAND_FLOOR.PROBABLE) return FactBand.PROBABLE;
diff --git a/apps/agent/agent/lib/facts.ts b/apps/agent/agent/lib/facts.ts
index b4f2204e..3b8a866c 100644
--- a/apps/agent/agent/lib/facts.ts
+++ b/apps/agent/agent/lib/facts.ts
@@ -3,36 +3,7 @@ import { type Evidence, scoreEvidence } from "./evidence";
import { currentFocus } from "./focus";
import { isDerivedName, splitName } from "./names";
-/**
- * The only way a claim reaches a contact record.
- *
- * Three rules live here rather than in a prompt, because a rule the model is
- * asked to follow is a rule the model can talk itself out of:
- *
- * 1. **A human outranks the agent.** A value on the record with no fact behind
- * it was typed by a person, and is never overwritten.
- * 2. **A dismissal is final.** Once a rep has said no to a value, it is not
- * offered again — otherwise every run re-proposes it and the suggestion
- * becomes something reps click through without reading.
- * 3. **Nothing is written without a primary source**, whatever the arithmetic
- * says. Enforced by `bandFor`, restated here because it is the rule that
- * stops a plausible stranger becoming a customer record.
- */
-
-/**
- * The fields a fact may be about.
- *
- * `column` is the `Contact` field an applied fact writes through to; the ones
- * without a column are true of the person but have nowhere on the record to
- * live, so they are read straight from the fact by the background panel. That
- * is deliberate: `employer` as a fact rather than a column is what makes a job
- * change a superseded row instead of a diffing job.
- */
const FIELDS = {
- /**
- * Their actual name. Applied by splitting into `firstName`/`lastName`, and
- * guarded differently from everything else — see `humanOwns`.
- */
name: { column: null },
title: { column: "title" },
linkedinUrl: { column: "linkedinUrl" },
@@ -64,7 +35,6 @@ export type RecordFactResult = {
band: FactBand | null;
score: number;
rationale: string;
- /** Why nothing happened, when nothing happened. Written for the model. */
reason?: string;
};
@@ -169,8 +139,6 @@ export async function recordFact(
await db.$transaction(async (tx) => {
if (applies && currentApplied) {
- // The old value is not deleted — it is history, and for `employer` it
- // is the job change itself.
await tx.contactFact.update({
where: { id: currentApplied.id },
data: { status: FactStatus.SUPERSEDED, supersededAt: new Date() },
@@ -222,7 +190,6 @@ export async function recordFact(
};
}
-/** Whether a job change just happened: an applied `employer` fact superseded. */
export async function lastEmployerChange(contactId: string) {
const [previous, current] = await Promise.all([
db.contactFact.findFirst({
@@ -293,16 +260,6 @@ export async function writeBrief(input: {
return { written: true, score: scored.score };
}
-/**
- * Whether the value already there belongs to a person rather than to us.
- *
- * For ordinary fields the test is simple: something is in the column and no
- * applied fact explains it, so a human typed it.
- *
- * A name needs a different test, because the sync always writes one. `Pmarchetti`
- * is a placeholder derived from `[email protected]` and is ours to replace;
- * anything that is not derived came from a mail header or a person, and is not.
- */
function humanOwns({
field,
column,
diff --git a/apps/agent/agent/lib/focus.ts b/apps/agent/agent/lib/focus.ts
index 46f223ce..10543ac6 100644
--- a/apps/agent/agent/lib/focus.ts
+++ b/apps/agent/agent/lib/focus.ts
@@ -1,36 +1,13 @@
import { defineState } from "eve/context";
-/**
- * Who and what this session is about, and what it has spent.
- *
- * Durable per-session state rather than an argument threaded through every
- * tool: the audit hook needs the contact id to file an event against a record,
- * and a hook receives the event, not the tool's arguments. Any tool that takes
- * a `contactId` sets it, so the hook always knows whose page to write to.
- *
- * The budget lives here for a different reason. Depth is supposed to be a
- * decision the agent makes per contact, and a decision needs something to spend
- * — a counter in a prompt is a suggestion, a counter in durable state is a
- * limit that survives a crash mid-run.
- */
export const focus = defineState("crm.focus", () => ({
contactId: null as string | null,
companyId: null as string | null,
sessionId: null as string | null,
- /** Vendor calls made. Cheap local reads do not count against it. */
spent: 0,
- /** Set from the task that started the session; 4 is a plain identity pass. */
budget: 4,
}));
-/**
- * The state, or nothing, if we are not inside an eve turn.
- *
- * `get()` throws outside framework-managed code, which is right for a tool and
- * wrong for everything else that shares this library: a test, a backfill
- * script, or the dispatcher deciding what to run next. Provenance is worth
- * having even when the session id is not.
- */
export function currentFocus(): {
contactId: string | null;
sessionId: string | null;
@@ -56,7 +33,6 @@ export function focusOn(input: {
}));
}
-/** Charges a vendor call against the budget, or explains why it cannot. */
export function spend(units = 1): { ok: true } | { ok: false; reason: string } {
const { spent, budget } = focus.get();
diff --git a/apps/agent/agent/lib/linkdapi.ts b/apps/agent/agent/lib/linkdapi.ts
index bd8b0b20..1b3be0cd 100644
--- a/apps/agent/agent/lib/linkdapi.ts
+++ b/apps/agent/agent/lib/linkdapi.ts
@@ -1,19 +1,6 @@
const HOST = "linkdapi-best-unofficial-linkedin-api.p.rapidapi.com";
const TIMEOUT_MS = 20_000;
-/**
- * LinkedIn data via LinkDAPI on RapidAPI.
- *
- * **There is deliberately no search function here.** LinkDAPI publishes no
- * people-search endpoint, and the undocumented `/search/people?keywords=` path
- * answers `HTTP 200` with entirely unrelated people — a query for "Paula Marchetti"
- * returned Brightwater's CEO, and a different random set on the next call. Anything
- * that looked like search here would be a well-typed way to file a stranger
- * against a real customer. Finding the slug is Perplexity's job.
- *
- * Given a slug this API is excellent, so that is all it is asked to do.
- */
-
export type Profile = {
slug: string;
profileUrl: string;
@@ -22,11 +9,10 @@ export type Profile = {
lastName: string | null;
headline: string | null;
location: string | null;
- /** Needed by every detail endpoint — they take `urn`, not `username`. */
urn: string | null;
followerCount: number | null;
connectionsCount: number | null;
- /** Current employers. The job-change signal lives here. */
+ photoUrl: string | null;
positions: { name: string; url: string | null }[];
};
@@ -59,7 +45,24 @@ export function linkedinEnabled(): boolean {
return key() !== null;
}
-/** A profile by its `linkedin.com/in/<slug>` handle. */
+export function slugFromProfileUrl(raw: string | null): string | null {
+ if (!raw) return null;
+
+ try {
+ const url = new URL(raw.trim());
+
+ const host = url.hostname.toLowerCase();
+ if (host !== "linkedin.com" && !host.endsWith(".linkedin.com")) return null;
+
+ const [section, slug] = url.pathname.split("/").filter(Boolean);
+ if (section !== "in" || !slug) return null;
+
+ return decodeURIComponent(slug);
+ } catch {
+ return null;
+ }
+}
+
export async function getProfile(slug: string): Promise<Outcome<Profile>> {
const result = await call<RawProfile>("/api/v1/profile/overview", {
username: slug,
@@ -80,6 +83,7 @@ export async function getProfile(slug: string): Promise<Outcome<Profile>> {
urn: str(d.urn),
followerCount: int(d.followerCount),
connectionsCount: int(d.connectionsCount),
+ photoUrl: profilePhotoUrl(d),
positions: (d.CurrentPositions ?? []).flatMap((p) =>
p?.name ? [{ name: p.name, url: str(p.url) }] : [],
),
@@ -87,7 +91,6 @@ export async function getProfile(slug: string): Promise<Outcome<Profile>> {
};
}
-/** Full work history. Takes the `urn` from a profile, not the slug. */
export async function getExperience(
urn: string,
): Promise<Outcome<Experience[]>> {
@@ -96,8 +99,6 @@ export async function getExperience(
});
if (!result.ok) return result;
- // The endpoint has been seen returning both a bare array and an object
- // wrapping one, so both are accepted rather than trusting either.
const payload = result.data;
const rows: RawExperienceRow[] = Array.isArray(payload)
? payload
@@ -116,7 +117,6 @@ export async function getExperience(
};
}
-/** Resolves a company name to LinkedIn's id. */
export async function lookupCompany(
query: string,
): Promise<Outcome<{ id: string; displayName: string }[]>> {
@@ -133,7 +133,6 @@ export async function lookupCompany(
};
}
-/** Company detail. Takes `name` (the universal name) or `id`. */
export async function getCompany(nameOrId: string): Promise<Outcome<Company>> {
const numeric = /^\d+$/.test(nameOrId);
const result = await call<RawCompany>("/api/v1/companies/company/info", {
@@ -155,12 +154,6 @@ export async function getCompany(nameOrId: string): Promise<Outcome<Company>> {
};
}
-/**
- * One call.
- *
- * LinkDAPI reports a failed lookup as `200 { success: false }` rather than a
- * status code, so the envelope is what has to be read.
- */
async function call<T>(
path: string,
params: Record<string, string>,
@@ -189,7 +182,6 @@ async function call<T>(
data?: T | null;
};
- // "no such profile" is an ordinary answer, not something to retry.
if (body.success !== true || body.data == null) {
return { ok: false, missing: true };
}
@@ -221,7 +213,65 @@ type RawProfile = {
followerCount?: unknown;
connectionsCount?: unknown;
CurrentPositions?: { name?: string; url?: unknown }[] | null;
-};
+} & Record<string, unknown>;
+
+const PHOTO_KEYS = [
+ "profilePictureURL",
+ "profilePicture",
+ "profilePictureUrl",
+ "profilePicUrl",
+ "profilePic",
+ "profilePicHighQuality",
+ "profilePhotoUrl",
+ "profilePhoto",
+ "pictureUrl",
+ "avatarUrl",
+ "avatar",
+];
+
+export function profilePhotoUrl(raw: Record<string, unknown>): string | null {
+ const byLowerKey = new Map<string, unknown>();
+ for (const [key, value] of Object.entries(raw)) {
+ byLowerKey.set(key.toLowerCase(), value);
+ }
+
+ for (const key of PHOTO_KEYS) {
+ const url = firstUrl(byLowerKey.get(key.toLowerCase()));
+ if (!url) continue;
+
+ try {
+ const { protocol, hostname } = new URL(url);
+ if (protocol !== "https:") continue;
+ if (hostname !== "licdn.com" && !hostname.endsWith(".licdn.com"))
+ continue;
+ return url;
+ } catch {}
+ }
+
+ return null;
+}
+
+function firstUrl(value: unknown): string | null {
+ if (typeof value === "string") return str(value);
+
+ if (Array.isArray(value)) {
+ for (const entry of [...value].reverse()) {
+ const found = firstUrl(entry);
+ if (found) return found;
+ }
+ return null;
+ }
+
+ if (value && typeof value === "object") {
+ const record = value as Record<string, unknown>;
+ for (const key of ["url", "displayUrl", "src", "large", "original"]) {
+ const found = firstUrl(record[key]);
+ if (found) return found;
+ }
+ }
+
+ return null;
+}
type RawExperienceRow = {
title?: unknown;
diff --git a/apps/agent/agent/lib/lookup.ts b/apps/agent/agent/lib/lookup.ts
index 85b551dd..ecd5fbe9 100644
--- a/apps/agent/agent/lib/lookup.ts
+++ b/apps/agent/agent/lib/lookup.ts
@@ -1,22 +1,6 @@
import { db } from "@crm/db";
import { domainOf, normalise } from "./names";
-/**
- * Turning what a rep said into the record they meant.
- *
- * This is the gap that produced "I need an actual identifier: a contact's
- * name, email address, or a contact ID". The agent had a lookup by id and a
- * lookup by email and nothing that took the words a person would actually
- * type, so a rep sitting on the Comp AI record — with the answer on screen —
- * was asked to go and find a cuid.
- *
- * Free, local, and deliberately not clever: containment against the fields a
- * human would have searched, then a score that puts exact matches first. No
- * fuzzy distance, because "Northwind" matching "Northwind Savings Group" is
- * useful and "Marchetti" matching "Marchetta" is a wrong record in a CRM.
- * Ambiguity is returned, not resolved — four Marchettis is an answer.
- */
-
export type RecordKind = "contact" | "company" | "deal";
export type ContactHit = {
@@ -59,13 +43,6 @@ export type SearchResult = {
total: number;
};
-/**
- * Everything in the CRM that could be what they meant.
- *
- * An address searches for the person who owns it *and* the company on its
- * domain, because "who is [email protected]" and "what is Fernhill" are the
- * same question asked from two ends.
- */
export async function searchCrm(
query: string,
options: { kinds?: RecordKind[]; limit?: number } = {},
@@ -80,8 +57,6 @@ export async function searchCrm(
const wants = (kind: RecordKind) => kinds.includes(kind);
const email = term.includes("@") ? term.toLowerCase() : null;
- // A bare domain is a company query in every case that matters: nobody types
- // "fernhill.com" hoping for a deal called Fernhill.com.
const domain = email ? domainOf(email) : bareDomain(term);
const words = term.split(/\s+/).filter((word) => word.length >= 2);
@@ -119,8 +94,6 @@ async function searchContacts(
? [{ email: { equals: email, mode: "insensitive" as const } }]
: []),
...contains,
- // The whole phrase against the company, so "Comp AI" finds the
- // people there rather than only a person called Comp.
{ company: { name: { contains: term, mode: "insensitive" as const } } },
],
},
@@ -250,21 +223,6 @@ async function searchDeals(
.map((row) => row.hit);
}
-/**
- * How well a row answers the query: exact, then prefix, then containment, and
- * only then the individual words.
- *
- * The two tiers matter because the SQL above is an `OR` across every word — it
- * has to be, or "Paula Marchetti" would miss a contact filed as "P. Marchetti"
- * — which means a two-word query drags in everything matching either half.
- * Whole-phrase hits score at least 1 and word hits always score below it, so
- * the row a person meant is never buried under the rows that share a word with
- * it.
- *
- * Ordering happens here rather than in Postgres because the interesting rank
- * is across three tables, and `similarity()` would mean an extension a
- * self-hoster has to install. These result sets are tens of rows.
- */
function score(term: string, fields: string[]): number {
const needle = normalise(term);
if (!needle) return 0;
@@ -289,7 +247,6 @@ function score(term: string, fields: string[]): number {
return words.filter((word) => hay.includes(word)).length / words.length;
}
-/** `fernhill.com` → `fernhill.com`; `Fernhill` → null. */
function bareDomain(term: string): string | null {
const candidate = term
.trim()
diff --git a/apps/agent/agent/lib/model.ts b/apps/agent/agent/lib/model.ts
new file mode 100644
index 00000000..76aca94f
--- /dev/null
+++ b/apps/agent/agent/lib/model.ts
@@ -0,0 +1,27 @@
+import { db } from "@crm/db";
+import { readAgentModel } from "@crm/db/settings";
+
+export interface ModelSelection {
+ model: string;
+ modelContextWindowTokens: number;
+}
+
+export async function selectedModel(): Promise<ModelSelection | null> {
+ try {
+ const setting = await readAgentModel(db);
+
+ if (setting.isDefault) return null;
+
+ return {
+ model: setting.id,
+ modelContextWindowTokens: setting.contextWindowTokens,
+ };
+ } catch (error) {
+ console.error(
+ `[agent] could not read the configured model, falling back: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ return null;
+ }
+}
diff --git a/apps/agent/agent/lib/names.ts b/apps/agent/agent/lib/names.ts
index 753dd184..d5761b73 100644
--- a/apps/agent/agent/lib/names.ts
+++ b/apps/agent/agent/lib/names.ts
@@ -1,22 +1,3 @@
-/**
- * Turning an email local part into something searchable, and checking the
- * answer that comes back.
- *
- * All pure, and all verified against real CRM addresses rather than reasoned
- * about: `[email protected]` → `marchetti` → `linkedin.com/in/paulamarchetti` →
- * Paula Marchetti, Growth Specialist at Fernhill.
- */
-
-/**
- * Search terms for an email local part, most specific first.
- *
- * Searching the raw handle finds nothing — `pmarchetti` is not a slug, a name or a
- * word. Searching the surname it contains finds them on the first result.
- *
- * The split is generated blind and every candidate it produces is verified
- * afterwards, so a wrong guess costs a search rather than producing a wrong
- * contact. Guess the *query*, never the answer.
- */
export function searchTerms(local: string): string[] {
const handle = local.toLowerCase().replace(/[^a-z0-9._-]/g, "");
const terms: string[] = [];
@@ -25,7 +6,6 @@ export function searchTerms(local: string): string[] {
if (term.length >= 3 && !terms.includes(term)) terms.push(term);
};
- // An explicit separator is not a guess — `jane.doe` says what it is.
const parts = handle.split(/[._-]+/).filter(Boolean);
if (parts.length > 1) {
add(parts.join(" "));
@@ -34,8 +14,6 @@ export function searchTerms(local: string): string[] {
add(handle);
- // One token: try the surname left when a one- or two-letter initial comes off
- // the front. This is the `pmarchetti` → `marchetti` step.
if (parts.length === 1) {
add(handle.slice(1));
add(handle.slice(2));
@@ -44,13 +22,6 @@ export function searchTerms(local: string): string[] {
return terms;
}
-/**
- * Whether a LinkedIn employer is the company we think it is.
- *
- * Loose enough that "Northwind Bank" matches a CRM company called "Northwind", but
- * anchored on containment rather than fuzzy distance — which would cheerfully
- * match "Northwind" to "Northwind Savings Group".
- */
export function looksLikeSameCompany(
employer: string,
companyName: string,
@@ -67,14 +38,6 @@ export function looksLikeSameCompany(
);
}
-/**
- * Whether a name is consistent with the address it was found from.
- *
- * The direction is the whole point: the name is checked against the local part,
- * never derived from it. `tokonkwo` is consistent with Tomi Okonkwo (`y` + `okonkwo`).
- * It is not consistent with Dario Fontana, which is how a confident wrong
- * answer from a search engine gets rejected.
- */
export function nameMatchesLocalPart(
person: { firstName: string | null; lastName: string | null },
local: string,
@@ -95,22 +58,12 @@ export function nameMatchesLocalPart(
last,
].filter(Boolean);
- // Either the handle is one of the usual constructions, or a prefix of one —
- // corporate directories truncate.
return forms.some(
(form) =>
form === handle || form.startsWith(handle) || handle.startsWith(form),
);
}
-/**
- * Whether a contact's name is still the placeholder the sync derived from
- * their address, rather than something a person or a mail header supplied.
- *
- * The test is narrow on purpose: no surname, and the first name is the whole
- * handle. "Pmarchetti" from `[email protected]` is a placeholder; "Paula" from a
- * mail header is not, even though both are single words.
- */
export function isDerivedName(
email: string | null,
firstName: string,
@@ -121,7 +74,6 @@ export function isDerivedName(
return nameMatchesLocalPart({ firstName, lastName: null }, local);
}
-/** Splits a display name into first and last. */
export function splitName(
fullName: string,
): { firstName: string; lastName: string | null } | null {
@@ -134,21 +86,11 @@ export function splitName(
return { firstName: first, lastName: rest.length ? rest.join(" ") : null };
}
-/** The domain part of an email, lowercased. */
export function domainOf(email: string): string | null {
const at = email.lastIndexOf("@");
return at > 0 ? email.slice(at + 1).toLowerCase() : null;
}
-/**
- * Whether two written names are the same person's.
- *
- * First and last have to agree; anything between them does not, so "Lewis
- * Carhart" matches "Lewis J. Carhart" and does not match "Lewis Carter".
- * Used where both sides are real names — a GitHub profile's `name` against the
- * one on the CRM record — as opposed to `nameMatchesLocalPart`, which checks a
- * name against a handle.
- */
export function namesMatch(a: string | null, b: string | null): boolean {
const left = words(a);
const right = words(b);
@@ -156,22 +98,16 @@ export function namesMatch(a: string | null, b: string | null): boolean {
if (left.length === 0 || right.length === 0) return false;
if (left.join("") === right.join("")) return true;
- // A single-word name is not enough to identify anybody: "Lewis" matches every
- // Lewis there is.
if (left.length < 2 || right.length < 2) return false;
return left[0] === right[0] && left.at(-1) === right.at(-1);
}
function words(value: string | null): string[] {
- return (
- (value ?? "")
- .split(/\s+/)
- .map(normalise)
- // Initials and honorifics carry no signal and would otherwise shift which
- // word counts as the surname.
- .filter((word) => word.length > 1)
- );
+ return (value ?? "")
+ .split(/\s+/)
+ .map(normalise)
+ .filter((word) => word.length > 1);
}
export function normalise(value: string): string {
diff --git a/apps/agent/agent/lib/perplexity.ts b/apps/agent/agent/lib/perplexity.ts
index ecb356f6..4f1c235d 100644
--- a/apps/agent/agent/lib/perplexity.ts
+++ b/apps/agent/agent/lib/perplexity.ts
@@ -1,20 +1,6 @@
const ENDPOINT = "https://api.perplexity.ai/chat/completions";
const TIMEOUT_MS = 45_000;
-/**
- * Perplexity, for the two things it is better at than anything else here:
- * finding where a person lives on the web, and saying what has happened
- * recently that a rep should know before a call.
- *
- * It is **not** the source of truth for identity. Asked for Paula Marchetti's job
- * title it answered "Account Executive L3" while their own LinkedIn profile says
- * "Growth Specialist at Fernhill" — an aggregator reconciling stale sources.
- * LinkedIn is self-reported and wins on identity; Perplexity wins on context.
- *
- * Every answer carries its citations, and a claim without one does not get
- * written to a record.
- */
-
export type Answer = {
text: string;
citations: string[];
@@ -27,14 +13,11 @@ export function perplexityEnabled(): boolean {
}
export type AskOptions = {
- /** `sonar` is fast and cited; `sonar-pro` reasons harder over more sources. */
model?: "sonar" | "sonar-pro";
- /** Narrow the search, e.g. `["linkedin.com"]`. */
domains?: string[];
system?: string;
};
-/** One grounded question. */
export async function ask(
question: string,
options: AskOptions = {},
@@ -78,8 +61,6 @@ export async function ask(
const text = body.choices?.[0]?.message?.content?.trim() ?? "";
if (!text) return { ok: false, reason: "Empty answer." };
- // The field moved between API versions; read whichever is present rather
- // than dropping citations on a version bump.
const citations =
body.citations ??
(body.search_results ?? []).flatMap((r) => (r.url ? [r.url] : []));
@@ -100,13 +81,6 @@ export async function ask(
}
}
-/**
- * LinkedIn profile URLs for a person, from their email and employer.
- *
- * Restricted to linkedin.com so the answer is a set of URLs rather than prose,
- * and the slugs are pulled out of the citations rather than out of the model's
- * text — a cited URL was actually retrieved, a quoted one may not have been.
- */
export async function findProfileUrls(
terms: string[],
companyName: string,
@@ -129,7 +103,6 @@ export async function findProfileUrls(
if (slug && !slugs.includes(slug)) slugs.push(slug);
}
- // The first term that produces anything is the most specific one.
if (slugs.length > 0) break;
}
diff --git a/apps/agent/agent/lib/portrait-sources.ts b/apps/agent/agent/lib/portrait-sources.ts
new file mode 100644
index 00000000..269e92e5
--- /dev/null
+++ b/apps/agent/agent/lib/portrait-sources.ts
@@ -0,0 +1,146 @@
+import { extract } from "./context-dev";
+import { getProfile, slugFromProfileUrl } from "./linkdapi";
+import { namesMatch } from "./names";
+
+export type PortraitSource = "linkedin" | "github" | "employer-site";
+
+export type PortraitCandidate = {
+ source: PortraitSource;
+ url: string;
+};
+
+export type PortraitSubject = {
+ id: string;
+ name: string | null;
+ linkedinUrl: string | null;
+ githubUrl: string | null;
+ companyName: string | null;
+ companyDomain: string | null;
+};
+
+export async function findPortrait(
+ subject: PortraitSubject,
+ spend: (units?: number) => { ok: boolean; reason?: string },
+): Promise<
+ | { found: true; candidate: PortraitCandidate }
+ | { found: false; tried: string[]; reason?: string }
+> {
+ const tried: string[] = [];
+
+ if (subject.linkedinUrl) {
+ const slug = slugFromProfileUrl(subject.linkedinUrl);
+ if (slug) {
+ const charge = spend();
+ if (!charge.ok) return { found: false, tried, reason: charge.reason };
+
+ const result = await getProfile(slug);
+ if (result.ok && result.data.photoUrl) {
+ return {
+ found: true,
+ candidate: { source: "linkedin", url: result.data.photoUrl },
+ };
+ }
+ tried.push(
+ result.ok
+ ? "LinkedIn profile has no picture"
+ : "LinkedIn profile could not be read",
+ );
+ }
+ }
+
+ const login = githubLogin(subject.githubUrl);
+ if (login) {
+ return {
+ found: true,
+ candidate: {
+ source: "github",
+ url: `https://github.com/${encodeURIComponent(login)}.png?size=460`,
+ },
+ };
+ }
+
+ if (subject.companyDomain && subject.name) {
+ const charge = spend(2);
+ if (!charge.ok) return { found: false, tried, reason: charge.reason };
+
+ const fromSite = await fromEmployerSite(subject);
+ if (fromSite) return { found: true, candidate: fromSite };
+ tried.push("Not on the company's own site");
+ }
+
+ return { found: false, tried };
+}
+
+const TEAM_SCHEMA = {
+ type: "object",
+ properties: {
+ people: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: { type: "string" },
+ title: { type: "string" },
+ photoUrl: {
+ type: "string",
+ description: "Absolute URL of this person's headshot.",
+ },
+ },
+ required: ["name"],
+ },
+ },
+ },
+ required: ["people"],
+};
+
+async function fromEmployerSite(
+ subject: PortraitSubject,
+): Promise<PortraitCandidate | null> {
+ const result = await extract(
+ `https://${subject.companyDomain}`,
+ TEAM_SCHEMA,
+ `Find the team, people, about or leadership page for ${subject.companyName ?? subject.companyDomain}. ` +
+ "List every named person shown with a headshot, giving the photograph's absolute URL. " +
+ "Do not include stock photography, customer logos, or people who are not staff.",
+ );
+
+ if (result.outcome !== "found") return null;
+
+ const people = (result.data as { people?: unknown } | null)?.people;
+ if (!Array.isArray(people)) return null;
+
+ for (const entry of people) {
+ if (!entry || typeof entry !== "object") continue;
+ const row = entry as Record<string, unknown>;
+
+ const name = typeof row.name === "string" ? row.name : null;
+ const photo = typeof row.photoUrl === "string" ? row.photoUrl : null;
+ if (!name || !photo) continue;
+ if (!namesMatch(name, subject.name)) continue;
+
+ try {
+ const parsed = new URL(photo);
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") continue;
+ return { source: "employer-site", url: parsed.toString() };
+ } catch {}
+ }
+
+ return null;
+}
+
+function githubLogin(raw: string | null): string | null {
+ if (!raw) return null;
+
+ try {
+ const url = new URL(raw.trim());
+ const host = url.hostname.toLowerCase().replace(/^www\./, "");
+ if (host !== "github.com") return null;
+
+ const segments = url.pathname.split("/").filter(Boolean);
+ if (segments.length !== 1) return null;
+
+ return segments[0] ?? null;
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/agent/agent/lib/portrait.ts b/apps/agent/agent/lib/portrait.ts
new file mode 100644
index 00000000..090ec3dc
--- /dev/null
+++ b/apps/agent/agent/lib/portrait.ts
@@ -0,0 +1,165 @@
+import { db } from "@crm/db";
+import { blobEnabled, isMirrored, mirror } from "@crm/db/blob";
+import { findPortrait, type PortraitSource } from "./portrait-sources";
+
+export type PortraitResult = {
+ stored: boolean;
+ imageUrl: string | null;
+ source?: PortraitSource;
+ reason?: string;
+};
+
+export async function storePortrait({
+ contactId,
+ sourceUrl,
+ verified,
+ force = false,
+}: {
+ contactId: string;
+ sourceUrl: string | null;
+ verified: boolean;
+ force?: boolean;
+}): Promise<PortraitResult> {
+ if (!sourceUrl) {
+ return {
+ stored: false,
+ imageUrl: null,
+ reason: "No photo on the profile.",
+ };
+ }
+
+ if (!verified) {
+ return {
+ stored: false,
+ imageUrl: null,
+ reason:
+ "The profile was not established to be this person, so its photo is not theirs to use.",
+ };
+ }
+
+ if (!blobEnabled()) {
+ return {
+ stored: false,
+ imageUrl: null,
+ reason:
+ "This install has no BLOB_READ_WRITE_TOKEN, so there is nowhere to keep a copy. " +
+ "The source URL expires within weeks and is never stored. Retrying will not help.",
+ };
+ }
+
+ const contact = await db.contact.findUnique({
+ where: { id: contactId },
+ select: { imageUrl: true },
+ });
+
+ if (!contact) {
+ return { stored: false, imageUrl: null, reason: "No such contact." };
+ }
+
+ if (!force && isMirrored(contact.imageUrl)) {
+ return {
+ stored: false,
+ imageUrl: contact.imageUrl,
+ reason: "They already have a photo.",
+ };
+ }
+
+ const stored = await mirror(sourceUrl, `contacts/${contactId}`);
+
+ if (!stored) {
+ return {
+ stored: false,
+ imageUrl: contact.imageUrl,
+ reason: "The photo could not be fetched. The record is unchanged.",
+ };
+ }
+
+ if (stored === contact.imageUrl) {
+ return { stored: false, imageUrl: stored, reason: "Unchanged." };
+ }
+
+ await db.contact.update({
+ where: { id: contactId },
+ data: { imageUrl: stored },
+ });
+
+ return { stored: true, imageUrl: stored };
+}
+
+export async function runPortrait({
+ contactId,
+ spend,
+ force = false,
+}: {
+ contactId: string;
+ spend: (units?: number) => { ok: boolean; reason?: string };
+ force?: boolean;
+}): Promise<PortraitResult> {
+ if (!blobEnabled()) {
+ return {
+ stored: false,
+ imageUrl: null,
+ reason:
+ "This install has no BLOB_READ_WRITE_TOKEN, so there is nowhere to keep a copy. Retrying will not help.",
+ };
+ }
+
+ const contact = await db.contact.findUnique({
+ where: { id: contactId },
+ select: {
+ id: true,
+ firstName: true,
+ lastName: true,
+ imageUrl: true,
+ linkedinUrl: true,
+ githubUrl: true,
+ company: { select: { name: true, domain: true } },
+ },
+ });
+
+ if (!contact) {
+ return { stored: false, imageUrl: null, reason: "No such contact." };
+ }
+
+ if (!force && contact.imageUrl) {
+ return {
+ stored: false,
+ imageUrl: contact.imageUrl,
+ reason: "They already have a photo.",
+ };
+ }
+
+ const found = await findPortrait(
+ {
+ id: contact.id,
+ name:
+ [contact.firstName, contact.lastName].filter(Boolean).join(" ") || null,
+ linkedinUrl: contact.linkedinUrl,
+ githubUrl: contact.githubUrl,
+ companyName: contact.company?.name ?? null,
+ companyDomain: contact.company?.domain ?? null,
+ },
+ spend,
+ );
+
+ if (!found.found) {
+ return {
+ stored: false,
+ imageUrl: contact.imageUrl,
+ reason:
+ found.reason ??
+ (found.tried.length > 0
+ ? `No picture found. Tried: ${found.tried.join("; ")}.`
+ : "Nothing on this contact points at a picture — no LinkedIn or GitHub profile, and no company website."),
+ };
+ }
+
+ const result = await storePortrait({
+ contactId,
+ sourceUrl: found.candidate.url,
+ verified: true,
+ force,
+ });
+
+ return { ...result, source: found.candidate.source };
+}
diff --git a/apps/agent/agent/lib/preamble.ts b/apps/agent/agent/lib/preamble.ts
index 895c15f8..a9ee133a 100644
--- a/apps/agent/agent/lib/preamble.ts
+++ b/apps/agent/agent/lib/preamble.ts
@@ -1,30 +1,7 @@
import { db } from "@crm/db";
import { capabilitiesMarkdown } from "./capabilities";
-/**
- * What a session is told before it says anything.
- *
- * Two things vary, and both were getting the agent into trouble.
- *
- * **Which record.** A person, a company and a deal are three different
- * conversations. The company preamble used to say "we know 6 contact(s) here"
- * and could not name one of them, so the agent — knowing people existed and
- * having no way to address any of them — asked the rep to paste a contact id
- * off the screen they were looking at. Every neighbouring record is now named
- * **with its id**, because an id in the preamble is a tool call and a count is
- * a dead end.
- *
- * **Who opened it.** A dispatched task is a research pass with a budget. A rep
- * in the contact sheet is a conversation. Told neither, the agent assumed the
- * first, which is how a question got a work plan back.
- *
- * Pure apart from reading the database: the focus to seed is *returned* rather
- * than set, so `instructions/task.ts` owns that one side effect and these are
- * testable outside an eve turn.
- */
-
export type Opened = {
- /** Started by `schedules/dispatch.ts` rather than by a person. */
dispatched: boolean;
kind?: string | null;
reason?: string | null;
@@ -33,11 +10,9 @@ export type Opened = {
export type Preamble = {
markdown: string;
- /** What the audit hook should file this session's events against. */
focus: { contactId?: string | null; companyId?: string | null };
};
-/** The record the session was opened on, whichever it is. */
export async function sessionPreamble(
record: {
contactId?: string | null;
@@ -52,13 +27,6 @@ export async function sessionPreamble(
return noRecordPreamble();
}
-/**
- * What kind of exchange this is, said in one line.
- *
- * The same record supports both, and they want opposite behaviour: a
- * dispatched pass should go and find things, a rep with the sheet open wants
- * the question in front of them answered from what we already have.
- */
function opening(opened: Opened, questions: string): string {
if (opened.dispatched) {
return [
@@ -76,14 +44,6 @@ function opening(opened: Opened, questions: string): string {
].join(" ");
}
-/**
- * A session opened from a person's record.
- *
- * Their company id is stated outright. Its absence was a dead end with a
- * confusing symptom: the agent could see where somebody worked, had no id to
- * pass to any company tool, and reported that no company was available — about
- * a contact who plainly had one.
- */
export async function contactPreamble(
contactId: string,
opened: Opened,
@@ -169,13 +129,6 @@ export async function contactPreamble(
};
}
-/**
- * A session opened from a company's record.
- *
- * The people are **named, with their ids**, which is the whole fix: a count
- * told the agent that contacts existed without letting it address one, so it
- * handed the CRM's own join back to the person using it.
- */
export async function companyPreamble(
companyId: string,
opened: Opened,
@@ -254,14 +207,6 @@ export async function companyPreamble(
return { markdown, focus: { companyId } };
}
-/**
- * A session opened from a deal's record.
- *
- * A deal is the one record where the *state* matters as much as the facts:
- * which stage, how much, who is on it, and when it was last touched. Those are
- * the questions a rep opens a deal to ask, so they are what the session starts
- * knowing.
- */
export async function dealPreamble(
dealId: string,
opened: Opened,
@@ -334,17 +279,9 @@ export async function dealPreamble(
capabilitiesMarkdown(),
].join("\n");
- // Focused on the company, because that is the record every fact the agent
- // can write hangs off — a deal has no fields of its own to enrich.
return { markdown, focus: { companyId: deal.company?.id ?? null } };
}
-/**
- * No record at all — the dev TUI, or a dispatched pass over the queue.
- *
- * Worth saying rather than falling through to bare capabilities: without it
- * the agent has no idea the CRM is searchable, and waits to be handed an id.
- */
export function noRecordPreamble(): Preamble {
return {
markdown: [
diff --git a/apps/agent/agent/lib/socials.ts b/apps/agent/agent/lib/socials.ts
index c1587303..2364ebd5 100644
--- a/apps/agent/agent/lib/socials.ts
+++ b/apps/agent/agent/lib/socials.ts
@@ -6,40 +6,11 @@ import {
} from "./names";
import { ask } from "./perplexity";
-/**
- * Finding somebody's X and GitHub accounts, and — the part that matters —
- * refusing to write one we cannot stand behind.
- *
- * The failure mode here is not "no link". It is a link to a *different real
- * person* with a similar handle, sitting on a customer record looking exactly
- * like a fact. `github.com/lewis` belongs to someone; so does `x.com/lewis`.
- * A search engine asked "what is Lewis Carhart's GitHub" will happily hand one
- * of them over, because that is what it was asked for.
- *
- * So each network is checked by whatever hard evidence that network actually
- * exposes, and the two are not equally checkable:
- *
- * - **GitHub** has a public API. We fetch the account and read its own `name`,
- * `company` and `bio`. That is the person's own page telling us who they are,
- * which is real corroboration.
- * - **X** has nothing readable — the profile page is a JavaScript shell to
- * anyone without a paid API key. So the bar is the handle being a
- * construction of their name *and* a search engine independently citing that
- * exact profile when asked about this person by name and employer. Handles
- * that clear neither are left empty.
- *
- * Every check in here runs against the CRM's own copy of who the contact is,
- * never against anything the model passed in — otherwise "verification" is just
- * the model marking its own homework.
- */
-
export type Network = "x" | "github";
export type SocialProfile = {
network: Network;
- /** Lowercased, no leading `@`. */
handle: string;
- /** The canonical profile URL, which is what gets written to the record. */
url: string;
};
@@ -52,17 +23,6 @@ export type Person = {
companyDomain: string | null;
};
-/**
- * What a check found, not what it decided.
- *
- * These functions used to return `accepted: true | false`, which made each one
- * its own little confidence policy — and meant a GitHub account that merely
- * shared an employer was written to a record with the same authority as one
- * that named the person. Returning evidence instead puts every network through
- * the same ledger, and the difference shows up where it should: a verified
- * GitHub account lands on the record, an X handle that can only ever be
- * corroborated indirectly becomes a suggestion.
- */
export type Verdict =
| { accepted: true; profile: SocialProfile; evidence: Evidence[] }
| { accepted: false; reason: string };
@@ -77,12 +37,6 @@ const X_HOSTS = new Set([
const GITHUB_HOSTS = new Set(["github.com", "www.github.com"]);
-/**
- * First-segment paths that look like a profile and are not one.
- *
- * `x.com/settings` and `github.com/pricing` parse identically to a username,
- * and both turn up in search results about a person.
- */
const X_RESERVED = new Set([
"i",
"home",
@@ -130,19 +84,9 @@ const GITHUB_RESERVED = new Set([
"notifications",
]);
-/** X's own rule: up to 15 word characters. */
const X_HANDLE = /^[A-Za-z0-9_]{1,15}$/;
-/** GitHub's own rule: alphanumerics and single inner hyphens, up to 39. */
const GITHUB_HANDLE = /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/;
-/**
- * A profile URL, or null for anything that is not one.
- *
- * Rejects deep links on purpose: `x.com/someone/status/123` and
- * `github.com/someone/repo` both contain a real handle, and both arrive as
- * citations constantly. Taking the first segment out of them would be right
- * about the handle and wrong about what the page proves.
- */
export function parseSocialUrl(raw: string): SocialProfile | null {
const trimmed = raw.trim();
if (!trimmed) return null;
@@ -185,7 +129,6 @@ export function parseSocialUrl(raw: string): SocialProfile | null {
return null;
}
-/** Every profile URL in a blob of text and citations, deduplicated. */
export function extractSocialUrls(haystack: string[]): SocialProfile[] {
const found: SocialProfile[] = [];
@@ -193,9 +136,6 @@ export function extractSocialUrls(haystack: string[]): SocialProfile[] {
for (const match of chunk.matchAll(
/https?:\/\/(?:www\.|mobile\.)?(?:x\.com|twitter\.com|github\.com)\/[^\s"'<>)\]},]+/gi,
)) {
- // Prose ends in punctuation and URLs do not: a link at the end of a
- // sentence arrives as `x.com/lewiscarhart.`, which is not a handle
- // either network could issue and would otherwise be dropped silently.
const profile = parseSocialUrl(match[0].replace(/[.,;:!?]+$/, ""));
if (profile && !found.some((f) => f.url === profile.url)) {
found.push(profile);
@@ -215,12 +155,6 @@ type GithubUser = {
type: string;
};
-/**
- * The account's own page, from GitHub's public API.
- *
- * `GITHUB_TOKEN` is read if it is set — unauthenticated calls are capped at 60
- * an hour per IP, which is fine for ten contacts but not for a backfill.
- */
async function fetchGithubUser(
handle: string,
): Promise<{ ok: true; user: GithubUser } | { ok: false; reason: string }> {
@@ -243,8 +177,6 @@ async function fetchGithubUser(
return { ok: false, reason: "No such GitHub account." };
}
if (response.status === 403 || response.status === 429) {
- // Rate limited is not "unverified" — it is "we do not know", and the two
- // must not collapse into a write.
return {
ok: false,
reason: "GitHub rate-limited the check. Try this contact again later.",
@@ -275,16 +207,6 @@ async function fetchGithubUser(
}
}
-/**
- * What GitHub's own API says about an account, as evidence.
- *
- * The account naming the person is primary — it is their page asserting who
- * they are. The employer matching while the name does not is emphatically
- * *not*: `github.com/octocat` with `company: @CompAI` is a colleague, and
- * writing it to Lewis's record because they share an employer is the same
- * mistake as writing a stranger's LinkedIn to a contact because the company
- * matched. Both are recorded; the ledger prices them differently.
- */
export async function verifyGithub(
profile: SocialProfile,
person: Person,
@@ -314,9 +236,6 @@ export async function verifyGithub(
);
if (named) {
- // One item, not one per matching field: the name and the company sit on
- // the same page, so treating them as independent sources would multiply a
- // single observation into false certainty.
const detail = employed
? `the account is named "${user.name}" and its company reads "${user.company}"`
: `the account is named "${user.name}"`;
@@ -373,17 +292,6 @@ export async function verifyGithub(
return { accepted: true, profile, evidence };
}
-/**
- * Whether an X account is this contact's, given that nobody can read X.
- *
- * Two things, and both are checked here rather than asked of the model. The
- * handle has to be a construction of their name, which rules out the
- * pseudonymous accounts we could never confirm; and a search engine has to cite
- * that exact profile when asked about them by name and employer, which is the
- * only outside corroboration available. A handle that is really the company's
- * account is rejected before either — `x.com/trycompai` passes a name check for
- * nobody and gets filed against everybody.
- */
export async function verifyX(
profile: SocialProfile,
person: Person,
@@ -416,8 +324,6 @@ export async function verifyX(
};
}
- // The tool does its own asking. A citation handed over by the model is a
- // citation the model can invent.
const answer = await ask(
`Is https://x.com/${profile.handle} the X (Twitter) account of ${person.fullName}` +
`${person.title ? `, ${person.title}` : ""}` +
@@ -447,10 +353,6 @@ export async function verifyX(
};
}
- // Neither of these is primary, and that is the honest result: X cannot be
- // read, so the strongest thing available is two indirect signals agreeing.
- // The ledger turns that into a suggestion for a rep rather than a write,
- // which is the right place for a link nobody can check.
return {
accepted: true,
profile,
@@ -469,13 +371,6 @@ export async function verifyX(
};
}
-/**
- * Candidate profile URLs from the open web.
- *
- * Candidates, never answers — same rule as LinkedIn slugs. The URLs are taken
- * from the citations rather than the prose, because a cited URL was actually
- * retrieved and a quoted one may have been composed on the spot.
- */
export async function findSocialCandidates(
person: Person,
network: Network,
diff --git a/apps/agent/agent/lib/tasks.ts b/apps/agent/agent/lib/tasks.ts
index c1c5cbb9..0680a0ac 100644
--- a/apps/agent/agent/lib/tasks.ts
+++ b/apps/agent/agent/lib/tasks.ts
@@ -1,14 +1,5 @@
import { db, type Prisma } from "@crm/db";
-/**
- * The work queue the agent both reads and writes.
- *
- * The point of a table rather than a cron expression per kind of work: a cron
- * can only say "every hour, for everybody". A row can say *this person, in
- * fourteen days, because a job change here would move a live deal* — and the
- * reason is the agent's own words, shown to the rep on the record.
- */
-
export type LeasedTask = {
id: string;
contactId: string | null;
@@ -19,7 +10,6 @@ export type LeasedTask = {
attempts: number;
};
-/** The subject of a row, which is what an enrichment status hangs off. */
export type TaskSubject = {
id: string;
contactId: string | null;
@@ -27,34 +17,10 @@ export type TaskSubject = {
kind: string;
};
-/** How long a dispatcher tick holds a row before another one may retry it. */
const LEASE_MS = 10 * 60_000;
-/**
- * How many hand-offs a row gets before it is given up on.
- *
- * The lease makes a crashed run recoverable; this makes an unrecoverable one
- * stop. Three is enough to ride out a redeploy and a transient vendor outage,
- * and small enough that a task which can never park costs three model turns
- * rather than one every ten minutes until somebody notices.
- */
export const MAX_ATTEMPTS = 3;
-/**
- * Claims due work atomically.
- *
- * `FOR UPDATE SKIP LOCKED` inside the subquery is what makes this safe to run
- * from more than one process at a time — two dispatchers ticking together take
- * disjoint sets rather than racing for the same row. That matters more than it
- * looks: it is what lets the agent be deployed twice (its own service, and
- * embedded in the app) without doing every job twice.
- *
- * The lease is a deadline rather than a flag, so a run that crashes mid-task
- * frees itself. A `finishedAt` is what actually retires a row.
- *
- * Each claim charges an attempt. Rows that have spent their allowance are
- * skipped here and retired by `retireExhausted`.
- */
export async function claimDue(limit: number): Promise<LeasedTask[]> {
const now = new Date();
const until = new Date(now.getTime() + LEASE_MS);
@@ -79,13 +45,6 @@ export async function claimDue(limit: number): Promise<LeasedTask[]> {
`;
}
-/**
- * Gives up on rows that have been dispatched their allowance without ever
- * reporting back, and hands them to the caller so the record can say so.
- *
- * Only unleased rows, so a run still legitimately in flight on its last
- * attempt is left alone.
- */
export async function retireExhausted(): Promise<TaskSubject[]> {
const now = new Date();
@@ -100,15 +59,6 @@ export async function retireExhausted(): Promise<TaskSubject[]> {
`;
}
-/**
- * Retires a row, once.
- *
- * The `finishedAt IS NULL` guard is what makes this idempotent: a session parks
- * at the end of every turn, and only the turn that belongs to this dispatch
- * should close the row. A second park — a rep carrying on the same thread from
- * the sheet, say — finds it already closed and returns null rather than
- * re-stamping an outcome over the real one.
- */
export async function completeTask(
taskId: string,
outcome: string,
@@ -131,7 +81,6 @@ export async function completeTask(
});
}
-/** Who a row is about, without disturbing it. */
export async function taskSubject(taskId: string): Promise<TaskSubject | null> {
return db.agentTask.findUnique({
where: { id: taskId },
@@ -139,13 +88,6 @@ export async function taskSubject(taskId: string): Promise<TaskSubject | null> {
});
}
-/**
- * Records which durable session took the work.
- *
- * Written at hand-off rather than at completion, because `receive` resolves as
- * soon as the session accepts the message — the run itself outlives the
- * dispatcher tick that started it, and this is the only thread back to it.
- */
export async function noteSession(
taskId: string,
sessionId: string,
@@ -156,13 +98,6 @@ export async function noteSession(
});
}
-/**
- * Books the next look at somebody.
- *
- * The reason is not decoration — it is shown on the record, and it is the
- * difference between an agent that runs on a schedule and one that has a view
- * about who is worth revisiting.
- */
export async function scheduleTask(input: {
contactId?: string | null;
companyId?: string | null;
@@ -172,9 +107,6 @@ export async function scheduleTask(input: {
priority?: number;
budget?: number;
}): Promise<{ id: string }> {
- // One outstanding task per subject and kind. An agent that queues itself
- // twice for the same person is an agent that spends twice as much to learn
- // the same thing.
const existing = await db.agentTask.findFirst({
where: {
kind: input.kind,
@@ -207,7 +139,6 @@ export async function scheduleTask(input: {
});
}
-/** What the agent last decided about a contact, for the sheet to show. */
export async function lastDecision(contactId: string) {
return db.agentTask.findFirst({
where: { contactId },
@@ -222,5 +153,4 @@ export async function lastDecision(contactId: string) {
});
}
-/** Kept for the raw query above to stay type-checked against the schema. */
export type { Prisma };
diff --git a/apps/agent/agent/sandbox/sandbox.ts b/apps/agent/agent/sandbox/sandbox.ts
index c6b1d7aa..a9f1c9fb 100644
--- a/apps/agent/agent/sandbox/sandbox.ts
+++ b/apps/agent/agent/sandbox/sandbox.ts
@@ -1,31 +1,5 @@
import { defaultBackend, defineSandbox } from "eve/sandbox";
-/**
- * The agent's shell, with the network taken away.
- *
- * Turning a sandbox on is what gives the model `bash`, `read_file`,
- * `write_file`, `glob` and `grep` — the difference between a tool-caller and
- * something that can keep a dossier on a person, diff this month's profile
- * against last month's, and grep a thread for a signature block.
- *
- * `deny-all` costs nothing, because of where the other tools run: `web_fetch`
- * executes in the app runtime and `web_search` at the model provider, so
- * retrieval is unaffected by the sandbox having no egress. What it removes is
- * the only path by which customer email bodies — which this agent reads in full
- * — could leave the building through a shell command.
- *
- * The other half of that rule is not here, because it is an absence: **the
- * sandbox is never given `DATABASE_URL`.** Backends take explicit `env`, so
- * nothing is inherited. CRM access is authored tools in the app runtime, never
- * `psql`. A shell with credentials and egress is exfiltration-shaped even in an
- * internal tool; a shell with neither is a text processor.
- *
- * The policy is set on the backend factory rather than in `onSession` so it
- * applies to every session by construction — a per-session call is a per-session
- * call somebody can forget. No backend is pinned: `defaultBackend()` resolves
- * Vercel Sandbox in production and Docker or microsandbox locally, and each one
- * is told the same thing.
- */
export default defineSandbox({
backend: defaultBackend({
vercel: { networkPolicy: "deny-all" },
diff --git a/apps/agent/agent/schedules/dispatch.ts b/apps/agent/agent/schedules/dispatch.ts
index 7f954fc2..11eb9e6f 100644
--- a/apps/agent/agent/schedules/dispatch.ts
+++ b/apps/agent/agent/schedules/dispatch.ts
@@ -2,39 +2,21 @@ import { EnrichmentStatus } from "@crm/db";
import { defineSchedule } from "eve/schedules";
import crm from "../channels/crm";
import { markRunning, settle } from "../lib/enrichment";
-import { claimDue, noteSession, retireExhausted } from "../lib/tasks";
+import { runPortrait } from "../lib/portrait";
+import {
+ claimDue,
+ completeTask,
+ noteSession,
+ retireExhausted,
+} from "../lib/tasks";
-/** Per tick. The cap is concurrency, not ambition — the queue keeps. */
const BATCH = 5;
-/**
- * The agent's clock.
- *
- * One schedule for everything, and it decides nothing: it leases whatever is
- * due and starts a session per row. What the work *is* comes from the row —
- * written by the API when something happened, or by the agent itself when it
- * decided a person was worth another look in a fortnight.
- *
- * This is the difference the plan is named for. The schedules it replaces said
- * "every 20 minutes, the ten oldest contacts", which treats the CEO of a live
- * opportunity and a bounced alias identically because they sorted adjacently.
- *
- * Handler form rather than markdown, because the batch has to be claimed in
- * code — and because a handler-form session can park for a human, which task
- * mode cannot.
- */
export default defineSchedule({
cron: "* * * * *",
async run({ receive, waitUntil, appAuth }) {
waitUntil(
(async () => {
- // Rows that spent their attempts without a session ever reporting
- // back. Retiring them before claiming keeps the sweep on the same
- // clock as the work rather than needing a schedule of its own.
- //
- // Guarded, because a throw here returns before `claimDue` and the
- // queue simply stops: a sweep that only tidies up must never be able
- // to prevent the work it tidies up after.
try {
for (const abandoned of await retireExhausted()) {
await settle(
@@ -51,19 +33,33 @@ export default defineSchedule({
await Promise.all(
tasks.map(async (task) => {
try {
+ if (task.kind === "portrait" && task.contactId) {
+ const portrait = await runPortrait({
+ contactId: task.contactId,
+ spend: () => ({ ok: true }),
+ });
+
+ // The outcome is the answer, not a tick. The backfill reads
+ // these rows to decide who not to look for again, so "no
+ // picture on LinkedIn, not on the company's site" has to
+ // survive here — otherwise the only record of a month's worth
+ // of paid lookups is that they happened.
+ await completeTask(
+ task.id,
+ portrait.stored
+ ? `Picture stored from ${portrait.source}.`
+ : (portrait.reason ?? "No picture found."),
+ );
+ return;
+ }
+
await markRunning(task);
const session = await receive(crm, {
message: brief(task),
- // The channel keys its continuation token off this, so a
- // re-dispatched lease resumes the run rather than starting
- // the research over.
target: { taskId: task.id },
auth: {
...appAuth,
- // Read by `instructions/task.ts` at `session.started`, so
- // the run opens knowing who it is about and what it may
- // spend instead of paying two tool calls to find out.
attributes: {
taskKind: task.kind,
reason: task.reason,
@@ -74,25 +70,11 @@ export default defineSchedule({
},
});
- // Hand-off, not completion: `receive` resolves the moment the
- // session accepts the message, and the run outlives this tick.
- // Retiring the row is the channel's `session.waiting` hook,
- // which fires when the turn is genuinely over. Completing here
- // instead would close rows before the research ran.
await noteSession(task.id, session.id);
} catch (error) {
const reason =
error instanceof Error ? error.message : String(error);
- // A hand-off that threw never reached a session, so nothing
- // downstream will ever close this row. Leave it open for the
- // lease to re-offer, bounded by the attempt cap, and say on the
- // record why nothing is happening yet.
- //
- // Nothing rethrows: one bad row must not take the batch down
- // with it. `waitUntil` receives the rejection with no handler
- // attached, which is an unhandled rejection inside the cron
- // task rather than a logged error.
await settle(task, EnrichmentStatus.FAILED, reason).catch(
() => {},
);
@@ -104,14 +86,6 @@ export default defineSchedule({
},
});
-/**
- * What the session is asked to do.
- *
- * Short on purpose. The detail — who this person is, what we already know, what
- * is missing — is assembled by the dynamic instructions from the database,
- * where it is current, rather than pasted into a prompt here, where it would be
- * a snapshot taken by whoever queued the row.
- */
function brief(task: {
kind: string;
reason: string;
@@ -119,9 +93,6 @@ function brief(task: {
companyId: string | null;
attempts: number;
}): string {
- // A retry resumes the same durable session, so the transcript is already
- // there — saying so is what stops it being read as a fresh identical request
- // and researched from scratch on somebody else's budget.
const again =
task.attempts > 1
? `This is attempt ${task.attempts}; the earlier one did not finish. Carry on from what is already in this thread rather than starting again. `
diff --git a/apps/agent/agent/skills/identity-matching.md b/apps/agent/agent/skills/identity-matching.md
index d943c43e..e5ff9f66 100644
--- a/apps/agent/agent/skills/identity-matching.md
+++ b/apps/agent/agent/skills/identity-matching.md
@@ -32,7 +32,10 @@ That is the shape of every match: guess where to look, never what you will find.
1. **`resolve_linkedin_profile`** with the email and company. It decomposes the
local part and returns candidate slugs. These are leads, not answers.
2. **`get_linkedin_profile`** on each candidate, passing the email, company name
- and domain. It returns the profile *and a verdict*.
+ and domain — **and the `contactId`**. It returns the profile *and a verdict*.
+ Passing the id is what lets it copy their photograph, which it does only if
+ the verdict comes back positive, in code, without asking you. Leaving it out
+ costs the contact their picture and saves nothing.
3. **Read the verdict, not the profile.** It checks two things:
- `employerMatches` — a current position matches the company we have.
- `nameMatches` — the real name is consistent with the email local part
@@ -42,6 +45,10 @@ That is the shape of every match: guess where to look, never what you will find.
5. If no candidate passes, **stop**. Leaving "Pmarchetti" in the CRM is the correct
outcome when you do not know.
+Somebody whose LinkedIn URL is **already on the record** has been through all of
+this before. Do not re-run it to get a picture — `fetch_contact_photo` is one
+call, and the URL sitting there is the verification.
+
## Reporting the match
Call `identify_contact` with what you actually saw:
diff --git a/apps/agent/agent/tools/enrich_company.ts b/apps/agent/agent/tools/enrich_company.ts
index 9dfe3a61..8ec6a790 100644
--- a/apps/agent/agent/tools/enrich_company.ts
+++ b/apps/agent/agent/tools/enrich_company.ts
@@ -1,22 +1,11 @@
import { db, EnrichmentStatus } from "@crm/db";
import { defineTool } from "eve/tools";
import { z } from "zod";
+import { mirrorBrandImages } from "../lib/brand-images";
import { brandToUpdate, filledFields } from "../lib/brand-mapping";
import { brandByDomain, contextDevEnabled } from "../lib/context-dev";
import { spend } from "../lib/focus";
-/**
- * A company's brand, firmographics and socials, from Context.dev.
- *
- * This used to be a Nest service on the API side, queued from a request
- * handler. Nothing about the lookup changed in the move; what changed is who
- * decides to make it. The API now says "a company exists with nothing but a
- * domain" and this decides whether that is worth ten credits.
- *
- * Fills gaps only. `brandToUpdate` has always refused to overwrite a field a
- * human filled in, and that rule is the same one the fact store applies to
- * people.
- */
export default defineTool({
description:
"Look up a company's brand, industry, location and social links by domain, and fill in the blanks on its record. Fills empty fields only — never overwrites what a person typed.",
@@ -88,8 +77,6 @@ export default defineTool({
},
});
- // `fresh` asks for a cache bypass; anything else takes whatever the vendor
- // has, because a 90-day-old logo is still the logo.
const result = await brandByDomain(company.domain, fresh ? 0 : undefined);
if (result.outcome === "skipped") {
@@ -108,12 +95,12 @@ export default defineTool({
const update = brandToUpdate(result.brand, {
...company,
- // A company the sync created is named after its domain until we know
- // better, and that is the one non-null field a lookup may replace.
nameIsPlaceholder: company.name === company.domain,
});
const filled = filledFields(update);
+ const { mirrored } = await mirrorBrandImages(companyId, update);
+
await db.$transaction([
db.company.update({ where: { id: companyId }, data: update }),
db.companyEnrichment.upsert({
@@ -134,6 +121,7 @@ export default defineTool({
return {
enriched: true as const,
filled,
+ mirrored,
note:
filled.length === 0
? "Everything it returned was already on the record."
diff --git a/apps/agent/agent/tools/fetch_contact_photo.ts b/apps/agent/agent/tools/fetch_contact_photo.ts
new file mode 100644
index 00000000..8b8f6f04
--- /dev/null
+++ b/apps/agent/agent/tools/fetch_contact_photo.ts
@@ -0,0 +1,30 @@
+import { blobEnabled } from "@crm/db/blob";
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+import { spend } from "../lib/focus";
+import { runPortrait } from "../lib/portrait";
+
+export default defineTool({
+ description:
+ "Find and store a photograph for a contact, from their LinkedIn profile, their GitHub account, or their employer's own team page — whichever is on the record. Never searches for a face by name. Reports which source it used, or what it tried.",
+ inputSchema: z.object({
+ contactId: z.string(),
+ force: z
+ .boolean()
+ .default(false)
+ .describe("Replace an existing photo. Only when a rep asked."),
+ }),
+ async execute({ contactId, force }) {
+ if (!blobEnabled()) {
+ return {
+ stored: false as const,
+ configured: false as const,
+ reason:
+ "This install has no BLOB_READ_WRITE_TOKEN, so there is nowhere to keep a copy, and " +
+ "the source URLs expire. Retrying will not help.",
+ };
+ }
+
+ return runPortrait({ contactId, spend, force });
+ },
+});
diff --git a/apps/agent/agent/tools/find_contact_socials.ts b/apps/agent/agent/tools/find_contact_socials.ts
index bd8e7bbb..307aa91e 100644
--- a/apps/agent/agent/tools/find_contact_socials.ts
+++ b/apps/agent/agent/tools/find_contact_socials.ts
@@ -4,14 +4,6 @@ import { personForVerification, stampSocialsChecked } from "../lib/crm";
import { focusOn, spend } from "../lib/focus";
import { findSocialCandidates } from "../lib/socials";
-/**
- * Candidates, never answers — the same contract as `resolve_linkedin_profile`.
- *
- * Perplexity is good at finding where somebody lives on the web and bad at
- * being sure it is the right somebody: asked for a person's GitHub it returns
- * *a* GitHub, because that is what the question wanted. `set_contact_socials`
- * is what decides.
- */
export default defineTool({
description:
"Search the web for a contact's X and GitHub profiles. Returns CANDIDATES ONLY — pass them to set_contact_socials, which re-checks each one against the account itself before writing. Never write these URLs any other way.",
@@ -19,7 +11,6 @@ export default defineTool({
contactId: z.string(),
}),
async execute({ contactId }) {
- // So the audit hook files this session's events against the right record.
focusOn({ contactId });
const person = await personForVerification(contactId);
@@ -27,8 +18,6 @@ export default defineTool({
return { searched: false as const, reason: "No such contact." };
}
- // Two searches, so two units. Most people have neither account, which is
- // exactly why this should not be the thing that empties a budget.
const charge = spend(2);
if (!charge.ok) return { searched: false as const, reason: charge.reason };
@@ -37,9 +26,6 @@ export default defineTool({
findSocialCandidates(person, "github"),
]);
- // Stamped here, not only on a successful write. Most people have neither
- // account, and "we looked and found nothing" has to be recorded or this
- // contact comes back around every hour for the same two searches.
await stampSocialsChecked(contactId);
return {
diff --git a/apps/agent/agent/tools/get_contact_work_history.ts b/apps/agent/agent/tools/get_contact_work_history.ts
index b7cfe705..b6ace330 100644
--- a/apps/agent/agent/tools/get_contact_work_history.ts
+++ b/apps/agent/agent/tools/get_contact_work_history.ts
@@ -4,17 +4,6 @@ import { enabled, unavailable } from "../lib/capabilities";
import { contactProfileSlug } from "../lib/crm";
import { getExperience, getProfile } from "../lib/linkdapi";
-/**
- * Reads the profile already on a contact's record — headline, current roles and
- * full work history.
- *
- * Takes a `contactId` rather than a slug on purpose. `get_linkedin_profile`
- * exists to *decide* whether a stranger is the person behind an address, and it
- * returns a verdict for exactly that reason; a second tool that reads any slug
- * without one would be the easy way to skip the check. This one can only read
- * the profile a verified match (or a rep) already put on the record, so there
- * is no identity question left for it to get wrong.
- */
export default defineTool({
description:
"Read the LinkedIn profile already on a CRM contact — headline, current roles and full work history. For writing a summary of somebody already identified. Cannot be used to identify anyone: use resolve_linkedin_profile and get_linkedin_profile for that.",
diff --git a/apps/agent/agent/tools/get_linkedin_profile.ts b/apps/agent/agent/tools/get_linkedin_profile.ts
index 2d12fc8b..bc4cf3f4 100644
--- a/apps/agent/agent/tools/get_linkedin_profile.ts
+++ b/apps/agent/agent/tools/get_linkedin_profile.ts
@@ -4,12 +4,8 @@ import { enabled, unavailable } from "../lib/capabilities";
import { spend } from "../lib/focus";
import { getExperience, getProfile } from "../lib/linkdapi";
import { looksLikeSameCompany, nameMatchesLocalPart } from "../lib/names";
+import { storePortrait } from "../lib/portrait";
-/**
- * Reads a candidate and judges it, rather than handing the model a profile and
- * hoping. The two checks are the thing standing between a search result and a
- * customer record.
- */
export default defineTool({
description:
"Read a LinkedIn profile by slug and check whether it is really the person behind an email address. Returns the profile plus an explicit verdict.",
@@ -22,14 +18,25 @@ export default defineTool({
.boolean()
.default(false)
.describe("Also fetch full work history — costs an extra call."),
+ contactId: z
+ .string()
+ .optional()
+ .describe(
+ "The CRM contact this candidate is for. Supply it and their photo is copied automatically if — and only if — the profile turns out to be them.",
+ ),
}),
- async execute({ slug, email, companyName, companyDomain, includeHistory }) {
+ async execute({
+ slug,
+ email,
+ companyName,
+ companyDomain,
+ includeHistory,
+ contactId,
+ }) {
if (!enabled("RAPIDAPI_KEY")) {
return { found: false as const, ...unavailable("RAPIDAPI_KEY") };
}
- // Charged before the call, not after: a budget that only counts successes
- // is a budget an unlucky contact can blow through four times over.
const charge = spend(includeHistory ? 2 : 1);
if (!charge.ok) return { found: false as const, reason: charge.reason };
@@ -51,16 +58,26 @@ export default defineTool({
const history =
includeHistory && profile.urn ? await getExperience(profile.urn) : null;
+ const isSamePerson = employerMatches && nameMatches;
+
+ const portrait =
+ contactId && isSamePerson
+ ? await storePortrait({
+ contactId,
+ sourceUrl: profile.photoUrl,
+ verified: true,
+ })
+ : null;
+
return {
found: true as const,
profile,
experience: history?.ok ? history.data : null,
+ photo: portrait ?? undefined,
verdict: {
employerMatches,
nameMatches,
- // Both, or it is not them. Stated as a decision rather than as two
- // facts so there is nothing to reinterpret.
- isSamePerson: employerMatches && nameMatches,
+ isSamePerson,
confidence:
employerMatches && nameMatches
? ("high" as const)
diff --git a/apps/agent/agent/tools/identify_contact.ts b/apps/agent/agent/tools/identify_contact.ts
index f30b32e2..015e8e3b 100644
--- a/apps/agent/agent/tools/identify_contact.ts
+++ b/apps/agent/agent/tools/identify_contact.ts
@@ -5,21 +5,6 @@ import { WEIGHTS } from "../lib/evidence";
import { recordFact } from "../lib/facts";
import { focusOn } from "../lib/focus";
-/**
- * Putting a real name to an address.
- *
- * This used to take a `confidence` enum from the model and refuse anything
- * below `high`. Two things were wrong with that. The bar was set by the thing
- * being judged — a rubric the model could talk itself out of — and everything
- * below the bar was thrown away, so an ambiguous address cost a lookup every
- * run and produced nothing, forever.
- *
- * Now it takes evidence. A profile carrying their email address, or a reply on
- * a thread we already have, names them outright and is written. One weak signal
- * short of that becomes a suggestion a rep settles in three seconds — which is
- * the case this tool exists for, because `[email protected]` has four
- * plausible Marchettis behind it and a human knows which.
- */
export default defineTool({
description:
"Put a verified name to a CRM contact, with the evidence for it. Strong evidence writes the name; anything less becomes a suggestion for a rep. Never overwrites a name a person supplied.",
diff --git a/apps/agent/agent/tools/list_outstanding_work.ts b/apps/agent/agent/tools/list_outstanding_work.ts
index bfb27583..fb6045d9 100644
--- a/apps/agent/agent/tools/list_outstanding_work.ts
+++ b/apps/agent/agent/tools/list_outstanding_work.ts
@@ -2,15 +2,6 @@ import { defineTool } from "eve/tools";
import { z } from "zod";
import { contactsNeedingWork } from "../lib/crm";
-/**
- * What is outstanding, not what to do about it.
- *
- * Each row says what is missing — a name, a background, socials — and the agent
- * decides which of those is worth doing for this person. The two tools this
- * replaced encoded that decision in their names, which meant the ordering of
- * the work was a property of the codebase rather than a judgement about the
- * contact.
- */
export default defineTool({
description:
"List CRM contacts with outstanding research: no real name yet, no background written, or socials never looked for. Each row says what is missing. Deciding what is worth doing, and in what order, is your job.",
diff --git a/apps/agent/agent/tools/read_company_history.ts b/apps/agent/agent/tools/read_company_history.ts
index fc542aab..aeab5da1 100644
--- a/apps/agent/agent/tools/read_company_history.ts
+++ b/apps/agent/agent/tools/read_company_history.ts
@@ -3,20 +3,6 @@ import { z } from "zod";
import { readCompanyHistory } from "../lib/accounts";
import { focusOn } from "../lib/focus";
-/**
- * The account, and everyone in it.
- *
- * The company equivalent of `read_crm_history`, and it exists because a
- * session opened on a company could count its contacts and not name one. The
- * agent's own words: "I don't have a tool that lists contacts by company, only
- * ones that look up a specific contact by ID or email" — so it asked the rep
- * to paste an id that the CRM had already joined for them.
- *
- * Free, like every read of our own database. It should be the first call in a
- * company session, and it is usually the last one needed: the people, the
- * deals, the correspondence and the notes come back together, each with the id
- * a follow-up tool wants.
- */
export default defineTool({
description:
"Read everything the CRM has on a company: every contact there with their id, title and whether we have heard from them; every deal with stage and value; recent email threads with full bodies; meetings; and notes. Free and fast — call it first in a company session, and whenever you need to find a person at a company you already know.",
diff --git a/apps/agent/agent/tools/read_crm_history.ts b/apps/agent/agent/tools/read_crm_history.ts
index 706acd87..a1370cbd 100644
--- a/apps/agent/agent/tools/read_crm_history.ts
+++ b/apps/agent/agent/tools/read_crm_history.ts
@@ -3,20 +3,6 @@ import { z } from "zod";
import { readCrmHistory } from "../lib/crm";
import { focusOn } from "../lib/focus";
-/**
- * What we already know, before spending anything to find out.
- *
- * This should usually be the *first* call on any contact, and it is free: no
- * vendor, no rate limit, no budget. It is also the strongest evidence available
- * anywhere in the system. A person who replied to us from an address is that
- * person, in a way no profile lookup can match, and their own signature block
- * outranks LinkedIn on a job title because people update a signature the week
- * they are promoted.
- *
- * Full message bodies are returned on purpose — single-tenant internal tool,
- * our own mailbox. The `data-boundaries` skill covers what may not then be done
- * with them.
- */
export default defineTool({
description:
"Read everything the CRM already has on a contact: email threads with full message bodies, meetings, whether they have ever replied, their company and its id, the deals they are on, and who else we know at their company. Free, fast, and the best evidence there is — call it before paying for a lookup.",
@@ -41,9 +27,6 @@ export default defineTool({
? "We have never actually spoken to this person. Nothing here is evidence of anything."
: "A signature block or a reply from their own address is primary evidence — record it as `crm.signature-block` or `crm.thread-reply`.";
- // The ids are called out because the absence of one used to end the
- // conversation: an agent that could see `companyName` and no id would
- // report that there was no company to look at.
const reach = history.contact.company
? ` Their company is \`${history.contact.company.id}\` — read_company_history or enrich_company take that id directly.`
: " They are not attached to a company; search_crm will find one by name or domain if the question needs it.";
diff --git a/apps/agent/agent/tools/read_deal_history.ts b/apps/agent/agent/tools/read_deal_history.ts
index e586e2f9..183c7b23 100644
--- a/apps/agent/agent/tools/read_deal_history.ts
+++ b/apps/agent/agent/tools/read_deal_history.ts
@@ -3,18 +3,6 @@ import { z } from "zod";
import { readDealHistory } from "../lib/accounts";
import { focusOn } from "../lib/focus";
-/**
- * Where a deal stands, rather than what its stage field says.
- *
- * A stage is a rep's last opinion, entered by hand, and it goes stale in
- * exactly the situation somebody opens the record to ask about. This returns
- * the things that disagree with it: how long it has sat in that stage, when
- * anyone on the other side last replied, whether there is a meeting booked,
- * and every stage it moved through to get here.
- *
- * Free. Nothing here costs budget, and it is the only way to answer "where
- * does this stand?" without asking the rep who is asking.
- */
export default defineTool({
description:
"Read a deal in full: stage and how long it has been there, value, close date, the whole stage history, who is on it with their contact ids, the correspondence and meetings with those people, and the notes. Free — call it first in a deal session.",
@@ -32,9 +20,6 @@ export default defineTool({
const history = await readDealHistory(dealId, { threads });
if (!history) return { found: false as const, reason: "No such deal." };
- // A deal has no fields of its own to enrich, so anything learned here is
- // recorded against the company or the people on it — which is what the
- // focus has to point at for the audit trail to file it correctly.
focusOn({ companyId: history.company.id });
return { found: true as const, ...history };
diff --git a/apps/agent/agent/tools/record_fact.ts b/apps/agent/agent/tools/record_fact.ts
index c5aa01c3..1f4925d8 100644
--- a/apps/agent/agent/tools/record_fact.ts
+++ b/apps/agent/agent/tools/record_fact.ts
@@ -5,18 +5,6 @@ import { WEIGHTS } from "../lib/evidence";
import { FACT_FIELDS, type FactField, recordFact } from "../lib/facts";
import { focusOn } from "../lib/focus";
-/**
- * One claim, with what backs it. The only write to a contact's fields.
- *
- * It takes evidence and never a score. That is the whole design: the model
- * reports what it *saw* — "their signature block says Head of Security" — and
- * the ledger decides what that is worth. A `confidence` argument would be the
- * model grading its own homework, and a `sourceUrl` accepted as proof would be
- * the same thing with extra steps.
- *
- * Whether this writes the record or offers a suggestion is decided by the
- * arithmetic, not by the caller. A rejection is a correct outcome.
- */
export default defineTool({
description:
"Record one claim about a contact — title, employer, a profile URL, seniority — together with the evidence for it. The evidence decides whether it is written to the record or offered to a rep as a suggestion. Never invent evidence you did not observe.",
diff --git a/apps/agent/agent/tools/record_job_change.ts b/apps/agent/agent/tools/record_job_change.ts
index cb5d3330..f6b6688e 100644
--- a/apps/agent/agent/tools/record_job_change.ts
+++ b/apps/agent/agent/tools/record_job_change.ts
@@ -6,29 +6,11 @@ import { writeTimelineNote } from "../lib/crm";
import { lastEmployerChange } from "../lib/facts";
import { focusOn } from "../lib/focus";
-/**
- * A champion changing employer — the highest-intent signal in B2B, and the one
- * nothing else in our stack sees.
- *
- * It costs nothing to detect, because it already happened: an `employer` fact
- * superseding an applied one *is* the job change. There is no diffing job and
- * no second data source. This tool turns that row into something a human will
- * actually notice.
- *
- * What it deliberately does **not** do is move the contact to their new
- * company. That re-parents the record — changes whose pipeline they sit in and
- * which timeline their history hangs off — and it is approval-gated for that
- * reason. Unattended, it raises the alert and lets their owner decide.
- */
export default defineTool({
description:
"Raise a job change on a contact's timeline and task their owner. Reads the change from the facts already recorded; call it after recording a new employer.",
inputSchema: z.object({
contactId: z.string(),
- /**
- * Moving them is the sensitive part, which is why it is a separate flag
- * rather than something that happens implicitly.
- */
moveToCompanyId: z
.string()
.optional()
@@ -65,8 +47,6 @@ export default defineTool({
.filter(Boolean)
.join(" ");
- // Lands on the *old* company's timeline, which is where the relationship
- // lives and where anyone reviewing that account will see it.
await writeTimelineNote(
contactId,
`${name} has moved to ${change.to}`,
diff --git a/apps/agent/agent/tools/research_company.ts b/apps/agent/agent/tools/research_company.ts
index c5841876..05b09a71 100644
--- a/apps/agent/agent/tools/research_company.ts
+++ b/apps/agent/agent/tools/research_company.ts
@@ -4,7 +4,6 @@ import { z } from "zod";
import { extract } from "../lib/context-dev";
import { spend } from "../lib/focus";
-/** The shape the brief is extracted into. */
const RESEARCH_SCHEMA = {
type: "object",
properties: {
@@ -39,15 +38,6 @@ const RESEARCH_INSTRUCTIONS =
"for a first call. Be specific and factual; leave a field empty rather than " +
"guessing.";
-/**
- * Reads a company's own site and writes a brief to its timeline.
- *
- * Ported from the API unchanged, schema and all. The one difference is who
- * calls it: this used to be a tRPC mutation that ran a vendor extraction inside
- * the request, and is now something the agent does when it decides a company is
- * worth understanding — including on its own initiative, which the old one
- * could never do.
- */
export default defineTool({
description:
"Read a company's marketing site and write a research brief to its timeline: positioning, pricing, who they sell to, notable customers, recent news.",
@@ -92,9 +82,6 @@ export default defineTool({
return { written: false as const, reason: result.reason };
}
- // `Activity.createdById` is required. Attribute to the company's owner, or
- // to any user if it is unowned; the meta marks it agent-written so the UI
- // never claims a person typed it.
const author =
company.ownerId ??
(await db.user.findFirst({ select: { id: true } }))?.id ??
diff --git a/apps/agent/agent/tools/research_person.ts b/apps/agent/agent/tools/research_person.ts
index 53d3dab8..82bbef6b 100644
--- a/apps/agent/agent/tools/research_person.ts
+++ b/apps/agent/agent/tools/research_person.ts
@@ -19,9 +19,6 @@ export default defineTool({
.describe("Reason over more sources. Slower, better for prep briefs."),
}),
async execute({ question, deep }) {
- // Checked before the budget is charged: an install without the key would
- // otherwise pay for the discovery every time, and a contact could burn a
- // whole budget learning the same thing four times over.
if (!enabled("PERPLEXITY_API_KEY"))
return unavailable("PERPLEXITY_API_KEY");
diff --git a/apps/agent/agent/tools/resolve_linkedin_profile.ts b/apps/agent/agent/tools/resolve_linkedin_profile.ts
index d5b9bfc8..23df16b6 100644
--- a/apps/agent/agent/tools/resolve_linkedin_profile.ts
+++ b/apps/agent/agent/tools/resolve_linkedin_profile.ts
@@ -5,12 +5,6 @@ import { spend } from "../lib/focus";
import { searchTerms } from "../lib/names";
import { findProfileUrls } from "../lib/perplexity";
-/**
- * Candidates, never an answer.
- *
- * The name is never taken from here — only the slug, which `get_linkedin_profile`
- * then verifies. A search for "Paula Marchetti" has returned Brightwater's CEO.
- */
export default defineTool({
description:
"Find candidate LinkedIn profile slugs for a work email address. Returns CANDIDATES ONLY — you must verify each with get_linkedin_profile before believing any of them.",
@@ -19,10 +13,6 @@ export default defineTool({
companyName: z.string().describe("The company the CRM has them at."),
}),
async execute({ email, companyName }) {
- // Finding the slug is Perplexity's job — see `lib/linkdapi.ts` for why
- // LinkDAPI is never asked to search. Without it there is no way in to a
- // profile, so this stops here rather than charging for a lookup that has
- // nowhere to look.
if (!enabled("PERPLEXITY_API_KEY")) {
return { candidateSlugs: [], ...unavailable("PERPLEXITY_API_KEY") };
}
diff --git a/apps/agent/agent/tools/schedule_recheck.ts b/apps/agent/agent/tools/schedule_recheck.ts
index 37b061ea..af05c2e6 100644
--- a/apps/agent/agent/tools/schedule_recheck.ts
+++ b/apps/agent/agent/tools/schedule_recheck.ts
@@ -2,22 +2,9 @@ import { defineTool } from "eve/tools";
import { z } from "zod";
import { scheduleTask } from "../lib/tasks";
-/** Bounds, not opinions: a day is churn, three years is forgetting. */
const MIN_DAYS = 1;
const MAX_DAYS = 730;
-/**
- * Deciding when to look at somebody again.
- *
- * The single most important tool in the agent, and the least impressive
- * looking. Everything else here answers a question; this one decides which
- * question gets asked next, which is what separates an agent from a cron job
- * with a language model attached.
- *
- * `reason` is mandatory and is shown to the rep on the record. An agent that
- * cannot say why it will be back in fourteen days does not have a reason, it
- * has a default.
- */
export default defineTool({
description:
"Decide when this contact is worth looking at again, and say why. Use a short interval for people whose job change would move a live deal, a long one for quiet records, and skip it entirely for addresses nobody will ever sell to.",
@@ -54,8 +41,6 @@ export default defineTool({
reason,
dueAt,
budget,
- // Behind anything a person or an event asked for. A recheck is never
- // the most urgent thing in the queue.
priority: 0,
});
diff --git a/apps/agent/agent/tools/search_crm.ts b/apps/agent/agent/tools/search_crm.ts
index d3e9c864..ffe1a137 100644
--- a/apps/agent/agent/tools/search_crm.ts
+++ b/apps/agent/agent/tools/search_crm.ts
@@ -2,19 +2,6 @@ import { defineTool } from "eve/tools";
import { z } from "zod";
import { searchCrm } from "../lib/lookup";
-/**
- * Finding the record somebody meant.
- *
- * Every other CRM tool here takes an id, and until this existed there was no
- * way to obtain one except from a rep. So the agent asked — "could you paste
- * the contact's name or email address" — which is the CRM asking its user to
- * do a lookup on its behalf, from a screen that is already showing the answer.
- *
- * Free, local, and returns ambiguity rather than resolving it. Four people
- * called Marchetti come back as four rows with their titles and employers,
- * because choosing between them is a rep's three-second decision and a wrong
- * guess is a wrong record.
- */
export default defineTool({
description:
"Find contacts, companies and deals by name, email address, domain or deal name — the way a person would search. Returns each match with its id, so you never have to ask a rep for one. Free. Use it whenever a question names a record you do not have the id for.",
diff --git a/apps/agent/agent/tools/set_contact_socials.ts b/apps/agent/agent/tools/set_contact_socials.ts
index 8088219e..28ac10f1 100644
--- a/apps/agent/agent/tools/set_contact_socials.ts
+++ b/apps/agent/agent/tools/set_contact_socials.ts
@@ -6,19 +6,6 @@ import { recordFact } from "../lib/facts";
import { focusOn } from "../lib/focus";
import { parseSocialUrl, verifyGithub, verifyX } from "../lib/socials";
-/**
- * The only way an X or GitHub link reaches a record.
- *
- * Verification happens here, against the CRM's own copy of who the contact is
- * and against evidence this tool fetches itself. Nothing the model says about a
- * candidate is taken as support for it — a `confidence` argument would be the
- * model marking its own homework, which is why there isn't one.
- *
- * What the checks produce is *evidence*, which then goes through the same
- * ledger as everything else. A GitHub account whose own profile names the
- * person is primary and lands on the record; a handle that merely looks like
- * their name is not, and becomes a suggestion at best.
- */
export default defineTool({
description:
"Write a contact's X and/or GitHub profile URLs after verifying each one. GitHub is checked against the account's own profile via the GitHub API; X is checked by handle and independent citation. Rejects anything it cannot corroborate — a rejection is a correct outcome, not a problem to work around.",
diff --git a/apps/agent/agent/tools/write_brief.ts b/apps/agent/agent/tools/write_brief.ts
index a6230054..95f0684a 100644
--- a/apps/agent/agent/tools/write_brief.ts
+++ b/apps/agent/agent/tools/write_brief.ts
@@ -5,21 +5,8 @@ import { WEIGHTS } from "../lib/evidence";
import { writeBrief } from "../lib/facts";
import { focusOn } from "../lib/focus";
-/** Three sentences of prose, and the length is the constraint that keeps it honest. */
const MAX_NARRATIVE = 400;
-/**
- * The background a rep reads before they dial.
- *
- * Length-capped rather than merely asked to be brief: at three sentences there
- * is only room for what a source says, and the padding a model reaches for when
- * it has nothing left to report — "a seasoned leader passionate about
- * innovation" — does not fit alongside two real facts.
- *
- * The structured `sections` are separate from the prose because the sheet
- * renders them as fields. Prose is what a person reads; fields are what they
- * scan.
- */
export default defineTool({
description:
"Write the Background panel on a contact: a short narrative plus the structured lines under it. Replaces the previous one. Every claim must come from something you read.",
@@ -65,9 +52,6 @@ export default defineTool({
const narrative = input.narrative.trim();
- // A one-liner that restates the title already on the record is worse than
- // an empty panel: it fills the space where a rep looks for something they
- // did not already know.
if (narrative.length < 40) {
return {
written: false as const,
diff --git a/apps/agent/package.json b/apps/agent/package.json
index e266c6be..97214c0a 100644
--- a/apps/agent/package.json
+++ b/apps/agent/package.json
@@ -5,6 +5,7 @@
"type": "module",
"license": "MIT",
"scripts": {
+ "backfill:images": "bun scripts/backfill-brand-images.ts",
"dev": "eve dev",
"build": "eve build",
"start": "eve start",
@@ -16,7 +17,6 @@
"dependencies": {
"@crm/db": "workspace:*",
"@crm/env": "workspace:*",
- "@vercel/blob": "^2.6.1",
"context.dev": "^2.7.0",
"eve": "^0.29.4",
"zod": "^4.4.3"
diff --git a/apps/agent/scripts/backfill-brand-images.ts b/apps/agent/scripts/backfill-brand-images.ts
new file mode 100644
index 00000000..7b8d3168
--- /dev/null
+++ b/apps/agent/scripts/backfill-brand-images.ts
@@ -0,0 +1,87 @@
+import { db } from "@crm/db";
+import { blobEnabled, isMirrored, mirror } from "@crm/db/blob";
+import { COMPANY_IMAGE_FIELDS } from "@crm/db/images";
+import { brandToUpdate } from "../agent/lib/brand-mapping";
+
+if (!blobEnabled()) {
+ console.warn(
+ "No BLOB_READ_WRITE_TOKEN — icon tone and dark artwork will still be " +
+ "filled in, but nothing will be copied into Blob.",
+ );
+}
+
+const rows = await db.companyEnrichment.findMany({
+ select: {
+ companyId: true,
+ raw: true,
+ company: {
+ select: {
+ name: true,
+ description: true,
+ logoUrl: true,
+ logoDarkUrl: true,
+ iconUrl: true,
+ iconDarkUrl: true,
+ iconTone: true,
+ brandColor: true,
+ industry: true,
+ subIndustry: true,
+ city: true,
+ stateCode: true,
+ country: true,
+ countryCode: true,
+ phone: true,
+ email: true,
+ linkedinUrl: true,
+ twitterUrl: true,
+ githubUrl: true,
+ pricingUrl: true,
+ careersUrl: true,
+ },
+ },
+ },
+});
+
+let updated = 0;
+let copied = 0;
+
+for (const row of rows) {
+ const brand = (row.raw as { brand?: unknown } | null)?.brand;
+ if (!brand) continue;
+
+ const update = brandToUpdate(brand as never, {
+ ...row.company,
+ nameIsPlaceholder: false,
+ });
+
+ const patch: Record<string, string> = {
+ ...(typeof update.iconDarkUrl === "string"
+ ? { iconDarkUrl: update.iconDarkUrl }
+ : {}),
+ ...(typeof update.iconTone === "string"
+ ? { iconTone: update.iconTone }
+ : {}),
+ };
+
+ for (const slot of COMPANY_IMAGE_FIELDS) {
+ const current = row.company[slot];
+ if (!current || isMirrored(current)) continue;
+
+ const stored = await mirror(current, `companies/${row.companyId}/${slot}`);
+ if (!stored || stored === current) continue;
+
+ patch[slot] = stored;
+ copied += 1;
+ }
+
+ if (Object.keys(patch).length === 0) continue;
+
+ await db.company.update({ where: { id: row.companyId }, data: patch });
+ updated += 1;
+ console.log(`${row.company.name}: ${Object.keys(patch).join(", ")}`);
+}
+
+console.log(
+ `\nUpdated ${updated} of ${rows.length} enriched companies. Copied ${copied} images.`,
+);
+await db.$disconnect();
diff --git a/apps/agent/test/accounts.integration.spec.ts b/apps/agent/test/accounts.integration.spec.ts
index 404857db..e66747c7 100644
--- a/apps/agent/test/accounts.integration.spec.ts
+++ b/apps/agent/test/accounts.integration.spec.ts
@@ -2,20 +2,6 @@ import { afterAll, beforeAll, describe, expect, it } from "bun:test";
import { ActivityType, DealStage, db, EmailDirection } from "@crm/db";
import { readCompanyHistory, readDealHistory } from "../agent/lib/accounts";
-/**
- * The account reads, against a real database.
- *
- * These exist because of one sentence the agent said to a rep: "I don't have a
- * tool that lists contacts by company." The assertion that matters in here is
- * not the shape of the payload — it is that a company read comes back holding
- * the **ids** of the people at it, because that is the difference between the
- * agent answering and the agent asking the human to do a join.
- *
- * A real Postgres rather than a mock, for the same reason `facts` is: the
- * joins are the behaviour. A stubbed Prisma would happily return contacts for
- * a thread filter that matches nothing in practice.
- */
-
const suffix = process.env.TEST_RUN_ID ?? "accounts-spec";
const domain = `fernhill-${suffix}.test`;
@@ -31,7 +17,6 @@ const daysAhead = (days: number) => new Date(Date.now() + days * 86_400_000);
beforeAll(async () => {
await cleanup();
- // Better Auth mints user ids, so the column has no database default.
const user = await db.user.create({
data: {
id: `user-${suffix}`,
@@ -67,7 +52,6 @@ beforeAll(async () => {
});
paulaId = paula.id;
- // Named after their own address, which is what `needsIdentity` reports.
const placeholder = await db.contact.create({
data: {
firstName: "Tsomerville",
@@ -126,7 +110,6 @@ beforeAll(async () => {
dealId,
createdById: userId,
},
- // A projection of an email. It must not come back as a note as well.
{
type: ActivityType.EMAIL,
subject: "Re: Contract",
@@ -219,8 +202,6 @@ describe("readCompanyHistory", () => {
it("names every contact at the company, with their id", async () => {
const history = await readCompanyHistory(companyId);
- // The whole reason this function exists: the ids are in the payload, so
- // the agent never has to ask a rep for one.
expect(history?.people.map((person) => person.id).sort()).toEqual(
[paulaId, placeholderId].sort(),
);
@@ -260,8 +241,6 @@ describe("readCompanyHistory", () => {
expect(history?.threads[0]?.subject).toBe("Re: Contract");
expect(history?.threads[0]?.contact?.id).toBe(paulaId);
- // Bodies, not snippets — a signature block is the best title evidence
- // there is, and it only exists in the body.
expect(history?.threads[0]?.messages[0]?.body).toContain(
"Growth Specialist",
);
@@ -289,8 +268,6 @@ describe("readDealHistory", () => {
expect(history?.deal.stage).toBe("CONTRACT_SENT");
expect(history?.deal.open).toBe(true);
- // Six weeks in contract-sent is the answer to "where does this stand",
- // and the stage field alone cannot say it.
expect(history?.deal.daysInStage).toBeGreaterThanOrEqual(41);
});
diff --git a/apps/agent/test/brand-mapping.spec.ts b/apps/agent/test/brand-mapping.spec.ts
index 5f7d5c1a..fdfdf997 100644
--- a/apps/agent/test/brand-mapping.spec.ts
+++ b/apps/agent/test/brand-mapping.spec.ts
@@ -5,7 +5,6 @@ import {
} from "../agent/lib/brand-mapping";
import type { Brand } from "../agent/lib/context-dev";
-/** A company with nothing filled in — every gap open. */
function emptyCompany(
overrides: Partial<CompanySnapshot> = {},
): CompanySnapshot {
@@ -115,7 +114,6 @@ describe("brandToUpdate", () => {
expect(update.description).toBeUndefined();
expect(update.city).toBeUndefined();
expect(update.phone).toBeUndefined();
- // The gaps are still filled.
expect(update.country).toBe("United States");
});
@@ -133,7 +131,6 @@ describe("brandToUpdate", () => {
});
it("writes nothing when the lookup found nothing", () => {
- // Every field on a brand is nullable, so the all-null case is real.
expect(brandToUpdate({}, emptyCompany())).toEqual({});
});
@@ -145,5 +142,3 @@ describe("brandToUpdate", () => {
expect(update.description).toBe("Payments, simplified.");
});
});
-
-/** The real queue, with the five-second backoff wound down. */
diff --git a/apps/agent/test/capabilities.spec.ts b/apps/agent/test/capabilities.spec.ts
index e3f7b0b8..33412346 100644
--- a/apps/agent/test/capabilities.spec.ts
+++ b/apps/agent/test/capabilities.spec.ts
@@ -10,6 +10,7 @@ const KEYS = [
"RAPIDAPI_KEY",
"PERPLEXITY_API_KEY",
"CONTEXT_DEV_API_KEY",
+ "BLOB_READ_WRITE_TOKEN",
] as const;
const saved: Record<string, string | undefined> = {};
@@ -42,8 +43,6 @@ describe("capabilities", () => {
});
it("treats blank and whitespace as unset", () => {
- // `.env.example` ships these commented out, but a self-hoster who
- // uncomments one and leaves it empty must not get a tool that tries.
process.env.RAPIDAPI_KEY = " ";
expect(enabled("RAPIDAPI_KEY")).toBe(false);
});
@@ -67,7 +66,6 @@ describe("the unavailable result", () => {
expect(result.ok).toBe(false);
expect(result.configured).toBe(false);
- // An agent told only "failed" will reasonably try again.
expect(result.reason).toContain("retrying will not help");
expect(result.reason).toContain("RAPIDAPI_KEY");
});
diff --git a/apps/agent/test/channel-auth.spec.ts b/apps/agent/test/channel-auth.spec.ts
index 08b682a7..0108b5d8 100644
--- a/apps/agent/test/channel-auth.spec.ts
+++ b/apps/agent/test/channel-auth.spec.ts
@@ -6,20 +6,9 @@ import {
} from "../agent/channels/eve";
import { isAutomated } from "../agent/lib/approval";
-/**
- * Who the agent thinks is calling.
- *
- * Two things are being protected here. The obvious one is that a forged or
- * expired token cannot reach an agent that can read every email in the CRM.
- * The subtler one is that a *valid* token has to resolve to a **person**:
- * `lib/approval.ts` pauses for a human only when it can tell one is there, and
- * eve's own `jwtHmac()` helper would have labelled this a service principal.
- */
-
const SECRET = "test-secret-at-least-long-enough-to-be-a-secret";
const auth = repFromCrm(SECRET);
-/** Mirrors `apps/app/lib/agent-bridge.ts`; the app-side test proves the pair. */
async function mint(
claims: Record<string, unknown>,
secret = SECRET,
@@ -78,8 +67,6 @@ describe("repFromCrm", () => {
});
it("produces a principal the approval policy reads as human", async () => {
- // The assertion the whole panel rests on: a rep asking is not the cron
- // principal, so a sensitive write prompts them instead of being refused.
const session = await auth(request(await mint(claims())));
expect(isAutomated({ auth: { current: session } })).toBe(false);
@@ -103,8 +90,6 @@ describe("repFromCrm", () => {
});
it("skips a token whose payload was swapped for another user", async () => {
- // The attack that matters: take your own valid token, rewrite `sub`, keep
- // the signature. Nothing else in the system re-checks who the caller is.
const token = await mint(claims());
const [header, , signature] = token.split(".");
const impersonated = Buffer.from(
@@ -120,11 +105,6 @@ describe("repFromCrm", () => {
const token = await mint(claims());
const [header, payload, signature] = token.split(".");
- // Flipped in the middle, deliberately. The *last* base64url character of
- // a 43-character signature carries only two significant bits — 32 bytes is
- // 256 bits and 43 characters hold 258 — so changing it can decode to the
- // same MAC and pass. A tamper test that only touches the final character
- // is a test that passes for the wrong reason.
const middle = Math.floor((signature as string).length / 2);
const swapped = (signature as string)[middle] === "A" ? "B" : "A";
const altered = `${(signature as string).slice(0, middle)}${swapped}${(
diff --git a/apps/agent/test/enrichment.integration.spec.ts b/apps/agent/test/enrichment.integration.spec.ts
index 6037fc07..837664fd 100644
--- a/apps/agent/test/enrichment.integration.spec.ts
+++ b/apps/agent/test/enrichment.integration.spec.ts
@@ -2,15 +2,6 @@ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
import { db, EnrichmentStatus } from "@crm/db";
import { markRunning, settle } from "../agent/lib/enrichment";
-/**
- * The status a rep reads off the record, against a real database.
- *
- * Worth pinning because the bug it replaces was invisible: `enrichmentStatus`
- * defaults to PENDING, nothing on the contact path ever wrote it, and the sheet
- * rendered PENDING as "Queued". Every contact in the database therefore claimed
- * to be queued from the moment it was inserted, and no test failed.
- */
-
const domain = "lifecycle.example.test";
async function clear() {
@@ -74,8 +65,6 @@ describe("the record follows the task", () => {
await settle(subject, EnrichmentStatus.COMPLETE);
const done = await statusOfContact(person.id);
expect(done?.enrichmentStatus).toBe("COMPLETE");
- // The sheet shows this, so a COMPLETE with no date would read as enriched
- // at the beginning of time.
expect(done?.enrichedAt).not.toBeNull();
});
@@ -99,8 +88,6 @@ describe("the record follows the task", () => {
await markRunning(subject);
- // What `enrich_company` does when there is no domain to look up: a
- // terminal answer, with a reason a rep can read.
await db.company.update({
where: { id: org.id },
data: {
@@ -109,8 +96,6 @@ describe("the record follows the task", () => {
},
});
- // The turn then parks and the task settles. It must not flatten that into
- // COMPLETE and throw away the message.
await settle(subject, EnrichmentStatus.COMPLETE);
const row = await db.company.findUnique({
@@ -129,8 +114,6 @@ describe("the record follows the task", () => {
await settle(subject, EnrichmentStatus.FAILED, "the vendor refused");
expect((await statusOfContact(person.id))?.enrichmentStatus).toBe("FAILED");
- // A retry is genuinely running again. Gating this on the previous status
- // would strand the record on FAILED with a session actively working on it.
await markRunning(subject);
const retried = await statusOfContact(person.id);
expect(retried?.enrichmentStatus).toBe("RUNNING");
@@ -149,7 +132,6 @@ describe("the record follows the task", () => {
await markRunning(subject);
await db.contact.delete({ where: { id: person.id } });
- // `update` would throw here and take the dispatcher tick with it.
await settle(subject, EnrichmentStatus.COMPLETE);
});
});
diff --git a/apps/agent/test/evidence.spec.ts b/apps/agent/test/evidence.spec.ts
index 4762c8fb..2c215acc 100644
--- a/apps/agent/test/evidence.spec.ts
+++ b/apps/agent/test/evidence.spec.ts
@@ -11,23 +11,16 @@ const of = (...kinds: Evidence["kind"][]): Evidence[] =>
describe("scoreEvidence", () => {
it("writes a fact when a primary source names them", () => {
- // Their own profile carrying their email address is as good as it gets.
const scored = scoreEvidence(of("profile.email-match"));
expect(scored.band).toBe("VERIFIED");
expect(scored.hasPrimary).toBe(true);
});
it("treats our own mailbox as primary evidence", () => {
- // The §1 argument in one assertion: a reply on a thread we synced is
- // worth more than anything a data vendor can sell us, and it carries a
- // fact on its own.
expect(scoreEvidence(of("crm.thread-reply")).band).toBe("VERIFIED");
});
it("writes a title a signature block states on a thread they replied to", () => {
- // The realistic shape of a title read out of our own mailbox: the reply
- // proves it is them, the signature states the role. Either alone is a
- // suggestion; together they are a fact.
expect(scoreEvidence(of("crm.signature-block")).band).toBe("PROBABLE");
expect(
scoreEvidence(of("crm.thread-reply", "crm.signature-block")).band,
@@ -44,24 +37,17 @@ describe("scoreEvidence", () => {
),
);
- // Four weak signals pile up to a confident-looking number and are still
- // not allowed to write. This is the rule that stops a plausible stranger
- // becoming a customer record.
expect(scored.score).toBeGreaterThan(BAND_FLOOR.PROBABLE);
expect(scored.hasPrimary).toBe(false);
expect(scored.band).toBe("PROBABLE");
});
it("holds the primary-source rule even if the weights are re-calibrated upwards", () => {
- // The invariant, independent of the numbers in the table: a score alone
- // never licenses a write.
expect(bandFor(0.99, false)).toBe("PROBABLE");
expect(bandFor(0.85, true)).toBe("VERIFIED");
});
it("makes an unreadable X handle a suggestion, not a value", () => {
- // Exactly what verifyX produces. X cannot be read, so the best available
- // is two indirect signals agreeing — which is a question for a human.
const scored = scoreEvidence(
of("handle.name-form", "search.cites-profile"),
);
diff --git a/apps/agent/test/facts.integration.spec.ts b/apps/agent/test/facts.integration.spec.ts
index e3d778e9..c84fab2b 100644
--- a/apps/agent/test/facts.integration.spec.ts
+++ b/apps/agent/test/facts.integration.spec.ts
@@ -3,14 +3,6 @@ import { db } from "@crm/db";
import type { Evidence } from "../agent/lib/evidence";
import { recordFact, writeBrief } from "../agent/lib/facts";
-/**
- * The fact store against a real database.
- *
- * Every rule in here is one that used to live in a prompt, so testing them
- * against Postgres rather than a mock is the point: "never overwrite a human"
- * is only true if the transaction says so.
- */
-
const suffix = process.env.TEST_RUN_ID ?? "facts-spec";
const email = `evidence.subject.${suffix}@example.test`;
@@ -71,7 +63,6 @@ describe("recordFact", () => {
where: { id: contactId },
select: { twitterUrl: true },
});
- // The suggestion exists; the field does not have it.
expect(contact?.twitterUrl).toBeNull();
});
diff --git a/apps/agent/test/images.spec.ts b/apps/agent/test/images.spec.ts
new file mode 100644
index 00000000..aef9e8e0
--- /dev/null
+++ b/apps/agent/test/images.spec.ts
@@ -0,0 +1,131 @@
+import { describe, expect, it } from "bun:test";
+import { profilePhotoUrl, slugFromProfileUrl } from "../agent/lib/linkdapi";
+import { findPortrait } from "../agent/lib/portrait-sources";
+
+const OVERVIEW = {
+ firstName: "Kelly",
+ lastName: "Wiarda",
+ fullName: "Kelly Wiarda",
+ publicIdentifier: "kellywiarda",
+ backgroundImageURL:
+ "https://media.licdn.com/dms/image/v2/D4D16AQHJgcgf0YCwWA/profile-displaybackgroundimage-shrink_350_1400/0/1673558147641?e=1787184000",
+ profilePictureURL:
+ "https://media.licdn.com/dms/image/v2/D5603AQGOxXbMuQk4jw/profile-displayphoto-shrink_100_100/0/1738873240305?e=1787184000",
+};
+
+describe("profilePhotoUrl", () => {
+ it("reads the key the API actually uses", () => {
+ expect(profilePhotoUrl(OVERVIEW)).toContain("profile-displayphoto");
+ });
+
+ it("never takes the background banner for a face", () => {
+ const { profilePictureURL, ...noPhoto } = OVERVIEW;
+ expect(profilePhotoUrl(noPhoto)).toBe(null);
+ });
+
+ it("tolerates the vendor recasing the key", () => {
+ expect(
+ profilePhotoUrl({ profilePictureUrl: OVERVIEW.profilePictureURL }),
+ ).toBe(OVERVIEW.profilePictureURL);
+ });
+
+ it("refuses a photo that is not on LinkedIn's CDN", () => {
+ expect(
+ profilePhotoUrl({ profilePictureURL: "https://evil.example/x.jpg" }),
+ ).toBe(null);
+ expect(
+ profilePhotoUrl({ profilePictureURL: "http://media.licdn.com/x.jpg" }),
+ ).toBe(null);
+ expect(
+ profilePhotoUrl({ profilePictureURL: "https://licdn.com.evil/x.jpg" }),
+ ).toBe(null);
+ });
+
+ it("is null for a profile with no picture, which is ordinary", () => {
+ expect(profilePhotoUrl({ firstName: "Nathan" })).toBe(null);
+ });
+});
+
+describe("slugFromProfileUrl", () => {
+ it("reads the handle out of a profile URL", () => {
+ expect(slugFromProfileUrl("https://www.linkedin.com/in/pmarchetti")).toBe(
+ "pmarchetti",
+ );
+ expect(slugFromProfileUrl("https://linkedin.com/in/pmarchetti/")).toBe(
+ "pmarchetti",
+ );
+ expect(
+ slugFromProfileUrl("https://uk.linkedin.com/in/paula-marchetti-1a2b3c"),
+ ).toBe("paula-marchetti-1a2b3c");
+ });
+
+ it("decodes an escaped handle", () => {
+ expect(slugFromProfileUrl("https://www.linkedin.com/in/j%C3%B8rn-a")).toBe(
+ "jørn-a",
+ );
+ });
+
+ it("refuses anything that is not a personal profile", () => {
+ expect(
+ slugFromProfileUrl("https://www.linkedin.com/company/fernhill"),
+ ).toBe(null);
+ expect(slugFromProfileUrl("https://www.linkedin.com/in/")).toBe(null);
+ expect(slugFromProfileUrl("https://notlinkedin.com/in/pmarchetti")).toBe(
+ null,
+ );
+ expect(slugFromProfileUrl("pmarchetti")).toBe(null);
+ expect(slugFromProfileUrl(null)).toBe(null);
+ });
+});
+
+describe("the portrait source chain", () => {
+ const NOBODY = {
+ id: "c1",
+ name: "Paula Marchetti",
+ linkedinUrl: null,
+ githubUrl: null,
+ companyName: null,
+ companyDomain: null,
+ };
+ const free = () => ({ ok: true });
+
+ it("uses a verified GitHub account when there is no LinkedIn", async () => {
+ const result = await findPortrait(
+ { ...NOBODY, githubUrl: "https://github.com/pmarchetti" },
+ free,
+ );
+
+ expect(result.found).toBe(true);
+ if (result.found) {
+ expect(result.candidate.source).toBe("github");
+ expect(result.candidate.url).toContain("github.com/pmarchetti.png");
+ }
+ });
+
+ it("does not mistake a repository for a person", async () => {
+ const result = await findPortrait(
+ { ...NOBODY, githubUrl: "https://github.com/acme/crm" },
+ free,
+ );
+
+ expect(result.found).toBe(false);
+ });
+
+ it("looks nowhere at all when the record points nowhere", async () => {
+ const result = await findPortrait(NOBODY, free);
+
+ expect(result.found).toBe(false);
+ if (!result.found) expect(result.tried).toEqual([]);
+ });
+
+ it("stops rather than spending past the budget", async () => {
+ const broke = () => ({ ok: false, reason: "Out of budget." });
+ const result = await findPortrait(
+ { ...NOBODY, linkedinUrl: "https://www.linkedin.com/in/pmarchetti" },
+ broke,
+ );
+
+ expect(result.found).toBe(false);
+ if (!result.found) expect(result.reason).toBe("Out of budget.");
+ });
+});
diff --git a/apps/agent/test/lookup.integration.spec.ts b/apps/agent/test/lookup.integration.spec.ts
index 99193e8f..6e441056 100644
--- a/apps/agent/test/lookup.integration.spec.ts
+++ b/apps/agent/test/lookup.integration.spec.ts
@@ -2,15 +2,6 @@ import { afterAll, beforeAll, describe, expect, it } from "bun:test";
import { DealStage, db } from "@crm/db";
import { searchCrm } from "../agent/lib/lookup";
-/**
- * Finding a record from what a person would type.
- *
- * The behaviour under test is the one whose absence was visible to a user: a
- * rep asked about "the Comp AI contact" and was told to paste an email
- * address, because every lookup the agent had took an id. Each case here is a
- * phrasing that has to resolve without help.
- */
-
const suffix = process.env.TEST_RUN_ID ?? "lookup-spec";
const domain = `northwind-${suffix}.test`;
const otherDomain = `brightwater-${suffix}.test`;
@@ -46,8 +37,6 @@ beforeAll(async () => {
});
brightwaterId = brightwater.id;
- // Two Marchettis at two companies: the ambiguity the tool is supposed to
- // hand back rather than resolve.
const paula = await db.contact.create({
data: {
firstName: "Paula",
@@ -116,8 +105,6 @@ describe("searchCrm", () => {
it("finds the people at a company named in the query", async () => {
const result = await searchCrm(`Northwind ${suffix}`);
- // "the Comp AI contact", in the shape it actually arrives in. Naming the
- // employer has to reach the person, or the agent is back to asking.
expect(result.contacts.map((hit) => hit.id)).toContain(paulaId);
});
@@ -127,7 +114,6 @@ describe("searchCrm", () => {
expect(result.contacts.map((hit) => hit.id).sort()).toEqual(
[paulaId, peterId].sort(),
);
- // Each carries what a rep needs to choose between them in one glance.
expect(result.contacts.every((hit) => hit.company !== null)).toBe(true);
expect(result.contacts.map((hit) => hit.title)).toContain("Controller");
});
@@ -171,9 +157,6 @@ describe("searchCrm", () => {
it("ranks a whole-phrase match above rows sharing only one word", async () => {
const result = await searchCrm(`Paula Marchetti`);
- // The SQL is an OR across the words — it has to be, or a contact filed
- // as "P. Marchetti" would be missed — so Peter comes back too. He must
- // not come back first.
expect(result.contacts[0]?.id).toBe(paulaId);
});
diff --git a/apps/agent/test/model.integration.spec.ts b/apps/agent/test/model.integration.spec.ts
new file mode 100644
index 00000000..f4cc839b
--- /dev/null
+++ b/apps/agent/test/model.integration.spec.ts
@@ -0,0 +1,58 @@
+import { afterEach, beforeEach, describe, expect, it } from "bun:test";
+import { db } from "@crm/db";
+import {
+ DEFAULT_AGENT_MODEL,
+ readAgentModel,
+ SETTINGS_ID,
+ writeAgentModel,
+} from "@crm/db/settings";
+import { selectedModel } from "../agent/lib/model";
+
+async function clear() {
+ await db.appSetting.deleteMany({ where: { id: SETTINGS_ID } });
+}
+
+beforeEach(clear);
+afterEach(clear);
+
+describe("the configured model", () => {
+ it("falls back when nothing has ever been chosen", async () => {
+ const setting = await readAgentModel(db);
+
+ expect(setting.id).toBe(DEFAULT_AGENT_MODEL.id);
+ expect(setting.isDefault).toBe(true);
+
+ expect(await selectedModel()).toBeNull();
+ });
+
+ it("returns the chosen model with its own context window", async () => {
+ await writeAgentModel(db, {
+ id: "anthropic/claude-sonnet-5",
+ contextWindowTokens: 200_000,
+ });
+
+ expect(await selectedModel()).toEqual({
+ model: "anthropic/claude-sonnet-5",
+ modelContextWindowTokens: 200_000,
+ });
+ });
+
+ it("goes back to the fallback when the choice is cleared", async () => {
+ await writeAgentModel(db, {
+ id: "anthropic/claude-sonnet-5",
+ contextWindowTokens: 200_000,
+ });
+ await writeAgentModel(db, null);
+
+ expect(await selectedModel()).toBeNull();
+ expect((await readAgentModel(db)).isDefault).toBe(true);
+ });
+
+ it("keeps one row rather than accumulating one per change", async () => {
+ await writeAgentModel(db, { id: "openai/gpt-5.5", contextWindowTokens: 1 });
+ await writeAgentModel(db, { id: "zai/glm-5.2", contextWindowTokens: 2 });
+
+ expect(await db.appSetting.count()).toBe(1);
+ expect((await readAgentModel(db)).id).toBe("zai/glm-5.2");
+ });
+});
diff --git a/apps/agent/test/names.spec.ts b/apps/agent/test/names.spec.ts
index 71938e4d..fc475b15 100644
--- a/apps/agent/test/names.spec.ts
+++ b/apps/agent/test/names.spec.ts
@@ -1,13 +1,5 @@
import { describe, expect, it } from "bun:test";
-/**
- * The identity helpers, tested where they now live.
- *
- * These moved here with the rest of enrichment. They were written against the
- * API's copy of `looksLikeSameCompany`/`nameMatchesLocalPart`/`searchTerms`,
- * which had silently drifted from the agent's — the whole argument for there
- * being one copy. Same assertions, one implementation.
- */
import {
looksLikeSameCompany,
nameMatchesLocalPart,
@@ -16,8 +8,6 @@ import {
describe("searchTerms", () => {
it("strips the initial off a run-together handle", () => {
- // The case that forced this: searching "pmarchetti" finds nothing, searching
- // "marchetti" returns linkedin.com/in/paulamarchetti as the first result.
expect(searchTerms("pmarchetti")).toContain("marchetti");
expect(searchTerms("tokonkwo")).toContain("okonkwo");
});
@@ -40,7 +30,6 @@ describe("searchTerms", () => {
describe("looksLikeSameCompany", () => {
it("matches an employer to the shorter name the CRM holds", () => {
- // Tomi Okonkwo's employer reads "Northwind Bank"; the CRM knows "Northwind".
expect(
looksLikeSameCompany("Northwind Bank", "Northwind", "northwind.com"),
).toBe(true);
@@ -50,8 +39,6 @@ describe("looksLikeSameCompany", () => {
});
it("rejects an unrelated employer", () => {
- // The failure this exists to prevent: search handed back Brightwater's CEO for
- // a Fernhill query, and something has to stop them being written down.
expect(
looksLikeSameCompany("Brightwater Group", "Fernhill", "fernhill.com"),
).toBe(false);
@@ -80,9 +67,6 @@ describe("nameMatchesLocalPart", () => {
});
it("rejects a stranger who merely turned up in the results", () => {
- // This is the guard that keeps Dario Fontana from being filed as
- // Paula Marchetti. The name is checked against the address, never derived
- // from it.
expect(
nameMatchesLocalPart(person("Antonio", "Fontana"), "pmarchetti"),
).toBe(false);
diff --git a/apps/agent/test/preamble.integration.spec.ts b/apps/agent/test/preamble.integration.spec.ts
index 4c9189f7..9c857a13 100644
--- a/apps/agent/test/preamble.integration.spec.ts
+++ b/apps/agent/test/preamble.integration.spec.ts
@@ -8,16 +8,6 @@ import {
sessionPreamble,
} from "../agent/lib/preamble";
-/**
- * What each kind of session is told before it speaks.
- *
- * Three records, three conversations — and the assertions that matter are the
- * ones about **ids**. A preamble that names a neighbouring record without its
- * id is the exact state the agent was in when it asked a rep to paste a
- * contact id off the screen in front of them, and when it reported that a
- * contact with an employer had no company available.
- */
-
const suffix = process.env.TEST_RUN_ID ?? "preamble-spec";
const domain = `fernhill-${suffix}.test`;
@@ -112,8 +102,6 @@ describe("companyPreamble", () => {
it("names every contact it lists, with their id", async () => {
const { markdown } = await companyPreamble(companyId, rep);
- // The fix, stated as a test: the agent can address these people without
- // asking anyone for anything.
expect(markdown).toContain(
`Paula Marchetti — Growth Specialist \`${paulaId}\``,
);
@@ -140,8 +128,6 @@ describe("contactPreamble", () => {
it("states the company id, not just its name", async () => {
const { markdown, focus } = await contactPreamble(paulaId, rep);
- // Without this the agent could see where somebody worked and still
- // report that there was no company available to look at.
expect(markdown).toContain(`company id \`${companyId}\``);
expect(focus).toEqual({ contactId: paulaId, companyId });
});
@@ -172,8 +158,6 @@ describe("dealPreamble", () => {
expect(markdown).toContain(`deal id \`${dealId}\``);
expect(markdown).toContain(`company id \`${companyId}\``);
expect(markdown).toContain(`Champion \`${paulaId}\``);
- // A deal has no fields of its own, so anything learned is filed against
- // the account.
expect(focus).toEqual({ companyId });
});
});
diff --git a/apps/agent/test/socials.spec.ts b/apps/agent/test/socials.spec.ts
index 969dacc5..cd0e56a5 100644
--- a/apps/agent/test/socials.spec.ts
+++ b/apps/agent/test/socials.spec.ts
@@ -9,7 +9,6 @@ describe("parseSocialUrl", () => {
handle: "lewiscarhart",
url: "https://x.com/lewiscarhart",
});
- // Canonicalised, so the same account found twice is written once.
expect(parseSocialUrl("https://twitter.com/LewisCarhart")?.url).toBe(
"https://x.com/LewisCarhart",
);
@@ -19,8 +18,6 @@ describe("parseSocialUrl", () => {
});
it("refuses a deep link, which is where most wrong handles come from", () => {
- // A cited tweet and a cited repo both contain a real handle, and neither is
- // evidence that the handle belongs to the person we asked about.
expect(parseSocialUrl("https://x.com/someone/status/1234")).toBeNull();
expect(parseSocialUrl("https://github.com/someone/some-repo")).toBeNull();
});
@@ -33,7 +30,6 @@ describe("parseSocialUrl", () => {
});
it("refuses handles neither network could issue", () => {
- // X caps at 15 characters; GitHub allows no trailing or doubled hyphen.
expect(parseSocialUrl("https://x.com/waytoolongforanxhandle")).toBeNull();
expect(parseSocialUrl("https://github.com/-lewis")).toBeNull();
expect(parseSocialUrl("https://github.com/lewis--carhart")).toBeNull();
@@ -80,7 +76,6 @@ describe("namesMatch", () => {
});
it("rejects a first name on its own", () => {
- // The GitHub account of "Lewis" is the account of every Lewis there is.
expect(namesMatch("Lewis", "Lewis Carhart")).toBe(false);
expect(namesMatch(null, "Lewis Carhart")).toBe(false);
});
diff --git a/apps/agent/test/tasks.integration.spec.ts b/apps/agent/test/tasks.integration.spec.ts
index 786fbb13..0c61db12 100644
--- a/apps/agent/test/tasks.integration.spec.ts
+++ b/apps/agent/test/tasks.integration.spec.ts
@@ -8,19 +8,9 @@ import {
scheduleTask,
} from "../agent/lib/tasks";
-/**
- * The work queue against a real database.
- *
- * The lease is raw SQL — `FOR UPDATE SKIP LOCKED` has no Prisma equivalent —
- * which is exactly the kind of code that typechecks and then does the wrong
- * thing at runtime. It is also the thing standing between one dispatcher and
- * two dispatchers doing every job twice.
- */
-
const kind = "test-lease";
async function clear() {
- // Tasks first: they reference the contacts below.
await db.agentTask.deleteMany({ where: { kind } });
await db.contact.deleteMany({ where: { email: { startsWith: "lease-" } } });
}
@@ -44,7 +34,6 @@ async function queue(
});
}
-/** Frees a leased row the way a dispatcher dying mid-run would. */
async function expire(taskId: string) {
await db.agentTask.update({
where: { id: taskId },
@@ -52,7 +41,6 @@ async function expire(taskId: string) {
});
}
-/** A contact to hang a task off, so the subject can be asserted on. */
async function someone() {
return db.contact.create({
data: {
@@ -78,8 +66,6 @@ describe("claimDue", () => {
it("does not hand the same row to two dispatchers", async () => {
await Promise.all([queue(), queue(), queue()]);
- // The case the raw SQL exists for: two ticks landing together must take
- // disjoint sets, not race for the same rows.
const [first, second] = await Promise.all([claimDue(3), claimDue(3)]);
const ids = [...first, ...second].map((t) => t.id);
@@ -108,7 +94,6 @@ describe("claimDue", () => {
expect(await claimDue(10)).toHaveLength(0);
- // A run that died mid-task must not strand its row forever.
await db.agentTask.update({
where: { id: task.id },
data: { leasedUntil: new Date(Date.now() - 1000) },
@@ -117,11 +102,6 @@ describe("claimDue", () => {
expect((await claimDue(10)).map((t) => t.id)).toContain(task.id);
});
- /**
- * The money bug. Two rows were re-leased every ten minutes for an hour and a
- * half, resuming the same durable session and paying for a model turn each
- * time, because nothing counted how often that had already happened.
- */
it("stops handing out a row that has spent its attempts", async () => {
const task = await queue();
@@ -167,8 +147,6 @@ describe("retireExhausted", () => {
const retired = await retireExhausted();
expect(retired.map((t) => t.id)).toContain(task.id);
- // The subject comes back so the caller can tell the record, rather than
- // leaving it saying somebody is still working on it.
expect(retired.find((t) => t.id === task.id)?.contactId).toBe(contact.id);
const row = await db.agentTask.findUnique({ where: { id: task.id } });
@@ -184,7 +162,6 @@ describe("retireExhausted", () => {
if (attempt < MAX_ATTEMPTS - 1) await expire(task.id);
}
- // Still holding a live lease: the run may yet park and close it itself.
expect(await retireExhausted()).toHaveLength(0);
});
@@ -205,8 +182,6 @@ describe("completeTask", () => {
const subject = await completeTask(task.id, "ran");
expect(subject?.contactId).toBe(contact.id);
- // A session parks at the end of every turn. Only the turn that belongs to
- // this dispatch may close the row — a later one must not re-stamp it.
expect(await completeTask(task.id, "ran again")).toBeNull();
const row = await db.agentTask.findUnique({ where: { id: task.id } });
expect(row?.outcome).toBe("ran");
diff --git a/apps/api/api/index.ts b/apps/api/api/index.ts
index f9f1b8d4..14797418 100644
--- a/apps/api/api/index.ts
+++ b/apps/api/api/index.ts
@@ -4,18 +4,6 @@ import { createApp } from "../src/create-app";
type ExpressInstance = (req: IncomingMessage, res: ServerResponse) => void;
-/**
- * The serverless entrypoint.
- *
- * Nest is built once per instance and reused: `instancePromise` is module
- * scope, so a warm invocation skips the whole `NestFactory.create` — module
- * resolution, the Prisma connection, route mapping — and only runs the
- * request. Storing the promise rather than the app also means two requests
- * arriving during a cold start share one boot instead of racing two.
- *
- * `app.init()` and not `app.listen()`: there is no port to bind here. Vercel
- * hands us `(req, res)` and Express takes it from there.
- */
let instancePromise: Promise<ExpressInstance> | null = null;
function getInstance(): Promise<ExpressInstance> {
diff --git a/apps/api/scripts/backfill-icon-tone.ts b/apps/api/scripts/backfill-icon-tone.ts
deleted file mode 100644
index ecd43096..00000000
--- a/apps/api/scripts/backfill-icon-tone.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { db } from "@crm/db";
-import { brandToUpdate } from "../src/enrichment/brand-mapping";
-
-/**
- * Fills `iconDarkUrl` and `iconTone` from the Context.dev payloads we already
- * stored.
- *
- * The whole point of keeping `CompanyEnrichment.raw` was that deriving a new
- * field later should cost nothing and no credits — this is that promise being
- * collected. Re-running is safe: `brandToUpdate` only fills fields that are
- * currently empty, so a value a human has since corrected is left alone.
- *
- * bun run scripts/backfill-icon-tone.ts
- */
-const rows = await db.companyEnrichment.findMany({
- select: {
- companyId: true,
- raw: true,
- company: {
- select: {
- name: true,
- description: true,
- logoUrl: true,
- logoDarkUrl: true,
- iconUrl: true,
- iconDarkUrl: true,
- iconTone: true,
- brandColor: true,
- industry: true,
- subIndustry: true,
- city: true,
- stateCode: true,
- country: true,
- countryCode: true,
- phone: true,
- email: true,
- linkedinUrl: true,
- twitterUrl: true,
- githubUrl: true,
- pricingUrl: true,
- careersUrl: true,
- },
- },
- },
-});
-
-let updated = 0;
-
-for (const row of rows) {
- const brand = (row.raw as { brand?: unknown } | null)?.brand;
- if (!brand) continue;
-
- const update = brandToUpdate(brand as never, {
- ...row.company,
- nameIsPlaceholder: false,
- });
-
- // Only the two new fields — this script is not a re-enrichment.
- const patch = {
- ...(update.iconDarkUrl ? { iconDarkUrl: update.iconDarkUrl } : {}),
- ...(update.iconTone ? { iconTone: update.iconTone } : {}),
- };
-
- if (Object.keys(patch).length === 0) continue;
-
- await db.company.update({ where: { id: row.companyId }, data: patch });
- updated += 1;
- console.log(`${row.company.name}: ${JSON.stringify(patch)}`);
-}
-
-console.log(`\nUpdated ${updated} of ${rows.length} enriched companies.`);
-await db.$disconnect();
diff --git a/apps/api/scripts/build-func.mjs b/apps/api/scripts/build-func.mjs
index 6c44a4be..e3391930 100644
--- a/apps/api/scripts/build-func.mjs
+++ b/apps/api/scripts/build-func.mjs
@@ -1,16 +1,3 @@
-/**
- * Builds the API as a single Vercel function, via the Build Output API.
- *
- * Vercel's own tracing cannot deploy this app: the workspace packages export
- * raw TypeScript (`@crm/auth` -> src/index.ts), and every relative import in
- * `src` is extensionless because the repo compiles with
- * `moduleResolution: "Bundler"`. Traced and run as-is, Node fails on one or
- * the other — a missing `.ts`, or a missing `./create-app`.
- *
- * Bundling settles both at build time: bun resolves the whole graph, inlines
- * the workspace source, and emits one ESM file with no runtime resolution
- * left to do. Nothing about how the packages export has to change.
- */
import { execSync } from "node:child_process";
import {
cpSync,
@@ -31,14 +18,6 @@ const outDir = join(repoRoot, ".vercel/output");
const funcDir = join(outDir, "functions/api/index.func");
const bun = process.env.BUN_BIN || "bun";
-/**
- * Left out of the bundle.
- *
- * The `@nestjs/*` entries are optional platforms Nest probes for at runtime
- * and this app never installs; bundling them turns an absent peer into a
- * build error. The rest are native or environment-specific modules that
- * cannot survive being inlined.
- */
const EXTERNALS = [
"@nestjs/microservices",
"@nestjs/websockets",
@@ -51,12 +30,6 @@ const EXTERNALS = [
"cardinal",
];
-/**
- * Copied into the function's `node_modules` instead of bundled.
- *
- * Express is resolved by name at runtime by `@nestjs/platform-express`, so a
- * bundled copy is invisible to it.
- */
const VENDOR_ROOTS = ["express"];
rmSync(outDir, { recursive: true, force: true });
@@ -71,11 +44,6 @@ execSync(
`--outfile=${JSON.stringify(join(funcDir, "index.mjs"))}`,
...EXTERNALS.map((e) => `--external ${e}`),
].join(" "),
- // NODE_ENV matters at *build* time, not just at run time: bun constant-folds
- // `process.env.NODE_ENV`, so `isProduction` in @crm/auth is burned into the
- // bundle as a literal. Built without this, it folds to `false`, Better Auth
- // drops the `__Secure-` cookie prefix, the app's proxy looks for the
- // prefixed name over HTTPS and bounces every signed-in user to /sign-in.
{
cwd: apiDir,
stdio: "inherit",
@@ -83,17 +51,6 @@ execSync(
},
);
-/**
- * Pin NODE_ENV at run time too.
- *
- * The line above settles everything bun folded, but vendored and external
- * packages still read `process.env.NODE_ENV` themselves, and Vercel does not
- * inject it into functions declared through the Build Output API (it also
- * strips the name from a function's `environment` map, since it is reserved).
- *
- * `??=` so a real environment value still wins, and prepended rather than
- * `--define`d because it has to run before any bundled module body reads it.
- */
console.log("• pinning NODE_ENV in the bundle...");
const entry = join(funcDir, "index.mjs");
writeFileSync(
@@ -101,14 +58,6 @@ writeFileSync(
`process.env.NODE_ENV ??= "production";\n${readFileSync(entry, "utf8")}`,
);
-/**
- * Vendoring walks bun's store rather than resolving by name across it.
- *
- * A store holds several versions of the same package side by side, so
- * resolving by name alone can copy a version the dependent never asked for.
- * Each `.bun/<pkg>@<ver>/node_modules/` entry links the exact versions that
- * package resolves to, so dependencies are followed from there.
- */
console.log("• vendoring runtime-resolved dependencies...");
const bunStore = join(repoRoot, "node_modules/.bun");
const stores = existsSync(bunStore) ? readdirSync(bunStore) : [];
@@ -200,17 +149,7 @@ writeFileSync(
shouldAddHelpers: false,
maxDuration: 60,
memory: 1769,
- /**
- * Vercel injects NODE_ENV for framework builds but not for functions
- * declared through the Build Output API, and Better Auth keys
- * `useSecureCookies` off it. Unset, it issued the session cookie without
- * the `__Secure-` prefix, the app's proxy looked for the prefixed name
- * over HTTPS, found nothing, and bounced every signed-in user back to
- * /sign-in. It also selects JSON logging over the colourised dev sink.
- */
environment: { NODE_ENV: "production" },
- // Beside the database: Neon is us-east-1, and every request makes
- // several round trips to it.
regions: ["iad1"],
}),
);
@@ -218,26 +157,7 @@ writeFileSync(
join(outDir, "config.json"),
JSON.stringify({
version: 3,
- // Nest owns its own routing — /health, /api/auth/*, /api/trpc/* — so
- // everything goes to the one function.
routes: [{ src: "/(.*)", dest: "/api/index" }],
- /**
- * The Gmail and Calendar sync.
- *
- * Declared here rather than in `apps/api/vercel.json`, because that file
- * is never read: this project's Root Directory is the repository root,
- * so Vercel looks for `/vercel.json` and the one beside the app is
- * inert. The cron silently did not exist — the sync only ever ran when
- * somebody called the route by hand, and the CRM quietly stopped
- * learning anything new from the mailbox.
- *
- * A root `vercel.json` is not the fix, because `crm-agent` builds from
- * the same root directory and would inherit a schedule for a route it
- * does not serve. The Build Output API is per-project by construction.
- *
- * The route fails closed without `CRON_SECRET`, so this is safe to
- * declare unconditionally.
- */
crons: [{ path: "/internal/sync/google", schedule: "*/5 * * * *" }],
}),
);
diff --git a/apps/api/scripts/chmod-trpc-binary.mjs b/apps/api/scripts/chmod-trpc-binary.mjs
index 63aeed1f..6ac15559 100644
--- a/apps/api/scripts/chmod-trpc-binary.mjs
+++ b/apps/api/scripts/chmod-trpc-binary.mjs
@@ -1,6 +1,3 @@
-// nestjs-trpc ships prebuilt native binaries that arrive without the execute
-// bit when Bun unpacks the tarball, so `nestjs-trpc generate` fails with EACCES
-// on a clean install. Restore it after every install.
import { chmodSync, existsSync } from "node:fs";
import { createRequire } from "node:module";
import { dirname, join, parse } from "node:path";
@@ -14,11 +11,6 @@ const NATIVE_TARGETS = [
"x86_64-unknown-linux-gnu",
];
-/**
- * The package root, found by walking up from whatever `nestjs-trpc` resolves
- * to. `nestjs-trpc/package.json` is not in the package's `exports` map, so it
- * cannot be resolved directly.
- */
function packageRoot() {
let dir;
try {
@@ -43,8 +35,6 @@ if (root) {
if (!existsSync(binary)) continue;
try {
chmodSync(binary, 0o755);
- } catch {
- // A read-only store is not a reason to fail `bun install`.
- }
+ } catch {}
}
}
diff --git a/apps/api/scripts/dev-session.ts b/apps/api/scripts/dev-session.ts
index f97c1dc6..421f6e80 100644
--- a/apps/api/scripts/dev-session.ts
+++ b/apps/api/scripts/dev-session.ts
@@ -1,19 +1,3 @@
-/**
- * Mints a signed session cookie for a local user.
- *
- * Google is the only sign-in method, which means there is no way to get a
- * session from a script, a test, or a terminal — you need a browser and a real
- * Google account. That is correct for the product and useless for development,
- * so this writes the two rows Better Auth would have written and prints the
- * cookie it would have set.
- *
- * bun run --filter=api dev:session # dev@localhost
- * bun run --filter=api dev:session [email protected]
- *
- * curl -H "Cookie: $(bun run --filter=api dev:session)" localhost:3001/auth/me
- *
- * Refuses to run in production: it hands out a valid session for any email.
- */
import { db } from "@crm/db";
const COOKIE_NAME = "better-auth.session_token";
@@ -33,7 +17,6 @@ if (!secret) {
const email = process.argv[2] ?? "dev@localhost";
const name = email.split("@")[0] ?? "Developer";
-/** `value.base64(hmacSha256(secret, value))`, url-encoded — Better Auth's format. */
async function signCookieValue(value: string): Promise<string> {
const key = await crypto.subtle.importKey(
"raw",
diff --git a/apps/api/src/activities/activities.contracts.ts b/apps/api/src/activities/activities.contracts.ts
index f7b2fbd7..a7a19f19 100644
--- a/apps/api/src/activities/activities.contracts.ts
+++ b/apps/api/src/activities/activities.contracts.ts
@@ -1,8 +1,6 @@
import { ActivityType } from "@crm/db";
import { z } from "zod";
-/** Types a human can log. `STAGE_CHANGE` and `ENRICHMENT` are written by the
- * system and the agent, and are not offered in the composer. */
const COMPOSABLE_TYPES = [
ActivityType.NOTE,
ActivityType.CALL,
@@ -13,46 +11,29 @@ const COMPOSABLE_TYPES = [
const composableEnum = z.enum(COMPOSABLE_TYPES);
-/**
- * Which slice of a timeline to show.
- *
- * `history` is `all` minus the tasks that are still outstanding: the timeline
- * pins those at the top, and an entry that appears both pinned and in the
- * history below it reads as two different things having happened.
- */
const TIMELINE_FILTERS = [
"all",
"history",
"notes",
"upcoming",
"done",
- /** Synced Gmail threads and logged emails. */
"email",
- /** Synced calendar events and logged meetings. */
"meetings",
] as const;
export type TimelineFilter = (typeof TIMELINE_FILTERS)[number];
-/**
- * Exactly one anchor. A timeline is always "everything about this thing", and
- * a company's timeline picks up its deals' and contacts' entries for free
- * because `companyId` is stamped on write.
- */
export const timelineInput = z.object({
companyId: z.string().optional(),
contactId: z.string().optional(),
dealId: z.string().optional(),
filter: z.enum(TIMELINE_FILTERS).default("all"),
- /** Activity id to continue after — timelines page by cursor, not by offset,
- * because new entries arrive at the top while you are reading. */
cursor: z.string().optional(),
limit: z.number().int().min(1).max(100).default(30),
});
export type TimelineInput = z.infer<typeof timelineInput>;
-/** The same anchor, without the paging — for the filter tab counts. */
export const timelineCountsInput = z.object({
companyId: z.string().optional(),
contactId: z.string().optional(),
@@ -64,9 +45,7 @@ export const activityCreateInput = z
type: composableEnum,
subject: z.string().trim().optional(),
body: z.string().trim().optional(),
- /** ISO-8601. When it happened, for something being logged after the fact. */
occurredAt: z.string().optional(),
- /** ISO-8601. When it is due, for a task. */
dueAt: z.string().nullable().optional(),
companyId: z.string().optional(),
contactId: z.string().optional(),
@@ -87,12 +66,10 @@ export type ActivityCreateInput = z.infer<typeof activityCreateInput>;
export const completeInput = z.object({
id: z.string(),
- /** `false` reopens a task that was ticked off by mistake. */
completed: z.boolean().default(true),
});
export const myTasksInput = z.object({
- /** `"overdue"`, `"upcoming"`, or `"all"` open tasks. */
window: z.enum(["overdue", "upcoming", "all"]).default("all"),
limit: z.number().int().min(1).max(100).default(25),
});
diff --git a/apps/api/src/activities/activities.service.ts b/apps/api/src/activities/activities.service.ts
index ab79e75e..23510a35 100644
--- a/apps/api/src/activities/activities.service.ts
+++ b/apps/api/src/activities/activities.service.ts
@@ -37,8 +37,6 @@ const ENTRY_SELECT = {
contact: { select: { id: true, firstName: true, lastName: true } },
deal: { select: { id: true, name: true } },
- // Summaries only. An email body never rides on a list payload — the row
- // carries a snippet, and the accordion fetches `google.thread` on expand.
emailThread: {
select: {
id: true,
@@ -59,7 +57,6 @@ const ENTRY_SELECT = {
},
} as const;
-/** Entries a `NOTE`-ish filter should keep — what someone wrote down. */
const NOTE_TYPES = [
ActivityType.NOTE,
ActivityType.CALL,
@@ -76,29 +73,14 @@ export class ActivitiesService {
private readonly stamp: ActivityStampService,
) {}
- /**
- * A record's timeline, newest first, paged by cursor.
- *
- * Cursor rather than offset because entries are added at the top while
- * someone is reading: page two of an offset query would repeat whatever the
- * new entry pushed down.
- */
async timeline(input: TimelineInput) {
const where = this.anchor(input);
Object.assign(where, filterClause(input.filter));
const rows = await this.db.activity.findMany({
where,
- // One more than asked for, so we know whether there is another page
- // without a second count query.
take: input.limit + 1,
...(input.cursor ? { cursor: { id: input.cursor }, skip: 1 } : {}),
- // By when it *happened*, not when the row was written. Those were the
- // same thing while a human logged everything by hand, and stopped being
- // the same thing the moment a sync started writing: a first sync stamps
- // every thread and meeting with roughly one `createdAt`, so ordering by
- // it would jumble a year of history into one arbitrary block. `id` breaks
- // ties so the cursor stays deterministic.
orderBy: [
{ occurredAt: { sort: "desc", nulls: "last" } },
{ id: "desc" },
@@ -115,11 +97,6 @@ export class ActivitiesService {
};
}
- /**
- * Counts for the timeline's filter tabs, over the same anchor.
- *
- * Separate from `timeline` so paging does not re-count on every scroll.
- */
async timelineCounts(
input: Pick<TimelineInput, "companyId" | "contactId" | "dealId">,
) {
@@ -146,8 +123,6 @@ export class ActivitiesService {
}
async create(input: ActivityCreateInput, actingUserId: string) {
- // A deal or contact activity is stamped with its company too, so a company
- // timeline is one indexed range scan instead of three joins.
const companyId = await this.resolveCompanyId(input);
const isTask = input.type === ActivityType.TASK;
@@ -157,15 +132,6 @@ export class ActivitiesService {
type: input.type,
subject: blankToNull(input.subject ?? ""),
body: blankToNull(input.body ?? ""),
- // Every entry is stamped with where it belongs on the timeline,
- // tasks included.
- //
- // A task is scheduled rather than logged, so this used to be null for
- // them — and `orderBy` sorts nulls last, so every task sank beneath
- // the whole history and stayed there. The one you added a second ago
- // appeared at the bottom of today, under things from this morning.
- // `dueAt` is when it is *for*; this is when it was written down, which
- // is what a reverse-chronological list is ordered by.
occurredAt: parseDate(input.occurredAt) ?? new Date(),
dueAt: isTask ? parseDate(input.dueAt) : null,
companyId,
@@ -190,7 +156,6 @@ export class ActivitiesService {
return serializeEntry(activity);
}
- /** Ticks a task off, or puts it back. */
async complete(id: string, completed: boolean) {
const activity = await this.db.activity.findUnique({
where: { id },
@@ -214,7 +179,6 @@ export class ActivitiesService {
return serializeEntry(updated);
}
- /** Open tasks assigned to whoever is asking. */
async myTasks(input: MyTasksInput, actingUserId: string) {
const now = new Date();
const where: Prisma.ActivityWhereInput = {
@@ -229,8 +193,6 @@ export class ActivitiesService {
const tasks = await this.db.activity.findMany({
where,
take: input.limit,
- // Undated tasks last: a task with no due date is a someday, and it
- // should not sit above something due this afternoon.
orderBy: [
{ dueAt: { sort: "asc", nulls: "last" } },
{ createdAt: "desc" },
@@ -241,7 +203,6 @@ export class ActivitiesService {
return tasks.map(serializeEntry);
}
- /** Exactly one of company/contact/deal, as the contract promises. */
private anchor(
input: Pick<TimelineInput, "companyId" | "contactId" | "dealId">,
): Prisma.ActivityWhereInput {
@@ -253,13 +214,6 @@ export class ActivitiesService {
);
}
- /**
- * The company an activity belongs to.
- *
- * Taken from the deal or contact when the caller did not say, which is what
- * makes the company timeline work without joins. A contact with no company
- * simply has no company stamp.
- */
private async resolveCompanyId(
input: ActivityCreateInput,
): Promise<string | null> {
@@ -296,17 +250,11 @@ function filterClause(filter: TimelineFilter): Prisma.ActivityWhereInput {
case "notes":
return { type: { in: NOTE_TYPES } };
case "upcoming":
- // Everything still outstanding, overdue included — "upcoming" on a
- // timeline means "not done yet", and hiding the overdue ones is how
- // they get forgotten.
return { type: ActivityType.TASK, completedAt: null };
case "done":
return { type: ActivityType.TASK, completedAt: { not: null } };
case "history":
return { NOT: { type: ActivityType.TASK, completedAt: null } };
- // Both cover what a rep logged by hand *and* what the Google sync
- // projected — from the timeline's point of view they are the same event,
- // and splitting them would make "did we email them?" two questions.
case "email":
return { type: ActivityType.EMAIL };
case "meetings":
@@ -318,7 +266,6 @@ function filterClause(filter: TimelineFilter): Prisma.ActivityWhereInput {
type Entry = Prisma.ActivityGetPayload<{ select: typeof ENTRY_SELECT }>;
-/** Dates as ISO strings so they survive JSON, and `meta` narrowed for the UI. */
function serializeEntry(entry: Entry) {
return {
...entry,
diff --git a/apps/api/src/agent/agent-queue.service.ts b/apps/api/src/agent/agent-queue.service.ts
index 9b4c675b..2089400d 100644
--- a/apps/api/src/agent/agent-queue.service.ts
+++ b/apps/api/src/agent/agent-queue.service.ts
@@ -2,35 +2,18 @@ import type { Db } from "@crm/db";
import { Injectable } from "@nestjs/common";
import { InjectDatabase } from "../database/database.constants";
-/**
- * Whether a record has agent work outstanding.
- *
- * This exists because `enrichmentStatus` cannot answer the question and was
- * being asked it anyway. `PENDING` is the column's *default*, so every contact
- * and company carries it from the moment it is inserted — and the sheet
- * rendered that as "Queued", on 62 of 73 records against 3 rows in the queue.
- * A status that is true at birth says nothing about whether anybody intends to
- * do anything.
- *
- * Reading the queue is filing, not intelligence: it counts rows the agent
- * wrote and decides nothing about a person, so it belongs on this side of
- * `docs/api.md`'s line.
- */
@Injectable()
export class AgentQueueService {
constructor(@InjectDatabase() private readonly db: Db) {}
- /** Of these companies, the ones with an unfinished task. */
async queuedCompanies(ids: readonly string[]): Promise<Set<string>> {
return this.queued("companyId", ids);
}
- /** Of these contacts, the ones with an unfinished task. */
async queuedContacts(ids: readonly string[]): Promise<Set<string>> {
return this.queued("contactId", ids);
}
- /** One record, for a detail view that has no list to batch with. */
async isQueued(subject: {
companyId?: string;
contactId?: string;
@@ -47,11 +30,6 @@ export class AgentQueueService {
return row !== null;
}
- /**
- * One query for the whole page rather than one per row — a list of 50
- * companies is 50 lookups done the obvious way, on every keystroke of the
- * table's search box.
- */
private async queued(
column: "companyId" | "contactId",
ids: readonly string[],
diff --git a/apps/api/src/agent/agent-trigger.service.ts b/apps/api/src/agent/agent-trigger.service.ts
index 70b9c510..b3ad1669 100644
--- a/apps/api/src/agent/agent-trigger.service.ts
+++ b/apps/api/src/agent/agent-trigger.service.ts
@@ -2,28 +2,12 @@ import type { Db } from "@crm/db";
import { Injectable, Logger } from "@nestjs/common";
import { InjectDatabase } from "../database/database.constants";
-/**
- * How the API tells the agent something happened.
- *
- * This is the whole of what Nest knows about enrichment, and it is deliberately
- * not enrichment: it reports an event and states why it might matter. No vendor
- * client, no scoring, no decision about a person. What the agent does with
- * "this company was just created" — whether to look it up now, later, or at all
- * — is the agent's business.
- *
- * A row rather than an HTTP call to the agent. The dispatcher already leases
- * work from this table, so a row *is* the message, and it survives the agent
- * being down, redeployed, or slower than the request that produced it. An
- * outbound call from a request handler would have to be awaited (slow), fired
- * and forgotten (lost), or queued — and queued is this.
- */
@Injectable()
export class AgentTriggerService {
private readonly logger = new Logger(AgentTriggerService.name);
constructor(@InjectDatabase() private readonly db: Db) {}
- /** A company we have never seen. Nothing on it but a domain. */
async companyCreated(
companyId: string,
reason = "New company",
@@ -37,25 +21,16 @@ export class AgentTriggerService {
});
}
- /** A rep pressed a button and is watching. */
async companyRequested(companyId: string, reason: string): Promise<void> {
await this.enqueue({
companyId,
kind: "company-profile",
reason,
- // Somebody is looking at the screen, so this goes to the front.
priority: 100,
budget: 8,
});
}
- /**
- * A contact arrived from a sync knowing only an address.
- *
- * The old path called an enrichment service here and it fired only when the
- * name looked derived. That test now lives with the agent, because "is this
- * name a placeholder" is a judgement about a person.
- */
async contactCreated(contactId: string, reason: string): Promise<void> {
await this.enqueue({
contactId,
@@ -66,18 +41,76 @@ export class AgentTriggerService {
});
}
- /** A meeting with someone we do not know yet, happening soon. */
async meetingSoon(contactId: string, when: Date): Promise<void> {
await this.enqueue({
contactId,
kind: "meeting-prep",
reason: `Meeting on ${when.toDateString()} with someone we know nothing about`,
- // Ahead of everything: the deadline is real and it is tomorrow.
priority: 200,
budget: 10,
});
}
+ async backfill(input: {
+ kind: string;
+ reason: string;
+ contactIds?: string[];
+ companyIds?: string[];
+ budget?: number;
+ }): Promise<{ queued: number; alreadyQueued: number }> {
+ const subject = input.contactIds ? "contactId" : "companyId";
+ const ids = [...new Set(input.contactIds ?? input.companyIds ?? [])];
+ if (ids.length === 0) return { queued: 0, alreadyQueued: 0 };
+
+ try {
+ const outstanding = await this.db.agentTask.findMany({
+ where: {
+ kind: input.kind,
+ finishedAt: null,
+ [subject]: { in: ids },
+ },
+ select: { [subject]: true },
+ });
+
+ const taken = new Set(
+ outstanding.map((row) => (row as Record<string, unknown>)[subject]),
+ );
+ const fresh = ids.filter((id) => !taken.has(id));
+
+ if (fresh.length > 0) {
+ await this.db.agentTask.createMany({
+ data: fresh.map((id) => ({
+ contactId: input.contactIds ? id : null,
+ companyId: input.companyIds ? id : null,
+ kind: input.kind,
+ reason: input.reason,
+ priority: 50,
+ budget: input.budget ?? 4,
+ dueAt: new Date(),
+ })),
+ });
+ }
+
+ this.logger.log({
+ message: "Backfill queued",
+ kind: input.kind,
+ queued: fresh.length,
+ alreadyQueued: ids.length - fresh.length,
+ });
+
+ return {
+ queued: fresh.length,
+ alreadyQueued: ids.length - fresh.length,
+ };
+ } catch (error) {
+ this.logger.error(
+ { message: "Could not queue backfill", kind: input.kind },
+ error instanceof Error ? error.stack : String(error),
+ );
+ throw error;
+ }
+ }
+
private async enqueue(task: {
contactId?: string;
companyId?: string;
@@ -87,9 +120,6 @@ export class AgentTriggerService {
budget: number;
}): Promise<void> {
try {
- // Nothing is queued twice for the same subject and kind while a run is
- // still outstanding — a company saved three times in a minute is one
- // piece of work, not three.
const pending = await this.db.agentTask.findFirst({
where: {
kind: task.kind,
@@ -121,8 +151,6 @@ export class AgentTriggerService {
companyId: task.companyId,
});
} catch (error) {
- // Never fail the request that caused it. Enrichment has never been on a
- // request path and this is not the moment to put it there.
this.logger.error(
{ message: "Could not queue agent task", kind: task.kind },
error instanceof Error ? error.stack : String(error),
diff --git a/apps/api/src/agent/agent.module.ts b/apps/api/src/agent/agent.module.ts
index 29bc1e3f..fb1c4067 100644
--- a/apps/api/src/agent/agent.module.ts
+++ b/apps/api/src/agent/agent.module.ts
@@ -2,15 +2,6 @@ import { Module } from "@nestjs/common";
import { AgentQueueService } from "./agent-queue.service";
import { AgentTriggerService } from "./agent-trigger.service";
-/**
- * The API's entire relationship with the research agent.
- *
- * Two services and two verbs: *this happened*, and *is anything outstanding*.
- * What replaced `EnrichmentModule` is smaller than the module docstring it
- * replaced, which is the point — there is no vendor client here, and nothing
- * that knows what a LinkedIn profile is. Writing a row saying a company was
- * created and counting the rows not yet done are both filing.
- */
@Module({
providers: [AgentTriggerService, AgentQueueService],
exports: [AgentTriggerService, AgentQueueService],
diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts
index 173164ba..ee2d875c 100644
--- a/apps/api/src/app.module.ts
+++ b/apps/api/src/app.module.ts
@@ -4,6 +4,7 @@ import { ConfigModule } from "@nestjs/config";
import { AuthModule as BetterAuthModule } from "@thallesp/nestjs-better-auth";
import { ActivitiesModule } from "./activities/activities.module";
import { AuthModule } from "./auth/auth.module";
+import { BackfillModule } from "./backfill/backfill.module";
import { AppCacheModule } from "./cache/cache.module";
import { CompaniesModule } from "./companies/companies.module";
import { validateEnv } from "./config/env.validation";
@@ -18,6 +19,7 @@ import { HealthModule } from "./health/health.module";
import { LoggingModule } from "./logging/logging.module";
import { logAuthRoute } from "./logging/request-logger.middleware";
import { SearchModule } from "./search/search.module";
+import { SettingsModule } from "./settings/settings.module";
import { TrpcModule } from "./trpc/trpc.module";
import { UsersModule } from "./users/users.module";
@@ -45,6 +47,8 @@ import { UsersModule } from "./users/users.module";
DashboardModule,
SearchModule,
GoogleModule,
+ SettingsModule,
+ BackfillModule,
],
})
export class AppModule {}
diff --git a/apps/api/src/auth/auth-hooks.service.ts b/apps/api/src/auth/auth-hooks.service.ts
index f50f96cc..d5b6fb8d 100644
--- a/apps/api/src/auth/auth-hooks.service.ts
+++ b/apps/api/src/auth/auth-hooks.service.ts
@@ -2,14 +2,6 @@ import { Injectable, Logger } from "@nestjs/common";
import { AfterUpdate, DatabaseHook } from "@thallesp/nestjs-better-auth";
import { AuthService } from "./auth.service";
-/**
- * Cached profiles are bounded by TTL; this drops one the moment its row
- * changes, so a rename never lingers for five minutes.
- *
- * A database hook rather than an endpoint hook: Better Auth also writes to
- * `user` when Google reports a changed name or avatar at sign-in, and that
- * never goes through `/update-user`.
- */
@DatabaseHook()
@Injectable()
export class AuthHooksService {
@@ -22,9 +14,6 @@ export class AuthHooksService {
try {
await this.authService.invalidateProfile(user.id);
} catch (error) {
- // This runs inside Better Auth's write pipeline: throwing here would
- // fail the update itself. A stale profile expires on its own within
- // the TTL, so log it and let the write stand.
this.logger.error(
{ message: "Failed to invalidate cached profile", userId: user.id },
error instanceof Error ? error.stack : String(error),
diff --git a/apps/api/src/auth/auth.service.ts b/apps/api/src/auth/auth.service.ts
index b69161c1..98b9408e 100644
--- a/apps/api/src/auth/auth.service.ts
+++ b/apps/api/src/auth/auth.service.ts
@@ -10,7 +10,6 @@ export interface UserProfile {
email: string;
emailVerified: boolean;
image: string | null;
- /** ISO-8601: a `Date` would come back from Redis as a string anyway. */
createdAt: string;
}
@@ -27,11 +26,6 @@ export class AuthService {
@Inject(CACHE_MANAGER) private readonly cache: Cache,
) {}
- /**
- * The session already carries a user, but it is the snapshot taken when the
- * cookie was minted. Reading the row means a profile change shows up within
- * the cache TTL instead of at the next sign-in.
- */
async getProfile(userId: string): Promise<UserProfile> {
const key = profileKey(userId);
const cached = await this.cache.get<UserProfile>(key);
@@ -55,8 +49,6 @@ export class AuthService {
});
if (!user) {
- // A live session pointing at a deleted row: worth a warning, because
- // it means a session outlived its user.
this.logger.warn({ message: "Session user no longer exists", userId });
throw new NotFoundException(`No user with id ${userId}.`);
}
diff --git a/apps/api/src/backfill/backfill.module.ts b/apps/api/src/backfill/backfill.module.ts
new file mode 100644
index 00000000..8915a83c
--- /dev/null
+++ b/apps/api/src/backfill/backfill.module.ts
@@ -0,0 +1,11 @@
+import { Module } from "@nestjs/common";
+import { AgentModule } from "../agent/agent.module";
+import { CompaniesModule } from "../companies/companies.module";
+import { BackfillService } from "./backfill.service";
+import { ImageMirrorService } from "./image-mirror.service";
+
+@Module({
+ imports: [AgentModule, CompaniesModule],
+ providers: [BackfillService, ImageMirrorService],
+})
+export class BackfillModule {}
diff --git a/apps/api/src/backfill/backfill.service.ts b/apps/api/src/backfill/backfill.service.ts
new file mode 100644
index 00000000..f8a749fa
--- /dev/null
+++ b/apps/api/src/backfill/backfill.service.ts
@@ -0,0 +1,248 @@
+import { onSignedIn } from "@crm/auth";
+import { type Db, EnrichmentStatus, type Prisma } from "@crm/db";
+import { CACHE_MANAGER } from "@nestjs/cache-manager";
+import { Inject, Injectable, Logger, type OnModuleInit } from "@nestjs/common";
+import type { Cache } from "cache-manager";
+import { AgentTriggerService } from "../agent/agent-trigger.service";
+import { FaviconService } from "../companies/favicon.service";
+import { InjectDatabase } from "../database/database.constants";
+import { ImageMirrorService } from "./image-mirror.service";
+
+export type BackfillScope = "companies" | "contacts" | "deals";
+
+export type BackfillResult = {
+ queued: number;
+ alreadyQueued: number;
+ remaining: number;
+ iconsResolving: number;
+};
+
+const MAX_PER_RUN = 500;
+
+const MAX_FAVICONS = 25;
+
+const NEVER_SUCCEEDED: Prisma.EnumEnrichmentStatusFilter = {
+ in: [EnrichmentStatus.PENDING, EnrichmentStatus.FAILED],
+};
+
+const AUTO_KEY = "backfill:auto";
+
+const AUTO_EVERY_MS = 5 * 60_000;
+
+/**
+ * How long a fruitless photo search stands the contact down for.
+ *
+ * Long, because the answer rarely changes: somebody with no LinkedIn account
+ * and no headshot on their employer's site is unlikely to acquire either this
+ * week, and the team-page read costs credits every time it is asked.
+ */
+const RECHECK_PHOTO_AFTER_MS = 30 * 24 * 60 * 60_000;
+
+@Injectable()
+export class BackfillService implements OnModuleInit {
+ private readonly logger = new Logger(BackfillService.name);
+
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly agent: AgentTriggerService,
+ private readonly favicon: FaviconService,
+ private readonly images: ImageMirrorService,
+ @Inject(CACHE_MANAGER) private readonly cache: Cache,
+ ) {}
+
+ onModuleInit(): void {
+ onSignedIn(() => {
+ void this.auto();
+ });
+ }
+
+ async auto(): Promise<{ started: boolean }> {
+ if (await this.cache.get(AUTO_KEY)) return { started: false };
+ await this.cache.set(AUTO_KEY, true, AUTO_EVERY_MS);
+
+ void (async () => {
+ try {
+ const companies = await this.runCompanies(false);
+ const contacts = await this.runContacts();
+
+ const mirrored = await this.images.sweep();
+
+ this.logger.log({
+ message: "Automatic backfill swept",
+ queued: companies.queued + contacts.queued,
+ remaining: companies.remaining + contacts.remaining,
+ iconsResolving: companies.iconsResolving,
+ imagesMirrored: mirrored.copied,
+ });
+ } catch (error) {
+ this.logger.error(
+ { message: "Automatic backfill failed" },
+ error instanceof Error ? error.stack : String(error),
+ );
+ }
+ })();
+
+ return { started: true };
+ }
+
+ async run(scope: BackfillScope): Promise<BackfillResult> {
+ if (scope === "contacts") return this.runContacts();
+
+ return this.runCompanies(scope === "deals");
+ }
+
+ private async runCompanies(dealsOnly: boolean): Promise<BackfillResult> {
+ const where: Prisma.CompanyWhereInput = {
+ ...this.companiesNeedingBrand(),
+ ...(dealsOnly ? { deals: { some: {} } } : {}),
+ };
+
+ const [total, rows] = await Promise.all([
+ this.db.company.count({ where }),
+ this.db.company.findMany({
+ where,
+ orderBy: { createdAt: "asc" },
+ take: MAX_PER_RUN,
+ select: { id: true },
+ }),
+ ]);
+
+ const queued = await this.agent.backfill({
+ kind: "company-profile",
+ reason: "Backfill — this company was never successfully looked up",
+ companyIds: rows.map((row) => row.id),
+ });
+
+ const iconsResolving = dealsOnly ? 0 : await this.sweepFavicons();
+
+ return {
+ ...queued,
+ remaining: Math.max(0, total - rows.length),
+ iconsResolving,
+ };
+ }
+
+ private async runContacts(): Promise<BackfillResult> {
+ const needsPhoto = await this.contactsNeedingPhoto();
+
+ const [photoTotal, photoRows] = await Promise.all([
+ this.db.contact.count({ where: needsPhoto }),
+ this.db.contact.findMany({
+ where: needsPhoto,
+ orderBy: { createdAt: "asc" },
+ take: MAX_PER_RUN,
+ select: { id: true },
+ }),
+ ]);
+
+ const photos = await this.agent.backfill({
+ kind: "portrait",
+ reason: "Backfill — somewhere to look for a picture, and no picture",
+ contactIds: photoRows.map((row) => row.id),
+ budget: 1,
+ });
+
+ const headroom = MAX_PER_RUN - photoRows.length;
+
+ const [researchTotal, researchRows] = await Promise.all([
+ this.db.contact.count({ where: this.contactsNeverResearched() }),
+ headroom > 0
+ ? this.db.contact.findMany({
+ where: this.contactsNeverResearched(),
+ orderBy: { createdAt: "asc" },
+ take: headroom,
+ select: { id: true },
+ })
+ : Promise.resolve([]),
+ ]);
+
+ const research = await this.agent.backfill({
+ kind: "identify",
+ reason: "Backfill — this contact was never researched",
+ contactIds: researchRows.map((row) => row.id),
+ });
+
+ return {
+ queued: photos.queued + research.queued,
+ alreadyQueued: photos.alreadyQueued + research.alreadyQueued,
+ remaining:
+ Math.max(0, photoTotal - photoRows.length) +
+ Math.max(0, researchTotal - researchRows.length),
+ iconsResolving: 0,
+ };
+ }
+
+ private async sweepFavicons(): Promise<number> {
+ const rows = await this.db.company.findMany({
+ where: { domain: { not: null }, iconUrl: null },
+ orderBy: { createdAt: "asc" },
+ take: MAX_FAVICONS,
+ select: { id: true, domain: true },
+ });
+
+ if (rows.length === 0) return 0;
+
+ void (async () => {
+ let resolved = 0;
+ for (const row of rows) {
+ if (await this.favicon.backfill(row.id, row.domain)) resolved += 1;
+ }
+ this.logger.log({
+ message: "Favicon sweep finished",
+ attempted: rows.length,
+ resolved,
+ });
+ })();
+
+ return rows.length;
+ }
+
+ private companiesNeedingBrand(): Prisma.CompanyWhereInput {
+ return { domain: { not: null }, enrichmentStatus: NEVER_SUCCEEDED };
+ }
+
+ /**
+ * Contacts with a face to fetch and nowhere it has been put yet.
+ *
+ * Three doors qualify, matching the agent's chain: a LinkedIn URL, a GitHub
+ * URL, or an employer with a website. The third is the expensive one — it
+ * spends Context.dev credits reading the company's team page — and it is in
+ * here because it works, which is the only reason worth having.
+ *
+ * Which makes the exclusion below load-bearing rather than an optimisation.
+ * Most people are not on their employer's team page and never will be, so
+ * without it every sweep would pay to re-read the same forty sites and find
+ * the same nothing, for as long as the install runs. A finished `portrait`
+ * task is the record that we looked; a month is long enough that a rebuilt
+ * team page or a new LinkedIn account is still picked up eventually.
+ */
+ private async contactsNeedingPhoto(): Promise<Prisma.ContactWhereInput> {
+ const since = new Date(Date.now() - RECHECK_PHOTO_AFTER_MS);
+
+ // `AgentTask.contactId` is a bare column with no Prisma relation, so this
+ // cannot be a nested `some`. Two queries, and the id list is bounded by
+ // the number of contacts we have already looked for.
+ const checked = await this.db.agentTask.findMany({
+ where: { kind: "portrait", finishedAt: { gte: since } },
+ select: { contactId: true },
+ });
+
+ const recentlyChecked = checked
+ .map((row) => row.contactId)
+ .filter((id): id is string => id !== null);
+
+ return {
+ imageUrl: null,
+ ...(recentlyChecked.length > 0 ? { id: { notIn: recentlyChecked } } : {}),
+ OR: [
+ { linkedinUrl: { not: null } },
+ { githubUrl: { not: null } },
+ { company: { domain: { not: null } } },
+ ],
+ };
+ }
+
+ private contactsNeverResearched(): Prisma.ContactWhereInput {
+ return { enrichmentStatus: NEVER_SUCCEEDED };
+ }
+}
diff --git a/apps/api/src/backfill/image-mirror.service.ts b/apps/api/src/backfill/image-mirror.service.ts
new file mode 100644
index 00000000..c6f46c85
--- /dev/null
+++ b/apps/api/src/backfill/image-mirror.service.ts
@@ -0,0 +1,157 @@
+import type { Db, Prisma } from "@crm/db";
+import { blobEnabled, mirror } from "@crm/db/blob";
+import { BLOB_HOST_SUFFIX, COMPANY_IMAGE_FIELDS } from "@crm/db/images";
+import { Injectable, Logger } from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+
+const MAX_PER_SWEEP = 25;
+
+export type ImageMirrorResult = {
+ scanned: number;
+ copied: number;
+};
+
+@Injectable()
+export class ImageMirrorService {
+ private readonly logger = new Logger(ImageMirrorService.name);
+
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ async sweep(): Promise<ImageMirrorResult> {
+ if (!blobEnabled()) return { scanned: 0, copied: 0 };
+
+ const results = [
+ await this.sweepCompanies(),
+ await this.sweepContacts(),
+ await this.sweepUsers(),
+ ];
+
+ const total = results.reduce(
+ (sum, result) => ({
+ scanned: sum.scanned + result.scanned,
+ copied: sum.copied + result.copied,
+ }),
+ { scanned: 0, copied: 0 },
+ );
+
+ if (total.copied > 0) {
+ this.logger.log({ message: "Mirrored external images", ...total });
+ }
+
+ return total;
+ }
+
+ private async sweepCompanies(): Promise<ImageMirrorResult> {
+ const rows = await this.db.company.findMany({
+ where: {
+ OR: COMPANY_IMAGE_FIELDS.map((field) => external(field)),
+ },
+ orderBy: { createdAt: "asc" },
+ take: MAX_PER_SWEEP,
+ select: {
+ id: true,
+ logoUrl: true,
+ logoDarkUrl: true,
+ iconUrl: true,
+ iconDarkUrl: true,
+ },
+ });
+
+ let copied = 0;
+
+ for (const row of rows) {
+ const data: Prisma.CompanyUpdateInput = {};
+
+ for (const field of COMPANY_IMAGE_FIELDS) {
+ const current = row[field];
+ if (!current) continue;
+
+ const stored = await mirror(current, `companies/${row.id}/${field}`);
+ if (!stored || stored === current) continue;
+
+ data[field] = stored;
+ copied += 1;
+ }
+
+ if (Object.keys(data).length === 0) continue;
+
+ await this.db.company.updateMany({
+ where: { id: row.id, ...unchanged(row) },
+ data,
+ });
+ }
+
+ return { scanned: rows.length, copied };
+ }
+
+ private async sweepContacts(): Promise<ImageMirrorResult> {
+ const rows = await this.db.contact.findMany({
+ where: external("imageUrl"),
+ orderBy: { createdAt: "asc" },
+ take: MAX_PER_SWEEP,
+ select: { id: true, imageUrl: true },
+ });
+
+ let copied = 0;
+
+ for (const row of rows) {
+ if (!row.imageUrl) continue;
+
+ const stored = await mirror(row.imageUrl, `contacts/${row.id}`);
+ if (!stored || stored === row.imageUrl) continue;
+
+ const { count } = await this.db.contact.updateMany({
+ where: { id: row.id, imageUrl: row.imageUrl },
+ data: { imageUrl: stored },
+ });
+
+ copied += count;
+ }
+
+ return { scanned: rows.length, copied };
+ }
+
+ private async sweepUsers(): Promise<ImageMirrorResult> {
+ const rows = await this.db.user.findMany({
+ where: external("image"),
+ take: MAX_PER_SWEEP,
+ select: { id: true, image: true },
+ });
+
+ let copied = 0;
+
+ for (const row of rows) {
+ if (!row.image) continue;
+
+ const stored = await mirror(row.image, `users/${row.id}/avatar`);
+ if (!stored || stored === row.image) continue;
+
+ const { count } = await this.db.user.updateMany({
+ where: { id: row.id, image: row.image },
+ data: { image: stored },
+ });
+
+ copied += count;
+ }
+
+ return { scanned: rows.length, copied };
+ }
+}
+
+function external<T extends string>(
+ field: T,
+): Record<T, { not: null }> & { NOT: Record<T, { contains: string }> } {
+ return {
+ ...({ [field]: { not: null } } as Record<T, { not: null }>),
+ NOT: { [field]: { contains: BLOB_HOST_SUFFIX } } as Record<
+ T,
+ { contains: string }
+ >,
+ };
+}
+
+function unchanged(row: Record<string, unknown>): Prisma.CompanyWhereInput {
+ return Object.fromEntries(
+ COMPANY_IMAGE_FIELDS.map((field) => [field, row[field] ?? null]),
+ );
+}
diff --git a/apps/api/src/companies/companies.contracts.ts b/apps/api/src/companies/companies.contracts.ts
index 10876b89..de7d8b45 100644
--- a/apps/api/src/companies/companies.contracts.ts
+++ b/apps/api/src/companies/companies.contracts.ts
@@ -1,33 +1,15 @@
import { z } from "zod";
import { listInput } from "../trpc/list-input";
-/**
- * The companies list adds three facets to the shared list input. Each defaults
- * to `"all"`, which is also what the URL parsers on the front end send when a
- * dropdown is untouched — so an unfiltered request and an unfiltered URL are
- * the same request.
- */
export const companyListInput = listInput.extend({
- /** A user id, `"unassigned"`, or `"all"`. */
owner: z.string().default("all"),
industry: z.string().default("all"),
- /** An `EnrichmentStatus`, or `"all"`. */
enrichment: z.string().default("all"),
- /**
- * A `RecordSource`, or `"all"`.
- *
- * What makes an auto-create rule reversible: filter to `EMAIL`, see exactly
- * what the sync decided, and delete the lot if it got it wrong.
- */
source: z.string().default("all"),
});
export type CompanyListInput = z.infer<typeof companyListInput>;
-/**
- * Creating a company asks for the three things a human actually knows. The
- * logo, description, industry, address and socials are the agent's job.
- */
export const companyCreateInput = z.object({
name: z.string().trim().min(1, "A company needs a name."),
domain: z.string().trim().optional(),
@@ -36,11 +18,6 @@ export const companyCreateInput = z.object({
export type CompanyCreateInput = z.infer<typeof companyCreateInput>;
-/**
- * Every field is optional and `undefined` means "leave it alone", so the inline
- * editors on the detail page can send one field at a time. An empty string
- * clears a value; `null` on `ownerId` unassigns.
- */
const companyUpdateInput = z.object({
name: z.string().trim().min(1).optional(),
domain: z.string().optional(),
@@ -70,7 +47,6 @@ export const setPrimaryContactInput = z.object({
contactId: z.string().nullable(),
});
-/** Free-text filter for the company picker; `""` means "the first hundred". */
export const companyOptionsInput = z.object({
q: z.string().default(""),
});
diff --git a/apps/api/src/companies/companies.router.ts b/apps/api/src/companies/companies.router.ts
index 1da3d274..6acd2d4d 100644
--- a/apps/api/src/companies/companies.router.ts
+++ b/apps/api/src/companies/companies.router.ts
@@ -37,7 +37,6 @@ export class CompaniesRouter {
return this.companies.byId(id);
}
- /** Company pickers and facet labels. */
@Query({ input: companyOptionsInput })
async options(@Input("q") q: string) {
return this.companies.options(q);
@@ -53,13 +52,11 @@ export class CompaniesRouter {
return this.companies.update(input.id, input.data);
}
- /** Re-runs the brand lookup, ignoring Context.dev's cache. */
@Mutation({ input: companyIdInput })
async enrich(@Input("id") id: string) {
return this.companies.enrich(id);
}
- /** Reads the company's site and posts a brief to its timeline. */
@Mutation({ input: companyIdInput })
async research(@Ctx() ctx: AuthedTrpcContext, @Input("id") id: string) {
return this.companies.research(id, ctx.user.id);
diff --git a/apps/api/src/companies/companies.service.ts b/apps/api/src/companies/companies.service.ts
index 9f4efef7..7705a2a3 100644
--- a/apps/api/src/companies/companies.service.ts
+++ b/apps/api/src/companies/companies.service.ts
@@ -41,7 +41,6 @@ const OWNER_SELECT = {
image: true,
} as const;
-/** One row of the companies table. */
export type CompanyRow = {
id: string;
name: string;
@@ -53,12 +52,6 @@ export type CompanyRow = {
brandColor: string | null;
industry: string | null;
enrichmentStatus: EnrichmentStatus;
- /**
- * Whether the agent actually has this company on its list.
- *
- * Separate from `enrichmentStatus` because that column defaults to PENDING
- * and so cannot tell "waiting its turn" from "nobody ever asked".
- */
queued: boolean;
source: RecordSource;
owner: {
@@ -69,18 +62,10 @@ export type CompanyRow = {
} | null;
contactCount: number;
openDealCount: number;
- /** ISO-8601, or null when nothing has happened yet. */
lastActivityAt: string | null;
createdAt: string;
};
-/**
- * Columns `?sort=` may name, and the Prisma ordering each one means.
- *
- * Spelled out rather than derived from the column id so `?sort=` can never
- * reach Prisma as an arbitrary field name — and because ordering by a relation
- * count is not a flat `{ [id]: dir }`.
- */
const SORTABLE: Record<
string,
(dir: Prisma.SortOrder) => Prisma.CompanyOrderByWithRelationInput
@@ -91,11 +76,7 @@ const SORTABLE: Record<
createdAt: (dir) => ({ createdAt: dir }),
contacts: (dir) => ({ contacts: { _count: dir } }),
deals: (dir) => ({ deals: { _count: dir } }),
- // By the owner's name, not their id — nobody scans a list of cuids.
- // Unassigned rows sort last either way: they are the least interesting.
owner: (dir) => ({ owner: { name: dir } }),
- // A real column, so this is an index scan. Never-touched rows sort last in
- // both directions, because "no activity" is not "the oldest activity".
lastActivity: (dir) => ({ lastActivityAt: { sort: dir, nulls: "last" } }),
};
@@ -149,8 +130,6 @@ export class CompaniesService {
this.facetCounts(input),
]);
- // After the page is known, so it is one query for the rows on screen
- // rather than a join that would have to be repeated for the facet counts.
const queued = await this.queue.queuedCompanies(rows.map((row) => row.id));
return {
@@ -230,6 +209,7 @@ export class CompaniesService {
lastName: true,
email: true,
title: true,
+ imageUrl: true,
owner: { select: OWNER_SELECT },
},
},
@@ -270,13 +250,6 @@ export class CompaniesService {
};
}
- /**
- * Companies for a picker or a facet label — id, name and enough to draw the
- * logo, nothing else.
- *
- * Capped at 100 and searchable, so the "which company?" dropdown on a contact
- * or a deal stays a dropdown rather than becoming a second list view.
- */
async options(q: string) {
return this.db.company.findMany({
where: this.searchFilter(q),
@@ -317,15 +290,8 @@ export class CompaniesService {
domain: company.domain,
});
- // Fire-and-forget: the create form should not wait on research, and the
- // detail page polls until it settles. All this says is that a company now
- // exists with nothing on it but a domain — what to do about that is the
- // agent's call.
await this.agent.companyCreated(company.id);
- // Not awaited, for the same reason: the icon is worth a second or two of
- // somebody else's origin being slow, and the form is not. The list polls
- // while the row is enriching, so it lands without a reload.
void this.favicon.backfill(company.id, company.domain);
return company;
@@ -365,8 +331,6 @@ export class CompaniesService {
);
}
data.domain = domain;
- // A new domain means the enrichment we have is for the wrong company.
- // Phase 6 picks PENDING rows up; until then this is honest bookkeeping.
const current = await this.db.company.findUnique({
where: { id },
select: { domain: true },
@@ -374,15 +338,6 @@ export class CompaniesService {
if (current && current.domain !== domain) {
data.enrichmentStatus = "PENDING";
data.enrichmentError = null;
- // The icon is one of the things that was about a different company,
- // and it is the one a rep can see. Cleared so the row shows a
- // placeholder until the new domain answers, rather than confidently
- // showing the old company's mark.
- //
- // All three variants, not just `iconUrl`: the agent's `brandToUpdate`
- // only fills fields that are null, so a stale `iconDarkUrl` would
- // survive re-enrichment and keep showing the previous company's mark
- // to anyone in dark mode.
data.iconUrl = null;
data.iconDarkUrl = null;
data.iconTone = null;
@@ -410,15 +365,6 @@ export class CompaniesService {
}
}
- /**
- * The "Look this up again" button.
- *
- * Queues the work at the front and returns immediately. It no longer forces
- * a vendor cache bypass, because the API no longer knows there is a vendor:
- * a rep asking for a fresh look is an event, and how to honour it — which
- * sources, how deep, whether the cached answer is still good — belongs to
- * the agent.
- */
async enrich(id: string): Promise<{ id: string; queued: boolean }> {
const company = await this.db.company.findUnique({
where: { id },
@@ -438,7 +384,6 @@ export class CompaniesService {
return { id, queued: true };
}
- /** Asks the agent for a written brief on the company's timeline. */
async research(id: string, actingUserId: string) {
const company = await this.db.company.findUnique({
where: { id },
@@ -463,12 +408,6 @@ export class CompaniesService {
return { ok: true as const, queued: true as const };
}
- /**
- * Points a company at the person to call.
- *
- * The contact has to already belong to the company: a "primary contact" who
- * works somewhere else is a data-entry accident, not a relationship.
- */
async setPrimaryContact(companyId: string, contactId: string | null) {
if (contactId) {
const contact = await this.db.contact.findUnique({
@@ -496,7 +435,6 @@ export class CompaniesService {
}
}
- /** `q` matches the name or the domain — the two things a rep would type. */
private searchFilter(q: string): Prisma.CompanyWhereInput {
const term = q.trim();
if (!term) return {};
@@ -530,13 +468,6 @@ export class CompaniesService {
return where;
}
- /**
- * Counts for the facet dropdowns.
- *
- * Computed against the search term only, not the other facets: counts that
- * shift every time you touch a different dropdown are hard to read, and
- * options that vanish are worse.
- */
private async facetCounts(input: CompanyListInput) {
const where = this.searchFilter(input.q);
@@ -571,7 +502,6 @@ export class CompaniesService {
};
}
- /** Prisma's constraint errors, said in a way a rep can act on. */
private translate(error: unknown, id: string): unknown {
if (error instanceof PrismaNamespace.PrismaClientKnownRequestError) {
if (error.code === "P2025") {
diff --git a/apps/api/src/companies/company-directory.service.ts b/apps/api/src/companies/company-directory.service.ts
index 6bf1974e..96f0b79e 100644
--- a/apps/api/src/companies/company-directory.service.ts
+++ b/apps/api/src/companies/company-directory.service.ts
@@ -4,21 +4,6 @@ import { AgentTriggerService } from "../agent/agent-trigger.service";
import { InjectDatabase } from "../database/database.constants";
import { domainFromEmail } from "./domain";
-/**
- * "Which company does this address belong to?" — the CRM half of a question
- * that used to be half enrichment.
- *
- * The old `EnrichmentService.companyForEmail` called Context.dev *inside the
- * request* so a new company could arrive already named "Stripe" rather than
- * "stripe.com". That was a nice touch bought at a bad price: a vendor lookup on
- * the path of every contact create and every sync tick, in the layer that is
- * not allowed to know vendors exist.
- *
- * So this does the part that is genuinely ours — find or create by domain — and
- * tells the agent a bare company now exists. The name is the domain for the few
- * seconds it takes the agent to replace it, and the sheet polls, which it
- * already did.
- */
@Injectable()
export class CompanyDirectoryService {
private readonly logger = new Logger(CompanyDirectoryService.name);
@@ -41,8 +26,6 @@ export class CompanyDirectoryService {
});
if (existing) return existing.id;
- // Two contacts at a new company can race here; the unique index on
- // `domain` is what actually settles it.
const company = await this.db.company.upsert({
where: { domain },
create: {
@@ -50,8 +33,6 @@ export class CompanyDirectoryService {
domain,
website: `https://${domain}`,
enrichmentStatus: EnrichmentStatus.PENDING,
- // An unowned company is nobody's job. Whoever's action produced it
- // owns it until someone reassigns.
ownerId: options.ownerId ?? null,
},
update: {},
diff --git a/apps/api/src/companies/domain.ts b/apps/api/src/companies/domain.ts
index 2010c545..0d8a04af 100644
--- a/apps/api/src/companies/domain.ts
+++ b/apps/api/src/companies/domain.ts
@@ -1,21 +1,9 @@
-/**
- * Reduces whatever a human typed to the bare host: "https://www.Stripe.com/pricing"
- * → "stripe.com".
- *
- * `Company.domain` is unique and is the enrichment key, so the same company
- * typed three ways has to collapse to one value — otherwise the constraint
- * never fires and we pay Context.dev twice for the same lookup.
- *
- * Returns `null` for anything that is not plausibly a hostname, so a typo
- * clears the field rather than creating a junk record that blocks the real one.
- */
export function normalizeDomain(
input: string | null | undefined,
): string | null {
const trimmed = input?.trim().toLowerCase();
if (!trimmed) return null;
- // `new URL` needs a scheme, and bare "stripe.com" is the common case.
const withScheme = /^[a-z][a-z0-9+.-]*:\/\//.test(trimmed)
? trimmed
: `https://${trimmed}`;
@@ -29,12 +17,9 @@ export function normalizeDomain(
const bare = host.replace(/^www\./, "");
- // At least one dot, and nothing but host characters — enough to reject
- // "localhost", "my company" and a pasted email address.
return /^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(bare) ? bare : null;
}
-/** The domain part of a work email, or `null` for a free or malformed address. */
export function domainFromEmail(
email: string | null | undefined,
): string | null {
@@ -44,10 +29,6 @@ export function domainFromEmail(
return domain && !FREE_EMAIL_DOMAINS.has(domain) ? domain : null;
}
-/**
- * Addresses that say nothing about where someone works. Creating a "Gmail"
- * company because a lead used a personal address is the classic CRM junk row.
- */
const FREE_EMAIL_DOMAINS = new Set([
"gmail.com",
"googlemail.com",
diff --git a/apps/api/src/companies/favicon.service.ts b/apps/api/src/companies/favicon.service.ts
index a373fdb5..47f3c58e 100644
--- a/apps/api/src/companies/favicon.service.ts
+++ b/apps/api/src/companies/favicon.service.ts
@@ -1,46 +1,23 @@
import type { Db } from "@crm/db";
+import { mirror } from "@crm/db/blob";
import { resolveFavicon } from "@crm/db/favicon";
import { Injectable, Logger } from "@nestjs/common";
import { InjectDatabase } from "../database/database.constants";
-/**
- * Stores the domain's own favicon as a stand-in icon.
- *
- * The resolving is in `@crm/db/favicon`, shared with the seed. This is only the
- * write, and the write is the part with a rule in it: the agent's Context.dev
- * icon is the curated one and always wins, so ours is never allowed to replace
- * it, and the agent is free to replace ours (see `brandToUpdate`).
- *
- * Sitting in the API at all is a deliberate exception to `docs/api.md`: there
- * is nothing here to decide. No vendor, no key, no matching, no scoring — so
- * there is no second judgement that can drift from the agent's, which is the
- * failure that rule exists to prevent.
- */
@Injectable()
export class FaviconService {
private readonly logger = new Logger(FaviconService.name);
constructor(@InjectDatabase() private readonly db: Db) {}
- /**
- * Resolve and store, without ever throwing at the caller.
- *
- * Callers fire this and move on, so a rejected promise here would be an
- * unhandled one. A company with no icon is the state we are already in.
- */
async backfill(companyId: string, domain: string | null): Promise<boolean> {
try {
- const iconUrl = await resolveFavicon(domain);
- if (!iconUrl) return false;
+ const resolved = await resolveFavicon(domain);
+ if (!resolved) return false;
+
+ const iconUrl =
+ (await mirror(resolved, `companies/${companyId}/icon`)) ?? resolved;
- // Filtered on the domain as well as `iconUrl`. The lookup is slow and
- // nothing awaits it, so two quick domain edits leave two in flight: the
- // older one can return last and stamp the previous company's icon onto
- // the new domain. Matching the domain we actually resolved makes a
- // late arrival a no-op instead.
- //
- // `iconUrl: null` for the other race — an icon the agent found while we
- // were fetching is never overwritten by ours.
const { count } = await this.db.company.updateMany({
where: { id: companyId, iconUrl: null, domain },
data: { iconUrl },
diff --git a/apps/api/src/config/env.validation.ts b/apps/api/src/config/env.validation.ts
index f8ecae6b..4ff62b56 100644
--- a/apps/api/src/config/env.validation.ts
+++ b/apps/api/src/config/env.validation.ts
@@ -11,19 +11,6 @@ import {
validateSync,
} from "class-validator";
-/**
- * Every variable the API reads, and nothing else.
- *
- * Five of these are required and the rest have working defaults, which is the
- * whole configuration surface of this repo. The list is short on purpose: a
- * variable that exists but is never read is a question a self-hoster has to
- * answer for no reason, and one that is read but not declared here fails at
- * three in the morning instead of at boot.
- *
- * Values are read from the environment, or from the repo-root `.env` that
- * `@crm/env` loads. See `.env.example`.
- */
-
export enum NodeEnv {
Development = "development",
Production = "production",
@@ -40,8 +27,6 @@ export class EnvironmentVariables {
@Max(65535)
PORT = 3001;
- // --- required -----------------------------------------------------------
-
@IsString()
@MinLength(1, {
message:
@@ -56,12 +41,6 @@ export class EnvironmentVariables {
})
BETTER_AUTH_SECRET!: string;
- /**
- * Who may sign in — a comma-separated list of email domains and addresses.
- *
- * This is the entire authorisation model, so it is required rather than
- * defaulted. See `@crm/auth`'s `workspace.ts`.
- */
@IsString()
@MinLength(1, {
message:
@@ -69,11 +48,6 @@ export class EnvironmentVariables {
})
ALLOWED_SIGN_IN!: string;
- /**
- * Google is the only sign-in method, so unlike `@crm/auth` — which stays
- * loadable without credentials for `better-auth generate` — the process that
- * serves the auth routes refuses to start without them.
- */
@IsString()
@MinLength(1, {
message:
@@ -85,30 +59,18 @@ export class EnvironmentVariables {
@MinLength(1, { message: "GOOGLE_CLIENT_SECRET is required." })
GOOGLE_CLIENT_SECRET!: string;
- // --- defaulted ----------------------------------------------------------
-
- /** Where this API is reachable. Only needs setting off localhost. */
@IsOptional()
@IsUrl({ require_tld: false })
API_URL?: string;
- /**
- * Where the browser is. Allowed to call the API with credentials, and the
- * allow-list Better Auth validates post-sign-in `callbackURL`s against.
- * Comma-separated if there is genuinely more than one.
- */
@IsOptional()
@IsString()
APP_URL?: string;
- // --- optional -----------------------------------------------------------
-
- /** Parent domain for session cookies when the API and app differ, e.g. ".example.com". */
@IsOptional()
@IsString()
AUTH_COOKIE_DOMAIN?: string;
- /** Without it the cache is per-instance and in-memory, which is fine. */
@IsOptional()
@IsString()
REDIS_URL?: string;
@@ -119,19 +81,16 @@ export class EnvironmentVariables {
@Min(0)
CACHE_TTL_MS?: number;
- /**
- * Bearer guard on `POST /internal/sync/google`.
- *
- * Not a feature flag — Gmail and Calendar sync is simply on, because mailbox
- * access is a condition of signing in. This is the one thing the cron route
- * genuinely needs, and the route fails closed without it.
- */
@IsOptional()
@IsString()
@MinLength(16, {
message: "CRON_SECRET must be at least 16 characters.",
})
CRON_SECRET?: string;
+
+ @IsOptional()
+ @IsString()
+ BLOB_READ_WRITE_TOKEN?: string;
}
export function validateEnv(
diff --git a/apps/api/src/contacts/contacts.contracts.ts b/apps/api/src/contacts/contacts.contracts.ts
index 7063ebdb..6230debf 100644
--- a/apps/api/src/contacts/contacts.contracts.ts
+++ b/apps/api/src/contacts/contacts.contracts.ts
@@ -2,21 +2,13 @@ import { z } from "zod";
import { listInput } from "../trpc/list-input";
export const contactListInput = listInput.extend({
- /** A user id, `"unassigned"`, or `"all"`. */
owner: z.string().default("all"),
- /** A company id, `"none"`, or `"all"`. */
company: z.string().default("all"),
- /** A `RecordSource`, or `"all"` — how a bad auto-create rule gets undone. */
source: z.string().default("all"),
});
export type ContactListInput = z.infer<typeof contactListInput>;
-/**
- * `email` is unique across the whole table, matching HubSpot, so an import can
- * be re-run without duplicating people. It is optional because a name and a
- * phone number is a real lead.
- */
export const contactCreateInput = z.object({
firstName: z.string().trim().min(1, "A contact needs a first name."),
lastName: z.string().trim().optional(),
@@ -29,7 +21,6 @@ export const contactCreateInput = z.object({
export type ContactCreateInput = z.infer<typeof contactCreateInput>;
-/** `undefined` leaves a field alone; `""` clears it. */
const contactUpdateInput = z.object({
firstName: z.string().trim().min(1).optional(),
lastName: z.string().optional(),
@@ -39,8 +30,6 @@ const contactUpdateInput = z.object({
linkedinUrl: z.string().optional(),
twitterUrl: z.string().optional(),
githubUrl: z.string().optional(),
- // `summary` is deliberately absent: the research agent owns it, and a field
- // a rep can retype is a field that gets overwritten on the next run.
companyId: z.string().nullable().optional(),
ownerId: z.string().nullable().optional(),
});
@@ -54,15 +43,6 @@ export const contactUpdateArgs = z.object({
export const contactIdInput = z.object({ id: z.string() });
-/**
- * A rep settling a proposal the agent could not settle itself.
- *
- * This is the one place the API touches enrichment output, and it is not
- * enrichment: no research, no scoring, no judgement about a person — a human
- * pressed accept, and the record follows. The decision is also the label that
- * calibrates the confidence model, which is why `decidedById` is stored rather
- * than the row simply being deleted.
- */
export const factDecisionInput = z.object({
factId: z.string(),
decision: z.enum(["accept", "dismiss"]),
diff --git a/apps/api/src/contacts/contacts.router.ts b/apps/api/src/contacts/contacts.router.ts
index b3f6f5ba..d47e1a02 100644
--- a/apps/api/src/contacts/contacts.router.ts
+++ b/apps/api/src/contacts/contacts.router.ts
@@ -46,7 +46,11 @@ export class ContactsRouter {
return this.contacts.update(input.id, input.data);
}
- /** A rep accepting or dismissing something the agent suggested. */
+ @Mutation({ input: contactIdInput })
+ async enrich(@Input("id") id: string) {
+ return this.contacts.enrich(id);
+ }
+
@Mutation({ input: factDecisionInput })
async decideFact(
@Ctx() ctx: AuthedTrpcContext,
diff --git a/apps/api/src/contacts/contacts.service.ts b/apps/api/src/contacts/contacts.service.ts
index 3ae2eaca..5fc7e8e3 100644
--- a/apps/api/src/contacts/contacts.service.ts
+++ b/apps/api/src/contacts/contacts.service.ts
@@ -51,17 +51,8 @@ const COMPANY_SELECT = {
logoUrl: true,
} as const;
-/** The facet value for a contact who works nowhere we know of. */
const NO_COMPANY = "none";
-/**
- * Which `Contact` column an accepted fact writes through to.
- *
- * The agent's `facts.ts` holds the same map, because it is the one deciding
- * what a field means; this half only needs to know where an accepted value
- * lands. Fields absent from here (`seniority`, `employer`, `location`) have no
- * column — they are read straight off the fact by the background panel.
- */
const FACT_COLUMNS: Record<string, string | undefined> = {
title: "title",
linkedinUrl: "linkedinUrl",
@@ -75,7 +66,6 @@ export type ContactRow = {
lastName: string | null;
email: string | null;
title: string | null;
- /** Our mirrored copy, never LinkedIn's expiring CDN URL. */
imageUrl: string | null;
company: {
id: string;
@@ -96,17 +86,10 @@ export type ContactRow = {
createdAt: string;
};
-/**
- * Orderings are arrays so every column can carry a tiebreak: without one,
- * everybody at the same company comes back in whatever order Postgres feels
- * like, and the order changes between pages of the same query.
- */
const SORTABLE: Record<
string,
(dir: Prisma.SortOrder) => Prisma.ContactOrderByWithRelationInput[]
> = {
- // Surname first — a list of people sorted by first name is a list nobody can
- // scan.
name: (dir) => [{ lastName: dir }, { firstName: dir }],
email: (dir) => [{ email: dir }],
title: (dir) => [{ title: dir }, { lastName: "asc" }],
@@ -192,10 +175,6 @@ export class ContactsService {
refreshedAt: true,
},
},
- // Applied facts are the provenance behind values already on the
- // record; proposed ones are suggestions the sheet offers. Dismissed
- // and superseded stay out of the read path — they are history, and
- // the timeline is where history belongs.
facts: {
where: { status: { in: [FactStatus.APPLIED, FactStatus.PROPOSED] } },
orderBy: { observedAt: "desc" },
@@ -249,7 +228,6 @@ export class ContactsService {
return {
...rest,
company,
- /** Whether the agent has this person on its list — see `AgentQueueService`. */
queued: await this.queue.isQueued({ contactId: id }),
createdAt: createdAt.toISOString(),
brief: brief
@@ -264,9 +242,7 @@ export class ContactsService {
evidence: fact.evidence as FactEvidence[],
observedAt: fact.observedAt.toISOString(),
})),
- /** What we have actually said to each other. */
relationship,
- /** True when this is the person to call at their company. */
isPrimaryContact: company?.primaryContactId === contact.id,
deals: deals.map(({ role, deal }) => ({
...deal,
@@ -293,15 +269,10 @@ export class ContactsService {
}
}
- // A work address tells us where someone works. Awaited rather than queued,
- // unlike company enrichment: the contact should arrive already attached to
- // the right company, not attach itself a few seconds later.
const companyId =
input.companyId ??
(email
? await this.companies.companyForEmail(email, {
- // Same rule as the sync: a company conjured out of somebody's
- // action belongs to them, not to nobody.
ownerId: input.ownerId,
})
: null);
@@ -321,10 +292,6 @@ export class ContactsService {
this.logger.log({ message: "Contact created", contactId: contact.id });
- // A person typed this one, so there is no placeholder name to fix — but
- // there is usually no title, no profile and no background either, and a
- // rep who has just added somebody is the likeliest person to open them
- // again in the next minute.
await this.agent.contactCreated(
contact.id,
"Added by a rep, with nothing on the record yet",
@@ -373,18 +340,6 @@ export class ContactsService {
}
}
- /**
- * What we already know from our own mailbox and calendar.
- *
- * The one block on this sheet no CRM that buys its data can render: how many
- * emails, whether they have ever actually replied, when we last heard from
- * them, what is in the diary, and who else we know at the same company.
- *
- * Counts and dates only — the bodies stay out of the API. The agent reads
- * those (they are the best evidence we have) but the browser has no use for
- * them here, and shipping a thread into a record payload is how message
- * content ends up somewhere nobody expected.
- */
private async relationship(contactId: string, companyId: string | null) {
const now = new Date();
@@ -431,9 +386,6 @@ export class ContactsService {
return {
emails: threads._sum.messageCount ?? 0,
threads: threads._count._all,
- // The distinction that matters on a sheet: we have emailed them 12
- // times and they have never once written back is a different
- // relationship from 12 emails with 6 replies.
lastReplyAt: lastReply?.sentAt.toISOString() ?? null,
meetings,
nextMeeting: nextMeeting
@@ -452,15 +404,31 @@ export class ContactsService {
};
}
- /**
- * A rep accepting or dismissing something the agent proposed.
- *
- * Accepting writes the value through to the record and supersedes whatever
- * was there; dismissing keeps the row so the agent can be told never to
- * offer it again. Neither branch researches anything — this is a human
- * decision being executed, which is the only enrichment-shaped thing that
- * belongs on this side of the wire.
- */
+ async enrich(id: string): Promise<{ id: string; queued: true }> {
+ const contact = await this.db.contact.findUnique({
+ where: { id },
+ select: { id: true, imageUrl: true, linkedinUrl: true },
+ });
+
+ if (!contact) {
+ throw new NotFoundException(`No contact with id ${id}.`);
+ }
+
+ await this.db.contact.update({
+ where: { id },
+ data: { enrichmentStatus: "PENDING", enrichmentError: null },
+ });
+
+ await this.agent.contactCreated(
+ id,
+ contact.linkedinUrl && !contact.imageUrl
+ ? "A rep asked for a fresh look — they have a LinkedIn profile on file but no picture"
+ : "A rep asked for a fresh look",
+ );
+
+ return { id, queued: true };
+ }
+
async decideFact(
input: FactDecisionInput,
userId: string,
@@ -540,7 +508,6 @@ export class ContactsService {
return { contactId: fact.contactId, field: fact.field, applied: accepted };
}
- /** `q` matches a name, an email address, or where they work. */
private searchFilter(q: string): Prisma.ContactWhereInput {
const term = q.trim();
if (!term) return {};
@@ -572,7 +539,6 @@ export class ContactsService {
return where;
}
- /** Counts against the search term only — see `CompaniesService.facetCounts`. */
private async facetCounts(input: ContactListInput) {
const where = this.searchFilter(input.q);
diff --git a/apps/api/src/conversations/conversations.contracts.ts b/apps/api/src/conversations/conversations.contracts.ts
index 3a04a13d..5b99ae34 100644
--- a/apps/api/src/conversations/conversations.contracts.ts
+++ b/apps/api/src/conversations/conversations.contracts.ts
@@ -1,6 +1,5 @@
import { z } from "zod";
-/** Which record's conversations. One of the two, checked in the service. */
export const conversationListInput = z.object({
contactId: z.string().optional(),
companyId: z.string().optional(),
@@ -9,12 +8,6 @@ export const conversationListInput = z.object({
export type ConversationListInput = z.infer<typeof conversationListInput>;
-/**
- * Where a conversation got to.
- *
- * The cursor is `useEveAgent`'s own `session` object, handed back so a reopened
- * panel resumes the thread instead of starting a new one.
- */
export const conversationSaveInput = z.object({
contactId: z.string().optional(),
companyId: z.string().optional(),
@@ -22,7 +15,6 @@ export const conversationSaveInput = z.object({
sessionId: z.string(),
continuationToken: z.string().nullish(),
streamIndex: z.number().int().min(0).optional(),
- /** The opening question. Only used the first time. */
title: z.string().optional(),
messageCount: z.number().int().min(0).optional(),
});
@@ -31,10 +23,8 @@ export type ConversationSaveInput = z.infer<typeof conversationSaveInput>;
export const conversationIdInput = z.object({ id: z.string() });
-/** The stored transcript of one conversation, for rehydrating the panel. */
export const conversationEventsInput = z.object({
id: z.string(),
- /** An ordered *prefix*, so a very long thread stays a bounded payload. */
limit: z.number().int().min(1).max(5000).default(2000),
});
diff --git a/apps/api/src/conversations/conversations.router.ts b/apps/api/src/conversations/conversations.router.ts
index 8b02f246..ac66ba8b 100644
--- a/apps/api/src/conversations/conversations.router.ts
+++ b/apps/api/src/conversations/conversations.router.ts
@@ -18,13 +18,6 @@ import {
} from "./conversations.contracts";
import { ConversationsService } from "./conversations.service";
-/**
- * A record's history with the agent.
- *
- * Every procedure is scoped to the signed-in user by the service, not by the
- * caller: a conversation id in a request body decides *which* row, never
- * *whose*.
- */
@Router({ alias: "conversations" })
@UseMiddlewares(AuthMiddleware)
export class ConversationsRouter {
@@ -41,7 +34,6 @@ export class ConversationsRouter {
return this.conversations.list(input, ctx.user.id);
}
- /** The stored transcript, for rehydrating a reopened thread. */
@Query({ input: conversationEventsInput })
async events(
@Ctx() ctx: AuthedTrpcContext,
diff --git a/apps/api/src/conversations/conversations.service.ts b/apps/api/src/conversations/conversations.service.ts
index 1443a752..c28b7786 100644
--- a/apps/api/src/conversations/conversations.service.ts
+++ b/apps/api/src/conversations/conversations.service.ts
@@ -15,24 +15,6 @@ import type {
ConversationSaveInput,
} from "./conversations.contracts";
-/**
- * A record's conversations with the agent.
- *
- * The transcript itself lives in `AgentEvent`, written by the agent's audit
- * hook. This is the handle: which durable eve session belongs to which record,
- * and enough to list them without touching an event.
- *
- * **This is not the API doing intelligence** (`api.md`). Nothing here
- * researches, scores or decides anything — it is a list of a record's history,
- * which is exactly the sort of thing the data surface is for. The agent still
- * owns every judgement; this owns the filing.
- *
- * Cached deliberately, per value, the way `AuthService.getProfile` is: read
- * through, write on miss, explicit invalidation when something changes. The
- * list is read on every open of a contact sheet and changes only when somebody
- * sends a message, which is the shape a cache is actually for.
- */
-
export interface ConversationSummary {
id: string;
sessionId: string;
@@ -40,17 +22,9 @@ export interface ConversationSummary {
streamIndex: number;
title: string | null;
messageCount: number;
- /** ISO-8601: a `Date` comes back from Redis as a string anyway. */
lastMessageAt: string;
}
-/**
- * Long, because every write invalidates.
- *
- * A TTL is the backstop for a missed invalidation, not the freshness
- * mechanism — five minutes of staleness on a list nobody changed is not worth
- * the round trips.
- */
const LIST_TTL_MS = 10 * 60_000;
const listKey = (userId: string, recordId: string) =>
@@ -65,13 +39,6 @@ export class ConversationsService {
@Inject(CACHE_MANAGER) private readonly cache: Cache,
) {}
- /**
- * Every conversation this rep has had about this record, newest first.
- *
- * Scoped to the caller. Two reps asking about the same contact are having
- * two different conversations, and half of one appearing in the other's
- * panel would be both confusing and a small privacy surprise.
- */
async list(
input: ConversationListInput,
userId: string,
@@ -114,14 +81,6 @@ export class ConversationsService {
return summaries;
}
- /**
- * Records where a conversation got to.
- *
- * Upserted on the session id, because the client calls this every time the
- * cursor moves and the first call is the one that creates the row. `title`
- * is written once — it is the opening question, and a thread renaming itself
- * as it goes is a thread nobody can find again.
- */
async save(
input: ConversationSaveInput,
userId: string,
@@ -150,8 +109,6 @@ export class ConversationsService {
select: { id: true, userId: true },
});
- // A session belongs to whoever started it. Nothing in the UI can produce
- // this, but a session id is guessable-ish and the check is one comparison.
if (conversation.userId !== userId) {
throw new BadRequestException(
"That conversation belongs to someone else.",
@@ -163,17 +120,6 @@ export class ConversationsService {
return { id: conversation.id };
}
- /**
- * The transcript of one conversation, in the shape the panel's reducer eats.
- *
- * Why this exists rather than replaying eve's own stream: these events are
- * already ours. The audit hook wrote them as they happened, they outlive
- * eve's 30-day session retention, and reading them costs the agent nothing —
- * a rep scrolling last month's thread should not wake the research runtime.
- *
- * An ordered prefix, oldest first, because that is what rehydrating a
- * projection means: the reducer replays it in order to rebuild the messages.
- */
async events(input: ConversationEventsInput, userId: string) {
const conversation = await this.db.agentConversation.findUnique({
where: { id: input.id },
@@ -194,12 +140,10 @@ export class ConversationsService {
return events.map((event) => ({
type: event.type,
data: event.data,
- // The envelope the client dedupes and orders on.
meta: { id: event.id, at: event.emittedAt.toISOString() },
}));
}
- /** Forgets a conversation, and the events behind it. */
async remove(id: string, userId: string): Promise<{ id: string }> {
const conversation = await this.db.agentConversation.findUnique({
where: { id },
@@ -239,7 +183,6 @@ export class ConversationsService {
return { id };
}
- /** One record per conversation, and it has to be said which. */
private recordId(input: {
contactId?: string;
companyId?: string;
diff --git a/apps/api/src/create-app.ts b/apps/api/src/create-app.ts
index c960a645..98cee688 100644
--- a/apps/api/src/create-app.ts
+++ b/apps/api/src/create-app.ts
@@ -8,14 +8,6 @@ import helmet from "helmet";
import { AppModule } from "./app.module";
import { ContextLogger } from "./logging/context-logger";
-/**
- * Builds the application without starting a listener.
- *
- * `main.ts` calls this and then listens; the serverless handler in `api/`
- * calls it and hands the Express instance each request instead. Everything
- * that shapes the app — pipes, helmet, the logger — lives here so the two
- * entrypoints cannot drift apart.
- */
export async function createApp(): Promise<NestExpressApplication> {
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
diff --git a/apps/api/src/crm/activity-stamp.service.ts b/apps/api/src/crm/activity-stamp.service.ts
index ca0e86a6..83f0ee1f 100644
--- a/apps/api/src/crm/activity-stamp.service.ts
+++ b/apps/api/src/crm/activity-stamp.service.ts
@@ -2,44 +2,16 @@ import type { Db } from "@crm/db";
import { Injectable } from "@nestjs/common";
import { InjectDatabase } from "../database/database.constants";
-/** The records one activity can belong to. All three are stamped. */
export type ActivityTarget = {
companyId?: string | null;
contactId?: string | null;
dealId?: string | null;
};
-/**
- * Keeps `lastActivityAt` current on companies, contacts and deals.
- *
- * The column is denormalised because it is a **sortable** column on every list,
- * and ordering by `max(activity.createdAt)` is an aggregate over a relation that
- * Prisma cannot express — the alternative is a correlated subquery per row,
- * which would be the slowest thing on the page.
- *
- * Denormalised means it can drift, so every activity write goes through here
- * rather than each caller remembering to update three tables. There are five
- * places that write activities (the composer, stage changes, the research
- * agent, and both Google syncs); the fan-out belongs to the shape of the data,
- * not to whichever feature happened to trigger it. **A new activity writer adds
- * a `touch()` call here, not its own update.**
- *
- * Stamped with the activity's `createdAt`, not `occurredAt`: a meeting booked
- * for next month must not make a company look like it was active in the future.
- * That also matches the lateral join this replaced.
- */
@Injectable()
export class ActivityStampService {
constructor(@InjectDatabase() private readonly db: Db) {}
- /**
- * Raises `lastActivityAt` to `at` wherever it is currently older or unset.
- *
- * A conditional update rather than a read-then-write: two syncs stamping the
- * same company concurrently would otherwise race, and the older one could
- * win. Guarding in the `where` makes the operation idempotent and
- * order-independent, so replaying a window cannot move the value backwards.
- */
async touch(target: ActivityTarget, at: Date): Promise<void> {
const stale = {
OR: [{ lastActivityAt: null }, { lastActivityAt: { lt: at } }],
@@ -67,13 +39,6 @@ export class ActivityStampService {
]);
}
- /**
- * Recomputes from the activity table.
- *
- * For deletes, where the value can only go *down* and `touch` — which never
- * lowers it — cannot help. Purging a mailbox is the case that needs it:
- * without this a company keeps claiming activity whose rows are gone.
- */
async recompute(target: ActivityTarget): Promise<void> {
if (target.companyId) {
const { _max } = await this.db.activity.aggregate({
@@ -109,13 +74,6 @@ export class ActivityStampService {
}
}
- /**
- * Rebuilds every row's stamp in three statements.
- *
- * For bulk deletes, where naming the affected records would mean collecting
- * ids across cascades. Set-based, so it stays a few hundred milliseconds on a
- * table this size rather than one query per record.
- */
async recomputeAll(): Promise<void> {
await this.db.$transaction([
this.db.$executeRaw`
diff --git a/apps/api/src/crm/crm.module.ts b/apps/api/src/crm/crm.module.ts
index 70494d54..ecca4361 100644
--- a/apps/api/src/crm/crm.module.ts
+++ b/apps/api/src/crm/crm.module.ts
@@ -2,14 +2,6 @@ import { Global, Module } from "@nestjs/common";
import { ActivityStampService } from "./activity-stamp.service";
import { EnrichmentLogService } from "./enrichment-log.service";
-/**
- * Cross-cutting CRM concerns.
- *
- * `@Global()` for the same reason `DatabaseModule` is: every module that writes
- * an activity needs the stamp, and threading it through four `imports` arrays
- * would make the dependency graph say something about layering that is not
- * true — the composer, deals, enrichment and both Google syncs are peers.
- */
@Global()
@Module({
providers: [ActivityStampService, EnrichmentLogService],
diff --git a/apps/api/src/crm/enrichment-log.service.ts b/apps/api/src/crm/enrichment-log.service.ts
index 35981f17..73f33569 100644
--- a/apps/api/src/crm/enrichment-log.service.ts
+++ b/apps/api/src/crm/enrichment-log.service.ts
@@ -8,23 +8,9 @@ export type EnrichmentEvent = {
contactId?: string | null;
subject: string;
body?: string | null;
- /** Where the facts came from, and what changed. Rendered on the entry. */
meta?: Record<string, unknown>;
};
-/**
- * Writes an `ENRICHMENT` activity when something is created or filled in
- * automatically.
- *
- * Without this the agents are invisible: a company appears with a logo and an
- * industry nobody typed, a contact renames itself overnight, and the only way
- * to find out when or why is to read the server logs. A record that changes on
- * its own has to say so on its own timeline — that is the difference between an
- * assistant and a haunted database.
- *
- * Deliberately the same `ENRICHMENT` type the research brief already uses, so
- * one filter shows everything the machines did.
- */
@Injectable()
export class EnrichmentLogService {
constructor(
@@ -32,13 +18,6 @@ export class EnrichmentLogService {
private readonly stamp: ActivityStampService,
) {}
- /**
- * Records one event, attributed to a system author.
- *
- * `Activity.createdById` is required, so an automatic write borrows the
- * record's owner and falls back to any user. `meta.automated` marks it, and
- * the timeline renders that as "via …" rather than as something a person did.
- */
async record(event: EnrichmentEvent): Promise<string | null> {
const author = await this.authorFor(event);
if (!author) return null;
@@ -65,7 +44,6 @@ export class EnrichmentLogService {
return activity.id;
}
- /** The owner of whatever this is about, or any user. */
private async authorFor(event: EnrichmentEvent): Promise<string | null> {
if (event.contactId) {
const contact = await this.db.contact.findUnique({
@@ -88,7 +66,6 @@ export class EnrichmentLogService {
}
}
-/** "logo, industry, description" — what a lookup actually filled in. */
export function describeFilled(fields: readonly string[]): string | null {
if (fields.length === 0) return null;
if (fields.length === 1) return `Filled in ${fields[0]}.`;
diff --git a/apps/api/src/crm/values.ts b/apps/api/src/crm/values.ts
index 3a999660..94393bd2 100644
--- a/apps/api/src/crm/values.ts
+++ b/apps/api/src/crm/values.ts
@@ -1,29 +1,13 @@
import type { Prisma } from "@crm/db";
-/**
- * Money crosses the wire as integer cents.
- *
- * Prisma's `Decimal` has no JSON representation, and a float would make summing
- * a pipeline lossy. Cents are exact integers well inside
- * `Number.MAX_SAFE_INTEGER` for anything `Decimal(14, 2)` can hold, and
- * `formatMoney` in `@crm/ui` already takes them.
- */
export function toCents(amount: Prisma.Decimal | null): number | null {
return amount === null ? null : amount.times(100).toNumber();
}
-/** Cents back to the column's scale, for a write. */
export function fromCents(cents: number | null | undefined): number | null {
return cents === null || cents === undefined ? null : cents / 100;
}
-/**
- * `""` means "clear this", `" x "` means `"x"`.
- *
- * Inline editors send whatever is in the box, and storing an empty string would
- * make "no phone number" and "a phone number that is blank" two different
- * states that render identically.
- */
export function blankToNull(value: string): string | null {
const trimmed = value.trim();
return trimmed === "" ? null : trimmed;
diff --git a/apps/api/src/dashboard/dashboard.contracts.ts b/apps/api/src/dashboard/dashboard.contracts.ts
index 08706002..3cc8ac4a 100644
--- a/apps/api/src/dashboard/dashboard.contracts.ts
+++ b/apps/api/src/dashboard/dashboard.contracts.ts
@@ -1,12 +1,5 @@
import { z } from "zod";
-/**
- * Whose numbers the overview shows.
- *
- * `"me"` is the default because the page answers "how am I doing" first — a rep
- * opening the app wants their own quarter, not the team's. `"everyone"` is the
- * same page over every owner, which is what a founder or a manager wants.
- */
const DASHBOARD_SCOPES = ["me", "everyone"] as const;
export const dashboardSummaryInput = z.object({
diff --git a/apps/api/src/dashboard/dashboard.router.ts b/apps/api/src/dashboard/dashboard.router.ts
index fb3648aa..ae7aa3fa 100644
--- a/apps/api/src/dashboard/dashboard.router.ts
+++ b/apps/api/src/dashboard/dashboard.router.ts
@@ -13,11 +13,6 @@ export class DashboardRouter {
@Inject(DashboardService) private readonly dashboard: DashboardService,
) {}
- /**
- * Everything on the overview: closed-won and the rolling rates behind it, the
- * open pipeline by stage, six months of won against created, what is due to
- * close, the biggest open deals, overdue tasks and recent activity.
- */
@Query({ input: dashboardSummaryInput })
async summary(
@Ctx() ctx: AuthedTrpcContext,
diff --git a/apps/api/src/dashboard/dashboard.service.ts b/apps/api/src/dashboard/dashboard.service.ts
index a94d478a..d2e56369 100644
--- a/apps/api/src/dashboard/dashboard.service.ts
+++ b/apps/api/src/dashboard/dashboard.service.ts
@@ -12,28 +12,18 @@ const OWNER_SELECT = {
image: true,
} as const;
-/** Months in the trend chart, the current one included. */
const TREND_MONTHS = 6;
-/**
- * Window behind the rolling rates — win rate, average deal size, cycle time.
- *
- * A quarter is long enough that one good week does not swing it and short
- * enough that it still describes how the rep is selling now.
- */
const RATE_WINDOW_DAYS = 90;
const DAY_MS = 24 * 60 * 60 * 1000;
-/** "Feb". The chart has room for three letters, not "February". */
const MONTH_LABEL = new Intl.DateTimeFormat("en-US", { month: "short" });
-/** Local month boundary, `offset` months from the one `from` falls in. */
function monthStart(from: Date, offset: number): Date {
return new Date(from.getFullYear(), from.getMonth() + offset, 1);
}
-/** Months since year zero — subtract two to get a bucket index. */
function monthKey(date: Date): number {
return date.getFullYear() * 12 + date.getMonth();
}
@@ -42,18 +32,6 @@ function monthKey(date: Date): number {
export class DashboardService {
constructor(@InjectDatabase() private readonly db: Db) {}
- /**
- * How the rep is doing: what they have closed, what is still open, the rates
- * that describe how they sell, and what needs attention today.
- *
- * The open pipeline spans all history, so it is aggregated in Postgres — the
- * alternative is a page that gets slower every quarter. Everything derived
- * from closed and newly created deals comes off one bounded read of the last
- * six months and is folded up here: that window does not grow with history,
- * it is a single index scan instead of a dozen aggregates, and it keeps the
- * KPI strip and the chart underneath it on exactly the same month boundaries
- * rather than letting SQL's idea of a month drift from JavaScript's.
- */
async summary(actingUserId: string, input: DashboardSummaryInput) {
const mine = input.scope === "me";
const owned = mine ? { ownerId: actingUserId } : {};
@@ -79,9 +57,6 @@ export class DashboardService {
_count: { _all: true },
_sum: { amount: true },
}),
- // One read covers the trend chart, this month vs. last, and the
- // 90-day rates. `amount` is the only wide column and there are four
- // of them, so this stays cheap even for a busy team.
this.db.deal.findMany({
where: {
...owned,
@@ -97,8 +72,6 @@ export class DashboardService {
closedAt: true,
},
}),
- // A count and a sum, not rows: the KPI strip quotes "due this month"
- // as one figure, and no list on the page shows the deals behind it.
this.db.deal.aggregate({
where: {
...owned,
@@ -123,12 +96,18 @@ export class DashboardService {
currency: true,
expectedCloseDate: true,
stageChangedAt: true,
- company: { select: { id: true, name: true, iconUrl: true } },
+ company: {
+ select: {
+ id: true,
+ name: true,
+ iconUrl: true,
+ iconDarkUrl: true,
+ iconTone: true,
+ },
+ },
owner: { select: OWNER_SELECT },
},
}),
- // Always the acting user's, in either scope: nobody else's tasks are
- // theirs to tick off.
this.db.activity.findMany({
where: {
type: ActivityType.TASK,
@@ -190,8 +169,6 @@ export class DashboardService {
for (const deal of recentDeals) {
const cents = toCents(deal.amount) ?? 0;
- // A deal closed inside the window but opened before it lands in no
- // created bucket — the index is negative, and the lookup misses.
const created = trend[monthKey(deal.createdAt) - firstBucket];
if (created) created.created += cents;
@@ -218,9 +195,6 @@ export class DashboardService {
wonCents += cents;
cycleDays += (closedAt.getTime() - deal.createdAt.getTime()) / DAY_MS;
} else if (stage === DealStage.CLOSED_LOST) {
- // Disqualified deals are deliberately neither: they never reached a
- // decision, so counting them would turn the win rate into a
- // measure of lead quality.
losses += 1;
}
}
@@ -236,7 +210,6 @@ export class DashboardService {
},
wonThisMonth,
wonPrevMonth,
- /** Rolling rates over `windowDays`. `null` where nothing has closed. */
performance: {
windowDays: RATE_WINDOW_DAYS,
wins,
@@ -245,7 +218,6 @@ export class DashboardService {
avgDealCents: wins === 0 ? null : Math.round(wonCents / wins),
avgCycleDays: wins === 0 ? null : Math.round(cycleDays / wins),
},
- /** Six months of closed-won value against new pipeline created. */
trend,
closingThisMonthTotal: {
count: closingThisMonthTotals._count._all,
diff --git a/apps/api/src/database/database.module.ts b/apps/api/src/database/database.module.ts
index 63bf1a68..5c0fa131 100644
--- a/apps/api/src/database/database.module.ts
+++ b/apps/api/src/database/database.module.ts
@@ -18,11 +18,6 @@ export class DatabaseModule implements OnModuleInit, OnApplicationShutdown {
constructor(@InjectDatabase() private readonly db: Db) {}
- /**
- * Prisma connects lazily on first query, which turns a bad `DATABASE_URL`
- * into a confusing 500 on some unrelated endpoint. Connecting at startup
- * fails the boot instead.
- */
async onModuleInit(): Promise<void> {
try {
await this.db.$connect();
diff --git a/apps/api/src/deals/deal-stage.ts b/apps/api/src/deals/deal-stage.ts
index c755ff8e..a0b1e990 100644
--- a/apps/api/src/deals/deal-stage.ts
+++ b/apps/api/src/deals/deal-stage.ts
@@ -1,9 +1,5 @@
import { DealStage } from "@crm/db";
-/**
- * Stages a deal can still be won from. Pipeline value and the forecast are the
- * sum over these.
- */
export const OPEN_DEAL_STAGES = [
DealStage.DEMO_BOOKED,
DealStage.QUALIFIED_TO_BUY,
@@ -11,18 +7,12 @@ export const OPEN_DEAL_STAGES = [
DealStage.CONTRACT_SENT,
] as const;
-/**
- * Stages a deal is finished in. `UNQUALIFIED_TO_BUY` belongs here rather than
- * mid-funnel: it is a disqualification, not a step forward, and counting it as
- * open would inflate the pipeline with deals nobody is working.
- */
export const CLOSED_DEAL_STAGES = [
DealStage.CLOSED_WON,
DealStage.CLOSED_LOST,
DealStage.UNQUALIFIED_TO_BUY,
] as const;
-/** Closed stages that need a reason typed in. */
export const LOSING_DEAL_STAGES = [
DealStage.CLOSED_LOST,
DealStage.UNQUALIFIED_TO_BUY,
diff --git a/apps/api/src/deals/deals.contracts.ts b/apps/api/src/deals/deals.contracts.ts
index b1463fef..cee609c9 100644
--- a/apps/api/src/deals/deals.contracts.ts
+++ b/apps/api/src/deals/deals.contracts.ts
@@ -2,7 +2,6 @@ import { DealStage } from "@crm/db";
import { z } from "zod";
import { listInput } from "../trpc/list-input";
-/** Buckets for the "closing" facet. */
export const CLOSING_WINDOWS = [
"overdue",
"this-month",
@@ -14,21 +13,9 @@ export const CLOSING_WINDOWS = [
export type ClosingWindow = (typeof CLOSING_WINDOWS)[number];
export const dealListInput = listInput.extend({
- /**
- * The tab: `"open"`, `"closed"` or `"all"`.
- *
- * Open and closed rather than one tab per stage — a rep wants "what am I
- * working" and "what happened", and the stage facet covers the rest.
- */
status: z.string().default("all"),
- /**
- * A user id, or `"all"`. `"unassigned"` is accepted so every list speaks the
- * same facet language, but a deal always has an owner, so it matches nothing.
- */
owner: z.string().default("all"),
- /** A `DealStage`, or `"all"`. */
stage: z.string().default("all"),
- /** A `ClosingWindow`, or `"all"`. */
closing: z.string().default("all"),
});
@@ -41,20 +28,15 @@ const stageEnum = z.enum(
export const dealCreateInput = z.object({
name: z.string().trim().min(1, "A deal needs a name."),
companyId: z.string().min(1, "A deal belongs to a company."),
- /** Required — every deal has a name against it. */
ownerId: z.string().min(1, "A deal needs an owner."),
stage: stageEnum.optional(),
- /** Integer cents, so summing a pipeline is exact. */
amountCents: z.number().int().min(0).nullable().optional(),
currency: z.string().length(3).optional(),
- /** ISO-8601 date. */
expectedCloseDate: z.string().nullable().optional(),
});
export type DealCreateInput = z.infer<typeof dealCreateInput>;
-/** `undefined` leaves a field alone. Stage is not here — it goes through
- * `setStage`, which also writes the timeline entry. */
const dealUpdateInput = z.object({
name: z.string().trim().min(1).optional(),
companyId: z.string().optional(),
@@ -76,7 +58,6 @@ export const dealIdInput = z.object({ id: z.string() });
export const setStageInput = z.object({
id: z.string(),
stage: stageEnum,
- /** Why it was lost or disqualified. Required for the losing stages. */
closedReason: z.string().trim().optional(),
});
diff --git a/apps/api/src/deals/deals.router.ts b/apps/api/src/deals/deals.router.ts
index 2f191026..6d916548 100644
--- a/apps/api/src/deals/deals.router.ts
+++ b/apps/api/src/deals/deals.router.ts
@@ -44,7 +44,6 @@ export class DealsRouter {
return this.deals.update(input.id, input.data);
}
- /** Moves the deal and writes the `STAGE_CHANGE` activity in one transaction. */
@Mutation({ input: setStageInput })
async setStage(
@Ctx() ctx: AuthedTrpcContext,
diff --git a/apps/api/src/deals/deals.service.ts b/apps/api/src/deals/deals.service.ts
index f6454426..6ac88467 100644
--- a/apps/api/src/deals/deals.service.ts
+++ b/apps/api/src/deals/deals.service.ts
@@ -51,6 +51,7 @@ const COMPANY_SELECT = {
iconUrl: true,
iconDarkUrl: true,
iconTone: true,
+ logoUrl: true,
} as const;
const LOSING = new Set<DealStage>(LOSING_DEAL_STAGES);
@@ -61,8 +62,6 @@ const SORTABLE: Record<
> = {
name: (dir) => [{ name: dir }],
company: (dir) => [{ company: { name: dir } }, { name: "asc" }],
- // Enum order is declaration order in Postgres, which is pipeline order — so
- // sorting by stage reads as "how far along", not alphabetically.
stage: (dir) => [{ stage: dir }, { expectedCloseDate: "asc" }],
amount: (dir) => [{ amount: dir }],
expectedCloseDate: (dir) => [{ expectedCloseDate: dir }],
@@ -106,9 +105,6 @@ export class DealsService {
}),
this.db.deal.count({ where }),
this.facetCounts(input),
- // Summed in Postgres over the *filtered* set, not the page: a footer
- // that says "$1.2M" for the 25 rows you can see is worse than no
- // number at all.
this.db.deal.aggregate({
where: { ...where, stage: { in: [...OPEN_DEAL_STAGES] } },
_sum: { amount: true },
@@ -135,7 +131,6 @@ export class DealsService {
),
total,
facetCounts,
- /** Open pipeline value across everything matching the filters. */
openValueCents: toCents(openValue._sum.amount),
} satisfies ListResult<unknown> & { openValueCents: number | null };
}
@@ -166,6 +161,7 @@ export class DealsService {
lastName: true,
email: true,
title: true,
+ imageUrl: true,
},
},
},
@@ -248,13 +244,6 @@ export class DealsService {
}
}
- /**
- * Moves a deal and records that it moved.
- *
- * One transaction, because a stage change with no timeline entry is a deal
- * nobody can explain a week later — and a timeline entry for a change that
- * did not commit is worse.
- */
async setStage(input: SetStageInput, actingUserId: string) {
const deal = await this.db.deal.findUnique({
where: { id: input.id },
@@ -296,8 +285,6 @@ export class DealsService {
subject: "Stage changed",
body: closedReason ?? null,
occurredAt: now,
- // Stamped with the company as well as the deal, so this shows on
- // the company timeline without a join.
companyId: deal.companyId,
dealId: deal.id,
createdById: actingUserId,
@@ -337,9 +324,6 @@ export class DealsService {
const where: Prisma.DealWhereInput = this.searchFilter(input.q);
if (input.owner !== FACET_ALL) {
- // `Deal.ownerId` is required, so unlike companies and contacts there is
- // no null to match — "unassigned" is a filter that can only ever be
- // empty, and `in: []` says that in Prisma's own terms.
where.ownerId =
input.owner === FACET_UNASSIGNED ? { in: [] } : input.owner;
}
@@ -350,8 +334,6 @@ export class DealsService {
where.stage = { in: [...CLOSED_DEAL_STAGES] };
}
- // An explicit stage wins over the tab: picking "Closed won" while the
- // "Open" tab is selected should show closed-won, not nothing.
if (input.stage !== FACET_ALL) {
where.stage = input.stage as DealStage;
}
@@ -407,7 +389,6 @@ export class DealsService {
return this.translateRelations(error);
}
- /** A missing company or owner is the caller's mistake, not a 500. */
private translateRelations(error: unknown): unknown {
if (
error instanceof PrismaNamespace.PrismaClientKnownRequestError &&
@@ -421,11 +402,6 @@ export class DealsService {
}
}
-/**
- * Month boundaries are computed here rather than in SQL so the buckets follow
- * the server's calendar rather than UTC's, which matters on the last day of a
- * month for a team in New York.
- */
function closingFilter(window: ClosingWindow): Prisma.DealWhereInput {
const now = new Date();
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
@@ -434,7 +410,6 @@ function closingFilter(window: ClosingWindow): Prisma.DealWhereInput {
switch (window) {
case "overdue":
- // Only open deals can be overdue; a closed deal's date is history.
return {
expectedCloseDate: { lt: now },
stage: { in: [...OPEN_DEAL_STAGES] },
diff --git a/apps/api/src/generated/server.ts b/apps/api/src/generated/server.ts
index a8f4d9d8..c393aab7 100644
--- a/apps/api/src/generated/server.ts
+++ b/apps/api/src/generated/server.ts
@@ -20,6 +20,7 @@ import { conversationListInput, conversationEventsInput, conversationSaveInput,
import { dashboardSummaryInput } from "../dashboard/dashboard.contracts";
import { dealListInput, dealIdInput, dealCreateInput, dealUpdateArgs, setStageInput } from "../deals/deals.contracts";
import { setAutoCreateInput, suppressDomainInput, threadInput, calendarEventInput } from "../google/google.contracts";
+import { setAgentModelInput } from "../settings/settings.contracts";
import type { ActivitiesRouter } from "../activities/activities.router";
import type { CompaniesRouter } from "../companies/companies.router";
import type { ContactsRouter } from "../contacts/contacts.router";
@@ -28,6 +29,7 @@ import type { DashboardRouter } from "../dashboard/dashboard.router";
import type { DealsRouter } from "../deals/deals.router";
import type { GoogleRouter } from "../google/google.router";
import type { SearchRouter } from "../search/search.router";
+import type { SettingsRouter } from "../settings/settings.router";
import type { UsersRouter } from "../users/users.router";
const appRouter = t.router({
@@ -87,6 +89,9 @@ const appRouter = t.router({
update: publicProcedure
.input(contactUpdateArgs)
.mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["update"]>>),
+ enrich: publicProcedure
+ .input(contactIdInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["enrich"]>>),
decideFact: publicProcedure
.input(factDecisionInput)
.mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["decideFact"]>>)
@@ -154,6 +159,15 @@ const appRouter = t.router({
.input(z.object({ q: z.string().default("") }))
.query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<SearchRouter["quick"]>>)
}),
+ settings: t.router({
+ agentModel: publicProcedure
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<SettingsRouter["agentModel"]>>),
+ modelCatalog: publicProcedure
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<SettingsRouter["modelCatalog"]>>),
+ setAgentModel: publicProcedure
+ .input(setAgentModelInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<SettingsRouter["setAgentModel"]>>)
+ }),
users: t.router({
me: publicProcedure
.query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<UsersRouter["me"]>>),
diff --git a/apps/api/src/google/calendar-sync.service.ts b/apps/api/src/google/calendar-sync.service.ts
index 6fa948ba..965c1bb4 100644
--- a/apps/api/src/google/calendar-sync.service.ts
+++ b/apps/api/src/google/calendar-sync.service.ts
@@ -20,10 +20,8 @@ import { GoogleTokenService } from "./google-token.service";
import type { Participant } from "./participants";
import { SyncStateService } from "./sync-state.service";
-/** How many pages one cron tick will pull before yielding. */
const MAX_PAGES_PER_TICK = 5;
-/** How far forward to look. Meetings matter before they happen. */
const HORIZON_DAYS = 180;
export type SyncOutcome = {
@@ -35,14 +33,6 @@ export type SyncOutcome = {
reason?: string;
};
-/**
- * Google Calendar → `CalendarEvent` → a projected `Activity` on the timeline.
- *
- * Calendar is the simpler of the two syncs and was built first deliberately: the
- * dedupe key is handed to us, there are no bodies to parse, and it proves the
- * whole connect → cron → match → project → render path before Gmail adds its
- * own problems.
- */
@Injectable()
export class CalendarSyncService {
private readonly logger = new Logger(CalendarSyncService.name);
@@ -101,13 +91,6 @@ export class CalendarSyncService {
const result = await this.calendar.listEvents(token.accessToken, {
syncToken,
pageToken,
- // Only meaningful on a full pass; ignored when a syncToken is set.
- //
- // `now`, never earlier: past meetings are not imported. Events that
- // *start* from now on are, though, including ones booked before the
- // sync was switched on — a meeting in next Tuesday's diary is the
- // point of the feature, and putting it on the timeline is not
- // back-dating anything.
timeMin: new Date().toISOString(),
timeMax: this.horizon().toISOString(),
});
@@ -163,8 +146,6 @@ export class CalendarSyncService {
pageToken = result.data.nextPageToken;
if (!pageToken) {
- // The sync token only appears on the final page; that is the signal
- // the window is fully drained and steady-state can begin.
syncToken = result.data.nextSyncToken ?? syncToken;
await this.state.settle(row.id, {
cursor: syncToken ?? null,
@@ -188,9 +169,6 @@ export class CalendarSyncService {
}
}
- // Ran out of page budget without reaching the last page, so there is no
- // sync token to keep. The next tick re-runs the window, which is free
- // because every write is an upsert on a natural key.
await this.state.settle(row.id, {
status: GoogleSyncStatus.IDLE,
});
@@ -205,11 +183,6 @@ export class CalendarSyncService {
};
}
- /**
- * One event: store it, project it, or delete what we stored before.
- *
- * Returns what it did so the caller can count without a second pass.
- */
private async apply(
event: GoogleEvent,
row: MailboxSync,
@@ -221,8 +194,6 @@ export class CalendarSyncService {
const start = eventTime(event.start);
const originalStart = eventTime(event.originalStartTime) ?? start;
- // An instance keeps its original start even when moved, which is what
- // identifies it within a recurring series.
if (!originalStart) return "ignored";
const key = {
@@ -233,8 +204,6 @@ export class CalendarSyncService {
};
if (event.status === "cancelled") {
- // Cancellations arrive as ordinary items because we ask for
- // showDeleted. Deleting cascades to the projected activity.
const deleted = await this.db.calendarEvent.deleteMany({
where: {
iCalUid,
@@ -249,8 +218,6 @@ export class CalendarSyncService {
const participants = this.participantsOf(event);
- // A meeting is two-way engagement on its own: somebody put time in a
- // diary. So calendar may create, subject to the row's own toggle.
const declinedByUs = event.attendees?.some(
(attendee) => attendee.self && attendee.responseStatus === "declined",
);
@@ -260,16 +227,12 @@ export class CalendarSyncService {
participants,
allowCreate: row.autoCreate && !declinedByUs,
source: RecordSource.CALENDAR,
- // Whoever's calendar this is owns what it creates — they are the
- // person with the relationship.
ownerId: row.userId,
},
context,
);
if (!match.companyId && !match.contactId) {
- // Nothing we track, and nothing worth creating — a dentist appointment.
- // Never stored, per the plan §5.
return "ignored";
}
@@ -324,13 +287,11 @@ export class CalendarSyncService {
return "written";
}
- /** Replaces the attendee list, linking anyone we already know as a contact. */
private async syncAttendees(
eventId: string,
event: GoogleEvent,
): Promise<void> {
const attendees = (event.attendees ?? []).filter(
- // Meeting rooms are attendees as far as Google is concerned.
(attendee) => attendee.email && !attendee.resource,
);
@@ -372,18 +333,6 @@ export class CalendarSyncService {
}
}
- /**
- * Tells the agent about people we are about to meet and do not know.
- *
- * The most useful thing the calendar knows is that a conversation is
- * *coming*, and nothing in the stack acted on it before. A contact with no
- * background, on a meeting tomorrow, is worth more research than the same
- * contact would be on any other day — and the deadline is real, so it goes
- * to the front of the queue rather than waiting its turn behind a backlog.
- *
- * Only for meetings actually ahead of us: back-filling a year of history
- * would queue research for every meeting that has already happened.
- */
private async prepareForMeeting(
eventId: string,
startsAt: Date,
@@ -395,7 +344,6 @@ export class CalendarSyncService {
where: {
eventId,
contactId: { not: null },
- // Whoever is taking the meeting is not who needs researching.
contact: { brief: { is: null } },
},
select: { contactId: true },
@@ -408,13 +356,6 @@ export class CalendarSyncService {
}
}
- /**
- * The timeline projection: one `Activity` per event, kept current.
- *
- * `occurredAt` is the meeting's start even when that is in the future, so an
- * upcoming meeting sorts where a rep expects to find it rather than at the
- * moment the sync happened to run.
- */
private async project(
calendarEventId: string,
userId: string,
@@ -468,8 +409,6 @@ export class CalendarSyncService {
});
}
- // A one-to-one booked through a scheduling link often has the customer as
- // organiser and nobody in `attendees`.
if (event.organizer?.email) {
people.push({
email: event.organizer.email.toLowerCase(),
diff --git a/apps/api/src/google/calendar.client.ts b/apps/api/src/google/calendar.client.ts
index ca576c57..3ccb293a 100644
--- a/apps/api/src/google/calendar.client.ts
+++ b/apps/api/src/google/calendar.client.ts
@@ -4,7 +4,6 @@ import { GoogleApiClient, type GoogleResult } from "./google-api.client";
const EVENTS_URL =
"https://www.googleapis.com/calendar/v3/calendars/primary/events";
-/** The slice of Google's event resource we actually read. */
export type GoogleEvent = {
id?: string;
iCalUID?: string;
@@ -34,9 +33,7 @@ export type GoogleEvent = {
};
export type GoogleEventTime = {
- /** Set on a timed event. */
dateTime?: string;
- /** Set on an all-day event; a bare `YYYY-MM-DD`. */
date?: string;
timeZone?: string;
};
@@ -48,7 +45,6 @@ export type EventsPage = {
};
export type EventsQuery = {
- /** Incremental. Mutually exclusive with the time window, per Google. */
syncToken?: string;
timeMin?: string;
timeMax?: string;
@@ -60,19 +56,10 @@ export type EventsQuery = {
export class CalendarClient {
constructor(private readonly api: GoogleApiClient) {}
- /**
- * One page of events.
- *
- * `singleEvents: true` expands recurring series into instances, which is what
- * makes `(iCalUID, originalStartTime)` a usable key — an unexpanded series
- * would be one row for "every Tuesday forever" and could not sit on a
- * timeline. `showDeleted: true` is how cancellations arrive at all.
- */
async listEvents(
accessToken: string,
query: EventsQuery,
): Promise<GoogleResult<EventsPage>> {
- // Google rejects a request carrying both a syncToken and a time window.
const window = query.syncToken
? {}
: { timeMin: query.timeMin, timeMax: query.timeMax };
@@ -88,7 +75,6 @@ export class CalendarClient {
}
}
-/** The best conference link on an event, if it has one. */
export function conferenceUrl(event: GoogleEvent): string | null {
if (event.hangoutLink) return event.hangoutLink;
@@ -99,7 +85,6 @@ export function conferenceUrl(event: GoogleEvent): string | null {
return entry?.uri ?? null;
}
-/** A Google event time as a Date, plus whether the event is all-day. */
export function eventTime(
time: GoogleEventTime | undefined,
): { at: Date; isAllDay: boolean } | null {
@@ -109,8 +94,6 @@ export function eventTime(
}
if (time?.date) {
- // A bare date is midnight local to the calendar; parsing it as UTC keeps
- // the key stable regardless of where the server runs.
const at = new Date(`${time.date}T00:00:00Z`);
return Number.isNaN(at.getTime()) ? null : { at, isAllDay: true };
}
diff --git a/apps/api/src/google/conversation.service.ts b/apps/api/src/google/conversation.service.ts
index f15f3f48..e08b1874 100644
--- a/apps/api/src/google/conversation.service.ts
+++ b/apps/api/src/google/conversation.service.ts
@@ -2,14 +2,6 @@ import type { Db } from "@crm/db";
import { Injectable, NotFoundException } from "@nestjs/common";
import { InjectDatabase } from "../database/database.constants";
-/**
- * Reading a synced thread or event back out.
- *
- * Separate from the sync services because this is the only path that returns
- * message bodies, and keeping it in one file makes "where can an email body
- * reach the browser" a question with one answer. The timeline never calls it —
- * it carries a snippet, and the accordion fetches this on expand.
- */
@Injectable()
export class ConversationService {
constructor(@InjectDatabase() private readonly db: Db) {}
@@ -47,6 +39,10 @@ export class ConversationService {
throw new NotFoundException(`No email thread with id ${threadId}.`);
}
+ const faces = await this.facesFor(
+ thread.messages.map((message) => message.fromEmail),
+ );
+
return {
...thread,
firstMessageAt: thread.firstMessageAt.toISOString(),
@@ -55,7 +51,7 @@ export class ConversationService {
...message,
sentAt: message.sentAt.toISOString(),
recipients: recipientsOf(message.recipients),
- /** Deep link back to Gmail, when we know which message it was. */
+ fromImageUrl: faces.get(message.fromEmail.toLowerCase()) ?? null,
gmailUrl: message.gmailMessageId
? `https://mail.google.com/mail/u/0/#all/${message.gmailMessageId}`
: null,
@@ -63,6 +59,36 @@ export class ConversationService {
};
}
+ private async facesFor(addresses: string[]): Promise<Map<string, string>> {
+ const emails = [
+ ...new Set(addresses.map((address) => address.toLowerCase())),
+ ];
+ if (emails.length === 0) return new Map();
+
+ const [contacts, users] = await Promise.all([
+ this.db.contact.findMany({
+ where: { email: { in: emails, mode: "insensitive" } },
+ select: { email: true, imageUrl: true },
+ }),
+ this.db.user.findMany({
+ where: { email: { in: emails, mode: "insensitive" } },
+ select: { email: true, image: true },
+ }),
+ ]);
+
+ const faces = new Map<string, string>();
+ for (const contact of contacts) {
+ if (contact.email && contact.imageUrl) {
+ faces.set(contact.email.toLowerCase(), contact.imageUrl);
+ }
+ }
+ for (const user of users) {
+ if (user.image) faces.set(user.email.toLowerCase(), user.image);
+ }
+
+ return faces;
+ }
+
async event(eventId: string) {
const event = await this.db.calendarEvent.findUnique({
where: { id: eventId },
@@ -88,6 +114,7 @@ export class ConversationService {
responseStatus: true,
isOrganizer: true,
contactId: true,
+ contact: { select: { imageUrl: true } },
},
},
},
@@ -101,11 +128,14 @@ export class ConversationService {
...event,
startsAt: event.startsAt.toISOString(),
endsAt: event.endsAt.toISOString(),
+ attendees: event.attendees.map(({ contact, ...attendee }) => ({
+ ...attendee,
+ imageUrl: contact?.imageUrl ?? null,
+ })),
};
}
}
-/** `recipients` is `Json`, so it is read back defensively. */
function recipientsOf(
value: unknown,
): { email: string; name: string | null; kind: string }[] {
diff --git a/apps/api/src/google/gmail-sync.service.ts b/apps/api/src/google/gmail-sync.service.ts
index 3e195290..b27d971e 100644
--- a/apps/api/src/google/gmail-sync.service.ts
+++ b/apps/api/src/google/gmail-sync.service.ts
@@ -28,7 +28,6 @@ import {
} from "./participants";
import { SyncStateService } from "./sync-state.service";
-/** Ceiling on one tick, so a burst of mail cannot stretch an invocation. */
const MAX_MESSAGES_PER_TICK = 120;
export type GmailSyncOutcome = {
@@ -40,7 +39,6 @@ export type GmailSyncOutcome = {
reason?: string;
};
-/** A message parsed into the shape the database wants. */
type ParsedMessage = {
rfcMessageId: string;
rootId: string;
@@ -52,13 +50,6 @@ type ParsedMessage = {
gmailMessageId: string | null;
};
-/**
- * Gmail → `EmailThread`/`EmailMessage` → one projected `Activity` per thread.
- *
- * The two things that make this harder than calendar: identity has to be
- * derived from RFC headers rather than handed to us, and a reply carries the
- * whole conversation in its body, so what gets stored needs pruning first.
- */
@Injectable()
export class GmailSyncService {
private readonly logger = new Logger(GmailSyncService.name);
@@ -96,8 +87,6 @@ export class GmailSyncService {
await this.state.markRunning(row.id);
- // Whose mailbox this is, so a message can be classed inbound or outbound
- // and so "did the rep reply?" is answerable.
const profile = await this.gmail.profile(token.accessToken);
if (profile.outcome !== "ok") {
return this.handleFailure(row, profile, "gmail");
@@ -114,9 +103,6 @@ export class GmailSyncService {
};
}
- // No cursor means this mailbox has never been seen. Sync is forward-only,
- // so the first pass imports nothing at all — it just records where "now"
- // is, and everything after that point arrives through `incremental`.
if (!row.cursor) {
return this.start(row, profile.data.historyId ?? null);
}
@@ -124,14 +110,6 @@ export class GmailSyncService {
return this.incremental(row, token.accessToken, mailbox, row.cursor);
}
- /**
- * Marks the starting line.
- *
- * Deliberately imports nothing. A CRM that suddenly fills with three months
- * of a rep's old mail is noise nobody asked for, and the history is not what
- * the feature is for — what matters is that from this moment on, the
- * conversation shows up on the record.
- */
private async start(
row: MailboxSync,
historyId: string | null,
@@ -159,7 +137,6 @@ export class GmailSyncService {
return { source: "gmail", userId: row.userId, status: "synced" };
}
- /** Everything added since the stored historyId. */
private async incremental(
row: MailboxSync,
accessToken: string,
@@ -171,11 +148,6 @@ export class GmailSyncService {
});
if (history.outcome === "cursor-invalid") {
- // The historyId fell out of Gmail's retention window — which takes about
- // a week of the sync not running at all. Forward-only means we do not
- // go back and fetch the gap: the cursor is re-pointed at now and the
- // missed window is simply not imported. Logged, because a mailbox that
- // keeps landing here is a sync that keeps failing.
await this.state.clearCursor(row.id, history.reason);
return {
@@ -205,10 +177,6 @@ export class GmailSyncService {
);
await this.state.settle(row.id, {
- // Hold the cursor when the batch was capped. Advancing past messages we
- // never read would drop them permanently; leaving it means the next tick
- // re-lists the same window, finds this run's writes already stored, and
- // works through the next hundred.
cursor:
remaining > 0
? startHistoryId
@@ -233,14 +201,6 @@ export class GmailSyncService {
};
}
- /**
- * Fetches and stores message ids, up to this tick's ceiling.
- *
- * Reports what it could not get to, so the caller knows whether it is safe to
- * advance the cursor. Filtering the already-stored ids out *before* taking the
- * batch is what makes a capped run make progress: otherwise every tick would
- * re-take the same first hundred, find them all present, and write nothing.
- */
private async ingest(
row: MailboxSync,
accessToken: string,
@@ -249,9 +209,6 @@ export class GmailSyncService {
): Promise<{ written: number; remaining: number }> {
if (ids.length === 0) return { written: 0, remaining: 0 };
- // The unique index on `rfcMessageId` is the backstop, but checking Gmail's
- // own id first avoids paying for a `messages.get` on something another
- // rep's sync already ingested.
const alreadyHave = await this.db.emailMessage.findMany({
where: { gmailMessageId: { in: [...ids] } },
select: { gmailMessageId: true },
@@ -290,7 +247,6 @@ export class GmailSyncService {
return { written, remaining };
}
- /** One message: match it, store it, keep its thread's projection current. */
private async store(
row: MailboxSync,
mailbox: string,
@@ -300,8 +256,6 @@ export class GmailSyncService {
const parsed = this.parse(message);
if (!parsed) return false;
- // Already ingested from another mailbox. The unique index would catch this
- // anyway; checking first keeps the log honest about what was written.
const existing = await this.db.emailMessage.findUnique({
where: { rfcMessageId: parsed.rfcMessageId },
select: { id: true },
@@ -311,8 +265,6 @@ export class GmailSyncService {
const participants = [parsed.from, ...parsed.recipients];
const outbound = parsed.from.email === mailbox;
- // The thread may already exist from an earlier message, in which case its
- // match is authoritative and the whole resolve step is skipped.
const thread = await this.db.emailThread.findUnique({
where: { rootMessageId: parsed.rootId },
select: { id: true, companyId: true, contactId: true },
@@ -322,9 +274,6 @@ export class GmailSyncService {
let contactId = thread?.contactId ?? null;
if (!thread) {
- // Two-way engagement: the rep has to have sent something. An inbound-only
- // thread is a newsletter, a recruiter or spam, and creating a company
- // from one is how a CRM fills with junk.
const repliedTo =
outbound || (await this.hasOutboundInThread(parsed.rootId, mailbox));
@@ -333,7 +282,6 @@ export class GmailSyncService {
participants,
allowCreate: row.autoCreate && repliedTo,
source: RecordSource.EMAIL,
- // Whoever's mailbox this is owns what it creates.
ownerId: row.userId,
},
context,
@@ -343,8 +291,6 @@ export class GmailSyncService {
contactId = match.contactId;
if (!companyId && !contactId) {
- // Not anybody we track and not worth creating. Dropped at ingest —
- // never written, per the plan §5.
return false;
}
}
@@ -381,9 +327,6 @@ export class GmailSyncService {
},
});
- // Recomputed rather than incremented: messages arriving out of order would
- // otherwise leave `lastMessageAt` pointing at whichever message happened to
- // arrive last, which is not the same as the latest one.
const stats = await this.db.emailMessage.aggregate({
where: { threadId: record.id },
_count: { _all: true },
@@ -400,8 +343,6 @@ export class GmailSyncService {
messageCount: stats._count._all,
firstMessageAt,
lastMessageAt,
- // A thread's subject is the one it started with, not the "Re: Re: Fwd:"
- // it acquired.
...(parsed.sentAt <= firstMessageAt ? { subject: parsed.subject } : {}),
},
});
@@ -417,7 +358,6 @@ export class GmailSyncService {
return true;
}
- /** Whether the mailbox owner has sent anything into this thread already. */
private async hasOutboundInThread(
rootMessageId: string,
mailbox: string,
@@ -433,12 +373,6 @@ export class GmailSyncService {
return found !== null;
}
- /**
- * One `Activity` per thread, updated as the thread grows.
- *
- * Not one per message: a forty-message thread would otherwise be forty
- * timeline rows saying almost the same thing.
- */
private async project(
emailThreadId: string,
userId: string,
@@ -476,7 +410,6 @@ export class GmailSyncService {
);
}
- /** Gmail's message resource → the fields we store. */
private parse(message: GmailMessage): ParsedMessage | null {
const headers = message.payload?.headers;
@@ -521,8 +454,6 @@ export class GmailSyncService {
message: GmailMessage,
headers: readonly GmailHeader[] | undefined,
): Date | null {
- // `internalDate` is Gmail's own receipt time in ms and is always present
- // and always parseable; the `Date` header is neither.
if (message.internalDate) {
const at = new Date(Number(message.internalDate));
if (!Number.isNaN(at.getTime())) return at;
diff --git a/apps/api/src/google/gmail.client.ts b/apps/api/src/google/gmail.client.ts
index ff7d1b9d..260b14c2 100644
--- a/apps/api/src/google/gmail.client.ts
+++ b/apps/api/src/google/gmail.client.ts
@@ -34,14 +34,6 @@ export type Profile = {
historyId?: string;
};
-/**
- * The Gmail query used for every backfill page.
- *
- * Narrowing here rather than after fetching is the difference between reading a
- * mailbox and reading the part of it that could possibly be work. Promotions,
- * social and chats are never customer conversations, and each excluded message
- * is a `messages.get` we do not pay for.
- */
export const WORK_MAIL_QUERY =
"-in:chats -category:promotions -category:social -category:forums";
@@ -49,12 +41,10 @@ export const WORK_MAIL_QUERY =
export class GmailClient {
constructor(private readonly api: GoogleApiClient) {}
- /** The mailbox's own address and current historyId — the backfill anchor. */
async profile(accessToken: string): Promise<GoogleResult<Profile>> {
return this.api.get<Profile>(`${BASE}/profile`, accessToken);
}
- /** Message ids in a time window, newest first. */
async listMessages(
accessToken: string,
options: {
@@ -64,7 +54,6 @@ export class GmailClient {
maxResults?: number;
},
): Promise<GoogleResult<MessageList>> {
- // Gmail's `after`/`before` take seconds since the epoch.
const after = Math.floor(options.after.getTime() / 1000);
const before = Math.ceil(options.before.getTime() / 1000);
@@ -75,13 +64,6 @@ export class GmailClient {
});
}
- /**
- * Changes since a historyId.
- *
- * A `startHistoryId` older than Gmail's retention window (documented as
- * "typically at least one week") comes back as 404, which
- * `GoogleApiClient` surfaces as `cursor-invalid`.
- */
async listHistory(
accessToken: string,
options: { startHistoryId: string; pageToken?: string },
@@ -94,7 +76,6 @@ export class GmailClient {
});
}
- /** One message, with headers and body. */
async getMessage(
accessToken: string,
id: string,
diff --git a/apps/api/src/google/google-api.client.ts b/apps/api/src/google/google-api.client.ts
index 686fe809..f84eb112 100644
--- a/apps/api/src/google/google-api.client.ts
+++ b/apps/api/src/google/google-api.client.ts
@@ -1,14 +1,5 @@
import { Injectable, Logger } from "@nestjs/common";
-/**
- * What a Google API call did.
- *
- * The interesting cases are the two cursor invalidations, and they are separate
- * variants rather than a status number because the whole sync design turns on
- * them: Gmail answers an out-of-range `startHistoryId` with 404, Calendar
- * answers a dead `syncToken` with 410, and both mean "your cursor is gone, fall
- * back to a bounded resync" rather than "something broke".
- */
export type GoogleResult<T> =
| { outcome: "ok"; data: T }
| { outcome: "cursor-invalid"; reason: string }
@@ -18,7 +9,6 @@ export type GoogleResult<T> =
const DEFAULT_TIMEOUT_MS = 20_000;
-/** Google's own suggestion when it rate limits us, with a sane floor. */
const MIN_BACKOFF_MS = 30_000;
const MAX_BACKOFF_MS = 15 * 60_000;
@@ -26,13 +16,6 @@ const MAX_BACKOFF_MS = 15 * 60_000;
export class GoogleApiClient {
private readonly logger = new Logger(GoogleApiClient.name);
- /**
- * A GET against a Google REST endpoint.
- *
- * Deliberately `fetch` rather than `googleapis`: we call four endpoints, the
- * SDK is tens of megabytes of generated surface, and a serverless bundle pays
- * for every byte on every cold start.
- */
async get<T>(
url: string,
accessToken: string,
@@ -77,24 +60,17 @@ export class GoogleApiClient {
return { outcome: "ok", data: (await response.json()) as T };
}
- // Read the body for the reason, but never log it verbatim — Google echoes
- // request parameters back in error messages, and those can carry addresses.
const detail = await this.reason(response);
switch (response.status) {
case 401:
return { outcome: "unauthorized", reason: detail };
- // Gmail: `startHistoryId` is older than the retained history window.
case 404:
- // Calendar: the `syncToken` expired or was invalidated by an ACL change.
case 410:
return { outcome: "cursor-invalid", reason: detail };
case 403:
- // 403 is overloaded: quota exhaustion looks the same as a genuine
- // permission failure until you read the reason. Only the quota flavour
- // is worth backing off for; the rest is terminal.
if (/rate|quota|userRateLimitExceeded|limitExceeded/i.test(detail)) {
return {
outcome: "rate-limited",
diff --git a/apps/api/src/google/google-connection.service.ts b/apps/api/src/google/google-connection.service.ts
index 2d0b1256..01479d07 100644
--- a/apps/api/src/google/google-connection.service.ts
+++ b/apps/api/src/google/google-connection.service.ts
@@ -22,18 +22,10 @@ export type SourceStatus = {
};
export type ConnectionStatus = {
- /** Whether Google issued a refresh token. False means reconnect. */
hasRefreshToken: boolean;
sources: SourceStatus[];
};
-/**
- * Everything the settings page asks about a rep's Google connection.
- *
- * Connection state is read from `Account.scope` rather than kept in a column of
- * our own: the grant is the truth, and a boolean we maintain alongside it is a
- * boolean that will eventually disagree with it.
- */
@Injectable()
export class GoogleConnectionService {
private readonly logger = new Logger(GoogleConnectionService.name);
@@ -47,10 +39,6 @@ export class GoogleConnectionService {
) {}
async status(userId: string): Promise<ConnectionStatus> {
- // Reconcile first: the grant is the source of truth, and the sync rows are
- // derived from it. Doing this here rather than in an OAuth-callback handler
- // means the settings page is correct the moment it loads, with no
- // coordination between the redirect and a mutation.
await this.onConnected(userId);
const [granted, rows, hasRefreshToken] = await Promise.all([
@@ -78,14 +66,6 @@ export class GoogleConnectionService {
return { hasRefreshToken, sources };
}
- /**
- * Makes the sync rows match what Google has actually granted.
- *
- * Idempotent and safe to call repeatedly — `ensure` keeps the cursor of a
- * mailbox already syncing. Called from `status` and from the cron\'s
- * reconcile step, so a rep who grants the scopes and then closes the tab
- * still gets synced without ever loading the settings page again.
- */
async onConnected(userId: string): Promise<void> {
const [granted, existing] = await Promise.all([
this.tokens.grantedScopes(userId),
@@ -101,9 +81,6 @@ export class GoogleConnectionService {
if (known.has(source)) continue;
await this.state.ensure(userId, source, {
- // Meetings are unambiguous, so calendar auto-creates from the start.
- // Gmail is opt-in: the first week of mailbox auto-creation is where a
- // bad rule shows up, and that should be a deliberate choice.
autoCreate: source === "calendar",
});
@@ -115,7 +92,6 @@ export class GoogleConnectionService {
}
}
- /** Every user whose grant covers a source but who has no sync row yet. */
async reconcileAll(): Promise<void> {
const accounts = await this.db.account.findMany({
where: {
@@ -132,24 +108,7 @@ export class GoogleConnectionService {
}
}
- /**
- * Deletes everything this user's mailbox put into the CRM, and re-imports
- * from scratch.
- *
- * Deliberately *not* a "disconnect". Mailbox access is a condition of having
- * an account here, so there is no supported state where a signed-in rep is
- * not syncing — and a local disconnect could not create one anyway: the grant
- * would still be there, and the next reconcile would rebuild the rows it had
- * just deleted. Naming it for what it does avoids a button that appears to
- * work and silently undoes itself.
- *
- * The real exit is `revoke`, which ends the grant and therefore the account's
- * access to the CRM.
- */
async purgeSyncedData(userId: string): Promise<{ purged: number }> {
- // Cascades take the messages, attendees and projected activities with
- // them, which is the point: "delete my mail from the CRM" should not need
- // a migration to answer.
const [threads, events] = await this.db.$transaction([
this.db.emailThread.deleteMany({
where: { messages: { some: { syncedByUserId: userId } } },
@@ -157,9 +116,6 @@ export class GoogleConnectionService {
this.db.calendarEvent.deleteMany({ where: { syncedByUserId: userId } }),
]);
- // Those cascades took activities with them, so every stamp they were the
- // high-water mark for is now overstated. `touch` cannot fix that — it only
- // ever raises — so the stamps are rebuilt.
await this.stamp.recomputeAll();
const purged = threads.count + events.count;
@@ -169,7 +125,6 @@ export class GoogleConnectionService {
return { purged };
}
- /** The explicit hard revoke. Kills sign-in access too — see the plan §3.4. */
async revoke(userId: string): Promise<{ revoked: boolean }> {
await this.state.remove(userId);
const revoked = await this.tokens.revoke(userId);
@@ -189,12 +144,6 @@ export class GoogleConnectionService {
await this.state.setAutoCreate(userId, source, enabled);
}
- /**
- * Marks a domain as "not a customer".
- *
- * Optionally deletes what it already matched, because the reason someone
- * presses this is that a vendor's domain is sitting on a timeline right now.
- */
async suppressDomain(
domain: string,
options: { reason?: string; purge: boolean },
diff --git a/apps/api/src/google/google-match.service.ts b/apps/api/src/google/google-match.service.ts
index 5029faa6..af5ef48b 100644
--- a/apps/api/src/google/google-match.service.ts
+++ b/apps/api/src/google/google-match.service.ts
@@ -14,25 +14,16 @@ import {
workDomain,
} from "./participants";
-/**
- * The two sources that can create records.
- *
- * `RecordSource` is generated as a const object rather than a TS enum, so its
- * members are values and this union is how you narrow to them in type position.
- */
export type SyncRecordSource =
| typeof RecordSource.EMAIL
| typeof RecordSource.CALENDAR;
-/** What a thread or an event resolved to. */
export type MatchResult = {
companyId: string | null;
contactId: string | null;
- /** The external participants that survived filtering, for the caller's log. */
external: Participant[];
};
-/** Loaded once per sync pass and threaded through every item in it. */
export type MatchContext = {
ourAddresses: ReadonlySet<string>;
ourDomains: ReadonlySet<string>;
@@ -41,33 +32,11 @@ export type MatchContext = {
export type MatchRequest = {
participants: readonly Participant[];
- /**
- * Whether this item is allowed to create records it cannot find.
- *
- * The caller decides, because the rule is per-source and per-item: a meeting
- * qualifies on its own, an email thread only once the rep has replied. See
- * the plan §6.
- */
allowCreate: boolean;
source: SyncRecordSource;
- /**
- * Who ends up owning anything created.
- *
- * The rep whose mailbox produced the thread or the meeting — they are, by
- * definition, the person with the relationship. Leaving it unassigned makes
- * every auto-created record somebody else's problem, which is how a CRM ends
- * up with a pile of ownerless rows nobody works.
- */
ownerId: string;
};
-/**
- * Turns the people on a Google payload into a company and a contact.
- *
- * Used by both syncs, because the rule has to be identical: if calendar matched
- * differently from Gmail, the same customer would land on two different company
- * records depending on which arrived first.
- */
@Injectable()
export class GoogleMatchService {
private readonly logger = new Logger(GoogleMatchService.name);
@@ -79,19 +48,6 @@ export class GoogleMatchService {
private readonly log: EnrichmentLogService,
) {}
- /**
- * Who counts as "us".
- *
- * Derived from the `User` table rather than configured: sign-in is Google-only
- * behind an Internal consent screen, so every user is on a company domain by
- * construction. That makes a `GOOGLE_WORKSPACE_DOMAIN` env var a second copy
- * of a fact the database already holds — and one that is silently wrong the
- * day the team adds a second domain. `workDomain` drops free hosts, so a
- * stray personal address cannot poison the set.
- *
- * Loaded once per sync pass, not per item: it changes about once a quarter,
- * and a thread-by-thread query would dominate the tick.
- */
async internalIdentity(): Promise<{
addresses: Set<string>;
domains: Set<string>;
@@ -99,10 +55,6 @@ export class GoogleMatchService {
const users = await this.db.user.findMany({ select: { email: true } });
const addresses = new Set<string>();
- // Seeded with the workspace domains rather than relying only on what the
- // User table happens to contain. Sign-in is restricted to these, so they
- // are internal by definition — and this holds on an empty database, and
- // for colleagues who have never signed in and so are not users yet.
const domains = new Set<string>(workspaceDomains());
for (const user of users) {
@@ -123,14 +75,6 @@ export class GoogleMatchService {
return new Set(rows.map((row) => row.domain));
}
- /**
- * Resolves participants to a company and contact, creating them when the
- * caller allows it and the guardrails pass.
- *
- * Returns `{ companyId: null, contactId: null }` when nothing matched and
- * nothing was created — the caller's cue to drop the item entirely rather
- * than store an unattached thread. Personal mail is never written.
- */
async resolve(
request: MatchRequest,
context: MatchContext,
@@ -145,8 +89,6 @@ export class GoogleMatchService {
return { companyId: null, contactId: null, external };
}
- // An exact contact match is the strongest signal there is — `Contact.email`
- // is unique, so this is the same person, not merely the same employer.
const contact = await this.db.contact.findFirst({
where: { email: { in: external.map((person) => person.email) } },
select: { id: true, companyId: true },
@@ -186,9 +128,6 @@ export class GoogleMatchService {
if (existing) {
return {
companyId: existing.id,
- // Known company, unknown person. Creating the contact is safe here
- // even without `allowCreate`: we already sell to them, and a thread
- // attributed to the company with no name against it is worse.
contactId: request.allowCreate
? await this.createContact(external, domain, existing.id, request)
: null,
@@ -203,14 +142,6 @@ export class GoogleMatchService {
return this.create(external, domain, request);
}
- /**
- * Creates the company and the contact behind a domain we have never seen.
- *
- * The company comes from `CompanyDirectoryService.companyForEmail`, which
- * normalises the domain, upserts against the unique index and tells the
- * agent a bare company exists — so an auto-created company arrives with a
- * logo and an industry a few seconds later, exactly like one typed by a rep.
- */
private async create(
external: Participant[],
domain: string,
@@ -226,8 +157,6 @@ export class GoogleMatchService {
ownerId: request.ownerId,
});
if (!companyId) {
- // Not a work domain, so there is nothing to file this against. Not an
- // error, and not a reason to invent a company row.
return { companyId: null, contactId: null, external };
}
@@ -262,7 +191,6 @@ export class GoogleMatchService {
return { companyId, contactId, external };
}
- /** Upserts the person on the domain, so a re-sync does not duplicate them. */
private async createContact(
external: Participant[],
domain: string,
@@ -276,8 +204,6 @@ export class GoogleMatchService {
const { firstName, lastName } = splitName(person.name, person.email);
- // `Contact.email` is unique, so this is the race-safe form: two reps'
- // syncs hitting the same new person resolve to one row.
const existing = await this.db.contact.findUnique({
where: { email: person.email },
select: { id: true },
@@ -293,7 +219,6 @@ export class GoogleMatchService {
source: request.source,
ownerId: request.ownerId,
},
- // Never overwrite a human's edits with a header's display name.
update: {},
select: { id: true, firstName: true, lastName: true },
});
@@ -308,11 +233,6 @@ export class GoogleMatchService {
});
}
- // Google hands back an attendee with no `displayName` far more often than
- // it hands back one with a name, so a contact is routinely created from the
- // address alone and then met again later with a real name attached. Taking
- // the better name when it arrives is the difference between "Pmarchetti" and
- // "Paula Marchetti" — but only over a name nobody has improved on.
const hasRealName = Boolean(person.name?.trim());
const isPlaceholder = isDerivedName(
person.email,
@@ -328,9 +248,6 @@ export class GoogleMatchService {
return contact.id;
}
- // Still only known by their address. Tell the agent; whether that is worth
- // a lookup, and how deep a one, is its call — this side no longer knows
- // what a sourced identity match costs or how it works.
if (isPlaceholder && !hasRealName) {
await this.agent.contactCreated(
contact.id,
diff --git a/apps/api/src/google/google-sync.service.ts b/apps/api/src/google/google-sync.service.ts
index 781b3366..7e284983 100644
--- a/apps/api/src/google/google-sync.service.ts
+++ b/apps/api/src/google/google-sync.service.ts
@@ -5,14 +5,6 @@ import type { SyncSource } from "./google.constants";
import { GoogleConnectionService } from "./google-connection.service";
import { SyncStateService } from "./sync-state.service";
-/**
- * How long a tick may run.
- *
- * Vercel's default function timeout is generous, but a cron that runs every five
- * minutes must finish well inside five minutes or ticks overlap. The budget is
- * checked between accounts, so one slow mailbox delays the next tick rather
- * than being cut off mid-write.
- */
const TICK_BUDGET_MS = 60_000;
export type TickSummary = {
@@ -23,15 +15,6 @@ export type TickSummary = {
durationMs: number;
};
-/**
- * Runs the due syncs.
- *
- * Deliberately not the in-process `EnrichmentQueue`: that queue drops queued
- * work on shutdown, which is right for enrichment (the company stays PENDING
- * and the next re-enrich picks it up) and wrong here, because a dropped sync
- * silently leaves a gap in someone's timeline. State lives in Postgres and the
- * cron is the scheduler.
- */
@Injectable()
export class GoogleSyncService {
private readonly logger = new Logger(GoogleSyncService.name);
@@ -43,7 +26,6 @@ export class GoogleSyncService {
private readonly connections: GoogleConnectionService,
) {}
- /** One cron tick: every account that is due, until the budget runs out. */
async runDue(): Promise<TickSummary> {
const startedAt = Date.now();
const summary: TickSummary = {
@@ -54,8 +36,6 @@ export class GoogleSyncService {
durationMs: 0,
};
- // Pick up anyone who granted the scopes but has no sync row yet — a rep who
- // connected and closed the tab never triggers anything else.
await this.connections.reconcileAll();
const due = await this.state.due(new Date());
@@ -86,7 +66,6 @@ export class GoogleSyncService {
}
} catch (error) {
summary.failed += 1;
- // One account's crash must not abandon the rest of the tick.
await this.state.markFailed(
row.id,
error instanceof Error ? error.message : String(error),
@@ -116,7 +95,6 @@ export class GoogleSyncService {
return summary;
}
- /** One account, one source. Also the path `google.syncNow` takes. */
async runOne(userId: string, source: SyncSource) {
const row = await this.state.get(userId, source);
if (!row) return null;
@@ -126,7 +104,6 @@ export class GoogleSyncService {
: this.gmail.sync(row);
}
- /** Every source for one user, for the "Sync now" button. */
async runForUser(userId: string): Promise<void> {
for (const source of ["calendar", "gmail"] as const) {
await this.runOne(userId, source);
diff --git a/apps/api/src/google/google-token.service.ts b/apps/api/src/google/google-token.service.ts
index b4b67714..f2442be5 100644
--- a/apps/api/src/google/google-token.service.ts
+++ b/apps/api/src/google/google-token.service.ts
@@ -8,29 +8,18 @@ import {
type SyncSource,
} from "./google.constants";
-/** Why a token could not be produced. Callers branch on this, not on a string. */
export type TokenFailure =
- /** No refresh token, or Google rejected it. The rep has to reconnect. */
| { outcome: "needs-reconnect"; reason: string }
- /** The grant never included this scope. Not an error — just not connected. */
| { outcome: "not-connected"; reason: string };
export type TokenResult = { outcome: "ok"; accessToken: string } | TokenFailure;
-/**
- * The only place an access token is obtained.
- *
- * Nothing reads `Account.accessToken` directly: Better Auth's `getAccessToken`
- * refreshes an expired token and persists the new one, so a hand-rolled refresh
- * would be a second, worse implementation of the same thing racing the first.
- */
@Injectable()
export class GoogleTokenService {
private readonly logger = new Logger(GoogleTokenService.name);
constructor(@InjectDatabase() private readonly db: Db) {}
- /** The scopes Google has actually granted this user, from the account row. */
async grantedScopes(userId: string): Promise<string[]> {
const account = await this.db.account.findFirst({
where: { userId, providerId: GOOGLE_PROVIDER_ID },
@@ -45,20 +34,11 @@ export class GoogleTokenService {
);
}
- /** Whether the grant covers a source. The grant *is* the connection state. */
async isConnected(userId: string, source: SyncSource): Promise<boolean> {
const scopes = await this.grantedScopes(userId);
return scopes.includes(SCOPE_FOR_SOURCE[source]);
}
- /**
- * Whether Google issued a refresh token for this grant.
- *
- * Google only returns one when it re-prompts. If a reconnect slipped through
- * without a prompt there is no refresh token, and everything works until the
- * access token expires an hour later — so the connect flow checks this
- * immediately rather than discovering it on the first cron tick.
- */
async hasRefreshToken(userId: string): Promise<boolean> {
const account = await this.db.account.findFirst({
where: { userId, providerId: GOOGLE_PROVIDER_ID },
@@ -68,12 +48,6 @@ export class GoogleTokenService {
return Boolean(account?.refreshToken);
}
- /**
- * A valid access token for a source, or why there isn't one.
- *
- * Returns a result rather than throwing: "this rep never connected Gmail" is
- * an ordinary state for a cron tick iterating every user, not an exception.
- */
async accessTokenFor(
userId: string,
source: SyncSource,
@@ -99,9 +73,6 @@ export class GoogleTokenService {
return { outcome: "ok", accessToken };
} catch (error) {
- // A refresh failure means the refresh token is gone — revoked, expired
- // or never issued. Retrying cannot fix it, so this is terminal until
- // the rep reconnects.
this.logger.warn({
message: "Google token refresh failed",
userId,
@@ -116,13 +87,6 @@ export class GoogleTokenService {
}
}
- /**
- * Revokes the grant at Google.
- *
- * This kills the *whole* grant, sign-in included, because one OAuth client
- * means one grant per user. It is deliberately not what the disconnect button
- * calls — see `GoogleConnectionService.disconnect`.
- */
async revoke(userId: string): Promise<boolean> {
const account = await this.db.account.findFirst({
where: { userId, providerId: GOOGLE_PROVIDER_ID },
@@ -147,8 +111,6 @@ export class GoogleTokenService {
return false;
}
- // The stored tokens are dead now; clearing them stops every later call
- // from trying to use them and getting a confusing 401.
await this.db.account.updateMany({
where: { userId, providerId: GOOGLE_PROVIDER_ID },
data: {
diff --git a/apps/api/src/google/google.constants.ts b/apps/api/src/google/google.constants.ts
index cdd3b688..f8dc2087 100644
--- a/apps/api/src/google/google.constants.ts
+++ b/apps/api/src/google/google.constants.ts
@@ -1,25 +1,13 @@
import { CALENDAR_SCOPE, GMAIL_SCOPE } from "@crm/auth";
-/**
- * The scope strings come from `@crm/auth`, which is where the OAuth request is
- * actually made. Re-declaring them here would be two lists that drift, and the
- * failure is silent: the grant looks right and `isConnected()` says no.
- */
export { CALENDAR_SCOPE, GMAIL_SCOPE, SYNC_SCOPES } from "@crm/auth";
-/**
- * The two sources sync independently: they have separate cursors, separate
- * failure modes and separate auto-create rules, so they get separate
- * `MailboxSync` rows rather than one row with two of everything.
- */
export const SYNC_SOURCES = ["calendar", "gmail"] as const;
export type SyncSource = (typeof SYNC_SOURCES)[number];
-/** Which scope has to be granted for a source to be syncable. */
export const SCOPE_FOR_SOURCE: Record<SyncSource, string> = {
calendar: CALENDAR_SCOPE,
gmail: GMAIL_SCOPE,
};
-/** Better Auth's provider id. One provider, one grant — see the plan §3.4. */
export const GOOGLE_PROVIDER_ID = "google";
diff --git a/apps/api/src/google/google.contracts.ts b/apps/api/src/google/google.contracts.ts
index bcdc31c3..f6b27626 100644
--- a/apps/api/src/google/google.contracts.ts
+++ b/apps/api/src/google/google.contracts.ts
@@ -13,7 +13,6 @@ export const setAutoCreateInput = z.object({
export const suppressDomainInput = z.object({
domain: z.string().trim().min(1),
reason: z.string().trim().max(200).optional(),
- /** Also remove the threads and events this domain already produced. */
purge: z.boolean().default(true),
});
diff --git a/apps/api/src/google/google.module.ts b/apps/api/src/google/google.module.ts
index 44a84b83..c9ba6c54 100644
--- a/apps/api/src/google/google.module.ts
+++ b/apps/api/src/google/google.module.ts
@@ -16,14 +16,6 @@ import { GoogleTokenService } from "./google-token.service";
import { SyncController } from "./sync.controller";
import { SyncStateService } from "./sync-state.service";
-/**
- * Gmail and Calendar.
- *
- * Depends on `CompaniesModule` for `companyForEmail` — turning a work address
- * into a found-or-created company — and on `AgentModule` to say that a contact
- * arrived with nothing but an address. Neither of those is enrichment: this
- * module reports what the sync saw and lets the agent decide what it means.
- */
@Module({
imports: [TrpcModule, AgentModule, CompaniesModule],
controllers: [SyncController],
diff --git a/apps/api/src/google/google.router.ts b/apps/api/src/google/google.router.ts
index b7061309..b16cf15d 100644
--- a/apps/api/src/google/google.router.ts
+++ b/apps/api/src/google/google.router.ts
@@ -20,13 +20,6 @@ import {
import { GoogleConnectionService } from "./google-connection.service";
import { GoogleSyncService } from "./google-sync.service";
-/**
- * The Google integration's data surface.
- *
- * Connecting is absent on purpose: the browser calls `authClient.linkSocial()`
- * directly, and `status` reads the result off the granted scopes. A procedure
- * here would only be a second way to describe the same grant.
- */
@Router({ alias: "google" })
@UseMiddlewares(AuthMiddleware)
export class GoogleRouter {
@@ -43,18 +36,11 @@ export class GoogleRouter {
return this.connection.status(ctx.user.id);
}
- /**
- * Deletes what this mailbox put into the CRM and re-imports it.
- *
- * Not a disconnect: syncing is a condition of having an account, so there is
- * no state where a signed-in rep is not syncing. `revokeAccess` is the exit.
- */
@Mutation()
async purgeSyncedData(@Ctx() ctx: AuthedTrpcContext) {
return this.connection.purgeSyncedData(ctx.user.id);
}
- /** Hard revoke. Ends sign-in access too — the UI confirms before calling it. */
@Mutation()
async revokeAccess(@Ctx() ctx: AuthedTrpcContext) {
return this.connection.revoke(ctx.user.id);
@@ -87,7 +73,6 @@ export class GoogleRouter {
});
}
- /** The messages behind a timeline entry. Only called when one is expanded. */
@Query({ input: threadInput })
async thread(@Input("threadId") threadId: string) {
return this.conversations.thread(threadId);
diff --git a/apps/api/src/google/mime.ts b/apps/api/src/google/mime.ts
index ffa084c8..ffa33af9 100644
--- a/apps/api/src/google/mime.ts
+++ b/apps/api/src/google/mime.ts
@@ -1,11 +1,3 @@
-/**
- * Turning a Gmail payload into something readable.
- *
- * All pure: the awkward cases here (nested multiparts, quoted-printable, a
- * forty-message quote trail) are exactly what wants table-driven tests without
- * a network or a database.
- */
-
export type GmailHeader = { name?: string; value?: string };
export type GmailPart = {
@@ -16,7 +8,6 @@ export type GmailPart = {
parts?: GmailPart[];
};
-/** Case-insensitive header lookup — Gmail is inconsistent about casing. */
export function header(
headers: readonly GmailHeader[] | undefined,
name: string,
@@ -26,7 +17,6 @@ export function header(
return found?.value?.trim() ?? null;
}
-/** Gmail encodes every body as base64url, which `atob` will not accept. */
export function decodeBase64Url(data: string): string {
const normalised = data.replace(/-/g, "+").replace(/_/g, "/");
const padded = normalised.padEnd(
@@ -41,13 +31,6 @@ export function decodeBase64Url(data: string): string {
}
}
-/**
- * The plain-text body.
- *
- * Prefers `text/plain`; falls back to stripping tags out of `text/html`,
- * because plenty of senders ship HTML only and "(no body)" on the timeline is
- * useless. Attachments are skipped — v1 stores no bytes.
- */
export function plainTextBody(payload: GmailPart | undefined): string {
if (!payload) return "";
@@ -64,7 +47,6 @@ export function plainTextBody(payload: GmailPart | undefined): string {
return "";
}
-/** Depth-first search for a mime type, skipping attachment parts. */
function findPart(part: GmailPart, mimeType: string): GmailPart | null {
if (part.mimeType === mimeType && !part.filename && part.body?.data) {
return part;
@@ -95,24 +77,12 @@ export function stripHtml(html: string): string {
.trim();
}
-/**
- * Where the quoted history starts.
- *
- * A reply carries the entire conversation beneath it, so storing the raw body
- * would mean the same text N times over a thread and a timeline entry that is
- * mostly `>`. Each pattern is a line that begins the quote; everything from the
- * first match is dropped.
- */
const QUOTE_MARKERS: RegExp[] = [
- // "On Tue, 5 Aug 2025 at 14:02, Jane <[email protected]> wrote:"
/^\s*On .+ wrote:\s*$/m,
- // Outlook and most corporate clients.
/^\s*-{2,}\s*Original Message\s*-{2,}\s*$/im,
/^\s*_{5,}\s*$/m,
/^\s*From:\s.+$/m,
- // Apple Mail.
/^\s*Begin forwarded message:\s*$/im,
- // Gmail's own divider when the client collapses history.
/^\s*-{3,}\s*Forwarded message\s*-{3,}\s*$/im,
];
@@ -126,8 +96,6 @@ export function stripQuotedHistory(body: string): string {
let trimmed = body.slice(0, cut);
- // Whatever survives, drop trailing lines that are pure quote — some clients
- // interleave rather than appending.
const lines = trimmed.split("\n");
while (lines.length > 0 && /^\s*>/.test(lines[lines.length - 1] ?? "")) {
lines.pop();
@@ -137,17 +105,6 @@ export function stripQuotedHistory(body: string): string {
return trimmed.replace(/\n{3,}/g, "\n\n").trim();
}
-/**
- * The id of the conversation root, from the reply chain.
- *
- * `References` lists the ancestry oldest-first, so its first entry is the root.
- * Falling back to `In-Reply-To` handles clients that omit `References`, and
- * finally a message that starts a thread is its own root.
- *
- * This is what makes a thread global. Gmail's `threadId` is scoped to one
- * mailbox, so two reps on the same conversation report different ids for it —
- * keying on those would put one conversation on a company's timeline twice.
- */
export function rootMessageId(
headers: readonly GmailHeader[] | undefined,
): string | null {
@@ -166,12 +123,10 @@ export function rootMessageId(
return own ? normaliseMessageId(own) : null;
}
-/** Strips the angle brackets so `<a@b>` and `a@b` are the same identity. */
export function normaliseMessageId(value: string): string {
return value.trim().replace(/^</, "").replace(/>$/, "").toLowerCase();
}
-/** A short preview for the timeline row. Never the whole body. */
export function snippetOf(body: string, limit = 200): string | null {
const flat = body.replace(/\s+/g, " ").trim();
if (!flat) return null;
diff --git a/apps/api/src/google/participants.ts b/apps/api/src/google/participants.ts
index 88505425..ce3c506f 100644
--- a/apps/api/src/google/participants.ts
+++ b/apps/api/src/google/participants.ts
@@ -1,17 +1,10 @@
import { domainFromEmail } from "../companies/domain";
-/** One address off a header or an attendee list. */
export type Participant = {
email: string;
name: string | null;
};
-/**
- * Local parts that never belong to a person worth putting in a CRM.
- *
- * Matched as whole local parts or prefixes: `noreply@` and `no-reply-1234@`
- * are both machines, but `robert@` must not be caught by `bot`.
- */
const AUTOMATED_LOCAL_PARTS = [
"noreply",
"no-reply",
@@ -25,9 +18,6 @@ const AUTOMATED_LOCAL_PARTS = [
"bounces",
"auto-confirm",
"automated",
- // Scheduling tools send the invite from their own address and put the
- // organiser's name in the display name, so without these you get a contact
- // called "Grand Ventures" whose email is [email protected].
"calendar-invite",
"calendar",
"invite",
@@ -49,14 +39,6 @@ const AUTOMATED_LOCAL_PARTS = [
"team",
];
-/**
- * Parses one address out of a mail header.
- *
- * Handles the three shapes Gmail actually returns: `[email protected]`,
- * `Name <[email protected]>`, and `"Last, First" <[email protected]>`. Anything else yields null
- * rather than a half-parsed address, because a junk `fromEmail` is worse than a
- * dropped one — it becomes a contact.
- */
export function parseAddress(input: string): Participant | null {
const trimmed = input.trim();
if (!trimmed) return null;
@@ -67,14 +49,11 @@ export function parseAddress(input: string): Participant | null {
if (!isEmailish(rawEmail)) return null;
const rawName = angled?.[1]?.trim() ?? "";
- // Display names arrive quoted more often than not, and the quotes are not
- // part of anybody's name.
const name = rawName.replace(/^"(.*)"$/, "$1").trim();
return { email: rawEmail, name: name || null };
}
-/** Splits a header that may carry several comma-separated addresses. */
export function parseAddressList(
header: string | null | undefined,
): Participant[] {
@@ -85,8 +64,6 @@ export function parseAddressList(
let inQuotes = false;
let inAngles = false;
- // Not a plain `split(",")`: `"Last, First" <[email protected]>` contains a comma that
- // is not a separator, and splitting on it produces two broken addresses.
for (const char of header) {
if (char === '"') inQuotes = !inQuotes;
if (char === "<") inAngles = true;
@@ -114,7 +91,6 @@ export function parseAddressList(
return participants;
}
-/** Whether an address is a machine rather than a person. */
export function isAutomatedAddress(email: string): boolean {
const local = email.split("@")[0]?.toLowerCase() ?? "";
if (!local) return true;
@@ -128,14 +104,6 @@ export function isAutomatedAddress(email: string): boolean {
);
}
-/**
- * Whether a name looks like it was derived from the address rather than given.
- *
- * `splitName` is deterministic, so a stored name that matches exactly what it
- * would produce from the email alone is a placeholder nobody has improved on.
- * That is the licence to overwrite it when a real display name turns up — and
- * the guarantee that a name a human typed is never touched.
- */
export function isDerivedName(
email: string,
firstName: string,
@@ -147,32 +115,16 @@ export function isDerivedName(
);
}
-/** A bare, lowercased hostname, or null for a free host or a malformed address. */
export function workDomain(email: string): string | null {
return domainFromEmail(email);
}
export type ExternalFilterOptions = {
- /**
- * Our own domains — everyone on one is "us", not a lead.
- *
- * A set rather than a single domain: derived from the `User` table, so a team
- * spread across two domains is handled without configuration.
- */
ourDomains: ReadonlySet<string>;
- /** Every address that belongs to a CRM user, for multi-domain teams. */
ourAddresses: ReadonlySet<string>;
- /** Domains a human has marked "not a customer". */
suppressedDomains: ReadonlySet<string>;
};
-/**
- * The external side of a conversation.
- *
- * Drops our own people, machines, free hosts and suppressed domains, in that
- * order. What survives is the set of addresses that could plausibly identify a
- * company we sell to.
- */
export function externalParticipants(
participants: readonly Participant[],
options: ExternalFilterOptions,
@@ -181,8 +133,6 @@ export function externalParticipants(
if (options.ourAddresses.has(participant.email)) return false;
const domain = workDomain(participant.email);
- // `workDomain` already returns null for gmail.com and friends, which is
- // what keeps a lead's personal address from becoming a "Gmail" company.
if (!domain) return false;
if (options.ourDomains.has(domain)) return false;
if (options.suppressedDomains.has(domain)) return false;
@@ -192,14 +142,6 @@ export function externalParticipants(
});
}
-/**
- * The domain a thread or an event is really about.
- *
- * A customer call often has their lawyer or their auditor on it, so the most
- * represented domain wins. `preferKnown` lets the caller break ties with
- * "whichever of these we already have a company for", which is almost always
- * the right answer and is why it is passed in rather than guessed here.
- */
export function dominantDomain(
participants: readonly Participant[],
preferKnown: ReadonlySet<string> = new Set(),
@@ -218,8 +160,6 @@ export function dominantDomain(
let bestScore = -1;
for (const [domain, count] of counts) {
- // A known company outranks a stranger with the same headcount on the
- // thread; otherwise a single cc'd lawyer could steal the match.
const score = count * 2 + (preferKnown.has(domain) ? 1 : 0);
if (score > bestScore) {
best = domain;
@@ -230,14 +170,6 @@ export function dominantDomain(
return best;
}
-/**
- * Splits a display name into first and last.
- *
- * Everything after the first token is the surname, which is wrong for a
- * minority of names and right for the overwhelming majority — and a contact
- * whose surname reads "van der Berg" is fixable in one edit, whereas no name at
- * all is a row nobody recognises.
- */
export function splitName(
name: string | null,
email: string,
@@ -245,7 +177,6 @@ export function splitName(
const cleaned = name?.trim().replace(/\s+/g, " ") ?? "";
if (cleaned && !cleaned.includes("@")) {
- // "Last, First" is how a lot of corporate directories render it.
const comma = cleaned.match(/^([^,]+),\s*(.+)$/);
if (comma?.[1] && comma[2]) {
return { firstName: comma[2].trim(), lastName: comma[1].trim() };
@@ -260,8 +191,6 @@ export function splitName(
}
}
- // No usable display name: the local part is the least-bad label, tidied so
- // "jane.doe" reads as "Jane Doe" rather than as a slug.
const local = email.split("@")[0] ?? email;
const words = local
.split(/[._-]+/)
diff --git a/apps/api/src/google/sync-state.service.ts b/apps/api/src/google/sync-state.service.ts
index beb54b4d..37cb924f 100644
--- a/apps/api/src/google/sync-state.service.ts
+++ b/apps/api/src/google/sync-state.service.ts
@@ -7,13 +7,6 @@ import { Injectable, Logger } from "@nestjs/common";
import { InjectDatabase } from "../database/database.constants";
import type { SyncSource } from "./google.constants";
-/**
- * The cursor store.
- *
- * Every mutation a sync makes to its own bookkeeping goes through here, so
- * "what state can a sync row be in" is answerable by reading one file rather
- * than by grepping two sync services for `update`.
- */
@Injectable()
export class SyncStateService {
private readonly logger = new Logger(SyncStateService.name);
@@ -30,26 +23,16 @@ export class SyncStateService {
return this.db.mailboxSync.findMany({ where: { userId } });
}
- /**
- * The rows a cron tick should attempt.
- *
- * Excludes `NEEDS_RECONNECT` — that state is terminal until a human acts, and
- * retrying it every five minutes would be a pointless call to Google forever.
- * Also excludes anything inside its rate-limit backoff.
- */
async due(now: Date): Promise<MailboxSync[]> {
return this.db.mailboxSync.findMany({
where: {
status: { notIn: [GoogleSyncStatus.NEEDS_RECONNECT] },
OR: [{ retryAfter: null }, { retryAfter: { lte: now } }],
},
- // Least-recently-synced first, so one busy mailbox cannot starve the
- // rest when a tick runs out of budget. A never-synced row sorts first.
orderBy: [{ lastSyncedAt: { sort: "asc", nulls: "first" } }],
});
}
- /** Creates the row when a source is first connected. Idempotent. */
async ensure(
userId: string,
source: SyncSource,
@@ -60,14 +43,9 @@ export class SyncStateService {
create: {
userId,
source,
- // No cursor yet. The first pass records where "now" is and imports
- // nothing — sync is forward-only.
status: GoogleSyncStatus.IDLE,
autoCreate: options.autoCreate,
},
- // Reconnecting keeps the cursor: re-consenting must not rewind a
- // mailbox. It *does* clear the error and lift a NEEDS_RECONNECT, which
- // is the whole point of reconnecting.
update: {
status: GoogleSyncStatus.IDLE,
lastError: null,
@@ -83,7 +61,6 @@ export class SyncStateService {
});
}
- /** A clean pass: advance the cursor, clear the error, stamp the time. */
async settle(
id: string,
update: {
@@ -102,13 +79,6 @@ export class SyncStateService {
});
}
- /**
- * The cursor is gone (Gmail 404 / Calendar 410).
- *
- * Drops it so the next pass starts from now. Forward-only means the gap is
- * not fetched — reaching here at all takes roughly a week of the sync not
- * running, so it is warned about rather than quietly healed.
- */
async clearCursor(id: string, reason: string): Promise<void> {
this.logger.warn({
message: "Sync cursor invalidated — resuming from now",
diff --git a/apps/api/src/google/sync.controller.ts b/apps/api/src/google/sync.controller.ts
index 7143181b..d092183d 100644
--- a/apps/api/src/google/sync.controller.ts
+++ b/apps/api/src/google/sync.controller.ts
@@ -12,13 +12,6 @@ import { AllowAnonymous } from "@thallesp/nestjs-better-auth";
import type { EnvironmentVariables } from "../config/env.validation";
import { GoogleSyncService } from "./google-sync.service";
-/**
- * The cron entrypoint.
- *
- * One of the few non-tRPC surfaces, alongside `/health` and Better Auth: no
- * user makes this request, so there is no session to authenticate and the tRPC
- * auth middleware has nothing to check. `CRON_SECRET` is the guard instead.
- */
@Controller("internal/sync")
export class SyncController {
private readonly logger = new Logger(SyncController.name);
@@ -31,28 +24,12 @@ export class SyncController {
this.secret = config.get("CRON_SECRET", { infer: true });
}
- /**
- * `GET`, because Vercel Cron only issues `GET`.
- *
- * This route was `POST`-only, and the scheduler dutifully called it every
- * five minutes and got a 404 every time — a sync that looked configured,
- * logged nothing alarming, and never ran.
- *
- * Two handlers rather than two decorators on one: Nest keeps only the last
- * HTTP-method decorator applied to a method, so stacking them silently
- * registers one verb and drops the other. That is how this was broken in
- * the first place, and it would have been broken the same way again.
- *
- * A `GET` that performs work is not REST, but the method is not the guard
- * here — `CRON_SECRET` is, and both paths run the identical check.
- */
@Get("google")
@AllowAnonymous()
async googleViaGet(@Headers("authorization") authorization?: string) {
return this.google(authorization);
}
- /** The same thing, for anything calling it by hand. */
@Post("google")
@AllowAnonymous()
async googleViaPost(@Headers("authorization") authorization?: string) {
@@ -60,11 +37,6 @@ export class SyncController {
}
private async google(authorization?: string) {
- // No secret configured means the route is open, which is worse than it
- // being unavailable. Fail closed. This is the only thing gating the sync —
- // there is no feature flag, because mailbox access is a condition of
- // signing in and a switch that can disable a mandatory feature is a switch
- // that is only ever wrong.
if (!this.secret) {
this.logger.error({
message: "CRON_SECRET is not set — refusing to run the sync route.",
@@ -80,12 +52,6 @@ export class SyncController {
}
}
-/**
- * Constant-time string comparison.
- *
- * A `===` on a shared secret leaks its prefix through response timing. The
- * length check up front is fine to leak — it is the content that matters.
- */
function timingSafeEquals(a: string, b: string): boolean {
if (a.length !== b.length) return false;
diff --git a/apps/api/src/health/health.controller.ts b/apps/api/src/health/health.controller.ts
index 4e05a822..a9764222 100644
--- a/apps/api/src/health/health.controller.ts
+++ b/apps/api/src/health/health.controller.ts
@@ -8,7 +8,6 @@ import {
import { AllowAnonymous } from "@thallesp/nestjs-better-auth";
import { InjectDatabase } from "../database/database.constants";
-/** A `SELECT 1` slower than this means the pool or the network is in trouble. */
const SLOW_PROBE_MS = 250;
@Controller("health")
@@ -27,8 +26,6 @@ export class HealthController {
} catch (error) {
this.logger.error(
{ message: "Database health check failed" },
- // Passed as the stack argument: handing Nest the error object
- // instead prints it as a second message and drops the trace.
error instanceof Error ? error.stack : String(error),
);
throw new ServiceUnavailableException({
diff --git a/apps/api/src/logging/all-exceptions.filter.ts b/apps/api/src/logging/all-exceptions.filter.ts
index 7f2cc088..7e987a0a 100644
--- a/apps/api/src/logging/all-exceptions.filter.ts
+++ b/apps/api/src/logging/all-exceptions.filter.ts
@@ -9,14 +9,6 @@ import {
import type { Request, Response } from "express";
import { getRequestContext } from "./request-context";
-/**
- * Logs every exception with its request context and returns a consistent body.
- *
- * Nest's built-in filter logs unhandled errors, but without the request id —
- * which is the one field that makes a production stack trace actionable. The
- * response shape is left alone apart from `requestId`, so an operator can quote
- * the id from a failed call and land on the exact log line.
- */
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
private readonly logger = new Logger("ExceptionsHandler");
@@ -38,8 +30,6 @@ export class AllExceptionsFilter implements ExceptionFilter {
this.log(exception, status, request);
- // A streamed or already-committed response can only be logged, not
- // rewritten.
if (response.headersSent) {
return;
}
@@ -64,8 +54,6 @@ export class AllExceptionsFilter implements ExceptionFilter {
return;
}
- // The access log already records 4xx as a warning; this adds the reason
- // for anyone who turns debug on, without doubling up in production.
this.logger.debug(payload);
}
}
@@ -86,8 +74,6 @@ function body(
const withRequestId = requestId ? { requestId } : {};
if (!(exception instanceof HttpException)) {
- // Never let an unexpected error's message reach the client: it is the
- // classic way internals leak. The log has the detail.
return {
statusCode: status,
message: "Internal server error",
diff --git a/apps/api/src/logging/context-logger.ts b/apps/api/src/logging/context-logger.ts
index 8ebaff8b..b3030e39 100644
--- a/apps/api/src/logging/context-logger.ts
+++ b/apps/api/src/logging/context-logger.ts
@@ -17,11 +17,6 @@ const DEVELOPMENT_LEVELS: LogLevel[] = [
"verbose",
];
-/**
- * Format and level follow `NODE_ENV` rather than having env vars of their own:
- * JSON at `log` and above in production, colourised with `debug`/`verbose`
- * locally. Read live, not captured at import, so tests can flip it.
- */
function consoleLoggerOptions(): ConsoleLoggerOptions {
const isProduction = process.env.NODE_ENV === "production";
@@ -33,17 +28,8 @@ function consoleLoggerOptions(): ConsoleLoggerOptions {
};
}
-/**
- * A log line with fields attached: `logger.log({ message: "Cache miss", userId })`.
- *
- * Nest treats extra arguments as separate messages and prints one line each, so
- * structured data has to arrive as a single object rather than a second
- * argument. Fields are hoisted to the top level in JSON and rendered after the
- * text in development.
- */
type StructuredMessage = { message: string } & Record<string, unknown>;
-/** What `ConsoleLogger` emits in JSON mode, plus our correlation fields. */
interface JsonLogRecord {
level: LogLevel;
pid: number;
@@ -55,15 +41,6 @@ interface JsonLogRecord {
userId?: string;
}
-/**
- * The application logger: `ConsoleLogger` with the current request stitched in,
- * so a line logged deep inside a service can still be traced back to the call
- * that caused it.
- *
- * Singleton, not request-scoped — the request data comes from
- * `AsyncLocalStorage`, so there is no reason to pay for a logger instance, and
- * a fresh dependency graph, per request.
- */
@Injectable()
export class ContextLogger extends ConsoleLogger {
constructor() {
@@ -82,8 +59,6 @@ export class ContextLogger extends ConsoleLogger {
const base = super.getJsonLogObject(message, options);
const request = getRequestContext();
- // Base keys win over caller-supplied fields: a stray `level` in a log
- // payload must not be able to relabel the line.
const record: JsonLogRecord = isStructuredMessage(message)
? { ...withoutMessage(message), ...base, message: message.message }
: base;
@@ -99,7 +74,6 @@ export class ContextLogger extends ConsoleLogger {
};
}
- /** Renders `{ message, ...fields }` as `text { fields }` instead of Nest's `Object(n) {…}`. */
protected override stringifyMessage(
message: unknown,
logLevel: LogLevel,
@@ -116,10 +90,6 @@ export class ContextLogger extends ConsoleLogger {
: `${text} ${inspect(fields, this.inspectOptions)}`;
}
- /**
- * The pretty path has no field to put a request id in, so it rides along
- * inside the context bracket: `[AuthService 3f9c1a2b]`.
- */
protected override formatContext(context: string): string {
const request = getRequestContext();
@@ -131,7 +101,6 @@ export class ContextLogger extends ConsoleLogger {
}
}
-/** Enough of a UUID to eyeball-match lines in a local terminal. */
function shortId(requestId: string): string {
return requestId.slice(0, 8);
}
diff --git a/apps/api/src/logging/logging.module.ts b/apps/api/src/logging/logging.module.ts
index 4282ec35..5cdb21aa 100644
--- a/apps/api/src/logging/logging.module.ts
+++ b/apps/api/src/logging/logging.module.ts
@@ -12,12 +12,6 @@ import { PrismaLogBridge } from "./prisma-log.bridge";
import { RequestLoggerMiddleware } from "./request-logger.middleware";
import { UserContextInterceptor } from "./user-context.interceptor";
-/**
- * Import this first in `AppModule`. Middleware runs in module-registration
- * order, and the request context has to be open before anything else — Better
- * Auth mounts its handler from `configure()` too, and a request that terminates
- * there would otherwise go unlogged.
- */
@Global()
@Module({
providers: [
@@ -32,7 +26,6 @@ export class LoggingModule implements NestModule {
configure(consumer: MiddlewareConsumer): void {
consumer
.apply(RequestLoggerMiddleware)
- // Express 5 requires named wildcards; the braces also match `/`.
.forRoutes({ path: "{*splat}", method: RequestMethod.ALL });
}
}
diff --git a/apps/api/src/logging/prisma-log.bridge.ts b/apps/api/src/logging/prisma-log.bridge.ts
index f786e650..3a0b9508 100644
--- a/apps/api/src/logging/prisma-log.bridge.ts
+++ b/apps/api/src/logging/prisma-log.bridge.ts
@@ -6,11 +6,6 @@ import {
type OnModuleInit,
} from "@nestjs/common";
-/**
- * Routes Prisma engine logs through the application logger, so a database
- * warning is formatted like everything else and carries the request that
- * triggered it.
- */
@Injectable()
export class PrismaLogBridge implements OnModuleInit, OnApplicationShutdown {
private readonly logger = new Logger("Prisma");
@@ -33,15 +28,11 @@ export class PrismaLogBridge implements OnModuleInit, OnApplicationShutdown {
return;
}
- // `query` and `info` only fire when PRISMA_LOG_QUERIES is set, and are
- // debug-level so they stay out of production logs even then.
this.logger.debug(payload);
});
}
onApplicationShutdown(): void {
- // The Prisma client outlives the Nest app during a hot reload; leaving a
- // sink pointing at a torn-down logger would log into nothing.
setPrismaLogSink(null);
}
}
diff --git a/apps/api/src/logging/request-context.ts b/apps/api/src/logging/request-context.ts
index 418161e3..2049a959 100644
--- a/apps/api/src/logging/request-context.ts
+++ b/apps/api/src/logging/request-context.ts
@@ -1,9 +1,5 @@
import { AsyncLocalStorage } from "node:async_hooks";
-/**
- * The per-request facts every log line should carry. Kept deliberately small:
- * anything larger tends to become a second, untyped request object.
- */
export interface RequestContext {
requestId: string;
method: string;
@@ -13,7 +9,6 @@ export interface RequestContext {
const storage = new AsyncLocalStorage<RequestContext>();
-/** Runs `fn`, and everything it awaits, with `context` attached. */
export function runInRequestContext<T>(
context: RequestContext,
fn: () => T,
@@ -25,10 +20,6 @@ export function getRequestContext(): RequestContext | undefined {
return storage.getStore();
}
-/**
- * The user is only known once the auth guard has run, which is well after the
- * context is created — so it is filled in rather than passed in.
- */
export function setRequestUserId(userId: string): void {
const context = storage.getStore();
diff --git a/apps/api/src/logging/request-logger.middleware.ts b/apps/api/src/logging/request-logger.middleware.ts
index fdc4b2b7..699549fe 100644
--- a/apps/api/src/logging/request-logger.middleware.ts
+++ b/apps/api/src/logging/request-logger.middleware.ts
@@ -5,16 +5,8 @@ import { type RequestContext, runInRequestContext } from "./request-context";
const REQUEST_ID_HEADER = "x-request-id";
-/** Liveness probes are the loudest thing in the log and the least interesting. */
const QUIET_PATHS = new Set(["/health"]);
-/**
- * Opens the request context and writes one access line per request.
- *
- * Deliberately logs no headers, query string or body: this is a CRM, and all
- * three routinely carry credentials and personal data. Anything worth logging
- * from a payload should be logged explicitly by the handler that understands it.
- */
@Injectable()
export class RequestLoggerMiddleware implements NestMiddleware {
private readonly logger = new Logger("HTTP");
@@ -32,8 +24,6 @@ export class RequestLoggerMiddleware implements NestMiddleware {
runInRequestContext(context, () => {
response.on("finish", () => {
- // `finish` is emitted from the socket's async context rather than
- // ours, so the context is re-entered explicitly, not inherited.
runInRequestContext(context, () => {
this.logCompleted(request, response, context, startedAt);
});
@@ -52,8 +42,6 @@ export class RequestLoggerMiddleware implements NestMiddleware {
const durationMs = Number(process.hrtime.bigint() - startedAt) / 1_000_000;
const { statusCode } = response;
- // The auth guard resolves the session long after the context is opened,
- // so this is the first point at which the user is reliably known.
const userId = sessionUserId(request);
if (userId) {
@@ -89,15 +77,9 @@ export class RequestLoggerMiddleware implements NestMiddleware {
}
}
-/**
- * A proxy or upstream service may already have stamped the request; reusing its
- * id is what makes a trace span more than one hop.
- */
function incomingRequestId(request: Request): string | undefined {
const header = request.get(REQUEST_ID_HEADER);
- // Untrusted input that ends up in every log line for this request, so it is
- // length-capped and stripped of anything that could forge a second field.
if (!header || header.length > 200 || !/^[\w.:-]+$/.test(header)) {
return undefined;
}
@@ -107,14 +89,6 @@ function incomingRequestId(request: Request): string | undefined {
const sharedInstance = new RequestLoggerMiddleware();
-/**
- * Better Auth mounts its handler directly onto the HTTP adapter while its
- * module is being configured — before Nest applies anything registered through
- * `MiddlewareConsumer` — so `/api/auth/*` terminates before the class above
- * ever runs. Its `middleware` option is the supported way in, and it is only
- * invoked for requests Better Auth itself will handle, so nothing is logged
- * twice.
- */
export function logAuthRoute(
request: Request,
response: Response,
diff --git a/apps/api/src/logging/user-context.interceptor.ts b/apps/api/src/logging/user-context.interceptor.ts
index 49bc31c9..3283f1c7 100644
--- a/apps/api/src/logging/user-context.interceptor.ts
+++ b/apps/api/src/logging/user-context.interceptor.ts
@@ -8,13 +8,6 @@ import type { Request } from "express";
import type { Observable } from "rxjs";
import { setRequestUserId } from "./request-context";
-/**
- * Copies the authenticated user id into the request context once the auth guard
- * has resolved the session, so logs written by handlers and services carry it.
- *
- * Interceptors run after guards, which is the earliest point where
- * `request.session` is populated by `@thallesp/nestjs-better-auth`.
- */
@Injectable()
export class UserContextInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
diff --git a/apps/api/src/search/search.router.ts b/apps/api/src/search/search.router.ts
index b6507a61..1230a6d0 100644
--- a/apps/api/src/search/search.router.ts
+++ b/apps/api/src/search/search.router.ts
@@ -11,7 +11,6 @@ const quickInput = z.object({ q: z.string().default("") });
export class SearchRouter {
constructor(@Inject(SearchService) private readonly search: SearchService) {}
- /** Backs the ⌘K switcher. */
@Query({ input: quickInput })
async quick(@Input("q") q: string) {
return this.search.quick(q);
diff --git a/apps/api/src/search/search.service.ts b/apps/api/src/search/search.service.ts
index bed94e31..7a435dca 100644
--- a/apps/api/src/search/search.service.ts
+++ b/apps/api/src/search/search.service.ts
@@ -2,32 +2,23 @@ import type { Db } from "@crm/db";
import { Injectable } from "@nestjs/common";
import { InjectDatabase } from "../database/database.constants";
-/** One hit in the quick switcher. */
export type SearchHit = {
kind: "company" | "contact" | "deal";
id: string;
label: string;
- /** The line under the label — domain, company, whatever identifies it. */
detail: string | null;
iconUrl: string | null;
iconDarkUrl: string | null;
iconTone: string | null;
+ imageUrl: string | null;
};
-/** Per kind. Enough to be useful, few enough that the list stays scannable. */
const PER_KIND = 5;
@Injectable()
export class SearchService {
constructor(@InjectDatabase() private readonly db: Db) {}
- /**
- * Everything matching one query string, across the three objects.
- *
- * Three indexed `contains` queries in parallel rather than a union view: the
- * result has to be grouped by kind for the UI anyway, and this keeps each
- * one's ordering and fields its own business.
- */
async quick(q: string): Promise<{ hits: SearchHit[] }> {
const term = q.trim();
if (term.length < 2) return { hits: [] };
@@ -66,6 +57,7 @@ export class SearchService {
firstName: true,
lastName: true,
email: true,
+ imageUrl: true,
company: { select: { name: true } },
},
}),
@@ -99,6 +91,7 @@ export class SearchService {
iconUrl: company.iconUrl,
iconDarkUrl: company.iconDarkUrl,
iconTone: company.iconTone,
+ imageUrl: null,
}),
),
...contacts.map(
@@ -112,6 +105,7 @@ export class SearchService {
iconUrl: null,
iconDarkUrl: null,
iconTone: null,
+ imageUrl: contact.imageUrl,
}),
),
...deals.map(
@@ -123,6 +117,7 @@ export class SearchService {
iconUrl: deal.company.iconUrl,
iconDarkUrl: deal.company.iconDarkUrl,
iconTone: deal.company.iconTone,
+ imageUrl: null,
}),
),
],
diff --git a/apps/api/src/settings/model-catalog.service.ts b/apps/api/src/settings/model-catalog.service.ts
new file mode 100644
index 00000000..5f7c515d
--- /dev/null
+++ b/apps/api/src/settings/model-catalog.service.ts
@@ -0,0 +1,124 @@
+import { CACHE_MANAGER } from "@nestjs/cache-manager";
+import { Inject, Injectable, Logger } from "@nestjs/common";
+import type { Cache } from "cache-manager";
+
+const CATALOG_URL = "https://ai-gateway.vercel.sh/v1/models";
+
+const CATALOG_TTL_MS = 30 * 60_000;
+
+const CATALOG_KEY = "settings:model-catalog";
+
+const CATALOG_TIMEOUT_MS = 5_000;
+
+export interface CatalogModel {
+ id: string;
+ name: string;
+ provider: string;
+ contextWindowTokens: number;
+ pricing: { input: number; output: number } | null;
+}
+
+interface GatewayModel {
+ id?: unknown;
+ name?: unknown;
+ owned_by?: unknown;
+ type?: unknown;
+ tags?: unknown;
+ context_window?: unknown;
+ pricing?: { input?: unknown; output?: unknown } | null;
+}
+
+function rate(value: unknown): number | null {
+ const parsed = typeof value === "string" ? Number(value) : value;
+ return typeof parsed === "number" && Number.isFinite(parsed) ? parsed : null;
+}
+
+function usable(model: GatewayModel): boolean {
+ const tags = Array.isArray(model.tags) ? model.tags : [];
+ return (
+ typeof model.id === "string" &&
+ model.type === "language" &&
+ tags.includes("tool-use") &&
+ typeof model.context_window === "number"
+ );
+}
+
+@Injectable()
+export class ModelCatalogService {
+ private readonly logger = new Logger(ModelCatalogService.name);
+
+ constructor(@Inject(CACHE_MANAGER) private readonly cache: Cache) {}
+
+ async models(): Promise<CatalogModel[] | null> {
+ const cached = await this.cache.get<CatalogModel[]>(CATALOG_KEY);
+ if (cached) return cached;
+
+ const models = await this.fetchCatalog();
+ if (!models) return null;
+
+ await this.cache.set(CATALOG_KEY, models, CATALOG_TTL_MS);
+ return models;
+ }
+
+ async find(id: string): Promise<CatalogModel | null> {
+ const models = await this.models();
+ return models?.find((model) => model.id === id) ?? null;
+ }
+
+ private async fetchCatalog(): Promise<CatalogModel[] | null> {
+ try {
+ const response = await fetch(CATALOG_URL, {
+ headers: { accept: "application/json" },
+ signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS),
+ });
+
+ if (!response.ok) {
+ this.logger.warn({
+ message: "Model catalog request failed",
+ status: response.status,
+ });
+ return null;
+ }
+
+ const body = (await response.json()) as { data?: unknown };
+ const rows = Array.isArray(body.data)
+ ? (body.data as GatewayModel[])
+ : [];
+
+ const models = rows.filter(usable).map((model): CatalogModel => {
+ const id = model.id as string;
+ const input = rate(model.pricing?.input);
+ const output = rate(model.pricing?.output);
+
+ return {
+ id,
+ name: typeof model.name === "string" && model.name ? model.name : id,
+ provider:
+ typeof model.owned_by === "string" && model.owned_by
+ ? model.owned_by
+ : (id.split("/")[0] ?? id),
+ contextWindowTokens: model.context_window as number,
+ pricing: input !== null && output !== null ? { input, output } : null,
+ };
+ });
+
+ models.sort(
+ (a, b) =>
+ a.provider.localeCompare(b.provider) || a.name.localeCompare(b.name),
+ );
+
+ this.logger.log({
+ message: "Model catalog loaded",
+ models: models.length,
+ });
+
+ return models;
+ } catch (error) {
+ this.logger.warn({
+ message: "Model catalog unavailable",
+ reason: error instanceof Error ? error.message : String(error),
+ });
+ return null;
+ }
+ }
+}
diff --git a/apps/api/src/settings/settings.contracts.ts b/apps/api/src/settings/settings.contracts.ts
new file mode 100644
index 00000000..d8c7a4c5
--- /dev/null
+++ b/apps/api/src/settings/settings.contracts.ts
@@ -0,0 +1,7 @@
+import { z } from "zod";
+
+export const setAgentModelInput = z.object({
+ modelId: z.string().trim().min(1).max(200).nullable(),
+});
+
+export type SetAgentModelInput = z.infer<typeof setAgentModelInput>;
diff --git a/apps/api/src/settings/settings.module.ts b/apps/api/src/settings/settings.module.ts
new file mode 100644
index 00000000..4465856f
--- /dev/null
+++ b/apps/api/src/settings/settings.module.ts
@@ -0,0 +1,12 @@
+import { Module } from "@nestjs/common";
+import { TrpcModule } from "../trpc/trpc.module";
+import { ModelCatalogService } from "./model-catalog.service";
+import { SettingsRouter } from "./settings.router";
+import { SettingsService } from "./settings.service";
+
+@Module({
+ imports: [TrpcModule],
+ providers: [ModelCatalogService, SettingsService, SettingsRouter],
+ exports: [SettingsService],
+})
+export class SettingsModule {}
diff --git a/apps/api/src/settings/settings.router.ts b/apps/api/src/settings/settings.router.ts
new file mode 100644
index 00000000..cdfc1681
--- /dev/null
+++ b/apps/api/src/settings/settings.router.ts
@@ -0,0 +1,29 @@
+import { Inject } from "@nestjs/common";
+import { Input, Mutation, Query, Router, UseMiddlewares } from "nestjs-trpc";
+import type { z } from "zod";
+import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";
+import { setAgentModelInput } from "./settings.contracts";
+import { SettingsService } from "./settings.service";
+
+@Router({ alias: "settings" })
+@UseMiddlewares(AuthMiddleware)
+export class SettingsRouter {
+ constructor(
+ @Inject(SettingsService) private readonly settings: SettingsService,
+ ) {}
+
+ @Query()
+ async agentModel() {
+ return this.settings.agentModel();
+ }
+
+ @Query()
+ async modelCatalog() {
+ return this.settings.modelCatalog();
+ }
+
+ @Mutation({ input: setAgentModelInput })
+ async setAgentModel(@Input() input: z.infer<typeof setAgentModelInput>) {
+ return this.settings.setAgentModel(input.modelId);
+ }
+}
diff --git a/apps/api/src/settings/settings.service.ts b/apps/api/src/settings/settings.service.ts
new file mode 100644
index 00000000..6e00825b
--- /dev/null
+++ b/apps/api/src/settings/settings.service.ts
@@ -0,0 +1,88 @@
+import type { Db } from "@crm/db";
+import {
+ DEFAULT_AGENT_MODEL,
+ readAgentModel,
+ writeAgentModel,
+} from "@crm/db/settings";
+import { BadRequestException, Injectable, Logger } from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+import {
+ type CatalogModel,
+ ModelCatalogService,
+} from "./model-catalog.service";
+
+export interface AgentModelSettings {
+ selectedId: string | null;
+ effectiveId: string;
+ defaultId: string;
+ effective: CatalogModel | null;
+ updatedAt: string | null;
+}
+
+export interface ModelCatalogResult {
+ models: CatalogModel[];
+ available: boolean;
+}
+
+@Injectable()
+export class SettingsService {
+ private readonly logger = new Logger(SettingsService.name);
+
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly catalog: ModelCatalogService,
+ ) {}
+
+ async agentModel(): Promise<AgentModelSettings> {
+ const [model, row] = await Promise.all([
+ readAgentModel(this.db),
+ this.db.appSetting.findFirst({ select: { updatedAt: true } }),
+ ]);
+
+ return {
+ selectedId: model.isDefault ? null : model.id,
+ effectiveId: model.id,
+ defaultId: DEFAULT_AGENT_MODEL.id,
+ effective: await this.catalog.find(model.id),
+ updatedAt: row?.updatedAt.toISOString() ?? null,
+ };
+ }
+
+ async setAgentModel(modelId: string | null): Promise<AgentModelSettings> {
+ if (modelId === null) {
+ await writeAgentModel(this.db, null);
+ this.logger.log({ message: "Agent model reset to the default" });
+ return this.agentModel();
+ }
+
+ const models = await this.catalog.models();
+
+ if (!models) {
+ throw new BadRequestException(
+ "Could not reach the AI Gateway to check that model. Try again in a moment.",
+ );
+ }
+
+ const chosen = models.find((model) => model.id === modelId);
+
+ if (!chosen) {
+ throw new BadRequestException(
+ `The AI Gateway does not serve a tool-using model called "${modelId}".`,
+ );
+ }
+
+ await writeAgentModel(this.db, {
+ id: chosen.id,
+ contextWindowTokens: chosen.contextWindowTokens,
+ });
+
+ this.logger.log({ message: "Agent model changed", modelId: chosen.id });
+
+ return this.agentModel();
+ }
+
+ async modelCatalog(): Promise<ModelCatalogResult> {
+ const models = await this.catalog.models();
+ return { models: models ?? [], available: models !== null };
+ }
+}
diff --git a/apps/api/src/trpc/context.types.ts b/apps/api/src/trpc/context.types.ts
index fb7029d2..39b4c9ff 100644
--- a/apps/api/src/trpc/context.types.ts
+++ b/apps/api/src/trpc/context.types.ts
@@ -6,7 +6,6 @@ export type BaseTrpcContext = {
session: Session | null;
};
-/** What every procedure behind `AuthMiddleware` sees. */
export type AuthedTrpcContext = BaseTrpcContext & {
user: SessionUser;
};
diff --git a/apps/api/src/trpc/list-input.ts b/apps/api/src/trpc/list-input.ts
index 1f16c6b2..e2b46fc9 100644
--- a/apps/api/src/trpc/list-input.ts
+++ b/apps/api/src/trpc/list-input.ts
@@ -1,12 +1,5 @@
import { z } from "zod";
-/**
- * The shape every list procedure speaks, so one `DataTable` on the front end can
- * drive companies, contacts and deals without per-module plumbing.
- *
- * Filtering, sorting and pagination all happen in Prisma — the browser never
- * receives more rows than it draws.
- */
export const listInput = z.object({
q: z.string().default(""),
sort: z.string().default(""),
@@ -17,7 +10,6 @@ export const listInput = z.object({
export type ListInput = z.infer<typeof listInput>;
-/** Facet id → value → number of rows that would match. */
type FacetCounts = Record<string, Record<string, number>>;
export type ListResult<TRow> = {
@@ -26,7 +18,6 @@ export type ListResult<TRow> = {
facetCounts: FacetCounts;
};
-/** `skip`/`take` for a 1-based page number. */
export function paginate(input: Pick<ListInput, "page" | "pageSize">): {
skip: number;
take: number;
@@ -37,14 +28,6 @@ export function paginate(input: Pick<ListInput, "page" | "pageSize">): {
};
}
-/**
- * Resolves the requested sort column against the columns a module actually
- * allows, so `?sort=` can never reach Prisma as an arbitrary field name.
- *
- * `orderBy` entries are spelled out per module rather than built from the
- * column id, because sorting by a relation (`company.name`) or an aggregate is
- * not a flat `{ [id]: dir }`.
- */
export function resolveOrderBy<TOrderBy>(
input: Pick<ListInput, "sort" | "dir">,
columns: Record<string, (dir: "asc" | "desc") => TOrderBy>,
@@ -54,12 +37,6 @@ export function resolveOrderBy<TOrderBy>(
return column ? column(input.dir) : fallback;
}
-/**
- * Turns a `groupBy` result into `{ value: count }`.
- *
- * Rows whose grouped value is null are dropped unless `nullKey` is given —
- * "unassigned" is a facet worth offering, "(blank industry)" usually is not.
- */
export function countsByKey<
TKey extends string,
TGroup extends { _count: { _all: number } } & {
@@ -77,18 +54,10 @@ export function countsByKey<
return counts;
}
-/** The facet value meaning "no filter". Every list procedure defaults to it. */
export const FACET_ALL = "all";
-/** The facet value meaning "nobody owns this". */
export const FACET_UNASSIGNED = "unassigned";
-/**
- * `ownerId` filter for an owner facet selection.
- *
- * Returns `undefined` for "all" so the caller can spread it into a `where`
- * without a branch.
- */
export function ownerFilter(
value: string,
): { ownerId: string | null } | undefined {
diff --git a/apps/api/src/trpc/middlewares/auth.middleware.ts b/apps/api/src/trpc/middlewares/auth.middleware.ts
index 1ef17869..a76be83b 100644
--- a/apps/api/src/trpc/middlewares/auth.middleware.ts
+++ b/apps/api/src/trpc/middlewares/auth.middleware.ts
@@ -8,10 +8,6 @@ import type {
import { setRequestUserId } from "../../logging/request-context";
import type { AuthedTrpcContext, BaseTrpcContext } from "../context.types";
-/**
- * Google sign-in is the only door, so "signed in" is the whole authorisation
- * model — there are no organizations, roles or permissions in this CRM.
- */
@Injectable()
export class AuthMiddleware implements TRPCMiddleware {
async use(opts: MiddlewareOptions): Promise<MiddlewareResponse> {
@@ -22,8 +18,6 @@ export class AuthMiddleware implements TRPCMiddleware {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
- // tRPC calls arrive as one HTTP request per batch, so the interceptor that
- // stamps `userId` for REST routes never runs. Stamp it here instead.
setRequestUserId(user.id);
const nextCtx: AuthedTrpcContext = { ...ctx, user };
diff --git a/apps/api/src/trpc/middlewares/domain-error.middleware.ts b/apps/api/src/trpc/middlewares/domain-error.middleware.ts
index 12b37f73..2b7bf7fb 100644
--- a/apps/api/src/trpc/middlewares/domain-error.middleware.ts
+++ b/apps/api/src/trpc/middlewares/domain-error.middleware.ts
@@ -34,11 +34,6 @@ function statusToTrpcCode(status: number): TrpcErrorCode {
}
}
-/**
- * Services throw Nest's `HttpException` family because they are also reachable
- * from REST controllers. Without this, a `NotFoundException` from a service
- * would reach the browser as a 500 with no message.
- */
@Injectable()
export class DomainErrorMiddleware implements TRPCMiddleware {
async use(opts: MiddlewareOptions): Promise<MiddlewareResponse> {
@@ -48,10 +43,6 @@ export class DomainErrorMiddleware implements TRPCMiddleware {
return result;
}
- // Read `error` off a widened alias rather than the narrowed union. The
- // `ok` discriminant narrows under this repo's tsconfig but not under the
- // one Vercel's Node builder compiles with, where `result.error` is a
- // deploy-breaking TS2339. The guard above already proved `ok` is false.
const failure = result as { error?: unknown };
const cause = (failure.error as { cause?: unknown } | undefined)?.cause;
diff --git a/apps/api/src/trpc/trpc.context.ts b/apps/api/src/trpc/trpc.context.ts
index bc351368..55ecc7a7 100644
--- a/apps/api/src/trpc/trpc.context.ts
+++ b/apps/api/src/trpc/trpc.context.ts
@@ -8,8 +8,6 @@ import type { BaseTrpcContext } from "./context.types";
export class TrpcContext implements TRPCContext {
async create(opts: ContextOptions): Promise<BaseTrpcContext> {
const req = "req" in opts ? opts.req : undefined;
- // A missing or expired cookie is an anonymous request, not an error —
- // `AuthMiddleware` is what turns that into UNAUTHORIZED.
const session = req
? await auth.api
.getSession({ headers: fromNodeHeaders(req.headers) })
diff --git a/apps/api/src/users/users.router.ts b/apps/api/src/users/users.router.ts
index 22f91d30..8a603433 100644
--- a/apps/api/src/users/users.router.ts
+++ b/apps/api/src/users/users.router.ts
@@ -13,16 +13,11 @@ export class UsersRouter {
@Inject(AuthService) private readonly auth: AuthService,
) {}
- /**
- * The signed-in user, read from the row rather than the session snapshot, so
- * a name or avatar change shows up without signing out.
- */
@Query()
async me(@Ctx() ctx: AuthedTrpcContext) {
return this.auth.getProfile(ctx.user.id);
}
- /** Owner pickers. */
@Query()
async list() {
return this.users.list();
diff --git a/apps/api/src/users/users.service.ts b/apps/api/src/users/users.service.ts
index e64ba9e2..68f62133 100644
--- a/apps/api/src/users/users.service.ts
+++ b/apps/api/src/users/users.service.ts
@@ -13,13 +13,6 @@ export interface UserOption {
export class UsersService {
constructor(@InjectDatabase() private readonly db: Db) {}
- /**
- * Everyone who can own a company, contact or deal.
- *
- * There are no roles here — a user row exists because someone signed in with
- * a Google account, and that is exactly the set of people work can be
- * assigned to.
- */
async list(): Promise<UserOption[]> {
return this.db.user.findMany({
select: { id: true, name: true, email: true, image: true },
diff --git a/apps/api/test/auth.e2e.spec.ts b/apps/api/test/auth.e2e.spec.ts
index 3b76990f..7d7292cf 100644
--- a/apps/api/test/auth.e2e.spec.ts
+++ b/apps/api/test/auth.e2e.spec.ts
@@ -3,18 +3,12 @@ import type { INestApplication } from "@nestjs/common";
import { Test, type TestingModule } from "@nestjs/testing";
import request from "supertest";
-/** Only fills a variable that is missing or blank — `.env` ships empty OAuth
- * placeholders, and an empty string still fails validation. */
const fallback = (key: string, value: string) => {
if (!process.env[key]) {
process.env[key] = value;
}
};
-// `ConfigModule.forRoot()` validates the environment while `AppModule` is being
-// evaluated, so these have to land before that module is imported — hence the
-// dynamic import below. Real values win; these only keep the suite runnable
-// somewhere without credentials, such as CI.
fallback(
"DATABASE_URL",
"postgresql://postgres:postgres@localhost:5432/crm?schema=public",
@@ -55,8 +49,6 @@ describe("Auth (e2e)", () => {
expect(response.body).toEqual({ authenticated: false, user: null });
});
- // Asserting the route is mounted rather than that it succeeds: Better Auth
- // stores rate limits in the database, so a 200 here needs a live Postgres.
it("mounts the Better Auth handler", async () => {
const response = await request(app.getHttpServer()).get("/api/auth/ok");
diff --git a/apps/api/test/conversations.spec.ts b/apps/api/test/conversations.spec.ts
index dbe741d1..8bc5bbb5 100644
--- a/apps/api/test/conversations.spec.ts
+++ b/apps/api/test/conversations.spec.ts
@@ -2,19 +2,10 @@ import { afterAll, beforeAll, describe, expect, it } from "bun:test";
import { db } from "@crm/db";
import { ConversationsService } from "../src/conversations/conversations.service";
-/**
- * A record's conversations, against a real database and a real cache.
- *
- * The cache is the part worth testing rather than asserting: a read-through
- * cache that never invalidates is indistinguishable from a working one until
- * somebody sends a second message and the panel does not show it.
- */
-
const suffix = process.env.TEST_RUN_ID ?? "conversations-spec";
const email = `conversation.subject.${suffix}@example.test`;
const userId = `user-${suffix}`;
-/** A minimal stand-in with the two methods the service uses. */
function memoryCache() {
const store = new Map<string, unknown>();
return {
@@ -94,7 +85,6 @@ describe("ConversationsService", () => {
sessionId: `ses_${suffix}_1`,
continuationToken: "eve:token-2",
streamIndex: 9,
- // A later save carries no title, and must not clear the one there.
messageCount: 4,
},
userId,
@@ -114,7 +104,6 @@ describe("ConversationsService", () => {
await service.list({ contactId }, userId);
expect(cache.store.size).toBe(1);
- // A write has to evict, or the panel shows yesterday's list.
await service.save(
{ contactId, sessionId: `ses_${suffix}_2`, messageCount: 1 },
userId,
diff --git a/apps/api/test/domain.spec.ts b/apps/api/test/domain.spec.ts
index 47b91f59..8ddf92fe 100644
--- a/apps/api/test/domain.spec.ts
+++ b/apps/api/test/domain.spec.ts
@@ -1,14 +1,6 @@
import { describe, expect, it } from "bun:test";
import { domainFromEmail, normalizeDomain } from "../src/companies/domain";
-/**
- * Domain parsing stayed on this side when enrichment left.
- *
- * It is not enrichment: turning " [email protected] " into `stripe.com` is
- * how the CRM decides which company row an address belongs to, and that
- * question has an answer without asking anybody anything.
- */
-
describe("normalizeDomain", () => {
it("reduces anything a human might type to the bare host", () => {
for (const input of [
@@ -46,8 +38,6 @@ describe("domainFromEmail", () => {
});
it("ignores free and malformed addresses", () => {
- // Creating a "Gmail" company from a personal address is the classic
- // CRM junk row.
for (const email of [
diff --git a/apps/api/test/google-api-client.spec.ts b/apps/api/test/google-api-client.spec.ts
index a4c14326..917b7ad3 100644
--- a/apps/api/test/google-api-client.spec.ts
+++ b/apps/api/test/google-api-client.spec.ts
@@ -7,7 +7,6 @@ afterEach(() => {
globalThis.fetch = realFetch;
});
-/** Stubs `fetch` with one canned response. */
function stub(
status: number,
body: unknown,
@@ -29,11 +28,6 @@ describe("GoogleApiClient", () => {
expect(await call()).toEqual({ outcome: "ok", data: { ok: true } });
});
- /**
- * The two cursor invalidations the whole sync design turns on. Both mean
- * "fall back to a bounded resync", not "something broke" — getting either
- * wrong stalls a mailbox silently.
- */
it("maps Gmail's 404 to cursor-invalid", async () => {
stub(404, { error: { message: "Requested entity was not found." } });
const result = await call();
@@ -62,8 +56,6 @@ describe("GoogleApiClient", () => {
});
it("treats a permission 403 as terminal", async () => {
- // The overloaded status: same code, opposite handling. A permission
- // failure retried every five minutes forever is a bug.
stub(403, { error: { message: "Insufficient Permission" } });
const result = await call();
diff --git a/apps/api/test/google-mime.spec.ts b/apps/api/test/google-mime.spec.ts
index 3779a0d8..b56cf52c 100644
--- a/apps/api/test/google-mime.spec.ts
+++ b/apps/api/test/google-mime.spec.ts
@@ -72,7 +72,6 @@ describe("plainTextBody", () => {
body: { data: encode("<p>Hello</p><p>World</p>") },
};
- // One newline per closing tag, not a blank line between paragraphs.
expect(plainTextBody(payload)).toBe("Hello\nWorld");
});
@@ -175,8 +174,6 @@ describe("rootMessageId", () => {
});
it("gives two mailboxes' copies of one conversation the same root", () => {
- // The whole point of keying on RFC headers rather than Gmail's threadId,
- // which differs per mailbox. Same conversation, two reps, one CRM thread.
const repA = [
{ name: "References", value: "<[email protected]>" },
{ name: "Message-ID", value: "<[email protected]>" },
diff --git a/apps/api/test/google-participants.spec.ts b/apps/api/test/google-participants.spec.ts
index fb2629f3..ab5ee316 100644
--- a/apps/api/test/google-participants.spec.ts
+++ b/apps/api/test/google-participants.spec.ts
@@ -36,8 +36,6 @@ describe("parseAddress", () => {
describe("parseAddressList", () => {
it("does not split on a comma inside a quoted display name", () => {
- // The whole reason this is not `header.split(",")`: naive splitting turns
- // one person into two broken addresses.
const parsed = parseAddressList(
);
@@ -72,8 +70,6 @@ describe("isAutomatedAddress", () => {
});
it("does not catch people whose names start with a marker", () => {
- // `bounce` must not swallow `bouncer@`, and a prefix rule that matched
- // substrings would.
for (const email of [
@@ -148,8 +144,6 @@ describe("dominantDomain", () => {
});
it("breaks a tie towards a company we already have", () => {
- // A customer plus their lawyer, one each. Without the tiebreak the lawyer
- // could take the thread.
const domain = dominantDomain(
[person("[email protected]"), person("[email protected]")],
new Set(["acme.com"]),
@@ -177,10 +171,8 @@ describe("splitName", () => {
{ firstName: "Jane", lastName: "van der Berg" },
],
["Jane", "[email protected]", { firstName: "Jane", lastName: null }],
- // No display name: the local part is tidied rather than used raw.
[null, "[email protected]", { firstName: "Jane", lastName: "Doe" }],
[null, "[email protected]", { firstName: "Jane", lastName: null }],
- // Some clients put the address in the display name slot.
["[email protected]", "[email protected]", { firstName: "Jane", lastName: null }],
];
@@ -193,9 +185,6 @@ describe("splitName", () => {
describe("isAutomatedAddress — scheduling tools", () => {
it("catches the addresses invites are sent from", () => {
- // The bug this came from: a Luma invite created a contact called
- // "Grand Ventures" whose email was [email protected], because the
- // tool puts the organiser's name in the display name of its own address.
for (const email of [
@@ -231,8 +220,6 @@ describe("isAutomatedAddress — scheduling tools", () => {
describe("isDerivedName", () => {
it("recognises a name that came from the address alone", () => {
- // "Pmarchetti" is what splitName produces from pmarchetti@…, so it is a
- // placeholder a real display name is allowed to replace.
expect(isDerivedName("[email protected]", "Pmarchetti", null)).toBe(
true,
);
diff --git a/apps/api/test/google-scopes.spec.ts b/apps/api/test/google-scopes.spec.ts
index f480f341..8ad1375b 100644
--- a/apps/api/test/google-scopes.spec.ts
+++ b/apps/api/test/google-scopes.spec.ts
@@ -30,11 +30,6 @@ describe("hasSyncScopes", () => {
expect(hasSyncScopes(BOTH)).toBe(true);
});
- /**
- * The case that makes the gate necessary. Google's granular consent lets
- * someone untick one scope and still complete sign-in, so "they signed in"
- * never implies "they granted it".
- */
it("is false when granular consent dropped one of them", () => {
expect(hasSyncScopes(`openid,email,profile,${GMAIL_SCOPE}`)).toBe(false);
expect(hasSyncScopes(`openid,email,profile,${CALENDAR_SCOPE}`)).toBe(false);
@@ -49,16 +44,12 @@ describe("hasSyncScopes", () => {
});
it("does not match on a prefix", () => {
- // A scope string that merely starts the same must not pass — set
- // membership, not `includes()`.
expect(hasSyncScopes(`${GMAIL_SCOPE}.metadata,${CALENDAR_SCOPE}`)).toBe(
false,
);
});
it("covers exactly the scopes the provider requests", () => {
- // Guards the two lists drifting: whatever sign-in asks for is what the
- // gate insists on.
expect(hasSyncScopes(SYNC_SCOPES.join(","))).toBe(true);
});
});
diff --git a/apps/api/test/logging.spec.ts b/apps/api/test/logging.spec.ts
index bf8be43b..0367b66b 100644
--- a/apps/api/test/logging.spec.ts
+++ b/apps/api/test/logging.spec.ts
@@ -8,7 +8,6 @@ import {
} from "../src/logging/request-context";
import { RequestLoggerMiddleware } from "../src/logging/request-logger.middleware";
-/** The logger reads `NODE_ENV` live so format can be exercised both ways. */
function withNodeEnv(value: string, fn: () => void): void {
const previous = process.env.NODE_ENV;
process.env.NODE_ENV = value;
@@ -96,9 +95,7 @@ describe("ContextLogger", () => {
expect(output).toContain("Hello");
expect(output).toContain("statusCode");
- // Nest's default rendering for a plain object, which this replaces.
expect(output).not.toContain("Object(2)");
- // The request id rides inside the context bracket.
expect(output).toContain("Ctx abcdef12");
});
});
diff --git a/apps/api/test/workspace.spec.ts b/apps/api/test/workspace.spec.ts
index 4d90277a..85a96839 100644
--- a/apps/api/test/workspace.spec.ts
+++ b/apps/api/test/workspace.spec.ts
@@ -2,8 +2,6 @@ import { beforeEach, describe, expect, it } from "bun:test";
import { isWorkspaceEmail } from "@crm/auth/workspace";
import { externalParticipants } from "../src/google/participants";
-// The allow-list is read from the environment on demand, so a test sets it the
-// same way a deployment does. Nothing here depends on whose CRM this is.
beforeEach(() => {
process.env.ALLOWED_SIGN_IN = "acme.com";
});
@@ -33,8 +31,6 @@ describe("isWorkspaceEmail", () => {
});
it("is not fooled by a lookalike domain", () => {
- // The boundary is a dot, not a substring — otherwise anyone could
- // register acme.com.evil.com and walk into a private CRM.
for (const email of [
@@ -46,16 +42,11 @@ describe("isWorkspaceEmail", () => {
});
it("fails closed when nothing is allowed", () => {
- // An unset list must admit nobody. The alternative — treating "no list"
- // as "anyone" — is a CRM full of customer data behind a sign-in that
- // accepts every Google account on earth.
process.env.ALLOWED_SIGN_IN = "";
expect(isWorkspaceEmail("[email protected]")).toBe(false);
});
it("admits a single address, for a one-person install", () => {
- // A solo self-hoster on a consumer mailbox has no domain to name, and
- // listing `gmail.com` would be an open door.
process.env.ALLOWED_SIGN_IN = "[email protected]";
expect(isWorkspaceEmail("[email protected]")).toBe(true);
@@ -72,8 +63,6 @@ describe("isWorkspaceEmail", () => {
});
describe("internal addresses never become leads", () => {
- // Empty sets: proves the workspace domain is excluded on its own, not
- // because a colleague happens to be a CRM user yet.
const options = {
ourDomains: new Set(["acme.com"]),
ourAddresses: new Set<string>(),
@@ -94,8 +83,6 @@ describe("internal addresses never become leads", () => {
});
it("stores nothing for a wholly internal thread", () => {
- // No external side means the sync drops the thread entirely — an internal
- // conversation is never written to the CRM.
expect(
externalParticipants(
[
diff --git a/apps/api/turbo.json b/apps/api/turbo.json
index 22bedcc0..3714bf7c 100644
--- a/apps/api/turbo.json
+++ b/apps/api/turbo.json
@@ -20,6 +20,7 @@
"passThroughEnv": [
"AUTH_COOKIE_DOMAIN",
"AUTH_TRUSTED_ORIGINS",
+ "BLOB_READ_WRITE_TOKEN",
"BETTER_AUTH_SECRET",
"BETTER_AUTH_URL",
"CACHE_TTL_MS",
@@ -34,6 +35,7 @@
"passThroughEnv": [
"AUTH_COOKIE_DOMAIN",
"AUTH_TRUSTED_ORIGINS",
+ "BLOB_READ_WRITE_TOKEN",
"BETTER_AUTH_SECRET",
"BETTER_AUTH_URL",
"CACHE_TTL_MS",
diff --git a/apps/app/app/(app)/companies/[companyId]/page.tsx b/apps/app/app/(app)/companies/[companyId]/page.tsx
index 885968bb..d6f6e3ea 100644
--- a/apps/app/app/(app)/companies/[companyId]/page.tsx
+++ b/apps/app/app/(app)/companies/[companyId]/page.tsx
@@ -1,13 +1,6 @@
import { redirect } from "next/navigation";
import { recordHref } from "@/lib/record-href";
-/**
- * The company page that used to live here.
- *
- * A company is a sheet over the companies table now, but the old URL is in
- * people's history and in links they have already sent, so it lands on the
- * table with that company open rather than on a 404.
- */
export default async function CompanyRedirect({
params,
}: {
diff --git a/apps/app/app/(app)/companies/companies-search-params.ts b/apps/app/app/(app)/companies/companies-search-params.ts
index b65f3143..fa38ad0c 100644
--- a/apps/app/app/(app)/companies/companies-search-params.ts
+++ b/apps/app/app/(app)/companies/companies-search-params.ts
@@ -1,12 +1,6 @@
import { createListSearchParams } from "@/components/data-table/list-search-params";
-/**
- * The companies list URL. Shared by the page's server-side prefetch and the
- * client table, so the two cannot ask for different things.
- */
export const companiesSearchParams = createListSearchParams({
- // Newest first: a CRM list is read to see what has changed, not to look
- // something up alphabetically — that is what ⌘K is for.
defaultSort: "createdAt",
defaultDir: "desc",
facetIds: ["owner", "industry", "enrichment"] as const,
diff --git a/apps/app/app/(app)/companies/companies-table.tsx b/apps/app/app/(app)/companies/companies-table.tsx
index dd9e8ae1..61aa0089 100644
--- a/apps/app/app/(app)/companies/companies-table.tsx
+++ b/apps/app/app/(app)/companies/companies-table.tsx
@@ -100,9 +100,6 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [
cell: (row) => <span className="tabular-nums">{row.openDealCount}</span>,
},
{
- // Hidden by default, but present: it is the table's default sort, and a
- // default you cannot see or return to after sorting by something else is
- // just an unexplained row order.
id: "createdAt",
header: "Created",
label: "Created date",
@@ -130,9 +127,6 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [
),
},
{
- // Off by default: while the agent is working through a backlog every row
- // says the same thing. The facet is the useful way in; this column is for
- // when you are looking at enrichment specifically.
id: "enrichment",
header: "Enrichment",
label: "Enrichment status",
@@ -152,13 +146,7 @@ export function CompaniesTable() {
const companies = useQuery({
...trpc.companies.list.queryOptions(input),
- // Keeps the previous page on screen while the next one loads, so paging
- // and typing never blank the table.
placeholderData: (previous) => previous,
- // A company added here is enriched in the background, and the agent
- // filling in its logo and industry is not a client action anyone can
- // invalidate on. Ask while any row on this page is still working — a new
- // company's logo then lands in the table rather than waiting for a reload.
refetchInterval: (query) =>
query.state.data?.rows.some((row) =>
isEnriching(row.enrichmentStatus, row.queued),
@@ -180,15 +168,11 @@ export function CompaniesTable() {
value: user.id,
label: user.name,
})),
- // An owner with nothing assigned is a dropdown entry that can only
- // ever produce an empty table.
].filter((option) => (facetCounts?.owner?.[option.value] ?? 0) > 0),
},
{
id: "industry",
label: "Industry",
- // The industries that exist, not a fixed list: they come from the
- // agent, so nobody here gets to decide what the set is.
options: Object.keys(facetCounts?.industry ?? {})
.sort()
.map((value) => ({ value, label: value })),
diff --git a/apps/app/app/(app)/companies/create-company-sheet.tsx b/apps/app/app/(app)/companies/create-company-sheet.tsx
index 600c4a30..5d610fad 100644
--- a/apps/app/app/(app)/companies/create-company-sheet.tsx
+++ b/apps/app/app/(app)/companies/create-company-sheet.tsx
@@ -38,21 +38,11 @@ import { useTRPC } from "@/lib/trpc/client";
const UNASSIGNED = "unassigned";
-/**
- * Name, domain, owner — nothing else.
- *
- * Everything a form could ask for next (industry, address, logo, socials) is
- * something the agent can find from the domain, and a form that asks a rep to
- * type it is a form they will skip.
- */
export function CreateCompanySheet() {
const openRecord = useOpenRecord();
const trpc = useTRPC();
const cache = useCrmCache();
- // Open state lives in the URL, like every other view state here: "add a
- // company" is then a link you can send someone, and Back closes the sheet
- // instead of leaving the page. Shallow, so it costs no server round trip.
const [open, setOpen] = useQueryState(
"new",
parseAsBoolean.withDefault(false),
@@ -71,7 +61,6 @@ export function CreateCompanySheet() {
onSuccess: async (company) => {
await cache.company(company.id);
toast.success(`${company.name} added.`);
- // `null` rather than `false` so the closed state leaves a clean URL.
await setOpen(null);
setName("");
setDomain("");
diff --git a/apps/app/app/(app)/companies/page.tsx b/apps/app/app/(app)/companies/page.tsx
index 4f224fc7..6609b03e 100644
--- a/apps/app/app/(app)/companies/page.tsx
+++ b/apps/app/app/(app)/companies/page.tsx
@@ -28,15 +28,10 @@ export default async function CompaniesPage({
}) {
await requireSession();
- // Parsed with the same parsers the table uses, so the first paint is already
- // filtered, sorted and on the right page.
const values = await companiesSearchParams.load(searchParams);
const trpc = getServerTrpc();
const queryClient = getServerQueryClient();
- // The rows are awaited so the first paint is the filtered, sorted, correct
- // page rather than a spinner. The owner and company pickers behind the facet
- // dropdowns are not — the table draws fine without them.
await queryClient.prefetchQuery(
trpc.companies.list.queryOptions(companiesSearchParams.toInput(values)),
);
diff --git a/apps/app/app/(app)/contacts/[contactId]/page.tsx b/apps/app/app/(app)/contacts/[contactId]/page.tsx
index 3c49310c..ed76688c 100644
--- a/apps/app/app/(app)/contacts/[contactId]/page.tsx
+++ b/apps/app/app/(app)/contacts/[contactId]/page.tsx
@@ -1,7 +1,6 @@
import { redirect } from "next/navigation";
import { recordHref } from "@/lib/record-href";
-/** Kept for links to the contact page this used to be. */
export default async function ContactRedirect({
params,
}: {
diff --git a/apps/app/app/(app)/contacts/contacts-search-params.ts b/apps/app/app/(app)/contacts/contacts-search-params.ts
index d1da088f..24da1e77 100644
--- a/apps/app/app/(app)/contacts/contacts-search-params.ts
+++ b/apps/app/app/(app)/contacts/contacts-search-params.ts
@@ -1,8 +1,6 @@
import { createListSearchParams } from "@/components/data-table/list-search-params";
export const contactsSearchParams = createListSearchParams({
- // Newest first: a CRM list is read to see what has changed, not to look
- // something up alphabetically — that is what ⌘K is for.
defaultSort: "createdAt",
defaultDir: "desc",
facetIds: ["owner", "company"] as const,
diff --git a/apps/app/app/(app)/contacts/contacts-table.tsx b/apps/app/app/(app)/contacts/contacts-table.tsx
index 3ee24496..bf3be4fa 100644
--- a/apps/app/app/(app)/contacts/contacts-table.tsx
+++ b/apps/app/app/(app)/contacts/contacts-table.tsx
@@ -1,13 +1,13 @@
"use client";
-import { Avatar, AvatarFallback, AvatarImage } from "@crm/ui/components/avatar";
import {
DataTable,
type DataTableColumn,
type DataTableFacet,
} from "@crm/ui/components/data-table";
import { EmptyCellValue } from "@crm/ui/components/empty-cell";
-import { initialsFromName, relativeTimeFromIso } from "@crm/ui/lib/format";
+import { PersonAvatar } from "@crm/ui/components/person-avatar";
+import { relativeTimeFromIso } from "@crm/ui/lib/format";
import { useQuery } from "@tanstack/react-query";
import { CompanyCell } from "@/components/crm/company-cell";
import { contactName } from "@/components/crm/contact-name";
@@ -30,10 +30,12 @@ const COLUMNS: DataTableColumn<ContactRow>[] = [
width: "w-[22%]",
cell: (row) => (
<span className="flex min-w-0 items-center gap-2">
- <Avatar size="sm">
- {row.imageUrl ? <AvatarImage alt="" src={row.imageUrl} /> : null}
- <AvatarFallback>{initialsFromName(contactName(row))}</AvatarFallback>
- </Avatar>
+ <PersonAvatar
+ src={row.imageUrl}
+ name={contactName(row)}
+ email={row.email}
+ size="sm"
+ />
<span className="truncate font-medium">{contactName(row)}</span>
</span>
),
@@ -80,9 +82,6 @@ const COLUMNS: DataTableColumn<ContactRow>[] = [
cell: (row) => <OwnerCell owner={row.owner} />,
},
{
- // Hidden by default, but present: it is the table's default sort, and a
- // default you cannot see or return to after sorting by something else is
- // just an unexplained row order.
id: "createdAt",
header: "Created",
label: "Created date",
diff --git a/apps/app/app/(app)/contacts/create-contact-sheet.tsx b/apps/app/app/(app)/contacts/create-contact-sheet.tsx
index 62002d9d..0975663e 100644
--- a/apps/app/app/(app)/contacts/create-contact-sheet.tsx
+++ b/apps/app/app/(app)/contacts/create-contact-sheet.tsx
@@ -33,17 +33,11 @@ import { useTRPC } from "@/lib/trpc/client";
const NONE = "none";
-export function CreateContactSheet({
- /** Pre-selects a company when opened from that company's page. */
- companyId,
-}: {
- companyId?: string;
-}) {
+export function CreateContactSheet({ companyId }: { companyId?: string }) {
const openRecord = useOpenRecord();
const trpc = useTRPC();
const cache = useCrmCache();
- // URL state, like every other view state here — see CreateCompanySheet.
const [open, setOpen] = useQueryState(
"new",
parseAsBoolean.withDefault(false),
diff --git a/apps/app/app/(app)/dashboard-summary.tsx b/apps/app/app/(app)/dashboard-summary.tsx
index 24fd2856..7f5a4581 100644
--- a/apps/app/app/(app)/dashboard-summary.tsx
+++ b/apps/app/app/(app)/dashboard-summary.tsx
@@ -13,6 +13,10 @@ import {
import { CardTableEmpty } from "@crm/ui/components/card-table";
import { Checkbox } from "@crm/ui/components/checkbox";
import { EmptyCellValue } from "@crm/ui/components/empty-cell";
+import {
+ EntityLogo,
+ type EntityLogoTone,
+} from "@crm/ui/components/entity-logo";
import {
SimpleTable,
type SimpleTableColumn,
@@ -43,38 +47,17 @@ import { useTRPC } from "@/lib/trpc/client";
import { overviewParsers } from "./overview-search-params";
import { SalesDashboard } from "./sales-dashboard";
-/**
- * Cell padding, in one constant.
- *
- * `SimpleTable` sets its own header padding and leaves the body to the caller,
- * so a table where one column forgot `py-2.5` is a row half a line taller than
- * the ones around it — which is most of what made these lists look ragged.
- */
const CELL = "px-3 py-2.5 align-middle";
-/**
- * Every list on the overview is a table: a header row naming the columns, rows
- * divided by hairlines, and no icon in the leading cell. A glyph per row is
- * what this page deliberately does not do.
- *
- * The two panels below the charts are framed and set to one height because
- * their rows scroll; the activity log at the bottom is unframed and runs as
- * long as it needs to, because nothing sits beside it to end level with.
- */
export function DashboardSummary() {
const trpc = useTRPC();
const cache = useCrmCache();
const openRecord = useOpenRecord();
- // Read, not written, here: the toggle in the page header owns the setter, and
- // both sides agree because the value lives in the URL rather than in a
- // provider threaded between them.
const [scope] = useQueryState("scope", overviewParsers.scope);
const summaryQuery = useQuery({
...trpc.dashboard.summary.queryOptions({ scope }),
- // Switching scope keeps the previous numbers on screen while the new ones
- // load, the same way the tables hold their rows while paging.
placeholderData: (previous) => previous,
});
@@ -129,11 +112,6 @@ export function DashboardSummary() {
<div className="flex flex-col gap-6">
<SalesDashboard summary={summary} />
- {/*
- * Two panels of one fixed height rather than four cards that each grew
- * to fit their rows: the pair always ends level, and the activity list
- * below them stays where a rep last saw it however many deals are open.
- */}
<div className="grid gap-6 @3xl/page-content:grid-cols-2">
<Card className="min-w-0">
<CardHeader>
@@ -163,9 +141,7 @@ export function DashboardSummary() {
<TableCell className={CELL}>
<DealCell
name={deal.name}
- company={deal.company.name}
- // Rendered on the server and again in the browser,
- // often a minute apart — the text is meant to drift.
+ company={deal.company}
meta={relativeTimeFromIso(deal.stageChangedAt)}
/>
</TableCell>
@@ -305,8 +281,6 @@ export function DashboardSummary() {
<TableCell
className={`${CELL} text-right text-muted-foreground`}
>
- {/* Rendered on the server and again in the browser, often a
- minute apart — the text is meant to drift. */}
<span suppressHydrationWarning>
{relativeTimeFromIso(entry.createdAt)}
</span>
@@ -320,36 +294,42 @@ export function DashboardSummary() {
);
}
-/**
- * A deal's name over the account it belongs to — two lines in one cell, so the
- * table keeps four columns in a half-width panel instead of seven.
- */
function DealCell({
name,
company,
meta,
}: {
name: string;
- company: string;
+ company: {
+ name: string;
+ iconUrl: string | null;
+ iconDarkUrl: string | null;
+ iconTone: string | null;
+ };
meta?: string;
}) {
return (
- <span className="flex min-w-0 flex-col">
- <span className="truncate font-medium">{name}</span>
- <span className="truncate text-muted-foreground" suppressHydrationWarning>
- {meta ? `${company} · ${meta}` : company}
+ <span className="flex min-w-0 items-center gap-2">
+ <EntityLogo
+ src={company.iconUrl}
+ darkSrc={company.iconDarkUrl}
+ tone={company.iconTone as EntityLogoTone | null | undefined}
+ name={company.name}
+ size="sm"
+ />
+ <span className="flex min-w-0 flex-col">
+ <span className="truncate font-medium">{name}</span>
+ <span
+ className="truncate text-muted-foreground"
+ suppressHydrationWarning
+ >
+ {meta ? `${company.name} · ${meta}` : company.name}
+ </span>
</span>
</span>
);
}
-/**
- * A deal's or a rep's share of the biggest one on the list.
- *
- * The same bar the charts use, in plain HTML: `bloom-*` is a theme-independent
- * utility in `globals.css` precisely so a meter beside a row matches the plot
- * above it. Hidden below `sm`, where the number alone has to carry it.
- */
function ValueMeter({ share, color }: { share: number; color: string }) {
return (
<span
@@ -361,8 +341,6 @@ function ValueMeter({ share, color }: { share: number; color: string }) {
style={
{
backgroundColor: color,
- // Rounded: a bar 24px wide cannot render the difference, and the
- // raw ratio puts fourteen decimal places in the markup.
"--share": `${Math.round(Math.max(Math.min(share, 100), 0))}%`,
} as CSSProperties
}
diff --git a/apps/app/app/(app)/deals/[dealId]/page.tsx b/apps/app/app/(app)/deals/[dealId]/page.tsx
index 6df89cd7..5481fcc5 100644
--- a/apps/app/app/(app)/deals/[dealId]/page.tsx
+++ b/apps/app/app/(app)/deals/[dealId]/page.tsx
@@ -1,7 +1,6 @@
import { redirect } from "next/navigation";
import { recordHref } from "@/lib/record-href";
-/** Kept for links to the deal page this used to be. */
export default async function DealRedirect({
params,
}: {
diff --git a/apps/app/app/(app)/deals/create-deal-sheet.tsx b/apps/app/app/(app)/deals/create-deal-sheet.tsx
index 1fa3a52f..7f4b8a93 100644
--- a/apps/app/app/(app)/deals/create-deal-sheet.tsx
+++ b/apps/app/app/(app)/deals/create-deal-sheet.tsx
@@ -40,17 +40,11 @@ import { useTRPC } from "@/lib/trpc/client";
const UNSET = "";
-export function CreateDealSheet({
- /** Pre-selects a company when opened from that company's page. */
- companyId,
-}: {
- companyId?: string;
-}) {
+export function CreateDealSheet({ companyId }: { companyId?: string }) {
const openRecord = useOpenRecord();
const trpc = useTRPC();
const cache = useCrmCache();
- // URL state, like every other view state here — see CreateCompanySheet.
const [open, setOpen] = useQueryState(
"new",
parseAsBoolean.withDefault(false),
@@ -70,7 +64,6 @@ export function CreateDealSheet({
const companies = useQuery(trpc.companies.options.queryOptions({ q: "" }));
const me = useQuery(trpc.users.me.queryOptions());
- // Whoever is adding the deal is almost always the one working it.
const resolvedOwner = ownerId || me.data?.id || UNSET;
const create = useMutation(
@@ -118,7 +111,6 @@ export function CreateDealSheet({
companyId: company,
ownerId: resolvedOwner,
stage: stage as never,
- // Typed in whole currency, stored and summed in cents.
amountCents: Number.isFinite(parsed)
? Math.round(parsed * 100)
: null,
diff --git a/apps/app/app/(app)/deals/deals-search-params.ts b/apps/app/app/(app)/deals/deals-search-params.ts
index ec5d8429..64850b83 100644
--- a/apps/app/app/(app)/deals/deals-search-params.ts
+++ b/apps/app/app/(app)/deals/deals-search-params.ts
@@ -1,10 +1,6 @@
import { createListSearchParams } from "@/components/data-table/list-search-params";
export const dealsSearchParams = createListSearchParams({
- // Pipeline order by default: the deals closest to closing are the ones a rep
- // opens this page to look at.
- // Newest first: a CRM list is read to see what has changed, not to look
- // something up alphabetically — that is what ⌘K is for.
defaultSort: "createdAt",
defaultDir: "desc",
tabId: "status",
diff --git a/apps/app/app/(app)/deals/deals-table.tsx b/apps/app/app/(app)/deals/deals-table.tsx
index 91b4d767..e9c39ce6 100644
--- a/apps/app/app/(app)/deals/deals-table.tsx
+++ b/apps/app/app/(app)/deals/deals-table.tsx
@@ -49,8 +49,6 @@ const COLUMNS: DataTableColumn<DealRow>[] = [
header: "Stage",
sortable: true,
width: "w-[18%]",
- // Editable in place: moving a deal along is the single most common thing
- // anyone does here, and it should not need a page load.
cell: (row) => <DealStageMenu dealId={row.id} stage={row.stage} />,
},
{
@@ -93,9 +91,6 @@ const COLUMNS: DataTableColumn<DealRow>[] = [
),
},
{
- // Hidden by default, but present: it is the table's default sort, and a
- // default you cannot see or return to after sorting by something else is
- // just an unexplained row order.
id: "createdAt",
header: "Created",
label: "Created date",
@@ -186,8 +181,6 @@ export function DealsTable() {
onRowClick={(row) => openRecord({ kind: "deal", id: row.id })}
empty="No deals match this view."
meta={
- // The open pipeline for everything the filters match, not just the
- // page — summed in Postgres.
openValueCents === null || openValueCents === undefined ? undefined : (
<span>
{deals.data?.total ?? 0} deals ·{" "}
diff --git a/apps/app/app/(app)/deals/page.tsx b/apps/app/app/(app)/deals/page.tsx
index ca349bea..60387667 100644
--- a/apps/app/app/(app)/deals/page.tsx
+++ b/apps/app/app/(app)/deals/page.tsx
@@ -32,9 +32,6 @@ export default async function DealsPage({
const trpc = getServerTrpc();
const queryClient = getServerQueryClient();
- // The rows are awaited so the first paint is the filtered, sorted, correct
- // page rather than a spinner. The owner and company pickers behind the facet
- // dropdowns are not — the table draws fine without them.
await queryClient.prefetchQuery(
trpc.deals.list.queryOptions(dealsSearchParams.toInput(values)),
);
diff --git a/apps/app/app/(app)/layout.tsx b/apps/app/app/(app)/layout.tsx
index 6facff82..ce20a7b9 100644
--- a/apps/app/app/(app)/layout.tsx
+++ b/apps/app/app/(app)/layout.tsx
@@ -10,9 +10,6 @@ export default async function AppLayout({
}: Readonly<{
children: React.ReactNode;
}>) {
- // Not just `requireSession`: mailbox access is a condition of using this
- // tool, and a granular-consent untick would otherwise leave someone inside
- // the app with a CRM that silently syncs nothing.
const { user } = await requireGoogleAccess();
return (
@@ -25,24 +22,13 @@ export default async function AppLayout({
image: user.image ?? null,
}}
/>
- {/*
- * No scroll container here: <PageShell> renders the scrolling
- * <main>, so the page can own its own transition snapshot while
- * the header and rail stay put.
- */}
<div className="flex min-h-0 flex-1">
<AppIconRail />
{children}
</div>
- {/*
- * Records open over whatever list you were on rather than as pages of
- * their own, so the sheet lives in the shell — one instance, driven
- * by `?record=`, reachable from every row, card and search hit.
- */}
<RecordSheetHost />
- {/* ⌘K from anywhere inside the app shell. */}
<QuickSwitcher />
</div>
</MobileNavProvider>
diff --git a/apps/app/app/(app)/overview-greeting.tsx b/apps/app/app/(app)/overview-greeting.tsx
index 7522bcd3..e4ab4a19 100644
--- a/apps/app/app/(app)/overview-greeting.tsx
+++ b/apps/app/app/(app)/overview-greeting.tsx
@@ -6,14 +6,6 @@ import { PageShellDescription, PageShellTitle } from "@/components/page-shell";
import { useTRPC } from "@/lib/trpc/client";
import { overviewParsers } from "./overview-search-params";
-/**
- * Reads the signed-in user from the API rather than the session cookie, so a
- * renamed account is right on the next load instead of the next sign-in.
- *
- * `useSuspenseQuery` because the page awaits the prefetch: the data is already
- * in the cache by the time this renders, and the alternative is an
- * `undefined` branch that can never actually be taken.
- */
export function OverviewGreeting() {
const trpc = useTRPC();
const { data: me } = useSuspenseQuery(trpc.users.me.queryOptions());
diff --git a/apps/app/app/(app)/overview-scope.tsx b/apps/app/app/(app)/overview-scope.tsx
index bf3ad621..f2cfc06c 100644
--- a/apps/app/app/(app)/overview-scope.tsx
+++ b/apps/app/app/(app)/overview-scope.tsx
@@ -17,13 +17,6 @@ function isScope(value: string): value is OverviewScope {
return (OVERVIEW_SCOPES as readonly string[]).includes(value);
}
-/**
- * Whose numbers the overview shows.
- *
- * In the URL rather than in state: "how the team closed this quarter" is then a
- * link someone can send, and the panel below reads the same key without either
- * side owning the other.
- */
export function OverviewScopeToggle() {
const [scope, setScope] = useQueryState("scope", overviewParsers.scope);
@@ -35,8 +28,6 @@ export function OverviewScopeToggle() {
spacing={0}
value={scope}
onValueChange={(next) => {
- // Radix clears the value when the active item is pressed again, and a
- // dashboard scoped to nobody is not a state worth having.
if (isScope(next)) void setScope(next);
}}
aria-label="Whose numbers to show"
diff --git a/apps/app/app/(app)/overview-search-params.ts b/apps/app/app/(app)/overview-search-params.ts
index dc51d69a..c9ebeda9 100644
--- a/apps/app/app/(app)/overview-search-params.ts
+++ b/apps/app/app/(app)/overview-search-params.ts
@@ -1,22 +1,10 @@
import { createLoader, parseAsStringLiteral } from "nuqs/server";
-/**
- * The overview URL. Shared by the page's server-side prefetch and the client
- * panel, so the two cannot ask for different things — the same reason the list
- * modules keep their parsers in one file.
- *
- * Imported from `nuqs/server`: parsers are plain data, and this module is pulled
- * into both a server component and a client one.
- */
-
-/** Kept in step with `DASHBOARD_SCOPES` in the API's dashboard contracts. */
export const OVERVIEW_SCOPES = ["me", "everyone"] as const;
export type OverviewScope = (typeof OVERVIEW_SCOPES)[number];
export const overviewParsers = {
- // A literal parser, not a plain string: `?scope=nonsense` then falls back to
- // the default rather than reaching the API as an unhandled value.
scope: parseAsStringLiteral(OVERVIEW_SCOPES).withDefault("me"),
};
diff --git a/apps/app/app/(app)/page.tsx b/apps/app/app/(app)/page.tsx
index 6f4f9900..eabcc976 100644
--- a/apps/app/app/(app)/page.tsx
+++ b/apps/app/app/(app)/page.tsx
@@ -21,16 +21,11 @@ export default async function OverviewPage({
}) {
await requireSession();
- // Parsed with the same parser the toggle uses, so the first paint is already
- // scoped to whoever the URL says rather than to the default.
const { scope } = await loadOverviewSearchParams(searchParams);
const trpc = getServerTrpc();
const queryClient = getServerQueryClient();
- // Both awaited: the greeting is one line of text and the dashboard is the
- // whole page, so a skeleton that flashes for the length of one API call is
- // worse than rendering a beat later.
await Promise.all([
queryClient.prefetchQuery(trpc.users.me.queryOptions()),
queryClient.prefetchQuery(trpc.dashboard.summary.queryOptions({ scope })),
diff --git a/apps/app/app/(app)/sales-dashboard.tsx b/apps/app/app/(app)/sales-dashboard.tsx
index 0a7fa5a6..e18c6f75 100644
--- a/apps/app/app/(app)/sales-dashboard.tsx
+++ b/apps/app/app/(app)/sales-dashboard.tsx
@@ -23,22 +23,11 @@ import type { RouterOutputs } from "@/lib/trpc/types";
type Summary = RouterOutputs["dashboard"]["summary"];
-/**
- * Won is the outcome, created is the input that produces it six weeks later.
- * `--success` for the first because a rep already reads green as "closed"; the
- * chart ramp for the second because it is a leading indicator, not a verdict.
- */
const TREND_CONFIG: ChartConfig = {
won: { label: "Closed won", color: "var(--success)" },
created: { label: "New pipeline", color: "var(--chart-1)" },
};
-/**
- * Percentage change, or nothing.
- *
- * With no baseline there is no percentage to quote — "+100%" against a month
- * where nothing closed is arithmetic, not information.
- */
function changeDelta(
current: number,
previous: number,
@@ -53,10 +42,6 @@ function changeDelta(
};
}
-/**
- * The KPI strip and the two charts behind it: six months of closed-won against
- * new pipeline, and where the open pipeline currently sits.
- */
export function SalesDashboard({ summary }: { summary: Summary }) {
const {
pipeline,
@@ -165,11 +150,6 @@ export function SalesDashboard({ summary }: { summary: Summary }) {
formatMoney(typeof value === "number" ? value : Number(value))
}
/>
- {/*
- * A legend of links rather than `onSliceClick`: clicking a
- * wedge is pointer-only, and "show me the contracts I have
- * out" is the most likely thing a rep wants from this chart.
- */}
<ul className="flex flex-col px-5 pb-1 md:px-6">
{stageSlices.map((slice) => (
<li key={slice.key} className="border-t first:border-t-0">
@@ -205,14 +185,6 @@ export function SalesDashboard({ summary }: { summary: Summary }) {
);
}
-/**
- * A titled, framed plot, built from the same `Card` header the lists below the
- * charts use so every section on the page shares one heading rhythm.
- *
- * The body keeps a border where a list does not: a chart floating against the
- * page with no frame reads as unmoored, and `flex-1` makes both columns of a
- * row end level however tall their plots are.
- */
function ChartPanel({
title,
description,
diff --git a/apps/app/app/(app)/settings/agent-model.tsx b/apps/app/app/(app)/settings/agent-model.tsx
new file mode 100644
index 00000000..403d731e
--- /dev/null
+++ b/apps/app/app/(app)/settings/agent-model.tsx
@@ -0,0 +1,185 @@
+"use client";
+
+import ChevronDown from "@carbon/icons-react/es/ChevronDown";
+import { Button } from "@crm/ui/components/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@crm/ui/components/card";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@crm/ui/components/command";
+import { Icon } from "@crm/ui/components/icon";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@crm/ui/components/popover";
+import { useMutation, useQuery } from "@tanstack/react-query";
+import { useState } from "react";
+import { toast } from "sonner";
+import { useCrmCache } from "@/lib/trpc/cache";
+import { useTRPC } from "@/lib/trpc/client";
+
+type CatalogModel = {
+ id: string;
+ name: string;
+ provider: string;
+ contextWindowTokens: number;
+ pricing: { input: number; output: number } | null;
+};
+
+const FOLLOW_DEFAULT = "__default__";
+
+function perMillion(rate: number): string {
+ const dollars = rate * 1_000_000;
+ return `$${dollars.toFixed(2).replace(/\.?0+$/, "")}`;
+}
+
+function priceHint(model: CatalogModel): string | null {
+ if (!model.pricing) return null;
+ return `${perMillion(model.pricing.input)} in · ${perMillion(model.pricing.output)} out per 1M`;
+}
+
+function contextHint(tokens: number): string {
+ return tokens >= 1_000_000
+ ? `${Math.round(tokens / 1_000_000)}M context`
+ : `${Math.round(tokens / 1_000)}K context`;
+}
+
+function byProvider(models: CatalogModel[]): [string, CatalogModel[]][] {
+ const groups = new Map<string, CatalogModel[]>();
+
+ for (const model of models) {
+ const list = groups.get(model.provider) ?? [];
+ list.push(model);
+ groups.set(model.provider, list);
+ }
+
+ return [...groups];
+}
+
+export function AgentModel() {
+ const trpc = useTRPC();
+ const cache = useCrmCache();
+ const [open, setOpen] = useState(false);
+
+ const settings = useQuery(trpc.settings.agentModel.queryOptions());
+ const catalog = useQuery(trpc.settings.modelCatalog.queryOptions());
+
+ const save = useMutation(
+ trpc.settings.setAgentModel.mutationOptions({
+ onSuccess: async () => {
+ await cache.settings();
+ toast.success("The agent will use this model from its next session.");
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ if (!settings.data) return null;
+
+ const { selectedId, effectiveId, defaultId, effective } = settings.data;
+ const models = catalog.data?.models ?? [];
+ const unavailable = catalog.data !== undefined && !catalog.data.available;
+
+ const defaultModel = models.find((model) => model.id === defaultId);
+ const current = selectedId ?? FOLLOW_DEFAULT;
+
+ const currentLabel = selectedId
+ ? (effective?.name ?? selectedId)
+ : `Default — ${defaultModel?.name ?? defaultId}`;
+
+ const choose = (id: string) => {
+ setOpen(false);
+ if (id === current) return;
+ save.mutate({ modelId: id === FOLLOW_DEFAULT ? null : id });
+ };
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Research agent</CardTitle>
+ <CardDescription>
+ The model the agent thinks with, routed through the Vercel AI Gateway.
+ </CardDescription>
+ </CardHeader>
+
+ <CardContent>
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ role="combobox"
+ aria-expanded={open}
+ aria-label="Model"
+ disabled={save.isPending || catalog.isPending || unavailable}
+ >
+ {currentLabel}
+ <Icon icon={ChevronDown} data-icon="inline-end" />
+ </Button>
+ </PopoverTrigger>
+
+ <PopoverContent align="start" size="fit" className="w-96">
+ <Command>
+ <CommandInput placeholder="Search models…" />
+ <CommandList>
+ <CommandEmpty>No model matches that.</CommandEmpty>
+
+ <CommandGroup>
+ <CommandItem
+ value={`default ${defaultId}`}
+ data-checked={current === FOLLOW_DEFAULT}
+ onSelect={() => choose(FOLLOW_DEFAULT)}
+ >
+ Default — {defaultModel?.name ?? defaultId}
+ </CommandItem>
+ </CommandGroup>
+
+ {byProvider(models).map(([provider, group]) => (
+ <CommandGroup key={provider} heading={provider}>
+ {group.map((model) => {
+ const price = priceHint(model);
+
+ return (
+ <CommandItem
+ key={model.id}
+ value={`${model.name} ${model.provider} ${model.id}`}
+ data-checked={current === model.id}
+ onSelect={() => choose(model.id)}
+ >
+ <span>{model.name}</span>
+ <span className="ml-auto text-muted-foreground text-xs">
+ {price ?? contextHint(model.contextWindowTokens)}
+ </span>
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ ))}
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+
+ <p className="text-muted-foreground text-xs">
+ {unavailable
+ ? `Could not reach the AI Gateway to list models. The agent is still running ${effectiveId}.`
+ : effective
+ ? `${effectiveId} · ${contextHint(effective.contextWindowTokens)}${
+ priceHint(effective) ? ` · ${priceHint(effective)}` : ""
+ }`
+ : effectiveId}
+ </p>
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/apps/app/app/(app)/settings/google-connection.tsx b/apps/app/app/(app)/settings/google-connection.tsx
index e960aaa0..9bf32a58 100644
--- a/apps/app/app/(app)/settings/google-connection.tsx
+++ b/apps/app/app/(app)/settings/google-connection.tsx
@@ -8,25 +8,40 @@ import {
AlertDescription,
AlertTitle,
} from "@crm/ui/components/alert";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@crm/ui/components/alert-dialog";
import { Button } from "@crm/ui/components/button";
+import {
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "@crm/ui/components/card";
import { Icon } from "@crm/ui/components/icon";
import { Label } from "@crm/ui/components/label";
import { StatusIndicator } from "@crm/ui/components/status-indicator";
import { Switch } from "@crm/ui/components/switch";
import { relativeTimeFromIso } from "@crm/ui/lib/format";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import Link from "next/link";
import { useState } from "react";
import { toast } from "sonner";
import { isSyncing, SYNC_POLL_MS } from "@/components/crm/sync-status";
import { useCrmCache } from "@/lib/trpc/cache";
import { useTRPC } from "@/lib/trpc/client";
-/**
- * What each source contributes, in the rep's terms.
- *
- * The toggle copy says what a record *becoming* real depends on, because that
- * is the only decision on this page with a consequence.
- */
const SOURCES = {
calendar: {
label: "Meetings",
@@ -38,14 +53,6 @@ const SOURCES = {
},
} as const;
-/**
- * Where a "Resolve" link is allowed to point.
- *
- * The URL is scraped out of a vendor error string with a regex, and the string
- * reaches us through a sync that talks to a third party. Rendering whatever it
- * contains as a link a rep will click is a phishing hop waiting to happen, so
- * the destination has to be somewhere the fix could actually live.
- */
const RESOLVE_HOSTS = [
"console.cloud.google.com",
"console.developers.google.com",
@@ -77,13 +84,6 @@ function explain(error: string) {
};
}
-/**
- * What is currently wrong, as one comparable string.
- *
- * Keyed by source *and* message so that a check which fixes Gmail and leaves
- * Calendar broken is a different state, not the same one — otherwise half a
- * repair would be reported as no progress at all.
- */
function failureSignature(
sources: readonly {
source: string;
@@ -105,8 +105,6 @@ export function GoogleConnection() {
const status = useQuery({
...trpc.google.status.queryOptions(),
- // A sync is background work no client action caused, so per the API rules
- // it is polled, not invalidated — and the poll stops the moment it settles.
refetchInterval: (query) =>
query.state.data?.sources.some((source) => isSyncing(source.status))
? SYNC_POLL_MS
@@ -125,9 +123,6 @@ export function GoogleConnection() {
const revoke = useMutation(
trpc.google.revokeAccess.mutationOptions({
- // A full navigation, not a router push: the grant is gone, so every
- // cached render is wrong and the gate has to re-evaluate. Lands on
- // /grant-access.
onSuccess: () => window.location.assign("/"),
onError: (error) => toast.error(error.message),
}),
@@ -140,12 +135,6 @@ export function GoogleConnection() {
}),
);
- /*
- * A check that lands on the same failure changes nothing on screen, so the
- * button looks broken rather than the connection. Incrementing this replays
- * the alert's attention animation — the page answering "still here" instead
- * of appearing not to have run.
- */
const [insistence, setInsistence] = useState(0);
const syncNow = useMutation(
@@ -154,8 +143,6 @@ export function GoogleConnection() {
const before = failureSignature(status.data?.sources ?? []);
await cache.google();
- // Read the refetched value rather than `status.data`, which is the
- // render's snapshot and is still the pre-check one inside here.
const after = failureSignature(
queryClient.getQueryData(trpc.google.status.queryKey())?.sources ??
[],
@@ -171,8 +158,6 @@ export function GoogleConnection() {
const { sources, hasRefreshToken } = status.data;
- // Both scopes come from one grant at sign-in, so "Gmail connected but
- // Calendar not" is not a state that exists. One section, not one per source.
const failing = sources.filter(
(source) => source.status === "NEEDS_RECONNECT" || source.lastError,
);
@@ -185,20 +170,20 @@ export function GoogleConnection() {
const healthy = failing.length === 0 && hasRefreshToken;
return (
- // No card: the page shell already owns the gutter, so a padded container
- // here would indent every line away from the heading above it — and there
- // is no border or fill to earn that indent. Sections separated by rules,
- // like the record sheets.
- <div className="flex max-w-3xl flex-col">
- <section className="flex flex-col gap-2 pb-5">
- <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
- <div className="flex items-center gap-3">
- <h2 className="font-medium text-sm">Google</h2>
- <StatusIndicator
- tone={healthy ? "success" : "warning"}
- label={healthy ? "Connected" : "Needs attention"}
- />
- </div>
+ <Card>
+ <CardHeader>
+ <CardTitle>Google</CardTitle>
+ <CardDescription>
+ New meetings and email threads are added to the matching company as
+ they happen.
+ </CardDescription>
+
+ <CardAction>
+ <StatusIndicator
+ size="sm"
+ tone={healthy ? "success" : "warning"}
+ label={healthy ? "Connected" : "Needs attention"}
+ />
<Button
variant="contrast"
@@ -208,14 +193,10 @@ export function GoogleConnection() {
>
{syncNow.isPending ? "Checking…" : "Check now"}
</Button>
- </div>
-
- <p className="text-pretty text-muted-foreground text-sm/6">
- New meetings and email threads are added to the matching company as
- they happen. Nothing from before you connected is imported, and
- nothing is ever sent on your behalf.
- </p>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
{!hasRefreshToken ? (
<Alert variant="destructive" attention={insistence}>
<Icon icon={Warning} />
@@ -242,13 +223,6 @@ export function GoogleConnection() {
{url ? (
<AlertAction>
- {/*
- * The inverted chip, not the primary fill. Green
- * means "the action you want" everywhere else, and
- * inside a failure panel it reads as reassurance.
- * On the alert's grey this is the loudest thing in
- * the box, which is what the one way out should be.
- */}
<Button variant="contrast" size="xs" asChild>
<a href={url} target="_blank" rel="noreferrer">
Resolve
@@ -267,9 +241,7 @@ export function GoogleConnection() {
: "Waiting for the first check"}
</p>
)}
- </section>
- <section className="flex flex-col gap-5 border-t py-5">
{sources.map((source) => {
const copy = SOURCES[source.source];
@@ -299,61 +271,78 @@ export function GoogleConnection() {
</div>
);
})}
- </section>
-
- {/*
- * Quiet by design. These are the irreversible actions and neither is
- * anybody's daily business, so they sit at the bottom in muted type
- * rather than as a third block competing for attention.
- */}
- <div className="flex flex-wrap items-center gap-x-4 gap-y-2 border-t pt-5 text-muted-foreground text-xs">
- <button
- type="button"
- className="underline underline-offset-3 hover:text-foreground disabled:opacity-50"
- disabled={purge.isPending}
- onClick={() => {
- if (
- !window.confirm(
- "Delete every synced email and meeting from the CRM?",
- )
- ) {
- return;
- }
- purge.mutate();
- }}
- >
- Delete synced data
- </button>
-
- <button
- type="button"
- className="underline underline-offset-3 hover:text-foreground disabled:opacity-50"
- disabled={revoke.isPending}
- onClick={() => {
- // Worth a confirm: one OAuth client means one grant, so this ends
- // CRM access entirely, not just syncing.
- if (
- !window.confirm(
- "Revoke Google access? You will be signed out and cannot use the CRM until you grant it again.",
- )
- ) {
- return;
- }
- revoke.mutate();
- }}
- >
- Revoke Google access
- </button>
-
- <a
- href="https://myaccount.google.com/permissions"
- target="_blank"
- rel="noreferrer"
- className="underline underline-offset-3 hover:text-foreground"
- >
- Manage in your Google account
- </a>
- </div>
- </div>
+
+ <CardFooter>
+ <div className="-ml-2 flex flex-wrap items-center gap-1 text-muted-foreground">
+ <AlertDialog>
+ <AlertDialogTrigger asChild>
+ <Button variant="ghost" size="xs" disabled={purge.isPending}>
+ Delete synced data
+ </Button>
+ </AlertDialogTrigger>
+
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete synced data?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Every email and meeting brought in from Google is removed
+ from the CRM. The next check starts from now, so nothing
+ deleted here comes back.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() => purge.mutate()}
+ >
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+
+ <AlertDialog>
+ <AlertDialogTrigger asChild>
+ <Button variant="ghost" size="xs" disabled={revoke.isPending}>
+ Revoke Google access
+ </Button>
+ </AlertDialogTrigger>
+
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Revoke Google access?</AlertDialogTitle>
+ <AlertDialogDescription>
+ You will be signed out, and you cannot use the CRM again
+ until you grant access.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() => revoke.mutate()}
+ >
+ Revoke
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+
+ <Button variant="ghost" size="xs" asChild>
+ <Link
+ href="https://myaccount.google.com/permissions"
+ target="_blank"
+ rel="noreferrer"
+ >
+ Manage in your Google account
+ </Link>
+ </Button>
+ </div>
+ </CardFooter>
+ </CardContent>
+ </Card>
);
}
diff --git a/apps/app/app/(app)/settings/page.tsx b/apps/app/app/(app)/settings/page.tsx
index f2c23916..2494b0dd 100644
--- a/apps/app/app/(app)/settings/page.tsx
+++ b/apps/app/app/(app)/settings/page.tsx
@@ -10,6 +10,7 @@ import {
import { requireSession } from "@/lib/session";
import { HydrateClient } from "@/lib/trpc/hydrate";
import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
+import { AgentModel } from "./agent-model";
import { GoogleConnection } from "./google-connection";
export const metadata: Metadata = {
@@ -22,9 +23,12 @@ export default async function SettingsPage() {
const trpc = getServerTrpc();
const queryClient = getServerQueryClient();
- // Awaited: the whole page is this one query, and rendering "Not connected"
- // for a beat before flipping to "Connected" is worse than waiting for it.
- await queryClient.prefetchQuery(trpc.google.status.queryOptions());
+ await Promise.all([
+ queryClient.prefetchQuery(trpc.google.status.queryOptions()),
+ queryClient.prefetchQuery(trpc.settings.agentModel.queryOptions()),
+ ]);
+
+ void queryClient.prefetchQuery(trpc.settings.modelCatalog.queryOptions());
return (
<PageShell>
@@ -39,7 +43,10 @@ export default async function SettingsPage() {
<PageShellContent>
<HydrateClient>
- <GoogleConnection />
+ <div className="flex max-w-3xl flex-col gap-6">
+ <GoogleConnection />
+ <AgentModel />
+ </div>
</HydrateClient>
</PageShellContent>
</PageShell>
diff --git a/apps/app/app/(auth)/grant-access/grant-access.tsx b/apps/app/app/(auth)/grant-access/grant-access.tsx
index a6e81bac..a5d5e62c 100644
--- a/apps/app/app/(auth)/grant-access/grant-access.tsx
+++ b/apps/app/app/(auth)/grant-access/grant-access.tsx
@@ -14,15 +14,8 @@ export function GrantAccess() {
async function handleGrant() {
setPending(true);
- // Absolute, like the sign-in button: the API owns /api/auth/*, so a
- // relative URL would resolve against the API's origin rather than this
- // app's. Better Auth checks it against the origins in APP_URL.
const origin = window.location.origin;
- // `linkSocial` rather than `signIn.social`: there is already a session and
- // an account row, and this is a scope upgrade on the existing grant.
- // Google's incremental authorisation means the resulting token covers the
- // union, so sign-in keeps working either way.
const { error } = await authClient.linkSocial({
provider: "google",
scopes: [...SYNC_SCOPES],
@@ -30,7 +23,6 @@ export function GrantAccess() {
errorCallbackURL: `${origin}/grant-access`,
});
- // On success the browser has already navigated to Google.
if (error) {
toast.error(error.message ?? "Could not reach Google.");
setPending(false);
@@ -64,10 +56,6 @@ export function GrantAccess() {
Grant access
</Button>
- {/*
- * Somebody who does not want to grant this needs a way out that is not
- * the back button into a redirect loop.
- */}
<Button
className="w-full"
onClick={() => {
diff --git a/apps/app/app/(auth)/grant-access/page.tsx b/apps/app/app/(auth)/grant-access/page.tsx
index c68eeb93..168b0451 100644
--- a/apps/app/app/(auth)/grant-access/page.tsx
+++ b/apps/app/app/(auth)/grant-access/page.tsx
@@ -10,16 +10,6 @@ export const metadata: Metadata = {
title: "Grant access",
};
-/**
- * The re-consent wall.
- *
- * Outside the `(app)` group deliberately: the gate lives in that group's
- * layout, so a page inside it would redirect to itself.
- *
- * Reached by someone who is signed in but has not granted Gmail and Calendar —
- * either they unticked a scope on Google's granular consent screen, or their
- * account predates those scopes being required.
- */
export default async function GrantAccessPage() {
const { user } = await requireSession();
@@ -28,8 +18,6 @@ export default async function GrantAccessPage() {
select: { scope: true },
});
- // Already granted — nothing to ask for. Guards the back button and a stale
- // link as much as anything.
if (hasSyncScopes(account?.scope)) {
redirect("/");
}
diff --git a/apps/app/app/(auth)/sign-in/google-sign-in.tsx b/apps/app/app/(auth)/sign-in/google-sign-in.tsx
index 8bf24c0c..8bee5dd7 100644
--- a/apps/app/app/(auth)/sign-in/google-sign-in.tsx
+++ b/apps/app/app/(auth)/sign-in/google-sign-in.tsx
@@ -13,9 +13,6 @@ export function GoogleSignIn() {
async function handleClick() {
setPending(true);
- // The API owns /api/auth/*, so both URLs have to be absolute — a relative
- // one would resolve against the API's origin, not this app's. Better Auth
- // checks them against the origins in APP_URL.
const origin = window.location.origin;
const { error } = await signIn.social({
@@ -24,7 +21,6 @@ export function GoogleSignIn() {
errorCallbackURL: `${origin}/sign-in`,
});
- // On success the client has already navigated to Google.
if (error) {
toast.error(error.message ?? "Could not reach the sign-in service.");
setPending(false);
diff --git a/apps/app/app/(auth)/sign-in/page.tsx b/apps/app/app/(auth)/sign-in/page.tsx
index 9fa27908..608dbee2 100644
--- a/apps/app/app/(auth)/sign-in/page.tsx
+++ b/apps/app/app/(auth)/sign-in/page.tsx
@@ -9,14 +9,6 @@ export const metadata: Metadata = {
};
export default async function SignInPage() {
- // The authoritative counterpart to the cookie sniff in `proxy.ts`, and the
- // reason that check is not in the proxy: only a session that verifies
- // against Postgres sends you back into the app. A cookie that no longer
- // resolves falls through to the form instead of ping-ponging with `/`.
- //
- // A database that cannot answer must not take this page down with it — it is
- // the one page that has to work when everything else is broken, so a failed
- // lookup counts as signed out.
const session = await getSession().catch((error: unknown) => {
console.error("Sign-in: could not read the session.", error);
return null;
diff --git a/apps/app/app/api/[...path]/route.ts b/apps/app/app/api/[...path]/route.ts
index 5dc69fbb..71435e7a 100644
--- a/apps/app/app/api/[...path]/route.ts
+++ b/apps/app/app/api/[...path]/route.ts
@@ -1,30 +1,13 @@
import { brotliDecompressSync, gunzipSync, inflateSync } from "node:zlib";
import { API_URL } from "@/lib/env";
-/**
- * Same-origin passthrough to the NestJS API.
- *
- * Without it every tRPC call from the browser would be a cross-origin,
- * credentialed request: CORS preflights, `SameSite` cookie rules and third-party
- * cookie blocking all become problems the moment the app and the API are not on
- * the same host. Forwarding through the app makes `/api/trpc` look local, and
- * the session cookie just works.
- */
-
-/**
- * `undici` transparently decompresses some responses and not others, so the
- * bytes we hold may or may not still be encoded. Try to decode; if it throws,
- * they were already plain.
- */
function decode(buf: Buffer, encoding: string | null): Buffer {
const enc = (encoding ?? "").toLowerCase();
try {
if (enc.includes("br")) return brotliDecompressSync(buf);
if (enc.includes("gzip")) return gunzipSync(buf);
if (enc.includes("deflate")) return inflateSync(buf);
- } catch {
- // Already decompressed upstream.
- }
+ } catch {}
return buf;
}
@@ -33,10 +16,6 @@ async function handler(request: Request): Promise<Response> {
const target = `${API_URL}${url.pathname}${url.search}`;
const headers = new Headers(request.headers);
- // Hop-by-hop and origin-describing headers belong to the browser→app hop,
- // not the app→API one. Leaving them on makes the API think it is behind a
- // proxy it is not, and re-sending `content-length` after we have touched the
- // body is a truncated request.
for (const header of [
"host",
"x-forwarded-host",
@@ -75,8 +54,6 @@ async function handler(request: Request): Promise<Response> {
responseHeaders.delete(header);
}
- // `Headers` folds repeated values into one comma-joined string, which mangles
- // cookies. `getSetCookie()` is the only way to keep them separate.
const setCookies = upstream.headers.getSetCookie?.() ?? [];
if (setCookies.length > 0) {
responseHeaders.delete("set-cookie");
@@ -85,8 +62,6 @@ async function handler(request: Request): Promise<Response> {
}
}
- // Streams pass straight through — buffering an SSE response would hold it
- // open forever and deliver nothing.
if (upstream.headers.get("content-type")?.includes("text/event-stream")) {
return new Response(upstream.body, {
status: upstream.status,
diff --git a/apps/app/app/eve/v1/[...path]/route.ts b/apps/app/app/eve/v1/[...path]/route.ts
index f83bc931..ed6d815f 100644
--- a/apps/app/app/eve/v1/[...path]/route.ts
+++ b/apps/app/app/eve/v1/[...path]/route.ts
@@ -5,21 +5,6 @@ import {
} from "@/lib/agent-bridge";
import { getSession } from "@/lib/session";
-/**
- * Same-origin passthrough to the research agent.
- *
- * Mounted at `/eve/v1/*` on purpose: that is where `useEveAgent()` looks by
- * default, so the panel needs no host configuration and the browser never
- * discovers that the agent is a separate deployment.
- *
- * Unlike the API proxy beside it, this one is an **enforcement point** rather
- * than a passthrough. The agent never sees the session cookie — it gets a
- * two-minute token minted here — so if this route did not check the session,
- * nothing downstream would. Every request is authenticated before it is
- * forwarded, and an unauthenticated one is refused rather than passed on.
- */
-
-/** Streaming, and per-request session reads. Never cache any of it. */
export const dynamic = "force-dynamic";
async function handler(request: Request): Promise<Response> {
@@ -40,10 +25,6 @@ async function handler(request: Request): Promise<Response> {
const headers = new Headers(request.headers);
- // Hop-by-hop and origin-describing headers belong to the browser→app hop,
- // not this one. `cookie` goes too: the agent has no use for a session it
- // cannot read, and forwarding credentials to a service that does not need
- // them is how they end up in somebody's log.
for (const header of [
"host",
"cookie",
@@ -60,11 +41,6 @@ async function handler(request: Request): Promise<Response> {
headers.delete(header);
}
- // Which record the rep has open, if any. Taken from a header the panel sets
- // and put into the token, so the agent gets it through the same
- // `session.auth` path the dispatcher uses — and the rep's own message stays
- // their own words. Not trusted for anything but focus: it decides what the
- // agent looks at, never what it may do.
const contactId = request.headers.get("x-crm-contact");
const companyId = request.headers.get("x-crm-company");
const dealId = request.headers.get("x-crm-deal");
@@ -92,8 +68,6 @@ async function handler(request: Request): Promise<Response> {
method: request.method,
headers,
redirect: "manual",
- // The event stream is long-lived and the client aborts it on unmount;
- // without this the upstream request outlives the reader.
signal: request.signal,
};
@@ -106,8 +80,6 @@ async function handler(request: Request): Promise<Response> {
try {
upstream = await fetch(target, init);
} catch (error) {
- // The agent being down is an ordinary condition for the rest of the CRM,
- // so it reads as one rather than a 500 with a stack trace in it.
return Response.json(
{
error: "The research agent is not reachable.",
@@ -127,9 +99,6 @@ async function handler(request: Request): Promise<Response> {
responseHeaders.delete(header);
}
- // The whole point of this route is the NDJSON event stream, so the body is
- // piped rather than buffered — reading it to completion first would deliver
- // the agent's reasoning in one lump after the run had already finished.
return new Response(upstream.body, {
status: upstream.status,
statusText: upstream.statusText,
@@ -147,7 +116,6 @@ export {
handler as PUT,
};
-/** A cuid, or nothing. Decides what the agent looks at, never what it may do. */
function cuid(value: string | null): string | undefined {
return value && /^[a-z0-9]{20,32}$/.test(value) ? value : undefined;
}
diff --git a/apps/app/app/layout.tsx b/apps/app/app/layout.tsx
index 5e8d23b9..d8280e30 100644
--- a/apps/app/app/layout.tsx
+++ b/apps/app/app/layout.tsx
@@ -8,8 +8,6 @@ import { NuqsAdapter } from "nuqs/adapters/next/app";
import { ThemeProvider } from "@/components/theme-provider";
import { TRPCReactProvider } from "@/lib/trpc/client";
-// --font-geist-sans / --font-geist-mono are the variables @crm/ui's theme reads
-// (see the @theme block in globals.css), so the design system picks these up.
const fontSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
@@ -26,8 +24,6 @@ export const metadata: Metadata = {
template: "%s · Comp AI CRM",
},
description: "Customer Relationship Management for Comp AI",
- // app/favicon.ico is picked up by Next's file convention and covers the
- // legacy /favicon.ico request on its own; these are the modern additions.
icons: {
icon: [
{ url: "/favicon.svg", type: "image/svg+xml" },
diff --git a/apps/app/components/app-header.tsx b/apps/app/components/app-header.tsx
index 4008a591..f44d2924 100644
--- a/apps/app/components/app-header.tsx
+++ b/apps/app/components/app-header.tsx
@@ -36,15 +36,9 @@ export function AppHeader({ user }: { user: User }) {
return;
}
- // A full navigation rather than router.push: the session cookie is gone,
- // so every cached server render has to be thrown away and `proxy.ts`
- // re-evaluated from scratch.
window.location.assign("/sign-in");
}
- // h-12 rather than mvp's h-14. mvp fills its bar with h-8 controls (org
- // switcher, search, credits), so 56px reads tight there; this bar holds only
- // a logo, a label and an avatar, so the same 56px reads empty.
return (
<header className="flex h-12 shrink-0 items-center gap-2 border-b px-3 [view-transition-name:app-header]">
<div className="flex shrink-0 items-center gap-1">
@@ -60,10 +54,6 @@ export function AppHeader({ user }: { user: User }) {
<Link
href="/"
aria-label="Homepage"
- // The mark wears the page's ink, not the brand green. `text-primary`
- // used to be near-black and became the accent when the palette
- // changed, which put a second green on screen competing with the
- // one button that is meant to be the only one.
className="hidden size-8 items-center justify-center text-foreground md:flex"
>
<Logo className="size-5" />
diff --git a/apps/app/components/crm/agent-conversations.tsx b/apps/app/components/crm/agent-conversations.tsx
index 60f8932c..94e778ff 100644
--- a/apps/app/components/crm/agent-conversations.tsx
+++ b/apps/app/components/crm/agent-conversations.tsx
@@ -26,14 +26,6 @@ const dateFormat = new Intl.DateTimeFormat(undefined, {
minute: "2-digit",
});
-/**
- * Which conversation you are in, and the ones before it.
- *
- * A record accumulates these — "is he still at Fleetio" on Monday, "what did
- * they announce" on Thursday — and the answers are worth keeping. Without this
- * the panel is a scratchpad that forgets, and a rep learns not to bother
- * typing into it.
- */
export function ConversationPicker({
conversations,
current,
@@ -133,12 +125,6 @@ function Forget({
);
}
-/**
- * The conversation list for one record.
- *
- * Read through the API's Redis-backed cache, so reopening a contact does not
- * pay for a query that changes only when somebody sends a message.
- */
export function useConversations(recordId: {
contactId?: string;
companyId?: string;
@@ -147,10 +133,6 @@ export function useConversations(recordId: {
return useQuery(trpc.conversations.list.queryOptions(recordId));
}
-/**
- * `pathKey()`, not `queryKey()` — the rule from `api.md`. The former carries no
- * query type, so it matches however the list is read.
- */
function useConversationCache() {
const trpc = useTRPC();
const queryClient = useQueryClient();
diff --git a/apps/app/components/crm/agent-panel.tsx b/apps/app/components/crm/agent-panel.tsx
index 72f9f972..48edb238 100644
--- a/apps/app/components/crm/agent-panel.tsx
+++ b/apps/app/components/crm/agent-panel.tsx
@@ -76,55 +76,12 @@ import {
import { useTRPC } from "@/lib/trpc/client";
import { useRecordSheetView } from "./record-sheet/record-stack";
-/**
- * The agent, on the record, while it works.
- *
- * The thing neither HubSpot nor Salesforce puts in front of a rep: not a
- * chatbot in a corner, but *this* agent working on *this* person, with its
- * steps visible and its questions answerable. Watching it reject a GitHub
- * account because that account is named somebody else is what makes the fields
- * it did fill in believable.
- *
- * Two choices carry the layout:
- *
- * - **The transcript is a `MessageScroller`,** which is doing more than it
- * looks. It follows streamed output only while the reader is already at the
- * bottom, so scrolling up to re-read a rejection does not get yanked away by
- * the next tool call. That behaviour is most of the reason to use it rather
- * than a `div`.
- * - **Tool calls are `Marker`s, not bubbles.** A bubble is something somebody
- * said; "read a LinkedIn profile" is something that happened. Rendering the
- * two differently is what makes a run skimmable — the eye can find three
- * sentences of prose among thirty steps.
- */
-/**
- * One record's panel, including which conversation is open.
- *
- * Which thread you are in lives in the URL (`?thread=`), like every other view
- * state in this sheet — so a refresh keeps your place and a conversation is a
- * link you can send someone. It is cleared when the record or the tab changes,
- * by the same rule that drops a half-typed quick-add form.
- *
- * **Nothing mounts until the list has loaded.** Rendering a thread while the
- * history is still in flight starts a *new* eve session, and the panel then
- * remounts onto the real one the moment the list arrives — which looked like
- * "the history only appears if I refresh or press something", because a second
- * visit had the list cached and got it right.
- */
export function AgentPanel({ record }: { record: AgentRecord }) {
const conversations = useConversations(recordFilter(record));
const { thread, setThread } = useRecordSheetView("overview");
const history = conversations.data ?? [];
- /**
- * Which conversation this panel opened on.
- *
- * Captured once, and deliberately not recomputed. Sending the first message
- * in a new thread adds a row to the list, and re-deriving "the latest one"
- * from that would change the `key` and remount the thread mid-answer — the
- * transcript would blink away while the agent was still talking.
- */
const landedOn = useRef<string | null>(null);
if (landedOn.current === null && conversations.isSuccess) {
landedOn.current = history[0]?.id ?? NEW_THREAD;
@@ -149,9 +106,6 @@ export function AgentPanel({ record }: { record: AgentRecord }) {
/>
<ThreadWithHistory
- // The selection, not the resolved row: the row gains a timestamp and
- // a message count as the conversation goes on, and none of that
- // should tear the session down.
key={openId ?? NEW_THREAD}
record={record}
conversation={current}
@@ -161,20 +115,6 @@ export function AgentPanel({ record }: { record: AgentRecord }) {
);
}
-/**
- * Loads a reopened thread's transcript before mounting it.
- *
- * `initialSession` seeds the session *identity and cursor* — it does not fetch
- * anything. Without `initialEvents` beside it the panel resumed the right
- * conversation and rendered it empty, which read as "my history is gone" while
- * the picker above it showed the thread's own title.
- *
- * Both come from one `session.snapshot()`: the events, the cursor to carry on
- * from, and — only if the session is genuinely parked — the token that lets the
- * next message land. Our own `AgentEvent` rows are the fallback for a thread
- * older than eve's 30-day retention, and for an agent that is not answering.
- */
-/** How often to re-ask a working session whether it has settled. */
const WORKING_POLL_MS = 3000;
function ThreadWithHistory({
@@ -188,9 +128,6 @@ function ThreadWithHistory({
}) {
const trpc = useTRPC();
- // The archive, for the two cases eve cannot answer: an expired session and
- // an agent that is down. Cheap — one indexed read — and it is also what
- // makes a month-old conversation still readable.
const archive = useQuery({
...trpc.conversations.events.queryOptions({ id: conversation?.id ?? "" }),
enabled: conversation !== null,
@@ -203,9 +140,6 @@ function ThreadWithHistory({
staleTime: 0,
refetchOnMount: "always",
refetchOnWindowFocus: false,
- // Only while a turn we are not attached to is running — after a reload
- // mid-answer, essentially. It stops on any other answer, and `loadThread`
- // retires a silent turn after ninety seconds, so it cannot spin forever.
refetchInterval: (query) =>
query.state.data?.status === "working" ? WORKING_POLL_MS : false,
queryFn: ({ signal }) =>
@@ -217,18 +151,11 @@ function ThreadWithHistory({
),
});
- // Mounting before the transcript arrives would build the projection from
- // nothing, and `initialEvents` is read once when the store is created — so
- // the history could never be added afterwards.
if (conversation && (archive.isPending || thread.isPending))
return <Loading />;
return (
<Thread
- // A turn that settles while we are watching from outside brings the
- // rest of the transcript with it, and that only reaches the store
- // through a remount. Nothing is streaming into the UI in that state,
- // so this is invisible other than the answer appearing.
key={thread.data?.status === "working" ? "working" : "settled"}
record={record}
conversation={conversation}
@@ -258,27 +185,14 @@ function Thread({
onNewThread: () => void;
}) {
const copy = recordCopy(record.kind);
- // The record travels in a header, which the proxy turns into a token claim
- // and the agent reads at `session.started`. Deliberately not in the message:
- // a rep's question should read as their question, not as
- // "About contact cmsai6u77… (…): Hey!".
const agent = useEveAgent({
headers: recordHeader(record),
- // Resumed from what `snapshot()` returned, not from what we had stored.
- // Its cursor points exactly after the events beside it, so the transcript
- // and the live stream meet with no gap and no overlap, and its token is
- // present only when the session will actually accept the next turn.
- //
- // An `offline` thread has events but no session: the transcript is still
- // readable, and the next message opens a fresh conversation rather than
- // being posted at a session we could not reach.
...(thread && "session" in thread
? { initialSession: thread.session, initialEvents: eventsOf(thread) }
: { initialEvents: eventsOf(thread) }),
});
const [draft, setDraft] = useState("");
- // Remembers the opening question so the thread has a name in the picker.
const opening = useRef<string | null>(conversation?.title ?? null);
useSavedConversation({
@@ -293,9 +207,6 @@ function Thread({
const messages = toTranscript(agent.data.messages);
const question = pendingQuestion(agent.data.messages);
- // Mid-turn is a wait; ended is permanent and needs a way out. Both used to
- // look identical from the outside: a composer that took a message and did
- // nothing at all with it.
const { locked, ended } = composerState(thread, busy);
const ask = (message: string) => {
@@ -307,22 +218,6 @@ function Thread({
return (
<div className="flex min-h-0 flex-1 flex-col">
- {/*
- * `autoScroll` and nothing else, deliberately.
- *
- * The scroller is a state machine — `following-bottom`,
- * `free-scrolling`, `anchored-to-message` — and `scrollAnchor` selects
- * the third. Anchoring a turn to the top of the viewport is the
- * ChatGPT behaviour, and it *stops the scroller following the bottom*:
- * the answer then streams below the fold while the two modes fight over
- * each new row, which is what the flicker was.
- *
- * Left alone, `autoScroll` does exactly what is wanted here: it keeps
- * the tail in view while the reader is at the bottom, and releases to
- * `free-scrolling` the moment they scroll away — so a reply that arrives
- * while you are reading something further up leaves you where you are
- * and lights the jump-to-end button instead.
- */}
<MessageScrollerProvider autoScroll defaultScrollPosition="end">
<MessageScroller className="flex-1">
<MessageScrollerViewport>
@@ -331,11 +226,6 @@ function Thread({
<Idle kind={record.kind} onAsk={ask} />
) : null}
- {/*
- * One row per message, which is the boundary the scroller
- * measures. A row per tool call would have it re-measuring
- * dozens of new boundaries inside a single answer.
- */}
{messages.map((message) => (
<MessageScrollerItem key={message.id} messageId={message.id}>
<div className="space-y-3">
@@ -360,11 +250,6 @@ function Thread({
{agent.error ? <Failure message={agent.error.message} /> : null}
- {/*
- * eve is explicit that only a *waiting* session accepts input. Sending
- * into one mid-turn used to do nothing at all, with no error — the
- * message went nowhere and the panel sat there. Saying so is the fix.
- */}
{thread?.status === "working" && !busy ? (
<p className="border-t px-5 py-2 text-muted-foreground text-xs">
Still working on the last question. Your next one can go in when it
@@ -372,14 +257,6 @@ function Thread({
</p>
) : null}
- {/*
- * An ended thread gets a way out rather than a locked box.
- *
- * This is where the panel stranded people: the agent had answered, the
- * answer was on screen, and the composer sat disabled under it with no
- * hint that the way on was to open a new thread. The transcript stays
- * exactly where it is; the button just moves the picker.
- */}
{ended ? (
<div className="flex items-center justify-between gap-3 border-t px-5 py-2">
<p className="text-muted-foreground text-xs">
@@ -418,17 +295,6 @@ function Thread({
);
}
-/**
- * The empty state, which is most reps' first impression of the agent.
- *
- * It says what the panel is *for* and gives something to press, because "ask me
- * anything" in front of somebody who has never used it produces nothing.
- *
- * Every word of it comes from `recordCopy`. A literal here is how this shipped
- * asking "Who is this person?" on a deal: the suggestions were wired to the
- * record and the heading above them was still hardcoded, so the two disagreed
- * on screen.
- */
function Idle({
kind,
onAsk,
@@ -438,13 +304,7 @@ function Idle({
}) {
const copy = recordCopy(kind);
- // The shared empty state, so the Agent tab reads like the Deals and Contacts
- // tabs beside it rather than like a second product. Only the mark differs —
- // this one is ours, not a Carbon glyph.
return (
- // `wide`, because this one sits in a record sheet rather than in a table
- // cell: at the narrow default measure the blurb broke over two lines and
- // the three questions wrapped onto two rows in a panel with room to spare.
<Empty width="wide">
<EmptyHeader>
<EmptyMedia>
@@ -472,13 +332,6 @@ function Idle({
);
}
-/**
- * Why the panel is not working, in terms of what to do about it.
- *
- * The two failures a self-hoster actually hits are "the agent is not running"
- * and "the two halves hold different secrets", and the bare text of an HTTP
- * error names neither.
- */
function Failure({ message }: { message: string }) {
const hint = message.includes("not reachable")
? "Start it with `bun run dev`, or check AGENT_URL."
@@ -520,17 +373,6 @@ function Item({ item }: { item: TranscriptItem }) {
<Message>
<AgentAvatar />
<MessageContent>
- {/*
- * `ghost`, so an answer runs full width with no surface behind it.
- * That is the AI Elements convention — "user messages in secondary
- * background and assistant messages full-width" — and it earns its
- * place here: these replies carry lists, links and the occasional
- * table, and a bubble at 80% width sets all of them in a column
- * half the panel wide.
- *
- * Markdown because the agent writes it. As plain text the same
- * answer reads as asterisks and pipes.
- */}
<Bubble variant="ghost">
<BubbleContent>
<Markdown>{item.text}</Markdown>
@@ -555,14 +397,6 @@ function Item({ item }: { item: TranscriptItem }) {
);
}
-/**
- * The pages behind a step.
- *
- * A stretch of `Attachment`'s remit — it is built for files — but a source is
- * the same shape: an icon, a name, and somewhere to go. The alternative was
- * inventing a chip, and `design.md` would rather we reached for what is already
- * in the package.
- */
function Sources({ sources }: { sources: Source[] }) {
return (
<AttachmentGroup>
@@ -575,12 +409,6 @@ function Sources({ sources }: { sources: Source[] }) {
<AttachmentTitle>{source.title}</AttachmentTitle>
</AttachmentContent>
- {/*
- * A stretched overlay rather than an anchor wrapped around the
- * card: it keeps the component's own layout intact, makes the whole
- * tile the hit area, and is what the root's `has-[>a]:hover` styling
- * is written against.
- */}
<AttachmentTrigger asChild>
<a href={source.url} target="_blank" rel="noreferrer noopener">
<span className="sr-only">Open {source.title}</span>
@@ -592,13 +420,6 @@ function Sources({ sources }: { sources: Source[] }) {
);
}
-/**
- * The agent wears the product's own mark.
- *
- * A generic robot glyph says "a chatbot was added here". The Comp AI logo says
- * this is the CRM speaking about its own record — which is what it is, and the
- * distinction is most of the difference in how much a rep trusts the answer.
- */
function AgentAvatar() {
return (
<MessageAvatar>
@@ -609,14 +430,6 @@ function AgentAvatar() {
);
}
-/**
- * The agent's own question, answered in place.
- *
- * The case the whole panel earns its keep on: several people with the same
- * surname work at the same company, and the person looking at the record knows
- * which one. `tinted` rather than a plain bubble because this one is *waiting*
- * on them — it should not read as more transcript.
- */
function Question({
question,
agent,
@@ -632,10 +445,6 @@ function Question({
<BubbleContent>{question.prompt}</BubbleContent>
</Bubble>
- {/*
- * `options` is optional: a freeform question has none, and the
- * composer under the transcript is how that one gets answered.
- */}
<div className="flex flex-wrap gap-2">
{(question.options ?? []).map((option) => (
<Button
@@ -659,17 +468,6 @@ function Question({
);
}
-/**
- * Writes the conversation's cursor back, so it can be reopened.
- *
- * `useEveAgent` hands out a serialisable `session` — id, continuation token,
- * how far the client has read — and that trio is the whole of what resuming a
- * thread needs. Saving it on change is what turns a scratchpad into history.
- *
- * Only when the cursor actually moves. The hook re-renders on every streamed
- * token, and a mutation per token would be a write storm for a value that
- * changes once a turn.
- */
function useSavedConversation({
record,
conversation,
@@ -680,7 +478,6 @@ function useSavedConversation({
record: { contactId?: string; companyId?: string; dealId?: string };
conversation: Conversation | null;
opening: React.RefObject<string | null>;
- /** `useEveAgent`'s own cursor. */
session: {
sessionId?: string;
continuationToken?: string;
@@ -697,23 +494,11 @@ function useSavedConversation({
const streamIndex = session?.streamIndex ?? 0;
const { contactId, companyId, dealId } = record;
- // **Not just "there was no conversation when we mounted".**
- //
- // A thread that has ended cannot be continued, so the next message opens a
- // fresh eve session inside the same mounted panel — a different session id
- // under the same row. That is a new conversation by every meaning that
- // matters here: it needs its own title, and the picker has to learn it
- // exists. Comparing the ids is what catches both cases with one rule.
const isNew = conversation === null || conversation.sessionId !== sessionId;
- // Everything the effect needs but must not re-run for. `save` and `record`
- // are new objects on every render, and this hook renders on every streamed
- // token — in the dependency array they would run the effect thousands of
- // times a conversation to do nothing.
const latest = useRef({ save, queryClient, trpc, opening });
latest.current = { save, queryClient, trpc, opening };
- // The last cursor written, so an unchanged one is not written again.
const written = useRef<string | null>(null);
useEffect(() => {
@@ -742,10 +527,6 @@ function useSavedConversation({
...(isNew ? { title: title.current ?? undefined } : {}),
},
{
- // A thread that has just come into existence has to appear in the
- // picker without a reload — that was the "history only shows up if I
- // refresh" half of this. An existing one has only moved its
- // timestamp, and refetching for that mid-answer is churn.
onSuccess: () => {
if (!isNew) return;
void cache.invalidateQueries({
diff --git a/apps/app/components/crm/closing-window.ts b/apps/app/components/crm/closing-window.ts
index 9c1ee2f3..92d983c9 100644
--- a/apps/app/components/crm/closing-window.ts
+++ b/apps/app/components/crm/closing-window.ts
@@ -1,9 +1,3 @@
-/**
- * Buckets for the "closing" facet, in the order a rep would scan them.
- *
- * Kept in step with `CLOSING_WINDOWS` in `apps/api/src/deals/deals.contracts.ts`
- * — the API owns which dates fall in which bucket; this is only the labels.
- */
export const CLOSING_OPTIONS = [
{ value: "overdue", label: "Overdue" },
{ value: "this-month", label: "Closing this month" },
diff --git a/apps/app/components/crm/company-cell.tsx b/apps/app/components/crm/company-cell.tsx
index afa42434..93212fab 100644
--- a/apps/app/components/crm/company-cell.tsx
+++ b/apps/app/components/crm/company-cell.tsx
@@ -10,12 +10,10 @@ export type CompanyRef = {
domain: string | null;
iconUrl: string | null;
iconDarkUrl?: string | null;
- /** `opaque` | `dark` | `light` — see `EntityLogo`. */
iconTone?: string | null;
logoUrl?: string | null;
};
-/** A company where it appears inside another record's row. */
export function CompanyCell({ company }: { company: CompanyRef | null }) {
if (!company) return <EmptyCellValue />;
diff --git a/apps/app/components/crm/contact-name.ts b/apps/app/components/crm/contact-name.ts
index 9e09acc0..74958f79 100644
--- a/apps/app/components/crm/contact-name.ts
+++ b/apps/app/components/crm/contact-name.ts
@@ -1,10 +1,3 @@
-/**
- * A contact's display name.
- *
- * Only `firstName` is required, so the join has to survive a missing surname
- * without leaving a trailing space behind — the table and the record sheet had
- * a copy of this each, which is one copy too many for a rule this small.
- */
export function contactName(contact: {
firstName: string;
lastName: string | null;
diff --git a/apps/app/components/crm/deal-stage.tsx b/apps/app/components/crm/deal-stage.tsx
index 0b38d8f9..2ae37ae4 100644
--- a/apps/app/components/crm/deal-stage.tsx
+++ b/apps/app/components/crm/deal-stage.tsx
@@ -1,20 +1,9 @@
-// `@crm/db/enums` and not `@crm/db`: the package root exports the Prisma client
-// instance, so a value import of an enum drags `pg` — and its `node:dns`
-// dependency — into the browser bundle. The generated enums module is a
-// standalone file of string constants.
import { DealStage } from "@crm/db/enums";
import {
StatusIndicator,
type StatusTone,
} from "@crm/ui/components/status-indicator";
-/**
- * Stage presentation, in pipeline order.
- *
- * `UNQUALIFIED_TO_BUY` sits with the other closed stages rather than between
- * "qualified" and "decision maker bought in": it is a disqualification, so
- * showing it mid-funnel would suggest a deal is progressing when it is over.
- */
const ORDER = [
DealStage.DEMO_BOOKED,
DealStage.QUALIFIED_TO_BUY,
@@ -35,15 +24,12 @@ const PRESENTATION: Record<DealStage, { label: string; tone: StatusTone }> = {
UNQUALIFIED_TO_BUY: { label: "Unqualified", tone: "neutral" },
};
-/** Stages a deal can still be won from — the pipeline. */
export const OPEN_STAGES = ORDER.slice(0, 4) as readonly DealStage[];
-/** Won, lost or disqualified — a deal that is no longer in the pipeline. */
export function isClosedStage(stage: DealStage): boolean {
return !OPEN_STAGES.includes(stage);
}
-/** The two the API refuses without a `closedReason`. */
export const LOSING_STAGES: readonly DealStage[] = [
DealStage.CLOSED_LOST,
DealStage.UNQUALIFIED_TO_BUY,
@@ -54,13 +40,6 @@ export const DEAL_STAGE_OPTIONS = ORDER.map((value) => ({
label: PRESENTATION[value].label,
}));
-/**
- * The chart ramp in pipeline order, so a stage is the same colour in the
- * overview's donut, its legend and every meter beside a deal.
- *
- * Only the open stages get one: a closed deal is not part of a breakdown of
- * where the pipeline sits, and `StatusTone` already colours won and lost.
- */
const OPEN_STAGE_COLORS = [
"var(--chart-1)",
"var(--chart-2)",
diff --git a/apps/app/components/crm/enrichment-actions.tsx b/apps/app/components/crm/enrichment-actions.tsx
index bcb106a3..90c899d7 100644
--- a/apps/app/components/crm/enrichment-actions.tsx
+++ b/apps/app/components/crm/enrichment-actions.tsx
@@ -10,13 +10,6 @@ import { toast } from "sonner";
import { useCrmCache } from "@/lib/trpc/cache";
import { useTRPC } from "@/lib/trpc/client";
-/**
- * The two things a rep can ask the agent for.
- *
- * Both are background work with no immediate result to show, so neither
- * navigates or blocks: the enrichment chip in the header goes to "Enriching"
- * and the page polls until it settles, and the brief appears on the timeline.
- */
export function EnrichmentActions({
companyId,
hasDomain,
@@ -51,16 +44,11 @@ export function EnrichmentActions({
}),
);
- // These sit in the sheet header, which on a phone is a full-width drawer
- // with a logo and a name already in it. The labels drop below `sm` so the
- // record's name keeps the room rather than two buttons about the agent.
return (
<>
<Button
variant="outline"
size="sm"
- // Without a domain there is nothing to look up, and the API would only
- // come back and say so.
disabled={!hasDomain || enrich.isPending}
onClick={() => enrich.mutate({ id: companyId })}
>
@@ -72,8 +60,6 @@ export function EnrichmentActions({
<span className="hidden sm:inline">Re-enrich</span>
</Button>
- {/* Research is the action on this record, so it takes the fill.
- * Re-enrich beside it is the quieter "do that again". */}
<Button
size="sm"
disabled={!hasDomain || research.isPending}
@@ -89,3 +75,36 @@ export function EnrichmentActions({
</>
);
}
+
+export function ContactEnrichmentAction({ contactId }: { contactId: string }) {
+ const trpc = useTRPC();
+ const cache = useCrmCache();
+
+ const enrich = useMutation(
+ trpc.contacts.enrich.mutationOptions({
+ onSuccess: async () => {
+ await cache.contact(contactId);
+ toast.success(
+ "Taking another look — this page will update when it finishes.",
+ );
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ return (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={enrich.isPending}
+ onClick={() => enrich.mutate({ id: contactId })}
+ >
+ {enrich.isPending ? (
+ <Spinner />
+ ) : (
+ <Icon icon={Renew} data-icon="inline-start" />
+ )}
+ <span className="hidden sm:inline">Re-enrich</span>
+ </Button>
+ );
+}
diff --git a/apps/app/components/crm/enrichment-status.tsx b/apps/app/components/crm/enrichment-status.tsx
index 34efb692..b93d9dba 100644
--- a/apps/app/components/crm/enrichment-status.tsx
+++ b/apps/app/components/crm/enrichment-status.tsx
@@ -4,19 +4,6 @@ import {
type StatusTone,
} from "@crm/ui/components/status-indicator";
-/**
- * How the agent is getting on with a record.
- *
- * `SKIPPED` is neutral, not an error: there was nothing to find (an unknown
- * domain, a free email host), and no credits were spent. `FAILED` is the one
- * worth chasing.
- *
- * `PENDING` is the awkward one, and it is why this takes a `queued` flag. It is
- * the column's *default*, so it is true of every record from the moment it is
- * inserted — it means "no research has run", which is not the same as "research
- * is about to run". Rendering it unconditionally as "Queued" told every rep
- * that all 62 unenriched records were in a queue that held 3.
- */
const PRESENTATION: Record<
EnrichmentStatus,
{ label: string; tone: StatusTone; busy?: boolean }
@@ -28,7 +15,6 @@ const PRESENTATION: Record<
SKIPPED: { label: "Nothing found", tone: "neutral" },
};
-/** What `PENDING` becomes when the agent really does have the record on its list. */
const QUEUED = { label: "Queued", tone: "neutral" as StatusTone, busy: false };
function present(status: EnrichmentStatus, queued: boolean) {
@@ -37,9 +23,7 @@ function present(status: EnrichmentStatus, queued: boolean) {
export function EnrichmentIndicator({
status,
- /** Whether an unfinished agent task names this record. */
queued = false,
- /** The error, when there is one — shown on hover rather than in the row. */
title,
className,
}: {
@@ -61,26 +45,12 @@ export function EnrichmentIndicator({
);
}
-/**
- * Still going to change on its own.
- *
- * Enrichment is background work with no client action behind it, so there is
- * nothing to invalidate — the only way to notice it finished is to ask. Anything
- * rendering an enriched field (a logo, an industry) polls on this while it is
- * true and stops the moment it settles.
- *
- * `PENDING` alone is not enough to keep polling, and used to be: a contact
- * could never leave it, so every open contact sheet asked the server the same
- * question every three seconds until the tab was closed.
- */
export function isEnriching(status: EnrichmentStatus, queued = false): boolean {
return status === "RUNNING" || (status === "PENDING" && queued);
}
-/** How often to ask, in ms, while the agent is still working. */
export const ENRICHMENT_POLL_MS = 3_000;
-/** Statuses in the order the facet dropdown should list them. */
export const ENRICHMENT_FACET_OPTIONS = (
Object.keys(PRESENTATION) as EnrichmentStatus[]
).map((value) => ({ value, label: PRESENTATION[value].label }));
diff --git a/apps/app/components/crm/facts.tsx b/apps/app/components/crm/facts.tsx
index eede71db..420c68cf 100644
--- a/apps/app/components/crm/facts.tsx
+++ b/apps/app/components/crm/facts.tsx
@@ -17,33 +17,18 @@ const dateFormat = new Intl.DateTimeFormat(undefined, {
year: "numeric",
});
-/**
- * The facts on a record, split the way the sheet renders them.
- *
- * `applied` decorates the value already in the field; `proposed` sits under an
- * empty one. Nothing else is returned, because dismissed and superseded facts
- * are history and the timeline is where history goes.
- */
export function factsByField(facts: Fact[]) {
const applied = new Map<string, Fact>();
const proposed = new Map<string, Fact>();
for (const fact of facts) {
const bucket = fact.status === "APPLIED" ? applied : proposed;
- // Ordered newest-first by the API, so the first one wins.
if (!bucket.has(fact.field)) bucket.set(fact.field, fact);
}
return { applied, proposed };
}
-/**
- * The tooltip body for a value the agent wrote.
- *
- * A field a person typed has no fact behind it and gets nothing — which is the
- * distinction the underline is *for*. Decorating everything would make it mean
- * nothing.
- */
export function provenanceFor(fact: Fact) {
return (
<Provenance
@@ -55,13 +40,6 @@ export function provenanceFor(fact: Fact) {
);
}
-/**
- * A proposal, and the two buttons that settle it.
- *
- * Accepting is the most valuable click in the product: it fills a field *and*
- * labels a training example for the confidence model, from the one person who
- * actually knows the answer.
- */
export function FactSuggestion({
fact,
contactId,
diff --git a/apps/app/components/crm/inline-field.tsx b/apps/app/components/crm/inline-field.tsx
index 86579815..a731467f 100644
--- a/apps/app/components/crm/inline-field.tsx
+++ b/apps/app/components/crm/inline-field.tsx
@@ -17,30 +17,11 @@ import { cn } from "@crm/ui/lib/utils";
import { useId, useState } from "react";
import { PROPERTY_LABEL, PROPERTY_ROW } from "@/components/detail-sheet";
-// The row shape is the sheet's, not this file's — a read-only fact and an
-// editable field are the same row with a different value slot.
const ROW = cn(PROPERTY_ROW, "items-center");
const LABEL = PROPERTY_LABEL;
-/**
- * Values look like text until you point at one.
- *
- * A row of boxed inputs shouts "form" at someone who came here to read a
- * record; a row of plain text gives no hint that a typo is one click from
- * fixed. The hover outline is the whole affordance, and it is the same on a
- * typed field and a chosen one so nothing looks more editable than the rest.
- */
const CONTROL =
"h-8 w-full justify-start px-2 font-normal hover:border-input hover:bg-muted/40 border border-transparent";
-/**
- * Which property a record's shared update mutation is currently writing.
- *
- * One `update` serves every row in a sheet, so its `isPending` says only that
- * *something* is saving. Handing that to each row puts a spinner on all seven
- * of them the moment you correct one — the whole form flashes for a write to a
- * single field. The variables of the write name the field, so the spinner can
- * land on the row that was actually edited and nowhere else.
- */
export function savingField(update: {
isPending: boolean;
variables?: { data?: object } | undefined;
@@ -68,21 +49,8 @@ export function InlineField({
saving?: boolean;
placeholder?: string;
type?: "text" | "url" | "email" | "tel";
- /** How the saved value reads when not being edited — a link, usually. */
render?: (value: string) => React.ReactNode;
- /**
- * Where this value came from, when a machine put it there.
- *
- * Left off, the field looks exactly as it always did — which is the right
- * default for the ones a person typed, and the only reason the underline
- * means anything on the ones they did not.
- */
provenance?: React.ReactNode;
- /**
- * Something the agent believes but is not sure enough to write. Rendered
- * *under* the field, never inside it: a suggestion that looks like a value
- * is a lie with a nice font.
- */
suggestion?: React.ReactNode;
}) {
const id = useId();
@@ -94,29 +62,14 @@ export function InlineField({
if (draft.trim() !== (value ?? "")) onSave(draft.trim());
};
- // Mid-write, the row reads back what was typed rather than what the record
- // still says. The input closes on commit but the new value only arrives with
- // the refetch, so reading `value` here would show the old one for the length
- // of a round trip — which looks like the edit was thrown away.
const shown = saving ? draft.trim() : (value ?? "");
const sourced = Boolean(provenance) && !editing && shown !== "";
- /**
- * A single element, never a fragment.
- *
- * When this row carries provenance it becomes a tooltip trigger, and Radix's
- * `asChild` clones the child to pass `aria-describedby` and its open state
- * onto it. A fragment cannot take props, so wrapping the ternary in one threw
- * `Invalid prop \`aria-describedby\` supplied to \`React.Fragment\`` — on
- * every field in the sheet, because the trigger is decided per row.
- */
const control = editing ? (
<Input
id={id}
type={type}
- // The input only exists because the user just clicked this field;
- // not focusing it would mean clicking twice to type once.
autoFocus
value={draft}
placeholder={placeholder}
@@ -156,9 +109,6 @@ export function InlineField({
</Button>
);
- // The tooltip goes on the control the row already has, rather than a new
- // wrapper: pointing at a value explains it, tabbing to it does the same, and
- // nothing extra becomes clickable.
const body =
sourced && provenance ? (
<SourcedValue source={provenance}>{control}</SourcedValue>
@@ -177,9 +127,6 @@ export function InlineField({
);
}
- // A suggestion belongs to its field, so it sits under it in the value
- // column rather than becoming a row of its own that a reader has to
- // associate back to something.
return (
<div className={cn(ROW, "items-start")}>
<label htmlFor={id} className={cn(LABEL, "pt-2")}>
@@ -193,14 +140,6 @@ export function InlineField({
);
}
-/**
- * The same row, for a day chosen from a calendar.
- *
- * A date is the one property here that was never really text: typed, it wanted
- * `2026-12-31` and silently kept the old value for anything else, so the
- * placeholder had to teach the format. The picker is the same ghost control as
- * the select below it, and `""` means the rep cleared it.
- */
export function InlineDateField({
label,
value,
@@ -209,7 +148,6 @@ export function InlineDateField({
placeholder = "—",
}: {
label: string;
- /** An ISO timestamp or a day string; only the day is read. */
value: string | null;
onSave: (next: string) => void;
saving?: boolean;
@@ -236,7 +174,6 @@ export function InlineDateField({
);
}
-/** The same row, for a value chosen from a list rather than typed. */
export function InlineSelectField({
label,
value,
@@ -258,8 +195,6 @@ export function InlineSelectField({
{label}
</label>
<Select value={value} onValueChange={onSave}>
- {/* `default` size, matching the text rows' 32px — a select that is a
- pixel shorter than the field above it makes the column look bent. */}
<SelectTrigger id={id} variant="ghost" className="w-full">
<SelectValue placeholder={placeholder} />
</SelectTrigger>
diff --git a/apps/app/components/crm/owner-cell.tsx b/apps/app/components/crm/owner-cell.tsx
index d588990a..3996f6cd 100644
--- a/apps/app/components/crm/owner-cell.tsx
+++ b/apps/app/components/crm/owner-cell.tsx
@@ -14,10 +14,8 @@ export type Owner = {
image: string | null;
};
-/** The person a company, contact or deal is assigned to. */
export function OwnerCell({
owner,
- /** Avatar only — for tight spots like a board card footer. */
compact = false,
}: {
owner: Owner | null;
diff --git a/apps/app/components/crm/quick-switcher.tsx b/apps/app/components/crm/quick-switcher.tsx
index 55837c4c..2152a4c8 100644
--- a/apps/app/components/crm/quick-switcher.tsx
+++ b/apps/app/components/crm/quick-switcher.tsx
@@ -13,6 +13,7 @@ import {
EntityLogo,
type EntityLogoTone,
} from "@crm/ui/components/entity-logo";
+import { PersonAvatar } from "@crm/ui/components/person-avatar";
import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";
import { useQuery } from "@tanstack/react-query";
import { parseAsBoolean, useQueryState } from "nuqs";
@@ -28,14 +29,6 @@ const GROUP_LABEL = {
const KINDS = ["company", "contact", "deal"] as const;
-/**
- * ⌘K over companies, contacts and deals.
- *
- * Open state is in the URL like every other overlay here, so a colleague can be
- * sent `?k=true` and land on the same thing. The query itself is not — a
- * half-typed search is not a view worth sharing, and it would put every
- * keystroke in the history.
- */
export function QuickSwitcher() {
const openRecord = useOpenRecord();
const trpc = useTRPC();
@@ -43,8 +36,6 @@ export function QuickSwitcher() {
const [open, setOpen] = useQueryState("k", parseAsBoolean.withDefault(false));
const [query, setQuery] = useState("");
- // The keyboard shortcut is a document-level listener, which is exactly what
- // `useMountEffect` is for — it is a subscription, not derived state.
useMountEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "k" && (event.metaKey || event.ctrlKey)) {
@@ -59,7 +50,6 @@ export function QuickSwitcher() {
const results = useQuery({
...trpc.search.quick.queryOptions({ q: query }),
- // Two characters is where the results stop being "everything".
enabled: open && query.trim().length >= 2,
placeholderData: (previous) => previous,
});
@@ -79,11 +69,6 @@ export function QuickSwitcher() {
title="Search"
description="Jump to a company, contact or deal"
>
- {/*
- * `shouldFilter={false}`: the API already matched and ranked these,
- * against fields the row does not always render (an email, a domain).
- * Letting cmdk filter again would drop hits whose match is invisible.
- */}
<Command shouldFilter={false}>
<CommandInput
placeholder="Search companies, contacts and deals…"
@@ -109,13 +94,21 @@ export function QuickSwitcher() {
value={`${hit.kind}:${hit.id}`}
onSelect={() => go(kind, hit.id)}
>
- <EntityLogo
- src={hit.iconUrl}
- darkSrc={hit.iconDarkUrl}
- tone={hit.iconTone as EntityLogoTone | null | undefined}
- name={hit.label}
- size="sm"
- />
+ {hit.kind === "contact" ? (
+ <PersonAvatar
+ src={hit.imageUrl}
+ name={hit.label}
+ size="sm"
+ />
+ ) : (
+ <EntityLogo
+ src={hit.iconUrl}
+ darkSrc={hit.iconDarkUrl}
+ tone={hit.iconTone as EntityLogoTone | null | undefined}
+ name={hit.label}
+ size="sm"
+ />
+ )}
<span className="flex min-w-0 flex-col">
<span className="truncate">{hit.label}</span>
{hit.detail ? (
diff --git a/apps/app/components/crm/record-sheet/company-sheet.tsx b/apps/app/components/crm/record-sheet/company-sheet.tsx
index 17a8a718..6125afdc 100644
--- a/apps/app/components/crm/record-sheet/company-sheet.tsx
+++ b/apps/app/components/crm/record-sheet/company-sheet.tsx
@@ -12,6 +12,7 @@ import {
type EntityLogoTone,
} from "@crm/ui/components/entity-logo";
import { Icon } from "@crm/ui/components/icon";
+import { PersonAvatar } from "@crm/ui/components/person-avatar";
import { SimpleTable, SimpleTableRow } from "@crm/ui/components/simple-table";
import { TableCell } from "@crm/ui/components/table";
import {
@@ -70,15 +71,6 @@ type CompanyDeal = Company["deals"][number];
const UNASSIGNED = "unassigned";
-/**
- * The fields only the agent can fill, that it has not filled yet.
- *
- * Strictly the ones with no editor anywhere in this sheet. Phone, email, city
- * and country are `InlineField`s a rep types into, so their emptiness means
- * "nobody has entered this" — listing them here would blame the agent for a
- * blank a human was always going to fill, and imply it was off looking for
- * something it never looks for.
- */
function pendingFields(company: Company): string[] {
const missing: string[] = [];
if (!company.industry) missing.push("industry");
@@ -114,7 +106,6 @@ const shortDateFormat = new Intl.DateTimeFormat(undefined, {
day: "numeric",
});
-/** The soonest a deal here could land, which is the number reps forecast on. */
function nextClose(deals: CompanyDeal[]): string | null {
const dates = deals
.map((deal) => deal.expectedCloseDate)
@@ -123,12 +114,6 @@ function nextClose(deals: CompanyDeal[]): string | null {
return dates[0] ?? null;
}
-/**
- * The last row of a list: "add another one".
- *
- * Part of the table rather than a button floating above it, so the affordance
- * is where you finish reading and does not need its own band of chrome.
- */
function AddRow({
label,
columns,
@@ -155,17 +140,8 @@ function AddRow({
);
}
-/**
- * A company, everything attached to it, and the agent's work on it.
- *
- * Polls while the agent is running: enrichment is a background write with no
- * client action behind it, so there is nothing to invalidate — the only way to
- * notice it finished is to ask. The interval stops the moment it settles.
- */
export function CompanySheet({ companyId }: { companyId: string }) {
const trpc = useTRPC();
- // Tab and quick-add form both live in `?tab=` / `?add=`, so a half-typed
- // contact survives a refresh and lands on the panel it was typed into.
const {
tab,
setTab,
@@ -248,12 +224,7 @@ export function CompanySheet({ companyId }: { companyId: string }) {
{
value: "agent",
label: "Agent",
- // Bare, not inside `DetailSheetBody`: the panel brings its own
- // scroll container, and nesting two gives the sheet two
- // scrollbars.
content: <AgentPanel record={{ kind: "company", id: company.id }} />,
- // Stays mounted behind the other tabs: this one holds a live
- // stream, and tearing it down mid-answer loses the answer.
keepMounted: true,
},
]
@@ -274,10 +245,6 @@ export function CompanySheet({ companyId }: { companyId: string }) {
/>
) : undefined
}
- // Only when there is something to say. "Enriched" is the resting state
- // of every company in here, and a row that says so on all of them is a
- // row nobody reads — which means nobody reads it when it says "failed"
- // either.
note={
company && company.enrichmentStatus !== "COMPLETE" ? (
<EnrichmentIndicator
@@ -349,8 +316,6 @@ function CompanyOverview({
const update = useMutation(
trpc.companies.update.mutationOptions({
- // `settle: "record"` — the row's spinner should last until the new value
- // is under it, not until the table behind the sheet has caught up too.
onSuccess: () => cache.company(company.id, { settle: "record" }),
onError: (error) => toast.error(error.message),
}),
@@ -371,14 +336,7 @@ function CompanyOverview({
</DetailSheetSection>
) : null}
- {/*
- * Promoted out of its tab. "Who do we know there" is the question a
- * rep opens a company to answer, and it was behind a click while
- * eight label/value rows had the whole panel.
- */}
<DetailSheetSection title="People">
- {/* Adding happens on the Contacts tab, which owns the form:
- * two quick-add forms bound to one `?add=` would both open. */}
<CompanyContacts
company={company}
adding={false}
@@ -389,11 +347,6 @@ function CompanyOverview({
</DetailSheetMain>
<DetailSheetRail>
- {/*
- * Only the fields a rep would correct by hand are editable: the brand,
- * industry and socials come from the agent, and a text box inviting
- * someone to retype them is a text box inviting someone to fight it.
- */}
<DetailSheetSection title="Details">
<DetailSheetProperties columns={1}>
<InlineField
@@ -548,8 +501,6 @@ function CompanyContacts({
size="icon-xs"
aria-pressed={isPrimary}
disabled={isPrimary || setPrimary.isPending}
- // Without this the row's own handler fires too and opens
- // the contact over the change just made.
onClick={(event) => {
event.stopPropagation();
setPrimary.mutate({
@@ -570,9 +521,21 @@ function CompanyContacts({
</Tooltip>
</TableCell>
<TableCell className="truncate px-3 py-2.5 font-medium">
- {[contact.firstName, contact.lastName]
- .filter(Boolean)
- .join(" ")}
+ <span className="flex min-w-0 items-center gap-2">
+ <PersonAvatar
+ src={contact.imageUrl}
+ name={[contact.firstName, contact.lastName]
+ .filter(Boolean)
+ .join(" ")}
+ email={contact.email}
+ size="sm"
+ />
+ <span className="truncate">
+ {[contact.firstName, contact.lastName]
+ .filter(Boolean)
+ .join(" ")}
+ </span>
+ </span>
</TableCell>
<TableCell className="truncate px-3 py-2.5">
{contact.title ?? <EmptyCellValue />}
diff --git a/apps/app/components/crm/record-sheet/contact-sheet.tsx b/apps/app/components/crm/record-sheet/contact-sheet.tsx
index b60255e5..ce319f3c 100644
--- a/apps/app/components/crm/record-sheet/contact-sheet.tsx
+++ b/apps/app/components/crm/record-sheet/contact-sheet.tsx
@@ -16,6 +16,7 @@ import {
type EntityLogoTone,
} from "@crm/ui/components/entity-logo";
import { Icon } from "@crm/ui/components/icon";
+import { PersonAvatar } from "@crm/ui/components/person-avatar";
import { SimpleTable, SimpleTableRow } from "@crm/ui/components/simple-table";
import { StatusIndicator } from "@crm/ui/components/status-indicator";
import { TableCell } from "@crm/ui/components/table";
@@ -23,6 +24,7 @@ import { useMutation, useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { AgentPanel } from "@/components/crm/agent-panel";
import { contactName } from "@/components/crm/contact-name";
+import { ContactEnrichmentAction } from "@/components/crm/enrichment-actions";
import {
ENRICHMENT_POLL_MS,
EnrichmentIndicator,
@@ -82,10 +84,6 @@ export function ContactSheet({ contactId }: { contactId: string }) {
const cache = useCrmCache();
const { tab, setTab } = useRecordSheetView("overview");
- // Polls while the agent is working, for the same reason the company sheet
- // does: enrichment is a background write with no client action behind it, so
- // there is nothing to invalidate and the only way to notice it finished is
- // to ask. Stops the moment it settles.
const query = useQuery({
...trpc.contacts.byId.queryOptions({ id: contactId }),
refetchInterval: (current) => {
@@ -128,17 +126,7 @@ export function ContactSheet({ contactId }: { contactId: string }) {
{
value: "agent",
label: "Agent",
- // A tab rather than a band on the overview: the panel opens a
- // durable session the moment it mounts, and a rep flicking through
- // records should not start one on every contact they glance at.
- //
- // Rendered bare, not inside `DetailSheetBody`. That wrapper is
- // itself a scroll container, and the panel brings its own — nesting
- // them gives the sheet two scrollbars and an agent transcript that
- // cannot reach its own bottom.
content: <AgentPanel record={{ kind: "contact", id: contact.id }} />,
- // Stays mounted behind the other tabs: this one holds a live
- // stream, and tearing it down mid-answer loses the answer.
keepMounted: true,
},
]
@@ -154,9 +142,6 @@ export function ContactSheet({ contactId }: { contactId: string }) {
<MetaLine parts={[contact.title, contact.company?.name]} />
) : undefined
}
- // Only when there is something to say. "Enriched" is the resting state
- // of every contact in here, and a row that says so on all of them is a
- // row nobody reads — which means nobody reads it when it says "failed".
note={
contact ? (
<>
@@ -176,17 +161,18 @@ export function ContactSheet({ contactId }: { contactId: string }) {
</>
) : null
}
- // A person, so initials rather than a logo — there are no avatars in
- // the CRM and a broken image placeholder is worse than two letters.
- // Still `EntityLogo` with no artwork: it draws exactly this, and a
- // hand-rolled square meant the contact header wore a border the company
- // header does not.
media={
- <EntityLogo name={contact ? contactName(contact) : "?"} size="lg" />
+ <PersonAvatar
+ src={contact?.imageUrl}
+ name={contact ? contactName(contact) : "?"}
+ email={contact?.email}
+ size="lg"
+ />
}
actions={
contact ? (
<>
+ <ContactEnrichmentAction contactId={contact.id} />
{contact.email ? (
<Button asChild variant="outline" size="sm">
<a href={`mailto:${contact.email}`}>
@@ -202,8 +188,6 @@ export function ContactSheet({ contactId }: { contactId: string }) {
disabled={setPrimary.isPending}
onClick={() =>
setPrimary.mutate({
- // Narrowed by the guard above; the API re-checks that this
- // person actually works there.
companyId: contact.company?.id ?? "",
contactId: contact.id,
})
@@ -216,8 +200,6 @@ export function ContactSheet({ contactId }: { contactId: string }) {
</>
) : null
}
- // How to reach this person, which is what anyone opening a contact
- // wants — the deal count is already on the tab beside it.
stats={
contact ? (
<DetailSheetStats>
@@ -299,7 +281,6 @@ function ContactOverview({ contact }: { contact: Contact }) {
const { applied, proposed } = factsByField(contact.facts);
- /** Everything a field needs to show where it came from and what is pending. */
const agentProps = (field: string) => {
const fact = applied.get(field);
const suggestion = proposed.get(field);
@@ -313,9 +294,6 @@ function ContactOverview({ contact }: { contact: Contact }) {
const update = useMutation(
trpc.contacts.update.mutationOptions({
- // `settle: "record"` — the row's spinner should last until the new value
- // is under it, not until the list behind the sheet and every cached
- // company have caught up too.
onSuccess: () => cache.contact(contact.id, { settle: "record" }),
onError: (error) => toast.error(error.message),
}),
@@ -372,13 +350,6 @@ function ContactOverview({ contact }: { contact: Contact }) {
onSave={(linkedinUrl) => save({ linkedinUrl })}
{...agentProps("linkedinUrl")}
/>
- {/*
- * No placeholders on these two. An empty inline field renders its
- * placeholder as the value, so an example handle reads as this
- * person's account rather than as a hint — and a plausible wrong
- * link on every contact is exactly the failure the rest of this
- * agent is built to avoid.
- */}
<InlineField
label="X"
value={contact.twitterUrl}
@@ -442,18 +413,6 @@ function ContactOverview({ contact }: { contact: Contact }) {
);
}
-/**
- * Who this person is, above the fields that describe them.
- *
- * The prose and the lines under it do different jobs and are stored separately
- * for that reason: the narrative is what a rep reads on the way into a call,
- * the lines are what they scan for one number — how long have they been there.
- *
- * Everything here was written by the agent, so the whole section is sourced
- * once at the top rather than field by field. Repeating a dotted underline on
- * six consecutive agent-written lines would decorate the section, not inform
- * anyone.
- */
function Background({ brief }: { brief: NonNullable<Contact["brief"]> }) {
const sections = brief.sections;
const previous = sections.previousRoles ?? [];
@@ -505,20 +464,6 @@ function Background({ brief }: { brief: NonNullable<Contact["brief"]> }) {
);
}
-/**
- * Where they worked before, folded away.
- *
- * It used to be one `·`-joined string, which was unreadable for a reason worth
- * writing down: the agent writes each role as `"Head of Growth · Leap AI (Mar
- * 2024 – Oct 2024)"`, so the separator between roles was the same separator
- * used *inside* them. Six jobs came out as one forty-word sentence with no way
- * to tell where a job ended.
- *
- * Closed by default because the narrative directly above already says this in
- * prose — "he previously spent eight months as Head of Growth at Leap AI" —
- * and the list is the dates behind that sentence, not news. One line when you
- * do not need it, one click when you do.
- */
function PreviousRoles({ roles }: { roles: string[] }) {
return (
<Accordion type="single" collapsible>
@@ -549,18 +494,6 @@ function daysAgo(iso: string): string {
return relativeFormat.format(-days, "day");
}
-/**
- * What we have actually said to each other.
- *
- * The block no CRM that buys its data can render. Everything above it could be
- * purchased from a vendor; this is ours, and it is the part a rep checks last
- * before dialling — have they ever replied, when, and who else do we know
- * there.
- *
- * "Never replied" is stated rather than omitted. Twelve emails into silence is
- * a fact about the relationship, and a panel that shows only the twelve reads
- * like progress.
- */
function WeKnowThem({
relationship,
contactName: name,
diff --git a/apps/app/components/crm/record-sheet/deal-sheet.tsx b/apps/app/components/crm/record-sheet/deal-sheet.tsx
index 89ec9489..fe81a614 100644
--- a/apps/app/components/crm/record-sheet/deal-sheet.tsx
+++ b/apps/app/components/crm/record-sheet/deal-sheet.tsx
@@ -6,6 +6,7 @@ import {
EntityLogo,
type EntityLogoTone,
} from "@crm/ui/components/entity-logo";
+import { PersonAvatar } from "@crm/ui/components/person-avatar";
import { SimpleTable, SimpleTableRow } from "@crm/ui/components/simple-table";
import { TableCell } from "@crm/ui/components/table";
import {
@@ -51,8 +52,6 @@ const CONTACT_COLUMNS = [
{ header: "Email", width: "w-[25%]" },
];
-// For `closedAt`, which is a real instant: the moment somebody marked the deal
-// won or lost. A close *date* is a day, and goes through `formatDay`.
const dateFormat = new Intl.DateTimeFormat(undefined, {
month: "short",
day: "numeric",
@@ -88,11 +87,7 @@ export function DealSheet({ dealId }: { dealId: string }) {
{
value: "agent",
label: "Agent",
- // Bare, not inside `DetailSheetBody`: the panel brings its own
- // scroll container.
content: <AgentPanel record={{ kind: "deal", id: deal.id }} />,
- // Stays mounted behind the other tabs: this one holds a live
- // stream, and tearing it down mid-answer loses the answer.
keepMounted: true,
},
]
@@ -103,8 +98,6 @@ export function DealSheet({ dealId }: { dealId: string }) {
loading={query.isPending}
error={query.error?.message ?? null}
title={deal?.name ?? "Deal"}
- // A deal is always somebody's deal, so the company is the subtitle and
- // it opens rather than just naming itself.
description={
deal ? (
<button
@@ -127,10 +120,6 @@ export function DealSheet({ dealId }: { dealId: string }) {
/>
) : null
}
- // A deal's stage is the state it is in and the thing you change about
- // it, so it is one control in the header — the same picker the deals
- // table puts in every row — rather than a read-only cell in the stats
- // strip plus a row of buttons further down the panel.
actions={
deal ? (
<DealStageMenu
@@ -154,16 +143,11 @@ export function DealSheet({ dealId }: { dealId: string }) {
</DetailSheetStat>
<DetailSheetStat label="Expected close">
{deal.expectedCloseDate ? (
- // The stored day, not the local rendering of a midnight-UTC
- // timestamp — that read a day early west of Greenwich and
- // disagreed with the close-date row further down the sheet.
formatDay(deal.expectedCloseDate)
) : (
<EmptyCellValue />
)}
</DetailSheetStat>
- {/* How long it has sat where it is — the staleness read that
- used to be a line of small print under the title. */}
<DetailSheetStat label="In stage">
{relativeTimeFromIso(deal.stageChangedAt)}
</DetailSheetStat>
@@ -189,9 +173,6 @@ function DealOverview({ deal }: { deal: Deal }) {
const update = useMutation(
trpc.deals.update.mutationOptions({
- // `settle: "record"` — the row's spinner should last until the new value
- // is under it, not until the board behind the sheet and every cached
- // company have caught up too.
onSuccess: () => cache.deal(deal.id, { settle: "record" }),
onError: (error) => toast.error(error.message),
}),
@@ -204,18 +185,9 @@ function DealOverview({ deal }: { deal: Deal }) {
return (
<DetailSheetBody>
- {/* Where the deal is, as a picture. Setting the stage — including
- * closing it — is the control in the header; this is the one-click
- * nudge to the next step. */}
<DetailSheetSection title="Stage">
<StageStepper dealId={deal.id} stage={deal.stage} />
- {/*
- * Two properties under the rail rather than an alert of its own.
- * The rail's last segment already says the deal is lost; a bordered
- * callout underneath repeats that in a heavier voice, and it was the
- * only boxed thing in any of the three sheets.
- */}
{deal.closedReason ? (
<DetailSheetProperties>
<DetailSheetProperty label="Closed">
@@ -242,7 +214,6 @@ function DealOverview({ deal }: { deal: Deal }) {
/>
<InlineField
label="Amount"
- // Edited in whole currency; stored and summed in cents.
value={
deal.amountCents === null ? null : String(deal.amountCents / 100)
}
@@ -325,7 +296,21 @@ function DealContacts({ deal }: { deal: Deal }) {
onClick={() => openRecord({ kind: "contact", id: contact.id })}
>
<TableCell className="truncate py-2.5 pr-3 pl-5 font-medium">
- {[contact.firstName, contact.lastName].filter(Boolean).join(" ")}
+ <span className="flex min-w-0 items-center gap-2">
+ <PersonAvatar
+ src={contact.imageUrl}
+ name={[contact.firstName, contact.lastName]
+ .filter(Boolean)
+ .join(" ")}
+ email={contact.email}
+ size="sm"
+ />
+ <span className="truncate">
+ {[contact.firstName, contact.lastName]
+ .filter(Boolean)
+ .join(" ")}
+ </span>
+ </span>
</TableCell>
<TableCell className="truncate px-3 py-2.5">
{contact.role ?? <EmptyCellValue />}
diff --git a/apps/app/components/crm/record-sheet/quick-add.tsx b/apps/app/components/crm/record-sheet/quick-add.tsx
index a635a2d6..9eba77aa 100644
--- a/apps/app/components/crm/record-sheet/quick-add.tsx
+++ b/apps/app/components/crm/record-sheet/quick-add.tsx
@@ -11,17 +11,6 @@ import { toast } from "sonner";
import { useCrmCache } from "@/lib/trpc/cache";
import { useTRPC } from "@/lib/trpc/client";
-/**
- * Adding a person or a deal without leaving the company you are looking at.
- *
- * An inline panel rather than a dialog over the sheet: you are already two
- * layers deep, a third one that has to be dismissed before you can see whether
- * the row landed is a layer too many. It also means adding three people in a
- * row is three forms, not three round trips through a modal.
- *
- * Only the fields you would actually have to hand go here. Everything else is
- * one click away on the record it just created.
- */
function QuickAddForm({
submitLabel,
pending,
@@ -71,7 +60,6 @@ export function QuickAddContact({
onDone,
}: {
companyId: string;
- /** Whoever owns the company — the person adding them almost never differs. */
ownerId: string | null;
onDone: () => void;
}) {
@@ -167,7 +155,6 @@ export function QuickAddDeal({
}: {
companyId: string;
companyName: string;
- /** The company's owner; falls back to whoever is signed in. */
ownerId: string | null;
onDone: () => void;
}) {
@@ -182,8 +169,6 @@ export function QuickAddDeal({
const amountId = useId();
const closeId = useId();
- // The API refuses a deal without an owner, and asking who owns a deal on
- // the company you already own is a question with one answer.
const me = useQuery(trpc.users.me.queryOptions());
const owner = ownerId ?? me.data?.id ?? null;
diff --git a/apps/app/components/crm/record-sheet/record-link.tsx b/apps/app/components/crm/record-sheet/record-link.tsx
index 7c0d5a24..c7aaa8f4 100644
--- a/apps/app/components/crm/record-sheet/record-link.tsx
+++ b/apps/app/components/crm/record-sheet/record-link.tsx
@@ -4,13 +4,6 @@ import { cn } from "@crm/ui/lib/utils";
import type { ReactNode } from "react";
import { type RecordKind, useOpenRecord } from "./record-stack";
-/**
- * A cross-reference to another record.
- *
- * A button rather than an anchor because there is nowhere to navigate to: the
- * record opens over whatever you are already looking at, and the URL it would
- * have pointed at is the one this sets.
- */
export function RecordLink({
kind,
id,
@@ -28,8 +21,6 @@ export function RecordLink({
<button
type="button"
onClick={(event) => {
- // Rows and cards are clickable too; without this both fire and the
- // wrong record wins.
event.stopPropagation();
open({ kind, id });
}}
diff --git a/apps/app/components/crm/record-sheet/record-parts.tsx b/apps/app/components/crm/record-sheet/record-parts.tsx
index 86976dd9..476eb4b4 100644
--- a/apps/app/components/crm/record-sheet/record-parts.tsx
+++ b/apps/app/components/crm/record-sheet/record-parts.tsx
@@ -11,19 +11,6 @@ import {
} from "@/components/detail-sheet";
import { useRecordStack } from "./record-stack";
-/**
- * The frame every record sheet is poured into.
- *
- * The contents of the panel, not the panel: the one dialog every record is
- * shown in belongs to `RecordSheetHost`, so stepping sideways from a company
- * to one of its deals swaps what is in here without rebuilding the panel
- * around it.
- *
- * The header renders before the record has loaded — a sheet has to have a
- * title from the first frame or the dialog is unlabelled, and a panel that
- * pops into existence a beat after the click reads as a bug rather than as
- * loading.
- */
export function RecordSheetFrame({
loading,
error,
@@ -49,9 +36,6 @@ export function RecordSheetFrame({
tab: string;
onTabChange: (tab: string) => void;
}) {
- // Back and close read from the same stack, so the frame does not need them
- // passed down: Back appears when there is a record underneath, and closing
- // leaves the trail.
const { stack, close, closeAll } = useRecordStack();
return (
@@ -89,7 +73,6 @@ export function RecordSheetFrame({
);
}
-/** Money, or the dash that means nobody has put a number on it yet. */
export function DealAmount({
amountCents,
currency,
@@ -103,11 +86,6 @@ export function DealAmount({
);
}
-/**
- * A record's meta line: `attio.com · London · Software`, with the first part
- * optionally a link. Assembled here so a company, a contact and a deal all
- * separate their facts the same way.
- */
export function MetaLine({
lead,
parts,
@@ -115,10 +93,6 @@ export function MetaLine({
lead?: ReactNode;
parts: (string | null | undefined)[];
}) {
- // Deduplicated, case-insensitively. The parts come from different fields that
- // can legitimately hold the same string — a contact at a company called
- // Architect whose title is "Architect" would otherwise read
- // "Architect · Architect", and render two children under the same key.
const seen = new Set<string>();
const rest: string[] = [];
@@ -146,7 +120,6 @@ export function MetaLine({
);
}
-/** The domain, as a link, which is what a domain is. */
export function DomainLink({
domain,
website,
diff --git a/apps/app/components/crm/record-sheet/record-prefetch.ts b/apps/app/components/crm/record-sheet/record-prefetch.ts
index dbf479f0..597f8a35 100644
--- a/apps/app/components/crm/record-sheet/record-prefetch.ts
+++ b/apps/app/components/crm/record-sheet/record-prefetch.ts
@@ -5,29 +5,12 @@ import { useCallback } from "react";
import { useTRPC } from "@/lib/trpc/client";
import type { RecordRef } from "./record-stack";
-/**
- * Warms the record a row would open, on hover.
- *
- * Opening a sheet is otherwise a cold fetch, so the panel arrives with a
- * spinner and a placeholder title and only becomes the record a moment later —
- * which reads as the sheet not having opened at all. A hover is half a second
- * of warning, and it is free: the query client's 30s `staleTime` means moving
- * back over the same row costs nothing.
- *
- * Takes a `RecordRef` so it is the exact twin of `useOpenRecord` at the call
- * site — `prefetchRecord(ref)` on hover, `openRecord(ref)` on click. Which
- * query backs which kind is decided here rather than in each of the three
- * tables, for the same reason `useCrmCache` owns invalidation.
- */
export function usePrefetchRecord() {
const trpc = useTRPC();
const queryClient = useQueryClient();
return useCallback(
({ kind, id }: RecordRef) => {
- // A switch rather than a kind → options lookup: each procedure returns a
- // different row shape, so a map of them is a union `prefetchQuery` will
- // not accept. Three lines, and every branch keeps its own types.
switch (kind) {
case "company":
void queryClient.prefetchQuery(
diff --git a/apps/app/components/crm/record-sheet/record-sheet-host.tsx b/apps/app/components/crm/record-sheet/record-sheet-host.tsx
index ee947c81..b765d826 100644
--- a/apps/app/components/crm/record-sheet/record-sheet-host.tsx
+++ b/apps/app/components/crm/record-sheet/record-sheet-host.tsx
@@ -8,20 +8,9 @@ import { ContactSheet } from "./contact-sheet";
import { DealSheet } from "./deal-sheet";
import { type RecordRef, recordKey, useRecordStack } from "./record-stack";
-/**
- * The one place a company, contact or deal is rendered.
- *
- * Mounted in the app shell rather than per page, so opening a contact from a
- * deal on the deals table works the same as opening one from the contacts
- * table — and so no list has to carry a copy of every sheet a row might lead
- * to.
- */
export function RecordSheetHost() {
const { stack, top, closeAll } = useRecordStack();
- // The record that was last open, kept a beat longer than the URL says.
- // Unmounting the instant `?record=` clears would cut the close animation
- // off halfway and make the sheet vanish rather than slide out.
const [shown, setShown] = useState<RecordRef | null>(top);
if (top && (!shown || recordKey(shown) !== recordKey(top))) {
setShown(top);
@@ -29,34 +18,12 @@ export function RecordSheetHost() {
return (
<>
- {/*
- * One dialog for every record, out here rather than inside each sheet.
- * Stepping sideways — a company to one of its deals to somebody on that
- * deal — then only swaps the contents, and the panel, its backdrop and
- * the body scroll lock stay exactly where they are.
- *
- * A dialog per record would instead be torn out and rebuilt on that
- * move, because the sheet being unmounted is a different component from
- * the one taking its place. Radix only animates the `open` prop
- * changing, so the old panel disappears without sliding out, the new
- * one replays its slide-in from the right, and the list behind the
- * translucent backdrop jumps by the width of the scrollbar as the
- * scroll lock is released and immediately re-applied. That is the
- * flicker, and it is not the record loading — it happens between two
- * records already in cache.
- */}
<DetailSheet
open={stack.length > 0}
onOpenChange={(next) => {
if (!next) closeAll();
}}
>
- {/*
- * Keyed by record so moving to another one starts fresh: a sheet on
- * Overview, scrolled to the top, rather than inheriting where you
- * happened to be in the last one. Inside the dialog, so that reset
- * costs the contents and not the panel around them.
- */}
{shown?.kind === "company" ? (
<CompanySheet key={recordKey(shown)} companyId={shown.id} />
) : null}
@@ -70,11 +37,6 @@ export function RecordSheetHost() {
) : null}
</DetailSheet>
- {/*
- * "Why did we lose it?" is asked from a table row, a board card and a
- * deal sheet. One dialog for all of them, reading which deal from the
- * URL, beats one per row.
- */}
<CloseReasonDialog />
</>
);
diff --git a/apps/app/components/crm/record-sheet/record-stack.ts b/apps/app/components/crm/record-sheet/record-stack.ts
index dab9a6c6..1a2b74a8 100644
--- a/apps/app/components/crm/record-sheet/record-stack.ts
+++ b/apps/app/components/crm/record-sheet/record-stack.ts
@@ -18,45 +18,20 @@ export type RecordKind = (typeof RECORD_KINDS)[number];
export type RecordRef = { kind: RecordKind; id: string };
-/** The quick-add forms a record sheet can have open inside it. */
const RECORD_FORMS = ["contact", "deal"] as const;
export type RecordForm = (typeof RECORD_FORMS)[number];
-/** The panel a quick-add form belongs to. */
const FORM_TAB: Record<RecordForm, string> = {
contact: "contacts",
deal: "deals",
};
-/**
- * Everything about what the sheet is showing: which records are open
- * (innermost last), which tab of the innermost one, which quick-add form inside
- * that, and how the Activity panel is filtered.
- *
- * A stack rather than a single id because the interesting move is sideways:
- * from a company to one of its deals to somebody on that deal. Closing the
- * deal should put you back on the company you came from, not on the table.
- *
- * All four ride in one hook so a write to any of them can clear the others.
- * Moving to another record has to reset the tab, drop a half-typed form and
- * forget the timeline filter — otherwise they reappear, out of context, on
- * whatever you opened next.
- *
- * They replace rather than push: flicking through tabs is reading, not
- * navigating, and a Back button that walks you through four panels before it
- * closes the sheet is a Back button nobody presses twice.
- */
const params = {
record: parseAsArrayOf(parseAsString, ",").withDefault([]),
tab: parseAsString,
add: parseAsStringLiteral(RECORD_FORMS),
- // Which agent conversation is open. `new` is a value rather than the
- // absence of one: "start a fresh thread" and "resume the latest" are
- // different intentions, and the absence has to mean the second.
thread: parseAsString,
- // Owned by the timeline, cleared from here. `useQueryState` over there and
- // this entry are the same key, so the two stay in step.
[TIMELINE_PARAM]: timelineTabParser,
};
@@ -84,7 +59,6 @@ export function useRecordStack() {
const write = useCallback(
(next: RecordRef[], history: "push" | "replace") => {
void setParams(
- // `null` clears each param rather than leaving `?record=` behind.
{
record: next.length === 0 ? null : next.map(recordKey),
tab: null,
@@ -98,20 +72,9 @@ export function useRecordStack() {
[setParams],
);
- /**
- * The whole trail is one history entry.
- *
- * Opening the first record pushes; stepping sideways to a related one
- * replaces. So the browser's Back always means "put the sheet away and give
- * me the list back" — one press, from however deep — and it never lands on
- * a half-unwound trail or reopens something that was just dismissed. Moving
- * up one level is what the sheet's own Back button is for.
- */
const open = useCallback(
(ref: RecordRef) => {
const key = recordKey(ref);
- // Re-opening something already below you promotes it instead of
- // stacking a second copy, so the trail cannot loop back on itself.
write(
[...stack.filter((entry) => recordKey(entry) !== key), ref],
stack.length === 0 ? "push" : "replace",
@@ -120,13 +83,11 @@ export function useRecordStack() {
[stack, write],
);
- /** Up one level, to whatever you opened this record from. */
const close = useCallback(
() => write(stack.slice(0, -1), "replace"),
[stack, write],
);
- /** Out of the trail entirely — the X, Escape, and clicking the backdrop. */
const closeAll = useCallback(() => write([], "replace"), [write]);
return {
@@ -138,35 +99,17 @@ export function useRecordStack() {
};
}
-/** Opens a record from anywhere — a table row, a link, a search hit. */
export function useOpenRecord() {
return useRecordStack().open;
}
-/**
- * What the open record sheet is showing — the tab, and the quick-add form
- * inside it.
- *
- * In the URL rather than component state, like every other view state here:
- * "the Attio deal, on Activity" is then a link you can send someone, and a
- * half-finished "add a contact" survives a refresh instead of being silently
- * discarded.
- */
export function useRecordSheetView(fallbackTab: string) {
const [{ tab, add, thread }, setParams] = useQueryStates(params);
- // A form open in a panel implies the panel: landing on `?add=contact`
- // should show the contacts tab, not leave the form mounted out of sight
- // behind whichever tab happened to be the default.
const active = add ? FORM_TAB[add] : (tab ?? fallbackTab);
const setTab = useCallback(
(next: string) => {
- // Leaving the panel abandons the form that lived in it and the filter
- // that was on it — the tabs unmount their contents, so a timeline
- // returned to has always started at All; the param going too is what
- // keeps that true now the filter outlives the component. The default
- // tab is the absence of the param rather than a value.
void setParams({
tab: next === fallbackTab ? null : next,
add: null,
diff --git a/apps/app/components/crm/social-links.tsx b/apps/app/components/crm/social-links.tsx
index 81e0d905..d1398eb7 100644
--- a/apps/app/components/crm/social-links.tsx
+++ b/apps/app/components/crm/social-links.tsx
@@ -23,11 +23,6 @@ export type ContactLinks = {
githubUrl: string | null;
};
-/**
- * The website is not in this list — it is the domain in the sheet header,
- * which is a link, because that is what a domain should be. What is left are
- * the places the agent found this company that its name does not give you.
- */
const COMPANY_LINKS: Link<CompanyLinks>[] = [
{ key: "linkedinUrl", label: "LinkedIn", icon: LogoLinkedin },
{ key: "twitterUrl", label: "X", icon: LogoX },
@@ -36,12 +31,6 @@ const COMPANY_LINKS: Link<CompanyLinks>[] = [
{ key: "careersUrl", label: "Careers", icon: UserMultiple },
];
-/**
- * The same row for a person, minus the two that only a company has.
- *
- * Email and phone are not here either: they are in the stats strip at the top
- * of the sheet, where the answer to "how do I reach them" belongs.
- */
const CONTACT_LINKS: Link<ContactLinks>[] = [
{ key: "linkedinUrl", label: "LinkedIn", icon: LogoLinkedin },
{ key: "twitterUrl", label: "X", icon: LogoX },
@@ -63,14 +52,6 @@ export function hasContactLinks(contact: ContactLinks): boolean {
return present(contact, CONTACT_LINKS).length > 0;
}
-/**
- * Every link says where it goes.
- *
- * A bare row of glyphs works for LinkedIn and GitHub, whose marks people know,
- * and fails for "pricing" and "careers", which have no mark — so the row comes
- * out half legible and reads as clip art. Labels cost one line and remove the
- * guessing.
- */
function SocialLinks<T>({ record, links }: { record: T; links: Link<T>[] }) {
const rows = present(record, links);
diff --git a/apps/app/components/crm/stage-change.tsx b/apps/app/components/crm/stage-change.tsx
index 43818b25..243caca5 100644
--- a/apps/app/components/crm/stage-change.tsx
+++ b/apps/app/components/crm/stage-change.tsx
@@ -34,19 +34,11 @@ import {
LOSING_STAGES,
} from "./deal-stage";
-/**
- * Which deal is being closed out, and to what.
- *
- * In the URL rather than component state so one dialog can serve every row of
- * the table as well as the detail page — and so a half-finished "why did we
- * lose this?" survives a refresh instead of silently discarding the answer.
- */
const closeReasonParams = {
closing: parseAsString,
closingStage: parseAsString,
};
-/** Invalidates everywhere a stage is visible. */
function useStageMutation(onDone?: () => void) {
const trpc = useTRPC();
const cache = useCrmCache();
@@ -62,18 +54,6 @@ function useStageMutation(onDone?: () => void) {
);
}
-/**
- * The one place a deal's stage is set — a table cell, a board card, or the
- * header of the deal's own sheet.
- *
- * `inline` is for a cell in a list, where a bordered control in every row
- * would out-shout the rows. `control` is for a sheet header, where it sits
- * beside real buttons and has to look like one.
- *
- * Losing stages divert through `CloseReasonDialog`: the API refuses them
- * without a reason, so asking here is friendlier than a toast full of the
- * rejection.
- */
export function DealStageMenu({
dealId,
stage,
@@ -89,7 +69,6 @@ export function DealStageMenu({
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
- {/* The row underneath opens a record on click; this control does not. */}
{variant === "control" ? (
<Button
variant="outline"
@@ -112,9 +91,6 @@ export function DealStageMenu({
)}
</DropdownMenuTrigger>
<DropdownMenuContent
- // The header control sits at the right edge of the sheet, so its menu
- // hangs from that edge rather than being pushed back by collision
- // detection a beat after it opens.
align={variant === "control" ? "end" : "start"}
className="min-w-52"
onClick={(event) => event.stopPropagation()}
@@ -145,12 +121,6 @@ export function DealStageMenu({
);
}
-/**
- * Asks why a deal was lost or disqualified.
- *
- * Rendered once per page; which deal it is about comes from the URL, so every
- * row can open it without each one carrying a dialog of its own.
- */
export function CloseReasonDialog() {
const reasonId = useId();
const [{ closing, closingStage }, setCloseParams] =
diff --git a/apps/app/components/crm/stage-stepper.tsx b/apps/app/components/crm/stage-stepper.tsx
index 4fc5ebae..849beac8 100644
--- a/apps/app/components/crm/stage-stepper.tsx
+++ b/apps/app/components/crm/stage-stepper.tsx
@@ -13,24 +13,8 @@ import {
import { useCrmCache } from "@/lib/trpc/cache";
import { useTRPC } from "@/lib/trpc/client";
-/**
- * Won is the end of the pipeline, so it is the last step on the rail.
- *
- * Lost and unqualified are not — they are exits, they can happen from any
- * step, and the API refuses them without a reason. Those stay in the stage
- * control in the header, which knows to ask why.
- */
const RAIL = [...OPEN_STAGES, DealStage.CLOSED_WON] as readonly DealStage[];
-/**
- * How far along the deal is, as a rail of segments.
- *
- * Mostly the picture, not the picker — jumping backwards, reopening and
- * closing-as-lost live in the stage control in the sheet header, next to the
- * record's name where the other sheets keep their state. What is here is the
- * move a rep makes constantly: nudging a deal to the next step, in one click,
- * all the way through to won.
- */
export function StageStepper({
dealId,
stage,
@@ -51,8 +35,6 @@ export function StageStepper({
}),
);
- // A deal that was lost or disqualified never reached won, so the rail shows
- // its four open steps unlit and hands the last segment to the outcome.
const exited = isClosedStage(stage) && stage !== DealStage.CLOSED_WON;
const steps = exited ? OPEN_STAGES : RAIL;
const currentIndex = steps.indexOf(stage);
@@ -78,9 +60,6 @@ export function StageStepper({
)}
>
<span className="block truncate">
- {/* The last segment is the outcome slot: the win the deal is
- heading for while it is open, and the actual result once
- it is not. */}
{current && option === DealStage.CLOSED_WON ? (
<DealStageIndicator stage={stage} className="text-xs" />
) : (
@@ -92,11 +71,6 @@ export function StageStepper({
);
})}
- {/*
- * Lost or disqualified, as the final segment. Not a button: coming back
- * into the pipeline means choosing a step, which the four to its left
- * already do, and a rail whose end undoes itself on click is a trap.
- */}
{exited ? (
<li className="flex min-w-0 flex-1">
<div className="min-w-0 flex-1 border-foreground border-t-2 pt-2">
diff --git a/apps/app/components/crm/sync-status.tsx b/apps/app/components/crm/sync-status.tsx
index 91472463..2e3e2f53 100644
--- a/apps/app/components/crm/sync-status.tsx
+++ b/apps/app/components/crm/sync-status.tsx
@@ -4,13 +4,6 @@ import {
type StatusTone,
} from "@crm/ui/components/status-indicator";
-/**
- * How a mailbox sync is getting on.
- *
- * `NEEDS_RECONNECT` is deliberately not an error tone shared with `FAILED`:
- * a failure is ours to chase, a reconnect is the rep's to fix, and the settings
- * page needs to tell those apart at a glance.
- */
const PRESENTATION: Record<
GoogleSyncStatus,
{ label: string; tone: StatusTone; busy?: boolean }
@@ -53,17 +46,8 @@ export function SyncIndicator({
);
}
-/**
- * Still going to change on its own.
- *
- * A sync is background work no client action caused, so — exactly like
- * enrichment — there is nothing to invalidate and the only way to notice it
- * finished is to ask. One definition, so the settings page and the record sheet
- * cannot disagree about when to stop asking.
- */
export function isSyncing(status: GoogleSyncStatus | null): boolean {
return status === "RUNNING";
}
-/** How often to ask, in ms, while a sync is still working. */
export const SYNC_POLL_MS = 5_000;
diff --git a/apps/app/components/crm/timeline/activity-composer.tsx b/apps/app/components/crm/timeline/activity-composer.tsx
index 61b16167..a5d22174 100644
--- a/apps/app/components/crm/timeline/activity-composer.tsx
+++ b/apps/app/components/crm/timeline/activity-composer.tsx
@@ -1,8 +1,6 @@
"use client";
import Calendar from "@carbon/icons-react/es/Calendar";
-// The shadcn calendar, aliased so it does not collide with the Carbon glyph on
-// the button that opens it.
import { Calendar as DayPicker } from "@crm/ui/components/calendar";
import { Icon } from "@crm/ui/components/icon";
import {
@@ -26,8 +24,6 @@ import { useTRPC } from "@/lib/trpc/client";
import { ActivityIcon, activityLabel } from "./activity-icon";
import type { TimelineAnchor } from "./timeline";
-/** Only what a person can log. Stage changes and enrichment write themselves,
- * and the API's create input refuses the other two for the same reason. */
const TYPES = ["NOTE", "CALL", "EMAIL", "MEETING", "TASK"] as const;
type ComposableType = (typeof TYPES)[number];
@@ -45,35 +41,6 @@ const PLACEHOLDER: Record<ComposableType, string> = {
TASK: "What needs doing?",
};
-/**
- * Logging what just happened: one box, and a toolbar inside it.
- *
- * Two rewrites got here, and both of the things it replaced are worth naming.
- *
- * It began as a button that swapped itself for a form — so reading the timeline
- * cost a click, and the state you were left in *after* logging one note was the
- * state that pushed the history off the fold. Then it lost the mode but kept
- * the shape: a bordered textarea, a bordered row of five type buttons, and a
- * bordered row of six filters underneath, three stacked bands of outlined boxes
- * for a panel whose actual job is to be read.
- *
- * This is one bordered element. The type toggles live *inside* the box, under a
- * rule, the way a formatting toolbar does — which is also what stops them
- * reading as a second copy of the filter row directly below, since that one is
- * borderless and outside. The submit button is always there and always in the
- * same place; nothing appears or disappears as you type, so nothing jumps.
- *
- * **There is no subject field.** It was optional on three types, load-bearing
- * on one, and the source of most of the branching in here — the old form asked
- * a different question per type and then disagreed with itself about which
- * answer made the button live. The box you type in is the entry: a task's title
- * or everything else's body. A logged call with no title reads "Call" on the
- * timeline, which is true, and the note under it is the part anyone reads.
- *
- * The draft stays in `useState`, which is the one piece of this panel that
- * belongs there — `record-stack` keeps the rest in the URL, and a half-written
- * note about a customer has no business in browser history.
- */
export function ActivityComposer({ anchor }: { anchor: TimelineAnchor }) {
const trpc = useTRPC();
const cache = useCrmCache();
@@ -125,8 +92,6 @@ export function ActivityComposer({ anchor }: { anchor: TimelineAnchor }) {
placeholder={PLACEHOLDER[type]}
aria-label="What happened"
onKeyDown={(event) => {
- // Plain Enter has to stay a newline — this is where a three
- // paragraph call note goes.
if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
event.preventDefault();
submit();
@@ -136,12 +101,6 @@ export function ActivityComposer({ anchor }: { anchor: TimelineAnchor }) {
/>
<InputGroupAddon align="block-end" className="gap-2 border-t">
- {/*
- * Borderless and inside the box. The filter row below is the same
- * control with the same shape, and the only reason the two do not
- * read as one confused pair of duplicates is that this one sits
- * under a rule inside a bordered container and that one does not.
- */}
<ToggleGroup
type="single"
value={type}
@@ -161,12 +120,6 @@ export function ActivityComposer({ anchor }: { anchor: TimelineAnchor }) {
))}
</ToggleGroup>
- {/*
- * A task is the one thing here with a future, so it is the one
- * thing that gets a date — and it gets a real calendar rather than
- * `<input type="date">`, whose picker is drawn by the browser and
- * knows nothing about any of these tokens.
- */}
{isTask ? (
<Popover>
<PopoverTrigger asChild>
@@ -186,13 +139,6 @@ export function ActivityComposer({ anchor }: { anchor: TimelineAnchor }) {
</Popover>
) : null}
- {/*
- * Only once there is something to submit. `--primary` in dark mode
- * is near-white, so a permanently-present disabled primary button
- * is a grey slab sitting in the corner of an empty box — it made
- * the whole composer read as switched off. It appears at the end of
- * a row that is already there, so nothing reflows around it.
- */}
{text === "" ? null : (
<InputGroupButton
type="submit"
diff --git a/apps/app/components/crm/timeline/email-thread-entry.tsx b/apps/app/components/crm/timeline/email-thread-entry.tsx
index dc4c1a59..3bdd0e5c 100644
--- a/apps/app/components/crm/timeline/email-thread-entry.tsx
+++ b/apps/app/components/crm/timeline/email-thread-entry.tsx
@@ -19,13 +19,6 @@ const timeFormat = new Intl.DateTimeFormat(undefined, {
minute: "2-digit",
});
-/**
- * A synced Gmail thread, collapsed to one line.
- *
- * The messages are fetched only when it is opened: the timeline payload carries
- * a snippet and a count, and email bodies are the one thing that must never
- * ride along on a list response.
- */
export function EmailThreadEntry({
threadId,
messageCount,
@@ -46,7 +39,6 @@ export function EmailThreadEntry({
type="single"
collapsible
onValueChange={(value) => {
- // Latched: collapsing again should not throw away what we fetched.
if (value) setOpened(true);
}}
>
@@ -72,6 +64,7 @@ export function EmailThreadEntry({
key={message.id}
from={message.fromName ?? message.fromEmail}
fromEmail={message.fromEmail}
+ fromImageUrl={message.fromImageUrl}
sentAt={timeFormat.format(new Date(message.sentAt))}
direction={message.direction}
body={message.body}
diff --git a/apps/app/components/crm/timeline/meeting-entry.tsx b/apps/app/components/crm/timeline/meeting-entry.tsx
index 7206638f..f95a89a9 100644
--- a/apps/app/components/crm/timeline/meeting-entry.tsx
+++ b/apps/app/components/crm/timeline/meeting-entry.tsx
@@ -21,13 +21,6 @@ const dayOnly = new Intl.DateTimeFormat(undefined, {
day: "numeric",
});
-/**
- * A synced calendar event on the timeline.
- *
- * The attendee list is fetched lazily for the same reason the thread is: the
- * timeline row carries a count, and pulling every attendee of every meeting on
- * a busy company would be a join per row for information most rows never show.
- */
export function MeetingEntry({
eventId,
startsAt,
@@ -45,7 +38,6 @@ export function MeetingEntry({
}) {
const trpc = useTRPC();
- // Only worth a request when there is somebody to show.
const event = useQuery({
...trpc.google.event.queryOptions({ eventId }),
enabled: attendeeCount > 0,
@@ -75,10 +67,6 @@ export function MeetingEntry({
);
}
-/**
- * "5 Aug, 14:00 – 15:00", collapsing the second date when it is the same day —
- * which it almost always is, and repeating it reads like a two-day meeting.
- */
function formatRange(
startsAt: string,
endsAt: string,
diff --git a/apps/app/components/crm/timeline/timeline-entry.tsx b/apps/app/components/crm/timeline/timeline-entry.tsx
index 2362d59a..da8ff5e7 100644
--- a/apps/app/components/crm/timeline/timeline-entry.tsx
+++ b/apps/app/components/crm/timeline/timeline-entry.tsx
@@ -24,40 +24,18 @@ const timeFormat = new Intl.DateTimeFormat(undefined, {
minute: "2-digit",
});
-/** `{ from, to }` on a STAGE_CHANGE, read back defensively — it is `Json`. */
function stageChange(meta: Record<string, unknown> | null) {
const from = typeof meta?.from === "string" ? meta.from : null;
const to = typeof meta?.to === "string" ? meta.to : null;
return from && to ? { from, to } : null;
}
-/** The record this timeline is already about, whichever kind it is. */
function anchorId(anchor: TimelineAnchor): string {
if ("companyId" in anchor) return anchor.companyId;
if ("contactId" in anchor) return anchor.contactId;
return anchor.dealId;
}
-/**
- * One thing that happened.
- *
- * Two rules decide the layout, and both came from the same mistake — treating
- * the *type* of an entry as its headline.
- *
- * **The content is whatever there is.** A synced meeting has a title and no
- * body; a logged note has a body and no title; an enrichment has both. When
- * there was a title it was set in medium foreground and the body underneath in
- * muted grey, which was right — and when there was not, the word "Email" got
- * promoted into the title slot and the thing you actually wrote was demoted to
- * grey small print beneath it. The row read "Email / Test" with the wrong half
- * emphasised. Now the first line of real content is the headline, and the type
- * is carried by the icon in the gutter, which was already there saying it.
- *
- * **Who and when go right, and cross-references only point elsewhere.** Every
- * row on a contact's timeline used to end with a link to that contact — six
- * copies of the name at the top of the panel. A chip is worth a line only when
- * it goes somewhere you are not.
- */
export function TimelineEntry({
entry,
anchor,
@@ -86,8 +64,6 @@ export function TimelineEntry({
const change = entry.type === "STAGE_CHANGE" ? stageChange(entry.meta) : null;
const when = entry.occurredAt ?? entry.createdAt;
- // A synced entry was not written by the person whose mailbox it came from,
- // so it is attributed to the source rather than to them.
const synced = entry.meta?.synced === true;
const author = synced
? entry.emailThread
@@ -99,8 +75,6 @@ export function TimelineEntry({
? `${dealStageLabel(change.from as never)} → ${dealStageLabel(change.to as never)}`
: entry.subject;
- // Only when they are somewhere else. On a deal's timeline the deal is the
- // page; on a contact's, the contact is.
const here = anchorId(anchor);
const deal = entry.deal && entry.deal.id !== here ? entry.deal : null;
const contact =
@@ -154,8 +128,6 @@ export function TimelineEntry({
</p>
) : null}
- {/* Something has to be on the line. A stage change and a bare
- logged call both arrive with nothing written on them. */}
{!headline && !entry.body ? (
<p className="text-muted-foreground">
{activityLabel(entry.type)}
@@ -163,12 +135,6 @@ export function TimelineEntry({
) : null}
</div>
- {/*
- * Who and when, together, on the right. A line of their own would
- * cost every note in the panel a second row to carry one short
- * grey string — most entries are a sentence and a signature, and
- * they should be one line.
- */}
<span className="shrink-0 text-muted-foreground">
<span className="hidden sm:inline">{author} · </span>
<span className="tabular-nums">
@@ -195,11 +161,6 @@ export function TimelineEntry({
/>
) : null}
- {/*
- * The footnotes: when it is due, and where else it belongs. Rendered
- * only when there is one — an entry with neither should not pay a
- * line for the possibility.
- */}
{footnotes ? (
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-muted-foreground">
{overdue ? (
diff --git a/apps/app/components/crm/timeline/timeline-search-params.ts b/apps/app/components/crm/timeline/timeline-search-params.ts
index 51a180de..0fbe4e48 100644
--- a/apps/app/components/crm/timeline/timeline-search-params.ts
+++ b/apps/app/components/crm/timeline/timeline-search-params.ts
@@ -1,24 +1,5 @@
import { parseAsStringLiteral } from "nuqs/server";
-/**
- * The timeline's filter, in the URL like every other view state here: "the
- * Attio deal, on Activity, showing what's outstanding" is then a link you can
- * send someone, and it survives a refresh.
- *
- * What makes that safe is `replace`, nuqs's default: flicking between Upcoming
- * and Done is reading, not navigating, so it rewrites the current history entry
- * instead of stacking four of them in front of the Back button that closes the
- * sheet. Same call `tab` and `add` make in `record-stack.ts`.
- *
- * Imported from `nuqs/server` for the same reason the list parsers are —
- * parsers are plain data, and nothing here should drag a client-only module
- * into a server component that wants to read the same key.
- */
-/**
- * `email` and `meetings` cover what a rep logged by hand *and* what the Google
- * sync projected. Splitting those apart would turn "have we spoken to them?"
- * into two questions with two answers.
- */
export const TIMELINE_TABS = [
"all",
"notes",
@@ -30,24 +11,11 @@ export const TIMELINE_TABS = [
export type TimelineTab = (typeof TIMELINE_TABS)[number];
-/**
- * The URL key, shared with `record-stack.ts`, which clears it when you leave
- * the Activity panel or move to another record — the filter describes one
- * record's timeline, and a `?timeline=done` still hanging off the URL two
- * records later is either a lie or a surprise.
- */
export const TIMELINE_PARAM = "timeline";
-/**
- * A literal parser rather than a plain string one, so a hand-edited
- * `?timeline=whatever` falls back to All instead of asking the API to filter
- * by a value it has never heard of. `all` is the default, and therefore the
- * absence of the param.
- */
export const timelineTabParser =
parseAsStringLiteral(TIMELINE_TABS).withDefault("all");
-/** The API filter a tab maps to. `all` splits into pinned + history. */
export function historyFilter(tab: TimelineTab) {
return tab === "all" ? ("history" as const) : tab;
}
diff --git a/apps/app/components/crm/timeline/timeline.tsx b/apps/app/components/crm/timeline/timeline.tsx
index f4e64bbf..121382da 100644
--- a/apps/app/components/crm/timeline/timeline.tsx
+++ b/apps/app/components/crm/timeline/timeline.tsx
@@ -25,7 +25,6 @@ import {
timelineTabParser,
} from "./timeline-search-params";
-/** Exactly one of these — a timeline is always about one record. */
export type TimelineAnchor =
| { companyId: string }
| { contactId: string }
@@ -40,14 +39,6 @@ const TAB_LABELS: Record<TimelineTab, string> = {
done: "Done",
};
-/**
- * What an empty filter means, said properly.
- *
- * One line of grey text reading "Nothing here yet" was the only empty state in
- * a record sheet that was not `DetailSheetEmpty` — and it said the same thing
- * on all six filters, so "this record has no history" and "this record has no
- * *email*" were indistinguishable.
- */
const EMPTY_STATES: Record<
TimelineTab,
{ title: string; description: string }
@@ -92,8 +83,6 @@ const EMPTY_ICONS: Record<TimelineTab, CarbonIcon> = {
done: Checkmark,
};
-// Abbreviated, because these are eyebrows like every other heading in a record
-// sheet — and "WEDNESDAY, SEPTEMBER 16, 2026" set in uppercase is a banner.
const dayFormat = new Intl.DateTimeFormat(undefined, {
weekday: "short",
month: "short",
@@ -101,13 +90,6 @@ const dayFormat = new Intl.DateTimeFormat(undefined, {
year: "numeric",
});
-/**
- * "Today" and "Yesterday" by name, everything else by date.
- *
- * Most of what a rep reads on a timeline happened in the last two days, and
- * "SAT, AUG 1, 2026" makes them work out that today is Saturday to learn that
- * this happened an hour ago.
- */
function dayLabel(at: Date): string {
const midnight = (date: Date) =>
new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
@@ -121,16 +103,6 @@ function dayLabel(at: Date): string {
return dayFormat.format(at);
}
-/**
- * Entries under one heading per day, in the order they arrive.
- *
- * Keyed by a map rather than by comparing against the previous entry: run-length
- * grouping silently depends on the list being sorted by the very field it groups
- * on, and the moment that stops being true it emits the same day twice — which
- * React sees as duplicate keys. The API does order by `occurredAt`, so runs
- * *are* contiguous; this just refuses to be the thing that breaks if that ever
- * changes.
- */
function byDay(entries: TimelineEntryData[]) {
const groups = new Map<
string,
@@ -152,14 +124,6 @@ function byDay(entries: TimelineEntryData[]) {
return [...groups.values()];
}
-/**
- * One day's entries under a heading that stays put.
- *
- * Sticky, because the heading is the only thing that says *when* — the entries
- * under it carry a clock time and nothing else, so scrolling a year of history
- * with the date scrolled off the top leaves "2:41 PM" meaning nothing. It needs
- * the panel's own surface behind it or the rows show through as they pass.
- */
function TimelineDay({
label,
entries,
@@ -183,17 +147,6 @@ function TimelineDay({
);
}
-/**
- * Everything that has happened to a record, and the box for adding to it.
- *
- * Built as a panel that fills its tab: the composer stays put at the top,
- * where a rep can log the call they just finished without scrolling past a
- * year of history to reach it.
- *
- * A company's timeline picks up its deals' and contacts' entries for free —
- * the API stamps `companyId` on every activity it can resolve one for, so this
- * is one indexed range scan rather than three joins.
- */
export function Timeline({ anchor }: { anchor: TimelineAnchor }) {
const trpc = useTRPC();
@@ -201,8 +154,6 @@ export function Timeline({ anchor }: { anchor: TimelineAnchor }) {
const counts = useQuery(trpc.activities.timelineCounts.queryOptions(anchor));
- // On the "All" tab, outstanding tasks are pinned above the history and the
- // history excludes them, so nothing appears twice.
const pinned = useQuery({
...trpc.activities.timeline.queryOptions({
...anchor,
@@ -224,23 +175,13 @@ export function Timeline({ anchor }: { anchor: TimelineAnchor }) {
return (
<div className="flex min-h-0 flex-1 flex-col">
- {/* One band of controls, then history. Two stacked bordered bands push
- the first entry off the fold on a laptop. */}
<div className="flex shrink-0 flex-col gap-2 border-b px-5 py-3">
<ActivityComposer anchor={anchor} />
- {/*
- * Borderless, and outside the composer's box. This is a view control,
- * not something you fill in — six outlined boxes gave it the same
- * weight as the five outlined boxes above it, and the pair read as one
- * confused row of eleven buttons.
- */}
<ToggleGroup
type="single"
value={tab}
onValueChange={(next) => {
- // The group clears its value when you click the active item;
- // a timeline with no filter at all is not a state it has.
if (next) void setTab(next as TimelineTab);
}}
size="sm"
@@ -249,10 +190,6 @@ export function Timeline({ anchor }: { anchor: TimelineAnchor }) {
{TIMELINE_TABS.map((option) => (
<ToggleGroupItem key={option} value={option}>
{TAB_LABELS[option]}
- {/* A zero is omitted rather than printed, the same rule the
- sheet's own tabs follow. Six filters each carrying a "0"
- is a row of noise on exactly the records where there is
- least to look at. */}
{counts.data?.[option] ? (
<span className="tabular-nums opacity-60">
{counts.data[option]}
diff --git a/apps/app/components/dashboard-charts.tsx b/apps/app/components/dashboard-charts.tsx
index 797bc347..5d26b1e6 100644
--- a/apps/app/components/dashboard-charts.tsx
+++ b/apps/app/components/dashboard-charts.tsx
@@ -3,12 +3,6 @@
import { Spinner } from "@crm/ui/components/spinner";
import dynamic from "next/dynamic";
-/**
- * Recharts measures the DOM to lay a chart out, so there is nothing useful to
- * render on the server — an SSR pass emits a zero-width plot that the browser
- * immediately throws away. Loading the charts on the client only also keeps
- * recharts out of the shell bundle every other page pays for.
- */
const load = () => import("@crm/ui/components/dashboard-chart");
const loading = () => (
diff --git a/apps/app/components/data-table/list-search-params.ts b/apps/app/components/data-table/list-search-params.ts
index dbb0f180..d93525ba 100644
--- a/apps/app/components/data-table/list-search-params.ts
+++ b/apps/app/components/data-table/list-search-params.ts
@@ -8,44 +8,15 @@ import {
parseAsStringLiteral,
} from "nuqs/server";
-/**
- * One parser map per list module, shared by the page (which parses
- * `searchParams` to prefetch on the server) and the client panel (which reads
- * the same keys through `useTableQuery`). Defining them twice is how a page
- * ends up prefetching a different query than the one the browser then asks
- * for — so they are defined once, here.
- *
- * Imported from `nuqs/server` deliberately: parsers are plain data, and this
- * module is pulled into both a server component and a client one.
- */
-
const SORT_DIRECTIONS = ["asc", "desc"] as const;
type StringParser = ParserBuilder<string> & { defaultValue: string };
-/**
- * The two keys the search box owns, identical on every list.
- *
- * Exported so `ListSearch` can bind to them without being handed a module's
- * whole parser map. Search genuinely does not care which list it is on, and
- * taking the map would cost more than it looks: parsers carry functions, a
- * server component cannot pass a function to a client one, so every page would
- * need a client wrapper of its own whose only job is to import the map on the
- * right side of the boundary.
- */
export const searchParsers = {
q: parseAsString.withDefault(""),
- // Paging is the one table change worth a Back button.
page: parseAsInteger.withDefault(1).withOptions({ history: "push" }),
};
-/**
- * Base keys every list has, plus one string key per tab and facet.
- *
- * `TKey` is a union of literal key names rather than `string`: an index
- * signature here would collide with `page: number` and make every setter
- * untypeable.
- */
type ListParsers<TKey extends string> = {
q: StringParser;
sort: StringParser;
@@ -60,7 +31,6 @@ export type ListSearchValues<TKey extends string> = {
page: number;
} & { [K in TKey]: string };
-/** What a list procedure receives: the shared `listInput` plus tab and facets. */
export type ListInput<TKey extends string> = {
q: string;
sort: string;
@@ -70,15 +40,11 @@ export type ListInput<TKey extends string> = {
} & { [K in TKey]: string };
export type ListTableConfig<TTab extends string, TFacet extends string> = {
- /** Column id sorted by default; `""` means the API's own ordering. */
defaultSort?: string;
defaultDir?: SortDirection;
pageSize?: number;
- /** Query key for the tab selector, e.g. `"stage"`. */
tabId?: TTab;
- /** Query keys for the facet dropdowns, e.g. `["owner", "industry"]`. */
facetIds?: readonly TFacet[];
- /** Facet id → value to start on, when it should not be `"all"`. */
facetDefaults?: Partial<Record<TFacet, string>>;
};
@@ -89,9 +55,7 @@ export type ListSearchParams<TTab extends string, TFacet extends string> = {
pageSize: number;
};
parsers: ListParsers<TTab | TFacet>;
- /** Server-side: `await load(searchParams)` in the page. */
load: LoaderFunction<ListParsers<TTab | TFacet>>;
- /** Parsed URL values → the object the module's `list` procedure takes. */
toInput: (
values: ListSearchValues<TTab | TFacet>,
) => ListInput<TTab | TFacet>;
@@ -131,9 +95,6 @@ export function createListSearchParams<
parsers,
load: createLoader(parsers),
toInput: (values) => {
- // `"all"` is passed through rather than stripped: every list procedure
- // defaults its tab and facets to "all", so the two sides agree without
- // either needing to know which keys are optional.
const selected: Record<string, string> = {};
for (const key of keys) {
selected[key] = values[key] ?? "all";
diff --git a/apps/app/components/data-table/list-search.tsx b/apps/app/components/data-table/list-search.tsx
index cd3e6cc5..f97eedcf 100644
--- a/apps/app/components/data-table/list-search.tsx
+++ b/apps/app/components/data-table/list-search.tsx
@@ -10,22 +10,9 @@ import { useSearchInput } from "@crm/ui/hooks/use-search-input";
import { useQueryStates } from "nuqs";
import { searchParsers } from "./list-search-params";
-/**
- * The list's search box, in the page header rather than above the table.
- *
- * It shares no props with the table and needs none: both read `q` out of the
- * URL, so typing here updates the table without either knowing the other
- * exists. The table renders no search field at all, so there is only ever one
- * input bound to the value.
- *
- * `q` and `page` are the same two keys on every list, so this takes no parser
- * map and is safe to render straight from a server page.
- */
export function ListSearch({ placeholder }: { placeholder: string }) {
const [{ q }, setState] = useQueryStates(searchParsers);
- // Back to page 1: staying on page 7 of a result set that now has two pages
- // shows an empty table.
const [value, setValue] = useSearchInput(q, (next) =>
setState({ q: next, page: 1 }),
);
diff --git a/apps/app/components/data-table/use-table-query.ts b/apps/app/components/data-table/use-table-query.ts
index 67db4af0..e3e98df4 100644
--- a/apps/app/components/data-table/use-table-query.ts
+++ b/apps/app/components/data-table/use-table-query.ts
@@ -9,23 +9,10 @@ import type {
} from "./list-search-params";
export type TableQuery<TKey extends string> = {
- /** Passed to `<DataTable query={…}>`. */
query: TableQueryState;
- /** Passed to the module's `list` procedure. */
input: ListInput<TKey>;
};
-/**
- * Binds a module's URL parsers to the `DataTable` contract.
- *
- * Lives in the app rather than in `@crm/ui` because it is routing state: the
- * design system renders the controls, the app decides what a URL means.
- *
- * Nothing here is debounced or deferred. `q` reaches the URL only once typing
- * has paused, because `ListSearch` holds the keystrokes in local state until
- * then — so by the time this reads it, every value in the URL is one a user
- * settled on and is worth a request.
- */
export function useTableQuery<TTab extends string, TFacet extends string>(
searchParams: ListSearchParams<TTab, TFacet>,
): TableQuery<TTab | TFacet> {
@@ -52,8 +39,6 @@ export function useTableQuery<TTab extends string, TFacet extends string>(
tab,
tabId,
filters,
- // Every filter change resets to page 1: staying on page 7 of a result set
- // that now has two pages shows an empty table.
toggleSort: (id) =>
setState((prev) =>
prev.sort === id
diff --git a/apps/app/components/detail-sheet.tsx b/apps/app/components/detail-sheet.tsx
index 8c63cfed..cb630749 100644
--- a/apps/app/components/detail-sheet.tsx
+++ b/apps/app/components/detail-sheet.tsx
@@ -36,60 +36,17 @@ import {
SheetTitle,
} from "@/components/responsive-sheet";
-/** One gutter for the whole panel, so every band lines up down the left edge. */
const GUTTER = "px-5";
-/**
- * Section headings are eyebrows, not titles.
- *
- * The only title in a record sheet is the record's name. "Details" and "About"
- * are labels on a filing cabinet — they need to be findable when you scan for
- * them and invisible when you are not.
- */
export const SECTION_TITLE =
"font-medium text-muted-foreground text-xs uppercase tracking-wider";
-/**
- * The one label column every property in every sheet is measured against.
- *
- * Exported because the editable rows in `crm/inline-field` are the same row
- * with a control in the value slot. Two definitions is how the Background block
- * ended up nine pixels left of the Details block above it — near enough to look
- * accidental, far enough to see.
- */
export const PROPERTY_ROW = "grid grid-cols-[6.5rem_minmax(0,1fr)] gap-2";
-/**
- * The label in that column, on every kind of row.
- *
- * Same size as the value it labels. Everything in a sheet is `text-xs` — which
- * is what `Button`, `Input`, `Select` and `Table` already are, so the panel is
- * uniform only as long as nothing overrides them upward. Hierarchy comes from
- * colour: a muted label against a foreground value.
- */
export const PROPERTY_LABEL = "truncate text-muted-foreground text-xs";
-/**
- * A read-only row wears the box an editable one already has.
- *
- * An editable value lives in a ghost button — one pixel of transparent border,
- * `px-2` of padding — so anything set flat beside it starts nine pixels
- * further left. Giving both cells of a read-only row the same invisible box is
- * what keeps a section of facts and a section of fields on one edge.
- */
const PROPERTY_CELL = "border border-transparent py-1";
-/**
- * The chrome every record sheet is built from.
- *
- * One shape for all of them — header, a strip of numbers, tabs, a scrolling
- * body — so a rep who has opened a company knows where everything is on a deal
- * without looking.
- *
- * `showCloseButton={false}`: the close control is part of the header's action
- * group instead of floating over the top-right corner, which is the only way
- * a record's own buttons can sit up there without being crowded by it.
- */
export function DetailSheet({
open,
onOpenChange,
@@ -112,11 +69,6 @@ export function DetailSheet({
side="right"
size={size}
showCloseButton={false}
- // Opening a record is a read, not a form. Left alone, Radix puts
- // focus on the first control in the panel, so the sheet arrives with
- // a focus ring already drawn on a button nobody pressed. Focusing the
- // panel itself keeps assistive tech inside the dialog and announces
- // the record's name, without anything looking pre-clicked.
onOpenAutoFocus={(event) => {
event.preventDefault();
content.current?.focus();
@@ -140,12 +92,9 @@ export function DetailSheetHeader({
}: {
media?: ReactNode;
title: ReactNode;
- /** The one line that says what this is — domain, company, location. */
description?: ReactNode;
- /** Only when there is something to say: an agent running, a failure. */
note?: ReactNode;
actions?: ReactNode;
- /** Up one record, when this was opened from another one. */
onBack?: () => void;
onClose: () => void;
}) {
@@ -182,10 +131,6 @@ export function DetailSheetHeader({
) : null}
</div>
- {/*
- * Actions and close travel together, so the record's own buttons can
- * never end up underneath the close control.
- */}
<div className="flex shrink-0 items-center gap-1">
{actions}
{actions ? (
@@ -201,16 +146,7 @@ export function DetailSheetHeader({
);
}
-/**
- * The numbers you would otherwise open a tab to find.
- *
- * Deliberately not the counts already printed on the tabs beside them — a
- * strip that repeats "Contacts 3" under a tab reading "Contacts 3" is a band
- * of furniture, not information.
- */
export function DetailSheetStats({ children }: { children: ReactNode }) {
- // A filled shelf rather than a bare band: the stats sit above the tabs and
- // below the identity, and the fill is what separates the three.
return (
<dl className="flex shrink-0 divide-x border-b bg-muted/40">{children}</dl>
);
@@ -226,8 +162,6 @@ export function DetailSheetStat({
return (
<div className={cn("flex min-w-0 flex-1 flex-col gap-1 py-2.5", GUTTER)}>
<dt className="truncate text-muted-foreground text-xs/5">{label}</dt>
- {/* The value outranks its label — it is the thing you opened the sheet
- * to read, and at the same size the two competed. */}
<dd className="min-w-0 truncate font-medium text-foreground text-sm/5">
{children}
</dd>
@@ -238,38 +172,11 @@ export function DetailSheetStat({
export type DetailSheetTab = {
value: string;
label: string;
- /** Shown next to the label — omit rather than render a zero. */
count?: number | null;
content: ReactNode;
- /**
- * Keep this tab rendered while another one is showing.
- *
- * Off by default, and it should stay off for anything that is a view of
- * data: a table nobody is looking at should not hold a subscription open.
- *
- * It is on for the Agent tab because that panel holds a *live connection*.
- * Unmounting it aborts the stream mid-answer, and the reply then lands in
- * the durable session with nothing attached to receive it — so coming back
- * to the tab showed a question with no answer under it, and no amount of
- * re-reading state on the way back in could conjure the events that were
- * dropped while it was gone. A conversation you can walk away from is the
- * whole point of the panel.
- *
- * It is *keep* mounted, not *always* mounted: nothing renders until the tab
- * has been opened once. A rep flicking through twenty records should not
- * load twenty transcripts from an agent they never asked anything.
- */
keepMounted?: boolean;
};
-/**
- * The tabs inside a record sheet.
- *
- * The active tab is component state, not a URL param: the sheet's identity is
- * already in `?record=`, and putting the tab there too would mean every glance
- * at "Activity" is a history entry the back button has to walk through before
- * it closes the sheet.
- */
export function DetailSheetTabs({
tabs,
value,
@@ -279,8 +186,6 @@ export function DetailSheetTabs({
value: string;
onValueChange: (value: string) => void;
}) {
- // Which tabs have been looked at. A `keepMounted` tab costs nothing until
- // it is opened, and from then until the sheet closes it stays alive.
const [opened] = useState(() => new Set<string>());
opened.add(value);
@@ -290,11 +195,6 @@ export function DetailSheetTabs({
onValueChange={onValueChange}
className="flex min-h-0 flex-1 flex-col gap-0"
>
- {/*
- * Tabs only. A panel's actions live in the panel — a button bolted to
- * the right of the tab strip reads as part of the navigation, and the
- * one thing it is not is somewhere you can go.
- */}
<TabsList
variant="line"
className={cn("w-full shrink-0 justify-start gap-6 border-b", GUTTER)}
@@ -311,12 +211,6 @@ export function DetailSheetTabs({
))}
</TabsList>
- {/*
- * The panel does not scroll — whatever is inside it does. A tab of
- * sections wraps itself in `DetailSheetBody`; a tab that is one long
- * table lets the table scroll under its own pinned header. Scrolling
- * here as well would give both of those a second scrollbar.
- */}
{tabs.map((tab) => (
<TabsContent
key={tab.value}
@@ -324,10 +218,6 @@ export function DetailSheetTabs({
forceMount={
tab.keepMounted && opened.has(tab.value) ? true : undefined
}
- // `data-[state=inactive]:hidden` is load-bearing under
- // `forceMount`: Radix marks the panel hidden, and `display:flex`
- // on the same element wins over the `hidden` attribute, so
- // without it a kept-alive tab renders on top of the visible one.
className="flex min-h-0 flex-1 flex-col overflow-hidden outline-none data-[state=inactive]:hidden"
>
{tab.content}
@@ -337,7 +227,6 @@ export function DetailSheetTabs({
);
}
-/** The scroll container for a tab made of sections rather than one table. */
export function DetailSheetBody({ children }: { children: ReactNode }) {
return (
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto">
@@ -376,15 +265,6 @@ export function DetailSheetSection({
);
}
-/**
- * An overview in two columns: what the record *is* on the left, what we know
- * *about* it on the right.
- *
- * One column made the sheet a long list of label/value rows with the useful
- * prose at the bottom, so a rep opening a company scrolled past eight fields to
- * reach the description and never saw the contacts at all. Collapses below `lg`,
- * where a rail would be too narrow to hold a value.
- */
export function DetailSheetSplit({ children }: { children: ReactNode }) {
return (
<div className="flex flex-col gap-6 lg:flex-row lg:items-start lg:gap-8">
@@ -393,15 +273,11 @@ export function DetailSheetSplit({ children }: { children: ReactNode }) {
);
}
-/** The wide half of a split: prose, and the records hanging off this one. */
export function DetailSheetMain({ children }: { children: ReactNode }) {
return <div className="flex min-w-0 flex-1 flex-col">{children}</div>;
}
-/** The narrow half of a split: the record's own fields, and its gaps. */
export function DetailSheetRail({ children }: { children: ReactNode }) {
- // `min-w-0` so a long value truncates inside the rail instead of pushing it
- // wider than the sheet and running off the edge of the screen.
return (
<div className="flex w-full min-w-0 shrink-0 flex-col lg:w-80">
{children}
@@ -409,24 +285,11 @@ export function DetailSheetRail({ children }: { children: ReactNode }) {
);
}
-/**
- * Two columns of editable properties on a wide panel, one on a narrow one.
- *
- * Paired rather than a single list because a company has eight of these and a
- * single column turns the first screen of the sheet into a ladder you scroll.
- */
export function DetailSheetProperties({
children,
columns = 2,
}: {
children: ReactNode;
- /**
- * One column when the properties sit in a `DetailSheetRail`.
- *
- * Each row is a 6.5rem label plus its value, so two of them inside a 288px
- * rail leave about 32px for the value and every one of them clips. Two
- * columns is right across a full-width panel and wrong anywhere narrow.
- */
columns?: 1 | 2;
}) {
return (
@@ -436,16 +299,6 @@ export function DetailSheetProperties({
);
}
-/**
- * What the agent has not filled in yet, as one line rather than a column of
- * em dashes.
- *
- * An empty field rendered as "—" costs a full row and says nothing; five of
- * them say nothing five times. Naming the gaps once, next to the fact that
- * something is working on them, is the same information in a tenth of the
- * space — and it gives the agent a visible presence on a record, which matters
- * in a product whose whole premise is that the agent does the looking.
- */
export function DetailSheetPending({
fields,
running,
@@ -476,17 +329,6 @@ export function DetailSheetPending({
);
}
-/**
- * A property nobody can edit — a fact the agent found, a count we derived.
- *
- * The read-only twin of `InlineField`, sharing its label column and its value
- * indent so a section of these under a section of those reads as one table
- * rather than two that nearly line up.
- *
- * `wide` for the ones that are a sentence rather than a value — a list of
- * previous employers, the names of everyone else at the company. Half a panel
- * turns those into a three-line paragraph wearing a label.
- */
export function DetailSheetProperty({
label,
wide = false,
@@ -498,8 +340,6 @@ export function DetailSheetProperty({
}) {
return (
<div className={cn(PROPERTY_ROW, "items-start", wide && "sm:col-span-2")}>
- {/* `text-xs/5` so the label's line box is the value's, and the two sit on
- one baseline without either being nudged by hand. */}
<span className={cn(PROPERTY_LABEL, PROPERTY_CELL, "text-xs/5")}>
{label}
</span>
@@ -510,28 +350,12 @@ export function DetailSheetProperty({
);
}
-/**
- * The one paragraph shape in the panel — a company's description, a contact's
- * background.
- *
- * Full width, not measured. A `max-w-prose` here looked like the text had been
- * cut off rather than set: the properties beneath it run the width of the
- * panel, so a paragraph stopping two thirds of the way across reads as a
- * rendering fault. At `text-xs` the line is short enough anyway.
- */
export function DetailSheetProse({ children }: { children: ReactNode }) {
return (
<p className="text-pretty text-muted-foreground text-xs/5">{children}</p>
);
}
-/**
- * Nothing here yet, said once, the same way everywhere.
- *
- * A real empty state rather than a line of grey text: an empty panel is the
- * most common thing a rep sees on a company they just added, so it is the one
- * place the app has to say what this list is for and how to start it.
- */
export function DetailSheetEmpty({
icon,
title,
diff --git a/apps/app/components/page-shell.tsx b/apps/app/components/page-shell.tsx
index a4d37a48..298e648d 100644
--- a/apps/app/components/page-shell.tsx
+++ b/apps/app/components/page-shell.tsx
@@ -22,10 +22,6 @@ function PageShell({ className, ...props }: React.ComponentProps<"div">) {
);
}
-/**
- * No breadcrumbs: the app is five lists and a sheet, so there is never a trail
- * to draw. A record's own trail lives in the sheet, where the nesting is.
- */
function PageShellHeader({
className,
children,
diff --git a/apps/app/components/page-transition.tsx b/apps/app/components/page-transition.tsx
index a271d1cf..99417e45 100644
--- a/apps/app/components/page-transition.tsx
+++ b/apps/app/components/page-transition.tsx
@@ -1,9 +1,6 @@
import type * as React from "react";
import { ViewTransition } from "react";
-// Every transition is opt-in by name: "none" means the new view swaps in with
-// no animation. A page only moves when a <Link transitionTypes={[...]}> names
-// one of these, so navigation stays still by default.
const directional = {
"nav-forward": "nav-forward",
"nav-back": "nav-back",
diff --git a/apps/app/components/responsive-sheet.tsx b/apps/app/components/responsive-sheet.tsx
index 6c0ce88e..772d2c9d 100644
--- a/apps/app/components/responsive-sheet.tsx
+++ b/apps/app/components/responsive-sheet.tsx
@@ -20,14 +20,6 @@ import { cn } from "@crm/ui/lib/utils";
import type * as React from "react";
import { createContext, useContext } from "react";
-/**
- * A sheet on a desktop, a drawer on a phone, one set of imports either way.
- *
- * Everything in this app that would have been a sub-page is a sheet, and a
- * 5xl panel sliding in from the right of a 390px screen is not a sheet, it is
- * a broken page. Swapping the primitive here rather than at each call site
- * means no screen has to know which one it got.
- */
const ResponsiveContext = createContext(false);
const useResponsive = () => useContext(ResponsiveContext);
@@ -63,14 +55,9 @@ function SheetContent({
side?: "top" | "right" | "bottom" | "left";
size?: SheetSize;
showCloseButton?: boolean;
- /** Radix's "where does focus land" hook — both branches forward it. */
onOpenAutoFocus?: (event: Event) => void;
}) {
if (useResponsive()) {
- // A bottom drawer is otherwise content-height, so a short body (or a tab
- // switch to a near-empty panel) collapses it and shifts the page. Pin a
- // stable default height for every drawer app-wide; callers can still
- // override via `className` since it merges last.
return (
<DrawerContent
className={cn(
diff --git a/apps/app/lib/agent-bridge.ts b/apps/app/lib/agent-bridge.ts
index 2bd02c82..699cb5b4 100644
--- a/apps/app/lib/agent-bridge.ts
+++ b/apps/app/lib/agent-bridge.ts
@@ -1,79 +1,20 @@
-/**
- * How a signed-in rep reaches the research agent.
- *
- * Server-side only, and structurally so: the secret is read from
- * `AGENT_BRIDGE_SECRET` at call time, and Next only inlines `NEXT_PUBLIC_*`
- * into the browser bundle. Imported from a client component this would find
- * `undefined` and throw rather than ship the secret — which is why the guard is
- * the variable's name rather than a `server-only` import that a test runner
- * resolves differently.
- *
- * The agent is its own deployment on its own origin, and the browser never
- * talks to it. Instead the app proxies `/eve/v1/*` from its own origin
- * (`app/eve/v1/[...path]/route.ts`) and mints a short-lived token naming the
- * person who is signed in.
- *
- * Three problems that solves at once:
- *
- * - **No CORS and no cross-site cookie.** Same trade the app already makes for
- * the API: a same-origin path means the session cookie just works, and we
- * never scope an auth cookie to a third host.
- * - **The agent learns *who* is asking**, not merely that the app is asking. A
- * shared service credential would make every rep look like the deployment,
- * and `lib/approval.ts` on the other side decides what to do based on whether
- * a person is present.
- * - **The blast radius is a minute.** The agent can read every email in the
- * CRM; a long-lived token in a browser tab is not a thing to hand out.
- *
- * HS256 rather than something asymmetric because both halves are ours and
- * deploy together. `AGENT_BRIDGE_SECRET` is the only new configuration, and it
- * is required on both sides for the panel to work at all.
- */
-
-/** Must match `apps/agent/agent/channels/eve.ts`. */
const ISSUER = "crm-app";
const AUDIENCE = "crm-agent";
-/** Long enough for a slow request, short enough not to be worth stealing. */
const TTL_SECONDS = 120;
-/**
- * `127.0.0.1`, not `localhost`.
- *
- * `eve dev` binds IPv4 only, while Node's resolver hands `localhost` back as
- * `::1` first — so a default of `http://localhost:2000` fails to connect on a
- * machine where the agent is plainly running, and reports itself as "the agent
- * is not reachable". Naming the address avoids the resolution entirely.
- */
export const AGENT_URL = process.env.AGENT_URL ?? "http://127.0.0.1:2000";
export function bridgeConfigured(): boolean {
return Boolean(process.env.AGENT_BRIDGE_SECRET);
}
-/**
- * A bearer token for one rep, valid for two minutes.
- *
- * Hand-rolled rather than pulling in a JWT library: this signs one fixed claim
- * set with one algorithm, and `crypto.subtle` does HMAC. A dependency here
- * would be more surface than code.
- */
export async function mintBridgeToken(
user: {
id: string;
email: string;
name: string;
},
- /**
- * The record the rep has open.
- *
- * Carried in the token rather than pasted into the message, because the
- * agent already knows how to read it from there: `instructions/task.ts`
- * resolves `attributes.contactId` at `session.started`, which is the same
- * path the dispatcher uses. The alternative — prefixing every message with
- * "About contact <cuid> (Name):" — put plumbing in front of a person and
- * made their own question unreadable.
- */
record: { contactId?: string; companyId?: string; dealId?: string } = {},
): Promise<string> {
const secret = process.env.AGENT_BRIDGE_SECRET;
@@ -92,8 +33,6 @@ export async function mintBridgeToken(
...(record.companyId ? { companyId: record.companyId } : {}),
...(record.dealId ? { dealId: record.dealId } : {}),
iat: now,
- // `nbf` a little in the past: the agent allows clock skew, but there is no
- // reason to hand it a token that is not valid yet.
nbf: now - 5,
exp: now + TTL_SECONDS,
};
diff --git a/apps/app/lib/agent-record.ts b/apps/app/lib/agent-record.ts
index 1df36304..f3d17a41 100644
--- a/apps/app/lib/agent-record.ts
+++ b/apps/app/lib/agent-record.ts
@@ -1,38 +1,15 @@
import type { CarbonIcon } from "@crm/ui/components/icon";
-/**
- * Which record the agent is being asked about.
- *
- * The panel appears on three sheets and the questions worth asking are
- * different on each: a person has a job and a history, a company has a market
- * and a story, a deal has a state and a next step. Offering "Who is this
- * person?" on a company is the tell that a chat box was bolted on rather than
- * built into the record.
- *
- * One shape carries it end to end — the header the panel sends, the claim the
- * proxy mints, the field the conversation is filed under, and the preamble the
- * agent opens with — so adding a fourth kind is one entry rather than four
- * edits in four layers.
- */
-
export type AgentRecordKind = "contact" | "company" | "deal";
export type AgentRecord = { kind: AgentRecordKind; id: string };
type RecordCopy = {
- /** The header the panel sends; the proxy turns it into a token claim. */
header: string;
- /** The tRPC field a conversation is filed under. */
field: "contactId" | "companyId" | "dealId";
title: string;
blurb: string;
placeholder: string;
- /**
- * What this agent is actually good at, per record.
- *
- * Three, because a wall of chips is a menu nobody reads, and each one maps
- * onto tools the agent has rather than to something it would have to invent.
- */
suggestions: string[];
};
@@ -82,12 +59,10 @@ export function recordCopy(kind: AgentRecordKind): RecordCopy {
return COPY[kind];
}
-/** The header a panel sends so the agent knows what it is looking at. */
export function recordHeader(record: AgentRecord): Record<string, string> {
return { [COPY[record.kind].header]: record.id };
}
-/** The shape the conversations API files a thread under. */
export function recordFilter(record: AgentRecord): {
contactId?: string;
companyId?: string;
diff --git a/apps/app/lib/agent-session.ts b/apps/app/lib/agent-session.ts
index 0da22051..e5668d9d 100644
--- a/apps/app/lib/agent-session.ts
+++ b/apps/app/lib/agent-session.ts
@@ -1,78 +1,32 @@
import type { MessageStreamEvent, SessionState } from "eve/client";
import { Client } from "eve/client";
-/**
- * Picking a conversation back up, the way eve says to.
- *
- * This file replaced a hand-rolled one that read the tail of the event stream
- * over raw `fetch` and inferred a state machine from the last line. Every bug
- * in the panel came out of that: the stream opens with a blank line, so the
- * "last line" was empty and every thread read as busy; the endpoint *follows*,
- * so awaiting the body never returned; a read that failed reported the session
- * as working rather than reporting itself as broken.
- *
- * `session.snapshot()` is the documented answer to the exact question that code
- * was asking, and it answers all of it at once: the complete event prefix, the
- * cursor that continues from it, and a continuation token *if and only if* the
- * session is parked and will accept another turn. One request, ~30ms against a
- * hundred-event thread, no parsing.
- */
-
-/** How long a turn can go silent before it is dead rather than working. */
const ABANDONED_AFTER_MS = 90_000;
export type Thread =
| {
- /** Nothing has been sent yet. There is no session to load. */
status: "new";
}
| {
- /** Parked, with a live token. The composer is open. */
status: "ready";
session: SessionState;
events: readonly MessageStreamEvent[];
}
| {
- /**
- * A turn is in flight — started by another tab, or by this one before
- * the page reloaded. eve will not take input until it settles.
- */
status: "working";
session: SessionState;
events: readonly MessageStreamEvent[];
}
| {
- /**
- * Over: completed, failed, or abandoned mid-sentence by a runtime that
- * restarted. Nothing can be sent into it again, so the panel offers a
- * new conversation instead of a disabled box.
- */
status: "ended";
session: SessionState;
events: readonly MessageStreamEvent[];
}
| {
- /**
- * The agent could not be reached, or the session has aged out of eve's
- * 30-day retention.
- *
- * Deliberately distinct from `working`: that is a claim about the
- * session, and this is a fact about us. Reported as the former it was
- * both untrue and unrecoverable — the read fails identically next time,
- * so the composer stayed shut forever. Here the transcript comes from
- * our own archive and a send starts a fresh session.
- */
status: "offline";
events: readonly MessageStreamEvent[];
};
-/**
- * Loads a thread: its transcript, its cursor, and whether it can be written to.
- *
- * `archive` is our own `AgentEvent` mirror, used only when eve cannot answer —
- * a month-old thread outlives the session it was held in, and a rep reopening
- * one should still be able to read it.
- */
export async function loadThread(
sessionId: string,
headers: Record<string, string>,
@@ -80,8 +34,6 @@ export async function loadThread(
signal?: AbortSignal,
): Promise<Thread> {
try {
- // `host: ""` is same-origin, which is where the app proxies `/eve/v1/*`
- // from — the browser never learns the agent has an origin of its own.
const snapshot = await new Client({ headers, host: "" })
.session({ sessionId, streamIndex: 0 })
.snapshot({ signal });
@@ -96,20 +48,11 @@ export async function loadThread(
}
}
-/**
- * Which of the three live states a snapshot describes.
- *
- * Exported for its tests: this is the one judgement call in the file, and the
- * cost of getting it wrong is a thread that can never be typed into again.
- */
export function classify(
session: SessionState,
events: readonly MessageStreamEvent[],
now: number = Date.now(),
): "ready" | "working" | "ended" {
- // The token is the authority, not our reading of the events: eve returns one
- // only when the captured prefix ends parked, which is exactly the condition
- // under which the next send will be accepted.
if (session.continuationToken) return "ready";
const last = events.at(-1);
@@ -119,11 +62,6 @@ export function classify(
return "ended";
}
- // Mid-turn, and the only question left is whether anything is still running.
- // A live turn emits constantly — deltas, steps, tool results — so a long gap
- // means the run died without a boundary, which a restart or a redeploy does
- // routinely. Those sessions never park, and calling them "working" locks the
- // thread for good.
const at = Date.parse(last.meta.at);
return Number.isNaN(at) || now - at < ABANDONED_AFTER_MS
@@ -131,27 +69,17 @@ export function classify(
: "ended";
}
-/** The transcript to render, whatever state the thread turned out to be in. */
export function eventsOf(
thread: Thread | undefined,
): readonly MessageStreamEvent[] {
return thread && "events" in thread ? thread.events : [];
}
-/** Whether the composer takes input, and whether this thread is over. */
export type ComposerState = {
locked: boolean;
- /** Permanently. The way on is a new conversation, not waiting. */
ended: boolean;
};
-/**
- * What the composer may do.
- *
- * `busy` is this panel's own send. Everything else comes from the thread, and
- * the two states that both disable the box mean very different things: one is a
- * wait of seconds, the other is permanent.
- */
export function composerState(
thread: Thread | undefined,
busy: boolean,
@@ -160,8 +88,6 @@ export function composerState(
return {
ended,
- // `offline` is not here on purpose: we could not ask, so let the send
- // try. It either works or raises an error the panel already shows.
locked: busy || ended || thread?.status === "working",
};
}
diff --git a/apps/app/lib/agent-transcript.ts b/apps/app/lib/agent-transcript.ts
index 8f415bce..7c5c2401 100644
--- a/apps/app/lib/agent-transcript.ts
+++ b/apps/app/lib/agent-transcript.ts
@@ -1,15 +1,5 @@
import type { EveMessage, EveMessagePart } from "eve/react";
-/**
- * The agent's event stream, projected into something a rep can read.
- *
- * Separate from the component because this is the part with opinions in it —
- * which tool call becomes which sentence, what counts as a refusal, which URLs
- * are worth showing — and none of it needs a browser to be wrong. The panel
- * renders what this returns.
- */
-
-/** Something said, or something done. A run is made of both. */
export type TranscriptItem =
| { kind: "said"; id: string; mine: boolean; text: string }
| {
@@ -25,23 +15,10 @@ export type Tone = "neutral" | "success" | "warning";
export type Source = {
url: string;
- /** The host, which is the part a rep recognises. */
title: string;
network: "linkedin" | "github" | "web";
};
-/**
- * Tool slugs are for the model; these lines are for a person.
- *
- * Every tool the agent can call belongs here, **including eve's own built-ins**
- * — those are the ones that get forgotten, because they arrive without anybody
- * adding a file for them, and `load_skill` sat in the middle of a transcript
- * reading exactly like that: a lowercase slug among finished English sentences.
- * `test/agent-transcript.spec.ts` walks `apps/agent/agent/tools` and this list
- * so a new tool cannot ship without a line.
- *
- * Past tense throughout, because a transcript is a record of what happened.
- */
const VERBS: Record<string, string> = {
read_crm_history: "Read our emails and meetings with them",
read_company_history: "Read everything we have on the company",
@@ -50,6 +27,7 @@ const VERBS: Record<string, string> = {
resolve_linkedin_profile: "Searched for their LinkedIn profile",
get_linkedin_profile: "Read a LinkedIn profile",
get_contact_work_history: "Read their work history",
+ fetch_contact_photo: "Fetched their profile picture",
find_contact_socials: "Searched for their other profiles",
set_contact_socials: "Checked a profile against the account itself",
identify_contact: "Put a name to the address",
@@ -62,8 +40,6 @@ const VERBS: Record<string, string> = {
record_job_change: "Raised a job change",
list_outstanding_work: "Looked for outstanding work",
- // eve's default harness. Named here for the same reason as the rest: a rep
- // reading a run should not have to know which of these we wrote.
load_skill: "Read its instructions for this",
web_search: "Searched the web",
web_fetch: "Read a web page",
@@ -78,39 +54,17 @@ const VERBS: Record<string, string> = {
grep: "Searched inside the files",
};
-/**
- * The last resort, for a tool nobody has written a line for yet.
- *
- * Sentence case rather than the raw slug: `set_contact_socials` reads as "Set
- * contact socials", which is plain but is at least English. The test makes
- * this unreachable for tools that exist today; it is here for the one somebody
- * adds on a Friday.
- */
function humanise(tool: string): string {
const words = tool.replace(/_/g, " ");
return words.charAt(0).toUpperCase() + words.slice(1);
}
-/** One message and everything it produced, in order. */
export type TranscriptMessage = {
id: string;
mine: boolean;
items: TranscriptItem[];
};
-/**
- * The stream, grouped by message.
- *
- * Grouped rather than flat because `MessageScrollerItem` is a *row boundary* —
- * the docs' own example is one item per message — and the scroller measures and
- * tracks each one. A separate row per tool call means dozens of boundaries
- * appearing and re-measuring during a single answer, which is visible as
- * flicker.
- *
- * Part ids prefer the tool call id, which is stable across the streaming states
- * of one call. A positional key would move as parts arrive and remount rows
- * mid-answer.
- */
export function toTranscript(
messages: readonly EveMessage[],
): TranscriptMessage[] {
@@ -169,7 +123,6 @@ export function toolName(part: EveMessagePart): string {
return part.type.replace(/^tool-/, "");
}
-/** Exported for the test that pins every tool to a line of English. */
export const TOOL_VERBS = VERBS;
export function describe(part: EveMessagePart): string {
@@ -177,17 +130,9 @@ export function describe(part: EveMessagePart): string {
const verb = VERBS[tool] ?? humanise(tool);
const reason = output(part)?.reason;
- // The reason a write did not happen is the interesting half.
return typeof reason === "string" ? `${verb} — ${reason}` : verb;
}
-/**
- * How a step reads at a glance.
- *
- * A refusal is a `warning`, never hidden: the agent declining to write a
- * plausible-looking match is the most trust-building thing on the page, and a
- * transcript that showed only successes would be advertising rather than a log.
- */
export function outcomeTone(part: EveMessagePart): Tone {
if ("state" in part && part.state === "output-error") return "warning";
@@ -200,7 +145,6 @@ export function outcomeTone(part: EveMessagePart): Tone {
return "neutral";
}
-/** The pages behind a step, so a rep can check them. */
export function sourcesOf(part: EveMessagePart): Source[] {
const result = output(part);
if (!result) return [];
@@ -227,13 +171,6 @@ export function sourcesOf(part: EveMessagePart): Source[] {
});
}
-/**
- * A question the agent is parked on, if there is one.
- *
- * Only the latest message is inspected: an older request has either been
- * answered or superseded, and re-rendering a stale prompt invites somebody to
- * answer a question nobody is waiting on.
- */
export function pendingQuestion(messages: readonly EveMessage[]) {
for (const part of messages.at(-1)?.parts ?? []) {
if (part.type !== "dynamic-tool") continue;
@@ -259,21 +196,8 @@ function hostOf(url: string): string {
}
}
-/** The sentinel for "start a fresh thread", as opposed to "resume the latest". */
export const NEW_THREAD = "new";
-/**
- * Which conversation a panel should show.
- *
- * Pulled out of the component because the rule has three cases and two of them
- * are easy to get wrong: the URL wins when it names a thread, a fresh thread
- * shows nothing, and no URL parameter means the most recent one — which is what
- * makes reopening a contact land where you left off.
- *
- * `landedOn` is the thread the panel *mounted* on, captured once. Re-deriving
- * "the latest" as the list changes would swap the open conversation out from
- * under a live answer the moment the first save added a row.
- */
export function resolveThread<T extends { id: string }>({
conversations,
fromUrl,
diff --git a/apps/app/lib/env.ts b/apps/app/lib/env.ts
index 400d0bef..30b75b39 100644
--- a/apps/app/lib/env.ts
+++ b/apps/app/lib/env.ts
@@ -1,8 +1,2 @@
-/**
- * Where the NestJS API lives.
- *
- * Public because the browser needs it for sign-in redirects; the server uses
- * the same value so there is only ever one origin to configure.
- */
export const API_URL =
process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:3001";
diff --git a/apps/app/lib/record-href.ts b/apps/app/lib/record-href.ts
index d1c4c70c..1616f99e 100644
--- a/apps/app/lib/record-href.ts
+++ b/apps/app/lib/record-href.ts
@@ -1,11 +1,3 @@
-/**
- * The URL that opens a record over a list.
- *
- * Records used to be pages, and links to those pages are already in Slack
- * threads and calendar invites. The old routes still exist and redirect here,
- * which is the only reason this is a shared helper rather than a string built
- * where it is needed.
- */
export function recordHref(
list: "/companies" | "/contacts" | "/deals",
kind: "company" | "contact" | "deal",
diff --git a/apps/app/lib/session.ts b/apps/app/lib/session.ts
index 10177f42..b58edbb4 100644
--- a/apps/app/lib/session.ts
+++ b/apps/app/lib/session.ts
@@ -19,12 +19,6 @@ export async function requireSession(): Promise<Session> {
return session;
}
-/**
- * The scopes Google has actually granted this user.
- *
- * `cache()`d, so the gate below costs one query per request no matter how many
- * layouts and pages ask.
- */
const grantedScope = cache(async (userId: string): Promise<string | null> => {
const account = await db.account.findFirst({
where: { userId, providerId: "google" },
@@ -34,19 +28,6 @@ const grantedScope = cache(async (userId: string): Promise<string | null> => {
return account?.scope ?? null;
});
-/**
- * A session that has granted Gmail and Calendar.
- *
- * Requesting the scopes at sign-in is not the same as having them: Google's
- * granular consent lets someone untick one and complete sign-in anyway, and an
- * account created before those scopes were required still carries the old
- * grant. Either way the CRM would look signed-in and quietly sync nothing, so
- * this is the check that makes mailbox access a real condition of using the
- * tool rather than an intention.
- *
- * Sends them to `/grant-access`, which is outside the app shell — gating inside
- * it would redirect the page that does the gating.
- */
export async function requireGoogleAccess(): Promise<Session> {
const session = await requireSession();
diff --git a/apps/app/lib/trpc/cache.ts b/apps/app/lib/trpc/cache.ts
index 21355919..c732aaf6 100644
--- a/apps/app/lib/trpc/cache.ts
+++ b/apps/app/lib/trpc/cache.ts
@@ -3,58 +3,19 @@
import { type QueryKey, useQueryClient } from "@tanstack/react-query";
import { useTRPC } from "./client";
-/**
- * What a write invalidates, in one place.
- *
- * Every mutation used to list its own keys in `onSuccess`, and the lists drifted
- * apart: a stage change wrote a `STAGE_CHANGE` activity without invalidating the
- * timeline it landed on, creating a deal from the deals page never refreshed the
- * list, and nothing at all invalidated the overview — so a rep could close a
- * deal and watch their own numbers not move. The fan-out belongs to the shape of
- * the data, not to the button that happened to trigger it, so it lives here and
- * each call site says only *what changed*.
- *
- * Per the API rules: freshness is TanStack Query's job, invalidated from the
- * mutation's `onSuccess` with the narrowest key that covers what changed. What
- * counts as "narrowest" is per-entity, which is exactly what these functions
- * encode.
- */
-
type Settle = "all" | "record";
type Options = {
- /**
- * Which refetches to wait for.
- *
- * `"all"` (the default) keeps the caller pending until every affected view is
- * fresh — right when the point of the action *is* the view changing, like a
- * row leaving the filtered list once its stage no longer matches.
- *
- * `"record"` waits only for the changed record's own query and lets the rest
- * refetch behind it, so an inline editor's spinner clears as soon as the value
- * under it is right rather than when the table behind the sheet has caught up.
- */
settle?: Settle;
};
export type CrmCache = {
- /** A company's name, logo, industry, owner, primary contact or enrichment. */
company(id?: string, options?: Options): Promise<void>;
- /** A contact's name, title, email or which company they belong to. */
contact(id?: string, options?: Options): Promise<void>;
- /** A deal's stage, amount, close date or owner — and so every sales number. */
deal(id?: string, options?: Options): Promise<void>;
- /** A note, a task, or a task being ticked off. */
activity(options?: Options): Promise<void>;
- /**
- * Connecting, disconnecting, a manual sync, or suppressing a domain.
- *
- * A *scheduled* sync is not this: nothing the browser did caused it, so it is
- * polled rather than invalidated (see `sync-status`). This is only for the
- * writes a rep triggers from the settings page.
- */
google(options?: Options): Promise<void>;
- /** An import writes across every table, so nothing is assumed to survive. */
+ settings(options?: Options): Promise<void>;
everything(): Promise<void>;
};
@@ -79,26 +40,16 @@ export function useCrmCache(): CrmCache {
).then(() => undefined);
};
- /**
- * The timeline history is an infinite query, so `pathKey()` — tRPC stamps the
- * query type into `queryKey()`, and `{ type: "query" }` cannot partially match
- * the `{ type: "infinite" }` the history is cached under. Getting this wrong
- * is silent: it reports success, refetches the sibling non-infinite queries,
- * and leaves the history stale until a reload.
- */
const activityKeys = () => [
trpc.activities.timeline.pathKey(),
trpc.activities.timelineCounts.queryKey(),
trpc.activities.myTasks.queryKey(),
];
- /** Where a record's name and logo are rendered other than on itself. */
const listKeys = () => [
trpc.companies.list.queryKey(),
trpc.contacts.list.queryKey(),
trpc.deals.list.queryKey(),
- // The ⌘K switcher searches names and domains, so a rename it cannot see
- // is a record the rep cannot find.
trpc.search.quick.queryKey(),
];
@@ -112,7 +63,6 @@ export function useCrmCache(): CrmCache {
],
[
...listKeys(),
- // A company's name and logo ride along on every contact and deal.
trpc.contacts.byId.queryKey(),
trpc.deals.byId.queryKey(),
trpc.dashboard.summary.queryKey(),
@@ -129,9 +79,6 @@ export function useCrmCache(): CrmCache {
],
[
...listKeys(),
- // Contact count and primary contact live on the company; a contact
- // can also be on a deal. Moving someone between companies changes
- // both, so the whole path is invalidated rather than one id.
trpc.companies.byId.queryKey(),
trpc.deals.byId.queryKey(),
],
@@ -143,14 +90,8 @@ export function useCrmCache(): CrmCache {
[id ? trpc.deals.byId.queryKey({ id }) : trpc.deals.byId.queryKey()],
[
...listKeys(),
- // Open deal count, open value and last activity all sit on the
- // company.
trpc.companies.byId.queryKey(),
- // Setting a stage writes a STAGE_CHANGE activity onto the deal's and
- // the company's timeline.
...activityKeys(),
- // Pipeline, closed-won, win rate, cycle time, the leaderboard — the
- // entire overview is a function of the deals table.
trpc.dashboard.summary.queryKey(),
],
options,
@@ -160,8 +101,6 @@ export function useCrmCache(): CrmCache {
run(
activityKeys(),
[
- // "Last activity" columns move whenever anything is logged, and the
- // record's own page shows the entry.
...listKeys(),
trpc.companies.byId.queryKey(),
trpc.contacts.byId.queryKey(),
@@ -175,10 +114,6 @@ export function useCrmCache(): CrmCache {
run(
[trpc.google.status.queryKey()],
[
- // A sync writes threads and meetings onto timelines, and
- // auto-creation writes whole companies and contacts — so a
- // disconnect-and-purge has to reach the lists too, not just the
- // settings page it was pressed on.
...activityKeys(),
...listKeys(),
trpc.companies.byId.queryKey(),
@@ -188,6 +123,9 @@ export function useCrmCache(): CrmCache {
options,
),
+ settings: (options) =>
+ run([trpc.settings.agentModel.queryKey()], [], options),
+
everything: () => queryClient.invalidateQueries(),
};
}
diff --git a/apps/app/lib/trpc/client.tsx b/apps/app/lib/trpc/client.tsx
index b3da5249..e2192abb 100644
--- a/apps/app/lib/trpc/client.tsx
+++ b/apps/app/lib/trpc/client.tsx
@@ -28,12 +28,7 @@ export function TRPCReactProvider({ children }: { children: ReactNode }) {
const queryClient = getQueryClient();
const [trpcClient] = useState(() =>
createTRPCClient<AppRouter>({
- links: [
- // Same-origin: `app/api/[...path]/route.ts` forwards to the API, so
- // the session cookie rides along without any CORS or credentials
- // choreography.
- httpBatchLink({ url: "/api/trpc" }),
- ],
+ links: [httpBatchLink({ url: "/api/trpc" })],
}),
);
diff --git a/apps/app/lib/trpc/hydrate.tsx b/apps/app/lib/trpc/hydrate.tsx
index 050e4c2a..08c91d80 100644
--- a/apps/app/lib/trpc/hydrate.tsx
+++ b/apps/app/lib/trpc/hydrate.tsx
@@ -3,13 +3,6 @@ import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import type { ReactNode } from "react";
import { getServerQueryClient } from "./server";
-/**
- * Ships everything the page prefetched to the browser, so the client component
- * inside renders with data instead of a spinner.
- *
- * Must be rendered after the `prefetchQuery` calls it is meant to carry —
- * `dehydrate` is a snapshot, not a subscription.
- */
export function HydrateClient({ children }: { children: ReactNode }) {
return (
<HydrationBoundary state={dehydrate(getServerQueryClient())}>
diff --git a/apps/app/lib/trpc/query-client.ts b/apps/app/lib/trpc/query-client.ts
index ccf253ec..2aa0831b 100644
--- a/apps/app/lib/trpc/query-client.ts
+++ b/apps/app/lib/trpc/query-client.ts
@@ -6,12 +6,8 @@ import {
export function makeQueryClient(): QueryClient {
return new QueryClient({
defaultOptions: {
- // Long enough that a server-prefetched query is not immediately refetched
- // on hydration, short enough that a stale list corrects itself.
queries: { staleTime: 30_000 },
dehydrate: {
- // Ship in-flight queries too, so a page can stream a prefetch it
- // started but did not await.
shouldDehydrateQuery: (query) =>
defaultShouldDehydrateQuery(query) ||
query.state.status === "pending",
@@ -22,10 +18,6 @@ export function makeQueryClient(): QueryClient {
let browserQueryClient: QueryClient | undefined;
-/**
- * One client per browser tab, a fresh one per server request — sharing a client
- * across requests would leak one user's data into another's cache.
- */
export function getQueryClient(): QueryClient {
if (typeof window === "undefined") {
return makeQueryClient();
diff --git a/apps/app/lib/trpc/server.ts b/apps/app/lib/trpc/server.ts
index 07865d62..2fc69f69 100644
--- a/apps/app/lib/trpc/server.ts
+++ b/apps/app/lib/trpc/server.ts
@@ -1,5 +1,5 @@
import "server-only";
-import { createTRPCClient, httpBatchLink } from "@trpc/client";
+import { createTRPCClient, httpBatchLink, type TRPCClient } from "@trpc/client";
import {
createTRPCOptionsProxy,
type TRPCOptionsProxy,
@@ -10,26 +10,14 @@ import { cache } from "react";
import { API_URL } from "@/lib/env";
import { makeQueryClient } from "./query-client";
-/**
- * The query client a server render prefetches into and then dehydrates.
- * `cache` keeps it to one per request, so several `prefetchQuery` calls across
- * a page land in the same store.
- */
export const getServerQueryClient = cache(makeQueryClient);
-/**
- * tRPC for server components. Goes straight to the API rather than through the
- * app's own proxy route — there is no browser in the loop, so there is no
- * same-origin problem to solve, and one fewer hop.
- */
export function getServerTrpc(): TRPCOptionsProxy<AppRouter> {
const client = createTRPCClient<AppRouter>({
links: [
httpBatchLink({
url: `${API_URL}/api/trpc`,
headers: async () => {
- // Forward the incoming session cookie so the API's AuthMiddleware
- // resolves the same user this render is for.
const cookie = (await cookies()).toString();
return cookie ? { cookie } : {};
},
diff --git a/apps/app/lib/trpc/types.ts b/apps/app/lib/trpc/types.ts
index 1a5c17fd..eccb58c4 100644
--- a/apps/app/lib/trpc/types.ts
+++ b/apps/app/lib/trpc/types.ts
@@ -1,10 +1,4 @@
import type { inferRouterOutputs } from "@trpc/server";
import type { AppRouter } from "api/app-router";
-/**
- * The API's own types, reachable from anywhere in the app.
- *
- * Prefer these over hand-written row types: `RouterOutputs["companies"]["list"]`
- * changes the moment the service's `select` does, which is the point.
- */
export type RouterOutputs = inferRouterOutputs<AppRouter>;
diff --git a/apps/app/next.config.ts b/apps/app/next.config.ts
index ba738d86..9c9bca2a 100644
--- a/apps/app/next.config.ts
+++ b/apps/app/next.config.ts
@@ -1,28 +1,8 @@
import { loadRootEnv } from "@crm/env";
import type { NextConfig } from "next";
-// Next only looks for `.env` files beside the app. The one in this repo is at
-// the workspace root, so it is read here — before `env` below is evaluated.
loadRootEnv();
-/**
- * The API origin, published to the browser.
- *
- * Self-hosters set `API_URL` once and both sides of the app agree: the server
- * components fetching tRPC and the browser sending someone to sign in. This
- * used to be two separate `NEXT_PUBLIC_*` variables that had to hold the same
- * value, which is one variable more than there are origins.
- *
- * `env` rather than a runtime read, because `NEXT_PUBLIC_*` is inlined at build
- * time and a value that only exists in the root `.env` would otherwise be
- * `undefined` in the bundle.
- *
- * `NEXT_PUBLIC_API_URL` is still honoured as a fallback. It is the name this
- * used to have, and a deployment that still sets it must not be silently
- * rewritten to `localhost` by the default below — that failure builds and
- * deploys cleanly, then every request from the browser goes to the reader's own
- * machine.
- */
const apiUrl =
process.env.API_URL ??
process.env.NEXT_PUBLIC_API_URL ??
@@ -33,23 +13,17 @@ const nextConfig: NextConfig = {
NEXT_PUBLIC_API_URL: apiUrl,
},
- // The @crm/* packages are just-in-time: they ship TypeScript sources, so
- // Next has to compile them rather than treat them as prebuilt dependencies.
transpilePackages: ["@crm/auth", "@crm/db", "@crm/ui"],
- // Prisma's runtime and the pg driver are Node-only and resolve files at
- // runtime; bundling them breaks that. @crm/db itself is still transpiled.
serverExternalPackages: ["@prisma/client", "@prisma/adapter-pg", "pg"],
images: {
remotePatterns: [
- // Google account avatars, which arrive as `user.image`.
- { protocol: "https", hostname: "lh3.googleusercontent.com" },
+ { protocol: "https", hostname: "**.blob.vercel-storage.com" },
],
},
experimental: {
- // The app shell uses `view-transition-name` and <Link transitionTypes>.
viewTransition: true,
},
};
diff --git a/apps/app/postcss.config.mjs b/apps/app/postcss.config.mjs
index a342880d..fb07e045 100644
--- a/apps/app/postcss.config.mjs
+++ b/apps/app/postcss.config.mjs
@@ -1,2 +1 @@
-// Single source of truth for PostCSS/Tailwind lives in @crm/ui.
export { default } from "@crm/ui/postcss.config";
diff --git a/apps/app/proxy.ts b/apps/app/proxy.ts
index dd8241a7..15f0b02b 100644
--- a/apps/app/proxy.ts
+++ b/apps/app/proxy.ts
@@ -1,22 +1,6 @@
import { getSessionCookie } from "better-auth/cookies";
import { type NextRequest, NextResponse } from "next/server";
-/**
- * Optimistic auth routing.
- *
- * This only looks at whether a session cookie is *present* — no database
- * round-trip, because proxy runs on prefetches too. The real check lives in
- * `requireSession()`, which every protected page calls.
- *
- * Deliberately one-directional. Turning anonymous traffic away from protected
- * routes is safe to guess at: the worst case is a redirect the authoritative
- * check would have made anyway. Turning cookie-bearing traffic away from
- * `/sign-in` is not, because a cookie can be present and still not resolve to a
- * session — expired, database reset, secret rotated, database down. Then this
- * bounces the browser to `/`, `requireSession()` bounces it straight back to
- * `/sign-in`, and neither side ever wins. Sending genuinely signed-in users off
- * `/sign-in` belongs on the sign-in page, where the session can be verified.
- */
export function proxy(request: NextRequest) {
const isSignedIn = getSessionCookie(request) !== null;
const isSignInPage = request.nextUrl.pathname === "/sign-in";
@@ -29,15 +13,6 @@ export function proxy(request: NextRequest) {
}
export const config = {
- // Static assets are excluded by extension rather than by name: the icon set
- // in `public/` (favicon.svg, favicon-96x96.png, apple-touch-icon.png,
- // site.webmanifest, web-app-manifest-*.png) is fetched by the browser with no
- // regard for auth, and redirecting those to /sign-in serves HTML where an
- // image or a manifest was expected.
- //
- // `/api/*` is excluded for the same reason: it is the passthrough to the
- // NestJS API, which does its own auth and answers with a 401. A caller
- // expecting JSON should get that, not a 307 to a sign-in page.
matcher: [
"/((?!api|_next/static|_next/image|.*\\.(?:ico|png|svg|jpg|jpeg|gif|webp|webmanifest)$).*)",
],
diff --git a/apps/app/test/agent-bridge.spec.ts b/apps/app/test/agent-bridge.spec.ts
index 53b43448..0c3a4d90 100644
--- a/apps/app/test/agent-bridge.spec.ts
+++ b/apps/app/test/agent-bridge.spec.ts
@@ -1,19 +1,8 @@
import { beforeAll, describe, expect, it } from "bun:test";
import { verifyJwtHmac } from "eve/channels/auth";
-/**
- * The token the contact sheet uses to reach the agent.
- *
- * This is the security boundary of the whole panel: the agent can read every
- * email in the CRM, and this token is what says a particular signed-in rep is
- * asking. So the test is a real round trip — minted by the app, verified by
- * eve's own verifier with the same configuration `agent/channels/eve.ts`
- * uses — rather than an assertion about what I believe the format to be.
- */
-
const SECRET = "test-secret-at-least-long-enough-to-be-a-secret";
-/** Must match `apps/agent/agent/channels/eve.ts`. */
const CONFIG = {
algorithm: "HS256",
audiences: ["crm-agent"],
@@ -43,16 +32,6 @@ describe("mintBridgeToken", () => {
});
it("names the rep, so the agent knows a person is driving", async () => {
- // The whole reason this is not a shared service credential: the approval
- // policy on the agent side behaves differently for a person than for the
- // cron principal, and `ask_question` only makes sense when someone is
- // there to answer.
- //
- // The *subject* is the rep. eve's own principal mapping labels an HMAC
- // token as a service and namespaces its id (`crm-app:user_123`), which is
- // the right default for a machine credential and wrong for this — so the
- // agent re-maps it in `repFromCrm`, and `channel-auth.spec.ts` covers that
- // half.
const token = await mintBridgeToken(rep);
const result = await verifyJwtHmac(token, CONFIG);
diff --git a/apps/app/test/agent-session.spec.ts b/apps/app/test/agent-session.spec.ts
index 5fd9e5f6..7e00682c 100644
--- a/apps/app/test/agent-session.spec.ts
+++ b/apps/app/test/agent-session.spec.ts
@@ -4,15 +4,6 @@ import type { MessageStreamEvent, SessionState } from "eve/client";
import { recordCopy, recordFilter, recordHeader } from "../lib/agent-record";
import { classify, composerState, eventsOf } from "../lib/agent-session";
-/**
- * Picking a conversation back up.
- *
- * The state of a thread comes from one `session.snapshot()` — events, cursor,
- * and a continuation token if and only if eve will accept another turn. What
- * is left to decide is what a snapshot with *no* token means, and that is the
- * whole of `classify`.
- */
-
const NOW = Date.parse("2026-08-01T12:00:00.000Z");
const event = (
@@ -31,9 +22,6 @@ const unparked: SessionState = { sessionId: "wrun_1", streamIndex: 3 };
describe("classify", () => {
it("trusts the token over any reading of the events", () => {
- // eve returns one only when the captured prefix ends parked, which is
- // exactly the condition under which the next send is accepted. Nothing we
- // could infer from the event list is a better answer than that.
expect(classify(parked, [event("message.appended")], NOW)).toBe("ready");
});
@@ -49,9 +37,6 @@ describe("classify", () => {
});
it("retires a turn that stopped mid-sentence", () => {
- // A restarted agent leaves sessions with no closing boundary. They never
- // park, so without this they read as working forever and that thread can
- // never be typed into again.
const stalled = event("message.appended", "2026-08-01T11:50:00.000Z");
expect(classify(unparked, [stalled], NOW)).toBe("ended");
@@ -82,8 +67,6 @@ describe("the composer", () => {
});
it("holds input while a turn is in flight, from either side", () => {
- // `busy` is this panel's own send; `working` is a turn somebody else
- // started. eve rejects input in both cases.
expect(
composerState({ status: "ready", session: parked, events: [] }, true)
.locked,
@@ -97,17 +80,12 @@ describe("the composer", () => {
});
it("says an ended thread is ended rather than merely busy", () => {
- // The bug this exists for: an answered question sat above a composer
- // disabled with "still working on the last question", forever, and the
- // only way on — a new thread — was never offered.
expect(
composerState({ status: "ended", session: unparked, events: [] }, false),
).toEqual({ locked: true, ended: true });
});
it("lets somebody type when the agent could not be reached", () => {
- // Not locked: that read fails the same way every time, so locking on it
- // is permanent. A send either works or raises a visible error.
expect(composerState({ status: "offline", events: [] }, false)).toEqual({
locked: false,
ended: false,
@@ -136,7 +114,6 @@ describe("record context", () => {
});
it("offers questions that suit the record", () => {
- // The tell of a bolted-on chat box is "Who is this person?" on a company.
expect(recordCopy("company").suggestions.join(" ")).not.toContain("person");
expect(recordCopy("deal").suggestions.join(" ")).not.toContain("person");
expect(recordCopy("contact").suggestions[0]).toBe("Who is this person?");
@@ -169,15 +146,6 @@ describe("the panel", () => {
"utf8",
);
- /**
- * A source-level check, deliberately.
- *
- * This bug shipped twice: the suggestions were wired to the record while the
- * heading above them stayed a literal, so a deal offered "Where does this
- * stand?" under "Ask about this person". There is no DOM here to render
- * against, and the defect is precisely "a string that should have come from
- * `recordCopy` did not" — which is visible in the file.
- */
it("takes its copy from the record, never from a literal", () => {
for (const kind of ["contact", "company", "deal"] as const) {
const copy = recordCopy(kind);
@@ -188,20 +156,12 @@ describe("the panel", () => {
});
it("offers a way out of a thread that has ended", () => {
- // A finished thread locks its composer. Without this button there is
- // nothing at all the reader can do with the sheet in front of them.
expect(source()).toContain("Start a new conversation");
expect(source()).toContain("onClick={onNewThread}");
});
});
describe("the record sheet", () => {
- /**
- * The panel holds a live stream. Radix unmounts an inactive tab by default,
- * which aborts it mid-answer — the reply then lands in the durable session
- * with nothing attached to receive it, and coming back to the tab showed a
- * question with no answer under it.
- */
it("keeps the agent tab mounted behind the others", () => {
for (const sheet of ["contact", "company", "deal"]) {
const source = readFileSync(
@@ -220,10 +180,7 @@ describe("the record sheet", () => {
"utf8",
);
- // Kept alive once opened, and not rendered at all before that.
expect(sheet).toContain("tab.keepMounted && opened.has(tab.value)");
- // Without this the kept-alive panel renders on top of the visible tab:
- // `display:flex` on the same element beats the `hidden` attribute.
expect(sheet).toContain("data-[state=inactive]:hidden");
});
});
diff --git a/apps/app/test/agent-transcript.spec.ts b/apps/app/test/agent-transcript.spec.ts
index 9dd3c578..d7cfb62d 100644
--- a/apps/app/test/agent-transcript.spec.ts
+++ b/apps/app/test/agent-transcript.spec.ts
@@ -12,15 +12,6 @@ import {
toTranscript,
} from "../lib/agent-transcript";
-/**
- * Turning the agent's event stream into something a rep can read.
- *
- * The panel is a rendering of this, so this is where the behaviour worth
- * pinning lives: which step reads as a refusal, which URLs are offered to
- * click, and — the bug that shipped — whether a rep's own question comes back
- * as their own words.
- */
-
const message = (parts: unknown[], role: "user" | "assistant" = "assistant") =>
({ id: "m1", role, parts }) as unknown as EveMessage;
@@ -36,10 +27,6 @@ const tool = (
describe("toTranscript", () => {
it("keeps a rep's question as the words they typed", () => {
- // The panel used to prefix every message with "About contact <cuid>
- // (Name):" so the agent knew the record. The rep then read their own
- // question back with plumbing bolted to the front of it. The record now
- // travels in a header, and this is the assertion that keeps it there.
const [first] = toTranscript([
message([{ type: "text", text: "Hey!" }], "user"),
]);
@@ -49,9 +36,6 @@ describe("toTranscript", () => {
});
it("keeps one message's parts in one row", () => {
- // The row is what the scroller measures. A row per tool call means a new
- // boundary every few hundred milliseconds during an answer, and that is
- // what the flicker was.
const grouped = toTranscript([
message([
{ type: "text", text: "Looking now." },
@@ -64,7 +48,6 @@ describe("toTranscript", () => {
});
it("gives a tool call the same id across its streaming states", () => {
- // An id that moves as parts arrive remounts the row mid-answer.
const streaming = toTranscript([
message([
tool("get_linkedin_profile", {
@@ -121,9 +104,6 @@ describe("describe", () => {
});
it("falls back to a readable form of an unknown tool", () => {
- // Sentence case, not the raw slug: `load skill` sitting in lowercase
- // among finished English sentences is what made the transcript look
- // half-built.
expect(describeStep(tool("some_new_tool") as never)).toBe("Some new tool");
});
});
@@ -247,8 +227,6 @@ describe("resolveThread", () => {
];
it("lands on the most recent conversation when the URL says nothing", () => {
- // Reopening a contact should show what you asked last time, not an
- // empty box.
const { current } = resolveThread({
conversations: rows,
fromUrl: null,
@@ -280,8 +258,6 @@ describe("resolveThread", () => {
});
it("does not move the open thread when the list grows underneath it", () => {
- // The bug this exists to stop: saving the first message adds a row, and
- // re-deriving "the latest" would swap the session out mid-answer.
const before = resolveThread({
conversations: rows,
fromUrl: null,
@@ -321,12 +297,6 @@ describe("resolveThread", () => {
});
describe("every tool has a line of English", () => {
- /**
- * The bug: `load_skill` appeared in the middle of a run, in lowercase, with
- * an underscore in it, between "Read a LinkedIn profile" and "Put a name to
- * the address". eve's built-ins arrive without anybody adding a file for
- * them, which is exactly why they are the ones that get missed.
- */
const BUILT_INS = [
"load_skill",
"web_search",
diff --git a/apps/app/test/day.spec.ts b/apps/app/test/day.spec.ts
index c20ea983..551f44c4 100644
--- a/apps/app/test/day.spec.ts
+++ b/apps/app/test/day.spec.ts
@@ -1,20 +1,8 @@
import { describe, expect, it } from "bun:test";
import { formatDay, fromDay, toDay } from "@crm/ui/lib/format";
-/**
- * A close date is a day on a calendar, not an instant.
- *
- * This is pinned because the bug it prevents is invisible in the timezone the
- * code was written in and off by a whole day in the one the reps are in: the
- * server stores `2026-12-31` as midnight **UTC**, and anything that reads that
- * back through `new Date(iso)` west of Greenwich renders December 30th. The
- * sheet shipped with the property row fixed and the stats strip two inches
- * above it not, so the same deal claimed two different close dates.
- */
describe("day strings", () => {
it("round-trips a date through its local parts", () => {
- // Late enough in the day that a UTC-based conversion would roll over to
- // the 1st anywhere east of Greenwich.
const date = new Date(2026, 11, 31, 23, 30);
expect(toDay(date)).toBe("2026-12-31");
expect(toDay(fromDay(toDay(date)) as Date)).toBe("2026-12-31");
@@ -25,7 +13,6 @@ describe("day strings", () => {
});
it("reads the day the server stored, not the local rendering of it", () => {
- // What the API returns for a deal closing on the 31st.
expect(formatDay("2026-12-31T00:00:00.000Z")).toBe("Dec 31, 2026");
expect(fromDay("2026-12-31T00:00:00.000Z")?.getDate()).toBe(31);
});
diff --git a/apps/app/tsconfig.json b/apps/app/tsconfig.json
index 62768cef..9240b501 100644
--- a/apps/app/tsconfig.json
+++ b/apps/app/tsconfig.json
@@ -2,13 +2,7 @@
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "@crm/typescript-config/nextjs.json",
"compilerOptions": {
- // `api/app-router` re-exports the router classes as types, so tsc walks
- // into apps/api and meets NestJS's legacy decorators. Nothing in this app
- // uses a decorator; this is purely so the imported sources parse.
"experimentalDecorators": true,
- // `bun:test` in `test/`. Additive rather than a replacement: Next's own
- // ambient types come from `next-env.d.ts` and the include list, not from
- // `types`, so naming one package here does not hide them.
"types": ["bun"],
"paths": {
"@/*": ["./*"]
diff --git a/biome.jsonc b/biome.jsonc
index 395e9b66..5c892fb5 100644
--- a/biome.jsonc
+++ b/biome.jsonc
@@ -9,18 +9,12 @@
"ignoreUnknown": false,
"includes": [
"**",
- // Prisma Client output — regenerated, never edited.
"!**/src/generated",
- // Vendored shadcn/ui source. Left in upstream formatting so that
- // `shadcn add --diff <component>` stays readable when re-syncing.
- // use-mobile.ts arrives the same way, pulled in by `sidebar`.
"!packages/ui/src/components",
"!packages/ui/src/hooks/use-mobile.ts",
"!**/.next",
"!**/dist",
- // Static assets, not source.
"!**/*.svg",
- // Agent tooling, managed outside this repo.
"!.claude",
"!.agents",
"!skills-lock.json"
@@ -38,7 +32,6 @@
},
"css": {
"parser": {
- // Tailwind v4 uses @theme / @apply in globals.css.
"tailwindDirectives": true
}
},
@@ -47,7 +40,6 @@
"quoteStyle": "double"
},
"parser": {
- // NestJS relies on parameter decorators (@Inject, @Session, @Body).
"unsafeParameterDecoratorsEnabled": true
}
},
@@ -61,7 +53,6 @@
},
"overrides": [
{
- // Replaces eslint-config-next / eslint-plugin-react.
"includes": ["apps/app/**"],
"linter": {
"domains": {
@@ -71,9 +62,6 @@
}
},
{
- // Nest resolves constructor dependencies from `design:paramtypes`
- // metadata, which only exists for value imports. Rewriting them to
- // `import type` erases the metadata and breaks DI at runtime.
"includes": ["apps/api/**"],
"linter": {
"rules": {
diff --git a/bun.lock b/bun.lock
index e888b78c..ace57518 100644
--- a/bun.lock
+++ b/bun.lock
@@ -16,7 +16,6 @@
"dependencies": {
"@crm/db": "workspace:*",
"@crm/env": "workspace:*",
- "@vercel/blob": "^2.6.1",
"context.dev": "^2.7.0",
"eve": "^0.29.4",
"zod": "^4.4.3",
@@ -132,6 +131,7 @@
"@crm/env": "workspace:*",
"@prisma/adapter-pg": "^7.9.1",
"@prisma/client": "^7.9.1",
+ "@vercel/blob": "^2.6.1",
},
"devDependencies": {
"@crm/typescript-config": "workspace:*",
@@ -158,6 +158,7 @@
"version": "0.0.0",
"dependencies": {
"@carbon/icons-react": "^11.82.0",
+ "@crm/db": "workspace:*",
"@shadcn/react": "^0.2.1",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -181,6 +182,7 @@
"@types/node": "^24.10.1",
"@types/react": "^19.2.18",
"@types/react-dom": "^19",
+ "next": "16.2.12",
"react": "19.2.4",
"react-dom": "19.2.4",
"shadcn": "^4.16.1",
@@ -188,6 +190,7 @@
"typescript": "5.9.2",
},
"peerDependencies": {
+ "next": "^16.0.0",
"react": "^19.2.0",
"react-dom": "^19.2.0",
},
@@ -2149,7 +2152,7 @@
"uint8array-extras": ["[email protected]", "", {}, "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A=="],
- "undici": ["[email protected]", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="],
+ "undici": ["[email protected]", "", {}, "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA=="],
"undici-types": ["[email protected]", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
@@ -2243,6 +2246,8 @@
"@ai-sdk/gateway/@vercel/oidc": ["@vercel/[email protected]", "", {}, "sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug=="],
+ "@ai-sdk/provider-utils/undici": ["[email protected]", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="],
+
"@babel/core/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
"@babel/helper-compilation-targets/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
@@ -2293,6 +2298,8 @@
"@dotenvx/dotenvx/open": ["[email protected]", "", { "dependencies": { "define-lazy-prop": "^2.0.0", "is-docker": "^2.1.1", "is-wsl": "^2.2.0" } }, "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ=="],
+ "@dotenvx/dotenvx/undici": ["[email protected]", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="],
+
"@dotenvx/dotenvx/yocto-spinner": ["[email protected]", "", { "dependencies": { "yoctocolors": "^2.1.1" } }, "sha512-DODGl1wJjA/s5pnJFKau9lIYHT81lnhob1i3e1TjxZRxEhWRKl74nTbWE6H5KlkViQQTo/Z29YFdxzTZAMY3ng=="],
"@mermaid-js/parser/@chevrotain/types": ["@chevrotain/[email protected]", "", {}, "sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw=="],
@@ -2463,8 +2470,6 @@
"@tailwindcss/oxide-wasm32-wasi/tslib": ["[email protected]", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
- "@vercel/blob/undici": ["[email protected]", "", {}, "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA=="],
-
"@vercel/cli-config/zod": ["[email protected]", "", {}, "sha512-WPsqwxITS2tzx1bzhIKsEs19ABD5vmCVa4xBo2tq/SrV4RNZtfws1EnCWQXM6yh8bD08a1idvkB5MZSBiZsjwg=="],
"@vercel/cli-exec/execa": ["[email protected]", "", { "dependencies": { "cross-spawn": "^7.0.3", "get-stream": "^6.0.0", "human-signals": "^2.1.0", "is-stream": "^2.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^4.0.1", "onetime": "^5.1.2", "signal-exit": "^3.0.3", "strip-final-newline": "^2.0.0" } }, "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg=="],
@@ -2569,6 +2574,8 @@
"shadcn/open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.4.0", "define-lazy-prop": "^3.0.0", "is-in-ssh": "^1.0.0", "is-inside-container": "^1.0.0", "powershell-utils": "^0.1.0", "wsl-utils": "^0.3.0" } }, "sha512-smsWv2LzFjP03xmvFoJ331ss6h+jixfA4UUV/Bsiyuu4YJPfN+FIQGOIiv4w9/+MoHkfkJ22UIaQWRVFRfH6Vw=="],
+ "shadcn/undici": ["[email protected]", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="],
+
"shadcn/zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"type-is/content-type": ["[email protected]", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="],
diff --git a/docker-compose.yml b/docker-compose.yml
index fa394eed..96fa7bf3 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,15 +1,3 @@
-# Postgres for local development.
-#
-# docker compose up -d
-#
-# The credentials match the DATABASE_URL in .env.example, so a fresh clone
-# needs no decisions: start this, copy the env file, migrate, and go. Nothing
-# else in the stack is containerised — the API, the app and the agent all run
-# from `bun run dev` with hot reload, which is what you want while working on
-# them.
-#
-# This is a development database. It has a trivial password and it publishes a
-# port on localhost; do not point production at it.
services:
postgres:
@@ -25,8 +13,6 @@ services:
volumes:
- crm-postgres:/var/lib/postgresql/data
healthcheck:
- # `bun run db:deploy` straight after `up -d` would otherwise race the
- # server's first start, which looks like an unreachable database.
test: ["CMD-SHELL", "pg_isready -U postgres -d crm"]
interval: 3s
timeout: 5s
diff --git a/docs/agent.md b/docs/agent.md
index 64786b92..053a6db4 100644
--- a/docs/agent.md
+++ b/docs/agent.md
@@ -23,6 +23,194 @@ expensive in a specific way: it typechecks, builds, and then behaves differently
from what you assumed — see the note on principal mapping under [the
bridge](#the-bridge).
+## The model is a setting, not a deploy
+
+The agent runs on **`zai/glm-5.2-fast`** by default, and a rep can change that
+on the settings page without touching the code.
+
+`DEFAULT_AGENT_MODEL` lives in [`@crm/db/settings`](../packages/db/src/settings.ts)
+because two processes need the same answer — the agent, to compile its
+fallback, and the API, to tell the settings page what "Default" resolves to.
+A second copy of that string is a second answer to the question.
+
+- **The choice is a row, not an env var.** `AppSetting` holds one record, and
+ `agent.ts` resolves it through `defineDynamic` on `session.started` — so a
+ change applies to the next session rather than the next deployment, which
+ matters in an install whose owner cannot redeploy. A conversation already
+ open finishes on the model it started with, and that is deliberate: prompt
+ caches are per model, so switching part-way re-ingests the thread at uncached
+ prices.
+- **The window travels with the id.** eve never inherits
+ `modelContextWindowTokens` from the fallback, so `lib/model.ts` always sends
+ it. A model with a smaller window than the default would otherwise be
+ compacted against a number it does not have, and the turn fails at the
+ provider after the context has been assembled and paid for.
+- **A failed read degrades, it does not throw.** No row, no database, a
+ resolver that raises — all of them leave the compiled fallback in force.
+ `lib/model.ts` logs the reason, because the alternative is a session quietly
+ running on a model nobody chose.
+- **The chooser only offers models this agent can run.** Every read the agent
+ has is a tool, so `ModelCatalogService` filters the gateway catalog to
+ language models tagged `tool-use`. An unreachable gateway makes the chooser
+ read-only rather than failing the page, and the id already stored keeps
+ running.
+- **Not a frontier model, on purpose.** The hard part of this job is refusing a
+ plausible-looking wrong answer, and that is enforced by the tools and the
+ evidence model below rather than by model strength. What the job does want is
+ a long window — a company preamble hands over every contact on the account —
+ and answers fast enough that the sheet's Agent tab reads as a conversation.
+
+## Pictures are copied, never linked
+
+A logo and a profile photograph both arrive as somebody else's URL, and neither
+may be stored as one. LinkedIn signs its CDN URLs with an expiry roughly three
+weeks out; a brand's own CDN is fine until it is a rate limit on a page drawing
+forty logos. Either way the failure is the same and it is the worst shape a
+failure can take here — a picture that works today and is a broken image next
+month, with nothing to connect the two.
+
+So `mirror()` copies the bytes into Vercel Blob and the record points at our
+copy.
+
+**It lives in [`@crm/db/blob`](../packages/db/src/blob.ts), not in the agent.**
+It started here, on the reasoning that whoever writes the URL onto the record
+should own fetching the bytes — which is still right, and is exactly why it had
+to move once more than one thing wrote one. There are four writers now, in three
+processes:
+
+| Writer | What it copies |
+| --- | --- |
+| `lib/brand-images.ts` (agent) | The four artwork columns on a company |
+| `lib/portrait.ts` (agent) | A contact's photograph |
+| `FaviconService` (API) | The icon a domain's own site serves |
+| `ImageMirrorService` (API) | Anything on an existing row still pointing off-site, including a signed-in user's Google avatar |
+
+`packages/db/prisma/seed.ts` is the fifth, and it matters more than it sounds:
+demo rows outlive their sources, and a clone seeded today is still open in six
+months.
+
+- **The key carries a hash of the bytes.** That is what makes re-running both
+ idempotent and correct: unchanged artwork lands on the same URL and the record
+ does not move, while a brand that redesigns its mark gets a *new* URL rather
+ than the same one behind a month of CDN cache.
+- **One list of the columns that hold a picture**, `COMPANY_IMAGE_FIELDS` in
+ [`@crm/db/images`](../packages/db/src/images.ts). Four things read it and a
+ column missing from one of them is a picture that is never brought in-house,
+ with nothing anywhere to say so.
+- **It fetches through `@crm/db/safe-fetch`**, which is the favicon resolver's
+ own guard, exported rather than copied. The URL came from a vendor's answer
+ about a domain a rep typed, so a logo link pointing at `169.254.169.254` is a
+ request forgery from inside our network. One copy of that rule, several
+ callers.
+- **No `BLOB_READ_WRITE_TOKEN` means no photographs**, and everything else keeps
+ the origin's URL. The distinction is deliberate: a face comes from a signed
+ CDN link that expires, so storing one would promise a picture that breaks in
+ three weeks, while a logo or a favicon merely stays somebody else's to serve.
+ It is an optional capability like every other, and it is in
+ `lib/capabilities.ts` so the agent is told before it plans.
+- **A mirrored URL is what lets the browser optimize it.** `isOptimizable` in
+ `@crm/db/images` is the whole of that decision and both halves are load
+ bearing: `next.config.ts` allow-lists our Blob host and nothing else, because
+ a wildcard would make the deployment an open image proxy — and a mirrored
+ *SVG* is still refused, because Blob's separate origin is the only reason we
+ store SVG at all, and `/_next/image` would re-serve those bytes from ours.
+ Everything that fails the check renders as the plain `<img>` it always was.
+- **Faces are not optimized, and that is not an oversight.** `EntityLogo` uses
+ `<Image>`; `AvatarImage` deliberately does not. Radix establishes an avatar's
+ load state by probing the URL with its own `new window.Image()`, so an
+ optimized child would request a second, different URL — two fetches per face
+ on a table drawing forty. There is nothing to win for the second one either:
+ every photograph we store arrives pre-thumbnailed by its source
+ (`shrink_100_100`, `=s96-c`), while brand artwork arrives at whatever size the
+ brand publishes.
+- **A photograph is only ever taken from a source already tied to this person.**
+ `lib/portrait.ts` holds the write and `lib/portrait-sources.ts` holds the
+ chain, in order of certainty: their LinkedIn profile, their GitHub account,
+ their employer's own team page. Every one is keyed on an identifier already on
+ the record, so each asks *what does this account look like* rather than *who
+ is this name*.
+- **There is no image search by name, and there must never be.** It is the
+ obvious fourth step and the one that breaks everything else. A search for
+ "Paula Marchetti" returned Brightwater's CEO, an HR lead at Reply and a data
+ engineer in Seattle, all confidently — and those were names, which a rep can
+ read and smell. Nobody audits a face. Guess where to look, never what you will
+ find: a team page is a guess about a URL, and the name printed beside the
+ photograph is the answer.
+- **`get_linkedin_profile` stores the picture itself** the moment it computes
+ `isSamePerson`, in code, rather than asking the model to remember a follow-up
+ call.
+
+### A portrait is not a research session
+
+`schedules/dispatch.ts` runs `portrait` rows **directly, without `receive`**.
+This is the one kind that skips the model, and it is worth knowing why: the work
+is three reads keyed on identifiers already on the record and a byte copy, with
+nothing in it to decide.
+
+Routed through a session it also did not work. Seven queued faces sat behind
+sixty LLM sessions at five a minute and had not landed twenty five minutes
+later, each one waiting to pay for a context window in order to make no
+decisions with it.
+
+The schedule still decides nothing, which is the rule it has to keep. The row
+says what the work is; the branch only says whether it needs a conversation.
+
+### Catching up what was missed
+
+Enrichment is queued when a record is created, so anything created before a
+capability existed never gets it. Two routes, and picking the wrong one is
+expensive:
+
+| | Covers | Cost |
+| --- | --- | --- |
+| Automatic sweep, on sign-in | Records never successfully looked up | Ten credits per company |
+| `ImageMirrorService`, in the same sweep | Rows whose picture is still served from somebody else's origin | Nothing |
+| `bun run --filter=agent backfill:images` | Records already enriched, missing only the *pictures* | Nothing |
+
+The middle row is the one that keeps "every picture is ours" true rather than
+true-since-Tuesday. Every writer copies as it writes, but that says nothing
+about rows written before it did, or rows whose copy failed at the time because
+the origin was down. Left alone those never resolve, and nothing looks broken —
+the pictures render perfectly, off someone else's server, forever. It is capped
+at twenty five rows per table per sweep, so a backlog drains over several
+sign-ins instead of in one burst that looks like a scrape.
+
+**A photo sweep queues anyone with a LinkedIn URL, a GitHub URL, or an employer
+with a website — the three doors the chain knows. The third reads the company's
+team page and costs Context.dev credits, which is why a **finished `portrait`
+task stands that contact down for thirty days**. Most people are not on their
+employer's team page and never will be; without the stand-down every sweep would
+pay to re-read the same sites and find the same nothing, forever. The task's
+`outcome` carries what was actually tried, so a month of paid lookups leaves
+something readable behind.
+
+The sweep has no button, deliberately.** It had one on each list page, and a
+control whose correct usage is "press it whenever you notice blanks" is a chore
+dressed as a feature — a rep has no way of knowing which records predate the
+favicon resolver, and no business fixing that by hand.
+
+The trigger is **signing in**, which is the one moment nothing else in the app
+can see. `packages/auth` owns it, through a Better Auth
+`databaseHooks.session.create.after`; `BackfillService.onModuleInit` subscribes
+via `onSignedIn`. The registry exists because the arrow cannot point the other
+way — `@crm/auth` is a dependency of the API, so it must not import a Nest
+provider — and it means the Next.js app, which imports the package only to read
+sessions, runs none of this.
+
+`BackfillService` has no router at all as a result. Nothing calls it; it is
+subscribed. A five-minute stand-down collapses a burst — a team arriving at
+nine, or Google linking an account mid-sign-in — and `auto()` returns before any
+work starts, so nothing is between a person and their CRM.
+
+It writes `AgentTask` rows and decides nothing, which is what keeps it on the
+API's side of the line in [`api.md`](./api.md); whether a given company is worth
+the credits stays the agent's call. Each pass is capped at 500 rows and the
+leftover is logged rather than rounded away.
+
+The script is the cheap half: it re-derives from the `CompanyEnrichment.raw`
+payloads already on disk, which is what keeping them was for. Reach for it when
+the records are fine and only the images are missing.
+
## Evidence, not confidence
**No tool accepts a confidence, a score, or a `sourceUrl` offered as proof.** A
diff --git a/docs/environment.md b/docs/environment.md
index bf8b9e06..dbc1d73e 100644
--- a/docs/environment.md
+++ b/docs/environment.md
@@ -137,7 +137,7 @@ with none of them. A missing key removes a place to look; it is never an error.
| `RAPIDAPI_KEY` | LinkedIn profiles via LinkDAPI — name, title, employer, tenure |
| `CONTEXT_DEV_API_KEY` | Company logo, industry, location and socials from a domain |
| `GITHUB_TOKEN` | Raises the GitHub rate limit from 60/hour when matching profiles |
-| `BLOB_READ_WRITE_TOKEN` | Mirrors profile pictures into Vercel Blob rather than linking them |
+| `BLOB_READ_WRITE_TOKEN` | Mirrors every logo and profile picture into Vercel Blob rather than linking them. Read by the API and the seed too — see below |
| `AI_GATEWAY_API_KEY` | The model. Not needed on Vercel, where OIDC handles it |
| `AGENT_BRIDGE_SECRET` | Lets a rep talk to the agent from the contact sheet — [the bridge](./agent.md#the-bridge) |
@@ -148,6 +148,15 @@ agent plans around what it actually has, and gives the tools a shared
research budget is charged, so an install without a key does not pay for the
discovery on every contact.
+`BLOB_READ_WRITE_TOKEN` is the one entry in that table the agent does not own
+alone, which is why it is also declared in `apps/api/src/config/env.validation.ts`
+and in `apps/api/turbo.json`. The API writes two pictures of its own — the
+favicon a domain serves, and the Google avatar of anyone who signs in — and
+`packages/db/prisma/seed.ts` writes fifteen. The Next.js app is deliberately
+*not* on that list: it only has to recognise one of our URLs to route it through
+the image optimizer, and recognising one needs no token. See
+[the agent's picture rules](./agent.md#pictures-are-copied-never-linked).
+
## Gmail and Calendar sync
Always on. Same OAuth client, same callback — the two read-only scopes are added
diff --git a/packages/auth/package.json b/packages/auth/package.json
index 35e23f70..823669e8 100644
--- a/packages/auth/package.json
+++ b/packages/auth/package.json
@@ -13,6 +13,7 @@
"auth:generate": "better-auth generate --config src/auth.ts --output ../db/prisma/schema.prisma --y",
"check-types": "tsc --noEmit",
"lint": "biome check .",
+ "test": "bun test",
"clean": "rm -rf .turbo node_modules"
},
"dependencies": {
diff --git a/packages/auth/src/auth.ts b/packages/auth/src/auth.ts
index e7ffdea3..619476bb 100644
--- a/packages/auth/src/auth.ts
+++ b/packages/auth/src/auth.ts
@@ -4,6 +4,7 @@ import { prismaAdapter } from "better-auth/adapters/prisma";
import { APIError } from "better-auth/api";
import { env } from "./env";
import { SYNC_SCOPES } from "./scopes";
+import { notifySignedIn } from "./signed-in";
import {
hasSignInAllowList,
isWorkspaceEmail,
@@ -16,37 +17,10 @@ if (env.google) {
socialProviders.google = {
...env.google,
- // Gmail and Calendar are asked for at sign-in, not behind a Connect
- // button. This is an internal, single-tenant tool: reading the mailbox is
- // what the CRM is for, so it is a condition of having an account rather
- // than an optional extra.
- //
- // Requesting them here is necessary but not sufficient — Google's granular
- // consent lets someone untick a scope and still finish signing in, so the
- // app also gates on what was actually granted. See
- // `requireGoogleAccess()` in the Next.js app.
scope: [...SYNC_SCOPES],
- // Offline access, so Google issues a refresh token. Without it the
- // connection dies silently one hour after sign-in, with nothing to
- // refresh from.
- //
- // Deliberately not `prompt: "consent"`: it would show the consent screen
- // on every single sign-in. It is not needed, because a first sign-in — and
- // any sign-in that asks for a scope the user has not yet granted — makes
- // Google prompt anyway, and it is that prompt which mints the refresh
- // token. The missing-refresh-token case is detected and repaired rather
- // than pre-empted.
accessType: "offline",
- // Google only offers accounts on our domain in the chooser. This is a
- // convenience, not the control — `hd` is a hint the client sends and a
- // determined caller can omit it, so the real check is the database hook
- // below, which sees the verified email.
- //
- // Omitted when the allow-list names no domain (a one-person install on a
- // consumer mailbox): `hd` has to be a real domain, and sending an empty
- // one hides every account in the chooser.
...(primaryWorkspaceDomain() ? { hd: primaryWorkspaceDomain() } : {}),
};
}
@@ -101,20 +75,6 @@ export const auth = betterAuth({
databaseHooks: {
user: {
create: {
- /**
- * The actual door.
- *
- * Runs against the profile Google verified, before a row exists, so
- * a personal account that gets past the `hd` hint never becomes a
- * user. This is a single-tenant internal tool: an account outside
- * the allow-list has nothing legitimate to do here, and every
- * record is visible to every signed-in person.
- *
- * An unset allow-list is refused rather than waved through. The
- * failure mode of the other choice is a CRM full of real customer
- * data that anyone with a Google account can read, and it would
- * look like it was working.
- */
before: async (user) => {
if (!hasSignInAllowList()) {
throw new APIError("FORBIDDEN", {
@@ -136,6 +96,19 @@ export const auth = betterAuth({
},
},
},
+
+ session: {
+ create: {
+ after: async (session) => {
+ const user = await db.user.findUnique({
+ where: { id: session.userId },
+ select: { id: true, email: true },
+ });
+
+ if (user) await notifySignedIn(user);
+ },
+ },
+ },
},
});
diff --git a/packages/auth/src/client.ts b/packages/auth/src/client.ts
index 93af55e8..252f2f07 100644
--- a/packages/auth/src/client.ts
+++ b/packages/auth/src/client.ts
@@ -1,11 +1,5 @@
import { createAuthClient } from "better-auth/react";
-/**
- * The browser's view of auth.
- *
- * Points at the API, which is the only process that mounts `/api/auth/*`. The
- * origin is inlined at build time from `API_URL` — see `next.config.ts`.
- */
export const authClient = createAuthClient({
baseURL: process.env.NEXT_PUBLIC_API_URL,
});
diff --git a/packages/auth/src/env.ts b/packages/auth/src/env.ts
index 5eb18438..99556bf4 100644
--- a/packages/auth/src/env.ts
+++ b/packages/auth/src/env.ts
@@ -1,17 +1,5 @@
-// `better-auth generate` loads this file directly, without going through
-// `@crm/db` — so the root `.env` has to be picked up here too.
import "@crm/env/load";
-/**
- * Auth configuration, and the defaults that keep it to four required values.
- *
- * Everything here except the Google credentials has a working localhost
- * default. That is the difference between a clone that runs and a clone that
- * makes you read a table of variables first, and the defaults are only ever
- * right for localhost — `API_URL` and `APP_URL` have to be set for any real
- * deployment, which is why they are the first two lines of `.env.example`.
- */
-
const DEFAULT_API_URL = "http://localhost:3001";
const DEFAULT_APP_URL = "http://localhost:3000";
@@ -38,27 +26,9 @@ const googleCredentials = ():
return { clientId, clientSecret };
};
-/**
- * Where the API is — the origin that mints session cookies and serves
- * `/api/auth/*`.
- *
- * `BETTER_AUTH_URL` is still read because Better Auth's own tooling looks for
- * it, but `API_URL` is the name in `.env.example`: one origin should not have
- * two spellings depending on which library is asking.
- */
const apiUrl =
optional("API_URL") ?? optional("BETTER_AUTH_URL") ?? DEFAULT_API_URL;
-/**
- * Where the browser is.
- *
- * Comma-separated, because a preview deployment and a production domain are
- * both legitimately "the app" — but the first one is canonical, and that is the
- * one sign-in redirects back to. This replaced a separate
- * `AUTH_TRUSTED_ORIGINS`: the set of origins allowed to call the API with
- * credentials was always exactly the set of places the app is served from, so
- * two variables could only ever disagree.
- */
const appUrls = (optional("APP_URL") ?? DEFAULT_APP_URL)
.split(",")
.map((origin) => origin.trim())
@@ -70,9 +40,6 @@ export const env = {
appUrl: apiUrl,
google: googleCredentials(),
cookieDomain: optional("AUTH_COOKIE_DOMAIN"),
- // The API's own origin is trusted too: Better Auth validates the
- // post-sign-in `callbackURL` against this list, and the OAuth round trip
- // starts and ends on the API.
trustedOrigins: [...new Set([...appUrls, apiUrl])],
isProduction: process.env.NODE_ENV === "production",
} as const;
diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts
index cd93d0ca..9b281734 100644
--- a/packages/auth/src/index.ts
+++ b/packages/auth/src/index.ts
@@ -8,6 +8,7 @@ export {
REQUIRED_SCOPES,
SYNC_SCOPES,
} from "./scopes";
+export { onSignedIn, type SignedInHandler } from "./signed-in";
export {
hasSignInAllowList,
isWorkspaceEmail,
diff --git a/packages/auth/src/scopes.ts b/packages/auth/src/scopes.ts
index a678eec3..9a898c19 100644
--- a/packages/auth/src/scopes.ts
+++ b/packages/auth/src/scopes.ts
@@ -1,48 +1,18 @@
-/**
- * The Google scopes this CRM runs on.
- *
- * Defined here rather than in the API because the OAuth request is made from
- * this package — and because the API, the sign-in page and the settings page all
- * have to agree on the exact strings. Two copies of a scope list drift, and the
- * failure mode is silent: the grant looks fine and `isConnected()` says no.
- */
-
-/** Identity. Always requested; Better Auth's Google provider adds these itself. */
export const IDENTITY_SCOPES = ["openid", "email", "profile"] as const;
export const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.readonly";
export const CALENDAR_SCOPE =
"https://www.googleapis.com/auth/calendar.readonly";
-/**
- * Read-only Gmail and Calendar.
- *
- * Requested at sign-in, not behind a Connect button: this is an internal,
- * single-tenant tool where seeing the conversation on a record is the point, so
- * a rep with a CRM account and no mailbox connected is a half-configured
- * account nobody notices is broken.
- *
- * Read-only is not negotiable in v1 — nothing writes back to Google.
- */
export const SYNC_SCOPES = [GMAIL_SCOPE, CALENDAR_SCOPE] as const;
-/** Everything a fully provisioned account has granted. */
export const REQUIRED_SCOPES = [...IDENTITY_SCOPES, ...SYNC_SCOPES] as const;
-/**
- * Whether a grant covers the sync scopes.
- *
- * Takes the raw comma-separated `Account.scope` string, because that is the
- * only place the truth lives — Google's granular consent lets someone untick a
- * scope and still complete sign-in, so "they signed in" does not imply "they
- * granted it".
- */
export function hasSyncScopes(scope: string | null | undefined): boolean {
const granted = parseScopes(scope);
return SYNC_SCOPES.every((needed) => granted.has(needed));
}
-/** `Account.scope` as a set. Google returns it comma- or space-separated. */
export function parseScopes(scope: string | null | undefined): Set<string> {
return new Set(
(scope ?? "")
diff --git a/packages/auth/src/signed-in.ts b/packages/auth/src/signed-in.ts
new file mode 100644
index 00000000..3c47cf22
--- /dev/null
+++ b/packages/auth/src/signed-in.ts
@@ -0,0 +1,23 @@
+export type SignedInHandler = (user: {
+ id: string;
+ email: string;
+}) => void | Promise<void>;
+
+const handlers: SignedInHandler[] = [];
+
+export function onSignedIn(handler: SignedInHandler): void {
+ handlers.push(handler);
+}
+
+export async function notifySignedIn(user: {
+ id: string;
+ email: string;
+}): Promise<void> {
+ for (const handler of handlers) {
+ try {
+ await handler(user);
+ } catch (error) {
+ console.error("[auth] a sign-in handler failed", error);
+ }
+ }
+}
diff --git a/packages/auth/src/workspace.ts b/packages/auth/src/workspace.ts
index 1b0311a1..d94bc1c2 100644
--- a/packages/auth/src/workspace.ts
+++ b/packages/auth/src/workspace.ts
@@ -1,52 +1,12 @@
import "@crm/env/load";
-/**
- * Who is allowed in, and who counts as "us".
- *
- * One list, used by two things that must never disagree: the sign-in guard, and
- * the sync's decision about which side of a conversation is external. If they
- * drifted, a colleague's address would either be refused at the door or filed
- * as a sales lead.
- *
- * This is the whole authorisation model. There are no roles, no organizations
- * and no invitations — "your address is on this list and Google says it is
- * really you" is the entire check, which is why it is a required value rather
- * than one with a friendly default. A CRM that let any Google account in would
- * hand your pipeline to the internet, and an empty list here fails closed:
- * nobody signs in until it is set.
- *
- * `ALLOWED_SIGN_IN` takes a comma-separated mix of the two things people
- * actually have:
- *
- * ```
- * ALLOWED_SIGN_IN="acme.com" # everyone at a workspace
- * ALLOWED_SIGN_IN="acme.com,[email protected]" # …plus one outsider
- * ALLOWED_SIGN_IN="[email protected]" # a one-person install
- * ```
- *
- * The third case is why bare addresses are supported at all: a solo self-hoster
- * on a consumer mailbox has no domain to name, and `gmail.com` would be an
- * open door.
- */
-
type AllowList = {
- /** Whole domains, subdomains included. */
domains: readonly string[];
- /** Individual addresses, for installs with no workspace domain. */
addresses: readonly string[];
};
const EMPTY: AllowList = { domains: [], addresses: [] };
-/**
- * Parsed on demand rather than at import.
- *
- * This module is imported by `auth.ts`, which the Better Auth CLI loads in a
- * process that has no `.env` at all, and by tests that need to set the list
- * themselves. Reading the variable when it is asked for — memoised on the raw
- * string, so repeated calls cost one comparison — means neither of those has to
- * care about import order.
- */
let cachedSource: string | undefined;
let cached: AllowList = EMPTY;
@@ -68,41 +28,23 @@ function allowList(): AllowList {
return cached;
}
-/** Domains whose Google accounts may sign in. */
export function workspaceDomains(): readonly string[] {
return allowList().domains;
}
-/**
- * The one Google shows in its account chooser.
- *
- * `undefined` when the allow-list is only bare addresses — `hd` has to be a
- * domain, and sending a garbage one hides every account in the chooser.
- */
export function primaryWorkspaceDomain(): string | undefined {
return allowList().domains[0];
}
-/** Whether anyone at all can sign in. False means `ALLOWED_SIGN_IN` is unset. */
export function hasSignInAllowList(): boolean {
const { domains, addresses } = allowList();
return domains.length > 0 || addresses.length > 0;
}
-/**
- * Whether an address belongs to us.
- *
- * Subdomain-aware, so `[email protected]` counts against `acme.com`, but a
- * lookalike like `acme.com.evil.com` does not — the boundary is a dot, not a
- * substring.
- */
export function isWorkspaceEmail(email: string | null | undefined): boolean {
const value = email?.trim().toLowerCase();
if (!value) return false;
- // Exactly one `@`. Reading the *last* one would let `[email protected]@acme.com`
- // look like it belongs to us. Google never issues an address like that, but
- // a door should not depend on the other side being well behaved.
const parts = value.split("@");
if (parts.length !== 2) return false;
diff --git a/packages/auth/test/signed-in.spec.ts b/packages/auth/test/signed-in.spec.ts
new file mode 100644
index 00000000..7c3f84fb
--- /dev/null
+++ b/packages/auth/test/signed-in.spec.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "bun:test";
+import { notifySignedIn, onSignedIn } from "../src/signed-in";
+
+const USER = { id: "u1", email: "[email protected]" };
+
+describe("the signed-in registry", () => {
+ it("hands the user to everything registered", async () => {
+ const seen: string[] = [];
+ onSignedIn((user) => {
+ seen.push(`a:${user.email}`);
+ });
+ onSignedIn((user) => {
+ seen.push(`b:${user.id}`);
+ });
+
+ await notifySignedIn(USER);
+
+ expect(seen).toEqual(["a:[email protected]", "b:u1"]);
+ });
+
+ it("does not let a failing handler fail the sign-in", async () => {
+ const after: string[] = [];
+ onSignedIn(() => {
+ throw new Error("backfill exploded");
+ });
+ onSignedIn(() => {
+ after.push("still ran");
+ });
+
+ await expect(notifySignedIn(USER)).resolves.toBeUndefined();
+ expect(after).toEqual(["still ran"]);
+ });
+});
diff --git a/packages/db/package.json b/packages/db/package.json
index 9341b8be..0bdd640b 100644
--- a/packages/db/package.json
+++ b/packages/db/package.json
@@ -5,9 +5,13 @@
"type": "module",
"exports": {
".": "./src/index.ts",
+ "./blob": "./src/blob.ts",
"./client": "./src/client.ts",
"./enums": "./src/generated/prisma/enums.ts",
- "./favicon": "./src/favicon.ts"
+ "./favicon": "./src/favicon.ts",
+ "./images": "./src/images.ts",
+ "./safe-fetch": "./src/safe-fetch.ts",
+ "./settings": "./src/settings.ts"
},
"scripts": {
"build": "prisma generate",
@@ -28,7 +32,8 @@
"dependencies": {
"@crm/env": "workspace:*",
"@prisma/adapter-pg": "^7.9.1",
- "@prisma/client": "^7.9.1"
+ "@prisma/client": "^7.9.1",
+ "@vercel/blob": "^2.6.1"
},
"devDependencies": {
"@crm/typescript-config": "workspace:*",
diff --git a/packages/db/prisma.config.ts b/packages/db/prisma.config.ts
index e9cce865..b0ef7596 100644
--- a/packages/db/prisma.config.ts
+++ b/packages/db/prisma.config.ts
@@ -1,4 +1,3 @@
-// The Prisma CLI runs from this package, so it needs the repo-root `.env` too.
import "@crm/env/load";
import path from "node:path";
diff --git a/packages/db/prisma/migrations/20260802120000_app_settings/migration.sql b/packages/db/prisma/migrations/20260802120000_app_settings/migration.sql
new file mode 100644
index 00000000..38d93c4b
--- /dev/null
+++ b/packages/db/prisma/migrations/20260802120000_app_settings/migration.sql
@@ -0,0 +1,19 @@
+-- Install-wide settings a rep can change, starting with the agent's model.
+--
+-- One row, id pinned to 'app' by `@crm/db/settings`. No unique constraint
+-- enforces that beyond the primary key, because the id is not derived from
+-- anything: a second row can only appear if something writes a different
+-- literal, and every writer goes through `writeAgentModel`.
+CREATE TABLE "appSetting" (
+ "id" TEXT NOT NULL,
+ "agentModelId" TEXT,
+ "agentModelContextWindow" INTEGER,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "appSetting_pkey" PRIMARY KEY ("id")
+);
+
+-- Deliberately not seeded. An absent row means "follow the built-in default",
+-- and writing the current default in here would freeze it: the next time
+-- DEFAULT_AGENT_MODEL changes, every existing install would keep running the
+-- old model while reporting itself as unconfigured.
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
index 89054c19..1755ac29 100644
--- a/packages/db/prisma/schema.prisma
+++ b/packages/db/prisma/schema.prisma
@@ -23,9 +23,6 @@ model User {
sessions Session[]
accounts Account[]
- // CRM ownership. Better Auth owns every field above and `bun run
- // auth:generate` rewrites them; these back-relations are ours and have to be
- // put back if that ever wipes them.
ownedCompanies Company[] @relation("CompanyOwner")
ownedContacts Contact[] @relation("ContactOwner")
ownedDeals Deal[] @relation("DealOwner")
@@ -96,17 +93,9 @@ model RateLimit {
@@map("rateLimit")
}
-// ---------------------------------------------------------------------------
-// CRM
-//
-// Companies are the top-level object; contacts and deals hang off them, and
-// everything that happens is an Activity on a timeline.
-// ---------------------------------------------------------------------------
-
enum DealStage {
DEMO_BOOKED
QUALIFIED_TO_BUY
- /// Terminal, not a step forward — disqualified, and excluded from pipeline value.
UNQUALIFIED_TO_BUY
DECISION_MAKER_BOUGHT_IN
CONTRACT_SENT
@@ -120,9 +109,7 @@ enum ActivityType {
EMAIL
MEETING
TASK
- /// Written by the system when Deal.stage changes.
STAGE_CHANGE
- /// Written by the enrichment agent.
ENRICHMENT
}
@@ -130,15 +117,10 @@ enum EnrichmentStatus {
PENDING
RUNNING
COMPLETE
- /// The lookup failed and is worth retrying — see Company.enrichmentError.
FAILED
- /// There is nothing to find (unknown domain, free email host). Not an error.
SKIPPED
}
-/// Where a record came from. Auto-created rows are tagged so a bad matching
-/// rule is visible and reversible in bulk, rather than silently indistinguishable
-/// from something a rep typed.
enum RecordSource {
MANUAL
IMPORT
@@ -149,33 +131,17 @@ enum RecordSource {
model Company {
id String @id @default(cuid())
name String
- /// Bare and normalised ("stripe.com"). Unique because two records for one
- /// domain is the fastest way to rot a CRM, and it is the enrichment key.
domain String? @unique
website String?
description String?
- // Brand, from Context.dev.
logoUrl String?
logoDarkUrl String?
- /// Square mark, used in table rows.
iconUrl String?
- /// The dark-mode square mark, when the brand publishes one. Rare — most
- /// brands ship a light-mode logo only, which is what `iconTone` is for.
iconDarkUrl String?
- /// How `iconUrl` behaves against a background, from Context.dev's `mode` plus
- /// the artwork's own dominant colour:
- ///
- /// - `opaque` — the icon is composed on its own background; never put a
- /// surface behind it.
- /// - `dark` — dark artwork on transparency; invisible in dark mode without
- /// a light surface behind it.
- /// - `light` — light artwork on transparency; the same problem in reverse.
iconTone String?
- /// Hex. An accent only — brand colours would fight the design tokens.
brandColor String?
- // Firmographics.
industry String?
subIndustry String?
city String?
@@ -183,7 +149,6 @@ model Company {
country String?
countryCode String?
- // Contact details and socials.
phone String?
email String?
linkedinUrl String?
@@ -202,16 +167,8 @@ model Company {
enrichmentError String?
enrichment CompanyEnrichment?
- /// MANUAL unless a sync created it. Filterable, so a bad auto-create rule can
- /// be undone in bulk.
source RecordSource @default(MANUAL)
- /// Denormalised max(activity.createdAt), written with the activity.
- ///
- /// A real column because it is a sortable column on every list, and ordering
- /// by an aggregate over a relation is something Prisma cannot express — the
- /// alternative is a correlated subquery per row, which would be the slowest
- /// thing on the page. Maintained through `ActivityStampService`.
lastActivityAt DateTime?
contacts Contact[] @relation("CompanyContacts")
@@ -229,8 +186,6 @@ model Company {
@@map("company")
}
-/// The raw Context.dev payload, kept so re-deriving a field costs nothing and
-/// no credits.
model CompanyEnrichment {
companyId String @id
company Company @relation(fields: [companyId], references: [id], onDelete: Cascade)
@@ -245,36 +200,20 @@ model Contact {
id String @id @default(cuid())
firstName String
lastName String?
- /// Unique, matching HubSpot, so a CSV import can be re-run safely. The cost:
- /// two people behind one info@ address need one email between them.
email String? @unique
phone String?
title String?
linkedinUrl String?
twitterUrl String?
githubUrl String?
- /// The contact's photo, mirrored into Vercel Blob.
- ///
- /// Never LinkedIn's own CDN URL: those carry an `e=` expiry parameter and go
- /// dead within weeks, so a hotlinked avatar silently becomes a broken image.
imageUrl String?
- /// When the agent last went looking for this person's X and GitHub accounts.
- ///
- /// Stamped whether or not it found any, which is the point: most people have
- /// neither, and without it the hourly run would search the same fruitless
- /// contacts forever. Null means never looked; a date with both URLs still
- /// null means looked and found nothing it could stand behind.
socialsCheckedAt DateTime?
- /// Mirrors `Company`, so the sheet reuses `isEnriching()` and the existing
- /// poll rather than inventing a second freshness mechanism.
enrichmentStatus EnrichmentStatus @default(PENDING)
enrichedAt DateTime?
enrichmentError String?
- /// Who this person is (§3 of the contact-intelligence plan) and every claim
- /// behind the fields above.
brief ContactBrief?
facts ContactFact[]
conversations AgentConversation[]
@@ -287,12 +226,6 @@ model Contact {
source RecordSource @default(MANUAL)
- /// Denormalised max(activity.createdAt), written with the activity.
- ///
- /// A real column because it is a sortable column on every list, and ordering
- /// by an aggregate over a relation is something Prisma cannot express — the
- /// alternative is a correlated subquery per row, which would be the slowest
- /// thing on the page. Maintained through `ActivityStampService`.
lastActivityAt DateTime?
deals DealContact[]
@@ -309,12 +242,6 @@ model Contact {
@@map("contact")
}
-/// How much of a claim we believe, and what that licenses.
-///
-/// The bands are the behaviour, not a label: `VERIFIED` is written to the
-/// record, `PROBABLE` is offered to a human, `POSSIBLE` is kept but never shown
-/// as a value. The numeric `score` beside them exists so the thresholds can be
-/// re-calibrated against evals without re-running the research.
enum FactBand {
VERIFIED
PROBABLE
@@ -328,36 +255,22 @@ enum FactStatus {
SUPERSEDED
}
-/// One claim about one field of one contact, with everything behind it.
-///
-/// The point of a separate table: `Contact.title` can only hold the answer,
-/// and the answer is the least interesting part. This holds where it came
-/// from, how sure we are, what else was considered, and what it replaced —
-/// which is what makes an enriched field auditable rather than merely present.
-///
-/// It is deliberately *not* the read path. Current values stay denormalised on
-/// `Contact` so a list is one query; this is the reasoning behind them.
model ContactFact {
id String @id @default(cuid())
contactId String
contact Contact @relation(fields: [contactId], references: [id], onDelete: Cascade)
- /// The `Contact` column this is about — "title", "linkedinUrl", "employer".
field String
value String
score Float
band FactBand
- /// The full ledger: `[{ kind, weight, detail, sourceUrl }]`. Kept so the
- /// score can be explained to a rep and recomputed after a re-calibration.
evidence Json
method String
sourceUrl String?
- /// The eve session that produced it, joining to `AgentEvent` for "show your
- /// work".
sessionId String?
status FactStatus @default(PROPOSED)
@@ -373,16 +286,11 @@ model ContactFact {
@@map("contactFact")
}
-/// The background panel on a contact: who they are, in prose and in fields.
model ContactBrief {
contactId String @id
contact Contact @relation(fields: [contactId], references: [id], onDelete: Cascade)
- /// Two or three sentences. Present tense, their name first.
narrative String
- /// `{ currentRole, tenure, previousRoles[], seniority, function, location }`
- /// — shaped by the agent, rendered by the sheet, so adding a line does not
- /// need a migration.
sections Json
score Float
@@ -394,12 +302,6 @@ model ContactBrief {
@@map("contactBrief")
}
-/// What the agent has decided to do, and why.
-///
-/// The work queue *and* the audit trail. A cron expression can only say "every
-/// hour for everybody"; a row here says "this person, in fourteen days,
-/// because a job change would move a live deal" — and the reason is shown to
-/// the rep rather than buried in a prompt.
model AgentTask {
id String @id @default(cuid())
contactId String?
@@ -409,21 +311,10 @@ model AgentTask {
reason String
priority Int @default(0)
- /// Research units this task may spend. Depth is a decision, and this is
- /// what the agent decides it against.
budget Int @default(4)
- /// How many times this row has been handed to a session.
- ///
- /// The lease is a deadline rather than a flag so a crashed run frees its
- /// row — but a deadline alone cannot tell "died, retry me" from "cannot
- /// ever finish". Without a count the second case is re-leased every ten
- /// minutes forever, resuming the same durable session and paying for a
- /// model turn each time. Two rows did exactly that for an hour and a half.
attempts Int @default(0)
dueAt DateTime
- /// Held by a dispatcher tick. An expired lease is free to reclaim, which is
- /// what makes a crashed run recoverable rather than stuck.
leasedUntil DateTime?
sessionId String?
@@ -438,15 +329,6 @@ model AgentTask {
@@map("agentTask")
}
-/// Every runtime event the agent emits, written by a hook.
-///
-/// The id is eve's own `meta.id` (a ULID), so an `on conflict do nothing`
-/// insert is replay-safe: reconnecting to a stream, rewinding it, or restoring
-/// a saved log cannot duplicate a row. Leading with a timestamp also keeps the
-/// primary key roughly append-ordered.
-///
-/// This is what "show your work" reads. Without it the agent's reasoning lives
-/// only in a log nobody can query and nobody can show a rep.
model AgentEvent {
id String @id
sessionId String
@@ -461,20 +343,9 @@ model AgentEvent {
@@map("agentEvent")
}
-/// A conversation between a rep and the agent, about one record.
-///
-/// The transcript itself is already in `AgentEvent` — this is the *handle*: the
-/// durable eve session to resume, and enough metadata to list a record's
-/// history without reading a single event. Reopening a contact should show what
-/// you asked last week rather than an empty box.
-///
-/// `sessionId` is unique because one eve session is one conversation. The
-/// cursor beside it (`continuationToken`, `streamIndex`) is what `useEveAgent`
-/// needs to pick the thread back up instead of starting a new one.
model AgentConversation {
id String @id @default(cuid())
- /// Which record it is about. Exactly one of these is set.
contactId String?
contact Contact? @relation(fields: [contactId], references: [id], onDelete: Cascade)
companyId String?
@@ -482,18 +353,13 @@ model AgentConversation {
dealId String?
deal Deal? @relation(fields: [dealId], references: [id], onDelete: Cascade)
- /// Whose conversation. Two reps asking about the same contact are having two
- /// different conversations, and neither should see the other's half-finished
- /// question.
userId String
user User @relation("ConversationOwner", fields: [userId], references: [id], onDelete: Cascade)
sessionId String @unique
continuationToken String?
- /// How far the client had read, so a reopened thread does not replay.
streamIndex Int @default(0)
- /// The first thing the rep asked, trimmed. Written once.
title String?
messageCount Int @default(0)
@@ -512,7 +378,6 @@ model Deal {
name String
companyId String
company Company @relation(fields: [companyId], references: [id], onDelete: Cascade)
- /// Required: every deal has a name against it.
ownerId String
owner User @relation("DealOwner", fields: [ownerId], references: [id])
@@ -524,12 +389,6 @@ model Deal {
closedAt DateTime?
closedReason String?
- /// Denormalised max(activity.createdAt), written with the activity.
- ///
- /// A real column because it is a sortable column on every list, and ordering
- /// by an aggregate over a relation is something Prisma cannot express — the
- /// alternative is a correlated subquery per row, which would be the slowest
- /// thing on the page. Maintained through `ActivityStampService`.
lastActivityAt DateTime?
contacts DealContact[]
@@ -563,15 +422,10 @@ model Activity {
subject String?
body String?
- /// Set when the thing already happened.
occurredAt DateTime?
- /// Set when it is scheduled. Overdue is dueAt in the past with no completedAt.
dueAt DateTime?
completedAt DateTime?
- /// Always stamped when it can be resolved, even for deal and contact
- /// activity, so a company timeline is one indexed range scan rather than
- /// three joins.
companyId String?
company Company? @relation(fields: [companyId], references: [id], onDelete: Cascade)
contactId String?
@@ -581,13 +435,8 @@ model Activity {
createdById String
createdBy User @relation("ActivityAuthor", fields: [createdById], references: [id])
- /// { from, to } for STAGE_CHANGE; the credit cost for ENRICHMENT; `{ synced:
- /// true }` for anything a Google sync projected.
meta Json?
- /// The projection links. Unique because a thread and an event each get exactly
- /// one timeline entry, updated in place as the thread grows or the event moves
- /// — the timeline stays one indexed range scan instead of a three-table union.
emailThreadId String? @unique
emailThread EmailThread? @relation(fields: [emailThreadId], references: [id], onDelete: Cascade)
calendarEventId String? @unique
@@ -604,18 +453,9 @@ model Activity {
@@map("activity")
}
-// ---------------------------------------------------------------------------
-// Google sync
-//
-// Gmail threads and Calendar events get real tables; the timeline gets one
-// projected Activity per thread and per event. Identity is deliberately global
-// rather than Google's per-mailbox ids — see docs/plan/gmail-calendar-plan.md §4.2.
-// ---------------------------------------------------------------------------
-
enum GoogleSyncStatus {
IDLE
RUNNING
- /// The refresh token is gone. Stop trying; the rep has to reconnect.
NEEDS_RECONNECT
FAILED
}
@@ -625,30 +465,17 @@ enum EmailDirection {
OUTBOUND
}
-/// Per-user, per-source cursor.
-///
-/// In Postgres because the API is a serverless function with no memory between
-/// invocations, and because the in-process EnrichmentQueue deliberately drops
-/// queued work on shutdown — fine for enrichment, fatal for a resumable sync.
model MailboxSync {
id String @id @default(cuid())
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
- /// "gmail" | "calendar".
source String
status GoogleSyncStatus @default(IDLE)
- /// Gmail: the last processed historyId. Calendar: nextSyncToken.
- ///
- /// Stamped with "now" the first time a mailbox is seen, which is what makes
- /// this forward-only: there is no backfill, so the cursor starts at the
- /// moment of connection and nothing before it is ever read.
cursor String?
lastSyncedAt DateTime?
lastError String?
- /// Set by the 429/403 handler; the cron skips this row until it passes.
retryAfter DateTime?
- /// Auto-creation is opt-in per source — on for calendar, off for Gmail.
autoCreate Boolean @default(false)
createdAt DateTime @default(now())
@@ -659,12 +486,8 @@ model MailboxSync {
@@map("mailboxSync")
}
-/// One conversation, whoever's mailbox it came from.
model EmailThread {
id String @id @default(cuid())
- /// The RFC 822 Message-ID of the thread root — global, unlike Gmail's
- /// mailbox-scoped threadId. This is what stops two reps on one thread
- /// producing two CRM threads.
rootMessageId String @unique
subject String?
@@ -693,21 +516,16 @@ model EmailMessage {
threadId String
thread EmailThread @relation(fields: [threadId], references: [id], onDelete: Cascade)
- /// Global message identity. Unique, so account B's sync skips what account A
- /// already ingested.
rfcMessageId String @unique
- /// Whose mailbox produced this copy, and its id there — for deep links.
syncedByUserId String?
gmailMessageId String?
direction EmailDirection
fromEmail String
fromName String?
- /// [{ email, name, kind: "to" | "cc" }]. Not a table: nothing queries it.
recipients Json
subject String?
snippet String?
- /// Plain text, quoted history stripped. Never logged; never in list payloads.
body String?
sentAt DateTime
@@ -719,11 +537,8 @@ model EmailMessage {
model CalendarEvent {
id String @id @default(cuid())
- /// Shared by every attendee's copy of the event, and by every instance of a
- /// recurrence — which is why the start time is part of the key.
iCalUid String
originalStartTime DateTime
- /// Set on an instance of a recurring series.
recurringEventId String?
title String?
@@ -763,7 +578,6 @@ model CalendarAttendee {
email String
name String?
- /// needsAction | declined | tentative | accepted
responseStatus String?
isOrganizer Boolean @default(false)
contactId String?
@@ -774,8 +588,6 @@ model CalendarAttendee {
@@map("calendarAttendee")
}
-/// Domains we never match on and never create from — vendors, ATSs, newsletters.
-/// Grows by hand and by a "not a customer" action in the UI.
model SuppressedDomain {
domain String @id
reason String?
@@ -783,3 +595,15 @@ model SuppressedDomain {
@@map("suppressedDomain")
}
+
+model AppSetting {
+ id String @id
+
+ agentModelId String?
+
+ agentModelContextWindow Int?
+
+ updatedAt DateTime @updatedAt
+
+ @@map("appSetting")
+}
diff --git a/packages/db/prisma/seed.ts b/packages/db/prisma/seed.ts
index d067482e..aee7235c 100644
--- a/packages/db/prisma/seed.ts
+++ b/packages/db/prisma/seed.ts
@@ -1,27 +1,8 @@
+import { mirror } from "../src/blob";
import { db } from "../src/client";
import { resolveFavicon } from "../src/favicon";
import { ActivityType, DealStage } from "../src/generated/prisma/enums";
-/**
- * A believable pipeline to develop against: real domains so the enrichment
- * agent has something to look up, deals spread across every stage, and tasks
- * that are genuinely overdue.
- *
- * Idempotent — companies key off `domain`, contacts off `email`, and deals off
- * a deterministic id — so re-running tops the data up rather than duplicating
- * it. Randomness comes from a seeded generator for the same reason: two runs
- * produce the same pipeline.
- *
- * Users are the exception. Better Auth owns them, and a row written here has no
- * Google account attached — but account linking is enabled for Google, so
- * signing in with a matching address adopts the row rather than creating a
- * second one. Real users are used when they exist; the placeholders below are
- * only created when the table is empty.
- */
-
-// --- deterministic randomness -----------------------------------------------
-
-/** mulberry32 — small, fast, and identical across runs. */
function makeRandom(seed: number): () => number {
let a = seed;
return () => {
@@ -51,7 +32,6 @@ function integer(min: number, max: number): number {
const DAY_MS = 24 * 60 * 60 * 1000;
const NOW = Date.now();
-/** Negative is the past. */
function daysFromNow(days: number, jitterHours = 0): Date {
const jitter = jitterHours
? (random() - 0.5) * jitterHours * 60 * 60 * 1000
@@ -59,8 +39,6 @@ function daysFromNow(days: number, jitterHours = 0): Date {
return new Date(NOW + days * DAY_MS + jitter);
}
-// --- source data ------------------------------------------------------------
-
const OWNERS = [
{ name: "Ada Okafor", email: "[email protected]" },
{ name: "Marcus Lindqvist", email: "[email protected]" },
@@ -322,9 +300,6 @@ const EMAIL_SUBJECTS = [
"Intro to your implementation lead",
] as const;
-// --- helpers ----------------------------------------------------------------
-
-/** Letters NFD cannot decompose into base + accent — they are their own letter. */
const TRANSLITERATIONS: Record<string, string> = {
ø: "o",
æ: "ae",
@@ -337,20 +312,15 @@ const TRANSLITERATIONS: Record<string, string> = {
};
function slug(value: string): string {
- return (
- value
- .toLowerCase()
- .replace(/[øæœåßđłþ]/g, (char) => TRANSLITERATIONS[char] ?? char)
- .normalize("NFD")
- // Combining marks left behind by NFD (é → e + ́ ).
- .replace(/\p{Mn}/gu, "")
- .replace(/[^a-z0-9]+/g, "-")
- .replace(/^-|-$/g, "")
- );
+ return value
+ .toLowerCase()
+ .replace(/[øæœåßđłþ]/g, (char) => TRANSLITERATIONS[char] ?? char)
+ .normalize("NFD")
+ .replace(/\p{Mn}/gu, "")
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-|-$/g, "");
}
-// --- seed -------------------------------------------------------------------
-
async function seedOwners(): Promise<string[]> {
const existing = await db.user.findMany({ select: { id: true } });
@@ -397,8 +367,6 @@ async function seedCompanies(
country: company.country,
countryCode: company.countryCode,
ownerId: pick(ownerIds),
- // Left PENDING on purpose: the logo, description and socials are the
- // agent's job, and this gives it real work on first run.
createdAt: daysFromNow(-integer(30, 400), 12),
},
update: {},
@@ -412,16 +380,6 @@ async function seedCompanies(
return companies.map(({ iconUrl: _, ...company }) => company);
}
-/**
- * The favicon each seeded company serves, so a fresh clone is a list of real
- * companies rather than a column of grey squares.
- *
- * Resolved here rather than hard-coded because these URLs rot — half of them
- * carry a deploy hash — and a dead `<img>` is worse than the initials it
- * replaced. Icons the agent has since found are left alone, and a machine with
- * no network simply seeds without them: every failure is a `null`, so the seed
- * cannot be broken by somebody else's origin being down.
- */
async function seedIcons(
companies: { id: string; domain: string | null; iconUrl: string | null }[],
): Promise<void> {
@@ -430,12 +388,13 @@ async function seedIcons(
);
if (missing.length === 0) return;
- // Sequential: this walks fifteen origins that did not ask to be walked, and
- // all at once is a burst that looks like a scan.
let resolved = 0;
for (const company of missing) {
- const iconUrl = await resolveFavicon(company.domain);
- if (!iconUrl) continue;
+ const source = await resolveFavicon(company.domain);
+ if (!source) continue;
+
+ const iconUrl =
+ (await mirror(source, `companies/${company.id}/icon`)) ?? source;
await db.company.updateMany({
where: { id: company.id, iconUrl: null },
@@ -456,8 +415,6 @@ async function seedContacts(
const contacts: SeededContact[] = [];
const used = new Set<string>();
- // A handful per company: a primary contact plus the stakeholders a real deal
- // drags in.
for (const company of companies) {
for (let index = 0; index < integer(2, 4); index++) {
const firstName = pick(FIRST_NAMES);
@@ -486,7 +443,6 @@ async function seedContacts(
}
}
- // The first contact at each company is the one to call.
for (const company of companies) {
const first = contacts.find((contact) => contact.companyId === company.id);
if (!first) continue;
@@ -514,7 +470,6 @@ async function seedDeals(
const deals: SeededDeal[] = [];
for (const [index, company] of companies.entries()) {
- // Every company has a deal; about half also have an expansion.
const count = index % 2 === 0 ? 2 : 1;
for (let n = 0; n < count; n++) {
@@ -524,11 +479,6 @@ async function seedDeals(
const ownerId = pick(ownerIds);
const createdDaysAgo = integer(20, 210);
const createdAt = daysFromNow(-createdDaysAgo, 12);
- // A closed deal closes somewhere between a fortnight after it opened and
- // today, so the overview's six-month trend and its rolling win rate have
- // something in every bucket. Closing them all inside the last fortnight —
- // which is what a flat `integer(1, 20)` did — made every chart a spike
- // against five empty months.
const closedDaysAgo = closed
? integer(0, Math.max(createdDaysAgo - 14, 0))
: null;
@@ -551,8 +501,6 @@ async function seedDeals(
stageChangedAt,
amount: integer(6, 90) * 1000,
currency: "USD",
- // A closed deal landed near the date it was forecast for; an open one
- // is still forecast, and some are already late.
expectedCloseDate: daysFromNow(
closedDaysAgo === null
? integer(-10, 75)
@@ -569,7 +517,6 @@ async function seedDeals(
update: {},
});
- // One or two people from the company are on the deal.
const companyContacts = contacts.filter(
(contact) => contact.companyId === company.id,
);
@@ -598,7 +545,6 @@ async function seedActivities(
deals: SeededDeal[],
ownerIds: string[],
): Promise<number> {
- // Re-running should not stack another 150 rows on top.
const existing = await db.activity.count();
if (existing > 0) {
console.log(`Activities already seeded (${existing}) — skipping.`);
@@ -635,7 +581,6 @@ async function seedActivities(
createdAt,
});
- // History on every deal: the calls, notes and emails that got it here.
for (const deal of deals) {
const dealContacts = contacts.filter((c) => c.companyId === deal.companyId);
@@ -651,8 +596,6 @@ async function seedActivities(
rows.push({
...base(deal.companyId, deal.ownerId, at),
type,
- // The company id is stamped above so this shows on the company
- // timeline as well as the deal's.
dealId: deal.id,
contactId: dealContacts.length > 0 ? pick(dealContacts).id : null,
subject:
@@ -668,7 +611,6 @@ async function seedActivities(
});
}
- // The stage change that landed it where it is.
rows.push({
...base(deal.companyId, deal.ownerId, daysFromNow(-integer(1, 20), 12)),
type: ActivityType.STAGE_CHANGE,
@@ -681,8 +623,6 @@ async function seedActivities(
});
}
- // Tasks: a spread of done, upcoming and overdue, so the dashboard has all
- // three to show on the first run.
for (const deal of deals) {
if (deal.closed) continue;
@@ -705,7 +645,6 @@ async function seedActivities(
}
}
- // A few notes that belong to the company rather than any one deal.
for (const company of companies) {
if (!chance(0.6)) continue;
rows.push({
diff --git a/packages/db/scripts/require-local-db.ts b/packages/db/scripts/require-local-db.ts
index ddba5cc3..e0c5bf0f 100644
--- a/packages/db/scripts/require-local-db.ts
+++ b/packages/db/scripts/require-local-db.ts
@@ -2,32 +2,6 @@ import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { parseEnv } from "@crm/env";
-/**
- * Refuses to run a destructive Prisma command against a database that is not
- * on this machine.
- *
- * The command that forced this: `prisma migrate dev` in `packages/db`, which
- * silently applied eleven migrations to the production Neon database. Nothing
- * was wrong with the command. The environment was wrong, and it was wrong
- * *invisibly* — `vercel env pull` writes production credentials into
- * `.env.local`, and `.env.local` beats `.env` by design, so every local
- * command quietly points at production until somebody notices.
- *
- * `migrate dev` is the sharp one: it can decide the database has drifted and
- * offer to reset it, which on a production database is the end of the
- * database. `db push` and `migrate reset` are the same class. `db:deploy` is
- * deliberately *not* guarded — pointing that at a remote database is the whole
- * point of it.
- *
- * **This resolves the URL the way Prisma will, not the way Bun would.** The
- * first version of this guard read `process.env.DATABASE_URL` and waved the
- * Neon case straight through, because Bun auto-loads the `.env` sitting in the
- * working directory before running a script, while Prisma's CLI is a Node
- * process that only sees `@crm/env/load`. The two disagreed, the guard checked
- * the wrong one, and a guard that is wrong in that direction is worse than no
- * guard at all.
- */
-
const LOCAL_HOSTS = new Set([
"localhost",
"127.0.0.1",
@@ -51,8 +25,6 @@ const host = hostOf(resolved.url);
if (LOCAL_HOSTS.has(host)) process.exit(0);
-// An explicit, per-invocation opt-in. A variable in a file would be back where
-// we started; this has to be typed on the line that does the damage.
if (process.env.ALLOW_REMOTE_DB === "1") {
console.warn(`\n ⚠ ${command} is running against ${host} — not local.\n`);
process.exit(0);
@@ -85,14 +57,6 @@ console.error(
process.exit(1);
-/**
- * The value Prisma will use, and where it came from.
- *
- * Same order as `loadRootEnv`: `.env`, then `.env.local` on top. A variable
- * already in the real environment beats both — but only if it did not come
- * from a file in the working directory, which is the case this exists to catch,
- * so the files are read first and win here.
- */
function resolveDatabaseUrl(): { url: string; from: string } | null {
const root = workspaceRoot();
@@ -102,9 +66,7 @@ function resolveDatabaseUrl(): { url: string; from: string } | null {
try {
const url = parseEnv(readFileSync(path, "utf8")).DATABASE_URL;
if (url) return { url, from: file };
- } catch {
- // Not there, or unreadable. Try the next one.
- }
+ } catch {}
}
}
@@ -114,7 +76,6 @@ function resolveDatabaseUrl(): { url: string; from: string } | null {
: null;
}
-/** The one directory with a `package.json` that declares workspaces. */
function workspaceRoot(): string | null {
let directory = process.cwd();
@@ -124,9 +85,7 @@ function workspaceRoot(): string | null {
readFileSync(join(directory, "package.json"), "utf8"),
) as { workspaces?: unknown };
if (manifest.workspaces) return directory;
- } catch {
- // No manifest here, or an unreadable one. Keep walking.
- }
+ } catch {}
const parent = dirname(directory);
if (parent === directory) return null;
diff --git a/packages/db/src/blob.ts b/packages/db/src/blob.ts
new file mode 100644
index 00000000..cbe5aa42
--- /dev/null
+++ b/packages/db/src/blob.ts
@@ -0,0 +1,92 @@
+import { createHash } from "node:crypto";
+import { isMirrored } from "./images";
+import { safeFetch } from "./safe-fetch";
+
+export { isMirrored, isOptimizable } from "./images";
+
+const MAX_BYTES = 3 * 1024 * 1024;
+const TIMEOUT_MS = 15_000;
+
+const ALLOWED: Record<string, string> = {
+ "image/jpeg": "jpg",
+ "image/png": "png",
+ "image/webp": "webp",
+ "image/gif": "gif",
+ "image/avif": "avif",
+ "image/svg+xml": "svg",
+ "image/x-icon": "ico",
+ "image/vnd.microsoft.icon": "ico",
+};
+
+export function blobEnabled(): boolean {
+ return Boolean(process.env.BLOB_READ_WRITE_TOKEN?.trim());
+}
+
+export async function mirror(
+ sourceUrl: string,
+ prefix: string,
+): Promise<string | null> {
+ if (!blobEnabled()) return null;
+ if (isMirrored(sourceUrl)) return sourceUrl;
+
+ try {
+ const result = await safeFetch(sourceUrl, { timeoutMs: TIMEOUT_MS });
+ if (!result?.response.ok) return null;
+
+ const { response } = result;
+ const type = response.headers.get("content-type")?.split(";")[0]?.trim();
+ const extension = type ? ALLOWED[type.toLowerCase()] : undefined;
+ if (!type || !extension) return null;
+
+ const bytes = await readCapped(response);
+ if (!bytes) return null;
+
+ const digest = createHash("sha256")
+ .update(bytes)
+ .digest("hex")
+ .slice(0, 12);
+
+ const { put } = await import("@vercel/blob");
+
+ const blob = await put(`${prefix}-${digest}.${extension}`, bytes, {
+ access: "public",
+ contentType: type,
+ addRandomSuffix: false,
+ allowOverwrite: true,
+ });
+
+ return blob.url;
+ } catch {
+ return null;
+ }
+}
+
+async function readCapped(response: Response): Promise<Buffer | null> {
+ const declared = Number(response.headers.get("content-length"));
+ if (Number.isFinite(declared) && declared > MAX_BYTES) {
+ await response.body?.cancel();
+ return null;
+ }
+
+ if (!response.body) return null;
+
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+
+ try {
+ while (size <= MAX_BYTES) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ size += value.byteLength;
+ chunks.push(value);
+ }
+ } catch {
+ return null;
+ } finally {
+ await reader.cancel().catch(() => {});
+ }
+
+ if (size === 0 || size > MAX_BYTES) return null;
+ return Buffer.concat(chunks);
+}
diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts
index 6963db19..6ae6ddce 100644
--- a/packages/db/src/client.ts
+++ b/packages/db/src/client.ts
@@ -1,5 +1,3 @@
-// First, and before anything reads `process.env`: every process that talks to
-// the database gets here, so this is where the repo-root `.env` is picked up.
import "@crm/env/load";
import { PrismaPg } from "@prisma/adapter-pg";
@@ -13,22 +11,15 @@ if (!connectionString) {
);
}
-/** A log line emitted by the Prisma engine, normalised for whichever sink is installed. */
export interface PrismaLogRecord {
level: Prisma.LogLevel;
message: string;
- /** The Prisma emitter, e.g. `quaint::connector::metrics`. */
target: string;
- /** Statement timing. Present on `query` records only. */
durationMs?: number;
}
export type PrismaLogSink = (record: PrismaLogRecord) => void;
-/**
- * Seeds, one-off scripts and the Next.js app have no application logger to hand,
- * so database problems still have to surface somewhere by default.
- */
const consoleSink: PrismaLogSink = ({ level, message, target, durationMs }) => {
const suffix = durationMs === undefined ? "" : ` (+${durationMs}ms)`;
const line = `[prisma:${level}] ${message}${suffix} [${target}]`;
@@ -44,21 +35,10 @@ const consoleSink: PrismaLogSink = ({ level, message, target, durationMs }) => {
let sink: PrismaLogSink = consoleSink;
-/**
- * Redirect Prisma engine logs. The API points this at the Nest logger so
- * database logs are formatted and correlated like every other log line.
- * Pass `null` to restore the console sink.
- */
export function setPrismaLogSink(next: PrismaLogSink | null): void {
sink = next ?? consoleSink;
}
-/**
- * Prisma logs every statement it runs when `query` is enabled, which buries
- * anything worth reading under a wall of `SELECT`s — so it is opt-in rather
- * than on in development. Bound parameters are dropped even when it is on:
- * they routinely carry session tokens and personal data.
- */
const logQueries = process.env.PRISMA_LOG_QUERIES === "true";
const logDefinitions: Prisma.LogDefinition[] = [
@@ -78,8 +58,6 @@ const createPrismaClient = () => {
log: logDefinitions,
});
- // Every level is subscribed; the ones missing from `logDefinitions` simply
- // never fire, so the engine does no work for logs nobody asked for.
client.$on("error", ({ message, target }) => {
sink({ level: "error", message, target });
});
diff --git a/packages/db/src/favicon.ts b/packages/db/src/favicon.ts
index a2e912a2..3aef0fb4 100644
--- a/packages/db/src/favicon.ts
+++ b/packages/db/src/favicon.ts
@@ -1,125 +1,16 @@
-import dns from "node:dns/promises";
-import net from "node:net";
+import {
+ isBlockedAddress,
+ resolvesToPublicHost,
+ safeFetch,
+} from "./safe-fetch";
+
+export { isBlockedAddress, resolvesToPublicHost };
const TIMEOUT_MS = 5_000;
const MAX_HTML_BYTES = 512_000;
-/**
- * A page can advertise as many `<link rel="icon">` tags as it likes, and each
- * one costs a HEAD request. Ten is more than any real site publishes and caps
- * a hostile one at eleven requests including the `/favicon.ico` fallback.
- */
const MAX_ICON_CANDIDATES = 10;
-/** Enough for the usual apex-to-www or http-to-https hop, and no further. */
-const MAX_REDIRECTS = 3;
-
-/**
- * Addresses that must never be fetched.
- *
- * The domain on a company is attacker-supplied — anyone who can create a
- * company picks it — and this code runs inside the API, which can reach things
- * the internet cannot: cloud metadata on 169.254.169.254, Postgres on the
- * private network, anything bound to loopback. A `<link rel="icon">` pointing
- * at one of those turns "resolve a favicon" into a request forgery primitive,
- * so every hop is checked rather than only the domain we started from.
- */
-export function isBlockedAddress(ip: string): boolean {
- const groups = ip.includes(":") ? expandIPv6(ip) : null;
-
- if (groups) {
- // An IPv4 address reachable through IPv6 is still that IPv4 address, and
- // the notation hides it: `::ffff:7f00:1` is loopback written in hex, and
- // a string comparison against "::ffff:127.0.0.1" never sees it. Both
- // mapped (`::ffff:0:0/96`) and compatible (`::/96`) forms carry the
- // address in the last 32 bits, so both are graded as IPv4.
- const marker = groups[5];
- if (
- groups.slice(0, 5).every((group) => group === 0) &&
- (marker === 0xffff || marker === 0)
- ) {
- const high = groups[6] ?? 0;
- return isBlockedIPv4(high >> 8, high & 0xff);
- }
-
- const first = groups[0] ?? 0;
- return (
- (first & 0xfe00) === 0xfc00 || // unique local, fc00::/7
- (first & 0xffc0) === 0xfe80 || // link-local, fe80::/10
- (first & 0xff00) === 0xff00 // multicast, ff00::/8
- );
- }
-
- if (net.isIPv4(ip)) {
- const [a = 0, b = 0] = ip.split(".").map(Number);
- return isBlockedIPv4(a, b);
- }
-
- // Neither notation parsed, so we cannot say it is safe.
- return true;
-}
-
-/** Every range this blocks is decided by the first two octets. */
-function isBlockedIPv4(a: number, b: number): boolean {
- return (
- a === 0 || // this network
- a === 10 || // private
- a === 127 || // loopback
- (a === 169 && b === 254) || // link-local, incl. cloud metadata
- (a === 172 && b >= 16 && b <= 31) || // private
- (a === 192 && b === 168) || // private
- (a === 100 && b >= 64 && b <= 127) || // carrier-grade NAT
- (a === 198 && (b === 18 || b === 19)) || // benchmarking
- a >= 224 // multicast and reserved
- );
-}
-
-/**
- * An IPv6 address as its eight 16-bit groups, or `null` if it is not one.
- *
- * Written out rather than compared as text because every abbreviation is a way
- * to write loopback that a prefix check misses: `::1`, `0:0:0:0:0:0:0:1`,
- * `::ffff:127.0.0.1` and `::ffff:7f00:1` are the same address.
- */
-function expandIPv6(ip: string): number[] | null {
- // A zone index (`fe80::1%eth0`) names an interface, not a different address.
- let text = (ip.split("%")[0] ?? "").toLowerCase();
-
- // A trailing dotted quad is the last two groups written in decimal.
- const embedded: number[] = [];
- const lastColon = text.lastIndexOf(":");
- const tail = text.slice(lastColon + 1);
- if (tail.includes(".")) {
- if (!net.isIPv4(tail)) return null;
- const [a = 0, b = 0, c = 0, d = 0] = tail.split(".").map(Number);
- embedded.push((a << 8) | b, (c << 8) | d);
- text = text.slice(0, lastColon + 1);
- }
-
- const [headText = "", runText, extra] = text.split("::");
- if (extra !== undefined) return null;
-
- const parse = (part: string) =>
- part
- .split(":")
- .filter((group) => group !== "")
- .map((group) =>
- /^[0-9a-f]{1,4}$/.test(group) ? Number.parseInt(group, 16) : Number.NaN,
- );
-
- const head = parse(headText);
- const run = runText === undefined ? [] : parse(runText);
- const missing = 8 - head.length - run.length - embedded.length;
- if (runText !== undefined && missing < 0) return null;
-
- const fill = runText === undefined ? [] : Array<number>(missing).fill(0);
- const groups = [...head, ...fill, ...run, ...embedded];
- if (groups.length !== 8 || groups.some((group) => Number.isNaN(group)))
- return null;
-
- return groups;
-}
-
const ICON_REL = /^(shortcut )?icon$|^apple-touch-icon(-precomposed)?$/i;
function iconsFromHtml(html: string, base: URL): string[] {
@@ -132,9 +23,6 @@ function iconsFromHtml(html: string, base: URL): string[] {
const href = /\bhref\s*=\s*["']?([^"'\s>]+)/i.exec(tag)?.[1]?.trim();
if (!href) continue;
- // "32x32" → 32. Unsized icons sort last rather than first: a declared
- // size is usually a real raster, and an undeclared one is often a 16px
- // .ico that looks like mud beside the artwork in the next row.
const sizes = /\bsizes\s*=\s*["']?(\d+)/i.exec(tag)?.[1];
try {
@@ -142,135 +30,14 @@ function iconsFromHtml(html: string, base: URL): string[] {
href: new URL(href, base).toString(),
size: Number(sizes ?? 0),
});
- } catch {
- // A malformed href is one skipped icon, not a failed resolve.
- }
+ } catch {}
}
return found.sort((a, b) => b.size - a.size).map((icon) => icon.href);
}
-/**
- * Whether every address a hostname resolves to is publicly routable.
- *
- * Checked before each request rather than once up front, because a redirect
- * can send us somewhere else entirely.
- *
- * This does not close the DNS-rebinding window: the name is resolved here and
- * again by `fetch`, and an attacker who runs the authority for their own
- * company domain can answer differently the second time. Closing it means
- * connecting to the address that was checked, and **that is not available in
- * this runtime** — the API runs on Bun, whose `node:http` client ignores both
- * a custom `lookup` and `createConnection`, and whose `fetch` has no
- * dispatcher. Verified, not assumed: pinning through `lookup` works under Node
- * and under Bun drops SNI, fails certificate validation against the bare
- * address, and then silently re-resolves the name. The alternative is an
- * HTTP/1.1 client written by hand over `tls.connect`, which is a larger risk
- * than the one it removes.
- *
- * What is left needs an authenticated colleague — `ALLOWED_SIGN_IN` is the
- * whole door — who also controls authoritative DNS and wins a race. The
- * practical attack, an icon link pointing straight at an internal host, is
- * blocked on every hop.
- */
-async function resolvesToPublicHost(hostname: string): Promise<boolean> {
- // A URL keeps the brackets on an IPv6 literal; `net.isIP` will not take them.
- const literal = hostname.replace(/^\[|\]$/g, "");
- if (net.isIP(literal)) return !isBlockedAddress(literal);
-
- // The lookup carries the same deadline as the request it precedes. An abort
- // signal on the fetch covers neither this nor the fetch's own resolution, so
- // without it a resolver hanging under a network partition holds a
- // fire-and-forget backfill open indefinitely rather than degrading to null.
- let timer: ReturnType<typeof setTimeout> | undefined;
- try {
- const addresses = await Promise.race([
- dns.lookup(hostname, { all: true }),
- new Promise<never>((_, reject) => {
- timer = setTimeout(
- () => reject(new Error(`${hostname} did not resolve in time`)),
- TIMEOUT_MS,
- );
- }),
- ]);
-
- return (
- addresses.length > 0 &&
- addresses.every((address) => !isBlockedAddress(address.address))
- );
- } catch {
- return false;
- } finally {
- clearTimeout(timer);
- }
-}
-
-/**
- * A fetch that refuses to leave the public internet.
- *
- * Redirects are followed by hand — `redirect: "follow"` would chase a `Location`
- * into the private network without ever showing it to us, which is exactly the
- * hop that needs checking.
- */
-async function request(
- url: string,
- method: "GET" | "HEAD" = "GET",
-): Promise<{ response: Response; url: URL } | null> {
- let target: URL;
- try {
- target = new URL(url);
- } catch {
- return null;
- }
-
- for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
- // Anything that is not plain HTTP can address things a browser would not:
- // file://, and the gopher/dict tricks that turn a fetcher into a client
- // for whatever is listening on an internal port.
- if (target.protocol !== "https:" && target.protocol !== "http:")
- return null;
- if (!(await resolvesToPublicHost(target.hostname))) return null;
-
- let response: Response;
- try {
- response = await fetch(target, {
- method,
- signal: AbortSignal.timeout(TIMEOUT_MS),
- redirect: "manual",
- // Some origins serve a different page, or none, to an unknown agent.
- headers: { "user-agent": "Mozilla/5.0 (compatible; CRM/1.0)" },
- });
- } catch {
- return null;
- }
-
- const location = response.headers.get("location");
- if (response.status >= 300 && response.status < 400 && location) {
- await response.body?.cancel();
- try {
- target = new URL(location, target);
- } catch {
- return null;
- }
- continue;
- }
-
- return { response, url: target };
- }
-
- return null;
-}
-
-/**
- * The page's HTML and the URL it ended up at, after redirects.
- *
- * Read a chunk at a time and cancelled at the cap, rather than `await
- * response.text()` and then slicing: slicing throws the excess away only after
- * the whole body is already in memory, so a hostile origin streaming gigabytes
- * would exhaust the API before the limit was ever applied.
- */
async function readPage(url: URL): Promise<{ body: string; url: URL } | null> {
- const result = await request(url.toString());
+ const result = await safeFetch(url.toString(), { timeoutMs: TIMEOUT_MS });
if (!result?.response.ok) return null;
const { response } = result;
@@ -301,15 +68,11 @@ async function readPage(url: URL): Promise<{ body: string; url: URL } | null> {
return { body, url: result.url };
}
-/**
- * Whether a URL actually serves an image.
- *
- * Checked because a great many sites answer `/favicon.ico` with a 200 and an
- * HTML error page, and storing that URL puts a broken image in every table row
- * — the one outcome worse than the placeholder it replaced.
- */
async function servesImage(url: string): Promise<boolean> {
- const result = await request(url, "HEAD");
+ const result = await safeFetch(url, {
+ method: "HEAD",
+ timeoutMs: TIMEOUT_MS,
+ });
if (!result?.response.ok) return false;
await result.response.body?.cancel();
@@ -318,12 +81,6 @@ async function servesImage(url: string): Promise<boolean> {
);
}
-/**
- * The best icon a domain advertises, or `null`.
- *
- * Never throws and never guesses: `null` is a real answer and the safe one,
- * because a company with no icon is the state we were already in.
- */
export async function resolveFavicon(
domain: string | null | undefined,
): Promise<string | null> {
@@ -333,21 +90,15 @@ export async function resolveFavicon(
const base = new URL(`https://${domain}`);
const page = await readPage(base);
- // Capped before the fallback is appended, so a page listing a thousand
- // icons cannot turn one company lookup into a thousand HEAD requests.
const candidates = page
? iconsFromHtml(page.body, page.url).slice(0, MAX_ICON_CANDIDATES)
: [];
- // Every site is entitled to this path whether it advertises it or not,
- // so it is the last candidate rather than a separate branch.
candidates.push(new URL("/favicon.ico", page?.url ?? base).toString());
for (const candidate of candidates) {
if (await servesImage(candidate)) return candidate;
}
- } catch {
- // A domain that does not parse is a null, like one that does not answer.
- }
+ } catch {}
return null;
}
diff --git a/packages/db/src/images.ts b/packages/db/src/images.ts
new file mode 100644
index 00000000..1352acc0
--- /dev/null
+++ b/packages/db/src/images.ts
@@ -0,0 +1,32 @@
+export const BLOB_HOST_SUFFIX = ".blob.vercel-storage.com";
+
+export const COMPANY_IMAGE_FIELDS = [
+ "logoUrl",
+ "logoDarkUrl",
+ "iconUrl",
+ "iconDarkUrl",
+] as const;
+
+export type CompanyImageField = (typeof COMPANY_IMAGE_FIELDS)[number];
+
+const OPTIMIZABLE = new Set(["jpg", "jpeg", "png", "webp", "avif", "gif"]);
+
+export function isMirrored(url: string | null | undefined): boolean {
+ if (!url) return false;
+ try {
+ return new URL(url).hostname.endsWith(BLOB_HOST_SUFFIX);
+ } catch {
+ return false;
+ }
+}
+
+export function isOptimizable(url: string | null | undefined): boolean {
+ if (!isMirrored(url) || !url) return false;
+
+ try {
+ const extension = new URL(url).pathname.split(".").pop()?.toLowerCase();
+ return extension !== undefined && OPTIMIZABLE.has(extension);
+ } catch {
+ return false;
+ }
+}
diff --git a/packages/db/src/json.ts b/packages/db/src/json.ts
index db20c0da..b65e04c0 100644
--- a/packages/db/src/json.ts
+++ b/packages/db/src/json.ts
@@ -1,24 +1,9 @@
-/**
- * The shapes inside our `Json` columns.
- *
- * Prisma types a `Json` column as `JsonValue`, which is honest and useless: the
- * column has a shape, three packages depend on it, and the alternative to
- * writing it down once is each of them casting to its own private idea of what
- * is in there. That is exactly how `looksLikeSameCompany` came to exist twice
- * and mean two different things.
- *
- * These live beside the schema because the schema is what guarantees them.
- */
-
-/** One observation behind a `ContactFact`. Weights live with the agent. */
export type FactEvidence = {
kind: string;
- /** What the source actually said, in a line a rep would understand. */
detail: string;
sourceUrl?: string;
};
-/** The structured lines under a `ContactBrief`'s narrative. */
export type ContactBriefSections = {
currentRole?: string;
tenure?: string;
diff --git a/packages/db/src/safe-fetch.ts b/packages/db/src/safe-fetch.ts
new file mode 100644
index 00000000..f575f73d
--- /dev/null
+++ b/packages/db/src/safe-fetch.ts
@@ -0,0 +1,172 @@
+import dns from "node:dns/promises";
+import net from "node:net";
+
+const MAX_REDIRECTS = 3;
+
+const DEFAULT_TIMEOUT_MS = 5_000;
+
+export function isBlockedAddress(ip: string): boolean {
+ const groups = ip.includes(":") ? expandIPv6(ip) : null;
+
+ if (groups) {
+ const marker = groups[5];
+ if (
+ groups.slice(0, 5).every((group) => group === 0) &&
+ (marker === 0xffff || marker === 0)
+ ) {
+ const high = groups[6] ?? 0;
+ return isBlockedIPv4(high >> 8, high & 0xff);
+ }
+
+ const first = groups[0] ?? 0;
+ return (
+ (first & 0xfe00) === 0xfc00 ||
+ (first & 0xffc0) === 0xfe80 ||
+ (first & 0xff00) === 0xff00
+ );
+ }
+
+ if (net.isIPv4(ip)) {
+ const [a = 0, b = 0] = ip.split(".").map(Number);
+ return isBlockedIPv4(a, b);
+ }
+
+ return true;
+}
+
+function isBlockedIPv4(a: number, b: number): boolean {
+ return (
+ a === 0 ||
+ a === 10 ||
+ a === 127 ||
+ (a === 169 && b === 254) ||
+ (a === 172 && b >= 16 && b <= 31) ||
+ (a === 192 && b === 168) ||
+ (a === 100 && b >= 64 && b <= 127) ||
+ (a === 198 && (b === 18 || b === 19)) ||
+ a >= 224
+ );
+}
+
+function expandIPv6(ip: string): number[] | null {
+ let text = (ip.split("%")[0] ?? "").toLowerCase();
+
+ const embedded: number[] = [];
+ const lastColon = text.lastIndexOf(":");
+ const tail = text.slice(lastColon + 1);
+ if (tail.includes(".")) {
+ if (!net.isIPv4(tail)) return null;
+ const [a = 0, b = 0, c = 0, d = 0] = tail.split(".").map(Number);
+ embedded.push((a << 8) | b, (c << 8) | d);
+ text = text.slice(0, lastColon + 1);
+ }
+
+ const [headText = "", runText, extra] = text.split("::");
+ if (extra !== undefined) return null;
+
+ const parse = (part: string) =>
+ part
+ .split(":")
+ .filter((group) => group !== "")
+ .map((group) =>
+ /^[0-9a-f]{1,4}$/.test(group) ? Number.parseInt(group, 16) : Number.NaN,
+ );
+
+ const head = parse(headText);
+ const run = runText === undefined ? [] : parse(runText);
+ const missing = 8 - head.length - run.length - embedded.length;
+ if (runText !== undefined && missing < 0) return null;
+
+ const fill = runText === undefined ? [] : Array<number>(missing).fill(0);
+ const groups = [...head, ...fill, ...run, ...embedded];
+ if (groups.length !== 8 || groups.some((group) => Number.isNaN(group)))
+ return null;
+
+ return groups;
+}
+
+export async function resolvesToPublicHost(
+ hostname: string,
+ timeoutMs: number = DEFAULT_TIMEOUT_MS,
+): Promise<boolean> {
+ const literal = hostname.replace(/^\[|\]$/g, "");
+ if (net.isIP(literal)) return !isBlockedAddress(literal);
+
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const addresses = await Promise.race([
+ dns.lookup(hostname, { all: true }),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error(`${hostname} did not resolve in time`)),
+ timeoutMs,
+ );
+ }),
+ ]);
+
+ return (
+ addresses.length > 0 &&
+ addresses.every((address) => !isBlockedAddress(address.address))
+ );
+ } catch {
+ return false;
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+export async function safeFetch(
+ url: string,
+ {
+ method = "GET",
+ timeoutMs = DEFAULT_TIMEOUT_MS,
+ headers,
+ }: {
+ method?: "GET" | "HEAD";
+ timeoutMs?: number;
+ headers?: Record<string, string>;
+ } = {},
+): Promise<{ response: Response; url: URL } | null> {
+ let target: URL;
+ try {
+ target = new URL(url);
+ } catch {
+ return null;
+ }
+
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
+ if (target.protocol !== "https:" && target.protocol !== "http:")
+ return null;
+ if (!(await resolvesToPublicHost(target.hostname, timeoutMs))) return null;
+
+ let response: Response;
+ try {
+ response = await fetch(target, {
+ method,
+ signal: AbortSignal.timeout(timeoutMs),
+ redirect: "manual",
+ headers: {
+ "user-agent": "Mozilla/5.0 (compatible; CRM/1.0)",
+ ...headers,
+ },
+ });
+ } catch {
+ return null;
+ }
+
+ const location = response.headers.get("location");
+ if (response.status >= 300 && response.status < 400 && location) {
+ await response.body?.cancel();
+ try {
+ target = new URL(location, target);
+ } catch {
+ return null;
+ }
+ continue;
+ }
+
+ return { response, url: target };
+ }
+
+ return null;
+}
diff --git a/packages/db/src/settings.ts b/packages/db/src/settings.ts
new file mode 100644
index 00000000..23b979a5
--- /dev/null
+++ b/packages/db/src/settings.ts
@@ -0,0 +1,48 @@
+import type { Db } from "./client";
+
+export const SETTINGS_ID = "app";
+
+export const DEFAULT_AGENT_MODEL = {
+ id: "zai/glm-5.2-fast",
+ contextWindowTokens: 1_000_000,
+} as const;
+
+export interface AgentModelSetting {
+ id: string;
+ contextWindowTokens: number;
+ isDefault: boolean;
+}
+
+export async function readAgentModel(db: Db): Promise<AgentModelSetting> {
+ const row = await db.appSetting.findUnique({
+ where: { id: SETTINGS_ID },
+ select: { agentModelId: true, agentModelContextWindow: true },
+ });
+
+ if (!row?.agentModelId) {
+ return { ...DEFAULT_AGENT_MODEL, isDefault: true };
+ }
+
+ return {
+ id: row.agentModelId,
+ contextWindowTokens:
+ row.agentModelContextWindow ?? DEFAULT_AGENT_MODEL.contextWindowTokens,
+ isDefault: false,
+ };
+}
+
+export async function writeAgentModel(
+ db: Db,
+ model: { id: string; contextWindowTokens: number } | null,
+): Promise<void> {
+ const fields = {
+ agentModelId: model?.id ?? null,
+ agentModelContextWindow: model?.contextWindowTokens ?? null,
+ };
+
+ await db.appSetting.upsert({
+ where: { id: SETTINGS_ID },
+ create: { id: SETTINGS_ID, ...fields },
+ update: fields,
+ });
+}
diff --git a/packages/db/test/favicon.spec.ts b/packages/db/test/favicon.spec.ts
index 91fb3d77..4b5c772c 100644
--- a/packages/db/test/favicon.spec.ts
+++ b/packages/db/test/favicon.spec.ts
@@ -1,13 +1,6 @@
import { describe, expect, it } from "bun:test";
import { isBlockedAddress } from "../src/favicon";
-/**
- * The company domain is attacker-supplied, so this filter is the only thing
- * between "resolve a favicon" and a request to cloud metadata. The cases below
- * are the notations a filter written against `127.0.0.1` misses — the first
- * version of this one compared strings and let `::ffff:7f00:1` through, which
- * is loopback with the last four octets written in hex.
- */
describe("isBlockedAddress", () => {
it("blocks loopback however it is written", () => {
for (const ip of [
diff --git a/packages/db/test/images.spec.ts b/packages/db/test/images.spec.ts
new file mode 100644
index 00000000..5eab842f
--- /dev/null
+++ b/packages/db/test/images.spec.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "bun:test";
+import { COMPANY_IMAGE_FIELDS, isMirrored, isOptimizable } from "../src/images";
+
+const OURS = "https://abc123.public.blob.vercel-storage.com";
+
+describe("isMirrored", () => {
+ it("recognises our own store, so a re-run does not re-upload", () => {
+ expect(isMirrored(`${OURS}/contacts/c1-9f8e.jpg`)).toBe(true);
+ });
+
+ it("does not recognise somebody else's CDN", () => {
+ expect(isMirrored("https://media.licdn.com/dms/image/x.jpg")).toBe(false);
+ expect(isMirrored("https://lh3.googleusercontent.com/a/x=s96-c")).toBe(
+ false,
+ );
+ });
+
+ it("is not fooled by a lookalike host", () => {
+ expect(
+ isMirrored("https://evil.com/public.blob.vercel-storage.com/x.jpg"),
+ ).toBe(false);
+ expect(isMirrored("https://blob.vercel-storage.com.evil.com/x.jpg")).toBe(
+ false,
+ );
+ });
+
+ it("treats nothing and nonsense as not ours", () => {
+ expect(isMirrored(null)).toBe(false);
+ expect(isMirrored("")).toBe(false);
+ expect(isMirrored("not a url")).toBe(false);
+ });
+});
+
+describe("isOptimizable", () => {
+ it("passes a raster we minted", () => {
+ for (const extension of ["jpg", "jpeg", "png", "webp", "avif", "gif"]) {
+ expect(isOptimizable(`${OURS}/companies/c1/icon-9f8e.${extension}`)).toBe(
+ true,
+ );
+ }
+ });
+
+ it("refuses an SVG even though it is ours", () => {
+ expect(isOptimizable(`${OURS}/companies/c1/logoUrl-9f8e.svg`)).toBe(false);
+ });
+
+ it("refuses an ico, which the optimizer cannot serve", () => {
+ expect(isOptimizable(`${OURS}/companies/c1/icon-9f8e.ico`)).toBe(false);
+ });
+
+ it("refuses anything we did not mint, whatever its extension", () => {
+ expect(isOptimizable("https://cdn.context.dev/logo.png")).toBe(false);
+ expect(isOptimizable("https://lh3.googleusercontent.com/a/x.jpg")).toBe(
+ false,
+ );
+ });
+
+ it("refuses a URL with no extension to read", () => {
+ expect(isOptimizable(`${OURS}/companies/c1/icon`)).toBe(false);
+ expect(isOptimizable(null)).toBe(false);
+ });
+});
+
+describe("COMPANY_IMAGE_FIELDS", () => {
+ it("names every artwork column and nothing else", () => {
+ expect([...COMPANY_IMAGE_FIELDS]).toEqual([
+ "logoUrl",
+ "logoDarkUrl",
+ "iconUrl",
+ "iconDarkUrl",
+ ]);
+ });
+});
diff --git a/packages/db/turbo.json b/packages/db/turbo.json
index b315e5bd..2037c345 100644
--- a/packages/db/turbo.json
+++ b/packages/db/turbo.json
@@ -38,7 +38,7 @@
},
"db:seed": {
"cache": false,
- "passThroughEnv": ["DATABASE_URL"]
+ "passThroughEnv": ["BLOB_READ_WRITE_TOKEN", "DATABASE_URL"]
},
"db:studio": {
"cache": false,
diff --git a/packages/env/src/index.ts b/packages/env/src/index.ts
index 215a470c..56cbbfbe 100644
--- a/packages/env/src/index.ts
+++ b/packages/env/src/index.ts
@@ -1,42 +1,10 @@
import { existsSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
-/**
- * One `.env`, at the root of the repo.
- *
- * Every process here — the API, the Next.js app, the agent, the Prisma CLI —
- * needs an overlapping subset of the same handful of values, and the secret and
- * the database URL have to be *identical* across them or the session cookie one
- * writes will not verify in the next. Five files that must agree is five files
- * that can disagree, and the failure is a silent redirect loop rather than an
- * error.
- *
- * So there is one file and it is read from the workspace root, whichever
- * directory the process happens to start in.
- *
- * **The real environment always wins.** A value already present in
- * `process.env` is never overwritten, so a platform's own configuration —
- * Vercel, Docker, systemd, CI — takes precedence and the file is purely a
- * local-development convenience. Nothing here is required: with no `.env` at
- * all this is a no-op, and the individual consumers report what they are
- * missing.
- */
-
-/** Loaded in order, so `.env.local` overrides `.env`. Neither is required. */
const FILES = [".env", ".env.local"] as const;
let loaded = false;
-/**
- * Walks up from `start` looking for the workspace root.
- *
- * The marker is a `package.json` that declares `workspaces` — the one thing
- * only the root has. Neither of the obvious alternatives works: every package
- * has a `package.json`, and several have their own `turbo.json`, so both stop
- * at whichever app the process started in and quietly read the wrong file (or
- * no file, which is worse — the failure is a missing variable reported three
- * frames away from the reason).
- */
function findWorkspaceRoot(start: string): string | null {
let directory = resolve(start);
@@ -62,19 +30,10 @@ function isWorkspaceRoot(directory: string): boolean {
parsed.workspaces !== undefined
);
} catch {
- // A malformed package.json is somebody else's problem to report.
return false;
}
}
-/**
- * A deliberately small `.env` parser.
- *
- * Handles what these files actually contain — `KEY=value`, optional quotes,
- * `#` comments, blank lines, an optional `export` prefix — and nothing else.
- * A dependency would be a supply-chain surface for thirty lines of string
- * handling that runs before anything else in the process.
- */
export function parseEnv(source: string): Record<string, string> {
const values: Record<string, string> = {};
@@ -98,15 +57,10 @@ export function parseEnv(source: string): Record<string, string> {
value.length > 1
) {
value = value.slice(1, -1);
- // Escapes are only meaningful inside double quotes, matching every
- // other dotenv implementation — a Windows path in single quotes should
- // survive intact.
if (quote === '"') {
value = value.replace(/\\n/g, "\n").replace(/\\r/g, "\r");
}
} else {
- // An unquoted value runs to the first ` #`, so `PORT=3001 # the api`
- // is a port and not a sentence.
const comment = value.indexOf(" #");
if (comment !== -1) value = value.slice(0, comment).trim();
}
@@ -117,11 +71,6 @@ export function parseEnv(source: string): Record<string, string> {
return values;
}
-/**
- * Reads the workspace-root `.env` files into `process.env`.
- *
- * Idempotent and safe to call from anywhere; the first call does the work.
- */
export function loadRootEnv(): void {
if (loaded) return;
loaded = true;
@@ -129,10 +78,6 @@ export function loadRootEnv(): void {
const root = findWorkspaceRoot(process.cwd());
if (!root) return;
- // Merged across files first, so `.env.local` beats `.env`. Applying each
- // file straight to `process.env` would let `.env` win instead: it is read
- // first, and the "never overwrite" rule below cannot tell a value set by an
- // earlier file from one set by the platform.
const merged: Record<string, string> = {};
for (const file of FILES) {
@@ -141,10 +86,7 @@ export function loadRootEnv(): void {
try {
Object.assign(merged, parseEnv(readFileSync(path, "utf8")));
- } catch {
- // An unreadable .env is not worth crashing a process over — the
- // consumer that needs a missing value will say so by name.
- }
+ } catch {}
}
for (const [key, value] of Object.entries(merged)) {
diff --git a/packages/env/src/load.ts b/packages/env/src/load.ts
index 90fc853f..322f6b9e 100644
--- a/packages/env/src/load.ts
+++ b/packages/env/src/load.ts
@@ -1,12 +1,3 @@
import { loadRootEnv } from "./index";
-/**
- * Side-effect entry point: `import "@crm/env/load";`.
- *
- * ES module imports are hoisted and evaluated before any statement in the
- * importing file, so a module that reads `process.env` at import time — as
- * `@crm/auth`'s config and `@crm/db`'s client both do — cannot load the file
- * itself from its own top-level code and still be sure it ran first. Importing
- * this module can only run before them.
- */
loadRootEnv();
diff --git a/packages/env/test/parse.spec.ts b/packages/env/test/parse.spec.ts
index 46808731..b8fcf6b8 100644
--- a/packages/env/test/parse.spec.ts
+++ b/packages/env/test/parse.spec.ts
@@ -1,11 +1,6 @@
import { describe, expect, it } from "bun:test";
import { parseEnv } from "../src/index";
-/**
- * The parser reads the one file every self-hoster edits by hand, so the cases
- * below are the ways people actually write these files rather than the ways a
- * spec says they should.
- */
describe("parseEnv", () => {
it("reads plain and quoted values", () => {
expect(
@@ -28,8 +23,6 @@ describe("parseEnv", () => {
});
it("keeps a # that is part of the value", () => {
- // Passwords contain these, and a generated secret routinely does. Only a
- // space-hash pair starts a trailing comment.
expect(parseEnv("PASSWORD=pa#ssword\nPORT=3001 # the api")).toEqual({
PASSWORD: "pa#ssword",
PORT: "3001",
@@ -41,9 +34,6 @@ describe("parseEnv", () => {
});
it("keeps base64 padding, which openssl rand emits", () => {
- // `openssl rand -base64 32` ends in `=` about a quarter of the time, and
- // a parser that split on every `=` would silently truncate the secret —
- // producing a session cookie the other process cannot verify.
const secret = "6oXI/PGPx8OGGiVz7zW2EODV6LcKmtyALiR+RvG2yc8=";
expect(parseEnv(`BETTER_AUTH_SECRET="${secret}"`)).toEqual({
BETTER_AUTH_SECRET: secret,
diff --git a/packages/env/test/root.spec.ts b/packages/env/test/root.spec.ts
index f22d3d4e..adf300b8 100644
--- a/packages/env/test/root.spec.ts
+++ b/packages/env/test/root.spec.ts
@@ -2,18 +2,6 @@ import { describe, expect, it } from "bun:test";
import { existsSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
-/**
- * Finding the workspace root is the part of this package that can fail
- * silently. If it stops one directory too early it reads a file that exists
- * but holds a different set of variables, and the symptom appears somewhere
- * else entirely — a missing `ALLOWED_SIGN_IN` reported by Nest's validator,
- * three frames from the reason.
- *
- * The first `turbo.json` walking up was exactly that bug: `apps/agent` and
- * `apps/api` have their own, so the API resolved its root to `apps/api`.
- */
-
-/** The same walk as `loadRootEnv`, kept here so the property is testable. */
function findRoot(start: string): string | null {
let directory = resolve(start);
@@ -30,9 +18,7 @@ function findRoot(start: string): string | null {
) {
return directory;
}
- } catch {
- // fall through
- }
+ } catch {}
}
const parent = dirname(directory);
@@ -49,7 +35,6 @@ describe("finding the workspace root", () => {
});
it("finds it from a package that has its own turbo.json", () => {
- // The regression. Both of these ship a turbo.json.
for (const app of ["apps/api", "apps/agent"]) {
expect(findRoot(join(repoRoot, app))).toBe(repoRoot);
}
@@ -64,7 +49,6 @@ describe("finding the workspace root", () => {
});
it("only matches a manifest that declares workspaces", () => {
- // Every package has a package.json; exactly one has `workspaces`.
const manifest: unknown = JSON.parse(
readFileSync(join(repoRoot, "apps", "api", "package.json"), "utf8"),
);
@@ -92,8 +76,6 @@ describe("the committed .env.example", () => {
});
it("ships no secret of its own", () => {
- // A committed example with a real-looking secret in it is a secret people
- // paste into production.
for (const line of example.split("\n")) {
if (line.startsWith("#") || !line.includes("=")) continue;
const value = line.slice(line.indexOf("=") + 1).trim();
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 8b3bc7e4..3a65efce 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -18,6 +18,7 @@
},
"dependencies": {
"@carbon/icons-react": "^11.82.0",
+ "@crm/db": "workspace:*",
"@shadcn/react": "^0.2.1",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -36,6 +37,7 @@
"vaul": "^1.1.2"
},
"peerDependencies": {
+ "next": "^16.0.0",
"react": "^19.2.0",
"react-dom": "^19.2.0"
},
@@ -45,6 +47,7 @@
"@types/node": "^24.10.1",
"@types/react": "^19.2.18",
"@types/react-dom": "^19",
+ "next": "16.2.12",
"react": "19.2.4",
"react-dom": "19.2.4",
"shadcn": "^4.16.1",
diff --git a/packages/ui/postcss.config.mjs b/packages/ui/postcss.config.mjs
index 6ba14df9..c42f31ca 100644
--- a/packages/ui/postcss.config.mjs
+++ b/packages/ui/postcss.config.mjs
@@ -1,4 +1,3 @@
-/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
"@tailwindcss/postcss": {},
diff --git a/packages/ui/src/components/accordion.tsx b/packages/ui/src/components/accordion.tsx
index d99f4871..31d44c3d 100644
--- a/packages/ui/src/components/accordion.tsx
+++ b/packages/ui/src/components/accordion.tsx
@@ -36,10 +36,6 @@ const accordionTriggerVariants = cva(
"group/accordion-trigger relative flex items-start rounded-md border border-transparent text-left outline-none transition-all focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:after:border-ring disabled:pointer-events-none disabled:opacity-50 **:data-[slot=accordion-trigger-icon]:text-muted-foreground",
{
variants: {
- // `subtle` is the one that belongs inside a record sheet: a line of
- // small print that happens to open, rather than a heading with a rule
- // under it. The panel is `text-xs` throughout and a `text-sm` trigger
- // in the middle of it reads as a different component.
variant: {
default:
"flex-1 justify-between py-2.5 font-medium text-sm hover:underline **:data-[slot=accordion-trigger-icon]:ml-auto **:data-[slot=accordion-trigger-icon]:size-4",
diff --git a/packages/ui/src/components/alert-dialog.tsx b/packages/ui/src/components/alert-dialog.tsx
new file mode 100644
index 00000000..53b4710e
--- /dev/null
+++ b/packages/ui/src/components/alert-dialog.tsx
@@ -0,0 +1,168 @@
+"use client";
+
+import { buttonVariants } from "@crm/ui/components/button";
+import { cn } from "@crm/ui/lib/utils";
+import type { VariantProps } from "class-variance-authority";
+import { AlertDialog as AlertDialogPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function AlertDialog({
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
+ return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />;
+}
+
+function AlertDialogTrigger({
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
+ return (
+ <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
+ );
+}
+
+function AlertDialogPortal({
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
+ return (
+ <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
+ );
+}
+
+function AlertDialogOverlay({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
+ return (
+ <AlertDialogPrimitive.Overlay
+ data-slot="alert-dialog-overlay"
+ className={cn(
+ "fixed inset-0 isolate z-50 bg-overlay duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AlertDialogContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
+ return (
+ <AlertDialogPortal>
+ <AlertDialogOverlay />
+ <AlertDialogPrimitive.Content
+ data-slot="alert-dialog-content"
+ className={cn(
+ "fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-lg bg-popover p-4 text-xs/relaxed text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
+ className,
+ )}
+ {...props}
+ />
+ </AlertDialogPortal>
+ );
+}
+
+function AlertDialogHeader({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="alert-dialog-header"
+ className={cn("flex flex-col gap-1 text-left", className)}
+ {...props}
+ />
+ );
+}
+
+function AlertDialogFooter({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="alert-dialog-footer"
+ className={cn(
+ "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AlertDialogTitle({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
+ return (
+ <AlertDialogPrimitive.Title
+ data-slot="alert-dialog-title"
+ className={cn("font-heading text-sm font-medium", className)}
+ {...props}
+ />
+ );
+}
+
+function AlertDialogDescription({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
+ return (
+ <AlertDialogPrimitive.Description
+ data-slot="alert-dialog-description"
+ className={cn(
+ "text-xs/relaxed text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AlertDialogAction({
+ className,
+ variant,
+ size,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Action> &
+ VariantProps<typeof buttonVariants>) {
+ return (
+ <AlertDialogPrimitive.Action
+ data-slot="alert-dialog-action"
+ className={cn(buttonVariants({ variant, size }), className)}
+ {...props}
+ />
+ );
+}
+
+function AlertDialogCancel({
+ className,
+ variant = "outline",
+ size,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
+ VariantProps<typeof buttonVariants>) {
+ return (
+ <AlertDialogPrimitive.Cancel
+ data-slot="alert-dialog-cancel"
+ className={cn(buttonVariants({ variant, size }), className)}
+ {...props}
+ />
+ );
+}
+
+export {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogOverlay,
+ AlertDialogPortal,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+};
diff --git a/packages/ui/src/components/alert.tsx b/packages/ui/src/components/alert.tsx
index 983f1fe8..9344820b 100644
--- a/packages/ui/src/components/alert.tsx
+++ b/packages/ui/src/components/alert.tsx
@@ -8,13 +8,6 @@ const alertVariants = cva(
variants: {
variant: {
default: "bg-card text-card-foreground",
- /*
- * Neutral, not red. A failure panel is already announced by its
- * heading and its position on the page; painting the whole surface
- * red makes a recoverable problem — an API that needs enabling —
- * read like data loss. The grey keeps the alert legible and lets the
- * one action inside it be the loudest thing in the box.
- */
destructive:
"bg-muted text-foreground *:[svg]:text-current *:data-[slot=alert-description]:text-foreground/80",
},
@@ -32,15 +25,6 @@ function Alert({
...props
}: React.ComponentProps<"div"> &
VariantProps<typeof alertVariants> & {
- /**
- * Bump this to make the alert re-assert itself.
- *
- * A counter rather than a boolean, and it is the `key`: an animation only
- * replays when the node is new, so a flag flipping back to `true` a second
- * time would do nothing at all. Every increment remounts the alert and the
- * animation runs again — which is the whole point, since the case this
- * exists for is the *same* problem reported twice.
- */
attention?: number;
}) {
return (
diff --git a/packages/ui/src/components/attendee-list.tsx b/packages/ui/src/components/attendee-list.tsx
index 2dc89825..2b004553 100644
--- a/packages/ui/src/components/attendee-list.tsx
+++ b/packages/ui/src/components/attendee-list.tsx
@@ -1,4 +1,4 @@
-import { Avatar, AvatarFallback } from "@crm/ui/components/avatar";
+import { PersonAvatar } from "@crm/ui/components/person-avatar";
import {
type StatusTone,
StatusIndicator,
@@ -15,17 +15,11 @@ export type Attendee = {
id: string;
email: string;
name: string | null;
- /** Google's own values: needsAction | declined | tentative | accepted. */
responseStatus: string | null;
isOrganizer: boolean;
+ imageUrl?: string | null;
};
-/**
- * Whether someone actually turned up to the invitation.
- *
- * Mapped onto the shared tones rather than to colours directly, so a declined
- * attendee reads the same red as a lost deal.
- */
const RESPONSE_TONE: Record<string, StatusTone> = {
accepted: "success",
declined: "error",
@@ -40,18 +34,6 @@ const RESPONSE_LABEL: Record<string, string> = {
needsAction: "No reply",
};
-/**
- * The people on a meeting, up to `max`, then a count. The full list is in the
- * tooltip because a nine-person kickoff should not push the timeline entry to
- * three lines.
- *
- * Side by side rather than the usual overlapping stack, and that is a fix, not
- * a preference. A stack needs a ring the colour of whatever is behind it to cut
- * each disc from the next — so the component had to name a surface, it named
- * `background`, and it is only ever rendered on `popover`, which drew a dark
- * halo round every face. The overlap also ate the second initial: two letters
- * in a 24px disc, eight of those pixels underneath the next avatar.
- */
function AttendeeList({
attendees,
max = 5,
@@ -76,9 +58,16 @@ function AttendeeList({
{shown.map((attendee) => (
<Tooltip key={attendee.id}>
<TooltipTrigger asChild>
- <Avatar size="sm">
- <AvatarFallback>{initialsOf(attendee)}</AvatarFallback>
- </Avatar>
+ <PersonAvatar
+ src={attendee.imageUrl}
+ name={
+ attendee.name?.trim() && !attendee.name.includes("@")
+ ? attendee.name
+ : null
+ }
+ email={attendee.email}
+ size="sm"
+ />
</TooltipTrigger>
<TooltipContent>
<span className="flex items-center gap-2">
@@ -103,18 +92,4 @@ function AttendeeList({
);
}
-function initialsOf(attendee: Attendee): string {
- const source =
- attendee.name?.trim() && !attendee.name.includes("@")
- ? attendee.name
- : attendee.email;
-
- return source
- .split(/[\s._-]+/)
- .filter(Boolean)
- .slice(0, 2)
- .map((word) => word.charAt(0).toUpperCase())
- .join("");
-}
-
export { AttendeeList };
diff --git a/packages/ui/src/components/button.tsx b/packages/ui/src/components/button.tsx
index 89969370..430d1bf6 100644
--- a/packages/ui/src/components/button.tsx
+++ b/packages/ui/src/components/button.tsx
@@ -8,38 +8,16 @@ const buttonVariants = cva(
{
variants: {
variant: {
- /*
- * Hover and press darken the fill rather than fading it. `/80`
- * let the page show through, so a primary button sat on a grey
- * row and a white one hovered to two different colours.
- */
default:
"bg-primary text-primary-foreground shadow-2xs hover:bg-[color-mix(in_oklch,var(--primary),black_12%)] active:bg-[color-mix(in_oklch,var(--primary),black_22%)] active:shadow-none",
- /*
- * A solid fill in dark, not `bg-input/30`. A translucent control
- * takes the colour of whatever is behind it, so the same filter
- * button was one shade on the page and another on a panel.
- */
outline:
"border-border bg-background shadow-2xs hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:bg-muted dark:hover:bg-accent",
secondary:
"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
ghost:
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
- /*
- * A solid fill, not a tint. Fills are reserved for the two ends
- * of the spectrum — the action you want and the one you cannot
- * undo — so destructive has to be unmistakable at a glance.
- */
destructive:
"bg-destructive text-destructive-foreground shadow-2xs hover:bg-[color-mix(in_oklch,var(--destructive),black_12%)] active:bg-[color-mix(in_oklch,var(--destructive),black_22%)] active:shadow-none focus-visible:ring-destructive/50",
- /*
- * The inverted chip: the page's own text colour as a fill, and the
- * page's background as the label. It is the highest-contrast button
- * available in either theme without spending green or red — white on
- * dark, near-black on light — so it carries the one action inside a
- * neutral panel that has no colour of its own to lean on.
- */
contrast:
"bg-foreground text-background shadow-2xs hover:bg-foreground/90 active:bg-foreground/80 active:shadow-none",
link: "text-primary underline-offset-4 hover:underline",
diff --git a/packages/ui/src/components/card-table.tsx b/packages/ui/src/components/card-table.tsx
index 50199c8a..d31c1d61 100644
--- a/packages/ui/src/components/card-table.tsx
+++ b/packages/ui/src/components/card-table.tsx
@@ -17,8 +17,6 @@ export function CardTable({
}) {
return (
<SimpleTable
- // Gutters rather than flush: the table now draws its own border, and
- // text sitting hard against it reads as a clipping bug.
className="min-w-[48rem] table-fixed [&_td:first-child]:pl-4 [&_td:last-child]:pr-4 [&_th:first-child]:pl-4 [&_th:last-child]:pr-4"
columns={columns}
>
diff --git a/packages/ui/src/components/card.tsx b/packages/ui/src/components/card.tsx
index d07e73cf..6e7c4fd8 100644
--- a/packages/ui/src/components/card.tsx
+++ b/packages/ui/src/components/card.tsx
@@ -73,15 +73,6 @@ function CardContent({ className, ...props }: React.ComponentProps<"div">) {
);
}
-/**
- * A card body pinned to one height, with its rows scrolling inside.
- *
- * Two lists side by side on a dashboard hold different numbers of rows, so
- * left to themselves one panel ends level with nothing and the page below
- * jumps whenever the shorter list gains a row. A set height fixes both the
- * pair and the page. Pair with `SimpleTable variant="panel"` so the column
- * header stays pinned while the rows move under it.
- */
function CardPanel({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
@@ -95,10 +86,6 @@ function CardPanel({ className, ...props }: React.ComponentProps<"div">) {
);
}
-/**
- * The empty state for a {@link CardPanel}: centred in the height the panel
- * holds open, rather than a line of text stranded at the top of it.
- */
function CardPanelEmpty({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
diff --git a/packages/ui/src/components/chart.tsx b/packages/ui/src/components/chart.tsx
index 1e82c344..3092964f 100644
--- a/packages/ui/src/components/chart.tsx
+++ b/packages/ui/src/components/chart.tsx
@@ -136,11 +136,6 @@ function ChartTooltipContent({
indicator?: "line" | "dot" | "dashed";
nameKey?: string;
labelKey?: string;
- /**
- * Formats the value only, keeping the indicator and label markup.
- * `formatter` replaces the whole row, which is more than a chart
- * plotting money needs.
- */
valueFormatter?: (value: number | string) => React.ReactNode;
} & Omit<
RechartsPrimitive.DefaultTooltipContentProps<
diff --git a/packages/ui/src/components/dashboard-chart.tsx b/packages/ui/src/components/dashboard-chart.tsx
index 37d3d99b..85b8a644 100644
--- a/packages/ui/src/components/dashboard-chart.tsx
+++ b/packages/ui/src/components/dashboard-chart.tsx
@@ -28,27 +28,15 @@ import {
type Datum = Record<string, number | string | null>;
type CartesianProps = {
- /** Rows to plot, already shaped for the chart. */
data: Datum[];
- /** Maps each series key to a label + color (use `color: "var(--chart-N)"`). */
config: ChartConfig;
- /** The category (x-axis) key. */
xKey: string;
- /** Which keys in `config` to draw as series. Defaults to all config keys. */
series?: string[];
className?: string;
- /** Plot height in px. Default 200. */
height?: number;
- /** Show the x-axis tick labels. Default true. */
showXAxis?: boolean;
- /** Show a legend (useful for multi-series). Default false. */
showLegend?: boolean;
- /** Format an x-axis tick (e.g. shorten a date). */
formatX?: (value: string) => string;
- /**
- * Format a plotted value in the tooltip. Pass this whenever the series is
- * money or a rate — a raw `1250000` in the tooltip tells a reader nothing.
- */
formatValue?: (value: number | string) => string;
};
@@ -78,12 +66,6 @@ const X_AXIS_PROPS = {
tickMargin: 12,
} as const;
-/**
- * With a full-bleed plot (zero horizontal margin) the first and last category
- * labels sit at the very edges, where a centered label clips against the card.
- * Anchor the edge labels inward (start / end) and center the rest. Recharts
- * clones this element per tick, injecting the computed coordinates + index.
- */
function EdgeTick({
x,
y,
@@ -333,10 +315,6 @@ function AreaTrend({
);
}
-/**
- * Grouped/stacked bar chart for discrete buckets (per-month counts, breakdowns).
- * Same prop shape as {@link AreaTrend} for drop-in consistency.
- */
function BarTrend({
data,
config,
@@ -461,11 +439,6 @@ function BarStat({
);
}
-/**
- * Donut chart with an optional bold value in the middle and a faint track
- * behind the data — ideal for a single-metric breakdown (members by role,
- * findings by severity, plan usage).
- */
function DonutStat({
data,
className,
@@ -507,7 +480,6 @@ function DonutStat({
/>
}
/>
- {/* Faint track so a partial ring still reads as a full circle. */}
<Pie
data={[{ value: 1 }]}
dataKey="value"
diff --git a/packages/ui/src/components/dashboard.tsx b/packages/ui/src/components/dashboard.tsx
index c5ee165a..48eac58a 100644
--- a/packages/ui/src/components/dashboard.tsx
+++ b/packages/ui/src/components/dashboard.tsx
@@ -2,24 +2,6 @@ import { Skeleton } from "@crm/ui/components/skeleton";
import { cn } from "@crm/ui/lib/utils";
import type * as React from "react";
-/**
- * Reusable, server-safe dashboard layout primitives. They establish their own
- * container-query context so the same grids reflow correctly regardless of
- * where the dashboard is mounted — sidebar open or not.
- *
- * Compose them as:
- * <DashboardSection title="Overview">
- * <StatGroup>{stats}</StatGroup>
- * <DashboardRow>{hero}{aside}</DashboardRow>
- * </DashboardSection>
- */
-
-/**
- * An elevated KPI strip: one bordered surface holding several {@link StatCard}s
- * separated by hairline dividers (stacked + horizontal on narrow widths, a
- * single divided row on wide). This is the premium alternative to a row of
- * standalone boxes — see the surfaces guideline.
- */
function StatGroup({
className,
children,
@@ -66,11 +48,6 @@ function DashboardGrid({
);
}
-/**
- * A 2-up content row that collapses to a single column on narrow widths.
- * By default the first child takes ~2/3 (the hero chart) and the second ~1/3
- * (an aside). Pass `split="even"` for a 1:1 layout.
- */
function DashboardRow({
className,
split = "hero",
@@ -93,12 +70,6 @@ function DashboardRow({
);
}
-/**
- * A bordered, subtly elevated surface for a single chart, with an optional
- * header (title / description / action) and footer. The body stretches so
- * sibling cards in a {@link DashboardRow} stay the same height. Pair with the
- * client chart wrappers in `dashboard-chart.tsx`.
- */
function ChartCard({
className,
title,
@@ -205,11 +176,6 @@ function DashboardSection({
);
}
-/**
- * A layout-matched loading state for the default dashboard composition
- * (KPI strip + hero/aside chart row). Use as a `<Suspense>` fallback so the
- * page paints instantly while server data streams in.
- */
function DashboardSkeleton({
stats = 4,
className,
diff --git a/packages/ui/src/components/data-table.tsx b/packages/ui/src/components/data-table.tsx
index 5dc496bb..092b3063 100644
--- a/packages/ui/src/components/data-table.tsx
+++ b/packages/ui/src/components/data-table.tsx
@@ -45,7 +45,6 @@ export type DataTableColumn<TRow> = {
id: string;
header: ReactNode;
cell: (row: TRow) => ReactNode;
- /** Name used in the Sort and Columns menus when `header` is not a string. */
label?: string;
sortable?: boolean;
width?: string;
@@ -88,14 +87,6 @@ export type DataTableProps<TRow, TSub> = {
facets?: DataTableFacet[];
tabs?: DataTableTabs;
onRowClick?: (row: TRow) => void;
- /**
- * The pointer or the keyboard has landed on a row, ahead of any click.
- *
- * For warming the record the row opens. Opening a sheet is a cold fetch
- * otherwise, so the panel appears with a spinner and a placeholder title
- * and only becomes the record a moment later — which reads as the sheet
- * not having opened at all.
- */
onRowHover?: (row: TRow) => void;
expandable?: DataTableExpandable<TRow, TSub>;
actions?: ReactNode;
@@ -145,16 +136,6 @@ function SortIndicator({
);
}
-/**
- * The list view for every module.
- *
- * Everything it renders is driven by `query`, which is URL state — so a filtered,
- * sorted, paged view is a link. Rows arrive already filtered and paged from the
- * API; this component never slices data itself.
- *
- * Two params it owns directly, because they are presentation rather than data:
- * `expand` (which rows are open) and `hide` (which columns are off).
- */
export function DataTable<TRow, TSub = unknown>({
query,
columns,
@@ -206,8 +187,6 @@ export function DataTable<TRow, TSub = unknown>({
? activeTabOption.label
: (tabs?.allLabel ?? "All");
- // Keeps typing responsive: the input updates immediately, the (expensive)
- // table body re-renders at a lower priority.
const deferredRows = useDeferredValue(rows);
const anyExpandable =
expandable != null &&
@@ -289,8 +268,6 @@ export function DataTable<TRow, TSub = unknown>({
<span className="flex-1">{tabs.allLabel ?? "All"}</span>
</DropdownMenuRadioItem>
{tabs.options.map((option) => {
- // A tab that can never match anything is noise, but only
- // once we actually know the count.
if (tabCounts?.[option.value] === 0) return null;
return (
<DropdownMenuRadioItem
@@ -438,23 +415,12 @@ export function DataTable<TRow, TSub = unknown>({
</div>
<Table
- // Fixed layout so columns honour their widths and long cell text
- // truncates (cells are overflow-hidden) instead of blowing the table
- // out horizontally.
className={cn(
"table-fixed [&_td:first-child]:pl-4 [&_th:first-child]:pl-4 [&_td:last-child]:pr-4 [&_th:last-child]:pr-4",
tableClassName,
)}
- // The shell: one rounded, bordered surface the rows live inside,
- // rather than rows floating on the page. `overflow-hidden` is what
- // makes the first and last row clip to the radius.
containerClassName="min-h-0 flex-1 overflow-auto rounded-lg border bg-card"
>
- {/*
- * The header is a shelf above the rows, not another row. It gets the
- * muted fill and an inset rule rather than a border, so it stays put
- * when the body scrolls under it.
- */}
<TableHeader className="sticky top-0 z-10 bg-muted [&_th]:bg-muted [&_tr]:border-0 [&_tr]:shadow-[inset_0_-1px_0_var(--border)]">
<TableRow>
{anyExpandable && (
@@ -468,8 +434,6 @@ export function DataTable<TRow, TSub = unknown>({
<TableHead
key={column.id}
className={cn(
- // overflow-hidden mirrors the body cells so a squeezed
- // header truncates instead of spilling into the next column.
"h-11 overflow-hidden px-3 font-normal text-muted-foreground",
column.width,
ALIGN_CLASS[column.align ?? "left"],
@@ -529,7 +493,6 @@ export function DataTable<TRow, TSub = unknown>({
if (set.has(id)) set.delete(id);
else set.add(id);
const next = [...set];
- // Empty array would still write `?expand=`; null clears it.
return next.length > 0 ? next : null;
});
} else {
diff --git a/packages/ui/src/components/date-picker.tsx b/packages/ui/src/components/date-picker.tsx
index d0df244b..f6bcb138 100644
--- a/packages/ui/src/components/date-picker.tsx
+++ b/packages/ui/src/components/date-picker.tsx
@@ -9,29 +9,12 @@ import {
PopoverContent,
PopoverTrigger,
} from "@crm/ui/components/popover";
-// The same trigger as a select, deliberately. A date and a stage sit in the
-// same column of the same record sheet, and two copies of these classes is how
-// one of them ends up a pixel taller than the other.
import { selectTriggerVariants } from "@crm/ui/components/select";
import { formatDay, fromDay, toDay } from "@crm/ui/lib/format";
import { cn } from "@crm/ui/lib/utils";
import type { VariantProps } from "class-variance-authority";
import { useState } from "react";
-/**
- * Picking a day, from a calendar rather than from the browser's own widget.
- *
- * `<input type="date">` is drawn by the platform: it ignores every token in
- * this repo, changes shape between Chrome and Safari, and on a record sheet
- * full of borderless rows it is the one control with a chrome outline and a
- * greyed `mm/dd/yyyy` in it. This is the shared calendar in a popover behind a
- * trigger that matches the select next to it.
- *
- * It speaks day strings, not `Date`s, because that is what the deal API stores
- * and what the callers hold in state — handing each of them a `Date` would
- * mean three copies of the conversion in `lib/format`, which is where the
- * timezone bug came from the first time.
- */
export function DatePicker({
id,
value,
@@ -40,9 +23,7 @@ export function DatePicker({
variant,
}: {
id?: string;
- /** `2026-12-31` — or a full ISO timestamp, of which only the day is read. */
value: string | null | undefined;
- /** The chosen day, or `""` when it was cleared. */
onChange: (next: string) => void;
placeholder?: string;
} & VariantProps<typeof selectTriggerVariants>) {
@@ -63,11 +44,7 @@ export function DatePicker({
id={id}
data-slot="date-picker-trigger"
data-size="default"
- // What Radix stamps on a select with nothing chosen, and what the
- // shared trigger greys the label on.
data-placeholder={selected ? undefined : ""}
- // Full width, like the select and the input it shares a column
- // with. Nothing here wants a date control sized to its own label.
className={cn(selectTriggerVariants({ variant }), "w-full")}
>
<span className="line-clamp-1">
@@ -83,23 +60,13 @@ export function DatePicker({
<Calendar
mode="single"
selected={selected}
- // A dropdown caption with no range given is clamped to the end of
- // *this* year by react-day-picker, so "December 2027" — an entirely
- // ordinary close date — was not in the year list at all, and the
- // next-month arrow stopped dead in December.
startMonth={new Date(thisYear - 10, 0)}
endMonth={new Date(thisYear + 10, 11)}
- // Opening on a record's own close date rather than on this month:
- // the reason to open this is usually to move a date, not to set
- // one from scratch.
defaultMonth={selected}
onSelect={(next) => choose(next ? toDay(next) : "")}
captionLayout="dropdown"
autoFocus
/>
- {/* Every date here is optional, and a calendar with no way back to
- "none" makes a mis-click permanent. Only once there is something
- to clear. */}
{selected ? (
<div className="border-t p-1">
<Button
diff --git a/packages/ui/src/components/drawer.tsx b/packages/ui/src/components/drawer.tsx
index d862db80..67a2b60f 100644
--- a/packages/ui/src/components/drawer.tsx
+++ b/packages/ui/src/components/drawer.tsx
@@ -5,8 +5,6 @@ import { cva, type VariantProps } from "class-variance-authority";
import type * as React from "react";
import { Drawer as DrawerPrimitive } from "vaul";
-// Mirrors `sheetTitleVariants` — a drawer is the small-screen form of a sheet,
-// so a record title has to read the same weight in both.
const drawerTitleVariants = cva("font-heading font-medium text-foreground", {
variants: {
size: {
diff --git a/packages/ui/src/components/empty-cell.tsx b/packages/ui/src/components/empty-cell.tsx
index bd10aa76..f369d6e2 100644
--- a/packages/ui/src/components/empty-cell.tsx
+++ b/packages/ui/src/components/empty-cell.tsx
@@ -1,9 +1,5 @@
import { cn } from "../lib/utils";
-/**
- * The em dash every table uses for "nothing here". Shared so a missing value
- * looks identical in People, Cloud Security and Code Security.
- */
export function EmptyCellValue({ className }: { className?: string }) {
return <span className={cn("text-muted-foreground", className)}>—</span>;
}
diff --git a/packages/ui/src/components/empty.tsx b/packages/ui/src/components/empty.tsx
index 9cecb323..2cf239d5 100644
--- a/packages/ui/src/components/empty.tsx
+++ b/packages/ui/src/components/empty.tsx
@@ -1,24 +1,7 @@
import { cn } from "@crm/ui/lib/utils";
import { cva, type VariantProps } from "class-variance-authority";
-/**
- * How much horizontal room the copy inside is allowed.
- *
- * `default` is a narrow measure, which is right for an empty table in the
- * middle of a page: prose past about sixty characters is harder to read, so a
- * one-line explanation is worth wrapping. It is wrong in a panel that is itself
- * wide and mostly empty — there the same limit sets a short sentence over two
- * ragged lines and wraps a row of three buttons onto two, which reads as
- * squashed rather than as considered.
- *
- * The variant lives on the container and reaches the parts through a group
- * selector, so a caller says how wide the empty state is once instead of
- * repeating a max-width on the header and again on the content.
- */
const emptyVariants = cva(
- // Sits at its natural height (a comfortable block) rather than stretching to
- // fill a flex-1 page shell. Opt into full-height centering per-usage with
- // `flex-1` on the className when needed.
"group/empty flex w-full min-w-0 flex-col items-center justify-center gap-4 rounded-lg border-dashed px-6 py-12 text-center text-balance",
{
variants: {
@@ -119,12 +102,6 @@ const emptyContentVariants = cva(
"flex w-full max-w-sm min-w-0 items-center gap-2.5 text-xs text-balance group-data-[width=wide]/empty:max-w-2xl",
{
variants: {
- /**
- * `stack` for one call to action under another; `row` for a set of
- * equals, which is what a handful of suggested questions is. The row
- * still wraps — it has to on a narrow sheet — but given the room it
- * keeps them on one line.
- */
layout: {
stack: "flex-col",
row: "flex-row flex-wrap justify-center",
diff --git a/packages/ui/src/components/entity-logo.tsx b/packages/ui/src/components/entity-logo.tsx
index cb3c0eb4..009b664f 100644
--- a/packages/ui/src/components/entity-logo.tsx
+++ b/packages/ui/src/components/entity-logo.tsx
@@ -1,53 +1,29 @@
"use client";
+import { isOptimizable } from "@crm/db/images";
import { initialsFromName } from "@crm/ui/lib/format";
import { cn } from "@crm/ui/lib/utils";
+import Image from "next/image";
import { useState } from "react";
export type EntityLogoSize = "xs" | "sm" | "default" | "lg" | "xl";
-/**
- * How the artwork behaves against a background, as resolved at enrichment time.
- *
- * - `opaque` — composed on its own tile; needs nothing from us.
- * - `dark` — dark mark on transparency; vanishes in dark mode.
- * - `light` — light mark on transparency; vanishes in light mode.
- */
+const PX: Record<EntityLogoSize, number> = {
+ xs: 16,
+ sm: 20,
+ default: 24,
+ lg: 32,
+ xl: 48,
+};
+
export type EntityLogoTone = "opaque" | "dark" | "light";
-/**
- * A surface, only for the theme where the artwork would otherwise disappear.
- *
- * Most brands publish one logo drawn for a white page, so on a dark row a black
- * wordmark is simply not there. The alternative — a tile behind every logo —
- * is what the note above rules out, and it would put a white square behind the
- * icons that already arrive on their own background.
- *
- * `invert` rather than a coloured tile for the monochrome cases: it keeps the
- * mark borderless, which is the whole point of this component, and a mark whose
- * dominant colour is near-black or near-white is monochrome by definition.
- */
const TONE_CLASS: Record<EntityLogoTone, string> = {
opaque: "",
dark: "dark:invert",
light: "invert dark:invert-0",
};
-/**
- * A square logo tile with an initials fallback.
- *
- * Square rather than an `Avatar`: a round crop is right for a face and wrong
- * for a wordmark, and company logos arrive from Context.dev as squares already.
- * Keeping it here rather than composing it per module means a company reads the
- * same in a table row, a sheet header and an embedded list.
- *
- * One format for every logo, and no chrome around it. A border drawn around
- * artwork that already carries its own edge — which is most of them, since the
- * icons arrive pre-composed on a brand colour — reads as a box the logo is
- * trapped in, and turns a column of companies into a strip of frames. Without
- * it the artwork is the artwork: contained, never cropped, and occupying the
- * same square whatever shape it came in.
- */
export function EntityLogo({
src,
darkSrc,
@@ -57,24 +33,18 @@ export function EntityLogo({
className,
}: {
src?: string | null;
- /** The brand's own dark-mode artwork, when it publishes one. */
darkSrc?: string | null;
tone?: EntityLogoTone | null;
name: string;
size?: EntityLogoSize;
className?: string;
}) {
- // The *url* that failed, not a boolean: enrichment fills `iconUrl` in behind
- // a poll, so a `true` left over from the placeholder would pin this to
- // initials forever once the real logo arrived.
const [failedSrc, setFailedSrc] = useState<string | null>(null);
const url = src?.trim() ? src : null;
const dark = darkSrc?.trim() ? darkSrc : null;
const showImage = url !== null && failedSrc !== url;
- // A real dark-mode logo always beats a synthetic one, so the tone fix is
- // skipped entirely when the brand published artwork for both.
const toneClass = dark ? "" : tone ? TONE_CLASS[tone] : "";
return (
@@ -82,33 +52,18 @@ export function EntityLogo({
data-slot="entity-logo"
data-size={size}
className={cn(
- "inline-flex size-8 shrink-0 select-none items-center justify-center overflow-hidden text-center font-medium text-muted-foreground text-xs uppercase leading-none",
- "data-[size=xs]:size-5 data-[size=xs]:text-[9px] data-[size=sm]:size-6 data-[size=sm]:text-[10px] data-[size=lg]:size-10 data-[size=lg]:text-sm data-[size=xl]:size-14 data-[size=xl]:text-lg",
- // Initials are type, and type needs a surface to sit on to read as a
- // logo's stand-in rather than as two stray letters in the row.
- // Artwork brings its own.
+ "inline-flex size-6 shrink-0 select-none items-center justify-center overflow-hidden text-center font-medium text-[10px] text-muted-foreground uppercase leading-none",
+ "data-[size=xs]:size-4 data-[size=xs]:text-[8px] data-[size=sm]:size-5 data-[size=sm]:text-[9px] data-[size=lg]:size-8 data-[size=lg]:text-xs data-[size=xl]:size-12 data-[size=xl]:text-base",
!showImage && "bg-muted",
className,
)}
>
{showImage ? (
<>
- <img
+ <Artwork
src={url}
- alt=""
- loading="lazy"
- decoding="async"
- // Several logo CDNs refuse a request that carries our origin.
- referrerPolicy="no-referrer"
- // A dead logo URL is common — brands move them — and the alt text
- // of a broken image is worse than the initials we would have shown.
+ px={PX[size]}
onError={() => setFailedSrc(url)}
- // `contain`, always: cropping a logo is never the right answer, and
- // with no border to letterbox against, a wide wordmark can use the
- // full width instead of being inset to escape the frame.
- //
- // Swapped by CSS rather than by reading the theme in JS: a hook
- // would render the wrong logo on the server and flip it on hydrate.
className={cn(
"size-full object-contain",
dark && "dark:hidden",
@@ -117,12 +72,9 @@ export function EntityLogo({
/>
{dark ? (
- <img
+ <Artwork
src={dark}
- alt=""
- loading="lazy"
- decoding="async"
- referrerPolicy="no-referrer"
+ px={PX[size]}
className="hidden size-full object-contain dark:block"
/>
) : null}
@@ -133,3 +85,31 @@ export function EntityLogo({
</span>
);
}
+
+function Artwork({
+ src,
+ px,
+ className,
+ onError,
+}: {
+ src: string;
+ px: number;
+ className: string;
+ onError?: () => void;
+}) {
+ const shared = {
+ alt: "",
+ loading: "lazy",
+ decoding: "async",
+ referrerPolicy: "no-referrer",
+ onError,
+ className,
+ } as const;
+
+ return isOptimizable(src) ? (
+ <Image src={src} width={px} height={px} {...shared} />
+ ) : (
+ // biome-ignore lint/performance/noImgElement: the optimizer may not serve this — see `isOptimizable`.
+ <img src={src} {...shared} />
+ );
+}
diff --git a/packages/ui/src/components/input-group.tsx b/packages/ui/src/components/input-group.tsx
index 74d10177..732be0cd 100644
--- a/packages/ui/src/components/input-group.tsx
+++ b/packages/ui/src/components/input-group.tsx
@@ -21,15 +21,6 @@ function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
);
}
-/**
- * `cursor-text` and click-to-focus belong to the inline aligns only.
- *
- * An inline addon is the padding either side of a field — a currency symbol, a
- * search glyph — so clicking it should behave as if you clicked the field. A
- * block addon is a toolbar under a rule, and giving a row of toggle buttons an
- * I-beam cursor that focuses something else when you miss one is a small lie
- * about what the row is.
- */
const inputGroupAddonVariants = cva(
"flex h-auto items-center justify-center gap-2 py-1.5 text-xs font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-none [&>svg:not([class*='size-'])]:size-4",
{
@@ -140,9 +131,6 @@ function InputGroupInput({
function InputGroupTextarea({
className,
- // One line until there is more than one line in it. A group exists to put
- // controls around a field, and a field that opens four rows tall pushes its
- // own toolbar off the bottom of whatever it sits in.
size = "sm",
...props
}: React.ComponentProps<typeof Textarea>) {
diff --git a/packages/ui/src/components/input.tsx b/packages/ui/src/components/input.tsx
index 32957602..911975c1 100644
--- a/packages/ui/src/components/input.tsx
+++ b/packages/ui/src/components/input.tsx
@@ -7,11 +7,6 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
type={type}
data-slot="input"
className={cn(
- /*
- * The focus ring sits outside the border rather than replacing
- * it, so the control does not appear to change size the moment
- * it is focused.
- */
"h-8 w-full min-w-0 rounded-md border border-input bg-background px-2.5 py-1 text-xs transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-xs file:font-medium file:text-foreground placeholder:text-muted-foreground hover:border-ring/40 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-60 aria-invalid:border-destructive aria-invalid:ring-2 aria-invalid:ring-destructive/25 md:text-xs dark:bg-muted dark:shadow-[inset_0_1px_1px_rgb(0_0_0/0.30)] dark:disabled:bg-muted",
className,
)}
diff --git a/packages/ui/src/components/markdown.tsx b/packages/ui/src/components/markdown.tsx
index 7617df8a..488101a1 100644
--- a/packages/ui/src/components/markdown.tsx
+++ b/packages/ui/src/components/markdown.tsx
@@ -3,22 +3,6 @@
import { cn } from "@crm/ui/lib/utils";
import { Streamdown } from "streamdown";
-/**
- * Markdown written by a machine, rendered like the rest of the app.
- *
- * `Streamdown` rather than a plain markdown renderer because this text arrives
- * a token at a time: a conventional parser sees `**bol` mid-stream and renders
- * the asterisks, then reflows the paragraph when the rest lands. This one
- * completes incomplete syntax as it goes, so a streaming answer reads as prose
- * the whole way through instead of flickering between source and output.
- *
- * The styling is spelled out rather than borrowed from a typography plugin.
- * The agent writes short answers with the occasional list, link or snippet —
- * six selectors cover all of it, and a prose preset would bring a type scale
- * that fights the sheet it sits in.
- *
- * No rounded corners, per `design.md`, including on code blocks.
- */
export function Markdown({
children,
className,
@@ -28,21 +12,14 @@ export function Markdown({
}) {
return (
<Streamdown
- // Shiki ships both themes; the surrounding `.dark` class picks one.
shikiTheme={["github-light", "github-dark"]}
className={cn(
- // `text-xs`, like everything else in a record sheet — this only ever
- // renders inside the Agent tab of one.
"min-w-0 space-y-2.5 text-xs/5 wrap-break-word",
- // Headings are rare in a chat answer and should not shout when they
- // do appear — the sheet already has a heading hierarchy.
"[&_h1]:font-medium [&_h1]:text-xs [&_h2]:font-medium [&_h2]:text-xs [&_h3]:font-medium [&_h3]:text-xs",
"[&_p]:text-pretty",
"[&_ul]:list-disc [&_ol]:list-decimal [&_ul]:pl-5 [&_ol]:pl-5 [&_li]:my-0.5",
"[&_a]:underline [&_a]:underline-offset-2",
"[&_strong]:font-medium",
- // Inline code sits inside a sentence, so it keeps the line height it
- // was given and takes only a tint.
"[&_code]:bg-muted [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[0.85em]",
"[&_pre]:overflow-x-auto [&_pre]:border [&_pre]:bg-muted [&_pre]:p-3 [&_pre_code]:bg-transparent [&_pre_code]:p-0",
"[&_blockquote]:border-l-2 [&_blockquote]:pl-3 [&_blockquote]:text-muted-foreground",
diff --git a/packages/ui/src/components/person-avatar.tsx b/packages/ui/src/components/person-avatar.tsx
new file mode 100644
index 00000000..ca9db46c
--- /dev/null
+++ b/packages/ui/src/components/person-avatar.tsx
@@ -0,0 +1,30 @@
+"use client";
+
+import { Avatar, AvatarFallback, AvatarImage } from "@crm/ui/components/avatar";
+import { initialsFromName } from "@crm/ui/lib/format";
+import type * as React from "react";
+
+export type PersonAvatarSize = "sm" | "default" | "lg";
+
+export function PersonAvatar({
+ src,
+ name,
+ email,
+ size = "default",
+ ...props
+}: Omit<React.ComponentProps<typeof Avatar>, "children" | "size"> & {
+ src?: string | null;
+ name?: string | null;
+ email?: string | null;
+ size?: PersonAvatarSize;
+}) {
+ const url = src?.trim() ? src : undefined;
+ const label = name?.trim() || email?.trim() || "";
+
+ return (
+ <Avatar size={size} {...props}>
+ {url ? <AvatarImage src={url} alt="" /> : null}
+ <AvatarFallback>{initialsFromName(label)}</AvatarFallback>
+ </Avatar>
+ );
+}
diff --git a/packages/ui/src/components/popover.tsx b/packages/ui/src/components/popover.tsx
index e409a14f..6420634e 100644
--- a/packages/ui/src/components/popover.tsx
+++ b/packages/ui/src/components/popover.tsx
@@ -22,9 +22,6 @@ const popoverContentVariants = cva(
"z-50 flex origin-(--radix-popover-content-transform-origin) flex-col rounded-lg bg-popover text-xs text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
{
variants: {
- // `fit` is for content that owns its own box — a calendar, a colour
- // grid. The default column of padded prose would put a second margin
- // around something already drawn to size.
size: {
default: "w-72 gap-2.5 p-2.5",
fit: "w-auto overflow-hidden p-0",
diff --git a/packages/ui/src/components/select.tsx b/packages/ui/src/components/select.tsx
index 235aae3e..56de822c 100644
--- a/packages/ui/src/components/select.tsx
+++ b/packages/ui/src/components/select.tsx
@@ -31,11 +31,6 @@ function SelectValue({
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
}
-// `ghost` is for a select sitting in a row of otherwise plain values — an
-// editable property in a record sheet. A boxed control among bare text reads
-// as the only thing on the panel you are allowed to touch, which is the
-// opposite of true: it borrows the surrounding row's look until you point at
-// it, and its chevron only appears on hover or focus.
const selectTriggerVariants = cva(
"flex w-fit items-center justify-between gap-1.5 rounded-md text-xs whitespace-nowrap transition-colors outline-none select-none disabled:cursor-not-allowed disabled:opacity-50 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
diff --git a/packages/ui/src/components/sheet.tsx b/packages/ui/src/components/sheet.tsx
index edfde0ef..78cfd131 100644
--- a/packages/ui/src/components/sheet.tsx
+++ b/packages/ui/src/components/sheet.tsx
@@ -7,11 +7,6 @@ import { XIcon } from "lucide-react";
import { Dialog as SheetPrimitive } from "radix-ui";
import type * as React from "react";
-// Width scale for left/right sheets (desktop only — the mobile drawer is
-// full-width). Default is `sm` (forms); `lg` is the standard detail width;
-// `xl` is for content that needs the extra room. `2xl` is the record sheet —
-// a company, contact or deal with its tabs, which replaces what would
-// otherwise be a page, and so gets close to page width.
const sheetContentVariants = cva(
"fixed z-50 flex flex-col bg-popover bg-clip-padding text-xs/relaxed text-popover-foreground shadow-lg duration-300 ease-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-open:animate-in data-[side=bottom]:data-open:slide-in-from-bottom-full data-[side=left]:data-open:slide-in-from-left-full data-[side=right]:data-open:slide-in-from-right-full data-[side=top]:data-open:slide-in-from-top-full data-closed:animate-out data-[side=bottom]:data-closed:slide-out-to-bottom-full data-[side=left]:data-closed:slide-out-to-left-full data-[side=right]:data-closed:slide-out-to-right-full data-[side=top]:data-closed:slide-out-to-top-full",
{
@@ -131,9 +126,6 @@ function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
);
}
-// `default` is the form sheet — a line of instruction above some fields.
-// `lg` is the record sheet, where the title is the name of the thing you
-// opened and has to carry the panel the way a page heading would.
const sheetTitleVariants = cva("font-heading font-medium text-foreground", {
variants: {
size: {
diff --git a/packages/ui/src/components/simple-table.tsx b/packages/ui/src/components/simple-table.tsx
index 06777e53..7bc0a13b 100644
--- a/packages/ui/src/components/simple-table.tsx
+++ b/packages/ui/src/components/simple-table.tsx
@@ -46,17 +46,7 @@ export function SimpleTable({
}: {
columns: SimpleTableColumn[];
children: ReactNode;
- /**
- * `panel` fills the remaining height of a sheet tab and pins the header
- * while the rows scroll under it. Everywhere else the table is one block in
- * a column of blocks and scrolls with the page.
- */
variant?: "default" | "panel";
- /**
- * What the pinned header sits on, so it hides the rows passing under it
- * instead of showing a strip of the wrong surface: `popover` inside a sheet,
- * `page` inside a panel on the page itself.
- */
surface?: keyof typeof PANEL_SURFACE;
className?: string;
containerClassName?: string;
@@ -71,9 +61,6 @@ export function SimpleTable({
className={cn("w-full", panel && "table-fixed", className)}
containerClassName={cn(
panel && "min-h-0 flex-1 overflow-x-hidden overflow-y-auto",
- // Standalone tables carry their own shell. The `panel` variant does
- // not: it sits inside `CardPanel`, which already draws the border,
- // and two of them read as a box inside a box.
!panel && "rounded-lg border bg-card",
containerClassName,
)}
@@ -81,9 +68,6 @@ export function SimpleTable({
<TableHeader
className={cn(
panel && ["sticky top-0 z-10", PANEL_SURFACE[surface]],
- // A filled shelf with an inset rule rather than a bottom border,
- // so the line sits inside the shell's rounded corners instead of
- // running out past them.
!panel &&
"bg-muted [&_tr]:border-0 [&_tr]:shadow-[inset_0_-1px_0_var(--border)]",
headerClassName,
diff --git a/packages/ui/src/components/sourced-value.tsx b/packages/ui/src/components/sourced-value.tsx
index 54c17b38..84015286 100644
--- a/packages/ui/src/components/sourced-value.tsx
+++ b/packages/ui/src/components/sourced-value.tsx
@@ -7,33 +7,8 @@ import {
} from "@crm/ui/components/tooltip";
import type * as React from "react";
-/**
- * The decoration on a value a machine wrote.
- *
- * One dotted underline, for the same reason `status-indicator` is a dot and a
- * word rather than a badge: a sheet speckled with chips is a sheet you read the
- * chips of. An underline says "there is more here" at a tenth of the ink and
- * vanishes when you are not looking for it.
- *
- * Exported as a class rather than a component because it has to sit on the text
- * *inside* whatever control already owns the row — wrapping the control would
- * either nest a button in a button or steal its focus behaviour.
- */
export const SOURCED_VALUE = "underline decoration-dotted underline-offset-4";
-/**
- * Hangs provenance off an existing control.
- *
- * `children` must be a single focusable element — the field's own button,
- * normally — so that pointing at a value explains it and tabbing to it does the
- * same. Nothing new becomes clickable.
- *
- * **Not a fragment.** `asChild` clones the child to pass `aria-describedby` and
- * the tooltip's open state onto it, and a fragment takes no props: React throws
- * `Invalid prop \`aria-describedby\` supplied to \`React.Fragment\``. The type
- * cannot catch this — a fragment is a perfectly good `ReactElement` — so it is
- * written down here instead.
- */
export function SourcedValue({
children,
source,
@@ -51,14 +26,6 @@ export function SourcedValue({
);
}
-/**
- * The body of a provenance tooltip: what we believe, why, and since when.
- *
- * Prose rather than a field table. "LinkedIn: employer and name both match" is
- * something a rep can act on; `score: 0.85, method: linkedin.profile` is
- * something they have to decode first, and a tooltip is not a place anybody
- * wants to decode anything.
- */
export function Provenance({
claim,
reasons,
diff --git a/packages/ui/src/components/stat-card.tsx b/packages/ui/src/components/stat-card.tsx
index e03b898f..36440b67 100644
--- a/packages/ui/src/components/stat-card.tsx
+++ b/packages/ui/src/components/stat-card.tsx
@@ -4,11 +4,8 @@ import type * as React from "react";
type TrendDirection = "up" | "down" | "neutral";
type StatDelta = {
- /** Pre-formatted change, e.g. "+12%" or "+3". */
value: string;
- /** Drives the color + arrow. Defaults to inferring from a leading sign. */
direction?: TrendDirection;
- /** Trailing context, e.g. "vs. last month". */
label?: string;
};
@@ -58,12 +55,6 @@ function StatDeltaText({
);
}
-/**
- * A single KPI — label, headline value, optional trend delta, and an optional
- * slot (`children`) for a sparkline. Intentionally borderless: drop several into
- * a {@link StatGroup} so they read as one divider-separated strip rather than a
- * row of competing boxes. Per the dashboard guidelines, KPIs carry no icons.
- */
function StatCard({
label,
value,
diff --git a/packages/ui/src/components/status-indicator.tsx b/packages/ui/src/components/status-indicator.tsx
index cc7b420c..bd41e6ed 100644
--- a/packages/ui/src/components/status-indicator.tsx
+++ b/packages/ui/src/components/status-indicator.tsx
@@ -3,15 +3,15 @@ import { type Bloom, bloomClass } from "@crm/ui/lib/dither";
import { cn } from "@crm/ui/lib/utils";
import type * as React from "react";
-/**
- * The five states anything in this app can be in.
- *
- * Named for meaning rather than colour so a status reads the same everywhere:
- * "the agent failed" and "the deal was lost" are both `error`, and neither
- * caller gets to pick a shade.
- */
export type StatusTone = "neutral" | "info" | "success" | "warning" | "error";
+export type StatusSize = "default" | "sm";
+
+const SIZE_CLASS: Record<StatusSize, string> = {
+ default: "",
+ sm: "text-xs",
+};
+
const TONE_COLOR: Record<StatusTone, string> = {
neutral: "var(--color-muted-foreground)",
info: "var(--color-info)",
@@ -30,7 +30,6 @@ function IndicatorDot({
...props
}: React.ComponentProps<"span"> & {
tone?: StatusTone;
- /** An explicit colour, for scales the tones do not cover. */
color?: string;
pulse?: boolean;
bloom?: Bloom;
@@ -59,21 +58,14 @@ function IndicatorDot({
);
}
-/**
- * A dot and a word — the only way this app shows a status.
- *
- * Deliberately not a badge: a table of pill-shaped chips in five colours is a
- * table you read the chips of instead of the rows. A dot carries the same
- * meaning at a tenth of the ink, and a column of them lines up.
- */
function StatusIndicator({
tone = "neutral",
color,
label,
pulse = false,
- /** In-flight work: a spinner replaces the dot, as nothing is settled yet. */
busy = false,
bloom = "low",
+ size = "default",
className,
...props
}: Omit<React.ComponentProps<"span">, "color"> & {
@@ -83,6 +75,7 @@ function StatusIndicator({
pulse?: boolean;
busy?: boolean;
bloom?: Bloom;
+ size?: StatusSize;
}) {
return (
<span
@@ -90,6 +83,7 @@ function StatusIndicator({
data-tone={tone}
className={cn(
"inline-flex min-w-0 items-center gap-2 text-muted-foreground",
+ SIZE_CLASS[size],
className,
)}
{...props}
diff --git a/packages/ui/src/components/suggestion.tsx b/packages/ui/src/components/suggestion.tsx
index 17303403..a679e4a5 100644
--- a/packages/ui/src/components/suggestion.tsx
+++ b/packages/ui/src/components/suggestion.tsx
@@ -7,18 +7,6 @@ import { Icon } from "@crm/ui/components/icon";
import { Spinner } from "@crm/ui/components/spinner";
import type * as React from "react";
-/**
- * Something a machine thinks is true, offered to somebody who can tell.
- *
- * The rule this encodes: **a suggestion is never rendered as a value.** It sits
- * under the empty field it would fill, in muted text, with the two buttons that
- * settle it. A guess formatted identically to a fact is how a CRM quietly
- * teaches people to distrust every field in it.
- *
- * It lives here rather than in the app because the same shape will be wanted on
- * companies and deals, and because "how does this product show uncertainty" is
- * exactly the sort of decision `design.md` says belongs in one place.
- */
export function Suggestion({
value,
rationale,
@@ -27,7 +15,6 @@ export function Suggestion({
onDismiss,
}: {
value: React.ReactNode;
- /** Why the agent thinks so, in one line. */
rationale?: React.ReactNode;
pending?: boolean;
onAccept: () => void;
diff --git a/packages/ui/src/components/switch.tsx b/packages/ui/src/components/switch.tsx
index 54f02035..82e743bc 100644
--- a/packages/ui/src/components/switch.tsx
+++ b/packages/ui/src/components/switch.tsx
@@ -16,11 +16,6 @@ function Switch({
<SwitchPrimitive.Root
data-slot="switch"
data-size={size}
- // The track height is deliberately a whole number. `items-center` splits
- // whatever is left over after the thumb between top and bottom, so an
- // 18.4px track left 0.2px a side and the browser rounded it into a thumb
- // that sat visibly high. Track minus its 1px borders now equals the thumb
- // exactly, which is how the `sm` size has always worked.
className={cn(
"peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-2 aria-invalid:ring-destructive/20 data-[size=default]:h-[18px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",
className
diff --git a/packages/ui/src/components/table-pagination.tsx b/packages/ui/src/components/table-pagination.tsx
index 001b80dd..1a6c535e 100644
--- a/packages/ui/src/components/table-pagination.tsx
+++ b/packages/ui/src/components/table-pagination.tsx
@@ -53,8 +53,6 @@ export function TablePagination({
<span className="text-muted-foreground text-xs tabular-nums">
{page} / {totalPages}
</span>
- {/* Next carries the weight: it is the one you press to move
- * through a list, and Previous is the way back. */}
<Button
variant="contrast"
size="sm"
diff --git a/packages/ui/src/components/table.tsx b/packages/ui/src/components/table.tsx
index 614dfd5a..9611a4f9 100644
--- a/packages/ui/src/components/table.tsx
+++ b/packages/ui/src/components/table.tsx
@@ -60,8 +60,6 @@ function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
<tr
data-slot="table-row"
className={cn(
- // The whole row is a click target, so it needs a hover the eye can
- // follow across all six columns — not just under the cursor.
"border-b transition-colors hover:bg-muted/60 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
className,
)}
@@ -75,8 +73,6 @@ function TableHead({ className, ...props }: React.ComponentProps<"th">) {
<th
data-slot="table-head"
className={cn(
- // Column labels are signposts, not data: muted and lighter than the
- // values beneath them, so the eye lands on the rows first.
"h-9 px-2 text-left align-middle font-medium whitespace-nowrap text-muted-foreground [&:has([role=checkbox])]:pr-0",
className,
)}
diff --git a/packages/ui/src/components/tabs.tsx b/packages/ui/src/components/tabs.tsx
index 6aad6e27..4c85bc6c 100644
--- a/packages/ui/src/components/tabs.tsx
+++ b/packages/ui/src/components/tabs.tsx
@@ -63,15 +63,7 @@ function TabsTrigger({
data-slot="tabs-trigger"
className={cn(
"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-sm border border-transparent px-1.5 py-0.5 text-xs font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start group-data-vertical/tabs:py-[calc(--spacing(1.25))] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
- // `flex-none` for line tabs: they are labels with a rule under the
- // active one, so each is as wide as its word. Letting them share the
- // row equally stretches four tabs across a whole sheet, and then the
- // underline and the hover target are a quarter of the panel wide with
- // the label marooned in the middle of them.
"group-data-[variant=line]/tabs-list:flex-none group-data-[variant=line]/tabs-list:px-0 group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent",
- // The raised thumb. In dark the track is the recessed thing and the
- // thumb sits above it, so the stacking order inverts rather than the
- // colours simply flipping.
"data-active:bg-background data-active:text-foreground data-active:shadow-2xs dark:data-active:border-border dark:data-active:bg-accent dark:data-active:text-foreground",
"after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",
className,
diff --git a/packages/ui/src/components/textarea.tsx b/packages/ui/src/components/textarea.tsx
index 3a240a84..74e4801a 100644
--- a/packages/ui/src/components/textarea.tsx
+++ b/packages/ui/src/components/textarea.tsx
@@ -2,14 +2,6 @@ import { cn } from "@crm/ui/lib/utils";
import { cva, type VariantProps } from "class-variance-authority";
import type * as React from "react";
-/**
- * `field-sizing-content` means the box is already the height of what is in it —
- * the only question a size answers is how tall it is when empty.
- *
- * `sm` is one line, for a field that is always on screen waiting to be typed
- * into. A four-line box sitting empty at the top of a panel is a form; a single
- * line is a place to start.
- */
const textareaVariants = cva(
"flex field-sizing-content w-full rounded-md border border-input bg-background px-2.5 py-2 text-xs transition-colors outline-none placeholder:text-muted-foreground hover:border-ring/40 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40 disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-60 aria-invalid:border-destructive aria-invalid:ring-2 aria-invalid:ring-destructive/25 md:text-xs dark:bg-muted dark:shadow-[inset_0_1px_1px_rgb(0_0_0/0.30)] dark:disabled:bg-muted",
{
diff --git a/packages/ui/src/components/thread-message.tsx b/packages/ui/src/components/thread-message.tsx
index 145f53b5..6150fa8e 100644
--- a/packages/ui/src/components/thread-message.tsx
+++ b/packages/ui/src/components/thread-message.tsx
@@ -1,17 +1,11 @@
-import { Avatar, AvatarFallback } from "@crm/ui/components/avatar";
+import { PersonAvatar } from "@crm/ui/components/person-avatar";
import { cn } from "@crm/ui/lib/utils";
import type * as React from "react";
-/**
- * One message in an email thread.
- *
- * Direction is carried by a rail down the left rather than by colour: a mail
- * client's blue-for-mine is a convention this design system does not have, and
- * a rail reads the same in both themes and to anyone who cannot see the hue.
- */
function ThreadMessage({
from,
fromEmail,
+ fromImageUrl,
sentAt,
direction,
body,
@@ -21,11 +15,10 @@ function ThreadMessage({
}: Omit<React.ComponentProps<"article">, "children"> & {
from: string;
fromEmail: string;
- /** Already formatted — the package does not own locale decisions. */
+ fromImageUrl?: string | null;
sentAt: string;
direction: "INBOUND" | "OUTBOUND";
body: string | null;
- /** A deep link back to Gmail, usually. */
action?: React.ReactNode;
}) {
const outbound = direction === "OUTBOUND";
@@ -41,9 +34,13 @@ function ThreadMessage({
)}
{...props}
>
- <Avatar size="sm" className="mt-0.5">
- <AvatarFallback>{initialsOf(from, fromEmail)}</AvatarFallback>
- </Avatar>
+ <PersonAvatar
+ src={fromImageUrl}
+ name={from}
+ email={fromEmail}
+ size="sm"
+ className="mt-0.5"
+ />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
@@ -72,15 +69,4 @@ function ThreadMessage({
);
}
-/** Up to two letters, from the display name if there is one. */
-function initialsOf(name: string, email: string): string {
- const source = name.trim() && !name.includes("@") ? name : email;
- const words = source.split(/[\s._-]+/).filter(Boolean);
-
- return words
- .slice(0, 2)
- .map((word) => word.charAt(0).toUpperCase())
- .join("");
-}
-
export { ThreadMessage };
diff --git a/packages/ui/src/components/toggle.tsx b/packages/ui/src/components/toggle.tsx
index f4d6fa1c..b9822f14 100644
--- a/packages/ui/src/components/toggle.tsx
+++ b/packages/ui/src/components/toggle.tsx
@@ -5,16 +5,6 @@ import { cva, type VariantProps } from "class-variance-authority";
import { Toggle as TogglePrimitive } from "radix-ui";
import type * as React from "react";
-/**
- * A toggle states its own colour rather than inheriting one.
- *
- * Off is muted, on is foreground — which is also the only difference a reader
- * can see at a glance, since `bg-muted` against a dark panel is nearly nothing.
- * Inheriting was worse than merely subtle: dropped inside an `InputGroupAddon`,
- * which sets `text-muted-foreground` for its own labels, a whole row of these
- * came out dimmer than the identical row forty pixels below it and read as
- * disabled.
- */
const toggleVariants = cva(
"group/toggle inline-flex items-center justify-center gap-1 rounded-md text-muted-foreground text-xs font-medium whitespace-nowrap transition-all outline-none hover:bg-muted hover:text-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 aria-pressed:bg-muted aria-pressed:text-foreground data-[state=on]:bg-muted data-[state=on]:text-foreground dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
diff --git a/packages/ui/src/hooks/use-search-input.ts b/packages/ui/src/hooks/use-search-input.ts
index 7aad6ce9..c994e90b 100644
--- a/packages/ui/src/hooks/use-search-input.ts
+++ b/packages/ui/src/hooks/use-search-input.ts
@@ -2,20 +2,6 @@
import { useEffect, useRef, useState } from "react";
-/**
- * A search box that types at keyboard speed and updates the URL afterwards.
- *
- * List state lives in the query string, so the obvious wiring — value from the
- * URL, `onChange` writes it straight back — puts a router transition between
- * the key press and the character appearing. Every keystroke re-renders the
- * page and the table with it, which reads as a laggy input even though the
- * fetch itself is already deferred.
- *
- * So the input is local state, and the URL is caught up once typing pauses.
- * The committed value is still the single source of truth: anything that
- * changes it elsewhere — the back button, a cleared filter, a reset link —
- * flows back down and replaces what is in the box.
- */
export function useSearchInput(
committed: string,
commit: (value: string) => void,
@@ -23,16 +9,12 @@ export function useSearchInput(
) {
const [value, setValue] = useState(committed);
- // Kept in a ref so the debounce effect depends on the typed value alone.
- // `commit` is a fresh closure on every render, and depending on it directly
- // would restart the timer each time and never fire.
const commitRef = useRef(commit);
commitRef.current = commit;
const committedRef = useRef(committed);
committedRef.current = committed;
- // The URL changed without us: adopt it.
useEffect(() => {
setValue(committed);
}, [committed]);
diff --git a/packages/ui/src/lib/format.ts b/packages/ui/src/lib/format.ts
index 53f1468f..d3b24230 100644
--- a/packages/ui/src/lib/format.ts
+++ b/packages/ui/src/lib/format.ts
@@ -1,23 +1,3 @@
-/**
- * Formatting shared by every module surface.
- *
- * `formatCount` existed three times over — identically — in
- * `code-security/cs-ui`, `cloud-security/cloud-ui` and `people/people-ui`.
- *
- * `relativeTimeFromIso` was defined in `code-security/cs-ui` and imported
- * across module boundaries by People. It is deliberately NOT merged with the
- * epoch-milliseconds `relativeTime` in `apps/app/lib/format-date`: they take
- * different inputs and disagree on the empty case ("—" vs "Never"), so folding
- * them together would silently change copy in one module or the other. Both
- * names are kept so the difference is visible at the call site.
- *
- * `formatMoney` moved here from `components/admin/admin-ui`, which is now needed
- * by the People upgrade surfaces too. It is deliberately NOT merged with the
- * billing page's local `formatMoney`: that one always renders two decimals
- * (invoice amounts), this one drops them for whole dollars. Folding them
- * together would silently change billing copy.
- */
-
export function formatCount(count: number, noun: string): string {
return `${count} ${count === 1 ? noun : `${noun}s`}`;
}
@@ -38,13 +18,6 @@ export function formatMoney(cents: number, currency = "usd"): string {
}).format(cents / 100);
}
-/**
- * `"$128K"` — a headline where the exact dollar is noise.
- *
- * Deliberately separate from `formatMoney`: a figure a rep reads at a glance
- * wants three characters, and a figure they are about to act on wants all of
- * them. Rounding a row in a table would be a bug; rounding a KPI is the point.
- */
export function formatMoneyCompact(cents: number, currency = "usd"): string {
return new Intl.NumberFormat(undefined, {
style: "currency",
@@ -54,7 +27,6 @@ export function formatMoneyCompact(cents: number, currency = "usd"): string {
}).format(cents / 100);
}
-/** A 0–1 rate as `"62%"`. */
export function formatPercent(rate: number): string {
return new Intl.NumberFormat(undefined, {
style: "percent",
@@ -72,24 +44,10 @@ function pad(value: number): string {
return String(value).padStart(2, "0");
}
-/**
- * `2026-07-31` — a day on a calendar, which is not an instant.
- *
- * These three go through the date's *parts* rather than `toISOString()` or
- * `new Date(value)`, and that is the whole point of them. `new Date(
- * "2026-07-16")` is midnight **UTC**, which is the 15th anywhere west of it —
- * so a deal's close date rendered a day early in San Francisco, and the field
- * that had been fixed to split the parts then disagreed with the stats strip
- * two inches above it that had not. One definition, so they cannot drift.
- */
export function toDay(date: Date): string {
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}
-/**
- * The inverse: local midnight on that day, or nothing if it is not a day.
- * Takes a full ISO timestamp too, reading the day the server stored.
- */
export function fromDay(value: string | null | undefined): Date | undefined {
if (!value) return undefined;
const [year, month, day] = value.slice(0, 10).split("-").map(Number);
@@ -98,7 +56,6 @@ export function fromDay(value: string | null | undefined): Date | undefined {
return Number.isNaN(date.getTime()) ? undefined : date;
}
-/** How a stored day reads: `"Jul 16, 2026"`. */
export function formatDay(value: string | null | undefined): string {
const date = fromDay(value);
return date ? dayFormat.format(date) : (value ?? "—");
diff --git a/packages/ui/src/lib/row-accent.ts b/packages/ui/src/lib/row-accent.ts
index ed70bcde..27f23036 100644
--- a/packages/ui/src/lib/row-accent.ts
+++ b/packages/ui/src/lib/row-accent.ts
@@ -1,7 +1,3 @@
-// NOTE: every class below must be written out as a literal string. Tailwind's
-// scanner only generates CSS for class names it finds verbatim in source — it
-// cannot see dynamically built/interpolated ones, so no template helpers here.
-
const BAR = [
"[&>td:first-child]:relative",
"[&>td:first-child]:before:pointer-events-none [&>td:first-child]:before:absolute",
@@ -10,7 +6,6 @@ const BAR = [
"[&:hover>td:first-child]:before:opacity-100",
].join(" ");
-// Content-first rows: slide the first cell's text right on hover.
export const ROW_ACCENT = [
"cursor-pointer",
BAR,
@@ -18,8 +13,6 @@ export const ROW_ACCENT = [
"[&:hover>td:first-child]:pl-5",
].join(" ");
-// Rows with a leading icon/expand column (a chevron isn't "the text"): keep the
-// bar on the first cell but slide the second cell — the first real content.
export const ROW_ACCENT_EXPANDABLE = [
"cursor-pointer",
BAR,
diff --git a/packages/ui/src/lib/table-query.ts b/packages/ui/src/lib/table-query.ts
index e09ee102..3b5549ea 100644
--- a/packages/ui/src/lib/table-query.ts
+++ b/packages/ui/src/lib/table-query.ts
@@ -1,26 +1,12 @@
export type SortDirection = "asc" | "desc";
-/**
- * The contract between a list page's URL state and `DataTable`.
- *
- * The table renders the controls and reads the current values; it never owns
- * them. The implementation lives in the app (`useTableQuery`) because routing
- * is not the design system's business — but the shape belongs next to the
- * component that consumes it, so the two cannot drift.
- *
- * Search is not in here. It is the one list control that lives in the page
- * header rather than the toolbar, so it reads `q` out of the URL itself and the
- * table never sees it.
- */
export type TableQueryState = {
sort: string;
dir: SortDirection;
page: number;
pageSize: number;
- /** `"all"` when no tab is selected. */
tab: string;
tabId?: string;
- /** Facet id → selected value, `"all"` when unfiltered. */
filters: Record<string, string>;
toggleSort: (id: string) => void;
setSort: (id: string) => void;
diff --git a/packages/ui/src/styles/globals.css b/packages/ui/src/styles/globals.css
index 235b7338..406968eb 100644
--- a/packages/ui/src/styles/globals.css
+++ b/packages/ui/src/styles/globals.css
@@ -2,35 +2,17 @@
@import "tw-animate-css";
@import "shadcn/tailwind.css";
-/*
- * Scan this package's own source so Tailwind generates classes used by the
- * shared components. The path resolves the same whether this file is read in
- * place (packages/ui/src/styles) or through the workspace symlink
- * (node_modules/@crm/ui/src/styles). Consuming apps scan their own files
- * via Tailwind's automatic content detection.
- */
@source "../../**/*.{ts,tsx}";
@custom-variant dark (&:is(.dark *));
:root {
- /*
- * Comp's palette: flat white, neutral greys, one brand green.
- *
- * The greys are deliberately untinted. There is no scene to tint them
- * toward — the brand is "flat white and #006B4F" — and a tinted grey
- * without a reason reads as indecision rather than as a choice.
- */
--background: #ffffff;
--foreground: #171717;
--card: #ffffff;
--card-foreground: #171717;
--popover: #ffffff;
--popover-foreground: #171717;
- /*
- * The brand green, spent on the most-pressed control in the product.
- * White on it measures 6.4:1, so a 13px label clears AA comfortably.
- */
--primary: #006b4f;
--primary-foreground: #ffffff;
--secondary: #f4f4f4;
@@ -39,10 +21,6 @@
--muted-foreground: #6b6b6b;
--accent: #f4f4f4;
--accent-foreground: #171717;
- /*
- * Bricked back from a pure red so it does not read as a holiday pairing
- * next to the green. Still 6.2:1 against white.
- */
--destructive: #ae2e24;
--destructive-foreground: #ffffff;
--success: oklch(0.55 0.13 150);
@@ -53,32 +31,8 @@
--info-foreground: #ffffff;
--border: #e2e2e2;
--input: #e2e2e2;
- /*
- * The scrim behind a modal. A token rather than `bg-black/10` because the
- * two themes need different strengths: 10% black over a near-black page is
- * almost nothing, so a dialog in dark had no separation from the page
- * underneath it.
- */
--overlay: rgb(0 0 0 / 0.18);
- /*
- * Focus is green. It is drawn as a ring outside the control's own border
- * rather than replacing it — a ring that swaps the border out changes the
- * control's apparent size the moment it is focused.
- */
--ring: #006b4f;
- /*
- * Categorical, not a ramp. Deal stages appear as segments of the overview
- * donut with a legend beside it, so adjacent stages have to be told apart —
- * a single-hue green ramp measured ΔE 8.3 between neighbours, which is below
- * the 15 floor at which full-colour vision can separate them.
- *
- * Validated: lightness band, chroma floor, CVD separation, normal-vision
- * floor and contrast all pass against the light surface. Assign in order,
- * never cycle — a stage keeps its hue when the others are filtered out.
- *
- * Slot 1 is a brighter step of the brand green; #006b4f itself measures
- * C 0.096, under the 0.10 chroma floor, so it reads grey in a chart.
- */
--chart-1: #00915f;
--chart-2: #2563eb;
--chart-3: #b45309;
@@ -100,11 +54,6 @@
--sidebar-ring: #006b4f;
--font-sans: var(--font-geist-sans, "Geist", sans-serif);
--font-mono: var(--font-geist-mono, "Geist Mono", monospace);
- /*
- * 5px, down from 10px. Enough to read as deliberately rounded next to the
- * square controls this replaced, tight enough that a dense table does not
- * start looking like a consumer app.
- */
--radius: 5px;
--shadow-x: 0px;
--shadow-y: 1px;
@@ -131,15 +80,6 @@
--card-foreground: #f5f5f5;
--popover: #171717;
--popover-foreground: #f5f5f5;
- /*
- * The same green as light, deliberately. A brand colour that changes value
- * per theme is not one colour, it is two — and both then need maintaining.
- * #006b4f still reads clearly green against near-black, and white on it is
- * unchanged at 6.4:1.
- *
- * This replaces a near-white primary, so a primary button in dark now
- * carries the brand rather than being a light slab.
- */
--primary: #006b4f;
--primary-foreground: #ffffff;
--secondary: #1f1f1f;
@@ -156,33 +96,10 @@
--warning-foreground: oklch(0.205 0 0);
--info: oklch(0.7 0.15 250);
--info-foreground: oklch(0.205 0 0);
- /* Lighter than the background: on near-black there is nothing darker to
- * draw a line with, so a border sits above its surface rather than below. */
--border: #2a2a2a;
- /*
- * The same value as `--border`. A control in dark is a #1f1f1f fill with a
- * #2a2a2a edge — the fill is what separates it from the page, and the edge
- * only has to define where it stops.
- *
- * This is deliberately below the 3:1 non-text contrast guideline. A lighter
- * edge reads as a bright grey outline on every input and filter at once,
- * which is louder than the controls themselves. The fill difference against
- * the page carries the affordance instead.
- */
--input: #2a2a2a;
- /* Much stronger than light: the page it covers is already dark. */
--overlay: rgb(0 0 0 / 0.55);
- /*
- * The one value that does NOT match its light counterpart. #006b4f is too
- * close to near-black to register as a ring at all. A fill carries the
- * brand; a ring only has to be seen, so this one lightens.
- */
--ring: #40be96;
- /*
- * Selected against the dark surface, not flipped from light. The dark
- * lightness band is L 0.48–0.67 — narrower *and* darker than light's
- * 0.43–0.77 — so the light steps do not simply carry over.
- */
--chart-1: #0fa871;
--chart-2: #4b87f0;
--chart-3: #c07e22;
@@ -204,8 +121,6 @@
--sidebar-ring: #40be96;
--font-sans: var(--font-geist-sans, "Geist", sans-serif);
--font-mono: var(--font-geist-mono, "Geist Mono", monospace);
- /* Matches light. The themes disagreed before — 10px against 12px — which
- * meant a control quietly changed shape when the theme was switched. */
--radius: 5px;
--shadow-x: 0px;
--shadow-y: 1px;
@@ -299,13 +214,6 @@
@apply bg-background text-foreground font-sans;
}
- /*
- * Modern, theme-aware scrollbars. Thin, transparent track, with a thumb
- * drawn from the design tokens so it follows light/dark automatically.
- * Firefox uses the standard properties; WebKit/Chromium uses the
- * ::-webkit-scrollbar pseudo-elements. `.no-scrollbar` still wins because
- * it sets `display: none` on the pseudo-element.
- */
* {
scrollbar-width: thin;
scrollbar-color: var(--border) transparent;
@@ -331,14 +239,6 @@
}
}
-/*
- * Bloom — the chart aesthetic (see dashboard-chart.tsx), ported to plain HTML
- * surfaces (status/severity indicators, meters, progress bars).
- *
- * `.bloom-*` adds a soft colored halo via box-shadow; set `--bloom-color` on
- * the element (it defaults to currentColor). Theme-independent, so a meter
- * beside a row matches the plot above it.
- */
@layer utilities {
.bloom-low {
box-shadow: 0 0 4px var(--bloom-color, currentColor);
@@ -353,16 +253,6 @@
}
}
-/*
- * Icon motion — expressive, per-icon hover animation for our Carbon glyphs
- * (see components/icon.tsx). The transform lands on the <svg> itself, so the
- * actual icon geometry moves rather than a wrapping box. A glyph animates when
- * hovered directly or when its nearest interactive ancestor (button, link, menu
- * item) or an opt-in `.icon-hover` container is hovered. Settle motions read
- * from `--cds-hover`; looping/keyframe motions override it while hovered. All of
- * it is gated behind `prefers-reduced-motion` so it disappears for users who ask
- * for less movement.
- */
@layer utilities {
.cds-icon {
transform-origin: center;
@@ -506,13 +396,6 @@
}
}
-/*
- * View transitions. Opt-in: the old snapshot is always hidden (so nothing
- * ghosts or doubles), and the new view appears instantly unless a transition
- * type opts into motion. Persistent chrome (header, icon rail) and the page
- * background never move. Hierarchical navigation (list -> detail) slides
- * forward/back; lateral navigation (rail menus) fades the new content in.
- */
:root {
--duration-exit: 150ms;
--duration-enter: 210ms;
@@ -597,10 +480,6 @@
}
}
-/*
- * Underline-on-hover links. Used by <LineHoverLink>, which picks a variant via
- * the `link-hover--*` modifier; the base class carries the shared geometry.
- */
.link-hover {
cursor: pointer;
position: relative;
@@ -962,25 +841,11 @@
.link-hover *,
.link-hover::before,
.link-hover::after {
- /* biome-ignore lint/complexity/noImportantStyles: reduced-motion reset must override animation declarations */
animation: none !important;
- /* biome-ignore lint/complexity/noImportantStyles: reduced-motion reset must override transition declarations */
transition-duration: 0.01ms !important;
}
}
-/*
- * "It is still here."
- *
- * Re-running a check that fails the same way changes nothing on screen, so the
- * button reads as broken rather than the connection. This replays whenever a
- * check lands on an error that is still the same one — a short nudge plus a
- * ring that fades out, which is enough to say the page did respond without
- * announcing a new problem that has not happened.
- *
- * The ring is the part that carries the message; the nudge is the part that
- * carries the urgency, so only the nudge is dropped under reduced motion.
- */
@keyframes alert-attention-nudge {
0%,
100% {