The frontend data service keeps a page in sync with its post without a reload. A small script polls two REST endpoints, notices when the post (or its linked conversation) has changed, and hands your JavaScript the fresh data as a browser event.
This document is the complete reference: what the service emits, what the payload contains, how change detection works, how to extend it from PHP, and how to debug it.
At a glance
The service:
- Only runs for logged-in users, and only on singular pages. The script is
enqueued from
template_redirectbehindis_user_logged_in()andis_singular(). Anonymous visitors and archive pages get nothing at all — no script, nowindow.cacbot_data. - Polls
/statusevery 5 seconds and fetches/payloadonly when the post has actually changed. - Detects changes to the post title, body, and author; to comments; and to watched post meta. (A body change signals, but the body itself is never shipped — see The post body is not in the payload.)
- Emits
CustomEvents onwindowso your code can re-render.
You do not need to call the REST routes yourself for a normal integration.
Subscribe to the events and read the payload from event.detail.response.
The two-step poll
- The script calls
/statuswith the post ID and the time it last saw a change. /statusanswers withlast_changed_atandis_stale.- If nothing has changed, the script emits
idleand makes no further request until the next poll. - If the post is stale, the script fetches
/payload, stores the newlast_changed_at, and emitspulse.
/status is deliberately cheap: it reads one meta value and compares it against
the timestamp the client reports. The expensive query (comments, meta) only runs
when there is something new to send.
REST routes (both GET, both require authentication):
| Route | Returns |
|---|---|
cacbot/v1/cacbot-cpt-frontend-data/status |
post_id, last_changed_at, is_stale |
cacbot/v1/cacbot-cpt-frontend-data/payload |
The full payload (see below) |
Authorization requires a logged-in user with read_post on the requested post
and, when one resolves, on the linked conversation post.
Quick start
(function () {
function onPulse(e) {
const payload = e.detail?.response;
if (!payload) return;
// Example: update UI when new poll data arrives
const count = document.querySelector('[data-cacbot-comment-count]');
if (count && typeof payload.comment_count !== 'undefined') {
count.textContent = String(payload.comment_count);
}
}
function onError(e) {
console.error('[CACBot] Polling error', e.detail.phase, e.detail.error);
}
window.addEventListener('cacbot:data-service:pulse', onPulse);
window.addEventListener('cacbot:data-service:error', onError);
})();
Events
Cacbot dispatches these CustomEvents on window:
| Event | When | detail fields |
|---|---|---|
cacbot:data-service:ready |
Once, immediately before the first poll | timestamp, post_id, poll_interval_ms, debug, debug_level, using_new_endpoints |
cacbot:data-service:poll-start |
Start of every poll cycle | timestamp, post_id, request_url, cycle |
cacbot:data-service:pulse |
Fresh payload delivered — use this for UI updates | timestamp, post_id, response (the payload), cycle |
cacbot:data-service:idle |
/status reported nothing new |
timestamp, post_id, response (the status response), cycle |
cacbot:data-service:error |
A request failed | timestamp, post_id, phase, error, cycle |
Notes:
detail.responseonpulseis the payload; onidleit is the much smaller/statusresponse. Don’t render from anidle.detail.phaseonerroris'status'or'payload', so you can tell which of the two requests failed without reading the message.detail.cycleis the poll-cycle correlation id (see Correlating a poll cycle).readyhas no cycle, because it fires outside one.
Registering listeners in time
cacbot.js is enqueued in the footer and dispatches ready synchronously
while it executes. A listener registered after that point will never see
ready, so:
- Register listeners in the
<head>, or early in the body, if you care aboutready. pulse,idle, anderrorare dispatched asynchronously from the poll loop, so ordering rarely matters for them — but registering early costs nothing.- Prefer treating
pulseas your only required event. The first poll fires immediately afterreadyand, for a post whose timestamp has never been set, is always stale — so apulsearrives on essentially every page load.
Recommended usage
- Put most of your integration logic in the
pulsehandler. - Use
readyonly for setup/logging. - Use
idlefor optional diagnostics (usually no UI changes needed). - Log or report
errorso you can spot broken auth/session states quickly.
Typical integration pattern
(function () {
const state = {
initialized: false,
lastChangedAt: 0,
};
function onReady(e) {
state.initialized = true;
console.debug('[CACBot] ready', e.detail);
}
function onPulse(e) {
const payload = e.detail?.response;
if (!payload) return;
state.lastChangedAt = Number(payload.last_changed_at || 0);
renderCacbotData(payload);
}
function onError(e) {
console.error('[CACBot] data-service error', e.detail.phase, e.detail.error);
}
function renderCacbotData(payload) {
// Keep this function app-specific. Fields often used by UI layers:
// payload.comment_count, payload.comments, payload.linked_to,
// payload.last_changed_at
}
window.addEventListener('cacbot:data-service:ready', onReady);
window.addEventListener('cacbot:data-service:pulse', onPulse);
window.addEventListener('cacbot:data-service:error', onError);
})();
The payload
Canonical data types
These three fields are what the service exists to keep fresh. Each one is watched for changes and refreshed when it changes:
title— the post title.comments— the post’s comment thread, oldest first (sanitized, see below). Which comments are visible follows the page: see Comment visibility and order.comment_count— number of comments in that thread.
The post body is not in the payload
There is deliberately no content field. The service does not read, render,
or ship the post body, and a client cannot use a pulse to refresh it.
A body edit still signals: post_content remains in the dirty-flag watch list,
so editing a post bumps last_changed_at and your pulse handler still fires.
The pulse simply carries no body for you to inject.
To pick up a new post body, reload the page. That renders it through the real
the_content pipeline, with wp_head/wp_footer running, which is the only way
to get what the page would actually have shown.
Why the field was removed, in short:
- Shortcodes and blocks that enqueue their own CSS/JS arrive inert. They
enqueue into a REST request that never runs
wp_headorwp_footer. Sliders, lightboxes, tab sets, and script-based embeds land on the page dead. Nothing server-side can fix this. - Embeds degrade. A REST request has no loop context, so the oEmbed post-meta
cache is bypassed; a failed lookup renders a bare
<a>where the page renders an<iframe>. - Replacing the body destroys client state. A playing video restarts, a form loses its input, a carousel resets — on every pulse, including the bootstrap pulse of every page load.
- Nothing in Cacbot writes
post_contentat runtime. The live data in this product is comments. The body only changes when a human edits the post in wp-admin, at which point a reload is both expected and cheap.
If you need to know that the body changed, listen for the pulse and offer the reader a refresh; if you need the new body live, fetch the permalink same-origin and swap your container — that goes through a real page render.
Default payload fields and how each signals dirty
Every /payload response carries exactly these default fields, plus any
payload-safe or third-party meta values that happen to be set.
“Signals dirty” means: changing it bumps the post’s monotonic last_changed_at
timestamp, /status reports is_stale: true on the next poll, the client
fetches /payload, and your pulse handler fires.
| Payload field | Type | Read from | Signals dirty when changed? | Watched via |
|---|---|---|---|---|
title |
string | viewed post | Yes | post_updated hook |
(no content field) |
— | — | Yes — post_content still signals dirty, it just is not carried |
post_updated hook |
comments |
array (sanitized) | linked conversation post, else viewed post | Yes | comment create/edit/status-change/delete hooks |
comment_count |
integer | same as comments |
Yes | same as comments |
excerpt |
string (wpautop + do_shortcode) |
viewed post | No — backward compatibility only | not watched |
post_id |
integer | request | n/a | — |
user_id |
integer | current session | n/a | — |
linked_to |
integer, or false when there is no linked post |
resolved per user | n/a | — |
conversation_state |
string: not_anchor, linked, no_conversation, invalid_pointer |
resolved per user | n/a | — |
action_enabled_create_new_linked_post |
boolean (always) | viewed post; a non-empty linked-post value takes precedence | Yes | watched meta hooks |
action_enabled_create_image |
boolean (always) | same | Yes | watched meta hooks |
action_enabled_build_plugin |
boolean (always) | same | Yes | watched meta hooks |
last_changed_at |
integer (Unix epoch ms) | max of viewed + linked post | — it is the dirty signal | — |
payload-safe meta (e.g. comment_form_placeholder_text) |
string | viewed post; linked post takes precedence | Yes | watched meta hooks |
| third-party meta keys (via filter) | mixed | viewed post and linked post | Yes | watched meta hooks (checked against the filter at event time) |
Two extra notes:
- A change to the post author also signals dirty, even though the author is not a payload field.
- The
action_enabled_*flags are always booleans in the payload. Raw stored values such as the string"0"are normalized throughrest_sanitize_boolean(), soif (payload.action_enabled_create_image)is safe in JavaScript.
Which post does each field come from?
title and excerpt always come from the post being viewed. (The post body
comes from nowhere — it is not in the payload; see
The post body is not in the payload.)
comments and comment_count come from the linked conversation post when
the viewed post is an anchor post with a linked conversation for the current
user; otherwise they come from the viewed post itself.
An anchor post with no resolvable conversation carries no comments at all —
comments: []. The anchor’s own thread (whatever predates it becoming an anchor)
is unreachable in the anchor model, and serving it would show a conversation
nobody can reply to.
conversation_state says why linked_to reads the way it does, which false
on its own cannot:
conversation_state |
Meaning |
|---|---|
not_anchor |
An ordinary post. Comments are the post’s own. |
linked |
An anchor post with an active conversation; linked_to is its id. |
no_conversation |
An anchor post this user has not started a conversation on yet. |
invalid_pointer |
An anchor post whose stored pointer no longer names a usable conversation (deleted, trashed, wrong type, or belonging to another anchor). Treated exactly like no_conversation when serving data. |
The service never creates a conversation: /payload is a GET, and a GET must
not have that side effect. A client that wants to offer “start a conversation”
should branch on conversation_state.
last_changed_at is the maximum of the two posts’ timestamps, so a change on
either side wakes the client.
Meta values are read from the viewed post first, then — when a linked post resolves — from the linked post, whose non-empty values overwrite. Only meta keys that are both transferable and payload-safe are read from the linked post; third-party keys registered via filter are read from both.
Comment visibility and order
Comments are always ordered oldest first (comment_date_gmt ASC), the order
a conversation reads in and the order the page rendered them in.
Which comments are included matches what the server put in the HTML, so the first pulse after a page load never reorders the thread or removes a comment the user is already looking at:
- On a linked conversation — a private post readable only by its author —
the whole thread, including replies held for moderation. This is what
comments_arrayrenders. - On an ordinary post, approved comments plus the requesting user’s own comments awaiting moderation. This is core’s rule for the comments template.
A password-protected post that the reader has not unlocked returns
comments: [], comment_count: 0, and excerpt: '', as core REST does. Once
the reader enters the password, the wp-postpass_ cookie travels with the REST
request and the thread is served. Only the viewed post is checked: a linked post
is only ever reached through its anchor, so its own password is ignored.
The rendered thread and the polled thread go through the same queries.
Comment sanitization
Each entry in comments contains only these fields: comment_ID,
comment_post_ID, comment_parent, comment_author, comment_date,
comment_date_gmt, comment_content, comment_type, and user_id.
Privileged fields — comment_author_email, comment_author_IP,
comment_agent, comment_karma, comment_approved — are never included.
WordPress core restricts these to users who can moderate comments, and this
payload is readable by any logged-in user who can read the post.
What is deliberately excluded
Sensitive plugin configuration (system_instructions, default_response,
model, the internal user-ID wiring, and the rest of the non-payload-safe meta)
never reaches the payload. The allowlist lives in
FrontendDataService::get_payload_safe_meta_keys(), and the third-party filter
cannot widen it (see Adding custom post meta keys).
Untrusted HTML
comment_content and excerpt are HTML. Treat them as untrusted when inserting
into the DOM — prefer textContent, or sanitize before assigning innerHTML.
(This used to name content first. The post body is no longer served at all,
which also retires the contradiction that came with it: the documented-safe
handling — sanitize before innerHTML — was exactly what stripped the
<iframe> out of an embed.)
Change detection
DirtyFlags writes a monotonic last_changed_at timestamp (Unix epoch
milliseconds) into post meta whenever monitored content mutates. “Monotonic”
means each touch stores max(existing + 1, now), so two changes inside the same
millisecond still produce two distinct values — without that, a client that had
already seen the timestamp would never learn about the second change.
A pulse is triggered when any of the following change:
- Post title, body (
post_content), or author — via thepost_updatedhook. Nothing else about the post is compared. A body change signals dirty even though the body is not a payload field: the pulse tells a client the post was edited, and reloading the page is how the reader sees it. - Comments — created (
wp_insert_comment), edited (edit_comment), status-changed (transition_comment_status, only on an actual transition), or deleted (deleted_comment). The timestamp is written to the comment’s own post, which is why comment activity on a linked conversation post wakes the anchor page. Trashing a conversation also retires it as the user’s active one and touches the anchor, so a page still showing it learns that it has gone. - Watched plugin meta keys — added, updated, or deleted. All three hooks are
registered, because
update_post_metadoes not fire for a key’s first write. - Third-party meta keys registered via the
cacbot_third_party_meta_keysfilter, resolved at event time. - The active conversation link itself — linking, switching, or unlinking a
conversation on an anchor post touches both the anchor and the conversation
(
ConversationLinkingService). Nothing else would: the pointer lives in user meta, which is not watched, and re-linking a conversation the anchor already knows writes no changed value for the meta hooks to see. Touching the anchor is the part that matters — the anchor’s timestamp is in themax()for every conversation on it, so switching to an older, quieter conversation still reads as stale against the busy one’s high-water mark.
Changes to excerpt and to other post fields do not trigger a refresh. The current excerpt value still rides along whenever some other change triggers a pulse.
Which meta keys are watched
The plugin constructs DirtyFlags with Properties::get_post_meta_keys() —
that is, every Cacbot meta key, not just the payload-safe ones. So editing
system_instructions or model does bump last_changed_at and does produce a
pulse, even though those values never appear in the payload. This is
intentional: a configuration change can alter what the page should render.
Meta keys are matched after stripping the plugin prefix _cacbot_, so
_cacbot_model matches the watched key model.
Polling behavior
What your code can rely on:
- Logged-in users, singular pages only. No script for anyone else.
- Two-step polling.
/statusfirst;/payloadonly whenis_staleis true. - Poll interval: 5 seconds.
poll_interval_msis not part of the localized config, so the JS default applies unless you inject one through thecacbot_localized_datafilter. - Freshness state lives in page memory, one token per document. Two tabs on
the same post never acknowledge each other’s payloads, and a fresh page load
starts at zero, so its first status check reports stale and it fetches one
payload. On start the client deletes the
localStoragekeys that older versions used (cacbot_last_seen_post_<post_id>_user_<user_id>and its_linked_tovariant). You never need to touch any of it. - A conversation switch resets that state. The client also remembers the
linked_toof the last payload, in page memory too. When a payload arrives from a different conversation, the stored timestamp belongs to the one the user just left, so it is dropped rather than compared against.pulseevents carrylinked_to_changedon the cycle where that happens. - Exponential backoff on repeated errors. The interval becomes
base × 2^consecutive_errors, capped at 5 minutes, and resets to the base interval on the first success. - Polling pauses when the tab is hidden and runs an immediate catch-up poll
when the tab becomes visible again. A
visibilitychangecatch-up poll can overlap a scheduled one, which is why log lines carry a cycle id. - Never more than one cycle in flight. A second poll that arrives while one is running is skipped rather than queued.
- Expired nonces recover automatically. The REST nonce minted at page load is
valid for 12–24 hours. On a 403 the client fetches a fresh nonce through core’s
rest-nonceadmin-ajax action and retries the request once before reporting an error. - Requests time out. Each request is aborted after 15 seconds, so a hung request can never permanently stall the poll loop.
- A never-touched post bootstraps itself. When
last_changed_atis 0,/statusreports stale so the client fetches once, and/payloadwrites the initial timestamp — otherwise every client would re-fetch the full payload on every cycle forever.
Extending the service from PHP
Third-party code has three integration surfaces:
- Consume the default fields in JavaScript — subscribe to
cacbot:data-service:pulseand read the fields from the table above (e.detail.response.title,.comments,.comment_count, …). No PHP required. - Ship your own post meta through the payload — register keys with the
cacbot_third_party_meta_keysfilter. Your values ride along under the unprefixed key name, and changes to those keys signal dirty on their own, so your frontend gets a fresh pulse without any other field changing. - Inject computed fields — use
cacbot_api_response_data_filtersto add derived values to every payload response, orcacbot_localized_datato add values towindow.cacbot_dataat page load.
Adding custom post meta keys to the payload
<?php
/**
* Add custom meta keys to CACBot frontend payload output.
*/
add_filter( 'cacbot_third_party_meta_keys', function( $meta_keys ) {
return [
'myplugin_campaign_id',
'myplugin_segment',
'myplugin_priority',
];
} );
Important notes:
- Return an array of meta key strings from your callback.
- Cacbot reads each key with the plugin prefix:
get_post_meta( $post_id, '_cacbot_' . $meta_key, true ). Store your values under_cacbot_myplugin_campaign_id, notmyplugin_campaign_id. - Empty-string values are skipped; non-empty values are added to the payload under the unprefixed key name.
- Keys are read from the current post and, when different, from the linked/anchor post.
- Changes to registered keys signal dirty: adding, updating, or deleting a
registered key bumps
last_changed_at, so your data triggers its ownpulse. - Sensitive internal keys are blocked. Registering an internal plugin key
(
system_instructions,default_response,model, the user-ID wiring keys, …) through this filter has no effect — the filter output is diffed against the non-payload-safe plugin keys before use, so they can never be re-exposed.
Reading them back in JavaScript:
window.addEventListener('cacbot:data-service:pulse', (e) => {
const payload = e.detail?.response;
if (!payload) return;
const campaignId = payload.myplugin_campaign_id;
const segment = payload.myplugin_segment;
const priority = payload.myplugin_priority;
console.debug('Custom CACBot meta', { campaignId, segment, priority });
});
cacbot_localized_data
Adds values to window.cacbot_data before it is encoded and printed with the
frontend data script.
add_filter('cacbot_localized_data', function(array $data, int $post_id, int $user_id) {
$data['poll_interval_ms'] = 10000;
$data['my_plugin_context'] = [
'post_id' => $post_id,
'user_id' => $user_id,
];
return $data;
}, 10, 3);
The config object is printed as an inline before script with
wp_json_encode(), not with wp_localize_script(). Localization casts every
top-level scalar to a string (false would become '', true '1', and
post_id a numeric string) while leaving nested values alone. Encoding the whole
object once keeps debug and debug_allowed real booleans and post_id /
user_id real integers all the way to the page — and anything you add through
this filter keeps its type too.
cacbot_api_response_data_filters
Modifies the full payload before /payload returns it.
add_filter('cacbot_api_response_data_filters', function(array $data, int $post_id, int $user_id) {
$data['my_extra_field'] = 'example';
return $data;
}, 10, 3);
Note that this filter runs after the action_enabled_* flags are normalized to
booleans, so a callback that overwrites one is responsible for its own type.
Debugging
The service ships with a structured, opt-in debug logger. When it is enabled the
client logs every meaningful decision — staleness checks, request timing, nonce
refreshes, backoff, timer and visibility transitions, phase-tagged errors — to
the browser console, exposes an interactive handle at window.cacbotDebug, and
can draw a live on-page HUD.
Debug output is privileged. It is only ever enabled for a user who can
edit_post the current post (filterable). Ordinary readers and anonymous
visitors never see it, and with debug off the client behaves exactly as it does
in production, with one deliberate exception: error-level console messages are
never suppressed, so a dead poll loop is still visible in production. Nothing
else prints, nothing is buffered, and window.cacbotDebug does not exist.
Enabling it
Every path below still requires the capability gate: a reader who sets the query parameter or the localStorage key gets nothing.
Browser-scoped (one developer, no effect on anyone else), in precedence order:
| How | Scope | Use it when |
|---|---|---|
?cacbot_debug=1 on the post URL |
this page load | Debugging a specific page right now. ?cacbot_debug=verbose also picks the level; ?cacbot_debug=0 turns it off again and clears the sticky opt-ins. |
localStorage.cacbot_debug = 'verbose' |
this browser, until cleared | Following a bug across several navigations. cacbotDebug.setLevel() writes this for you. |
Site-wide (every capable user), consulted only when neither browser opt-in applies:
| How | Use it when |
|---|---|
| Settings → CACBot Frontend Data → Debug | Leaving debug on for a staging site. |
define('CACBOT_DEBUG', true); in wp-config.php |
Same, from config rather than the database. |
add_filter('cacbot_debug_enabled', '__return_true'); |
Conditional logic (specific users, environments). Has the final word. |
WP_DEBUG deliberately does not enable this — turning on WordPress debugging
must not start shipping polling internals to every editor’s console. Enabling is
always an explicit choice.
When debug is active the console prints the resolved level, where it came from,
and how to reach window.cacbotDebug.
How the opt-in reaches the server
The two browser opt-ins are browser state. A REST call to /status or
/payload is a separate HTTP request: it does not carry the page’s query string,
and it cannot read localStorage. So whenever debug resolves on, the client
also writes a cacbot_debug cookie naming the level, and deletes it whenever
debug resolves off (including via ?cacbot_debug=0). That cookie is what lets
the server attach its _debug block to a poll
response without the whole site being switched on.
The cookie is a session cookie, scoped path=/ with SameSite=Lax (and Secure
on HTTPS), and holds no secret — just a level name. It is an opt-in signal
only: the server still runs the cacbot_user_can_debug gate before honoring it,
so forging one buys a reader nothing. On the server, ?cacbot_debug=0 is checked
after the cookie and therefore remains the reliable escape hatch for a single
page load.
You rarely set this cookie by hand. It is listed here because you will see it in devtools and because clearing it by hand is a legitimate way to reset a stuck opt-in.
Using window.cacbotDebug
From the browser console:
| Call | What it does |
|---|---|
cacbotDebug.getState() |
Live snapshot: resolved level and its source, base/current interval, cycle_count, consecutive_errors, poll_in_flight, timer_scheduled, tab_hidden, last_seen_at, last_poll_at, last_result, the storage key, the endpoint URLs, and nonce_present (the nonce value itself is never exposed). Also available as state(). |
cacbotDebug.getConfig() |
The localized window.cacbot_data config with the nonce removed and replaced by nonce_present. |
cacbotDebug.getLog() |
The in-memory ring buffer of log entries (default 200), so intermittent failures survive console clears and scrollback. getLog('warn') filters to warnings and errors. dump() is an alias of the unfiltered call. |
cacbotDebug.getEvents() |
The recently emitted CustomEvents with their detail payloads (same ring size). |
cacbotDebug.table() |
Print state and the last 25 log entries as console tables. |
cacbotDebug.export() |
A JSON string of config + state + log + events, ready to paste into a bug report. |
cacbotDebug.pollNow() |
Force one poll cycle immediately (refused if one is already in flight). |
cacbotDebug.setLevel('verbose') |
Raise/lower console verbosity at runtime, remember it in localStorage, and keep the server-facing cookie in step. |
cacbotDebug.getLevel() |
The level currently in effect. |
cacbotDebug.hud() |
Toggle the on-page HUD (below). |
cacbotDebug.clear() |
Empty both ring buffers. |
Log levels
Ordered silent < error < warn < info < debug < verbose. A message prints when
its level is at or below the active one. trace is accepted everywhere as an
alias of verbose; 1/true/on/yes resolve to debug and
0/false/off/no to silent.
| Level | What you get |
|---|---|
silent |
Nothing beyond the always-on error output (production default). |
error |
Failed requests, timeouts, nonce-refresh failures. |
warn |
Recoverable oddities: a 403 triggering a nonce refresh, backoff, missing config. |
info |
Lifecycle: boot, nonce recovered, backoff reset, pollNow(). |
debug |
Per-cycle decisions: staleness verdict and the branch taken, payload summary, request durations, localStorage writes, visibility transitions, the server’s _debug block. |
verbose |
Everything above plus request URLs, whether a nonce was attached, response timing, raw payloads, and every dispatched event. |
The default level is debug; tune it with the cacbot_debug_level filter or
setLevel(). Note that entries are recorded into the ring buffer at every level
regardless of the print threshold, so lowering verbosity does not lose history —
but nothing is recorded at all while debug is off.
Correlating a poll cycle
Every poll cycle gets an incrementing id. All console lines and all recorded
events from that cycle carry it, printed as #7 right after the [CACBot DS]
prefix and available as entry.cycle / event.detail.cycle:
[CACBot DS] #7 09:14:02.118 Poll cycle start: fetching status. {…}
[CACBot DS] #7 09:14:02.145 GET https://…/status?post_id=42&client_last_seen_at=0 {…}
[CACBot DS] #7 09:14:02.201 Response received. { http_status: 200, duration_ms: 56.4 }
[CACBot DS] #7 09:14:02.203 Staleness decision. { is_stale: true, branch: "fetch payload", … }
Cycles can interleave — a tab-visibility catch-up poll can overlap a scheduled one — so the id, rather than console grouping, is what tells you which lines belong together.
// Every log line from the cycle that failed:
const failed = cacbotDebug.getLog('error')[0];
cacbotDebug.getLog().filter(e => e.cycle === failed.cycle);
The on-page HUD
cacbotDebug.hud() toggles a small fixed overlay in the bottom-right corner
showing the live level, cycle count, current interval, consecutive errors,
in-flight and timer state, tab visibility, and last_seen_at, plus a scrolling
tail of the last 12 log lines and buttons to force a poll or clear the buffer.
It is pure DOM with no dependencies, writes every value with textContent (so
logged content can never inject markup), removes itself completely when toggled
off, and remembers whether it was open across reloads. Useful for demonstrating
polling behavior without opening devtools.
The server’s _debug block
When debug is active, /status and /payload responses carry an extra _debug
key with the server’s own reasoning, which the client logs at debug level next
to its own decision for the same cycle.
Both endpoints include:
endpoint—statusorpayload.user_id,post_id,linked_post_id,is_anchor_linked— how the linked conversation post resolved for this user.duration_msandserver_time_ms— server-side timing.last_changed_at— thepostandlinkedtimestamps, theeffectivevalue, andsource: which of the two posts the change came from.debug_source— which opt-in switched debug on.
/status adds client_last_seen_at, is_stale, and stale_reason in plain
language. /payload adds comment_source_post_id, comment_count,
field_count, the payload_safe_meta_keys and third_party_meta_keys
names, and response_filter_count.
The block is gated hard: it needs an authenticated user who passes the debug
capability gate and an active opt-in. It carries no meta values, no plugin
configuration, and no nonce — nothing that is not already visible to that user. A
normal response never contains the key at all, so a _debug-aware client must
treat it as optional.
Debug filters
| Filter | Signature | Purpose |
|---|---|---|
cacbot_user_can_debug |
(bool $can, int $post_id, int $user_id) |
Widen or narrow who may receive debug output. Default: current_user_can('edit_post', $post_id). This is the gate that also decides whether ?cacbot_debug and localStorage.cacbot_debug are honored at all. |
cacbot_debug_enabled |
(bool $enabled, int $post_id, int $user_id) |
Force debug on/off after the capability gate passes. Has the final word over the option, the constant, the cookie, and the query parameter. |
cacbot_debug_level |
(string $level, int $post_id) |
Default console verbosity: silent, error, warn, info, debug (default), or verbose. Receives any level named in ?cacbot_debug= or in the cookie, so it can respect or override it. An unrecognized return falls back to debug. |
cacbot_debug_buffer_size |
(int $size, int $post_id) |
Ring-buffer capacity for log entries and recorded events. Default 200 each. |
// Enable debug for administrators only, at maximum verbosity.
add_filter('cacbot_user_can_debug', function ($can, $post_id, $user_id) {
return user_can($user_id, 'manage_options');
}, 10, 3);
add_filter('cacbot_debug_enabled', '__return_true');
add_filter('cacbot_debug_level', function () { return 'verbose'; });
Debug-related localized config
window.cacbot_data carries three debug-related keys:
debug— whether the server switched debug on for this request.debug_allowed— whether this user passed the capability gate. The client honors?cacbot_debugandlocalStorage.cacbot_debugonly when this is true, which is what keeps the gate authoritative without a second round trip.debug_config—{ level, buffer_size, trace_events, expose_global }.
AI Style integration
The AI Style theme renders a post’s comments as a chat thread but, to stay
within WordPress.org theme rules, no longer updates it live. FDS does that on
the theme’s behalf with one extra ES module, aiplugin7139/ai-style-live-comments. The classic client is untouched.
When it is enqueued. All of these must hold:
- the FDS gate passed (a logged-in user on a singular view);
get_template()isai-style, so child themes of AI Style count;- the post is not password-protected, or the reader has unlocked it;
aiplugin7139_ai_style_live_comments_enabled($enabled, $post_id, $user_id) returns true. Return false to opt out:
add_filter('aiplugin7139_ai_style_live_comments_enabled', '__return_false');
What it does. On each cacbot:data-service:pulse for this post it builds a
fingerprint of the thread (ID, GMT date, and content of every comment-type
comment, plus linked_to) and compares it, and the title, with what is on
screen. Only when one differs, or linked_to_changed is true, it fetches the
post’s permalink with the user’s cookies, takes the server-rendered
#chat-messages and title from it, and merges the thread by data-message-id:
removed messages go, new ones are inserted in (date, ID) order with
.message-fade-in, messages whose server markup changed are replaced, and the
rest keep their DOM nodes. Sides and wide-code handling come from the theme’s
ai-style/chat-messages module. It scrolls to the newest message only if the
reader was already near the bottom or the new message is their own, keeps focus
on a replaced message, and announces messages from others with a short, polite
@wordpress/a11y message (“1 new message”).
Cost. Nothing new is polled. The 5-second /status check already runs for
every logged-in singular view. The only new request is one page GET per real
change to the thread or title, the same work as a reload. Pulses for meta
changes, such as Cacbot’s writes during an AI reply, fetch nothing.
What it relies on in the theme. The #scrollable-content and
#chat-messages markup, .message[data-message-id][data-message-date][data-author-id]
per comment, the .ai-style-singular-meta__title heading, and the
aiStyleApplyConversationSides() / aiStyleMakeWideCodeScrollable() exports of
ai-style/chat-messages. Every theme and core import is a dynamic dependency
loaded with import(), so if the theme drops or renames a module, live comments
switch off quietly instead of breaking the page’s other modules. A page without
#chat-messages never starts the module.
Debugging. The module’s data block (#wp-script-module-data-aiplugin7139/ai-style-live-comments)
carries postId, pageUrl, currentUserId, and debug. With FDS debug on, it
logs its decisions to the console with console.debug, prefixed
[FDS AI Style live comments].
Design notes
Rationale behind choices that are easy to second-guess when reading the code.
Debug is gated on a capability, not on being logged in. The service itself
only loads for logged-in users, but “logged in” is not a meaningful bar for
privileged output — it would let any logged-in reader switch polling internals on
for themselves. debug_allowed reports the server’s edit_post verdict to the
client so the browser toggles inherit the same gate without an extra round trip.
WP_DEBUG is not an implicit enabler. Enabling WordPress debugging is a
broad, common act; shipping this service’s internals to every editor’s console
should be a narrow, deliberate one. The admin checkbox, the CACBOT_DEBUG
constant, and the filters are all explicit.
No console.groupCollapsed per cycle. Grouping cannot bracket an async
cycle correctly: overlapping cycles — a visibility catch-up poll landing inside a
scheduled one — nest into each other’s groups and produce misleading output. The
#N cycle id on every line and entry.cycle on every buffered entry achieve the
same “see one cycle at a time” goal without that failure mode.
The _debug block is attached in the REST handlers, not inside
get_status_response_data() / get_payload_response_data(). Those two are pure
data builders whose exact field sets are pinned by tests; keeping the debug
concern out of them means debug mode cannot perturb the documented contract.
The opt-in cookie exists because REST calls are separate requests. Neither
the page’s query string nor its localStorage is visible to /status and
/payload. Without the cookie, the browser-scoped toggles could only ever switch
on the client logger, and seeing the server’s reasoning would require switching
the whole site on.
Freshness state is keyed per post and per user. Payloads are user-specific because of linked conversations, so two users sharing a browser must not share a last-seen timestamp.
last_changed_at is monotonic, not just “now”. Two changes within the same
millisecond would otherwise collapse into one timestamp, and a client that had
already seen it would never fetch the second change.
Troubleshooting
No events received
– Confirm you are logged in. The service does not load at all for anonymous
visitors — check whether window.cacbot_data even exists.
– Confirm you are on a singular page (single post/page), not an archive.
– If you are missing only ready: your listener is registered too late.
cacbot.js loads in the footer and fires ready synchronously. Register
listeners earlier, or rely on pulse instead.
error events appear repeatedly
– Read e.detail.phase to see whether /status or /payload failed, and
e.detail.error for the message.
– An expired nonce alone will not cause repeated errors — the client refreshes it
automatically via admin-ajax.php?action=rest-nonce. Repeated 403s usually mean
the login session itself has ended.
– Remember the backoff: after several failures the interval grows to as much as 5
minutes, so errors will appear to slow down rather than stop.
UI not updating
– Verify your pulse handler reads e.detail?.response, and that you are not
rendering from idle (whose response is the status object, not the payload).
– Only title, body, author, comments, and watched meta keys trigger refreshes.
Post body not updating
– Expected, and not fixable from the client. The payload has no content field;
the service never ships the post body. The edit does produce a pulse — reload
the page to render the new body. See
The post body is not in the payload.
Excerpt not updating – Expected. Excerpt changes do not signal dirty. The excerpt value in the payload refreshes only when some other tracked change triggers a pulse.
A third-party meta key produces pulses but never appears in the payload
– You are almost certainly storing it unprefixed. Dirty detection strips the
_cacbot_ prefix before matching, so a bare myplugin_campaign_id still marks
the post dirty — but the payload reader only ever looks up
_cacbot_myplugin_campaign_id. Store the value with the prefix.
Expecting commenter emails or IPs in the payload – Deliberately excluded for privacy. Comment entries carry only public fields.
Debug will not turn on
– Check window.cacbot_data.debug_allowed. If it is false, you do not pass the
capability gate and no query parameter or localStorage value will help.
– Check for a leftover cacbot_debug cookie or localStorage entry pulling the
level somewhere unexpected; ?cacbot_debug=0 clears both.
– Check whether a cacbot_debug_enabled filter is forcing it off — that filter
has the final word.