Skip to content

Commit f3607b1

Browse files
authored
fix: preserve agent ownership across global sessions and bindings (#133715)
* fix: preserve task requesters and replacement bindings * fix: carry prepared agent ownership through global sessions * refactor(ui): let the CSS compiler own mask prefixes * test: align native policy fixture with its session owner
1 parent be3d86b commit f3607b1

158 files changed

Lines changed: 2700 additions & 1427 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/automation/tasks.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,10 @@ When a task reaches a terminal state, OpenClaw notifies you. There are two deliv
177177

178178
**Session-queued delivery** - if direct delivery fails or no origin is set, the update is queued as a system event in the requester's session and surfaces on the next heartbeat.
179179

180+
Notifications retain the recorded requester agent, even when another agent executes
181+
the task. With `session.scope: "global"`, queued updates and heartbeat wakes stay
182+
with that requester; another agent sharing the `global` session key cannot consume them.
183+
180184
When `gateway.publicOrigin` is configured and the Control UI is enabled,
181185
direct channel notifications include an `Inspect` link to the task's own
182186
session. Session-queued notifications do not include this link.

‎docs/concepts/session.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ DM channels, with group activity and background work flowing into it — see
2828
| Cron jobs | Fresh session per run |
2929
| Webhooks | Isolated per hook |
3030

31+
With `session.scope: "global"`, the selected agent still owns its session.
32+
The shared key `global` does not merge different agents' conversations:
33+
commands, skills, replies, and background task notifications retain the
34+
agent selected by the route or explicit request.
35+
3136
## DM isolation
3237

3338
By default, all DMs share one session for continuity, which is fine for

‎docs/plugins/hooks.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -998,6 +998,10 @@ approval resumes, policy summaries, background monitor
998998
deltas, and command continuations that should be visible to the model on the
999999
next turn but should not become permanent system prompt text.
10001000

1001+
Pass `agentId` with an unscoped `sessionKey`, such as `global`, when multiple
1002+
agents are configured. Enqueueing, consumption, and plugin session state stay in
1003+
that agent's store; the owner selector is not part of the persisted injection.
1004+
10011005
Cleanup semantics are part of the contract. Session extension cleanup and
10021006
runtime lifecycle cleanup callbacks receive `reset`, `delete`, `disable`, or
10031007
`restart`. The host removes the owning plugin's persistent session extension

‎docs/plugins/sdk-channel-plugins.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,10 @@ Plugin-owned targets do not require an OpenClaw agent id; use
459459
`openclaw/plugin-sdk/conversation-binding-runtime` to distinguish them from
460460
agent-owned targets before resolving an agent.
461461

462+
For agent-owned targets with an unscoped session key such as `global`, preserve
463+
`metadata.agentId` so routing keeps the binding's owner. An agent-scoped target
464+
key remains authoritative over conflicting metadata.
465+
462466
## Approvals and channel capabilities
463467

464468
Most channel plugins do not need approval-specific code. Core owns same-chat

‎extensions/discord/src/monitor/thread-bindings.lifecycle.test.ts‎

Lines changed: 61 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import path from "node:path";
44
import { expectDefined } from "@openclaw/normalization-core";
55
import { ChannelType } from "discord-api-types/v10";
66
import { getSessionBindingService } from "openclaw/plugin-sdk/conversation-runtime";
7+
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
78
import type { OpenKeyedStoreOptions } from "openclaw/plugin-sdk/plugin-state-runtime";
89
import {
910
createPluginStateSyncKeyedStoreForTests,
@@ -294,6 +295,54 @@ describe("thread binding lifecycle", () => {
294295
return binding;
295296
};
296297

298+
it.each([false, true])(
299+
"ignores stale sweep results after rebinding (restart=%s)",
300+
async (restart) => {
301+
vi.useFakeTimers();
302+
const probe = createDeferred<void>();
303+
let manager = createDefaultSweeperManager();
304+
try {
305+
await bindDefaultThreadTarget(manager);
306+
hoisted.restGet.mockImplementationOnce(async () => {
307+
await probe.promise;
308+
return {
309+
id: "thread-1",
310+
type: 11,
311+
parent_id: "parent-1",
312+
thread_metadata: { archived: true },
313+
};
314+
});
315+
await vi.advanceTimersByTimeAsync(120_000);
316+
expect(hoisted.restGet).toHaveBeenCalledTimes(1);
317+
318+
if (restart) {
319+
manager.stop();
320+
manager = createDefaultSweeperManager();
321+
}
322+
await manager.bindTarget({
323+
threadId: "thread-1",
324+
channelId: "parent-1",
325+
targetKind: "subagent",
326+
targetSessionKey: "agent:main:subagent:replacement",
327+
agentId: "main",
328+
webhookId: "wh-1",
329+
webhookToken: "tok-1",
330+
});
331+
probe.resolve();
332+
await vi.advanceTimersByTimeAsync(0);
333+
334+
expect(manager.getByThreadId("thread-1")?.targetSessionKey).toBe(
335+
"agent:main:subagent:replacement",
336+
);
337+
expect(hoisted.sendMessageDiscord).not.toHaveBeenCalled();
338+
} finally {
339+
probe.resolve();
340+
manager.stop();
341+
vi.useRealTimers();
342+
}
343+
},
344+
);
345+
297346
it.each([
298347
{
299348
name: "auto-unbinds idle-expired bindings and sends inactivity message",
@@ -1025,23 +1074,27 @@ describe("thread binding lifecycle", () => {
10251074
expect(usedStartupCfg).toBe(false);
10261075
});
10271076

1028-
it("refreshes manager token when an existing manager is reused", async () => {
1029-
createTestThreadBindingManager({
1077+
it.each([false, true])("keeps refreshed tokens after stale cleanup=%s", async (lateStop) => {
1078+
const initialOptions = {
10301079
accountId: "runtime",
10311080
token: "token-old",
10321081
persist: false,
10331082
enableSweeper: false,
10341083
idleTimeoutMs: 24 * 60 * 60 * 1000,
10351084
maxAgeMs: 0,
1036-
});
1085+
};
1086+
const initial = createTestThreadBindingManager(initialOptions);
1087+
if (lateStop) {
1088+
initial.stop();
1089+
createTestThreadBindingManager(initialOptions);
1090+
}
10371091
const manager = createTestThreadBindingManager({
1038-
accountId: "runtime",
1092+
...initialOptions,
10391093
token: "token-new",
1040-
persist: false,
1041-
enableSweeper: false,
1042-
idleTimeoutMs: 24 * 60 * 60 * 1000,
1043-
maxAgeMs: 0,
10441094
});
1095+
if (lateStop) {
1096+
initial.stop();
1097+
}
10451098

10461099
hoisted.createThreadDiscord.mockClear();
10471100
hoisted.createThreadDiscord.mockResolvedValueOnce({ id: "thread-created-token-refresh" });

‎extensions/discord/src/monitor/thread-bindings.manager.ts‎

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -60,17 +60,6 @@ import {
6060
type ThreadBindingRecord,
6161
} from "./thread-bindings.types.js";
6262

63-
function registerManager(manager: ThreadBindingManager) {
64-
MANAGERS_BY_ACCOUNT_ID.set(manager.accountId, manager);
65-
}
66-
67-
function unregisterManager(accountId: string, manager: ThreadBindingManager) {
68-
const existing = MANAGERS_BY_ACCOUNT_ID.get(accountId);
69-
if (existing === manager) {
70-
MANAGERS_BY_ACCOUNT_ID.delete(accountId);
71-
}
72-
}
73-
7463
function createNoopManager(accountIdRaw?: string): ThreadBindingManager {
7564
const accountId = normalizeAccountId(accountIdRaw);
7665
return {
@@ -125,6 +114,8 @@ export function createThreadBindingManager(params: {
125114
);
126115
const resolveCurrentCfg = () => getRuntimeConfigSnapshot() ?? params.cfg;
127116
const resolveCurrentToken = () => getThreadBindingToken(accountId) ?? params.token;
117+
const getCurrentBinding = (threadId: string) =>
118+
MANAGERS_BY_ACCOUNT_ID.get(accountId) === manager ? manager.getByThreadId(threadId) : undefined;
128119

129120
let sweepTimer: NodeJS.Timeout | null = null;
130121
const runSweepOnce = async () => {
@@ -137,7 +128,7 @@ export function createThreadBindingManager(params: {
137128
// Re-read live state after any awaited work from earlier iterations.
138129
// This avoids unbinding based on stale snapshot data when activity touches
139130
// happen while the sweeper loop is in-flight.
140-
const binding = manager.getByThreadId(snapshotBinding.threadId);
131+
const binding = getCurrentBinding(snapshotBinding.threadId);
141132
if (!binding) {
142133
continue;
143134
}
@@ -198,6 +189,10 @@ export function createThreadBindingManager(params: {
198189
}
199190
try {
200191
const channel = await getChannel(rest, binding.threadId);
192+
// A completed probe only owns the manager and binding that started it.
193+
if (getCurrentBinding(binding.threadId) !== binding) {
194+
continue;
195+
}
201196
if (!channel || typeof channel !== "object") {
202197
logVerbose(
203198
`discord thread binding sweep probe returned invalid payload for ${binding.threadId}`,
@@ -212,6 +207,9 @@ export function createThreadBindingManager(params: {
212207
});
213208
}
214209
} catch (err) {
210+
if (getCurrentBinding(binding.threadId) !== binding) {
211+
continue;
212+
}
215213
if (isDiscordThreadGoneError(err)) {
216214
logVerbose(
217215
`discord thread binding sweep removing stale binding ${binding.threadId}: ${summarizeDiscordError(err)}`,
@@ -493,13 +491,15 @@ export function createThreadBindingManager(params: {
493491
clearInterval(sweepTimer);
494492
sweepTimer = null;
495493
}
496-
unregisterManager(accountId, manager);
494+
if (MANAGERS_BY_ACCOUNT_ID.get(accountId) === manager) {
495+
MANAGERS_BY_ACCOUNT_ID.delete(accountId);
496+
forgetThreadBindingToken(accountId);
497+
}
497498
unregisterSessionBindingAdapter({
498499
channel: "discord",
499500
accountId,
500501
adapter: sessionBindingAdapter,
501502
});
502-
forgetThreadBindingToken(accountId);
503503
},
504504
};
505505

@@ -524,7 +524,7 @@ export function createThreadBindingManager(params: {
524524

525525
registerSessionBindingAdapter(sessionBindingAdapter);
526526

527-
registerManager(manager);
527+
MANAGERS_BY_ACCOUNT_ID.set(accountId, manager);
528528
return manager;
529529
}
530530

‎extensions/feishu/src/thread-bindings.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,25 @@ describe("Feishu thread bindings", () => {
253253
conversationId: "oc_group_chat:topic:om_topic_root",
254254
}),
255255
).toBeNull();
256+
257+
const restarted = createFeishuThreadBindingManager({ cfg: baseCfg, accountId: "default" });
258+
const conversation = {
259+
channel: "feishu",
260+
accountId: "default",
261+
conversationId: "oc_group_chat:topic:om_restarted",
262+
};
263+
const replacement = await getSessionBindingService().bind({
264+
conversation,
265+
targetSessionKey: "agent:codex:acp:replacement",
266+
targetKind: "session",
267+
});
268+
269+
manager.stop();
270+
271+
expect(createFeishuThreadBindingManager({ cfg: baseCfg, accountId: "default" })).toBe(
272+
restarted,
273+
);
274+
expect(getSessionBindingService().resolveByConversation(conversation)).toEqual(replacement);
256275
});
257276

258277
it.each(["refresh", "session", "kind"] as const)(

‎extensions/feishu/src/thread-bindings.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -275,12 +275,15 @@ export function createFeishuThreadBindingManager(params: {
275275
return removed;
276276
},
277277
stop: () => {
278-
for (const key of getState().bindingsByAccountConversation.keys()) {
279-
if (key.startsWith(`${accountId}:`)) {
280-
getState().bindingsByAccountConversation.delete(key);
278+
// A repeated shutdown must not remove a replacement manager's live bindings.
279+
if (getState().managersByAccountId.get(accountId) === manager) {
280+
for (const key of getState().bindingsByAccountConversation.keys()) {
281+
if (key.startsWith(`${accountId}:`)) {
282+
getState().bindingsByAccountConversation.delete(key);
283+
}
281284
}
285+
getState().managersByAccountId.delete(accountId);
282286
}
283-
getState().managersByAccountId.delete(accountId);
284287
unregisterSessionBindingAdapter({
285288
channel: "feishu",
286289
accountId,

‎extensions/matrix/src/matrix/conversation-route-owner.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,53 @@ describe("resolveMatrixConversationRouteOwner", () => {
7676
).toEqual({ kind: "agent", agentId: "finance" });
7777
});
7878

79+
it.each([
80+
{
81+
targetSessionKey: "global",
82+
metadata: { agentId: "finance" },
83+
expected: { kind: "agent", agentId: "finance" },
84+
},
85+
{
86+
targetSessionKey: "plugin-thread-1",
87+
metadata: {
88+
pluginBindingOwner: "plugin",
89+
pluginId: "demo-plugin",
90+
pluginRoot: "/tmp/demo-plugin",
91+
},
92+
expected: { kind: "plugin", pluginId: "demo-plugin", fallbackAgentId: "main" },
93+
},
94+
])(
95+
"reports the recorded owner for $targetSessionKey",
96+
({ targetSessionKey, metadata, expected }) => {
97+
registerSessionBindingAdapter({
98+
...adapter,
99+
resolveByConversation: (conversation) => ({
100+
bindingId: "binding-room",
101+
targetSessionKey,
102+
targetKind: "session",
103+
conversation,
104+
status: "active",
105+
boundAt: 1,
106+
metadata,
107+
}),
108+
});
109+
110+
expect(
111+
resolveMatrixConversationRouteOwner({
112+
cfg: {
113+
agents: {
114+
ownership: "explicit",
115+
entries: { main: { default: true }, finance: {} },
116+
},
117+
bindings: [{ agentId: "main", match: { channel: "matrix", accountId: "default" } }],
118+
},
119+
accountId: "default",
120+
conversation: { kind: "channel", peerId: "!room:example.org" },
121+
}),
122+
).toEqual(expected);
123+
},
124+
);
125+
79126
it("reports temporary binding-store unavailability", () => {
80127
unregisterSessionBindingAdapter({ channel: "matrix", accountId: "default", adapter });
81128

‎extensions/matrix/src/matrix/conversation-route-owner.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
2-
import { parseAgentSessionKey, resolveAgentRoute } from "openclaw/plugin-sdk/routing";
2+
import { resolveAgentRoute } from "openclaw/plugin-sdk/routing";
33
import { resolveMatrixAccount } from "./accounts.js";
44
import { resolveMatrixInboundRoute } from "./monitor/route.js";
55

@@ -34,10 +34,12 @@ export function resolveMatrixConversationRouteOwner(params: {
3434
if (!result.bindingOwnerAvailable) {
3535
return { kind: "unavailable" as const };
3636
}
37-
if (result.runtimeBindingId && !parseAgentSessionKey(result.route.sessionKey)?.agentId) {
38-
// Matrix's store cannot project plugin metadata. A non-agent runtime target therefore
39-
// cannot authorize detached delivery through an inferred fallback owner.
40-
return null;
37+
if (result.pluginId) {
38+
return {
39+
kind: "plugin" as const,
40+
pluginId: result.pluginId,
41+
fallbackAgentId: result.route.agentId,
42+
};
4143
}
4244
return { kind: "agent" as const, agentId: result.route.agentId };
4345
}

0 commit comments

Comments
 (0)