Tickets

Use with AI

The ticket, its thread and its activity log: what the tables hold, who may see what, and the endpoints a client calls. Specified by REQUIREMENTS §4.1, ARCHITECTURE §5 and DOMAIN-RULES §2 and §7. Implemented by M1-02 (tickets), M1-03 (messages) and M1-08 (the state machine).

The admin screen built on it is the ticket workspace (M1-15, first part).

The model

Local M11 implementation, pending batch verification: imported tickets expose imported: { source, number, url } | null on workspace responses. Original numbers and native IDs are searchable alongside Helpdock’s new ticket number, and from any view: an exact one finds the ticket even when the view’s filters would hide it (listing, #221). The original URL is a navigation link with query strings/fragments removed; an unsafe or ambiguous address is omitted. The Source filter distinguishes imported and native tickets and can be saved in a view. Every source lookup still narrows the ticket’s existing brand/department policy. Name-only former agents retain their saved display name in message history. The imported activity line retains original source dates; history never implies a new delivery to the customer. These UI/API changes have not yet passed the deferred regression/browser batch.

tickets ──< ticket_messages          one thread per ticket, ordered by `seq`
        ──< ticket_activity          who changed what, and how
        ──< ticket_tags ──> tags     the chips, the brand's own list
        ──< ticket_participants      the CCs (M1-13)
        ──> ticket_statuses          the brand's own list, mapped to four system states
Table Scope Notes
ticket_statuses brand The statuses a brand offers. Brand-scoped, not department-scoped: an Agent has to read the name of the status a ticket in their own department is in.
tickets brand and department department_id is not null. A ticket with no department would be invisible to everyone.
ticket_messages brand and department department_id is denormalised from the ticket by trigger.
ticket_activity brand and department The same, and for the same reason.
ticket_tags brand and department The same again (M1-06). The primary key is (ticket_id, tag_id), so adding a tag twice is one row.
ticket_participants brand and department The CCs (M1-13). Unique on (ticket_id, contact_id), so copying somebody in twice is one row.
tags, custom_field_defs, ticket_templates brand Configuration, not tickets: the same list in every department. Ticketing settings covers them.

Department scope

DOMAIN-RULES §1.3 layer 3: the three ticket tables carry the department predicate on top of the brand one.

brand_id = ANY(app.brand_ids)
  AND (app.all_departments OR department_id = ANY(app.department_ids))

The child tables carry a denormalised department_id so the policy never needs a join. Three triggers, built from two functions, keep it true, and nothing else writes it:

Trigger When What
ticket_messages_department, ticket_activity_department before insert Reads the parent ticket’s department and overwrites whatever was passed. The read is subject to the caller’s own policies, so a ticket the caller cannot see raises insufficient_privilege naming the ticket.
tickets_department_moved after a department change Rewrites every message and activity row of that ticket. A ticket escalated from Support to Billing takes its thread with it, or Support would keep reading it.

What this means in practice: an Agent of Support asking for a Billing ticket of the same brand gets 404 by id, by message cursor and by activity, a list that simply does not contain it, and a forbidden acknowledgement on a ticket:<id> socket join. Never 403 over HTTP — the transaction cannot see the row, so the api genuinely does not know whether it exists, and “forbidden” would confirm that it does. No answer distinguishes “not found” from “not yours”.

Escalation into a department you cannot see is allowed — §1.2: “it is how escalation works” — and M1-08 is what made it work. The WITH CHECK half of the department policy would refuse the write, and the policy shape is deliberately the same on every tenant table, so the move runs inside a briefly widened department scope rather than under a second policy or a SECURITY DEFINER function (packages/db/src/tenant.ts, withWidenedDepartments).

Three statements need that window and all three are inside it: the UPDATE, the tickets_department_moved trigger that follows the thread, and the activity row whose own department the trigger then overwrites. The brand is never widened, the previous scope is restored in a finally, and the audit row is written outside the window — audit_log is brand-scoped, so it does not need it, and writing it outside is the proof.

Afterwards the ticket is gone from the actor’s view: the PATCH answers 200, and the next GET answers 404. See the lifecycle below.

Statuses

Four system states — open, on_hold, escalated, closed — and a row per status mapped to one of them, with two flags (§2.1):

Flag Meaning
pauses_sla SLA clocks are paused while the ticket is in this status
awaiting_customer The ball is with the customer; time-based rules and reports read it

Every brand is seeded with seven when it is created, by seedBrandStatuses:

Name System state Flags Why it exists
Open open default Where a new or reopened ticket lands
Awaiting customer on_hold pauses_sla, awaiting_customer §2.1 ships it with every brand
Snoozed on_hold pauses_sla (the resolution clock only) M14-02: a ticket put away until a time; see Snooze
Escalated escalated — So the fourth state is reachable without adding a status
Closed closed — §2.2
Spam closed — §2.1: no auto-responder, no CSAT, excluded from reports
Merged closed — §2.4: what the secondary of a merge closes into

Spam and Merged additionally carry excluded_from_reports: §2.1 words Spam as “closed, excluded from reports” and §2.4 says the same of Merged, and §2.2 makes it the reason a close into one of them schedules no CSAT. It is a flag rather than a name, because a brand may rename Spam.

They are marked is_system. A brand may rename and recolour them; nothing deletes them, because code refers to what they are rather than what they are called. Their system state and their two behaviour flags are fixed for the same reason — the api answers status-state-fixed to a request that would move one. color is one of the five status hues of DESIGN §2.1 — a brand tints, it never adds a hue.

A brand created before M1-02 has no statuses and cannot hold a ticket; the api answers 409 and says so. seedBrandStatuses is exported from @helpdock/db for whatever creates a brand.

Numbers

A ticket’s display number comes from that brand’s own sequence, created with the brand — brand_ticket_seq_<the brand's uuid with its hyphens removed> — and prefix is copied onto the row rather than joined: HD-1042 is printed in emails that outlive a rename.

Numbers are not dense. nextval is non-transactional by design — that is what lets two requests draw two numbers without waiting for each other — so a rolled-back creation burns its number. A gap is not a defect; a duplicate would be, and tickets_brand_number_key is what would catch one.

Tags and custom values

A ticket carries two things a brand defines for itself (M1-06). Both are described in Ticketing settings; what follows is what they look like on a ticket.

Tags

The chips are embedded in the ticket, exactly as the status is, because every list row draws them and a row that had to resolve its own tag ids would render before it knew what it was showing:

{
  "id": "0199f4b2-…",
  "subject": "Refund for order 42",
  "tags": [{ "id": "0199f4b2-…", "name": "Refund", "nameAr": "استرداد", "color": "info" }]
}

tags is optional on the wire and the api always fills it: it arrived after the ticket did, so a client built against the M1-02 shape and a fixture written against it stay valid, and a renderer that has not learned about tags draws nothing rather than crashing on undefined.

They are replaced as a set, never added and removed one at a time:

PUT /api/brands/:brandId/tickets/:ticketId/tags

{ "tagIds": ["0199f4b2-…", "0199f4b3-…"] }

That makes it idempotent, it is one activity row instead of four when an agent changes three chips at once, and two agents editing the same ticket end at one of the two sets rather than at a mixture of both. A replace that changes nothing writes nothing — no ticket.tags.changed row, no outbox event — for the same reason a PATCH that changes nothing does not.

A change bumps updated_at, because the list orders by it and a ticket that has just become urgent must not sit at the bottom of the queue.

An id that is not this brand’s answers 404. A ticket in another department answers 404 too, from the policy: the ticket_tags_department trigger looks the parent up under the caller’s own row-level security, finds nothing, and the insert never happens — the same shape ticket_messages and attachments use.

Participants (M1-13)

A ticket’s participants are its contact, its CCs and its staff (DOMAIN-RULES §2.5). They decide who may thread into the ticket by email (§4.3) and who receives public replies — both M2’s to act on. Only the CCs are stored: the contact is tickets.contact_id, and the staff are the assignee and every staff member who wrote on the ticket.

A CC is a contact with the normalised address it was added under. Typing an address links the contact that already holds it, or creates one holding it unverified (email.cc): copying somebody in grants that contact nothing, so there is no history to protect and no reason for a second contact. The address stays on the row, so a later merge of the CC’s contact never changes who may thread in; the list shows the surviving contact’s name.

GET    /api/brands/:brandId/tickets/:ticketId/participants
POST   /api/brands/:brandId/tickets/:ticketId/participants     { "email": "finance@acme.de" }
DELETE /api/brands/:brandId/tickets/:ticketId/participants/:participantId

All three answer { contact, ccs, staff }. Adding is idempotent, and copying in the ticket’s own contact changes nothing. An address that is not one answers 400 with contact.reason = identity-invalid and a problem. Each change writes ticket.participants.changed to the activity log — naming the contact id, never the address — bumps updated_at and enqueues ticket.updated.

ticket_participants is department-scoped like every child of a ticket: its department_id is filled by the shared trigger, follows the ticket through a department move, and a ticket in another department answers 404.

Another module copies a contact in by id through TicketParticipantsService.addCcParticipant(context, ticketId, contactId), exported by ParticipantsModule. M1-09’s ticket merge uses it to add the secondary’s contact as a CC (§2.4); M2’s inbound email uses it for a Cc: line.

Custom values

tickets.custom is a jsonb object keyed by custom_field_defs.key. Every write is validated against the brand’s own ticket definitions before it reaches the column, so a value that does not fit its type, or a key nobody defined, is a 400 rather than a row somebody believes they saved.

POST /api/brands/:brandId/tickets
{ …, "custom": { "tier": "gold", "renews_on": "2026-03-01" } }

PATCH /api/brands/:brandId/tickets/:ticketId
{ "custom": { "tier": "silver", "renews_on": null } }

A POST is a create: every required field has to arrive. A PATCH is a patch: a key it omits is left alone, and a key set to null is cleared. The stored object never holds a null, so “unset” has one representation.

A key whose definition has since been deleted is filtered out on the way to a screen rather than rewritten out of the row, so deleting a definition is not a migration over the whole brand and re-creating it brings its values back.

A ticket field marked required to close (M14-17, Ticketing settings has the full rule) stops a person’s close: a PATCH that moves the ticket into a closed state while the field is empty answers 409 with error.lifecycle.reason = 'fields-required-to-close' and error.lifecycle.fields naming the keys that are still empty. Filling the field and closing in one request goes through. The system’s closes — a rule, a time-based rule, a merge, a mark as spam — are never stopped, and their activity row records closedWithout with the keys it went without, and the thread shows it as “ closed the ticket without ”. A merge records it on the ticket that closes, not on the primary. Choosing Spam from the status picker is not stopped either. Imports write closed tickets with no gate.

Messages and seq

DOMAIN-RULES §7: “Every message has a client-generated client_id (UUIDv7) and a server-assigned seq, monotonic per conversation.”

  • seq is assigned inside the request’s transaction. nextMessageSeq takes a SELECT … FOR UPDATE lock on the ticket row first, then reads max(seq) + 1. Twenty simultaneous replies queue on that lock, so no two read the same maximum; ticket_messages_ticket_seq_key is the backstop. The ticket row is locked rather than the messages because the first message of a ticket has no message row to lock.
  • client_id is looked up inside that lock, so a retry that arrives while the first attempt is still committing finds the row rather than writing a second one. A retried send returns the stored message, with the same id and the same seq.
  • A message is “sent” when the client holds a seq. Until then the composer shows “sending”; the socket frame is a notification, never the receipt.
  • external_message_id is unique per (brand, channel), which is what stops a redelivered IMAP message or Telegram update becoming a second row (§6).

Bodies are sanitised on the way in and stored sanitised (ADR 0007). body_text is extracted from the sanitised html by the same call, so the text can never come from a body the sanitiser has not seen. Remote <img src> is blocked by default and cid: references are kept for M1-10 to resolve; M2-07 adds the per-brand toggle.

Two things about the sanitiser are worth knowing before rendering a body:

  • A URL survives only if it is absolute. A scheme allowlist is applied only to a URL that has a scheme, so src="/pixel.gif" and href="/settings" are dropped outright: a relative URL in a message from a stranger resolves against whatever page renders it, which makes it a read receipt fired by the reader’s own browser, or a link that looks like a genuine in-app one.
  • body_text is text, and only text. Entities are decoded, so a message that literally reads <script>alert(1)</script> comes back as those characters. That is right for the email text part, the list preview and AI retrieval — and it must never be interpolated into HTML. body_html is the field that is safe to render.

Two more things the sanitiser does to a body, which change what is stored:

  • every surviving <a> leaves with rel="noopener noreferrer nofollow", whatever it arrived with, and a target is normalised to _blank;
  • a body carrying more than 6,000 opening tags is refused with 400. The sanitiser’s cost is super-linear in nesting depth rather than in size, and it runs synchronously inside the request’s open transaction, so a body built to be expensive would stall every other request on the replica. The count is taken on the raw input, before the parser sees it, and is deliberately a conservative over-count.

Activity

ticket_activity is part of the ticket, not the brand’s administrative trail: it is rendered in the thread, it is department-scoped like the ticket, and retention purges it with the ticket. audit_log stays what an admin reads.

Local M11 pagination, pending batch verification: ticket details include the newest activity page and activityNextBefore. The activity endpoint returns activity plus nextBefore; pass that UUID as before to read an older page. Pages contain at most 100 entries and render oldest first within each page. The UUID anchors a row in this same visible ticket, and PostgreSQL compares its native timestamp/UUID tuple, retaining sub-millisecond precision. A missing or foreign anchor is refused. The workspace offers older/newer/latest controls and keeps only one older activity payload in memory, with inactive page caches discarded immediately. Message paging remains independently available.

Action Written when
ticket.created A ticket is created; to.arrival records how it arrived (below, M14-08)
ticket.updated Subject, priority, department, team or assignee moved — one row, with from and to naming every field that moved
ticket.status.changed The status moved, through the transition hook
ticket.replied A public reply was added
ticket.note_added An internal note was added
ticket.closed The status change took the ticket into a closed state (M1-08)
ticket.reopened It took the ticket out of one (M1-08)
ticket.continued A customer reply past the reopen window started a new ticket; written on both (M1-08). On the new ticket, to.arrival records the continuation (M14-08)
ticket.deleted An Admin soft-deleted it (M1-08)
ticket.escalated Recorded in audit_log, not here: the activity row moves with the ticket
ticket.source_article A widget conversation or web form ticket was opened from a help center article’s “Still need help?”; to holds articleId, title and locale, and the thread shows “Came from the help center article …” (M5-08)
ticket.imported Imported provenance, original number and dates (local M11 implementation), and to.arrival with entry: import (M14-08)
ticket.imported.event Original source activity with its preserved actor, date and changes (local M11 implementation)

ticket.status.changed is written for every status move. A close or a reopen writes it and the more specific verb beside it, because a reader of the thread wants the second word.

via is how: ui for the admin, api for an api key, rule for M3-03’s rules, ai for M7, system for a worker. A field set to the value it already holds is not a change and is not logged. A rule’s AI triage action that applies its answer (M7-07) writes its changes as the rule (rule:<id>) with via = ai, which is how the routing trail tells “by AI triage” from “by rule”.

Arrival and the routing trail

M14-08, DOMAIN-RULES §2.8. Every path that files a ticket records how it arrived in its creation row’s to.arrival, through one helper (apps/api/src/tickets/routing/arrival.ts), so the writers cannot drift:

{ "entry": "mailbox", "entryId": "<mailbox id>", "address": "billing@acme.com",
  "departmentId": "<department id>", "reason": "entry_department" }
Path entry entryId reason
Inbound email mailbox the mailbox, with address: the address the message was written to — the mailbox’s own when it is among the recipients, otherwise Delivered-To (or X-Original-To when absent) if nonempty and at most 320 characters, otherwise the mailbox’s own address; unrelated To/Cc recipients are never used as a fallback entry_department; referenced_ticket when the mail named a ticket its sender is not a participant of and was filed in that ticket’s department (§4.3)
Chat widget widget null brand_first_department: the widget files into the brand’s first department until M19-02 gives each widget its own
Web form web_form null entry_department when the form names a department, otherwise brand_first_department
Telegram telegram_bot the bot entry_department
WhatsApp, Messenger, Instagram meta_account the number, Page or account entry_department
POST /tickets with an API key api_key the key named_by_api
POST /tickets or a split by a person staff the person chosen_by_staff
A reply past the reopen window (§2.3) where the reply came in: the mailbox (with the address written to), the bot, the account or the widget — not necessarily the closed ticket’s that entry’s continued_from, in the closed ticket’s department, on the new ticket’s ticket.continued row
An importer (M11) import the import run import_mapping, on the ticket.imported row

GET /tickets/:ticketId/routing reads the trail back from the activity log; nothing new is stored. It is read in the request’s own transaction, so it follows the ticket’s department policy: a ticket in another department answers 404 like every other read of it. The answer is structured, and the admin words it in the reader’s language:

  • origin: recorded (the channel, entry, address, reason and the arrival department), unrecorded for a ticket filed before M14 (its channel only), or imported with the source, for which the trail stops there: imports run no rules and assign no one.
  • steps: every department, team, priority and assignee change written by the system after the arrival, oldest first, until the first change by a person (a staff member or an API key; a reply or a note is not a change), at most 50. Each names its actor: rule with the rule’s name, or name: null for a rule since deleted; ai_triage; assignment with the department’s mode; sla for an escalation step; system for anything else.

The workspace shows it as How it got here.

The lifecycle

DOMAIN-RULES §2.2 is the whole of it, and M1-08 implements it as one constant, apps/api/src/tickets/lifecycle/transitions.ts, rather than as rules spread across the handlers that cause each event. transitions.test.ts holds a second copy typed out from the document and asserts the two agree cell by cell, so a change to one without the other fails.

Current state Event Result
open, on hold, escalated Customer public reply The brand’s default open status. awaiting_customer is cleared with it, because the flag lives on the status
open Agent public reply, toggle on Awaiting customer
any Agent sets status That status
open-like Agent closes closed_at set, onResolved, and onClosedForCsat unless excluded
closed Customer reply The reopen policy, below
closed Agent reopens Default open status, closed_at cleared, onReopened
any Marked spam Spam: closed_at kept or set, onResolved, no onClosedForCsat, ticket.spam rather than ticket.closed; see Spam
any Merged Merged, with merged_into_id — see Merge and split
any Soft-deleted by Admin Hidden from every view; purged by retention (§11)

Two facts are checked before the table and refuse every event, because they answer all of them the same way: a ticket with merged_into_id belongs to the one it was merged into (§2.4), and a soft-deleted ticket is not acted on at all. Both answer 409 with error.lifecycle.reason — ticket-merged, ticket-deleted, ticket-not-closed for a reopen of something that was never closed, or ticket-not-spam for “Not spam” on a ticket that is not — so the screen picks a sentence rather than printing the api’s.

An agent “closing” a ticket is an agent setting a status whose system state is closed: there is one control on the screen and it is a status picker. Which of the three rows happened is read off the states afterwards, which is what decides whether closed_at moves and which hook fires.

Which status plays which part

Never by name — a brand may rename any of them (packages/db/src/ticket-statuses.ts). A flag where one says what the row is; system_key (M1-09) where the flags cannot tell two rows apart, which is Spam and Merged:

Part Found by
Where a new or reopened ticket lands is_default
Awaiting customer awaiting_customer, seeded rows first
Out of reports and round-robin counts excluded_from_reports (Spam and Merged)
Spam — no CSAT, no auto-reply, the 30-day purge system_key = 'spam', read as is_spam (below)
The secondary of a merge — no CSAT merged_into_id on the ticket
The status a merge closes into system_key = 'merged' (seeded, backfilled by migration 0016)

One answer to “which row is Spam?”. system_key is the source: seeded as spam on every brand, backfilled by migrations 0016 and 0017, and unique per brand. ticket_statuses.is_spam is a generated column, coalesce(system_key = 'spam', false), kept because everything that treats spam differently reads a boolean through isSpamStatus (@helpdock/schemas): the lifecycle’s “Mark as spam” and CSAT exclusion (M1-11, M1-12), and the spam purge (M1-14). Nothing writes it, so it cannot disagree with the key. excluded_from_reports is wider — Merged carries it too — and is only ever read as “leave it out of a count”.

The reopen policy

§2.3, per brand:

reopenPolicy A customer reply to a closed ticket
{ "kind": "within_days", "days": 7 } Reopens if closed_at is less than N days ago, otherwise a new ticket
{ "kind": "always" } Always reopens
{ "kind": "never" } Always a new ticket

“Less than N days ago” is taken literally: a reply at exactly N days creates a new ticket. The window is wall-clock time, not business hours — §3.1 says “business hours” where it means them, and a customer’s week does not pause for a brand’s holidays. A closed ticket with no closed_at reopens: of the two wrong answers, “the thread stayed together” is the one a customer can live with.

A reopen returns the ticket to the default open status, clears closed_at, writes ticket.reopened to the activity log, fires onReopened and enqueues ticket.reopened.

A new ticket gets parent_id = the closed ticket, the same department, contact, priority and channel, and a fresh number. Both tickets get a system message — “Continued from HD-1042” on the new one, “Continued in HD-1101” on the old — written in the contact’s language, falling back to the brand’s default locale. A desk that reads Arabic must not decide what an English-speaking customer is sent. Auto-responders treat it as a new ticket, which is M2’s to honour: it is an ordinary ticket with a parent_id, and nothing suppresses anything.

Retries are covered on both branches. The reply path looks for the client_id on the ticket that was written to and on any ticket continuing it, so a retried send never creates a second continuation (§7).

The hooks later milestones fill

apps/api/src/tickets/lifecycle/hooks.ts names eight moments. They are a provider, so M3-02 and M1-12 replace one line of TicketsModule rather than editing the service that calls them. Both lines are in: SlaLifecycleHooks (apps/api/src/sla/sla-hooks.ts) fills the clocks’ moments and extends CsatLifecycleHooks (apps/api/src/csat/csat-hooks.ts), which fills onClosedForCsat. What the clocks do at each is the SLA guide.

Hook Fires when Filled by
onCreated A ticket is filed: created, continued (§2.3) or split (§2.4). Every path that inserts a ticket calls it M3-02: starts the clocks
onChanged After every status, priority or department write, with the previous department on a move M3-02: pause, resume, retarget
onResponded A public staff reply (by: 'staff'); M3-03’s rule reply and M7’s auto-reply call it with rule and ai M3-02: meets the response clock
onResolved A ticket reaches a closed state, including spam — a clock left running on a ticket nobody will touch again is a clock that breaches. Not on a merge, which fires onMerged M3-02: resolution met; spam stops the clocks
onClosedForCsat The same, unless the ticket is merged or the status is Spam (is_spam) M1-12: writes csat.requested to the outbox when the brand has CSAT on
onReopened A closed ticket comes back, by policy or by an agent (§3.5) M3-02: next-response and resolution clocks
onMerged A ticket was merged into another (§2.4): stop both clocks without recording them as met, and keep the ticket out of compliance M3-02
onUnmerged A merge was undone; mergedMs is how long it lasted, to leave out of the clocks M3-02

Every hook runs inside the caller’s transaction, after the ticket row has moved and before the outbox row is written, so whatever it writes commits with the transition or rolls back with it. A hook that needs a job enqueues it through the outbox like everything else; it must not enqueue directly and must not open a transaction of its own.

Soft deletion

DELETE /api/brands/:brandId/tickets/:ticketId, brand:manage. It stamps deleted_at and nothing else: the ticket keeps the status it was in, because restoring one and reporting on what was deleted both need it.

Every read narrows on deleted_at IS NULL from there — the list, the ticket’s own URL, the thread, the activity — and all of them answer 404, the same answer a ticket in another department gives. A 410 would confirm it had existed. The department-delete guard still counts it, which is what stops a department being removed out from under a ticket that could be restored.

Spam

DOMAIN-RULES §2.2: “Marked spam — Spam status; no auto-responder, no CSAT, sender added to block list if the agent ticks ‘block sender’, excluded from reports and round-robin counts.” M1-11.

Marking is POST /tickets/:ticketId/spam with { "blockSender": true|false }. The ticket moves to the brand’s Spam status — the row with is_spam, never found by name — and in the same transaction:

  • ticket.status.changed and ticket.marked_spam go to the activity log;
  • a ticket that was open-like gets closed_at and fires onResolved, so M3’s clock stops; one that was already closed keeps its closed_at;
  • onClosedForCsat does not fire, because the status is Spam (isSpamStatus);
  • the outbox gets ticket.spam, not ticket.closed, so nothing that acts on a close — a survey, an auto-responder — can mistake spam for one;
  • with blockSender, the ticket’s sender goes on the block list (ticketing settings). Which identifier is the sender follows the channel: a Telegram ticket blocks the chat, a WhatsApp, Messenger or Instagram ticket blocks the customer’s id on that platform, and anything else the contact’s address, then phone, then chat. A visitor id or an external id is never blocked. The brand’s own address or domain is refused (sender-is-own) and the whole request rolls back with it.

Picking Spam from the status picker is the same move without the block, and it sends ticket.spam too. GET /tickets/:ticketId/spam-sender is what the dialog reads first: the sender, whether the brand offers the checkbox (offerBlockSender), whether it may be blocked, and whether it already is.

“Not spam” is DELETE /tickets/:ticketId/spam. It is an agent reopen: the default open status, closed_at cleared, onReopened, ticket.reopened — a ticket wrongly marked as spam is a ticket somebody is still waiting on. On a ticket that is not spam it answers 409 ticket-not-spam (or ticket-not-closed when it is not closed at all). A block made with it stays; undoing that is the Spam tab’s.

What being spam means to everybody else is one predicate, read off the status and never off its name, exported from @helpdock/schemas:

Consumer Asks And then
Auto-responders (M2) isSpamStatus(status) send nothing
CSAT (M1-12) nothing: the lifecycle already withholds onClosedForCsat —
Round-robin and load caps (M1-07) countsInReports(status) a spam or merged ticket counts against nobody
Reports (M3) countsInReports(status), or ticket_statuses.excluded_from_reports = false in SQL left out
Retention (M1-14) ticket_statuses.is_spam purged after the brand’s spam retention (§11, 30 days by default)

The default views already leave spam out: every one of them asks only for open-like system states, and Spam is closed. “All tickets” shows it, with its danger badge, because that view is the desk’s whole history. The sidebar’s counts are the views’ own filters, so they leave it out too; M1 has no report to exclude it from yet.

Merge and split

DOMAIN-RULES §2.4, built by M1-09 in apps/api/src/tickets/merge/. The rules are pure functions in merge-rules.ts; merge.service.ts writes the rows. All three routes are ticket:write, and every path names the ticket the agent has open.

Route Answers
POST /tickets/:ticketId/merge { "primaryTicketId": "…" } { primary, secondary } — :ticketId is the secondary, which closes
POST /tickets/:ticketId/unmerge { primary, secondary } — inside 24 hours of the merge
POST /tickets/:ticketId/split { messageIds, subject, departmentId, priority? } 201 and the new ticket’s detail

A ticket the actor cannot read — the primary in another department, or in another brand — answers 404, exactly like one that does not exist (§1.2). A rule that refuses answers 409 with error.lifecycle.reason:

Reason When
merge-into-self The primary is the secondary
ticket-merged The secondary is already merged — unmerge is the only way back. Also a split of a merged ticket, and a PATCH that would move a merged ticket’s department
merge-into-merged The primary is itself merged; merge into the ticket it went to. This is also what makes a cycle impossible
ticket-not-merged Unmerging a ticket that is not merged
merge-window-closed Unmerging 24 hours or more after the merge
merge-primary-deleted Unmerging a ticket whose primary an Admin has since deleted
attachments-in-flight A message to split has an attachment the pipeline has not finished with

Merge

In one transaction:

  1. both tickets are locked, in id order, so two merges of the same pair queue rather than deadlock;
  2. the primary gets a system message “HD-1042 was merged into this ticket”, in its contact’s language, as §2.3’s “Continued in” is;
  3. the secondary moves to the Merged status with merged_into_id, merged_at, merged_by_id, closed_at (kept if it was already closed) and what an unmerge needs: pre_merge_status_id, pre_merge_department_id and merge_message_id;
  4. the secondary moves into the primary’s department;
  5. the primary’s tags become the union of both (ticket.tags.changed);
  6. onMerged fires, and MergeParticipantsHook.onContactMerged when the two contacts differ;
  7. ticket.merged is written to both activity logs, and ticket.updated to the outbox for both, which is ticket:changed in both rooms.

Messages are not moved. GET /tickets/:primaryId answers with merged: every ticket merged into it — a chain is flattened, and mergedIntoId says which ticket each went into — with the oldest 100 of its messages, read-only, each keeping its own ticketId. The secondary’s read answers with mergedInto. Both carry unmergeableUntil, null once the 24 hours have passed.

Access follows the primary because of step 4. §2.4 allows a merge across departments; the secondary’s thread, activity, tags and attachments follow it through helpdock_ticket_department_moved, and the tickets_merged_follow_primary trigger (migration 0016) keeps every merged ticket in its primary’s department when the primary moves later, down a chain. So whoever may read the primary may read the messages shown inline in it and open their attachments — at /tickets/:secondaryId/attachments/:id, under the ordinary department policy, with no second authorisation path — and nobody else may. A merged ticket’s department cannot be changed on its own: PATCH refuses it with ticket-merged.

Clocks. A merge stops the secondary’s clocks and keeps it out of compliance: the Merged status is excluded_from_reports and the ticket has merged_into_id. It does not fire onResolved — the ticket was folded into another, not resolved. The primary’s clocks are untouched.

The contact. §2.4 makes the secondary’s contact a CC of the primary when the two differ. Participants are M1-13’s (§2.5), so the merge calls MergeParticipantsHook.onContactMerged — a provider in TicketsModule that does nothing today and that M1-13 replaces.

Unmerge

Inside 24 hours of merged_at, and refused at exactly 24 hours. The secondary goes back to the status it was in (or the default open status if that one has been deleted since), gets closed_at back only if that status is a closed one, and returns to the department it was merged from — which, when that department is outside the actor’s scope, is the escalation §1.2 already allows, made in the same widened window PATCH uses. merged_ms accumulates how long the merge lasted and onUnmerged passes it on, which is how “clocks resume with the time paused during the merge excluded” reaches M3-02. The primary gets “HD-1042 was unmerged from this ticket” and keeps the tags the merge gave it: §2.4 does not say they go, and nothing records which ones it would not otherwise have by now.

A deleted primary keeps the merge. When an Admin has soft-deleted the primary, unmerge answers 409 merge-primary-deleted rather than 404, and the secondary stays merged: §2.2 hides a deleted ticket from every view, so nothing can be written to it, and a 404 would claim the secondary in the path does not exist. It leaks nothing. A secondary always sits in its primary’s department, so whoever can read the secondary could read the primary, and the only way it is missing is the delete.

Linked tickets

Every ticket read carries related, each ticket linked to this one with how: parent (the closed ticket this one continues, §2.3), mergedInto and mergedFrom (the two ends of a merge), splitFrom and splitTo (the two ends of a split), in that order. apps/api/src/tickets/merge/related.ts builds it from one query under the caller’s scope.

A visible entry has the id, reference, subject and status. A link the reader cannot open comes in two kinds (§1.2):

  • One the read ticket names itself (parentId, mergedIntoId, splitFromId) is { "visible": false, "relation": "…" } and nothing else. The id is already on the ticket, so saying there is a ticket there adds nothing; which ticket, and whether it sits in another department or was deleted, is what stays unsaid.
  • One that names the read ticket (merged into it, split from it) is not found by the scoped query, so it is left out.

Split

The named messages are copied onto a new ticket: split_from_id, the same contact and channel, the department and subject the agent chose, the priority chosen or the original’s, a fresh number, and the default open status. Each copy has copied_from_message_id, keeps its original created_at and historical author_display, and takes the new ticket’s own seq from 1; a system message “Split from HD-1042” follows them, and the original gets “Messages split to HD-1043”. The new ticket is announced with ticket.created, which is where M3-02’s fresh clocks start; the original’s are not touched.

The department is one the actor may file a ticket in, as for creation — a split is filing a ticket, not escalating one. An id that is not a message of the ticket answers 404; a system message answers 400.

Attachments are copied as rows, not bytes. A copy of a ready attachment points at the same object with the new ticket’s ticket_id, message_id and — through the trigger — department_id, which is what authorises a download through it; copied_from_attachment_id names the original. The copy retains the original’s origin, including imported and channel files. attachments.s3_key is therefore unique among originals only (attachments_s3_key_original_key). Rejected and infected rows are not copied, and a message whose attachment is still pending or processing is refused with attachments-in-flight, because its copy would never hear from the worker. Every read and purge of the bytes goes by the row’s s3_key, never its ids (media/keys.ts objectKeyBeside), so a copy downloads the original’s objects; and a purge — retention’s or a contact’s erasure (M1-14) — leaves an object alone while any row it is not removing still names the key (media/object-purge.ts). The last row to go takes the bytes with it.

Both tickets’ reads carry related: the ticket this one was split from and the tickets split from it, so the thread can link the references its system messages name.

Views

A view is a list query with a name (M1-05, REQUIREMENTS §4.1). Its filters are the GET /tickets query schema itself, less the cursor and the page size — one schema, not two — so anything the list accepts a view can save, and a view can never ask for something the list does not understand. Views are rows of the views table (migration 0022_views), brand-scoped like every tenant table.

A view never widens access. Resolving one produces list parameters, and those go through the same department-scoped read as a query typed by hand. A view shared with Billing shows a Support agent nothing they could not already see; its count is the list’s own WHERE, run in the reader’s transaction.

Who sees which

View Sees it Changes it
Personal Its owner, and nobody else Its owner
Shared with the brand Everybody in the brand An Admin, or a Team Leader who reaches every department
Shared with departments Staff whose scope reaches one of them An Admin, or a Team Leader who leads all of them

A personal view is guarded by the database, not by the service: a restrictive policy (views_owner_only) on top of the brand policy keeps a row with an owner_id its owner’s, so another person’s personal view is a row the request cannot read, and every route answers 404 for it — the same answer as for an id that does not exist. The RLS negative suite covers it. Sharing needs ticketing:manage, so an Agent or a Viewer keeps personal views only; a Team Leader restricted to some departments may share only with departments they lead, never with the whole brand. Every change to a shared view is audited (view.created, view.updated, view.deleted); a personal one is nobody else’s business.

The built-in views

Every brand is seeded with My open (assigneeId=me, the live states), Snoozed (snoozed=only, assigneeId=me; Snooze), Unassigned (assigneeId=unassigned, the live states), Overdue (overdue=true, the live states), Escalated (systemState=escalated), and one All open · per department (that department, the live states), in both languages. The department ones follow the department: created with it, renamed with it unless the brand has renamed the view itself, and deleted with it.

A built-in view may be renamed, reordered and hidden for the brand. It may not be deleted, refiltered or reshared: those answer 409 view-is-built-in, because REQUIREMENTS §4.1 promises every brand those queues. Only a shared view can be hidden; a person deletes their own.

Counts

GET /views/counts answers one number per view the sidebar shows, in one statement: a scalar subquery per view, each the list’s WHERE with a LIMIT 1000 inside the count, so each walks the index its filters reach and stops. A number past 999 reads 999+ (capped: true); nobody triages a queue by whether it holds a thousand or four. Migration 0022 adds one index for it, tickets_brand_status_updated_idx (brand_id, status_id, updated_at, id), which turns a view narrowed by state across departments — Escalated, Overdue’s live states — into a range scan per status rather than a read of every ticket in the brand. The counts request is a scenario of the performance gate.

Side effects and realtime

Every mutation writes its outbox row in the same transaction as the change (DOMAIN-RULES §6). Seven events: ticket.created, ticket.updated, ticket.replied, ticket.note_added, from M1-08 ticket.closed and ticket.reopened, and from M1-11 ticket.spam.

The last three carry the same payload as ticket.updated and reach the same rooms. What they add is a name, so M1-12’s survey and M3’s clocks can consume one event instead of diffing two reads of the ticket — and so a move into Spam is never heard as a close.

request  →  tickets + ticket_activity + outbox   (one transaction)
relay    →  BullMQ outbox.event                  (after commit, jobId = outbox.id)
worker   →  Redis pub/sub                        (the api process runs no queue)
api      →  RealtimePublisher → sockets          (every replica, its own sockets)

The third hop exists because APP_ROLE=worker runs no Nest application and holds no Socket.IO namespace, while APP_ROLE=api runs no queue. It is the same Redis pub/sub shape principal.revoked already uses.

Each event reaches ticket:<id> (whoever has the ticket open) and department:<id> (whoever has a queue open, because a new ticket has to appear in a list nobody was looking at). A move reaches the old department’s room as well, or the ticket would sit in a queue it has left until somebody reloaded, and it turns the ticket room out: everyone in it joined under the old department’s scope, so they re-join through the same check they passed once.

The payloads carry ids only — no body — so an internal note cannot leak over a socket, and a screen re-reads over REST. See the realtime guide.

Endpoints

All under /api/brands/:brandId, and every one declares a permission. What a role may ask for is DOMAIN-RULES §1.2; which departments it reaches is the policies’.

Route Declares Answers
GET /ticket-statuses ticket:read The brand’s statuses, for the picker and the badge
GET /ticket-mailboxes ticket:read The brand’s mailboxes (id, address, display name, department), for the list’s Mailbox filter. No connection settings; those stay behind brand:manage
GET /tickets ticket:read A filtered, sorted, cursor-paged list
POST /tickets ticket:write A ticket and its first message
GET /tickets/:ticketId ticket:read The ticket, the first page of its thread and its activity
PATCH /tickets/:ticketId ticket:write Subject, priority, department, assignee, status, custom values, and snoozedUntil to snooze, move or end a snooze (M14-02, Snooze). Setting a team answers 400 until M1-01; clearing one with null is allowed
GET /tickets/:ticketId/messages ticket:read The thread after a seq
POST /tickets/:ticketId/messages ticket:write A public reply or an internal note
DELETE /tickets/:ticketId brand:manage Soft-deletes it (§2.2). Admin only: hiding a ticket from the whole brand is not an edit
GET /tickets/:ticketId/activity ticket:read Bounded activity pages; newest page by default, each page returned oldest first. before=<entry UUID> loads an older page; limit is 1–100
GET /tickets/:ticketId/snooze-presets ticket:read The Snooze menu’s four times against the department calendar (M14-02)
POST /tickets/bulk ticket:write, then per ticket Previews or applies one set of changes to up to 50 tickets (M14-03, below)
POST /tickets/bulk/:operationId/undo ticket:write, the actor only Puts back a bulk edit within 60 seconds (M14-03)
GET /tickets/:ticketId/routing ticket:read How it got here: the arrival and the automatic steps after it (above, M14-08)
GET /tickets/:ticketId/tags ticket:read The chips on one ticket (M1-06)
PUT /tickets/:ticketId/tags ticket:write Replaces the whole set (M1-06)
GET /tickets/:ticketId/spam-sender ticket:read Who “Block sender” would block, and whether the dialog offers it (M1-11)
POST /tickets/:ticketId/spam ticket:write Marks it as spam, and blocks the sender when blockSender is true (M1-11)
DELETE /tickets/:ticketId/spam ticket:write “Not spam”: back to the default open status (M1-11)
GET /tickets/:ticketId/participants ticket:read The contact, the CCs and the staff (M1-13)
POST /tickets/:ticketId/participants ticket:write Copies an address in as a CC (M1-13)
DELETE /tickets/:ticketId/participants/:participantId ticket:write Takes a CC off (M1-13)
GET /tickets/:ticketId/time-entries ticket:read The ticket’s time, newest first, with the total (M1-12)
POST /tickets/:ticketId/time-entries ticket:write A manual entry: { seconds, note? }. 409 time-tracking-off while the brand has it off
DELETE /tickets/:ticketId/time-entries/:entryId ticket:write Your own entry; anybody’s with ticketing:manage (Team Leader, Admin), otherwise 403

Two routes live outside the brand, because the person calling them has no session — see satisfaction surveys:

Route Declares Answers
GET /api/public/csat/:token @Public() The rating page’s state: open with the brand, reference and subject; or used / expired with the brand alone. The brand carries helpCenterUrl (below)
POST /api/public/csat/:token @Public() { rating: 1–5, comment? }. Answers rated once, then used; expired after 30 days
POST /tickets/:ticketId/merge ticket:write Closes it into another ticket (M1-09, below)
POST /tickets/:ticketId/unmerge ticket:write Undoes a merge inside 24 hours (M1-09)
POST /tickets/:ticketId/split ticket:write Copies messages onto a new ticket (M1-09)

The saved views of Views are under the same prefix, every one ticket:read; what a shared view needs on top is decided per view:

Route Declares Answers
GET /views ticket:read The views the reader may see: shared ones in the brand’s order, then their own
GET /views/counts ticket:read One capped count per view the sidebar shows
POST /views ticket:read Saves a view: personal by default, shared with ticketing:manage
PATCH /views/:viewId ticket:read Name, Arabic name, filters, visibility, hidden
DELETE /views/:viewId ticket:read A view that is not built in
POST /views/reorder ticket:read { viewIds }: some shared views, or some of the reader’s own, in a new order

Listing

In 1.1, the list’s Sort menu and the view editor offer SLA due: oldest breached running clock first, then the soonest due clock, then tickets without a running clock. Paused, satisfied and stopped clocks do not count. sort=slaDue always uses this urgency order; direction does not reverse it. Equal due times and tickets without a clock use ascending ticket ID as a stable cursor tiebreaker. Changing the sort starts a fresh list; saved views retain it. Exact ticket-reference search matches still appear ahead of the view’s filtered matches, as with the other sorts.

The SLA engine maintains first_response_due_at and resolution_due_at only while clocks count. PostgreSQL stores their least in the generated column sla_next_due_at; one null leaves the other value, and two nulls produce null. The index is (brand_id, sla_next_due_at, id). Its 50k-ticket p95 under DOMAIN-RULES §14 has not been re-measured locally for M14-07.

GET /api/brands/:brandId/tickets
  ?statusId=<uuid>            repeatable
  &systemState=open           repeatable: open | on_hold | escalated | closed
  &priority=urgent            repeatable: low | medium | high | urgent
  &departmentId=<uuid>        repeatable
  &channel=email              repeatable: email | chat | telegram | form | api | manual | whatsapp | messenger | instagram
  &assigneeId=<uuid>          repeatable; `unassigned` and `me` are values of their own
  &tagId=<uuid>               repeatable; `tagIds` is the same filter under another name
  &q=printer                  the words, the contact's name, or a reference or original number (first, past the other filters)
  &overdue=true               only tickets whose SLA has run out (M1-05)
  &mailboxId=<uuid>           repeatable; the mailbox the ticket arrived at (M14-26)
  &toAddress=refunds@acme.com the address the customer wrote to, exact, any case (M14-26)
  &fieldFilter={"key":"severity","op":"any_of","values":["Sev 1"]}   repeatable; one JSON object per custom-field filter, all must match (M14-16)
  &snoozed=exclude            exclude (default) | only | include: snoozed tickets (M14-02); a reference in `q` finds one regardless
  &sort=updatedAt             updatedAt | createdAt | number | priority | slaDue
  &direction=desc             asc | desc
  &limit=25                   1–100
  &cursor=<opaque>            from the previous page's `nextCursor`
{
  "tickets": [
    {
      "id": "0199f4b2-…",
      "number": 1042,
      "prefix": "HD",
      "subject": "Refund for order 42",
      "status": { "id": "0199f4b2-…", "name": "Open", "systemState": "open", "color": "info", "…": "…" },
      "priority": "medium",
      "channel": "manual",
      "departmentId": "0199f4b2-…",
      "assigneeId": "0199f4b2-…",
      "assignee": { "id": "0199f4b2-…", "name": "Lina Haddad" },
      "contactId": "0199f4b2-…",
      "contact": { "id": "0199f4b2-…", "name": "Nadia Karim" },
      "slaBreached": false,
      "closedAt": null,
      "updatedAt": "2026-09-19T12:00:00.000Z"
    }
  ],
  "nextCursor": "eyJzIjoidXBkYXRlZEF0Iiw…"
}

Each row names its contact (M1-15): contact is { id, name }, read for the whole page in one primary-key lookup, or null when the ticket names nobody. It is the name and nothing else, because an address on every row of a list is fifty addresses nobody asked to see. GET /tickets/:ticketId embeds the same thing. The field is left off for a caller without contact:read (every staff role holds it; an api key scoped to tickets alone would not), who still has contactId, and the write routes leave it off too. Absent means “not said”, which a client must not read as “nobody”.

Paging is keyset, not offset. OFFSET 10000 makes Postgres walk ten thousand rows it throws away, and it skips rows: a ticket updated between page 2 and page 3 moves to the front of an updated_at ordering and is never seen. The cursor says “the row after this one”, which is stable under writes and is an index seek (REQUIREMENTS §5.2: p95 under 150 ms at 50k tickets per brand).

The cursor is opaque and is not a token: it carries nothing secret and grants nothing, because every row it can reach is a row the policies would have shown anyway. It is validated all the same, and a cursor issued under a different sort is refused with 400 rather than reinterpreted.

Search reads the words of each ticket’s subject and first message (M1-15 part 2, ADR 0011). q is turned into lexemes by the same english text-search configuration tickets.search uses, so refunds finds “refund” and stop words such as the are dropped. A ticket matches when it carries every word, in any order. A word typed as -word rules out the tickets that carry it. Quotes are not a phrase operator (the words must all appear, anywhere), or is a stop word rather than an operator, and replies after the first message are not searched.

When the exact words fill less than a page and the words are at least three characters long, the list falls back to a fuzzy reading: each word also matches a stored word that starts with the same three characters and is word-similar to it (<%, pg_trgm’s 0.6 threshold). renewa finds “renewal”; rfund does not find “refund”, because the first three letters differ. The fallback is decided on the first page and the cursor carries it, so every page of one search is answered the same way. The term is always bound as a parameter. Why the search works this way, and what it costs, is under Search under row-level security.

From M1-09 the same q also matches the contact’s name (ILIKE, with % and _ escaped, through contacts, which is brand-scoped) and a reference: HD-1042, #1042 or 1042 match ticket number 1042 whatever the prefix, because a brand has one sequence. The merge dialog’s search is this list read.

A term that names a ticket finds it past the filters (#221). When q is a reference or a bare ticket number, or an imported ticket’s original number or native ID (580, #580, the vendor’s ID; see Importing), the tickets it names come first, and the request’s other filters (systemState, statusId, assigneeId, priority, departmentId, channel, imported, tags, overdue) do not apply to them. Somebody who types an exact number wants that ticket whatever its status, so #580 from “My open” finds the closed ticket the import made. Everything else stays as it was: the words and the contact’s name are still matched inside the filters, so a word from a closed ticket’s subject does not find it from an open-only view. Named tickets are still only tickets the reader can already see: row-level security and department scope apply, and a soft-deleted ticket is never named.

The list reads the named tickets with a statement of their own (the same brand_id, soft-delete rule and ordering, under none of the view’s filters), then fills the rest of the page with the view’s matches, which leave the named tickets out, so no ticket appears twice. When the named tickets fill a page, the cursor says so (n), and the next page carries on through them before it starts the view’s matches from the top. Each read stays a keyset read of one ordering, and the named half is three index lookups (tickets_brand_number_key, import_external_ids_number_idx, import_external_ids_native_lookup_idx).

tagId has all-of semantics (M1-06): a ticket matches when it carries every tag named, not any of them. Two chips in a filter are how somebody narrows a queue, and “any” would widen it — the reading that is wrong in the direction that shows rows the reader asked to exclude. tagIds is the same filter under another name, and naming both is naming their union.

assigneeId=me is whoever is asking, resolved from the session (M1-05). A saved view says me rather than a person’s id, so one shared “My open” means mine to everybody who opens it.

overdue=true keeps the tickets whose clock has run out: not closed, not in a status that pauses the SLA (“Awaiting customer” is waiting, not late), and either sla_breached or past first_response_due_at or resolution_due_at by the transaction’s now(). false is the same as leaving it off. It narrows the scan the other live-state filters use rather than needing an index of its own.

Filtering by a custom field

fieldFilter (M14-16) narrows the list by the value of a ticket custom field. Each parameter is one JSON object, URL-encoded; send several to require all of them. A saved view stores the same objects in filters.fieldFilter, so anything the list accepts a view can keep.

op Field types Shape Matches
any_of select, multi-select {"key","op","values":["Sev 1","Sev 2"]} the value is one of values (any member of a multi-select)
not_set every type {"key","op"} the ticket has no value, which is how a cleared field is stored
is checkbox {"key","op","value":true} ticked; false is “not ticked” and includes a box never touched
before, after number, date {"key","op","value":10} or "2026-03-01" strictly less or greater
between number, date {"key","op","from":1,"to":9} both ends included; from may not be after to
any_of person {"key","op","values":["<user id>"]} the value is one of the staff ids (M14-27); the filter popover offers names
contains text, long text, link, email {"key","op","value":"stripe"} a case-insensitive substring; % and _ mean themselves

The api reads the field’s type from the brand’s definition, never from the request, and refuses with 400 a key that is not a ticket field (a typo is not an empty list), an operator the type has no use for, a number compared with a day, a field named twice, and more than ten filters. A ticket with a value of another kind than its field’s (a leftover from before a type was fixed) simply does not match a comparison. Values reach SQL as bound parameters, the filters run under the same row-level security and department scope as every other filter, and a view’s sidebar count uses the same WHERE as its list.

Visibility. A field whose Visible to agents is off can be filtered only by somebody who holds ticketing:manage (Admin, Team Leader). For everyone else, including an API key, it answers as if the field did not exist, because a filter on it would let a reader learn by narrowing what the details panel hides. A shared view is checked as an Agent would read it when it is saved, so it cannot name such a field; a view whose field was deleted since counts nothing in the sidebar and answers 400 when opened, until it is edited.

No index. There is no index on tickets.custom. A jsonb_path_ops GIN was built and measured on the 50k-ticket dataset of DOMAIN-RULES §14: the plans were identical with and without it (12 to 45 ms for a rare value, a common one and a department-restricted Agent), because @> is not LEAKPROOF and Postgres therefore does not run it ahead of the row-level-security policies, and the list is paged by the tickets_brand_* indexes anyway. pnpm --filter @helpdock/api perf:tickets carries four field-filter cases (a rare value, a common one, a multi-select, and a filter with the live states) so the numbers can be taken again.

The Severity recipe. Helpdock has no Severity field of its own; priority is what the SLA engine targets. A team that wants one: add a Select field named Severity with Sev 1 to Sev 4 under Inbox › Custom fields and tick Pin on rows and the ticket header; filter the list by Severity is any of Sev 1, add Open as the state, and Save as a view called “Sev 1 open”; then add a rule (When ticket updated, if Severity is Sev 1, set priority Urgent and notify the on-call team) in Automation.

Creating

POST /api/brands/:brandId/tickets
Content-Type: application/json

{
  "subject": "Refund for order 42",
  "bodyHtml": "<p>Where is my refund?</p>",
  "departmentId": "0199f4b2-…",
  "priority": "medium",
  "channel": "manual",
  "contactId": "0199f4b2-…",
  "tagIds": ["0199f4b2-…"],
  "custom": { "tier": "gold" },
  "clientId": "0199f4b2-…"
}

Or from a template, which fills whatever the request leaves out:

POST /api/brands/:brandId/tickets

{ "templateId": "0199f4b2-…", "contactId": "0199f4b2-…" }

subject, bodyHtml and departmentId are required unless the request names a templateId; a request with neither is a 400 naming the three fields. A template that itself names no department leaves the request to name one, and a request that names neither is refused. Everything the request does name wins over what the template says.

contactId is optional: a ticket typed into the admin may have nobody attached yet, and M1-13’s identity rules are what attach one later. It is a foreign key to contacts with on delete set null, so erasing a contact (DOMAIN-RULES §11) does not take their tickets with them — the work and the SLA history outlive the person’s record.

Answers 201 with the ticket, its first message and its activity. The body is the first message: a ticket with no message is a row nobody can answer, so the two are never written apart.

Creating a ticket is not idempotent, and clientId does not make it so. The uniqueness D §7 defines is (conversation_id, client_id), and a conversation does not exist until the ticket does — so a retried POST /tickets writes a second ticket. What clientId does here is give the first message the same dedupe key a reply gets. Idempotent creation needs a key that outlives the request: M2-04’s email threading key, M4’s conversation id.

A department outside the actor’s own scope answers 403 with a sentence rather than letting the policy answer 500.

A PATCH whose fields all already hold the values it names answers 200 and writes nothing — no activity row, no outbox event — because “priority: medium → medium” is an entry nobody reads and a phantom ticket.updated makes every screen re-read for nothing. An empty body is a 400, so a caller retrying a failed write can still tell the two apart.

teamId is refused with 400 until M1-01 creates teams: tickets.team_id has no foreign key yet, so any uuid would be stored permanently. An assigneeId must belong to somebody who holds a role in the brand — tickets.assignee_id references the global users table, so the foreign key alone would accept a stranger (400). M1-07 adds the department: the assignee must be able to work the department the ticket is in — or is moving to — and not be a Viewer or deactivated (not-eligible, 409), and only an Admin assigns a ticket to an Admin (assignee-above-actor, 403). The load cap is not checked: a person may give an agent at cap another ticket. A move into a department the current assignee cannot work clears the assignee, and a ticket that is created or moved unassigned into a department that routes by itself is handed to the rotation through the outbox — see Assignment.

Replying

POST /api/brands/:brandId/tickets/:ticketId/messages

{
  "kind": "public",
  "bodyHtml": "<p>On its way.</p>",
  "clientId": "0199f4b2-…",
  "attachmentIds": ["0199f4c1-…"]
}

kind is public or note and is required — a note posted as a public reply by an omitted default is the worst bug this endpoint could have. system and ai are the server’s to write.

The response carries the seq. Posting the same clientId twice returns the first message. A reply also bumps the ticket’s updated_at, so it rises to the front of the queue it just became urgent in, even though none of the ticket’s own columns moved.

attachmentIds is optional and names uploads already presigned, uploaded and confirmed against this ticket by this principal (M1-10). They are linked in the same transaction as the message, so a message never commits without the files somebody believes they sent with it — and the whole send is refused rather than shortened if any one of them cannot be linked. Every message carries its attachments on the way back out, and on every later read of the thread. The attachments guide has the rules.

A message on the wire carries neither external_message_id nor ai_meta nor its denormalised department_id: the first is a channel’s threading handle, the second is cost accounting, and the ticket already says which department it is in. M8 decides separately what the public API exposes.

Reply windows

WhatsApp, Messenger and Instagram let a business write to a customer only for a time after the customer’s last message (M10-06, DOMAIN-RULES §2.6, ADR 0025). Helpdock enforces the window itself, so a reply that cannot leave is never written as if it could.

Platform The window For a person’s reply
WhatsApp 24 hours from the customer’s last message The same: free text cannot extend it
Messenger 24 hours 7 days, when the account’s Human Agent switch is on
Instagram 24 hours 7 days, as Messenger

The anchor is the time of the customer’s last message on that conversation (meta_conversations.last_inbound_at). A delivery or read report, a reaction or an echo does not move it. It closes at its instant: a reply at 23 h 59 m goes out, one at 24 h 00 m does not. The 7 days belong to a person: the assistant’s message, a rule’s canned reply and the survey get the 24 hours whatever the switch says. (A reply written in the extended days is sent with Meta’s HUMAN_AGENT tag on every part of it, and the delivery records the tag.)

At compose time. A public reply on a Meta ticket whose window is closed is refused with 409 and writes nothing: no message, no delivery, no outbox row, no sequence number. An internal note is never refused.

{
  "error": {
    "code": "conflict",
    "message": "The customer's reply window is closed",
    "meta": {
      "reason": "reply-window-closed",
      "details": {
        "platform": "whatsapp",
        "anchorAt": "2026-10-10T08:00:00.000Z",
        "closedAt": "2026-10-11T08:00:00.000Z"
      }
    }
  }
}

anchorAt and closedAt are null for a customer who never wrote. The ticket view reads the window first (below) and disables Send, so this refusal is for the race.

When the job runs. meta.send asks again before its first part, because the window can close while the job waits. A reply that is past it is recorded refused with the platform’s code (131047 on WhatsApp, 10/2018278 on Messenger and Instagram) and is never retried. The same happens when Meta itself says the window is closed. A message that nothing asked first, as the assistant’s never is, and that finds the window closed is written refused with no job at all: the message stays in the thread, and the delivery says why it did not go.

Reading it.

GET  /api/brands/:brandId/tickets/:ticketId/meta                          ticket:read
GET  /api/brands/:brandId/tickets/:ticketId/meta/deliveries               ticket:read
POST /api/brands/:brandId/tickets/:ticketId/meta/deliveries/:id/retry     ticket:write

The first answers { context, deliveries, unsent }. context is null for a ticket that is not on a Meta channel or has no conversation. Otherwise it names the account (id, platform, externalId, displayName, and username or displayPhone when there is one), the customer (customerId, phone and phoneVerified for a WhatsApp number Meta sent, profileName, username) and the window for a person writing now: { state: "open", closesAt }, { state: "human_agent", closesAt } or { state: "closed", closedAt }. Each delivery carries status (queued, sent, delivered, read, failed, refused), partsSent of partsTotal (the text in the platform’s parts, then one message per attachment), attempts, Meta’s lastError and errorCode, the four times, and leftOut: the files the platform would not take, each with its name and unsupported-type or too-large. The customer was told in their language; the agent reads it under the reply. A delivery moves forward only, and the platform’s own reports (delivered, read) arrive by webhook. unsent (Instagram tickets only, oldest first) names each message the customer took back and the system line that marks it, with when: a ticket message carries no platform id on the wire, so this is how the thread draws the mark on the message (below).

Retry puts a failed delivery back, keeping the parts already sent as sent. A refused one answers 409 with the same reply-window-closed, and its details when the window is closed still: the customer has to write first, and the agent writes a new reply. A delivery that is queued or sent is left alone.

How a reply leaves. The text is cut at 4096 characters (WhatsApp), 2000 (Messenger) or 1000 bytes (Instagram, about 500 Arabic letters), at a paragraph, a line or a space, never inside a letter. Each attachment follows as a message of its own. WhatsApp takes one message per six seconds to one user, so the parts of a reply, and two replies to one customer, go six seconds apart: a part that finds the customer’s slot taken moves its job to delayed for the remainder, which spends no attempt. Messenger and Instagram are not paced. The Meta channels guide has the file limits, the pricing note and what Meta must be able to reach.

Catching up

GET /api/brands/:brandId/tickets/:ticketId/messages?after=12&limit=25
{ "messages": [{ "seq": 13, "…": "…" }], "nextAfter": null }

nextAfter is null on the last page, which is how a client knows it has caught up rather than guessing from a short page. A client that receives a socket frame with seq > last_seq + 1, or that reconnects, calls this.

The admin workspace

The ticket-list header uses icon-only Sort and Filter buttons so its 360 px column fits in English and Arabic. Hover or keyboard focus shows their localized tooltips; Filter shows the active count in a badge, its tooltip and accessible name. Every counted filter has a removable chip, including Source. New ticket keeps its text label. The tooltips do not capture clicks and close when you open a menu or move focus away. Closing a menu restores focus without reopening its tooltip; tab away and back to read it again.

A row in the list (M14-20) has one meta line under the subject: the reference, the contact, the status as a plain word, the SLA time (or the wake time of a snoozed ticket) and the pinned field. At the end of the row sit the time of the last update and the assignee: their initials in a teal circle, or a dashed ring when nobody has the ticket. The status word is left out when the view is already filtered to one status, such as Escalated. A screen reader hears the same things in the row link’s name, ending in “Assigned to Lina Haddad” or “Unassigned”.

In the details panel the order is the contact, Assignee, Status, Priority, Department, SLA, Tags, custom fields and Participants. Each select has its label above it. Participants is one line, “2 participants · Add CC”; press it to see the list and the field for copying somebody in.

apps/admin/src/screens/tickets/ is the Admin · ticket view artboard: the list, the thread and the details panel, on one route. The boundary it reads through is apps/admin/src/tickets/ — TicketsApi, an http adapter and a fixture — the same shape the contact screens use.

It covers what the api can answer today. Views (M1-05, below), tags and custom-field editing (below), the state machine’s transitions (M1-08), merge and split (M1-09) and attachments (M1-10) add to it rather than change it; what the screen still cannot do is at the end of this section.

Tickets on a narrow screen (M14-22)

Below 1024 px, on a tablet or a narrow window, the ticket list is the whole screen: there is no empty “No ticket open” area to get past. Tapping a ticket opens it over the list, under a bar with Back to the view you came from (for example “Back to My open”; the arrow points the other way in Arabic) and a Details button, which opens the ticket’s details as a drawer from the inline end. Back, or your browser’s back, returns to the list where you left it, scrolled to the same place, with the last ticket you read focused (scrolled into view if it was off screen). Ticking rows, the bulk bar and j, k, Enter, x and / work as they do on a wide screen while the list shows (/ and a filter chosen from the sidebar bring the list back first). With a ticket open, x, Shift+x and Esc do nothing, so a selection you cannot see is never changed; [ does nothing either, since there is no second column to put away. Back adds a history entry (it is a step to the list, not an undo), so the browser’s back then returns to the ticket. Phone layouts under 600 px are a later milestone (M17-07).

The compact composer and the 1280 px layout (M14-19)

At 1280 × 720 the thread has about 700 px: the details panel is a drawer below 1440 px (the Details button in the ticket header opens it), and [ puts the list away for more room ([ again, or Show the ticket list, brings it back). The reply box is short on purpose. On a ticket answered by email it is one line, “To Mona Khalil · from billing@helpdock.io”, with Cc 2 after it when there are copies; press it to see From, To, Cc and your signature, and press it again to put them away. The text starts at two lines and grows as you type, up to 45 % of the ticket’s height, after which the box scrolls inside itself with the Send row kept in view. A reply that fails to send leaves the box as it was and the text in a “Not sent, retry” message in the thread. The ticket’s subject is one line in the header; hover it for the whole subject.

There is one way in to macros: Macros in the reply box, / in the text, m, or Apply a macro in the command palette (⌘K). The header has no Macro button.

One screen, one route

/tickets is the list with nothing open and /tickets/<id> is that ticket beside it, and both are one <Route> — /tickets/*, with the id read from the path. Two routes rendering the same component would unmount and remount it every time a ticket was opened or closed, throwing away the composer’s draft and whichever sends were still in flight.

The URL is the state, as it is on the contact screens: the view, the search term and every filter live in the query string, so a filtered queue is a link an agent can send a colleague and the back button steps through what they looked at rather than out of the screen.

Parameter
view A view’s id, or all for the whole desk. Absent means the first view of the sidebar.
q Free text, debounced 250 ms, passed to the api’s own search. A term typed into a view does not count as changing it. A reference, ticket number or imported original number lists that ticket first even when the view’s filters would hide it, such as a closed ticket in “My open”; its row’s status badge says it is closed (#221)
state, status, priority, assignee, department, tag, channel Repeatable, one per chip in the filter popover. assignee=me is whoever opens the link
overdue, sort, dir overdue=1; the order when it is not “last updated, newest first”
custom Present when the filters above replace the view’s rather than being empty
intent filters or save: the sidebar asking the workspace to open the filters or the save dialog. Acted on once and dropped from the URL

A row is one link, named by what it shows. A screen reader hears the priority (“Urgent priority”, which the dot says only in colour), the subject, the reference, the contact, what the assistant did, the status, and the SLA in words (“4h left” where the row prints 4h). Until the list’s first page arrives it draws six skeleton rows, and an opening ticket draws the shape of its header and two messages, each under aria-busy.

Views in the workspace

The sidebar’s Views group (views-nav.tsx, Admin/View-Dialogs panels 1–2) lists the brand’s shared views in the order Inbox › Views gives them, then the reader’s own under Mine. The names and the counts are two reads, so the rows are usable before the numbers arrive; Overdue’s number is in the danger hue while it is above zero. A ⋯ appears on hover and on focus for a view the reader may change: Edit filters, Rename, Share with… (a personal view, for Team Leaders and Admins) and Delete; a built-in view offers Rename alone. The + beside “Views” opens “Save as a view” on whatever the list shows.

Changing a filter on a view writes the whole resulting filter set into the URL beside view and custom=1, so a changed view is still a link a colleague can open. When those filters differ from the saved ones, the list header grows the Filters changed · Reset · Save as new · Save bar (panel 4) and every filter that is on is a chip that removes itself. Reset drops the filter parameters; Save overwrites the view and is offered only where it can succeed — the reader’s own view, or a shared one they manage, never a built-in one; Save as new opens Save as a view (panel 3): a name, “Only me” or (for Team Leaders and Admins) “Shared with departments”, and the filters and sort in words. A view the reader cannot see — a link to somebody else’s personal view — falls back to the whole desk, filtered by whatever the link carried.

Sending, sent, not sent

The composer implements §7 exactly. A send draws its bubble at once with a client-generated clientId; the bubble says sending until the response carries a seq, and not sent, retry when ten seconds pass without one. Retrying posts the same clientId, which the api de-duplicates on (conversation_id, client_id), so retrying a request that actually succeeded returns the original message rather than posting a second one.

“Then set status” is applied after the send, never with it: a status moved by a reply that never left would be a lie about what happened.

Realtime

The workspace joins ticket:<id> while a ticket is open and department:<id> for every department on the list. No frame is ever applied to the cache — sockets are notifications and REST is the truth — so ticket:changed re-reads the ticket and ticket:message reads ?after=<the highest seq held>. A reconnection does exactly the same thing, which is why a missed frame and a dropped connection have one recovery between them.

The collision indicator

“Somebody else has this ticket open” is derived from a new ticket:viewing event rather than from room membership, because a Socket.IO room is not a membership list: a replica can enumerate the sockets it is holding and no more, and the answer has to be true across every replica. So each client says so every 30 s, the gateway authorises the announcement exactly as it authorises the join and relays it to the rest of the room, and every client drops a name nobody has repeated for 90 s. Nothing is stored, and “closed the tab”, “lost the network” and “went to lunch with it open” are one answer.

M1-09 added activity: replying while the composer holds something unsent, viewing otherwise. A change is announced at once rather than at the next interval, the pill says “Mona is replying” and puts whoever is replying first, and the same authorisation covers both words. It stays stateless on purpose: “is replying” is not a lock, so a browser that crashes mid-reply cannot leave a ticket claimed.

The relayed event carries a user id, not a name. The ticket view names it the way the assignee picker names an assignee: from the department’s assignable list (M1-07), which an Agent can read, then from the staff list, which needs staff:manage, and otherwise as a shortened id.

Merge and split in the workspace

The ⋯ menu in the header (ticket-actions-menu.tsx) draws the entries it is handed, in order; M1-09 passes Merge and Split, and M1-12’s Log time and M1-11’s Mark as spam are added to the same array. A merged ticket offers neither. The merge dialog searches with the list read and never offers the ticket itself or a merged one; the split dialog lists the ticket’s own messages, oldest first. After either, the workspace opens the ticket the work continues on. On the primary, each merged ticket is drawn where its announcement was: a banner with Unmerge while its 24 hours last, a divider, and its messages read-only on bg.canvas, each marked with its origin. The secondary shows the banner the other way round above the thread, and no composer. Built from AdminTicketDialogs panels 1, 2, 4 and 7.

A system line names who acted (“Messages split to HD-1043 by Lina · 14:12”) only when that was a staff member. The row’s author_id is whoever made the request, which can be an api key or a job, and the screen names it only when it finds that id in the staff directory.

The details panel’s Linked tickets (linked-tickets.tsx, panel 6 of Admin · view dialogs) draws related: a card per visible ticket with its reference, status, subject and relation, which opens it, and a locked line (“A ticket you cannot open · Split from · hidden from you”) for a hidden one.

Previous tickets on the contact card

Under the contact’s name, the details panel lists the contact’s other tickets, so a returning customer is visible without leaving the ticket (#237, artboard Admin/Ticket-ContactHistory, previous-tickets.tsx). It reads the contact timeline the panel already loads for the hidden count (contacts guide), so it is department-scoped like every ticket read: it lists only tickets the viewer may open.

  • Up to three rows, newest first, the open ticket and any deleted or spam ticket left out; a merged ticket is listed with its status. Each row is one link to that ticket: the subject, the reference and the day it was created (with the year when it was not this year), and its status badge.
  • The heading counts every other ticket the viewer may see, not only the three rows: “Previous tickets · 5”. The count comes from the timeline’s visibleCount, because its items stop at the newest 50.
  • Under the rows, the hidden count (“2 hidden (other departments)”) when the viewer’s departments exclude any, then “View all on Mona Khalil’s page”, which opens the contact page.
  • A first ticket says “This is their first ticket.” When the contact’s only other tickets are hidden from the viewer, the hidden count stands in for that sentence.
  • While the timeline loads, three skeleton rows hold the space. A ticket without a contact has no section, and neither does one whose timeline could not be read: an empty list there would claim a first ticket the panel cannot vouch for.

Attachments

Attach is real from M1-10. A file goes up as soon as it is chosen: the brand’s content policy is checked in the browser first, so a file the brand would refuse costs no bytes, and the api applies the same rules to the presign request and again to the stored object — a client’s opinion is not an authorisation.

A message may be sent while the pipeline is still working. upload resolves at processing, the ids travel with the send as attachmentIds, and the api links them in the message’s own transaction; it refuses the whole send if any one of them cannot be linked, so a failure is a message that was not sent rather than one that quietly lost a file. A retry carries the same ids for the same reason it carries the same clientId.

A chip has three states, because the pipeline has three answers: working on it, done, and refused. A refusal is drawn rather than hidden — the file is not coming, and a chip that quietly disappeared would leave somebody believing they had sent it. No thumbnails: a render URL is presigned, lives five minutes and has to be asked for per attachment, so a thread of them would be a burst of requests for pictures nobody has opened.

How it got here

The “How it got here” card in the details panel, under the SLA card (Admin/Ticket-Routing), is collapsed to one line — “Email to billing@acme.com → Billing · assigned by round-robin” — and expands to the arrival and each step with its time: “Arrived at billing@acme.com · Billing · the mailbox’s department”, “Moved to Billing › Refunds by rule “Refunds to the refund team””, “Priority raised to High by AI triage”, “Assigned to Lina Haddad by round-robin”. A ticket filed before 1.1 says “Arrived by email” and that the entry point was not recorded; an imported one says “Imported from Zendesk”. The card reads the trail again whenever the ticket changes, keeping the one it read on screen meanwhile, and offers “Try again” when the read fails.

Keyboard

The workspace answers to the keyboard: j and k through the list, r to reply, e to close, ⌘/Ctrl+Enter to send, g then a letter to open a view, and more. Every shortcut, where each answers, how they work on an Arabic keyboard layout and how to turn single-key shortcuts off are in Keyboard shortcuts; ? shows the same list in the app. The sidebar’s ⌘\ / Ctrl+\ (since 1.0.2) is one of them.

Anywhere in the admin, ⌘\ on a Mac or Ctrl+\ elsewhere collapses the sidebar to a 56 px icon rail and expands it again, which leaves the list and the thread more room (since 1.0.2). It carries a modifier, so it works while typing too, and it is matched by the physical key, so it is the same key on an Arabic layout. The Collapse sidebar button above your name does the same. The browser remembers the choice; until you make one, the sidebar is expanded on a window 1280 px or wider and collapsed between 1024 and 1279 px. On short windows, scroll the navigation independently of the brand and account controls. A hairline at either edge means more items are available there; Tab brings each focused item and its focus ring fully into view. The rail uses an inset focus ring so the gutter cannot clip it. The rail shows its thin scrollbar whenever the navigation overflows.

Tags and custom fields in the workspace

The details panel edits both (artboard Admin/Ticket-Tags). A Viewer, who has no ticket:write, sees the same panel with nothing to press: chips without × or Add, and the custom fields disabled.

Tags sit below Priority as chips in each tag’s tint. The × on a chip takes it off at once. Add opens a multi-select Combobox of the brand’s tags: typing filters by either name, ↑ and ↓ move through the list, Enter toggles the highlighted tag, a click toggles too, and Esc closes it. A ticked tag is on the ticket. The picker never creates a tag. When nothing matches it says so and points to Inbox › Tags, because what a brand labels its tickets with is configuration (ticketing:manage), not something to make up mid-ticket.

Each change sends the whole new set to PUT /tickets/:id/tags and draws it before the answer arrives. When the api refuses (most often because somebody deleted a tag after the ticket was read), the chips go back to what they were and a toast says the tags were not changed. Either way the ticket is read again afterwards, so its activity line appears.

Custom fields are one editor per ticket definition, in the brand’s order, of the definition’s type:

Type Editor Saves
Text text input on blur, or Enter
Number number input on blur, or Enter; sent as a number
Date date input on blur, or Enter
Select select with an empty “—” option on change
Multi-select multi-select Combobox with chips inside on change
Checkbox checkbox on change

Each save is a PATCH naming that one key (Custom values). Emptying a field sends null, which clears it. A blur that changed nothing sends nothing. The api is the only judge of a value: when it answers 400, a sentence for the field’s type appears under the field as an alert, the input is marked invalid, and the stored value comes back. A field whose definition is not visible to agents is left out for Agents and Viewers, and shown to Admins and Team Leaders.

Filtering and the pinned field (M14-16)

The Filter popover (Admin/Ticketing-FieldFilters) ends with a Custom fields section: Add filter lists the ticket fields the reader may filter by (the ones hidden from Agents are left out for Agents), each row is the field, an operator that suits its type and the value the operator needs, and Apply sends the rows. A row with no value yet is not a filter: Apply waits, and says so. Applied filters become chips under the list header, each removing only itself, are part of the link (field=<json>), and are saved with a view like any other filter. The Views tab’s editor has the same rows, applied as they are made.

The pinned field’s value is a neutral chip on the row’s caption line and in the ticket header. A ticket without a value shows nothing; the field’s name is there for a screen reader (“Severity: Sev 1”).

The ⋯ menu

The ⋯ button in the header opens the ticket’s actions menu (Admin · ticket dialogs, panel 2). Its items are an array each deliverable contributes to — ticket-actions-menu.tsx draws whatever it is handed — so merge and split (M1-09) and log time (M1-12) add entries rather than markup. M1-11’s is the last: Mark as spam, in danger text behind a separator, which opens the confirmation of panel 5 with a ticked “Block ” card when the api says the sender may be blocked; or Not spam on a ticket already in Spam, which reopens it at once. A merged secondary offers neither.

A WhatsApp, Messenger or Instagram ticket

What an agent sees on a ticket that is with a customer on WhatsApp, Messenger or Instagram (M10-08, Admin/Ticket-Meta). It is the ticket view above plus a few additions that appear only on these three channels; a ticket on any other channel draws none of them. The rules behind them (the window, the parts, what a refusal does) are in Reply windows and the Meta channels guide.

Which account. The header’s chip names the brand’s side of the conversation, then the department: “WhatsApp · +1 555 0142 · Support”, “Messenger · Helpdock · Support”, “Instagram · @helpdock · Sales”. The customer is named in the details panel, not here. In the ticket list the platform is an icon after the reference, with its name for a screen reader. A customer’s message says “via +1 555 0142” (the number, Page or handle the customer wrote to) and an agent’s reply says “to WhatsApp”.

Where a reply stands. The end of a reply’s author line says what the platform last reported, and only ever moves forward:

Shows Means
Sending, or “Sending · part 2 of 3” Queued, or some of its parts have gone. Helpdock reads the deliveries again every five seconds while one is sending
Sent The platform accepted every part
Delivered 09:44 The customer’s device has it
Read 09:44, with two checks The customer opened it. Sent and Delivered keep one check, as the widget’s Seen does, so the word is what tells the three apart
“· 2 messages” The reply was cut or carried files and went as several

A reply that did not go is a red strip under it, never a toast. Not sent means the window had closed before the first part: it gives the platform’s words and code and says “No Retry: write a new reply once the customer writes again”, because Retry cannot mend it. Not delivered is a failure: it gives the part that failed, Meta’s words, the code and the attempts, with Retry, and when earlier parts reached the customer it says so (“The first part reached the customer; Retry sends the rest”). A file the platform would not take is a line under the reply, “warranty-terms.docx left out: Instagram sends PDF files only. The customer was told.” A reply’s accessible name carries its state (“Reply from Lina Haddad, read”). Nothing in the thread is a live region of its own: a message, a reaction or a failure that arrives is announced, and Sent, Delivered and Read changing in place are not.

What the customer sent. A quoted earlier message, when it is on the ticket, leads the message as a quote with its author. A sticker is a figure. A story reply or mention has a “Replied to your story” caption over the story’s picture. A location or shared contact is text. A reaction, an edit and anything Helpdock cannot show are lines of the thread with an icon. A message an Instagram customer unsent keeps its words and gains “Unsent by the customer · 10:26” under them; the line that marks it is left out of the thread (the ticket read says which message each one belongs to, unsent below).

The reply window strip. Between the thread and the composer, one strip says whether a reply may be written now. It is a role="status" outside the thread, so it speaks when its state changes and not every minute: the countdown is hidden from a screen reader and moves once a minute, and the closing time is a <time>.

State When It says
Open The window is open and has more than an hour left “Reply window open · 22h 54m left · closes tomorrow at 09:25”, and the platform’s rule at the end
Closing The last hour of an open window The same in the warning colour, and “Send now, or the customer must write first.”
Human Agent Messenger or Instagram, after 24 hours, with the account’s switch on The days left, and that only a person’s reply may use them
Closed Nothing may be written When it closed, that the platform accepts no reply until the customer writes again, and on Messenger and Instagram that an internal note is still possible

A closed window is waiting on the customer, as Awaiting customer is, so it is a warning and never a danger. The strip reads the window the api answered against the clock, so a window that runs out while the ticket is open turns closed on the next minute without a request (and the ticket is read again, because on Messenger and Instagram the Human Agent days may begin where the 24 hours ended). If the api refuses a reply with reply-window-closed while the strip still said open (the last minute’s race), the strip turns closed and adds “Not sent: the window closed at 09:25 while you were writing. Your text is kept below.” The text, its files and a staged macro go back into the composer, nothing was written, and there is no bubble to retry.

The composer. The recipient caption names the customer, the platform, their number or handle and the brand’s account: “To Daniel Reyes on WhatsApp +44 7700 900123 · from +1 555 0142”. Under the text a caption counts the messages the reply becomes, by the same function the send job cuts them with: “Plain text. Sent as 3 messages: 1 text, 2 attachments. Meta may charge for each.” (the charge is WhatsApp’s), “Sent as 2 messages: the text is cut at 2000 characters.” (Messenger), “Sent as 3 messages: the text in 2 parts of up to 1000 bytes, 1 attachment.” (Instagram). The first message opens with the agent’s public name and the brand, “Lina · Helpdock” (Replying), and that line is counted: a reply that is only files counts it as one text message. On Instagram a file that is not a PDF is named in the warning colour before Send, because it will be left out. While the strip is closed, Send keeps its place but is aria-disabled and described by the strip, the text stays, and the caption says what the reply would be (“Would go as 1 message; Send turns on when Sara M. writes again.”). An internal note is never refused.

The details panel. A card under the contact says who the customer is on the platform, with the id in mono and a Copy button named after it (“Copy user id”): WhatsApp shows the user id, the phone with a verified mark (or “Not shared by the customer” when Meta sent none), the profile name and the brand’s number; Messenger the page-scoped id, the name (or “Messenger user” until the app passes Meta’s review for profile access) and the Page; Instagram the Instagram-scoped id, the @username, the name and the account. Its footer says which value Meta verifies and which can change.

What it reads. GET …/tickets/:id/meta once the ticket opens (window, account, customer, deliveries and the unsent messages), and again whenever the thread grows, after a send, and every five seconds while a reply is sending. context: null (a ticket on another channel, or one with no conversation) draws nothing Meta. Retry is POST …/meta/deliveries/:id/retry; a refused delivery answers 409 and the screen says the customer has to write first.

Not there yet. “Send template…” on a closed WhatsApp window and the Human Agent tag on a reply in the extended days are M10-09: until then a reply written in those days is refused by Meta and ends Not sent. The closed strip says when the window closed rather than who wrote last, because the context carries the window and not the message that opened it.

What the screen cannot do yet, and why

Drawn State Owner
Translate disabled, with the reason M7
The AI bubble’s confidence not drawn: ai_meta is deliberately not on the wire M7
The assignee picker (M1-07, AdminTicketDialogs panel 3) reads
GET /brands/:id/assignment/:departmentId/assignable, which ticket:write
reaches, rather than the staff roster, which is staff:manage and which an
Agent does not hold. It lists everybody who can work the ticket’s department —
minus Admins, for anybody who is not one — with a presence dot and their open
tickets against the department’s cap (“8/8 at cap” in danger, “offline” instead
of a count). The button names the current assignee even when they are outside
the list, from the staff read when it has them and as a shortened id when not.

The rows name their contact from the ticket itself: the list embeds contact: { id, name } (Listing), so a row no longer depends on its contact being on the first page of GET /contacts, and the workspace no longer reads that page at all. The open ticket reads its one contact in full, for the details card and the thread’s address line.

The list also embeds assignee: { id, name } (M14-20; null for an unassigned ticket or a person who no longer holds a role in the brand), read for the page in one query. A row draws the initials from it, because GET /staff needs staff:manage and an Agent holds no such permission.

Bulk edit

POST /api/brands/:brandId/tickets/bulk changes up to 50 tickets at once (M14-03, DOMAIN-RULES §2.7, ADR 0036). It is a staff-session route of the admin: it is not in the public API v1, which has no bulk route. The ticket list drives it (in the admin).

Bulk edit in the admin

Anybody who may change tickets (everyone but a Viewer) sees a checkbox on each row of the list, named “Select HD-1042”, and a select-all box above the rows.

  • Ticking. Click a box; Shift-click ticks every row from the one ticked last to this one; the header box ticks the loaded rows (indeterminate when only some are ticked). x ticks the focused row and Shift+x the range, Esc clears (keyboard shortcuts). At most 50 at a time: a longer page ticks its first 50 and the caption says “the limit is 50”. The selection survives j/k and a refresh that keeps the rows, and is dropped when the view, a filter or the search changes.
  • The bar. While anything is ticked the list’s footer shows two rows: the count and Clear, then Status, Close, Assign, Snooze and More. More holds Priority, Team, Department, Tags, Set a field, Wake snoozed tickets and Mark as spam. The bar stays inside the list column at every width, so it never covers the open ticket. Assign is the details panel’s picker with “Assign to me” first, and offers the people who can take the tickets’ departments; Snooze is the header’s menu. Choosing a change previews it.
  • Applying. If every ticket would change it is applied at once. Otherwise a dialog says “10 of 12 tickets will be closed. 2 can’t be closed:” and lists each ticket that cannot, with its reference and the reason in words; the primary is “Close 10” (or “Apply to 10”). When nothing would change there is no primary. If a ticket changed between the preview and the apply the api answers bulk-changed (409) and the dialog opens again with the new list and a note; an apply is all or nothing against what was previewed.
  • Undo. A toast “Closed 10 tickets · Undo” stays ten seconds, paused while the pointer or focus is on it. The api accepts the undo for sixty, and Undo last bulk change in the command palette (⌘K) offers it for that minute from any screen. A field somebody changed since is left as it is and the toast says how many tickets that was.
  • A lost answer. If the apply’s answer never arrives (a dropped connection, a 502) the toast says “We couldn’t confirm whether the change was made. Check the list.” and the list is read again; “Nothing was changed” is said only when the api answered with a refusal.
  • Limits. Twenty applies and undos a minute per person; the twenty-first answers 429 and the toast says how long to wait. Nothing is changed.
POST /api/brands/:brandId/tickets/bulk
{ "ticketIds": ["…", "…"],
  "changes": { "priority": "high", "assigneeId": "me", "addTagIds": ["…"] },
  "mode": "preview" }

changes takes any of: statusId (anything but Snoozed), close: true, priority, assigneeId (a person, "me", or null for nobody), teamId, departmentId, addTagIds, removeTagIds, snoozedUntil (an instant to snooze until, or null to wake), spam: true (it never blocks the sender) and customField: { key, value } (one value). statusId, close, snoozedUntil and spam are one at a time. Anything else (a reply, a note, a merge, a split, a delete) is refused as an unknown key. At least one change, 1 to 50 distinct ticket ids.

Every ticket goes through the code a single edit uses, so the same rules answer: the transition table, the assignment ceiling, closed tickets refusing a snooze, the activity row (recorded via: bulk), the outbox events, the SLA effects, the rules and the webhooks, once per ticket.

Preview ("mode": "preview") writes nothing and answers, in the order the ids were sent, one result per ticket: will_change with the fields that move, unchanged, refused with the single edit’s code (ticket-closed, assignee-above-actor, snooze-requires-time, unknown-reference, invalid, …), or not_found. A ticket in a department you cannot see is not_found, the same as one that does not exist.

Apply ("mode": "apply") must name expect, the ids the preview said would change. It runs in one transaction and is all or nothing: if the tickets that would now change are not exactly expect, nothing is written and the answer is 409 with lifecycle: bulk-changed; preview again. A successful apply that changed something answers the same results plus operationId and undoUntil (60 seconds on).

Undo (POST /tickets/bulk/:operationId/undo) is the actor’s alone and answers per ticket reverted, partly_reverted, kept or not_found, with the reverted and kept fields. A field somebody changed since is kept; tags are put back as a set. It answers 404 for another person’s operation, 409 bulk-undo-expired after the 60 seconds and 409 bulk-already-undone the second time. An Undo that closes a ticket again keeps the original close time and sends no survey. It withdraws the assignment notifications for the tickets whose assignee it put back, if nobody has read them; a webhook or push already sent, and an email already delivered, are not recalled.

A bulk close asks for its satisfaction survey 60 seconds later, so an Undo inside the window sends none. Limits: 20 applies and undos a minute per person (429 beyond), 60 previews. Operations are kept 7 days.

Performance

The M1 exit criterion is “ticket list of 50k seeded tickets loads under 150 ms p95 under the D §14 conditions” (DOMAIN-RULES §14, REQUIREMENTS §5.2). What makes that true, how it is measured, and what it measured last.

The index set

The default list uses the keyset (updated_at, id) (0021_ticket_list_indexes.sql); SLA due uses (sla_next_due_at, id), ascending with nulls last. Each ordered-scan index ends in its list keyset:

Index Serves
tickets_brand_updated_idx (brand_id, updated_at, id) The default list; every view that filters rather than narrows (the live states, Escalated, Unassigned); search; page 2 onwards
tickets_brand_assignee_updated_idx (brand_id, assignee_id, updated_at, id) “My open”: one person’s tickets, already in list order. Replaces the PRD’s (brand_id, assignee_id), which is its prefix
tickets_brand_department_status_updated_idx (brand_id, department_id, status_id, updated_at, id) The filter popover’s department and status chips. id was added so one department in one status is in keyset order too
tickets_brand_status_updated_idx (brand_id, status_id, updated_at, id) A view narrowed by state across departments, and its sidebar count (M1-05, 0022_views.sql)
tickets_brand_number_key (brand_id, number) sort=number
tickets_brand_sla_due_idx (brand_id, sla_next_due_at, id) sort=slaDue, including page 2; brand equality enables ordered scans, while department RLS filters rows
ticket_tags_brand_tag_idx (brand_id, tag_id) The all-of tag filter, one scan however many tags are named (M1-06)
ticket_search_tokens_brand_token_idx (brand_id, token, ticket_id, department_id) Search: every word of q is an index lookup, and the fuzzy fallback a prefix range (M1-15 part 2)
tickets_brand_contact_idx (brand_id, contact_id) Search by the contact’s name: the tickets of the contacts whose name matched (M1-15 part 2)
tickets_search_idx (tsvector GIN), tickets_subject_trgm_idx (trigram GIN) Not the list: see Search under row-level security

sort=createdAt and sort=priority have no index of their own. The workspace never asks for them, and at 50k tickets they are a top-N sort of the visible rows, which is what the default list was before its index (27 ms of database time); an index per sort key would be paid on every write for a sort nobody uses yet.

The brand equality

The list’s WHERE carries tickets.brand_id = <the brand in the path> (ticket-query.ts). It is not isolation: the policy’s brand_id = ANY(app.brand_ids) already decides that, and the equality cannot widen it. It is for the planner. Against an array it cannot know that one brand is involved, so it cannot read (brand_id, updated_at, id) in order, and it fetched every visible ticket and sorted them. With the equality, a page is a backward index scan that stops after limit + 1 rows. The key lines, before and after, as the runtime role under an Admin’s context at 50k tickets:

-- before: every visible ticket, then a sort
Sort  Sort Key: tickets.updated_at DESC, tickets.id DESC  Sort Method: top-N heapsort
  ->  Parallel Bitmap Heap Scan on tickets  (rows=16591 loops=3)
        ->  Bitmap Index Scan on tickets_brand_assignee_idx  (rows=50000)
Execution Time: 27.248 ms

-- after: one page, in index order
Limit
  ->  Index Scan Backward using tickets_brand_updated_idx on tickets  (rows=26 loops=1)
        Index Cond: ((brand_id = ANY (…app.brand_ids…)) AND (brand_id = '…'::uuid))
Execution Time: 0.210 ms

Every list query of the benchmark, as Admin and as Agent (key lines; every run prints the full plans):

Query Admin Agent (2 of 5 departments)
All tickets Index Scan Backward using tickets_brand_updated_idx, 26 rows read, 0.21 ms same index, 129 read (103 removed by the department policy), 0.33 ms
My open Index Scan Backward using tickets_brand_assignee_updated_idx, 0.05 ms same index, 3.9 ms
Unassigned (live states) tickets_brand_updated_idx, 750 read, 2.7 ms same, 1.6 ms
Live states (Overdue) tickets_brand_updated_idx, 413 read, 0.85 ms same, 1.9 ms
Escalated tickets_brand_updated_idx, 1 350 read, 3.1 ms same, 6.0 ms
Search refund Index Only Scan using ticket_search_tokens_brand_token_idx, Index Cond: … token = ANY('{refund}'), 3 191 ids, then tickets_pkey and a top-N sort, 37 ms same, 17 ms
Search renewa (half-typed) exact half: token index, 0 ids, 9.1 ms; fuzzy fallback: prefix range of the token index, 53 ms 8.7 ms; 30 ms
Search matching nothing exact half: token index, 0 ids, 8.8 ms; fuzzy fallback: prefix range, 0 candidates, 9.5 ms 8.2 ms; 8.2 ms
Two tags, all-of Bitmap Index Scan on ticket_tags_brand_tag_idx, then Index Scan using tickets_pkey, 22.6 ms same, 15.5 ms
SLA due (expected; reference-host run owed) Index Scan using tickets_brand_sla_due_idx, ascending due time then ID, nulls last, stopping after one page same index, department policy filters rows
SLA due page 2 (expected; reference-host run owed) same index, null-aware cursor filter over (sla_next_due_at, id), stopping after one page same index and cursor filter, with department policy
Page 2 Index Scan Backward using tickets_brand_updated_idx, Index Cond: … ROW(updated_at, id) < ROW(…), 0.15 ms same, 0.42 ms

The SLA rows above are expected plans, not measured results. The harness runs SLA due and SLA due page 2 for Admin and Agent and prints their plans; the 50k-ticket p95 run on the owner’s DOMAIN-RULES §14 reference host is still owed. The SLA index omits department_id before the sort key because its RLS predicate cannot be an index condition; the explicit brand equality allows an ordered scan with department filtering.

“Unassigned” reads the brand-wide index rather than the assignee one: IS NULL is an index condition but not an equality, so Postgres cannot treat the assignee index as ordered past it, and walking the newest tickets is cheaper than sorting all 4 800 unassigned ones.

Search under row-level security

Postgres will not use a condition as an index condition ahead of a row-level security policy unless the condition’s operator is LEAKPROOF: a function that is not could raise an error that reveals a row the policy was about to hide. @@ (ts_match_vq) and <% (word_similarity_op) are not leakproof (nor is = on an enum, which is why the priority and channel filters are filters too). Until M1-15 part 2 the list evaluated a search on each visible ticket, newest first, until it had a page, and a term that matched nothing read every visible ticket: 257 ms for an Admin at 50k tickets.

ADR 0011 moved search onto ticket_search_tokens, one row per lexeme of a ticket’s subject and first message, under the same FORCEd brand and department policies as every ticket child table. = and the range comparisons on text are leakproof, so the token lookup is an index condition ahead of the policy, and the policy’s department check runs on the index entry (department_id is in the index, so no heap is read). The key lines, as the runtime role under an Admin’s context at 50k tickets, for a term nothing matches:

-- exact half
Index Only Scan using ticket_search_tokens_brand_token_idx on ticket_search_tokens tokens  (rows=0 loops=1)
  Index Cond: ((brand_id = ANY (…app.brand_ids…)) AND (brand_id = '…'::uuid) AND (token = ANY ('{zebra}'::text[])))
  Filter: (COALESCE(…app.all_departments…) OR (department_id = ANY (…app.department_ids…)))
Execution Time: 8.798 ms

-- fuzzy fallback: the words sharing the first three letters, then <%
Index Only Scan using ticket_search_tokens_brand_token_idx on ticket_search_tokens near  (rows=0 loops=1)
  Index Cond: ((brand_id = ANY (…)) AND (brand_id = '…'::uuid) AND (token >= "left"(wanted.lexeme, 3)) AND (token < ("left"(wanted.lexeme, 3) || '…'::text)))
Execution Time: 9.487 ms

Most of those 9 ms is the contact-name half (ILIKE over the brand’s 20 000 contacts); the token lookups themselves take well under a millisecond. The fuzzy half’s candidates are read in a LATERAL subquery kept apart with OFFSET 0: flattened, the planner read every token of the brand and applied the range as a join filter (151 ms). An integration test (tickets.integration.test.ts, “looks the … words up in the token index ahead of the policy”) EXPLAINs both halves as the runtime role and fails if the token condition leaves Index Cond.

What it costs: a common word is no longer “stop after a page”. Every ticket carrying refund (3 191 of 50 000) is found, joined and top-N sorted, so that search went from p95 47 ms to 86 ms under load. That is inside the gate and grows with how many tickets share a word, not with the brand’s size.

The two GIN indexes stay: the PRD names the tsvector one, and both serve paths that run as the owner. LEAKPROOF wrappers were rejected: the operators can raise, so the promise would be false.

How it is measured

pnpm --filter @helpdock/api build
pnpm --filter @helpdock/api perf:tickets

apps/api/src/testing/perf/, run by apps/api/vitest.perf.config.ts. The help center and realtime gates of M9-03 run on the same harness (performance).

  1. Dataset (dataset.ts): five brands. The measured one has 50 000 tickets, about 200 000 messages and 20 000 contacts, the other four 10 000 tickets each. The rows are written by INSERT … SELECT generate_series(…) as the runtime role inside each brand’s system transaction, so every one passes the same policies and department triggers as the api’s own writes, and each ticket is numbered from the brand’s own sequence. The shape is a desk two years in: 70 % Closed, 3 % Spam, 2 % Merged, and the live queues (Open 14 %, Awaiting customer 8 %, Escalated 3 %) recent; five departments at 45/20/15/12/8 %; twenty assignees, a quarter of the live queue unassigned; 0–3 tags per ticket on a power law; 0.5 % soft-deleted. Every random choice is seeded, so a run is repeatable. Articles and knowledge chunks have no tables until M5.
  2. Stack: pgvector/pgvector:pg17 and redis:7-alpine in containers, and two api replicas started from dist/ as separate processes with NODE_ENV=production.
  3. Load (load.ts): 50 concurrent staff sessions, closed loop, each waiting 1 s between a response and its next request, spread over the two replicas. Each session cycles through every scenario, once as an Admin and once as an Agent confined to the two smallest departments (20 % of the tickets): All tickets, My open, Unassigned, the live states of Overdue, Escalated, search refund, search renewa, a search nothing matches (zebra), two tags, page 2, opening a ticket, and the sidebar’s view counts (GET /views/counts, M1-05). Two minutes of warm-up, ten measured, p50/p95/p99 by nearest rank.
  4. Zero-match search: a search nothing matches is in the mix like every other scenario, gated by its own budget, PERF_NO_MATCH_P95_MS (ADR 0011). Until M1-15 part 2 it was measured alone and reported, not gated.
  5. Plans: EXPLAIN (ANALYZE, BUFFERS) of every list query, built by the repository’s own listTicketsStatement, run as the runtime role inside the tenant context the request would carry.
Variable Default
PERF_CONCURRENCY 50 staff sessions
PERF_THINK_MS 1000 pause between one session’s requests
PERF_WARMUP_S / PERF_DURATION_S 120 / 600
PERF_REPLICAS 2 api processes
PERF_P95_MS 150 the gate
PERF_NO_MATCH_P95_MS 150 the zero-match search’s own gate
PERF_SCALE 1 multiplies the dataset; 0.1 for a smoke run
PERF_REPORT none also write the results and plans as JSON

What differs from §14, so the numbers are read for what they are: the host is whatever runs the command, not a dedicated 2 vCPU / 4 GB machine; the load generator shares it; there is no worker and no widget traffic; and there are no articles or chunks. On a shared or busy machine the tail measures the machine, so run it on an idle one.

What it measured last (2026-09-25)

The gate passes, zero-match search and the sidebar’s view counts included (M1-15 part 2 after ADR 0011, integrated with M1-05 views). The full §14 run: 50 sessions, 1 s think time, 2 min warm-up, 10 min measured, two replicas; 48.5 req/s, overall p95 72 ms, no errors. The slowest gated scenario is 115 ms against the 150 ms gate (renewa as an Admin, which runs both halves of the search). The load generator and the api replicas were pinned to two cores (taskset -c 0,1) and the machine was otherwise idle (load average below 1 at the start). The previous column is the pinned, idle run of the index set before the token table.

Scenario Admin p50 / p95 / p99 ms Agent p50 / p95 / p99 ms Before, p95 Admin / Agent
All tickets 13 / 29 / 48 14 / 30 / 52 32 / 32
My open 8 / 21 / 37 14 / 29 / 47 21 / 28
Unassigned 15 / 33 / 57 17 / 35 / 55 31 / 33
Live states (Overdue) 15 / 33 / 57 16 / 37 / 62 29 / 34
Escalated 17 / 35 / 61 22 / 41 / 61 36 / 39
Search refund 55 / 86 / 108 36 / 64 / 88 47 / 51
Search renewa (fuzzy fallback) 75 / 115 / 144 59 / 94 / 117 46 / 48
Search matching nothing 32 / 56 / 81 32 / 56 / 80 284 / 186 (alone, not gated)
Two tags, all-of 28 / 53 / 75 33 / 62 / 84 50 / 53
Page 2 14 / 31 / 58 14 / 31 / 50 28 / 29
Open a ticket 21 / 47 / 79 21 / 45 / 81 46 / 41
View counts (sidebar) 30 / 57 / 77 45 / 72 / 101 new in M1-05

The zero-match search went from reading every visible ticket to two index probes: p95 284 ms measured alone to 56 ms inside the full load. A word many tickets share costs more than before, and a half-typed word pays for two statements (the exact half, then the fallback); both are explained under Search under row-level security.

An earlier run (2026-09-24) on the same container while six other build jobs shared it (load average 27–64) put list p95 at 0.8–2.1 s: that measured the machine’s queue, not the api, which is why a run belongs on an idle host.

Before the index set and the brand equality, the same quieter-machine comparison could not be made, but the plans could: the default list read and sorted every visible ticket (27 ms of database time on its own, before load), and a first full-scale run on the same shared machine put the default list’s p50 at 114 ms against 20 ms after the change.

Time tracking

M1-12, and optional per brand (REQUIREMENTS §4.1): Inbox › Feedback › Track time on tickets, off by default.

ticket_time_entries holds one row per entry: who, how long in whole seconds (1 to 24 h 59 m, the Log time dialog’s bounds), an optional staff-only note, and the reply it was logged with when it came from the per-reply timer. It is a child of the ticket and department-scoped like the thread: the shared triggers copy the ticket’s department on insert and move it with the ticket, so an agent who cannot read a ticket cannot read or log its time, and the RLS negative suite covers the table.

There are three ways time gets logged:

From How Row
The Log time dialog (header ⋯ → “Log time…”, or “Add time manually”) POST …/time-entries message_id null, with the note
The Time card’s timer, Log POST …/time-entries with what the timer counted message_id null
The per-reply timer timeSpentSeconds on POST …/messages, written in the same transaction as the reply message_id = the reply

The timer lives in the browser (apps/admin/src/screens/tickets/use-ticket-timer.ts): nothing reaches the server until a reply is sent or Log is pressed, so an abandoned timer costs nothing. With Start the timer when an agent opens the composer on, it starts when the caret enters the reply box; sending a reply or a note stops it and sends its time with the message. A timer left running for longer than one entry allows is capped rather than refused, because the reply must not fail over it. A reply’s timer is dropped, never refused, while the brand has tracking off.

Anybody who can write to the ticket may log time; an entry is deleted by whoever logged it, or by a Team Leader or an Admin. A Viewer reads the card and has none of its controls. Entries are not realtime yet: another agent’s Time card updates on its next read.

Satisfaction surveys

M1-12 (REQUIREMENTS §4.1, DOMAIN-RULES §2.2 and §4.6). Inbox › Feedback › Ask for a rating when a ticket closes, on by default.

One survey per close. A close that is not spam or a merge (read off the status’s is_spam through isSpamStatus and the ticket’s merged_into_id, never off a name) runs onClosedForCsat, which — when the brand has CSAT on — writes csat.requested { ticketId, closedAt } to the outbox in the closing transaction. The worker’s handler (apps/api/src/csat/csat-events.ts) re-reads the ticket and creates the row in csat_responses only if that close still stands: a ticket reopened, merged, marked as spam or deleted before the job ran gets none. (ticket_id, closed_at) is unique, so a redelivered job is a no-op, and a ticket reopened and closed again gets a second survey. csat_responses is department-scoped like the other children of a ticket.

Delivery on close (M8-06). The run that creates the survey also sends it, in the same transaction, on the ticket’s channel (apps/api/src/csat/csat-delivery.ts):

The ticket came in by The customer gets sent_at is set
The widget (chat) A card in the conversation (Widget/CSAT-EN): five scores, an optional comment of up to 1000 characters, Skip and Send rating. It replaces the composer until answered or skipped, and is pushed as a csat socket event and read over REST (see the widget protocol) when the card is offered
Telegram The question with five buttons, 1 to 5, and Add a comment, which opens the rating page (Telegram/Chat-EN, panel 5). A tap records the score at once when Telegram accepts the message
WhatsApp, Messenger, Instagram Nothing (M10): those contacts have no address, and the survey after a close is usually outside the reply window. It needs a WhatsApp template or Messenger’s customer_feedback template (M10-09 or later). The survey stays pending and the agent can still share the link never
Email, the web form, the api or a ticket filed by hand A survey email (Email/CSAT-EN-AR) to the contact alone, no CCs, from the department’s sender, in the contact’s language or the brand’s when the relay accepts the email

Email and Telegram go through the outbox like every message to a customer: an email_deliveries row of kind csat (one per survey, Message-ID <hd.c.<surveyId>@…>, header Auto-Submitted: auto-generated) and its email.send, or a telegram.notice of kind csat_survey. A ticket with nobody to reach (no address, no chat, a brand with no sender) keeps its survey pending, and the agent can still share the link. The survey goes out at once, on the one channel the ticket came in by: Inbox › Feedback has no delay and no channel choice.

The email’s five links only open the page. Each is the survey’s link with ?rating=<n>&lang=<locale>: the page opens with that score pressed and records nothing until the customer presses Send, so a mail scanner that follows every link in a message casts no rating. The plain-text part lists the same five links.

A Telegram tap records the score in one go. The button’s data is csat:<surveyId>:<n>. The webhook records it only if the chat that pressed it is the ticket’s contact’s; then the bot removes the score buttons, keeps Add a comment and thanks the contact: “Thanks! You rated this request 4 · Good. You can still add a comment on the survey page until 4 Nov.” A second tap, a tap after the 30 days or a tap from another chat records nothing and gets “This survey has closed.” The link stays usable once after a tap: the page opens with the tapped score pressed, and Send stores the comment (and the score, if changed) as the link’s answer.

Skip on the widget card records no answer; it stores skipped_at so the card is not offered again on any device, and draws “You skipped the rating”. A link shared another way still works.

Every answer emits csat.received. Whichever way it arrives — the page (rated_via link), the widget card (widget) or a Telegram tap (telegram) — a recorded answer writes an audit_log row (csat.rated, with the score and the channel) as the survey’s system principal and the outbox event csat.received { ticketId, surveyId, rating, via, ratedAt }, in the same transaction (apps/api/src/csat/csat-answers.ts). Workflow rules with the CSAT received event run on it (automation); the comment is not in the event, so the outbox holds no customer text.

The link. APP_URL/csat/<token>. The token is <ids>.<mac>: the brand and survey ids, and an HMAC-SHA256 over them under a key derived from APP_MASTER_KEY with HKDF (apps/api/src/csat/tokens.ts). Only a SHA-256 of it is stored. It is:

  • signed — an altered or guessed token is refused before any query runs;
  • bound to one ticket — it names one survey, and the survey one ticket;
  • single-use — the rating is written by an UPDATE … WHERE rated_at IS NULL AND expires_at > now(), so two submissions cannot both win; the second answers used. The one exception is a Telegram tap with no comment yet, which leaves the link open for one submission (M8-06);
  • expiring — 30 days after the survey is created, it answers expired.

A token signed under APP_MASTER_KEY_PREVIOUS still verifies, so a key rotation does not strand the surveys already out; a key older than that does not.

The public routes are an explicit system path. The token names the brand, so the api opens a transaction scoped to exactly that brand as the system principal csat:<surveyId>, reads one survey and its ticket’s reference and subject, and writes an audit_log row (csat.viewed, csat.rated) for every use of a valid link. Opening the page, from an email’s link or any other, only reads. Both routes share a per-address budget of 30 requests in 15 minutes (CSAT_PUBLIC_RULE), and both collapse the token to :token before the request line is logged. A spent link answers with the brand alone — never the subject.

The agent’s view. GET /tickets/:ticketId carries csat for the latest close: pending (created, not delivered yet, or nobody to reach), sent (a channel delivered it), rated (with the rating and comment) or expired, and the link while it can still be used. The details panel draws it on a Satisfaction card with Copy survey link, for sharing it another way.

If there is no native survey, the card may show the latest imported historical answer instead. An original answer whose scale cannot be established appears as imported_unscored; expand Original survey answers to read its questions and values. It has no share link and does not affect score averages. Imported answers also appear in the ticket timeline at their original response dates, so older answers remain readable when a newer native survey exists. Their history events do not trigger satisfaction workflows or send a survey.

The contact card. A contact’s stats.csat is the share of their answered surveys rated 4 or 5, as a percentage, over the tickets the viewer can see; null when they have answered none.

The rating page is served by the admin bundle at /csat/<token> but mounted without any of the staff app (ADR 0010). Its language is ?lang= when it names en or ar, otherwise the brand’s default. ?rating= from 1 to 5 presses that score when the page opens, and an open link a Telegram tap already answered sends its score as rating and presses it; either way nothing is recorded until Send. It is themed with the brand accent when the brand has one (none do until M5/M6’s themes).

Who closed it. An open link’s ticket.closedBy is the public name (the first name until one is set) of the staff member who closed the ticket (“closed by Lina”), and null otherwise. It is set only when that person is still active in the brand and wrote a public reply on the ticket, so the page names nobody the customer has not already heard from. That keeps it inside §4.6’s “nothing beyond their purpose”. An api key, a rule, or a staff member who never replied is not named. A spent link sends no name.

Browse the help center. The thanks and the spent-link screens end with “Browse the help center” (CsatEN), linking to brand.helpCenterUrl: the brand’s help center on its primary verified domain, or APP_URL/hc/<brandId>/ until it has one. The api sends it only while the help center has something public to read: at least one published public article and access not set to internal-only. Otherwise it is null and the link is left out. The preview never shows it, as it reads nothing.

The preview. Inbox › Feedback › Open the rating page as a customer sees it opens /csat/preview?lang=<admin's language> in a new tab. That is the same page over a fixed sample (apps/admin/src/csat/preview-api.ts), under a line that says it is a preview. It makes no request: it holds no token, reads no ticket, and a rating sent from it is drawn as sent and stored nowhere. preview cannot collide with a real token, which is always two base64url halves joined by a dot.

What later milestones add

Milestone Adds
M1-13 Shipped. Identity rules, contact merge with undo (guide), and the participants card in the details panel
M1-09 Shipped in branch. Merge, unmerge and split (above), and “is replying” on the collision indicator. Leaves MergeParticipantsHook for M1-13 and onMerged / onUnmerged for M3-02
M1-10 Shipped. attachments hangs off the ticket and, once sent, off ticket_messages.id; POST …/messages takes attachmentIds and every message carries its attachments (guide)
M1-11 Shipped in branch. is_spam on the Spam status, POST/DELETE …/spam, ticket.spam, the sender block list and its inbound gate (Spam)
M1-12 Shipped. Time tracking and satisfaction surveys (above)
M8-06 Built in branch. The survey sent on close by email, in the widget and on Telegram, and csat.received on every answer (above)
M10-06 Built in branch. Replies to WhatsApp, Messenger and Instagram, the reply window refused at compose time and again by the job, and the ticket’s …/meta routes (above)
M1-15 The rest of the admin UI, as each deliverable above lands — including the tag picker and the custom field editors in the details panel
M2 Inbound and outbound email on the same ticket_messages, keyed by external_message_id
M3 Macros, which set a status, a priority, an assignee and tags in one action, and rules whose conditions read custom field keys
M3-02 Built in branch. The SLA engine fills first_response_due_at, resolution_due_at, sla_breached, sla_policy_id and sla_cycle; a ticket read carries sla, a list row ticket.sla (guide)
M7 AI that suggests tags, a priority and a department for a ticket
M5 Per-locale search configuration; tickets.search uses english for every brand today

Search

Type to search the docs, features, channels, comparisons and changelog.