perf(hub,web): emit structured patches for session todos/teamState/metadata/agentState writes (closes #895, second half of #884) (#897)

* perf(hub,web): emit structured patches for session todos/teamState/metadata/agentState writes (#895, closes second half of #884)

Today the four CLI handlers in `sessionHandlers.ts` that write session-scoped
state (TodoWrite messages -> setSessionTodos; team-state deltas ->
setSessionTeamState; update-metadata RPC; update-state RPC) emit
`session-updated` events with no `data` payload. `syncEngine.handleRealtimeEvent`
intercepts each one, re-reads the row from SQLite, and broadcasts the entire
~5KB Session via SSE. That works (the web client's `isSessionRecord` shortcut
keeps the cache patched), but it costs a DB read and a full-payload SSE
fan-out per write, and any failure mode that drops the broadcast data falls
through to `useSSE.ts:509-512` and triggers per-session REST refetches - the
storm vector documented in #884.

This is the architectural follow-up to #885. #885 added `staleTime` on the
detail query (eliminates focus / mount refetches inside a 30s window). This
PR removes the structural reason these four writes touch the REST path at all.

`SessionPatchSchema` learns four optional structured fields:
- `todos` (array)
- `teamState` (object)
- `metadata` (versioned `{ version, value }` wrapper)
- `agentState` (versioned `{ version, value }` wrapper)

`.strict()` preserved so unknown keys still throw. The versioned wrappers
mirror the existing socket.io `update-session` broadcast at lines 211 / 259 so
metadata and agentState always travel as an atomic (version, value) pair -
caches need the version to reject stale patches.

Each of the four emit-sites now carries a structured `data` payload with the
delta it just wrote. `syncEngine.handleRealtimeEvent` for `session-updated`
events with non-empty patch data: applies the patch to the in-memory Session
in place via the new `sessionCache.applySessionPatch`, then forwards the event
as-is. Empty patches, no-data events, and patches against uncached sessions
all fall back to the legacy `refreshSession` path so behavior for other
emitters (e.g. `cursor/codexDesktop.ts`) is unchanged. Dedup hook against
agent-session-id changes preserved on the fast path.

`patchSessionDetail` is no longer a blanket spread - it enumerates each field
explicitly so the versioned metadata / agentState patches can be unwrapped
into the Session's flat (metadata, metadataVersion) and (agentState,
agentStateVersion) pairs. Spreading the patch wholesale would have written a
`{ version, value }` object into `session.metadata` and corrupted the cache.

`patchSessionSummary` recomputes the touched derivations - `todoProgress` from
todos, `pendingRequestsCount` / `pendingRequestKinds` from agentState,
SessionSummaryMetadata from metadata - via three new pure helpers exposed
from `shared/src/sessionSummary.ts` (`computeTodoProgress`,
`computePendingRequestKinds`, `toSessionSummaryMetadata`). `toSessionSummary`
is refactored to use these helpers - identical output, single source of
truth.

- shared: `SessionPatchSchema` parses each new patch shape, stays strict,
  rejects empty metadata without `version`, rejects full Session payloads
  (those go through `isSessionRecord`).
- shared: summary derivation helpers covered against bare AgentState /
  Metadata inputs (the shape the SSE patch path provides).
- hub: each emit-site asserted to carry the expected structured payload.
- hub: `applySessionPatch` unit-tests cover todos / metadata / agentState
  application, empty-patch rejection (forces caller back to refreshSession),
  cross-namespace guard, and missing-session fallback.

Empirical wire round-trip verifies each patch shape survives `JSON.stringify`
intact and routes the web client through `getSessionPatch` (non-empty result)
instead of the REST invalidation fallback.

Per #884 expectation: with this fix on top of #885, idle GET /api/sessions/<id>
rate is expected to drop to near-zero on the reporter's 100+ session install.
Operator (heavygee) will attach the live-measured before / after to the PR
post-merge.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(hub): snapshot metadata reference before applySessionPatch mutation so dedup-on-id-change fires

The structured-patch fast path added in 05147a6a (closes #884 second half)
broke the dedup-on-metadata-change trigger in handleRealtimeEvent.

Root cause: applySessionPatch MUTATES the cached Session in place
(reassigns session.metadata = patch.metadata.value). The dedup check
compares before vs after agent session IDs, but `before = getSession(id)`
and `after = getSession(id)` returned the SAME object reference, so
before.metadata had already been overwritten by the time the check ran.
hasSameAgentSessionIds always returned true and dedup silently never
fired on the fast path.

The legacy refreshSession path got dedup for free because it REPLACES
the cache map entry with a new Session object, leaving the pre-refresh
reference intact for the comparator.

Fix: capture beforeMetadata before applySessionPatch runs; use it for
both branches so the comparison contract is identical.

Adds syncEngineHandleRealtimeEvent.test.ts with three regression guards:
- structured metadata patch with changed cursorSessionId fires dedup
- todos-only patch does NOT fire dedup (no false positives)
- legacy refresh path (no patch data) still fires dedup

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(schemas): reorder SessionPatchSchema fields so soup-merge with codex-usage layer conflicts cleanly

Pure reorder (no semantic change). feat/codex-usage-indicator-rebased adds
a flat `metadata: MetadataSchema.nullable().optional()` + `metadataVersion`
to SessionPatchSchema in the same line range upstream/main has the model/
modelReasoningEffort fields. My branch added the versioned `metadata` field
at the END of the object, so git 3-way merge silently auto-merged both,
producing an invalid object literal with duplicate `metadata` keys.

By placing my `metadata` / `agentState` / `todos` / `teamState` insertions
in the SAME line range codex inserts (between updatedAt and model), git
now raises an explicit CONFLICT during the soup merge, which can be
resolved correctly once and replayed by rerere. No behavior change on a
clean upstream/main merge.

Pure cosmetic; no test or runtime impact.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(sse): propagate TeamDelete clear through structured patch path

Closes PR #897 Major review (HAPI Bot, 2026-06-13): TeamDelete events
drove `applyTeamStateDelta` to return `null`, but the emit-site
coalesced that to `undefined`. JSON serialization then dropped the key,
the hub cache skipped its assignment branch (`patch.teamState !==
undefined` was false), and the web client saw an empty patch and fell
back to REST invalidation — exactly the storm path this PR was supposed
to close. Sidebar / NotificationHub / dedup all served stale team state
until the next full refresh.

Fix in four coordinated places (wire ↔ cache contract):

- shared/src/schemas.ts: `teamState: TeamStateSchema.nullable().optional()`
  so `null` is a valid wire shape meaning "cleared". Comment documents
  the discriminator contract for consumers.
- hub/src/socket/handlers/cli/sessionHandlers.ts: drop the
  `?? undefined` coalesce so `null` survives JSON serialization.
- hub/src/sync/sessionCache.ts (applySessionPatch): use
  `Object.prototype.hasOwnProperty.call(patch, 'teamState')` to
  discriminate "field absent" from "field is null", then map null →
  undefined to match the cached `Session.teamState` type.
- web/src/hooks/useSSE.ts (patchSessionDetail): same
  hasOwnProperty discriminator + null → undefined mapping.

Regression tests:

- schemas.sessionPatch.test.ts: `{ teamState: null }` parses
  successfully (locks the wire contract).
- sessionCache.applySessionPatch.test.ts: TeamDelete clears cached
  teamState; todos-only patch leaves teamState untouched (guards the
  hasOwnProperty branch against a regression back to `!== undefined`).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(sse): version-gate metadata/agentState patches against cache regression

Closes PR #897 follow-up Major review (HAPI Bot, 2026-06-16): the new
structured SSE patch path unwraps versioned metadata/agentState fields
without checking the cached metadataVersion/agentStateVersion. SSE
reconnects + the existing per-query invalidation can leave a detail
cache repopulated by a fresh REST refetch BEFORE a buffered older patch
replays. Without the gate the older patch overwrites the newer cache,
regressing resume / session-id / pending-requests state.

Mirrors the hub-side CLI room handler contract (`incoming.version >
currentVersion`, `web/src/hooks/useSSE.ts`):

- `patchSessionDetail`: gate metadata/agentState assignment behind
  `isNewerVersionedPatch(patch.version, nextSession.<field>Version)`.
  The pre-patch version is captured by `{ ...previous.session }` so
  the comparison is against the cache-at-write-time.
- `patchSessionSummary`: read the detail cache (via queryClient) for
  the canonical metadataVersion / agentStateVersion. Use `>=` (not `>`)
  because the callsite runs `patchSessionDetail` first — when detail
  accepts a newer patch the cache already holds the new version, so
  matching `>=` keeps summary aligned with detail's acceptance; when
  detail rejects, `>=` aligns summary with detail's rejection.
- Exported `isNewerVersionedPatch(patchVersion, currentVersion)` as a
  pure helper so the rule is unit-testable in isolation.
- Test: `useSSE.test.ts` pins the 4 cases (newer ✓ / older ✗ /
  same-version ✗ / first-write currentVersion=0 ✓).

Hub-side `applySessionPatch` does NOT need the same gate: in-process
events from `handleUpdateMetadata` / `handleUpdateState` are emitted
only AFTER the optimistic-concurrency check at the store layer
succeeds, and `syncEngine.handleRealtimeEvent` consumes them
synchronously in order. The vulnerability is the SSE
reconnect/replay window on the web client.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(sse): include updatedAt in structured patches + pendingRequests summary

Closes PR #897 post-rebase bot review (HAPI Bot, 2026-06-18):

Major — structured patches dropped session.updatedAt. TodoWrite,
teamState, metadata, and agentState DB writes all touch sessions.updated_at,
but the fast path forwarded only field deltas. Hub/web caches and session
list ordering stayed stale until a full refresh. All four emit-sites in
sessionHandlers now reload the stored row after a successful write and
include updatedAt in the SSE patch payload (applySessionPatch already
applies it via Math.max).

Minor — agentState summary patches updated pendingRequestsCount/kinds but
left pendingRequests stale, so SessionAttentionIndicator tooltips showed
old request tools after an SSE patch. patchSessionSummary now uses
computePendingRequestsCount + computePendingRequests alongside the
existing kinds helper.

Tests: sessionHandlers.test.ts asserts updatedAt on todos/metadata/agentState
patches.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web,hub): apply serviceTier in structured session patch path

Closes PR #897 bot Minor (2026-06-18): field-by-field patchSessionDetail
stopped copying serviceTier after the spread refactor, so Codex Fast/
Standard could show stale tier until a full refetch. Mirror nullable
hasOwnProperty handling in patchSessionDetail and hub applySessionPatch.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(hub): allow same-ms updatedAt on structured patch emit asserts

Date.now() resolution makes create+update land on the same millisecond in
unit tests; the store still touches updated_at. Use >= so CI is not flaky.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): refuse versioned summary SSE patches without detail version source

When session detail is not cached, defaulting metadata/agentState versions to
0 let stale buffered patches overwrite a freshly refetched list and suppress
list invalidation. Bail out so the list refetches instead.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): keep updatedAt monotonic when applying SSE session patches

Stale versioned metadata/agentState replays can still carry an older
updatedAt. Use Math.max on detail and summary paths so rejected replays
cannot rewind list/detail clocks while patched=true suppresses invalidation.

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore: retrigger Codex PR review after infra stream failure

Prior pr-review run died on reconnect (stream closed before
response.completed); no code findings. Empty commit to re-fire
pull_request_target.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): compare all summary metadata fields in keep-alive skip

isRenderIrrelevantPatch omitted path/machineId/flavor/worktree, so a
same-ms metadata patch could be dropped while summaryPatched stayed true
and list invalidation never repaired grouping/icon/path.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(sse): version-wrap todos/teamState patches for dual-SSE races

Global + session EventSources can deliver out of order. Carry store
todos_updated_at / team_state_updated_at as patch versions, gate web
applies, and tighten keep-alive skip compares (metadata + request tool/kind).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): put SSE version watermarks on SessionSummary

Requiring a detail query to apply versioned list patches forced O(N)
/sessions invalidation on every global SSE write. Gate against summary
watermarks instead; skip no-op detail clones on duplicate deliveries.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(hub): ratchet todosUpdatedAt on rewind rebuild

replaceSessionTodos was stamping the remaining TodoWrite's older
createdAt, so a lagged pre-rewind structured SSE patch could resurrect
deleted todos. Advance the watermark on force-replace instead.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): apply copilotAgentMode in structured detail SSE patches

Field-by-field detail mapper dropped the new Copilot keep-alive field,
so detailPatched suppressed invalidation and SessionChat kept a stale mode.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Debian <heavygee@oos-linux.in.lockhouse>
This commit is contained in:
HeavyGee
2026-08-04 10:59:35 +08:00
committed by GitHub
co-authored by Cursor Debian
parent 3c83fe58c9
commit 8e34e7599b
21 changed files with 1428 additions and 87 deletions
+104
View File
@@ -0,0 +1,104 @@
import { describe, expect, it } from 'vitest';
import { SessionPatchSchema } from './schemas';
// Guard the contract for the second-half-of-#884 fix. The web client routes
// `session-updated` events to the structured-patch path only when the event's
// `data` parses as a SessionPatch — these tests pin the schema shape so a
// future refactor that drops `.strict()`, the versioned (version, value)
// wrappers, or any of the new optional fields breaks the build instead of
// silently re-introducing the refetch storm.
describe('SessionPatchSchema structured patches (closes #884 follow-up)', () => {
it('parses a versioned todos patch', () => {
const parsed = SessionPatchSchema.safeParse({
todos: {
version: 10,
value: [{ content: 'thing', status: 'pending' }]
}
});
expect(parsed.success).toBe(true);
});
it('rejects bare todos without a version (dual-SSE watermark required)', () => {
const parsed = SessionPatchSchema.safeParse({
todos: [{ content: 'thing', status: 'pending' }]
});
expect(parsed.success).toBe(false);
});
it('parses a versioned teamState patch', () => {
const parsed = SessionPatchSchema.safeParse({
teamState: {
version: 11,
value: {
teamName: 'crew',
members: [{ name: 'one' }]
}
}
});
expect(parsed.success).toBe(true);
});
it('parses a teamState clear patch (null value = TeamDelete)', () => {
// PR #897 review (HAPI Bot, 2026-06-13 Major + 2026-07-30 Major):
// teamState travels as { version, value }; value null clears the
// cached row. Version gates dual-SSE reordering.
const parsed = SessionPatchSchema.safeParse({
teamState: { version: 12, value: null }
});
expect(parsed.success).toBe(true);
if (parsed.success) {
expect(parsed.data.teamState?.value).toBeNull();
}
});
it('parses a versioned metadata patch', () => {
const parsed = SessionPatchSchema.safeParse({
metadata: {
version: 7,
value: { path: '/tmp', host: 'h' }
}
});
expect(parsed.success).toBe(true);
});
it('parses a versioned agentState patch with null value', () => {
const parsed = SessionPatchSchema.safeParse({
agentState: { version: 3, value: null }
});
expect(parsed.success).toBe(true);
});
it('rejects metadata without a version (must stay versioned for cache safety)', () => {
const parsed = SessionPatchSchema.safeParse({
metadata: { value: { path: '/tmp', host: 'h' } }
});
expect(parsed.success).toBe(false);
});
it('stays strict and rejects unknown keys (catches silent .strict() removal)', () => {
const parsed = SessionPatchSchema.safeParse({
todos: { version: 1, value: [] },
notARealField: true
});
expect(parsed.success).toBe(false);
});
it('rejects a full Session payload (full-session SSE goes through isSessionRecord instead)', () => {
const fullSession = {
id: 's1',
namespace: 'default',
seq: 1,
createdAt: 1,
updatedAt: 1,
active: true,
activeAt: 1,
metadata: null,
metadataVersion: 0,
agentState: null,
agentStateVersion: 0,
thinking: false,
thinkingAt: 0
};
expect(SessionPatchSchema.safeParse(fullSession).success).toBe(false);
});
});
+47
View File
@@ -295,6 +295,12 @@ export const SessionSchema = z.object({
backgroundTaskCount: z.number().optional(),
todos: TodosSchema.optional(),
teamState: TeamStateSchema.optional(),
// Watermarks for structured SSE patches (PR #897). Dual EventSource
// connections can deliver todos/teamState out of order; caches reject
// stale patches with version <= these fields. Optional so older
// full-session payloads and hand-built Session literals stay valid.
todosUpdatedAt: z.number().optional(),
teamStateUpdatedAt: z.number().optional(),
model: z.string().nullable().optional().default(null),
modelReasoningEffort: z.string().nullable().optional().default(null),
effort: z.string().nullable().optional().default(null),
@@ -306,11 +312,52 @@ export const SessionSchema = z.object({
export type Session = z.infer<typeof SessionSchema>
// Versioned wrappers mirror the socket.io `update-session` broadcast shape so
// metadata/agentState always travel as an atomic (version, value) pair — the
// version is the only safe way for downstream caches to reject stale patches.
const VersionedMetadataPatchSchema = z.object({
version: z.number(),
value: MetadataSchema.nullable()
})
const VersionedAgentStatePatchSchema = z.object({
version: z.number(),
value: AgentStateSchema.nullable()
})
// Same dual-SSE race as metadata/agentState: global + session EventSources
// have no shared order. Version = store `todos_updated_at` /
// `team_state_updated_at`. Normal TodoWrite / team writes stamp message
// `createdAt`; rewind/fork `replaceSessionTodos` ratchets the watermark
// so a lagged pre-rewind patch cannot resurrect deleted todos.
const VersionedTodosPatchSchema = z.object({
version: z.number(),
value: TodosSchema
})
const VersionedTeamStatePatchSchema = z.object({
version: z.number(),
// `null` value = TeamDelete clear. Discriminator remains "key present".
value: TeamStateSchema.nullable()
})
export const SessionPatchSchema = z.object({
active: z.boolean().optional(),
thinking: z.boolean().optional(),
activeAt: z.number().optional(),
updatedAt: z.number().optional(),
// Structured-patch fields for the second half of #884. Letting the four
// hub-side emit-sites in cli/sessionHandlers.ts (todos, teamState,
// metadata, agentState writes) carry their delta means the web client's
// SSE handler can patch the cache in place instead of falling through to
// the invalidation fallback that triggers per-session REST refetches.
// Versioned wrappers for metadata/agentState mirror the socket.io
// `update-session` broadcast shape — the version field is the only safe
// way for downstream caches to reject stale patches.
metadata: VersionedMetadataPatchSchema.optional(),
agentState: VersionedAgentStatePatchSchema.optional(),
todos: VersionedTodosPatchSchema.optional(),
teamState: VersionedTeamStatePatchSchema.optional(),
model: z.string().nullable().optional(),
modelReasoningEffort: z.string().nullable().optional(),
effort: z.string().nullable().optional(),
+54 -1
View File
@@ -2,9 +2,13 @@ import { describe, expect, it } from 'bun:test'
import type { Session } from './schemas'
import {
PENDING_REQUEST_SUMMARY_CAP,
computePendingRequestKinds,
computePendingRequestsCount,
computeTodoProgress,
getPendingRequestKinds,
getPendingRequests,
toSessionSummary
toSessionSummary,
toSessionSummaryMetadata
} from './sessionSummary'
function makeSession(overrides: Partial<Session> = {}): Session {
@@ -259,3 +263,52 @@ describe('getPendingRequestKinds', () => {
expect(kinds).toEqual(['permission', 'input'])
})
})
// The SSE patch path (useSSE.ts patchSessionSummary) calls these directly
// against the patch payload — no full Session needed — to keep the session
// list summary consistent with structured todos/teamState/metadata/agentState
// patches landing for the second half of #884.
describe('summary derivation helpers', () => {
it('computeTodoProgress returns null for empty / undefined todos', () => {
expect(computeTodoProgress(undefined)).toBeNull()
expect(computeTodoProgress([])).toBeNull()
})
it('computeTodoProgress counts completed vs total', () => {
const progress = computeTodoProgress([
{ content: 'a', status: 'pending', priority: 'medium', id: '1' },
{ content: 'b', status: 'completed', priority: 'medium', id: '2' },
{ content: 'c', status: 'completed', priority: 'medium', id: '3' }
])
expect(progress).toEqual({ completed: 2, total: 3 })
})
it('computePendingRequestKinds works on a bare AgentState without a Session', () => {
const kinds = computePendingRequestKinds({
requests: {
req1: { tool: 'Bash', arguments: {} },
req2: { tool: 'AskUserQuestion', arguments: {} }
}
})
expect(kinds).toEqual(['permission', 'input'])
})
it('computePendingRequestsCount handles null agentState', () => {
expect(computePendingRequestsCount(null)).toBe(0)
expect(computePendingRequestsCount(undefined)).toBe(0)
})
it('toSessionSummaryMetadata returns null for null metadata', () => {
expect(toSessionSummaryMetadata(null)).toBeNull()
expect(toSessionSummaryMetadata(undefined)).toBeNull()
})
it('toSessionSummaryMetadata derives agentSessionId from the first non-null source id', () => {
const summary = toSessionSummaryMetadata({
path: '/p',
host: 'h',
cursorSessionId: 'cursor-xyz'
})
expect(summary?.agentSessionId).toBe('cursor-xyz')
})
})
+92 -55
View File
@@ -1,4 +1,4 @@
import type { Metadata, Session, WorktreeMetadata } from './schemas'
import type { AgentState, Metadata, Session, TodoItem, WorktreeMetadata } from './schemas'
import { isKnownFlavor } from './flavors'
import type { AgentFlavor } from './modes'
@@ -22,8 +22,9 @@ export type PendingRequest = {
id: string
kind: PendingRequestKind
tool: string
/** Epoch ms when the request was raised; falls back to `session.updatedAt`
* for older requests that were stored without `createdAt`. */
/** Epoch ms when the request was raised; falls back to the caller-supplied
* `fallbackSince` (typically `session.updatedAt`) for older requests
* stored without `createdAt`. */
since: number
}
@@ -49,6 +50,12 @@ export type SessionSummary = {
activeAt: number
updatedAt: number
metadata: SessionSummaryMetadata | null
/** Watermarks for structured SSE patches (PR #897). List cache must gate
* without requiring a detail query — otherwise global SSE forces O(N)
* /sessions invalidation for every versioned write. */
metadataVersion: number
agentStateVersion: number
todosUpdatedAt: number
todoProgress: { completed: number; total: number } | null
pendingRequestsCount: number
pendingRequestKinds: PendingRequestKind[]
@@ -65,35 +72,11 @@ export type SessionSummary = {
effort: string | null
}
export function getPendingRequests(
session: Session,
cap: number = PENDING_REQUEST_SUMMARY_CAP
): PendingRequest[] {
const requests = session.agentState?.requests
if (!requests) {
return []
}
const items: PendingRequest[] = []
for (const [id, request] of Object.entries(requests)) {
items.push({
id,
kind: classifyKind(request.tool),
tool: request.tool,
since: typeof request.createdAt === 'number' ? request.createdAt : session.updatedAt
})
}
items.sort((a, b) => {
if (a.since !== b.since) return a.since - b.since
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0
})
return cap >= items.length ? items : items.slice(0, cap)
}
export function getPendingRequestKinds(session: Session): PendingRequestKind[] {
const requests = session.agentState?.requests
// Re-exported as a standalone derivation so SSE patch handlers can recompute
// summary fields from a structured `agentState` patch without needing the
// full Session in hand.
export function computePendingRequestKinds(agentState: AgentState | null | undefined): PendingRequestKind[] {
const requests = agentState?.requests
if (!requests) {
return []
}
@@ -108,6 +91,59 @@ export function getPendingRequestKinds(session: Session): PendingRequestKind[] {
: Array.from(kinds)
}
export function computePendingRequests(
agentState: AgentState | null | undefined,
fallbackSince: number,
cap: number = PENDING_REQUEST_SUMMARY_CAP
): PendingRequest[] {
const requests = agentState?.requests
if (!requests) {
return []
}
const items: PendingRequest[] = []
for (const [id, request] of Object.entries(requests)) {
items.push({
id,
kind: classifyKind(request.tool),
tool: request.tool,
since: typeof request.createdAt === 'number' ? request.createdAt : fallbackSince
})
}
items.sort((a, b) => {
if (a.since !== b.since) return a.since - b.since
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0
})
return cap >= items.length ? items : items.slice(0, cap)
}
export function getPendingRequestKinds(session: Session): PendingRequestKind[] {
return computePendingRequestKinds(session.agentState)
}
export function getPendingRequests(
session: Session,
cap: number = PENDING_REQUEST_SUMMARY_CAP
): PendingRequest[] {
return computePendingRequests(session.agentState, session.updatedAt, cap)
}
export function computePendingRequestsCount(agentState: AgentState | null | undefined): number {
return agentState?.requests ? Object.keys(agentState.requests).length : 0
}
export function computeTodoProgress(todos: TodoItem[] | undefined): SessionSummary['todoProgress'] {
if (!todos?.length) {
return null
}
return {
completed: todos.filter((todo) => todo.status === 'completed').length,
total: todos.length
}
}
const AGENT_SESSION_ID_FIELD_BY_FLAVOR = {
claude: 'claudeSessionId',
codex: 'codexSessionId',
@@ -144,36 +180,37 @@ function getSummaryAgentSessionId(metadata: Metadata): string | undefined {
?? undefined
}
export function toSessionSummaryMetadata(metadata: Metadata | null | undefined): SessionSummaryMetadata | null {
if (!metadata) {
return null
}
return {
name: metadata.name,
path: metadata.path,
machineId: metadata.machineId ?? undefined,
summary: metadata.summary ? { text: metadata.summary.text } : undefined,
flavor: metadata.flavor ?? null,
worktree: metadata.worktree,
agentSessionId: getSummaryAgentSessionId(metadata),
lifecycleState: metadata.lifecycleState
}
}
export function toSessionSummary(session: Session): SessionSummary {
const pendingRequestsCount = session.agentState?.requests ? Object.keys(session.agentState.requests).length : 0
const metadata: SessionSummaryMetadata | null = session.metadata ? {
name: session.metadata.name,
path: session.metadata.path,
machineId: session.metadata.machineId ?? undefined,
summary: session.metadata.summary ? { text: session.metadata.summary.text } : undefined,
flavor: session.metadata.flavor ?? null,
worktree: session.metadata.worktree,
agentSessionId: getSummaryAgentSessionId(session.metadata),
lifecycleState: session.metadata.lifecycleState
} : null
const todoProgress = session.todos?.length ? {
completed: session.todos.filter(t => t.status === 'completed').length,
total: session.todos.length
} : null
return {
id: session.id,
active: session.active,
thinking: session.thinking,
activeAt: session.activeAt,
updatedAt: session.updatedAt,
metadata,
todoProgress,
pendingRequestsCount,
pendingRequestKinds: getPendingRequestKinds(session),
pendingRequests: getPendingRequests(session),
metadata: toSessionSummaryMetadata(session.metadata),
metadataVersion: session.metadataVersion,
agentStateVersion: session.agentStateVersion,
todosUpdatedAt: session.todosUpdatedAt ?? 0,
todoProgress: computeTodoProgress(session.todos),
pendingRequestsCount: computePendingRequestsCount(session.agentState),
pendingRequestKinds: computePendingRequestKinds(session.agentState),
pendingRequests: computePendingRequests(session.agentState, session.updatedAt),
backgroundTaskCount: session.backgroundTaskCount ?? 0,
futureScheduledMessageCount: 0,
nextScheduledAt: null,