Skip to content

The agent that grows with you

fix(desktop): deliver a gateway event once even when two sockets to one backend carry it

teknium171b61884a440
diff --git a/apps/desktop/src/app/gateway/gateway-event-dedupe.test.ts b/apps/desktop/src/app/gateway/gateway-event-dedupe.test.ts
new file mode 100644
index 00000000000..d93c4b60e3a
--- /dev/null
+++ b/apps/desktop/src/app/gateway/gateway-event-dedupe.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest'
+
+import { createGatewayEventDedupe, DUPLICATE_WINDOW_MS } from './gateway-event-dedupe'
+
+const delta = (seq: number, extra: Record<string, unknown> = {}) =>
+ ({
+ payload: { text: 'Two tools' },
+ replayEpoch: 'epoch-a',
+ seq,
+ session_id: 'rt-1',
+ type: 'message.delta',
+ ...extra
+ }) as never
+
+describe('gateway event dedupe (#120005)', () => {
+ it('admits a frame once even when a second socket to the same backend delivers it again', () => {
+ // The backend stamps `seq` before its transport fan-out, so both sockets
+ // carry the same (epoch, session, seq); the second copy must not reach
+ // the stores or the streaming text doubles.
+ const gate = createGatewayEventDedupe()
+
+ expect(gate.admit(delta(359), 1_000)).toBe(true)
+ expect(gate.admit(delta(359, { connectionId: 'local' }), 1_005)).toBe(false)
+ expect(gate.admit(delta(360), 1_010)).toBe(true)
+
+ // A different backend process has a different epoch: never a duplicate.
+ expect(gate.admit(delta(359, { replayEpoch: 'epoch-b' }), 1_020)).toBe(true)
+ })
+
+ it('accepts a re-numbered session after the window, and always passes seq-less events', () => {
+ const gate = createGatewayEventDedupe()
+
+ for (let seq = 1; seq <= 5; seq += 1) {
+ expect(gate.admit(delta(seq), 1_000 + seq)).toBe(true)
+ }
+
+ // The backend restarts the counter at 1 when the session leaves its replay
+ // ring; a short session's whole restart would otherwise be swallowed.
+ expect(gate.admit(delta(1), 1_010 + DUPLICATE_WINDOW_MS)).toBe(true)
+
+ expect(gate.admit(delta(2, { seq: undefined }), 1_000)).toBe(true)
+ expect(gate.admit(delta(2, { seq: undefined }), 1_000)).toBe(true)
+ expect(gate.admit({ payload: {}, type: 'skin.changed' } as never, 1_000)).toBe(true)
+ expect(gate.admit({ payload: {}, type: 'skin.changed' } as never, 1_000)).toBe(true)
+ })
+})
diff --git a/apps/desktop/src/app/gateway/gateway-event-dedupe.ts b/apps/desktop/src/app/gateway/gateway-event-dedupe.ts
new file mode 100644
index 00000000000..2c45cd25a01
--- /dev/null
+++ b/apps/desktop/src/app/gateway/gateway-event-dedupe.ts
@@ -0,0 +1,117 @@
+import type { GatewayEvent } from '@hermes/shared'
+
+/**
+ * Cross-socket duplicate gate for backend events (#120005 / #120007).
+ *
+ * The backend joins EVERY socket that sends a session call to that chat's
+ * transport fan-out (`tui_gateway/session_transports.py`, intended: shared
+ * chats keep every attached client in sync) and stamps `seq` once per event
+ * before the fan-out. When this renderer holds two sockets to ONE backend
+ * (a registry secondary next to the primary during a swap, a reconnect that
+ * overlaps a live socket, a relay-retained secondary) it receives the same
+ * frame twice, and every `message.delta` is appended twice while the second
+ * `message.interim` seals a duplicate bubble. `JsonRpcGateway` is one instance
+ * per socket, so its per-socket `lastSeenSeq` cannot see the other copy; this
+ * gate sits where both fan-ins meet, before any store runs.
+ *
+ * Key: `(replay_epoch, session_id, seq)`. Two sockets to the same process
+ * share the epoch (a uuid4 minted per backend process, adopted per socket from
+ * `gateway.ready`), so the key cannot collide across different backends.
+ *
+ * A duplicate is a frame with the same key seen within `DUPLICATE_WINDOW_MS`.
+ * The window matters: the backend restarts a session's counter at 1 when the
+ * session drops out of its 64-session replay ring, so "seq is not above the
+ * highest seen" would swallow the whole restart of any session that had fewer
+ * events than the restart reaches. Fan-out copies arrive within milliseconds;
+ * a legitimately re-numbered frame with the same seq inside the window would
+ * need 64 other sessions to emit in between, and is accepted once the window
+ * lapses either way.
+ *
+ * Events without `seq` or `session_id` (session-less globals, client-local
+ * events, legacy backends) always pass — there is no ordering contract to
+ * enforce on them.
+ */
+export const DUPLICATE_WINDOW_MS = 30_000
+const SEQS_PER_SESSION_MAX = 2048
+const SESSIONS_MAX = 256
+
+interface SessionSeen {
+ /** seq → wall-clock time first admitted; insertion order = admission order. */
+ seen: Map<number, number>
+}
+
+export interface GatewayEventDedupe {
+ /** True when the event is new and must be handled; false when another socket already delivered it. */
+ admit(event: GatewayEvent, now?: number): boolean
+}
+
+function sessionKey(event: GatewayEvent): string {
+ // Before `gateway.ready` a socket has no epoch; bucket by connection so the
+ // pair still deduplicates within one backend URL.
+ const epoch = event.replayEpoch ?? `conn:${event.connectionId ?? ''}`
+
+ return `${epoch}\u0000${event.session_id}`
+}
+
+export function createGatewayEventDedupe(): GatewayEventDedupe {
+ const sessions = new Map<string, SessionSeen>()
+
+ const touch = (key: string): SessionSeen => {
+ let entry = sessions.get(key)
+
+ if (entry) {
+ // Re-insert so Map iteration order doubles as LRU order.
+ sessions.delete(key)
+ } else {
+ entry = { seen: new Map() }
+ }
+
+ sessions.set(key, entry)
+
+ while (sessions.size > SESSIONS_MAX) {
+ const oldest = sessions.keys().next().value
+
+ if (oldest === undefined) {
+ break
+ }
+
+ sessions.delete(oldest)
+ }
+
+ return entry
+ }
+
+ return {
+ admit(event, now = Date.now()) {
+ const seq = event.seq
+
+ if (!event.session_id || typeof seq !== 'number' || !Number.isFinite(seq)) {
+ return true
+ }
+
+ const entry = touch(sessionKey(event))
+ const firstSeenAt = entry.seen.get(seq)
+
+ if (firstSeenAt !== undefined && now - firstSeenAt < DUPLICATE_WINDOW_MS) {
+ return false
+ }
+
+ // Re-admitting after the window (counter reset) refreshes the stamp;
+ // deleting first keeps insertion order meaningful for the cap below.
+ entry.seen.delete(seq)
+ entry.seen.set(seq, now)
+
+ while (entry.seen.size > SEQS_PER_SESSION_MAX) {
+ const oldest = entry.seen.keys().next().value
+
+ if (oldest === undefined) {
+ break
+ }
+
+ entry.seen.delete(oldest)
+ }
+
+ return true
+ }
+ }
+}
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
index 74666783d2f..58e5449f4b3 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -9,6 +9,7 @@ import {
} from '@hermes/shared'
import { useEffect, useRef } from 'react'
+import { createGatewayEventDedupe } from '@/app/gateway/gateway-event-dedupe'
import { shouldApplyPostBootProgressError } from '@/components/boot-failure-reauth'
import type { DesktopBootProgress, HermesConnection, HermesWindowState } from '@/global'
import { HermesGateway } from '@/hermes'
@@ -905,6 +906,22 @@ export function useGatewayBoot({
const gateway = adoptedFromHmr ? survivor!.gateway : new HermesGateway()
+ // Every socket this window owns (the primary below, every registry
+ // secondary via onEvent) funnels through this one gate before any store
+ // sees the event: two sockets to ONE backend both receive each frame of a
+ // chat they joined, and handled twice a delta doubles the streaming text
+ // (#120005). Keyed by the backend's own (epoch, session, seq) stamp.
+ const eventDedupe = createGatewayEventDedupe()
+
+ const deliverGatewayEvent = (event: GatewayEvent) => {
+ if (!eventDedupe.admit(event)) {
+ return
+ }
+
+ recordSessionEventScope(event)
+ callbacksRef.current.handleGatewayEvent(event)
+ }
+
callbacksRef.current.onGatewayReady(gateway)
setPrimaryGateway(gateway, survivor?.profile ?? normalizeProfileKey($activeGatewayProfile.get()))
// Secondary (background-profile) sockets funnel into the same handler.
@@ -947,10 +964,7 @@ export function useGatewayBoot({
$activeGatewayProfile.set(key)
}
},
- onEvent: event => {
- recordSessionEventScope(event)
- callbacksRef.current.handleGatewayEvent(event)
- },
+ onEvent: deliverGatewayEvent,
onActiveConnectionInvalidated: (fallbackProfile, invalidationEpoch) => {
$activeGatewayProfile.set(fallbackProfile)
// Bounded like every other getConnection() call in this file (#93454):
@@ -1042,8 +1056,7 @@ export function useGatewayBoot({
const ownedEvent =
$connection.get()?.sharedPrimary === true ? stampSecondaryProfileOwner(scopedEvent, sourceProfile) : scopedEvent
- recordSessionEventScope(ownedEvent)
- callbacksRef.current.handleGatewayEvent(ownedEvent)
+ deliverGatewayEvent(ownedEvent)
})
// Secondary sockets reach the same handler through the registry's onServerRequest.
diff --git a/apps/shared/src/gateway-events.ts b/apps/shared/src/gateway-events.ts
index 617790a90a5..6c86696e04c 100644
--- a/apps/shared/src/gateway-events.ts
+++ b/apps/shared/src/gateway-events.ts
@@ -36,6 +36,10 @@ export type GatewayEventName = keyof GatewayEventMap
export interface GatewayEvent<K extends GatewayEventName = GatewayEventName> {
/** Client-local: recovered/held during reconnect, not fresh user-facing work. */
replayed?: boolean
+ /** Client-local: the backend process's `replay_epoch` the delivering socket had adopted
+ * (from `gateway.ready`) when it dispatched this event. Two sockets to one process share
+ * it, so a renderer can recognise the same frame arriving on both. */
+ replayEpoch?: string
/** Registry connection whose socket delivered the event (renderer-side tag;
* absent for the local/legacy primary path). */
connectionId?: string
diff --git a/apps/shared/src/json-rpc-gateway.ts b/apps/shared/src/json-rpc-gateway.ts
index a9519a30f50..71374ee5a3c 100644
--- a/apps/shared/src/json-rpc-gateway.ts
+++ b/apps/shared/src/json-rpc-gateway.ts
@@ -604,7 +604,10 @@ export class JsonRpcGatewayClient {
}
private dispatchEvent(event: GatewayEvent): void {
- this.events.dispatch(event)
+ // Tag the frame with the process epoch this socket adopted so a consumer
+ // holding several sockets to one backend can recognise the same event
+ // arriving on each of them; the epoch is per process, not per socket.
+ this.events.dispatch(this.replayEpoch ? { ...event, replayEpoch: this.replayEpoch } : event)
}
private setState(state: ConnectionState): void {