Skip to content

feat(agui): hand off active runs to live frames - #4039

Draft
chcodex wants to merge 21 commits into
agentscope-ai:mainfrom
chcodex:feat/agui-live-handoff
Draft

chcodex wants to merge 21 commits into
agentscope-ai:mainfrom
chcodex:feat/agui-live-handoff

Conversation

@chcodex

@chcodex chcodex commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Depends on #4026 and #3988; both are contained in this branch. The branch is also prepared on top of #4085 and #4068, which merge first. Until those four land, this PR also contains their commits; the #4039-specific changes start at feat(agui): hand off active runs to live frames.

This PR also aligns replay and live delivery on one message identity: text uses the SessionLog turn id, reasoning uses turnId:reasoning, and tool-bound interrupt ids use turnId:toolCallId.

This PR adds process-local live handoff on top of the session-log replay path: attach first bridges from the caller's cursor to the broadcaster's recent frames, then continues with the live tail, without a gap or a duplicate frame for recent cursors.

Older cursors still replay the session log up to the oldest buffered event and then continue from the buffer and tail. If no live tail is available, attach falls back to the existing log polling path.

What changed

Live handoff

  • Add AguiRunBroadcaster, a process-local broadcaster keyed by userId + agentId + threadId.
    • Bounded per-tail queue; overflow ends the tail and degrades attach to log polling.
    • Bounded recent-frame buffer captured under the same lock as the tail, so a cursor inside the buffer is served without waiting for a log commit.
    • Complete source events are published as batches, so a snapshot never lands in the middle of a multi-frame event.
  • AguiAgentAdapter.runFramed / framesFor expose every AG-UI frame together with its source sequence and optional replay cursor.
  • AguiRequestProcessor publishes complete source events and keeps RUN_STARTED log-replayed.
  • AguiSessionLogAttach now bridges [log up to oldest buffered - 1] + [recent frames] + [live tail], then drains the remaining committed log.
  • Forwarded subagent events never use the parent's cursor: their child journal sequence is not comparable with the parent log, so they remain uncursored and are delivered by the live tail.

Recovery anchors

  • AguiSessionLogAttach.runStartedPrefix reads SessionLog.lastRunStartSeq() first, which JournalSessionLog answers from anchors.json instead of walking back through commit segments. Stores whose lastRunStartSeq() returns 0 keep the previous per-segment scan as a fallback.

Replay/live message identity

  • Replay text message ids use SessionEvent.turnId(); reasoning ids use turnId + ":reasoning" (from feat(agui): resume active runs from the session log #4026's presentation change).
  • Live TextBlock / ThinkingBlock conversion resolves the same ids from AgentEvent.execution.turnId(), with the previous per-block id only as a fallback for streams that carry no execution identity.
  • AguiInterrupts now scopes tool-bound interrupts by turn: replay takes SessionEvent.turnId(), live takes AgentEvent.execution.turnId(), and both produce turnId:toolCallId. The reply id remains in interrupt metadata; streams without a turn id keep the legacy replyId:toolCallId / toolCallId form.
  • A live tail therefore appends to the same assistant/reasoning message that replay announced, and an interrupt reconstructed from the log has the same id as the one emitted live.

Replay performance

  • The main no-live replay path runAttach → startAttach → pollOnce now scans from the cursor to the current head in one pass (log.scan(cursor, head.seq())) instead of readAfter(cursor, 256) batches that re-walked the commit chain.
  • Frames are forwarded to the sink while the delta is traversed; the first frame no longer waits for the whole delta. Every event and frame checks sink.isCancelled().
  • The cursor advances per event, so a projection failure stops at the last event already sent; the existing regression test now expects cursor 1 instead of 0.
  • AguiSessionLogAttach.attachUntil still replays the live catch-up/drain range with a single scan; uncommitted-boundary wait, timeout, cancellation and error-frame semantics are unchanged.
  • Real service replay: after=0 first frame 1.49s → 0.32s; after=1000 total 1.65s; after=5000 total 0.68s. The earlier 5,704-frame full replay went from 72.80s with 13+ stalls to 6.01s with one 1.67s stall.
  • after=0 segment location still depends on perf(core): locate journal segments by sequence and load them in bounded batches #4085 (fdbfb34fe): this PR does not cherry-pick the core change. Once perf(core): locate journal segments by sequence and load them in bounded batches #4085 lands, rebasing this branch obtains sequence-indexed segment loading instead of a bulk load.
  • Known risk: Flux.create uses the default BUFFER strategy, so a slow client can accumulate frames. This PR does not change the backpressure strategy.

Core sequence propagation

  • SessionRecorder:
    • SESSION_SEQ_KEY / SESSION_SOURCE_SEQ_KEY;
    • lastAppendedSeq, type-checked boundary reads;
    • recordMessage / recordAssistantMessage with messageId -> seq;
    • interaction boundaries tagged with their exact sequence.
  • SessionModels tags each model chunk with its session sequence.
  • ReActAgent:
    • model chunks carry source sequence only (not a replay boundary);
    • model/end, run/end, tool result ends carry cursors;
    • assistant tool-call messages and tool/requested are recorded before tool results, keeping log order equal to conversation order;
    • provisional tool results are used when legacy PostActing hooks may rewrite the result; the final result is recorded after the hook and is the only conversation-history record.
  • ChatResponse.withMetadataEntry; ReasoningContext excludes the internal seq key from persisted message metadata.

Docs

English and Chinese AG-UI protocol docs updated for the live/recent-buffer handoff, cursor boundaries, and uncursored subagent frames.

Tests

  • agentscope-core: 3001 tests, 1 known pre-existing failure (SkillBoxTest$SkillBoxUploadSecurityGate), 9 skipped.
  • agentscope-extensions-agui: 660 tests, all passing.
  • agentscope-harness: 1619 tests, 0 failures, 12 skipped. The inbox scheduling regression test disables background memory hooks so unrelated flush/consolidation model calls cannot overwrite its last-request assertion.
  • spotless:check for both modules passes.
  • git diff --check passes.
  • Docs: npm test, npm run validate, npm run broken-links pass.
  • CI note: one ubuntu run failed JevSupervisionMiddlewareTest#humanAdviceDoesNotInterruptOrReplayTheWorker with expected MANUAL_REVIEW but was CONTINUE. Six consecutive local reruns passed; the failure is a pre-existing timer race in that test (the adjacent synchronous-worker test documents the same scheduling race) and is unrelated to the AG-UI/session-log changes.

New coverage includes:

  • broadcaster recent-frame snapshot and whole-event publication;
  • attach served from the recent buffer without reading the log;
  • older cursor replayed from the log before the buffer;
  • tail overflow degraded to log polling;
  • all-uncursored live tail falling back to log replay;
  • forwarded child events not carrying the parent cursor;
  • provisional tool result not advancing the cursor;
  • assistant tool-call message preceding its tool result in the log;
  • processor-level active-run attach through the live tail;
  • replay and live tail using the same turn-scoped text message id;
  • attach not announcing or appending the assistant message twice across the handoff;
  • replay and live producing the same turn-scoped interrupt id.

Limitations

  • The recent buffer is process-local and bounded by frame count; older cursors still wait for the log commit.
  • Multi-instance deployments still need a shared SessionLogStore; the recent buffer does not cross processes.
  • A live stream whose frames all lack session sequences falls back to the log to avoid duplicate delivery. Content that exists only in the live tail (for example subagent-only forwarded frames) is not replayable in that fallback.
  • With legacy PostActing hooks present, tool-result live frames intentionally do not advance the SSE id; reconnecting from the previous cursor replays the finalized result once.

Merge order

Commits

  • perf(core): anchor session recovery at latest checkpoint and run start #3988: perf(core): anchor session recovery at latest checkpoint and run start, fix(agui): prefer recovery anchors when announcing RUN_STARTED
  • feat(agui): resume active runs from the session log #4026: feat(agui): resume active runs from the session log, fix(agui): emit RUN_STARTED first on session-log attach, fix(agui): use turnId for session-log replay message ids, docs(agui): document turn-scoped session-log message ids
  • feat(agui): hand off active runs to live frames #4039: feat(agui): hand off active runs to live frames, test(agui): adapt MVC controller fixture to framed runs, fix(agui): publish live frames and keep per-segment boundaries, fix(agui): use session turn ids for replay and live message identities, test(harness): isolate inbox scheduling test from memory hooks, perf(agui): replay the session log in one pass, perf(agui): replay committed session-log delta in one scan, perf(agui): stream session-log replay instead of buffering the whole delta, test(agui): align replay coverage with streaming one-scan polls

@mintlify

mintlify Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 39a305e.

Approve preview

JournalSessionLog.scan unconditionally called loadCommitSegments(), so every incremental read (after > 0, e.g. the AG-UI connect poll every 200ms) listed and read every commit segment in the journal even though only the head -> after suffix is needed.

Bulk pre-read is now limited to a full replay (after == 0); incremental reads fall back to per-segment reads via committedSegment(id, null). The commit walk and event filtering are unchanged.

Tests: add a counting AtomicSessionStorage and assert incremental scans never call listPaths/readAll, full replays still do, and both paths return the same event sequence.
Bridge attach from the session log to a process-local live tail, with a bounded recent-frame buffer, source-sequence deduplication and a log-polling fallback. Propagate session sequence metadata through the core model and tool boundaries, keep forwarded subagent frames uncursored, and document the handoff contract.
AguiRequestProcessor now invokes runFramed, so the test adapter must override the framed entry point to keep exercising controller cancellation and completion paths.
Recovery previously replayed the whole EVENT_LOG journal, costing one remote read per commit segment (about 35s on a 445-segment session).

Maintain an O(1) anchors.json next to the journal head with the latest checkpoint and run/start sequences. Anchors update only after the commit and head are durable, only increase, and are rebuilt from the committed chain when missing or corrupt.

Start projection at the earlier of the two anchors so stateJson, activeRuns, and uncertainToolCalls match a full replay. Transcript now merges checkpoint state without dropping history, and the export cursor advances in batches of 200 events with at-least-once replay.

Refs agentscope-ai#3987
@chcodex
chcodex force-pushed the feat/agui-live-handoff branch from e490fdc to a386210 Compare November 10, 2026 03:17
pollOnce read the log with readAfter(cursor, 256). Every call walks the commit chain from the head down to the cursor, so a full replay (afterSequence=0) paid that walk once per 256 events: quadratic in the number of commit segments and visibly stalled for seconds between batches.

Read the whole committed delta of a poll with a single scan(cursor, through) instead, bounded by REPLAY_CHUNK so a very long session still yields between polls. Measured on a 5,704-frame replay: 72.8s -> 6.0s.
…delta

A poll now scans from the cursor to the current head in one pass and forwards each projected frame to the sink as it is produced. The first frame no longer waits for the whole delta, and cancellation is checked per event. The cursor advances per event, so a projection failure stops at the last frame the client already received (attachKeepsCursorWhenEventProjectionFails expects 1 instead of 0).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 重要不紧急

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants