War Room Developer Guide - edmozley/freeitsm GitHub Wiki

War Room β€” Developer Guide

How the war room is built, and the handful of decisions that everything else hangs off. For what it does and how to use it, see War Room.


1. πŸ“ The files involved

Colour key: βš™οΈ service Β· πŸ”Œ API Β· πŸ–₯️ page Β· πŸ€– Warbot Β· 🎨 CSS/JS Β· πŸ—„οΈ schema Β· 🩺 health Β· 🌍 i18n Β· πŸ“„ docs

🎨 File What it does
βš™οΈ includes/warroom.php The whole service layer. Channels, access rules, messages, mentions, attachments, search, presence, retention, and the situation-report prompt. Every page and endpoint comes through here, so the access rule exists once
πŸ”Œ api/war-room/poll.php The 3-second heartbeat: new messages, presence in, presence out, the channel list with unread and mention counts β€” one request, four jobs
πŸ”Œ api/war-room/send.php Post a message, JSON or multipart. Both shapes land here because a message with a screenshot is still one message
πŸ”Œ api/war-room/message.php Edit (author only), delete (author or war_room.manage), and react (anyone who can post - 5.9.0)
πŸ”Œ api/war-room/channels.php Create / rename / archive a channel, open a DM, list
πŸ”Œ api/war-room/search.php Search the conversations you can see
πŸ”Œ api/war-room/attachment.php Serve one file, authorised against its channel
πŸ”Œ api/war-room/sitrep.php The AI situation report
πŸ”Œ api/war-room/alerts.php What is waiting for me β€” called by the header on every page, so it is the cheapest endpoint in the app
πŸ€– includes/warbot/tools.php The tool registry. Seven read-only tools: name, description, JSON schema, capability, handler
πŸ€– includes/warbot/warbot.php The engine: slash commands (no model), the system prompt, posting as the bot
πŸ”Œ api/war-room/warbot.php Ask Warbot to answer a message. Re-derives all trust; refuses to answer twice
βš™οΈ includes/ai_provider.php aiProviderChatTools() β€” the tool-calling loop, added additively so the eight existing AI features are untouched
πŸ–₯️ war-room/index.php The page. Channel list server-rendered for first paint, then refreshed by the poll
πŸ–₯️ war-room/settings/index.php + manifest.php Retention and the AI provider. The manifest's setting_keys is what authorises those keys
πŸ–₯️ war-room/help.php The user guide, on the shared help.css house style
πŸ–₯️ includes/waffle-menu.php renderWarRoomAlerts() β€” the notifications bell. One shared function, so it reaches all 22 module headers with one edit
🎨 assets/css/war-room.css Everything the module looks like
🎨 assets/js/war-room.js All of the client side
🎨 assets/js/war-room-emoji.json The emoji the picker offers and the server accepts - generated by scripts/gen_warroom_emoji.php from Unicode's emoji-test.txt (5.9.0)
🎨 assets/css/mobile.css LAYER 19
🎨 assets/css/theme.css --war-room-accent and friends, in both palettes
πŸ—„οΈ database/freeitsm.sql, includes/db_verify_schema.php, includes/db_verify_indexes.php, api/system/db_verify.php Seven tables, their indexes, their foreign keys, and the one-time migration off the original shape
🩺 api/system/debug-tools/D008_war_room.php + system/debug-tools/d008/index.php The health check
🌍 lang/en/war-room.php ⚠️ English only. The other 23 locales fall back to English rather than erroring
πŸ“„ CHANGELOG.local.md, README.md, this wiki logged as #1008–#1012

2. πŸ—„οΈ Four kinds of channel, one foreign key

Every conversation is a row in warroom_channels with a kind, so warroom_messages needs exactly one foreign key instead of a nullable column per kind. What differs is where each kind's identity comes from:

Kind Identity Lifecycle
all Fixed. One seeded row None
team team_id, UNIQUE, CASCADE. Name is not stored β€” read from teams at display time None
custom A stored name Create, rename, archive
dm dm_key = "<lower id>:<higher id>", UNIQUE None

πŸ”‘ The team kind keeps every property that made the original "a channel IS a team" rule attractive β€” cannot duplicate, cannot orphan, cannot be renamed into a lie β€” but by constraint rather than by being the whole design.

⚠️ dm_key UNIQUE is not tidiness. Without it, two people opening a DM with each other simultaneously get one conversation each and neither sees the other's β€” precisely the failure you would hit mid-incident.

Channels are created on demand at list time (warRoomEnsureChannels), so a team created ten minutes ago has a channel the first time anybody looks. No installer step, no cron.

The delete rules differ on purpose

Constraint Rule Why
fk_warroom_messages_channel CASCADE delete a channel, its conversation goes
fk_warroom_messages_analyst SET NULL delete an analyst and the conversation SURVIVES β€” this is the record of an incident
fk_warroom_messages_deleter SET NULL a tombstone outlives the person who wrote it
fk_warroom_channels_team CASCADE a team channel goes with its team
fk_warroom_channels_creator SET NULL a channel outlives whoever opened it

D008 checks every one of these, because a wrong rule does nothing at all until somebody is deleted β€” and then it quietly destroys an incident record that nobody looks at again until the review.


3. πŸ” The poll contract

One request every 3 seconds carries messages, presence, the channel list, unread and mention counts. Not SSE: Apache + mod_php holds one process per open connection, so thirty analysts on an EventSource would sit on thirty workers during an incident. It stops while the tab is hidden.

⚠️ m.id > since_id cannot see an EDIT or a DELETE. Both change a message the caller already holds, so its id is below the watermark and it never comes back β€” an edit would stay stale on everyone else's screen. warRoomMessages() therefore also re-sends anything changed in the last 30 seconds.

πŸ› And that is why the client must UPSERT, not append. The first version appended, so a deleted message piled up as one tombstone every three seconds β€” "Message deleted by Sarah Williams", ten times. Fixed by replacing on data-msg-id.

πŸ”‘ The general rule: the moment a poll can repeat itself, its consumer has to be idempotent. Re-delivery and blind append cannot coexist.


4. πŸ”‘ Mentions are resolved from the text, server-side

The client sends no list of ids. That is forced by the composer UX: you pick a name, and may then backspace down to just the first name. Anything the client resolved at pick time is wrong the moment the text is edited, and a hand-typed mention would never resolve at all.

So the body is stored exactly as typed β€” no @[39] tokens, which would leak into search results and into the transcript the AI reads β€” and warRoomResolveMentions() matches longest-first, full names before first names. An ambiguous first name notifies every match: two people looking beats nobody looking.

Recipients are filtered to warRoomChannelAudience(), or naming somebody would put a private channel's name and a snippet into their notifications panel.

⚠️ warRoomChannelAudience() is warRoomCanAccessChannel() turned inside out, and the two must agree. A name that resolves in one but fails the other posts a mention nobody can open.

⚠️ The client's highlighting regex must fall back the same way. It first allowed a surname greedily, so @James hello abc captured "James hello", matched nobody and highlighted nothing β€” while the server, falling back to the first word, was notifying James.

Unread is derived from warroom_reads, not a second column β€” so opening a channel clears its mentions and the two can never disagree.


5. πŸ€– Warbot: the hands and the brain

Needs the internet?
Hands β€” includes/warbot/tools.php No. Plain SQL
Brain β€” the model Yes

The war room exists for the day the internet is down, so Warbot degrades rather than dies: slash commands run the same handlers with no model. A bot that goes silent during the outage it exists for reads as broken, not absent.

The registry is the product. Each tool is declared once, and an MCP server is a second consumer of that same array rather than a rewrite.

  • ⚠️ Read-only, all of them. Anyone in the room can type instructions at Warbot. The limit is in what it can do, not what it is told not to do.
  • ⚠️ is_bot exists because analyst_id NULL already means "deleted analyst". Without the flag every Warbot message renders as Former analyst.
  • The reply is triggered by the browser after the send, so no message waits on a model round trip β€” which makes the trigger untrusted and repeatable, so api/war-room/warbot.php re-derives the channel, the asker and whether Warbot was addressed, and checks reply_to_id before answering.

A module gate, for the tools that name one (3.3.0). A tool may carry 'module' => 'projects'; warbotToolAllowed() then needs analystCanAccessModule() as well as the capability, in both warbotToolsFor() (what the model is offered) and warbotRunTool() (what a slash command or a model call may run). The older tools name no module and are unchanged - whether the room is install-wide is still the open question in warbotToolSearchKnowledge(). The Projects tools (list_projects, project_overview, project_raid, project_tasks, project_dates) are thin handlers over includes/projects/assistant.php - the same text the MCP server gives - scoped by activeTenantReadFilter() (the asker's active company, as on the portfolio), without the budget, and a ServiceError (no such project, several match) is returned as the answer rather than as That lookup failed. Commands: /projects, /project <name>, /dates [days].

πŸ› The trap in the tool loop, and it is PHP's not the API's. A tool taking no arguments arrives as "input": {}. json_decode(…, true) makes that an empty PHP array, which re-encodes as [] β€” a JSON array. Anthropic then rejects the echoed assistant turn with tool_use.input: Input should be an object. It fails intermittently, only once the model reaches a parameterless tool, so it looks like a flaky provider. aiProviderChatTools() casts every tool_use input back to an object.

⚠️ The model answers in markdown unless told not to. We render with textContent, so asterisks would show literally. Fixed in the prompt β€” not by rendering HTML from model output, which would undo the rule below.


6. πŸ”’ Security posture

  • Every access check is server-side, on every read and every write β€” never by rendering a shorter channel list. Anything unexpected fails closed.
  • All message text is inserted with textContent. Never innerHTML, not for bodies, not for filenames, not for the AI report. There is no sanitiser on purpose: not producing HTML is stronger than cleaning it.
  • Attachments: stored through includes/uploads.php (the one home for the rules), served through an authorising endpoint with the Content-Type derived from our own extension map. The directory is denied wholesale by .htaccess + web.config.
  • ⚠️ There is no content_type column, deliberately β€” storing the uploader's claim would leave something for a future endpoint to trust by mistake.
  • ⚠️ Retention is not the only way a message disappears. Deleting a team cascades channel β†’ messages β†’ attachment rows, and nothing in that chain touches the filesystem. warRoomSweepOrphanFiles() runs on the send path, hourly, regardless of the retention setting β€” otherwise "keep forever" means the rows go and the bytes stay.

⚠️ When testing access, pair every "cannot do X" with a positive control. The first negative-control pass here showed four clean 403s and proved nothing: the test analyst had no war-room module access, so every refusal was module-level. Grant the module, re-run, then the channel checks mean something.


7. 🩺 D008

System β†’ Debug Tools β†’ D008 exists because this is a break-glass feature: every other module tells you it is broken the moment you use it, but this one is opened for the first time during an incident.

It checks the tables, the delete rules above, the all-hands channel, duplicated DM threads, the attachments folder and its guards, orphaned files, retention backlog, and runs one Warbot tool live β€” a tool whose query names a column that does not exist returns no rows rather than an error, so "registered" proves nothing.

The end-to-end test writes a message, reads it back and records presence inside a transaction that is rolled back, so nothing appears in an open war room. (D007 cannot do this; a full-text search cannot see uncommitted rows.)


7a. πŸ’¬ Doing things with a message (5.9.0)

Design Β· built in pieces; piece 1 is reactions, quotes, permanent links and the shared viewer.

The menu (openMenu() in war-room.js) opens on contextmenu, on the β‹― button in .wr-msg-acts, and on a 550 ms long press (addLongPress(), phones). Selected text keeps the browser's own menu. Arrow keys move through it, Escape closes it and focus goes back to the β‹― button. Edit and Delete stay on the message as well: "a message you can act on and one you cannot should not look identical" (see Β§2).

Reactions - table warroom_reactions (message, analyst, emoji, unique on all three; both foreign keys cascade, so retention and analyst deletion need nothing new; registered personal in analystReferenceRegistry()).

warRoomReact($conn, $analystId, $messageId, $emoji, $on);   // false: unknown emoji, no such / deleted message, cannot post
  • Only emoji from the list. warRoomEmojiAllowed() checks against assets/js/war-room-emoji.json - the very file the picker draws - not a pattern. Two emoji glued together, text or markup are refused.
  • ⚠️ TRAP - the column is utf8mb4_bin. Under the table's utf8mb4_unicode_ci, MySQL says 'πŸ˜€' = 'πŸ˜‚' is true (checked on MariaDB/MySQL here, 21 Nov 2026), so the unique key would refuse a second, different emoji from the same person and grouping would merge them. tests/warroom-message-actions.php has the control.
  • The poll. A reaction changes a message the reader already holds, below their since_id. warRoomReact() stamps warroom_messages.changed_datetime, and warRoomMessages()' "changed in the last 30 seconds" clause includes it (index ix_warroom_messages_changed (channel_id, changed_datetime)), so everybody's next poll re-sends the message and the client's upsert redraws it (Β§3).
  • warRoomMessages(..., $viewerId) returns reactions: [{emoji, count, mine, names}] in the order first given.

Quotes - warroom_messages.quote_of_id, set by warRoomSend(..., $quoteOfId) only for a live message in the same channel (anything else is dropped, not refused). Deliberately no foreign key: when retention removes the original, the id stays and warRoomAttachQuotes() returns {gone: true}, so the reply says "no longer available" instead of silently losing its context. A deleted original gives {deleted: true}. A quote is only ever filled from the same channel, so it can never be used to read another one.

Permanent links - war-room/?channel=<id>&message=<id> (database ids). war-room/index.php asks warRoomChannelOfMessage(): the message's channel if the analyst can read it, else 0 - one answer for "gone" and "not yours", so a link cannot probe which message ids exist. The page loads with poll.php?...&around=<id>, which returns up to 30 messages before it and everything after (500 at most); the poll carries on from the newest. Clicking a quote of a message that is not on the page reloads around it the same way.

Pin, save, mark as unread (piece 2):

Table / column Function Rule
Pin warroom_pins (channel, message - unique, pinned_by, pinned_datetime) warRoomPin($conn, $analystId, $messageId, $on) β†’ 'ok' / 'full' / 'no' anyone who can post; WARROOM_MAX_PINS = 50 per channel (HTTP 409 pins_full); stamps changed_datetime so everyone's poll redraws it; pinned_by is history in the analyst lifecycle (kept, shown). The poll sends pins (warRoomPinCount(), deleted messages not counted) and pin_top (warRoomPinTop(): id, author, first 300 characters, lang, stored translation) for the bar's preview
Save warroom_saved (analyst, message - unique) warRoomSave(...), warRoomSavedList($conn, $analystId) anyone who can read; personal, so the client redraws locally and nothing is stamped; the list is filtered through the reader's own warRoomChannelList(..., true), which both names a DM from their side and drops a channel they have left
Unread warroom_reads.last_read_message_id warRoomMarkUnread(...) sets the marker to the previous message's id - the one place it moves backwards (warRoomMarkRead() uses GREATEST). The client then polls with read=0 for that channel (holdRead) until the analyst switches away

warRoomMessages() returns pinned: {by, at}|null and saved: bool (for the viewer); poll.php returns pins (the count) for the bar; api/war-room/lists.php serves ?list=pins&channel_id= and ?list=saved. warRoomDeleteMessage() deletes the message's pins and saves - a pin or a bookmark of a tombstone would point at nothing.

Copy is two items, Copy text and Copy with name and time, rather than a hover submenu (Ed asked for a choice; two plain items work the same by keyboard and on a phone, where nothing hovers).

Copying goes through window.copyToClipboard() (assets/js/clipboard.js), which works on plain HTTP where navigator.clipboard does not exist - and says so when the browser refuses.

Attachments open in FilesViewer.openUrl() (assets/js/files-viewer.js, with float-window.js and files-icons.js loaded by the page, float-window.css for its look). Its libraries ship in assets/js/vendor/ and load on first use, so the no-internet rule holds. openUrl() returns null for a type it cannot show; the click then follows the link as before.

Tested by tests/warroom-message-actions.php (64 checks, rolled back - piece 2 adds pins, the 50 limit, save, leaving a private channel, delete clearing both, mark as unread; piece 3 adds threads: the id trap, not in the conversation, counts, one level, also-sent, the thread view, the re-send, another channel's root, unread): reactions per viewer, the collation control, refusals, the poll re-sending a changed message (with an untouched control), quotes in/out of channel, deleted and gone originals, links. The screen was driven on the test install: link landing and flash, the menu, react, the picker (1,850 emoji, search), un-react, quote, copy, the PDF opening in the viewer.

7g. βš™οΈ Personal preferences live in Preferences (5.9.0)

The three per-person choices are drawn and saved by system/preferences/index.php, on a War room tab shown only when analystCanAccessModule(..., 'war-room'). The keys and values did not change, so nothing migrates:

user_preferences key Values (default) Read by
warroom_desktop_alerts '1' / '0' ('0') includes/waffle-menu.php β†’ window.WRA_DESKTOP - the header's mention button, on every page but the war room
warroom_translate '1' / '0' ('1') war-room/index.php β†’ WR_TRANSLATE.on; the section shows only when warRoomTranslateEnabled()
warroom_mention_style short / full / strip (short) war-room/index.php β†’ WR_MENTION_STYLE

The war room page only reads them; its left panel has a link to system/preferences/#war-room. The preferences page loads the war-room translation namespace for the labels. tests/preferences-switch-hit-area.php counts the page's switches - add one and update its two counts.

7f. 🧰 Before Database Verification (5.9.0)

Every column this release adds to warroom_messages (quote_of_id, changed_datetime, lang, thread_root_id, also_in_channel, forwarded_from_id and the fwd_* snapshots) is read only after warRoomHasCol($conn, $col) - one cached information_schema read per request. Without a column, its feature switches off: threads and forwards are not offered, quotes are dropped, the poll's "changed" re-send falls back to edits and deletes. The new tables are read inside try blocks.

⚠️ TRAP - how this came about. The channel list's unread count gained AND (wm.thread_root_id IS NULL OR wm.also_in_channel = 1) with threads. On an install that had not yet run Database Verification, that one clause failed warRoomChannelList() - which the page and every poll call - so the whole war room returned HTTP 500 (Ed, 21 Nov 2026). Any new war room column: read it through warRoomHasCol(), and add it to warRoomSchemaBehind(), which shows administrators "Some newer war room features are switched off until Database Verification has been run" with a link, instead of failing.

Proved by putting the test install's war room schema back to 5.8.0 (dropping every new column and table): the page, the poll and sending - with a thread and a quote asked for - all returned 200, the notice showed; Database Verification then restored everything and the notice went away.

7e. πŸ“ Files cards (5.9.0)

warroom_file_links (message - FK cascade, file_item_id - no FK to files_items, a purged file just shows as gone, and name - the name when shared).

  • Sharing - send.php accepts files_items (JSON array or files_items[]); warRoomAddFileLinks() keeps at most WARROOM_MAX_FILE_LINKS (5) and only items the sender can open (FilesAttach::viewFor()->access), each with its name as it was.
  • Reading - warRoomAttachFileLinks() asks FilesAttach::viewFor($conn, $viewer, $item) - the Files module's own answer: module access, the folder's level, deleted or binned (a binned folder counts) - once per item per request. With access: the live name, size and type; without: the shared name and nothing else; gone: gone: true. Nothing about a file is decided in the war room.
  • Opening - FilesViewer.openItem($item) (the same as a Files link in a ticket), which goes through api/files/view.php, so View only and watermarks apply; on refusal the page falls back to files/?item=.
  • Forwarding copies the link rows (the same item); deleting a message deletes its links.
  • The + button - when WR_FILES (the analyst can use Files) and FilesPicker is loaded, a click on #wrAttachLabel shows Computer / Files instead of the file chooser; Computer clicks the hidden input as before; Files opens FilesPicker.open({mode: 'link'}); picks wait as dashed chips (pendingLinks) until sent. The card's icon is FilesIcons.file(name, 32) - drawn from the file type (a fixed table), never from the name's text.

Tested by tests/warroom-message-actions.php (87 checks): share only what you can see, per-viewer name/size/access, a rename live for those with access, the shared name for those without, forwarding the same link, a binned file gone, delete removing cards - on a temporary Files folder, grant and item inside the rolled-back transaction. The screen was driven with a real PDF uploaded through Files' own API: the card, the + menu, the picker, and the card opening the PDF in the viewer.

7d. β†ͺ️ Forward and πŸ‘€ Seen by (5.9.0)

Forward - warRoomForward($conn, $analystId, $messageId, $toChannel, $comment), message.php action forward with to_channel or to_analyst (β†’ warRoomOpenDm()).

  • Must be able to READ the original's channel and POST in the destination; returns 0 otherwise.
  • The comment goes first through warRoomSend() (so its own @names do notify). The forward itself is inserted directly, not through warRoomSend(), so the forwarded text's @names are not resolved again.
  • warroom_messages.forwarded_from_id (no FK) + fwd_author, fwd_channel (named from the forwarder's side, via their channel list), fwd_created - snapshots, because the readers may not be able to look the original up. The row's forward is {from, author, channel, created}; the page draws it as a link to ?message=<from>, which index.php answers with "not available" for anyone who cannot read it.
  • Files are copied to new random names in fileStoreDir('war-room'); a missing source file is skipped.
  • ⚠️ lastInsertId() is read straight after the insert (Β§8).

Seen by - warroom_read_marks (analyst, channel, up_to_message_id, read_datetime; FKs cascade; lifecycle personal).

  • warRoomMarkRead() adds a row whenever an analyst's marker moves forward - only while warRoomSeenByEnabled(): setting warroom_seen_by (owned by the retention tab), absent = on. Off means nothing is recorded.
  • warRoomSeenBy($conn, $analystId, $messageId) = MIN(read_datetime) per analyst over marks with up_to_message_id >= id, author left out; not yet from warRoomChannelAudience() ([id => name]) when it has 30 or fewer people. Mark as unread does not change the first read time (a later re-read only adds a later mark). A thread-only reply returns null.
  • lists.php?list=seen&id=; warRoomPrune() also drops marks older than the retention period.

Tested by tests/warroom-message-actions.php (79 checks): forward text and origin, the comment, a real file copied byte for byte under a new name, no repeat mentions, both permission refusals, forwarding to a person; Seen by's list and times, the author left out, first-read time kept across mark-unread, thread-only replies, access, and switched off = nothing recorded.

7c. 🧡 Threads (5.9.0)

warroom_messages.thread_root_id (the first message - always top-level) and also_in_channel; index (thread_root_id, id). No foreign key, as with quotes: retention may remove the first message and its replies stay.

  • One function for both views. warRoomMessages(..., $threadRootId): 0 = the conversation (thread_root_id IS NULL OR also_in_channel = 1, in all three query shapes - first load, since, around); > 0 = the first message and every reply. So reactions, quotes, pins, saved, translations and the poll's "changed recently" re-send behave identically in a thread.
  • thread: {count, last} on a first message (warRoomAttachThreadCounts(), one grouped query); thread_root and in_channel on a reply.
  • Sending - warRoomSend(..., $quoteOfId, $threadRootId, $alsoInChannel). A reply to a reply joins its root (one level); a root that is not a live message of the same channel posts an ordinary message instead. The root's changed_datetime is stamped so everyone's poll re-sends it with the new count. ⚠️ TRAP (Β§8's): that UPDATE runs after lastInsertId() is read - before it, the new message's id came back as 0. tests/warroom-message-actions.php checks a reply gets a real id.
  • The poll carries an open thread: poll.php?...&thread_root=&thread_since= returns thread (the thread's new or changed messages) in the same request - no second timer. With around, focus_root says the linked message is a thread reply, and the page opens the thread and highlights it. The war room bell's mentions now link ?channel=&message=, so a mention in a thread lands on the reply.
  • Unread (warRoomChannelList()) ignores thread-only replies. Known gap: a mention in a thread is counted read once the reader's channel marker passes its id, even if the thread was never opened.
  • Client - renderMessage(m, ctx) ('main' / 'thread'); openThread() draws the side panel with the list (threadMsgs) and its own reply box; appendThread() upserts like appendMessages() (the panel body is the scroller); refreshRows() redraws a message wherever it is shown (reactions, saving, translation); isShown() covers both for translation. In the thread, the menu leaves out Reply in thread and Quote (Quote fills the conversation's box). Warbot asked in a thread answers in the conversation.

7b. 🌍 Translation (5.9.0)

Ed's idea (21 Nov 2026): four people typing English, French, Spanish and German, each reading the whole room in their own language. Replaces the design's on-request Translate (piece 5).

Where What
Switch system_settings.warroom_translate ('1' = on; owned by the AI tab in war-room/settings/manifest.php) warRoomTranslateEnabled() = switched on and aiConfigured(aiSettingsLoad($conn, 'warroom_ai')) - the same provider as the situation report
Per person user_preferences.warroom_translate (default on) Show messages in my language in Preferences β†’ War room (system/preferences/, 5.9.0 - it was in the left panel)
Language of a message warroom_messages.lang (VARCHAR 16, NULL = not detected yet) detected once, by the same AI call that first translates it
Translations warroom_translations (message, lang, body; unique message+lang; FK cascade) one per message per language, never per person
Endpoint api/war-room/translate.php POST {channel_id, ids} the target is the caller's own I18n::getLocale(), never a value they send

warRoomTranslate($conn, $analystId, $channelId, $ids, $target) - checks the channel, takes at most 60 ids, answers from the store (lang already the target β†’ text: null; a stored translation β†’ it), and only the rest go to the provider, 20 to a call (warRoomTranslateBatch()). A GET_LOCK('wr_tr_<channel>_<lang>') around the call, with a re-read after it, means two readers of the same language asking at once pay once. Languages are compared by primary subtag (warRoomLangKey(): pt-BR = pt).

The prompt (warRoomTranslatePrompt()) asks for a JSON array [{id, lang, same, text}] and to keep @mentions, names, host names, IPs, URLs, emails, paths, ticket/change references, error codes, code, numbers, emoji and line breaks exactly as written. The reply is parsed from the first [ to the last ]; only ids that were asked about are accepted; an answer that is not JSON stores nothing (the reader keeps the original); a provider failure throws RuntimeException β†’ provider_unreachable, and the page simply asks again a minute later.

Edits and deletes call warRoomForgetTranslations() - drop the translations, reset lang - so nobody reads a translation of words that are no longer there.

The poll passes the viewer's language to warRoomMessages(..., $viewerLang), which attaches tr (a stored translation) and lang to every message - a conversation already translated is in your language from the first paint, at no cost. The page then asks translate.php only for messages with neither (requestTranslations(), after a 300 ms pause, in batches of 20), keeps each answer tied to the exact text it translates (trCache[id].body), fades it in once (.wr-tr-fade), and draws Translated from {lang} Β· Show original (translationNote(); the language name from the browser's own Intl.DisplayNames, no internet).

⚠️ TRAP - the preference saves are chained. Two quick clicks on the box sent side by side landed in the wrong order and left the preference opposite to the box (caught driving the screen). trSaving sends each after the last.

Models. Any provider set on the AI tab works. A small fast model is the right one: Claude Haiku 5.5 is about 1/40 the price of Opus 5.5 and translates two-line chat as well. ⚠️ FreeITSM used to send temperature: 0 to Anthropic, which the newest models refuse with a 400 - fixed in the same release (aiAnthropicAcceptsTemperature(), changelog #3078), or Haiku 5.5 would have failed outright.

Tested by tests/warroom-translate/run.php (23 checks, rolled back) against tests/warroom-translate/mock.php - a stand-in model started with php -S (and bypass_shell - TRAP: without it Windows leaves the server orphaned and the run hangs), which "detects" by a word and logs every call, so the test proves one call for three messages, none on a second reader, a known-language message never sent again, edit/delete forgetting, channel access, a prose answer and a provider that is down. The screen was driven against the same stand-in on the test install: translations fading in with their note, Show original both ways, the left-panel box off and on, and a second visit showing the stored translations from the first paint with no new call.

8. Gotchas worth knowing before you touch this

  • ⚠️ lastInsertId() returns 0 if anything else touches the connection first. warRoomSend() prunes after inserting; reading the id after the prune gave 0 while the message saved fine. Read the id first.
  • ⚠️ Column names: read them out of information_schema, do not remember them. Four were wrong on the first pass of the Warbot tools β€” status_services/status_incidents (not service_status_*), changes.title, assets.hostname, and CMDB from_object_id/to_object_id (not source_/target_). That last is the dangerous kind: a wrong column returns no rows, not an error, so Warbot reported "no recorded relationships" for every object.
  • ⚠️ Phantom tokens. The module used var(--war-room-accent, #ea580c) everywhere before those tokens existed in theme.css. The fallback masks it β€” and means dark mode never adapts. Grep every var(--x) against theme.css.
  • ⚠️ Bump the cache-busters. mobile.css, theme.css, war-room.css, war-room.js β€” and mobile.css/theme.css are linked from every page, so bump them everywhere.

Reference

  • User guide: War Room Β· Help page: war-room/help.php
  • Related: Mobile‑Friendly Β· Full‑Text Search (and why search here does not use it) Β· Theming and Dark Mode
  • Changelog: #1008 (first cut) Β· #1009 (channels, DMs, search, attachments, situation report) Β· #1010 (mentions, notifications, edit/delete) Β· #1011 (mention typing) Β· #1012 (Warbot)
⚠️ **GitHub.com Fallback** ⚠️