4 Commits

Author SHA1 Message Date
h z
0111fdf699 Merge pull request 'feat(triage): 3-state delivery + admin observer + admin cache' (#2) from feat/triage-3state-delivery into main 2026-05-22 21:59:19 +00:00
hanghang zhang
e87700d198 feat(triage): 3-state delivery + admin observer + admin cache
Triage channels now compute a 3-state delivery decision per recipient
(wake / observer / skip) instead of the binary wakeup flag, and route
according to:

  1. author never gets back their own message            → skip
  2. wake_mapping member (on-duty)                       → wake
  3. mention (NEW: was 'skip' for triage before)         → wake
  4. Center-scoped admin (at most 1)                     → observer
  5. anyone else                                         → skip
                                                         (was 'deliver wake=false')

Skipping means the websocket emit is omitted entirely — the recipient's
openclaw plugin never sees the message and the agent's session stays
free of background noise. Observer means delivered with wakeup=false
(silent UI / no model dispatch on the plugin side).

## What this PR ships

### realtime/realtime.gateway.ts
- new `computeDelivery()` returns DeliveryDecision = 'wake'|'observer'|'skip'
- old `computeWakeup()` kept as a deprecated wrapper for callers that
  still want the boolean answer (treats observer + skip as false)
- `emitMessageCreated` accepts `adminUserId?: string|null` and now
  short-circuits on 'skip' (no socket emit at all)
- general kept its current behavior; custom kept its current behavior
  (members not in wake_mapping become observer instead of `wake=false`)
  — the user-visible bit is just that the response field is the same
  `wakeup: boolean`; the explicit 'skip' is new for triage

### common/center-auth.ts
- `fetchAdminEmail()` calls GET `${center}/auth/admin-email` with the
  existing x-api-key (same auth as introspect/resolve-names). Returns
  `{email, userId}` or `null` on either "no admin" or any error

### common/admin-cache.service.ts (NEW)
- `AdminCacheService` — in-memory cache, 1-day TTL, lazy refresh.
  `get(force=true)` bypasses TTL for cli-triggered refresh
- exposed by MessagingModule

### messaging/messaging.controller.ts
- non-rotating branch threads `adminUserId` into emitMessageCreated

### cli/admin-refresh.ts (NEW)
- `node dist/cli/admin-refresh.js` — force-refresh cache and print
  before/after JSON. Use after a Center `user set-admin` so triage
  delivery picks up the new admin without waiting for 24h TTL

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 22:14:05 +01:00
h z
5b835e0871 Merge pull request 'feat(realtime): push channel.joined/left events to user-scoped rooms' (#1) from feat/push-channel-membership-events into main 2026-05-21 07:12:51 +00:00
hanghang zhang
e33f1ecc53 feat(realtime): push channel.joined/left events to user-scoped rooms
Backend half of the plugin push-based channel sync (companion to
nav/Fabric.OpenclawPlugin#1 follow-up). Before this, the OpenClaw
fabric inbound had to poll `/api/channels?guildId=...` every 60s to
discover newly-joined channels (any DM another user just dragged the
agent into). Now the server tells the agent's socket directly so
sub/unsub is realtime.

Changes:
- realtime.gateway.ts:
  * handleConnection joins the socket into a `user:<userId>` room.
    All of a user's connected sockets now share that room.
  * New `emitToUser(userId, event, data)` helper that emits into
    that room. No-op for offline users (next connect resyncs via the
    plugin's initial channel-list fetch).
- channels.service.ts:
  * Inject RealtimeGateway (RealtimeModule is @Global, no module
    plumbing needed).
  * Private `notifyMembership(kind, channelId, userIds, extra)`
    helper that emits `channel.<kind>` (joined|left) with payload
    {channelId, userId, xType, occurredAt}.
  * create(): emit channel.joined to every seeded member (creator +
    explicit memberUserIds + triage on-duty).
  * joinChannel(): emit channel.joined to userId (only if the row was
    actually inserted, idempotent on existing membership).
  * leaveChannel(): emit channel.left to userId iff a row was
    actually deleted.

Event shape:
  {
    channelId: string,
    userId: string,
    xType?: string,
    occurredAt: ISO string,
  }

Client-side contract (fabric plugin):
  socket.on('channel.joined', m => socket.emit('join_channel', {channelId: m.channelId}))
  socket.on('channel.left',   m => socket.emit('leave_channel', {channelId: m.channelId}))

The plugin keeps its 60s polling resync as a safety net for missed
events (transient socket drops between emit and reconnect, partial
failures, etc).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 08:07:46 +01:00
12 changed files with 9 additions and 288 deletions

View File

@@ -1,42 +0,0 @@
import { BadRequestException, Body, Controller, Get, Param, Put } from '@nestjs/common';
import { AgentPresenceService, PresenceStatus } from './agent-presence.service.js';
const VALID: PresenceStatus[] = ['idle', 'on_call', 'busy', 'exhausted', 'offline', 'unknown'];
interface PutBody {
status?: string;
source?: string;
}
@Controller('agents/:userId/presence')
export class AgentPresenceController {
constructor(private readonly svc: AgentPresenceService) {}
/**
* Read a user's current presence cache row.
* Auth: ApiKeyGuard (global). Any introspected center user can read.
*/
@Get()
async get(@Param('userId') userId: string): Promise<{ userId: string; status: PresenceStatus }> {
const status = await this.svc.getStatus(userId);
return { userId, status };
}
/**
* Push a presence update. Called by Fabric.OpenclawPlugin's
* `presence-sync` loop on each delta. Auth: ApiKeyGuard (global) +
* the plugin uses its center-introspected api key.
*
* `source` is a debug tag describing who pushed (e.g. 'hf-plugin',
* 'manual'). Stored verbatim for trail.
*/
@Put()
async put(@Param('userId') userId: string, @Body() body: PutBody): Promise<{ userId: string; status: PresenceStatus }> {
if (!body?.status || !VALID.includes(body.status as PresenceStatus)) {
throw new BadRequestException(`status must be one of ${VALID.join('|')}`);
}
const source = (body.source ?? 'unknown').slice(0, 64);
const row = await this.svc.setStatus(userId, body.status as PresenceStatus, source);
return { userId: row.userId, status: row.status };
}
}

View File

@@ -1,13 +0,0 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AgentPresence } from '../entities/agent-presence.entity.js';
import { AgentPresenceController } from './agent-presence.controller.js';
import { AgentPresenceService } from './agent-presence.service.js';
@Module({
imports: [TypeOrmModule.forFeature([AgentPresence])],
controllers: [AgentPresenceController],
providers: [AgentPresenceService],
exports: [AgentPresenceService],
})
export class AgentPresenceModule {}

View File

@@ -1,61 +0,0 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AgentPresence } from '../entities/agent-presence.entity.js';
export type PresenceStatus = 'idle' | 'on_call' | 'busy' | 'exhausted' | 'offline' | 'unknown';
@Injectable()
export class AgentPresenceService {
constructor(
@InjectRepository(AgentPresence)
private readonly repo: Repository<AgentPresence>,
) {}
/**
* Get a user's current presence. Returns 'unknown' if no row.
* Used by `RealtimeGateway` per-recipient when xType === 'announce'.
*/
async getStatus(userId: string): Promise<PresenceStatus> {
if (!userId) return 'unknown';
const row = await this.repo.findOne({ where: { userId } });
return row?.status ?? 'unknown';
}
/** Bulk variant for delivery-time lookups across many recipients in one trip. */
async getStatusMap(userIds: string[]): Promise<Map<string, PresenceStatus>> {
const out = new Map<string, PresenceStatus>();
for (const id of userIds) out.set(id, 'unknown');
if (userIds.length === 0) return out;
const rows = await this.repo
.createQueryBuilder('p')
.where('p.userId IN (:...ids)', { ids: userIds })
.getMany();
for (const r of rows) out.set(r.userId, r.status);
return out;
}
/**
* Upsert a user's presence. Source is a free-text tag for debugging
* (e.g. "hf-plugin", "manual", "test"). PUT /agents/:id/presence
* calls this; the plugin pushes only on diff so writes are sparse.
*
* Implementation note: the older findOne+save split was a read-modify-
* write race — two concurrent first-time writes for the same userId
* would both read no row, both INSERT, second hits unique-key dup
* (`agent_presences.PRIMARY`) and 500s. Fabric.OpenclawPlugin's
* presence-sync occasionally fires two PUTs for the same agent within
* ~10 ms (tick overlap on its side — separate fix in the plugin),
* which surfaced this race in prod.
*
* `repo.upsert(values, conflictPaths)` compiles to MySQL
* `INSERT … ON DUPLICATE KEY UPDATE` and is atomic at the storage
* engine level — no read needed, no race window. We synthesize the
* returned entity from what we just wrote rather than round-tripping
* a SELECT — the controller only reads {userId, status} off it.
*/
async setStatus(userId: string, status: PresenceStatus, source: string): Promise<AgentPresence> {
await this.repo.upsert({ userId, status, source }, ['userId']);
return this.repo.create({ userId, status, source });
}
}

View File

@@ -16,7 +16,6 @@ import { MembersModule } from './members/members.module.js';
import { FilesModule } from './files/files.module.js'; import { FilesModule } from './files/files.module.js';
import { CanvasModule } from './canvas/canvas.module.js'; import { CanvasModule } from './canvas/canvas.module.js';
import { CommandsModule } from './commands/commands.module.js'; import { CommandsModule } from './commands/commands.module.js';
import { AgentPresenceModule } from './agents/agent-presence.module.js';
@Module({ @Module({
imports: [ imports: [
@@ -31,7 +30,6 @@ import { AgentPresenceModule } from './agents/agent-presence.module.js';
FilesModule, FilesModule,
CanvasModule, CanvasModule,
CommandsModule, CommandsModule,
AgentPresenceModule,
], ],
controllers: [HealthController, MetricsController], controllers: [HealthController, MetricsController],
providers: [ providers: [

View File

@@ -1,4 +1,4 @@
import { BadRequestException, Body, Controller, Get, Param, Patch, Post, Query, Req, UnauthorizedException } from '@nestjs/common'; import { Body, Controller, Get, Param, Post, Query, Req, UnauthorizedException } from '@nestjs/common';
import { ChannelsService } from './channels.service.js'; import { ChannelsService } from './channels.service.js';
// ApiKeyGuard attaches the introspected Center user id onto the request. // ApiKeyGuard attaches the introspected Center user id onto the request.
@@ -32,33 +32,11 @@ export class ChannelsController {
bypassUserIds: Array.isArray(body.bypassUserIds) bypassUserIds: Array.isArray(body.bypassUserIds)
? (body.bypassUserIds as string[]) ? (body.bypassUserIds as string[])
: [], : [],
purpose: body.purpose as string | undefined,
}, },
userId, userId,
); );
} }
// Patch a channel's free-form purpose. Body: { purpose: string }. Pass
// empty string to clear. Auth: channel member (or anyone for public
// channels, mirroring close()). Frontend doesn't call this today —
// intended for agent-side use (fabric-channel-set-purpose tool).
@Patch(':id')
patch(
@Req() req: AuthedRequest,
@Param('id') channelId: string,
@Body() body: Record<string, unknown>,
) {
const userId = req.userId ?? '';
if (!userId) throw new UnauthorizedException('missing user');
// Only `purpose` is patchable today. Future patchable fields would
// get their own typed branch; we explicitly NOT allow {} no-op patches
// because that signals a caller bug.
if (typeof body.purpose !== 'string') {
throw new BadRequestException('purpose (string) is required');
}
return this.channelsService.updatePurpose(channelId, userId, body.purpose);
}
// Move an order member into the bypass list (discuss/work only). // Move an order member into the bypass list (discuss/work only).
@Post(':id/bypass') @Post(':id/bypass')
bypass( bypass(

View File

@@ -7,7 +7,7 @@ import { WakeMapping } from '../entities/wake-mapping.entity.js';
import { TurnService } from './turn.service.js'; import { TurnService } from './turn.service.js';
import { RealtimeGateway } from '../realtime/realtime.gateway.js'; import { RealtimeGateway } from '../realtime/realtime.gateway.js';
const X_TYPES = ['general', 'work', 'report', 'discuss', 'triage', 'custom', 'dm', 'announce'] as const; const X_TYPES = ['general', 'work', 'report', 'discuss', 'triage', 'custom', 'dm'] as const;
type XType = (typeof X_TYPES)[number]; type XType = (typeof X_TYPES)[number];
type CreateChannelInput = { type CreateChannelInput = {
@@ -24,10 +24,6 @@ type CreateChannelInput = {
// discuss/work only: members excluded from rotation (no wakeup unless // discuss/work only: members excluded from rotation (no wakeup unless
// @-mentioned). order and bypass partition the members disjointly. // @-mentioned). order and bypass partition the members disjointly.
bypassUserIds?: string[]; bypassUserIds?: string[];
// Free-form description of what this channel is for. Optional; agents
// typically fill it when creating, members can later edit via
// PATCH /api/channels/:id.
purpose?: string;
}; };
@Injectable() @Injectable()
@@ -170,9 +166,6 @@ export class ChannelsService {
// allowed (create() always makes a fresh one, no dedup). // allowed (create() always makes a fresh one, no dedup).
const isPublic = xType === 'dm' ? false : Boolean(input.isPublic); const isPublic = xType === 'dm' ? false : Boolean(input.isPublic);
const purposeRaw = String(input.purpose ?? '').trim();
const purpose = purposeRaw === '' ? null : purposeRaw;
const channel = await this.channelRepo.save( const channel = await this.channelRepo.save(
this.channelRepo.create({ this.channelRepo.create({
guildId, guildId,
@@ -181,7 +174,6 @@ export class ChannelsService {
kind: input.kind === 'announcement' ? 'announcement' : 'text', kind: input.kind === 'announcement' ? 'announcement' : 'text',
isPrivate: !isPublic, isPrivate: !isPublic,
isPublic, isPublic,
purpose,
lastSeq: 0, lastSeq: 0,
}), }),
); );
@@ -227,27 +219,6 @@ export class ChannelsService {
return channel; return channel;
} }
// Update a channel's free-form purpose. Any channel member may do this
// (or any guild user if the channel is public, mirroring closeChannel's
// member-or-public rule). Pass an empty string to clear.
async updatePurpose(channelId: string, actorUserId: string, purpose: string) {
const channel = await this.channelRepo.findOne({ where: { id: channelId } });
if (!channel) throw new NotFoundException('channel not found');
const member = await this.memberRepo.findOne({ where: { channelId, userId: actorUserId } });
if (!member && !channel.isPublic) {
throw new ForbiddenException('not a channel member');
}
const trimmed = String(purpose ?? '').trim();
channel.purpose = trimmed === '' ? null : trimmed;
const saved = await this.channelRepo.save(channel);
return {
id: saved.id,
name: saved.name,
xType: saved.xType,
purpose: saved.purpose,
};
}
// Move an order member into the bypass list (discuss/work only). // Move an order member into the bypass list (discuss/work only).
// Any channel member may do this. // Any channel member may do this.
async moveToBypass(channelId: string, actorUserId: string, targetUserId: string) { async moveToBypass(channelId: string, actorUserId: string, targetUserId: string) {

View File

@@ -14,7 +14,6 @@ import { IdempotencyRecord } from './entities/idempotency-record.entity.js';
import { StoredFile } from './entities/stored-file.entity.js'; import { StoredFile } from './entities/stored-file.entity.js';
import { ChannelCanvas } from './entities/channel-canvas.entity.js'; import { ChannelCanvas } from './entities/channel-canvas.entity.js';
import { GuildCommand } from './entities/guild-command.entity.js'; import { GuildCommand } from './entities/guild-command.entity.js';
import { AgentPresence } from './entities/agent-presence.entity.js';
export const buildTypeOrmConfig = (): TypeOrmModuleOptions => ({ export const buildTypeOrmConfig = (): TypeOrmModuleOptions => ({
type: 'mysql', type: 'mysql',
@@ -39,7 +38,6 @@ export const buildTypeOrmConfig = (): TypeOrmModuleOptions => ({
StoredFile, StoredFile,
ChannelCanvas, ChannelCanvas,
GuildCommand, GuildCommand,
AgentPresence,
], ],
synchronize: (process.env.FABRIC_BACKEND_GUILD_DB_SYNC ?? 'true') === 'true', synchronize: (process.env.FABRIC_BACKEND_GUILD_DB_SYNC ?? 'true') === 'true',
logging: (process.env.FABRIC_BACKEND_GUILD_DB_LOGGING ?? 'false') === 'true', logging: (process.env.FABRIC_BACKEND_GUILD_DB_LOGGING ?? 'false') === 'true',

View File

@@ -1,35 +0,0 @@
import { Column, Entity, PrimaryColumn, UpdateDateColumn } from 'typeorm';
/**
* Per-user (typically agent) presence cache.
*
* Populated by Fabric.OpenclawPlugin's presence-sync loop: every ~30s
* it reads each connected agent's HF status from the cross-plugin
* `globalThis.__hfAgentStatus.get(agentId)` (exposed by
* HarborForge.OpenclawPlugin) and pushes diffs via
* `PUT /agents/:userId/presence`.
*
* Used by `RealtimeGateway.computeDelivery` for `announce`-type
* channels to skip delivery to recipients whose status is `busy`.
* Defaults to `unknown` if no row exists (treated as not-busy).
*/
@Entity('agent_presences')
export class AgentPresence {
// Same id as the Fabric Center user id (UUID v4 string, char(36)).
@PrimaryColumn({ type: 'char', length: 36 })
userId!: string;
@Column({
type: 'enum',
enum: ['idle', 'on_call', 'busy', 'exhausted', 'offline', 'unknown'],
default: 'unknown',
})
status!: 'idle' | 'on_call' | 'busy' | 'exhausted' | 'offline' | 'unknown';
/** Free-text source tag for debugging ("hf-plugin", "manual", etc.). */
@Column({ type: 'varchar', length: 64, default: 'unknown' })
source!: string;
@UpdateDateColumn()
updatedAt!: Date;
}

View File

@@ -16,23 +16,13 @@ export class Channel {
@Column({ @Column({
name: 'x_type', name: 'x_type',
type: 'enum', type: 'enum',
enum: ['general', 'work', 'report', 'discuss', 'triage', 'custom', 'dm', 'announce'], enum: ['general', 'work', 'report', 'discuss', 'triage', 'custom', 'dm'],
}) })
xType!: 'general' | 'work' | 'report' | 'discuss' | 'triage' | 'custom' | 'dm' | 'announce'; xType!: 'general' | 'work' | 'report' | 'discuss' | 'triage' | 'custom' | 'dm';
@Column({ type: 'varchar', length: 16, default: 'text' }) @Column({ type: 'varchar', length: 16, default: 'text' })
kind!: 'text' | 'announcement'; kind!: 'text' | 'announcement';
// Free-form description of what this channel is for — what topics get
// posted, who participates, why it exists. Surfaced via GET /api/channels
// so agents can pick a channel by intent ("which announce channel is for
// debate broadcasts?") without channel id hard-coded into workflows.
// Any channel member can set it via PATCH /api/channels/:id (writes
// require membership the same way moveToBypass / close do). The frontend
// create form does NOT post this today — purpose stays optional.
@Column({ type: 'text', nullable: true })
purpose!: string | null;
@Column({ type: 'boolean', default: false }) @Column({ type: 'boolean', default: false })
isPrivate!: boolean; isPrivate!: boolean;

View File

@@ -166,11 +166,6 @@ export class MessagingController {
// Guild C-1: caller must be a participant of the channel, and the // Guild C-1: caller must be a participant of the channel, and the
// author is always the authenticated user — body.authorUserId is // author is always the authenticated user — body.authorUserId is
// ignored so a caller can never post as someone else. // ignored so a caller can never post as someone else.
//
// announce channels: any participant can POST. Use case is one-off
// recruitment / broadcast messages posted by the agent that just
// created the originating topic (e.g. dialectic invites). No
// server-side privileged path — author is always a real user.
const userId = String(req.userId ?? ''); const userId = String(req.userId ?? '');
if (!userId) throw new ForbiddenException('missing user'); if (!userId) throw new ForbiddenException('missing user');
const channel = await this.assertParticipant(channelId, userId); const channel = await this.assertParticipant(channelId, userId);

View File

@@ -11,17 +11,7 @@ import { Logger } from '@nestjs/common';
import { Server, Socket } from 'socket.io'; import { Server, Socket } from 'socket.io';
import { introspectGuildToken } from '../common/center-auth.js'; import { introspectGuildToken } from '../common/center-auth.js';
type XType = 'general' | 'work' | 'report' | 'discuss' | 'triage' | 'custom' | 'dm' | 'announce'; type XType = 'general' | 'work' | 'report' | 'discuss' | 'triage' | 'custom' | 'dm';
/**
* Cross-presence info needed by `announce`-type delivery: a recipient
* with hf-side status === 'busy' has the message discarded silently
* (don't enter their session, no UI emit). Other statuses + non-announce
* channels are unaffected. Presence is sourced from the
* `agent_presences` table populated by Fabric.OpenclawPlugin's
* presence-sync loop (which reads from HF plugin's `__hfAgentStatus`).
*/
export type PresenceStatus = 'idle' | 'on_call' | 'busy' | 'exhausted' | 'offline' | 'unknown';
/** /**
* Per-recipient delivery decision for a non-rotating channel message. * Per-recipient delivery decision for a non-rotating channel message.
@@ -53,12 +43,10 @@ export interface ComputeDeliveryArgs {
mentionUserIds?: Set<string>; mentionUserIds?: Set<string>;
/** Single Center-scoped admin userId, or null. */ /** Single Center-scoped admin userId, or null. */
adminUserId?: string | null; adminUserId?: string | null;
/** Recipient's current presence; only consulted for `announce` xType. Defaults to 'unknown' (treated as not-busy). */
recipientPresence?: PresenceStatus;
} }
export function computeDelivery(args: ComputeDeliveryArgs): DeliveryDecision { export function computeDelivery(args: ComputeDeliveryArgs): DeliveryDecision {
const { xType, recipientUserId, authorUserId, wakeUserIds, mentionUserIds, adminUserId, recipientPresence } = args; const { xType, recipientUserId, authorUserId, wakeUserIds, mentionUserIds, adminUserId } = args;
if (recipientUserId === authorUserId) return 'skip'; if (recipientUserId === authorUserId) return 'skip';
switch (xType) { switch (xType) {
@@ -79,16 +67,6 @@ export function computeDelivery(args: ComputeDeliveryArgs): DeliveryDecision {
return wakeUserIds.has(recipientUserId) ? 'wake' : 'observer'; return wakeUserIds.has(recipientUserId) ? 'wake' : 'observer';
case 'dm': case 'dm':
return 'wake'; return 'wake';
case 'announce':
// System-broadcast channels (e.g. Dialectic topic announcements).
// Recipients with HF status === 'busy' have the message discarded
// silently — busy agents should not be distracted by signup pings
// they can't act on. All other presences (idle/on_call/exhausted/
// offline/unknown) get the message as 'observer' (no wake): the
// channel itself is browsable; agents proactively decide what to
// do with announcements when they next look at their inbox.
if (recipientPresence === 'busy') return 'skip';
return 'observer';
default: default:
// report (and anything else): deliver as observer, no wake // report (and anything else): deliver as observer, no wake
return 'observer'; return 'observer';
@@ -122,12 +100,6 @@ export class RealtimeGateway implements OnGatewayConnection, OnGatewayDisconnect
private readonly logger = new Logger(RealtimeGateway.name); private readonly logger = new Logger(RealtimeGateway.name);
private readonly onlineUsers = new Set<string>(); private readonly onlineUsers = new Set<string>();
// Optional: injected at module wiring time. Used by emitMessageCreated
// to pre-load recipient presence for announce-type channels.
// Typed loosely to avoid a circular import between realtime and agents
// modules; the actual interface lives in agents/agent-presence.service.
presence?: { getStatusMap(ids: string[]): Promise<Map<string, PresenceStatus>> };
private userIdFromClient(client: Socket): string { private userIdFromClient(client: Socket): string {
const authUser = client.handshake.auth?.userId; const authUser = client.handshake.auth?.userId;
const headerUser = client.handshake.headers['x-user-id']; const headerUser = client.handshake.headers['x-user-id'];
@@ -253,8 +225,7 @@ export class RealtimeGateway implements OnGatewayConnection, OnGatewayDisconnect
// Emits message.created per-recipient using the 3-state delivery // Emits message.created per-recipient using the 3-state delivery
// decision (wake / observer / skip). Skipped recipients receive // decision (wake / observer / skip). Skipped recipients receive
// nothing — used by triage channels to keep non-on-duty / non-mention // nothing — used by triage channels to keep non-on-duty / non-mention
// / non-admin users completely out of the loop, and by announce // / non-admin users completely out of the loop.
// channels to suppress delivery to recipients whose presence is busy.
async emitMessageCreated( async emitMessageCreated(
channelId: string, channelId: string,
data: Record<string, unknown>, data: Record<string, unknown>,
@@ -268,18 +239,6 @@ export class RealtimeGateway implements OnGatewayConnection, OnGatewayDisconnect
}, },
): Promise<void> { ): Promise<void> {
const sockets = await this.server.in(`channel:${channelId}`).fetchSockets(); const sockets = await this.server.in(`channel:${channelId}`).fetchSockets();
// For announce-type channels, pre-load presence for all recipients
// in one query so the per-recipient loop doesn't fan out to N round
// trips. For other xTypes, presence is irrelevant — skip the lookup.
let presenceMap: Map<string, PresenceStatus> | undefined;
if (ctx.xType === 'announce' && this.presence) {
const recipientIds = sockets
.map((s) => (typeof s.data.userId === 'string' ? (s.data.userId as string) : ''))
.filter((id) => id && !id.startsWith('anon:'));
presenceMap = await this.presence.getStatusMap(recipientIds);
}
for (const s of sockets) { for (const s of sockets) {
const recipientUserId = typeof s.data.userId === 'string' ? s.data.userId : `anon:${s.id}`; const recipientUserId = typeof s.data.userId === 'string' ? s.data.userId : `anon:${s.id}`;
const decision = computeDelivery({ const decision = computeDelivery({
@@ -289,7 +248,6 @@ export class RealtimeGateway implements OnGatewayConnection, OnGatewayDisconnect
wakeUserIds: ctx.wakeUserIds, wakeUserIds: ctx.wakeUserIds,
mentionUserIds: ctx.mentionUserIds, mentionUserIds: ctx.mentionUserIds,
adminUserId: ctx.adminUserId, adminUserId: ctx.adminUserId,
recipientPresence: presenceMap?.get(recipientUserId) ?? 'unknown',
}); });
if (decision === 'skip') continue; if (decision === 'skip') continue;
s.emit('message.created', { s.emit('message.created', {

View File

@@ -1,25 +1,9 @@
import { Global, Module, OnModuleInit } from '@nestjs/common'; import { Global, Module } from '@nestjs/common';
import { RealtimeGateway } from './realtime.gateway.js'; import { RealtimeGateway } from './realtime.gateway.js';
import { AgentPresenceModule } from '../agents/agent-presence.module.js';
import { AgentPresenceService } from '../agents/agent-presence.service.js';
@Global() @Global()
@Module({ @Module({
imports: [AgentPresenceModule],
providers: [RealtimeGateway], providers: [RealtimeGateway],
exports: [RealtimeGateway], exports: [RealtimeGateway],
}) })
export class RealtimeModule implements OnModuleInit { export class RealtimeModule {}
// Wire presence into the gateway at startup. Using assignment (vs
// constructor injection) keeps the gateway free of the agents-module
// import — no risk of circular dependency, and announce-channel
// delivery degrades gracefully (presence stays undefined → 'unknown'
// status → no busy-discard) if AgentPresenceModule is ever removed.
constructor(
private readonly gateway: RealtimeGateway,
private readonly presence: AgentPresenceService,
) {}
onModuleInit(): void {
this.gateway.presence = this.presence;
}
}