mirror of
https://github.com/wu736139669/hapi.git
synced 2026-08-05 06:24:37 +00:00
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:
co-authored by
Cursor
Debian
parent
3c83fe58c9
commit
8e34e7599b
@@ -19,6 +19,9 @@ function makeSummary(overrides: Partial<SessionSummary> & { id: string }): Sessi
|
||||
activeAt: 0,
|
||||
updatedAt: 0,
|
||||
metadata: null,
|
||||
metadataVersion: 0,
|
||||
agentStateVersion: 0,
|
||||
todosUpdatedAt: 0,
|
||||
todoProgress: null,
|
||||
pendingRequestsCount: 0,
|
||||
pendingRequestKinds: [],
|
||||
|
||||
@@ -20,6 +20,9 @@ function makeSession(overrides: Partial<SessionSummary> & { id: string }): Sessi
|
||||
activeAt: 0,
|
||||
updatedAt: 0,
|
||||
metadata: null,
|
||||
metadataVersion: 0,
|
||||
agentStateVersion: 0,
|
||||
todosUpdatedAt: 0,
|
||||
todoProgress: null,
|
||||
pendingRequestsCount: 0,
|
||||
pendingRequestKinds: [],
|
||||
|
||||
@@ -16,6 +16,9 @@ function makeSession(overrides: Partial<SessionSummary> & { id: string }): Sessi
|
||||
activeAt: 0,
|
||||
updatedAt: 0,
|
||||
metadata: null,
|
||||
metadataVersion: 0,
|
||||
agentStateVersion: 0,
|
||||
todosUpdatedAt: 0,
|
||||
todoProgress: null,
|
||||
pendingRequestsCount: 0,
|
||||
pendingRequestKinds: [],
|
||||
|
||||
@@ -28,6 +28,9 @@ function makeSession(overrides: Partial<SessionSummary> & { id: string }): Sessi
|
||||
activeAt: 0,
|
||||
updatedAt: 0,
|
||||
metadata: null,
|
||||
metadataVersion: 0,
|
||||
agentStateVersion: 0,
|
||||
todosUpdatedAt: 0,
|
||||
todoProgress: null,
|
||||
pendingRequestsCount: 0,
|
||||
pendingRequestKinds: [],
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { SessionSummary } from '@/types/api'
|
||||
import type { Session } from '@/types/api'
|
||||
import { isGlobalScopedMessageStreamEvent, isRenderIrrelevantPatch, isRenderIrrelevantSessionPatch, shouldInvalidateSessionListForEvent } from './useSSE'
|
||||
import {
|
||||
applySessionDetailPatch,
|
||||
canApplyVersionedSummaryPatch,
|
||||
isGlobalScopedMessageStreamEvent,
|
||||
isNewerVersionedPatch,
|
||||
isRenderIrrelevantPatch,
|
||||
isRenderIrrelevantSessionPatch,
|
||||
shouldInvalidateSessionListForEvent
|
||||
} from './useSSE'
|
||||
|
||||
function makeSummary(overrides: Partial<SessionSummary> = {}): SessionSummary {
|
||||
return {
|
||||
@@ -11,6 +19,9 @@ function makeSummary(overrides: Partial<SessionSummary> = {}): SessionSummary {
|
||||
activeAt: 1_000,
|
||||
updatedAt: 2_000,
|
||||
metadata: null,
|
||||
metadataVersion: 0,
|
||||
agentStateVersion: 0,
|
||||
todosUpdatedAt: 0,
|
||||
todoProgress: null,
|
||||
pendingRequestsCount: 0,
|
||||
pendingRequestKinds: [],
|
||||
@@ -24,6 +35,81 @@ function makeSummary(overrides: Partial<SessionSummary> = {}): SessionSummary {
|
||||
} as SessionSummary
|
||||
}
|
||||
|
||||
describe('canApplyVersionedSummaryPatch (PR #897 review, HAPI Bot 2026-07-23 Major)', () => {
|
||||
it('allows non-versioned patches without a detail cache', () => {
|
||||
expect(canApplyVersionedSummaryPatch({}, false)).toBe(true)
|
||||
expect(canApplyVersionedSummaryPatch({ metadata: undefined, agentState: undefined }, false)).toBe(true)
|
||||
})
|
||||
|
||||
it('refuses metadata/agentState/todos summary patches when detail version source is missing', () => {
|
||||
expect(
|
||||
canApplyVersionedSummaryPatch(
|
||||
{ metadata: { version: 1, value: null } },
|
||||
false
|
||||
)
|
||||
).toBe(false)
|
||||
expect(
|
||||
canApplyVersionedSummaryPatch(
|
||||
{ agentState: { version: 1, value: null } },
|
||||
false
|
||||
)
|
||||
).toBe(false)
|
||||
expect(
|
||||
canApplyVersionedSummaryPatch(
|
||||
{ todos: { version: 1, value: [] } },
|
||||
false
|
||||
)
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('allows teamState-only patches without detail (summary no-op)', () => {
|
||||
expect(
|
||||
canApplyVersionedSummaryPatch(
|
||||
{ teamState: { version: 1, value: null } },
|
||||
false
|
||||
)
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('allows versioned summary patches when detail is present', () => {
|
||||
expect(
|
||||
canApplyVersionedSummaryPatch(
|
||||
{ metadata: { version: 2, value: null } },
|
||||
true
|
||||
)
|
||||
).toBe(true)
|
||||
expect(
|
||||
canApplyVersionedSummaryPatch(
|
||||
{ todos: { version: 2, value: [] } },
|
||||
true
|
||||
)
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isNewerVersionedPatch (PR #897 review, HAPI Bot 2026-06-16 Major)', () => {
|
||||
// Pin the version-monotonicity contract for structured metadata /
|
||||
// agentState patches. Without this gate, an SSE reconnect that replays
|
||||
// a buffered older patch after a fresh REST refetch would regress the
|
||||
// cache (e.g. drop a newer resume id / pending request). Mirrors the
|
||||
// hub's CLI room handler check (`incoming.version > currentVersion`).
|
||||
it('accepts a strictly newer patch', () => {
|
||||
expect(isNewerVersionedPatch(5, 4)).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects an older patch (the bug case: stale buffered patch on reconnect)', () => {
|
||||
expect(isNewerVersionedPatch(4, 5)).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects a same-version patch (idempotent / duplicate replay)', () => {
|
||||
expect(isNewerVersionedPatch(5, 5)).toBe(false)
|
||||
})
|
||||
|
||||
it('accepts the first write into a freshly-cached session (currentVersion=0)', () => {
|
||||
expect(isNewerVersionedPatch(1, 0)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useSSE scope handling', () => {
|
||||
it('invalidates the global session list when message ownership changes', () => {
|
||||
expect(shouldInvalidateSessionListForEvent('global', 'messages-invalidated')).toBe(true)
|
||||
@@ -68,7 +154,21 @@ describe('isRenderIrrelevantPatch', () => {
|
||||
['model', { model: 'opus' }],
|
||||
['modelReasoningEffort', { modelReasoningEffort: 'high' }],
|
||||
['effort', { effort: 'medium' }],
|
||||
['pendingRequestsCount', { pendingRequestsCount: 2 }]
|
||||
['pendingRequestsCount', { pendingRequestsCount: 2 }],
|
||||
['metadata.path', { metadata: { path: '/other', name: undefined } }],
|
||||
['metadata.flavor', { metadata: { path: '/tmp', flavor: 'claude' as const } }],
|
||||
['metadata.machineId', { metadata: { path: '/tmp', machineId: 'Teemo' } }],
|
||||
['metadata.worktree.branch', {
|
||||
metadata: {
|
||||
path: '/tmp',
|
||||
worktree: {
|
||||
basePath: '/tmp',
|
||||
branch: 'feat/x',
|
||||
name: 'x',
|
||||
worktreePath: '/tmp/x'
|
||||
}
|
||||
}
|
||||
}]
|
||||
] as Array<[string, Partial<SessionSummary>]>)('reports %s changes as relevant', (_field, change) => {
|
||||
const current = makeSummary()
|
||||
const next = makeSummary({ ...change, activeAt: 11_000 })
|
||||
@@ -138,3 +238,47 @@ describe('isRenderIrrelevantSessionPatch', () => {
|
||||
expect(isRenderIrrelevantSessionPatch(session, {})).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('applySessionDetailPatch (PR #897 review, Copilot keep-alive)', () => {
|
||||
const session = {
|
||||
id: 'session-1',
|
||||
active: true,
|
||||
thinking: false,
|
||||
activeAt: 1_000,
|
||||
updatedAt: 2_000,
|
||||
model: 'gpt-5',
|
||||
effort: null,
|
||||
permissionMode: 'default',
|
||||
collaborationMode: undefined,
|
||||
copilotAgentMode: 'interactive',
|
||||
serviceTier: null,
|
||||
metadataVersion: 1,
|
||||
agentStateVersion: 1,
|
||||
todosUpdatedAt: 0,
|
||||
teamStateUpdatedAt: 0
|
||||
} as unknown as Session
|
||||
|
||||
it('applies a copilotAgentMode keep-alive change to the detail session', () => {
|
||||
// Hub emits copilotAgentMode from markSessionActive keep-alives. The
|
||||
// field-by-field mapper must copy it — otherwise detailPatched=true
|
||||
// suppresses invalidation and SessionChat keeps the stale mode.
|
||||
const next = applySessionDetailPatch(session, {
|
||||
active: true,
|
||||
thinking: false,
|
||||
activeAt: 11_000,
|
||||
copilotAgentMode: 'plan'
|
||||
})
|
||||
expect(next).not.toBeNull()
|
||||
expect(next?.copilotAgentMode).toBe('plan')
|
||||
expect(next?.activeAt).toBe(11_000)
|
||||
})
|
||||
|
||||
it('returns null for a keep-alive that only repeats the current Copilot mode', () => {
|
||||
expect(applySessionDetailPatch(session, {
|
||||
active: true,
|
||||
thinking: false,
|
||||
activeAt: 11_000,
|
||||
copilotAgentMode: 'interactive'
|
||||
})).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
+172
-7
@@ -1,6 +1,14 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { isObject, toSessionSummary } from '@hapi/protocol'
|
||||
import {
|
||||
computePendingRequestKinds,
|
||||
computePendingRequests,
|
||||
computePendingRequestsCount,
|
||||
computeTodoProgress,
|
||||
isObject,
|
||||
toSessionSummary,
|
||||
toSessionSummaryMetadata
|
||||
} from '@hapi/protocol'
|
||||
import { MachinePatchSchema, MachineSchema, SessionPatchSchema, SessionSchema } from '@hapi/protocol/schemas'
|
||||
import type {
|
||||
Machine,
|
||||
@@ -38,6 +46,36 @@ export function shouldInvalidateSessionListForEvent(scope: SSEScope, eventType:
|
||||
return scope === 'global' && eventType === 'messages-invalidated'
|
||||
}
|
||||
|
||||
// Version-monotonicity gate for structured patches carrying metadata or
|
||||
// agentState. SSE reconnects + per-query invalidation can leave the cache
|
||||
// holding state that's NEWER than a buffered older patch about to replay;
|
||||
// applying that older patch would regress resume / session-id / pending-
|
||||
// requests state. Mirrors the CLI room handler contract: strictly newer
|
||||
// only. Exported so the rule is unit-testable in isolation from the hook.
|
||||
export function isNewerVersionedPatch(patchVersion: number, currentVersion: number): boolean {
|
||||
return patchVersion > currentVersion
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Prefer gating against SessionSummary watermarks. Kept for unit
|
||||
* tests of the old "detail required" rule; summary path no longer uses this
|
||||
* for metadata/agentState/todos (teamState is a summary no-op).
|
||||
*/
|
||||
export function canApplyVersionedSummaryPatch(
|
||||
patch: Pick<SessionPatch, 'metadata' | 'agentState' | 'todos' | 'teamState'>,
|
||||
detailPresent: boolean
|
||||
): boolean {
|
||||
// teamState is not rendered on SessionSummary — never block list patches.
|
||||
if (
|
||||
patch.metadata === undefined
|
||||
&& patch.agentState === undefined
|
||||
&& patch.todos === undefined
|
||||
) {
|
||||
return true
|
||||
}
|
||||
return detailPresent
|
||||
}
|
||||
|
||||
type VisibilityState = 'visible' | 'hidden'
|
||||
|
||||
type ToastEvent = Extract<SyncEvent, { type: 'toast' }>
|
||||
@@ -89,6 +127,69 @@ export function isRenderIrrelevantSessionPatch(session: Session, patch: SessionP
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a validated SessionPatch onto a detail Session. Returns null when
|
||||
* nothing render-relevant changed (keep prior object identity). Field-by-field
|
||||
* only — never wholesale-spread versioned `{ version, value }` wrappers.
|
||||
* Exported for unit tests (Copilot mode keep-alive must not be dropped).
|
||||
*/
|
||||
export function applySessionDetailPatch(session: Session, patch: SessionPatch): Session | null {
|
||||
if (isRenderIrrelevantSessionPatch(session, patch)) {
|
||||
return null
|
||||
}
|
||||
let changed = false
|
||||
const nextSession: Session = { ...session }
|
||||
const assign = <K extends keyof Session>(key: K, value: Session[K]) => {
|
||||
if (nextSession[key] !== value) {
|
||||
nextSession[key] = value
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (patch.active !== undefined) assign('active', patch.active)
|
||||
if (patch.thinking !== undefined) assign('thinking', patch.thinking)
|
||||
if (patch.activeAt !== undefined) assign('activeAt', patch.activeAt)
|
||||
// Monotonic with hub applySessionPatch: a rejected stale
|
||||
// metadata/agentState replay must not rewind updatedAt.
|
||||
if (patch.updatedAt !== undefined) {
|
||||
const nextUpdatedAt = Math.max(nextSession.updatedAt, patch.updatedAt)
|
||||
assign('updatedAt', nextUpdatedAt)
|
||||
}
|
||||
if (patch.model !== undefined) assign('model', patch.model)
|
||||
if (patch.modelReasoningEffort !== undefined) assign('modelReasoningEffort', patch.modelReasoningEffort)
|
||||
if (patch.effort !== undefined) assign('effort', patch.effort)
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'serviceTier')) {
|
||||
assign('serviceTier', patch.serviceTier ?? null)
|
||||
}
|
||||
if (patch.permissionMode !== undefined) assign('permissionMode', patch.permissionMode)
|
||||
if (patch.collaborationMode !== undefined) assign('collaborationMode', patch.collaborationMode)
|
||||
if (patch.copilotAgentMode !== undefined) assign('copilotAgentMode', patch.copilotAgentMode)
|
||||
if (patch.backgroundTaskCount !== undefined) assign('backgroundTaskCount', patch.backgroundTaskCount)
|
||||
// Version gates: dual SSE can deliver duplicates out of order.
|
||||
// Only mark changed when a strictly newer version lands —
|
||||
// otherwise keep previous object identity (no redundant render).
|
||||
if (patch.todos !== undefined && isNewerVersionedPatch(patch.todos.version, nextSession.todosUpdatedAt ?? 0)) {
|
||||
nextSession.todos = patch.todos.value
|
||||
nextSession.todosUpdatedAt = patch.todos.version
|
||||
changed = true
|
||||
}
|
||||
if (patch.teamState !== undefined && isNewerVersionedPatch(patch.teamState.version, nextSession.teamStateUpdatedAt ?? 0)) {
|
||||
nextSession.teamState = patch.teamState.value ?? undefined
|
||||
nextSession.teamStateUpdatedAt = patch.teamState.version
|
||||
changed = true
|
||||
}
|
||||
if (patch.metadata !== undefined && isNewerVersionedPatch(patch.metadata.version, nextSession.metadataVersion)) {
|
||||
nextSession.metadata = patch.metadata.value
|
||||
nextSession.metadataVersion = patch.metadata.version
|
||||
changed = true
|
||||
}
|
||||
if (patch.agentState !== undefined && isNewerVersionedPatch(patch.agentState.version, nextSession.agentStateVersion)) {
|
||||
nextSession.agentState = patch.agentState.value
|
||||
nextSession.agentStateVersion = patch.agentState.version
|
||||
changed = true
|
||||
}
|
||||
return changed ? nextSession : null
|
||||
}
|
||||
|
||||
function isSessionRecord(value: unknown): value is Session {
|
||||
return SessionSchema.safeParse(value).success
|
||||
}
|
||||
@@ -102,6 +203,30 @@ function isSessionRecord(value: unknown): value is Session {
|
||||
* `updatedAt` and sorts on active/pendingRequestsCount/updatedAt - so storing
|
||||
* it costs a new object identity and a full list re-render for nothing.
|
||||
*/
|
||||
export function sameSessionSummaryMetadata(
|
||||
current: SessionSummary['metadata'],
|
||||
next: SessionSummary['metadata']
|
||||
): boolean {
|
||||
if (current === next) {
|
||||
return true
|
||||
}
|
||||
if (current == null || next == null) {
|
||||
return current == null && next == null
|
||||
}
|
||||
return current.name === next.name
|
||||
&& current.path === next.path
|
||||
&& current.machineId === next.machineId
|
||||
&& current.summary?.text === next.summary?.text
|
||||
&& current.flavor === next.flavor
|
||||
&& current.agentSessionId === next.agentSessionId
|
||||
&& current.lifecycleState === next.lifecycleState
|
||||
&& current.worktree?.basePath === next.worktree?.basePath
|
||||
&& current.worktree?.branch === next.worktree?.branch
|
||||
&& current.worktree?.name === next.worktree?.name
|
||||
&& current.worktree?.worktreePath === next.worktree?.worktreePath
|
||||
&& current.worktree?.createdAt === next.worktree?.createdAt
|
||||
}
|
||||
|
||||
export function isRenderIrrelevantPatch(current: SessionSummary, next: SessionSummary): boolean {
|
||||
return current.active === next.active
|
||||
&& current.thinking === next.thinking
|
||||
@@ -111,6 +236,25 @@ export function isRenderIrrelevantPatch(current: SessionSummary, next: SessionSu
|
||||
&& current.modelReasoningEffort === next.modelReasoningEffort
|
||||
&& current.effort === next.effort
|
||||
&& current.pendingRequestsCount === next.pendingRequestsCount
|
||||
// Structured SSE patches (#897) can move these without touching the
|
||||
// keep-alive fields above; omit them and a todos/metadata/agentState
|
||||
// patch would be dropped as "activeAt-only" churn.
|
||||
&& current.todoProgress?.completed === next.todoProgress?.completed
|
||||
&& current.todoProgress?.total === next.todoProgress?.total
|
||||
&& (current.todoProgress == null) === (next.todoProgress == null)
|
||||
&& current.pendingRequestKinds.length === next.pendingRequestKinds.length
|
||||
&& current.pendingRequestKinds.every((kind, i) => kind === next.pendingRequestKinds[i])
|
||||
&& current.pendingRequests.length === next.pendingRequests.length
|
||||
&& current.pendingRequests.every((req, i) => {
|
||||
const nextReq = next.pendingRequests[i]
|
||||
return req.id === nextReq?.id
|
||||
&& req.kind === nextReq.kind
|
||||
&& req.tool === nextReq.tool
|
||||
})
|
||||
&& sameSessionSummaryMetadata(current.metadata, next.metadata)
|
||||
&& current.metadataVersion === next.metadataVersion
|
||||
&& current.agentStateVersion === next.agentStateVersion
|
||||
&& current.todosUpdatedAt === next.todosUpdatedAt
|
||||
}
|
||||
|
||||
function getSessionPatch(value: unknown): SessionPatch | null {
|
||||
@@ -412,7 +556,11 @@ export function useSSE(options: {
|
||||
active: patch.active ?? current.active,
|
||||
thinking: patch.thinking ?? current.thinking,
|
||||
activeAt: patch.activeAt ?? current.activeAt,
|
||||
updatedAt: patch.updatedAt ?? current.updatedAt,
|
||||
// Monotonic: stale versioned-patch replays can carry an
|
||||
// older updatedAt; never move the list clock backward.
|
||||
updatedAt: patch.updatedAt !== undefined
|
||||
? Math.max(current.updatedAt, patch.updatedAt)
|
||||
: current.updatedAt,
|
||||
backgroundTaskCount: Object.prototype.hasOwnProperty.call(patch, 'backgroundTaskCount')
|
||||
? patch.backgroundTaskCount ?? 0
|
||||
: current.backgroundTaskCount,
|
||||
@@ -423,6 +571,25 @@ export function useSSE(options: {
|
||||
effort: Object.prototype.hasOwnProperty.call(patch, 'effort') ? patch.effort ?? null : current.effort
|
||||
}
|
||||
|
||||
// Gate versioned fields against THIS summary's watermarks —
|
||||
// not the detail query. Global SSE covers every session;
|
||||
// requiring detail would force O(N) /sessions invalidation.
|
||||
// teamState is a summary no-op (not rendered on the list).
|
||||
if (patch.todos !== undefined && patch.todos.version >= current.todosUpdatedAt) {
|
||||
nextSummary.todoProgress = computeTodoProgress(patch.todos.value)
|
||||
nextSummary.todosUpdatedAt = patch.todos.version
|
||||
}
|
||||
if (patch.agentState !== undefined && patch.agentState.version >= current.agentStateVersion) {
|
||||
nextSummary.pendingRequestsCount = computePendingRequestsCount(patch.agentState.value)
|
||||
nextSummary.pendingRequestKinds = computePendingRequestKinds(patch.agentState.value)
|
||||
nextSummary.pendingRequests = computePendingRequests(patch.agentState.value, nextSummary.updatedAt)
|
||||
nextSummary.agentStateVersion = patch.agentState.version
|
||||
}
|
||||
if (patch.metadata !== undefined && patch.metadata.version >= current.metadataVersion) {
|
||||
nextSummary.metadata = toSessionSummaryMetadata(patch.metadata.value)
|
||||
nextSummary.metadataVersion = patch.metadata.version
|
||||
}
|
||||
|
||||
patched = true
|
||||
// The keep-alive patch repeats every field every ~10s per active
|
||||
// session, and `activeAt` is the only one that actually moves.
|
||||
@@ -445,15 +612,13 @@ export function useSSE(options: {
|
||||
return previous
|
||||
}
|
||||
patched = true
|
||||
if (isRenderIrrelevantSessionPatch(previous.session, patch)) {
|
||||
const nextSession = applySessionDetailPatch(previous.session, patch)
|
||||
if (!nextSession) {
|
||||
return previous
|
||||
}
|
||||
return {
|
||||
...previous,
|
||||
session: {
|
||||
...previous.session,
|
||||
...patch
|
||||
}
|
||||
session: nextSession
|
||||
}
|
||||
})
|
||||
return patched
|
||||
|
||||
@@ -9,6 +9,9 @@ function makeSummary(overrides: Partial<SessionSummary> & { id: string }): Sessi
|
||||
activeAt: 0,
|
||||
updatedAt: 1000,
|
||||
metadata: null,
|
||||
metadataVersion: 0,
|
||||
agentStateVersion: 0,
|
||||
todosUpdatedAt: 0,
|
||||
todoProgress: null,
|
||||
pendingRequestsCount: 0,
|
||||
pendingRequestKinds: [],
|
||||
|
||||
@@ -16,6 +16,9 @@ function makeSession(overrides: Partial<SessionSummary> & { id: string }): Sessi
|
||||
activeAt: 0,
|
||||
updatedAt: 0,
|
||||
metadata: null,
|
||||
metadataVersion: 0,
|
||||
agentStateVersion: 0,
|
||||
todosUpdatedAt: 0,
|
||||
todoProgress: null,
|
||||
pendingRequestsCount: 0,
|
||||
pendingRequestKinds: [],
|
||||
|
||||
Reference in New Issue
Block a user