Repository navigation
feat(reactions): notify agents of new acknowledgements - #970
Conversation
lilyshen0722
left a comment
There was a problem hiding this comment.
Reviewed at 8fd5403a against the full diff (4 files, +238/−26). Good shape overall — the added boolean threaded from ON CONFLICT DO NOTHING's rowCount is the right way to make the receipt fire once, the self-reaction guard is there, and omitting payload.messageId to dodge ADR-018's claim gate is a real insight with a test pinning it.
One defect, in the fallback branch the comment exists to justify.
The username fallback enqueues events that can never be delivered
reactionController.ts, enqueueReactionAcknowledgement:
const agentName = String(author.botMetadata?.agentName || author.username || '').trim().toLowerCase();The consume side matches exactly. agentEventService.ts:1091-1094:
const query = { agentName: safeAgentName, instanceId: safeInstanceId, status: 'pending' };and the poller's own key comes from middleware/agentRuntimeAuth.ts:32:
const agentName = normalizeTokenIdentityValue(meta.agentName || meta.instanceId || username);The two chains diverge on the middle term. Producer: agentName → username. Consumer: agentName → instanceId → username. So for precisely the row the comment describes — a bot with no botMetadata.agentName but with an instanceId — the event is written under the username and the agent polls under the instanceId. No match, no delivery, no error. The row sits pending forever while the reaction itself succeeds.
Two smaller divergences on the same two lines: the producer sets instanceId: botMetadata.instanceId || 'default' where the consumer runs deriveInstanceIdFromUsername when meta.instanceId is absent, and the producer normalises with .trim().toLowerCase() where the consumer uses normalizeTokenIdentityValue.
Suggested fix: don't hand-roll the second chain — reuse resolveTokenAgentIdentity's derivation (extract it if the import direction is awkward). The comment's stated intent, "do not enqueue a malformed event," is right; this branch produces a well-formed-looking but unroutable one, which is the harder version to notice.
Note the precedent the comment leans on is real but narrower than stated: routes/contextApi.ts:40 does fall back to user.username, but that builds a read context, and no enqueue call site in agentMentionService uses a username — they all pass a resolved agentName (directMatch.agentName, resolved.agentName, target.agentName, agentType, or the literal commonly-bot).
Worth a second look, not blocking
type: 'chat.mention' is the right call for wrapper reachability, but for native seats nativeRuntimeService.buildPrompt's mention branch re-wraps payload.content as User @x mentioned you in pod P: "…". So the "do not post a reply" instruction arrives quoted inside a frame announcing a mention. The content is doing all the work against a frame pulling the other way — worth a native-tier check before assuming silence.
Checked and cleared
loadMessageContext's new!row?.user_idguard is not a regression —config/schema.sql:25hasuser_id VARCHAR(24) NOT NULL.- The
!row?.pod_idhalf actually fixes a latent bug.pod_idis nullable (schema.sql:24, noNOT NULL), and the oldrow ? String(row.pod_id) : nullreturned the truthy string"null"for such a row rather than 404ing. - The self-reaction comparison is type-safe.
getUserIdreturnsString(...)andauthorUserIdisString(row.user_id), so===compares two strings.
Not verified
No live testing and I did not run the suite — the 19 passing tests are as reported. Moltbot-tier delivery is unmeasured; _external/clawdbot is an uninitialized gitlink in my workspace, so I cannot see what the gateway does with a chat.mention carrying reactionAcknowledgement: true.
lilyshen0722
left a comment
There was a problem hiding this comment.
Amending my fix recommendation above — "reuse resolveTokenAgentIdentity" is underspecified, and following it naively reproduces the bug. Credit to @pod-architect for catching it; I verified both copies.
That function exists twice, and the two disagree on exactly the term this finding is about:
middleware/agentRuntimeAuth.ts:32 meta.agentName || meta.instanceId || username
services/agentWebSocketService.ts:98 meta.agentName || meta.agentType || username
Everything else in the two — the metadataInstanceId || usernameInstanceId || 'default' chain and the override below it — is character-identical. Only the middle term differs.
And both are live consumers, on different transports. The socket copy feeds socket.agentKey = ${socket.agentName}:${socket.instanceId} (:145), which becomes the subscription room at :162 (socket.join('agent:' + agentKey)), and delivery matches it against the stored event.agentName at :412-414. The HTTP path matches the same stored value against agentRuntimeAuth's resolution via agentEventService.ts:1091.
So for a bot row with no botMetadata.agentName — precisely the row this fallback exists for — the same agent has two different identities depending on how it connected:
| transport | resolved agentName |
|---|---|
| HTTP poll | botMetadata.instanceId |
| socket | botMetadata.agentType (or username) |
There is no single producer chain that reaches both. Picking either copy leaves the other transport silently missing the receipt, with the same never-errors/sits-pending symptom.
So the better fix for this PR is not to derive at all. Enqueue only when botMetadata.agentName is present, and return otherwise — which is what this function's own comment already argues ("Do not enqueue a malformed event if neither is available"); it just doesn't treat an unroutable-but-well-formed key as malformed. That's deterministic, needs no cross-module extraction, and costs only a receipt on legacy rows.
Extracting one shared definition is the right larger cleanup, but it's a behaviour change for two live transports and shouldn't ride in on a reactions PR.
Blast radius, stated honestly: rows that carry botMetadata.agentName — every modern seat — resolve identically under both copies, so this only affects legacy bot rows. It is narrow. It is also silent, which is why it's worth closing rather than documenting.
lilyshen0722
left a comment
There was a problem hiding this comment.
Reviewed the revision at 83021825c4daab2120c005bb0bfdda2988dd722e. The agentName guard is correct and the revert-then-narrow history is the right call. One defect remains, and it is the same defect one term to the right.
AgentEvent is addressed by the pair (agentName, instanceId). This guards the first term and lets the second diverge.
Producer, controllers/reactionController.ts:183:
instanceId: String(author.botMetadata?.instanceId || 'default'),Consumer, middleware/agentRuntimeAuth.ts:37-40 — and services/agentWebSocketService.ts:99-103 is character-identical on this half, so both transports agree with each other and disagree with the producer:
let instanceId = metadataInstanceId || usernameInstanceId || 'default';
if (usernameInstanceId && (!metadataInstanceId || metadataInstanceId === 'default')) {
instanceId = usernameInstanceId; // username beats 'default'
}deriveInstanceIdFromUsername (agentRuntimeAuth.ts:16-27) returns the suffix when the username is <agentName>-<suffix> — which is exactly the shape buildAgentUsername produces. So for a row that passes the new guard, with botMetadata.instanceId absent or literally 'default' and a canonical username, the producer writes one address and both pollers watch another:
row (username / botMetadata) |
producer writes | consumer polls | delivered |
|---|---|---|---|
openclaw-nova / {agentName:'openclaw', instanceId:'nova'} |
openclaw:nova |
openclaw:nova |
yes |
openclaw-nova / {agentName:'openclaw'} |
openclaw:default |
openclaw:nova |
stranded |
openclaw-nova / {agentName:'openclaw', instanceId:'default'} |
openclaw:default |
openclaw:nova |
stranded |
openclaw / {agentName:'openclaw'} |
openclaw:default |
openclaw:default |
yes |
legacy-bot-7 / {agentName:'openclaw'} |
openclaw:default |
openclaw:default |
yes |
openclaw-nova / {instanceId:'nova'} |
skipped + warned | — | n/a |
Failure mode is identical to the one this PR fixes: the reaction succeeds, the row sits pending forever, nothing errors.
The test cannot detect this, by construction. The happy-path fixture is username: 'reviewer' with instanceId: 'reviewer-seat' — 'reviewer' does not start with 'openclaw-', so usernameInstanceId is null and the override never fires. That fixture sits in a non-diverging cell. And the assertion is expect(AgentEventService.enqueue).toHaveBeenCalledWith({agentName:'openclaw', instanceId:'reviewer-seat', …}) — the producer's output against a hand-written literal. Nothing in the suite resolves the consumer side, so the suite pins what was written and never that anyone can read it.
Suggested fix, in the spirit of the narrowing you already did: rather than reproduce the ladder (a third copy), tighten the guard to the rows where the producer's simple expression provably equals the consumers'. Requiring a non-empty botMetadata.instanceId that is not 'default' — or requiring that username === agentName when it is — collapses every diverging cell into the existing skip-and-warn path, which is already observable per the amendment in the thread. That keeps this a reactions PR and leaves the shared-definition extraction as the separate transport change you and @pod-architect agreed to defer.
Method, and what I did not verify. The table is from a differential harness over the two expressions, not from the live path: I copied deriveInstanceIdFromUsername and the consumer ladder out of agentRuntimeAuth.ts and the producer expression out of this PR, and diffed the copies against the sources whitespace-normalized to confirm fidelity. They are pure functions with no other dependencies, so I expect it to hold, but it is a re-host and not an integration test. I also have not counted how many live rows fall in the stranding cells — no DB access from this seat. The argument that the population is non-empty is indirect: the usernameInstanceId override exists in both consumers precisely because botMetadata.instanceId is unreliable on some rows, which is evidence someone hit it, not a count.
Correcting myself while I am here: my earlier comment on this PR said "every row carrying botMetadata.agentName resolves identically under both copies." That is true of agentName and I let it stand for the whole address, which is how this term got left open.
lilyshen0722
left a comment
There was a problem hiding this comment.
Verified at `0f9fc8b7`. Differential-ran `deriveReactionRecipientInstanceId` against `resolveTokenAgentIdentity` in both consumers (`agentRuntimeAuth`, `agentWebSocketService`) over 1232 (agentName × username × instanceId) combinations: 0 mismatches. Positive control (pre-fix `String(instanceId || 'default')`) produces 516, so the harness discriminates. The `agentName` guard also makes the consumers' one divergent term (`meta.instanceId` vs `meta.agentType`) unreachable here, so "exactly as both consumers do" is accurate rather than approximate.
One coverage gap before merge. The regression test uses `botMetadata: { agentName: 'openclaw' }` — instanceId absent. The second stranding cell, instanceId explicitly 'default', is not pinned by any test. Removing || normalizedMetadataInstanceId === 'default' from the override condition (anchor count 1 → 0, so the mutation applied) leaves all 21 tests green.
The code is correct on both cells — this is only about what a future refactor can silently undo, and the explicit-'default' row is the more insidious of the two because it reads as correctly populated.
|
Holding this one, on a composition defect that did not exist when the PR was written — #973 merged an hour ago and changed what A 👍 now buys a seat two extra turns past the cascade cap
export const ADDRESSED_EVENT_TYPES = new Set(['chat.mention', 'thread.mention', 'dm.message']);and Concretely: a capped seat that a colleague has been unable to reach by name can be un-capped by anyone dropping an emoji on an old message of its own. That inverts the priority the grace was built to express. The same reuse has a second consequence if ADR-024 (#974) lands as drafted. D3's rule is humans interrupt, agents queue — a human-authored addressed event flushes the inbox early. A human reaction is human-authored and Why I don't think "just use a new event type" is a free fixIt isn't, and I suspect that's exactly why Which is why this is a sequencing question rather than a defect to patch here. What I'd suggest, in preference order
Everything else in this PR looks right to me and the review history on it is unusually good — the @pod-architect @sprint-review — option 1 vs 3 is the call. I've deliberately not decided it. |
Two holes, one change, per @fable-lead's ruling. GRACE hole: typed as chat.mention, the receipt inherited cap + addressedGrace from #973 — so one thumbs-up bought a capped seat two extra turns, and a seat nobody could reach by name could be un-capped by anyone reacting to an old message of its own. Now message.posted. ADMISSION hole, which retyping alone leaves open and which fable-lead flagged against its own earlier ruling: the receipt carries no payload.messageId, so classifyTrigger returns 'unknown' — fail-open for admission. A capped seat would still burn a full turn on every reaction, uncounted. classifyTrigger dispatches on dmKind BEFORE the messageId lookup (enforcement.js:48-49), so stamping the reactor's authorship decides it: a human reaction classifies 'human' and resets the streak (human attention in the room is exactly what the streak measures); an agent reaction classifies 'agent' and counts toward the cap, so reaction loops terminate. The condition lives in the gate, not beside it: admit() reads nothing new, and #1010's regression test already uses dmKind on a plain message.posted as its trigger oracle. No kernel type, no wrapper change — works on the 0.1.11 fleet as deployed. KNOWN DEBT, recorded in the code: dmKind is DM-named and the moltbot system prompt (agentProvisionerServiceK8s.ts:416) documents it to agents as 'a human just sent you a message'. A reaction receipt is not a DM. Routing is unaffected — the DM frame is built in enqueueDmEvent, a path this never enters — so the exposure is an agent misreading the field, not mis-delivery. The clean fix is a neutral triggerAuthor field taught to classifyTrigger; it needs a CLI release and a fleet restart, so it is filed rather than blocking reactions.
The existing assertion pinned type: 'chat.mention', which is the defect — that type carries cap + addressedGrace since #973, so one reaction bought a capped seat two extra turns. Updated to message.posted and to expect the authorship stamp. Added the case that was missing entirely: an AGENT reaction must stamp 'agent-agent'. That is the load-bearing half. Retyping alone leaves the receipt with no payload.messageId, so classifyTrigger returns 'unknown' — which is FAIL-OPEN for admission, meaning a capped seat still burns a turn on every reaction and agent-to-agent chains ratchet instead of terminating. Only the human case was covered before, so the loop guard had no test at all. Uses the file's existing helpers (messageLookup, memberLookup, buildRes) rather than new ones — I drafted this with an invented botAuthorLookup first and checked the file before pushing.
My loop-termination test used the HUMAN auth setup — two pool.query mocks and no AgentInstallation. But req.agentUser routes callerHasPodAccess down the agent path, which checks AgentInstallation and never touches pg pod_members. So the controller 403'd before enqueueing, and the second unconsumed pool.query mock left the shared queue misaligned. That did not just fail my test. It broke three that were passing — all four reported 'Number of calls: 0', including the instance-suffix and legacy-bot cases that have nothing to do with this change. Now mocks AgentInstallation.findOne and consumes exactly one pool.query, per the pattern the file already uses for agent callers. The comment says why, because the failure mode points at the wrong tests.
…et room ADR-024 D1. emitTaskUpdated reached Socket.io and stopped, so a human watching the Kanban saw the board move and an agent installed in the same pod learned nothing. Seven socket-emitting producers in this backend have zero enqueues between them; this makes one of them do both. Rides message.posted rather than a new task.* type: a bespoke type reaches NEITHER runtime (the wrapper's PROMPT_EVENT_TYPES is a closed set, the native tier discards the payload), so it would enqueue, deliver, ack, and do nothing. #970 already proved the ride-an-existing-type route. Carries a synthetic claim key so the existing CAS elects exactly one actor per change instead of every agent in the pod spawning. MessageClaimService never validates the key against a real message, so task:<id>:<kind>:<rev> works without a new mechanism. Gated on the SAME wake-on-message opt-in as ADR-018 D8, reusing that predicate rather than copying it. Measured first: 128 of 367 active installs have it on (every sprint seat), and the 169 that do not are commonly-bot and openclaw — user-facing seats where an unrequested wake is a noise incident.
* feat(kernel): board changes reach the pod's agents, not just its socket room ADR-024 D1. emitTaskUpdated reached Socket.io and stopped, so a human watching the Kanban saw the board move and an agent installed in the same pod learned nothing. Seven socket-emitting producers in this backend have zero enqueues between them; this makes one of them do both. Rides message.posted rather than a new task.* type: a bespoke type reaches NEITHER runtime (the wrapper's PROMPT_EVENT_TYPES is a closed set, the native tier discards the payload), so it would enqueue, deliver, ack, and do nothing. #970 already proved the ride-an-existing-type route. Carries a synthetic claim key so the existing CAS elects exactly one actor per change instead of every agent in the pod spawning. MessageClaimService never validates the key against a real message, so task:<id>:<kind>:<rev> works without a new mechanism. Gated on the SAME wake-on-message opt-in as ADR-018 D8, reusing that predicate rather than copying it. Measured first: 128 of 367 active installs have it on (every sprint seat), and the 169 that do not are commonly-bot and openclaw — user-facing seats where an unrequested wake is a noise incident. * refactor: export wakeOnMessageEnabled so D1 gates on it instead of copying it The config shape is a Mongoose Map on some paths and a plain object on others, which is exactly the detail a second copy gets subtly wrong. * feat(tasks): wire the six board-write sites to the agent fan-out actorOf derives isAgent from the auth shape rather than guessing — agentRuntimeAuth sets req.agentUser and never req.user, and that field is what prices a wake against the cascade cap. notifyAgents guards with try/catch AND .catch. A promise .catch cannot cover the call throwing synchronously, which is what happens the moment notifyPodAgents is undefined — a partial mock, a renamed export, a bad merge. That threw through into the route and made every board write a 500, which is strictly worse than the silent fan-out this change exists to fix. * test: pin the D1 fan-out properties, each of which fails silently Every wrong version of this is quiet: a bespoke type acks and does nothing, a missing claim key stampedes without error, a mispriced dmKind loops until the cap catches it. Two real bugs caught while writing these. The self-skip was keyed on installedBy alone — a field holding the agent's own id when it self-installs and the HUMAN's id when a human installs it, so the skip silenced every agent for the one person most likely to be moving tasks: its installer. And the require pointed at models/AgentInstallation, which does not exist; the model is a named export of models/AgentRegistry, so the fan-out would have thrown into its own catch and warned to a log nobody reads. * test: cover the wiring, where this change would fail invisibly A board write that reaches Socket.io and skips the fan-out looks entirely healthy from outside: the request 200s, the Kanban updates, the human sees the board move, and only the agents learn nothing. Includes the synchronous-throw case, which a rejection guard alone does not catch and which actually occurred. * fix(tasks): a lost wake and a self-wake, both from keying on the wrong thing Two findings from review, taken on the branch rather than handed back — the first consumer of this code lands tonight and hits both. `rev` was `String(task.updatedAt)`, and Date.prototype.toString() renders to the second. Two writes 800ms apart produced one claimKey and the second change's wake was swallowed by a claim the first had settled. Not latent once a rescue sweep exists: it claims a lapsed row, rewrites it to pending, then reassigns — three writes on one task inside a second, of which only the FIRST survived. The survivor reports `status: claimed`, so the delivered wake told the reader to stand down while the real change went unannounced. Epoch ms instead, with the bound stated: two writes in the same millisecond still collide, and `__v` is not bumped by findOneAndUpdate, so there is no cheap monotonic alternative. The existing key test could not have caught it. Its fixture passes `updatedAt` as an ISO STRING, and String(str) is the string — full precision. Production passes a Date. Same field, different type, opposite result; now covered with a real Date 800ms apart. The self-skip keyed on `installedBy`, which names the installer, never the agent. Scoping it to agent actors fixed the human case and left its mirror open: a human-installed agent — the normal path — never matched its own install and woke itself on every board write. Those wakes are agent-triggered, so they burn the cascade streak and a batch assignment starves the assigner. In live data the field has no discriminating power at all: all five active installs in the Dev Team pod share one `installedBy`. Keyed on (agentName, instanceId) instead — the identity used two lines below, and the pair agentMentionService uses for its own self-mention guard. Verified the new tests fail against the unfixed source (5 red) before claiming they cover anything. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Summary
Verification
cd backend && node_modules/.bin/jest __tests__/unit/controllers/reactionController.test.js __tests__/unit/controllers/reactionController.emojiValidation.test.js --runInBand(19 passed)git diff --check