Skip to content

Agent host: responses render only at turn end because the optimistic turn start is never retired #332087

Open

Agent suggestions

Public preview

Description

@RyanEwen

Enabling the agent-host debug logging settings stops the chat rendering incrementally. The response still arrives at the same speed, but nothing is painted until the turn finishes, at which point the entire reply appears at once. Two separate settings each cause it on their own.

This is easy to miss because the settings are exactly what you turn on to investigate a chat problem, and turning them on changes the behaviour you are trying to observe.

Steps to reproduce

  1. In a Claude agent-host session, send a prompt that produces a long, pure-text answer with no tool calls, for example "Without using any tools at all, write a numbered list from 1 to 60 where each line is the number followed by one sentence about database indexing."
  2. Watch the response render.
  3. Set chat.agentHost.ahpJsonlLoggingEnabled to true, reload the window, and send the same prompt.

Expected: the text streams in continuously in both cases.

Actual: with the setting on, the chat shows only the thinking indicator for the whole turn, then the complete answer appears in a single update.

Measurements

Sampled once per second by reading the length of the last .interactive-response element and counting distinct values, so each "update" is a visible change on screen.

Fresh profile (empty user-data-dir), identical build, same dev container and agent host:

Settings Distinct updates in a ~35s response
none 25
chat.agentHost.ahpJsonlLoggingEnabled 3
chat.agentHost.agentDebugLog.enabled 2

Existing profile, same build:

Settings Distinct updates
all three logging settings on 2
all three off 37

The third setting is github.copilot.chat.agentDebugLog.fileLogging.enabled. Turning off only the two chat.agentHost.* ones was not sufficient in the existing profile; all three had to be off.

The host is streaming normally

With AgentHostStateManager's envelope logging temporarily raised to info, a failing turn shows the host emitting 100 chat/delta envelopes, one or two every second, evenly across the turn, and ProtocolServer broadcasting each one. The frames are produced and sent correctly. Only the client rendering collapses into a single paint.

Why this does not look like ordinary slowness

Turn duration is unchanged: about 31 seconds with logging on and about 35 seconds with it off, for comparable output sizes. Work that merely competed for the thread would make the turn slower and produce fewer, laggier paints. Instead the turn takes the same time and produces no intermediate paints at all.

Notes toward a cause, not a diagnosis

I could not pin the mechanism, so this is offered as a lead rather than a conclusion.

Each received frame pays synchronous work before dispatch, in webSocketTransport:

this._ahpLogger?.log(message, 'c2s', getAhpLogByteLength(text));
this._onMessage.fire(message);

and inside AhpJsonlLogger.log:

const entry = { ...message, _ahpLog: meta };
let body = stringifyAhpLogEntry(entry);
this._pending.push(VSBuffer.fromString(line));

That is a clone, a full JSON.stringify, and two complete UTF-8 encodes per frame, since getAhpLogByteLength(text) re-encodes the raw text only to count its bytes while log() encodes the serialized line again. The double encode looks worth removing regardless of this bug.

However, the disk writes themselves are queued and non-blocking, so log() should not delay _onMessage.fire(), and the arithmetic does not obviously support saturation: the clearest failure is the light case, roughly 3 frames per second, where a few passes over a small payload should cost nothing. The fact that a second, independent setting (chat.agentHost.agentDebugLog.enabled) reproduces it suggests a shared effect of attaching any per-frame observer to the stream, rather than the cost of the logging itself.

Version

Visual Studio Code 1.1.3 (stable), server commit 110a328ea54b42367b803ec53ee0bf52ef26b419, dev container on linux-arm64, Windows 11 host.

Disclosure about the binary: this install carries local modifications to workbench.desktop.main.js and agentHostMain.js. The comparisons above hold the binary constant and vary only settings, and the effect also reproduces in a fresh profile, so the modifications are not implicated. Say if a clean-install reproduction would help and I will produce one.

AI disclosure: this issue and the related investigation were written with the assistance of AI.

Public patches and patcher scripts

Public patch catalog and patcher scripts · Source patch index. The public collection includes the maintained patchers, rollback instructions, regression scripts, and historical snapshots. Build restrictions and exact installer coverage are documented there.

Activity

  1. RyanEwen commented on Aug 22, 2026

    @RyanEwen
    ContributorAuthor

    Correction and an addition, both from further testing.

    The setting only gates half the logging

    I implied above that chat.agentHost.ahpJsonlLoggingEnabled controls AHP JSONL logging. It controls only the client-side loggers. The agent host writes its own AHP log unconditionally: all three WebSocketProtocolServer.create call sites in agentHostMain.ts pass the log options with no setting check,

    const wsServer = await WebSocketProtocolServer.create(
    	{ socketPath, connectionTokenValidate },
    	logService,
    	{ instantiationService, logsHome },
    );

    and _createAhpLogger() returns a logger whenever those options are present. Observed with the setting false: a live 2 MB ahp-...-agent-host-1-....jsonl in the container's log directory, still growing, in a session started minutes earlier. These accumulate per session and are never gated by anything the user can see.

    That looks worth fixing on its own, separately from the rendering problem: either honour the setting on the host side too, or document that the host always logs.

    The rendering fault is workspace-specific

    Two dev containers on the same machine, same VS Code build, same server commit, same shared agent-host bundle, same user profile with all logging settings off, measured minutes apart:

    Workspace Distinct updates in a ~40s response
    A 42
    B 2

    So disabling the client-side settings fixes some workspaces and not others, which means those settings are one trigger rather than the whole cause. The failing container runs a heavier extension set, and since the remote extension host is the process holding the AHP client, contention in that process is a plausible common factor for both triggers. I have not verified that, so treat it as a lead.

    The earlier measurements stand as recorded; this only narrows what they mean.

    AI disclosure: this comment and the related investigation were written with the assistance of AI.

  2. RyanEwen commented on Aug 22, 2026

    @RyanEwen
    ContributorAuthor

    Retracting part of my previous comment, and adding what further testing ruled out.

    "Workspace-specific" was wrong

    I reported that one dev container streamed (42 updates) while another did not (2). The first workspace now fails the same way with no configuration change, so that framing does not hold. The failure moves over time in a way I cannot yet predict, and the same prompt in the same window gives 42 updates at one point and 2 an hour later.

    Ruled out, with evidence

    • Extension-host contention. Sampling /proc in the container during a failing turn: the extension host used 0 to 1 CPU ticks per second, the agent host 1 to 2. Nothing is saturated.
    • Renderer saturation. A CPU profile of the renderer across a failing 40 second turn: 73% idle, roughly 0.3 seconds of JavaScript total, the rest attributed to (program). Top JS frames are trivial (probeDynamicHeightForItem 60ms, markdown parse and sanitize under 60ms combined).
    • Window focus and visibility. Throughout a failing turn the document reported visibilityState: "visible" and hasFocus: true, and an explicit Page.bringToFront changed nothing.
    • Client-side debug logging. Still off for all of the above.

    Confirmed: the host streams real answer text on time

    From the agent host's own AHP log for a failing turn, frames with content, starting two seconds in:

    12:54:20  chat/delta  "1"
    12:54:20  chat/delta  ". An"
    12:54:21  chat/delta  "index is a separate data structure that lets the"
    ...
    13:00:59  chat/turnComplete
    

    48 text deltas spread evenly across the turn. There is no long reasoning phase; the answer text exists from the start and simply is not shown.

    Net position

    Frames are produced on time by the host, both the extension host and the renderer are idle, the window is focused and visible, and nothing is painted until the turn completes. The stall is somewhere on the path between the agent host and the renderer, with both ends doing nothing while it happens.

    One reproducible asymmetry

    In the same window, minutes apart: a short response (8 list items, about 600 characters) streams normally, while a long one (60 items, about 6,500 characters) produces two updates. Repeated twice with the same result.

    AI disclosure: this comment and the related investigation were written with the assistance of AI.

  3. changed the title [-]Agent host: enabling AHP debug logging stops the chat rendering incrementally[/-] [+]Agent host: responses render only at turn end because the optimistic turn start is never retired[/+] on Aug 22, 2026
  4. RyanEwen commented on Aug 22, 2026

    @RyanEwen
    ContributorAuthor

    Root cause found, and it is not the logging setting. The framing in the title is wrong and I retract it.

    What is actually happening

    The client applies its own chat/turnStarted optimistically and holds it in ChatStateSubscription._pendingActions until the backend echoes it back carrying the originating clientSeq. In every failing turn I measured, that echo never retires the pending action, so the start stays pending for the whole turn.

    _recomputeOptimistic() rebuilds the optimistic state on every confirmed action by replaying the pending list on top of confirmed state. Replaying a turn start resets activeTurn to a fresh empty turn, so activeTurn.responseParts reads as empty no matter how many deltas have already been folded into confirmed state.

    The UI reads the optimistic state. In _observeTurn, turn$ resolves to the correct turn by id for the whole turn, but its responseParts is empty, so autorunPerKeyedItem never creates a per-part observer and _setupMarkdownPart is never called. On completion the turn moves into state.turns, which a replayed turn start does not touch, and the entire response becomes visible in one step.

    Measurements

    Instrumented renderer, dev container, single turn, a prompt producing about 2.4 KB of markdown and no tool calls.

    value
    chat/delta envelopes reaching the renderer 17, from 8.0s to 19.4s
    envelopes passing ChatStateSubscription._isRelevantEnvelope 17 of 17, channel matched
    confirmed activeTurn.responseParts.length 1, from 8.0s onward
    optimistic activeTurn.responseParts.length after rebase 0, on all 19 rebases
    pending actions throughout the turn [chat/turnStarted], never retired
    _setupMarkdownPart first called 19.4s, at chat/turnComplete
    markdown emits 1, carrying all 2,432 characters

    The transport, the channel routing and the reducer are all behaving. The deltas are folded into confirmed state correctly and then discarded by the optimistic overlay on every recompute.

    The code already anticipates the missing clientSeq

    _promotePendingTurnStartIfTerminal exists for exactly this reason:

    // A backend-originated terminal turn action may arrive without the clientSeq
    // that would normally confirm our optimistic turn start. Promote that start
    // first so the terminal action can close it instead of leaving it pending.

    It fires only for chat/turnComplete, chat/turnCancelled and chat/error, which is precisely why the text lands all at once: the promotion does happen, just not until the turn is over.

    Fix

    Promote on the first backend action naming the turn instead of only on a terminal one.

    -			this._promotePendingTurnStartIfTerminal(envelope.action);
    +			this._promotePendingTurnStart(envelope.action);
    
    -	private _promotePendingTurnStartIfTerminal(action: StateAction): void {
    -		// A backend-originated terminal turn action may arrive without the clientSeq
    -		// that would normally confirm our optimistic turn start. Promote that start
    -		// first so the terminal action can close it instead of leaving it pending.
    +	/**
    +	 * Confirms an optimistic turn start from the first backend action naming its
    +	 * turn, since a backend-originated action may arrive without our clientSeq.
    +	 */
    +	private _promotePendingTurnStart(action: StateAction): void {
     		if (!isChatAction(action)) {
     			return;
     		}
    -		if (action.type !== ActionType.ChatTurnComplete && action.type !== ActionType.ChatTurnCancelled && action.type !== ActionType.ChatError) {
    +		const turnId = 'turnId' in action ? action.turnId : undefined;
    +		if (turnId === undefined) {
     			return;
     		}
    -		const index = this._pendingActions.findIndex(p => p.action.type === ActionType.ChatTurnStarted && p.action.turnId === action.turnId);
    +		const index = this._pendingActions.findIndex(p => p.action.type === ActionType.ChatTurnStarted && p.action.turnId === turnId);
     		if (index === -1) {
     			return;
     		}
     		const [{ action: pendingAction }] = this._pendingActions.splice(index, 1);
    -		if (this._confirmedState && (!this._confirmedState.activeTurn || this._confirmedState.activeTurn.id !== action.turnId)) {
    +		if (this._confirmedState && (!this._confirmedState.activeTurn || this._confirmedState.activeTurn.id !== turnId)) {
     			this._confirmedState = this._applyReducer(this._confirmedState, pendingAction);
     		}
     	}

    After the fix

    Same prompt, same build, same window.

    before after
    DOM updates during the turn 2 13
    _setupMarkdownPart first called 19.4s (turn end) 7.8s (first part)
    markdown emits 1 16, spread over 12 seconds
    rebases resetting parts to 0 19 1, before the backend confirmed the turn

    The node unit suite is green: 15,162 passing, 0 failing.

    On the intermittency reported earlier

    Earlier comments here attributed the failure to debug settings, then to specific workspaces, then to created versus restored sessions. All three were wrong and I retract them. The real variable is whether the echoed chat/turnStarted retires the pending optimistic action: when it does, streaming works, and when it does not, the overlay masks the whole turn. I have not established what makes the echo carry the clientSeq on some turns and not others, and the fix does not depend on that, since it retires the pending start on the first action naming the turn either way.

    Fix is up as #332122, with a unit test that fails on main and passes with the change.

    AI disclosure: this comment and the related code were written with the assistance of AI.

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

Metadata

Metadata

Assignees

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