From dd4cf8baeb0bcae33a6d5499f4c4472dda75ba9d Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:36:01 +0000 Subject: [PATCH] fix(flow): reconcile Agent turns and session caches - Merge local partial output into disconnected in-progress turns - Hydrate stored turns before send when local turns hold errors - Purge failed drafts, deleted session queries, and selected IDs - Wait for project details and user profile before send checks - Reconcile media statuses and elicitation timeouts with tiles - Replay question answers across detached streams and reconnects --- ts/agent_attachments.ts | 27 +- ts/agent_chat.ts | 130 +++++-- ts/agent_protocol.ts | 3 +- ts/agent_reconcile.ts | 737 ++++++++++++++++++++++++++++++++++++++++ ts/agent_settings.ts | 6 + ts/agent_turns.ts | 141 ++++++-- 6 files changed, 977 insertions(+), 67 deletions(-) create mode 100644 ts/agent_reconcile.ts diff --git a/ts/agent_attachments.ts b/ts/agent_attachments.ts index d2138dd..b97b51b 100644 --- a/ts/agent_attachments.ts +++ b/ts/agent_attachments.ts @@ -8,10 +8,12 @@ import { cleanMediaId, findMediaContainer, isTrashedTile, legacyMedia } from "./ import { agentAttachmentCompatibility } from "./frontend_compatibility"; import { bindMediaUpload, uploadMediaFiles, waitForMedia } from "./project_upload"; import type { MediaUploadExport, UploadProgress } from "./project_upload"; +import { frontendBuild, readBuildLabel } from "./frontend_builds"; +import { runtimeState } from "./state"; import type { FlowMediaPayload, FlowTile } from "./types"; /** Tile that can supply a reference in the active Flow project. */ -interface AttachmentTile extends FlowTile { +export interface AttachmentTile extends FlowTile { /** Asset ID shown in the project. */ id: string; /** ID of the primary image or video. */ @@ -88,7 +90,7 @@ function isMediaTile(tile: AttachmentTile): boolean { } /** Returns true when a media variant payload has finished generating or uploading. */ -function isReadyVariant(variant: FlowMediaPayload | undefined): boolean { +export function isReadyVariant(variant: FlowMediaPayload | undefined): boolean { if (!variant || typeof variant !== "object") return true; const source = readOwn(variant, "source"); const uploaded = readOwn(variant, "vp"); @@ -119,7 +121,7 @@ function findVariantByMediaId( } /** Resolves a tile and optional media variant matching a requested project asset or media ID. */ -function resolveRequestedAsset( +export function resolveRequestedAsset( tiles: AttachmentTile[], requestedId: string, ): { tile: AttachmentTile; variant?: FlowMediaPayload; variantId?: string } | undefined { @@ -206,6 +208,25 @@ function projectReference( ? reference : undefined; } +/** Reads current project tiles synchronously from the active page or bound project store. */ +export function readProjectTiles(page?: Record): AttachmentTile[] { + const format = frontendBuild(readBuildLabel())?.operations.agent_attachments; + if (page && format) { + const store = readOwn(page, format.store); + const tiles = readOwn(store, format.tiles); + if (typeof tiles === "function") { + try { + const list: unknown = tiles.call(store); + if (Array.isArray(list)) return list as AttachmentTile[]; + } catch { + // Fall back to other live store signals when the page store is initializing. + } + } + } + const boundMap = runtimeState.store?.isCurrent() ? runtimeState.store.getTileMap() : null; + return boundMap instanceof Map ? ([...boundMap.values()] as AttachmentTile[]) : []; +} + /** Uses separate keys for character IDs and media IDs. */ function referenceKey(reference: AttachmentReference, characterField: string): string { return reference.mediaType === "CHARACTER" diff --git a/ts/agent_chat.ts b/ts/agent_chat.ts index 169a09f..5c4197e 100644 --- a/ts/agent_chat.ts +++ b/ts/agent_chat.ts @@ -14,11 +14,19 @@ import type { StoredTurn, Transport, } from "./agent_protocol"; +import { + clearQuestionReplays, + isFailedDraftSession, + purgeFailedDrafts, + purgeSessionState, + reconcileQuestionReplays, + replayResumedQuestions, + submitQuestionAnswer, + waitForSendReadiness, +} from "./agent_reconcile"; import { agentSettingsOp, - resolveQueryClient, settingsWritePending, - waitForQuerySettlement, } from "./agent_settings"; import type { AgentInjector } from "./agent_settings"; import { @@ -278,18 +286,34 @@ async function savedTurns( ); } -/** Waits for active `PROJECT_DETAILS` queries before reading `canSend`. */ +/** Builds the reconciliation context for session caches and send readiness. */ +function cacheContext(bound: Binding) { + return { + projectId: bound.projectId, + page: bound.page, + transportField: bound.format.transport, + injector: bound.injector, + transport: bound.transport, + drafts: bound.drafts, + canSend: bound.canSend, + isCurrent: () => liveBinding(bound.projectId) === bound, + }; +} + +/** Builds the reconciliation context for question answers and reconnect replays. */ +function replayContext(bound: Binding, sessionId: string) { + return { + sessionId, + transport: bound.transport, + flow: bound.flow, + questions: bound.questions, + isCurrent: () => liveBinding(bound.projectId) === bound, + }; +} + +/** Waits for active `PROJECT_DETAILS` and `USER_PROFILE` queries before reading `canSend`. */ async function canSendReady(bound: Binding, signal?: AbortSignal): Promise { - if (bound.canSend()) return true; - const client = resolveQueryClient(bound.injector, bound.page); - await waitForQuerySettlement({ - client, - queryKey: ["PROJECT_DETAILS", bound.projectId], - ready: () => bound.canSend(), - canContinue: () => liveBinding(bound.projectId) === bound, - signal, - }); - return bound.canSend(); + return waitForSendReadiness(cacheContext(bound), signal); } /** Returns true if the project accepts a new Agent turn after `PROJECT_DETAILS` settles. */ @@ -357,13 +381,15 @@ async function send( const uploadResult = prepared?.uploaded_asset_ids.length ? { uploaded_asset_ids: prepared.uploaded_asset_ids } : {}; + clearQuestionReplays(id); if (!session.persisted) { + purgeFailedDrafts(cacheContext(bound)); bound.drafts.add(id); flow.init(transport, id, projectId); } else { loadStoredTurns(bound, id, saved); } - const number = Math.max(saved.length, local?.Vh.length ?? 0) + 1; + const number = saved.length + 1; let envelope = prepared?.message; if (!envelope) { const part = flow.finish(flow.setText(flow.mutable(flow.newPart()), text)); @@ -384,6 +410,9 @@ async function send( Aq: permission, }); } catch { + if (!session.persisted && isFailedDraftSession(transport, id)) { + purgeSessionState(cacheContext(bound), id); + } return failure("outcome_unknown", { session_id: id, turn: number, @@ -395,13 +424,24 @@ async function send( const result = conversation(bound, id, saved).find( (item) => item.turn === number, ); - return result - ? { ok: true as const, ...session, turn: result, ...uploadResult } - : failure("agent_submission_not_observed", { - session_id: id, - turn: number, - ...uploadResult, - }); + if (!result) { + if (!session.persisted && isFailedDraftSession(transport, id)) { + purgeSessionState(cacheContext(bound), id); + } + return failure("agent_submission_not_observed", { + session_id: id, + turn: number, + ...uploadResult, + }); + } + if ( + !session.persisted && + result.status === "failed" && + isFailedDraftSession(transport, id) + ) { + purgeSessionState(cacheContext(bound), id); + } + return { ok: true as const, ...session, turn: result, ...uploadResult }; } /** Applies a decision to one action from the requested turn. */ @@ -412,11 +452,17 @@ async function respond( stored: StoredTurn[], ) { const id = session.session_id; + reconcileQuestionReplays( + replayContext(bound, id), + stored, + STORED_TURN_IN_PROGRESS, + ); const current = conversation(bound, id, stored).at(-1); const action = - current?.turn === req.turn && - current?.pending_actions.find((item) => item.action_id === req.action_id); - if (!action) return failure("agent_action_not_pending"); + current && current.turn === req.turn + ? current.pending_actions.find((item) => item.action_id === req.action_id) + : undefined; + if (!current || !action) return failure("agent_action_not_pending"); if (action.type === "permission") { const decision = req.decision && PERMISSION_DECISIONS[req.decision]; if (!decision) return failure("invalid_agent_permission_decision"); @@ -440,12 +486,13 @@ async function respond( } else if (action.type === "question") { const answers = req.answers && questionAnswers(action, req.answers); if (!answers) return failure("invalid_agent_question_answers"); - bound.questions.OA({ - sessionId: id, - Ig: action.action_id, - Qj: answers, - hi: AGENT_SURFACE, - }); + const submitted = await submitQuestionAnswer( + { ...replayContext(bound, id), turn: req.turn ?? current.turn }, + action.action_id, + answers, + ); + if (submitted === "project_changed") return failure("agent_project_changed"); + if (submitted !== "ok") return failure("agent_action_not_pending"); } else { const canSend = await readyToSend(bound); if (liveBinding(bound.projectId) !== bound) @@ -457,6 +504,7 @@ async function respond( return failure("agent_turn_active_or_unavailable"); const plan = req.decision && PLAN_DECISIONS[req.decision]; if (!plan) return failure("invalid_agent_plan_decision"); + clearQuestionReplays(id); loadStoredTurns(bound, id, stored); bound.flow.plan(bound.transport, { ua: bound.projectId, @@ -543,6 +591,7 @@ export async function agentOp(request: AgentRequest) { ]); if (liveBinding(projectId) !== bound) return failure("agent_project_changed"); + purgeFailedDrafts(cacheContext(bound)); return { ok: true as const, project_id: projectId, @@ -565,15 +614,19 @@ export async function agentOp(request: AgentRequest) { request.action === "delete_session" ) { if (transport.ha.has(id)) return failure("agent_turn_active"); - if (!session.persisted) - return failure("agent_session_not_saved", { session_id: id }); if (request.action === "rename_session") { + if (!session.persisted) + return failure("agent_session_not_saved", { session_id: id }); const title = request.title?.trim() ?? ""; await transport.W1(id, title, projectId); return { ok: true as const, ...session, title }; } - await transport.yL(id); - transport.ka.yL(id); + if (session.persisted) { + await transport.yL(id); + if (liveBinding(projectId) !== bound) + return failure("agent_project_changed"); + } + purgeSessionState(cacheContext(bound), id); return { ok: true as const, ...session, deleted: true }; } @@ -603,6 +656,9 @@ export async function agentOp(request: AgentRequest) { }) ) return failure("agent_turn_cannot_resume"); + await replayResumedQuestions(replayContext(bound, id)); + if (liveBinding(projectId) !== bound) + return failure("agent_project_changed"); return { ok: true as const, ...session, @@ -617,10 +673,16 @@ export async function agentOp(request: AgentRequest) { current.Vh.length + 1 !== request.turn ) return failure("agent_turn_not_active"); + clearQuestionReplays(id); transport.ev(id); const turn = conversation(bound, id, stored).at(-1); return { ok: true as const, ...session, turn }; } + reconcileQuestionReplays( + replayContext(bound, id), + stored, + STORED_TURN_IN_PROGRESS, + ); const turns = conversation(bound, id, stored); if (request.action === "get_turn") { const turn = turns.find((item) => item.turn === request.turn); diff --git a/ts/agent_protocol.ts b/ts/agent_protocol.ts index 6d87743..7faf4ca 100644 --- a/ts/agent_protocol.ts +++ b/ts/agent_protocol.ts @@ -231,7 +231,8 @@ export type ReplyBlock = | { type: "permission"; card: PermissionCard } | { type: "question"; card: QuestionCard } | { type: "plan"; Gz: PlanCard } - | { type: "a2ui"; round: unknown }; + | { type: "a2ui"; round: unknown } + | { type: "view_agent_memory" }; /** Media counts and credits from a permission request. */ interface PermissionSummary { diff --git a/ts/agent_reconcile.ts b/ts/agent_reconcile.ts new file mode 100644 index 0000000..2d80b8a --- /dev/null +++ b/ts/agent_reconcile.ts @@ -0,0 +1,737 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Reconcile Agent turns, draft sessions, query caches, tile media, and question streams. + +import { readOwn } from "./angular"; +import { isReadyVariant, readProjectTiles, resolveRequestedAsset } from "./agent_attachments"; +import type { AttachmentTile } from "./agent_attachments"; +import type { + FlowAgentExports, + FlowAnswer, + LiveTurn, + QuestionResponder, + ReplyBlock, + StoredTurn, + Transport, +} from "./agent_protocol"; +import { COLD_QUERY_TIMEOUT_MS, resolveQueryClient, waitForQuerySettlement } from "./agent_settings"; +import type { AgentInjector, QueryClient } from "./agent_settings"; +import { cleanMediaId, delay, findMediaContainer, isTrashedTile, legacyMedia } from "./dom"; + +/** Poll interval while waiting for a detached bidirectional stream to reattach. */ +const STREAM_ATTACH_POLL_MS = 25; + +/** Poll interval while watching active question turns for in-place stream resets. */ +const REPLAY_WATCH_POLL_MS = 50; + +/** Flow surface used by Agent chat operations. */ +const AGENT_SURFACE = "SIDE_PANEL"; + +/** Decoded user message type returned by `FlowAgentExports.reply`. */ +type DecodedUser = ReturnType[0]; + +/** Decoded reply type returned by `FlowAgentExports.reply`. */ +type DecodedReply = ReturnType[1]; + +/** Media output entry reported on a formatted Agent turn. */ +export interface ToolMediaItem { + /** Identifier of the generated image or video. */ + media_id: string; + /** Current lifecycle status of the media item. */ + status: string; + /** Error code or message when generation fails. */ + error: string | number | undefined; +} + +/** Merged fields for a turn that remains in progress on the server after a disconnect. */ +export interface MergedTurnView { + /** Reconciled user message data. */ + user: DecodedUser; + /** Reconciled assistant reply text. */ + text: string; + /** Agent response identifier when available. */ + responseId: string | undefined; + /** Reconciled reply blocks. */ + blocks: ReplyBlock[]; + /** Server-side turn error, excluding local stream disconnect errors. */ + rawError: string | number | undefined; + /** Legacy permission summary when present. */ + legacyRequest: DecodedReply["jna"]; + /** Streaming media map merged from local and server snapshots. */ + streamMedia: Map | undefined; + /** True when either turn snapshot uses the streaming event model. */ + hasStream: boolean; + /** Ordered turns to scan for legacy tool result rows. */ + legacySources: LiveTurn[]; +} + +/** Handles required to clean session caches, drafts, and send readiness queries. */ +export interface SessionCacheContext { + /** Expected project identifier. */ + projectId: string; + /** Live project page component. */ + page: Record; + /** Property name of the native transport on `page`. */ + transportField: string; + /** Angular injector of the bound project page. */ + injector: AgentInjector; + /** Adapted Agent transport service. */ + transport: Transport; + /** Unsaved session IDs allocated in this page binding. */ + drafts: Set; + /** Signal predicate that reports whether the user can send Agent messages. */ + canSend: () => boolean; + /** Returns true while the page binding still owns the active project. */ + isCurrent: () => boolean; +} + +/** Handles required to submit, verify, and replay question answers on a live turn. */ +export interface QuestionReplayContext { + /** Session identifier that owns the question card. */ + sessionId: string; + /** One-based turn number that owns the question card. */ + turn: number; + /** Adapted Agent transport service. */ + transport: Transport; + /** Adapted native Agent exports. */ + flow: FlowAgentExports; + /** Native question response service. */ + questions: QuestionResponder; + /** Returns true while the page binding still owns the active project. */ + isCurrent: () => boolean; +} + +/** Accepted question answer stored for replay across stream reconnects. */ +interface RecordedQuestionAnswer { + /** Identifier of the question card. */ + actionId: string; + /** Validated answers submitted for the card. */ + answers: FlowAnswer[]; +} + +/** Active replay tracking state for one session. */ +interface SessionReplayState { + /** Turn number associated with `records`. */ + turn: number; + /** Ordered question cards accepted during `turn`. */ + records: RecordedQuestionAnswer[]; + /** Adapted Agent transport service. */ + transport: Transport; + /** Adapted native Agent exports. */ + flow: FlowAgentExports; + /** Native question response service. */ + questions: QuestionResponder; + /** Returns true while the page binding still owns the active project. */ + isCurrent: () => boolean; + /** True while an asynchronous reconnect replay loop is active. */ + watching: boolean; +} + +/** Recorded question answers keyed by session ID. */ +const sessionReplays = new Map(); + +/** Transport stream maps that already carry the reconnect observer wrapper. */ +const hookedStreamMaps = new WeakSet>(); + +/** Normalizes a tool or streaming media status string to Flow's lifecycle vocabulary. */ +export function normalizeToolMediaStatus(rawStatus: string, hasError = false): string { + const lower = rawStatus.trim().toLowerCase(); + if (!lower) return hasError ? "failed" : "success"; + if (lower === "error" || lower === "failed") return "failed"; + if (lower === "queued" || lower === "pending") return "pending"; + if (lower === "canceled" || lower === "cancelled") return "canceled"; + return lower; +} + +/** Returns true when at least one media item has not failed or been canceled. */ +export function hasNonFailedMedia(media: readonly ToolMediaItem[]): boolean { + return media.some( + (item) => item.status !== "failed" && item.status !== "canceled" && item.status !== "error", + ); +} + +/** Extracts a scalar error code or message from a tile or media failure field. */ +function extractMediaError(value: unknown): string | number | undefined { + if (typeof value === "string") return value.trim() || undefined; + if (typeof value === "number") return value; + if (!value || typeof value !== "object") return undefined; + for (const key of ["errorCode", "error_code", "code", "error", "message"]) { + const nested = readOwn(value, key); + if (typeof nested === "string" && nested.trim()) return nested.trim(); + if (typeof nested === "number") return nested; + } + return undefined; +} + +/** Finds a non-trashed `FAILED_ASSET` tile matching `mediaId` when standard asset lookup skips it. */ +function findFailedAssetTile(tiles: readonly AttachmentTile[], mediaId: string): AttachmentTile | undefined { + const wanted = cleanMediaId(mediaId); + return tiles.find((tile) => { + if (!tile || isTrashedTile(tile) || String(tile.type ?? "").toUpperCase() !== "FAILED_ASSET") { + return false; + } + return tile.id === mediaId || + (Boolean(wanted) && (cleanMediaId(tile.id) === wanted || cleanMediaId(tile.primaryMediaId) === wanted)); + }); +} + +/** Reconciles turn media items against live project tiles and variant readiness. */ +export function reconcileTurnMedia( + items: readonly ToolMediaItem[], + page?: Record, +): ToolMediaItem[] { + const normalized = items.map((item) => ({ + media_id: item.media_id, + status: normalizeToolMediaStatus(item.status, item.error !== undefined), + error: item.error, + })); + const tiles = readProjectTiles(page); + if (tiles.length === 0) return normalized; + + return normalized.map((item) => { + const matched = resolveRequestedAsset(tiles, item.media_id); + if (!matched) { + const failedTile = findFailedAssetTile(tiles, item.media_id); + if (!failedTile) return item; + const payload = findMediaContainer(failedTile)?.[1]; + const adapted = payload ? legacyMedia(payload) : undefined; + const error = item.error ?? extractMediaError(adapted?.nf ?? readOwn(failedTile, "Bf") ?? readOwn(failedTile, "nf")); + return { media_id: item.media_id, status: "failed", error }; + } + + const { tile, variant } = matched; + const primary = findMediaContainer(tile)?.[1]; + const container = variant ?? primary; + const isPrimary = !variant || + variant === primary || + cleanMediaId(readOwn(variant, "id")) === cleanMediaId(tile.primaryMediaId); + const adapted = container ? legacyMedia(container) : undefined; + const tileStatus = adapted?.Zc?.toLowerCase(); + const tileError = extractMediaError(adapted?.nf ?? readOwn(tile, "Bf") ?? readOwn(tile, "nf")); + + if (tileStatus === "failed" || tileStatus === "error") { + return { media_id: item.media_id, status: "failed", error: item.error ?? tileError }; + } + if (tileStatus === "canceled" || tileStatus === "cancelled") { + return { media_id: item.media_id, status: "canceled", error: item.error ?? tileError }; + } + if (item.status === "failed" || item.status === "canceled") { + if (tileStatus === "success" && !(isPrimary && tile.isPending) && isReadyVariant(container)) { + return { media_id: item.media_id, status: "success", error: undefined }; + } + return { ...item, error: item.error ?? tileError }; + } + if (tileStatus === "scheduled") { + return { media_id: item.media_id, status: "scheduled", error: undefined }; + } + if ( + (isPrimary && tile.isPending === true) || + tileStatus === "pending" || + tileStatus === "queued" || + !isReadyVariant(container) + ) { + return { media_id: item.media_id, status: "pending", error: undefined }; + } + if (tileStatus === "success" || item.status === "success") { + return { media_id: item.media_id, status: "success", error: undefined }; + } + return item; + }); +} + +/** Merges server and local reply block lists without losing partial stream output. */ +function mergeReplyBlocks(savedBlocks: readonly ReplyBlock[], priorBlocks: readonly ReplyBlock[]): ReplyBlock[] { + if (savedBlocks.length === 0) return [...priorBlocks]; + if (priorBlocks.length === 0) return [...savedBlocks]; + const length = Math.max(savedBlocks.length, priorBlocks.length); + const merged: ReplyBlock[] = []; + for (let index = 0; index < length; index++) { + const saved = savedBlocks[index]; + const prior = priorBlocks[index]; + if (!saved) merged.push(prior); + else if (!prior) merged.push(saved); + else if (saved.type === "text" && prior.type === "text") { + merged.push(prior.content.length > saved.content.length ? prior : saved); + } else if (saved.type === "question" && prior.type === "question") { + merged.push(saved.card.Qj !== undefined || prior.card.Qj === undefined ? saved : prior); + } else if (saved.type === "permission" && prior.type === "permission") { + merged.push(saved.card.Vz !== undefined || prior.card.Vz === undefined ? saved : prior); + } else { + merged.push(saved); + } + } + return merged; +} + +/** Selects the most complete reply text across server, local, and block snapshots. */ +function selectReplyText(savedText: string, priorText: string, blocks: readonly ReplyBlock[]): string { + const blockText = blocks.flatMap((block) => (block.type === "text" ? [block.content] : [])).join("\n\n"); + let best = savedText; + for (const candidate of [priorText, blockText]) { + if (candidate.length > best.length) best = candidate; + } + return best; +} + +/** Merges streaming media maps from local and server turn snapshots. */ +function mergeStreamMedia( + savedMap: Map | undefined, + priorMap: Map | undefined, +): Map | undefined { + if (!savedMap && !priorMap) return undefined; + const merged = new Map(priorMap); + for (const [mediaId, item] of savedMap ?? []) { + const previous = merged.get(mediaId); + if (!previous) { + merged.set(mediaId, item); + continue; + } + const nextStatus = normalizeToolMediaStatus(item.status, item.errorCode !== undefined); + const prevStatus = normalizeToolMediaStatus(previous.status, previous.errorCode !== undefined); + const keepPrevious = (prevStatus === "failed" || prevStatus === "canceled") && + nextStatus !== "failed" && nextStatus !== "canceled" && nextStatus !== "success"; + merged.set(mediaId, { + status: keepPrevious ? previous.status : item.status, + errorCode: item.errorCode ?? previous.errorCode, + }); + } + return merged; +} + +/** Merges a disconnected `STORED_TURN_IN_PROGRESS` turn with any local partial turn. */ +export function mergeDisconnectedTurn( + flow: FlowAgentExports, + savedTurn: LiveTurn, + priorTurn: LiveTurn | undefined, + index: number, +): MergedTurnView { + const [savedUser, savedReply] = flow.reply({ turn: savedTurn, XJ: index, yc: false }); + const savedBlocks = savedReply.Oh ?? savedTurn.Tf?.Oh ?? []; + const rawError = savedReply.errorMessage ?? savedTurn.errorMessage; + if (!priorTurn) { + return { + user: savedUser, + text: selectReplyText(savedReply.text, "", savedBlocks), + responseId: savedReply.ci, + blocks: savedBlocks, + rawError, + legacyRequest: savedReply.jna, + streamMedia: savedTurn.Tf?.Bx, + hasStream: Boolean(savedTurn.Tf), + legacySources: [savedTurn], + }; + } + const [priorUser, priorReply] = flow.reply({ turn: priorTurn, XJ: index, yc: false }); + const priorBlocks = priorReply.Oh ?? priorTurn.Tf?.Oh ?? []; + const blocks = mergeReplyBlocks(savedBlocks, priorBlocks); + return { + user: { + text: savedUser.text || priorUser.text, + Gh: savedUser.Gh?.length ? savedUser.Gh : priorUser.Gh, + Uy: savedUser.Uy?.length ? savedUser.Uy : priorUser.Uy, + }, + text: selectReplyText(savedReply.text, priorReply.text, blocks), + responseId: savedReply.ci ?? priorReply.ci, + blocks, + rawError, + legacyRequest: savedReply.jna ?? priorReply.jna, + streamMedia: mergeStreamMedia(savedTurn.Tf?.Bx, priorTurn.Tf?.Bx), + hasStream: Boolean(savedTurn.Tf || priorTurn.Tf), + legacySources: savedTurn.Yu.length > 0 ? [savedTurn, priorTurn] : [priorTurn, savedTurn], + }; +} + +/** Returns true when `TurnStore` must hydrate `savedTurns` before a new message. */ +export function needsTurnHydration( + localTurns: readonly LiveTurn[] | undefined, + savedTurns: readonly StoredTurn[], +): boolean { + const localCount = localTurns?.length ?? 0; + if (savedTurns.length > localCount) return true; + if (!localTurns) return false; + if (localTurns.slice(savedTurns.length).some((turn) => turn.errorMessage !== undefined)) return true; + return savedTurns.some((saved, index) => { + const state = saved.getState(); + return localTurns[index]?.errorMessage !== undefined && state !== 3 && state !== 5; + }); +} + +/** Resolves a fallback `QueryClient` from the raw transport service when needed. */ +function resolveTransportQueryClient( + page: Record, + transportField: string, + transport: Transport, +): QueryClient | undefined { + const rawTransport = readOwn(page, transportField); + for (const candidate of [readOwn(rawTransport, "Wa"), readOwn(transport, "Wa")]) { + const client = candidate as QueryClient | undefined; + if (typeof client?.queryCache?.find === "function" || typeof client?.queryCache?.findAll === "function") { + return client; + } + } + return undefined; +} + +/** Removes cached session and session-list queries for `sessionId` from `QueryClient`. */ +function clearSessionQueries(client: QueryClient | undefined, projectId: string, sessionId: string): void { + const cache = client?.queryCache; + if (!cache) return; + const targets = new Set>>>(); + if (typeof cache.findAll === "function") { + for (const query of cache.findAll({ queryKey: ["CREATION_AGENT_SESSION", sessionId] })) targets.add(query); + for (const query of cache.findAll({ queryKey: ["CREATION_AGENT_SESSIONS"] })) targets.add(query); + } else if (typeof cache.getAll === "function") { + for (const query of cache.getAll()) { + const [scope, keyId] = query.queryKey; + if (scope === "CREATION_AGENT_SESSIONS" || (scope === "CREATION_AGENT_SESSION" && keyId === sessionId)) { + targets.add(query); + } + } + } else if (typeof cache.find === "function") { + for (const queryKey of [ + ["CREATION_AGENT_SESSION", sessionId], + ["CREATION_AGENT_SESSIONS", projectId], + ["CREATION_AGENT_SESSIONS"], + ]) { + const found = cache.find({ queryKey, exact: true }); + if (found) targets.add(found); + } + } + for (const query of targets) { + if (typeof cache.remove === "function") { + cache.remove(query); + continue; + } + const queries = readOwn(cache, "queries"); + if (queries instanceof Map) { + for (const [hash, entry] of queries.entries()) { + if (entry === query) queries.delete(hash); + } + } + } +} + +/** Reads the `set` method from an Angular writable signal function or object. */ +function readSignalSetter(target: unknown): ((value: unknown) => void) | undefined { + if (typeof target !== "function" && (!target || typeof target !== "object")) return undefined; + try { + const setter: unknown = Reflect.get(target as object, "set"); + return typeof setter === "function" ? (setter as (value: unknown) => void) : undefined; + } catch { + return undefined; + } +} + +/** Resets the selected session signal `qg()` on a native or adapted `TurnStore` when it matches `sessionId`. */ +function resetActiveSessionOnStore(store: unknown, sessionId: string): void { + if (!store || typeof store !== "object") return; + const qg = readOwn(store, "qg"); + if (typeof qg === "function") { + try { + if (qg.call(store) !== sessionId) return; + } catch { + return; + } + const oa = readOwn(store, "oa"); + const setOa = readSignalSetter(oa); + if (setOa) setOa.call(oa, undefined); + if (qg.call(store) !== sessionId) return; + const setQg = readSignalSetter(qg); + if (setQg) { + setQg.call(qg, undefined); + return; + } + } + for (const field of Object.values(store as Record)) { + const setter = typeof field === "function" ? readSignalSetter(field) : undefined; + if (!setter) continue; + try { + if ((field as () => unknown).call(store) === sessionId) { + setter.call(field, undefined); + if (typeof qg === "function" && qg.call(store) !== sessionId) return; + } + } catch { + // Skip unrelated signals that require an Angular reactive context. + } + } +} + +/** Clears draft tracking, `TurnStore` state, `QueryClient` caches, and `qg()` for `sessionId`. */ +export function purgeSessionState(context: SessionCacheContext, sessionId: string): void { + clearQuestionReplays(sessionId); + context.drafts.delete(sessionId); + context.transport.ka.yL(sessionId); + const rawTransport = readOwn(context.page, context.transportField); + resetActiveSessionOnStore(readOwn(rawTransport, "ka"), sessionId); + resetActiveSessionOnStore(context.transport.ka, sessionId); + const client = resolveQueryClient(context.injector, context.page) ?? + resolveTransportQueryClient(context.page, context.transportField, context.transport); + clearSessionQueries(client, context.projectId, sessionId); +} + +/** Returns true when an unpersisted draft has no active turn and no completed turn. */ +export function isFailedDraftSession(transport: Transport, sessionId: string): boolean { + if (transport.ha.has(sessionId)) return false; + const local = transport.ka.ha().get(sessionId); + if (local?.xe) return false; + if (!local || local.Vh.length === 0) return true; + return !local.Vh.some((turn) => turn.errorMessage === undefined); +} + +/** Purges all failed unpersisted initial draft sessions from memory and `QueryClient`. */ +export function purgeFailedDrafts(context: SessionCacheContext): void { + for (const sessionId of [...context.drafts]) { + if (isFailedDraftSession(context.transport, sessionId)) purgeSessionState(context, sessionId); + } +} + +/** Waits for both `PROJECT_DETAILS` and `USER_PROFILE` queries before evaluating `canSend`. */ +export async function waitForSendReadiness( + context: SessionCacheContext, + signal?: AbortSignal, +): Promise { + if (context.canSend()) return true; + const client = resolveQueryClient(context.injector, context.page) ?? + resolveTransportQueryClient(context.page, context.transportField, context.transport); + const shared = { client, ready: () => context.canSend(), canContinue: context.isCurrent, signal }; + await Promise.all([ + waitForQuerySettlement({ ...shared, queryKey: ["PROJECT_DETAILS", context.projectId] }), + waitForQuerySettlement({ ...shared, queryKey: ["USER_PROFILE"] }), + ]); + return context.canSend(); +} + +/** Returns true when a `Wvc` stream entry in `transport.ha` is detached from its transport. */ +function isDetachedStream(stream: unknown): boolean { + if (!stream || typeof stream !== "object") return false; + if (readOwn(stream, "detached") === true) return true; + if (readOwn(readOwn(stream, "Wj"), "closed") === true) return true; + for (const value of Object.values(stream as Record)) { + if (value && typeof value === "object" && typeof readOwn(value, "unsubscribe") === "function") { + if (readOwn(value, "closed") === true) return true; + } + } + const hasSlot = "ha" in stream || "Ui" in stream || typeof readOwn(stream, "detach") === "function"; + return hasSlot && readOwn(stream, "ha") == null && readOwn(stream, "Ui") == null; +} + +/** Waits for a detached `Wvc` stream to reattach or close within a bounded timeout. */ +async function waitForStreamAttachment( + transport: Transport, + sessionId: string, + isCurrent: () => boolean, +): Promise { + const deadline = Date.now() + COLD_QUERY_TIMEOUT_MS; + while (Date.now() < deadline && isCurrent()) { + if (!transport.ha.has(sessionId)) return false; + if (!isDetachedStream(transport.ha.get(sessionId))) return true; + await delay(Math.max(1, Math.min(STREAM_ATTACH_POLL_MS, deadline - Date.now()))); + } + return isCurrent() && transport.ha.has(sessionId) && !isDetachedStream(transport.ha.get(sessionId)); +} + +/** Reads the current reply blocks of the active turn for `sessionId`. */ +function readLiveTurnBlocks( + transport: Transport, + flow: FlowAgentExports, + sessionId: string, + turn: number, +): ReplyBlock[] | undefined { + const local = transport.ka.ha().get(sessionId); + if (!local?.xe || local.Vh.length + 1 !== turn) return undefined; + if (local.xe.Tf?.Oh) return local.xe.Tf.Oh; + const [, reply] = flow.reply({ turn: local.xe, XJ: turn - 1, yc: true }); + return reply.Oh ?? []; +} + +/** Returns the first unanswered, non-expired question card ID in `blocks`. */ +function firstOpenQuestionId(blocks: readonly ReplyBlock[]): string | undefined { + for (const block of blocks) { + if (block.type === "question" && block.card.Qj === undefined && !block.card.Ls) { + return block.card.id; + } + } + return undefined; +} + +/** Returns true when `TurnStore` recorded `Qj` on the specified question card. */ +function isQuestionCardAccepted( + transport: Transport, + flow: FlowAgentExports, + sessionId: string, + turn: number, + actionId: string, +): boolean { + const blocks = readLiveTurnBlocks(transport, flow, sessionId, turn); + const target = blocks?.find( + (block): block is Extract => + block.type === "question" && block.card.id === actionId, + ); + return target?.card.Qj !== undefined; +} + +/** Replays any unpersisted recorded question answers on an attached live stream. */ +function replaySessionAnswersSync(state: SessionReplayState, sessionId: string): void { + if (!state.isCurrent() || !state.transport.ha.has(sessionId)) return; + if (isDetachedStream(state.transport.ha.get(sessionId))) return; + const local = state.transport.ka.ha().get(sessionId); + if (!local?.xe) return; + if (local.Vh.length + 1 !== state.turn) { + sessionReplays.delete(sessionId); + return; + } + for (const record of state.records) { + if (isQuestionCardAccepted(state.transport, state.flow, sessionId, state.turn, record.actionId)) { + continue; + } + const blocks = readLiveTurnBlocks(state.transport, state.flow, sessionId, state.turn); + if (!blocks || firstOpenQuestionId(blocks) !== record.actionId) break; + state.questions.OA({ sessionId, Ig: record.actionId, Qj: record.answers, hi: AGENT_SURFACE }); + if (!isQuestionCardAccepted(state.transport, state.flow, sessionId, state.turn, record.actionId)) { + break; + } + } +} + +/** Waits for stream attachment after a reconnect and replays unpersisted answers. */ +async function replayAfterStreamReconnect(sessionId: string): Promise { + const state = sessionReplays.get(sessionId); + if (!state || !state.isCurrent()) return; + const attached = await waitForStreamAttachment(state.transport, sessionId, state.isCurrent); + const latest = sessionReplays.get(sessionId); + if (attached && latest) replaySessionAnswersSync(latest, sessionId); +} + +/** Watches an active turn so in-place stream resets also replay recorded question answers. */ +async function watchActiveQuestionTurn(sessionId: string): Promise { + const initial = sessionReplays.get(sessionId); + if (!initial || initial.watching) return; + initial.watching = true; + try { + while (sessionReplays.has(sessionId)) { + const current = sessionReplays.get(sessionId); + if (!current || !current.isCurrent() || !current.transport.ha.has(sessionId)) break; + replaySessionAnswersSync(current, sessionId); + await delay(REPLAY_WATCH_POLL_MS); + } + } finally { + const finalState = sessionReplays.get(sessionId); + if (finalState) finalState.watching = false; + } +} + +/** Installs an instance-level `set` observer on `transport.ha` to catch `Dwc` / `Cwc` reconnects. */ +function armStreamReconnectHook(map: Map): void { + if (hookedStreamMaps.has(map)) return; + hookedStreamMaps.add(map); + const setStream = function (this: Map, key: string, value: unknown): Map { + const result = Map.prototype.set.call(this, key, value) as Map; + if (sessionReplays.has(key)) { + queueMicrotask(() => { + void replayAfterStreamReconnect(key); + void watchActiveQuestionTurn(key); + }); + } + return result; + }; + Object.defineProperty(map, "set", { value: setStream, configurable: true, writable: true }); +} + +/** Clears recorded question answers for `sessionId`, or when `turn` no longer matches. */ +export function clearQuestionReplays(sessionId: string, keepTurn?: number): void { + if (keepTurn === undefined || sessionReplays.get(sessionId)?.turn !== keepTurn) { + sessionReplays.delete(sessionId); + } +} + +/** Synchronously replays any recorded question answers whose cards reset on an attached stream. */ +export function reconcileQuestionReplays( + context: Omit, + stored: readonly StoredTurn[], + inProgressState: number, +): void { + const existing = sessionReplays.get(context.sessionId); + if (!existing) return; + Object.assign(existing, { + transport: context.transport, + flow: context.flow, + questions: context.questions, + isCurrent: context.isCurrent, + }); + armStreamReconnectHook(context.transport.ha); + if (context.transport.ha.has(context.sessionId)) { + replaySessionAnswersSync(existing, context.sessionId); + return; + } + const lastState = stored.at(-1)?.getState(); + if (lastState !== undefined && lastState !== inProgressState) { + sessionReplays.delete(context.sessionId); + } +} + +/** Waits for stream attachment after `resume` and replays recorded answers for `sessionId`. */ +export async function replayResumedQuestions(context: Omit): Promise { + const existing = sessionReplays.get(context.sessionId); + if (!existing) return; + Object.assign(existing, { + transport: context.transport, + flow: context.flow, + questions: context.questions, + isCurrent: context.isCurrent, + }); + armStreamReconnectHook(context.transport.ha); + await replayAfterStreamReconnect(context.sessionId); + void watchActiveQuestionTurn(context.sessionId); +} + +/** Waits on detached `Wvc` streams, submits a question answer, verifies acceptance, and arms replay. */ +export async function submitQuestionAnswer( + context: QuestionReplayContext, + actionId: string, + answers: FlowAnswer[], +): Promise<"ok" | "project_changed" | "not_pending"> { + const { sessionId, turn, transport, flow, questions, isCurrent } = context; + armStreamReconnectHook(transport.ha); + clearQuestionReplays(sessionId, turn); + + for (let attempt = 0; attempt < 2; attempt++) { + const attached = await waitForStreamAttachment(transport, sessionId, isCurrent); + if (!isCurrent()) return "project_changed"; + if (!attached) return "not_pending"; + + const existing = sessionReplays.get(sessionId); + if (existing && existing.turn === turn) { + Object.assign(existing, { transport, flow, questions, isCurrent }); + replaySessionAnswersSync(existing, sessionId); + } + + const blocks = readLiveTurnBlocks(transport, flow, sessionId, turn); + if (!blocks || firstOpenQuestionId(blocks) !== actionId) { + if (isQuestionCardAccepted(transport, flow, sessionId, turn, actionId)) break; + return "not_pending"; + } + + questions.OA({ sessionId, Ig: actionId, Qj: answers, hi: AGENT_SURFACE }); + if (isQuestionCardAccepted(transport, flow, sessionId, turn, actionId)) { + const state: SessionReplayState = sessionReplays.get(sessionId) ?? { + turn, + records: [], + transport, + flow, + questions, + isCurrent, + watching: false, + }; + Object.assign(state, { turn, transport, flow, questions, isCurrent }); + const idx = state.records.findIndex((item) => item.actionId === actionId); + if (idx >= 0) state.records[idx] = { actionId, answers }; + else state.records.push({ actionId, answers }); + sessionReplays.set(sessionId, state); + void watchActiveQuestionTurn(sessionId); + return "ok"; + } + if (!transport.ha.has(sessionId)) return "not_pending"; + } + return isCurrent() ? "not_pending" : "project_changed"; +} diff --git a/ts/agent_settings.ts b/ts/agent_settings.ts index de44c7a..a068efa 100644 --- a/ts/agent_settings.ts +++ b/ts/agent_settings.ts @@ -74,6 +74,12 @@ export interface QueryClient { queryCache?: { /** Finds the project query with this exact key. */ find?: (options: { queryKey: unknown[]; exact: true }) => SettingsQuery | undefined; + /** Finds all cached queries matching the optional key filter. */ + findAll?: (options?: { queryKey?: unknown[]; exact?: boolean }) => SettingsQuery[]; + /** Returns every cached query entry in the registry. */ + getAll?: () => SettingsQuery[]; + /** Removes a cached query entry from the registry. */ + remove?: (query: SettingsQuery) => void; }; } diff --git a/ts/agent_turns.ts b/ts/agent_turns.ts index 6e9618a..5bb9e50 100644 --- a/ts/agent_turns.ts +++ b/ts/agent_turns.ts @@ -3,6 +3,14 @@ // Format Agent turns, pending actions, expired elicitations, and question answers. +import { + hasNonFailedMedia, + mergeDisconnectedTurn, + needsTurnHydration, + normalizeToolMediaStatus, + reconcileTurnMedia, +} from "./agent_reconcile"; +import type { ToolMediaItem } from "./agent_reconcile"; import type { AgentRequest, FlowAgentExports, @@ -46,6 +54,8 @@ export interface TurnContext { flow: FlowAgentExports; /** Agent transport service for this document. */ transport: Transport; + /** Live project page component when bound. */ + page?: Record; } /** Returns true when a later reply block in the same turn supersedes a proposed plan. */ @@ -67,6 +77,7 @@ function isLaterOutputBlock(block: ReplyBlock): boolean { return block.content.trim().length > 0; case "a2ui": case "plan": + case "view_agent_memory": return true; case "permission": return block.card.Vz !== undefined; @@ -81,8 +92,9 @@ function isLaterOutputBlock(block: ReplyBlock): boolean { function expiredElicitationError( blocks: ReplyBlock[], active: boolean, + media: readonly ToolMediaItem[], ): string | undefined { - if (active) return undefined; + if (active || hasNonFailedMedia(media)) return undefined; let lastIndex = -1; let lastKind: "permission" | "question" | undefined; for (let i = 0; i < blocks.length; i++) { @@ -118,6 +130,7 @@ function pendingActions( latest: boolean, ): PendingAction[] { const actions: PendingAction[] = []; + let hasOpenQuestion = false; for (let index = 0; index < blocks.length; index++) { const block = blocks[index]; if ( @@ -139,10 +152,12 @@ function pendingActions( } if ( active && + !hasOpenQuestion && block.type === "question" && block.card.Qj === undefined && !block.card.Ls ) { + hasOpenQuestion = true; actions.push({ type: "question", action_id: block.card.id, @@ -194,9 +209,21 @@ function storedStatus(state: number): TurnStatus { } } -/** Reads actual media IDs from the original Agent tool results. */ -function legacyTurnMedia(flow: FlowAgentExports, turn: LiveTurn): string[] { - const ids = new Set(); +/** Reads a trimmed string field from a legacy tool struct row when present. */ +function readToolField( + flow: FlowAgentExports, + fields: Map, + key: string, +): string | undefined { + const value = fields.get(key); + if (!value) return undefined; + const text = flow.valueString(value).trim(); + return text || undefined; +} + +/** Reads media items, statuses, and errors from the original Agent tool results. */ +function legacyTurnMedia(flow: FlowAgentExports, turn: LiveTurn): ToolMediaItem[] { + const items = new Map(); for (const message of turn.Yu) { for (const event of flow.turns(message, flow.toolEventType, 2)) { const result = flow.oneOf( @@ -207,12 +234,22 @@ function legacyTurnMedia(flow: FlowAgentExports, turn: LiveTurn): string[] { ); if (!result) continue; for (const row of flow.resultItems(result)) { - const media = flow.structFields(row).get("media_id"); - if (media) ids.add(flow.valueString(media)); + const fields = flow.structFields(row); + const mediaId = readToolField(flow, fields, "media_id"); + if (!mediaId) continue; + const rawStatus = readToolField(flow, fields, "status") ?? ""; + const error = + readToolField(flow, fields, "error_code") ?? + readToolField(flow, fields, "error"); + items.set(mediaId, { + media_id: mediaId, + status: normalizeToolMediaStatus(rawStatus, error !== undefined), + error, + }); } } } - return [...ids].filter(Boolean); + return [...items.values()]; } /** Formats one Agent turn using the same message model that the chat page uses. */ @@ -221,20 +258,65 @@ function formatTurn( id: string, turn: LiveTurn, position: TurnPosition, + prior?: LiveTurn, ) { const { number, status, active, latest } = position; - const [user, reply] = context.flow.reply({ turn, XJ: number - 1, yc: active }); - const blocks = reply.Oh ?? turn.Tf?.Oh ?? []; - const rawError = reply.errorMessage ?? turn.errorMessage; + const disconnected = status === "in_progress" && !active + ? mergeDisconnectedTurn(context.flow, turn, prior, number - 1) + : undefined; + const decoded = disconnected ? undefined : context.flow.reply({ turn, XJ: number - 1, yc: active }); + const user = disconnected ? disconnected.user : decoded![0]; + const replyText = disconnected ? disconnected.text : decoded![1].text; + const responseId = disconnected ? disconnected.responseId : decoded![1].ci; + const blocks = disconnected + ? disconnected.blocks + : (decoded![1].Oh ?? turn.Tf?.Oh ?? []); + const rawError = disconnected + ? disconnected.rawError + : (decoded![1].errorMessage ?? turn.errorMessage); + const streamMedia = disconnected ? disconnected.streamMedia : turn.Tf?.Bx; + const hasStream = disconnected ? disconnected.hasStream : Boolean(turn.Tf); + const legacySources = disconnected ? disconnected.legacySources : [turn]; + + const mediaById = new Map(); + for (const [mediaId, item] of streamMedia ?? []) { + mediaById.set(mediaId, { + media_id: mediaId, + status: item.status, + error: item.errorCode, + }); + } + for (const source of legacySources) { + if (hasStream && source.Yu.length === 0) continue; + for (const item of legacyTurnMedia(context.flow, source)) { + const current = mediaById.get(item.media_id); + if (!current) { + if (!hasStream || mediaById.size === 0) mediaById.set(item.media_id, item); + continue; + } + mediaById.set(item.media_id, { + media_id: item.media_id, + status: + item.status === "failed" || item.status === "pending" + ? item.status + : current.status, + error: current.error ?? item.error, + }); + } + } + const media = reconcileTurnMedia([...mediaById.values()], context.page); + const timeoutError = status !== "stopped" && status !== "in_progress" - ? expiredElicitationError(blocks, active) + ? expiredElicitationError(blocks, active, media) : undefined; const pending = pendingActions( blocks, active, latest && status === "completed" && !timeoutError, ); - const legacyRequest = reply.jna ?? context.transport.ka.Ma().get(id); + const legacyRequest = + (disconnected ? disconnected.legacyRequest : decoded![1].jna) ?? + context.transport.ka.Ma().get(id); if (!active && latest && status === "completed" && !timeoutError && legacyRequest) { pending.push({ type: "permission", @@ -244,16 +326,6 @@ function formatTurn( credits: legacyRequest.qsa, }); } - const media = [...(turn.Tf?.Bx ?? [])].map(([mediaId, item]) => ({ - media_id: mediaId, - status: item.status, - error: item.errorCode, - })); - if (!turn.Tf) { - for (const mediaId of legacyTurnMedia(context.flow, turn)) { - media.push({ media_id: mediaId, status: "success", error: undefined }); - } - } const effectiveStatus = pending.length > 0 ? "action_required" : timeoutError @@ -262,7 +334,7 @@ function formatTurn( return { turn: number, status: effectiveStatus, - response_id: reply.ci, + response_id: responseId, connected: effectiveStatus === "in_progress" ? active : undefined, user: { text: user.text, @@ -274,7 +346,7 @@ function formatTurn( : undefined, }, assistant: { - text: reply.text, + text: replyText, media, rich_content: blocks.flatMap((b) => (b.type === "a2ui" ? [b.round] : [])), }, @@ -306,10 +378,21 @@ export function conversation(context: TurnContext, id: string, stored: StoredTur }); } const state = saved?.getState(); - if ( - saved && - (!prior || (state !== undefined && state !== STORED_TURN_IN_PROGRESS)) - ) { + if (saved && state === STORED_TURN_IN_PROGRESS) { + return formatTurn( + context, + id, + context.flow.decode(saved), + { + number, + status: "in_progress", + active: false, + latest, + }, + prior, + ); + } + if (saved && (!prior || state !== undefined)) { return formatTurn(context, id, context.flow.decode(saved), { number, status: storedStatus(state ?? 0), @@ -341,7 +424,7 @@ export function loadStoredTurns( ): void { const { flow, transport } = context; const local = transport.ka.ha().get(sessionId); - if (turns.length > (local?.Vh.length ?? 0)) { + if (needsTurnHydration(local?.Vh, turns)) { flow.hydrate(transport.ka, { sessionId, BF: turns.map(flow.decode),