-
-
Notifications
You must be signed in to change notification settings - Fork 29
Ticket AI Reading Developer Guide
The two AI features from discussion #104: the maintained summary at the top of a ticket, and "Read it for me".
The three automatic (non-AI) behaviours are in Reading Long Tickets β Developer Guide. The user-facing page is Reading Long Tickets.
Neither feature removes, rewrites or replaces anything. Read this before changing either of them:
-
Neither one touches
emailsorticket_notes. Both read. The only table they write isticket_ai_summaries, which is additive-only βINSERTandSELECT, noUPDATEof a summary and noDELETEanywhere in the feature. -
A refresh writes a new version. It never overwrites the old one.
$version = $latest ? ((int)$latest['version'] + 1) : 1;β and every earlier version stays readable in History. - The summary never replaces the conversation. It is an extra pane above a thread that renders exactly as it did before. Switch the feature off and the ticket is unchanged; the stored summaries are simply not shown.
-
It says what it has not read.
last_email_idrecords how far it got, so the panel states "4 messages have arrived since this was written" rather than quietly presenting a stale reading as current. - A truncated answer is recorded as truncated, not served as though it were whole.
Why so absolute: this is the one feature in FreeITSM that could quietly become the only thing anybody reads. A summary that silently stands in for the ticket is a worse outcome than no summary, so every design decision here is arranged to keep the real conversation in front of the reader and to keep the summary visibly, checkably second-hand.
The companion guide's boundary note applies here too:
stripInboundThread()at ingestion stores only the new part of an inbound reply. Nothing on this page does that β these features read whatever is stored.
| File | What it holds |
|---|---|
includes/ticket_ai.php |
Settings, the transcript builder, staleness helpers, both prompts |
api/tickets/ai_summary.php |
GET current / GET history / POST new version |
api/tickets/ai_read.php |
GET stored briefing / POST new one |
assets/js/inbox.js |
The panel, the modal, the busy guards, the counting wait |
assets/css/inbox.css |
.ai-summary*, .ai-panel*, .ai-history*
|
database/freeitsm.sql Β· includes/db_verify_schema.php
|
ticket_ai_summaries |
One table, two kinds:
CREATE TABLE IF NOT EXISTS `ticket_ai_summaries` (
`id` INT NOT NULL AUTO_INCREMENT,
`ticket_id` INT NOT NULL,
-- 'summary' = the standing panel at the top of the ticket; 'read' = a
-- "read it for me" briefing. One table because they want the same three
-- things β a version history, a record of how much was read, and a way to
-- know the conversation has moved on since. Two tables would be two sets
-- of those rules, and they would drift.
`kind` VARCHAR(16) NOT NULL DEFAULT 'summary',
-- Numbered per (ticket, kind), so a briefing and a summary count separately.
`version` INT NOT NULL DEFAULT 1,
`summary` MEDIUMTEXT NOT NULL,
β¦
`last_email_id` INT NULL,
`generated_by` INT NULL,
`truncated` TINYINT(1) NOT NULL DEFAULT 0,
KEY `ix_ticket_ai_summaries_ticket` (`ticket_id`, `kind`, `version`),generated_by NULL means FreeITSM refreshed it by itself; an analyst id means
somebody pressed the button. Recording an analyst on an automatic refresh would
make it look as though a person had asked for it.
The obvious implementation compares timestamps. That is wrong twice over: two
messages can share a received_datetime to the second, and a summary written at
14:03 may or may not have read a message stored at 14:03.
last_email_id is what the summary actually read, so the comparison is exact:
/* By id rather than by timestamp: two messages can share a received time to
the second, and "newer than the last one I read" has to be exact. */
$stmt = $conn->prepare("SELECT COUNT(*) FROM emails WHERE ticket_id = ? AND id > ?");
$stmt->execute([$ticketId, $lastEmailId]);
return (int)$stmt->fetchColumn();// Recorded even when the body turns out to be empty: this is "how far I
// have read", and an empty message still moves that mark forward.
$lastEmailId = (int)$m['id'];
if ($plain === '') continue;Skip that and an attachment-only message makes every subsequent summary report itself as permanently one behind.
One builder for both features (and available to the merge summary). It had been written twice before this and the copies had not disagreed yet, which is the only reason nobody had noticed.
/* The most RECENT messages, not the first ones. A ticket that overflows the
cap overflows it at the old end, and the old end is the part somebody
picking this up cares least about. Fetched newest-first under the limit
and then reversed, so the transcript still reads forwards. */
$stmt = $conn->prepare(
"SELECT e.id, e.direction, e.from_name, e.from_address, e.received_datetime,
e.subject, e.body_content, e.body_type
FROM emails e
WHERE e.ticket_id = ?
ORDER BY e.received_datetime DESC, e.id DESC
LIMIT $maxMessages"
);
$stmt->execute([$ticketId]);
$messages = array_reverse($stmt->fetchAll(PDO::FETCH_ASSOC));$maxMessages is interpolated, which is safe only because it is clamped to an
int first β max(1, min(500, (int)β¦)) at the top of the function. Keep it that
way; a LIMIT placeholder does not bind portably in emulated-prepare mode.
// Did we leave anything behind? Worth saying out loud in the prompt, so the
// model does not confidently describe a beginning it never saw.
$stmt = $conn->prepare("SELECT COUNT(*) FROM emails WHERE ticket_id = ?");
$stmt->execute([$ticketId]);
$truncated = (int)$stmt->fetchColumn() > count($messages);β¦and it goes into the prompt as words:
$user .= "NOTE: this ticket is longer than what follows. You are seeing the "
. "most recent part of the conversation only. Do not describe how the "
. "ticket began unless the text below actually says.\n\n";Without it the model narrates an opening it never saw, confidently and wrongly.
Markup is noise that costs tokens β and stripping it means no HTML from a stranger's email is ever echoed back into anything FreeITSM renders.
The two rules doing the real work in the summary prompt are both about what not
to do (this is the prompt text as the model receives it, assembled in
ticketAiSummarySystemPrompt()):
- State only what the conversation says. Never infer a cause, a fix or a
resolution nobody wrote down.
- If something important is unclear or missing, say it is unclear. That is a
useful answer, not a failure.
A summary that invents a fix reads exactly like one that did not. And a summary that hides its uncertainty removes the only signal telling somebody to go and read the thread themselves.
"Read it for me" is allowed to suggest, and therefore has to mark suggestions
(from ticketAiReadSystemPrompt()):
What I would do next
- concrete suggestions. Begin this section with the line 'These are suggestions,
not conclusions.'
β¦
- Separate what the ticket SAYS from what you are guessing, every time.
Both are told internal notes are staff-only, and never to phrase anything as if it were going to the customer.
Every one of these exists because the alternative charges somebody.
$auto = !empty($input['auto']);
if ($auto) {
/* The server decides, not the browser. Two tabs opening the same ticket
would otherwise bill twice for the same summary, and a page that
refreshes on a timer would bill for ever. */
if ($settings['summary_auto_after'] <= 0) {
echo json_encode(['success' => false, 'error' => 'auto_disabled']);
exit;
}
if ($latest !== null && $behind < $settings['summary_auto_after']) {
echo json_encode(['success' => false, 'error' => 'not_due']);
exit;
}
}The page asks for an automatic refresh; this decides. Both refusals happen
before aiProviderChat() is reached, so a refused request costs nothing.
An automatic refresh only ever happens when somebody opens the ticket. A nightly sweep across an open queue would bill for summaries of tickets nobody looked at, and the bill would arrive before the feature had been any use to anyone. Cost is therefore proportional to tickets actually read.
ai_read.php answers GET from the table and never touches the provider. Only a
re-read spends anything.
Measured: 62 seconds β 0.16 seconds. The first build stored nothing, on the reasoning that a stored suggestion becomes a fact the next reader takes for a person's assertion β but the lived experience of that was waiting a minute for a briefing you had already read. Storing it and labelling it properly is the better trade, and the labelling is the same as the summary's: datestamp, what it read, an AI badge, and how far behind it is.
// The maintained summary panel at the top of a ticket (idea 7).
'summary_enabled' => 0,
β¦
'read_enabled' => 0,with a catch that falls back to the same array:
} catch (Exception $e) {
// Defaults β and the defaults are OFF, so a settings table we cannot
// read can never start spending somebody's money.
}Every other setting in this area changes how something already free is displayed. These two spend money with somebody else's API key, so a settings table we cannot read must fail towards not spending.
async function runReadForMe() {
if (_aiReadBusy || !_aiReadTicketId) return;
_aiReadBusy = true;const started = Date.now();
const tick = setInterval(() => {
const el = document.getElementById('aiReadWait');
if (el) el.textContent = t('tickets.ai.working_secs').replace('{n}', Math.round((Date.now() - started) / 1000));
}, 1000);Counts up rather than animating: "38s" says it is still going and roughly how
long this model takes on this desk. Cleared in finally so it cannot outlive the
request.
/* β οΈ A reasoning model on a long ticket takes a MINUTE β measured at 62s on a
real one. PHP's default limit would kill the request after the provider had
already been paid and before anything was written down, which is the worst
of both. */
@set_time_limit(300);Both endpoints hit this, and so does every other AI feature. Full write-up in AI Providers; the part that matters here:
A reasoning model spends its output budget thinking before it writes a single
character. With a modest max_tokens you get HTTP 200, a full usage record and
content: "". Measured on qwen/qwen3.7-plus, a one-sentence question spent
375 reasoning tokens of 383.
So neither endpoint treats an empty answer as a generic failure:
if ($text === '') {
/* Nothing came back, and there are two very different reasons for that.
A reasoning model that ran out of budget mid-thought is a SETTINGS
problem with a fix the administrator can act on; anything else is not.
Reported as itself, because "that did not work" sends somebody looking
at their API key for a problem that is nowhere near it. */
$ranOut = in_array($result['finish_reason'] ?? '', ['length', 'max_tokens'], true)
|| (int)($result['reasoning_tokens'] ?? 0) > 0;
echo json_encode(['success' => false, 'error' => $ranOut ? 'reasoning_overran' : 'empty_response']);
exit;
}And a truncated answer β worse than an empty one, because it reads almost complete and the section it loses is the last β is recorded rather than hidden:
/* Did it finish? A truncated summary is the worst thing this can produce β
it reads almost like a complete one, and the section it lost is usually the
last, which is where "waiting on" lives. Stored as a fact so the panel can
say so, rather than being dropped (half a summary is still worth reading if
you know that is what it is). */
$wasCut = in_array($result['finish_reason'] ?? '', ['length', 'max_tokens'], true) ? 1 : 0;The real fix is not a bigger budget β it is System β AI thinking, which turns extended thinking off per feature. Measured on a two-message ticket: 54.7s with thinking on, 6.9s with it off, and the fast answer was the better one.
Both endpoints gate on tenancy before anything else:
// Multi-tenancy: a summary of a ticket you cannot open would be a novel way
// to read one.
if (!analystCanAccessTicket($conn, $analystId, $ticketId)) {
echo json_encode(['success' => false, 'error' => 'Ticket not found']);
exit;
}'Ticket not found' for both missing and forbidden β the same wording, so the
response does not confirm a ticket exists in a company you cannot see.
kind never reaches SQL from a request:
// Never interpolated from a request: an unknown kind falls back rather than
// reaching the query.
if (!in_array($kind, TICKET_AI_KINDS, true)) $kind = 'summary';Both use TICKET_AI_NS = 'tickets_reply_cleanup' β the same one the reply cleanup
and merge summary already use, so an administrator configures "the AI that reads
tickets" once rather than pasting a key into a third panel.
Use the messy fixture, not a clean database β see the companion guide. Then check, in order:
-
With both settings off:
ai_summary.phpreturns{"disabled":true}andai_read.phpreturns{"error":"disabled"}β no provider call. -
auto: truewhen not due:not_due; withauto_after = 0:auto_disabled. Both before any spend. -
A real refresh writes
version + 1and leaves the previous row alone. - Reopen a briefing: served from the table, sub-second, and the network tab shows no provider traffic.
- The panel shows the datestamp, the message count, the version, and the "n messages have arrived since" line when the ticket has moved on.
- Reading Long Tickets β the user-facing page
- Reading Long Tickets β Developer Guide
- AI Providers β the client, the thinking switch, the reasoning trap
- Knowledge Assistant β Developer Guide β the other "judge then draft" feature
FreeITSM β an open-source IT Service Management platform Β· github.com/edmozley/freeitsm Β· MIT licence
- Installation
- β° Scheduled tasks (cron jobs)
- Architecture
- π§ͺ Developer tests
- AI Providers
- Internationalisation (i18n)
- Timezones & Time Handling
- π Date & Time Formats
- Theming & Dark Mode
- ποΈ Recent β getting back to what you were doing
- β¨οΈ Command palette (βK)
- π Searching inside tickets
- π Attached documents
-
MobileβFriendly
- β³ π« Mobile: Tickets
- β³ π» Mobile: Assets
- β³ π Mobile: Calendar
- β³ π Mobile: Knowledge
- β³ π¦ Mobile: Service Status
- β³ πΌ Mobile: Watchtower
- β³ π§© Mobile: Problem Management
- β³ π Mobile: Change Management
- β³ πΏ Mobile: Software
- β³ β Mobile: Tasks
- β³ π Mobile: Forms
- β³ π Mobile: Contracts
- β³ π Mobile: Domains
- β³ π Mobile: People
- β³ π Mobile: LMS
- β³ πΊοΈ Mobile: CMDB
- β³ πΊοΈ Mobile: Network Mapper
- β³ π§ Mobile: Process Mapper
- β³ βοΈ Mobile: Workflow
- β³ π₯οΈ Mobile: System
- β³ π Mobile: Reporting
- β³ π Mobile: System Wiki
- β³ π Mobile: Self-Service Portal
- β³ π§° Mobile: Techniques & Tricks
-
Security
- Layer 1 β which modules you can enter
- β³ π§© Module Access Control
- β³ π οΈ Module Access β Developer Guide
- Layer 2 β what you can administer
- β³ π Roles & Permissions
- β³ π οΈ Roles β Developer Guide
- β³ π€ Why capabilities are constants
- Layer 3 β the System module
- β³ π Admin Access Control
- Hardening
- β³ π Security review response 2026-08
- β³ π‘οΈ Security hardening 2026-08
- β³ π οΈ Security hardening 2026-08 β Developer Guide
- β³ π‘οΈ Round three β plain English
- β³ π οΈ Round three β Developer Guide
- β³ π‘οΈ CSRF protection (S4) β Developer Guide
- Single Sign-On (SSO)
- ποΈ LDAP & Active Directory
- π CardDAV contact sync
- Browser Extension
- API Reference
-
π REST API β how it works
- β³ π« REST API: Tickets
- β³ π» REST API: Assets
- β³ π΄ REST API: Problems
- β³ π REST API: Changes
- β³ π REST API: Knowledge
- β³ β REST API: Tasks
- β³ ποΈ REST API: CMDB
- β³ π REST API: Contracts
- β³ ποΈ REST API: Calendar
- β³ πΏ REST API: Software
- β³ π REST API: Domains
- β³ π¦ REST API: Service Status
- β³ βοΈ REST API: Morning Checks
- β³ π REST API: Forms
- β³ βοΈ REST API: Workflow
- β³ π·οΈ REST API: Cost centres
- β³ πΊοΈ REST API: Network Mapper
- β³ π§ Using the API docs page
- β³ π OpenAPI specification
- β³ β OpenAPI: kept correct
- β³ π οΈ Maintaining the catalogue
- Watchtower
-
Tickets
- β³ π Rota copy and paste β Developer Deep Dive
- β³ β Checklists & SOPs
- β³ βοΈ Mandatory fields
- β³ π·οΈ Ticket categories
- β³ π₯ Assigning tickets to a team, and escalation
- β³ π’ One board across every company
- β³ Mailbox Authentication
- β³ π€ Email send log
- β³ Basic IMAP mailboxes
- β³ Email rendering & images
- β³ SLA Management
- β³ WhatsApp channel
-
β³
βοΈ Telegram channel - β³ β CSAT company scope and filters β Developer Guide
- β³ π₯ Microsoft Teams channel
- β³ π¨οΈ Mattermost channel
- β³ π¬ Web chat channel
- β³ π£ Slack channel
- β³ π Linking tickets
- β³ β Record previews
- β³ π Ticket notes: internal or shared
- β³ ποΈ Canned responses
- β³ βοΈ Limiting replies to particular senders
- β³ π¨ Telling the analyst a ticket is theirs
- β³ βοΈ Email signatures
- β³ π The public web address
- β³ π’ Ticket numbering
- β³ π Raising a ticket for someone else
- β³ π Merging tickets
- β³ π Confidential tickets
- β³ π₯ Portal managers
- β³ π Who has seen a ticket
- β³ π Reading long tickets
- β³ β Splitting tickets
- β³ β Selecting several tickets
- β³ ποΈ The folder pane
- β³ π½ Just my tickets, or no closed ones
- β³ π οΈ Snoozing tickets β Developer Guide
- β³ π₯ Collision detection
- β³ β±οΈ Time tracking
- β³ π Scheduled work in your own calendar
- Problem Management
- Tasks
-
Assets
- β³ π’ Moving an asset between companies
- β³ π Shared asset locations
- β³ π§βπΌ Assigning assets to analysts
- β³ π Warranty and lease alerts
- β³ π Saved table views
- β³ π¨οΈ Recording anything, and importing it
- β³ π·οΈ QR asset labels
- β³ π Who holds what, and handover documents
- β³ π₯οΈ The inventory agent (PowerShell)
- β³ ποΈ Proxmox VE servers
- β³ βοΈ VMware Cloud Director servers
- β³ π Linking equipment to tickets
- β³ βοΈ Follow-up tasks on a ticket
- Knowledge
- Change Management
- Calendar
- Morning Checks
- Reporting
- Software
-
Forms
- β³ π¨ The form designer β Developer Guide
- β³ π Layout & the grid β Developer Guide
- β³ ποΈ Collections β grouping submissions
- β³ π Submissions as PDFs
- β³ β‘ What happens next β a form's own actions
- β³ π οΈ Sections & conditional logic β Developer Guide
- β³ π οΈ Lookup fields β Developer Guide
- β³ π‘οΈ Catalogue request approvals
- People
- Domains
- Contracts
- Service Status
- π Notifications
- π¨ War Room
- Self-Service Portal
- LMS
- Process Mapper
- CMDB
- Network Mapper
- Workflows
- Issue trackers (Jira, Azure DevOps)
- System
-
Overview
- β³ π Progress tracker
- β³ Concepts & vocabulary
- β³ Email routing & mailboxes
- β³ Settings: global vs per-company
- β³ Users & self-service
- β³ Staff cross-company access
- β³ π’ One board across every company
- β³ Worked examples
- β³ Pitfalls & gotchas
- β³ Scope: what it's for
- β³ π οΈ Developer Guide (make a module multi-company)
- β³ ποΈ Case study: CMDB (a linked graph)
- β³ π§ͺ Test harness (prove it's isolated)
- What this is
-
π Bugs resolved
- β³ πΌοΈ Logo and courses broke on Apache with PHP-FPM
- β³ π’ Chat tickets ignored your ticket numbering
- β³ π Dates shown as a dash, or in server time
- β³ π Assets β Users showed people from other companies
- β³ π Restricted analysts could read other modules' data
- β³ πΌοΈ Replies with a picture in the thread failed to send
- β³ π Reply attachments never reached the customer
- β³ π οΈ Outbound email attachments β Developer Guide
- β³ π A global SSO provider was missing from the portal
- β³ π Behind a proxy, the SSO redirect said http
- β³ βοΈ The portal tagline moved when you saved it
- β³ π¨ The portal settings screen forgot what you saved
- β³ π‘οΈ The approvals inbox said "Error" and nothing else
- β³ π A table's answers were missing from the PDF
- β³ β A single-select column let you tick every option
- β³ π The portal ignored a form's field widths
- β³ π The tasks board stopped taking clicks
- β³ ποΈ #121 The index list is out of date after upgrading
- β³ π #133 The calendar subscription was empty
- β³ π #131 Tasks always reopened on the board
- β³ π₯ #129 Every page returned HTTP 500 after upgrading
- β³ π³ #127 A PHP warning above the System page
- β³ π #126 Notes stamped with the server's clock
- β³ π Storing every date in UTC
- β³ πͺ The portal was down for everyone signed in
- β³ βοΈ #120 Workflow notes could never be written
- β³ βοΈ #123 Three errors when running Database Verification
- β³ π #122 The description box was a stub in the corner
- β³ π£ Demo data deleted real accounts
- β³ π #117 Sign-in redirected to the wrong address
- β³ π¨ #108 The priority dot was invisible
- β³ β±οΈ #116 Time logged from the right-click menu
- β³ π #114 API keys refused by our own guard
- β³ ποΈ #110 Assigning a task told nobody
- β³ πͺ #107 Signed out while still working
- β³ π #103 "Share with Requester" reached nobody
- β³ π #102 Search found nothing for hyphens
- β³ πͺ #101 Source code editor opened behind
- β³ βοΈ #88 Subtasks could not be ticked off
- β³ π» #84 Asset deep link selected nothing
- β³ π« #79 A new ticket arrived with no status
- β³ π§ #79 A ticket from email did not say so
- β³ π #78 Bell opened to nothing
- β³ π¬ #77 Mail only collected from Inbox
- β³ π #74 The default password could not be changed
- β³ π¦ #70 Renaming an impact level
- β³ π€ #67 App-only mailboxes could not send
- β³ π #45 Verify only ever worked for Microsoft
- β³ π #45 IMAP reported as not authenticated
- β³ βοΈ An email template stopped escaping itself
- β³ π The portal dashboard showed the wrong time
- β³ π’ The folder said 99 and the list showed 96