Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
Enhance AgentPanel and ActivityComposer components for improved user experience
Lewis Carhartb9d290a9cf92
diff --git a/apps/api/src/activities/activities.service.ts b/apps/api/src/activities/activities.service.tsindex 4bef31a3..ab79e75e 100644--- a/apps/api/src/activities/activities.service.ts+++ b/apps/api/src/activities/activities.service.ts@@ -157,9 +157,16 @@ export class ActivitiesService {type: input.type,subject: blankToNull(input.subject ?? ""),body: blankToNull(input.body ?? ""),- // A task is scheduled, not logged; everything else already happened- // unless the composer says otherwise.- occurredAt: isTask ? null : (parseDate(input.occurredAt) ?? new Date()),+ // 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,contactId: input.contactId ?? null,diff --git a/apps/app/app/(app)/deals/create-deal-sheet.tsx b/apps/app/app/(app)/deals/create-deal-sheet.tsxindex 5a8f3878..a45132ab 100644--- a/apps/app/app/(app)/deals/create-deal-sheet.tsx+++ b/apps/app/app/(app)/deals/create-deal-sheet.tsx@@ -2,6 +2,7 @@import Add from "@carbon/icons-react/es/Add";import { Button } from "@crm/ui/components/button";+import { DatePicker } from "@crm/ui/components/date-picker";import {Field,FieldDescription,@@ -204,11 +205,11 @@ export function CreateDealSheet({<Field><FieldLabel htmlFor={closeDateId}>Expected close date</FieldLabel>- <Input+ <DatePickerid={closeDateId}- type="date"value={closeDate}- onChange={(event) => setCloseDate(event.target.value)}+ onChange={setCloseDate}+ placeholder="No date yet"/></Field></FieldGroup>diff --git a/apps/app/components/crm/agent-panel.tsx b/apps/app/components/crm/agent-panel.tsxindex 22acc3e9..72f9f972 100644--- a/apps/app/components/crm/agent-panel.tsx+++ b/apps/app/components/crm/agent-panel.tsx@@ -58,7 +58,12 @@ import {recordFilter,recordHeader,} from "@/lib/agent-record";-import { type ResumeState, readResumeState } from "@/lib/agent-resume";+import {+ composerState,+ eventsOf,+ loadThread,+ type Thread as ThreadState,+} from "@/lib/agent-session";import {NEW_THREAD,pendingQuestion,@@ -150,6 +155,7 @@ export function AgentPanel({ record }: { record: AgentRecord }) {key={openId ?? NEW_THREAD}record={record}conversation={current}+ onNewThread={() => setThread(NEW_THREAD)}/></div>);@@ -163,76 +169,71 @@ export function AgentPanel({ record }: { record: AgentRecord }) {* conversation and rendered it empty, which read as "my history is gone" while* the picker above it showed the thread's own title.*- * The events come from our own `AgentEvent` rows rather than eve's stream:- * they outlive the 30-day session retention, and reading a month-old thread- * should not wake the research runtime.+ * 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({record,conversation,+ onNewThread,}: {record: AgentRecord;conversation: Conversation | null;+ onNewThread: () => void;}) {const trpc = useTRPC();- /**- * Where the session actually got to, asked of the agent rather than the- * database.- *- * A stored continuation token goes stale as soon as a turn finishes with- * this panel unmounted, and eve rejects a stale one — so sending did- * nothing, silently. This reads the live tail instead.- */- const resume = useQuery({- queryKey: ["agent-resume", conversation?.sessionId],+ // 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,+ staleTime: Number.POSITIVE_INFINITY,+ });++ const thread = useQuery<ThreadState>({+ queryKey: ["agent-thread", conversation?.sessionId],+ enabled: conversation !== null && !archive.isPending,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 }) =>- readResumeState(+ loadThread(conversation?.sessionId ?? "",recordHeader(record),+ (archive.data ?? []) as never,signal,),});- const history = useQuery({- ...trpc.conversations.events.queryOptions({ id: conversation?.id ?? "" }),- enabled: conversation !== null,- // **Always refetch on mount.**- //- // Switching tabs unmounts this panel and tears the live stream down with- // it; coming back rebuilds the transcript from here. Cached, that rebuild- // is the transcript as it stood *before* the last answer — which looked- // like "the newest reply is missing until I reload the page", because a- // reload was the only thing clearing the cache.- //- // The events keep arriving in the database while the panel is away, so- // what is on screen after a tab switch is only ever as fresh as this- // fetch. It is one indexed read of a few hundred rows.- staleTime: 0,- refetchOnMount: "always",- // Not on focus, though: clicking back into the window mid-answer would- // refetch a transcript the live stream is already ahead of.- refetchOnWindowFocus: false,- });-- // Same rule as the list: mounting before the events arrive would build the- // projection from nothing and then be unable to add them.- // Only the transcript gates the mount. Whether the session will accept a- // message is a question about the composer, and holding the whole panel on- // a network read of a *streaming* endpoint is how a spinner becomes- // permanent.- if (conversation && history.isPending) return <Loading />;+ // 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}- initialEvents={history.data}- resume={resume.isPending ? { status: "checking" } : resume.data}+ thread={thread.data}+ onNewThread={onNewThread}/>);}@@ -248,13 +249,13 @@ function Loading() {function Thread({record,conversation,- initialEvents,- resume,+ thread,+ onNewThread,}: {record: AgentRecord;conversation: Conversation | null;- initialEvents: unknown[] | undefined;- resume: ResumeState | undefined;+ thread: ThreadState | undefined;+ onNewThread: () => void;}) {const copy = recordCopy(record.kind);// The record travels in a header, which the proxy turns into a token claim@@ -263,33 +264,17 @@ function Thread({// "About contact cmsai6u77… (…): Hey!".const agent = useEveAgent({headers: recordHeader(record),- // Resumes the durable session rather than starting another one. eve keeps- // sessions for 30 days, so last week's thread is still live.+ // 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.//- // `streamIndex: 0` deliberately, not the saved cursor: reopening a thread- // should show what was said in it, and the cursor is where the *last- // reader* stopped. Replaying from the start is what fills the transcript;- // the saved index is only useful to a client that never unmounted.- ...(conversation- ? {- initialSession: {- sessionId: conversation.sessionId,- // The recovered token wins over the stored one, which is only- // as fresh as the last turn this panel watched finish.- continuationToken:- resume?.status === "waiting"- ? resume.continuationToken- : (conversation.continuationToken ?? undefined),- // Where the stream should carry on from. The transcript itself- // comes from `initialEvents`, so this is the tail we have- // already seen rather than a request to replay.- streamIndex: initialEvents?.length ?? 0,- },- initialEvents: (initialEvents ?? []) as NonNullable<- Parameters<typeof useEveAgent>[0]- >["initialEvents"],- }- : {}),+ // 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("");@@ -308,10 +293,10 @@ function Thread({const messages = toTranscript(agent.data.messages);const question = pendingQuestion(agent.data.messages);- // A session that is mid-turn cannot take input, so the composer says so- // rather than swallowing it.- const locked =- busy || resume?.status === "busy" || resume?.status === "checking";+ // 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) => {if (!message.trim() || locked) return;@@ -380,13 +365,32 @@ function Thread({* 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.*/}- {resume?.status === "busy" && !busy ? (+ {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 itfinishes.</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">+ This conversation has ended.+ </p>+ <Button variant="outline" size="sm" onClick={onNewThread}>+ Start a new conversation+ </Button>+ </div>+ ) : null}+<formclassName="flex items-center gap-2 border-t px-5 py-3"onSubmit={(event) => {@@ -438,7 +442,10 @@ function Idle({// tabs beside it rather than like a second product. Only the mark differs —// this one is ours, not a Carbon glyph.return (- <Empty>+ // `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><span className="flex size-8 items-center justify-center bg-foreground text-background">@@ -449,7 +456,7 @@ function Idle({<EmptyDescription>{copy.blurb}</EmptyDescription></EmptyHeader>- <EmptyContent className="flex-row flex-wrap justify-center">+ <EmptyContent layout="row">{copy.suggestions.map((suggestion) => (<Buttonkey={suggestion}@@ -670,7 +677,7 @@ function useSavedConversation({session,messages,}: {- record: { contactId?: string; companyId?: string };+ record: { contactId?: string; companyId?: string; dealId?: string };conversation: Conversation | null;opening: React.RefObject<string | null>;/** `useEveAgent`'s own cursor. */@@ -688,8 +695,16 @@ function useSavedConversation({const sessionId = session?.sessionId ?? null;const token = session?.continuationToken ?? null;const streamIndex = session?.streamIndex ?? 0;- const { contactId, companyId } = record;- const isNew = conversation === null;+ 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@@ -719,6 +734,7 @@ function useSavedConversation({{...(contactId ? { contactId } : {}),...(companyId ? { companyId } : {}),+ ...(dealId ? { dealId } : {}),sessionId,continuationToken: token,streamIndex,@@ -738,5 +754,14 @@ function useSavedConversation({},},);- }, [sessionId, token, streamIndex, messages, contactId, companyId, isNew]);+ }, [+ sessionId,+ token,+ streamIndex,+ messages,+ contactId,+ companyId,+ dealId,+ isNew,+ ]);}diff --git a/apps/app/components/crm/inline-field.tsx b/apps/app/components/crm/inline-field.tsxindex 61de0d9f..86579815 100644--- a/apps/app/components/crm/inline-field.tsx+++ b/apps/app/components/crm/inline-field.tsx@@ -1,6 +1,7 @@"use client";import { Button } from "@crm/ui/components/button";+import { DatePicker } from "@crm/ui/components/date-picker";import { EmptyCellValue } from "@crm/ui/components/empty-cell";import { Input } from "@crm/ui/components/input";import {@@ -192,6 +193,49 @@ 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,+ onSave,+ saving = false,+ placeholder = "—",+}: {+ label: string;+ /** An ISO timestamp or a day string; only the day is read. */+ value: string | null;+ onSave: (next: string) => void;+ saving?: boolean;+ placeholder?: string;+}) {+ const id = useId();++ return (+ <div className={ROW}>+ <label htmlFor={id} className={LABEL}>+ {label}+ </label>+ <div className="flex min-w-0 items-center gap-1.5">+ <DatePicker+ id={id}+ variant="ghost"+ value={value?.slice(0, 10) ?? null}+ placeholder={placeholder}+ onChange={onSave}+ />+ {saving ? <Spinner /> : null}+ </div>+ </div>+ );+}+/** The same row, for a value chosen from a list rather than typed. */export function InlineSelectField({label,diff --git a/apps/app/components/crm/record-sheet/company-sheet.tsx b/apps/app/components/crm/record-sheet/company-sheet.tsxindex 0296d497..34e96718 100644--- a/apps/app/components/crm/record-sheet/company-sheet.tsx+++ b/apps/app/components/crm/record-sheet/company-sheet.tsx@@ -221,6 +221,9 @@ export function CompanySheet({ companyId }: { companyId: string }) {// 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,},]: [];diff --git a/apps/app/components/crm/record-sheet/contact-sheet.tsx b/apps/app/components/crm/record-sheet/contact-sheet.tsxindex 213800ed..956957c5 100644--- a/apps/app/components/crm/record-sheet/contact-sheet.tsx+++ b/apps/app/components/crm/record-sheet/contact-sheet.tsx@@ -135,6 +135,9 @@ export function ContactSheet({ contactId }: { contactId: string }) {// 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,},]: [];diff --git a/apps/app/components/crm/record-sheet/deal-sheet.tsx b/apps/app/components/crm/record-sheet/deal-sheet.tsxindex 34801b53..89ec9489 100644--- a/apps/app/components/crm/record-sheet/deal-sheet.tsx+++ b/apps/app/components/crm/record-sheet/deal-sheet.tsx@@ -8,11 +8,16 @@ import {} from "@crm/ui/components/entity-logo";import { SimpleTable, SimpleTableRow } from "@crm/ui/components/simple-table";import { TableCell } from "@crm/ui/components/table";-import { formatMoney, relativeTimeFromIso } from "@crm/ui/lib/format";+import {+ formatDay,+ formatMoney,+ relativeTimeFromIso,+} from "@crm/ui/lib/format";import { useMutation, useQuery } from "@tanstack/react-query";import { toast } from "sonner";import { AgentPanel } from "@/components/crm/agent-panel";import {+ InlineDateField,InlineField,InlineSelectField,savingField,@@ -46,31 +51,14 @@ 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",year: "numeric",});-/** `2026-07-31` — what `<input type="date">` speaks. */-function toDateInput(iso: string | null): string | null {- return iso ? (iso.slice(0, 10) ?? null) : null;-}--/**- * A close date is a day on a calendar, not an instant.- *- * `new Date("2026-07-16")` is midnight UTC, which is the 15th anywhere west of- * it — so the field read "Jul 15" while the stats strip two inches above it,- * formatting the full timestamp, read "Jul 16". Split the parts and build a- * local date so both agree.- */-function formatDay(value: string): string {- const [year, month, day] = value.split("-").map(Number);- if (!year || !month || !day) return value;- return dateFormat.format(new Date(year, month - 1, day));-}-export function DealSheet({ dealId }: { dealId: string }) {const trpc = useTRPC();const openRecord = useOpenRecord();@@ -103,6 +91,9 @@ export function DealSheet({ dealId }: { dealId: string }) {// 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,},]: [];@@ -163,7 +154,10 @@ export function DealSheet({ dealId }: { dealId: string }) {</DetailSheetStat><DetailSheetStat label="Expected close">{deal.expectedCloseDate ? (- dateFormat.format(new Date(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 />)}@@ -279,16 +273,11 @@ function DealOverview({ deal }: { deal: Deal }) {save({ currency: currency.toUpperCase() });}}/>- <InlineField+ <InlineDateFieldlabel="Close date"- // Edited as `2026-12-31`, which is what a date input speaks, and- // read as "Jul 16, 2026", which is what the stats strip two- // inches above it says.- value={toDateInput(deal.expectedCloseDate)}- placeholder="2026-12-31"+ value={deal.expectedCloseDate}saving={isSaving("expectedCloseDate")}onSave={(next) => save({ expectedCloseDate: next || null })}- render={formatDay}/><InlineSelectFieldlabel="Company"diff --git a/apps/app/components/crm/record-sheet/quick-add.tsx b/apps/app/components/crm/record-sheet/quick-add.tsxindex cf14fee8..a635a2d6 100644--- a/apps/app/components/crm/record-sheet/quick-add.tsx+++ b/apps/app/components/crm/record-sheet/quick-add.tsx@@ -1,6 +1,7 @@"use client";import { Button } from "@crm/ui/components/button";+import { DatePicker } from "@crm/ui/components/date-picker";import { Field, FieldLabel } from "@crm/ui/components/field";import { Input } from "@crm/ui/components/input";import { Spinner } from "@crm/ui/components/spinner";@@ -253,11 +254,11 @@ export function QuickAddDeal({</Field><Field><FieldLabel htmlFor={closeId}>Expected close</FieldLabel>- <Input+ <DatePickerid={closeId}- type="date"value={closeDate}- onChange={(event) => setCloseDate(event.target.value)}+ onChange={setCloseDate}+ placeholder="No date yet"/></Field></QuickAddForm>diff --git a/apps/app/components/crm/timeline/activity-composer.tsx b/apps/app/components/crm/timeline/activity-composer.tsxindex 01cd22e8..61b16167 100644--- a/apps/app/components/crm/timeline/activity-composer.tsx+++ b/apps/app/components/crm/timeline/activity-composer.tsx@@ -1,12 +1,25 @@"use client";-import { Button } from "@crm/ui/components/button";-import { Input } from "@crm/ui/components/input";+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 {+ InputGroup,+ InputGroupAddon,+ InputGroupButton,+ InputGroupTextarea,+} from "@crm/ui/components/input-group";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@crm/ui/components/popover";import { Spinner } from "@crm/ui/components/spinner";-import { Textarea } from "@crm/ui/components/textarea";import { ToggleGroup, ToggleGroupItem } from "@crm/ui/components/toggle-group";import { useMutation } from "@tanstack/react-query";-import { useId, useState } from "react";+import { useState } from "react";import { toast } from "sonner";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";@@ -19,31 +32,47 @@ const TYPES = ["NOTE", "CALL", "EMAIL", "MEETING", "TASK"] as const;type ComposableType = (typeof TYPES)[number];-const SUBJECT_PLACEHOLDER: Partial<Record<ComposableType, string>> = {- CALL: "Discovery call",- EMAIL: "Re: next steps",- MEETING: "Product demo",+const dueFormat = new Intl.DateTimeFormat(undefined, {+ month: "short",+ day: "numeric",+});++const PLACEHOLDER: Record<ComposableType, string> = {+ NOTE: "Log a note, call, email, meeting or task…",+ CALL: "What came out of the call?",+ EMAIL: "What was said?",+ MEETING: "What came out of the meeting?",+ TASK: "What needs doing?",};/**- * Logging what just happened, in one field that is always there.+ * Logging what just happened: one box, and a toolbar inside it.*- * There used to be an `open` boolean: the panel showed a button pretending to- * be an input, and clicking it swapped in a form four times the height. Two- * problems, and the second is the one that mattered. Reading the timeline is- * what people come here for, and the expanded form pushed the first entry off- * the fold — so the state you were left in after logging one note was the state- * that hid the history. The click was the tax; the mode was the bug.+ * Two rewrites got here, and both of the things it replaced are worth naming.*- * Now there is no mode. One line of textarea sits at the top, `field-sizing`- * grows it as you type, and the things that only matter once you have started —- * what kind of thing this is, its subject, when it is due — appear underneath- * when there is something to attach them to. Empty, the whole composer is- * shorter than the button that used to open it.+ * 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.*- * What is left in `useState` is the draft itself, which is the one thing that- * genuinely belongs there: a half-written note about a customer has no business- * in the URL, where `record-stack` keeps the rest of this panel's state.+ * 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();@@ -51,26 +80,14 @@ export function ActivityComposer({ anchor }: { anchor: TimelineAnchor }) {const [type, setType] = useState<ComposableType>("NOTE");const [draft, setDraft] = useState("");- const [subject, setSubject] = useState("");- const [dueAt, setDueAt] = useState("");-- const subjectId = useId();- const dueId = useId();+ const [dueAt, setDueAt] = useState<Date | undefined>(undefined);const isTask = type === "TASK";-- // One rule for every type: the box you typed in holds the point of the- // entry. For a task that is what needs doing, so it lands in `subject`;- // for everything else it is the body. The old form asked a different- // question per type and then disagreed with itself about which one made the- // submit button live.const text = draft.trim();- const started = text !== "";const reset = () => {setDraft("");- setSubject("");- setDueAt("");+ setDueAt(undefined);};const create = useMutation(@@ -84,97 +101,112 @@ export function ActivityComposer({ anchor }: { anchor: TimelineAnchor }) {);const submit = () => {- if (!started || create.isPending) return;+ if (text === "" || create.isPending) return;create.mutate({...anchor,type,- subject: isTask ? text : subject || undefined,+ subject: isTask ? text : undefined,body: isTask ? undefined : text,- dueAt: isTask ? dueAt || null : undefined,+ dueAt: isTask ? (dueAt?.toISOString() ?? null) : undefined,});};return (<form- className="flex flex-col gap-2"onSubmit={(event) => {event.preventDefault();submit();}}>- <Textarea- size="sm"- value={draft}- onChange={(event) => setDraft(event.target.value)}- placeholder="Log a note, call, email, meeting or task…"- aria-label="What happened"- onKeyDown={(event) => {- // Submit without leaving the keyboard. Plain Enter has to stay a- // newline — this is the field a three-paragraph call note goes in.- if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {- event.preventDefault();- submit();- }- if (event.key === "Escape") reset();- }}- />+ <InputGroup>+ <InputGroupTextarea+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ 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();+ }+ if (event.key === "Escape") reset();+ }}+ />++ <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}+ onValueChange={(next) => next && setType(next as ComposableType)}+ size="sm"+ spacing={0}+ >+ {TYPES.map((option) => (+ <ToggleGroupItem+ key={option}+ value={option}+ aria-label={activityLabel(option)}+ >+ <ActivityIcon type={option} />+ {activityLabel(option)}+ </ToggleGroupItem>+ ))}+ </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>+ <InputGroupButton variant="ghost" size="xs">+ <Icon icon={Calendar} data-icon="inline-start" />+ {dueAt ? dueFormat.format(dueAt) : "Due date"}+ </InputGroupButton>+ </PopoverTrigger>+ <PopoverContent size="fit" align="start">+ <DayPicker+ mode="single"+ selected={dueAt}+ onSelect={setDueAt}+ autoFocus+ />+ </PopoverContent>+ </Popover>+ ) : null}- {started ? (- <>- <div className="flex flex-wrap items-center justify-between gap-2">- <ToggleGroup- type="single"- value={type}- onValueChange={(next) => next && setType(next as ComposableType)}- variant="outline"- size="sm"+ {/*+ * 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"+ variant="default"+ size="xs"+ className="ml-auto"+ disabled={create.isPending}>- {TYPES.map((option) => (- <ToggleGroupItem- key={option}- value={option}- aria-label={activityLabel(option)}- >- <ActivityIcon type={option} />- {activityLabel(option)}- </ToggleGroupItem>- ))}- </ToggleGroup>-- <Button type="submit" size="sm" disabled={create.isPending}>{create.isPending ? <Spinner /> : null}{isTask ? "Add task" : `Log ${activityLabel(type).toLowerCase()}`}- </Button>- </div>-- {isTask ? (- <div className="flex flex-wrap items-center gap-2">- <label htmlFor={dueId} className="text-muted-foreground text-xs">- Due- </label>- {/* A width on the wrapper, not on the control: `Input` is- `w-full` by design and a date is eight characters wide. */}- <div className="w-40">- <Input- id={dueId}- type="date"- value={dueAt}- onChange={(event) => setDueAt(event.target.value)}- />- </div>- </div>- ) : SUBJECT_PLACEHOLDER[type] ? (- <Input- id={subjectId}- value={subject}- onChange={(event) => setSubject(event.target.value)}- placeholder={SUBJECT_PLACEHOLDER[type]}- aria-label="Subject"- autoComplete="off"- />- ) : null}- </>- ) : null}+ </InputGroupButton>+ )}+ </InputGroupAddon>+ </InputGroup></form>);}diff --git a/apps/app/components/crm/timeline/timeline-entry.tsx b/apps/app/components/crm/timeline/timeline-entry.tsxindex 92aa54f9..2362d59a 100644--- a/apps/app/components/crm/timeline/timeline-entry.tsx+++ b/apps/app/components/crm/timeline/timeline-entry.tsx@@ -3,6 +3,7 @@import { Checkbox } from "@crm/ui/components/checkbox";import { StatusIndicator } from "@crm/ui/components/status-indicator";import { relativeTimeFromIso } from "@crm/ui/lib/format";+import { cn } from "@crm/ui/lib/utils";import { useMutation } from "@tanstack/react-query";import { toast } from "sonner";import { dealStageLabel } from "@/components/crm/deal-stage";@@ -13,6 +14,7 @@ import type { RouterOutputs } from "@/lib/trpc/types";import { ActivityIcon, activityLabel } from "./activity-icon";import { EmailThreadEntry } from "./email-thread-entry";import { MeetingEntry } from "./meeting-entry";+import type { TimelineAnchor } from "./timeline";export type TimelineEntryData =RouterOutputs["activities"]["timeline"]["entries"][number];@@ -29,13 +31,39 @@ function stageChange(meta: Record<string, unknown> | 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,- /** Hide the deal/contact chips on that record's own timeline. */- showContext = true,+ anchor,}: {entry: TimelineEntryData;- showContext?: boolean;+ anchor: TimelineAnchor;}) {const trpc = useTRPC();const cache = useCrmCache();@@ -67,9 +95,24 @@ export function TimelineEntry({: "via Calendar": entry.createdBy.name;+ const headline = change+ ? `${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 =+ entry.contact && entry.contact.id !== here ? entry.contact : null;++ const footnotes = Boolean(+ deal || contact || (isTask && !done && entry.dueAt),+ );+return (<li className="flex gap-2.5 py-2">- <span className="mt-0.5 text-muted-foreground">+ <span className="mt-0.5 shrink-0 text-muted-foreground">{isTask ? (<Checkboxchecked={done}@@ -80,52 +123,60 @@ export function TimelineEntry({}/>) : (- <ActivityIcon type={entry.type} />+ <span role="img" aria-label={activityLabel(entry.type)}>+ <ActivityIcon type={entry.type} />+ </span>)}</span>- <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">- <span className="font-medium text-xs">- {change- ? `${dealStageLabel(change.from as never)} → ${dealStageLabel(change.to as never)}`- : (entry.subject ?? activityLabel(entry.type))}- </span>+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <div className="flex min-w-0 items-baseline gap-3">+ <div className="min-w-0 flex-1 space-y-0.5">+ {headline ? (+ <p+ className={cn(+ "wrap-anywhere font-medium",+ done && "text-muted-foreground line-through",+ )}+ >+ {headline}+ </p>+ ) : null}- {overdue ? (- <StatusIndicator- tone="error"- label={`Overdue ${relativeTimeFromIso(entry.dueAt)}`}- />- ) : isTask && !done && entry.dueAt ? (- <StatusIndicator- tone="info"- label={`Due ${relativeTimeFromIso(entry.dueAt)}`}- />- ) : null}+ {entry.body ? (+ <p+ className={cn(+ "whitespace-pre-wrap text-pretty wrap-anywhere",+ headline && "text-muted-foreground",+ )}+ >+ {entry.body}+ </p>+ ) : null}- <span className="text-muted-foreground text-xs">{author}</span>+ {/* 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)}+ </p>+ ) : null}+ </div>{/*- * Pushed to the right edge, so the times form a column you can run- * your eye down instead of sitting at a different offset on every- * row. Same place `ThreadMessage` puts it.- *- * The thread's message count used to live here too, next to a- * timestamp that *is* its last message — and directly above an- * accordion whose label is the same count.+ * 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="ml-auto shrink-0 text-muted-foreground text-xs tabular-nums">- {timeFormat.format(new Date(when))}+ <span className="shrink-0 text-muted-foreground">+ <span className="hidden sm:inline">{author} · </span>+ <span className="tabular-nums">+ {timeFormat.format(new Date(when))}+ </span></span></div>- {entry.body ? (- <p className="whitespace-pre-wrap text-pretty text-muted-foreground text-xs/5">- {entry.body}- </p>- ) : null}-{entry.calendarEvent ? (<MeetingEntryeventId={entry.calendarEvent.id}@@ -144,16 +195,34 @@ export function TimelineEntry({/>) : null}- {showContext && (entry.deal || entry.contact) ? (- <div className="flex flex-wrap items-center gap-3 text-xs">- {entry.deal ? (- <RecordLink kind="deal" id={entry.deal.id}>- {entry.deal.name}+ {/*+ * 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 ? (+ <StatusIndicator+ tone="error"+ label={`Overdue ${relativeTimeFromIso(entry.dueAt)}`}+ />+ ) : isTask && !done && entry.dueAt ? (+ <StatusIndicator+ tone="info"+ label={`Due ${relativeTimeFromIso(entry.dueAt)}`}+ />+ ) : null}++ {deal ? (+ <RecordLink kind="deal" id={deal.id}>+ {deal.name}</RecordLink>) : null}- {entry.contact ? (- <RecordLink kind="contact" id={entry.contact.id}>- {[entry.contact.firstName, entry.contact.lastName]++ {contact ? (+ <RecordLink kind="contact" id={contact.id}>+ {[contact.firstName, contact.lastName].filter(Boolean).join(" ")}</RecordLink>diff --git a/apps/app/components/crm/timeline/timeline.tsx b/apps/app/components/crm/timeline/timeline.tsxindex 916028ea..f4e64bbf 100644--- a/apps/app/components/crm/timeline/timeline.tsx+++ b/apps/app/components/crm/timeline/timeline.tsx@@ -163,9 +163,11 @@ function byDay(entries: TimelineEntryData[]) {function TimelineDay({label,entries,+ anchor,}: {label: string;entries: TimelineEntryData[];+ anchor: TimelineAnchor;}) {return (<section>@@ -174,7 +176,7 @@ function TimelineDay({</h3><ul className="divide-y">{entries.map((entry) => (- <TimelineEntry key={entry.id} entry={entry} />+ <TimelineEntry key={entry.id} entry={entry} anchor={anchor} />))}</ul></section>@@ -224,9 +226,15 @@ export function Timeline({ anchor }: { anchor: TimelineAnchor }) {<div className="flex min-h-0 flex-1 flex-col">{/* One band of controls, then history. Two stacked bordered bands pushthe first entry off the fold on a laptop. */}- <div className="flex shrink-0 flex-col gap-3 border-b px-5 py-3">+ <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.+ */}<ToggleGrouptype="single"value={tab}@@ -235,8 +243,8 @@ export function Timeline({ anchor }: { anchor: TimelineAnchor }) {// a timeline with no filter at all is not a state it has.if (next) void setTab(next as TimelineTab);}}- variant="outline"size="sm"+ spacing={0}>{TIMELINE_TABS.map((option) => (<ToggleGroupItem key={option} value={option}>@@ -268,7 +276,11 @@ export function Timeline({ anchor }: { anchor: TimelineAnchor }) {) : (<div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-5 pb-4">{pinnedEntries.length > 0 ? (- <TimelineDay label="Outstanding" entries={pinnedEntries} />+ <TimelineDay+ label="Outstanding"+ entries={pinnedEntries}+ anchor={anchor}+ />) : null}{byDay(entries).map((group) => (@@ -276,6 +288,7 @@ export function Timeline({ anchor }: { anchor: TimelineAnchor }) {key={group.day}label={group.label}entries={group.entries}+ anchor={anchor}/>))}diff --git a/apps/app/components/detail-sheet.tsx b/apps/app/components/detail-sheet.tsxindex c15e0278..88b9bcb0 100644--- a/apps/app/components/detail-sheet.tsx+++ b/apps/app/components/detail-sheet.tsx@@ -27,7 +27,7 @@ import {TooltipTrigger,} from "@crm/ui/components/tooltip";import { cn } from "@crm/ui/lib/utils";-import { type ReactNode, useRef } from "react";+import { type ReactNode, useRef, useState } from "react";import {Sheet,SheetContent,@@ -233,6 +233,25 @@ export type DetailSheetTab = {/** 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;};/**@@ -252,6 +271,11 @@ 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);+return (<Tabsvalue={value}@@ -289,7 +313,14 @@ export function DetailSheetTabs({<TabsContentkey={tab.value}value={tab.value}- className="flex min-h-0 flex-1 flex-col overflow-hidden outline-none"+ 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}</TabsContent>diff --git a/apps/app/lib/agent-resume.ts b/apps/app/lib/agent-resume.tsdeleted file mode 100644index 36883257..00000000--- a/apps/app/lib/agent-resume.ts+++ /dev/null@@ -1,199 +0,0 @@-/**- * Picking a conversation back up.- *- * A stored continuation token goes stale the moment a turn finishes without- * this panel watching — which is the normal case, because switching tabs- * unmounts it. eve is explicit about the consequence: *only waiting sessions- * can accept the next user input*, and a stale token is rejected. Sending into- * one does nothing at all, which is exactly what it looked like.- *- * So the token is recovered from the session's own tail rather than trusted- * from the database, following eve's documented recipe for "if you only- * persisted `sessionId`": read the newest durable event and take the token off- * `session.waiting`.- */--export type ResumeState =- | {- /** The tail has not come back yet. Briefly, on opening an old thread. */- status: "checking";- }- | {- /** Parked and ready for the next message. */- status: "waiting";- continuationToken: string | undefined;- }- | {- /** Mid-turn. It cannot accept input yet, and saying so beats silence. */- status: "busy";- }- | {- /** Over. The next message starts a fresh session, per eve's contract. */- status: "finished";- };--/**- * The resume state, read off the tail of a session's event stream.- *- * The endpoint answers newline-delimited JSON, and a tail read can return more- * than one line, so the *last* parseable event is the one that counts.- */-/**- * How quiet a turn has to go before it counts as dead rather than working.- *- * A running turn emits constantly — reasoning deltas, steps, tool results — so- * a gap this long means the run ended without a boundary: the process was- * restarted, or the deploy rolled. Those sessions never reach- * `session.waiting`, and without this they would read as "busy" forever and- * lock the composer on a conversation that can never answer again.- */-const ABANDONED_AFTER_MS = 90_000;--export function parseResumeTail(- ndjson: string,- now: number = Date.now(),-): ResumeState {- const last = lastEvent(ndjson);-- if (!last) return { status: "busy" };-- if (last.type === "session.waiting") {- const token = (last.data as { continuationToken?: unknown } | undefined)- ?.continuationToken;-- return {- status: "waiting",- continuationToken: typeof token === "string" ? token : undefined,- };- }-- if (last.type === "session.completed" || last.type === "session.failed") {- return { status: "finished" };- }-- // Anything else — a step, a tool result, a token of reasoning — means a turn- // is in flight, *if* it is still moving. One that stopped mid-sentence is- // over, whatever it was doing, and the next message starts a new session.- return now - last.at > ABANDONED_AFTER_MS- ? { status: "finished" }- : { status: "busy" };-}--function lastEvent(- ndjson: string,-): { type: string; data?: unknown; at: number } | null {- let found: { type: string; data?: unknown; at: number } | null = null;-- for (const line of ndjson.split("\n")) {- const trimmed = line.trim();- if (!trimmed) continue;-- try {- const event = JSON.parse(trimmed) as {- type?: unknown;- data?: unknown;- meta?: { at?: unknown };- };- if (typeof event.type === "string") {- const at =- typeof event.meta?.at === "string"- ? Date.parse(event.meta.at)- : Number.NaN;-- found = {- type: event.type,- data: event.data,- // An event with no readable timestamp is treated as current, so a- // missing field never retires a live session.- at: Number.isNaN(at) ? Date.now() : at,- };- }- } catch {- // A tail read can slice a line in half. Skip it rather than give up on- // the ones that did arrive whole.- }- }-- return found;-}--/**- * How long to wait for the tail before assuming the session is busy.- *- * This read is against a *stream* endpoint. On a session that is mid-turn it- * does not return — it keeps delivering events as they happen — so without a- * deadline the panel waits forever on a question whose answer is already- * "busy". Reading for a moment and taking what arrived is both faster and the- * same answer.- */-const TAIL_TIMEOUT_MS = 4000;--/**- * Asks the agent where a session got to.- *- * Goes through the app's own `/eve/v1` proxy, so it carries the session cookie- * and needs no agent credentials of its own.- *- * Never throws and never resolves to "ready" on doubt: a wrong `waiting` sends- * somebody's message into a void, while a wrong `busy` only asks them to try- * again in a moment.- */-export async function readResumeState(- sessionId: string,- headers: Record<string, string>,- signal?: AbortSignal,-): Promise<ResumeState> {- const deadline = AbortSignal.timeout(TAIL_TIMEOUT_MS);- const abort = signal ? AbortSignal.any([signal, deadline]) : deadline;-- try {- const response = await fetch(- `/eve/v1/session/${encodeURIComponent(sessionId)}/stream?startIndex=-1&includeTailIndex=1`,- { headers, signal: abort },- );-- if (!response.ok || !response.body) return { status: "busy" };-- return parseResumeTail(await firstLine(response.body));- } catch {- // Timed out, aborted, or the agent is down. All of them mean "do not- // promise this session will accept a message".- return { status: "busy" };- }-}--/**- * The first line of the stream, and then stop reading.- *- * This endpoint **follows**: it keeps the connection open and delivers events- * as they happen, and `includeTailIndex` is a header for the *client* to stop- * on, not an instruction to the server to close. Awaiting the whole body- * therefore waits forever — which read as "every session is busy", because the- * deadline fired every time and the composer was never unlocked.- *- * `startIndex=-1` asks for the newest event, so the first complete line is the- * whole answer. Take it and hang up.- */-async function firstLine(body: ReadableStream<Uint8Array>): Promise<string> {- const reader = body.getReader();- const decoder = new TextDecoder();- let buffer = "";-- try {- while (true) {- const { done, value } = await reader.read();- if (done) break;-- buffer += decoder.decode(value, { stream: true });-- const newline = buffer.indexOf("\n");- if (newline !== -1) return buffer.slice(0, newline);- }- } finally {- // Nothing else is coming out of this stream, and leaving it open holds a- // request against the agent for the life of the page.- await reader.cancel().catch(() => {});- }-- return buffer;-}diff --git a/apps/app/lib/agent-session.ts b/apps/app/lib/agent-session.tsnew file mode 100644index 00000000..0da22051--- /dev/null+++ b/apps/app/lib/agent-session.ts@@ -0,0 +1,167 @@+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>,+ archive: readonly MessageStreamEvent[] = [],+ 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 });++ return {+ status: classify(snapshot.session, snapshot.events),+ session: snapshot.session,+ events: snapshot.events,+ } as Thread;+ } catch {+ return { status: "offline", events: archive };+ }+}++/**+ * 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);+ if (!last) return "ended";++ if (last.type === "session.completed" || last.type === "session.failed") {+ 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+ ? "working"+ : "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,+): ComposerState {+ const ended = thread?.status === "ended";++ 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.tsindex 323fef11..6436b555 100644--- a/apps/app/lib/agent-transcript.ts+++ b/apps/app/lib/agent-transcript.ts@@ -30,7 +30,18 @@ export type Source = {network: "linkedin" | "github" | "web";};-/** Tool slugs are for the model; these lines are for a person. */+/**+ * 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",resolve_linkedin_profile: "Searched for their LinkedIn profile",@@ -47,8 +58,36 @@ const VERBS: Record<string, string> = {schedule_recheck: "Decided when to look again",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",+ todo: "Updated its plan",+ ask_question: "Asked a question",+ agent: "Handed part of the job to a helper",+ connection_search: "Looked for a tool it could use",+ bash: "Ran a command",+ read_file: "Read a file",+ write_file: "Wrote a file",+ glob: "Looked for files",+ 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;@@ -127,9 +166,12 @@ 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 {const tool = toolName(part);- const verb = VERBS[tool] ?? tool.replace(/_/g, " ");+ const verb = VERBS[tool] ?? humanise(tool);const reason = output(part)?.reason;// The reason a write did not happen is the interesting half.diff --git a/apps/app/test/agent-resume.spec.ts b/apps/app/test/agent-resume.spec.tsdeleted file mode 100644index 5c5f45d4..00000000--- a/apps/app/test/agent-resume.spec.ts+++ /dev/null@@ -1,179 +0,0 @@-import { describe, expect, it } from "bun:test";-import { readFileSync } from "node:fs";-import { recordCopy, recordFilter, recordHeader } from "../lib/agent-record";-import { parseResumeTail } from "../lib/agent-resume";--/**- * Picking a conversation back up.- *- * The bug these exist for: sending into a resumed thread did nothing at all.- * eve only accepts input on a *waiting* session, and the token we had stored- * was from before the last turn ended — so the send was rejected in silence.- */--const NOW = Date.parse("2026-08-01T12:00:00.000Z");--const line = (- type: string,- data: unknown = {},- at: string = "2026-08-01T12:00:00.000Z",-) => JSON.stringify({ type, data, meta: { id: `evt_${type}`, at } });--describe("parseResumeTail", () => {- it("recovers the current token from a waiting session", () => {- const state = parseResumeTail(- line("session.waiting", { continuationToken: "eve:fresh" }),- NOW,- );-- expect(state).toEqual({- status: "waiting",- continuationToken: "eve:fresh",- });- });-- it("reads a mid-turn session as busy rather than ready", () => {- // This is the exact case that swallowed a message: the turn was still- // running, so nothing could be accepted.- expect(parseResumeTail(line("actions.requested"), NOW)).toEqual({- status: "busy",- });- expect(parseResumeTail(line("reasoning.appended"), NOW)).toEqual({- status: "busy",- });- });-- it("retires a turn that stopped mid-sentence instead of locking on it", () => {- // A restarted agent leaves sessions with no closing boundary. They never- // reach `session.waiting`, so without this they read as busy forever and- // the composer can never be used on that thread again.- const abandoned = line(- "reasoning.appended",- {},- "2026-08-01T11:50:00.000Z",- );-- expect(parseResumeTail(abandoned, NOW)).toEqual({ status: "finished" });- });-- it("does not retire a turn that is merely between events", () => {- const recent = line("step.started", {}, "2026-08-01T11:59:30.000Z");-- expect(parseResumeTail(recent, NOW)).toEqual({ status: "busy" });- });-- it("never retires a live session for want of a timestamp", () => {- const noMeta = JSON.stringify({ type: "actions.requested", data: {} });-- expect(parseResumeTail(noMeta, NOW)).toEqual({ status: "busy" });- });-- it("knows a finished session cannot be continued", () => {- // eve resets local state on these, and the next send starts fresh.- expect(parseResumeTail(line("session.completed"), NOW)).toEqual({- status: "finished",- });- expect(parseResumeTail(line("session.failed"), NOW)).toEqual({- status: "finished",- });- });-- it("takes the last event when the tail returns several", () => {- const state = parseResumeTail(- [- line("step.completed"),- line("turn.completed"),- line("session.waiting", { continuationToken: "eve:last" }),- ].join("\n"),- NOW,- );-- expect(state).toEqual({ status: "waiting", continuationToken: "eve:last" });- });-- it("survives a half-written line, which a tail read can produce", () => {- const state = parseResumeTail(- `${line("session.waiting", { continuationToken: "eve:whole" })}\n{"type":"acti`,- NOW,- );-- expect(state).toEqual({- status: "waiting",- continuationToken: "eve:whole",- });- });-- it("treats an empty or unreadable tail as busy, never as ready", () => {- // Failing closed: a wrong "ready" sends a message into a void, a wrong- // "busy" only asks somebody to try again.- expect(parseResumeTail("", NOW)).toEqual({ status: "busy" });- expect(parseResumeTail("not json at all", NOW)).toEqual({ status: "busy" });- });-- it("does not invent a token a waiting session did not carry", () => {- expect(parseResumeTail(line("session.waiting"), NOW)).toEqual({- status: "waiting",- continuationToken: undefined,- });- });-});--describe("record context", () => {- it("asks about the thing you are actually looking at", () => {- expect(recordCopy("contact").title).toBe("Ask about this person");- expect(recordCopy("company").title).toBe("Ask about this company");- expect(recordCopy("deal").title).toBe("Ask about this deal");- });-- 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?");- });-- it("tells the agent which record it is on", () => {- expect(recordHeader({ kind: "contact", id: "c1" })).toEqual({- "x-crm-contact": "c1",- });- expect(recordHeader({ kind: "company", id: "co1" })).toEqual({- "x-crm-company": "co1",- });- expect(recordHeader({ kind: "deal", id: "d1" })).toEqual({- "x-crm-deal": "d1",- });- });-- it("files a conversation under one record and no other", () => {- expect(recordFilter({ kind: "deal", id: "d1" })).toEqual({ dealId: "d1" });- expect(Object.keys(recordFilter({ kind: "company", id: "co1" }))).toEqual([- "companyId",- ]);- });-});--describe("the panel's copy", () => {- /**- * 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("comes from the record, never from a literal in the component", () => {- const source = readFileSync(- new URL("../components/crm/agent-panel.tsx", import.meta.url),- "utf8",- );-- // Anything user-facing and record-specific belongs in `agent-record.ts`.- for (const kind of ["contact", "company", "deal"] as const) {- const copy = recordCopy(kind);- for (const literal of [copy.title, copy.blurb, copy.placeholder]) {- expect(source).not.toContain(literal);- }- }- });-});diff --git a/apps/app/test/agent-session.spec.ts b/apps/app/test/agent-session.spec.tsnew file mode 100644index 00000000..5fd9e5f6--- /dev/null+++ b/apps/app/test/agent-session.spec.ts@@ -0,0 +1,229 @@+import { describe, expect, it } from "bun:test";+import { readFileSync } from "node:fs";+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 = (+ type: string,+ at: string = "2026-08-01T12:00:00.000Z",+): MessageStreamEvent =>+ ({ type, data: {}, meta: { id: `evt_${type}`, at } }) as MessageStreamEvent;++const parked: SessionState = {+ sessionId: "wrun_1",+ continuationToken: "eve:live",+ streamIndex: 3,+};++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");+ });++ it("knows a terminal session cannot be continued", () => {+ expect(classify(unparked, [event("session.completed")], NOW)).toBe("ended");+ expect(classify(unparked, [event("session.failed")], NOW)).toBe("ended");+ });++ it("reads a turn still emitting as working", () => {+ const recent = event("message.appended", "2026-08-01T11:59:30.000Z");++ expect(classify(unparked, [recent], NOW)).toBe("working");+ });++ 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");+ });++ it("does not retire a live turn for want of a timestamp", () => {+ const undated = { type: "step.started", data: {}, meta: { id: "x" } };++ expect(classify(unparked, [undated as MessageStreamEvent], NOW)).toBe(+ "working",+ );+ });+});++describe("the composer", () => {+ it("takes input on a parked thread, and on one not started yet", () => {+ expect(+ composerState({ status: "ready", session: parked, events: [] }, false),+ ).toEqual({ locked: false, ended: false });+ expect(composerState({ status: "new" }, false)).toEqual({+ locked: false,+ ended: false,+ });+ expect(composerState(undefined, false)).toEqual({+ locked: false,+ ended: false,+ });+ });++ 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,+ ).toBe(true);+ expect(+ composerState(+ { status: "working", session: unparked, events: [] },+ false,+ ),+ ).toEqual({ locked: true, ended: false });+ });++ 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,+ });+ });+});++describe("eventsOf", () => {+ it("renders the transcript in every state that has one", () => {+ const events = [event("message.completed")];++ expect(eventsOf({ status: "offline", events })).toEqual(events);+ expect(eventsOf({ status: "ended", session: unparked, events })).toEqual(+ events,+ );+ expect(eventsOf({ status: "new" })).toEqual([]);+ expect(eventsOf(undefined)).toEqual([]);+ });+});++describe("record context", () => {+ it("asks about the thing you are actually looking at", () => {+ expect(recordCopy("contact").title).toBe("Ask about this person");+ expect(recordCopy("company").title).toBe("Ask about this company");+ expect(recordCopy("deal").title).toBe("Ask about this deal");+ });++ 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?");+ });++ it("tells the agent which record it is on", () => {+ expect(recordHeader({ kind: "contact", id: "c1" })).toEqual({+ "x-crm-contact": "c1",+ });+ expect(recordHeader({ kind: "company", id: "co1" })).toEqual({+ "x-crm-company": "co1",+ });+ expect(recordHeader({ kind: "deal", id: "d1" })).toEqual({+ "x-crm-deal": "d1",+ });+ });++ it("files a conversation under one record and no other", () => {+ expect(recordFilter({ kind: "deal", id: "d1" })).toEqual({ dealId: "d1" });+ expect(Object.keys(recordFilter({ kind: "company", id: "co1" }))).toEqual([+ "companyId",+ ]);+ });+});++describe("the panel", () => {+ const source = () =>+ readFileSync(+ new URL("../components/crm/agent-panel.tsx", import.meta.url),+ "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);+ for (const literal of [copy.title, copy.blurb, copy.placeholder]) {+ expect(source()).not.toContain(literal);+ }+ }+ });++ 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(+ new URL(+ `../components/crm/record-sheet/${sheet}-sheet.tsx`,+ import.meta.url,+ ),+ "utf8",+ );++ expect(source).toContain("keepMounted: true");+ }++ const sheet = readFileSync(+ new URL("../components/detail-sheet.tsx", import.meta.url),+ "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.tsindex 6c77f5c9..9dd3c578 100644--- a/apps/app/test/agent-transcript.spec.ts+++ b/apps/app/test/agent-transcript.spec.ts@@ -1,4 +1,5 @@import { describe, expect, it } from "bun:test";+import { readdirSync } from "node:fs";import type { EveMessage } from "eve/react";import {describe as describeStep,@@ -7,6 +8,7 @@ import {pendingQuestion,resolveThread,sourcesOf,+ TOOL_VERBS,toTranscript,} from "../lib/agent-transcript";@@ -119,7 +121,10 @@ describe("describe", () => {});it("falls back to a readable form of an unknown tool", () => {- expect(describeStep(tool("some_new_tool") as never)).toBe("some new 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");});});@@ -314,3 +319,47 @@ describe("resolveThread", () => {expect(current).toBeNull();});});++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",+ "web_fetch",+ "todo",+ "ask_question",+ "agent",+ "connection_search",+ "bash",+ "read_file",+ "write_file",+ "glob",+ "grep",+ ];++ const authored = readdirSync(+ new URL("../../agent/agent/tools", import.meta.url),+ )+ .filter((file) => file.endsWith(".ts"))+ .map((file) => file.replace(/\.ts$/, ""));++ it("covers every tool the agent ships with", () => {+ expect(authored.length).toBeGreaterThan(0);++ for (const tool of [...authored, ...BUILT_INS]) {+ expect(TOOL_VERBS[tool]).toBeString();+ }+ });++ it("writes them as sentences, not as slugs", () => {+ for (const [tool, verb] of Object.entries(TOOL_VERBS)) {+ expect(verb, tool).not.toContain("_");+ expect(verb[0], tool).toBe(verb[0]?.toUpperCase() ?? "");+ }+ });+});diff --git a/apps/app/test/day.spec.ts b/apps/app/test/day.spec.tsnew file mode 100644index 00000000..c20ea983--- /dev/null+++ b/apps/app/test/day.spec.ts@@ -0,0 +1,39 @@+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");+ });++ it("pads single-digit months and days", () => {+ expect(toDay(new Date(2026, 0, 5))).toBe("2026-01-05");+ });++ 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);+ });++ it("has nothing to show for nothing", () => {+ expect(fromDay(null)).toBeUndefined();+ expect(fromDay("")).toBeUndefined();+ expect(fromDay("someday")).toBeUndefined();+ expect(formatDay(null)).toBe("—");+ });+});diff --git a/bun.lock b/bun.lockindex 31ece402..e888b78c 100644--- a/bun.lock+++ b/bun.lock@@ -162,10 +162,12 @@"class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",+ "date-fns": "^4.4.0","lucide-react": "^1.28.0","next-themes": "^0.4.6","nuqs": "^2.8.9","radix-ui": "^1.6.0",+ "react-day-picker": "^10.0.1","recharts": "3.8.0","sonner": "^2.0.7","streamdown": "^2.5.0",@@ -341,6 +343,8 @@"@crm/ui": ["@crm/ui@workspace:packages/ui"],+ "@date-fns/tz": ["@date-fns/[email protected]", "", {}, "sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg=="],+"@dotenvx/dotenvx": ["@dotenvx/[email protected]", "", { "dependencies": { "@dotenvx/primitives": "^0.8.0", "commander": "^11.1.0", "conf": "^10.2.0", "dotenv": "^17.2.1", "enquirer": "^2.4.1", "env-paths": "^2.2.1", "execa": "^5.1.1", "fdir": "^6.2.0", "ignore": "^5.3.0", "object-treeify": "1.1.33", "open": "^8.4.2", "picomatch": "^4.0.4", "systeminformation": "^5.22.11", "undici": "^7.11.0", "which": "^4.0.0", "yocto-spinner": "^1.1.0" }, "bin": { "dotenvx": "src/cli/dotenvx.js" } }, "sha512-/BITOC9dmS/edY2zQwZNicQ059O6RKabtQfyEafV0nGtfYRNHYy1DIPiYVcov40+tob9hfmBnbR963dS+EQ1DQ=="],"@dotenvx/primitives": ["@dotenvx/[email protected]", "", {}, "sha512-VYJy0uhFm9zTJ1TxBaW/pA8bjbOM/OttaNMwZ1RHG4JKyRG7DhSdiqD1ipQoAyoD22olUtxbP78W9xY3Wd11bg=="],@@ -1175,6 +1179,8 @@"dagre-d3-es": ["[email protected]", "", { "dependencies": { "d3": "^7.9.0", "lodash-es": "^4.17.21" } }, "sha512-P4rFMVq9ESWqmOgK+dlXvOtLwYg0i7u0HBGJER0LZDJT2VHIPAMZ/riPxqJceWMStH5+E61QxFra9kIS3AqdMg=="],+ "date-fns": ["[email protected]", "", {}, "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w=="],+"dayjs": ["[email protected]", "", {}, "sha512-98IT+HOahAisibz/yjKbzuOBwYcjJ7BCLPzARyHiyEBmRz4fatF+KPJszEHXsGYjUG234aH/cOjW1wwTbKUZlA=="],"db0": ["[email protected]", "", { "peerDependencies": { "@electric-sql/pglite": "*", "@libsql/client": "*", "better-sqlite3": "*", "drizzle-orm": "*", "mysql2": "*", "sqlite3": "*" }, "optionalPeers": ["@electric-sql/pglite", "@libsql/client", "better-sqlite3", "drizzle-orm", "mysql2", "sqlite3"] }, "sha512-RiXXi4WaNzPTHEOu8UPQKMooIbqOEyqA1t7Z6MsdxSCeb8iUC9ko3LcmsLmeUt2SM5bctfArZKkRQggKZz7JNw=="],@@ -1905,6 +1911,8 @@"react": ["[email protected]", "", {}, "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw=="],+ "react-day-picker": ["[email protected]", "", { "dependencies": { "@date-fns/tz": "^1.4.1", "date-fns": "^4.1.0" }, "peerDependencies": { "@types/react": ">=16.8.0", "react": ">=16.8.0" }, "optionalPeers": ["@types/react"] }, "sha512-eNh6BlwcYInWaJtRv18mXQ06Ys/H6rdTZAnTaSdOYJuTpwP1JMCHNd1FDRadA+gbeinq+psdULN5Xnowy9mV8w=="],+"react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.4" } }, "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ=="],"react-is": ["[email protected]", "", {}, "sha512-s5un28nYxKJw5gvUHyW5PCC28CvBqLu9r3cWgzHT4Vo/5fqqkFcdRYsGcKf50WMPpjjFZS5d76fn3YCo2njKwQ=="],diff --git a/docs/agent.md b/docs/agent.mdindex eb44cbb6..94022f98 100644--- a/docs/agent.md+++ b/docs/agent.md@@ -177,11 +177,48 @@ is stored twice.as the list changes would swap the open conversation out from under a liveanswer the moment the first save adds a row. `resolveThread` in`lib/agent-transcript.ts` holds the rule, and it is tested.-- **The transcript refetches on every mount** (`refetchOnMount: "always"`).- Switching tabs unmounts the panel and tears the live stream down with it, so- coming back rebuilds from the stored events — and a cached rebuild is the- transcript as it stood *before* the last answer. That presented as "the newest- reply is missing until I reload".+- **The panel is not unmounted when you switch tabs.** It holds a live stream,+ and Radix drops an inactive tab by default — which aborts the stream+ mid-answer, so the reply landed in the durable session with nothing attached+ to receive it. That is the "I went to another tab and the answer never came+ back" bug, and no amount of re-reading state on the way in could fix it,+ because the events had been dropped. `keepMounted` on the tab descriptor+ (`detail-sheet.tsx`) keeps it alive; it renders nothing until the tab is+ opened once, so flicking through records costs nothing.+- **A thread is loaded with `session.snapshot()`, not by hand.** One call+ returns the complete event prefix, the cursor that continues from it, and a+ continuation token *if and only if* eve will accept another turn — about 30ms+ against a hundred-event thread. `lib/agent-session.ts` is the whole of it.++ What it replaced is worth remembering, because every panel bug of the last+ day came out of it: a raw `fetch` of `…/stream?startIndex=-1`, parsing the+ last line into a state machine. The endpoint *follows*, so awaiting the body+ never returned. The stream opens with a bare newline, so "the first line" was+ empty — which failed closed to "busy" and locked **every** reopened+ conversation with "still working on the last question", including ones parked+ with a perfectly good token. And a read that failed reported the *session* as+ working rather than reporting itself as broken, so it could never recover.+ The framework had a documented answer to the exact question that code was+ asking. Read the guide before hand-rolling the protocol.+- **The token is the authority on whether a message can be sent**, not our+ reading of the events. eve returns one only when the captured prefix ends+ parked, which is precisely the condition under which the next send lands.+- **A turn that has gone quiet for 90 seconds is over, not working.** A+ restarted agent leaves sessions with no closing boundary; they never park, and+ treating them as in-flight locks that thread forever.+- **An unreachable agent is `offline`, not `working`.** One is a fact about us+ and the other a claim about the session; stated as the latter it is both+ untrue and unrecoverable, since the read fails identically next time. The+ transcript then comes from our own `AgentEvent` archive — which is also what+ makes a thread older than eve's 30-day retention still readable — and the+ composer stays usable.+- **An ended thread gets a button, not a locked box.** Ended and working both+ disable the composer and mean completely different things: one is a wait of+ seconds, the other is permanent. `composerState()` keeps them apart, and an+ ended thread offers **Start a new conversation**, which moves the picker to a+ new thread. The transcript stays on screen throughout, and the save hook+ treats the fresh session as a new conversation by comparing session ids+ rather than by whether the panel started empty.- **`autoScroll` and nothing else.** The scroller is a state machine(`following-bottom`, `free-scrolling`, `anchored-to-message`) and`scrollAnchor` selects the third, which *stops it following the bottom* — the@@ -192,19 +229,9 @@ is stored twice.scroller measures; a row per tool call adds a boundary every few hundredmilliseconds during an answer. Part ids prefer `toolCallId`, which is stableacross a call's streaming states.-- **The continuation token is recovered, not trusted.** eve accepts input only- on a *waiting* session, and a stored token goes stale the moment a turn ends- with the panel unmounted — which is every tab switch. `lib/agent-resume.ts`- reads the session's newest durable event and takes the token off- `session.waiting`, per eve's own recipe. Without it, sending into a resumed- thread did nothing and said nothing.-- **That read takes the first line and hangs up.** The stream endpoint- *follows*; `includeTailIndex` is a header for the client to stop on, not an- instruction to the server to close. Awaiting the whole body never returns, so- every session read as busy and the composer stayed locked.-- **A turn that has gone quiet for 90 seconds is finished, not busy.** A- restarted agent leaves sessions with no closing boundary; they never reach- `session.waiting`, and treating them as in-flight locks that thread forever.+- **A thread nobody has spoken in is loaded from nothing.** The snapshot query+ is disabled without a conversation; a brand-new thread mounts with no session+ and no events, and its first message creates both.- **Scoped to the rep.** Two people asking about the same contact are having twoconversations. `ConversationsService` filters on the caller, and a session idin a request body decides which row, never whose.diff --git a/packages/db/prisma/migrations/20260801180000_task_timeline_position/migration.sql b/packages/db/prisma/migrations/20260801180000_task_timeline_position/migration.sqlnew file mode 100644index 00000000..4b0be7aa--- /dev/null+++ b/packages/db/prisma/migrations/20260801180000_task_timeline_position/migration.sql@@ -0,0 +1,13 @@+-- Tasks had no place on the timeline.+--+-- `occurredAt` was written as NULL for TASK rows on the grounds that a task is+-- scheduled rather than logged. The timeline orders by it DESC NULLS LAST, so+-- every task sank beneath the entire history and stayed there — a task added a+-- second ago appeared at the bottom of today, under things from that morning.+--+-- The write path now stamps every activity, tasks included. This is the same+-- fix for the rows written before it: where a task sits on the timeline is when+-- it was written down. `dueAt` is when it is *for*, and stays untouched.+UPDATE "activity"+SET "occurredAt" = "createdAt"+WHERE "occurredAt" IS NULL;diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 0d679826..8b3bc7e4 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -22,10 +22,12 @@"class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",+ "date-fns": "^4.4.0","lucide-react": "^1.28.0","next-themes": "^0.4.6","nuqs": "^2.8.9","radix-ui": "^1.6.0",+ "react-day-picker": "^10.0.1","recharts": "3.8.0","sonner": "^2.0.7","streamdown": "^2.5.0",diff --git a/packages/ui/src/components/attendee-list.tsx b/packages/ui/src/components/attendee-list.tsxindex 49d267c0..2dc89825 100644--- a/packages/ui/src/components/attendee-list.tsx+++ b/packages/ui/src/components/attendee-list.tsx@@ -41,11 +41,16 @@ const RESPONSE_LABEL: Record<string, string> = {};/**- * The people on a meeting.+ * 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.*- * Stacked avatars 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,@@ -67,11 +72,11 @@ function AttendeeList({className={cn("flex items-center gap-2", className)}{...props}>- <div className="flex items-center -space-x-2">+ <div className="flex items-center gap-1">{shown.map((attendee) => (<Tooltip key={attendee.id}><TooltipTrigger asChild>- <Avatar size="sm" className="ring-2 ring-background">+ <Avatar size="sm"><AvatarFallback>{initialsOf(attendee)}</AvatarFallback></Avatar></TooltipTrigger>diff --git a/packages/ui/src/components/calendar.tsx b/packages/ui/src/components/calendar.tsxnew file mode 100644index 00000000..41483184--- /dev/null+++ b/packages/ui/src/components/calendar.tsx@@ -0,0 +1,222 @@+"use client"++import * as React from "react"+import {+ DayPicker,+ getDefaultClassNames,+ type DayButton,+ type Locale,+} from "react-day-picker"++import { cn } from "@crm/ui/lib/utils"+import { Button, buttonVariants } from "@crm/ui/components/button"+import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from "lucide-react"++function Calendar({+ className,+ classNames,+ showOutsideDays = true,+ captionLayout = "label",+ buttonVariant = "ghost",+ locale,+ formatters,+ components,+ ...props+}: React.ComponentProps<typeof DayPicker> & {+ buttonVariant?: React.ComponentProps<typeof Button>["variant"]+}) {+ const defaultClassNames = getDefaultClassNames()++ return (+ <DayPicker+ showOutsideDays={showOutsideDays}+ className={cn(+ "group/calendar bg-background p-2 [--cell-radius:0px] [--cell-size:--spacing(7)] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent",+ String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,+ String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,+ className+ )}+ captionLayout={captionLayout}+ locale={locale}+ formatters={{+ formatMonthDropdown: (date) =>+ date.toLocaleString(locale?.code, { month: "short" }),+ ...formatters,+ }}+ classNames={{+ root: cn("w-fit", defaultClassNames.root),+ months: cn(+ "relative flex flex-col gap-4 md:flex-row",+ defaultClassNames.months+ ),+ month: cn("flex w-full flex-col gap-4", defaultClassNames.month),+ nav: cn(+ "absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",+ defaultClassNames.nav+ ),+ button_previous: cn(+ buttonVariants({ variant: buttonVariant }),+ "size-(--cell-size) p-0 select-none aria-disabled:opacity-50",+ defaultClassNames.button_previous+ ),+ button_next: cn(+ buttonVariants({ variant: buttonVariant }),+ "size-(--cell-size) p-0 select-none aria-disabled:opacity-50",+ defaultClassNames.button_next+ ),+ month_caption: cn(+ "flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",+ defaultClassNames.month_caption+ ),+ dropdowns: cn(+ "flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-xs font-medium",+ defaultClassNames.dropdowns+ ),+ dropdown_root: cn(+ "relative rounded-(--cell-radius)",+ defaultClassNames.dropdown_root+ ),+ dropdown: cn(+ "absolute inset-0 bg-popover opacity-0",+ defaultClassNames.dropdown+ ),+ caption_label: cn(+ "font-medium select-none",+ captionLayout === "label"+ ? "text-xs"+ : "flex items-center gap-1 rounded-(--cell-radius) text-xs [&>svg]:size-3.5 [&>svg]:text-muted-foreground",+ defaultClassNames.caption_label+ ),+ month_grid: cn("w-full border-collapse", defaultClassNames.month_grid),+ weekdays: cn("flex", defaultClassNames.weekdays),+ weekday: cn(+ "flex-1 rounded-(--cell-radius) text-xs font-normal text-muted-foreground select-none",+ defaultClassNames.weekday+ ),+ week: cn("mt-2 flex w-full", defaultClassNames.week),+ week_number_header: cn(+ "w-(--cell-size) select-none",+ defaultClassNames.week_number_header+ ),+ week_number: cn(+ "text-[0.8rem] text-muted-foreground select-none",+ defaultClassNames.week_number+ ),+ day: cn(+ "group/day relative aspect-square h-full w-full rounded-(--cell-radius) p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius)",+ props.showWeekNumber+ ? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)"+ : "[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)",+ defaultClassNames.day+ ),+ range_start: cn(+ "relative isolate z-0 rounded-l-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:right-0 after:w-4 after:bg-muted",+ defaultClassNames.range_start+ ),+ range_middle: cn("rounded-none", defaultClassNames.range_middle),+ range_end: cn(+ "relative isolate z-0 rounded-r-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:left-0 after:w-4 after:bg-muted",+ defaultClassNames.range_end+ ),+ today: cn(+ "rounded-(--cell-radius) bg-muted text-foreground data-[selected=true]:rounded-none",+ defaultClassNames.today+ ),+ outside: cn(+ "text-muted-foreground aria-selected:text-muted-foreground",+ defaultClassNames.outside+ ),+ disabled: cn(+ "text-muted-foreground opacity-50",+ defaultClassNames.disabled+ ),+ hidden: cn("invisible", defaultClassNames.hidden),+ ...classNames,+ }}+ components={{+ Root: ({ className, rootRef, ...props }) => {+ return (+ <div+ data-slot="calendar"+ ref={rootRef}+ className={cn(className)}+ {...props}+ />+ )+ },+ Chevron: ({ className, orientation, ...props }) => {+ if (orientation === "left") {+ return (+ <ChevronLeftIcon className={cn("size-4", className)} {...props} />+ )+ }++ if (orientation === "right") {+ return (+ <ChevronRightIcon className={cn("size-4", className)} {...props} />+ )+ }++ return (+ <ChevronDownIcon className={cn("size-4", className)} {...props} />+ )+ },+ DayButton: ({ ...props }) => (+ <CalendarDayButton locale={locale} {...props} />+ ),+ WeekNumber: ({ children, ...props }) => {+ return (+ <td {...props}>+ <div className="flex size-(--cell-size) items-center justify-center text-center">+ {children}+ </div>+ </td>+ )+ },+ ...components,+ }}+ {...props}+ />+ )+}++function CalendarDayButton({+ className,+ day,+ modifiers,+ locale,+ ...props+}: React.ComponentProps<typeof DayButton> & { locale?: Partial<Locale> }) {+ const defaultClassNames = getDefaultClassNames()++ const ref = React.useRef<HTMLButtonElement>(null)+ React.useEffect(() => {+ if (modifiers.focused) ref.current?.focus()+ }, [modifiers.focused])++ return (+ <Button+ ref={ref}+ variant="ghost"+ size="icon"+ data-day={day.date.toLocaleDateString(locale?.code)}+ data-selected-single={+ modifiers.selected &&+ !modifiers.range_start &&+ !modifiers.range_end &&+ !modifiers.range_middle+ }+ data-range-start={modifiers.range_start}+ data-range-end={modifiers.range_end}+ data-range-middle={modifiers.range_middle}+ className={cn(+ "relative isolate z-10 flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 border-0 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-(--cell-radius) data-[range-end=true]:rounded-r-(--cell-radius) data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-muted data-[range-middle=true]:text-foreground data-[range-start=true]:rounded-(--cell-radius) data-[range-start=true]:rounded-l-(--cell-radius) data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-foreground [&>span]:text-xs [&>span]:opacity-70",+ defaultClassNames.day,+ className+ )}+ {...props}+ />+ )+}++export { Calendar, CalendarDayButton }diff --git a/packages/ui/src/components/date-picker.tsx b/packages/ui/src/components/date-picker.tsxnew file mode 100644index 00000000..d0df244b--- /dev/null+++ b/packages/ui/src/components/date-picker.tsx@@ -0,0 +1,118 @@+"use client";++import CalendarGlyph from "@carbon/icons-react/es/Calendar";+import { Button } from "@crm/ui/components/button";+import { Calendar } from "@crm/ui/components/calendar";+import { Icon } from "@crm/ui/components/icon";+import {+ Popover,+ 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,+ onChange,+ placeholder = "Select a date",+ 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>) {+ const [open, setOpen] = useState(false);+ const selected = fromDay(value);+ const thisYear = new Date().getFullYear();++ const choose = (next: string) => {+ setOpen(false);+ if (next !== (value ?? "")) onChange(next);+ };++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <button+ type="button"+ 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">+ {selected ? formatDay(value) : placeholder}+ </span>+ <Icon+ icon={CalendarGlyph}+ className="size-4 text-muted-foreground transition-opacity"+ />+ </button>+ </PopoverTrigger>+ <PopoverContent size="fit" align="start">+ <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+ variant="ghost"+ size="sm"+ className="w-full justify-start"+ onClick={() => choose("")}+ >+ Clear+ </Button>+ </div>+ ) : null}+ </PopoverContent>+ </Popover>+ );+}diff --git a/packages/ui/src/components/empty.tsx b/packages/ui/src/components/empty.tsxindex 01071291..27e3f19e 100644--- a/packages/ui/src/components/empty.tsx+++ b/packages/ui/src/components/empty.tsx@@ -1,17 +1,48 @@import { cn } from "@crm/ui/lib/utils";import { cva, type VariantProps } from "class-variance-authority";-function Empty({ className, ...props }: React.ComponentProps<"div">) {+/**+ * 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-none border-dashed px-6 py-12 text-center text-balance",+ {+ variants: {+ width: {+ default: "",+ wide: "",+ },+ },+ defaultVariants: {+ width: "default",+ },+ },+);++function Empty({+ className,+ width = "default",+ ...props+}: React.ComponentProps<"div"> & VariantProps<typeof emptyVariants>) {return (<divdata-slot="empty"- className={cn(- // 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.- "flex w-full min-w-0 flex-col items-center justify-center gap-4 rounded-none border-dashed px-6 py-12 text-center text-balance",- className,- )}+ data-width={width}+ className={cn(emptyVariants({ width, className }))}{...props}/>);@@ -21,7 +52,11 @@ function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) {return (<divdata-slot="empty-header"- className={cn("flex max-w-sm flex-col items-center gap-2", className)}+ className={cn(+ "flex max-w-sm flex-col items-center gap-2",+ "group-data-[width=wide]/empty:max-w-xl",+ className,+ )}{...props}/>);@@ -80,14 +115,36 @@ function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {);}-function EmptyContent({ className, ...props }: React.ComponentProps<"div">) {+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",+ },+ },+ defaultVariants: {+ layout: "stack",+ },+ },+);++function EmptyContent({+ className,+ layout,+ ...props+}: React.ComponentProps<"div"> & VariantProps<typeof emptyContentVariants>) {return (<divdata-slot="empty-content"- className={cn(- "flex w-full max-w-sm min-w-0 flex-col items-center gap-2.5 text-xs text-balance",- className,- )}+ className={cn(emptyContentVariants({ layout, className }))}{...props}/>);diff --git a/packages/ui/src/components/input-group.tsx b/packages/ui/src/components/input-group.tsxindex 2c5220df..74a00e36 100644--- a/packages/ui/src/components/input-group.tsx+++ b/packages/ui/src/components/input-group.tsx@@ -21,15 +21,24 @@ 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 cursor-text 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",+ "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",{variants: {align: {"inline-start":- "order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]",+ "order-first cursor-text pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]","inline-end":- "order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]",+ "order-last cursor-text pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]","block-start":"order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2","block-end":@@ -54,6 +63,7 @@ function InputGroupAddon({data-align={align}className={cn(inputGroupAddonVariants({ align }), className)}onClick={(e) => {+ if (align === "block-start" || align === "block-end") return;if ((e.target as HTMLElement).closest("button")) {return;}@@ -130,11 +140,16 @@ 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<"textarea">) {+}: React.ComponentProps<typeof Textarea>) {return (<Textareadata-slot="input-group-control"+ size={size}className={cn("flex-1 resize-none rounded-none border-0 bg-transparent py-2 shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",className,diff --git a/packages/ui/src/components/popover.tsx b/packages/ui/src/components/popover.tsxnew file mode 100644index 00000000..2ecacf2b--- /dev/null+++ b/packages/ui/src/components/popover.tsx@@ -0,0 +1,106 @@+"use client"++import * as React from "react"+import { Popover as PopoverPrimitive } from "radix-ui"++import { cn } from "@crm/ui/lib/utils"+import { cva, type VariantProps } from "class-variance-authority"++function Popover({+ ...props+}: React.ComponentProps<typeof PopoverPrimitive.Root>) {+ return <PopoverPrimitive.Root data-slot="popover" {...props} />+}++function PopoverTrigger({+ ...props+}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {+ return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />+}++const popoverContentVariants = cva(+ "z-50 flex origin-(--radix-popover-content-transform-origin) flex-col rounded-none 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",+ },+ },+ defaultVariants: { size: "default" },+ }+)++function PopoverContent({+ className,+ align = "center",+ sideOffset = 4,+ size,+ ...props+}: React.ComponentProps<typeof PopoverPrimitive.Content> &+ VariantProps<typeof popoverContentVariants>) {+ return (+ <PopoverPrimitive.Portal>+ <PopoverPrimitive.Content+ data-slot="popover-content"+ align={align}+ sideOffset={sideOffset}+ className={cn(popoverContentVariants({ size }), className)}+ {...props}+ />+ </PopoverPrimitive.Portal>+ )+}++function PopoverAnchor({+ ...props+}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {+ return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />+}++function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="popover-header"+ className={cn("flex flex-col gap-0.5 text-xs", className)}+ {...props}+ />+ )+}++function PopoverTitle({ className, ...props }: React.ComponentProps<"h2">) {+ return (+ <div+ data-slot="popover-title"+ className={cn("font-medium", className)}+ {...props}+ />+ )+}++function PopoverDescription({+ className,+ ...props+}: React.ComponentProps<"p">) {+ return (+ <p+ data-slot="popover-description"+ className={cn("text-muted-foreground", className)}+ {...props}+ />+ )+}++export {+ Popover,+ popoverContentVariants,+ PopoverAnchor,+ PopoverContent,+ PopoverDescription,+ PopoverHeader,+ PopoverTitle,+ PopoverTrigger,+}diff --git a/packages/ui/src/components/select.tsx b/packages/ui/src/components/select.tsxindex 12eabac4..7179c99a 100644--- a/packages/ui/src/components/select.tsx+++ b/packages/ui/src/components/select.tsx@@ -212,5 +212,6 @@ export {SelectScrollUpButton,SelectSeparator,SelectTrigger,+ selectTriggerVariants,SelectValue,};diff --git a/packages/ui/src/components/toggle.tsx b/packages/ui/src/components/toggle.tsxindex 5c024c5e..b0d354e7 100644--- a/packages/ui/src/components/toggle.tsx+++ b/packages/ui/src/components/toggle.tsx@@ -5,8 +5,18 @@ 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-none text-xs font-medium whitespace-nowrap transition-all outline-none hover:bg-muted hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] 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 data-[state=on]:bg-muted dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "group/toggle inline-flex items-center justify-center gap-1 rounded-none 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-[3px] 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",{variants: {variant: {diff --git a/packages/ui/src/lib/format.ts b/packages/ui/src/lib/format.tsindex 24ae28c1..53f1468f 100644--- a/packages/ui/src/lib/format.ts+++ b/packages/ui/src/lib/format.ts@@ -62,6 +62,48 @@ export function formatPercent(rate: number): string {}).format(rate);}+const dayFormat = new Intl.DateTimeFormat(undefined, {+ month: "short",+ day: "numeric",+ year: "numeric",+});++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);+ if (!year || !month || !day) return undefined;+ const date = new Date(year, month - 1, day);+ 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 ?? "—");+}+export function relativeTimeFromIso(iso: string | null | undefined): string {if (!iso) return "—";const then = new Date(iso).getTime();