-
Notifications
You must be signed in to change notification settings - Fork 21
feat(console): reactive traces + session-events live streams #224
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
f7d9c92
feat: implement live-refresh for traces using engine trigger
ytallo c74c973
feat: enhance traces live refresh with onExtra callback for silent up…
ytallo 99899e6
feat(console): direct session-events live stream + traces search dedup
ytallo 5365182
Merge origin/main into feat/traces-live-stream
ytallo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
155 changes: 155 additions & 0 deletions
155
console/web/src/lib/backend/session-events-live.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| import { describe, expect, it, vi } from 'vitest' | ||
| import type { IiiClient } from '@/lib/iii-client' | ||
| import type { AgentEvent } from '@/types/iii-agent-event' | ||
| import { | ||
| extractSessionEvent, | ||
| startSessionEventsSubscription, | ||
| } from './session-events-live' | ||
|
|
||
| /** | ||
| * Build the raw `agent::events` stream frame the engine delivers to a stream | ||
| * trigger handler: `serde_json::to_value(StreamWrapperMessage)` → | ||
| * `{ type, timestamp, streamName, groupId, id, event: { data } }`, where | ||
| * `event.data` is the AgentEvent the harness wrote via `stream::set`. | ||
| */ | ||
| function frame(groupId: string, event: AgentEvent, opts?: { flat?: boolean }) { | ||
| if (opts?.flat) { | ||
| return { groupId, streamName: 'agent::events', data: event } | ||
| } | ||
| return { | ||
| type: 'set', | ||
| timestamp: 1, | ||
| streamName: 'agent::events', | ||
| groupId, | ||
| id: `${groupId}-epoch-00000000`, | ||
| event: { data: event }, | ||
| } | ||
| } | ||
|
|
||
| const UPDATE = { type: 'message_update' } as unknown as AgentEvent | ||
| const END = { type: 'agent_end', messages: [] } as unknown as AgentEvent | ||
|
|
||
| describe('extractSessionEvent', () => { | ||
| it('extracts the inner AgentEvent from a real engine frame (event.data)', () => { | ||
| expect(extractSessionEvent(frame('sess-1', UPDATE), 'sess-1')).toEqual( | ||
| UPDATE, | ||
| ) | ||
| }) | ||
|
|
||
| it('falls back to a flat `data` field when there is no event wrapper', () => { | ||
| expect( | ||
| extractSessionEvent(frame('sess-1', END, { flat: true }), 'sess-1'), | ||
| ).toEqual(END) | ||
| }) | ||
|
|
||
| it('accepts the snake_case group_id key as well as camelCase groupId', () => { | ||
| const snake = { group_id: 'sess-1', data: UPDATE } | ||
| expect(extractSessionEvent(snake, 'sess-1')).toEqual(UPDATE) | ||
| }) | ||
|
|
||
| it('drops a frame whose group_id is a different session', () => { | ||
| expect(extractSessionEvent(frame('sess-2', UPDATE), 'sess-1')).toBeNull() | ||
| }) | ||
|
|
||
| it('drops a frame with no group_id (cannot confirm ownership)', () => { | ||
| expect(extractSessionEvent({ data: UPDATE }, 'sess-1')).toBeNull() | ||
| }) | ||
|
|
||
| it('returns null for null / non-object / payload-less frames', () => { | ||
| expect(extractSessionEvent(null, 'sess-1')).toBeNull() | ||
| expect(extractSessionEvent('nope', 'sess-1')).toBeNull() | ||
| expect(extractSessionEvent({ groupId: 'sess-1' }, 'sess-1')).toBeNull() | ||
| }) | ||
| }) | ||
|
|
||
| function fakeClient() { | ||
| const triggers: Array<{ | ||
| type: string | ||
| function_id: string | ||
| config?: unknown | ||
| }> = [] | ||
| let handler: ((p: unknown) => void) | null = null | ||
| const offHandler = vi.fn() | ||
| const triggerUnregister = vi.fn() | ||
|
|
||
| const on = vi.fn((_fn: string, h: (p: unknown) => void) => { | ||
| handler = h | ||
| return offHandler | ||
| }) | ||
| const registerTrigger = vi.fn( | ||
| (input: { type: string; function_id: string; config?: unknown }) => { | ||
| triggers.push(input) | ||
| return triggerUnregister | ||
| }, | ||
| ) | ||
|
|
||
| const client = { | ||
| browserId: 'console-test', | ||
| on, | ||
| registerTrigger, | ||
| call: vi.fn(), | ||
| addConnectionStateListener: vi.fn(), | ||
| dispose: vi.fn(async () => {}), | ||
| } as unknown as IiiClient | ||
|
|
||
| return { | ||
| client, | ||
| on, | ||
| registerTrigger, | ||
| triggers, | ||
| offHandler, | ||
| triggerUnregister, | ||
| fire: (f: unknown) => handler?.(f), | ||
| } | ||
| } | ||
|
|
||
| describe('startSessionEventsSubscription', () => { | ||
| it('registers an iii::-prefixed handler and a stream trigger scoped to the session', () => { | ||
| const { client, on, triggers } = fakeClient() | ||
|
|
||
| startSessionEventsSubscription(client, 'sess-1', () => {}) | ||
|
|
||
| expect(on).toHaveBeenCalledWith( | ||
| 'iii::console::session_event', | ||
| expect.any(Function), | ||
| ) | ||
| expect(triggers).toEqual([ | ||
| { | ||
| type: 'stream', | ||
| function_id: 'iii::console::session_event::console-test', | ||
| config: { stream_name: 'agent::events', group_id: 'sess-1' }, | ||
| }, | ||
| ]) | ||
| }) | ||
|
|
||
| it('delivers each extracted AgentEvent for this session to onEvent', () => { | ||
| const { client, fire } = fakeClient() | ||
| const onEvent = vi.fn() | ||
|
|
||
| startSessionEventsSubscription(client, 'sess-1', onEvent) | ||
| fire(frame('sess-1', UPDATE)) | ||
|
|
||
| expect(onEvent).toHaveBeenCalledTimes(1) | ||
| expect(onEvent).toHaveBeenCalledWith(UPDATE) | ||
| }) | ||
|
|
||
| it('does not deliver a frame addressed to another session', () => { | ||
| const { client, fire } = fakeClient() | ||
| const onEvent = vi.fn() | ||
|
|
||
| startSessionEventsSubscription(client, 'sess-1', onEvent) | ||
| fire(frame('sess-2', UPDATE)) | ||
|
|
||
| expect(onEvent).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('unregisters the handler and the trigger on cleanup', () => { | ||
| const { client, offHandler, triggerUnregister } = fakeClient() | ||
|
|
||
| const stop = startSessionEventsSubscription(client, 'sess-1', () => {}) | ||
| stop() | ||
|
|
||
| expect(offHandler).toHaveBeenCalledTimes(1) | ||
| expect(triggerUnregister).toHaveBeenCalledTimes(1) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| /** | ||
| * Direct subscription to a session's `agent::events` stream, replacing the | ||
| * harness fanout hop (`ui::subscribe` → per-browser `ui::session::event` push). | ||
| * | ||
| * The browser registers a local handler and binds a SCOPED engine stream | ||
| * trigger (`config.group_id = session_id`) to it. The engine matches stream | ||
| * triggers by `(stream_name, group_id, item_id)` and delivers only matching | ||
| * frames straight to this browser's WS connection (engine | ||
| * `stream.rs::invoke_triggers`), so a browser receives exactly its own | ||
| * session's events — without the harness re-pushing them, and with no | ||
| * `harness::fanout::*` / per-browser `ui::session::event` spans. | ||
| * | ||
| * The handler is named with the `iii::` prefix (`is_iii_builtin_function_id`), | ||
| * so the spans produced by DELIVERING this trigger are tagged | ||
| * `iii.function.kind=internal` — hidden from the Traces view by the default | ||
| * `include_internal:false` query and skipped by the engine's trigger | ||
| * loop-break, matching the `traces-live.ts` approach. Without this, every | ||
| * delivery would flood the trace list with `session_event` spans. | ||
| * | ||
| * The iii-browser-sdk replays both registered functions and triggers on | ||
| * reconnect (see `onSocketOpen`), so the trigger re-binds automatically; the | ||
| * chat backend re-seeds turn state on start via `turn::get_state`, mirroring | ||
| * the pre-existing fanout behavior (no per-event replay on reconnect). | ||
| */ | ||
|
|
||
| import type { IiiClient } from '@/lib/iii-client' | ||
| import type { AgentEvent } from '@/types/iii-agent-event' | ||
|
|
||
| /** iii:: prefix → engine-internal → delivery spans hidden + trigger loop-break skip. */ | ||
| const SESSION_EVENT_FN = 'iii::console::session_event' | ||
| /** The firehose stream the harness writes every agent event onto. */ | ||
| const EVENTS_STREAM = 'agent::events' | ||
|
|
||
| /** | ||
| * Pull the AgentEvent out of a raw `agent::events` stream frame, scoped to one | ||
| * session. The engine serializes `StreamWrapperMessage` as | ||
| * `{ groupId, event: { data }, … }`; some shapes carry a flat `data`. This | ||
| * mirrors the extraction the (now-removed) harness `agent::events` fanout | ||
| * pump performed before browsers subscribed to the stream directly. | ||
| * | ||
| * Returns null when the frame is malformed, carries no extractable event, or | ||
| * is addressed to a different session. The stream trigger is already | ||
| * group-scoped, so the session check is defense-in-depth against mis-delivery | ||
| * and preserves the strict `session_id` guard the fanout path enforced. | ||
| */ | ||
| export function extractSessionEvent( | ||
| frame: unknown, | ||
| sessionId: string, | ||
| ): AgentEvent | null { | ||
| if (!frame || typeof frame !== 'object') return null | ||
| const obj = frame as Record<string, unknown> | ||
|
|
||
| const groupId = | ||
| (typeof obj.groupId === 'string' && obj.groupId) || | ||
| (typeof obj.group_id === 'string' && obj.group_id) || | ||
| null | ||
| if (groupId !== sessionId) return null | ||
|
|
||
| const wrapper = | ||
| obj.event && typeof obj.event === 'object' | ||
| ? (obj.event as Record<string, unknown>) | ||
| : null | ||
| const inner = wrapper && 'data' in wrapper ? wrapper.data : (obj.data ?? null) | ||
| if (!inner || typeof inner !== 'object') return null | ||
| return inner as AgentEvent | ||
| } | ||
|
|
||
| /** | ||
| * Register the handler + a `agent::events` stream trigger scoped to | ||
| * `sessionId`, delivering each extracted AgentEvent to `onEvent`. Returns a | ||
| * cleanup that unregisters both (replacing the old `ui::unsubscribe`). | ||
| */ | ||
| export function startSessionEventsSubscription( | ||
| client: Pick<IiiClient, 'browserId' | 'on' | 'registerTrigger'>, | ||
| sessionId: string, | ||
| onEvent: (event: AgentEvent) => void, | ||
| ): () => void { | ||
| const off = client.on(SESSION_EVENT_FN, (frame: unknown) => { | ||
| const event = extractSessionEvent(frame, sessionId) | ||
| if (event) onEvent(event) | ||
| }) | ||
|
|
||
| // `on()` registers under `<fn>::<browserId>`; the trigger must target that id. | ||
| const functionId = `${SESSION_EVENT_FN}::${client.browserId}` | ||
| const offTrigger = client.registerTrigger({ | ||
| type: 'stream', | ||
| function_id: functionId, | ||
| config: { stream_name: EVENTS_STREAM, group_id: sessionId }, | ||
| }) | ||
|
|
||
| return () => { | ||
| off() | ||
| try { | ||
| offTrigger() | ||
| } catch { | ||
| // SDK already disposed; nothing to do. | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Handle partial subscription failure rollback.
If
client.registerTrigger(...)throws afterclient.on(...)succeeds (Line 78 → Line 85), the handler remains registered. This leaks listeners and can cause duplicate delivery behavior on later retries. Unregisteroffin acatchbefore rethrowing.Suggested fix
export function startSessionEventsSubscription( client: Pick<IiiClient, 'browserId' | 'on' | 'registerTrigger'>, sessionId: string, onEvent: (event: AgentEvent) => void, ): () => void { const off = client.on(SESSION_EVENT_FN, (frame: unknown) => { const event = extractSessionEvent(frame, sessionId) if (event) onEvent(event) }) // `on()` registers under `<fn>::<browserId>`; the trigger must target that id. const functionId = `${SESSION_EVENT_FN}::${client.browserId}` - const offTrigger = client.registerTrigger({ - type: 'stream', - function_id: functionId, - config: { stream_name: EVENTS_STREAM, group_id: sessionId }, - }) + let offTrigger: (() => void) | null = null + try { + offTrigger = client.registerTrigger({ + type: 'stream', + function_id: functionId, + config: { stream_name: EVENTS_STREAM, group_id: sessionId }, + }) + } catch (err) { + off() + throw err + } return () => { off() try { - offTrigger() + offTrigger?.() } catch { // SDK already disposed; nothing to do. } } }🤖 Prompt for AI Agents