import { Disposable } from "../../../../../base/common/lifecycle.js"; import { IObservable } from "../../../../../base/common/observable.js"; import { URI } from "../../../../../base/common/uri.js"; import { ICommandService } from "../../../../../platform/commands/common/commands.service.js"; import { ILogService } from "../../../../../platform/log/common/log.service.js"; import { IAuthenticationService } from "../../../../services/authentication/common/authentication.service.js"; import { IVoiceTranscriptStore } from "../../../agentsVoice/common/voiceTranscriptStore.service.js"; import { IVoiceClientService } from "../../common/voiceClient/voiceClientService.service.js"; import { IMicCaptureService } from "./micCaptureService.service.js"; import { ITtsPlaybackService } from "./ttsPlaybackService.service.js"; import { IVoiceToolDispatchService } from "./voiceToolDispatchService.service.js"; import { IVoicePlaybackService } from "../../common/voicePlaybackService.service.js"; import { IAgentSessionsService } from "../agentSessions/agentSessionsService.service.js"; import { IAgentHostConnectionsService } from "../../../../../platform/agentHost/common/agentHostConnectionsService.service.js"; import { IChatService } from "../../common/chatService/chatService.service.js"; import { IChatWidgetService } from "../chat.service.js"; import { IWorkbenchEnvironmentService } from "../../../../services/environment/common/environmentService.service.js"; import { ITelemetryService } from "../../../../../platform/telemetry/common/telemetry.service.js"; import { IConfigurationService } from "../../../../../platform/configuration/common/configuration.service.js"; import { IAccessibilitySignalService } from "../../../../../platform/accessibilitySignal/browser/accessibilitySignalService.service.js"; import { IAccessibilityService } from "../../../../../platform/accessibility/common/accessibility.service.js"; import { INotificationService } from "../../../../../platform/notification/common/notification.service.js"; import { IStorageService } from "../../../../../platform/storage/common/storage.service.js"; import { IPromptsService } from "../../common/promptSyntax/service/promptsService.service.js"; import { IChatEntitlementService } from "../../../../services/chat/common/chatEntitlementService.service.js"; import { IVoiceSessionController } from "./voiceSessionController.service.js"; export type VoiceState = "idle" | "listening" | "processing" | "speaking" | "error"; export declare function isVoiceEntitled(chatEntitlementService: IChatEntitlementService): boolean; export interface IPendingToolConfirmation { readonly type: "approval" | "input"; readonly sessionLabel: string; readonly sessionResource: URI; readonly description: string; approve(): void; deny(): void; } export interface ITranscriptTurn { readonly speaker: "user" | "assistant"; readonly text: string; /** Stable-recognition prefix of `text`. User turns only; empty otherwise. */ readonly committed: string; /** True while the user is still speaking (live recognition). */ readonly isPartial: boolean; } export type VoiceNewSessionPreparationResult = "prepared" | "sent" | "failed"; /** * Whether a chat input owns the current Voice Mode session. A session that * targets a draft belongs only to the input whose host owns that draft. */ export declare function isVoiceSessionActiveForInput(inputFocused: boolean, targetSession: URI | undefined, hasDraftTarget: boolean, sessionResource: URI | undefined, ownsDraftTarget?: boolean): boolean; export declare class VoiceSessionController extends Disposable implements IVoiceSessionController { private readonly voiceClientService; private readonly micCaptureService; private readonly ttsPlaybackService; private readonly voiceToolDispatchService; private readonly voicePlaybackService; private readonly agentSessionsService; private readonly chatService; private readonly commandService; private readonly authenticationService; private readonly voiceTranscriptStore; private readonly logService; private readonly environmentService; private readonly telemetryService; private readonly configurationService; private readonly accessibilitySignalService; private readonly accessibilityService; private readonly chatWidgetService; private readonly notificationService; private readonly promptsService; private readonly chatEntitlementService; private readonly connectionsService; private readonly storageService; readonly _serviceBrand: undefined; private readonly _voiceState; readonly voiceState: IObservable; private readonly _statusText; readonly statusText: IObservable; private static readonly _MAX_TURNS; private readonly _transcriptTurns; readonly transcriptTurns: IObservable; private readonly _isConnected; readonly isConnected: IObservable; get isUsingGptLive(): boolean; private readonly _isConnecting; readonly isConnecting: IObservable; private readonly _isReconnecting; readonly isReconnecting: IObservable; /** User-facing microphone mute. When set, captured audio is not forwarded to * the backend, but the session stays connected so the user can unmute and * resume without a new handshake. Reset to `false` on (re)connect. */ private readonly _isMuted; readonly isMuted: IObservable; /** Set when the connection closed terminally (e.g. another window took over * the session). Suppresses the reconnect display path so the controller * settles to a clean, restartable state instead of a stuck "Reconnecting...". * Cleared on the next {@link connect}. */ private _fatalDisconnect; private readonly _pendingToolConfirmations; readonly pendingToolConfirmations: IObservable; /** * Session resources whose pending confirmations were dropped at a terminal * teardown (disconnect/fatal). The always-on tracker excludes them so it * can't repopulate {@link _pendingToolConfirmations} from the still-pending * old session before the next {@link connect}, which clears this set. */ private readonly _suppressedConfirmationSessions; private readonly _targetSession; readonly targetSession: IObservable; private readonly _hasDraftTarget; readonly hasDraftTarget: IObservable; private _pttHeld; /** True once speech is detected in the current passive hands-free turn. */ private _speechDetectedInTurn; /** * Whether the current held turn's `ptt_start` was passive (a hands-free * open mic: auto-listen or barge-in). A passive turn tells the backend not * to latch `user_is_speaking`; a deliberate press (non-passive) does latch. * Read by {@link _prepareForPlayback} to decide whether aborting the held * turn (which sends no `ptt_end`) is safe. Only meaningful while `_pttHeld`. */ private _pttCurrentTurnPassive; private _remoteAudioSpeaking; private _pttToggleMode; /** * True while a passive hands-free barge-in listen is streaming during the * assistant's playback (opened by `_startBargeInListen`). It is NOT toggle * mode — an explicit `pttDown()` promotes this stream into a user-driven * interrupt rather than finishing it. Cleared once the turn ends, is * promoted, or transitions to a normal listening turn when playback stops. */ private _bargeInListenActive; /** When true, the auto-listen loop is suppressed (user pressed Stop * Recording). Cleared on the next explicit `pttDown` or on connect. */ private _autoListenSuppressed; /** * Auto-listen hold taken by UI that must not be talked over (see * {@link setAutoListenHeld}). Deliberately separate from * `_autoListenSuppressed`, which pttDown, playback prep and disconnect all * clear as part of normal turn-taking - a hold has to outlive all of that. */ private _autoListenHeld; /** Timestamp (ms) until which unscoped voice sends and pending responses are dropped after a * discarded turn, so buffered speech from a focus-change discard can't be * misrouted to the newly focused session. Cleared on the next `pttDown`. */ private _suppressSendToChatUntil; private readonly _discardedInputTurns; /** One-shot session that the next finalized turn must be submitted to, * regardless of which session is focused. Set when listening is stopped on * a focus change while the user is actively dictating, so their words land * in the session they were dictating into rather than the newly focused * one. Consumed by the next `send_to_chat`; also cleared on `pttDown` and * after {@link _PINNED_SUBMIT_EXPIRY_MS}. */ private _pinnedSubmitSession; private _pinnedSubmitTimer; /** Armed on a fresh connect (hands-free); consumed on `session_init` to * enter listening once the backend acks the session. */ private _enterListenOnSessionInit; private _pttCurrentTurnId; private _transcriptionTurnState; private _window; private readonly _voiceEventDisposables; private readonly _voiceRequestDisposables; private readonly _windowFocusDisposables; private readonly _voiceAutorunDisposable; /** * Holds the model reference for a session created by {@link newSessionAsTarget} * until a host adopts it. `ChatService` deletes empty untitled local sessions * once their last reference is disposed, so releasing this eagerly would leave * {@link _targetSession} pointing at a session that no longer exists whenever * no chat pane picks the new session up. */ private readonly _newSessionRef; /** * Watchdog that resets `isConnecting` (and surfaces feedback) if the connect * handshake never completes. Armed up front in {@link connect} so a step that * hangs (e.g. resolving the GitHub session while a chat request is in flight) * can't leave the toolbar spinner stuck indefinitely. */ private readonly _connectWatchdog; private static readonly _CONNECT_TIMEOUT_MS; /** * Grace window between the socket opening and the backend acking the session. * A rejected connect is accepted and then closed (so the close frame can carry * a reason), which means `onopen` fires for doomed sockets too; committing * `isConnected` on open would flash a connected UI on every retry. Doubles as * the "session_init never arrived" fallback for entering hands-free listening. */ private readonly _sessionAckGrace; private static readonly _SESSION_ACK_GRACE_MS; /** Connect telemetry held until the backend acks; see {@link _commitConnected}. */ private _pendingConnectTelemetry; private _connectAttemptGeneration; private _sessionInitializationGeneration; private readonly _autoApprovedSessions; private _transcriptFadeTimer; private _pttMaxDurationTimer; private static readonly _PTT_MAX_DURATION_MS; /** Short-tap threshold: if the key is held for less than this, enter * toggle mode where a second tap finishes the recording. */ private static readonly _PTT_TOGGLE_THRESHOLD_MS; /** Debounce before re-entering listening after assistant stops speaking. */ private static readonly _AUTO_LISTEN_QUIET_MS; private _delayedMicStopTimer; private _autoListenTimer; private _pttWaitingForPlayback; /** Guards auto re-listen: only re-arm after a reply has actually played. */ private _replyPlayedSinceSend; /** Set after send_to_chat; blocks auto-listen until the reply TTS starts. */ private _awaitingReplyAudio; /** * Session awaiting the user's reply. Other-session narration is unsolicited * even while `_awaitingReplyAudio` is true, so stale on-focus re-reads drop. */ private _awaitingReplyForSession; private _awaitingReplyWatchdog; private readonly _audioQueue; private _currentPlaybackSessionId; private _currentPlaybackResponseId; private _currentPlaybackNarration; private _currentPlaybackTranscript; private _lastSpokenResponseSessionId; private _currentPlaybackFinalized; private _isProcessingQueue; private _suppressIncomingAudio; /** Turn/response ids whose playback was cancelled by barge-in. */ private readonly _interruptedAudioIds; /** * Session resource string most recently *shown* to the user in any chat * widget - updated on focus AND on a widget's view-model swap. `chatWidgetService` * only reports focus for the DOM-focused widget, so opening a session from the * sessions list (which reveals it in the chat view pane without moving DOM * focus off the list) leaves `lastFocusedWidget` pointing at the previously * viewed session. That stale focus makes the first click fail to flush a * buffered response or re-narrate a pending confirmation (it only works on the * second click, once the widget finally takes focus). Tracking the last-shown * session across all widgets closes that gap. */ private _lastShownSessionId; private readonly _widgetSessionListeners; /** * Agents-window active-session override. Beats focus/last-shown heuristics, * which are unreliable with multiple rendered chat widgets. */ private _activeSessionShown; /** * True once an embedder drives the active session via `setActiveSessionShown`. * Focus/last-shown heuristics are then disabled. */ private _externalActiveSessionMode; /** * Buffered audio for responses that arrived while their session was not the * one shown to the user. Keyed by session, each session holds a FIFO list of * whole responses (a background session that produces several updates before * the user returns keeps ALL of them, in order). Every response is a group of * audio chunks plus a `finalized` flag (set on its final chunk) so * continuation chunks attach to the still-open response rather than starting a * new one. Flushed - all responses, in order - when the session is shown. */ private readonly _deferredResponses; /** * Maps a backend chat resource string (bare provider scheme, e.g. * `copilotcli:/`) to the UI agent-host session resource string * (`agent-host-:/`) that owns it. The voice backend tags a * background (unfocused) session's audio with its bare backend id, while the * UI - focus tracking, defer/flush buffer keys, and the sessions-list pending * indicator - all work in the agent-host resource space. Canonicalizing an * incoming id through this map keeps a deferred response's buffer key aligned * with the resource we flush on focus, so it is read exactly once when the * session becomes focused rather than stranded forever. Rebuilt from the live * session list and cleared on disconnect. */ private readonly _uiResourceByBackendId; /** Sessions currently showing a pending-response indicator because they are * awaiting confirmation while unfocused (client-driven, no audio needed). */ private readonly _confirmationPendingSessions; /** Narration ids of confirmation prompts whose confirmation was resolved * (e.g. the user pressed Allow) before the narration finished. Any * `audio_response` chunks echoing one of these ids are dropped so a * just-answered approval is never read aloud. Bounded, and an id is * removed once its final chunk arrives. */ private readonly _cancelledPendingNarrationIds; /** Sessions showing a pending-response indicator because a reply COMPLETED * while they were unfocused (client-driven, mirrors the confirmation * indicator). Maps to the response summary to narrate when the session is * focused - stored so playback is reliable even if the model has since * unloaded. Independent of the audio-defer buffer ({@link _deferredResponses}), * which only exists when the backend proactively sent audio. */ private readonly _pendingResponseSummaries; /** * Keys (session resource string, or ``''`` for untagged audio) of responses * we are currently playing live rather than deferring. Recorded on the first * chunk so the remaining chunks of that response follow the same decision and * a response is never split between playback and the deferred buffer. * * A SET rather than a single key so overlapping responses for DIFFERENT * sessions each keep their own routing: a live reply for session B must not * clear the live route of an in-flight reply for session A (which would send * A's continuation chunks down the focus-based fallback). Two concurrent * responses for the SAME session still can't be told apart without a backend * response/turn id; that remains a known limitation. */ private readonly _liveReplyKeys; /** * Per-response routing decision, keyed by the backend-echoed `responseId` * (see {@link IVoiceAudioResponse.responseId}). A response's fate (`live` vs * `deferred`) is decided ONCE, when its first chunk is seen, and every later * chunk of that same response follows it - so interleaved responses for * different sessions never steal each other's routing (which a single global * key did) and a response is never split between playback and the buffer. A * deferred entry is flipped to `live` when its session is focused (the buffer * is flushed), so post-flush continuation chunks keep playing. Entries are * removed on the final chunk. Used only when the backend echoes a responseId; * otherwise the legacy session-keyed {@link _liveReplyKeys} path applies. */ private readonly _responseRoutes; private readonly _responseSessionIds; private readonly _ownershipDroppedResponseIds; /** * Per-session record of the reply we most recently read for a session (played * live or flushed from the deferred buffer): its transcript and when it was * read. The backend re-emits a session's reply when that session becomes * active (on focus), which would double-read it. Durable dedup is mirrored in * `_lastHeardTranscriptById`; this record also supports activation/flush * bookkeeping. */ private readonly _recentlyReadResponse; /** In-flight backend re-narrations we are dropping, so continuation chunks are * dropped too (not just the first). Keyed by responseId when the backend * echoes one (so a different same-session response streaming concurrently is * NOT dropped), else by sessionId as a fallback. */ private readonly _droppingRenarration; /** Narration ids this client explicitly requested via {@link _narrate} (the * `narration_id` we sent on `request_narration`, which the backend echoes as * `responseId` on the audio it produces). Audio whose `responseId` is one of * these was solicited by us and must never be classified as an unsolicited * duplicate re-narration, even when its transcript matches content we * read (e.g. narrating a completed reply on focus). Ids are pruned when their * stream ends (final chunk) and cleared on disconnect. */ private readonly _solicitedNarrationIds; /** * Last reply transcript heard per session. This is the durable exactly-once * guard: a backend re-read of that response is always dropped. */ private readonly _lastHeardTranscriptById; private readonly _sessionAudioCache; private _replaySourceNode; private readonly _prevSessionStates; private readonly _userCancelledSessions; private static readonly _USER_CANCEL_SUPPRESS_MS; /** After a focus-change discard, drop a stray backend `send_to_chat` for * this long so late-finalized buffered speech isn't misrouted. */ private static readonly _DISCARD_SEND_SUPPRESS_MS; /** How long a focus-change submit stays pinned to the original session * while the backend finalizes the turn and emits `send_to_chat`, before the * pin is cleared so it can't misroute a much later, unrelated turn. */ private static readonly _PINNED_SUBMIT_EXPIRY_MS; private readonly _confirmationFlushWatchdogs; private static readonly _CONFIRMATION_FLUSH_DELAY_MS; /** * Latest state change per session, buffered and flushed once after a short * settle window (see {@link _emitPendingStateChanges}) so a rapid * ``thinking <-> idle`` replay storm coalesces into a single net emission * instead of spamming the backend with contradictory transitions. Each entry * also records the burst's baseline (``fromState``/``fromDetail``) so a wobble * that returns to its starting state is recognized as net-zero. */ private readonly _pendingStateChanges; private _stateChangeEmitTimer; private static readonly _STATE_CHANGE_SETTLE_MS; /** Model refs eagerly loaded for sessions awaiting input (no UI focus needed). */ private readonly _eagerModelRefs; /** Sessions with an in-flight eager model load, to dedupe concurrent loads. */ private readonly _eagerModelLoading; /** * Sessions whose ``idle`` transition is being deferred until their chat * model loads, so the narration can include ``last_response_summary``. * While a session id is in this set we suppress emitting a premature, * summary-less ``idle`` to the backend (see _buildSessionContext). */ private readonly _pendingIdleNarration; /** * Sessions that entered `thinking` during this controller's lifetime and are * therefore genuinely awaiting a completion. A summary-only transition (idle * state unchanged, but `last_response_summary` appeared/changed) only counts * as a NEW reply when the session is in this set - otherwise an OLD summary * surfacing because a dormant model was (re)hydrated would be mistaken for a * fresh response and wrongly light the sessions-list pending indicator. * Armed on an observed idle/waiting→thinking transition (never during eager * loading / replay) and consumed once the resulting idle+summary is accepted. */ private readonly _sessionsAwaitingResponseSummary; /** * Last response summary captured per session WHILE its chat model was * resident. Copilot/remote session models are disposed as soon as the user * switches away, so a completion that lands while the session is unfocused * would otherwise be reported to the backend as a summary-less ``idle`` and * never narrated (the eager reload to recover the summary races the switch's * re-disposal). Caching the summary here — independent of the model's * lifetime — lets the no-model paths still report ``last_response_summary``. * Refreshed whenever a resident model exposes a summary; cleared when the * session starts a new turn (``thinking``) so a stale reply is never narrated. */ private readonly _lastResponseSummaryById; /** * The exact text last narrated per session, used to de-duplicate narration * requests. Before asking the backend to speak a session's pending item we * check this map: an identical text was already spoken (live or on a prior * focus), so we skip it — this single guard replaces the old summary-identity * dedup, the recently-read window, and the focus/live double-narrate races. * Cleared for a session when it starts a new turn (`thinking`) so a repeated * identical reply later still narrates. */ private readonly _lastNarratedText; /** * Narrations that could not be sent because the socket was closed (see * {@link _narrate}). Replayed once on the next `session_init` so a reply or * confirmation that landed during a disconnect is still spoken on reconnect. */ private readonly _pendingNarrationRetries; /** * Narrations we requested (got a `narration_id` back) but whose audio has not * yet finished arriving. Keyed by that narration id. A request being accepted * by the backend is NOT proof the reply was heard - the audio can still be * dropped, deferred, or never returned - so we defer marking the reply as * narrated ({@link _lastNarratedText}) and clearing its pending indicator * until the final audio chunk for this id arrives (see {@link _markNarrationHeard}). * A safety timer releases the in-flight guard if no audio ever comes, so a * later focus/state event can retry rather than the reply being lost. */ private readonly _pendingSolicitedNarrations; private static readonly _SOLICITED_NARRATION_AUDIO_START_TIMEOUT_MS; private static readonly _VOICE_PROGRESS_INITIAL_DELAY_MS; private static readonly _VOICE_PROGRESS_INTERVAL_MS; private static readonly _MAX_VOICE_PROGRESS_PER_REQUEST; private static readonly _MAX_CONFIRMATION_NARRATION_CHARS; private static readonly _MAX_QUESTIONNAIRE_QUESTIONS; private static readonly _MAX_QUESTIONNAIRE_OPTIONS; private static readonly _MAX_CONFIRMATION_FIELD_CHARS; private readonly _voiceProgressListeners; private readonly _voiceProgressSessionByResponse; private readonly _lastSpokenAtBySession; private static readonly _SESSION_REF_RELEASE_TIMEOUT_MS; private readonly _sessionRefReleaseWatchers; private readonly _floatingResponseWatchers; /** * Narrations the backend bounced (`narration_ack` `busy`) or cancelled * (`narration_interrupted`), awaiting retry. Keyed by canonical session key, * latest-wins (at most one pending per session). Retried on the * `narration_unblocked` nudge and replayed on `session_init`/`session_resumed`, * since a dropped socket loses any in-flight nudge. See * `_retryDeferredNarration`. Cleared on a new turn (`thinking`) or teardown. */ private readonly _deferredNarrations; /** * The confirmation detail text last actually HEARD (final audio arrived) per * canonical session key. Confirmations are deliberately excluded from * {@link _lastNarratedText} (a tool can legitimately re-raise the identical * prompt), so this is the per-occurrence "already spoken" marker that stops a * still-pending confirmation from being re-narrated on every refocus (see * {@link _activateShownSession}). Recorded only once its audio finalizes (in * {@link _markNarrationHeard}), so a confirmation that was deferred/dropped and * never heard is still retried on focus. Cleared when the session leaves * `waiting_for_confirmation` (in the autorun) so a genuinely new confirmation - * even with identical text - narrates again. */ private readonly _narratedPending; private _telemetrySessionIndex; private _telemetrySessionStart; private _telemetryTurnCount; private _telemetryReconnectCount; private _telemetryFirstConnect; private _telemetryConnectStartMs; private _telemetryLastConnectMs; private _telemetryPttDownMs; private _telemetryPttUpMs; private _telemetryFirstTranscriptionMs; private _telemetryTtsInterrupted; private _entitlementCheckScheduled; private _usingGptLiveByok; /** Cached GitHub login resolved on connect; used as transcript partition key. */ private _userLogin; /** Locally-persisted turn id of the last assistant turn we appended. * Used as the ancestor of the next user turn we persist. */ private _lastPersistedTurnId; /** Last-N cross-session timeline entries — voice turns, voice tool * calls, coding-session events, plus a synthesized first-2-sentences * summary of the latest Copilot reply per active session. Sent to the * BE on the next start_session and then cleared — single-shot recall. */ private _pendingPriorTimeline; /** * How many of the most recent persisted timeline entries we forward * to the BE (across all kinds). Coding-agent reply synthesis happens * on top of this — we add one entry per active coding session. */ private static readonly PRIOR_TIMELINE_ENTRY_LIMIT; /** * Max sentences of Copilot's last reply we include per active coding * session when synthesizing ``coding_agent_reply`` entries. Bounded * because the full reply can be arbitrarily long. */ private static readonly CODING_AGENT_REPLY_SENTENCE_LIMIT; constructor(voiceClientService: IVoiceClientService, micCaptureService: IMicCaptureService, ttsPlaybackService: ITtsPlaybackService, voiceToolDispatchService: IVoiceToolDispatchService, voicePlaybackService: IVoicePlaybackService, agentSessionsService: IAgentSessionsService, chatService: IChatService, commandService: ICommandService, authenticationService: IAuthenticationService, voiceTranscriptStore: IVoiceTranscriptStore, logService: ILogService, environmentService: IWorkbenchEnvironmentService, telemetryService: ITelemetryService, configurationService: IConfigurationService, accessibilitySignalService: IAccessibilitySignalService, accessibilityService: IAccessibilityService, chatWidgetService: IChatWidgetService, notificationService: INotificationService, promptsService: IPromptsService, chatEntitlementService: IChatEntitlementService, connectionsService: IAgentHostConnectionsService, storageService: IStorageService); connect(window: Window & typeof globalThis): Promise; private _isVoiceModeEnabled; setActiveWindow(window: Window & typeof globalThis): void; /** * Arms (or re-arms) the watchdog that resets voice mode if the connect * handshake never completes. Without this, a hung connect step leaves the * toolbar spinner spinning forever with no way to recover; on timeout we drop * back to a disconnected state and tell the user so they can retry. */ private _armConnectWatchdog; /** * Promote an open socket to a live session. Called when the backend acks * (`session_init` / `session_resumed`), or from the ack grace timer if no ack * arrives. `viaFallback` also runs the hands-free auto-listen that the ack * would otherwise have triggered. */ private _commitConnected; /** Emit the connect telemetry the socket-open path deferred until admission. */ private _flushConnectTelemetry; private _resetFailedConnection; /** * Exclude the currently-pending confirmation sessions from the always-on * tracker until the next {@link connect}, so a terminal teardown's cleared * snapshot can't be repopulated from the still-pending old session. */ private _suppressPendingConfirmationsUntilConnect; disconnect(source?: "explicit" | "internal"): void; /** DEV ONLY: Simulate a connected session with fake transcript for UI testing. */ simulateConnection(): void; /** * Handle a terminal, non-recoverable close (e.g. another window took over the * single voice session -> backend closes this one with 4008). Unlike a * transient drop (see {@link _onConnectionLost}), there is no reconnect, so * fully tear down capture/playback and settle to a clean, restartable state * instead of leaving the UI stuck on "Reconnecting...". Fires before the * connection-state change, so `_fatalDisconnect` short-circuits that path. */ private _handleFatalDisconnect; private _fatalDisconnectMessage; private _reconnectingMessage; private _promptFatalDisconnect; private _endTelemetrySession; private _onConnectionLost; private _beginTranscriptionTurn; private _markTranscriptionTurnPending; private _resetTranscriptionTurn; private _handleTurnAutoEnded; private _handleBargeIn; private _rememberInterruptedPlaybackIds; private _rememberInterruptedAudioId; private _isInterruptedAudio; private _dropInterruptedDeferredAudio; private _handleTranscription; pttDown(source?: "explicit" | "auto" | "connect", forceNewTurn?: boolean): void; pttUp(source?: "explicit" | "internal", forceFinish?: boolean): void; setAutoListenHeld(held: boolean): void; setMuted(muted: boolean): void; stopListening(source?: "explicit" | "internal"): void; discardListening(): void; finishListeningAndSubmitTo(session: URI): void; private _setPinnedSubmitSession; private _consumePinnedSubmitSession; /** * Finish the current push-to-talk press. * * ``reason`` is ``'local'`` for a user-driven end (button release / toggle * tap / keyword) — the mic drains its tail and the ``onPttEnd`` → ``ptt_end`` * path fires. It is ``'auto'`` when the backend ended the turn itself * (``turn_auto_ended``): the mic is aborted with no drain and NO ``ptt_end`` * is sent for the turn. ``'discard'`` * throws the press away on a focus change: like ``'auto'`` the mic is aborted * with NO ``ptt_end`` (so the backend never finalizes it into a * `send_to_chat`), but the state settles to ``idle`` rather than * ``processing`` since nothing is being sent. */ private _finishPtt; private _playRecordingStoppedSignal; markUserCancelled(sessionId: string): void; setTargetSession(resource: URI | undefined): void; getLastSpokenResponseSession(): URI | undefined; setDraftTarget(): void; promoteDraftTarget(resource: URI): void; newSessionAsTarget(): void; /** * Release the session created by {@link newSessionAsTarget} once voice stops * targeting it, so it is no longer kept alive on its behalf. */ private _releaseNewSessionRefUnlessTargeting; private _prepareDirectVoiceForInputChange; private _setTargetSession; private _scheduleDelayedMicStop; private _isHandsFreeEnabled; private _shouldEnterListenOnSessionInit; private _isLiveTranscriptEnabled; /** * Strip a trailing stop phrase (e.g. "send it") from a transcript before it * is sent to chat. The backend is supposed to strip the matched phrase from * `agents.voice.turn.stopPhrases`, but when it doesn't the raw phrase leaks * into the request, so we defensively strip it client-side. Matching is * case-insensitive, ignores trailing punctuation, and only strips on a word * boundary so phrases aren't removed from the middle of a word. */ private _stripStopPhrase; /** * Whether this controller's window currently has OS focus. In multi-window * setups (e.g. an editor window + the agents window) each window has its own * controller/WebSocket, so without this gate every open window would re-arm * hands-free auto-listen and reply simultaneously. Only the focused window * should keep listening (#8507). */ private _isWindowFocused; /** Called when this controller's window loses OS focus. Aborts any open * passive turn so the background window stops recording while the newly * focused window can take over hands-free listening (#8507). */ private _onWindowBlur; /** Called when this controller's window gains OS focus. Re-arms hands-free * auto-listen so the focused window is always the one that listens (#8507). */ private _onWindowFocus; /** Re-enter listening via synthetic short tap. */ private _enterAutoListen; private _playListeningStartedSignal; /** * Hands-free barge-in listen: open a passive PTT streaming turn WITHOUT * interrupting the assistant's playback, so the backend's server-VAD keeps * receiving mic audio and can detect the user talking over the assistant. * * Unlike `pttDown()` (a user-driven interrupt) this does NOT stop playback, * clear the audio queue, or suppress incoming audio. The backend decides * when a real interruption happened and emits `speech_started` / `barge_in` * (already wired to cut off TTS). If the user stays silent the turn simply * stays open and becomes the next listening turn once playback ends * (`onPlaybackStopped` sees `_pttHeld` and stays in 'listening'). * * Hands-free session initialization keeps capture warm before the backend can * send playback. Idempotent: a no-op while a turn is already held. */ private _startBargeInListen; /** Debounced re-listen after assistant stops speaking. */ private _scheduleAutoListen; private _clearAutoListenTimer; /** Block auto-listen until reply audio arrives (with 30s watchdog). */ private _setAwaitingReply; private _clearAwaitingReply; private _acceptVoiceInput; private _sendVoiceRequest; private _watchVoiceProgress; private _isVoiceProgressEnabled; private _cancelVoiceProgress; /** * Send transcription text to the target session or active chat. * * Returns `true` once the text has been accepted by a chat surface or send * request, and `false` when delivery was rejected or no send occurred. */ private _sendTranscriptionToChat; private _holdSessionRefUntilResponseStops; private _prepareNewSessionTarget; /** * Watch a session's latest response and surface it in the floating window * transcript. Called when voice sends to a non-visible session so the user * can see the reply without switching the chat panel. */ private _watchResponseForFloatingWindow; private _pushTurn; /** * Start a new user turn at the tail of the buffer. If the previous tail is * already an empty user turn (rapid PTT toggle before any transcription * landed), reuse it instead of pushing a duplicate empty entry. */ private _startUserTurn; private _updateUserTurn; /** * Update the assistant turn at the tail of the buffer with `text`. * * The streaming TTS pipeline pushes a monotonically-growing transcript * with each audio chunk of a response. `startNewTurn` distinguishes * the first chunk of a NEW response (push a fresh assistant turn) * from continuation chunks of the SAME response (replace the tail's * text as the transcript grows). This prevents two distinct * assistant responses from collapsing into one when they happen * back-to-back without an intervening user turn (e.g. proactive * narration followed by a command reply). */ private _setAssistantTurn; private _cancelTranscriptFade; /** * Append a final entry to the on-disk transcript store. * * Entry ids are generated locally — voice_code's backend has no persistent * conversation memory today, so there's no server-issued id to defer to. * Each new entry chains off the previous one via ``ancestorIds`` so a UI * can show the linear conversation order. * * ``user_voice`` and ``agent_voice`` are user-visible in the transcripts * pane. ``agent_tool_call`` and ``coding_event`` are persisted only so we * can replay them as cross-session context to the backend on reconnect. */ private _persistEntry; /** Back-compat thin shim for the two existing voice call sites. */ private _persistTurn; /** * One-line, human/LLM-readable summary of a voice tool call for the * timeline. Backend's prior_timeline renderer expects this format — keep * it stable. * * send_to_chat(text="Open a new terminal and cd into the current directory.") * send_to_chat(text="Refactor upload service", new_session=true) * respond_to_session(...) */ private _renderToolCallSummary; /** * Convert persisted transcript turns into typed timeline entries for * the BE, then top up with a synthesized ``coding_agent_reply`` per * active coding session (first ~2 sentences of the latest Copilot * response). The synthetic entries are *not* persisted — they read * live ``IChatModel`` state so the summary stays fresh on every * reconnect. * * Output is chronological (oldest first), matching what the BE * renders into its ``[PRIOR_CONTEXT]`` block. Synthetic * ``coding_agent_reply`` entries are appended at the end since they * represent the *current* state of coding sessions at reconnect. */ private _buildPriorTimeline; /** * Return the first ``n`` sentences of ``text``. Cheap regex split — * good enough for a prompt-prefix summary; we don't need perfect NLP * boundaries here. Falls back to a hard char cap if no terminator * shows up in the first 600 chars. */ private _firstSentences; /** * Record the backend→UI resource alias for an agent-host session so a response * the voice backend tags with the bare backend id resolves to this UI session * resource (the space in which focus, defer/flush buffer keys, and the pending * indicator operate). No-op for non-agent-host resources. */ private _recordSessionAlias; /** Move every session-scoped entry (and the visible indicator) from a bare * backend id to its canonical UI key once the alias becomes known. */ private _rekeySession; /** * The single canonical key for a session: the UI agent-host resource when the * backend tagged it with the bare backend id, else the id unchanged. Every * session-scoped collection is keyed by this, so the two id spaces never * diverge and ownership checks are plain O(1) map/set lookups. */ private _sessionKey; /** Whether any of the three indicator owners still holds this canonical key. */ private _pendingOwned; /** * Canonicalize a session id to the UI agent-host resource space when the * backend tagged it with the bare backend id. Untagged / non-agent-host ids * pass through unchanged. */ private _canonicalSessionId; /** * Refresh the cached focused session and flush any response that was held * for the session that just became focused. */ /** * The session the user is currently looking at, read live from the * last-focused chat widget (the same source that fires * `onDidChangeFocusedSession`). Reading live - rather than trusting a value * cached on the change event - protects the defer/flush decision from a * missed or out-of-order focus event, which would otherwise leave a response * buffered forever or drop it into the wrong session. */ private _getFocusedSessionId; private _onFocusedSessionChanged; /** * Track a chat widget's view-model so we notice when a session is shown in it, * even if that widget never takes DOM focus (so `onDidChangeFocusedSession` * stays silent). Opening a session from the sessions list reveals it in the * chat view pane this way. */ private _trackWidgetSession; private _rebindMaterializedSession; /** A session became visible (opened/revealed): treat like a focus change — make it active, flush any buffered response, clear its pending indicator, and narrate its pending item. */ private _onSessionShown; /** Make a shown/focused session active: flush its buffered response, clear its pending indicator, and narrate its pending confirmation/response (loading the model first if a confirmation's detail isn't resident). */ private _activateShownSession; /** Ask the backend to narrate a session's pending item, de-duped by the exact text last spoken for it ({@link _lastNarratedText}) and by any in-flight request for the same text ({@link _pendingSolicitedNarrations}); the single narration trigger for both live and on-focus paths. Returns `true` when a request was actually SENT - NOT that the reply was heard (the audio may still be dropped/deferred/never arrive). The reply is marked narrated and its pending indicator cleared only once its audio finalizes (see {@link _markNarrationHeard}). */ private _narrate; private _markSolicitedNarrationAudioStarted; private _handleSolicitedNarrationAudioStartTimeout; /** True while any tracked solicited narration is still waiting for its audio * to start (i.e. a no-audio watchdog is still outstanding). */ private _hasNarrationAwaitingAudio; private _clearPendingSolicitedNarration; private _notifyCheckpointPlaybackComplete; private _restoreVoiceStateAfterNarrationTimeout; /** Mark a solicited narration's reply as actually heard once its final audio * chunk arrives (responseId === the narration id we sent). Only now do we set * the exactly-once dedup and clear the session's pending-response indicator, * since a mere request acceptance is not proof the reply played. */ private _markNarrationHeard; /** * Handle a `narration_ack` for a `request_narration` we sent. * * `accepted` needs nothing: the request is already tracked in * {@link _pendingSolicitedNarrations} and its audio will finalize normally. * `busy` means the backend could not play right now (user speaking / reply in * flight); it will nudge us with `narration_unblocked` when the guard clears, * so we stop tracking the id as in-flight and remember it for a revalidated * retry. `invalid` and legacy `suppressed` are terminal, so we drop them entirely. */ private _handleNarrationAck; /** * Handle a `narration_interrupted`: an accepted, in-flight narration was * cancelled by barge-in. The backend evicted the id, so stop tracking it and * defer a revalidated retry (driven by the `narration_unblocked` that follows * once the barge-in turn ends). */ private _handleNarrationInterrupted; private _deferInterruptedNarration; /** * The `narration_unblocked` nudge fired for a deferred narration. Revalidate * against the current session state and only re-request if it is still * warranted, reusing the same id for a busy retry when the text is unchanged * (so the backend dedups a lost ack), but minting a fresh id after an * interruption because the old id is tombstoned for late-audio suppression. * If it is no longer warranted (resolved, or a different kind), drop it. */ private _retryDeferredNarration; private _retryPendingNarration; /** Drop a deferred narration. */ private _clearDeferred; /** The pending item a session would narrate now (waiting confirmation prompt or completed reply summary), from the resident model or cached summary/status; returns undefined (kicking off a load) if a confirmation's detail isn't ready. */ private _currentNarratable; /** * The id of the pending item a session is showing right now, or `''`. * * Used as a per-occurrence fingerprint in state-transition detection: the * prose `detail` two forms produce can be identical, so without this, * replacing one form with another inside `waiting_for_confirmation` looks * like no change at all and is never narrated. */ private _pendingIdFor; /** * The identity of one *occurrence* of a narratable item, for dedup. * * Two forms can ask the same questions and two tools can raise the same * prompt, so keying "already heard" on text alone swallows the second one. * Text is only a fallback for narratables with no structured pending. */ private _narratableIdentity; /** * The spoken form of a session's pending question form, if it has one. * * This asks for *the form*, not a particular question in it: the backend owns * the draft of answers so far, so only it knows which question the form is * waiting on. Naming one here would leave a partially answered form silent, * since the client only ever sees question 1. The text is used during the * debounce window before the backend's mirror catches up, which is by * definition first sighting. */ private _questionNarratable; /** Identify the exact structured approval being narrated, not merely its text. */ private _pendingNarrationReference; /** * True when a session is awaiting confirmation but its confirmation detail is * not yet available (model not loaded, or the pending-confirmation part hasn't * rendered). Used to avoid narrating a detail-less confirmation on the first * context send followed by the detailed one moments later. */ private _confirmationDetailPending; /** * The session the user is actively working with for the purpose of routing * voice audio: the explicitly targeted session if one is set, otherwise the * session most recently shown to the user (across all widgets, so an opened * session that hasn't taken DOM focus still counts), falling back to the raw * focused widget. This mirrors how `_buildSessionContext` computes the * backend's `is_active` session, so playback and the backend agree on which * session is "active" and everything else is a background narration. */ private _getActiveSessionId; /** * The session the user is currently looking at, used to route deferral and * decide which completions narrate immediately vs. defer + indicate. * * In focus-based (main-window) mode this is the LIVE focused session, NOT the * sticky `_lastShownSessionId`: that field is updated by any tracked chat * widget's view-model swap (see `_trackWidgetSession`), so while the backend * works a background session it can transiently point there and make that * session look "shown" - which suppressed deferral, the pending indicator, and * on-focus playback for responses. The confirmation indicator has always used * live focus (see `_reconcileConfirmationIndicators`) and worked correctly; * this keeps responses consistent with it. Opening a session still flushes its * buffer directly via `_onSessionShown`, so the sticky value isn't needed here. * Unlike {@link _getActiveSessionId} it ignores the sticky input * `_targetSession` (where the next utterance is sent, not what is viewed). */ private _shownSessionId; private _pinActiveSessionAsTarget; setActiveSessionShown(resource: URI | null | undefined): void; activateSession(resource: URI): void; /** * Routing decision for one audio-response chunk. When the backend echoes a * per-response id, decide the whole response's fate once (on its first chunk), * store it in {@link _responseRoutes}, and make every later chunk of that id * follow it - so interleaved responses for different sessions never steal each * other's routing and a response is never split. Without a responseId, defer * to the legacy session-keyed {@link _shouldDeferResponse}. */ private _shouldDeferResponseStream; /** Whether two session ids refer to the same session, tolerant of the two id * spaces (bare backend id vs UI resource) and trivial serialization * differences. Mirrors the matching used to flush buffered responses so the * defer decision and the flush agree on identity. */ private _isSameSession; /** Alias-aware read of the last text narrated for a session, used for * exactly-once dedupe. */ private _getLastNarratedText; private _wasResponseHeard; /** Clear the last-narrated dedupe for a session. */ private _clearLastNarratedText; /** Whether a response for `sessionId` should defer: true unless it is the * session currently shown to the user (untagged audio → play). A reply the * user is awaiting is NOT exempted: if they switched away before it arrived, * it is deferred like any other background narration and flushed on return. */ private _shouldDeferForSession; /** True when one of the session's buffered responses is the SAME stream as * `responseId` (so a live chunk for it is a promotion, not a new response). */ private _deferredBufferHasResponse; /** * A response is deferred when it is a background narration for a session the * user is NOT looking at. It plays immediately only for the shown session (or * when it is untagged audio); a reply the user was awaiting but has since * switched away from is deferred like any other background narration. * * The decision is made on the first chunk and recorded in `_liveReplyKeys`; * remaining chunks follow the same decision so a response is never split * between playback and the deferred buffer. This session-keyed heuristic is * the fallback for backends that don't echo a per-response id; when they do, * {@link _shouldDeferResponseStream} routes by that id instead. */ private _shouldDeferResponse; private _deferResponse; /** Find the buffered-response key for a now-shown session. The buffer is keyed * by the canonical session key ({@link _sessionKey}); a structural URI-equality * fallback guards a trivial serialization difference between the backend's * coding_session_id and the focused sessionResource. */ private _matchDeferredKey; /** Replays all buffered responses for a now-shown session, in arrival order. * Returns whether anything was flushed plus the normalized final transcript * of each response played, so the caller can mark _lastNarratedText only for * text that was actually read (never a newer, unplayed summary). */ private _flushDeferredResponse; private _isUserActivelySpeaking; /** * Get the controller out of listening/auto-listen and ready the playback slot * so an about-to-arrive (or just-buffered) narration actually plays instead of * being suppressed. Used before flushing a deferred response and before * narrating a freshly-shown session's pending item (e.g. a confirmation, which * carries no buffered audio and so never hits the flush path) - otherwise the * controller can sit in listening and the echoed audio is dropped, leaving the * user staring at a focused session that never speaks. * * Returns `true` when the playback slot is ready (no press held, or a passive * open-mic turn was torn down), and `false` when it deliberately preserved a * held non-passive press. A `false` return tells the flush caller to leave its * buffered audio deferred rather than play it over the user's live press. */ private _prepareForPlayback; /** * True when an incoming reply is a re-narration of a reply we recently read * for this session (played live or flushed from the deferred buffer). The * backend re-emits a session's reply when that session becomes active (on * focus), which would otherwise be read a second time. We drop it ONLY when * its transcript matches the last reply actually heard for the session. * That dedupe is durable: focus/context refreshes must never replay a response * the user already heard. A genuinely new reply (different text) still plays, * including while another reply from the same session is awaited. * The whole response (including continuation chunks) is dropped until final. * * This is purely content-based: it never suppresses a reply just because the * session was heard before, which is what let the backend's server-side * deferral of a NEW reply (delivered as an on-focus narration) be swallowed. */ private _isRenarration; /** Lowercase, collapse whitespace and strip surrounding punctuation so two * transcripts of the same reply compare equal despite minor formatting. */ private _normalizeTranscript; private _markPendingResponse; /** * Reconcile the sessions-list "pending response" indicator for confirmations. * A session that is awaiting user confirmation while NOT focused should show * the indicator; once it is focused or the confirmation is resolved the * indicator is cleared. This is driven purely from client-observed session * state, so it is accurate regardless of whether the backend narrates the * confirmation as audio. */ private _reconcileConfirmationIndicators; private _clearConfirmationIndicator; /** Drop a session's pending-response (completed-reply) indicator/summary. */ private _clearPendingResponse; /** Hide the sessions-list indicator only when no owner still needs it. The * same visible indicator is shared by three independent sources - an * unfocused confirmation, buffered deferred audio, and a completed * background reply - so it must stay visible until all are resolved. */ private _maybeHideIndicator; private _clearDeferredResponses; private _suspendPlaybackForHiddenSessions; private _preemptCheckpointPlayback; private _interruptAssistantPlayback; private _stopVoicePlayback; private _stopCurrentPlaybackAsInterrupted; /** * Stop reading an actionable pending request aloud once it has been resolved * (e.g. the user pressed Allow, or answered the form with the mouse, before * the narration finished). Cancels the session's in-flight * confirmation/question narration(s): drops their queued audio, remembers * their ids so trailing / not-yet arrived chunks are swallowed in the * `audio_response` handler, and cuts off playback if one of them is what is * currently speaking. The agent's subsequent real reply uses a different * narration id and is unaffected. * * Responses are deliberately exempt: a completed reply stays worth hearing * after the thing it describes has been dealt with, whereas a prompt for an * action that has already been taken is only confusing. */ private _stopPendingNarration; /** * A confirmation or question supersedes completed-response audio for the * same session. Do not make the user hear an older reply before the prompt * they can act on now. */ private _discardResponsesSupersededByPending; private _hasResponseAudioInFlight; private _enqueueAudio; private _playChunk; private _processQueue; private _replaySessionAudio; private _stopReplay; private _sendContext; /** * (Re)arm the settle timer that emits buffered session state changes. Each * detected transition resets the timer, so a rapid burst (e.g. the history * replay ``thinking <-> idle`` storm) is collapsed to one emission once the * state stops changing. See {@link _pendingStateChanges}. */ private _scheduleStateChangeEmit; /** React to a session reaching a narratable state. If it's the shown session, speak it now; a completed reply on another background session instead shows the sessions-list pending indicator and is read when focused. A new turn (`thinking`) clears both the dedup and any stale pending indicator. */ private _handleNarratableStateChange; /** The resident chat model for a session id, or `undefined` when it isn't loaded (or the id isn't a URI). */ private _modelForSession; /** * Flush the coalesced session state changes to the backend and persist only * true net changes to the local timeline. {@link _sendContext} rebuilds the * full context from the now-settled model state and `_sendDelta` merge-patches * against the last-sent snapshot, so an oscillation that returned to its prior * state produces no delta. Each buffered change carries the burst's baseline * (`fromState`/`fromDetail`); we compare the settled state against it so a * net-zero wobble is neither traced nor persisted as a `coding_event` (which * would otherwise replay a phantom transition to the backend on reconnect), * and a detail change reached via an intermediate state (e.g. * `waiting(old) → thinking → waiting(new)`) is still treated as detail-only. */ private _emitPendingStateChanges; /** * Paranoid mitigation for the "confirmation narration not fired while user * is on the same session" symptom. Even though the autorun calls * `_sendContext + flushSessionContext` at the transition, in practice * users observed that the BE-side narration ("I need approval to run X") * only fires after they navigate AWAY from the session. * * As a guarded fallback we schedule a single delayed context re-flush and * client-driven narration retry per session that's awaiting confirmation. * Backend auto-narration is disabled for this client, so re-sending context * alone cannot recover a missed local transition. `_retryPendingNarration` * revalidates the exact current occurrence and the common narration path * suppresses both in-flight and already-heard duplicates. * * The watchdog auto-clears once the autorun observes the session has left * `waiting_for_confirmation`. */ private _armConfirmationFlushWatchdog; /** * Check all sessions for state changes and send notifications to backend. * This catches state transitions for sessions without a loaded chat model * (which the autorun can't track via observables), and also regular chat * sessions that are not agent sessions. */ private _checkSessionStateChanges; /** * Scope confirmations to the active session before reporting to the backend. * * Only the active (focused/target) session's `waiting_for_confirmation` state * is reported as such; any OTHER session awaiting confirmation is downgraded * to `thinking` (and its confirmation detail dropped). This does two things: * * 1. The backend only ever sees a single confirmation, so it never asks the * user "which one do you want me to approve?". * 2. When the user focuses a session that was awaiting confirmation while * unfocused, `_buildSessionContext` starts reporting it as * `waiting_for_confirmation`. The backend observes the fresh * `thinking -> waiting_for_confirmation` transition and narrates the * confirmation at that moment (the "read it out on focus" behaviour). * * The sessions-list pending indicator for the unfocused confirmation is * driven separately from client-observed state (_reconcileConfirmationIndicators), * so it stays accurate even though the backend isn't told about it. */ private _reportedAgentState; private _getInputContext; private _hasSessionInProgress; private _buildSessionContext; /** * Eagerly load a chat model for a session that needs input but hasn't been * opened in the UI yet. Once loaded, the autorun observables will re-fire * with full confirmation detail so the backend can narrate properly. */ private _ensureModelLoaded; /** * Defer narrating a session's ``idle`` transition until its chat model is * resident, so the narration can include ``last_response_summary``. Remote/ * Copilot sessions don't keep their model loaded, so without this the * backend would only ever see a summary-less completion. Eagerly loads the * model; once it resolves the autorun re-fires and narrates with the summary. */ private _deferIdleNarrationUntilModelLoaded; /** * Cache (or invalidate) a session's response summary based on the current * state observed from its resident model. Called wherever a resident model's * state is computed so the summary survives the model's disposal. * - `idle` with a summary → cache it (the completed reply). * - `thinking` → a new turn started; drop the stale summary so a later * completion never narrates the previous reply. */ private _cacheResponseSummary; /** * Drop per-session caches for sessions no longer in the tracked set, so a * long-lived voice connection doesn't retain summaries/state for archived, * removed, or disposed sessions that will never be narrated again. */ private _pruneSessionCaches; /** * The state to report for a resident model, applying the idle-narration hold. * * When a completion is detected for an unfocused session we eagerly reload * its (disposed) model to recover ``last_response_summary``. That reloaded * model is briefly resident with an EMPTY response while its history is still * replaying, so reporting its bare ``idle`` now would ship a summary-less * completion (which the backend never narrates) AND consume the ``idle`` * transition before the summary exists. While the eager load is still in * flight we therefore hold — report the prior state — so the ``idle`` isn't * shipped until it can carry the summary. The load always resolves (its * callback clears ``_eagerModelLoading``), so the hold can never last forever. */ private _effectiveResidentState; private _visibleConfirmationText; private _boundedConfirmationLines; private _visibleQuestionnaireFromCarousel; private _visibleQuestionnaireFromToolInvocation; private _formatQuestionnaireNarration; private _formatChoiceLabels; private _formatPlanNarration; private _formatElicitationNarration; private _formatConfirmationNarration; private _formatToolNarration; private _formatToolNarrationFallback; private _formatToolAuthenticationNarration; private _selectPendingPart; private _isOpenPendingPart; private _getPendingConfirmationInfo; private _getAgentStateInfo; private _hasResolvedPendingToolApproval; /** * Describe what a session is waiting on, structurally. * * `_getAgentStateInfo` flattens the same state into `agent_state_detail`, * which is fine to *say* but cannot be *acted on*: a form becomes * `questions: `, losing the options, their values and the ids. This * returns what the backend needs to route an answer back to the exact part. * * Uses the same typed pending selection as narration, so the backend never * receives an id for a different action than the one the user heard. */ private _buildPendingPayload; private _plainText; private _classifyPendingType; private _getConfirmationDescription; private _autoApproveCheck; private _autoApprovePendingTools; private _getMachineId; submitFeedback(feedbackText: string): Promise<{ ok: boolean; error?: string; }>; }