@dxv-systems/helpdesk
v0.19.0
Published
Mailbox helpdesk domain logic for DXV apps — idempotent delta ingestion, conservative threading, ticket state machine, noise detection, and replies that a person approves in the helpdesk before they are sent from the mailbox (quoted history kept, retry-sa
Maintainers
Readme
@dxv-systems/helpdesk
Domain logic for a mailbox helpdesk on Microsoft Graph: idempotent delta ingestion, conservative threading, a ticket state machine, noise detection, and one way of answering: a reply (written by staff or by an AI drafter) is approved by a person in the helpdesk and only then sent from the mailbox, with the quoted history kept and no double sends.
Pure logic behind interfaces, plus the staff inbox (see Inbox UI). No database, no environment reading, and zero runtime dependencies. The app implements four small interfaces and calls the functions below. All time comes from an injected Clock.
npm i @dxv-systems/helpdeskIntegrating into an app
The app owns the schema and the cron, and mounts the inbox (see Inbox UI). It passes one HelpdeskDeps object to every function.
| Interface | What the app implements |
|---|---|
| HelpdeskStore | Threads (including the nullable dismissedBy staff id), messages (with their direction, inbound or outbound), sync state (one link per folder), draft runs, send intents. Methods marked atomic in types.ts must be one transaction. Unique keys: message on (mailbox, id), draft run on (mailbox, inboundMessageId, generation), send intent on id. getLatestMessageForThread returns the newest inbound message only. |
| MailboxGateway | One mailbox: delta, getMessage, createReply, updateDraftBody, sendDraft (and optionally listAttachments, downloadAttachment, addAttachment). Declared structurally against @dxv-systems/mail-graph's MailboxClient, so createMailboxClient(http, address) can be passed as is. Use immutable ids (Prefer: IdType="ImmutableId"). An expired delta link (410, syncStateNotFound, resyncRequired) may throw DeltaLinkExpiredError or mail-graph's GraphDeltaExpiredError; both are recognised by name or signal. |
| Drafter (optional) | Without one, no draft is generated and staff write every reply (see Staff-written replies). start(request) starts a run and returns its id. It must treat the same idempotencyKey as the same run (request.eventKey is that key in the AI gateway's alphabet). With read(runId) the app's cron polls the result with collectDrafts; without it the app calls completeDraft when the result comes. See Drafting. |
| Notifier (optional) | review_needed, send_outcome_unknown, sync_failing, sync_recovered and assigned, each with its mailbox. A throwing notifier never breaks the flow. Deliver an event only to people allowed to see it: people with access to that mailbox, and for assigned the assignee (see Access per mailbox, Assigning tickets). |
const deps: HelpdeskDeps = {
store,
gatewayFor: (mailbox) => createMailboxClient(http, mailbox),
drafter,
clock: { now: () => new Date() },
config: { ownAddresses: ["[email protected]"], connectedMailboxes: ["[email protected]"] },
// Read again at the start of every call; a function lets a flipped switch apply at once.
controls: async () => ({ paused: await killSwitchIsOn(), writeMode: "approve_and_send" }),
};
await connectMailbox(deps, "[email protected]"); // once, when the mailbox is connected
await syncMailbox(deps, "[email protected]"); // cron, one run per mailbox at a time
await collectDrafts(deps, mailbox); // cron, after syncMailbox: completes finished drafter runs
await sweepStuckDrafts(deps, mailbox); // cron: fails runs with no report after 15 minutesWhat the app must call: connectMailbox once per mailbox; syncMailbox on a cron; with a drafter, collectDrafts on a cron (for example in the sync cron right after syncMailbox: it reads each started run and completes the finished ones), or, for a drafter without read, completeDraft whenever it reports (pass the run's idempotencyKey; a report for anything but the latest run is ignored); sweepStuckDrafts on a cron (a run still in flight after config.draftTimeoutMs, default 15 minutes, fails so the ticket reaches review as drafter_failed; a report that arrives later is a no-op); and the staff actions below.
Pilot controls
Three switches the app passes in deps.controls (a value, or a function that is called at the start of every entry point, so a change applies on the next call without a restart). The package reads no environment and keeps no state of its own.
| Control | Values | Default |
|---|---|---|
| paused | true stops everything (kill switch) | false |
| writeMode | read_only, approve_and_send | read_only |
| writeModes | per-mailbox override, { "[email protected]": "approve_and_send" } (case-insensitive), so a mailbox that is still being set up can stay read_only | none |
| draftMode | auto (the drafter starts for every new ticket), on_request (only when staff ask; see Drafting) | auto |
| draftModes | per-mailbox override, same shape as writeModes | none |
Write modes. The helpdesk has one way of answering: a reply is written in the helpdesk (by staff, or proposed by the drafter), a person approves it there, and the helpdesk sends it from the mailbox. Nothing is placed in Outlook before that approval.
read_only: sync and drafting work, and the reply text is stored on the run (commentText), but the package makes no mailbox write at all.approveAndSendanswers{ status: "write_blocked", mode }. This is the safe state while a client is being set up.approve_and_send: the reply lives only in app state, andeditDraftchanges only the stored text. Nothing reaches Outlook until a person approves:approveAndSendthen callscreateReply(inboundId)without a comment, puts the approved text in front of the body Exchange returned (prependToDraftBody, right after<body>, so the quoted history stays), writes it withupdateDraftBodyand callssendDraft. The send intent is keyed per draft run (send:<mailbox>:<run key>) and records the draft id, so a retry after a failed send reuses that draft and builds the same body again instead of prepending twice.
The package default is read_only, so a mailbox nobody configured is never written to.
Kill switch. With paused: true, ingestPage, ingestSentPage, syncMailbox, ensureDraft, completeDraft, collectDrafts, regenerateDraft, editDraft, sweepStuckDrafts, unignoreThread, approveAndSend, markRepliedExternally and dismissThread return { status: "paused" } (ensureDraft: "paused") and make no Graph call, no drafter call and no store write. isPaused(result) narrows it. A sync that is paused between pages returns the pages already done. A drafter report that arrives while paused is dropped; the run stays in flight and, after the pause, sweepStuckDrafts moves it to review as drafter_failed. Bookkeeping without mailbox access (connectMailbox, resolveUnknownSend, markWaiting, closeThread) is not paused. Use it as the emergency stop: removing the Exchange role can take up to 2 hours to apply.
Mailbox scope. config.connectedMailboxes is the helpdesk's scope. Any call for another mailbox (a mailbox argument, a thread or a drafter report of another mailbox, or a gateway whose address differs from the mailbox asked for) throws MailboxNotInScopeError before any Graph call. The same Entra app may reach other mailboxes for other features; this helpdesk never touches them.
Every gateway write also passes a guard that throws MailboxWriteBlockedError for a write the mode does not allow (any write in read_only), as a last line of defence behind the checks above.
Run syncMailbox for a mailbox from one worker at a time (a lock or a queue). Overlapping runs are safe against duplicates, but they can move the stored link backwards, which only costs a re-read.
Ingestion
ingestPage(deps, mailbox) fetches one Inbox delta page and processes it; ingestSentPage(deps, mailbox) does the same for Sent Items (see Sent Items). syncMailbox runs Inbox pages until the round is complete, then Sent Items pages, each folder with its own maxPages budget, and returns the results of both in one array (IngestResult.folder is inbox or sentitems). An Inbox round that is not complete yet skips Sent Items for that run.
- Idempotent on the immutable message id. A message already stored is never inserted again. A re-read of stored mail only finishes work a crash left open (a draft run that was never created, a draft ready to be routed to review).
- The link is stored last.
nextLinkordeltaLinkis saved after every item of the page is processed. A crash re-reads the page. - Expired link.
DeltaLinkExpiredError(or any error named so) clears the link and restarts a first-page delta frommax(connectedAt, lastReceivedAt - 48 h). Stored mail is skipped by id. - Skipped without a trace: drafts, mail the mailbox sent itself, and mail received before
connectedAt. - Mailbox state of each message. A stored message keeps
fromName,preview(Graph's first 255 characters as plain text),hasAttachments,isRead,locationandlastVerb(replied to or forwarded, in the app or in Outlook, and when). Read state is the mailbox's own, shared by everyone with the mailbox, as in Outlook. - Changes to existing mail (read or unread, preview, attachments, a reply or forward) are reported by delta as items we already store. They update those fields (
IngestResult.updated) and nothing else: no ticket change, no draft, no notification. - Removed items set
removedAtandlocationon the stored message. The ticket keeps its state. Graph reports a move to another folder and a delete alike, both as@removedwith reasondeleted(seen in a real tenant), so the sync reads the message by its immutable id: its folder givesarchive,deleteditemsorother, and a message that no longer exists isgone. The folder ids come from the gateway'sgetWellKnownFolderIds(mail-graph 0.2). A message reported removed that is still in the synced folder is left alone. One read per removed message, plus the folder ids once per page. - Mail Microsoft refuses (403, such as
ErrorAccessDeniedon reading one message that delta does list) is skipped and counted inIngestResult.denied, with its id indeniedIdsand, indeniedItems, when it arrived and the sender's domain (never the subject or full address), so one such item does not stop the sync on every later run. The delta page itself was readable, so this is about the item, not the mailbox; a 403 on the delta call still throws. LogdeniedItemsin the app. - Mail that comes back (moved back to the Inbox in Outlook, or an undo after archiving) keeps its id, so the sync finds it stored:
removedAtis cleared andlocationisinboxagain (IngestResult.restored). It is not new mail: no new ticket, no draft, no notification, and the ticket keeps its state. - Items are processed oldest first, so a reply in the same page finds its parent.
Sent Items
The ticket shows every reply the mailbox sent to the customer, whether it went out through the helpdesk or from Outlook. ingestSentPage reads the mailbox's Sent Items folder (folderId: "sentitems") with the same rules as the Inbox: items first, link stored last, an expired link restarts from max(connectedAt, sentLastReceivedAt - 48 h), and the kill switch returns { status: "paused" }. The folder has its own link and newest time on the sync state (sentLink, sentLastReceivedAt).
- Display only. A sent mail is stored as a message with
direction: "outbound",fromAddressthe mailbox, andreceivedAtthe send time. It never changes a ticket: no state change, no newlatestInboundId, no draft, and it never opens a ticket. - Matching. Always inside the same mailbox. An
In-Reply-Tothat names a stored mail picks that ticket. Otherwise the ticket is found through theReferenceschain and theconversationId; a ticket found only by conversation also needs a header hit, or a To or Cc recipient that is one of its participants. Sent mail without a subject is matched on its headers only. The sent mail is stored only when exactly one ticket is left. No match, or more than one: it is skipped and counted inIngestResult.unmatched, and never stored. - Replies sent by the helpdesk. With immutable ids a draft keeps its id after it is sent, so the Sent Items copy of an approved reply has the id the send intent recorded. The inbox uses that to show it once (see Inbox UI).
- Skipped: drafts, mail sent before
connectedAt, and mail already stored (a re-read changes nothing). - Removed items set
removedAtandlocation, as in the Inbox; a sent mail moved back to Sent Items is restored the same way. - Customer replies to our mail. A customer reply's
In-Reply-Tousually names our sent mail. Once that mail is synced, the reply threads through its headers like any other.
Mail the mailbox sent to itself or that lands in its own Inbox is still skipped by the Inbox sync.
Threading
matchThread in this order, always inside one mailbox (also checked on the rows a store returns):
conversationId. Accepted when the sender already wrote in that thread, or the mail's In-Reply-To / References point into it. An unknown sender with only a matching conversation id starts a new thread: Exchange groups mail without thread headers by subject, so a bare match can join strangers. If the headers point at a different thread than the conversation id, it also starts a new thread. A mail without a subject (alsoRe:with nothing after it) skips this step: Exchange gives every such mail the same conversation id, so only In-Reply-To and References can place it.In-Reply-Toand the wholeReferenceschain, against storedinternetMessageIds (lowercase, no angle brackets). The whole chain matters because the reply a customer answers is our own sent mail, which is stored only once Sent Items is synced (and never when it matched no ticket); the earlier ids in the chain still hit. Several open threads in one chain: no match. One open thread next to closed or ignored ones: the open one. A forward (FW:,Fwd:,WG:) from someone outside the thread is new business even though it carries old headers.- Normalised subject plus the same sender, within 14 days (
subjectWindowMs). PrefixesRe,Antw,AW,SV,FW,Fwd,WG,TR,VS,Re[2], and gateway tags like[EXTERN]are stripped. An empty subject never matches. More than one open candidate: no match.
Ticket states
New, Ignored, Drafted, Review, Sent, Waiting, Closed.
| From | Event | To |
|---|---|---|
| new | ignore | ignored |
| new | draft | drafted |
| drafted | needs_review | review |
| review | approve | sent |
| review | redraft | drafted |
| sent | settle | waiting |
| waiting | customer_reply | new |
| waiting | close | closed |
| ignored | unignore | new |
| new, drafted, review | dismiss | ignored |
| sent, waiting | bounce | review |
transition(state, event) is the pure function; anything else throws InvalidTransitionError (with from and event). ignore belongs to the noise filter and dismiss to staff, so the filter can never set aside a ticket that already has a draft. unignoreThread is the staff action for mail that was wrongly ignored: ignored to new, latestInboundId set to the newest inbound message (never our own sent mail), dismissedBy cleared, and a draft starts.
No reply needed. dismissThread(deps, { threadId, dismissedBy }) is the staff action for mail that needs no answer (a newsletter the filter missed, "thanks, got it", spam): new, drafted or review to ignored, with Thread.dismissedBy set to the staff id (null on a ticket the noise filter ignored, so analytics can tell the two apart). It returns { status: "paused" } under the kill switch and refuses a mailbox outside the scope. It throws SendPendingError (code send_in_progress or send_outcome_unknown) while a send is under way or unclear; a sending intent older than 2 minutes is turned into unknown first, so staff get the resolve buttons. After the state change it stops an in-flight draft run (marked failed, so a late report is a no-op). It touches no mailbox. approveAndSend checks the state again after it claims the send, so a dismissal that lands just before the claim stops the send (StaleThreadError, the intent becomes failed). Ignored stays final: a later reply opens a new ticket. Only the app decides when to call markWaiting (sent to waiting) and closeThread (waiting to closed, for example after N quiet days).
Where a state is set in practice. A noise mail opens its ticket directly as ignored (the New to Ignored step is collapsed into creation, so a crash cannot leave a noise ticket in new). completeDraft goes new to drafted to review in one write. Every reply ends in review, because a person always approves it, with reviewReason low_confidence, policy, stale_draft, drafter_failed, staff_edited or (no drafter) no_draft. A bounce of a sent reply brings a ticket back to review with delivery_failed.
A customer mail (one that is not noise) arrives for a ticket in:
| State | What happens |
|---|---|
| new | Appended. No second draft run starts while one is in flight; its result is stale and goes to review. |
| drafted | Appended, state kept. The draft is stale. |
| review | Appended, state kept, reviewReason becomes stale_draft. Staff regenerates (review to drafted) or approves with acceptStale. |
| sent, waiting | Same ticket goes to new (via settle then customer_reply) and a draft starts. |
| closed, ignored | Final. The mail opens a new ticket with relatedThreadId pointing at the old one. |
A noise mail (out-of-office, bounce, a colleague's connected mailbox) that threads onto a ticket is stored in it and leaves its state alone, so an auto-reply to our answer does not wake a waiting ticket. It does move lastActivityAt to its arrival, like every mail that joins a ticket, so the conversation rises to the top of the list. lastActivityAt never moves back for an older mail that arrives late.
Bounces of a sent reply. A bounce (NDR) is matched to its ticket on its own terms, because its sender is never a participant. The NDR body quotes the headers of the bounced reply; their In-Reply-To and References point at the customer mail we answered, which is stored. When those name no single ticket, the conversation id is used, but only if exactly one ticket in that conversation is sent or waiting. A matched ticket in sent or waiting gets the NDR as a message and goes to review with reviewReason: "delivery_failed" (label "Niet afgeleverd"), and the notifier gets review_needed with that reason. In any other state the NDR is only stored. No match: the NDR opens its own ignored ticket as before. The inbox then offers only "Opnieuw verstuurd vanuit Outlook" (replied_externally) and "Geen antwoord meer nodig" (dismiss) for that ticket: the reply was already sent, so staff resend it from Outlook (for example to a corrected address) and say so, or set the ticket aside. IngestResult.deliveryFailures counts these.
Noise detection
classifyNoise returns { action: "ignore" | "process", reason }. Every rule needs a positive signal; unclear means process.
- bounces: sender
postmaster/mailer-daemonor Exchange Online's system sender (microsoftexchangeplus 32 hex characters), adelivery-statuscontent type, or Exchange's NDR header. A subject alone never counts. Checked beforeAuto-Submitted, which NDRs usually carry as well. Auto-Submittedpresent and notnoPrecedence: bulk | junk | list | auto_reply- out-of-office:
X-Autoreply,X-Autorespond, or a subject that starts with the Outlook prefix (Automatic reply:,Automatisch antwoord:,Out of Office:and similar) List-IdorList-Unsubscribe- sender local part
noreply,no-reply,do-not-reply,donotreply,bounce(s), unlessReply-Toholds a different address that is not machine-like or ours (a website form). Then the mail is processed,Reply-Tobecomes the ticket'scustomerAddress, and both addresses are participants so threading keeps working.Auto-Submitted, bounces and lists still ignore such mail. - the app's own addresses and every connected mailbox
X-Auto-Response-Suppress does not ignore mail: it asks auto-responders to stay quiet, and business systems set it on mail a person may need to answer. The mail is processed and StoredMessage.suppressAutoResponse is set, so the app can see that no automatic answer was wanted.
Not noise on purpose: acknowledgements ("bedankt"), info@, notifications@, newsletter@ and the client's own domain. Wrongly ignoring a customer is worse than a needless draft.
Drafting
ensureDraft runs from ingestion for a new ticket. It creates the run with createDraftRunIfAbsent (one per inbound message) and calls drafter.start with draft:<mailbox>:<messageId>:<generation> as the idempotency key. A run that was claimed but never started is resumed after 2 minutes, with the same key.
completeDraft stores the text, confidence, reason and category on the run and moves the ticket to review. It writes nothing to the mailbox.
The drafter as a platform agent. The drafter is meant to be a DXV platform agent run (helpdesk-drafter) started through the AI gateway. The platform never calls the app, so nothing reports back: the app polls. The app adapts createRuns({ feature: "helpdesk.draft" }) of @dxv-systems/ai (this package does not import it), the same way as the distiller:
start(request):fireRun(request.input, { eventKey: request.eventKey }).eventKeyisdraft-<hash of the idempotency key>, so a retried start answers the run it already started.read(runId):getRun(runId)as{ status, result, error }, statuses as the gateway has them (pending,implementing,completed,failed,cancelled); null for an unknown run.
collectDrafts(deps, mailbox) is the cron's call (the recipe runs it in the sync cron, per mailbox, after syncMailbox). For each started run of the mailbox that is still the ticket's latest, it reads the run once: completed goes through completeDraft with the parsed result (ticket to review); failed, cancelled or unknown goes through completeDraft as a failure (drafter_failed, the error on the run); pending or implementing is left, and sweepStuckDrafts fails it after config.draftTimeoutMs (default 15 minutes). A read that throws is counted as unreadable and tried again next round. It returns { completed, failed, running, unreadable, lastError }, or { status: "paused" }. Without drafter.read it does nothing. It reads only the store and the gateway; it never touches the mailbox.
Run input (request.input, DraftRunInput): { idempotencyKey, mailbox, subject, conversation }. conversation is the conversation of the mail to answer, oldest first: { direction: "inbound" | "outbound", from, fromName?, at, text } per message, from the sender address, fromName the customer's display name on inbound messages (when Graph has one, so the agent can greet them; never on our own messages), no other recipients, text the plain text the message adds (Graph's uniqueBody through listConversation, any folder; without that gateway method or a conversation id, only the mail to answer through getMessage). Drafts and mail in Deleted Items or Junk Email are left out (the same check as the FAQ distillation); at most the newest DRAFT_MAX_MESSAGES (20) messages, each cut to DRAFT_MAX_TEXT_CHARS (4,000). No attachments. When the mail to answer is no longer in the mailbox, the run fails before it starts. Reading the conversation (and the well-known folder ids) are the only Graph calls start adds, reads allowed in every write mode.
Run result (what the agent writes, DraftOutput): { text, confidence, reason?, category? }, as an object or as that object in JSON text. text the reply as staff see it in "Jouw antwoord", confidence a number from 0 to 1 (below config.minConfidence, default 0.7, the review reason is low_confidence), reason a short note for staff (cut to 300 characters), category a free label. Anything else fails the run with The drafter's result is not a draft: <why>; parseDraftOutput is the check.
Drafting on request. With the control draftMode: "on_request" (or per mailbox in draftModes), ensureDraft starts no run: a new ticket goes to review with reviewReason: "no_draft", exactly as without a drafter, and returns "on_request". Staff start the drafter themselves with regenerateDraft (review to drafted, the next generation, or the first when there is none); the inbox offers it as "Voorstel schrijven" while there is no draft and "Nieuw voorstel" after; collectDrafts brings the text in on its next round. Each run then costs only when someone asks for it. The control is read on every call, so switching a mailbox to auto later needs no deploy.
Staff edits. editDraft(deps, { threadId, text }) stores the new text (commentText) and sets the ticket back to review (staff_edited). It writes nothing to the mailbox; the approved text is put in front of the quoted history only when the reply is sent (see Sending). Never call updateDraftBody yourself.
Failures never strand a ticket. A drafter that cannot start or a failure result moves the ticket to review with drafter_failed, the error stored on the run, and the page still completes. regenerateDraft (review to drafted, next generation) is the staff action; markRepliedExternally closes a review when staff answered from Outlook.
Staff-written replies. Staff can always write the reply themselves when there is no usable draft: no run, a failed run, or (without a drafter) only a run for older mail. Without deps.drafter, ensureDraft moves a new ticket straight to review with reviewReason: "no_draft" (and notifies review_needed); regenerateDraft throws DraftNotReadyError. editDraft then creates the next generation of the run for the newest inbound message as a staff run: status succeeded, text: null (no drafter text), reason: "staff", the staff text in commentText. The ticket goes review to drafted to review (staff_edited). From there it is an ordinary run: further edits, approveAndSend and send intents work unchanged. One internal rule decides which run staff work on, for the domain functions and the inbox alike.
Outlook drafts
The only Outlook draft the helpdesk makes is the one approveAndSend creates at the moment a person approves, and it is sent straight away. The helpdesk never deletes a draft. A send that Graph refused (failed_not_sent) leaves that draft in Outlook's Drafts; the next approval reuses it. If staff then answer from Outlook or mark the ticket as needing no reply, the leftover draft stays in Drafts until someone removes it there.
Known limit: if the process dies between createReply and storing the draft id, that Outlook draft is a duplicate nobody knows about. Its id was never stored, so it stays until someone deletes it in Outlook.
Sending
approveAndSend(deps, { threadId, approvedBy }):
- The ticket must be in review and have reply text (a finished draft run, or a staff reply saved with
editDraft); a reply older than the newest customer mail needsacceptStale: true. A reply whose own text (commentText, elsetext) is empty or whitespace throwsEmptyReplyErrorbefore any intent or Graph call: a quoted history alone is never sent.editDraftrefuses blank text the same way. Inread_onlythe answer iswrite_blocked. - A send intent (
send:<mailbox>:<run key>) is stored first, then compare-and-set fromintendedtosending. Only one caller wins that compare-and-set. Then the Outlook draft is created withcreateReply(inboundId), the text goes in front of the quoted body, any files are added, andsendDraftis called. - Success marks the intent
sentand the ticketsent. A second approval returnsalready_sent. - An HTTP 400, 401, 403 or 429 means Graph refused it:
failed_not_sent, and the same flow can be retried. - Anything else (network error, timeout, 5xx, 404) may have sent. The result is
unknown_outcome, the intent becomesunknown,send_outcome_unknownis notified, and the package never resends. Asendingintent left behind by a dead worker turns intounknownafter 2 minutes. Staff checks Sent Items and callsresolveUnknownSendwithsentornot_sent.
Concurrent callers get in_progress or already_sent.
Inbox UI
The staff inbox ships with the package: a route handler (@dxv-systems/helpdesk/server, framework-neutral, handle(Request): Promise<Response>) and a React page (@dxv-systems/helpdesk/react, a "use client" entry; React is an optional peer dependency). The app mounts both and implements one more interface for the reads the domain store does not have.
Route app/api/helpdesk/[...path]/route.ts:
import { createHelpdeskHandlers } from "@dxv-systems/helpdesk/server";
import { helpdeskDeps } from "@/lib/helpdesk/deps"; // the same HelpdeskDeps the cron uses
import { helpdeskInbox } from "@/lib/helpdesk/inbox"; // HelpdeskInboxQueries over the app's tables
import { getSession } from "@/lib/auth";
const { handle } = createHelpdeskHandlers({
deps: helpdeskDeps,
inbox: helpdeskInbox,
getStaff: async (request) => {
const user = await getSession(request);
if (!user?.isStaff) return null;
// The mailboxes this person may see, from the app's own assignment (one shared mailbox: all staff get it).
return { id: user.id, name: user.name, email: user.email, mailboxes: await mailboxesFor(user) };
},
isProduction: process.env.VERCEL_ENV === "production",
});
export { handle as GET, handle as POST, handle as PUT, handle as DELETE };Page app/(staff)/helpdesk/page.tsx:
import { HelpdeskInbox } from "@dxv-systems/helpdesk/react";
export default function HelpdeskPage() {
return <HelpdeskInbox renderCustomerContext={(thread) => <CustomerCard email={thread.customerAddress} />} />;
}| createHelpdeskHandlers option | |
|---|---|
| deps | The HelpdeskDeps (store, gatewayFor, optional drafter, notifier, controls, clock, config). The handlers call the domain functions with it and nothing else. |
| inbox | HelpdeskInboxQueries: listThreads(query) (always applied: rows whose mailbox is in mailboxes, the viewer's mailboxes and possibly empty, OR whose assignee is viewerId; then states, mailbox, assigneeId: undefined is anyone, null is unassigned; cursor and limit; newest activity first; returns { rows: [{ thread, assignee }], nextCursor }), listMessages(threadId) (every message of both directions, oldest first), getAssignee(threadId), listAssignees() (the people a ticket may be assigned to, { id, name }), setAssignee(threadId, { id, name } \| null, { by, note }). Assignment and its note are app data; the domain never reads them. |
| getStaff(request) | { id, name, email, mailboxes } for staff, null for anyone else (every route answers 401). mailboxes is the list this person may see (see Access per mailbox). id is stored as approvedBy on a send and as dismissedBy on a dismissal. |
| isProduction | Outside production every route answers 403 not_production. |
| basePath | Default /api/helpdesk. |
| appOrigin | Writes with an Origin header from elsewhere answer 403. Default: the request URL's origin. |
| onError | Unexpected errors (default console.error); the response is a generic 500 without details. |
Routes (under basePath). Every write answers { detail, message, outcome? } with the thread as it is after the action.
| Route | Calls |
|---|---|
| GET threads?state=review,new&mailbox=&assignee=me\|none\|<id>&cursor=&limit= | inbox.listThreads over the viewer's mailboxes; also returns viewer (with mailboxes), the pilot switches and sync problems of those mailboxes |
| GET threads/:id | thread, messages (metadata; outbound: true for mail synced from Sent Items), latest draft, send status (send.messageId: the sent mail's id once the status is sent), and actions the state machine and pilot controls allow now |
| GET threads/:id/messages/:messageId | gateway.getMessage through the scope check; body as plain text and as cleaned HTML (html, null for a text-only mail), with to and cc, plus its attachments (gateway.listAttachments; inline images go into html, not into the list). A sent mail's body and attachments load the same way. For a delivery report (bounce: true in the detail's messages, inbound only) also bounce: { recipient, statusCode, reason, diagnostic }, read on the server, with reason one plain Dutch sentence (e.g. 5.1.1 "Dit adres bestaat niet.") |
| GET threads/:id/messages/:messageId/attachments/:attachmentId | download of one file attachment of that message (gateway.downloadAttachment) |
| PUT threads/:id/draft { text } | editDraft |
| POST threads/:id/regenerate | regenerateDraft |
| POST threads/:id/send { acceptStale? } | approveAndSend |
| GET assignees | inbox.listAssignees() as { assignees: [{ id, name }] }; empty for someone without access to any mailbox (they cannot assign) |
| POST threads/:id/assign { assigneeId?, note? } | inbox.setAssignee: without assigneeId to the signed-in staff member, else to that candidate (see Assigning tickets) |
| DELETE threads/:id/assign | inbox.setAssignee to nobody |
| POST threads/:id/waiting | markWaiting |
| POST threads/:id/close | closeThread |
| POST threads/:id/unignore | unignoreThread |
| POST threads/:id/replied-externally | markRepliedExternally |
| POST threads/:id/dismiss | dismissThread, with the signed-in staff id as dismissedBy |
| POST threads/:id/resolve-send { outcome: "sent" \| "not_sent" } | resolveUnknownSend |
Errors are { error, message } with a Dutch message (INBOX_ERROR_MESSAGES): paused (423), write_blocked (409, with mode), mailbox_not_in_scope (403), stale_draft, draft_not_ready, invalid_transition, stale_thread, send_in_progress, send_outcome_unknown (409), empty_reply (422), send_failed (502, Graph refused, nothing sent), thread_not_found (404), assign_not_allowed (403), invalid_assignee (422). A send whose outcome is unclear answers 200 with outcome: "unknown_outcome". Responses never carry draft bodies from Outlook, idempotency keys, draft ids or raw error text. The one exception is send.messageId of a sent reply: once sent, the draft id is the id of the mail in Sent Items.
Attachments. The message body route lists the attachments of a customer mail; inline images (signature logos) are left out. A file up to 4 MB gets a download link on the app itself; a larger file, an attached mail (item) or a link to a shared file (reference) is listed with a note to open it in Outlook, because a Vercel function answers at most 4.5 MB. The download is checked like the body (the message must belong to the ticket, scope check, paused refuses) and the attachment id must be one Graph lists for that message. It is always served as application/octet-stream with Content-Disposition: attachment, X-Content-Type-Options: nosniff and a sandbox CSP, so customer files never render on the app's origin. Both gateway methods are optional: a gateway without them shows no attachments. mail-graph's MailboxClient has them. Attachments are never stored by the helpdesk.
Files on a reply. With deps.attachments (ReplyAttachmentsDeps: a ReplyAttachmentStore over the app's table and ReplyFiles over its file storage) and a gateway with addAttachment, staff can add files to the reply they are writing. The file never passes the app server: startReplyUpload checks the ticket and the limits and lets the app presign a direct upload, the browser PUTs the file to storage, and addReplyAttachment has the app verify the stored object before the file joins the reply. Limits: 10 files and 20 MB together per reply, checked before the upload and again on the real object. Files can be added while the reply can still be approved (review, not a bounced ticket) and removed until it is sent (removeReplyAttachment). Outlook is touched only at approval: approveAndSend adds the files to the draft it creates at that moment, right before sendDraft; a file that cannot be added fails the send as failed_not_sent, so nothing goes out without the approved files, and a retry on the same draft skips files already on it. After the send the files are marked as sent with that intent, also when staff confirm an unclear send. Dismissing a ticket or "Al beantwoord in Outlook" drops the unsent files. Routes: POST threads/:id/attachments/upload ({ name, contentType, size }, answers the upload target), POST threads/:id/attachments ({ uploadToken }), DELETE threads/:id/attachments/:attachmentId. The detail carries replyAttachments (unsent ones, and those of the latest sent reply) and the action attach.
Message bodies: text, and HTML for a sandboxed frame. The body is asked from Graph as HTML. text is htmlToPlainText of it (tags, scripts, styles and comments dropped, entities decoded), and the built-in page shows only that, as a text node with white-space: pre-wrap.
html is for apps that show formatted mail:
- Cleaning: scripts, frames, objects, forms,
base,link,meta, SVG andon…attributes are removed. URLs go through an allowlist after decoding entities and dropping whitespace and control characters: linkshttp(s),mailto,teland#; imageshttp(s)anddata:image/png|jpeg|gif|webp. Anything else becomes#. Styles, tables, links and images stay. - Inline images:
cid:images are put in place as data URIs: png, jpeg, gif and webp only, at most 1 MB each and 3 MB per mail, otherwise blank. A sandboxed frame has no session, so it could not fetch them from the app. They need mail-graph 0.3.1 or later (AttachmentInfo.contentId). - The frame is the security boundary, not the cleaning. Show
htmlonly throughmailFrameDocument(html)from./client, in<iframe sandbox={MAIL_FRAME_SANDBOX} srcdoc>(allow-same-origin, nothing else), and callattachMailFrame(iframe)once it is mounted (it returns a cleanup).- No script runs in the frame: the sandbox has no
allow-scripts, and the document's policy allows no script, forms, frames or fetches. Never addallow-scripts: together withallow-same-originthe mail could reach the app. - Height:
attachMailFramesets the frame's height to the mail's and follows it (images loading, a narrower column), so there is no second scrollbar. - Links: the sandbox has no
allow-popups, so the mail itself opens nothing.attachMailFrameopens absolutehttp(s),mailtoandtellinks in a new tab withnoopener, and scrolls to the target of a#link inside the mail. Any other link, relative ones included, does nothing. - External images load (
img-src https: http: data:).
- No script runs in the frame: the sandbox has no
to and cc are { address, name }. Bodies are fetched per message, once per open thread; while the helpdesk is paused they are not fetched (no Graph call), the rest of the thread still shows.
| HelpdeskInbox prop | |
|---|---|
| apiBasePath | Default /api/helpdesk. |
| classNames | Partial HelpdeskInboxClassNames; defaults (DEFAULT_HELPDESK_INBOX_CLASSNAMES) use the shadcn tokens of the company app template. The only way to style it. |
| pollIntervalMs | List and open thread refresh, default 30000, at least 5000. A draft being edited is never overwritten. |
| fetch | Custom fetch (tests, a wrapper that adds headers). |
| renderCustomerContext | (thread) => ReactNode, shown above the messages: the app's own data for the customer or project. |
| initialThreadId, onThreadChange | Open a thread first (a link from a review_needed notification) and keep the open thread in the URL. |
What staff sees: one page with the list and the open ticket side by side; on a phone the two are shown one at a time with "Terug naar tickets" (hidden from md up, where the list stays visible). A paused helpdesk shows a banner.
- List. Status and assignee filters side by side (native, labelled selects with the app's input style; the chosen status shows the count the list already has), a mailbox filter below them when there are several mailboxes, and "Meer laden". Each ticket shows its subject and time, the customer, and one status badge.
- One status badge. State and review reason make one label: a bounced reply shows "Niet afgeleverd" instead of "Te beoordelen"; other reasons appear as small text next to the badge ("Voorstel klaar", "Zelf antwoorden").
- Header. Subject, the status badge,
customer · naar <mailbox>, the assignment ("Niet toegewezen", "Toegewezen aan jou", "Toegewezen aan "; a click opens the picker, see Assigning tickets) and a "Meer acties" menu with "Geen antwoord nodig" and "Al beantwoord in Outlook" (both ask inline first). An assignee without access to the mailbox sees the assignment as a label and gives the ticket back with "Toewijzing weghalen" in that menu. - Conversation. One chronological list: customer mails on the left with initials, every reply the mailbox sent on the right ("Jouw antwoord · vanaf ", the body and files loaded like customer mail, "Verstuurd, staat in Verzonden items"). Attachments are file chips with type and size. A delivery report is an event ("Jouw antwoord is niet afgeleverd", the Dutch reason, and the raw text under "Technische details van Microsoft"), never the raw mail. A reply just sent through the helpdesk shows its approved text until its Sent Items copy is synced (up to one sync interval); from then on only the copy is shown.
- Reply. A "Jouw antwoord" card: "Voorstel van de AI · pas aan waar nodig" while the text is the drafter's, the reply box, files ("Bijlage toevoegen", max. 10 files, 20 MB together), and a footer with the sending mailbox and "Nieuw voorstel", "Opslaan" and "Goedkeuren en versturen". In
read_onlythe ticket carries an "Alleen lezen" badge and the send button is disabled with the reason next to it. Without a usable draft the box is empty, and sending saves the typed reply first; a blank reply cannot be sent. Sending always asks for confirmation inline (recipient and mailbox named; edits are saved first), a stale reply asks again with "Toch versturen", and an unclear send shows "Het staat in Verzonden items" / "Het is niet verstuurd". - Bounced ticket. Instead of the reply card, "Wat nu?" with "Opnieuw verstuurd vanuit Outlook" (
replied-externally) and "Geen antwoord meer nodig" (dismiss).
A dismissed ticket leaves the list (a ticket whose new state falls outside the chosen view always does) and stays open with "Toch behandelen" to undo it.
Access per mailbox
Each staff member sees only the mailboxes the app gives them. The app owns that assignment (its own table, settings page, roles, audit log); the package enforces it on every inbox route, so the app never filters around the package's paths.
- The contract.
getStaff(request)returnsmailboxes: readonly string[]: the mailboxes this person may see, already resolved by the app. It is required. Addresses are compared case-insensitively, and only those that are also inconfig.connectedMailboxescount. An empty list means no access to any mailbox: that person sees only tickets assigned to them. For a helpdesk on one shared mailbox, give every helpdesk user that mailbox. - The rule. A person may see a ticket when its mailbox is one of theirs, OR the ticket is assigned to them. The second half covers exactly one ticket at a time: an assignee without access to the mailbox sees that ticket, not the mailbox's other tickets, its pilot settings or its sync problems.
- The list.
GET threadsasksinbox.listThreadswithquery.mailboxes(the viewer's connected mailboxes, spelled as inconnectedMailboxes, possibly empty) andquery.viewerId(the signed-in staff id). Return a row when its mailbox is inmailboxesOR its assignee isviewerId, in the query itself (mailbox in (...) or assignee_id = ...), so pages stay full and the cursor stays correct. Never let an emptymailboxesturn into "every mailbox". The handler drops any other row as a second guard, using the assignee the row carries. Amailboxfilter outside the viewer's mailboxes answers 403mailbox_not_in_scope, the same as a mailbox that is not connected, also when the viewer has tickets assigned in it.pilot.mailboxesandsyncIssueshold only the viewer's mailboxes. - No access. A viewer without any mailbox gets
viewer.mailboxes: [], no pilot or sync data, and only the tickets assigned to them. The React page then shows those tickets (in every state, with "Je ziet alleen tickets die aan jou zijn toegewezen."); with none assigned it shows "Je hebt nog geen toegang tot een mailbox." instead of the filters and tickets. - Everything by thread id. Every route under
threads/:id(detail, message bodies, attachment downloads, draft, regenerate, send, assign, waiting, close, unignore, replied-externally, dismiss, resolve-send, reply files) first checks the thread's mailbox, then (without mailbox access) whetherinbox.getAssignee(threadId)is the viewer. Without either the answer is 404thread_not_found, the same as for a thread that does not exist: no content and no hint that it is there. Nothing is changed and no mailbox is touched. - Working an assigned ticket. An assignee without access to the mailbox works the ticket like anyone else: read, write and approve the reply (it goes out from the ticket's mailbox; the detail's
pilot.writeModeis that mailbox's mode), close, dismiss, and give it back. They cannot assign it to someone else (403assign_not_allowed; the detail has noassignaction). Once they give it back, the ticket answers 404 for them again; thatDELETEanswers{ detail: null, message }. - Notifications.
review_needed,send_outcome_unknown,sync_failingandsync_recoveredcarrymailbox. The package has no recipients: the app's notifier must deliver each event only to people with access to that mailbox.assignedgoes to the assignee only (assigneeId). - Not per person. The domain functions the crons call (
syncMailbox,completeDraft,sweepStuckDrafts) and the pilot controls work per mailbox, not per person, and are unchanged.
Assigning tickets
A ticket can be assigned to one person: anyone who may use the helpdesk, also someone without access to the ticket's mailbox (for example a colleague who knows the customer). The app keeps the assignment; the package decides who may change it and who then sees the ticket.
- Candidates.
inbox.listAssignees()returns everyone a ticket may be assigned to, as{ id, name }(ids asgetStaffreturns them). The inbox fetches it withGET assigneeswhen the picker opens; onlyidandnameleave the server. - Who may assign. Only someone with access to the ticket's mailbox (
HelpdeskStaff.mailboxes). The detail then carries the actionassign. An assignee who reaches the ticket only through the assignment gets 403assign_not_allowedand can only give it back (DELETE threads/:id/assign). - The write.
POST threads/:id/assignwith{ assigneeId?, note? }. WithoutassigneeId(or with the own id) the signed-in person takes it. Any other id must be one oflistAssignees(), checked on the server; else 422invalid_assignee. The name stored is the onelistAssigneesgave, never one from the request.noteis optional, at most 2,000 characters, trimmed, and an empty note isnull. The handler callsinbox.setAssignee(threadId, { id, name }, { by, note });DELETEcallssetAssignee(threadId, null, { by, note: null }). - The note. An internal note for the assignee ("Kun jij deze oppakken? Klant belde al."). The app stores it with the assignment. The package never puts it in a reply, a draft or any mail, and never returns it in the inbox responses.
- The event. Assigning someone else sends
{ type: "assigned", threadId, mailbox, subject, assigneeId, assignedById, note }to the notifier, so the app can tell the assignee (with a link to the ticket). Taking a ticket yourself sends nothing. Deliver it to the assignee only: it carries the internal note. - What the assignee sees. See Access per mailbox: the ticket appears in their list and they can work it, without the mailbox's other tickets or settings.
- The picker. The header's assignment opens a small panel: "Toewijzen aan" with "Niemand", "Aan mij" and the colleagues, and for a colleague an optional "Notitie voor " ("Alleen intern, gaat nooit naar de klant."), then "Toewijzen". It is the inbox's only assign control: an app that built its own picker on 0.4 removes it.
Mailbox actions
Staff can handle a ticket's mail the way they would in Outlook, and Outlook shows the same. The actions work on the ticket's customer mail in its own mailbox. Our replies in Sent Items stay where they are. They never change the ticket's state.
Read or unread:
setThreadRead(deps, { threadId, read, messages }), orPOST threads/:id/readwith{ read: true | false }. It changes only mail in the Inbox that Mail does not show in that state yet. Mail shows onlyisRead === falseas unread, so mail with an unknown read state is left alone when marking read, and is marked when marking unread. Read state belongs to the mailbox, as in Outlook: everyone with the mailbox sees it.Archive, delete, move:
moveThread(deps, { threadId, destination, messages }), orPOST threads/:id/movewith one of these bodies:{ to: "archive" }{ to: "deleteditems" }{ to: "folder", folderId }, wherefolderIdis a folder's id. The well-known names go throughtoand are refused here.
Delete is a move to Deleted Items, as in Outlook. The helpdesk never deletes mail for good. The stored messages get
locationandremovedAtright away, so the list does not wait for the next sync.Undo, or bring mail back:
{ to: "inbox" }moves mail that left the Inbox back. Ids are immutable, so the next sync finds the mail stored and in place: no new ticket, no draft, no notification.Partial failure. Each message is recorded right after its own move or read change. A retry after an error only does what is left.
Who. Everyone who sees the ticket: staff with access to its mailbox, and its assignee. Nothing happens while paused (423). A mailbox in
read_onlyrefuses it (409write_blocked, before any Graph call).What the detail offers.
actionshasmark_readandmovewhile the ticket has customer mail in the Inbox, andrestorewhile some of it is elsewhere. Each message in the detail carrieslocation,isRead,fromName,previewandhasAttachments.Gateway.
MailboxGateway.markReadandmoveMessage. mail-graph'sMailboxClienthas both. The guard lets them through inapprove_and_sendonly.
messages is the ticket's stored mail as the app's inbox.listMessages(threadId) returns it. The handlers pass it themselves.
Conversation list and counts
For apps that build their own mail-style screen on the package (headless). The ticket list (GET threads) stays for the built-in inbox page.
GET conversationslists conversations newest activity first, with what a list row needs. Each row has the ticket summary plus:unread: unread customer mail in the listed folder;hasAttachments;messageCount: both directions, without mail gone from the mailbox;latest: the newest customer mail'sfromAddress,fromName,previewandreceivedAt.
Query parameters:
folder:inbox(default),archiveordeleteditems. The stored location of the customer mail decides.unread=1andattachments=1.q: case-insensitive text, at most 200 characters, matched in the subject and in each message's sender address, sender name and preview. The full body is not stored, so it is not searched.mailbox,assignee(me,noneor an id),cursorandlimit, as onGET threads.
The response also carries
viewer,pilotandsyncIssues, like the ticket list.Unread window: mail older than
UNREAD_WINDOW_DAYS(120) never counts as unread, inunread,unread=1and the counts. Imported history keeps Outlook's read state without flooding the badges.GET countsgives{ mailboxes: [{ address, unread }], assignedToMe, total }: unread conversations in the Inbox per mailbox of the viewer, those assigned to the viewer in any mailbox, and a total that counts each conversation once. It is meant for a badge in the menu.Access is the same as the ticket list: the viewer's mailboxes, plus what is assigned to them. It is filtered in the app's query, with the handler as a second guard.
The app implements
listConversations(query)andcountUnread({ mailboxes, viewerId })onHelpdeskInboxQueries, in SQL so pages stay full. The recipe has both.createMemoryInbox(store)in./testingis the reference implementation: an app's SQL must give the same rows.
Live folders and sync now
A mail client also shows the folders the helpdesk does not store, such as Archive, Deleted Items and the mailbox's own Outlook folders. These are read live from Microsoft 365 through the mailbox routes. They are never stored.
| Route | What |
|---|---|
| GET mailboxes/:mailbox/folders | Top-level folders. Outlook's own carry wellKnown (inbox, archive, deleteditems, sentitems, drafts, junkemail). |
| GET mailboxes/:mailbox/folders/:id/folders | A folder's children. |
| GET mailboxes/:mailbox/folders/:id/messages | One page, newest first (limit, cursor, q). Each message has to and cc, and threadId when the helpdesk stores it. q finds mail whose sender, recipients (To, Cc, Bcc), subject or body has every word (at most 200 characters, 400 without a letter or digit); the cursor keeps the search. |
| GET mailboxes/:mailbox/messages/:id | A message's text and attachments, as for a ticket, plus bcc (only on the mailbox's own copy of sent mail and drafts). |
| GET mailboxes/:mailbox/messages/:id/attachments/:attachmentId | Download, same limits and headers as for a ticket. |
| POST mailboxes/:mailbox/messages/:id/move | { to } as for a ticket. A stored message gets its new location. |
| POST mailboxes/:mailbox/sync | Pull to refresh: calls the app's syncNow(mailbox) and answers { status: "done" \| "busy" \| "paused" \| "failing" }. Without the hook it answers 404. |
- Access: only staff with access to the mailbox. Being assigned a ticket does not give access to the mailbox's folders. Any other mailbox answers 403
mailbox_not_in_scope. - Guards: while paused, reads and moves answer 423 and nothing reaches Microsoft. A move in
read_onlyanswers 409. Delete is a move to Deleted Items. - The cursor is Graph's next page link. It is refused (400) unless it reads the same mailbox and folder.
- Gateway:
MailboxGatewayrequireslistFolders,listChildFoldersandlistFolderMessages. mail-graph 0.2 has all three. syncNow: the app runs its own sync under its own lease, the same run as its cron. The recipe passesrunHelpdeskSync.
History import
The live sync stores mail from the moment of connection on. The history import adds older mail: by default the last HISTORY_MONTHS (6) before the connection, from the Inbox and Sent Items only. It is off until someone starts it per mailbox.
- Read only. It lists the folders and stores what it finds. It never marks, moves or sends, starts no drafts and sends no notifications.
- Tickets. Mail joins the ticket of its conversation (
conversationId) when there is one, display only: a live ticket keeps its state. Mail without a subject never joins by conversation. Otherwise it starts a ticket inclosed(noise:ignored). Sent mail that starts a conversation takes its first recipient as the customer (one Graph read). A later customer reply opens a new ticket, as after any closed ticket. - Read state is Outlook's. Marking a conversation read sends only the mail Mail shows as unread (0.11.1), and old unread mail does not count (see "Unread window").
- Load.
runHistory(deps, mailbox, { maxPages })reads at mostmaxPagespages of 50 (default 4), newest first, Inbox and Sent Items in turn. Most mail costs no Graph call of its own: it threads from the list page. Run it from a cron of its own, never inside the sync cron. On 429 or an outage it stops and waits for Microsoft's Retry-After, at least 15 minutes ({ status: "throttled" }). - Progress is saved per page in
HistoryState, through the store'sgetHistoryState/saveHistoryState. A crash or a deploy resumes from the last page. Mail already stored, by the live sync or before, is skipped. - Pause:
pauseHistorystops it,startHistorygoes on. The helpdesk's own pause stops it too, with no Graph call.
| Route | What |
|---|---|
| GET mailboxes/:mailbox/history | { supported, state, done, stage, retryAfter, completeUntil }. state null: never started. supported false: the store has no history state. |
| POST mailboxes/:mailbox/history | { action: "start" } (or go on after a pause) or { action: "pause" }. Same response. Database work only; the cron imports. |
Access: staff with access to the mailbox. The typed client has history, startHistory and pauseHistory.
A settings screen shows the response as it is; historyProgress(state, now) works it out:
stage:not_started,running,waiting(Microsoft asked to slow down; it goes on by itself afterretryAfter),pausedordone.completeUntil: all mail of both folders received from this moment on is stored. It is the later of how far each folder got, a done folder counting assince; null until both folders have read a page.
The recipe's helpdesk settings page has the card: one per connected mailbox, with Starten, Pauzeren and Hervatten.
FAQ distillation
Turns the replies a mailbox sent into general answers in the app's kennisbank, so an agent can learn from them. The package only collects question and answer pairs and starts runs of the platform agent klantenservice-faq, which writes klantenservice/faq/<onderwerp>.md. It calls no LLM itself. It is off until someone starts it per mailbox.
- Source: Sent Items only. Every reply lands there, from the helpdesk or straight from Outlook. For each sent reply the package reads its conversation once (
listConversation, any folder, so Archive and the user's own folders count) and takes Graph'suniqueBody: the text without the quoted history. - Pairs. The answer is the reply's own text. The question is the customer's mail after our previous message in the conversation and before this reply. Drafts, mail in Deleted Items or Junk Email, mail from the mailbox itself or from
config.ownAddresses, noise (classifyNoise), forwards and replies without a question are skipped. Each field is cut to 2,000 characters;answeredAtis the reply's date in Europe/Amsterdam. A pair is exactly the agent's input:{ kind: "reply", channel: "email", question, answer, answeredAt }, and a run's input is{ pairs, team: [], batch: { from, to, count } }.teamstays empty: no names or roles from the mailbox. - Two walks. The backfill goes back from the moment of starting to the start date (default
DISTILL_YEARS, 3). Forward picks up new replies after that, every round. Both remember where they got by time and message id, so a page that shifted because new mail came in is never read twice. - Batches. At most 40 pairs and 60 KB of JSON per run. A run starts when a full batch waits, or when anything waits and the last run went out 24 hours ago (or never). One run per mailbox is out at a time. A failed or cancelled run is started once more with the same pairs (event key
<key>-retry); a second failure drops it and says so inlastError. A run without a result after 48 hours counts as failed. At mostDISTILL_MAX_RUNS_PER_DAY(20) runs a day per mailbox, so a long backfill spreads out and its cost stays predictable. - Idempotent. The event key is
faq-<mailbox hash>-<from>-<to>-<content hash>: the same batch always gets the same key. When starting a run throws, the pairs stay pending and the same batch goes again under the same key, so the gateway answers the run it may already have started. - Load.
runDistill(deps, mailbox, { maxPages, maxRunsPerDay })reads at mostmaxPagespages of 50 sent mails (default 4), new replies first, plus about one conversation read per reply. Collection waits while 80 pairs are pending. Run it from a cron of its own. On 429 or an outage it waits for Microsoft's Retry-After, at least 15 minutes ({ status: "throttled" }). - Read only toward the mailbox. No marks, moves, drafts, sends or notifications. The helpdesk's own pause stops it too, with no Graph call.
- State is one JSON value per mailbox (
DistillState), through the store'sgetDistillState/saveDistillState. The cursors and the pending pairs are saved together, so a crash never skips or repeats a reply.
Deps. All three are optional; without any of them the route says supported: false and nothing runs:
- Store:
getDistillState(mailbox)andsaveDistillState(mailbox, state). deps.distiller:{ fire(input, { eventKey }): Promise<{ runId }>; read(runId): Promise<{ status, error? } | null> }. The app adaptscreateRuns({ feature: "helpdesk.faq-distill" })from@dxv-systems/ai; this package does not import it. The feature must point toklantenservice-faqin the Portal.- Gateway:
listConversation(conversationId, { bodyType }). mail-graph 0.5'sMailboxClienthas it.
| Route | What |
|---|---|
| GET mailboxes/:mailbox/distill | { supported, stage, retryAfter, reachedBack, pairsSent, runsSent, since, pendingPairs, runOpen, lastError, lastRunAt }. Counts only: the pair texts never reach the browser. |
| POST mailboxes/:mailbox/distill | { action: "start", since?: "yyyy-mm-dd" } (since on the first start only; it must be before today) or { action: "pause" }. Same response. Database work only; the cron does the rest. |
Access: staff with access to the mailbox. The typed client has distill, startDistill(address, { since? }) and pauseDistill. distillProgress(state, now) works out the stage: not_started, running, waiting, paused or done_backfill (the backfill reached the start date; new replies keep coming in). reachedBack is how far back the backfill got. pairsSent and runsSent count completed runs.
The recipe's helpdesk settings page has the card "Kennisbank vullen uit mailhistorie": one per connected mailbox, with a start date, Starten, Pauzeren and Hervatten.
Typed client
@dxv-systems/helpdesk/client calls every JSON route from the browser, so an app's own screens never write fetch calls, paths or bodies themselves. It contains no server code. Attachment downloads are not methods: use each attachment's href from a message body as a plain link, so the browser downloads it with the response's own headers.
import { createHelpdeskClient, HelpdeskClientError } from "@dxv-systems/helpdesk/client";
const helpdesk = createHelpdeskClient(); // { basePath: "/api/helpdesk", fetch } by default
const { conversations, nextCursor } = await helpdesk.conversations({ folder: "inbox", unread: true, q: "trap" });
const { total } = await helpdesk.counts();
await helpdesk.move(threadId, { to: "archive" }); // undo: { to: "inbox" }
await helpdesk.markRead(threadId, true);
const folders = await helpdesk.folders(mailbox);
const sent = await helpdesk.folderMessages(mailbox, sentItemsId, { q: "frank" }); // each message has to, cc
await helpdesk.syncNow(mailbox);A refused call throws HelpdeskClientError with the route's code, status and Dutch message for staff. Each method returns the route's response type from this package. The ticket routes are there too: send, drafts, assignment, reply files.
Upgrading from 0.18.4
0.19.0 adds runSyncRound: the sync cron's whole round (lease, connectMailbox, syncMailbox, collectDrafts, paused and unreachable handling, refused messages, sweepStuckDrafts, reconcileUnknownSends, throw after the round) moved from the app's runHelpdeskSync into the package, and it logs one helpdesk sync: <outcome> line per run in every outcome. That line is how DXV staff read an app's helpdesk from the Vercel runtime logs: which mailboxes are connected, whether any is failing, and whether the app is not connected at all. No migration. Replace the body of runHelpdeskSync in src/lib/helpdesk/service.ts:
import { loadM365C