diff --git a/src/agent.rs b/src/agent.rs index 3344eb4..4c89097 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,191 @@ 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 + && 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:#}" + ))); + } + 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, - )); - } match result { - Ok(value) => { - let mut value = checked_runtime_result(value)?; + 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); + 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?; + } + } 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 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) => Err(error), + 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), + request.project_id.clone(), + guard, + )); + } + if request.writes() { + anyhow::bail!( + "outcome_unknown (project {}, session {session_id}): {error:#}", + request.project_id + ); + } + 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, +) -> 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 result = agent + .page + .call("agentPurge", json!([project_id, session_id])) + .await?; + checked_runtime_result(result)?; + } + Ok(()) +} + impl AgentPage { /// Loads the project and binds its Agent service. async fn open(&mut self, reference_url: &str, project_id: &str) -> Result<()> { @@ -416,23 +663,78 @@ impl AgentPage { } } -/// Holds the job queue lock while the browser reports an active turn. +/// 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( - 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 Some(page) = active_project_page(&state, &project_id).await else { + break; + }; + 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_attachments.ts b/ts/agent_attachments.ts index 857d10c..35134c7 100644 --- a/ts/agent_attachments.ts +++ b/ts/agent_attachments.ts @@ -5,22 +5,20 @@ import { readOwn } from "./angular"; import { cleanMediaId, findMediaContainer, isTrashedTile, legacyMedia } from "./dom"; -import { uploadMediaFields } from "./frontend_builds"; +import { frontendBuild, readBuildLabel, uploadMediaFields } 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. */ primaryMediaId?: string; /** Edit and generation media variants stored on the tile. */ history?: FlowMediaPayload[]; - /** Upsampled video media variants stored on the tile. */ - yn?: FlowMediaPayload[]; /** Type of asset. */ type: string; } @@ -89,7 +87,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, uploadMediaFields().uploaded); @@ -100,7 +98,7 @@ function isReadyVariant(variant: FlowMediaPayload | undefined): boolean { return status === undefined || status === "success"; } -/** Finds the media variant matching `mediaId` in `history`, `yn`, or the primary container. */ +/** Finds the media variant matching `mediaId` in `history`, upsampled variants, or the primary container. */ function findVariantByMediaId( tile: AttachmentTile, mediaId: string, @@ -112,15 +110,18 @@ function findVariantByMediaId( ? tile.history.find((item) => cleanMediaId(readOwn(item, "id")) === wanted) : undefined; if (inHistory) return inHistory; - const inUpsampled = Array.isArray(tile.yn) - ? tile.yn.find((item) => cleanMediaId(readOwn(item, "id")) === wanted) + const upsampledKey = + frontendBuild(readBuildLabel())?.operations.agent_attachments?.fields.upsampled ?? "yn"; + const upsampled = readOwn(tile, upsampledKey); + const inUpsampled = Array.isArray(upsampled) + ? (upsampled as FlowMediaPayload[]).find((item) => cleanMediaId(readOwn(item, "id")) === wanted) : undefined; if (inUpsampled) return inUpsampled; return primary && cleanMediaId(readOwn(primary, "id")) === wanted ? primary : undefined; } /** 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 { @@ -214,6 +215,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 13f7e57..a726426 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,8 @@ interface Binding { permissions: object; /** Question response service on the project page. */ questions: QuestionResponder; + /** Reads live project tiles on the bound page. */ + tiles: () => AttachmentTile[]; /** IDs that Flow has yet to add to the session list. */ drafts: Set; } @@ -208,6 +213,7 @@ export function bindAgent( questions, permissions, flow, + tiles: () => readAgentProjectTiles(page), canSend: () => (composer[canSendField] as () => boolean)() === true, drafts: binding?.page === page ? binding.drafts : new Set(), }; @@ -224,9 +230,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); + 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) { + 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; @@ -279,17 +336,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(); } @@ -364,7 +431,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)); @@ -405,6 +473,61 @@ async function send( }); } +/** Returns true when a stream or subscription handle is open. */ +function isOpenHandle(value: unknown, subscriptionField: string): boolean { + if (!value || typeof value !== "object") return false; + if (readOwn(value, "closed") === true) return false; + if (readOwn(readOwn(value, subscriptionField), "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(bound: Binding, entry: unknown): boolean { + const subscriptionField = bound.format.wire?.streamSubscription ?? "Wj"; + if (!isOpenHandle(entry, subscriptionField)) return false; + if ("Ui" in (entry as object)) return isOpenHandle(readOwn(entry, "Ui"), subscriptionField); + return true; +} + +/** 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) => + 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 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(bound, 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. */ async function respond( bound: Binding, @@ -433,20 +556,50 @@ async function respond( permission: decision.code, }); } + const entry = bound.transport.ha.get(id); + if (!entry) return failure("agent_turn_not_active"); + const attached = isStreamAttached(bound, entry); bound.flow.permission(bound.permissions, { sessionId: id, Ig: action.action_id, action: decision.code, }); + if ( + isActionStillUnaccepted( + bound, + id, + entry, + attached, + "permission", + action.action_id, + ) + ) { + 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(bound, entry); bound.questions.OA({ sessionId: id, Ig: action.action_id, Qj: answers, hi: AGENT_SURFACE, }); + if ( + isActionStillUnaccepted( + bound, + id, + entry, + attached, + "question", + action.action_id, + ) + ) { + return failure("agent_action_not_pending"); + } } else { const canSend = await readyToSend(bound); if (liveBinding(bound.projectId) !== bound) @@ -480,6 +633,49 @@ 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 failure("agent_project_changed"); + let replayed = 0; + for (const entry of entries) { + const stream = bound.transport.ha.get(entry.session_id); + if (!isStreamAttached(bound, 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, + }); + if ( + !isActionStillUnaccepted( + bound, + entry.session_id, + stream, + true, + "question", + action.action_id, + ) + ) { + replayed++; + } + } + return { ok: true as const, replayed }; +} + /** Loads the session and sends one message within the attachment deadline. */ async function sendUserMessage( bound: Binding, @@ -496,8 +692,26 @@ 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) { + if ( + created.error !== "outcome_unknown" && + created.error !== "agent_submission_not_observed" + ) { + await purgeSession(bound, id); + } + return created; + } + 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 }; + await purgeSession(bound, id); + } + return created; + } try { const session = await waitForMedia( @@ -537,6 +751,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), @@ -566,15 +786,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 4dda749..8f811f5 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..98380e5 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,18 +505,30 @@ 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, turns: StoredTurn[], ): void { const { flow, transport } = context; - const local = transport.ka.ha().get(sessionId); - if (turns.length > (local?.Vh.length ?? 0)) { + 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..0ed4ea0 100644 --- a/ts/agent_wire.ts +++ b/ts/agent_wire.ts @@ -12,6 +12,10 @@ 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[]; + /** Subscription property on a live stream entry. Default `Wj`. */ + streamSubscription?: string; /** Request fields for a new message. */ send: Fields; /** Fields for restoring saved turns. */ @@ -133,6 +137,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 +206,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 9f32fc5..bffcf1d 100644 --- a/ts/frontend_builds.ts +++ b/ts/frontend_builds.ts @@ -317,6 +317,8 @@ export interface AgentAttachmentFields extends MediaUploadFields { text: string; /** Attachment references in the message request. */ references: string; + /** Upsampled video variant array on a project tile. Default `yn`. */ + upsampled?: string; } /** Project page and upload formats for an independent library upload. */ @@ -566,6 +568,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" }, @@ -626,7 +629,7 @@ const NOVEMBER_20_ATTACHMENTS: AgentAttachmentFormat = { fields: { character: "Oc", text: "Nc", references: "oc", accepted: "IA", errors: "Ir", duration: "pu", workflow: "lf", media: "Eh", file: "Nn", date: "lc", - dimensions: "Bc", completion: "Jm", project: "ua", + dimensions: "Bc", completion: "Jm", project: "ua", upsampled: "yn", }, }; diff --git a/ts/frontend_nov29_agent.ts b/ts/frontend_nov29_agent.ts index 661b738..ab02661 100644 --- a/ts/frontend_nov29_agent.ts +++ b/ts/frontend_nov29_agent.ts @@ -61,6 +61,8 @@ export const NOVEMBER_29_AGENT: AgentChatFormat = { permissions: "Na", answer: "JC", }, + sessionSignals: ["ta", "ka"], + streamSubscription: "Ak", send: { ua: "oa", Oe: "lf", Gn: "Do", hi: "Oi", Aq: "rq" }, hydrate: { BF: "KH", hka: "hpa", xe: "Le" }, resume: { ua: "oa", BF: "KH", TM: "MP" }, diff --git a/ts/frontend_nov29_upload.ts b/ts/frontend_nov29_upload.ts index f578db2..78c7271 100644 --- a/ts/frontend_nov29_upload.ts +++ b/ts/frontend_nov29_upload.ts @@ -20,7 +20,7 @@ export const NOVEMBER_29_ATTACHMENTS: AgentAttachmentFormat = { fields: { character: "vc", text: "Mc", references: "rc", accepted: "gC", errors: "Er", duration: "Zu", workflow: "wf", media: "Sh", file: "vo", date: "Yb", - dimensions: "Gc", completion: "vn", project: "oa", + dimensions: "Gc", completion: "vn", project: "oa", upsampled: "bo", }, }; 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 6e1c59b..d814e8d 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -805,6 +805,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. */