Skip to content

Commit a482a50

Browse files
steipeteampagent
andauthored
perf(ui): bootstrap session rosters in one request (#130294)
* perf(ui): collapse session roster bootstrap RPCs Amp-Thread-ID: https://ampcode.com/threads/T-01a037b3-be95-76ea-8fb3-75979929acf1 * fix(gateway): isolate and bound session roster bootstrap Scope cached projections to the authenticated viewer, apply startup admission consistently, and preserve the independent owner and shared preview budgets. Regenerate the Swift client and document the bootstrap and cursor contract. Publish Gateway test configuration atomically to remove the deferred-reader race. Co-authored-by: Amp <[email protected]> * test(gateway): extract session roster cache fixtures --------- Co-authored-by: Amp <[email protected]>
1 parent 820d167 commit a482a50

28 files changed

Lines changed: 542 additions & 313 deletions

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5205,6 +5205,7 @@ public struct SessionsListParams: Codable, Sendable {
52055205
public let boardface: AnyCodable?
52065206
public let creatorid: String?
52075207
public let ownerid: String?
5208+
public let ownerfirst: Bool?
52085209
public let involvingme: Bool?
52095210
public let spawnedby: String?
52105211
public let agentid: String?
@@ -5226,6 +5227,7 @@ public struct SessionsListParams: Codable, Sendable {
52265227
boardface: AnyCodable? = nil,
52275228
creatorid: String? = nil,
52285229
ownerid: String? = nil,
5230+
ownerfirst: Bool? = nil,
52295231
involvingme: Bool? = nil,
52305232
spawnedby: String? = nil,
52315233
agentid: String? = nil,
@@ -5246,6 +5248,7 @@ public struct SessionsListParams: Codable, Sendable {
52465248
self.boardface = boardface
52475249
self.creatorid = creatorid
52485250
self.ownerid = ownerid
5251+
self.ownerfirst = ownerfirst
52495252
self.involvingme = involvingme
52505253
self.spawnedby = spawnedby
52515254
self.agentid = agentid
@@ -5268,6 +5271,7 @@ public struct SessionsListParams: Codable, Sendable {
52685271
case boardface = "boardFace"
52695272
case creatorid = "creatorId"
52705273
case ownerid = "ownerId"
5274+
case ownerfirst = "ownerFirst"
52715275
case involvingme = "involvingMe"
52725276
case spawnedby = "spawnedBy"
52735277
case agentid = "agentId"

‎docs/gateway/clients.md‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -145,8 +145,10 @@ snapshot, so re-read them on every reconnect.
145145
Treat every successful reconnect as a new projection over durable history and
146146
current in-memory run state:
147147

148-
1. Re-establish `sessions.subscribe` and the selected session's
149-
`sessions.messages.subscribe` subscription.
148+
1. Re-establish `sessions.subscribe` with your list parameters to receive the
149+
current roster in the same response, as described
150+
[below](/gateway/clients#subscribe-instead-of-polling-usage). Also re-establish
151+
the selected session's `sessions.messages.subscribe` subscription.
150152
2. Call `chat.history` for the selected `sessionKey` and replace local persisted
151153
rows with the returned `messages` projection.
152154
3. If `inFlightRun` is present, adopt its `runId`, buffered `text`, and optional
@@ -240,8 +242,27 @@ archive history; anchored responses intentionally omit numeric paging metadata.
240242

241243
## Subscribe instead of polling usage
242244

243-
Load the initial catalog with `sessions.list`, then call `sessions.subscribe` once
244-
per connection. Merge `sessions.changed` events by `sessionKey`. Session change
245+
Install the `sessions.changed` listener, then call `sessions.subscribe` once per
246+
connection with your `sessions.list` parameters, such as
247+
`{ limit: 60, ownerFirst: true }`. The response is `{ subscribed: true, list }`,
248+
where `list` is the normal `SessionsListResult` snapshot. Passing `{}` activates
249+
the subscription but returns only `{ subscribed: true }`, without a list.
250+
251+
The Gateway activates the subscription before reading the snapshot. Events can
252+
therefore arrive before the response. Track changes received during bootstrap
253+
and follow the response with a `sessions.list` refresh when needed; do not let
254+
the snapshot silently overwrite a newer event. Re-establish this flow after
255+
every reconnect.
256+
257+
`ownerFirst: true` prepends up to 60 matching sessions owned by the authenticated
258+
viewer to the normal first page, removing duplicates within that response. It
259+
applies only when `offset` is zero or omitted. The Gateway derives the viewer
260+
identity from the authenticated connection, not a client-supplied identity.
261+
The shared page's pagination metadata is unchanged, so use `nextOffset`, not the
262+
number of returned rows, when loading another page, and merge rows by session
263+
key. See [Session list bootstrap](/gateway/protocol#session-list-bootstrap).
264+
265+
Merge subsequent `sessions.changed` events by `sessionKey`. Session change
245266
payloads can carry live `inputTokens`, `outputTokens`, `totalTokens`,
246267
`totalTokensFresh`, `contextTokens`, `estimatedCostUsd`, response-usage settings,
247268
and active-run state.

‎docs/gateway/protocol.md‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -651,7 +651,7 @@ methods. Treat this as feature discovery, not a full enumeration of
651651

652652
<Accordion title="Session control">
653653
- `sessions.list` returns the current session index, including per-row `agentRuntime` metadata when an agent runtime backend is configured. `hasActiveRun` is the authoritative aggregate direct-session activity fact. When projected, `activeRunIds` is the complete exact active set; an empty array proves the session is idle. If aggregate activity is true while the field is omitted, another runtime owner is active but its exact identities are unavailable. Snapshot omission means identities unavailable. On incremental events, omission means no change, `null` is the event-only tombstone that clears cached exact IDs to unavailable, and an array replaces the cache. Clients correlate only exact IDs they own locally or received from requests, history, or events and never select the first list entry as an owner. When cloud-worker placement is enabled or durable recovery state exists, session rows also include a closed `placement` state (`local`, `requested`, `provisioning`, `syncing`, `starting`, `active`, `draining`, `reconciling`, `reclaimed`, or `failed`) plus state-specific environment, owner-epoch, workspace, bundle, ACK-cursor, or recovery fields. Active placements may include an advisory `diskSpace` sample with `status` (`ok`, `warning`, or `critical`), `availableBytes`, `totalBytes`, and `observedAtMs`. An active paired-device placement also includes `runner: { kind: "device", status: "available" | "offline", deviceId? }`; `deviceId` names the paired device hosting the placement (the selected host for `autoDevice` dispatch), and non-device placements omit the field. This availability is process-current, derived from the exact active environment binding and reconnect-scoped node-runner proof, and starts offline after Gateway restart until that runner reconnects. Inventory changes emit `sessions.changed` so clients refresh the canonical row. Rows carry ownership projections — write-once `createdActor`, the mutable `owner` (actor plus `assignedBy`/`assignedAt`), a bounded `participants` list (owner excluded, up to 4 actors), and the full `participantCount`; actor display labels and avatars are resolved from current profiles and agent identities at read time. Pass `creatorId` to filter by immutable `createdActor.id`; pass `ownerId` to filter by the current assignable owner, falling back to `createdActor` when no owner is assigned. The complete `owners` facet is independent of pagination and remains unfiltered by either query, so clients can render the full owner picker. Authenticated callers can pass `involvingMe: true` to keep only sessions the caller owns or has prompted, evaluated against the full participant history (profile-backed human participants only).
654-
- `sessions.subscribe` enables session change events for the current WebSocket client. The subscription ends when that client disconnects.
654+
- `sessions.subscribe` enables session change events for the current WebSocket client and accepts the same parameters as `sessions.list` to return an initial list in the same response. Empty `{}` parameters return only the subscription acknowledgment. The subscription ends when that client disconnects. See [Session list bootstrap](/gateway/protocol#session-list-bootstrap).
655655
- `sessions.messages.subscribe` and `sessions.messages.unsubscribe` toggle transcript/message event subscriptions for one session. Pass `includeApprovals: true` to also receive sanitized `session.approval` lifecycle events for approvals whose persisted audience includes that exact session and whose reviewer binding authorizes the subscribing client. The subscribe response then includes a bounded pending `approvalReplay`; it is authoritative when `truncated` is false. The opt-in is per subscribe call, not sticky: re-subscribing to the same session without `includeApprovals: true` removes an existing approval subscription. In addition to normal session-read authority, this opt-in requires `operator.admin`, or `operator.approvals` on a paired device.
656656
- `sessions.preview` returns bounded transcript previews for specific session keys.
657657
- `sessions.describe` returns one gateway session row for an exact session key.
@@ -748,6 +748,37 @@ methods. Treat this as feature discovery, not a full enumeration of
748748
</Accordion>
749749
</AccordionGroup>
750750

751+
### Session list bootstrap
752+
753+
Call `sessions.subscribe` with a non-empty `sessions.list` parameter object, such
754+
as `{ limit: 60, ownerFirst: true }`, to subscribe and load the initial roster in
755+
one request. A successful WebSocket response has the payload
756+
`{ subscribed: true, list }`, where `list` is the normal `SessionsListResult`.
757+
Calling with `{}` preserves the acknowledgment-only response
758+
`{ subscribed: true }` and does not read a snapshot.
759+
List parameters select the snapshot; they do not filter the connection's session
760+
event subscription.
761+
762+
The Gateway registers the subscription before projecting the list. Clients must
763+
listen for `sessions.changed` before making the request: events can arrive while
764+
the snapshot is being built. Reconcile those events with the response and issue
765+
a trailing `sessions.list` refresh when needed, including when an event only
766+
invalidates the cached list. Reconnects require a new subscription and snapshot.
767+
768+
Both methods accept `ownerFirst: true` to prepend up to 60 matching viewer-owned
769+
rows (or `limit`, when smaller) to the normal first page, deduplicated by session key. This applies only
770+
when `offset` is zero or omitted; later pages use normal pagination. Owned rows
771+
must pass the same visibility and list filters as the shared page. The Gateway
772+
resolves the viewer from the authenticated connection; no client-supplied
773+
identity selects these rows. Without an authenticated viewer identity, or when
774+
`ownerFirst` is false or omitted, the list uses normal ordering.
775+
776+
The shared page still determines `limitApplied`, `offset`, `nextOffset`,
777+
`hasMore`, and `totalCount`. Prepended rows can make `sessions.length` and `count`
778+
exceed the shared page size. Use `nextOffset` to advance and deduplicate rows by
779+
session key across pages; do not derive the next offset from the displayed row
780+
count.
781+
751782
### Common event families
752783

753784
- `chat`: UI chat updates such as `chat.inject` and other transcript-only chat

‎packages/gateway-protocol/src/schema/sessions.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,8 @@ export const SessionsListParamsSchema = closedObject({
418418
creatorId: Type.Optional(NonEmptyString),
419419
/** Filter rows by their current assignable owner identity. */
420420
ownerId: Type.Optional(NonEmptyString),
421+
/** Prepend the authenticated viewer's owned rows to the normal first page. */
422+
ownerFirst: Type.Optional(Type.Boolean()),
421423
/** Limit rows to sessions owned by or previously prompted by the authenticated viewer. */
422424
involvingMe: Type.Optional(Type.Boolean()),
423425
spawnedBy: Type.Optional(NonEmptyString),

‎src/gateway/methods/core-descriptors.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ const CORE_GATEWAY_METHOD_SPECS = [
258258
["secrets.resolve", null, "operator.admin", "<=2026.7"],
259259
["voicewake.routing.get", "voicewake-routing", "operator.read", "<=2026.7"],
260260
["sessions.list", "sessions-read", "operator.read", "<=2026.7", { startup: true }],
261-
["sessions.subscribe", "sessions-subscriptions", "operator.read", "<=2026.7"],
261+
["sessions.subscribe", "sessions-subscriptions", "operator.read", "<=2026.7", { startup: true }],
262262
["sessions.messages.subscribe", "sessions-subscriptions", "operator.read", "<=2026.7"],
263263
["sessions.messages.unsubscribe", "sessions-subscriptions", "operator.read", "<=2026.7"],
264264
["sessions.viewers.set", "sessions-subscriptions", "operator.read", "2026.7"],

‎src/gateway/server-methods.control-plane-rate-limit.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,9 @@ describe("gateway control-plane write rate limit", () => {
233233
expect(suspension?.release()).toBe(true);
234234
});
235235

236-
it.each(STARTUP_UNAVAILABLE_GATEWAY_METHODS)(
236+
it.each([
237+
...new Set(["sessions.list", "sessions.subscribe", ...STARTUP_UNAVAILABLE_GATEWAY_METHODS]),
238+
])(
237239
"blocks startup-gated method %s before dispatch with a retryable startup error",
238240
async (method) => {
239241
const handlerCalls = vi.fn();

‎src/gateway/server-methods/sessions-list-cache.ts‎

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -116,28 +116,15 @@ function matchesSessionListFence(value: SessionListFence, fence: SessionListFenc
116116
);
117117
}
118118

119-
function sessionListVisibilityIdentity(
120-
client: GatewayClient | null,
121-
config: OpenClawConfig,
122-
): string {
123-
if (isGatewayAdmin(client)) {
124-
return "admin";
125-
}
126-
const profileId = gatewayClientSessionCreator(client)?.id;
127-
if (!profileId) {
128-
return "anonymous";
129-
}
130-
const sessionPolicy = operatorSessionCap(client, config);
131-
return sessionPolicy ? `profile:${profileId}:sessions:${sessionPolicy}` : `profile:${profileId}`;
132-
}
133-
134119
function sessionListWorkKey(
135120
params: SessionsListParams,
136121
client: GatewayClient | null,
137122
config: OpenClawConfig,
138123
): string {
139124
return JSON.stringify([
140-
sessionListVisibilityIdentity(client, config),
125+
// Admin visibility is global, but owner-first and involving-me rows remain viewer-specific.
126+
gatewayClientSessionCreator(client)?.id ?? null,
127+
isGatewayAdmin(client) ? "admin" : (operatorSessionCap(client, config) ?? null),
141128
Object.entries(params).toSorted(([left], [right]) => left.localeCompare(right)),
142129
]);
143130
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { expect, vi } from "vitest";
2+
import type { SessionsListParams } from "../../../packages/gateway-protocol/src/index.js";
3+
import type { OpenClawConfig } from "../../config/types.openclaw.js";
4+
import type { GatewaySessionRow } from "../session-utils.types.js";
5+
import { sessionReadHandlers } from "./sessions-read.js";
6+
import type { GatewayClient, GatewayRequestContext, RespondFn } from "./types.js";
7+
8+
export { sessionReadHandlers };
9+
10+
export function identifiedClient(profileId: string): GatewayClient {
11+
return {
12+
connect: {
13+
minProtocol: 1,
14+
maxProtocol: 1,
15+
client: { id: "openclaw-control-ui", version: "test", platform: "test", mode: "webchat" },
16+
role: "operator",
17+
scopes: ["operator.read", "operator.write"],
18+
},
19+
authenticatedUserProfile: {
20+
profileId,
21+
displayName: profileId,
22+
hasAvatar: false,
23+
updatedAt: 1,
24+
},
25+
};
26+
}
27+
28+
export function requestContext(config: OpenClawConfig): GatewayRequestContext {
29+
return {
30+
chatAbortControllers: new Map(),
31+
getRuntimeConfig: () => config,
32+
getSessionEventSubscriberConnIds: () => new Set(),
33+
loadGatewayModelCatalog: async () => [],
34+
logGateway: { debug: vi.fn() },
35+
} as unknown as GatewayRequestContext;
36+
}
37+
38+
export async function listSessions(params: {
39+
client: GatewayClient;
40+
context: GatewayRequestContext;
41+
request: SessionsListParams;
42+
}) {
43+
const responses: Parameters<RespondFn>[] = [];
44+
await sessionReadHandlers["sessions.list"]?.({
45+
params: params.request,
46+
client: params.client,
47+
context: params.context,
48+
respond: (...response: Parameters<RespondFn>) => responses.push(response),
49+
} as never);
50+
expect(responses).toHaveLength(1);
51+
expect(responses[0]?.[0]).toBe(true);
52+
return responses[0]?.[1] as {
53+
count: number;
54+
nextOffset: number | null;
55+
sessions: GatewaySessionRow[];
56+
totalCount: number;
57+
};
58+
}

‎src/gateway/server-methods/sessions-read-cache.test.ts‎

Lines changed: 43 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,14 @@ import { withOpenClawTestState } from "../../test-utils/openclaw-test-state.js";
3333
import { invalidateOperatorRolePolicy } from "../operator-role-policy.js";
3434
import { bumpSessionAutomationVersion } from "../session-automation-index.js";
3535
import { persistGatewaySessionLifecycleEvent } from "../session-lifecycle-state.js";
36-
import type { GatewaySessionRow } from "../session-utils.types.js";
3736
import type { WorkerSessionPlacementRecord } from "../worker-environments/placement-store.js";
38-
import type { GatewayClient, GatewayRequestContext, RespondFn } from "./types.js";
37+
import {
38+
identifiedClient,
39+
listSessions,
40+
requestContext,
41+
sessionReadHandlers,
42+
} from "./sessions-read-cache.test-support.js";
43+
import type { GatewayRequestContext } from "./types.js";
3944

4045
const loader = vi.hoisted(() => ({
4146
calls: vi.fn(),
@@ -68,60 +73,9 @@ vi.mock("../session-utils.js", async (importOriginal) => {
6873
};
6974
});
7075

71-
const { sessionReadHandlers } = await import("./sessions-read.js");
7276
const { emitSessionsChanged } = await import("./session-change-event.js");
7377
const { emitSessionTranscriptUpdate } = await import("../../sessions/transcript-events.js");
7478

75-
function identifiedClient(profileId: string): GatewayClient {
76-
return {
77-
connect: {
78-
minProtocol: 1,
79-
maxProtocol: 1,
80-
client: { id: "openclaw-control-ui", version: "test", platform: "test", mode: "webchat" },
81-
role: "operator",
82-
scopes: ["operator.read", "operator.write"],
83-
},
84-
authenticatedUserProfile: {
85-
profileId,
86-
displayName: profileId,
87-
hasAvatar: false,
88-
updatedAt: 1,
89-
},
90-
};
91-
}
92-
93-
function requestContext(config: OpenClawConfig): GatewayRequestContext {
94-
return {
95-
chatAbortControllers: new Map(),
96-
getRuntimeConfig: () => config,
97-
getSessionEventSubscriberConnIds: () => new Set(),
98-
loadGatewayModelCatalog: async () => [],
99-
logGateway: { debug: vi.fn() },
100-
} as unknown as GatewayRequestContext;
101-
}
102-
103-
async function listSessions(params: {
104-
client: GatewayClient;
105-
context: GatewayRequestContext;
106-
request: SessionsListParams;
107-
}) {
108-
const responses: Parameters<RespondFn>[] = [];
109-
await sessionReadHandlers["sessions.list"]?.({
110-
params: params.request,
111-
client: params.client,
112-
context: params.context,
113-
respond: (...response: Parameters<RespondFn>) => responses.push(response),
114-
} as never);
115-
expect(responses).toHaveLength(1);
116-
expect(responses[0]?.[0]).toBe(true);
117-
return responses[0]?.[1] as {
118-
count: number;
119-
nextOffset: number | null;
120-
sessions: GatewaySessionRow[];
121-
totalCount: number;
122-
};
123-
}
124-
12579
async function seedSessions(): Promise<OpenClawConfig> {
12680
const config: OpenClawConfig = {
12781
agents: { list: [{ id: "main", default: true }, { id: "work" }] },
@@ -938,6 +892,42 @@ describe("sessions.list single-flight", () => {
938892
});
939893
});
940894

895+
it.each(["ownerFirst", "involvingMe"] as const)(
896+
"keeps administrator %s projections scoped to their authenticated profiles",
897+
async (projection) => {
898+
await withOpenClawTestState({ scenario: "minimal" }, async () => {
899+
const config: OpenClawConfig = { agents: { list: [{ id: "main", default: true }] } };
900+
const context = requestContext(config);
901+
const clients = ["[email protected]", "[email protected]"].map((email) => {
902+
const client = identifiedClient(ensureProfileForEmail(email).id);
903+
client.connect.scopes = ["operator.admin"];
904+
return client;
905+
});
906+
for (const [index, client] of clients.entries()) {
907+
await upsertSessionEntryCore(
908+
{ agentId: "main", sessionKey: `agent:main:profile-${index}` },
909+
{
910+
sessionId: `profile-${index}`,
911+
updatedAt: index + 1,
912+
createdActor: { type: "human", id: client.authenticatedUserProfile!.profileId },
913+
},
914+
);
915+
}
916+
const request: SessionsListParams = { agentId: "main", limit: 1, [projection]: true };
917+
918+
const results = await Promise.all(
919+
clients.map((client) => listSessions({ client, context, request })),
920+
);
921+
922+
for (const [index, client] of clients.entries()) {
923+
expect(results[index]?.sessions[0]?.key).toBe(`agent:main:profile-${index}`);
924+
expect(await listSessions({ client, context, request })).toBe(results[index]);
925+
}
926+
expect(loader.calls).toHaveBeenCalledTimes(2);
927+
});
928+
},
929+
);
930+
941931
it("fences cached rows across client identities and operator-role changes", async () => {
942932
await withOpenClawTestState({ scenario: "minimal" }, async () => {
943933
const config = await seedSessions();

0 commit comments

Comments
 (0)