Skip to content

Commit 1d872fe

Browse files
authored
fix: filter watched-session presence for each recipient (#130764)
1 parent cfe00c3 commit 1d872fe

14 files changed

Lines changed: 581 additions & 21 deletions

‎docs/concepts/presence.md‎

Lines changed: 37 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,32 @@ Presence entries are structured objects with fields like:
3434
- `reason`: free-form client-supplied string; the Gateway itself only emits `self`, `connect`, and `disconnect`
3535
- `deviceId`, `roles`, `scopes`: device identity and role/scope hints from the connect handshake
3636
- `ts`: last update timestamp (ms since epoch)
37+
- `watchedSessions`: session keys the client explicitly declares it is viewing, filtered for the recipient
38+
39+
### Watched session references
40+
41+
Hello snapshots, `system-presence`, and `presence` events include only watched
42+
session references that the recipient can see under the current session-list
43+
visibility rules. Drafts, incognito sessions, and operator role restrictions
44+
follow those same rules. Missing or deleted sessions are omitted, including for
45+
admins. Keys retain their agent scope, including agent-qualified `global` and
46+
`unknown` references.
47+
48+
Session references require an operator connection with read access
49+
(`operator.read`, `operator.write`, or `operator.admin`). Nodes, pairing-only
50+
clients, and non-admin clients awaiting authenticated profile verification still
51+
receive the non-session presence roster in hello snapshots and events, without
52+
watched references. An established admin grant does not depend on profile
53+
verification. `system-presence` itself requires operator read access.
54+
55+
Filtering preserves the connection and person metadata and the presence timestamp.
56+
When no references are visible, `watchedSessions` is omitted, just as when the
57+
client declares no watches; there are no hidden-session counts or markers.
58+
Message subscriptions alone do not declare viewer presence.
59+
60+
These are coordination features within a shared agent, not isolation between
61+
mutually untrusted users. Everyone operating an agent shares that agent's
62+
capabilities. See [Multi-user trust boundary](/concepts/multi-user#trust-boundary).
3763

3864
## Producers (where presence comes from)
3965

@@ -73,16 +99,17 @@ is sampled for this compatibility value.
7399
When a node connects over the Gateway WebSocket with `role: node`, the Gateway
74100
upserts a presence entry for that node (same flow as other WS clients).
75101

76-
## Merge + dedupe rules (why `instanceId` matters)
102+
## Connection rows and beacon deduplication
77103

78-
Presence entries are stored in a single in-memory map, keyed case-insensitively
79-
by the first available of, in order: a paired device id, `connect.client.instanceId`,
80-
or the per-connection id as a last resort.
104+
Presence entries are stored in a single in-memory map with case-insensitive keys.
105+
User WebSocket clients have one row per connection, so two tabs watching different
106+
sessions cannot overwrite each other. Node connections use their device id,
107+
then `connect.client.instanceId`, then the connection id.
81108

82-
Ephemeral control-plane clients are excluded from tracking entirely (see
83-
above), so their connection ids never become keys. For every other client, the
84-
connection id fallback means a client that reconnects without a stable
85-
`instanceId` shows up as a **duplicate** row.
109+
`system-event` beacons merge by device id or instance id when supplied, otherwise
110+
by parsed host or other beacon metadata. A stable `instanceId` helps consumers
111+
associate rows with the same client; it does not merge separate user WebSocket
112+
connections. Ephemeral control-plane clients are excluded from tracking entirely.
86113

87114
## TTL and bounded size
88115

@@ -116,11 +143,11 @@ indicator (Active/Idle/Stale) based on the age of the last update.
116143

117144
## Debugging tips
118145

119-
- To see the raw list, call `system-presence` against the Gateway.
146+
- To see the list projected for your connection, call `system-presence` against the Gateway.
120147
- If you see duplicates:
121148
- confirm clients send a stable `client.instanceId` in the handshake
122149
- confirm periodic beacons use the same `instanceId`
123-
- check whether the connection-derived entry is missing `instanceId` (duplicates are expected)
150+
- check for multiple tabs or reconnects; separate user connections have separate rows, and old rows expire after the TTL
124151

125152
## Related
126153

‎src/gateway/gateway-misc.test.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -367,10 +367,11 @@ function makeScopedBroadcastClients() {
367367

368368
function makeScopedBroadcastContext() {
369369
const scoped = makeScopedBroadcastClients();
370-
return {
371-
...scoped,
372-
...createGatewayBroadcaster({ clients: scoped.clients }),
373-
};
370+
const broadcaster = createGatewayBroadcaster({
371+
clients: scoped.clients,
372+
preparePresenceProjection: (presence) => () => presence,
373+
});
374+
return { ...scoped, ...broadcaster };
374375
}
375376

376377
function sentEvents(socket: RecordingSocket) {

‎src/gateway/presence-projection.ts‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import type { SessionEntry } from "../config/sessions.js";
2+
import type { OpenClawConfig } from "../config/types.openclaw.js";
3+
import type { SystemPresence } from "../infra/system-presence.js";
4+
import { parseAgentSessionKey } from "../routing/session-key.js";
5+
import { authorizeOperatorScopesForRequiredScope, READ_SCOPE } from "./method-scopes.js";
6+
import { isGatewayClientProfilePending } from "./server-methods/gateway-client-identity.js";
7+
import type { GatewayClient } from "./server-methods/types.js";
8+
import { createSessionListEntryFilter, isGatewayAdmin } from "./session-sharing.js";
9+
import {
10+
resolveGatewaySessionStoreTargetWithStore,
11+
type GatewaySessionStoreDiscoveryCache,
12+
} from "./session-utils-store-lookup.js";
13+
import { resolveCanonicalSessionStoreMatchFromStoreKeys } from "./session-utils-store.js";
14+
15+
/** One synchronous snapshot/fanout owns these reads; never reuse them across broadcasts. */
16+
export function createPresenceRecipientProjection(params: {
17+
cfg: OpenClawConfig;
18+
presence: SystemPresence[];
19+
}): (client: GatewayClient | null) => SystemPresence[] {
20+
const targets = new Map<string, { canonicalKey: string; entry: SessionEntry } | undefined>();
21+
const targetDiscoveryCache: GatewaySessionStoreDiscoveryCache = new Map();
22+
const resolveTarget = (sessionKey: string) => {
23+
if (!targets.has(sessionKey)) {
24+
const parsed = parseAgentSessionKey(sessionKey);
25+
// Viewer declarations wrap sentinel keys with their agent. The stored key
26+
// remains global/unknown in that agent's store, not a literal prefixed row.
27+
const key =
28+
parsed?.rest === "global" || parsed?.rest === "unknown" ? parsed.rest : sessionKey;
29+
const target = resolveGatewaySessionStoreTargetWithStore({
30+
cfg: params.cfg,
31+
key,
32+
agentId: parsed?.agentId,
33+
readOnly: true,
34+
exactRead: true,
35+
clone: false,
36+
targetDiscoveryCache,
37+
});
38+
const match = resolveCanonicalSessionStoreMatchFromStoreKeys(target.store, target.storeKeys);
39+
targets.set(
40+
sessionKey,
41+
match ? { canonicalKey: target.canonicalKey, entry: match.entry } : undefined,
42+
);
43+
}
44+
return targets.get(sessionKey);
45+
};
46+
return (client) => {
47+
const canRead =
48+
client?.connect != null &&
49+
(client.connect.role ?? "operator") === "operator" &&
50+
authorizeOperatorScopesForRequiredScope(READ_SCOPE, client.connect.scopes ?? []).allowed &&
51+
// Match session reads: an established admin grant does not depend on profile verification.
52+
(isGatewayAdmin(client) || !isGatewayClientProfilePending(client));
53+
const entryFilter = canRead
54+
? createSessionListEntryFilter({ cfg: params.cfg, client })
55+
: undefined;
56+
return params.presence.map((row) => {
57+
if (!row.watchedSessions) {
58+
return row;
59+
}
60+
const watchedSessions = canRead
61+
? row.watchedSessions.filter((key) => {
62+
const target = resolveTarget(key);
63+
return target && (entryFilter?.(target.canonicalKey, target.entry) ?? true);
64+
})
65+
: [];
66+
const { watchedSessions: _watchedSessions, ...person } = row;
67+
return watchedSessions.length ? { ...person, watchedSessions } : person;
68+
});
69+
};
70+
}

0 commit comments

Comments
 (0)