Skip to content

fix(flow): coordinate agent sessions and answer replays - #40

Closed
google-labs-stitch[bot] wants to merge 2 commits into
mainfrom
stitch/coordinate-agent-sessions-and-replays-jm1-d695d2df-8818-492b-b079-b2b0b331abcd
Closed

google-labs-stitch[bot] wants to merge 2 commits into
mainfrom
stitch/coordinate-agent-sessions-and-replays-jm1-d695d2df-8818-492b-b079-b2b0b331abcd

Conversation

@google-labs-stitch

@google-labs-stitch google-labs-stitch Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Coordinate Flow Agent session state, turn hydration, media status reconciliation, and elicitation answer replay across the Rust runtime (src/agent.rs) and TypeScript browser helpers (ts/):

  • Disconnected server turns and local turn hydration (ts/agent_turns.ts, ts/agent_chat.ts): Report in_progress with connected: false when getAgentSession returns STORED_TURN_IN_PROGRESS without a live stream, keep richer partial blocks from local.Vh while clearing transient disconnect errors, and re-hydrate in loadStoredTurns only when turns.length > localTurns.length or local turns contain unpersisted non-stopped failures while preserving unsaved trailing local turns when server persistence lags.
  • Draft session tracking, queue lock retention, and cache purge (src/agent.rs, ts/agent_chat.ts, ts/agent_wire.ts, ts/frontend_builds.ts, ts/frontend_nov29_agent.ts, ts/agent_protocol.ts, ts/index.ts, ts/types.ts): Track allocated draft IDs in AgentState.drafts, sync persisted sessions on list_sessions and get_session, keep drafts unpurged and spawn hold_while_active with the JobQueue lock when create_session encounters a CDP error/timeout or post-submission outcome_unknown / agent_submission_not_observed, and purge local transport entries (transport.ka.yL), verified turn-store sessionSignals (["oa", "ka"] on 20261120.00_p0 and ["ta", "ka"] on 20261129.06_p0 via own property descriptors), and TanStack Query cache entries (CREATION_AGENT_SESSION, CREATION_AGENT_SESSIONS) via agentPurge on delete_session and pre-submission or unpersisted terminal create_session failures.
  • Cold-load user profile settlement (ts/agent_chat.ts, ts/agent_settings.ts): Wait for ["USER_PROFILE"] query settlement in canSendReady when bound.canSend() stays false after ["PROJECT_DETAILS", projectId], with prefix query fallback and a post-settlement tick flush.
  • Turn media status and tile reconciliation (ts/agent_turns.ts, ts/agent_attachments.ts, ts/frontend_builds.ts, ts/frontend_nov29_upload.ts): Parse status, error_code, and error on legacy _.yjb tool result structs and reconcile turn.Tf.Bx and legacy media items against live project tile variants (readAgentProjectTiles, resolveRequestedAsset, isReadyVariant), reading upsampled video variants from verified build descriptors (yn on 20261120.00_p0, bo on 20261129.06_p0).
  • Memory blocks and elicitation output detection (ts/agent_protocol.ts, ts/agent_turns.ts): Emit { type: "view_agent_memory" } blocks for view_agent_memory tool calls and treat view_agent_memory blocks and non-failed media items as productive turn output in expiredElicitationError.
  • Sequential question cards, immediate turn completion, and lock-free reconnect replay (src/agent.rs, ts/agent_turns.ts, ts/agent_chat.ts, ts/agent_wire.ts, ts/frontend_nov29_agent.ts): Expose only the first unanswered question card in pendingActions, verify card acceptance through isActionAccepted and isActionStillUnaccepted (with verified streamSubscription: Wj on 20261120.00_p0, Ak on 20261129.06_p0) so respond succeeds when a turn finishes immediately upon submission, record question answers (PendingAnswer) in AgentState.answers, release the AgentState mutex before agentBusy and agentReplay CDP calls in hold_while_active, and handle CDP errors explicitly in purge_session_state and hold_while_active.

Verification

  • Run cargo xtask ci (formatting, license headers, 800-code-line limit, doc examples, forbidden constructs, tsc --noEmit, flow contracts, clippy, rustdoc, debug build, and cargo deny).
  • Run RUSTFLAGS="-D warnings" cargo build --release --locked --bin flow-mcp, cargo xtask collect-licenses, and cargo deny --locked --workspace check.
  • Run flow-mcp --headless doctor --json (flow-build: ok on boq_labs-ai-sandbox-frontend_20261129.06_p0).
  • Verify runtime behavior across Flow 20261120.00_p0 and 20261129.06_p0 workspaces.

- 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

@byteland-app byteland-app left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hold_while_active calls agentReplay on every busy poll and ignores its return value. agentReplay sends again whenever the local question still appears pending, which can happen before remote acknowledgement or after a stale reconnect. Separate read-only turn recovery from answer replay. For replay, keep the session, turn, and action identity pinned and use an authoritative acknowledgement or an idempotent write. Check that a delayed acknowledgement and repeated reconnect cannot send the same answer twice. Acquire the execution lock before sending a response that resumes the turn. The current Rust path sends first and ignores lock contention afterward.

@byteland-app

Copy link
Copy Markdown
Contributor

Changes requested.

  1. src/agent.rs (create_session): after a timeout or an error, the code runs agentPurge and drops the execution guard (no hold_while_active). Flow can still produce the answer, and the JobQueue lock is free. A second job can start in parallel, which breaks the one-job-at-a-time rule. The returned outcome_unknown points to a session that is already purged.
  2. src/agent.rs (hold_while_active): it runs agentBusy and agentReplay while it holds the state mutex. All new requests wait during each poll. Release the lock before the CDP calls.
  3. ts/agent_turns.ts (loadStoredTurns): the condition changed from turns.length > local to !==. If the server has not saved the last turn yet, the shorter saved list replaces the local turns, and the next send can lose a turn or repeat a turn number.
  4. ts/agent_chat.ts (clearActiveSessionSignals): it calls every function that has a .set property with no arguments, and it uses minified names (qg, oa, la, ka). A getter with side effects or a new Flow build can clear the wrong state.
  5. respond: the check right after the call can return agent_action_not_pending when the turn ends at once. A retry can send the same action twice.
  6. purge_session_state and hold_while_active ignore CDP errors with let _ =. Handle them. isQuestionAccepted and isPermissionAccepted are almost the same function.

This PR also changes ts/agent_chat.ts, as #29 does.

- 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
@google-labs-stitch

Copy link
Copy Markdown
Contributor Author

Addressed all six review items in commit f10570e:

  1. create_session timeout / error handling (src/agent.rs, ts/agent_chat.ts):

    • Kept the allocated draft session unpurged and spawned hold_while_active with the JobQueue execution guard whenever agentOp returns a CDP error/timeout (Err) or a post-submission outcome_unknown / agent_submission_not_observed error, so outcome_unknown still points to a live draft and the one-job-at-a-time lock stays held while Flow finishes the turn.
    • Restricted purge_session_state / purgeSession on create_session to pre-submission failures (stage_agent_files or pre-send agentOp errors) and terminal unpersisted failed turns (persisted == false, turn.status == "failed", and no open stream in transport.ha).
  2. Lock-free CDP polling in hold_while_active (src/agent.rs):

    • Extracted short-lived mutex helpers (active_project_page and pending_project_answers) so hold_while_active drops the AgentState lock before calling agentBusy and agentReplay over CDP. Concurrent flow_agent requests no longer wait on in-flight poll calls.
  3. loadStoredTurns when server persistence lags (ts/agent_turns.ts):

    • Restored the turns.length > localTurns.length || hasStaleLocalFailure condition (ignoring stopped turn errors flow.errors.IC).
    • Preserved trailing non-failed local turns (localTurns.slice(turns.length)) during hydration so unsaved completed local turns are never dropped or overwritten with duplicate turn numbers when getAgentSession lags behind local state.
  4. Signal clearing without arbitrary .set calls or hardcoded minified names (ts/agent_chat.ts, ts/agent_wire.ts, ts/frontend_builds.ts):

    • Removed clearActiveSessionSignals and resetActiveSession.
    • Added sessionSignals?: readonly string[] to AgentWireFormat (sessionSignals: ["oa", "ka"] on NOVEMBER_20_AGENT.wire) and clearSessionSignal inside adaptAgentWire (transport.ka.yL), reading own property descriptors via Object.getOwnPropertyDescriptor (never invoking getters or scanning unrelated service properties) and clearing only verified zero-argument writable signals holding sessionId.
  5. respond when the turn ends immediately (ts/agent_chat.ts):

    • Added isActionStillUnaccepted, which returns agent_action_not_pending only when the same attached stream remains open on local.xe without recording the response. When a response ends the turn immediately (local.xe becomes null or the stream closes after sending), respond returns the updated turn instead of agent_action_not_pending, avoiding duplicate retries.
  6. Explicit CDP error handling & helper deduplication (src/agent.rs, ts/agent_chat.ts, ts/agent_protocol.ts):

    • Changed purge_session_state to return Result<()> using ? and checked_runtime_result (attaching context on cleanup after an earlier failure and propagating errors directly on delete_session / terminal unpersisted failures), and made agentPurge succeed cleanly when unbound while agentReplay returns failure("agent_project_changed").
    • Updated hold_while_active to match Ok / Err on both agentBusy and agentReplay, counting failures from either call toward TURN_POLL_ERROR_LIMIT and breaking immediately on agent_project_changed.
    • Merged isQuestionAccepted and isPermissionAccepted into isActionAccepted.

Also verified 3-way merge compatibility of ts/agent_chat.ts against #29 (git merge-file produces 0 conflicts).

@byteland-app

Copy link
Copy Markdown
Contributor

Closing this pull request. It conflicts with main, and main now supports Google Flow build 20261129.06_p0 with new field names in the code that this change edits. Please open a new pull request on current main if the change is still needed.

@byteland-app
byteland-app deleted the stitch/coordinate-agent-sessions-and-replays-jm1-d695d2df-8818-492b-b079-b2b0b331abcd branch December 1, 2026 03:30
@google-labs-stitch

Copy link
Copy Markdown
Contributor Author

Opened #59 against current main (47de826) with verified descriptors for Google Flow build boq_labs-ai-sandbox-frontend_20261129.06_p0 (sessionSignals: ["ta", "ka"], streamSubscription: "Ak", upsampled: "bo", and composer[canSendField]).

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant