agentscope-java icon indicating copy to clipboard operation
agentscope-java copied to clipboard

[Feature]: AguiSnapshotStore + Hydrate for AG-UI presentation-state recovery (MESSAGES/STATE/ACTIVITY_SNAPSHOT)

Open chcodex opened this issue 3 months ago • 7 comments

Is your feature request related to a problem? Please describe.

agentscope-extensions-agui already defines AG-UI snapshot types (StateSnapshot / StateDelta / MessagesSnapshot / ActivitySnapshot / ActivityDelta in AguiEvent.java + AguiEventType.java, AguiStateConverter exists) but the core pipeline never emits them. AguiStreamContext has no emit*Snapshot API, AguiAdapterConfig.emitStateEvents is not consumed in the core module, converter/ lacks AguiActivityConverter, and AguiAgentAdapter / AgentEventConverterRegistry (8 converters) never produce MESSAGES/ACTIVITY/STATE_SNAPSHOT on the wire. Emission today only lives in examples/copilotkit (WorkbenchAguiEventConverter / WorkbenchEventMiddleware).

As a result, generic AG-UI frontends cannot recover presentation state on refresh / SSE disconnect / reconnect: no MESSAGES_SNAPSHOT to restore history, no STATE_SNAPSHOT/DELTA to restore shared state, no ACTIVITY_SNAPSHOT/DELTA to restore render activities. The only recovery signal is RUN_FINISHED.outcome.interrupts via AguiResumeCoordinator, which covers HITL resume but not UI projection. This also leaves serverSideMemory=false vs true input-trimming (hasMemory → extractLatestUserMessage) without a snapshot to reconcile client vs server history.

Related: #2911 (history replay re-activates interrupt UI), #2907.

Describe the solution you'd like

Introduce a presentation-state layer decoupled from execution state. Core principle verified against current [email protected]:

AgentStateStore restores Agent execution state (AgentEvent → AgentState → Agent); AguiSnapshotStore restores AG-UI presentation state (AguiEvent → AguiThreadSnapshot → Frontend). Both are Event → State materializations, projection relationship, independently closed loops. Adapter only projects AgentEvent → AguiEvent; Store only materializes AguiEvent into AguiThreadSnapshot.

Architecture

                         AgentEvent
                        /          \
                       /            \
                      ▼              ▼
             AgentStateStore     AguiAdapter (projection only)
                    │                │
                    ▼                ▼
               AgentState        AguiEvent
                    │                │
                    ▼                ▼
               Agent recovery   AguiSnapshotStore ─→ AguiThreadSnapshot ─→ Hydrate ─→ Frontend
                                     │                    │
                                     │              {messages, state, activity}
                                     │                    │
                                     ▼                    ▼
                               latest-only covering write per threadId (InMemory, LRU 1000, deep-copy)
  • AguiSnapshotStore is a State Store, not an Event Store: API is save(threadId, AguiThreadSnapshot) / get(threadId) / delete / clear, not save(event). Internal flow is AguiEvent → materialize → AguiThreadSnapshot: MESSAGES_SNAPSHOT → snapshot.messages = …, STATE_SNAPSHOT → snapshot.state = …, ACTIVITY_SNAPSHOT → snapshot.activity = …, STATE_DELTA / ACTIVITY_DELTA → snapshot.state/activity = applyDelta(baseline, delta) via AguiStateConverter.computeDelta baseline diff. No event sequence is persisted.
  • Interrupt is not part of AguiThreadSnapshot execution state. Hydrate replays RUN_FINISHED(outcome.interrupts) only as presentation-level interrupt metadata so the frontend can re-render the approval UI. Authoritative HITL state remains in AguiResumeCoordinator + Agent runtime, not in the snapshot.
  • Hydrate is a read-only synthetic AG-UI run, not an Agent re-execution: Frontend refresh → Hydrate → SnapshotStore → Snapshot events → Frontend (never Agent.call() → LLM).

Hydrate contract (refined)

Hydrate Request = messages == [] && resume == null && snapshotStoreEnabled && snapshot exists
  • messages==[] alone is not sufficient; the server explicitly classifies the request as Hydrate and returns RUN_STARTED → [STATE_SNAPSHOT] → [MESSAGES_SNAPSHOT] → [ACTIVITY_SNAPSHOT] → RUN_FINISHED(outcome.interrupts?) without invoking the Agent. Any resume request bypasses hydration and follows the existing AguiResumeCoordinator path. Future AG-UI sync/hydrate protocol semantics should be aligned when available.

Plan

  1. New store/ in agentscope-extensions-agui (agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agui):

    • AguiThreadSnapshot (messages / state / activity)
    • AguiSnapshotStore (save(threadId, AguiThreadSnapshot) / get(threadId) / delete / clear) + InMemoryAguiSnapshotStore (covering write, baseline state/activity + STATE_DELTA/ACTIVITY_DELTA materialization)
    • AguiActivityConverter (mirror AguiStateConverter for ACTIVITY_SNAPSHOT/DELTA)
  2. Wiring

    • AguiStreamContext: add emitMessagesSnapshot / emitStateSnapshot / emitStateDelta / emitActivitySnapshot / emitActivityDelta (enqueue to pendingEvents only, stays stateless).
    • AguiAgentAdapter.streamWithRuntimeContext: after convertAgentEvents → drainEvents, materialize each snapshot event into AguiThreadSnapshot and call store.save(threadId, snapshot). DELTA events apply to the stored baseline.
    • AguiRequestProcessor.process: inject Optional<AguiSnapshotStore>; before beginRun, if hydration quadruple holds and store.get(threadId) is present, return Flux.fromIterable(hydrateEvents(runId, snapshot)) directly (run RUN_STARTED is always emitted by hydrate_events).
  3. Config

    • AguiAdapterConfig + AguiProperties: new snapshotStoreEnabled (default false, opt-in to avoid breaking existing frontends). No coupling to serverSideMemory; hydratable projection is AguiEvent-derived.
  4. Docs & examples

    • Update docs/v2/en/integration/protocol/agui.md mapping table + dual-store responsibility boundary (AgentStateStore vs AguiSnapshotStore table).
    • Extend agentscope-examples/agui to demo refresh/reconnect via empty-message Hydrate.

Describe alternatives you've considered

  • Depend on com.ag-ui.community:java-core: rejected for this iteration; keep zero external dep, stay on agentscope-extensions-agui.
  • Emit snapshots directly from AguiStreamContext without a store: rejected; Converter would become stateful and reconnect would require full event replay. Store keeps Converter stateless and supports latest-only replay.
  • Read AgentState.getContext() to build MESSAGES_SNAPSHOT: rejected; violates projection boundary (AgentState is internal runtime state).
  • Persist event sequence in the store (save(event)): rejected; store is a State Store, not an Event Store. Only AguiThreadSnapshot is persisted.

Additional context

  • Validated on main: AguiEvent.java:45 / AguiEventType.java, converter/ 3 files, AguiStreamContext:373, AguiAgentAdapter:194, Registry:69.
  • Reference principle: Microsoft agent-framework-ag-ui Hydrate — dual Event→State materializations, latest-only InMemory store, read-only hydration on empty-message request, interrupt replayed as presentation metadata via RUN_FINISHED.outcome. Referenced at principle/behavior level only, no code copied.
  • Labels: enhancement, area/ext/integration, area/ext/spring-boot, area/examples.

chcodex avatar Aug 31 '26 09:08 chcodex

请问这部分预计什么时间发布

shenghuitian avatar Sep 01 '26 06:09 shenghuitian

请问这部分预计什么时间发布

还在设计阶段

chcodex avatar Sep 01 '26 08:09 chcodex

#2922 这里会不会是重复工作

dragondyt avatar Sep 03 '26 02:09 dragondyt

设计有没有考虑到多租户,分布式。agui这块状态复用AgentState会不会更好点

Image

dragondyt avatar Sep 03 '26 03:09 dragondyt

For the multi-tenant/distributed boundary, the store contract should make ownership explicit rather than relying on a process-local threadId. A useful SPI could accept a composite key (tenantId, threadId) and an optional version/ETag on save, with compare-and-set semantics so reconnects from two nodes cannot overwrite a newer snapshot. get should return an immutable/deep-copied snapshot, and hydrate should carry the snapshot version used to render it. This keeps the in-memory implementation simple while making Redis/MySQL adapters possible without changing the adapter/event model. I agree that reusing AgentState directly would couple a presentation projection to execution internals; the two stores should remain separate, with an explicit mapping only for the messages/state fields that AG-UI exposes.

CryoThrust avatar Sep 04 '26 05:09 CryoThrust

Issue Evaluation

Category: enhancement | Area: area/ext/integration (AG-UI) | Status: Evaluated — feasible

Feasibility: feasible. Verified on current main: the AG-UI snapshot/delta event types exist in the protocol model (AguiEvent, AguiEventType), but AguiStreamContext exposes no emit*Snapshot APIs, AguiAdapterConfig.emitStateEvents is not consumed by the core converters, there is no AguiActivityConverter, and the built-in converters only emit lifecycle/message/tool events. Snapshot emission currently exists only in the copilotkit example; no AguiSnapshotStore / hydrate layer exists. Scope: agentscope-extensions-agui (stream context, converter registry, adapter config) plus a persistence/hydrate component. Compatibility: additive; no breaking changes expected if snapshot emission is opt-in via emitStateEvents. Recommendation: proceed — but the store abstraction (what is snapshotted, TTL, hydrate ordering vs. live events) deserves a short design note before implementation.


Automated evaluation by github-manager-bot

oss-maintainer avatar Sep 14 '26 15:09 oss-maintainer

您好,您发给我的邮件已收到。

shenghuitian avatar Oct 14 '26 08:10 shenghuitian