The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(desktop): extract branch-added gateway-event handler branches
Teknium32aa2806144b
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.tsindex b4a4eb0cc29..c2b3ca7b94d 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts@@ -93,6 +93,49 @@ const HANDLERS: GatewayEventHandler[] = [handleStatusEvent]+type ExecutionAuthorities = Parameters<typeof acceptExecutionEvent>[0]++/** The event's own timestamp (epoch seconds) when finite, else now. */+function gatewayEventOccurredAt(payload: GatewayEventPayload | undefined): number {+ return typeof payload?.timestamp === 'number' && Number.isFinite(payload.timestamp)+ ? payload.timestamp+ : Date.now() / 1000+}++/** Fence the event against the session's claimed execution. Returns false+ * when a stamped late frame must be dropped; an accepted newer owner+ * start/snapshot retires the previous execution's interrupted latch. */+function admitExecutionEvent(+ authorities: ExecutionAuthorities,+ event: GatewayEvent,+ sessionId: null | string,+ deps: GatewayEventDeps+): boolean {+ const authorityKey = `${registryBackendScopeKey(event.connectionId ?? null, event.profile ?? null)}\u0000${sessionId}`++ const previousAuthority = authorities.get(authorityKey)++ if (sessionId && !acceptExecutionEvent(authorities, authorityKey, event.type, event)) {+ return false+ }++ const authority = authorities.get(authorityKey)++ if (+ sessionId &&+ previousAuthority &&+ authority &&+ !authority.terminal &&+ (authority.epoch !== previousAuthority.epoch || authority.generation > previousAuthority.generation)+ ) {+ // Stop belongs to the cancelled execution, not the shared session.+ // Only an accepted newer owner start/snapshot may retire its latch.+ deps.updateSessionState(sessionId, state => (state.interrupted ? { ...state, interrupted: false } : state))+ }++ return true+}+/** The gateway-event dispatcher, extracted from useMessageStream. */export function useGatewayEventHandler(deps: GatewayEventDeps) {const executionAuthorities = useRef(new Map())@@ -152,10 +195,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {registryBackendScopeKey(event.connectionId ?? null, event.profile ?? null) ===registryBackendScopeKey(activeGatewayConnectionId(), event.profile ?? null)- const occurredAt =- typeof payload?.timestamp === 'number' && Number.isFinite(payload.timestamp)- ? payload.timestamp- : Date.now() / 1000+ const occurredAt = gatewayEventOccurredAt(payload)const explicitSid = event.session_id || ''@@ -173,19 +213,9 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {}const sessionId = route.sessionId- const authorityKey = `${registryBackendScopeKey(event.connectionId ?? null, event.profile ?? null)}\u0000${sessionId}`- const previousAuthority = executionAuthorities.current.get(authorityKey)-- if (sessionId && !acceptExecutionEvent(executionAuthorities.current, authorityKey, event.type, event)) {return}-- const authority = executionAuthorities.current.get(authorityKey)-- if (sessionId && previousAuthority && authority && !authority.terminal &&- (authority.epoch !== previousAuthority.epoch || authority.generation > previousAuthority.generation)) {- // Stop belongs to the cancelled execution, not the shared session.- // Only an accepted newer owner start/snapshot may retire its latch.- deps.updateSessionState(sessionId, state => state.interrupted ? { ...state, interrupted: false } : state)+ if (!admitExecutionEvent(executionAuthorities.current, event, sessionId, deps)) {+ return}// Late stragglers: an unscoped stream event attributed via thediff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.tsindex d608fb25517..c0cdfccef3c 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts@@ -41,6 +41,47 @@ const isConnectionRequestEvent = (event: GatewayEvent): event is ConnectionRequeconst isConnectionUpdateEvent = (event: GatewayEvent): event is ConnectionUpdateEvent =>event.type === 'connection.update' && event.payload !== undefined+/** `approval.settled` / `clarify.settled {prompt_id}`: take down the card+ * parked under that server request id. Returns false for other events. */+function handlePromptSettledEvent(ctx: GatewayEventContext): boolean {+ const { deps, event, payload, sessionId } = ctx++ if (event.type !== 'approval.settled' && event.type !== 'clarify.settled') {+ return false+ }++ const promptId = (payload as { prompt_id?: unknown } | undefined)?.prompt_id++ if (typeof promptId !== 'string' || !promptId) {+ return true+ }++ forgetServerRequest(promptId)+ const key = sessionId ?? ''++ if (event.type === 'clarify.settled') {+ if ($clarifyRequests.get()[key]?.requestId === promptId) {+ clearClarifyRequest(promptId, sessionId)++ if (sessionId) {+ deps.updateSessionState(sessionId, state => ({ ...state, needsInput: false }))+ }+ }++ return true+ }++ const approval = sessionApprovalRequests(sessionId ?? null)+ .get()+ .find(request => request.serverRequestId === promptId)++ if (approval) {+ clearApprovalRequest(sessionId, approval.requestId)+ }++ return true+}+/** The blocking-input family arrives as server→client REQUESTS (see* `server-requests.ts`); the one EVENT in the family is `request.cancel`, the* backend withdrawing an open request (timeout / interrupt / session close):@@ -101,36 +142,7 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {// turn ended). The prompt id is the server request id this window parked the// card under. Only the parked card comes down: the answer itself reaches the// transcript through the tool's own completion, so no "skipped" projection.- if (event.type === 'approval.settled' || event.type === 'clarify.settled') {- const promptId = (payload as { prompt_id?: unknown } | undefined)?.prompt_id-- if (typeof promptId !== 'string' || !promptId) {- return true- }-- forgetServerRequest(promptId)- const key = sessionId ?? ''-- if (event.type === 'clarify.settled') {- if ($clarifyRequests.get()[key]?.requestId === promptId) {- clearClarifyRequest(promptId, sessionId)-- if (sessionId) {- deps.updateSessionState(sessionId, state => ({ ...state, needsInput: false }))- }- }-- return true- }-- const approval = sessionApprovalRequests(sessionId ?? null)- .get()- .find(request => request.serverRequestId === promptId)-- if (approval) {- clearApprovalRequest(sessionId, approval.requestId)- }-+ if (handlePromptSettledEvent(ctx)) {return true}@@ -208,7 +220,16 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {}})}- } else if ($sudoRequests.get()[key]?.requestId === id) {+ } else {+ cancelParkedCredentialRequest(key, sessionId, id)+ }++ return true+}++/** Withdraw the sudo / secret / vault card parked under `id`, first match wins. */+function cancelParkedCredentialRequest(key: string, sessionId: GatewayEventContext['sessionId'], id: string): void {+ if ($sudoRequests.get()[key]?.requestId === id) {clearSudoRequest(sessionId, id)} else if ($sudoRequests.get()['']?.requestId === id) {clearSudoRequest(null, id) // the app-level Bot Screen install card: not owned by any chat@@ -221,6 +242,4 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {} else if ($vaultUnlockRequests.get()[key]?.requestId === id) {clearVaultUnlockRequest(sessionId, id)}-- return true}diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.tsindex bb2d9f9452f..1ec2b66ff7e 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts@@ -19,12 +19,7 @@ import { clearAllPrompts, clearApprovalRequest } from '@/store/prompts'import { markRuntimeGone } from '@/store/runtime-gone'import { getSessionOwnerHint, knownSessionOwner, ownerLookupSessionRows, requestSessionResume } from '@/store/session'import type { SessionOwnerScope } from '@/store/session-request-router'-import {- $sessionTiles,- dropSessionState,- sessionTileDelegate,- unbindTileRuntime-} from '@/store/session-states'+import { $sessionTiles, dropSessionState, sessionTileDelegate, unbindTileRuntime } from '@/store/session-states'// Leaf import (not the `@/themes` barrel) to avoid pulling the ThemeProvider// module graph into the gateway event hot path.import { ingestBackendSkin } from '@/themes/backend-sync'@@ -172,44 +167,52 @@ export function handleLifecycleEvent(ctx: GatewayEventContext): boolean {return true}- if (event.type === 'session.replay_gap') {- const runtimeId = event.session_id || ''+ return handleReplayGapEvent(ctx)+}- const storedSessionId = runtimeId- ? deps.sessionStateByRuntimeIdRef.current.get(runtimeId)?.storedSessionId- : null+/** session.replay_gap: the owner's replay window no longer covers this+ * viewer, so re-snapshot the matching pane or tile authoritatively. */+function handleReplayGapEvent(ctx: GatewayEventContext): boolean {+ const { deps, event } = ctx- const source = gatewayEventSource(event)+ if (event.type !== 'session.replay_gap') {+ return false+ }- const ownerForStoredSession = (id: string): SessionOwnerScope =>- getSessionOwnerHint(id, source) ?? knownSessionOwner(ownerLookupSessionRows(), id)+ const runtimeId = event.session_id || ''- if (storedSessionId && runtimeId === deps.activeSessionIdRef.current) {- const ownerRoute = ownerForStoredSession(storedSessionId)+ const storedSessionId = runtimeId ? deps.sessionStateByRuntimeIdRef.current.get(runtimeId)?.storedSessionId : null- if (eventSourceMatchesOwner(source, ownerRoute)) {- requestSessionResume(storedSessionId, ownerRoute && typeof ownerRoute === 'object' ? ownerRoute : undefined, {- authoritativeSnapshot: true- })+ const source = gatewayEventSource(event)- return true- }- }+ const ownerForStoredSession = (id: string): SessionOwnerScope =>+ getSessionOwnerHint(id, source) ?? knownSessionOwner(ownerLookupSessionRows(), id)- const tile = $sessionTiles.get().find(candidate => {- if (candidate.runtimeId !== runtimeId) {- return false- }+ if (storedSessionId && runtimeId === deps.activeSessionIdRef.current) {+ const ownerRoute = ownerForStoredSession(storedSessionId)- return eventSourceMatchesOwner(source, candidate.ownerRoute ?? ownerForStoredSession(candidate.storedSessionId))- })+ if (eventSourceMatchesOwner(source, ownerRoute)) {+ requestSessionResume(storedSessionId, ownerRoute && typeof ownerRoute === 'object' ? ownerRoute : undefined, {+ authoritativeSnapshot: true+ })- if (tile) {- void sessionTileDelegate()?.resumeTile(tile.storedSessionId, { authoritativeSnapshot: true }).catch(() => undefined)+ return true}+ }- return true+ const tile = $sessionTiles.get().find(candidate => {+ if (candidate.runtimeId !== runtimeId) {+ return false+ }++ return eventSourceMatchesOwner(source, candidate.ownerRoute ?? ownerForStoredSession(candidate.storedSessionId))+ })++ if (tile) {+ void sessionTileDelegate()+ ?.resumeTile(tile.storedSessionId, { authoritativeSnapshot: true })+ .catch(() => undefined)}- return false+ return true}diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.tsindex 6998e5bb9c3..2b4ef52ca4b 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts@@ -133,6 +133,19 @@ function maybeRebindPaneToRebuiltRuntime(ctx: GatewayEventContext): boolean {return true}+/** Project the runtime's pending-submission receipts onto the durable+ * session's composer queue (keyed by stored id when known). */+function reconcileSessionInfoPendingSubmissions(ctx: GatewayEventContext): void {+ const { deps, payload, sessionId } = ctx++ if (sessionId) {+ const storedId =+ payload?.stored_session_id ?? deps.sessionStateByRuntimeIdRef.current.get(sessionId)?.storedSessionId ?? sessionId++ reconcilePendingSubmissions(storedId, (payload as Record<string, unknown>)?.pending_submissions)+ }+}+/** session.info / session.usage / session.title. */export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {const { deps, event, payload, sessionId, explicitSid, isActiveEvent, occurredAt, fromActiveSource } = ctx@@ -156,10 +169,7 @@ export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {// subsequent isActiveEvent gate keeps matching (#93942 scenario B).const rebound = maybeRebindPaneToRebuiltRuntime(ctx)- if (sessionId) {- const storedId = payload?.stored_session_id ?? sessionStateByRuntimeIdRef.current.get(sessionId)?.storedSessionId ?? sessionId- reconcilePendingSubmissions(storedId, (payload as Record<string, unknown>)?.pending_submissions)- }+ reconcileSessionInfoPendingSubmissions(ctx)// Apply session-scoped fields when the event targets the active// session, OR when it's a global broadcast and we have no session.@@ -407,9 +417,16 @@ export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {typeof armedAt === 'number' && Date.now() - armedAt < PRE_TURN_LIVE_SETTLE_GRACE_MS// The owner stamps its claimed execution on the event params, not the payload.- const authoritative = typeof event.authority_epoch === 'number' && typeof event.execution_generation === 'number'-- if (!authoritative && state.awaitingResponse && !state.sawAssistantPayload && !state.turnLive && withinPreStartGrace) {+ const authoritative =+ typeof event.authority_epoch === 'number' && typeof event.execution_generation === 'number'++ if (+ !authoritative &&+ state.awaitingResponse &&+ !state.sawAssistantPayload &&+ !state.turnLive &&+ withinPreStartGrace+ ) {return state}