diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f397348a74..5c3fd4343d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -122,17 +122,23 @@ jobs: needs: build-impact if: ${{ !cancelled() && needs.build-impact.outputs.rust_required != 'false' }} runs-on: ${{ matrix.os }} - timeout-minutes: 30 + timeout-minutes: ${{ matrix.timeout_minutes }} strategy: fail-fast: false matrix: include: - os: ubuntu-latest cache_key: ubuntu - - os: macos-15 - cache_key: macos + timeout_minutes: 30 + # Pin the Intel pool for macOS OS-contract validation; release jobs + # select their Apple Silicon / Intel targets independently. + - os: macos-15-intel + cache_key: macos-intel + # A cold Intel build can still be compiling the CLI at 30 minutes. + timeout_minutes: 75 - os: windows-latest cache_key: windows + timeout_minutes: 30 steps: - uses: actions/checkout@v5 @@ -211,7 +217,7 @@ jobs: matrix: os: - ubuntu-latest - - macos-15 + - macos-15-intel - windows-latest steps: - uses: actions/checkout@v5 diff --git a/docs/architecture/peer-device-mode.md b/docs/architecture/peer-device-mode.md index a4106b4fd0..28fa6c7eaa 100644 --- a/docs/architecture/peer-device-mode.md +++ b/docs/architecture/peer-device-mode.md @@ -125,6 +125,30 @@ records and responses from a device that is no longer rendered. Desktop `RelaySessionHistory` owns the subscription across initial loading, realtime delivery and older-page prefetch. +Desktop/Web FlowChat history publishes complete Turns. The Rust subscriber offers +`turn_history: {version: 1}` on `read_stream`; a response acknowledgement enables +single-Turn snapshots. Hosts also advertise `host_stream_turn_history_v1`. The +first read selects only the last Turn, independently of the ordering of live +events. Large Turns travel in byte/event-bounded packets of one immutable snapshot; +packet offsets and the older-Turn boundary are separate. The live cursor captured +before source IO fences snapshot revisions, and normal live publication resumes +after it. Snapshots are ephemeral, controller scoped, epoch fenced and byte bounded +(one oversized Turn may exceed the budget); they add no persisted format or relay +storage. Identity-only tombstone tracking preserves deletions without suppressing +live publication to another controller. + +Hosts that omit the acknowledgement keep the record-page path: optional root +`turnRecordIds` membership proves completeness across pages, including unchanged +items older than a republished root. Older hosts without membership remain +readable by finishing their available history before publication, so their first +open can be slower. Missing records, non-advancing packets and epoch changes fail +without exposing fragments. A terminal header alone never proves completeness. +`RelaySessionHistory` stages controller-annotated `historyReplay` records outside +the replica until ready. Live records remain incremental even while an older Turn +is loading. After the last Turn is visibly presented, a visible view may prefetch +one adjacent Turn; further reads follow reader demand. Switching back to a partial +session does not automatically drain its history. + Native mobile history keeps these record-page boundaries; a page is not a complete conversation turn. The initial replay and each older-history request reduce all received records before publishing one transcript projection. A turn @@ -251,6 +275,16 @@ the same before, during and after a switch. Seeds carry no history or state machine; they are promoted through the normal metadata path before any open, and a seed that has been opened is never replaced by a later seed. +The displayed row count belongs to the surface/workspace/source view and is +published when the user expands or collapses it. Live and background lists +read the same snapshot during replacement; an unmount-time handoff is too late +for React's incoming render. Collapsing a workspace resets its source views; +Collapse All resets every view. Counts are window-local presentation state. +Disconnecting a control attachment disposes transcripts but leaves the +independent catalog read lease intact. Disposal invalidates the projection's +array deduplication and immediately reseeds metadata from that catalog, so +the still-visible sidebar does not empty while waiting for another read. + A cross-device open publishes a `DeviceOpenIntent` for its whole duration. While it is set, every device keeps its background rows (the rendered device hands over to its live list once, after the open, so the live list's reads never diff --git a/docs/architecture/rust-build-dependency-boundaries.md b/docs/architecture/rust-build-dependency-boundaries.md index ea5487fd96..0a7f548bb8 100644 --- a/docs/architecture/rust-build-dependency-boundaries.md +++ b/docs/architecture/rust-build-dependency-boundaries.md @@ -223,6 +223,7 @@ CI 负责 workspace 级检查、真实产品 feature 组合、跨平台、完整 ### 7.1 Hosted CI 关键路径与缓存 +- 日常 Rust/CLI 验证保留 Linux、Windows 和 macOS 三个平台,macOS 固定使用标准 Intel macOS 15 runner(`macos-15-intel`),避免默认标签的架构迁移和 ARM64 托管资源池分配失败阻塞 OS 契约验证。CLI 与 Rust 使用相同平台矩阵,缓存键区分 Intel。这提供 macOS x64 原生测试证据,不代表 Apple Silicon 运行验证;ARM64/x64 发布目标仍由发布 workflow 的矩阵拥有。 - 验证 job 只依赖自身的编译期前置条件。Tauri `check`/`test` 只要求配置中的前端和资源目录存在时,Rust job 自行创建空目录,不等待或传递可发布前端产物;真实静态资源仍由前端构建和产品打包 owner 负责。 - Rust/CLI 影响分类必须保守且 fail-closed:只有活动路径全部位于 `src/web-ui/**` 时才允许跳过 Rust 与 CLI matrix;仓库根目录/`docs/**` 的 Markdown 和 `png/**` 可作为已知中性伴随路径。其他嵌套 Markdown 可能是 `include_str!`/`include_bytes!` 输入,workflow 不得宽泛忽略全部 Markdown。空变更、非法或不可用 diff range、Rust/build 输入、CI 脚本、其他产品 surface 和所有未识别路径都必须运行完整验证,不能依赖易漏维护的“已知 Rust 目录”名单。PR 使用 base/head 的 merge-base range,只分类 PR 自身改动;`main` push 使用事件 before/head 的 direct range,保留 force-push 或回退提交的实际影响。 - “纯 Web”前提必须是可执行边界:影响分类 job 在计算 diff 前,从 Git 跟踪文件列表扫描全仓 `.rs`(包括 workspace 外 Installer 和根 build script)。除逐行精确登记的既有测试 fixture 外,非注释 Rust 源码不得出现 `web-ui` 路径 token;因此 `include_dir!`、编译嵌入、分段 `PathBuf::join` 和间接路径变量都会在分类前失败。Frontend job 同时显式运行边界 contract tests 和真实 repository boundary check;跨 surface 的命令注册和调用分别由 owner 测试看护。新增类似源码读取时应修复所有权,而不是给影响分类器追加隐式例外。 diff --git a/scripts/check-github-config.test.mjs b/scripts/check-github-config.test.mjs index 46679d4da0..fab2c78af0 100644 --- a/scripts/check-github-config.test.mjs +++ b/scripts/check-github-config.test.mjs @@ -429,7 +429,7 @@ test('keeps Rust CI independent, restore-only on PRs, and target-focused', () => ); assert.deepEqual( rustJob.strategy.matrix.os, - ['ubuntu-latest', 'macos-15', 'windows-latest'], + ['ubuntu-latest', 'macos-15-intel', 'windows-latest'], 'Rust validation must retain the reviewed Linux, macOS, and Windows matrix', ); assert.equal( @@ -472,7 +472,21 @@ test('keeps Rust CI independent, restore-only on PRs, and target-focused', () => } const cliJob = workflow.jobs['cli-test']; - assert.equal(cliJob['timeout-minutes'], 30); + assert.deepEqual( + cliJob.strategy.matrix.include.map((entry) => entry.os), + rustJob.strategy.matrix.os, + 'CLI and Rust validation must exercise the same Linux, Intel macOS, and Windows hosts', + ); + assert.equal( + cliJob.strategy.matrix.include.find((entry) => entry.os === 'macos-15-intel').cache_key, + 'macos-intel', + ); + assert.equal(cliJob['timeout-minutes'], '${{ matrix.timeout_minutes }}'); + assert.deepEqual( + cliJob.strategy.matrix.include.map((entry) => entry.timeout_minutes), + [30, 75, 30], + 'Only the cold Intel macOS CLI build needs a longer job budget', + ); assert.ok( cliJob.strategy.matrix.include.some((entry) => entry.os === 'windows-latest'), 'Windows ConPTY contracts must run before Nightly', diff --git a/src/crates/services/services-integrations/AGENTS.md b/src/crates/services/services-integrations/AGENTS.md index 1ce4f32bb0..47dc024928 100644 --- a/src/crates/services/services-integrations/AGENTS.md +++ b/src/crates/services/services-integrations/AGENTS.md @@ -35,16 +35,32 @@ slices that are outside pure product logic but still platform-neutral. reader. Neither the relay nor any client persists stream content; do not add relay-stored history, `get_session_key`, or a durable stream cache here. - Session history reads use `HostStreamHub::read_history` with a Core-owned - source loader. Backfill allocates decreasing JS-safe sequences below the + source loader. The optional `turn_history` v1 offer selects exactly one Turn; + its response acknowledgement enables the mode, while older hosts retain the + existing record-page reader. Hosts advertise `host_stream_turn_history_v1`. + The immutable snapshot spans bounded packets, carries an older-Turn boundary + separately from its packet offset, and uses the live cursor captured before + source IO as its revision fence. It never allocates live event sequences. + Snapshot IDs are controller/stream scoped and epoch fenced; retained bodies + are byte bounded and expire with leases/grace (one oversized Turn may exceed + the budget). Identity-only tombstone tracking must not suppress subsequent + live publication to other controllers. The subscriber publishes only a + validated complete snapshot and catches up live events during older reads. + Legacy record-page backfill allocates decreasing JS-safe sequences below the live sequence range; it never advances the forward cursor. One source gate orders backfill, live publication, and history invalidation. Undo/import and cache misses across evicted pages require an epoch fence, never silent skips. Only the requested page's bodies enter the bounded log; the pending source - batch is at most one persisted turn, which can itself be large. No wire or - persisted-format migration is required; all controllers retain `read_stream`. - `limit` is a budget for history reads: a page grows to the first record of its + batch is at most one persisted turn, which can itself be large. No persisted + migration is required; the optional wire fields keep `read_stream` compatible. + In legacy record paging, `limit` is a budget: a page grows to the first record of its oldest turn so no turn splits across pages, within the hard event and byte bounds. Controllers must not assume a page holds at most `limit` events. + Root records carry optional `turnRecordIds` membership. The Rust subscriber + joins bounded history pages until those members are present, even if a live + root moved ahead of its unchanged children; legacy hosts without membership + finish their available history read before presentation. Never treat a page + limit, a terminal header or a timeout as proof of a complete Turn. - The `remote-persistence` feature is the lightweight persisted-shape owner shared by Remote Connect, remote SSH, and offline migration. Keep it free of network, SSH transport, and runtime orchestration dependencies so owner readers and @@ -144,7 +160,7 @@ cargo test -p openbitfun-services-integrations --no-default-features --features cargo test --locked -p openbitfun-services-integrations --no-default-features --features remote-ssh-concrete --lib remote_ssh::relay_deploy::tests:: cargo test --locked -p openbitfun-services-integrations --no-default-features --features remote-connect --lib remote_connect::account::tests cargo test --locked -p openbitfun-services-integrations --no-default-features --features remote-connect --lib remote_connect::relay_client::tests:: -cargo test --locked -p openbitfun-services-integrations --no-default-features --features remote-connect --lib remote_connect::host_stream::tests:: +cargo test --locked -p openbitfun-services-integrations --no-default-features --features remote-connect --lib remote_connect::host_stream:: cargo test --locked -p openbitfun-services-integrations --no-default-features --features remote-connect --lib remote_connect::host_stream_subscriber::tests:: cargo test -p openbitfun-services-integrations --no-default-features --features file-watch --test file_watch_contracts cargo test --locked -p openbitfun-services-integrations --no-default-features --features workspace-search --test workspace_search_contracts diff --git a/src/crates/services/services-integrations/src/remote_connect.rs b/src/crates/services/services-integrations/src/remote_connect.rs index 3f1bc7cf9f..bcf40734b7 100644 --- a/src/crates/services/services-integrations/src/remote_connect.rs +++ b/src/crates/services/services-integrations/src/remote_connect.rs @@ -572,7 +572,7 @@ pub const REMOTE_CAPABILITY_PLAN_BUILD_V1: &str = "plan_build_v1"; /// must check this string before offering the write; a host without it can /// still answer `get_model_catalog` read-only. pub const REMOTE_CAPABILITY_DEVICE_MODEL_DEFAULTS_V1: &str = "device_model_defaults_v1"; -pub use host_stream::REMOTE_CAPABILITY_HOST_STREAM_V1; +pub use host_stream::{REMOTE_CAPABILITY_HOST_STREAM_V1, REMOTE_CAPABILITY_TURN_HISTORY_V1}; fn remote_host_capabilities() -> Vec { vec![ @@ -586,6 +586,7 @@ fn remote_host_capabilities() -> Vec { REMOTE_CAPABILITY_USER_QUESTION_INTERACTION_V1.to_string(), REMOTE_CAPABILITY_BACKGROUND_RESULT_DELIVERY_V1.to_string(), REMOTE_CAPABILITY_HOST_STREAM_V1.to_string(), + REMOTE_CAPABILITY_TURN_HISTORY_V1.to_string(), REMOTE_CAPABILITY_DEVICE_MODEL_DEFAULTS_V1.to_string(), ] } diff --git a/src/crates/services/services-integrations/src/remote_connect/host_stream.rs b/src/crates/services/services-integrations/src/remote_connect/host_stream.rs index acf19362e8..72ccedb0de 100644 --- a/src/crates/services/services-integrations/src/remote_connect/host_stream.rs +++ b/src/crates/services/services-integrations/src/remote_connect/host_stream.rs @@ -14,6 +14,10 @@ use std::{ time::{Duration, Instant}, }; +mod turn_history; +use turn_history::TurnSnapshot; +pub use turn_history::{TurnHistoryPage, TurnHistoryRequest}; + /// Contains a separator rejected by runtime Session IDs, so control metadata /// cannot alias a user's session. pub const HOST_CATALOG_ID: &str = "@host/catalog"; @@ -21,6 +25,7 @@ pub const HOST_CATALOG_ID: &str = "@host/catalog"; pub const HOST_STREAM_CHANGED_EVENT: &str = "host-stream-changed"; /// Advertised in `get_workspace_info.capabilities` by hosts serving `read_stream`. pub const REMOTE_CAPABILITY_HOST_STREAM_V1: &str = "host_stream_v1"; +pub const REMOTE_CAPABILITY_TURN_HISTORY_V1: &str = "host_stream_turn_history_v1"; /// Returned to controllers that still ask for a relay-stored session key. pub const RELAY_SESSION_HISTORY_RETIRED_MESSAGE: &str = "Relay-stored session history has been retired; session content is now read directly from the online host. Update the controlling app to continue."; @@ -59,6 +64,9 @@ pub struct StreamPage { /// Older history was evicted from host memory; `has_more=false` then means /// "unavailable", not "complete". pub truncated: bool, + /// Present only when the host accepted the optional single-Turn read offer. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub turn_history: Option, } /// A stream read request as carried by `RemoteCommand::ReadStream`. @@ -79,6 +87,9 @@ pub struct StreamReadRequest { /// Keep (or start) receiving change hints for this stream. #[serde(default)] pub subscribe: bool, + /// Optional read negotiation. Older hosts ignore it and return ordinary pages. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub turn_history: Option, } /// Delivers an encrypted `DeviceEvent` hint to one subscribed device. Hosts own @@ -143,6 +154,10 @@ struct StreamLog { truncated: bool, subscribers: HashMap, last_activity: Instant, + turn_snapshots: HashMap, + /// Snapshot identities participate in tombstones, but must not suppress a + /// later live publication that other subscribers have not received yet. + snapshot_record_turns: HashMap, } impl StreamLog { @@ -158,6 +173,8 @@ impl StreamLog { truncated: false, subscribers: HashMap::new(), last_activity: Instant::now(), + turn_snapshots: HashMap::new(), + snapshot_record_turns: HashMap::new(), } } @@ -358,6 +375,7 @@ impl StreamLog { cursor: self.latest(), oldest_seq: self.oldest(), truncated: self.truncated, + turn_history: None, }) } } @@ -471,6 +489,10 @@ impl HostStreamHub { let now = Instant::now(); state.streams.retain(|_, log| { log.subscribers.retain(|_, expires| *expires > now); + log.turn_snapshots.retain(|_, snapshot| { + now.duration_since(snapshot.last_activity) < STREAM_GRACE + && log.subscribers.contains_key(&snapshot.device) + }); !log.subscribers.is_empty() || now.duration_since(log.last_activity) < STREAM_GRACE }); @@ -553,7 +575,10 @@ impl HostStreamHub { let Some(log) = state.streams.get_mut(session_id) else { return false; }; - if log.history.is_none() { + if log.history.is_none() + && log.turn_snapshots.is_empty() + && log.snapshot_record_turns.is_empty() + { return false; } let subscribers = std::mem::take(&mut log.subscribers); @@ -595,6 +620,9 @@ impl HostStreamHub { F: FnMut(Option) -> Fut, Fut: std::future::Future>, { + if let Some(history) = &request.turn_history { + return self.read_turn_history(device, request, history, load).await; + } if request.after.is_some() && request.before.is_some() { bail!("read_stream accepts either after or before, not both"); } @@ -758,6 +786,8 @@ impl HostStreamHub { let mut state = self.lock(); if let Some(log) = state.streams.get_mut(stream_id) { log.subscribers.remove(source_device_id); + log.turn_snapshots + .retain(|_, snapshot| snapshot.device != source_device_id); log.last_activity = Instant::now(); } } @@ -769,6 +799,8 @@ impl HostStreamHub { for log in state.streams.values_mut() { log.subscribers .retain(|device, _| online_device_ids.iter().any(|id| id == device)); + log.turn_snapshots + .retain(|_, snapshot| online_device_ids.contains(&snapshot.device)); } } @@ -930,11 +962,16 @@ fn diff_records( let removed: Vec = log .record_index .iter() - .filter(|(id, entry)| !present.contains(*id) && (full || scope.contains(&entry.turn))) + .map(|(id, entry)| (id, &entry.turn)) + .chain(log.snapshot_record_turns.iter()) + .filter(|(id, turn)| !present.contains(*id) && (full || scope.contains(*turn))) .map(|(id, _)| id.clone()) + .collect::>() + .into_iter() .collect(); for id in removed { log.record_index.remove(&id); + log.snapshot_record_turns.remove(&id); changed.push(serde_json::json!({"sessionId":session_id,"id":id,"deleted":true})); } if changed.is_empty() { diff --git a/src/crates/services/services-integrations/src/remote_connect/host_stream/turn_history.rs b/src/crates/services/services-integrations/src/remote_connect/host_stream/turn_history.rs new file mode 100644 index 0000000000..68d99295d1 --- /dev/null +++ b/src/crates/services/services-integrations/src/remote_connect/host_stream/turn_history.rs @@ -0,0 +1,546 @@ +//! Optional single-Turn snapshots over the existing encrypted stream RPC. +//! The source, replica and live stream keep their owners. A snapshot only pins +//! one source read across bounded packets; it is not an offline history cache. +use super::*; + +const VERSION: u32 = 1; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TurnHistoryRequest { + pub version: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub before_turn: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub snapshot_id: Option, + #[serde(default)] + pub offset: usize, +} + +impl TurnHistoryRequest { + pub fn latest() -> Self { + Self { + version: VERSION, + before_turn: None, + snapshot_id: None, + offset: 0, + } + } +} + +/// Echoing version 1 accepts the controller's offer. An absent field is an +/// older host, so the controller must keep the ordinary stream-page reader. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TurnHistoryPage { + pub version: u32, + pub snapshot_id: String, + pub turn_id: Option, + pub record_count: usize, + pub offset: usize, + pub next_offset: Option, + pub before_turn: Option, +} + +pub(super) struct TurnSnapshot { + pub(super) device: String, + pub(super) last_activity: Instant, + bytes: usize, + cursor: u64, + before_turn: Option, + turn_id: Option, + events: Vec<(StreamEvent, usize)>, +} + +impl HostStreamHub { + pub(super) async fn read_turn_history( + &self, + device: &str, + request: &StreamReadRequest, + history: &TurnHistoryRequest, + mut load: F, + ) -> Result + where + F: FnMut(Option) -> Fut, + Fut: std::future::Future>, + { + if history.version != VERSION { + bail!("Unsupported Turn history version"); + } + if request.stream_id.is_empty() || request.after.is_some() || request.before.is_some() { + bail!("Turn history reads cannot use event cursors"); + } + if history.snapshot_id.is_none() && history.offset != 0 { + bail!("Turn history offset requires a snapshot"); + } + let gate = self.source_gate(&request.stream_id).await; + let _source = gate.lock().await; + let cursor = { + let mut state = self.lock(); + let log = state + .streams + .entry(request.stream_id.clone()) + .or_insert_with(Self::paged_log); + // A materialized but empty legacy log has no positive revision yet. + if log.latest() == 0 { + log.next_seq = HISTORY_SEQUENCE_CEILING; + } + log.last_activity = Instant::now(); + if request.subscribe { + log.subscribers + .insert(device.to_owned(), Instant::now() + SUBSCRIPTION_LEASE); + } + if request.epoch.is_some_and(|epoch| epoch != log.epoch) { + // No stale snapshot content: the normal epoch fence tells the + // reader to reopen, including after undo/import/host restart. + return log.read(&request.stream_id, request); + } + if let Some(id) = &history.snapshot_id { + return log.read_turn_snapshot( + device, + &request.stream_id, + id, + history.offset, + request.limit, + ); + } + // Capture BEFORE IO. Controls may append while the source is read; + // catch-up must still deliver them. Canonical record publication + // shares this source gate, so subsequent revisions exceed this fence. + log.latest() + }; + let started = Instant::now(); + let batch = load(history.before_turn).await?; + if history + .before_turn + .zip(batch.before) + .is_some_and(|(old, next)| next >= old) + { + bail!("Turn history source did not advance"); + } + let mut turn_id = None; + let mut identities = HashSet::new(); + let mut events = Vec::with_capacity(batch.records.len()); + let mut bytes = 0; + for mut payload in batch.records { + if payload["sessionId"].as_str() != Some(request.stream_id.as_str()) { + bail!("Turn snapshot session identity mismatch"); + } + let turn = payload + .pointer("/turn/turnId") + .and_then(Value::as_str) + .context("Turn snapshot identity missing")? + .to_owned(); + if turn_id.as_ref().is_some_and(|selected| selected != &turn) { + bail!("Turn history source returned more than one Turn"); + } + turn_id = Some(turn); + let id = payload["id"] + .as_str() + .context("Turn snapshot record identity missing")? + .to_owned(); + if !identities.insert(id) { + bail!("Duplicate Turn snapshot record"); + } + // These records describe the same atomic source snapshot at the + // receive fence. They do not allocate live event sequences. A later + // live upsert/tombstone has a greater revision in the same replica. + payload["revision"] = cursor.into(); + let size = estimate_bytes(&payload) + 48; + bytes += size; + events.push(( + StreamEvent { + seq: cursor, + event: "session-record".into(), + payload, + }, + size, + )); + } + if let Some(turn) = &turn_id { + if !identities.contains(&format!("turn/{turn}")) { + bail!("Turn snapshot root missing"); + } + } else if batch.before.is_some() { + bail!("Empty Turn history source did not exhaust history"); + } + let id = format!( + "{:016x}{:016x}", + rand::random::(), + rand::random::() + ); + let mut state = self.lock(); + let log = state + .streams + .get_mut(&request.stream_id) + .context("History stream expired")?; + for record in identities { + log.snapshot_record_turns + .insert(record, turn_id.clone().unwrap()); + } + log.turn_snapshots.insert( + id.clone(), + TurnSnapshot { + device: device.to_owned(), + last_activity: Instant::now(), + bytes, + cursor, + before_turn: batch.before, + turn_id, + events, + }, + ); + // Keep only reconstructable bounded state. As with the source's pending + // Turn, one oversized Turn may exceed the budget; competing snapshots + // are evicted explicitly and their readers receive a retryable error. + let now = Instant::now(); + log.turn_snapshots.retain(|key, snapshot| { + key == &id || now.duration_since(snapshot.last_activity) < STREAM_GRACE + }); + while log.turn_snapshots.len() > 1 + && log + .turn_snapshots + .values() + .map(|snapshot| snapshot.bytes) + .sum::() + > STREAM_BYTES_BUDGET + { + let oldest = log + .turn_snapshots + .iter() + .filter(|(key, _)| *key != &id) + .min_by_key(|(_, snapshot)| snapshot.last_activity) + .map(|(key, _)| key.clone()) + .unwrap(); + log.turn_snapshots.remove(&oldest); + } + log::debug!( + "Read single Turn history: stream_id={} records={} bytes={} has_more={} elapsed_ms={}", + request.stream_id, + log.turn_snapshots[&id].events.len(), + bytes, + batch.before.is_some(), + started.elapsed().as_millis() + ); + log.read_turn_snapshot(device, &request.stream_id, &id, 0, request.limit) + } +} + +impl StreamLog { + fn read_turn_snapshot( + &mut self, + device: &str, + stream: &str, + id: &str, + offset: usize, + limit: Option, + ) -> Result { + let snapshot = self + .turn_snapshots + .get_mut(id) + .context("Turn history snapshot expired; retry the read")?; + if snapshot.device != device { + bail!("Turn history snapshot belongs to another controller"); + } + if offset > snapshot.events.len() { + bail!("Invalid Turn history snapshot offset"); + } + snapshot.last_activity = Instant::now(); + let mut bytes = 0; + let mut events = Vec::new(); + for (event, size) in snapshot.events.iter().skip(offset) { + if !events.is_empty() + && (events.len() + >= limit + .unwrap_or(DEFAULT_PAGE_EVENTS) + .clamp(1, MAX_PAGE_EVENTS) + || bytes + size > PAGE_BYTES) + { + break; + } + bytes += size; + events.push(event.clone()); + } + let end = offset + events.len(); + Ok(StreamPage { + stream_id: stream.to_owned(), + epoch: self.epoch, + events, + has_more: snapshot.before_turn.is_some(), + cursor: snapshot.cursor, + oldest_seq: snapshot.cursor, + truncated: false, + turn_history: Some(TurnHistoryPage { + version: VERSION, + snapshot_id: id.to_owned(), + turn_id: snapshot.turn_id.clone(), + record_count: snapshot.events.len(), + offset, + next_offset: (end < snapshot.events.len()).then_some(end), + before_turn: snapshot.before_turn, + }), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct Quiet; + impl HostStreamNotifier for Quiet { + fn notify(&self, _: &str, _: Value) {} + } + fn request() -> StreamReadRequest { + StreamReadRequest { + stream_id: "s".into(), + subscribe: true, + turn_history: Some(TurnHistoryRequest::latest()), + ..Default::default() + } + } + pub(super) fn records(index: usize, items: usize) -> Vec { + let turn = serde_json::json!({"turnId":format!("t{index}"),"sessionId":"s","turnIndex":index,"status":"completed"}); + let mut records = + vec![serde_json::json!({"sessionId":"s","id":format!("turn/t{index}"),"turn":turn})]; + for item in 0..items { + records.push( + serde_json::json!({"sessionId":"s","id":format!("item/{index}-{item}"),"turn":turn, + "round":{"id":format!("r{index}"),"turnId":format!("t{index}"),"roundIndex":0}, + "item":{"type":"text","data":{"id":format!("{index}-{item}"),"content":"body"}}}), + ); + } + records + } + fn continuation(page: &StreamPage) -> StreamReadRequest { + let history = page.turn_history.as_ref().unwrap(); + StreamReadRequest { + epoch: Some(page.epoch), + turn_history: Some(TurnHistoryRequest { + snapshot_id: Some(history.snapshot_id.clone()), + offset: history.next_offset.unwrap(), + ..TurnHistoryRequest::latest() + }), + ..request() + } + } + + #[tokio::test] + async fn opens_only_the_last_turn_independently_of_total_history_size_or_live_event_order() { + let hub = HostStreamHub::start(Arc::new(Quiet)); + hub.activate("s"); + hub.synchronize_records("s".into(), false, || async { Ok(records(0, 2)) }) + .await + .unwrap(); + let reads = AtomicUsize::new(0); + let first = hub + .read_history("desktop", &request(), |before| { + reads.fetch_add(1, Ordering::SeqCst); + assert!(before.is_none()); + async { + Ok(HistoryBatch { + records: records(999, 1), + before: Some(999), + }) + } + }) + .await + .unwrap(); + assert_eq!(reads.load(Ordering::SeqCst), 1); + assert_eq!(first.events.len(), 2); + assert!(first + .events + .iter() + .all(|event| event.payload["turn"]["turnIndex"] == 999)); + assert_eq!(first.turn_history.as_ref().unwrap().next_offset, None); + assert!(first.has_more); + // No source scan to fill 48/200 events, even for a two-record last Turn. + let older_request = StreamReadRequest { + epoch: Some(first.epoch), + turn_history: Some(TurnHistoryRequest { + before_turn: first.turn_history.as_ref().unwrap().before_turn, + ..TurnHistoryRequest::latest() + }), + ..request() + }; + let older = hub + .read_history("desktop", &older_request, |before| { + assert_eq!(before, Some(999)); + async { + Ok(HistoryBatch { + records: records(998, 1), + before: Some(998), + }) + } + }) + .await + .unwrap(); + assert_eq!(older.turn_history.unwrap().turn_id.as_deref(), Some("t998")); + } + + #[tokio::test] + async fn large_turn_packets_are_immutable_and_live_updates_and_deletions_resume_after_the_fence( + ) { + let hub = HostStreamHub::start(Arc::new(Quiet)); + let first = hub + .read_history( + "desktop", + &StreamReadRequest { + limit: Some(2), + ..request() + }, + |_| async { + Ok(HistoryBatch { + records: records(5, 5), + before: Some(5), + }) + }, + ) + .await + .unwrap(); + assert_eq!(first.events.len(), 2); + let mut changed = records(5, 4); // Delete the final item while the snapshot is in flight. + changed[1]["item"]["data"]["content"] = "new live content".into(); + hub.synchronize_records("s".into(), false, || async { Ok(changed) }) + .await + .unwrap(); + let second_request = continuation(&first); + let second = hub + .read_history("desktop", &second_request, |_| async { + panic!("continuations never reread the source") + }) + .await + .unwrap(); + let retried = hub + .read_history("desktop", &second_request, |_| async { + panic!("retry is the same immutable packet") + }) + .await + .unwrap(); + assert_eq!(second, retried); + assert_eq!(second.events.len(), 4); + assert!(second + .events + .iter() + .all(|event| event.payload["item"]["data"]["content"] == "body")); + assert_eq!(second.cursor, first.cursor); + assert_eq!(second.turn_history.unwrap().next_offset, None); + let live = hub + .read( + "desktop", + &StreamReadRequest { + stream_id: "s".into(), + after: Some(first.cursor), + epoch: Some(first.epoch), + subscribe: true, + ..Default::default() + }, + ) + .unwrap(); + assert!(live.events.iter().all(|event| event.seq > first.cursor)); + assert!(live + .events + .iter() + .any(|event| event.payload["item"]["data"]["content"] == "new live content")); + assert!(live + .events + .iter() + .any(|event| event.payload["id"] == "item/5-4" && event.payload["deleted"] == true)); + } + + #[tokio::test] + async fn packets_keep_byte_bounds_and_snapshots_are_controller_scoped_and_epoch_fenced() { + let hub = HostStreamHub::start(Arc::new(Quiet)); + let mut body = records(0, 2); + body[1]["item"]["data"]["content"] = "a".repeat(PAGE_BYTES).into(); + let first = hub + .read_history("desktop", &request(), |_| { + let records = body.clone(); + async { + Ok(HistoryBatch { + records, + before: None, + }) + } + }) + .await + .unwrap(); + assert_eq!(first.events.len(), 1); + let next = continuation(&first); + assert!(hub + .read_history("other", &next, |_| async { unreachable!() }) + .await + .is_err()); + let second = hub + .read_history("desktop", &next, |_| async { unreachable!() }) + .await + .unwrap(); + assert_eq!(second.events.len(), 1); // A single oversized event travels alone. + assert!(hub.invalidate_paged_history("s").await); + let stale = hub + .read_history("desktop", &continuation(&second), |_| async { + unreachable!() + }) + .await + .unwrap(); + assert_ne!(stale.epoch, first.epoch); + assert!(stale.turn_history.is_none()); + assert!(stale.events.is_empty()); + } + + #[tokio::test] + async fn live_publication_is_not_suppressed_by_a_snapshot_seen_by_only_one_controller() { + let hub = HostStreamHub::start(Arc::new(Quiet)); + let snapshot = hub + .read_history("a", &request(), |_| async { + Ok(HistoryBatch { + records: records(0, 1), + before: None, + }) + }) + .await + .unwrap(); + hub.synchronize_records("s".into(), false, || async { Ok(records(0, 1)) }) + .await + .unwrap(); + let live = hub + .read( + "b", + &StreamReadRequest { + stream_id: "s".into(), + after: Some(snapshot.cursor), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(live.events.len(), 2); + hub.unsubscribe("a", "s"); + assert!(hub.lock().streams["s"].turn_snapshots.is_empty()); + } + + #[test] + fn legacy_wire_shapes_round_trip_without_new_fields_and_ignore_the_read_offer() { + let old = serde_json::json!({"stream_id":"s","subscribe":true,"limit":48}); + let read: StreamReadRequest = serde_json::from_value(old.clone()).unwrap(); + assert!(read.turn_history.is_none()); + assert_eq!(serde_json::to_value(read).unwrap(), old); + #[derive(Deserialize)] + struct LegacyRequest { + stream_id: String, + limit: Option, + subscribe: bool, + } + let offered = serde_json::to_value(StreamReadRequest { + limit: Some(48), + ..request() + }) + .unwrap(); + let legacy: LegacyRequest = serde_json::from_value(offered).unwrap(); + assert_eq!(legacy.stream_id, "s"); + assert_eq!(legacy.limit, Some(48)); + assert!(legacy.subscribe); + let old_page = serde_json::json!({"stream_id":"s","epoch":1,"events":[],"has_more":false,"cursor":1,"oldest_seq":1,"truncated":false}); + let page: StreamPage = serde_json::from_value(old_page.clone()).unwrap(); + assert!(page.turn_history.is_none()); + assert_eq!(serde_json::to_value(page).unwrap(), old_page); + } +} diff --git a/src/crates/services/services-integrations/src/remote_connect/host_stream_subscriber.rs b/src/crates/services/services-integrations/src/remote_connect/host_stream_subscriber.rs index 9a704f3e3e..142586996d 100644 --- a/src/crates/services/services-integrations/src/remote_connect/host_stream_subscriber.rs +++ b/src/crates/services/services-integrations/src/remote_connect/host_stream_subscriber.rs @@ -3,20 +3,23 @@ //! RPC, and closing the subscriber only stops observing that host. use super::{ account::{AccountClient, AccountSession, StreamHint}, - host_stream::{StreamPage, StreamReadRequest}, + host_stream::{StreamPage, StreamReadRequest, TurnHistoryRequest}, }; use anyhow::{anyhow, bail, Context, Result}; use serde::Deserialize; -use std::{sync::Arc, time::Duration}; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, + time::Duration, +}; use tokio::sync::{broadcast, mpsc, oneshot}; const KEEPALIVE: Duration = Duration::from_secs(4 * 60); /// Event budget of the first page of an open: enough to fill a transcript view, /// so the session shows after one small read instead of a full 200-event / /// 768 KiB page over the relay. Older pages follow in the background. Every -/// host honours `limit`, so no capability is needed; current hosts extend the -/// page to the first record of the turn the budget ran out in, older ones cut it -/// mid-turn and their boundary turn fills in with the next page. +/// host honours `limit`. Transport pages are joined until their Turn membership +/// is complete; no transport budget is a presentation boundary. const FIRST_PAGE_EVENTS: usize = 48; const UNSUPPORTED_HOST_MESSAGE: &str = "The controlled device runs an older OpenBitFun version that does not support on-demand session streaming. Update OpenBitFun on that device to continue."; @@ -65,6 +68,7 @@ impl StreamTransport for DeviceRpcTransport { "epoch": request.epoch, "limit": request.limit, "subscribe": request.subscribe, + "turn_history": request.turn_history, }); let response = AccountClient::new() .device_rpc( @@ -111,6 +115,7 @@ pub struct HostStreamSubscriber { unsubscribe: Option>, } +#[derive(Clone)] struct Reader { transport: Arc, session_id: String, @@ -119,6 +124,9 @@ struct Reader { cursor: u64, oldest: u64, has_more: bool, + /// Set only after a host acknowledges the optional Turn-history offer. + turn_history: bool, + before_turn: Option, } impl Reader { @@ -130,12 +138,215 @@ impl Reader { Ok(page) } - fn emit_page(&self, page: &StreamPage) -> Result<()> { + /// A root's optional membership list proves which records form a whole + /// Turn, even when live updates moved that root ahead of unchanged items. + /// Old hosts have no such proof: finish their bounded pages before exposing + /// history, rather than guessing from a header, count, or elapsed time. + async fn read_history(&self, request: StreamReadRequest) -> Result { + let expected_epoch = request.epoch; + let mut page = self.read(request).await?; + if expected_epoch.is_some_and(|epoch| epoch != page.epoch) { + return Ok(page); + } + if page.turn_history.is_some() { + return self.join_turn_snapshot(page).await; + } + if self.turn_history && expected_epoch.is_some() { + bail!("The host stopped supporting Turn history; reopen the session to retry"); + } + let mut record_ids = HashSet::::new(); + let mut turns = HashMap::)>>::new(); + let mut batches = Vec::new(); + loop { + for event in &page.events { + if event.event != "session-record" { + continue; + } + let payload = &event.payload; + let Some(id) = payload["id"].as_str() else { + continue; + }; + record_ids.insert(id.to_owned()); + let Some(turn_id) = payload.pointer("/turn/turnId").and_then(|id| id.as_str()) + else { + continue; + }; + let membership = turns.entry(turn_id.to_owned()).or_default(); + if id == format!("turn/{turn_id}") { + if let Some(ids) = payload.get("turnRecordIds") { + let ids: Vec = serde_json::from_value(ids.clone()) + .context("Invalid history Turn membership")?; + if !ids.iter().any(|key| key == id) { + bail!("History Turn membership omitted its root"); + } + let revision = payload["revision"].as_u64().unwrap_or(event.seq); + if membership.as_ref().is_none_or(|(old, _)| revision > *old) { + *membership = Some((revision, ids)); + } + } + } + } + let complete = !turns.is_empty() + && turns.values().all(|membership| { + membership + .as_ref() + .is_some_and(|(_, ids)| ids.iter().all(|id| record_ids.contains(id))) + }); + let missing_record = turns + .values() + .flatten() + .any(|(_, ids)| ids.iter().any(|id| !record_ids.contains(id))); + if complete || !page.has_more { + if !complete && (page.truncated || missing_record) { + bail!("The host could not provide a complete history Turn; reopen the session to retry"); + } + // Reads travel backwards; delivery stays chronological. This + // also preserves ordering of runtime controls between records. + for batch in batches.into_iter().rev() { + page.events.extend(batch); + } + return Ok(page); + } + let before = page + .events + .first() + .map(|event| event.seq) + .context("History page did not advance")?; + let older = self + .read(StreamReadRequest { + stream_id: self.session_id.clone(), + before: Some(before), + epoch: Some(page.epoch), + subscribe: true, + ..Default::default() + }) + .await?; + if older.epoch != page.epoch { + bail!( + "Session history restarted while reading a Turn; reopen the session to retry" + ); + } + if older + .events + .first() + .is_some_and(|event| event.seq >= before) + || (older.events.is_empty() && older.has_more) + { + bail!("History page did not advance"); + } + batches.push(page.events); + // Forward catch-up starts at the snapshot with which this read + // began. Later appends must still be delivered by catch_up. + let cursor = page.cursor; + page = older; + page.cursor = cursor; + } + } + + async fn join_turn_snapshot(&self, mut page: StreamPage) -> Result { + let snapshot = page + .turn_history + .clone() + .context("Turn history acknowledgement missing")?; + if snapshot.version != 1 || snapshot.offset != 0 { + bail!("Invalid Turn history acknowledgement"); + } + let mut events = Vec::new(); + loop { + let part = page + .turn_history + .as_ref() + .context("Turn history continuation is unsupported")?; + if part.version != snapshot.version + || part.snapshot_id != snapshot.snapshot_id + || part.turn_id != snapshot.turn_id + || part.record_count != snapshot.record_count + || part.before_turn != snapshot.before_turn + || part.offset != events.len() + || page.has_more != snapshot.before_turn.is_some() + { + bail!("Turn history snapshot changed during the read"); + } + let next = part.next_offset; + events.append(&mut page.events); + if events.len() > snapshot.record_count { + bail!("Turn history exceeded its record count"); + } + let Some(offset) = next else { + break; + }; + if offset != events.len() || offset <= part.offset || offset >= snapshot.record_count { + bail!("Turn history continuation did not advance"); + } + let older = self + .read(StreamReadRequest { + stream_id: self.session_id.clone(), + epoch: Some(page.epoch), + subscribe: true, + turn_history: Some(TurnHistoryRequest { + version: 1, + snapshot_id: Some(snapshot.snapshot_id.clone()), + offset, + before_turn: None, + }), + ..Default::default() + }) + .await?; + if older.epoch != page.epoch || older.cursor != page.cursor { + bail!( + "Session history restarted while reading a Turn; reopen the session to retry" + ); + } + page = older; + } + if events.len() != snapshot.record_count { + bail!("Incomplete Turn history snapshot"); + } + let mut ids = HashSet::new(); + for event in &events { + if event.event != "session-record" + || event.payload["sessionId"].as_str() != Some(self.session_id.as_str()) + || event + .payload + .pointer("/turn/turnId") + .and_then(|id| id.as_str()) + != snapshot.turn_id.as_deref() + || event.payload["revision"].as_u64() != Some(page.cursor) + || !event.payload["id"] + .as_str() + .is_some_and(|id| ids.insert(id)) + { + bail!("Invalid Turn history snapshot record"); + } + } + if let Some(turn) = &snapshot.turn_id { + if !ids.contains(format!("turn/{turn}").as_str()) { + bail!("Turn history snapshot root missing"); + } + } else if !events.is_empty() { + bail!("Turn history snapshot identity missing"); + } + page.events = events; + page.turn_history = Some(super::host_stream::TurnHistoryPage { + offset: 0, + next_offset: None, + ..snapshot + }); + Ok(page) + } + + fn emit_page(&self, page: &StreamPage, history: bool) -> Result<()> { for event in &page.events { + let mut payload = event.payload.clone(); + if history && event.event == "session-record" { + // Controller-local annotation: the frontend stages only replay + // records, so an older read cannot hold up live output. + payload["historyReplay"] = true.into(); + } (self.emit)(SessionEvent { session_id: self.session_id.clone(), event: event.event.clone(), - payload: event.payload.clone(), + payload, })?; } Ok(()) @@ -145,17 +356,19 @@ impl Reader { (self.emit)(SessionEvent { session_id: self.session_id.clone(), event: "relay://session-ready".into(), - payload: serde_json::json!({"sessionId":self.session_id,"hasMore":self.has_more,"oldestSeq":self.oldest,"cursor":self.cursor}), + payload: serde_json::json!({"sessionId":self.session_id,"hasMore":self.has_more,"oldestSeq":self.oldest,"cursor":self.cursor,"historyBatches":true}), }) } /// Latest page first, like opening a chat at its bottom. async fn resync(&mut self) -> Result<()> { + let started = std::time::Instant::now(); let page = self - .read(StreamReadRequest { + .read_history(StreamReadRequest { stream_id: self.session_id.clone(), subscribe: true, limit: Some(FIRST_PAGE_EVENTS), + turn_history: Some(TurnHistoryRequest::latest()), ..Default::default() }) .await?; @@ -167,7 +380,14 @@ impl Reader { .map(|event| event.seq) .unwrap_or(page.cursor + 1); self.has_more = page.has_more; - self.emit_page(&page)?; + self.turn_history = page.turn_history.is_some(); + self.before_turn = page + .turn_history + .as_ref() + .and_then(|history| history.before_turn); + log::debug!("Session first history ready: session_id={} turn_snapshot={} records={} has_more={} elapsed_ms={}", + self.session_id, self.turn_history, page.events.len(), page.has_more, started.elapsed().as_millis()); + self.emit_page(&page, true)?; self.emit_ready() } @@ -186,7 +406,7 @@ impl Reader { if page.epoch != self.epoch { return Ok(false); } - self.emit_page(&page)?; + self.emit_page(&page, false)?; if let Some(last) = page.events.last() { self.cursor = self.cursor.max(last.seq); } @@ -209,31 +429,49 @@ impl Reader { self.resync().await } - async fn load_older(&mut self) -> Result { - if !self.has_more { - return Ok(true); - } - let page = self - .read(StreamReadRequest { - stream_id: self.session_id.clone(), - before: Some(self.oldest), - epoch: Some(self.epoch), - subscribe: true, - ..Default::default() - }) - .await?; + async fn read_older_page(&self) -> Result { + self.read_history(StreamReadRequest { + stream_id: self.session_id.clone(), + before: (!self.turn_history).then_some(self.oldest), + turn_history: self.turn_history.then(|| TurnHistoryRequest { + before_turn: self.before_turn, + ..TurnHistoryRequest::latest() + }), + epoch: Some(self.epoch), + subscribe: true, + ..Default::default() + }) + .await + } + + fn apply_older_page(&mut self, page: StreamPage) -> Result { if page.epoch != self.epoch { return Ok(false); } - self.emit_page(&page)?; + if self.turn_history && page.turn_history.is_none() { + bail!("The host stopped supporting Turn history; reopen the session to retry"); + } + self.emit_page(&page, true)?; if let Some(first) = page.events.first() { self.oldest = first.seq; } self.has_more = page.has_more; + self.before_turn = page + .turn_history + .as_ref() + .and_then(|history| history.before_turn); self.emit_ready()?; Ok(true) } + async fn load_older(&mut self) -> Result { + if !self.has_more { + return Ok(true); + } + let page = self.read_older_page().await?; + self.apply_older_page(page) + } + /// Announce a restarted stream. A full replay from the latest page always /// follows, so `resync` tells the controller to rebuild its records from /// that replay: the new epoch carries no tombstones for what it dropped. @@ -289,6 +527,8 @@ impl HostStreamSubscriber { cursor: 0, oldest: 1, has_more: false, + turn_history: false, + before_turn: None, }; // The first page is awaited so an unsupported or offline host fails the // open call instead of retrying silently in the background. @@ -323,7 +563,38 @@ impl HostStreamSubscriber { let result = match wake { Wake::Refresh => reader.refresh().await, Wake::Older(reply) => { - let result = match reader.load_older().await { + // A large historical Turn may span several RPCs. Its + // immutable snapshot lets live catch-up keep running; + // no user message or approval waits behind those bytes. + let read = if reader.turn_history && reader.has_more { + let history_reader = reader.clone(); + let page = history_reader.read_older_page(); + tokio::pin!(page); + let result = loop { + tokio::select! { + result = &mut page => break result, + hint = hints.recv() => { + let refresh = match hint { + Ok(Some(hint)) => reader.hint_is_new(&hint, &target), + Ok(None) | Err(broadcast::error::RecvError::Lagged(_)) => true, + Err(broadcast::error::RecvError::Closed) => return, + }; + if refresh { + if let Err(failure) = reader.refresh().await { + error(describe_stream_error(&failure)); + } + if reader.epoch != history_reader.epoch { + break Err(anyhow!("Session history restarted during the older read")); + } + } + } + } + }; + result.and_then(|page| reader.apply_older_page(page)) + } else { + reader.load_older().await + }; + let result = match read { Ok(true) => Ok(()), Ok(false) => { let _ = reader.gap("host stream restarted"); @@ -502,7 +773,331 @@ mod tests { } fn record(session: &str, turn: &str, status: &str) -> serde_json::Value { - serde_json::json!({"sessionId":session,"id":format!("turn/{turn}"),"turn":{"turnId":turn,"sessionId":session,"status":status}}) + serde_json::json!({"sessionId":session,"id":format!("turn/{turn}"),"turnRecordIds":[format!("turn/{turn}")],"turn":{"turnId":turn,"sessionId":session,"status":status}}) + } + + struct ScriptedHistory { + pages: Mutex>, + reads: Mutex>, + } + #[async_trait::async_trait] + impl StreamTransport for ScriptedHistory { + async fn read_stream(&self, request: StreamReadRequest) -> Result { + self.reads.lock().unwrap().push(request); + self.pages + .lock() + .unwrap() + .pop_front() + .context("Unexpected history read") + } + async fn unsubscribe_stream(&self, _: &str) -> Result<()> { + Ok(()) + } + } + fn history_page(seq: u64, records: Vec, has_more: bool) -> StreamPage { + use super::super::host_stream::StreamEvent; + StreamPage { + stream_id: "s".into(), + epoch: 1, + events: records + .into_iter() + .enumerate() + .map(|(index, mut payload)| { + payload["revision"] = (seq + index as u64).into(); + StreamEvent { + seq: seq + index as u64, + event: "session-record".into(), + payload, + } + }) + .collect(), + has_more, + cursor: 100, + oldest_seq: 1, + truncated: false, + turn_history: None, + } + } + fn scripted_reader( + pages: Vec, + ) -> (Reader, Arc, Arc>>) { + let transport = Arc::new(ScriptedHistory { + pages: Mutex::new(pages.into()), + reads: Mutex::new(Vec::new()), + }); + let events = Arc::new(Mutex::new(Vec::new())); + let output = events.clone(); + ( + Reader { + transport: transport.clone(), + session_id: "s".into(), + emit: Arc::new(move |event| { + output.lock().unwrap().push(event); + Ok(()) + }), + epoch: 0, + cursor: 0, + oldest: 1, + has_more: false, + turn_history: false, + before_turn: None, + }, + transport, + events, + ) + } + fn item(id: &str) -> serde_json::Value { + serde_json::json!({"sessionId":"s","id":format!("item/{id}"),"turn":{"turnId":"one","sessionId":"s","status":"completed"},"round":{"id":"r","turnId":"one"},"item":{"type":"text","data":{"id":id}}}) + } + + #[tokio::test] + async fn history_waits_for_all_members_even_when_the_terminal_root_arrived_first() { + let mut root = record("s", "one", "completed"); + root["turnRecordIds"] = serde_json::json!(["turn/one", "item/a", "item/b", "item/c"]); + let (mut reader, transport, events) = scripted_reader(vec![ + history_page(8, vec![root, item("c")], true), + history_page(5, vec![item("b")], true), + history_page(2, vec![item("a")], true), + ]); + reader.resync().await.unwrap(); + let reads = transport.reads.lock().unwrap(); + assert_eq!( + reads.iter().map(|read| read.before).collect::>(), + vec![None, Some(8), Some(5)] + ); + let events = events.lock().unwrap(); + assert_eq!(events.len(), 5); + assert_eq!(events[0].payload["id"], "item/a"); + assert_eq!(events[3].payload["id"], "item/c"); + assert_eq!(events[4].event, "relay://session-ready"); + assert_eq!(events[4].payload["hasMore"], true); + assert_eq!(events[4].payload["oldestSeq"], 2); + assert_eq!(events[4].payload["cursor"], 100); + } + + #[tokio::test] + async fn legacy_pages_without_membership_remain_readable_and_publish_once_complete() { + let mut root = record("s", "one", "completed"); + root.as_object_mut().unwrap().remove("turnRecordIds"); + // Round trip the old wire shape, without inventing a new capability. + let first: StreamPage = serde_json::from_value( + serde_json::to_value(history_page(8, vec![root], true)).unwrap(), + ) + .unwrap(); + let (mut reader, transport, events) = scripted_reader(vec![ + first, + history_page(5, vec![item("b")], true), + history_page(1, vec![item("a")], false), + ]); + reader.resync().await.unwrap(); + assert_eq!(transport.reads.lock().unwrap().len(), 3); + let events = events.lock().unwrap(); + assert_eq!(events.len(), 4); + assert_eq!(events.last().unwrap().payload["hasMore"], false); + assert_eq!(events[0].payload["item"]["data"]["id"], "a"); + } + + #[tokio::test] + async fn missing_members_and_failed_continuations_never_emit_partial_turns() { + for has_more in [false, true] { + let mut root = record("s", "one", "completed"); + root["turnRecordIds"] = serde_json::json!(["turn/one", "item/missing"]); + let (mut reader, _, events) = + scripted_reader(vec![history_page(8, vec![root], has_more)]); + assert!(reader.resync().await.is_err()); + assert!(events.lock().unwrap().is_empty()); + } + } + + #[tokio::test] + async fn continuation_epoch_changes_and_stalled_cursors_never_publish_fragments() { + for kind in ["epoch", "empty", "same-cursor"] { + let mut root = record("s", "one", "completed"); + root["turnRecordIds"] = serde_json::json!(["turn/one", "item/a"]); + let mut older = history_page( + if kind == "same-cursor" { 8 } else { 2 }, + vec![item("a")], + true, + ); + if kind == "epoch" { + older.epoch = 2; + } + if kind == "empty" { + older.events.clear(); + } + let (mut reader, _, events) = + scripted_reader(vec![history_page(8, vec![root], true), older]); + assert!(reader.resync().await.is_err(), "{kind}"); + assert!(events.lock().unwrap().is_empty(), "{kind}"); + } + } + + #[tokio::test] + async fn a_control_only_page_does_not_complete_an_empty_transcript() { + let mut controls = history_page(8, vec![serde_json::json!({"sessionId":"s"})], true); + controls.events[0].event = "session-interaction-changed".into(); + let (mut reader, transport, events) = scripted_reader(vec![ + controls, + history_page(2, vec![record("s", "one", "completed")], true), + ]); + reader.resync().await.unwrap(); + assert_eq!(transport.reads.lock().unwrap().len(), 2); + let events = events.lock().unwrap(); + assert_eq!(events[0].payload["id"], "turn/one"); + assert_eq!(events[2].event, "relay://session-ready"); + } + + #[tokio::test] + async fn turn_snapshot_chunks_publish_once_and_reject_a_changed_snapshot_without_fragments() { + for invalid in [false, true] { + let mut first = history_page(8, vec![record("s", "one", "completed"), item("a")], true); + let mut next = history_page(5, vec![item("b")], true); + for (page, offset, next_offset) in [(&mut first, 0, Some(2)), (&mut next, 2, None)] { + for event in &mut page.events { + event.seq = 100; + event.payload["revision"] = 100.into(); + } + page.turn_history = Some(super::super::host_stream::TurnHistoryPage { + version: 1, + snapshot_id: "snapshot".into(), + turn_id: Some("one".into()), + record_count: 3, + offset, + next_offset, + before_turn: Some(1), + }); + } + if invalid { + next.cursor += 1; + } + let (mut reader, transport, events) = scripted_reader(vec![first, next]); + let result = reader.resync().await; + if invalid { + assert!(result.is_err()); + assert!(events.lock().unwrap().is_empty()); + } else { + result.unwrap(); + assert_eq!(transport.reads.lock().unwrap().len(), 2); + assert!(reader.turn_history); + assert_eq!(reader.before_turn, Some(1)); + let emitted = events.lock().unwrap(); + assert_eq!(emitted.len(), 4); + assert!(emitted[..3] + .iter() + .all(|event| event.payload["historyReplay"] == true)); + assert_eq!(emitted[3].event, "relay://session-ready"); + } + } + } + + #[tokio::test] + async fn older_snapshot_io_does_not_block_live_catch_up_and_never_publishes_half_a_turn() { + use super::super::host_stream::HistoryBatch; + use std::sync::atomic::{AtomicUsize, Ordering}; + struct Transport { + hub: Arc, + blocked: tokio::sync::Notify, + release: tokio::sync::Notify, + reads: AtomicUsize, + } + #[async_trait::async_trait] + impl StreamTransport for Transport { + async fn read_stream(&self, request: StreamReadRequest) -> Result { + if request + .turn_history + .as_ref() + .is_some_and(|history| history.offset > 0) + { + self.blocked.notify_one(); + self.release.notified().await; + } + self.hub + .read_history("controller", &request, |before| { + self.reads.fetch_add(1, Ordering::SeqCst); + async move { + if before.is_none() { + return Ok(HistoryBatch { + records: vec![record("s", "latest", "inprogress")], + before: Some(1), + }); + } + assert_eq!(before, Some(1)); + let mut records = vec![record("s", "one", "completed")]; + records.extend((0..201).map(|index| item(&index.to_string()))); + Ok(HistoryBatch { + records, + before: None, + }) + } + }) + .await + } + async fn unsubscribe_stream(&self, session: &str) -> Result<()> { + self.hub.unsubscribe("controller", session); + Ok(()) + } + } + let (hints, _) = broadcast::channel(16); + let hub = HostStreamHub::start(Arc::new(HintFanout(hints.clone(), "desktop".into()))); + let transport = Arc::new(Transport { + hub: hub.clone(), + blocked: Default::default(), + release: Default::default(), + reads: AtomicUsize::new(0), + }); + let events = Arc::new(Mutex::new(Vec::::new())); + let live = Arc::new(tokio::sync::Notify::new()); + let output = events.clone(); + let live_signal = live.clone(); + let errors = Arc::new(Mutex::new(Vec::new())); + let failures = errors.clone(); + let subscriber = HostStreamSubscriber::start_with_transport( + transport.clone(), + hints.subscribe(), + "desktop".into(), + "s".into(), + Arc::new(move |event| { + if event.payload["id"] == "turn/latest" && event.payload["historyReplay"].is_null() + { + live_signal.notify_one(); + } + output.lock().unwrap().push(event); + Ok(()) + }), + Arc::new(move |error| failures.lock().unwrap().push(error)), + ) + .await + .unwrap(); + assert_eq!(transport.reads.load(Ordering::SeqCst), 1); + assert_eq!(events.lock().unwrap().len(), 2); // Only latest + ready. + let older = tokio::spawn(subscriber.load_older()); + tokio::time::timeout(Duration::from_secs(2), transport.blocked.notified()) + .await + .unwrap(); + assert_eq!(events.lock().unwrap().len(), 2); // No older fragment escaped. + hub.synchronize_records("s".into(), false, || async { + Ok(vec![record("s", "latest", "completed")]) + }) + .await + .unwrap(); + tokio::time::timeout(Duration::from_secs(2), live.notified()) + .await + .unwrap(); + assert!(!older.is_finished()); + assert_eq!(events.lock().unwrap().len(), 3); // Live output arrived during blocked history IO. + transport.release.notify_one(); + older.await.unwrap().unwrap(); + let events = events.lock().unwrap(); + assert_eq!(events.last().unwrap().event, "relay://session-ready"); + assert_eq!( + events + .iter() + .filter(|event| event.payload["turn"]["turnId"] == "one") + .count(), + 202 + ); + assert_eq!(transport.reads.load(Ordering::SeqCst), 2); // One source read per Turn, not per packet. + assert!(errors.lock().unwrap().is_empty()); } #[tokio::test] diff --git a/src/crates/services/services-integrations/src/remote_connect/session_records.rs b/src/crates/services/services-integrations/src/remote_connect/session_records.rs index a9aa177067..6d9112be03 100644 --- a/src/crates/services/services-integrations/src/remote_connect/session_records.rs +++ b/src/crates/services/services-integrations/src/remote_connect/session_records.rs @@ -64,6 +64,7 @@ pub fn records_from_turns( ) -> Result> { let mut records = Vec::new(); for source in turns { + let turn_start = records.len(); let mut turn = serde_json::to_value(source)?; turn.as_object_mut() .expect("turn serializes as object") @@ -95,6 +96,15 @@ pub fn records_from_turns( } } } + // A transport page is byte/event bounded and can split even one Turn. + // Put membership on its root only, so a controller can prove it has the + // whole snapshot without duplicating this list on every item. This is + // an optional wire field; persisted Turns and older readers are unchanged. + let record_ids: Vec = records[turn_start..] + .iter() + .map(|record| record["id"].clone()) + .collect(); + records[turn_start]["turnRecordIds"] = Value::Array(record_ids); } Ok(records) } diff --git a/src/crates/services/services-integrations/tests/remote_connect_contracts.rs b/src/crates/services/services-integrations/tests/remote_connect_contracts.rs index 52ba3d88f0..bd02a6201c 100644 --- a/src/crates/services/services-integrations/tests/remote_connect_contracts.rs +++ b/src/crates/services/services-integrations/tests/remote_connect_contracts.rs @@ -53,7 +53,7 @@ use openbitfun_services_integrations::remote_connect::{ REMOTE_CAPABILITY_DEVICE_MODEL_DEFAULTS_V1, REMOTE_CAPABILITY_DIALOG_STEER_V1, REMOTE_CAPABILITY_HARNESS_PROFILES_V1, REMOTE_CAPABILITY_HOST_STREAM_V1, REMOTE_CAPABILITY_PLAN_BUILD_V1, REMOTE_CAPABILITY_SESSION_ROLLBACK_V1, - REMOTE_FILE_MAX_CHUNK_BYTES, REMOTE_FILE_MAX_READ_BYTES, + REMOTE_CAPABILITY_TURN_HISTORY_V1, REMOTE_FILE_MAX_CHUNK_BYTES, REMOTE_FILE_MAX_READ_BYTES, }; use std::path::PathBuf; use std::sync::{Arc, Mutex}; @@ -476,6 +476,14 @@ fn relay_records_carry_attachment_pixels_on_the_turn_record_alone() { .iter() .find(|record| record["id"] == "turn/turn-1") .expect("turn record is published"); + assert_eq!( + turn_record["turnRecordIds"], + serde_json::json!(["turn/turn-1", "round/round-1", "item/item-1"]) + ); + assert!(records + .iter() + .skip(1) + .all(|record| record.get("turnRecordIds").is_none())); assert_eq!( images_of(turn_record), vec![ @@ -2363,6 +2371,7 @@ fn remote_connect_workspace_response_helpers_own_wire_shape() { "user_question_interaction_v1", "background_result_delivery_v1", REMOTE_CAPABILITY_HOST_STREAM_V1, + REMOTE_CAPABILITY_TURN_HISTORY_V1, REMOTE_CAPABILITY_DEVICE_MODEL_DEFAULTS_V1 ]) ); @@ -2613,6 +2622,7 @@ fn remote_connect_session_response_helpers_own_pagination_and_timestamps() { "user_question_interaction_v1", "background_result_delivery_v1", REMOTE_CAPABILITY_HOST_STREAM_V1, + REMOTE_CAPABILITY_TURN_HISTORY_V1, REMOTE_CAPABILITY_DEVICE_MODEL_DEFAULTS_V1 ]) ); diff --git a/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPet.scss b/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPet.scss index 3618010a71..717143b9e0 100644 --- a/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPet.scss +++ b/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPet.scss @@ -364,30 +364,18 @@ width: 180px; max-width: 100%; box-sizing: border-box; - /* Same language as the device overview: the opaque themed surface lit - from the corner nearest the title by the task state, a faint ring in - that light, and the tail corner pointing at the pet. */ + /* Both themes use an 80% opaque neutral surface. Task color belongs to the + status glyph; a neutral inset edge keeps the bubble clear on any desktop. */ --_bubble-light: var(--openbitfun-color-accent-default); - --_bubble-glow: radial-gradient( - 130% 150% at 0% 0%, - color-mix(in srgb, var(--_bubble-light) 20%, transparent), - transparent 68% - ); - /* No border: the bubble is defined by its surface, the state light, the - theme's top highlight and a soft tinted drop shadow cast down and to - the right at 45 degrees. Its reach stays inside the column: none to the - left, and the column's inline-end room covers the right. */ --_bubble-edge: - var(--openbitfun-shadow-inner-highlight), - 10px 10px 24px -10px color-mix(in srgb, var(--_bubble-light) 40%, transparent); + inset 0 0 0 var(--openbitfun-border-width-default) var(--openbitfun-color-border-subtle), + var(--openbitfun-shadow-raised); padding: 9px 12px; border: none; border-radius: 14px 14px 4px 14px; - background-color: var(--openbitfun-color-surface-raised); - background-image: var(--_bubble-glow); + background-color: color-mix(in srgb, var(--openbitfun-color-surface-raised) 80%, transparent); color: var(--openbitfun-color-content-primary); box-shadow: var(--_bubble-edge); - backdrop-filter: blur(10px); cursor: pointer; position: relative; z-index: 0; @@ -518,15 +506,9 @@ } } - /* Each state sets the light and lays its status tint over the opaque themed - surface, fading away from the lit corner so the bubble stays calm. */ + /* All task states share the translucent surface; glyphs carry the status color. */ &__bubble--attention { --_bubble-light: var(--openbitfun-color-status-warning-content); - background-image: linear-gradient( - 135deg, - var(--openbitfun-color-status-warning-surface), - transparent 72% - ), var(--_bubble-glow); box-shadow: var(--_bubble-edge), inset 0 0 0 1px color-mix(in srgb, var(--openbitfun-color-status-warning-content) 40%, transparent); @@ -535,30 +517,15 @@ &__bubble--waiting { --_bubble-light: var(--openbitfun-color-status-warning-content); - background-image: linear-gradient( - 135deg, - var(--openbitfun-color-status-warning-surface), - transparent 72% - ), var(--_bubble-glow); } &__bubble--completed { --_bubble-light: var(--openbitfun-color-status-success-content); - background-image: linear-gradient( - 135deg, - var(--openbitfun-color-status-success-surface), - transparent 72% - ), var(--_bubble-glow); } &__bubble--error, &__bubble--interrupted { --_bubble-light: var(--openbitfun-color-status-danger-content); - background-image: linear-gradient( - 135deg, - var(--openbitfun-color-status-danger-surface), - transparent 72% - ), var(--_bubble-glow); } .openbitfun-agent-companion-pet { diff --git a/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPetStyles.test.ts b/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPetStyles.test.ts index 496d56400d..fed96d99fc 100644 --- a/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPetStyles.test.ts +++ b/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPetStyles.test.ts @@ -42,7 +42,7 @@ describe('AgentCompanionDesktopPet styles', () => { const output = extractBlock(stylesheet, '&__bubble-output'); const composerInput = extractBlock(stylesheet, '&__bubble-composer-input'); - expect(bubble).toContain('background-color: var(--openbitfun-color-surface-raised);'); + expect(bubble).toContain('background-color: color-mix(in srgb, var(--openbitfun-color-surface-raised) 80%, transparent);'); expect(bubble).toContain('color: var(--openbitfun-color-content-primary);'); // Status words are drawn as a glyph; the text stays for assistive tech only. expect(status).toContain('clip-path: inset(50%);'); @@ -62,19 +62,26 @@ describe('AgentCompanionDesktopPet styles', () => { ); }); - it('layers translucent task-state colors over the opaque themed bubble surface', () => { + it('keeps the themed bubble background 20% transparent without fading its content', () => { const stylesheet = readStylesheet(); + const bubble = extractBlock(stylesheet, '&__bubble'); + + expect(bubble).toContain('background-color: color-mix(in srgb, var(--openbitfun-color-surface-raised) 80%, transparent);'); + expect(bubble).not.toMatch(/^\s*opacity\s*:/m); + expect(bubble).not.toMatch(/gradient\(|background-image:|backdrop-filter:/); + expect(bubble).toContain('var(--openbitfun-color-border-subtle)'); + expect(bubble).toContain('var(--openbitfun-shadow-raised)'); + expect(stylesheet).not.toContain('--_bubble-glow'); - for (const [selector, surfaceToken] of [ - ['&__bubble--attention', '--openbitfun-color-status-warning-surface'], - ['&__bubble--waiting', '--openbitfun-color-status-warning-surface'], - ['&__bubble--completed', '--openbitfun-color-status-success-surface'], - ['&__bubble--error,\n &__bubble--interrupted', '--openbitfun-color-status-danger-surface'], + for (const [selector, contentToken] of [ + ['&__bubble--attention', '--openbitfun-color-status-warning-content'], + ['&__bubble--waiting', '--openbitfun-color-status-warning-content'], + ['&__bubble--completed', '--openbitfun-color-status-success-content'], + ['&__bubble--error,\n &__bubble--interrupted', '--openbitfun-color-status-danger-content'], ] as const) { const state = extractBlock(stylesheet, selector); - expect(state).toContain('background-image: linear-gradient('); - expect(state).toContain(`var(${surfaceToken})`); - expect(state).not.toContain(`background: var(${surfaceToken});`); + expect(state).toContain(`--_bubble-light: var(${contentToken});`); + expect(state).not.toMatch(/background(?:-color|-image)?:|gradient\(/); } }); diff --git a/src/web-ui/src/app/components/NavPanel/NavPanel.scss b/src/web-ui/src/app/components/NavPanel/NavPanel.scss index 03471b0891..1187c38a19 100644 --- a/src/web-ui/src/app/components/NavPanel/NavPanel.scss +++ b/src/web-ui/src/app/components/NavPanel/NavPanel.scss @@ -1561,8 +1561,7 @@ $_section-header-height: 22px; // Device overview — one compact model, local and connected states // ────────────────────────────────────────────── -// The light that fills the card is the displayed device's state; registering it -// lets the whole surface cross-fade between devices instead of snapping. +// State color is limited to the device controls; the card stays neutral. @property --_device-overview-light { syntax: ''; inherits: true; @@ -1577,10 +1576,8 @@ $_section-header-height: 22px; --_device-overview-inline-size: min(312px, calc(100vw - 16px)); --_device-overview-stage-size: 120px; --_device-overview-inset: var(--openbitfun-space-4); - // Silver until a device is under control: this device and a device not yet - // connected share one neutral light; only a live connection turns green. + // Local and disconnected devices use neutral controls; a live connection is green. --_device-overview-light: var(--openbitfun-color-content-secondary); - --_device-overview-light-strength: 16%; position: fixed; z-index: var(--openbitfun-layer-popover); width: var(--_device-overview-inline-size); @@ -1589,25 +1586,10 @@ $_section-header-height: 22px; display: flex; flex-direction: column; box-sizing: border-box; - background: - radial-gradient( - 120% 78% at 50% 0%, - color-mix(in srgb, var(--_device-overview-light) var(--_device-overview-light-strength), transparent), - transparent 74% - ), - radial-gradient( - 90% 55% at 100% 100%, - color-mix(in srgb, var(--_device-overview-light) calc(var(--_device-overview-light-strength) / 3), transparent), - transparent 70% - ), - var(--openbitfun-color-surface-raised); + background: var(--openbitfun-color-surface-raised); transition: --_device-overview-light var(--openbitfun-motion-duration-slow) var(--openbitfun-motion-easing-standard); animation: openbitfun-nav-popover-in 150ms cubic-bezier(0.23, 1, 0.32, 1) both; - :where([data-color-scheme='dark']) & { - --_device-overview-light-strength: 26%; - } - &[data-control-state='active'] { --_device-overview-light: var(--openbitfun-color-status-success-content); } @@ -1937,7 +1919,7 @@ $_section-header-height: 22px; } } -// A soft top-lit fill reads as a material rather than a flat cut-out. +// A single neutral fill keeps the device silhouette legible on the solid card. .openbitfun-device-overview__artwork-glyph { position: relative; justify-self: center; @@ -1945,11 +1927,7 @@ $_section-header-height: 22px; height: 56%; margin-block-end: var(--openbitfun-space-2); aspect-ratio: 140 / 78; - background: linear-gradient( - to bottom, - color-mix(in srgb, var(--openbitfun-color-content-primary) 72%, transparent), - color-mix(in srgb, var(--openbitfun-color-content-primary) 42%, transparent) - ); + background: var(--openbitfun-color-content-secondary); mask: url('./assets/device.svg') center / contain no-repeat; } diff --git a/src/web-ui/src/app/components/NavPanel/components/DeviceStatusControl.test.tsx b/src/web-ui/src/app/components/NavPanel/components/DeviceStatusControl.test.tsx index e1cde0d5aa..c3c700db41 100644 --- a/src/web-ui/src/app/components/NavPanel/components/DeviceStatusControl.test.tsx +++ b/src/web-ui/src/app/components/NavPanel/components/DeviceStatusControl.test.tsx @@ -208,6 +208,44 @@ afterEach(() => { }); describe('device status card', () => { + it.each(['signed-out', 'loading', 'authorizing'])( + 'opens device management directly when account identity is %s', status => { + state.identity = { status, me: null }; + render(false); + + act(() => element('nav-footer-device-status').click()); + + expect(onManageDevices).toHaveBeenCalledOnce(); + expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false); + expect(element('nav-footer-device-status').getAttribute('aria-expanded')).toBe('false'); + expect(document.querySelector('[data-testid="nav-device-status-popover"]')).toBeNull(); + expect(state.refresh).not.toHaveBeenCalled(); + expect(state.accountListDevices).not.toHaveBeenCalled(); + }, + ); + + it.each([false, true])('toggles the overview when signed in (peer active: %s)', async peerActive => { + state.identity = { status: 'signed-in', me: { user: { accountId: 'acct' } } }; + state.overview = overview({ peer: peerActive ? { deviceId: 'peer-1', deviceName: 'Remote Mac' } : null }); + state.getDeviceInfo.mockResolvedValue({ device_id: 'local', device_name: 'Workstation' }); + state.accountListDevices.mockResolvedValue([]); + function Footer() { + const [open, setOpen] = React.useState(false); + return ; + } + act(() => root.render(