Repository navigation
Session management improvements and dashboard API - #50101
Conversation
Greptile SummaryThis is a large, multi-faceted PR spanning session lifecycle management, dashboard APIs, real-time WebSocket events, cost tracking, and auth changes. The broad scope touches 100 files across the gateway, agent runtime, and config layers. The overall direction is well-considered — changing the default idle policy to "never reset" (via Key observations:
Confidence Score: 3/5
Prompt To Fix All With AIThis is a comment left during a code review.
Path: src/gateway/server-close.ts
Line: 27
Comment:
**`lifecycleUnsub` is not cleaned up on gateway shutdown**
`server.impl.ts` creates a `lifecycleUnsub` via `onSessionLifecycleEvent` (line 856) and passes it to `createGatewayCloseHandler` (line 1210), but `createGatewayCloseHandler`'s params type only added `transcriptUnsub` — `lifecycleUnsub` is absent from the type definition and has no corresponding cleanup block.
As a result, the `SESSION_LIFECYCLE_LISTENERS` set in `session-lifecycle-events.ts` will retain the listener after gateway shutdown. Beyond the memory leak this creates a risk of stale closures firing against a partially-torn-down server.
To fix, add `lifecycleUnsub` alongside the existing `transcriptUnsub`:
```suggestion
transcriptUnsub: (() => void) | null;
lifecycleUnsub: (() => void) | null;
```
And add a corresponding cleanup block in the shutdown body (after the `transcriptUnsub` block):
```typescript
if (params.lifecycleUnsub) {
try {
params.lifecycleUnsub();
} catch {
/* ignore */
}
}
```
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: src/gateway/sessions-history-http.ts
Line: 107-112
Comment:
**`hasMore: true` can be returned without a `nextCursor`**
`paginateSessionMessages` sets `hasMore: start > 0` unconditionally, but `nextCursor` is only included when `firstSeq` is a number:
```typescript
...(start > 0 && typeof firstSeq === "number" ? { nextCursor: String(firstSeq) } : {}),
```
If the first message in the returned page lacks seq metadata (i.e. `resolveMessageSeq(items[0])` returns `undefined`), the response will have `{ hasMore: true }` with no `nextCursor`. Any client that uses `nextCursor` to paginate to the previous page will be unable to do so, silently dropping history.
Consider either guaranteeing that all messages have seq metadata before this path is reached, or falling back to an index-based cursor when `firstSeq` is unavailable:
```typescript
...(start > 0
? { nextCursor: typeof firstSeq === "number" ? String(firstSeq) : String(start) }
: {}),
```
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: src/gateway/session-transcript-key.ts
Line: 24-51
Comment:
**O(n) session-store scan on every transcript update**
`resolveSessionKeyForTranscriptFile` does a full linear scan over the entire combined session store, calling `resolveGatewaySessionStoreTarget` and `resolveSessionTranscriptCandidates` for every session entry on each invocation. It is called from the hot `onSessionTranscriptUpdate` handler in `server.impl.ts` whenever `update.sessionKey` is missing.
With a large session store (hundreds of long-running sessions), this will block the event loop noticeably on each transcript append. Consider caching the `sessionFile → sessionKey` lookup or ensuring that `update.sessionKey` is always provided so this fallback is never reached in the common path.
How can I resolve this? If you propose a fix, please make it concise.Last reviewed commit: "feat: change default..." |
| @@ -24,6 +24,7 @@ export function createGatewayCloseHandler(params: { | |||
| mediaCleanup: ReturnType<typeof setInterval> | null; | |||
| agentUnsub: (() => void) | null; | |||
| heartbeatUnsub: (() => void) | null; | |||
| transcriptUnsub: (() => void) | null; | |||
There was a problem hiding this comment.
lifecycleUnsub is not cleaned up on gateway shutdown
server.impl.ts creates a lifecycleUnsub via onSessionLifecycleEvent (line 856) and passes it to createGatewayCloseHandler (line 1210), but createGatewayCloseHandler's params type only added transcriptUnsub — lifecycleUnsub is absent from the type definition and has no corresponding cleanup block.
As a result, the SESSION_LIFECYCLE_LISTENERS set in session-lifecycle-events.ts will retain the listener after gateway shutdown. Beyond the memory leak this creates a risk of stale closures firing against a partially-torn-down server.
To fix, add lifecycleUnsub alongside the existing transcriptUnsub:
| transcriptUnsub: (() => void) | null; | |
| transcriptUnsub: (() => void) | null; | |
| lifecycleUnsub: (() => void) | null; |
And add a corresponding cleanup block in the shutdown body (after the transcriptUnsub block):
if (params.lifecycleUnsub) {
try {
params.lifecycleUnsub();
} catch {
/* ignore */
}
}Prompt To Fix With AI
This is a comment left during a code review.
Path: src/gateway/server-close.ts
Line: 27
Comment:
**`lifecycleUnsub` is not cleaned up on gateway shutdown**
`server.impl.ts` creates a `lifecycleUnsub` via `onSessionLifecycleEvent` (line 856) and passes it to `createGatewayCloseHandler` (line 1210), but `createGatewayCloseHandler`'s params type only added `transcriptUnsub` — `lifecycleUnsub` is absent from the type definition and has no corresponding cleanup block.
As a result, the `SESSION_LIFECYCLE_LISTENERS` set in `session-lifecycle-events.ts` will retain the listener after gateway shutdown. Beyond the memory leak this creates a risk of stale closures firing against a partially-torn-down server.
To fix, add `lifecycleUnsub` alongside the existing `transcriptUnsub`:
```suggestion
transcriptUnsub: (() => void) | null;
lifecycleUnsub: (() => void) | null;
```
And add a corresponding cleanup block in the shutdown body (after the `transcriptUnsub` block):
```typescript
if (params.lifecycleUnsub) {
try {
params.lifecycleUnsub();
} catch {
/* ignore */
}
}
```
How can I resolve this? If you propose a fix, please make it concise.| return { | ||
| items, | ||
| messages: items, | ||
| hasMore: start > 0, | ||
| ...(start > 0 && typeof firstSeq === "number" ? { nextCursor: String(firstSeq) } : {}), | ||
| }; |
There was a problem hiding this comment.
hasMore: true can be returned without a nextCursor
paginateSessionMessages sets hasMore: start > 0 unconditionally, but nextCursor is only included when firstSeq is a number:
...(start > 0 && typeof firstSeq === "number" ? { nextCursor: String(firstSeq) } : {}),If the first message in the returned page lacks seq metadata (i.e. resolveMessageSeq(items[0]) returns undefined), the response will have { hasMore: true } with no nextCursor. Any client that uses nextCursor to paginate to the previous page will be unable to do so, silently dropping history.
Consider either guaranteeing that all messages have seq metadata before this path is reached, or falling back to an index-based cursor when firstSeq is unavailable:
...(start > 0
? { nextCursor: typeof firstSeq === "number" ? String(firstSeq) : String(start) }
: {}),Prompt To Fix With AI
This is a comment left during a code review.
Path: src/gateway/sessions-history-http.ts
Line: 107-112
Comment:
**`hasMore: true` can be returned without a `nextCursor`**
`paginateSessionMessages` sets `hasMore: start > 0` unconditionally, but `nextCursor` is only included when `firstSeq` is a number:
```typescript
...(start > 0 && typeof firstSeq === "number" ? { nextCursor: String(firstSeq) } : {}),
```
If the first message in the returned page lacks seq metadata (i.e. `resolveMessageSeq(items[0])` returns `undefined`), the response will have `{ hasMore: true }` with no `nextCursor`. Any client that uses `nextCursor` to paginate to the previous page will be unable to do so, silently dropping history.
Consider either guaranteeing that all messages have seq metadata before this path is reached, or falling back to an index-based cursor when `firstSeq` is unavailable:
```typescript
...(start > 0
? { nextCursor: typeof firstSeq === "number" ? String(firstSeq) : String(start) }
: {}),
```
How can I resolve this? If you propose a fix, please make it concise.| export function resolveSessionKeyForTranscriptFile(sessionFile: string): string | undefined { | ||
| const targetPath = resolveTranscriptPathForComparison(sessionFile); | ||
| if (!targetPath) { | ||
| return undefined; | ||
| } | ||
| const cfg = loadConfig(); | ||
| const { store } = loadCombinedSessionStoreForGateway(cfg); | ||
| for (const [key, entry] of Object.entries(store)) { | ||
| if (!entry?.sessionId) { | ||
| continue; | ||
| } | ||
| const target = resolveGatewaySessionStoreTarget({ | ||
| cfg, | ||
| key, | ||
| scanLegacyKeys: false, | ||
| store, | ||
| }); | ||
| const sessionAgentId = normalizeAgentId(target.agentId); | ||
| const matches = resolveSessionTranscriptCandidates( | ||
| entry.sessionId, | ||
| target.storePath, | ||
| entry.sessionFile, | ||
| sessionAgentId, | ||
| ).some((candidate) => resolveTranscriptPathForComparison(candidate) === targetPath); | ||
| if (matches) { | ||
| return key; | ||
| } | ||
| } |
There was a problem hiding this comment.
O(n) session-store scan on every transcript update
resolveSessionKeyForTranscriptFile does a full linear scan over the entire combined session store, calling resolveGatewaySessionStoreTarget and resolveSessionTranscriptCandidates for every session entry on each invocation. It is called from the hot onSessionTranscriptUpdate handler in server.impl.ts whenever update.sessionKey is missing.
With a large session store (hundreds of long-running sessions), this will block the event loop noticeably on each transcript append. Consider caching the sessionFile → sessionKey lookup or ensuring that update.sessionKey is always provided so this fallback is never reached in the common path.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/gateway/session-transcript-key.ts
Line: 24-51
Comment:
**O(n) session-store scan on every transcript update**
`resolveSessionKeyForTranscriptFile` does a full linear scan over the entire combined session store, calling `resolveGatewaySessionStoreTarget` and `resolveSessionTranscriptCandidates` for every session entry on each invocation. It is called from the hot `onSessionTranscriptUpdate` handler in `server.impl.ts` whenever `update.sessionKey` is missing.
With a large session store (hundreds of long-running sessions), this will block the event loop noticeably on each transcript append. Consider caching the `sessionFile → sessionKey` lookup or ensuring that `update.sessionKey` is always provided so this fallback is never reached in the common path.
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 00d052a661
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| "sessions.create", | ||
| "sessions.send", | ||
| "sessions.abort", |
There was a problem hiding this comment.
Classify sessions.steer as operator write method
sessions.steer is implemented in sessionsHandlers, but it is not added to METHOD_SCOPE_GROUPS. Because authorizeOperatorScopesForMethod falls back unclassified methods to operator.admin, any client connected with least-privilege operator.write scopes will be blocked from steering with a missing scope: operator.admin error, even though sessions.send/sessions.abort are write-level operations in the same flow.
Useful? React with 👍 / 👎.
| "sessions.create", | ||
| "sessions.send", | ||
| "sessions.abort", |
There was a problem hiding this comment.
Advertise sessions.steer in gateway feature method list
The gateway now supports sessions.steer, but listGatewayMethods() does not include it in the advertised method set. Since hello payloads expose features.methods from this list, capability-aware clients can conclude steering is unsupported and skip calling the RPC despite the handler existing, creating a protocol/feature-discovery mismatch.
Useful? React with 👍 / 👎.
Transcript-update broadcasts were serialized behind one global promise queue, so one session's pending async seq read head-of-line blocked every other session's session.message and sessions.changed delivery. Ordering is a per-transcript contract, so key the queue by transcript identity and drop drained lanes. Per-message transcript usage stays derived: session.message payloads carry live totalTokens/estimatedCostUsd as a dashboard API contract (#50101).
* perf(gateway): per-transcript broadcast lanes Transcript-update broadcasts were serialized behind one global promise queue, so one session's pending async seq read head-of-line blocked every other session's session.message and sessions.changed delivery. Ordering is a per-transcript contract, so key the queue by transcript identity and drop drained lanes. Per-message transcript usage stays derived: session.message payloads carry live totalTokens/estimatedCostUsd as a dashboard API contract (#50101). * fix(ui): target the Cloud Worker Desktop labs row in its toggle test The row added in #120727 reused index 6, which belongs to Message audit metadata, so the case toggled the audit row and asserted its patch. Labs features render in registry order, and workerDesktop is the eighth entry.
* perf(gateway): per-transcript broadcast lanes Transcript-update broadcasts were serialized behind one global promise queue, so one session's pending async seq read head-of-line blocked every other session's session.message and sessions.changed delivery. Ordering is a per-transcript contract, so key the queue by transcript identity and drop drained lanes. Per-message transcript usage stays derived: session.message payloads carry live totalTokens/estimatedCostUsd as a dashboard API contract (openclaw#50101). * fix(ui): target the Cloud Worker Desktop labs row in its toggle test The row added in openclaw#120727 reused index 6, which belongs to Message audit metadata, so the case toggled the audit row and asserted its patch. Labs features render in registry order, and workerDesktop is the eighth entry.
* fix: make cleanup "keep" persist subagent sessions indefinitely * feat: expose subagent session metadata in sessions list * fix: include status and timing in sessions_list tool * fix: hide injected timestamp prefixes in chat ui * feat: push session list updates over websocket * feat: expose child subagent sessions in subagents list * feat: add admin http endpoint to kill sessions * Emit session.message websocket events for transcript updates * Estimate session costs in sessions list * Add direct session history HTTP and SSE endpoints * Harden dashboard session events and history APIs * Add session lifecycle gateway methods * Add dashboard session API improvements * Add dashboard session model and parent linkage support * fix: tighten dashboard session API metadata * Fix dashboard session cost metadata * Persist accumulated session cost * fix: stop followup queue drain cfg crash * Fix dashboard session create and model metadata * fix: stop guessing session model costs * Gateway: cache OpenRouter pricing for configured models * Gateway: add timeout session status * Fix subagent spawn test config loading * Gateway: preserve operator scopes without device identity * Emit user message transcript events and deduplicate plugin warnings * feat: emit sessions.changed lifecycle event on subagent spawn Adds a session-lifecycle-events module (similar to transcript-events) that emits create events when subagents are spawned. The gateway server.impl.ts listens for these events and broadcasts sessions.changed with reason=create to SSE subscribers, so dashboards can pick up new subagent sessions without polling. * Gateway: allow persistent dashboard orchestrator sessions * fix: preserve operator scopes for token-authenticated backend clients Backend clients (like agent-dashboard) that authenticate with a valid gateway token but don't present a device identity were getting their scopes stripped. The scope-clearing logic ran before checking the device identity decision, so even when evaluateMissingDeviceIdentity returned 'allow' (because roleCanSkipDeviceIdentity passed for token-authed operators), scopes were already cleared. Fix: also check decision.kind before clearing scopes, so token-authenticated operators keep their requested scopes. * Gateway: allow operator-token session kills * Fix stale active subagent status after follow-up runs * Fix dashboard image attachments in sessions send * Fix completed session follow-up status updates * feat: stream session tool events to operator UIs * Add sessions.steer gateway coverage * Persist subagent timing in session store * Fix subagent session transcript event keys * Fix active subagent session status in gateway * bump session label max to 512 * Fix gateway send session reactivation * fix: publish terminal session lifecycle state * feat: change default session reset to effectively never - Change DEFAULT_RESET_MODE from "daily" to "idle" - Change DEFAULT_IDLE_MINUTES from 60 to 0 (0 = disabled/never) - Allow idleMinutes=0 through normalization (don't clamp to 1) - Treat idleMinutes=0 as "no idle expiry" in evaluateSessionFreshness - Default behavior: mode "idle" + idleMinutes 0 = sessions never auto-reset - Update test assertion for new default mode * fix: prep session management followups (openclaw#50101) (thanks @clay-datacurve) --------- Co-authored-by: Tyler Yust <[email protected]>
* fix: make cleanup "keep" persist subagent sessions indefinitely * feat: expose subagent session metadata in sessions list * fix: include status and timing in sessions_list tool * fix: hide injected timestamp prefixes in chat ui * feat: push session list updates over websocket * feat: expose child subagent sessions in subagents list * feat: add admin http endpoint to kill sessions * Emit session.message websocket events for transcript updates * Estimate session costs in sessions list * Add direct session history HTTP and SSE endpoints * Harden dashboard session events and history APIs * Add session lifecycle gateway methods * Add dashboard session API improvements * Add dashboard session model and parent linkage support * fix: tighten dashboard session API metadata * Fix dashboard session cost metadata * Persist accumulated session cost * fix: stop followup queue drain cfg crash * Fix dashboard session create and model metadata * fix: stop guessing session model costs * Gateway: cache OpenRouter pricing for configured models * Gateway: add timeout session status * Fix subagent spawn test config loading * Gateway: preserve operator scopes without device identity * Emit user message transcript events and deduplicate plugin warnings * feat: emit sessions.changed lifecycle event on subagent spawn Adds a session-lifecycle-events module (similar to transcript-events) that emits create events when subagents are spawned. The gateway server.impl.ts listens for these events and broadcasts sessions.changed with reason=create to SSE subscribers, so dashboards can pick up new subagent sessions without polling. * Gateway: allow persistent dashboard orchestrator sessions * fix: preserve operator scopes for token-authenticated backend clients Backend clients (like agent-dashboard) that authenticate with a valid gateway token but don't present a device identity were getting their scopes stripped. The scope-clearing logic ran before checking the device identity decision, so even when evaluateMissingDeviceIdentity returned 'allow' (because roleCanSkipDeviceIdentity passed for token-authed operators), scopes were already cleared. Fix: also check decision.kind before clearing scopes, so token-authenticated operators keep their requested scopes. * Gateway: allow operator-token session kills * Fix stale active subagent status after follow-up runs * Fix dashboard image attachments in sessions send * Fix completed session follow-up status updates * feat: stream session tool events to operator UIs * Add sessions.steer gateway coverage * Persist subagent timing in session store * Fix subagent session transcript event keys * Fix active subagent session status in gateway * bump session label max to 512 * Fix gateway send session reactivation * fix: publish terminal session lifecycle state * feat: change default session reset to effectively never - Change DEFAULT_RESET_MODE from "daily" to "idle" - Change DEFAULT_IDLE_MINUTES from 60 to 0 (0 = disabled/never) - Allow idleMinutes=0 through normalization (don't clamp to 1) - Treat idleMinutes=0 as "no idle expiry" in evaluateSessionFreshness - Default behavior: mode "idle" + idleMinutes 0 = sessions never auto-reset - Update test assertion for new default mode * fix: prep session management followups (openclaw#50101) (thanks @clay-datacurve) --------- Co-authored-by: Tyler Yust <[email protected]>
* fix: make cleanup "keep" persist subagent sessions indefinitely * feat: expose subagent session metadata in sessions list * fix: include status and timing in sessions_list tool * fix: hide injected timestamp prefixes in chat ui * feat: push session list updates over websocket * feat: expose child subagent sessions in subagents list * feat: add admin http endpoint to kill sessions * Emit session.message websocket events for transcript updates * Estimate session costs in sessions list * Add direct session history HTTP and SSE endpoints * Harden dashboard session events and history APIs * Add session lifecycle gateway methods * Add dashboard session API improvements * Add dashboard session model and parent linkage support * fix: tighten dashboard session API metadata * Fix dashboard session cost metadata * Persist accumulated session cost * fix: stop followup queue drain cfg crash * Fix dashboard session create and model metadata * fix: stop guessing session model costs * Gateway: cache OpenRouter pricing for configured models * Gateway: add timeout session status * Fix subagent spawn test config loading * Gateway: preserve operator scopes without device identity * Emit user message transcript events and deduplicate plugin warnings * feat: emit sessions.changed lifecycle event on subagent spawn Adds a session-lifecycle-events module (similar to transcript-events) that emits create events when subagents are spawned. The gateway server.impl.ts listens for these events and broadcasts sessions.changed with reason=create to SSE subscribers, so dashboards can pick up new subagent sessions without polling. * Gateway: allow persistent dashboard orchestrator sessions * fix: preserve operator scopes for token-authenticated backend clients Backend clients (like agent-dashboard) that authenticate with a valid gateway token but don't present a device identity were getting their scopes stripped. The scope-clearing logic ran before checking the device identity decision, so even when evaluateMissingDeviceIdentity returned 'allow' (because roleCanSkipDeviceIdentity passed for token-authed operators), scopes were already cleared. Fix: also check decision.kind before clearing scopes, so token-authenticated operators keep their requested scopes. * Gateway: allow operator-token session kills * Fix stale active subagent status after follow-up runs * Fix dashboard image attachments in sessions send * Fix completed session follow-up status updates * feat: stream session tool events to operator UIs * Add sessions.steer gateway coverage * Persist subagent timing in session store * Fix subagent session transcript event keys * Fix active subagent session status in gateway * bump session label max to 512 * Fix gateway send session reactivation * fix: publish terminal session lifecycle state * feat: change default session reset to effectively never - Change DEFAULT_RESET_MODE from "daily" to "idle" - Change DEFAULT_IDLE_MINUTES from 60 to 0 (0 = disabled/never) - Allow idleMinutes=0 through normalization (don't clamp to 1) - Treat idleMinutes=0 as "no idle expiry" in evaluateSessionFreshness - Default behavior: mode "idle" + idleMinutes 0 = sessions never auto-reset - Update test assertion for new default mode * fix: prep session management followups (openclaw#50101) (thanks @clay-datacurve) --------- Co-authored-by: Tyler Yust <[email protected]>
Summary
Comprehensive session management improvements spanning subagent lifecycle, dashboard APIs, real-time events, cost tracking, and default reset behavior.
Changes
Session Reset Defaults
dailytoidleDEFAULT_IDLE_MINUTESto0(meaning disabled/never reset)idleMinutes=0as "no idle expiry" — sessions never auto-reset by defaultDashboard Session API
sessions.create,sessions.send, etc.)Real-time Events & WebSocket
session.messagewebsocket events for transcript updatessessions.changedlifecycle event on subagent spawnSubagent Session Management
cleanup: "keep"persist subagent sessions indefinitelysessions.steergateway coverageCost Tracking
Session Lifecycle & State
Auth & Security
Misc Fixes
sessions_listtoolCommits (42)