Skip to content

[Copilot] Define a structured streaming event protocol with cancel and reconnect #27

Open

Description

@helsome

Background

Folio 已经有基础 streaming 能力,但真实 Copilot 不能只把 LLM token 当成一条字符串流。一次回答还包含工具调用、金融数据查询、来源发现、citation 绑定、错误、取消和最终完成状态。

如果 renderer 只消费裸 text delta,后续很容易出现:消息重复、工具状态丢失、引用最后一刻才跳出来、网络重连后重复内容、取消按钮只停 UI 不停 runtime 等问题。

需要把 Copilot streaming 提升为稳定、可版本化的事件协议。

Requirements

定义统一 stream event envelope,至少支持等价事件:

  • run_started
  • message_started
  • text_delta
  • tool_started
  • tool_progress(适用时)
  • tool_result
  • citation_added / evidence update
  • status
  • error
  • cancelled
  • message_completed / run_completed

每个 event 至少包含:

  • protocol version;
  • run/message id;
  • monotonic sequence id;
  • event type;
  • timestamp;
  • typed payload。

Lifecycle

  • renderer 可主动 cancel,且 cancellation 必须传播到实际 Agent/model/tool runtime;
  • transport 中断后可基于 run id / sequence 进行合理 reconnect/resume 或明确失败;
  • 重复 event 不应导致文本、tool card、citation 重复插入;
  • partial answer 在 error/cancel 时应保留,并显示明确终止状态;
  • stream completion 与 persistence 使用同一最终状态,避免 UI 显示完成但数据库仍 running。

Security / UX

Related: #17 #18 #19

Acceptance Criteria

  • Copilot 不再依赖仅有裸字符串 delta 的隐式协议。
  • text、tool、citation、error、completion 至少都有 typed event。
  • event 有稳定 sequence,可以安全处理 duplicate/out-of-order 情况。
  • Cancel 会真实停止 runtime,而不是只隐藏 loading。
  • transport 中断后至少存在明确 reconnect/resume contract。
  • partial answer 在失败/取消后可读且状态明确。
  • 同一 stream event contract 可被持久化/replay 用于测试。
  • 真实跑一次包含模型输出 + 至少一个 tool call + citation 的 Copilot 回答,并在中途分别测试 cancel 与 transport interruption。PR 附事件序列和 UI 结果。

Non-goals

Activity

  1. shi-felix commented on Sep 11, 2026

    @shi-felix
    Collaborator

    Hi, I'd like to take this one.

    I'm an AI application developer focused on Agent engineering. I've built an AgentEvent streaming protocol used across Electron and Web clients (unified model backend, event bus, per-session context), and a multi-channel Agent platform, so this issue maps directly onto what I've already done: structured event envelopes, monotonic sequencing, cancel propagation all the way down to the runtime, and reconnect/resume semantics.

    My plan:

    1. Propose a versioned event envelope schema (protocol version, run/message id, monotonic sequence id, event type, timestamp, typed payload) as a short ADR for community review.
    2. Draft the event types from the issue list as TypeScript types plus runtime validation.
    3. Implement cancel propagation (renderer -> actual Agent/model/tool runtime) and run-id/sequence-based reconnect/resume.
    4. Add idempotency handling so replayed events never duplicate text, tool cards, or citations.

    I'll also keep the constraints of #17/#18/#19 in mind: redaction before tool payloads reach the UI, and a single final state shared between stream completion and persistence. Happy to hear feedback before I start the implementation.

  2. shi-felix commented on Sep 11, 2026

    @shi-felix
    Collaborator

    Proposal: Stream Event Protocol v1 (ADR draft)

    Thanks for scoping this out. I did a quick read of the current code before drafting, so this is grounded in the existing AgentEvent layer rather than a rewrite:

    • Events already flow kernel -> kernelHost -> webContents.send('agent:event', ...) -> preload -> renderer atoms (IPC channel is there).
    • run-manager already owns the single final state (run.status / run.answer → runs.json), and cancelRun already propagates to the runtime.
    • What's missing vs. the issue's requirements: a protocol version, a monotonic sequence, typed payload contracts, independent cancelled / tool_progress / citation_added / status events, and reconnect/resume semantics.

    Here is the proposal for review before I start implementing.

    1. Event envelope

    export interface StreamEventEnvelope {
      protocolVersion: 1;          // versioned for forward compat
      runId: string;               // identifies one run
      messageId: string;           // equals runId in v1, split out later if needed
      sequence: number;            // monotonic per run; idempotency key = runId + sequence
      type: StreamEventType;
      timestamp: string;           // ISO 8601 UTC; display only, never identity
      payload: StreamEventPayload; // discriminated by type
    }

    2. Event types and payloads (12 events)

    export type StreamEventType =
      | 'run_started' | 'message_started'
      | 'text_delta' | 'tool_started' | 'tool_progress' | 'tool_result'
      | 'citation_added' | 'status'
      | 'error' | 'cancelled'
      | 'message_completed' | 'run_completed';
    
    export type StreamEventPayload =
      | { type: 'run_started'; input: string; startedAt: string }
      | { type: 'message_started' }
      | { type: 'text_delta'; text: string }                    // incremental, append-only
      | { type: 'tool_started'; callId: string; name: string; input?: unknown }
      | { type: 'tool_progress'; callId: string; progress?: unknown }
      | { type: 'tool_result'; callId: string; name: string; result: unknown }
      | { type: 'citation_added'; citationId: string; sourceId: string }   // ties into #30/#20
      | { type: 'status'; phase: 'thinking' | 'searching' | 'working'; detail?: string } // no chain-of-thought
      | { type: 'error'; code: string; message: string; retryable: boolean }
      | { type: 'cancelled'; reason: 'user' | 'budget' | 'runtime'; partial: { text: string } }
      | { type: 'message_completed' }
      | { type: 'run_completed'; stopReason: 'completed' | 'cancelled' | 'error' | 'budget' };

    Note: today's message_delta carries a full answer snapshot; the new protocol moves to text_delta increments. See the compat window in §5.

    3. Idempotency · cancel · reconnect

    Capability Contract
    Idempotency renderer dedupes on runId + sequence; replayed events never re-insert text, tool cards, or citations
    Cancel renderer cancelRun -> runtime propagates -> runtime explicitly emits cancelled (no more inferring from run_failed); partial answer is preserved
    Reconnect client reconnects with lastSequence; gap range is replayed (resume), already-consumed events are not re-applied
    Final-state parity UI stopReason and persisted run.status come from the same single final state in run-manager (aligns with #18)

    4. Security (aligns with #19)

    • status exposes only task phases/activity, never hidden chain-of-thought.
    • Tool payloads go through redaction before reaching the UI.
    • The renderer never executes model-returned code.

    5. Migration path

    1. Envelope + types land in packages/shared/src/kernel/events.ts first (pure types, zero runtime change) — this could be its own tiny PR.
    2. Runtime event loop (run-manager) emits the new typed events.
    3. Transport upgrade (kernelHost + preload), renderer consumes the new protocol.
    4. Compat window: keep message_delta as a "resume snapshot backfill" event — transport emits a full snapshot once on reconnect, then only text_delta increments.

    Open questions for reviewers

    1. Resume data source: today only the final answer is persisted (runs.json), there is no event log. For v1 I propose the runtime keeps in-memory events for the lifetime of a run, and persisting an event log is deferred (ties into [Reproducibility] Persist immutable run manifests for Agent / Deep Research #21 immutable run manifests). OK?
    2. status.phase enum: is thinking / searching / working sufficient, or should it be derived from actual Copilot steps?
    3. messageId vs runId: merge them in v1 and split only when a single message can span multiple runs?

    Happy to adjust per your feedback before I write code.

  3. added
    claimed
    on Sep 11, 2026
  4. 9 remaining items

  5. github-actions commented on Sep 21, 2026

    @github-actions

    @sjr666666 这个 Issue 已认领超过 7 天,目前没有发现关联的 open PR,也没有看到最近 7 天的进度更新。

    如果仍在推进,请在 3 天内 留一条简短进度说明(包括正在等待的前置依赖也可以);如果已经有 PR,请贴出链接。若 3 天内没有回应,认领会自动释放,方便其他贡献者接手。

  6. github-actions commented on Sep 25, 2026

    @github-actions

    @sjr666666 在提醒后 3 天内没有进度回应,且仍未发现关联的 open PR;本次认领已自动释放。Issue 保持开放,可以重新认领。

  7. removed
    claimed
    on Sep 25, 2026
  8. wenyuxuan19-stack commented on Oct 18, 2026

    @wenyuxuan19-stack
    Contributor

    /claim

    我来处理持久化重放日志的 run 保留策略修复,已提交 PR #342:https://github.com/helsome/folio/pull/342。

    本次范围:按最近一次有效事件保留 run,与内存历史的 LRU 语义一致,避免裁剪时丢失近期活跃 run 的重放历史;补充交错事件、重复/倒退序号、磁盘重载与游标重放测试。28 项聚焦测试及全部工作区类型检查通过。

    此 PR 对应 #27 的一个独立子范围,其他 streaming 协议验收仍需后续推进。

  9. added
    claimed
    on Oct 18, 2026
  10. github-actions commented on Oct 18, 2026

    @github-actions

    @wenyuxuan19-stack 已认领该 Issue,并已自动设为 Assignee。提交 PR 时请在描述中写 Closes #27。

  11. github-actions commented on Oct 26, 2026

    @github-actions

    @wenyuxuan19-stack 这个 Issue 已认领超过 7 天,目前没有发现关联的 open PR,也没有看到最近 7 天的进度更新。

    如果仍在推进,请在 3 天内 留一条简短进度说明(包括正在等待的前置依赖也可以);如果已经有 PR,请贴出链接。若 3 天内没有回应,认领会自动释放,方便其他贡献者接手。

  12. removed
    claimed
    on Oct 29, 2026
  13. github-actions commented on Oct 29, 2026

    @github-actions

    @wenyuxuan19-stack 在提醒后 3 天内没有进度回应,且仍未发现关联的 open PR;本次认领已自动释放。Issue 保持开放,可以重新认领。

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions