Skip to content

Commit f1cd367

Browse files
committed
fix: keep main session aware of isolated groups
Keep ambient main-session group notices working when direct messages use an isolated dmScope, while preserving explicit session watches and routed group topology.
1 parent 561effa commit f1cd367

9 files changed

Lines changed: 57 additions & 94 deletions

File tree

‎docs/concepts/main-session.md‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ coding/CLI sessions under **Coding**.
3333
The main session is not just a chat log; it is the place where your agent's
3434
world converges:
3535

36-
- **Group activity.** Group and room sessions stay isolated by default (see
37-
below), but under the default DM scope the main session automatically watches them.
36+
- **Group activity.** Under `session.groupScope: "per-group"` (the default),
37+
group and room sessions stay isolated while the main session automatically watches them.
3838
Activity queues up as compact notices — coalesced per conversation, never
3939
one wake-up per message — and the agent sees them the next time it runs: on
4040
your next message or on a scheduled heartbeat. Under the default `tree`
@@ -97,12 +97,13 @@ to. If several people can message your agent, isolate DMs:
9797
}
9898
```
9999

100-
With an isolating scope, each sender gets their own session, group watching
101-
from the main session is disabled, and cross-conversation memory recall
102-
defaults off. `openclaw security audit` recommends isolation when it detects
103-
multiple DM senders. The full scope matrix, identity linking, and per-route
104-
overrides are covered in [Session management](/concepts/session) and
105-
[Channel routing](/channels/channel-routing).
100+
With an isolating scope, each sender gets their own session and
101+
cross-conversation memory recall defaults off. Group watching remains controlled
102+
independently by `session.groupScope`: `per-group` keeps ambient main-session
103+
visibility, while `main` puts the room in the main conversation directly.
104+
`openclaw security audit` recommends DM isolation when it detects multiple
105+
senders. The full scope matrix, identity linking, and per-route overrides are
106+
covered in [Session management](/concepts/session) and [Channel routing](/channels/channel-routing).
106107

107108
Groups and rooms use separate sessions by default. To make selected trusted
108109
team rooms part of the rolling main conversation, set

‎docs/concepts/session-state.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,10 @@ Log-only kinds exist for reconciliation history, not notification: ordinary chil
3939

4040
## Watchers
4141

42-
A watcher is a session that holds a cursor (`session_watch_cursors`) on a target. Cursors come from two places:
42+
A watcher is a session that holds a cursor (`session_watch_cursors`) on a target. Cursors come from three places:
4343

4444
- **Implicit (spawn edges).** When a session spawns a sub-agent or ACP child, the parent's cursor is seeded automatically at the child's spawn version. Parents never subscribe manually.
45+
- **Ambient groups.** Under `session.groupScope: "per-group"`, the agent's main session watches its isolated group, room, and channel sessions after their first human turn. This is independent of `session.dmScope`; routing a room into main needs no watch because it already shares the main conversation.
4546
- **Explicit (`sessions_send watch: true`).** Any coordinator can watch a non-spawned target: pass `watch: true` on `sessions_send`, and after the send dispatches successfully the sender is registered as a watcher of the session that actually received the message. Registration starts at the target's current state version — prior history never produces notices. The tool result reports `watched: true|false` when the parameter was set.
4647

4748
Watcher identity must be an agent-qualified session key. Under `session.scope="global"` the shared `global` key is ambiguous across agents, so such sessions get the durable log and `changesSince` but no proactive notices.

‎src/agents/watched-sessions-prompt.test.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,7 @@ function stubStateDir() {
1717
}
1818

1919
function watchGroup(sessionKey: string) {
20-
expect(registerMainSessionGroupWatch({ sessionKey, agentId: "main", dmScope: "main" })).toBe(
21-
true,
22-
);
20+
expect(registerMainSessionGroupWatch({ sessionKey, agentId: "main" })).toBe(true);
2321
}
2422

2523
afterEach(() => {

‎src/auto-reply/reply/session.test.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,10 @@ import {
3737
isSessionLifecycleMutationActive,
3838
runExclusiveSessionLifecycleMutation,
3939
} from "../../sessions/session-lifecycle-admission.js";
40-
import { listSessionStateEventsSince } from "../../sessions/session-state-events.js";
40+
import {
41+
listAmbientGroupWatchTargets,
42+
listSessionStateEventsSince,
43+
} from "../../sessions/session-state-events.js";
4144
import {
4245
closeOpenClawAgentDatabasesForTest,
4346
resolveIncognitoOpenClawAgentSqlitePath,
@@ -434,6 +437,34 @@ afterEach(async () => {
434437
await sessionMcpTesting.resetSessionMcpRuntimeManager();
435438
});
436439
describe("initSessionState guarded initialization", () => {
440+
it("registers per-group ambient visibility when direct messages use isolated sessions", async () => {
441+
const stateDir = await makeCaseDir("openclaw-per-group-main-watch-");
442+
const storePath = path.join(stateDir, "sessions.json");
443+
const groupSessionKey = "agent:main:telegram:group:family";
444+
445+
await withEnvAsync({ OPENCLAW_STATE_DIR: stateDir }, async () => {
446+
await initSessionState({
447+
ctx: {
448+
Body: "hello group",
449+
ChatType: "group",
450+
DmScope: "per-channel-peer",
451+
From: "telegram:group:family",
452+
Provider: "telegram",
453+
SessionKey: groupSessionKey,
454+
},
455+
cfg: {
456+
session: {
457+
store: storePath,
458+
dmScope: "per-channel-peer",
459+
groupScope: "per-group",
460+
},
461+
} as OpenClawConfig,
462+
});
463+
464+
expect(listAmbientGroupWatchTargets("agent:main:main")).toEqual(new Set([groupSessionKey]));
465+
});
466+
});
467+
437468
it("pins an admitted non-default-agent incognito session to its process-local store", async () => {
438469
const stateDir = await makeCaseDir("openclaw-session-incognito-init-");
439470
await withEnvAsync({ OPENCLAW_STATE_DIR: stateDir }, async () => {

‎src/auto-reply/reply/session.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1083,7 +1083,6 @@ async function initSessionStateAttemptLocked(
10831083
sessionKey,
10841084
agentId,
10851085
entry: sessionEntry,
1086-
dmScope: ctx.DmScope ?? sessionCfg?.dmScope ?? "main",
10871086
mainKey,
10881087
});
10891088
}

‎src/config/schema.help.automation.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ export const AUTOMATION_FIELD_HELP: Record<string, string> = {
77
"session.dmScope":
88
'DM session scoping: "main" keeps continuity, while "per-peer", "per-channel-peer", and "per-account-channel-peer" increase isolation. Use isolated modes for shared inboxes or multi-account deployments.',
99
"session.groupScope":
10-
'Group/channel session scoping: "per-group" keeps rooms isolated by default, while "main" shares the agent main session. Use "main" only for rooms whose context should join the agent\'s primary conversation.',
10+
'Group/channel session scoping: "per-group" keeps rooms separate while the agent main session ambiently watches them, independently of dmScope; "main" merges room context into main and needs no watch. Use "main" only for trusted rooms.',
1111
"session.identityLinks":
1212
"Maps canonical identities to provider-prefixed peer IDs so equivalent users resolve to one DM thread (example: telegram:123456). Use this when the same human appears across multiple channels or accounts.",
1313
"session.resetTriggers":

‎src/config/schema.help.runtime.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,7 @@ export const RUNTIME_FIELD_HELP: Record<string, string> = {
303303
"bindings[].session.dmScope":
304304
'Optional DM session scope override for this route binding. For example, keep global session.dmScope="main" while using "per-account-channel-peer" for selected direct peers.',
305305
"bindings[].session.groupScope":
306-
'Optional group/channel session scope override for this route binding. Use "main" to merge only selected rooms into the agent main session while other rooms keep the global "per-group" default.',
306+
'Optional group/channel session scope override for this route binding. "per-group" keeps matched rooms separate and ambiently watched by the agent main session regardless of dmScope; "main" merges their context into main and needs no watch.',
307307
"bindings[].match":
308308
"Match rule object for deciding when a binding applies, including channel and optional account/peer constraints. Keep rules narrow to avoid accidental agent takeover across contexts.",
309309
"bindings[].match.channel":

‎src/sessions/session-state-events.test.ts‎

Lines changed: 8 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -534,31 +534,20 @@ describe("session state events", () => {
534534
});
535535
});
536536

537-
it("registers the main watcher once only under dmScope main", () => {
537+
it("registers one ambient main watcher for a distinct group session", () => {
538538
const database = createDatabaseOptions();
539539
expect(
540540
registerMainSessionGroupWatch(
541-
{ sessionKey: group, agentId: "main", dmScope: "main" },
541+
{ sessionKey: group, agentId: "main" },
542542
{ ...database, now: 100 },
543543
),
544544
).toBe(true);
545545
expect(
546546
registerMainSessionGroupWatch(
547-
{ sessionKey: group, agentId: "main", dmScope: "main" },
547+
{ sessionKey: group, agentId: "main" },
548548
{ ...database, now: 200 },
549549
),
550550
).toBe(true);
551-
expect(
552-
registerMainSessionGroupWatch(
553-
{
554-
sessionKey: "agent:main:slack:channel:room-2",
555-
agentId: "main",
556-
dmScope: "per-channel-peer",
557-
},
558-
database,
559-
),
560-
).toBe(false);
561-
562551
const rows = openOpenClawStateDatabase(database)
563552
.db.prepare(
564553
`SELECT watcher_session_key, target_session_key, provenance, updated_at
@@ -595,50 +584,21 @@ describe("session state events", () => {
595584
agentId: "main",
596585
mainKey: "work",
597586
entry: { sessionId: "session-main", updatedAt: 100, chatType: "group" },
598-
dmScope: "main",
599587
},
600588
database,
601589
),
602590
).toBe(false);
603591
expect(listAmbientGroupWatchTargets(mainSessionKey, database)).toEqual(new Set());
604592
});
605593

606-
it("revokes ambient watches outside main scope but preserves explicit watches", () => {
607-
const database = createDatabaseOptions();
608-
registerMainSessionGroupWatch(
609-
{ sessionKey: group, agentId: "main", dmScope: "main" },
610-
database,
611-
);
612-
expect(
613-
registerMainSessionGroupWatch(
614-
{ sessionKey: group, agentId: "main", dmScope: "per-channel-peer" },
615-
database,
616-
),
617-
).toBe(false);
618-
expect(listAmbientGroupWatchTargets(watcher, database)).toEqual(new Set());
619-
expect(readCursor(database, watcher, group)).toBeUndefined();
620-
621-
registerSessionStateWatch({ watcherSessionKey: watcher, targetSessionKey: group }, database);
622-
expect(
623-
registerMainSessionGroupWatch(
624-
{ sessionKey: group, agentId: "main", dmScope: "per-channel-peer" },
625-
database,
626-
),
627-
).toBe(false);
628-
expect(readCursor(database, watcher, group)).toBeDefined();
629-
});
630-
631594
it("records and coalesces group activity without an immediate wake", async () => {
632595
vi.useFakeTimers();
633596
const wakes = vi.fn(async () => ({ status: "ran" as const, durationMs: 1 }));
634597
disposeHeartbeatWakeHandler = setHeartbeatWakeHandler(wakes);
635598
await vi.advanceTimersByTimeAsync(300);
636599
wakes.mockClear();
637600
const database = createDatabaseOptions();
638-
registerMainSessionGroupWatch(
639-
{ sessionKey: group, agentId: "main", dmScope: "main" },
640-
database,
641-
);
601+
registerMainSessionGroupWatch({ sessionKey: group, agentId: "main" }, database);
642602

643603
for (const actorId of ["human-1", "human-2"]) {
644604
recordSessionHumanDirectMessage(
@@ -667,11 +627,11 @@ describe("session state events", () => {
667627
const dormantGroup = "agent:main:slack:channel:dormant";
668628
const registeredAt = 100;
669629
registerMainSessionGroupWatch(
670-
{ sessionKey: group, agentId: "main", dmScope: "main" },
630+
{ sessionKey: group, agentId: "main" },
671631
{ ...database, now: registeredAt },
672632
);
673633
registerMainSessionGroupWatch(
674-
{ sessionKey: dormantGroup, agentId: "main", dmScope: "main" },
634+
{ sessionKey: dormantGroup, agentId: "main" },
675635
{ ...database, now: registeredAt },
676636
);
677637

@@ -731,10 +691,7 @@ describe("session state events", () => {
731691
await vi.advanceTimersByTimeAsync(300);
732692
wakes.mockClear();
733693
const database = createDatabaseOptions();
734-
registerMainSessionGroupWatch(
735-
{ sessionKey: group, agentId: "main", dmScope: "main" },
736-
database,
737-
);
694+
registerMainSessionGroupWatch({ sessionKey: group, agentId: "main" }, database);
738695
expect(listAmbientGroupWatchTargets(watcher, database)).toEqual(new Set([group]));
739696

740697
registerSessionStateWatch({ watcherSessionKey: watcher, targetSessionKey: group }, database);
@@ -748,10 +705,7 @@ describe("session state events", () => {
748705
.get(watcher, group),
749706
).toEqual({ provenance: "explicit" });
750707
// Later inbound group registration must not downgrade the explicit watch.
751-
registerMainSessionGroupWatch(
752-
{ sessionKey: group, agentId: "main", dmScope: "main" },
753-
database,
754-
);
708+
registerMainSessionGroupWatch({ sessionKey: group, agentId: "main" }, database);
755709

756710
recordSessionHumanDirectMessage(
757711
{

‎src/sessions/session-state-events.ts‎

Lines changed: 3 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import { safeParseJsonRecord } from "@openclaw/normalization-core/json-coercion"
44
import type { Insertable, Selectable } from "kysely";
55
import { loadSessionEntryReadOnly } from "../config/sessions/session-accessor.js";
66
import type { SessionEntry } from "../config/sessions/types.js";
7-
import type { DmScope } from "../config/types.base.js";
87
import {
98
executeSqliteQuerySync,
109
executeSqliteQueryTakeFirstSync,
@@ -901,13 +900,12 @@ export function registerSessionStateWatch(
901900
}
902901
}
903902

904-
/** Register the personal agent's main session to observe one routed group session. */
903+
/** Register the agent's main session to observe one routed group session. */
905904
export function registerMainSessionGroupWatch(
906905
params: {
907906
sessionKey: string;
908907
agentId: string;
909908
entry?: SessionEntry;
910-
dmScope: DmScope;
911909
mainKey?: string;
912910
},
913911
options: OpenClawStateDatabaseOptions & { now?: number } = {},
@@ -919,33 +917,14 @@ export function registerMainSessionGroupWatch(
919917
agentId: params.agentId,
920918
mainKey: params.mainKey,
921919
});
920+
// groupScope already chose the routed key: "main" is the watcher itself,
921+
// while every distinct group key is a per-group target. dmScope is orthogonal.
922922
if (params.sessionKey === watcherSessionKey) {
923923
return false;
924924
}
925925
const now = options.now ?? Date.now();
926926
try {
927927
const { db: readDb } = openOpenClawStateDatabase(options);
928-
if (params.dmScope !== "main") {
929-
if (!isAmbientGroupWatchCursor(readCursor(readDb, watcherSessionKey, params.sessionKey))) {
930-
return false;
931-
}
932-
runOpenClawStateWriteTransaction(({ db }) => {
933-
// Recheck provenance in the write transaction: an explicit registration
934-
// may have promoted this pair after the read-only preflight.
935-
if (!isAmbientGroupWatchCursor(readCursor(db, watcherSessionKey, params.sessionKey))) {
936-
return;
937-
}
938-
executeSqliteQuerySync(
939-
db,
940-
getSessionStateKysely(db)
941-
.deleteFrom("session_watch_cursors")
942-
.where("target_session_key", "=", params.sessionKey)
943-
.where("watcher_session_key", "=", watcherSessionKey)
944-
.where("provenance", "=", SESSION_WATCH_PROVENANCE_AMBIENT_GROUP),
945-
);
946-
}, options);
947-
return false;
948-
}
949928
// This runs on every human group turn. Keep the steady-state path read-only;
950929
// the transaction below is only for first registration and its race recheck.
951930
if (readCursor(readDb, watcherSessionKey, params.sessionKey)) {

0 commit comments

Comments
 (0)