From b4111c5c29ee8a31b5725c31de840a2cfb7f3c6c 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 05:45:29 +0000 Subject: [PATCH 1/2] fix(flow): coordinate agent sessions and answer replays - Report disconnected server turns as in progress and hydrate failures - Track draft sessions in Rust and purge deleted or failed sessions - Wait for user profile query settlement before send checks - Reconcile turn media status and errors against live project tiles - Parse memory blocks and preserve non-failed media turn completion - Expose one question card at a time and replay dropped answers --- src/agent.rs | 306 ++++++++++++++++++++++++++++++++++------ ts/agent_attachments.ts | 22 ++- ts/agent_chat.ts | 276 ++++++++++++++++++++++++++++++++++-- ts/agent_protocol.ts | 17 +++ ts/agent_settings.ts | 38 +++-- ts/agent_turns.ts | 232 ++++++++++++++++++++++++++---- ts/index.ts | 4 + ts/types.ts | 4 + 8 files changed, 809 insertions(+), 90 deletions(-) diff --git a/src/agent.rs b/src/agent.rs index 3344eb4..0f1134b 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -10,6 +10,7 @@ use anyhow::{Context, Result, ensure}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use tokio::sync::{Mutex, OwnedMutexGuard}; use tokio::time::{Duration, sleep}; @@ -52,7 +53,7 @@ enum AgentAction { CreateSession, /// Changes the title of a saved session. RenameSession, - /// Deletes a saved session and its conversation history. + /// Deletes a saved or draft session and its conversation history. DeleteSession, /// Reads conversation history, including the active turn. ListMessages, @@ -247,10 +248,98 @@ fn valid_id(id: &str) -> bool { .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_') } -/// Owns the Agent page and serializes requests to its runtime. +/// Question response that the poll loop sends again if a stream reconnect resets the turn. +#[derive(Debug, Clone, Serialize)] +struct PendingAnswer { + /// Session ID that owns the turn. + session_id: String, + /// Turn number. Starts at one. + turn: u32, + /// Action ID of the question card. + action_id: String, + /// Validated answers from the `respond` request. + answers: Vec, +} + +/// Shared state for the Agent page, draft sessions, and question answers. +#[derive(Default)] +struct AgentState { + /// Active browser page and bound project. + agent: Option, + /// Allocated draft session IDs by project ID. + drafts: BTreeMap>, + /// Accepted question answers by project ID. + answers: BTreeMap>, +} + +impl AgentState { + /// Records an allocated draft session ID for `project_id`. + fn record_draft(&mut self, project_id: &str, session_id: &str) { + self.drafts + .entry(project_id.to_string()) + .or_default() + .insert(session_id.to_string()); + } + + /// Removes `session_id` from the draft set for `project_id`. + fn remove_draft(&mut self, project_id: &str, session_id: &str) { + let remove_project = if let Some(ids) = self.drafts.get_mut(project_id) { + ids.remove(session_id); + ids.is_empty() + } else { + false + }; + if remove_project { + self.drafts.remove(project_id); + } + } + + /// Removes draft IDs that Flow reports as saved on the server. + fn sync_persisted(&mut self, project_id: &str, value: &Value) { + if value["persisted"].as_bool() == Some(true) + && let Some(id) = value["session_id"].as_str() + { + self.remove_draft(project_id, id); + } + if let Some(sessions) = value["sessions"].as_array() { + for session in sessions { + if session["persisted"].as_bool() == Some(true) + && let Some(id) = session["session_id"].as_str() + { + self.remove_draft(project_id, id); + } + } + } + } + + /// Stores an accepted question answer in order for its turn. + fn record_answer(&mut self, project_id: &str, entry: PendingAnswer) { + let items = self.answers.entry(project_id.to_string()).or_default(); + items.retain(|item| { + item.session_id != entry.session_id + || (item.turn == entry.turn && item.action_id != entry.action_id) + }); + items.push(entry); + } + + /// Removes all saved question answers for `session_id` in `project_id`. + fn clear_session_answers(&mut self, project_id: &str, session_id: &str) { + let remove_project = if let Some(items) = self.answers.get_mut(project_id) { + items.retain(|item| item.session_id != session_id); + items.is_empty() + } else { + false + }; + if remove_project { + self.answers.remove(project_id); + } + } +} + +/// Owns the Agent page and serializes requests and answer replays to its runtime. pub(crate) struct AgentChat { - /// Page and project currently used for chat. - state: Mutex>, + /// Page, draft session IDs, and saved question answers. + state: Arc>, } /// Agent page for a project. @@ -267,7 +356,7 @@ impl AgentChat { /// Creates the chat controller. Chrome starts on the first request. pub(crate) fn new() -> Self { Self { - state: Mutex::new(None), + state: Arc::new(Mutex::new(AgentState::default())), } } @@ -285,24 +374,50 @@ impl AgentChat { ) .await?; let mut state = self.state.lock().await; - if state.as_ref().is_none_or(|agent| !agent.page.is_alive()) { + if state + .agent + .as_ref() + .is_none_or(|agent| !agent.page.is_alive()) + { let page = Arc::new(engine.open_background_page().await?); - *state = Some(AgentPage { + state.answers.clear(); + state.agent = Some(AgentPage { page, project_id: String::new(), workspace_url: String::new(), }); } let reference_url = engine.current_url().await.unwrap_or_default(); - let agent = state.as_mut().context("Agent page unavailable")?; - agent.open(&reference_url, &request.project_id).await?; + { + let agent = state.agent.as_mut().context("Agent page unavailable")?; + agent.open(&reference_url, &request.project_id).await?; + } let mut args = serde_json::to_value(&request)?; if let Some(fields) = args.as_object_mut() { fields.remove("files"); + if request.action == AgentAction::ListSessions + && let Some(drafts) = state.drafts.get(&request.project_id) + && !drafts.is_empty() + { + fields.insert("drafts".to_string(), json!(drafts)); + } else if let Some(ref sid) = request.session_id + && state + .drafts + .get(&request.project_id) + .is_some_and(|drafts| drafts.contains(sid)) + { + fields.insert("draft".to_string(), Value::Bool(true)); + } } let execution = if request.starts_turn() { + let busy = state + .agent + .as_ref() + .context("Agent page unavailable")? + .busy() + .await?; ensure!( - !agent.busy().await?, + !busy, "An Agent turn is active. Read it or stop it before you start another turn" ); Some(queue.try_lock_execution()?) @@ -310,59 +425,152 @@ impl AgentChat { None }; if request.action == AgentAction::CreateSession { - let result = checked_runtime_result( - agent - .page - .call("agentAllocate", json!([request.project_id])) - .await?, - )?; - args["session_id"] = Value::String( + let allocated = { + let agent = state.agent.as_ref().context("Agent page unavailable")?; + let result = checked_runtime_result( + agent + .page + .call("agentAllocate", json!([request.project_id])) + .await?, + )?; result["session_id"] .as_str() .context("Flow did not allocate a session ID")? - .to_string(), - ); + .to_string() + }; + state.record_draft(&request.project_id, &allocated); + args["session_id"] = Value::String(allocated); } let session_id = args["session_id"].clone(); + let session_id_str = session_id.as_str().map(str::to_owned); if !files.is_empty() { - agent.page.stage_agent_files(&files).await?; + let stage_result = state + .agent + .as_ref() + .context("Agent page unavailable")? + .page + .stage_agent_files(&files) + .await; + if let Err(error) = stage_result { + if request.action == AgentAction::CreateSession + && let Some(ref sid) = session_id_str + { + purge_session_state(&mut state, &request.project_id, sid).await; + } + return Err(error); + } args["file_count"] = json!(files.len()); } + let page = Arc::clone(&state.agent.as_ref().context("Agent page unavailable")?.page); let result = if !files.is_empty() || request .asset_ids .as_ref() .is_some_and(|ids| !ids.is_empty()) { - agent - .page - .call_with_timeout("agentOp", json!([args]), ATTACHMENT_CALL_TIMEOUT) + page.call_with_timeout("agentOp", json!([args]), ATTACHMENT_CALL_TIMEOUT) .await } else { - agent.page.call("agentOp", json!([args])).await + page.call("agentOp", json!([args])).await }; - if let Some(guard) = execution { - tokio::spawn(hold_while_active( - Arc::clone(&agent.page), - request.project_id.clone(), - guard, - )); + let initial_failed = request.action == AgentAction::CreateSession + && match &result { + Err(_) => true, + Ok(raw) => { + raw["ok"].as_bool() != Some(true) + || (raw["persisted"].as_bool() == Some(false) + && raw["turn"]["status"].as_str() == Some("failed")) + } + }; + if initial_failed && let Some(ref sid) = session_id_str { + purge_session_state(&mut state, &request.project_id, sid).await; } match result { - Ok(value) => { - let mut value = checked_runtime_result(value)?; + Ok(raw) => { + let mut value = checked_runtime_result(raw)?; + state.sync_persisted(&request.project_id, &value); + if request.action == AgentAction::DeleteSession { + if let Some(ref sid) = session_id_str { + purge_session_state(&mut state, &request.project_id, sid).await; + } + } else if request.action != AgentAction::Resume + && (request.action == AgentAction::Stop || request.starts_turn()) + && let Some(ref sid) = session_id_str + { + state.clear_session_answers(&request.project_id, sid); + } else if request.action == AgentAction::Respond + && let (Some(sid), Some(turn), Some(action_id), Some(answers)) = ( + request.session_id.clone(), + request.turn, + request.action_id.clone(), + request.answers.clone(), + ) + { + state.record_answer( + &request.project_id, + PendingAnswer { + session_id: sid, + turn, + action_id, + answers, + }, + ); + } + if !initial_failed { + if let Some(guard) = execution { + tokio::spawn(hold_while_active( + Arc::clone(&self.state), + request.project_id.clone(), + guard, + )); + } else if request.action == AgentAction::Respond + && request.answers.is_some() + && let Ok(guard) = queue.try_lock_execution() + { + tokio::spawn(hold_while_active( + Arc::clone(&self.state), + request.project_id.clone(), + guard, + )); + } + } value["project_id"] = Value::String(request.project_id); Ok(value) } - Err(error) if request.writes() => anyhow::bail!( - "outcome_unknown (project {}, session {session_id}): {error:#}", - request.project_id - ), + Err(error) if request.writes() => { + if let Some(guard) = execution + && !initial_failed + { + tokio::spawn(hold_while_active( + Arc::clone(&self.state), + request.project_id.clone(), + guard, + )); + } + anyhow::bail!( + "outcome_unknown (project {}, session {session_id}): {error:#}", + request.project_id + ) + } Err(error) => Err(error), } } } +/// Removes a session from local state and clears browser drafts and caches. +async fn purge_session_state(state: &mut AgentState, project_id: &str, session_id: &str) { + state.remove_draft(project_id, session_id); + state.clear_session_answers(project_id, session_id); + if let Some(ref agent) = state.agent + && agent.page.is_alive() + { + let _ = agent + .page + .call("agentPurge", json!([project_id, session_id])) + .await; + } +} + impl AgentPage { /// Loads the project and binds its Agent service. async fn open(&mut self, reference_url: &str, project_id: &str) -> Result<()> { @@ -416,15 +624,33 @@ impl AgentPage { } } -/// Holds the job queue lock while the browser reports an active turn. +/// Keeps the job queue lock and sends dropped question answers again while a turn is active. async fn hold_while_active( - page: Arc, + state: Arc>, project_id: String, _guard: OwnedMutexGuard<()>, ) { let mut errors = 0; - while page.is_alive() { - match page.call("agentBusy", json!([project_id])).await { + loop { + let outcome = { + let mut locked = state.lock().await; + let Some(agent) = locked.agent.as_ref() else { + locked.answers.remove(&project_id); + break; + }; + if !agent.page.is_alive() || agent.project_id != project_id { + locked.answers.remove(&project_id); + break; + } + let page = Arc::clone(&agent.page); + let replay = locked.answers.get(&project_id).cloned().unwrap_or_default(); + let busy = page.call("agentBusy", json!([project_id])).await; + if matches!(busy, Ok(Value::Bool(true))) && !replay.is_empty() { + let _ = page.call("agentReplay", json!([project_id, replay])).await; + } + busy + }; + match outcome { Ok(Value::Bool(false)) => break, Ok(Value::Bool(true)) => errors = 0, _ => { diff --git a/ts/agent_attachments.ts b/ts/agent_attachments.ts index d2138dd..86a642e 100644 --- a/ts/agent_attachments.ts +++ b/ts/agent_attachments.ts @@ -5,13 +5,14 @@ import { readOwn } from "./angular"; import { cleanMediaId, findMediaContainer, isTrashedTile, legacyMedia } from "./dom"; +import { frontendBuild, readBuildLabel } from "./frontend_builds"; import { agentAttachmentCompatibility } from "./frontend_compatibility"; import { bindMediaUpload, uploadMediaFiles, waitForMedia } from "./project_upload"; import type { MediaUploadExport, UploadProgress } from "./project_upload"; 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 +89,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 +120,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 { @@ -213,6 +214,21 @@ function referenceKey(reference: AttachmentReference, characterField: string): s : `media:${reference.mediaId}`; } +/** Reads the current project tiles from the bound page store when available. */ +export function readAgentProjectTiles(page: Record): AttachmentTile[] { + const format = frontendBuild(readBuildLabel())?.operations.agent_attachments; + if (!format) return []; + const store = readOwn(page, format.store); + const tiles = readOwn(store, format.tiles); + if (typeof tiles !== "function") return []; + try { + const items: unknown = tiles.call(store); + return Array.isArray(items) ? (items as AttachmentTile[]) : []; + } catch { + return []; + } +} + /** Resolves project references, uploads local files, and builds the native Agent message. */ export async function buildAttachmentMessage(input: AttachmentInput) { const compatibility = agentAttachmentCompatibility(); diff --git a/ts/agent_chat.ts b/ts/agent_chat.ts index 169a09f..2d2f609 100644 --- a/ts/agent_chat.ts +++ b/ts/agent_chat.ts @@ -3,10 +3,13 @@ // Flow Agent session queries, live turns, and user responses. -import { buildAttachmentMessage } from "./agent_attachments"; +import { readOwn } from "./angular"; +import { buildAttachmentMessage, readAgentProjectTiles } from "./agent_attachments"; +import type { AttachmentTile } from "./agent_attachments"; import { MEDIA_UPLOAD_TIMEOUT_MS, takeMediaFiles, waitForMedia } from "./project_upload"; import type { AgentDecision, + AgentReplayEntry, AgentRequest, FlowAgentExports, QuestionResponder, @@ -20,7 +23,7 @@ import { settingsWritePending, waitForQuerySettlement, } from "./agent_settings"; -import type { AgentInjector } from "./agent_settings"; +import type { AgentInjector, QueryClient, SettingsQuery } from "./agent_settings"; import { LEGACY_PERMISSION_ID, STORED_TURN_IN_PROGRESS, @@ -53,6 +56,10 @@ interface Binding { permissions: object; /** Question response service on the project page. */ questions: QuestionResponder; + /** Reads live project tiles on the bound page. */ + tiles: () => AttachmentTile[]; + /** Resets active session signals when they hold `sessionId`. */ + resetActiveSession: (sessionId: string) => void; /** IDs that Flow has yet to add to the session list. */ drafts: Set; } @@ -146,6 +153,54 @@ export function agentPrototype(): object | null { return typeof type === "function" ? type.prototype : null; } +/** Resets writable signals on the native services when they hold `sessionId`. */ +function clearActiveSessionSignals( + targets: Record[], + sessionId: string, +): void { + const store = targets[0]; + const active = targets.find((target) => typeof target.qg === "function"); + if (active && (active.qg as () => unknown)() === sessionId) { + const primary = store?.oa; + if ( + primary && + (typeof primary === "function" || typeof primary === "object") && + typeof (primary as { set?: unknown }).set === "function" + ) { + (primary as { set: (value: undefined) => void }).set(undefined); + } + } + const allocated = typeof store?.la === "function" ? store.la() : undefined; + if (allocated === sessionId) { + const pending = store?.ka; + if ( + pending && + (typeof pending === "function" || typeof pending === "object") && + typeof (pending as { set?: unknown }).set === "function" + ) { + (pending as { set: (value: undefined) => void }).set(undefined); + } + } + for (const target of targets) { + for (const value of Object.values(target)) { + if ( + typeof value === "function" && + typeof (value as { set?: unknown }).set === "function" + ) { + try { + if (value() === sessionId) { + (value as unknown as { set: (next: undefined) => void }).set( + undefined, + ); + } + } catch { + // Ignore unrelated functions on the service. + } + } + } + } +} + /** Finds a live project page and takes its project-scoped service handles. */ export function bindAgent( instances: Record[], @@ -207,6 +262,16 @@ export function bindAgent( questions, permissions, flow, + tiles: () => readAgentProjectTiles(page), + resetActiveSession: (sessionId: string) => + clearActiveSessionSignals( + [ + nativeTransport.ka as unknown as Record, + nativeTransport as unknown as Record, + composer as unknown as Record, + ], + sessionId, + ), canSend: () => composer.wb?.() === true, drafts: binding?.page === page ? binding.drafts : new Set(), }; @@ -223,9 +288,60 @@ export async function agentAllocate(projectId: string) { const bound = liveBinding(projectId); if (!bound) return failure("agent_project_changed"); const { id } = await bound.flow.allocate(); + bound.drafts.add(id); return { ok: true as const, session_id: id }; } +/** Cancels and removes matching cached query entries from the shared `QueryClient`. */ +async function removeCachedQueries( + client: QueryClient | undefined, + prefixKey: unknown[], + exactKey: unknown[], +): Promise { + const cache = client?.queryCache; + if (!cache) return; + const matched = new Set(); + if (typeof cache.findAll === "function") { + for (const query of cache.findAll({ queryKey: prefixKey })) { + matched.add(query); + } + } + if (typeof cache.find === "function") { + const exact = cache.find({ queryKey: exactKey, exact: true }); + if (exact) matched.add(exact); + } + for (const query of matched) { + await query.cancel?.({ revert: true }).catch(() => undefined); + cache.remove?.(query); + } +} + +/** Purges local draft state, turn store state, active session signals, and query caches. */ +async function purgeSession(bound: Binding, sessionId: string): Promise { + bound.drafts.delete(sessionId); + bound.transport.ka.yL(sessionId); + bound.resetActiveSession(sessionId); + const client = resolveQueryClient(bound.injector, bound.page); + await removeCachedQueries( + client, + ["CREATION_AGENT_SESSION", sessionId], + ["CREATION_AGENT_SESSION", sessionId], + ); + await removeCachedQueries( + client, + ["CREATION_AGENT_SESSIONS"], + ["CREATION_AGENT_SESSIONS", bound.projectId], + ); +} + +/** Clears local drafts, turn signals, active session state, and query caches for one session. */ +export async function agentPurge(projectId: string, sessionId: string) { + const bound = liveBinding(projectId); + if (!bound) return failure("agent_project_changed"); + await purgeSession(bound, sessionId); + return { ok: true as const, session_id: sessionId }; +} + /** Reads a fresh session list from Flow for the pinned project. */ async function savedSessions(bound: Binding): Promise { const { flow, transport, projectId } = bound; @@ -278,17 +394,27 @@ async function savedTurns( ); } -/** Waits for active `PROJECT_DETAILS` queries before reading `canSend`. */ +/** 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); + const canContinue = () => liveBinding(bound.projectId) === bound; await waitForQuerySettlement({ client, queryKey: ["PROJECT_DETAILS", bound.projectId], ready: () => bound.canSend(), - canContinue: () => liveBinding(bound.projectId) === bound, + canContinue, signal, }); + if (!bound.canSend()) { + await waitForQuerySettlement({ + client, + queryKey: ["USER_PROFILE"], + ready: () => bound.canSend(), + canContinue, + signal, + }); + } return bound.canSend(); } @@ -363,7 +489,8 @@ async function send( } else { loadStoredTurns(bound, id, saved); } - const number = Math.max(saved.length, local?.Vh.length ?? 0) + 1; + const currentLocal = transport.ka.ha().get(id); + const number = Math.max(saved.length, currentLocal?.Vh.length ?? 0) + 1; let envelope = prepared?.message; if (!envelope) { const part = flow.finish(flow.setText(flow.mutable(flow.newPart()), text)); @@ -404,6 +531,50 @@ async function send( }); } +/** Returns true when a stream or subscription handle is open. */ +function isOpenHandle(value: unknown): boolean { + if (!value || typeof value !== "object") return false; + if (readOwn(value, "closed") === true) return false; + if (readOwn(readOwn(value, "Wj"), "closed") === true) return false; + if ("ha" in value && !readOwn(value, "ha")) return false; + return true; +} + +/** Returns true when a live transport entry holds an open stream. */ +function isStreamAttached(entry: unknown): boolean { + if (!isOpenHandle(entry)) return false; + if ("Ui" in (entry as object)) return isOpenHandle(readOwn(entry, "Ui")); + return true; +} + +/** Returns true when the turn records an answer for the question card. */ +function isQuestionAccepted(bound: Binding, sessionId: string, actionId: string): boolean { + const session = bound.transport.ka.ha().get(sessionId); + const turn = session?.xe ?? session?.Vh.at(-1); + const blocks = turn?.Tf?.Oh; + if (!blocks) return false; + return blocks.some( + (block) => + block.type === "question" && + block.card.id === actionId && + block.card.Qj !== undefined, + ); +} + +/** Returns true when the turn records a decision for the permission card. */ +function isPermissionAccepted(bound: Binding, sessionId: string, actionId: string): boolean { + const session = bound.transport.ka.ha().get(sessionId); + const turn = session?.xe ?? session?.Vh.at(-1); + const blocks = turn?.Tf?.Oh; + if (!blocks) return false; + return blocks.some( + (block) => + block.type === "permission" && + block.card.id === actionId && + block.card.Vz !== undefined, + ); +} + /** Applies a decision to one action from the requested turn. */ async function respond( bound: Binding, @@ -432,20 +603,43 @@ async function respond( permission: decision.code, }); } + const entry = bound.transport.ha.get(id); + if (!entry) return failure("agent_turn_not_active"); + const attached = isStreamAttached(entry); bound.flow.permission(bound.permissions, { sessionId: id, Ig: action.action_id, action: decision.code, }); + const after = bound.transport.ha.get(id); + if ( + attached && + (!isPermissionAccepted(bound, id, action.action_id) || + (after !== undefined && !isStreamAttached(after))) + ) { + return failure("agent_action_not_pending"); + } } else if (action.type === "question") { const answers = req.answers && questionAnswers(action, req.answers); if (!answers) return failure("invalid_agent_question_answers"); + const entry = bound.transport.ha.get(id); + if (!entry) return failure("agent_turn_not_active"); + const attached = isStreamAttached(entry); bound.questions.OA({ sessionId: id, Ig: action.action_id, Qj: answers, hi: AGENT_SURFACE, }); + const after = bound.transport.ha.get(id); + if ( + attached && + (!isQuestionAccepted(bound, id, action.action_id) || + (after !== undefined && + (!isStreamAttached(after) || readOwn(after, "na") !== undefined))) + ) { + return failure("agent_action_not_pending"); + } } else { const canSend = await readyToSend(bound); if (liveBinding(bound.projectId) !== bound) @@ -479,6 +673,45 @@ async function respond( }; } +/** Sends recorded question answers again on open streams after a reconnect resets turn state. */ +export function agentReplay(projectId: string, entries: AgentReplayEntry[]) { + const bound = liveBinding(projectId); + if (!bound) return { ok: false as const, replayed: 0 }; + let replayed = 0; + for (const entry of entries) { + const stream = bound.transport.ha.get(entry.session_id); + if (!isStreamAttached(stream)) continue; + const local = bound.transport.ka.ha().get(entry.session_id); + if (!local?.xe || local.Vh.length + 1 !== entry.turn) continue; + const current = conversation(bound, entry.session_id, []).at(-1); + const action = + current?.turn === entry.turn + ? current.pending_actions.find( + (item): item is Extract => + item.type === "question" && item.action_id === entry.action_id, + ) + : undefined; + if (!action) continue; + const formatted = questionAnswers(action, entry.answers); + if (!formatted) continue; + bound.questions.OA({ + sessionId: entry.session_id, + Ig: action.action_id, + Qj: formatted, + hi: AGENT_SURFACE, + }); + const after = bound.transport.ha.get(entry.session_id); + if ( + isQuestionAccepted(bound, entry.session_id, action.action_id) && + (after === undefined || + (isStreamAttached(after) && readOwn(after, "na") === undefined)) + ) { + replayed++; + } + } + return { ok: true as const, replayed }; +} + /** Loads the session and sends one message within the attachment deadline. */ async function sendUserMessage( bound: Binding, @@ -495,8 +728,21 @@ async function sendUserMessage( text: request.message ?? "", attachments: signal ? { assetIds, files, signal } : undefined, }; - if (request.action === "create_session") - return send(bound, draftSession(id), [], input); + if (request.action === "create_session") { + const created = await send(bound, draftSession(id), [], input); + if (!created.ok) { + await purgeSession(bound, id); + return created; + } + if (created.turn.status === "failed") { + const saved = (await savedSessions(bound).catch(() => [])).find( + (item) => item.session_id === id, + ); + if (saved) return { ...created, ...saved }; + await purgeSession(bound, id); + } + return created; + } try { const session = await waitForMedia( @@ -536,6 +782,12 @@ export async function agentOp(request: AgentRequest) { }, request.settings ?? undefined); } const id = request.session_id; + if (request.drafts) { + for (const draftId of request.drafts) bound.drafts.add(draftId); + } + if (request.draft && id) { + bound.drafts.add(id); + } if (request.action === "list_sessions") { const [saved, canSend] = await Promise.all([ savedSessions(bound), @@ -565,15 +817,17 @@ 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); + } + await purgeSession(bound, id); return { ok: true as const, ...session, deleted: true }; } diff --git a/ts/agent_protocol.ts b/ts/agent_protocol.ts index 6d87743..97be971 100644 --- a/ts/agent_protocol.ts +++ b/ts/agent_protocol.ts @@ -62,6 +62,22 @@ export interface AgentRequest { limit?: number | null; /** Exclusive upper bound on returned turn numbers. */ before_turn?: number | null; + /** True when the server tracks this session ID as an unsaved draft. */ + draft?: boolean; + /** Unsaved draft session IDs that the server tracks for this project. */ + drafts?: string[]; +} + +/** Question response that the server sends again if a reconnect resets the turn. */ +export interface AgentReplayEntry { + /** Session ID that owns the turn. */ + session_id: string; + /** Turn number. Starts at one. */ + turn: number; + /** Action ID of the question card. */ + action_id: string; + /** Validated caller answers for the question card. */ + answers: NonNullable; } /** Title and state of one session. */ @@ -231,6 +247,7 @@ export type ReplyBlock = | { type: "permission"; card: PermissionCard } | { type: "question"; card: QuestionCard } | { type: "plan"; Gz: PlanCard } + | { type: "view_agent_memory" } | { type: "a2ui"; round: unknown }; /** Media counts and credits from a permission request. */ diff --git a/ts/agent_settings.ts b/ts/agent_settings.ts index de44c7a..1d85d76 100644 --- a/ts/agent_settings.ts +++ b/ts/agent_settings.ts @@ -55,13 +55,15 @@ interface QueryState { } /** Native query entry in the shared query cache. */ -interface SettingsQuery { +export interface SettingsQuery { /** Key of the cached query. */ queryKey: unknown[]; /** Current query state. */ state?: QueryState; /** Returns true when at least one observer enables this query. */ isActive?: () => boolean; + /** Cancels an active network fetch for this query. */ + cancel?: (options?: { revert?: boolean }) => Promise; /** Fetches current project metadata from Flow. */ fetch(options?: unknown, control?: { cancelRefetch: boolean }): Promise; } @@ -72,8 +74,12 @@ export interface QueryClient { ha?: (key: unknown[]) => unknown; /** Query registry. */ queryCache?: { - /** Finds the project query with this exact key. */ - find?: (options: { queryKey: unknown[]; exact: true }) => SettingsQuery | undefined; + /** Finds the project query with this key. */ + find?: (options: { queryKey: unknown[]; exact?: boolean }) => SettingsQuery | undefined; + /** Finds all cached queries that match this filter. */ + findAll?: (options?: { queryKey?: unknown[] }) => SettingsQuery[]; + /** Removes one cached query entry from the cache. */ + remove?: (query: SettingsQuery) => void; }; } @@ -136,6 +142,13 @@ function isCatalogue(value: unknown): value is ModelCatalogue { Boolean(readOwn(value, "Wx")); } +/** Returns true when `value` exposes a query cache lookup method. */ +function hasQueryCache(value: unknown): value is QueryClient { + if (!value || typeof value !== "object") return false; + const cache = (value as QueryClient).queryCache; + return typeof cache?.find === "function" || typeof cache?.findAll === "function"; +} + /** Resolves the shared native `QueryClient` from the active page injector or component. */ export function resolveQueryClient( injector: AgentInjector, @@ -147,17 +160,15 @@ export function resolveQueryClient( const token = readOwn(namespace, support.format.exports.projectService); if (typeof token === "function") { const project = service(injector, token); - const client = readOwn(project, support.format.queryClient) as QueryClient | undefined; - if (typeof client?.queryCache?.find === "function") return client; + const client = readOwn(project, support.format.queryClient); + if (hasQueryCache(client)) return client; } } for (const value of Object.values(page ?? {})) { if (!value || typeof value !== "object") continue; - const direct = value as QueryClient; - if (typeof direct.queryCache?.find === "function") return direct; + if (hasQueryCache(value)) return value; for (const nested of Object.values(value as Record)) { - const candidate = nested as QueryClient | undefined; - if (typeof candidate?.queryCache?.find === "function") return candidate; + if (hasQueryCache(nested)) return nested; } } return undefined; @@ -186,9 +197,12 @@ export async function waitForQuerySettlement(options: QueryWaitOptions): Promise const start = Date.now(); const deadline = start + COLD_QUERY_TIMEOUT_MS; const graceDeadline = start + COLD_QUERY_GRACE_MS; + let sawPending = false; while (Date.now() < deadline && canContinue() && !signal?.aborted) { if (ready()) return; - const query = client?.queryCache?.find?.({ queryKey, exact: true }); + const query = + client?.queryCache?.find?.({ queryKey, exact: true }) ?? + client?.queryCache?.find?.({ queryKey }); const status = query?.state?.status; const fetchStatus = query?.state?.fetchStatus; const activeObserver = typeof query?.isActive === "function" @@ -200,9 +214,13 @@ export async function waitForQuerySettlement(options: QueryWaitOptions): Promise : client?.queryCache?.find && Date.now() < graceDeadline, ); if (!queryPending && !extraPending?.()) break; + sawPending = true; const remaining = Math.max(1, Math.min(COLD_QUERY_POLL_MS, deadline - Date.now())); await delay(remaining); } + if (sawPending && !ready() && canContinue() && !signal?.aborted) { + await delay(0); + } } /** Reads the model catalogue and the same tier that the settings panel uses. */ diff --git a/ts/agent_turns.ts b/ts/agent_turns.ts index 6e9618a..bca5e24 100644 --- a/ts/agent_turns.ts +++ b/ts/agent_turns.ts @@ -3,6 +3,10 @@ // Format Agent turns, pending actions, expired elicitations, and question answers. +import { readOwn } from "./angular"; +import { isReadyVariant, resolveRequestedAsset } from "./agent_attachments"; +import type { AttachmentTile } from "./agent_attachments"; +import { legacyMedia, legacyTile } from "./dom"; import type { AgentRequest, FlowAgentExports, @@ -40,12 +44,24 @@ interface TurnPosition { latest: boolean; } +/** Status and optional failure detail of one generated media item in a turn. */ +interface TurnMediaItem { + /** Flow media identifier. */ + media_id: string; + /** Lifecycle status of the media item. */ + status: string; + /** Error code or message when generation fails. */ + error: string | number | undefined; +} + /** Native Agent handles required to decode and hydrate turns. */ export interface TurnContext { /** Library exports used to decode and format turns. */ flow: FlowAgentExports; /** Agent transport service for this document. */ transport: Transport; + /** Optional reader for live project tiles on this page. */ + tiles?: () => AttachmentTile[]; } /** Returns true when a later reply block in the same turn supersedes a proposed plan. */ @@ -67,6 +83,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; @@ -77,9 +94,16 @@ function isLaterOutputBlock(block: ReplyBlock): boolean { } } +/** Returns true when a generated media item does not have a failed or canceled status. */ +function isNonFailedMedia(item: TurnMediaItem): boolean { + const status = item.status.toLowerCase(); + return status !== "failed" && status !== "canceled" && status !== "error"; +} + /** Returns a timeout message when an unanswered expired elicitation has no later output. */ function expiredElicitationError( blocks: ReplyBlock[], + media: TurnMediaItem[], active: boolean, ): string | undefined { if (active) return undefined; @@ -105,7 +129,12 @@ function expiredElicitationError( } } if (lastIndex < 0 || !lastKind) return undefined; - if (blocks.slice(lastIndex + 1).some(isLaterOutputBlock)) return undefined; + if ( + blocks.slice(lastIndex + 1).some(isLaterOutputBlock) || + media.some(isNonFailedMedia) + ) { + return undefined; + } return lastKind === "permission" ? "Generation approval timed out." : "Question request timed out."; @@ -118,6 +147,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 +169,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 +226,85 @@ 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(); +/** Converts a raw tool or stream media status to a standard Flow status. */ +function normalizeMediaStatus(raw: string | undefined, hasError: boolean): string { + const status = + raw?.trim().toLowerCase().replace(/^media_generation_status_/, "") ?? ""; + if (status === "error" || status === "failed") return "failed"; + if (status === "canceled" || status === "cancelled") return "canceled"; + if ( + status === "queued" || + status === "in_progress" || + status === "active" || + status === "generating" + ) { + return "pending"; + } + if (status === "succeeded" || status === "successful" || status === "completed") { + return hasError ? "failed" : "success"; + } + if (status) return status; + return hasError ? "failed" : "success"; +} + +/** Reads an error code or message from a media error value. */ +function readMediaError(value: unknown): string | number | undefined { + if (typeof value === "number") return value; + if (typeof value === "string") return value.trim() || undefined; + if (!value || typeof value !== "object") return undefined; + for (const key of ["errorCode", "error_code", "code", "error", "message"]) { + const field = readOwn(value, key); + if (typeof field === "number") return field; + if (typeof field === "string" && field.trim()) return field.trim(); + } + return undefined; +} + +/** Updates one turn media item with the live project tile variant status. */ +function reconcileTurnMedia(item: TurnMediaItem, tiles: AttachmentTile[]): TurnMediaItem { + const normalizedStatus = normalizeMediaStatus(item.status, item.error !== undefined); + const matched = tiles.length > 0 ? resolveRequestedAsset(tiles, item.media_id) : undefined; + if (!matched) { + return { ...item, status: normalizedStatus }; + } + const payload = matched.variant + ? legacyMedia(matched.variant) + : legacyTile(matched.tile).Fb; + const tileStatus = payload?.Zc?.trim().toLowerCase(); + const tileError = readMediaError(payload?.nf); + if (tileStatus === "canceled") { + return { media_id: item.media_id, status: "canceled", error: item.error ?? tileError }; + } + if (tileStatus === "failed" || tileStatus === "error" || (!tileStatus && tileError !== undefined)) { + return { media_id: item.media_id, status: "failed", error: item.error ?? tileError }; + } + const ready = matched.variant + ? isReadyVariant(matched.variant) + : matched.tile.isPending !== true && (tileStatus === undefined || tileStatus === "success"); + if (!ready || tileStatus === "pending" || tileStatus === "scheduled") { + const pendingStatus = tileStatus === "scheduled" ? "scheduled" : "pending"; + return { + media_id: item.media_id, + status: + normalizedStatus === "failed" || normalizedStatus === "canceled" + ? normalizedStatus + : pendingStatus, + error: item.error, + }; + } + if ( + ready && + (tileStatus === undefined || tileStatus === "success") && + (normalizedStatus === "pending" || normalizedStatus === "scheduled") + ) { + return { media_id: item.media_id, status: "success", error: undefined }; + } + return { ...item, status: normalizedStatus }; +} + +/** Reads media IDs, statuses, and errors from legacy Agent tool results. */ +function legacyTurnMedia(flow: FlowAgentExports, turn: LiveTurn): TurnMediaItem[] { + 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 +315,26 @@ 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 media = fields.get("media_id"); + const mediaId = media ? (flow.valueString(media) ?? "").trim() : ""; + if (!mediaId) continue; + const rawStatus = fields.get("status"); + const errorCode = fields.get("error_code"); + const errorDetail = fields.get("error"); + const errorText = + (errorCode ? (flow.valueString(errorCode) ?? "").trim() : "") || + (errorDetail ? (flow.valueString(errorDetail) ?? "").trim() : "") || + undefined; + const status = normalizeMediaStatus( + rawStatus ? flow.valueString(rawStatus) : undefined, + errorText !== undefined, + ); + items.set(mediaId, { media_id: mediaId, status, error: errorText }); } } } - return [...ids].filter(Boolean); + return [...items.values()]; } /** Formats one Agent turn using the same message model that the chat page uses. */ @@ -226,8 +348,18 @@ function formatTurn( 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 rawMedia: TurnMediaItem[] = + turn.Tf && turn.Tf.Bx.size > 0 + ? [...turn.Tf.Bx].map(([mediaId, item]) => ({ + media_id: mediaId, + status: item.status, + error: item.errorCode ?? readMediaError(item), + })) + : legacyTurnMedia(context.flow, turn); + const projectTiles = rawMedia.length > 0 ? (context.tiles?.() ?? []) : []; + const media = rawMedia.map((item) => reconcileTurnMedia(item, projectTiles)); const timeoutError = status !== "stopped" && status !== "in_progress" - ? expiredElicitationError(blocks, active) + ? expiredElicitationError(blocks, media, active) : undefined; const pending = pendingActions( blocks, @@ -244,16 +376,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 @@ -279,14 +401,54 @@ function formatTurn( rich_content: blocks.flatMap((b) => (b.type === "a2ui" ? [b.round] : [])), }, pending_actions: pending, - error: timeoutError ?? rawError, + error: effectiveStatus === "in_progress" ? undefined : (timeoutError ?? rawError), }; } +/** Selects the turn with more content when a server turn stays in progress after a disconnect. */ +function disconnectedInProgressTurn( + context: TurnContext, + saved: StoredTurn, + prior: LiveTurn | undefined, + index: number, +): LiveTurn { + const decoded = context.flow.decode(saved); + if (!prior) return decoded; + const [savedUser, savedReply] = context.flow.reply({ + turn: decoded, + XJ: index, + yc: false, + }); + const [priorUser, priorReply] = context.flow.reply({ + turn: prior, + XJ: index, + yc: false, + }); + if (priorUser.text !== savedUser.text) return decoded; + if (savedReply.ci && priorReply.ci && savedReply.ci !== priorReply.ci) { + return decoded; + } + const savedBlocks = savedReply.Oh?.length ?? decoded.Tf?.Oh.length ?? 0; + const priorBlocks = priorReply.Oh?.length ?? prior.Tf?.Oh.length ?? 0; + const savedMedia = decoded.Tf?.Bx.size ?? 0; + const priorMedia = prior.Tf?.Bx.size ?? 0; + if ( + Boolean(priorReply.ci && !savedReply.ci) || + priorBlocks > savedBlocks || + priorMedia > savedMedia || + priorReply.text.length > savedReply.text.length || + prior.Yu.length > decoded.Yu.length + ) { + return prior; + } + return decoded; +} + /** Formats the current and persisted turns without treating a local partial reply as final. */ export function conversation(context: TurnContext, id: string, stored: StoredTurn[]) { const local = context.transport.ka.ha().get(id); const inProgress = local?.xe; + const hasTransport = context.transport.ha.has(id); const count = Math.max( stored.length, (local?.Vh.length ?? 0) + (inProgress ? 1 : 0), @@ -301,15 +463,25 @@ export function conversation(context: TurnContext, id: string, stored: StoredTur return formatTurn(context, id, inProgress, { number, status: "in_progress", - active: true, + active: hasTransport, latest, }); } 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, + disconnectedInProgressTurn(context, saved, prior, i), + { + number, + status: "in_progress", + active: false, + latest, + }, + ); + } + if (saved && (!prior || state !== undefined)) { return formatTurn(context, id, context.flow.decode(saved), { number, status: storedStatus(state ?? 0), @@ -333,7 +505,7 @@ export function conversation(context: TurnContext, id: string, stored: StoredTur }); } -/** Loads saved turns into the browser before a follow-up message. */ +/** Loads saved turns into the browser and replaces unpersisted local failures before a follow-up message. */ export function loadStoredTurns( context: TurnContext, sessionId: string, @@ -341,7 +513,15 @@ export function loadStoredTurns( ): void { const { flow, transport } = context; const local = transport.ka.ha().get(sessionId); - if (turns.length > (local?.Vh.length ?? 0)) { + const localCount = local?.Vh.length ?? 0; + const hasLocalFailure = Boolean( + local?.Vh.some( + (turn, index) => + turn.errorMessage !== undefined && + (index >= turns.length || turns[index]?.getState() !== 3), + ), + ); + if (turns.length !== localCount || hasLocalFailure) { flow.hydrate(transport.ka, { sessionId, BF: turns.map(flow.decode), diff --git a/ts/index.ts b/ts/index.ts index f28568a..a3abf16 100644 --- a/ts/index.ts +++ b/ts/index.ts @@ -11,6 +11,8 @@ import { agentBusy, agentOp, agentPrototype, + agentPurge, + agentReplay, agentStatus, bindAgent, } from "./agent_chat"; @@ -63,6 +65,8 @@ if (!window.__flowMcp) { agentBusy, agentOp, agentPrototype, + agentPurge, + agentReplay, agentStatus, bindAgent, bindAngularViews, diff --git a/ts/types.ts b/ts/types.ts index 2e1369d..35d2e3a 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -799,6 +799,10 @@ export interface FlowMcpRuntime { agentBusy: typeof import("./agent_chat").agentBusy; /** Runs one operation on the bound Agent. */ agentOp: typeof import("./agent_chat").agentOp; + /** Clears local drafts, turn state, and caches for a session. */ + agentPurge: typeof import("./agent_chat").agentPurge; + /** Sends recorded question answers again on open streams after a reconnect. */ + agentReplay: typeof import("./agent_chat").agentReplay; /** Returns the project page prototype for CDP instance discovery. */ agentPrototype: typeof import("./agent_chat").agentPrototype; /** Checks the Agent build and chat exports. */ From f10570ee865ea01a1ddb79bae37a6f2bc80b08a4 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:21:27 +0000 Subject: [PATCH 2/2] fix(flow): preserve active session locks and local turn hydration - Keep create_session drafts and queue locks on post-send errors - Release the state lock before agentBusy and agentReplay calls - Preserve unsaved local turns when stored turns lag in loadStoredTurns - Clear only verified turn-store session signals in adaptAgentWire - Accept respond calls when the turn ends immediately after submission - Handle CDP errors in purge_session_state and hold_while_active - Combine question and permission checks into isActionAccepted --- src/agent.rs | 220 ++++++++++++++++++++++++++++-------------- ts/agent_chat.ts | 163 +++++++++++++------------------ ts/agent_turns.ts | 26 ++--- ts/agent_wire.ts | 20 +++- ts/frontend_builds.ts | 1 + 5 files changed, 248 insertions(+), 182 deletions(-) diff --git a/src/agent.rs b/src/agent.rs index 0f1134b..4c89097 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -454,8 +454,12 @@ impl AgentChat { if let Err(error) = stage_result { if request.action == AgentAction::CreateSession && let Some(ref sid) = session_id_str + && let Err(purge_error) = + purge_session_state(&mut state, &request.project_id, sid).await { - purge_session_state(&mut state, &request.project_id, sid).await; + return Err(error.context(format!( + "Could not clear draft session {sid}: {purge_error:#}" + ))); } return Err(error); } @@ -473,50 +477,70 @@ impl AgentChat { } else { page.call("agentOp", json!([args])).await }; - let initial_failed = request.action == AgentAction::CreateSession - && match &result { - Err(_) => true, - Ok(raw) => { - raw["ok"].as_bool() != Some(true) - || (raw["persisted"].as_bool() == Some(false) - && raw["turn"]["status"].as_str() == Some("failed")) - } - }; - if initial_failed && let Some(ref sid) = session_id_str { - purge_session_state(&mut state, &request.project_id, sid).await; - } match result { + Ok(raw) if raw["ok"].as_bool() != Some(true) => { + let submitted = matches!( + raw["error"].as_str(), + Some("outcome_unknown" | "agent_submission_not_observed") + ); + if submitted { + if let Some(guard) = execution { + tokio::spawn(hold_while_active( + Arc::clone(&self.state), + request.project_id.clone(), + guard, + )); + } + return checked_runtime_result(raw); + } + let Err(error) = checked_runtime_result(raw) else { + anyhow::bail!("The browser runtime returned an invalid error response"); + }; + if request.action == AgentAction::CreateSession + && let Some(ref sid) = session_id_str + && let Err(purge_error) = + purge_session_state(&mut state, &request.project_id, sid).await + { + return Err(error.context(format!( + "Could not clear draft session {sid}: {purge_error:#}" + ))); + } + Err(error) + } Ok(raw) => { let mut value = checked_runtime_result(raw)?; state.sync_persisted(&request.project_id, &value); - if request.action == AgentAction::DeleteSession { + let unpersisted_failed = request.action == AgentAction::CreateSession + && value["persisted"].as_bool() == Some(false) + && value["turn"]["status"].as_str() == Some("failed"); + if unpersisted_failed || request.action == AgentAction::DeleteSession { if let Some(ref sid) = session_id_str { - purge_session_state(&mut state, &request.project_id, sid).await; + purge_session_state(&mut state, &request.project_id, sid).await?; + } + } else { + if request.action != AgentAction::Resume + && (request.action == AgentAction::Stop || request.starts_turn()) + && let Some(ref sid) = session_id_str + { + state.clear_session_answers(&request.project_id, sid); + } else if request.action == AgentAction::Respond + && let (Some(sid), Some(turn), Some(action_id), Some(answers)) = ( + request.session_id.clone(), + request.turn, + request.action_id.clone(), + request.answers.clone(), + ) + { + state.record_answer( + &request.project_id, + PendingAnswer { + session_id: sid, + turn, + action_id, + answers, + }, + ); } - } else if request.action != AgentAction::Resume - && (request.action == AgentAction::Stop || request.starts_turn()) - && let Some(ref sid) = session_id_str - { - state.clear_session_answers(&request.project_id, sid); - } else if request.action == AgentAction::Respond - && let (Some(sid), Some(turn), Some(action_id), Some(answers)) = ( - request.session_id.clone(), - request.turn, - request.action_id.clone(), - request.answers.clone(), - ) - { - state.record_answer( - &request.project_id, - PendingAnswer { - session_id: sid, - turn, - action_id, - answers, - }, - ); - } - if !initial_failed { if let Some(guard) = execution { tokio::spawn(hold_while_active( Arc::clone(&self.state), @@ -537,9 +561,16 @@ impl AgentChat { value["project_id"] = Value::String(request.project_id); Ok(value) } - Err(error) if request.writes() => { - if let Some(guard) = execution - && !initial_failed + Err(error) => { + if let Some(guard) = execution { + tokio::spawn(hold_while_active( + Arc::clone(&self.state), + request.project_id.clone(), + guard, + )); + } else if request.action == AgentAction::Respond + && request.answers.is_some() + && let Ok(guard) = queue.try_lock_execution() { tokio::spawn(hold_while_active( Arc::clone(&self.state), @@ -547,28 +578,36 @@ impl AgentChat { guard, )); } - anyhow::bail!( - "outcome_unknown (project {}, session {session_id}): {error:#}", - request.project_id - ) + if request.writes() { + anyhow::bail!( + "outcome_unknown (project {}, session {session_id}): {error:#}", + request.project_id + ); + } + Err(error) } - Err(error) => Err(error), } } } /// Removes a session from local state and clears browser drafts and caches. -async fn purge_session_state(state: &mut AgentState, project_id: &str, session_id: &str) { +async fn purge_session_state( + state: &mut AgentState, + project_id: &str, + session_id: &str, +) -> Result<()> { state.remove_draft(project_id, session_id); state.clear_session_answers(project_id, session_id); if let Some(ref agent) = state.agent && agent.page.is_alive() { - let _ = agent + let result = agent .page .call("agentPurge", json!([project_id, session_id])) - .await; + .await?; + checked_runtime_result(result)?; } + Ok(()) } impl AgentPage { @@ -624,6 +663,40 @@ impl AgentPage { } } +/// Returns the active Agent page for `project_id`, or clears saved answers when unbound. +async fn active_project_page( + state: &Mutex, + project_id: &str, +) -> Option> { + let mut locked = state.lock().await; + let Some(agent) = locked.agent.as_ref() else { + locked.answers.remove(project_id); + return None; + }; + if !agent.page.is_alive() || agent.project_id != project_id { + locked.answers.remove(project_id); + return None; + } + Some(Arc::clone(&agent.page)) +} + +/// Returns saved question answers when `project_id` remains bound on a live page. +async fn pending_project_answers( + state: &Mutex, + project_id: &str, +) -> Option> { + let mut locked = state.lock().await; + let Some(agent) = locked.agent.as_ref() else { + locked.answers.remove(project_id); + return None; + }; + if !agent.page.is_alive() || agent.project_id != project_id { + locked.answers.remove(project_id); + return None; + } + Some(locked.answers.get(project_id).cloned().unwrap_or_default()) +} + /// Keeps the job queue lock and sends dropped question answers again while a turn is active. async fn hold_while_active( state: Arc>, @@ -632,33 +705,36 @@ async fn hold_while_active( ) { let mut errors = 0; loop { - let outcome = { - let mut locked = state.lock().await; - let Some(agent) = locked.agent.as_ref() else { - locked.answers.remove(&project_id); - break; - }; - if !agent.page.is_alive() || agent.project_id != project_id { - locked.answers.remove(&project_id); - break; - } - let page = Arc::clone(&agent.page); - let replay = locked.answers.get(&project_id).cloned().unwrap_or_default(); - let busy = page.call("agentBusy", json!([project_id])).await; - if matches!(busy, Ok(Value::Bool(true))) && !replay.is_empty() { - let _ = page.call("agentReplay", json!([project_id, replay])).await; - } - busy + let Some(page) = active_project_page(&state, &project_id).await else { + break; }; - match outcome { + let poll_ok = match page.call("agentBusy", json!([&project_id])).await { Ok(Value::Bool(false)) => break, - Ok(Value::Bool(true)) => errors = 0, - _ => { - errors += 1; - if errors == TURN_POLL_ERROR_LIMIT { + Ok(Value::Bool(true)) => { + let Some(replay) = pending_project_answers(&state, &project_id).await else { break; + }; + if replay.is_empty() { + true + } else { + match page.call("agentReplay", json!([&project_id, replay])).await { + Ok(reply) if reply["ok"].as_bool() == Some(true) => true, + Ok(reply) if reply["error"].as_str() == Some("agent_project_changed") => { + break; + } + Ok(_) | Err(_) => false, + } } } + Ok(_) | Err(_) => false, + }; + if poll_ok { + errors = 0; + } else { + errors += 1; + if errors >= TURN_POLL_ERROR_LIMIT { + break; + } } sleep(TURN_POLL_INTERVAL).await; } diff --git a/ts/agent_chat.ts b/ts/agent_chat.ts index 2d2f609..5dbc738 100644 --- a/ts/agent_chat.ts +++ b/ts/agent_chat.ts @@ -58,8 +58,6 @@ interface Binding { questions: QuestionResponder; /** Reads live project tiles on the bound page. */ tiles: () => AttachmentTile[]; - /** Resets active session signals when they hold `sessionId`. */ - resetActiveSession: (sessionId: string) => void; /** IDs that Flow has yet to add to the session list. */ drafts: Set; } @@ -153,54 +151,6 @@ export function agentPrototype(): object | null { return typeof type === "function" ? type.prototype : null; } -/** Resets writable signals on the native services when they hold `sessionId`. */ -function clearActiveSessionSignals( - targets: Record[], - sessionId: string, -): void { - const store = targets[0]; - const active = targets.find((target) => typeof target.qg === "function"); - if (active && (active.qg as () => unknown)() === sessionId) { - const primary = store?.oa; - if ( - primary && - (typeof primary === "function" || typeof primary === "object") && - typeof (primary as { set?: unknown }).set === "function" - ) { - (primary as { set: (value: undefined) => void }).set(undefined); - } - } - const allocated = typeof store?.la === "function" ? store.la() : undefined; - if (allocated === sessionId) { - const pending = store?.ka; - if ( - pending && - (typeof pending === "function" || typeof pending === "object") && - typeof (pending as { set?: unknown }).set === "function" - ) { - (pending as { set: (value: undefined) => void }).set(undefined); - } - } - for (const target of targets) { - for (const value of Object.values(target)) { - if ( - typeof value === "function" && - typeof (value as { set?: unknown }).set === "function" - ) { - try { - if (value() === sessionId) { - (value as unknown as { set: (next: undefined) => void }).set( - undefined, - ); - } - } catch { - // Ignore unrelated functions on the service. - } - } - } - } -} - /** Finds a live project page and takes its project-scoped service handles. */ export function bindAgent( instances: Record[], @@ -263,15 +213,6 @@ export function bindAgent( permissions, flow, tiles: () => readAgentProjectTiles(page), - resetActiveSession: (sessionId: string) => - clearActiveSessionSignals( - [ - nativeTransport.ka as unknown as Record, - nativeTransport as unknown as Record, - composer as unknown as Record, - ], - sessionId, - ), canSend: () => composer.wb?.() === true, drafts: binding?.page === page ? binding.drafts : new Set(), }; @@ -320,7 +261,6 @@ async function removeCachedQueries( async function purgeSession(bound: Binding, sessionId: string): Promise { bound.drafts.delete(sessionId); bound.transport.ka.yL(sessionId); - bound.resetActiveSession(sessionId); const client = resolveQueryClient(bound.injector, bound.page); await removeCachedQueries( client, @@ -337,8 +277,9 @@ async function purgeSession(bound: Binding, sessionId: string): Promise { /** Clears local drafts, turn signals, active session state, and query caches for one session. */ export async function agentPurge(projectId: string, sessionId: string) { const bound = liveBinding(projectId); - if (!bound) return failure("agent_project_changed"); - await purgeSession(bound, sessionId); + if (bound) { + await purgeSession(bound, sessionId); + } return { ok: true as const, session_id: sessionId }; } @@ -547,32 +488,42 @@ function isStreamAttached(entry: unknown): boolean { return true; } -/** Returns true when the turn records an answer for the question card. */ -function isQuestionAccepted(bound: Binding, sessionId: string, actionId: string): boolean { +/** Returns true when the turn records the caller response on the target action card. */ +function isActionAccepted( + bound: Binding, + sessionId: string, + kind: "permission" | "question", + actionId: string, +): boolean { const session = bound.transport.ka.ha().get(sessionId); const turn = session?.xe ?? session?.Vh.at(-1); const blocks = turn?.Tf?.Oh; if (!blocks) return false; - return blocks.some( - (block) => - block.type === "question" && - block.card.id === actionId && - block.card.Qj !== undefined, + return blocks.some((block) => + kind === "question" + ? block.type === "question" && + block.card.id === actionId && + block.card.Qj !== undefined + : block.type === "permission" && + block.card.id === actionId && + block.card.Vz !== undefined, ); } -/** Returns true when the turn records a decision for the permission card. */ -function isPermissionAccepted(bound: Binding, sessionId: string, actionId: string): boolean { - const session = bound.transport.ka.ha().get(sessionId); - const turn = session?.xe ?? session?.Vh.at(-1); - const blocks = turn?.Tf?.Oh; - if (!blocks) return false; - return blocks.some( - (block) => - block.type === "permission" && - block.card.id === actionId && - block.card.Vz !== undefined, - ); +/** Returns true when an attached stream stays on the same open turn without recording the action. */ +function isActionStillUnaccepted( + bound: Binding, + sessionId: string, + entry: unknown, + attached: boolean, + kind: "permission" | "question", + actionId: string, +): boolean { + if (!attached) return false; + const after = bound.transport.ha.get(sessionId); + if (after !== entry || !isStreamAttached(after)) return false; + if (!bound.transport.ka.ha().get(sessionId)?.xe) return false; + return !isActionAccepted(bound, sessionId, kind, actionId); } /** Applies a decision to one action from the requested turn. */ @@ -611,11 +562,15 @@ async function respond( Ig: action.action_id, action: decision.code, }); - const after = bound.transport.ha.get(id); if ( - attached && - (!isPermissionAccepted(bound, id, action.action_id) || - (after !== undefined && !isStreamAttached(after))) + isActionStillUnaccepted( + bound, + id, + entry, + attached, + "permission", + action.action_id, + ) ) { return failure("agent_action_not_pending"); } @@ -631,12 +586,15 @@ async function respond( Qj: answers, hi: AGENT_SURFACE, }); - const after = bound.transport.ha.get(id); if ( - attached && - (!isQuestionAccepted(bound, id, action.action_id) || - (after !== undefined && - (!isStreamAttached(after) || readOwn(after, "na") !== undefined))) + isActionStillUnaccepted( + bound, + id, + entry, + attached, + "question", + action.action_id, + ) ) { return failure("agent_action_not_pending"); } @@ -676,7 +634,7 @@ async function respond( /** Sends recorded question answers again on open streams after a reconnect resets turn state. */ export function agentReplay(projectId: string, entries: AgentReplayEntry[]) { const bound = liveBinding(projectId); - if (!bound) return { ok: false as const, replayed: 0 }; + if (!bound) return failure("agent_project_changed"); let replayed = 0; for (const entry of entries) { const stream = bound.transport.ha.get(entry.session_id); @@ -700,11 +658,15 @@ export function agentReplay(projectId: string, entries: AgentReplayEntry[]) { Qj: formatted, hi: AGENT_SURFACE, }); - const after = bound.transport.ha.get(entry.session_id); if ( - isQuestionAccepted(bound, entry.session_id, action.action_id) && - (after === undefined || - (isStreamAttached(after) && readOwn(after, "na") === undefined)) + !isActionStillUnaccepted( + bound, + entry.session_id, + stream, + true, + "question", + action.action_id, + ) ) { replayed++; } @@ -731,11 +693,16 @@ async function sendUserMessage( if (request.action === "create_session") { const created = await send(bound, draftSession(id), [], input); if (!created.ok) { - await purgeSession(bound, id); + if ( + created.error !== "outcome_unknown" && + created.error !== "agent_submission_not_observed" + ) { + await purgeSession(bound, id); + } return created; } - if (created.turn.status === "failed") { - const saved = (await savedSessions(bound).catch(() => [])).find( + if (created.turn.status === "failed" && !bound.transport.ha.has(id)) { + const saved = (await savedSessions(bound)).find( (item) => item.session_id === id, ); if (saved) return { ...created, ...saved }; diff --git a/ts/agent_turns.ts b/ts/agent_turns.ts index bca5e24..98380e5 100644 --- a/ts/agent_turns.ts +++ b/ts/agent_turns.ts @@ -512,19 +512,23 @@ export function loadStoredTurns( turns: StoredTurn[], ): void { const { flow, transport } = context; - const local = transport.ka.ha().get(sessionId); - const localCount = local?.Vh.length ?? 0; - const hasLocalFailure = Boolean( - local?.Vh.some( - (turn, index) => - turn.errorMessage !== undefined && - (index >= turns.length || turns[index]?.getState() !== 3), - ), - ); - if (turns.length !== localCount || hasLocalFailure) { + const localTurns = transport.ka.ha().get(sessionId)?.Vh ?? []; + const hasStaleLocalFailure = localTurns.some((turn, index) => { + if (turn.errorMessage === undefined || turn.errorMessage === flow.errors.IC) { + return false; + } + return index >= turns.length || turns[index]?.getState() !== 3; + }); + if (turns.length > localTurns.length || hasStaleLocalFailure) { + const trailing = localTurns + .slice(turns.length) + .filter( + (turn) => + turn.errorMessage === undefined || turn.errorMessage === flow.errors.IC, + ); flow.hydrate(transport.ka, { sessionId, - BF: turns.map(flow.decode), + BF: [...turns.map(flow.decode), ...trailing], hka: false, xe: null, }); diff --git a/ts/agent_wire.ts b/ts/agent_wire.ts index 38f4860..ce57992 100644 --- a/ts/agent_wire.ts +++ b/ts/agent_wire.ts @@ -12,6 +12,8 @@ type Fields = Readonly>; export interface AgentWireFormat { /** Native methods for the transport, turn store, and question service. */ methods: Fields; + /** Writable session ID signals on the turn store. */ + sessionSignals?: readonly string[]; /** Request fields for a new message. */ send: Fields; /** Fields for restoring saved turns. */ @@ -133,6 +135,17 @@ function method(service: object | undefined, name: string): T | undefined { return typeof value === "function" ? value.bind(service) as T : undefined; } +/** Clears a verified writable session signal on the turn store when it holds `sessionId`. */ +function clearSessionSignal(store: object, name: string, sessionId: string): void { + const signal: unknown = Object.getOwnPropertyDescriptor(store, name)?.value; + if (typeof signal !== "function" || signal.length !== 0) return; + const set: unknown = Object.getOwnPropertyDescriptor(signal, "set")?.value; + if (typeof set !== "function") return; + if ((signal as () => unknown)() === sessionId) { + (set as (value: undefined) => void).call(signal, undefined); + } +} + /** Converts this build's service without modifying a native object. */ export function adaptAgentWire( native: AgentWire, @@ -191,7 +204,12 @@ export function adaptAgentWire( } return summaries; }, - yL: clear, + yL: (id) => { + clear(id); + for (const signal of format.sessionSignals ?? []) { + clearSessionSignal(nativeStore, signal, id); + } + }, }, }, flow: { diff --git a/ts/frontend_builds.ts b/ts/frontend_builds.ts index c10c146..1d95e8f 100644 --- a/ts/frontend_builds.ts +++ b/ts/frontend_builds.ts @@ -529,6 +529,7 @@ const NOVEMBER_20_AGENT: AgentChatFormat = { }, wire: { methods: { stop: "uv", deleteSession: "eM", renameSession: "Z2", clearSession: "eM", permissions: "La", answer: "nB" }, + sessionSignals: ["oa", "ka"], send: { Oe: "Te", Gn: "Wn", hi: "wi", Aq: "Wq" }, hydrate: { BF: "hG", hka: "Rla", xe: "Ce" }, resume: { BF: "hG", TM: "BN" },