From b3016850f4a983b121b885fa031413457a9029d3 Mon Sep 17 00:00:00 2001 From: Joep Meindertsma Date: Thu, 1 Oct 2026 06:06:52 +0200 Subject: [PATCH 1/3] Live updates and full lists for things shared out of other drives A guest in a chat shared from someone else's drive saw only their own messages and the ones present when they joined, got none of the host's later messages live, and so got no notifications for them. - Server: a commit is also sent to WebSocket subscribers of the resource's parent. The guest can't subscribe to the host's drive, and a new message is a new subject, so neither the resource nor the drive subscription reached them. Read rights are checked per subscriber against the resource at send time (the subscription was admitted on the parent, and access can be taken back since), under ctx.wait so it stays in order with later commits. A connection already reached through the resource itself or its drive is skipped, so nothing arrives twice. - Store.subscribeLive holds a per-resource SUB, counted and re-sent on reconnect. MessageNotifier holds one for everything in Shared with me while the app runs. - Collection: a non-empty local answer was always trusted, but only a synced drive has its whole membership locally. For a drive this client hasn't synced the server is asked once per page per session; its members are written locally as they load and live updates keep them current. Members only the local DB knows (writes not yet acknowledged) are kept. Synced drives make no extra request. ws_parent_fanout covers delivery, a sibling the guest can't read, one frame for a connection on both child and parent, and no delivery after read is revoked; the last two fail on the version without the send-time check. --- CHANGELOG.md | 8 + browser/CHANGELOG.md | 13 + .../Notifications/MessageNotifier.tsx | 14 + .../lib/src/collection-partial-local.test.ts | 85 +++++ browser/lib/src/collection-sort-order.test.ts | 29 +- browser/lib/src/collection.ts | 57 ++++ browser/lib/src/store.subscribe-live.test.ts | 44 +++ browser/lib/src/store.ts | 33 ++ browser/lib/src/websockets.ts | 23 ++ server/src/commit_monitor.rs | 72 ++++- server/tests/it/main.rs | 1 + server/tests/it/ws_parent_fanout.rs | 301 ++++++++++++++++++ 12 files changed, 675 insertions(+), 5 deletions(-) create mode 100644 browser/lib/src/collection-partial-local.test.ts create mode 100644 browser/lib/src/store.subscribe-live.test.ts create mode 100644 server/tests/it/ws_parent_fanout.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index f149f47aa9..841a3a29ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ See [STATUS.md](server/STATUS.md) to learn more about which features will remain ## UNRELEASED +- A commit is also sent to WebSocket subscribers of the resource's parent. A + resource shared out of a drive the recipient can't read (a chatroom) can only + be subscribed to on its own, and a new child is a new subject, so its new + messages reached neither that subscription nor a drive subscription the + recipient could hold. Read rights are checked per subscriber against the + resource when it is sent, and a connection already reached through the + resource or its drive doesn't get it twice. + - New default ontology `notifications` (`lib/defaults/notifications.json`): the `Inbox` and `Notification` classes, and an `inbox` property the private drive points to its Inbox with. diff --git a/browser/CHANGELOG.md b/browser/CHANGELOG.md index 576a999d26..49c33fc85b 100644 --- a/browser/CHANGELOG.md +++ b/browser/CHANGELOG.md @@ -4,6 +4,19 @@ This changelog covers all five packages, as they are (for now) updated as a whol ## UNRELEASED +- Someone given a chat, or anything else, out of a drive they can't open sees + all of it. A list answered from the local database was trusted whenever it + was non-empty, but only a drive synced to this device has its whole list + there: the guest's own messages and the ones present when they joined were + shown as the entire chat, and a reload asked the same database again. For a + drive this device hasn't synced the server is now asked once per list per + session, and anything only the local database knows (a write not yet + confirmed) is kept. +- Things shared with you out of someone else's drive update live and notify + you. The app only listened to the drive you had open, so a guest in a shared + chat never received new messages from the host, and got no notifications for + them. Everything in "Shared with me" is now subscribed for as long as the app + runs (`Store.subscribeLive`). - An app asking to use one of your accounts (Google Calendar, Clockify and so on) now asks in a dialog instead of a bar above the app, in plainer words: which app, which account, and that you approve it on the next page, on the diff --git a/browser/data-browser/src/components/Notifications/MessageNotifier.tsx b/browser/data-browser/src/components/Notifications/MessageNotifier.tsx index bb48328d70..682a3dd558 100644 --- a/browser/data-browser/src/components/Notifications/MessageNotifier.tsx +++ b/browser/data-browser/src/components/Notifications/MessageNotifier.tsx @@ -27,6 +27,7 @@ import { recordNotification, } from '../../helpers/notifications/inbox'; import { usePrivateDrive } from '../../hooks/usePrivateDrive'; +import { usePrivateDriveList } from '../../hooks/usePrivateDriveList'; const TEXT_MAX = 140; @@ -95,6 +96,7 @@ export function MessageNotifier(): null { const { activePanel, setPanelOpen } = useRightPanel(); const navigate = useNavigateWithTransition(); const { privateDrive } = usePrivateDrive(); + const [sharedWithMe] = usePrivateDriveList(core.properties.sharedWithMe); const handled = useRef(new Set()); // Inbox writes still in flight, per target, so reading waits for them. @@ -229,6 +231,18 @@ export function MessageNotifier(): null { showOsNotification({ title, body, tag: subject, onClick: () => open(n) }); }); + // Things shared with you out of drives you can't open are only delivered to + // a subscription on the thing itself; the open drive's subscription never + // covers them. Hold one for as long as the app runs, not only while the + // sidebar happens to show the item, or a shared chat stays silent. + useEffect(() => { + const unsubscribers = sharedWithMe.map(subject => + store.subscribeLive(subject), + ); + + return () => unsubscribers.forEach(unsubscribe => unsubscribe()); + }, [store, sharedWithMe]); + useEffect( () => store.on(StoreEvents.ResourceUpdated, resource => { diff --git a/browser/lib/src/collection-partial-local.test.ts b/browser/lib/src/collection-partial-local.test.ts new file mode 100644 index 0000000000..3b1668698e --- /dev/null +++ b/browser/lib/src/collection-partial-local.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it, vi } from 'vitest'; +import { CollectionBuilder } from './collectionBuilder.js'; +import { Store } from './store.js'; +import { core } from './ontologies/core.js'; +import { collections } from './ontologies/collections.js'; +import type { ClientDbWorker } from './client-db.js'; + +/** + * A non-empty local answer is only the whole answer for a drive this client + * has synced. A guest in a chatroom shared from someone else's drive never + * syncs that drive: their local database holds their own messages and the + * ones that were there when they joined. Trusting it hid every later message + * from the host, and a reload asked the same local database again. + */ +const HOME = 'https://app.example.com'; +const OWN_DRIVE = 'did:ad:own-drive'; +const HOST_DRIVE = 'did:ad:host-drive'; +const ROOM = 'did:ad:room'; +const MINE = 'did:ad:my-message'; +const THEIRS = 'did:ad:their-message'; + +function setup() { + const store = new Store({ serverUrl: HOME, connect: false }); + store.setClientDb({ + isReady: true, + waitForReady: async () => true, + query: vi.fn(async () => ({ subjects: [MINE], count: 1 })), + } as unknown as ClientDbWorker); + const requests: URL[] = []; + store.injectFetch(async input => { + const url = new URL(String(input)); + requests.push(url); + + return new Response( + JSON.stringify({ + '@id': url.href, + [collections.properties.members]: [MINE, THEIRS], + [collections.properties.totalMembers]: 2, + }), + { status: 200 }, + ); + }); + store.setDrive(OWN_DRIVE); + store.finishDriveSync(OWN_DRIVE, 1, Date.now()); + store.setServerConnected(true); + + return { store, requests }; +} + +function messagesIn(store: Store, drive: string) { + return new CollectionBuilder(store) + .setProperty(core.properties.parent) + .setValue(ROOM) + .setDrive(drive) + .buildAndFetch(); +} + +describe('a non-empty local result for a drive this client never synced', () => { + it('asks the server for the rest', async () => { + const { store, requests } = setup(); + const collection = await messagesIn(store, HOST_DRIVE); + + expect(requests.length).toBeGreaterThan(0); + expect(collection.totalMembers).toBe(2); + expect(await collection.getMemberWithIndex(1)).toBe(THEIRS); + }); + + it('asks once per query, not on every mount', async () => { + const { store, requests } = setup(); + await messagesIn(store, HOST_DRIVE); + const asked = requests.length; + await messagesIn(store, HOST_DRIVE); + + expect(asked).toBeGreaterThan(0); + expect(requests.length).toBe(asked); + }); + + it('still trusts the local database for a synced drive', async () => { + const { store, requests } = setup(); + const collection = await messagesIn(store, OWN_DRIVE); + + expect(requests).toEqual([]); + expect(collection.totalMembers).toBe(1); + }); +}); diff --git a/browser/lib/src/collection-sort-order.test.ts b/browser/lib/src/collection-sort-order.test.ts index 3f9ceb7225..b1ac13c40d 100644 --- a/browser/lib/src/collection-sort-order.test.ts +++ b/browser/lib/src/collection-sort-order.test.ts @@ -159,10 +159,31 @@ describe('Collection: local surplus is not "stale"', () => { await collection.waitForReady(); await new Promise(r => setTimeout(r, 30)); + // The drive isn't synced here, so the server is asked (see + // collection-partial-local.test.ts); its smaller answer must not drop + // the row only the local index has. + expect(urls.length).toBeGreaterThan(0); expect(collection.totalMembers).toBe(local.length); - const fullFetches = urls.filter( - u => new URL(u).searchParams.get('page_size') !== '1', - ); - expect(fullFetches).toEqual([]); + const members: Array = []; + + for (let i = 0; i < collection.totalMembers; i++) { + members.push(await collection.getMemberWithIndex(i)); + } + + expect(members).toContain('atomic:pending'); + }); + + it('does not ask the server at all once the drive has synced', async ({ + expect, + }) => { + const { store, urls } = storeWithServer(['atomic:row1']); + store.setClientDb(stubClientDb(['atomic:row1', 'atomic:row2'])); + store.finishDriveSync(DRIVE, 2, Date.now()); + + const collection = new Collection(store, 'https://example.com', params()); + await collection.waitForReady(); + + expect(urls).toEqual([]); + expect(collection.totalMembers).toBe(2); }); }); diff --git a/browser/lib/src/collection.ts b/browser/lib/src/collection.ts index d306b7c9b1..0e9ea037eb 100644 --- a/browser/lib/src/collection.ts +++ b/browser/lib/src/collection.ts @@ -325,6 +325,10 @@ export class Collection { */ private _assemblingPage = false; private static legacyQueryServers = new WeakMap>(); + /** Pages of unsynced drives the server has answered this session. Its + * members were written to the local DB as they loaded and live updates keep + * it current, so the local answer is whole from then on. */ + private static completedByServer = new WeakMap>(); private legacyQuery = false; private legacyMembers?: Promise; @@ -945,6 +949,24 @@ export class Collection { // here. The cold-load case pays at most one extra OPFS wait // before the server fetch fires. if (hasClientDb && (await this.fetchPageFromLocalDb(page)) === 'ok') { + // Only a drive synced into this client has its whole membership here. + // Anything else holds what this client happened to fetch or create: a + // guest in a chatroom shared from someone else's drive had their own + // messages and the ones present when they joined, and trusting that + // hid every later message from the host, on every reload. Asked once + // per page per session, not on every mount. + if ( + this.store.serverConnected && + !this.store.hasCompletedDriveSyncFor( + this.params.drive ?? this.store.getDrive(), + ) && + !Collection.completedByServer + .get(this.store) + ?.has(this.buildSubject(page)) + ) { + await this.completeFromServer(page); + } + return; } @@ -984,6 +1006,41 @@ export class Collection { } } + /** + * Replace a page the local DB answered with the server's, keeping any member + * only the local DB knows: a write the server hasn't acknowledged yet must + * not vanish because the server answered first. When the server can't be + * reached, the local page stands. + */ + private async completeFromServer(page: number): Promise { + const local = this.pages.get(page)?.props.members ?? []; + + try { + await this.fetchPageFromServer(page); + } catch { + return; + } + + const answered = + Collection.completedByServer.get(this.store) ?? new Set(); + answered.add(this.buildSubject(page)); + Collection.completedByServer.set(this.store, answered); + + const fetched = this.pages.get(page); + + if (!fetched) return; + + const members = fetched.props.members ?? []; + const localOnly = local.filter(s => !members.includes(s)); + + if (localOnly.length === 0) return; + + const total = (this._totalMembers ?? members.length) + localOnly.length; + this.writePageMembers(fetched, [...members, ...localOnly], total); + this.setPage(page, fetched); + this._totalMembers = total; + } + /** * Resolve a page from the local WASM DB. Returns: * - `'ok'` — query ran and the page is populated (possibly with zero diff --git a/browser/lib/src/store.subscribe-live.test.ts b/browser/lib/src/store.subscribe-live.test.ts new file mode 100644 index 0000000000..f11b788625 --- /dev/null +++ b/browser/lib/src/store.subscribe-live.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it, vi } from 'vitest'; +import { Store } from './store.js'; +import type { WSClient } from './websockets.js'; + +/** + * Something shared with you out of a drive you can't open only reaches you + * through a subscription on the thing itself. Several parts of the app may + * hold one; the server hears one `SUB` and one `UNSUB`. + */ +describe('Store.subscribeLive', () => { + const ROOM = 'did:ad:room'; + + function setup() { + const store = new Store({ + serverUrl: 'https://example.com', + connect: false, + }); + const ws = { + subscribeResource: vi.fn(), + unsubscribeResource: vi.fn(), + }; + vi.spyOn(store, 'getWebSocketForSubject').mockReturnValue( + ws as unknown as WSClient, + ); + + return { store, ws }; + } + + it('subscribes once and lets go when the last holder does', () => { + const { store, ws } = setup(); + const first = store.subscribeLive(ROOM); + const second = store.subscribeLive(ROOM); + + expect(ws.subscribeResource).toHaveBeenCalledOnce(); + + first(); + expect(ws.unsubscribeResource).not.toHaveBeenCalled(); + expect(store.liveSubjects.has(store.normalizeSubject(ROOM))).toBe(true); + + second(); + expect(ws.unsubscribeResource).toHaveBeenCalledOnce(); + expect(store.liveSubjects.has(store.normalizeSubject(ROOM))).toBe(false); + }); +}); diff --git a/browser/lib/src/store.ts b/browser/lib/src/store.ts index 02937502d7..f013a1833a 100644 --- a/browser/lib/src/store.ts +++ b/browser/lib/src/store.ts @@ -517,6 +517,9 @@ function commitLogValuesEqual( export class Store { /** A list of all functions that need to be called when a certain resource is updated */ public subscribers: Map; + /** Subjects held live on their own, not via the open drive: see + * {@link Store.subscribeLive}. Counted, so each holder can let go. */ + public liveSubjects: Map = new Map(); private loroSyncSubscribers: Map = new Map(); private loroEphemeralSubscribers: Map = new Map(); @@ -5794,6 +5797,36 @@ export class Store { ); } + /** + * Keep changes to `subject`, and to its children, arriving while the app + * runs. The open drive's subscription covers everything in it; this is for + * what lives elsewhere and was shared with you on its own, like a chatroom + * in someone else's drive, which that subscription can never reach. + * Survives reconnects. Returns a function that lets go. + */ + public subscribeLive(subject: string): () => void { + const normalized = this.normalizeSubject(subject); + const count = this.liveSubjects.get(normalized) ?? 0; + this.liveSubjects.set(normalized, count + 1); + + if (count === 0) { + this.getWebSocketForSubject(normalized)?.subscribeResource(normalized); + } + + return () => { + const left = (this.liveSubjects.get(normalized) ?? 1) - 1; + + if (left > 0) { + this.liveSubjects.set(normalized, left); + + return; + } + + this.liveSubjects.delete(normalized); + this.getWebSocketForSubject(normalized)?.unsubscribeResource(normalized); + }; + } + /** Drive resources use drive-wide fan-out. Mounted agent profiles also need * a targeted subscription: another user's profile is outside our drive. */ public subscribeWebSocket(subject: string): void { diff --git a/browser/lib/src/websockets.ts b/browser/lib/src/websockets.ts index b246e43089..b3f28d4ba8 100644 --- a/browser/lib/src/websockets.ts +++ b/browser/lib/src/websockets.ts @@ -1627,6 +1627,23 @@ export class WSClient { this.sendBinary(encodeSub(this.wireSubject(subject))); } + /** A `SUB` for one resource, held via {@link Store.subscribeLive}. */ + public subscribeResource(subject: string): void { + if (this.readyState !== WebSocket.OPEN) return; + if (this.store.isLocalOnlySubject(subject)) return; + if ( + this.store.getAgent()?.subject && + this.authenticatedWith !== this.store.getAgent()?.subject + ) + return; + this.sendBinary(encodeSub(this.wireSubject(subject))); + } + + public unsubscribeResource(subject: string): void { + if (this.readyState !== WebSocket.OPEN) return; + this.sendBinary(encodeUnsub(this.wireSubject(subject))); + } + public unsubscribeAgentProfile(subject: string): void { if (!isAgentSubject(subject) || this.readyState !== WebSocket.OPEN) return; this.sendBinary(encodeUnsub(this.wireSubject(subject))); @@ -1643,6 +1660,12 @@ export class WSClient { } } + for (const subject of this.store.liveSubjects.keys()) { + if (this.store.getWebSocketForSubject(subject) === this) { + this.subscribeResource(subject); + } + } + // Loro and presence subscriptions carry an identity (peers see who // is editing), so the server refuses them before AUTH with // `AUTH_REQUIRED`. Don't send them for a session without an agent; diff --git a/server/src/commit_monitor.rs b/server/src/commit_monitor.rs index b0805d9c72..655bf9bf90 100644 --- a/server/src/commit_monitor.rs +++ b/server/src/commit_monitor.rs @@ -617,7 +617,7 @@ impl Handler for CommitMonitor { type Result = ResponseActFuture; #[tracing::instrument(name = "handle_commit_message", skip_all, fields(subscriptions = &self.subscriptions.len(), s = %msg.commit_response.commit_resource.get_subject()))] - fn handle(&mut self, msg: CommitMessage, _: &mut Context) -> Self::Result { + fn handle(&mut self, msg: CommitMessage, ctx: &mut Context) -> Self::Result { // Normalize the subject using the base domain so it matches subscriptions let target_subject = atomic_lib::Subject::from_raw( msg.commit_response.commit.subject.as_str(), @@ -630,6 +630,8 @@ impl Handler for CommitMonitor { // per-connection. let frames = encode_commit_frames(&self.store, &msg); + #[allow(clippy::mutable_key_type)] + let mut parent_subscribers: Vec<(Addr, Subscriber)> = Vec::new(); if let Some(frames) = frames.as_ref() { // Per-resource subscribers if let Some(subscribers) = self.subscriptions.get(&target_subject) { @@ -665,13 +667,81 @@ impl Handler for CommitMonitor { .as_ref() .and_then(|r| r.get_drive()); let owner = resource_drive.as_ref().unwrap_or(&target_subject); + #[allow(clippy::mutable_key_type)] + let mut sent: HashSet<&Addr> = HashSet::new(); for (drive, subscribers) in &self.drive_subscriptions { let drive_subject = atomic_lib::Subject::from_raw(drive, base_domain.as_deref()); if !owner.is_within_drive(&drive_subject) { continue; } send_scheme_frames(subscribers, frames, |_| false); + sent.extend(subscribers.keys()); } + + // Subscribers of the parent. Someone given one resource out of a + // drive they can't read (a shared chatroom) can subscribe to that + // resource but not to the drive, and a new child is a new subject, + // so neither map above reaches them: every message after the one + // they loaded never arrived. A connection already reached above, + // through the drive or the resource itself, is skipped so it + // doesn't get the frame twice. + if let Some(subscribers) = self.subscriptions.get(&target_subject) { + sent.extend(subscribers.keys()); + } + let parent = msg + .commit_response + .resource_new + .as_ref() + .or(msg.commit_response.resource_old.as_ref()) + .and_then(|r| r.get(atomic_lib::urls::PARENT).ok()) + .map(|p| atomic_lib::Subject::from_raw(&p.to_string(), base_domain.as_deref())); + if let Some(subscribers) = parent.and_then(|p| self.subscriptions.get(&p)) { + parent_subscribers.extend( + subscribers + .iter() + .filter(|(connection, _)| !sent.contains(connection)) + .map(|(connection, subscriber)| (connection.clone(), subscriber.clone())), + ); + } + } + + // Rights are checked again at send time, per subscriber, against the + // resource itself: the subscription was admitted on the parent, and a + // child can carry rights of its own. `ctx.wait` keeps this delivery in + // order with the commits that follow it. + if !parent_subscribers.is_empty() { + let store = self.store.clone(); + let msg = msg.clone(); + ctx.wait( + async move { + let Some(resource) = msg + .commit_response + .resource_new + .as_ref() + .or(msg.commit_response.resource_old.as_ref()) + else { + return; + }; + let mut allowed = Vec::new(); + for (connection, subscriber) in parent_subscribers { + let agent = ForAgent::from(subscriber.agent.clone()); + if atomic_lib::hierarchy::check_read(&store, resource, &agent) + .await + .is_ok() + { + allowed.push((connection, subscriber)); + } + } + if let Some(frames) = encode_commit_frames(&store, &msg) { + for (connection, subscriber) in &allowed { + connection.do_send(SendFrame { + frame: frames.for_subscriber(subscriber), + }); + } + } + } + .into_actor(self), + ); } let store = self.store.clone(); diff --git a/server/tests/it/main.rs b/server/tests/it/main.rs index 7ac6fbd293..42cc7895f8 100644 --- a/server/tests/it/main.rs +++ b/server/tests/it/main.rs @@ -28,4 +28,5 @@ mod ws_errors; mod ws_fragmented; mod ws_get; mod ws_get_unauthorized_latency; +mod ws_parent_fanout; mod ws_unsub; diff --git a/server/tests/it/ws_parent_fanout.rs b/server/tests/it/ws_parent_fanout.rs new file mode 100644 index 0000000000..0e8bc5ddcc --- /dev/null +++ b/server/tests/it/ws_parent_fanout.rs @@ -0,0 +1,301 @@ +//! A resource shared out of a drive the recipient can't read must still get +//! its new children live. +//! +//! Bob shares one chatroom from his private drive with Alice. Alice can read +//! the room, not the drive, so she subscribes to the room. A new message is a +//! new subject in Bob's drive: without fanning out to subscribers of the +//! parent, it reached neither her resource subscription nor a drive +//! subscription she could hold, and she never saw Bob's messages after the +//! ones she loaded. +//! +//! Run: cargo test -p atomic-server --test it ws_parent_fanout + +use atomic_lib::{ + client::{ + connected::Client, + ws::{WsClient, WsMessage}, + }, + errors::AtomicResult, + Storelike, Value, +}; +use std::time::Duration; + +use crate::common::{start_server, wait_for_server}; + +/// A genesis `did:ad:` commit for a resource under `parent`, signed by +/// `store`'s default agent. Returns `(subject, wire-JSON commit)`. +async fn make_child( + store: &atomic_lib::Store, + parent: &str, + name: &str, + read: Option<&str>, +) -> AtomicResult<(String, String)> { + let mut res = atomic_lib::Resource::new("did:ad:placeholder".into()); + res.set_unsafe( + atomic_lib::urls::IS_A.into(), + Value::ResourceArray(vec![atomic_lib::urls::CLASS.into()]), + )?; + res.set_unsafe(atomic_lib::urls::PARENT.into(), parent.to_string().into())?; + res.set_name(name)?; + res.set_unsafe( + atomic_lib::urls::SHORTNAME.into(), + Value::Slug(name.to_lowercase().replace(' ', "-")), + )?; + res.set_unsafe( + atomic_lib::urls::DESCRIPTION.into(), + Value::String("parent fan-out test resource".into()), + )?; + if let Some(agent) = read { + res.set_unsafe( + atomic_lib::urls::READ.into(), + Value::ResourceArray(vec![agent.into()]), + )?; + } + + let agent = store.get_default_agent()?; + let mut commit_builder = res.get_commit_builder().clone(); + commit_builder.is_genesis = true; + let commit = atomic_lib::Commit::create_did(commit_builder, &agent, store).await?; + let commit_json = atomic_lib::client::commit_to_wire_json(&commit, store).await?; + + Ok((commit.subject.to_string(), commit_json)) +} + +/// Everything `rx` delivers until `until` arrives or the timeout passes. +async fn drain_until( + rx: &mut tokio::sync::broadcast::Receiver, + until: &str, +) -> (bool, Vec) { + let mut seen = Vec::new(); + let arrived = tokio::time::timeout(Duration::from_secs(10), async { + loop { + match rx.recv().await { + Ok(WsMessage::Update { subject, .. }) => { + let done = subject == until; + seen.push(subject); + if done { + return true; + } + } + Ok(_) => {} + Err(_) => return false, + } + } + }) + .await + .unwrap_or(false); + + (arrived, seen) +} + +#[tokio::test] +async fn children_of_a_shared_resource_reach_its_subscribers() -> AtomicResult<()> { + let port = start_server("ws_parent_fanout"); + wait_for_server(port).await; + let server_url = format!("http://localhost:{}", port); + let ws_url = format!("ws://localhost:{}/ws", port); + + let client_a = Client::new(&server_url).await?; + let agent_a = client_a.new_agent("Alice").await?; + let client_b = Client::new(&server_url).await?; + let agent_b = client_b.new_agent("Bob").await?; + let drive_b = client_b.new_drive(&agent_b, "Bob private drive").await?; + + let ws_b = WsClient::connect(&ws_url).await?; + ws_b.authenticate(&agent_b).await?; + + // Bob makes a room Alice may read, and a sibling she may not. + let (room, room_commit) = make_child( + client_b.store(), + &drive_b, + "Shared Room", + Some(&agent_a.subject.to_string()), + ) + .await?; + ws_b.post_commit(1, &room_commit).await?; + let (secret, secret_commit) = + make_child(client_b.store(), &drive_b, "Secret Room", None).await?; + ws_b.post_commit(2, &secret_commit).await?; + + // Alice holds the room, not the drive. + let ws_a = WsClient::connect(&ws_url).await?; + ws_a.authenticate(&agent_a).await?; + ws_a.subscribe_resource(&room).await?; + let mut rx_a = ws_a.subscribe(); + tokio::time::sleep(Duration::from_millis(300)).await; + + // A child of the secret room first, then a message in the shared room. + let (hidden, hidden_commit) = + make_child(client_b.store(), &secret, "Hidden Message", None).await?; + ws_b.post_commit(3, &hidden_commit).await?; + let (message, message_commit) = + make_child(client_b.store(), &room, "Room Message", None).await?; + ws_b.post_commit(4, &message_commit).await?; + + let (arrived, seen) = drain_until(&mut rx_a, &message).await; + + assert!( + arrived, + "Alice, subscribed to the room {room} Bob shared with her, never received \ + the new message {message} in it. Seen: {seen:?}" + ); + assert!( + !seen.contains(&hidden), + "SECURITY LEAK: Alice received {hidden}, a child of a room she can't read." + ); + + Ok(()) +} + +/// Change `subject` as `client`'s agent and post the commit on `ws`. +async fn update( + client: &Client, + agent: &atomic_lib::agents::Agent, + ws: &WsClient, + request_id: u16, + subject: &str, + change: impl FnOnce(&mut atomic_lib::Resource) -> AtomicResult<()>, +) -> AtomicResult<()> { + let mut resource = client.get_resource(subject).await?; + change(&mut resource)?; + let snapshot = resource.build_state_doc()?.export_snapshot(); + let mut builder = resource.get_commit_builder().clone(); + builder.set_loro_update(snapshot); + let commit = builder.sign(agent, client.store(), &resource).await?; + let json = atomic_lib::client::commit_to_wire_json(&commit, client.store()).await?; + ws.post_commit(request_id, &json).await?; + + Ok(()) +} + +/// Alice's own control resource, posted on a second connection of hers so +/// her subscriber connection receives it: anything queued for her before it +/// has arrived by the time it does. +async fn control( + client: &Client, + agent: &atomic_lib::agents::Agent, + ws_url: &str, + drive: &str, +) -> AtomicResult { + let (subject, commit) = make_child(client.store(), drive, "Control", None).await?; + let ws = WsClient::connect(ws_url).await?; + ws.authenticate(agent).await?; + ws.post_commit(1, &commit).await?; + + Ok(subject) +} + +#[tokio::test] +async fn a_connection_on_both_child_and_parent_gets_one_frame() -> AtomicResult<()> { + let port = start_server("ws_parent_fanout_once"); + wait_for_server(port).await; + let server_url = format!("http://localhost:{}", port); + let ws_url = format!("ws://localhost:{}/ws", port); + + let client_a = Client::new(&server_url).await?; + let agent_a = client_a.new_agent("Alice").await?; + let drive_a = client_a.new_drive(&agent_a, "Alice private drive").await?; + let client_b = Client::new(&server_url).await?; + let agent_b = client_b.new_agent("Bob").await?; + let drive_b = client_b.new_drive(&agent_b, "Bob private drive").await?; + let ws_b = WsClient::connect(&ws_url).await?; + ws_b.authenticate(&agent_b).await?; + + let (room, room_commit) = make_child( + client_b.store(), + &drive_b, + "Shared Room", + Some(&agent_a.subject.to_string()), + ) + .await?; + ws_b.post_commit(1, &room_commit).await?; + let (message, message_commit) = + make_child(client_b.store(), &room, "Room Message", None).await?; + ws_b.post_commit(2, &message_commit).await?; + + // Alice holds the room, the message in it, and her own drive. + let ws_a = WsClient::connect(&ws_url).await?; + ws_a.authenticate(&agent_a).await?; + ws_a.subscribe_resource(&room).await?; + ws_a.subscribe_resource(&message).await?; + ws_a.subscribe_drive(&drive_a).await?; + let mut rx_a = ws_a.subscribe(); + tokio::time::sleep(Duration::from_millis(300)).await; + + update(&client_b, &agent_b, &ws_b, 3, &message, |r| { + r.set_name("Edited Message").map(|_| ()) + }) + .await?; + let control = control(&client_a, &agent_a, &ws_url, &drive_a).await?; + + let (arrived, seen) = drain_until(&mut rx_a, &control).await; + assert!( + arrived, + "inconclusive: Alice's control never arrived. Seen: {seen:?}" + ); + let frames = seen.iter().filter(|s| **s == message).count(); + assert_eq!( + frames, 1, + "Alice subscribed to both the message and its room; the edit should reach \ + her once, not {frames} times. Seen: {seen:?}" + ); + + Ok(()) +} + +#[tokio::test] +async fn losing_read_on_the_parent_stops_its_children() -> AtomicResult<()> { + let port = start_server("ws_parent_fanout_revoked"); + wait_for_server(port).await; + let server_url = format!("http://localhost:{}", port); + let ws_url = format!("ws://localhost:{}/ws", port); + + let client_a = Client::new(&server_url).await?; + let agent_a = client_a.new_agent("Alice").await?; + let drive_a = client_a.new_drive(&agent_a, "Alice private drive").await?; + let client_b = Client::new(&server_url).await?; + let agent_b = client_b.new_agent("Bob").await?; + let drive_b = client_b.new_drive(&agent_b, "Bob private drive").await?; + let ws_b = WsClient::connect(&ws_url).await?; + ws_b.authenticate(&agent_b).await?; + + let (room, room_commit) = make_child( + client_b.store(), + &drive_b, + "Shared Room", + Some(&agent_a.subject.to_string()), + ) + .await?; + ws_b.post_commit(1, &room_commit).await?; + + let ws_a = WsClient::connect(&ws_url).await?; + ws_a.authenticate(&agent_a).await?; + ws_a.subscribe_resource(&room).await?; + ws_a.subscribe_drive(&drive_a).await?; + let mut rx_a = ws_a.subscribe(); + tokio::time::sleep(Duration::from_millis(300)).await; + + // Bob takes the room back. Alice's subscription was admitted while she + // could read it; the message after this must not reach her. + update(&client_b, &agent_b, &ws_b, 2, &room, |r| { + r.set_unsafe(atomic_lib::urls::READ.into(), Value::ResourceArray(vec![])) + .map(|_| ()) + }) + .await?; + let (message, message_commit) = + make_child(client_b.store(), &room, "After Revoke", None).await?; + ws_b.post_commit(3, &message_commit).await?; + let control = control(&client_a, &agent_a, &ws_url, &drive_a).await?; + + let (arrived, seen) = drain_until(&mut rx_a, &control).await; + assert!( + arrived, + "inconclusive: Alice's control never arrived. Seen: {seen:?}" + ); + assert!( + !seen.contains(&message), + "SECURITY LEAK: Alice lost read on {room} but still received {message} in it." + ); + + Ok(()) +} From 2cbc15934811ab5a4bf0ea2eac0c9ba1dd6ca9ff Mon Sep 17 00:00:00 2001 From: Joep Meindertsma Date: Thu, 1 Oct 2026 06:34:38 +0200 Subject: [PATCH 2/3] Pay the class picker's first render in the hook, not in the first test "shows a fetched external class for a partial name" timed out at 5 s in CI (run 36813877203) though it takes a few milliseconds: as the first render in the file it paid styled-components building its stylesheet, jsdom parsing it and the picker's modules running for the first time. The same fix as cb085dc79 for the table grid. --- .../forms/SearchBox/SearchBoxWindow.test.tsx | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/browser/data-browser/src/components/forms/SearchBox/SearchBoxWindow.test.tsx b/browser/data-browser/src/components/forms/SearchBox/SearchBoxWindow.test.tsx index a69569dfe3..95ac57002e 100644 --- a/browser/data-browser/src/components/forms/SearchBox/SearchBoxWindow.test.tsx +++ b/browser/data-browser/src/components/forms/SearchBox/SearchBoxWindow.test.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom // @wc-ignore-file -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import React, { createRef } from 'react'; import { cleanup, @@ -147,6 +147,16 @@ describe('searchLoadedExternal', () => { }); describe('class picker', () => { + // The first render in this file is where styled-components builds its + // stylesheet, jsdom parses it and the picker's modules run for the first + // time. Under CI load that one-time cost put whichever test ran first over + // vitest's 5 s default, though the test itself takes a few milliseconds. + // Paid here, under the hook's own timeout. + beforeAll(() => { + show(storeWithFetchedClasses(), { searchValue: '' }); + cleanup(); + }); + it('shows a fetched external class for a partial name, marked with its origin', () => { fixture.serverResults = [LOCAL_CLASS]; const { onSelect } = show(storeWithFetchedClasses(), { From 700a71bd8778249c0d8b33d089a24ac5ff475c4f Mon Sep 17 00:00:00 2001 From: Joep Meindertsma Date: Thu, 1 Oct 2026 14:14:09 +0200 Subject: [PATCH 3/3] Scope presence to shared resources Presence was one channel per drive. A guest given one chat out of a drive they can't read was refused that channel ("presence update from non-subscriber" on the server), so host and guest never saw each other in the chat, nor who was typing. - Store.presenceScope(subject): the nearest loaded resource at or above it with its own read list, below the drive. That's what an invite or a share writes to, and host and guest compute it from the same data. The server already accepts presence on any subject the agent can read. - useResourcePresence and useTypingPresence announce in the drive channel and in that scope's channel, and read both. - useDrivePresenceManager leaves the drive channel out when the drive is unauthorized; FollowContext uses it too. - One presenceSessionId per tab across all managers, so a session in both channels is one entry, and filtering out our own is one check. --- browser/CHANGELOG.md | 8 + .../src/components/Presence/FollowContext.tsx | 4 +- browser/lib/src/presence.ts | 5 +- browser/lib/src/store.presence-scope.test.ts | 65 ++++++++ browser/lib/src/store.ts | 34 +++++ browser/react/src/usePresence.ts | 139 ++++++++++++++---- 6 files changed, 221 insertions(+), 34 deletions(-) create mode 100644 browser/lib/src/store.presence-scope.test.ts diff --git a/browser/CHANGELOG.md b/browser/CHANGELOG.md index bfb2db3321..9e439eb8b2 100644 --- a/browser/CHANGELOG.md +++ b/browser/CHANGELOG.md @@ -17,6 +17,14 @@ This changelog covers all five packages, as they are (for now) updated as a whol chat never received new messages from the host, and got no notifications for them. Everything in "Shared with me" is now subscribed for as long as the app runs (`Store.subscribeLive`). +- Presence works in things shared out of someone else's drive. Presence was a + channel per drive, which a guest given one chat can't read: the server + refused them, so host and guest never saw each other there, nor who was + typing. A view now also announces in the channel of the shared resource it + is in (`Store.presenceScope`: the nearest resource with its own `read` + list), and leaves the drive channel alone when it can't read the drive. One + tab is one session across channels (`Store.presenceSessionId`), so nobody + shows up twice. - Notifications are less noisy. The Notifications page shows one row per conversation ("Sanne and Polle: 3 new messages in Team chat") with names and titles as they are now, in your language. Coming back to the window while diff --git a/browser/data-browser/src/components/Presence/FollowContext.tsx b/browser/data-browser/src/components/Presence/FollowContext.tsx index cf9cad7215..a8fd253cb0 100644 --- a/browser/data-browser/src/components/Presence/FollowContext.tsx +++ b/browser/data-browser/src/components/Presence/FollowContext.tsx @@ -13,6 +13,7 @@ import { useCurrentAgent, useDrive, useDrivePresence, + useDrivePresenceManager, useStore, type PresenceItem, type Store, @@ -153,7 +154,8 @@ export function FollowProvider({ * reload ends leadership; the banner hides once presence expires). */ const [activeMeeting, setActiveMeeting] = useState(); - const manager = drive ? store.getPresence(drive) : undefined; + // Not the drive's channel when this agent can't read the drive. + const manager = useDrivePresenceManager(); // While leading a meeting, the presence session points at it — joiners // read it and open the meeting chat. (Following without a meeting shares diff --git a/browser/lib/src/presence.ts b/browser/lib/src/presence.ts index 4a656aee08..c958f4caf2 100644 --- a/browser/lib/src/presence.ts +++ b/browser/lib/src/presence.ts @@ -131,7 +131,10 @@ export class DrivePresenceManager { private store: Store, private drive: string, ) { - this.sessionId = crypto.randomUUID(); + // One id per tab across every channel it is in: a session announcing in + // its drive and in a shared resource's channel is one person to anyone + // who reads both. + this.sessionId = store.presenceSessionId; } /** diff --git a/browser/lib/src/store.presence-scope.test.ts b/browser/lib/src/store.presence-scope.test.ts new file mode 100644 index 0000000000..ba2f2496fc --- /dev/null +++ b/browser/lib/src/store.presence-scope.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest'; +import { Store } from './store.js'; +import { JSONADParser } from './parse.js'; +import { core } from './ontologies/core.js'; +import { server } from './ontologies/server.js'; + +/** + * Someone given one chat out of a drive they can't read is refused that + * drive's presence channel. Host and guest meet in the channel of the nearest + * resource carrying its own `read` list: what the invite wrote to. + */ +describe('Store.presenceScope', () => { + const DRIVE = 'did:ad:drive'; + const ROOM = 'did:ad:room'; + const MESSAGE = 'did:ad:message'; + const FOLDER = 'did:ad:folder'; + const NOTE = 'did:ad:note'; + + function setup() { + const store = new Store({ + serverUrl: 'https://example.com', + connect: false, + }); + const parser = new JSONADParser(); + + const add = (json: Record) => { + for (const r of parser.parse(json, json['@id'] as string)) { + r.loading = false; + store.addResource(r); + } + }; + + add({ + '@id': DRIVE, + [core.properties.isA]: [server.classes.drive], + [core.properties.read]: ['did:ad:agent:host'], + }); + add({ + '@id': ROOM, + [core.properties.parent]: DRIVE, + [core.properties.read]: ['did:ad:agent:guest'], + }); + add({ '@id': MESSAGE, [core.properties.parent]: ROOM }); + add({ '@id': FOLDER, [core.properties.parent]: DRIVE }); + add({ '@id': NOTE, [core.properties.parent]: FOLDER }); + + return store; + } + + it('is the shared resource itself, and so for what is in it', () => { + const store = setup(); + const room = store.normalizeSubject(ROOM); + + expect(store.presenceScope(ROOM)).toBe(room); + expect(store.presenceScope(MESSAGE)).toBe(room); + }); + + it('leaves the rest of the drive to the drive channel', () => { + const store = setup(); + + expect(store.presenceScope(NOTE)).toBeUndefined(); + expect(store.presenceScope(DRIVE)).toBeUndefined(); + expect(store.presenceScope('did:ad:not-loaded')).toBeUndefined(); + }); +}); diff --git a/browser/lib/src/store.ts b/browser/lib/src/store.ts index f013a1833a..fc34235d15 100644 --- a/browser/lib/src/store.ts +++ b/browser/lib/src/store.ts @@ -527,6 +527,8 @@ export class Store { /** One presence manager per drive; managers remove themselves when * their last subscriber leaves. */ private presenceManagers: Map = new Map(); + /** This tab's presence session, shared by every channel it announces in. */ + public readonly presenceSessionId: string = crypto.randomUUID(); private injectedFetch: Fetch; /** The base URL of an Atomic Server. Where commits, search, and * new-instance requests are sent. */ @@ -6018,6 +6020,38 @@ export class Store { return manager; } + /** + * The presence channel for viewing `subject`, when it isn't the drive's: + * the nearest resource at or above it that carries its own `read` list. + * That is what an invite or a share writes to, so it is where someone given + * this one thing out of a drive they can't open can meet the people who + * can. Host and guest compute it from the same resource data, so they land + * in the same channel. `undefined` means the drive's channel covers it. + * Only walks resources already loaded; a parent that isn't is the top. + */ + public presenceScope(subject: string): string | undefined { + let current = this.resources.get(this.normalizeSubject(subject)); + + for (let depth = 0; current && depth < 32; depth++) { + if (current.error || current.loading) return undefined; + if (current.hasClasses(server.classes.drive)) return undefined; + + const readers = current.get(core.properties.read); + + if (Array.isArray(readers) && readers.length > 0) { + return current.subject; + } + + const parent = current.get(core.properties.parent); + + if (typeof parent !== 'string') return undefined; + + current = this.resources.get(this.normalizeSubject(parent)); + } + + return undefined; + } + /** Subscribe to raw presence payloads for a drive. Transport-level — * use `getPresence(drive)` for the decoded presence list. */ public subscribePresenceUpdates( diff --git a/browser/react/src/usePresence.ts b/browser/react/src/usePresence.ts index ad53d3f970..8290e13c94 100644 --- a/browser/react/src/usePresence.ts +++ b/browser/react/src/usePresence.ts @@ -5,37 +5,102 @@ import { useRef, useSyncExternalStore, } from 'react'; -import type { DrivePresenceManager, PresenceItem } from '@tomic/lib'; -import { useStore } from './index.js'; +import { + isUnauthorized, + type DrivePresenceManager, + type PresenceItem, +} from '@tomic/lib'; +import { useStore, useResource } from './index.js'; import { useDrive } from './useDrive.js'; import { useCurrentAgent } from './useCurrentAgent.js'; const EMPTY: PresenceItem[] = []; -/** Subscribe to a drive's presence manager and return its live snapshot - * (all sessions, including our own). */ -function usePresenceSnapshot(): { - manager: DrivePresenceManager | undefined; - snapshot: PresenceItem[]; -} { +/** + * The current drive's presence manager, unless this agent can't read the + * drive. Someone given one resource out of it is refused that channel, and + * what they announce there is dropped; they meet the others in the shared + * resource's own channel instead (`Store.presenceScope`). + */ +export function useDrivePresenceManager(): DrivePresenceManager | undefined { const store = useStore(); const [drive] = useDrive(); + const driveResource = useResource(drive); - const manager = drive ? store.getPresence(drive) : undefined; + if (!drive || isUnauthorized(driveResource.error)) return undefined; + return store.getPresence(drive); +} + +/** The presence manager of the resource shared out of its drive that + * `subject` is in, if any (`Store.presenceScope`). */ +function useScopePresenceManager( + subject: string | undefined, +): DrivePresenceManager | undefined { + const store = useStore(); + // Re-evaluate once the resource (and with it its rights) has loaded. + useResource(subject); + const scope = subject ? store.presenceScope(subject) : undefined; + + return scope ? store.getPresence(scope) : undefined; +} + +/** A presence manager's live snapshot (all sessions, including our own). */ +function useManagerSnapshot( + manager: DrivePresenceManager | undefined, +): PresenceItem[] { const subscribe = useCallback( (callback: () => void) => manager ? manager.subscribe(callback) : () => undefined, [manager], ); - const snapshot = useSyncExternalStore( + return useSyncExternalStore( subscribe, () => manager?.getSnapshot() ?? EMPTY, () => EMPTY, ); +} - return { manager, snapshot }; +/** + * The drive's presence plus, for `subject`, its shared resource's channel: + * the managers to announce in and every session either one knows, once each. + * All managers share this tab's session id, so a session in both channels is + * one entry. + */ +function usePresenceChannels(subject?: string): { + managers: DrivePresenceManager[]; + snapshot: PresenceItem[]; + sessionId: string; +} { + const store = useStore(); + const driveManager = useDrivePresenceManager(); + const scopeManager = useScopePresenceManager(subject); + const driveSnapshot = useManagerSnapshot(driveManager); + const scopeSnapshot = useManagerSnapshot(scopeManager); + + const managers = useMemo( + () => + [driveManager, scopeManager].filter( + (m, i, all): m is DrivePresenceManager => !!m && all.indexOf(m) === i, + ), + [driveManager, scopeManager], + ); + + const snapshot = useMemo(() => { + if (scopeSnapshot === EMPTY || scopeManager === driveManager) { + return driveSnapshot; + } + + const seen = new Set(driveSnapshot.map(item => item.sessionId)); + + return [ + ...driveSnapshot, + ...scopeSnapshot.filter(item => !seen.has(item.sessionId)), + ]; + }, [driveSnapshot, scopeSnapshot, driveManager, scopeManager]); + + return { managers, snapshot, sessionId: store.presenceSessionId }; } /** @@ -47,14 +112,15 @@ function usePresenceSnapshot(): { * per-session); dedupe by `agent` where that's unwanted. */ export function useDrivePresence(): PresenceItem[] { - const { manager, snapshot } = usePresenceSnapshot(); + const store = useStore(); + const snapshot = useManagerSnapshot(useDrivePresenceManager()); return useMemo( () => snapshot.filter( - item => item.sessionId !== manager?.sessionId, + item => item.sessionId !== store.presenceSessionId, ) as PresenceItem[], - [snapshot, manager], + [snapshot, store], ); } @@ -83,7 +149,7 @@ export function useResourcePresence( setData: (data: T | undefined) => void; } { const { announce = true } = options; - const { manager, snapshot } = usePresenceSnapshot(); + const { managers, snapshot, sessionId } = usePresenceChannels(subject); const [agent] = useCurrentAgent(); const agentSubject = agent?.subject; @@ -94,27 +160,30 @@ export function useResourcePresence( // owned by other features — e.g. follow mode — survive navigation; the // view payload is cleared since it described the previous resource. useEffect(() => { - if (announce && manager && subject && agentSubject) { - manager.patchLocal({ resource: subject, data: undefined }); + if (announce && subject && agentSubject) { + for (const manager of managers) { + manager.patchLocal({ resource: subject, data: undefined }); + } } - }, [announce, manager, subject, agentSubject]); + }, [announce, managers, subject, agentSubject]); const setData = useCallback( (data: T | undefined) => { - if (announce && manager && subject) { - manager.patchLocal({ resource: subject, data }); + if (announce && subject) { + for (const manager of managers) { + manager.patchLocal({ resource: subject, data }); + } } }, - [announce, manager, subject], + [announce, managers, subject], ); const presence = useMemo( () => snapshot.filter( - item => - item.resource === subject && item.sessionId !== manager?.sessionId, + item => item.resource === subject && item.sessionId !== sessionId, ) as PresenceItem[], - [snapshot, subject, manager], + [snapshot, subject, sessionId], ); return { presence, setData }; @@ -147,7 +216,7 @@ export function useTypingPresence(subject: string | undefined): { /** Clear this session's typing announcement immediately. */ stopTyping: () => void; } { - const { manager, snapshot } = usePresenceSnapshot(); + const { managers, snapshot, sessionId } = usePresenceChannels(subject); const [agent] = useCurrentAgent(); const agentSubject = agent?.subject; @@ -166,18 +235,24 @@ export function useTypingPresence(subject: string | undefined): { if (activeRef.current) { activeRef.current = false; - manager?.patchLocal({ typing: undefined }); + + for (const manager of managers) { + manager.patchLocal({ typing: undefined }); + } } - }, [manager]); + }, [managers]); const notifyTyping = useCallback(() => { - if (!manager || !subject || !agentSubject) { + if (managers.length === 0 || !subject || !agentSubject) { return; } if (!activeRef.current) { activeRef.current = true; - manager.patchLocal({ typing: subject }); + + for (const manager of managers) { + manager.patchLocal({ typing: subject }); + } } if (idleTimer.current) { @@ -185,7 +260,7 @@ export function useTypingPresence(subject: string | undefined): { } idleTimer.current = setTimeout(stopTyping, TYPING_IDLE_MS); - }, [manager, subject, agentSubject, stopTyping]); + }, [managers, subject, agentSubject, stopTyping]); // Stop announcing when the thread changes or the composer unmounts — the // previous `typing` value would otherwise linger via the heartbeat. @@ -195,7 +270,7 @@ export function useTypingPresence(subject: string | undefined): { const seen = new Set(); return snapshot.filter(item => { - if (item.typing !== subject || item.sessionId === manager?.sessionId) { + if (item.typing !== subject || item.sessionId === sessionId) { return false; } @@ -209,7 +284,7 @@ export function useTypingPresence(subject: string | undefined): { return true; }); - }, [snapshot, subject, manager, agentSubject]); + }, [snapshot, subject, sessionId, agentSubject]); return { typers, notifyTyping, stopTyping }; }