fix(webui): update usage and tool progress during active turns (#6553)

* fix(webui): stream model status and usage during active turns

* fix(webui): keep live rounds and active-run status consistent

* fix(webui): reuse existing run indicators without extra status text

* fix(webui): preserve live activity and batch durable delivery

Cancel and drain sibling tools when progress notifications fail, retain balanced checkpoints, and keep model telemetry separate from answer provenance.

Group-commit already queued activity at the channel delivery boundary while preserving FIFO, generation ownership, per-envelope admission, and commit-before-fanout semantics. Isolate invalid members without dropping valid neighboring events.

Retain tool detail lazy grouping and cover scheduling, cancellation, persistence, encoding failures, and projection regressions.

* test(webui): separate standard-library imports in batch regression

* test: tighten live execution checks and clarify contracts

* refactor: remove redundant live execution comments

* refactor: settle tool results through one output path
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-04 16:27:24 +08:00
1 parent 006a535537
commit 8ff04aad2b
52 files changed
+2065 -211

No files matched your search

+58 -11
View File
@@ -80,6 +80,7 @@ _TURN_DISPLAY_EVENTS: frozenset[str] = frozenset({
"stream_end",
"message",
"file_edit",
"model_request",
"turn_end",
})
MAX_SESSION_MENTIONS = 8
@@ -563,6 +564,11 @@ class WebUITranscriptRecorder:
async def append(
self, chat_id: str, event: dict[str, Any], *, metadata: dict[str, Any] | None,
) -> bool:
return await self.append_many(chat_id, [event], metadata=metadata)
async def append_many(
self, chat_id: str, events: Sequence[dict[str, Any]], *, metadata: dict[str, Any] | None,
) -> bool:
if self.sessions is None:
return True # A transport-only channel has no durable session service.
@@ -570,14 +576,27 @@ class WebUITranscriptRecorder:
if not isinstance(generation, str) or not generation:
self._log.warning("history event has no admitted generation for {}", chat_id)
return False
facts: list[HistoryFact] = []
valid = True
for event in events:
try:
fact = fact_from_record(_record_for_append(event))
if len(events) > 1:
# An invalid member must not roll back otherwise valid activity.
fact.encode()
facts.append(fact)
except (ValueError, TypeError) as exc:
self._log.warning("history append failed for {}: {}", chat_id, exc)
valid = False
if not facts:
return False
try:
fact = fact_from_record(_record_for_append(event))
await self.sessions.state.append_history(webui_session_key(chat_id), [fact],
await self.sessions.state.append_history(webui_session_key(chat_id), facts,
expected_generation=generation)
except (OSError, ValueError, TypeError, sqlite3.Error, SessionConflictError, SessionOperationQueueFullError) as exc:
self._log.warning("history append failed for {}: {}", chat_id, exc)
return False
return True
return valid
def _next_turn_seq(self, chat_id: str, turn_id: str) -> int:
key = (chat_id, turn_id)
@@ -1292,7 +1311,7 @@ def build_webui_trace_detail_response(
events = [
event
for record in lines[group.start:group.stop]
if (
if record.get("event") != "model_request" and (
event := _client_projection_event(
record,
augment_user_media=None,
@@ -1496,8 +1515,19 @@ def _client_projection_event(
projected["reason"] = reason
return projected
if event == "turn_end":
projected = {"event": "turn_end", **common}
if event in {"turn_end", "model_request"}:
projected = {"event": event, **common}
if event == "model_request":
request_id, run_id = record.get("request_id"), record.get("run_id")
sequence, phase = record.get("sequence"), record.get("phase")
if (
not isinstance(request_id, str) or not request_id
or not isinstance(run_id, str) or not run_id
or not isinstance(sequence, int) or isinstance(sequence, bool) or sequence < 1
or phase not in ("started", "completed", "failed", "cancelled")
):
return None
projected.update(request_id=request_id, run_id=run_id, sequence=sequence, phase=phase)
latency_ms = record.get("latency_ms")
if isinstance(latency_ms, int | float) and latency_ms >= 0:
projected["latency_ms"] = int(latency_ms)
@@ -1511,8 +1541,8 @@ def _client_projection_event(
for item in cast(list[object], raw_round_usages)
if (sanitized := _sanitize_turn_usage(item)) is not None
]
if round_usages:
projected["round_usages"] = round_usages
if round_usages or event == "model_request":
projected["round_usages"] = round_usages[-8:] if event == "model_request" else round_usages
context_window = record.get("context_window_tokens")
if isinstance(context_window, int | float) and context_window >= 0:
projected["context_window_tokens"] = int(context_window)
@@ -1552,6 +1582,10 @@ def _client_projection_deferred_trace_groups(
trace_count = 0
for index, record in enumerate(lines):
# Usage belongs to the turn, not the activity body. It must not split
# one deferred tool group into many eagerly loaded fragments.
if record.get("event") == "model_request":
continue
is_activity = (
record.get("event") == "message"
and record.get("kind") in {"tool_hint", "progress"}
@@ -1591,6 +1625,7 @@ def _client_projection_page_event_count(turn: list[dict[str, Any]]) -> int:
"message",
"file_edit",
"context_compaction",
"model_request",
"turn_end",
}
return max(1, sum(record.get("event") in supported for record in turn))
@@ -1608,7 +1643,7 @@ def _client_projection_events(
deferred_groups = _client_projection_deferred_trace_groups(lines)
deferred_until = 0
for index, record in enumerate(lines):
if index < deferred_until:
if index < deferred_until and record.get("event") != "model_request":
continue
if record.get("event") == WEBUI_FORK_MARKER_EVENT:
if fork_boundary_event_index is None:
@@ -1635,7 +1670,10 @@ def _client_projection_events(
)
event["text"] = _trace_summary(last_text)
event.pop("tool_events", None)
receipts = _projection_receipts(lines[group.start:group.stop])
receipts = _projection_receipts([
grouped for grouped in lines[group.start:group.stop]
if grouped.get("event") != "model_request"
])
if receipts:
event["projection_receipts"] = receipts
if detail_ref is not None:
@@ -1737,8 +1775,9 @@ def build_webui_thread_response(
before: str | None = None,
after: str | None = None,
stats: TranscriptReplayStats | None = None,
include_model_requests: bool = False,
) -> dict[str, Any] | None:
"""Return canonical transcript events for the WebUI projector."""
"""Return canonical events, hiding additive request events from old clients."""
replay_stats = stats or TranscriptReplayStats()
lines, page = _select_transcript_page(
history=history,
@@ -1821,6 +1860,14 @@ def build_webui_thread_response(
augment_assistant_media=augment_assistant_media,
augment_assistant_text=augment_assistant_text,
)
if not include_model_requests:
# Select pages and stable identities before capability filtering, so an
# older client's cursors still navigate the same durable transcript.
if fork_boundary_event_index is not None:
fork_boundary_event_index = sum(
event["event"] != "model_request" for event in events[:fork_boundary_event_index]
)
events = [event for event in events if event["event"] != "model_request"]
replay_stats.replay_ms += int((time.perf_counter() - replay_started) * 1000)
payload["projection"] = "events"
payload["events"] = events