Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(unread): selected is not watched — stop marking off-screen messages read (#260)

Xialie Zhuang768eae62403a
diff --git a/src/App.tsx b/src/App.tsx
index ecd920a..b9a220a 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,6 +1,8 @@
import { useEffect, useRef, useState } from 'react'
import { useIsMobile } from '@/lib/utils'
import { useApp } from '@/stores/app'
+import { isWindowAttentive, subscribeWindowAttention } from '@/lib/windowAttention'
+import { isWatchingConversation } from '@/lib/watching'
import { useAuth } from '@/stores/auth'
import { useMessages, bootMessagesStream } from '@/stores/messages'
import { bootParticipants, useParticipants } from '@/stores/participants'
@@ -131,16 +133,40 @@ function AuthedApp() {
return () => window.cumora?.dock?.setUnreadDot(false)
}, [])
- // Lazy-load messages + mark conversation as read when selected
+ // Attention is a live value: the window can go behind another app at any
+ // moment, and the read decision has to follow it.
+ const mobileStack = useApp((s) => s.mobileStack)
+ const [attentive, setAttentive] = useState(() => isWindowAttentive())
+ useEffect(() => subscribeWindowAttention(setAttentive), [])
+ const watching = convoId != null && isWatchingConversation({
+ conversationId: convoId,
+ selectedConversationId: convoId,
+ view,
+ mobileStack,
+ attentive,
+ })
+
+ // Lazy-load messages when a conversation is selected. Loading is not reading:
+ // this still runs while the thread is off screen, so coming back is instant.
useEffect(() => {
if (!convoId || !selectedConvoExists) return
void useMessages.getState().loadConversation(convoId)
- // Clear the badge locally, then persist. The server response tells us
- // nothing the client doesn't already know, so refetching the whole list
- // to learn that one count went to zero is pure waste.
+ }, [convoId, selectedConvoExists])
+
+ // Mark read exactly when the user starts watching — by any route: selecting
+ // the conversation, returning to the conversations view, swiping back to the
+ // chat screen, or bringing the window to the front. Keying this on `watching`
+ // rather than on `convoId` is what keeps a badge earned off screen from
+ // sticking once the user is actually looking at the messages.
+ //
+ // Clear the badge locally, then persist. The server response tells us nothing
+ // the client doesn't already know, so refetching the whole list to learn that
+ // one count went to zero is pure waste.
+ useEffect(() => {
+ if (!convoId || !selectedConvoExists || !watching) return
useConversations.getState().markLocallyRead(convoId)
void api.markRead(convoId).catch(() => { /* swallow */ })
- }, [convoId, selectedConvoExists])
+ }, [convoId, selectedConvoExists, watching])
// Lazy-refresh whisper list when entering whispers view
useEffect(() => {
diff --git a/src/components/NotificationToasts.tsx b/src/components/NotificationToasts.tsx
index a12d068..fce436c 100644
--- a/src/components/NotificationToasts.tsx
+++ b/src/components/NotificationToasts.tsx
@@ -23,6 +23,7 @@ import { useMe } from '@/stores/auth'
import { useConversations, isMuted } from '@/stores/conversations'
import { useParticipants } from '@/stores/participants'
import { isElectron } from '@/lib/runtime'
+import { isWindowAttentive, setNativeAppFocused } from '@/lib/windowAttention'
import { playNotificationChime } from '@/lib/chime'
import { Avatar } from './Avatar'
import { ICalendar } from './icons'
@@ -62,24 +63,6 @@ interface Toast {
count: number
}
-/** Renderer-side cache of the main window's native OS focus state,
- * updated by `cumora.app.onFocusChange`. We trust this over
- * `document.hasFocus()` because the latter can return stale `true`
- * values in Electron on macOS, suppressing notifications incorrectly.
- * Seeded from `cumora.app.isFocused()` at mount; pessimistic default
- * of `true` avoids a half-second window of spurious toasts. */
-let nativeAppFocused = true
-
-/** Quick visibility check — works in both browser and Electron renderer.
- * In Electron we trust the native focus state populated by IPC. */
-function isWindowAttentive(): boolean {
- if (typeof document === 'undefined') return true
- if (document.visibilityState === 'hidden') return false
- if (isElectron) return nativeAppFocused
- if (typeof document.hasFocus === 'function' && !document.hasFocus()) return false
- return true
-}
-
export function NotificationToasts() {
const [toasts, setToasts] = useState<Toast[]>([])
const meId = useMe()
@@ -94,17 +77,19 @@ export function NotificationToasts() {
useEffect(() => { meRef.current = meId }, [meId])
useEffect(() => { focusRef.current = { selectedId, view } }, [selectedId, view])
- // Keep the renderer-side `nativeAppFocused` cache in sync with the
- // main process. This is the source of truth for `isWindowAttentive()`
- // when running in Electron — `document.hasFocus()` can lie there.
+ // Keep the shared native-focus cache in sync with the main process. It is
+ // the source of truth for `isWindowAttentive()` in Electron, where
+ // `document.hasFocus()` can lie — and it now gates read-marking too, so this
+ // bridge is the only thing standing between a backgrounded window and a
+ // silently cleared badge.
useEffect(() => {
if (!isElectron) return
const bridge = window.cumora?.app
if (!bridge) return
// Seed from the current main-window focus state at mount, then keep
// in sync with the main process's 500ms focus heartbeat.
- void bridge.isFocused().then((f) => { nativeAppFocused = f }).catch(() => { /* swallow */ })
- return bridge.onFocusChange((focused) => { nativeAppFocused = focused })
+ void bridge.isFocused().then(setNativeAppFocused).catch(() => { /* swallow */ })
+ return bridge.onFocusChange(setNativeAppFocused)
}, [])
useEffect(() => {
diff --git a/src/lib/watching.ts b/src/lib/watching.ts
new file mode 100644
index 0000000..dd5c1d4
--- /dev/null
+++ b/src/lib/watching.ts
@@ -0,0 +1,42 @@
+/**
+ * "Is the user actually watching this conversation right now?"
+ *
+ * `selectedConversationId` was standing in for that, and it is not the same
+ * question. Nothing clears it, and three ordinary navigations leave it pointing
+ * at a thread the user cannot see:
+ *
+ * - the window goes behind another app (still selected, socket still live)
+ * - desktop leaves `view === 'conversations'` — DesktopApp mounts views
+ * conditionally, so the whole ChatPane is unmounted (see the note in
+ * stores/app.ts about composer drafts, which exists for the same reason)
+ * - mobile swipes back to the list or opens the info overlay, which only
+ * moves `mobileStack`
+ *
+ * In all three the arriving message was marked read on the spot: the sidebar
+ * badge never appeared, and `POST /conversations/:id/read` advanced the
+ * server's cursor to NOW(), which no reload undoes. There is no unread divider
+ * in the thread, so the badge was the only thing that would have said "you
+ * missed twenty messages".
+ *
+ * Requiring both `view` and `mobileStack` keeps this shell-agnostic: desktop
+ * never moves `mobileStack` off 'chat' (only src/mobile touches it, and
+ * `selectConversation` sets it), and mobile keeps `view === 'conversations'`
+ * while it is in a chat.
+ */
+export interface WatchInputs {
+ /** The conversation a message just arrived in. */
+ conversationId: string
+ selectedConversationId: string | null
+ /** `useApp().view` — desktop's top-level section. */
+ view: string
+ /** `useApp().mobileStack` — which mobile screen is on top. */
+ mobileStack: string
+ /** Is the app itself in front? See lib/windowAttention. */
+ attentive: boolean
+}
+
+export function isWatchingConversation(w: WatchInputs): boolean {
+ if (!w.attentive) return false
+ if (w.selectedConversationId !== w.conversationId) return false
+ return w.view === 'conversations' && w.mobileStack === 'chat'
+}
diff --git a/src/lib/windowAttention.ts b/src/lib/windowAttention.ts
new file mode 100644
index 0000000..27c66b8
--- /dev/null
+++ b/src/lib/windowAttention.ts
@@ -0,0 +1,100 @@
+/**
+ * "Is the user actually looking at this app right now?"
+ *
+ * This used to be a private helper inside NotificationToasts, where it gated
+ * desktop toasts: notify only when the app is NOT in front. It is shared now
+ * because a second path needs the same answer and was getting it wrong.
+ *
+ * `stores/conversations` marks an arriving message read when it belongs to the
+ * SELECTED conversation. Selected is not the same as watched: a window sitting
+ * behind a browser is still "selected", still has a live socket, and still
+ * receives every message. Those messages were marked read, the sidebar badge
+ * was cleared, and `POST /conversations/:id/read` advanced the server's cursor
+ * to NOW() — so nothing, not even a reload, could bring the count back. The
+ * badge is the only "there is something new here" signal in the product; there
+ * is no unread divider in the thread to fall back on.
+ *
+ * The decision is split from the globals it reads so it can be tested without
+ * a DOM, which is how the rest of src/lib is arranged.
+ */
+import { isElectron } from '@/lib/runtime'
+
+export interface AttentionEnv {
+ /** `document.visibilityState`, or undefined outside a browser. */
+ visibility: string | undefined
+ /** Running inside the Electron shell. */
+ electron: boolean
+ /** The main process's view of native window focus. Only consulted in Electron. */
+ nativeFocused: boolean
+ /** `document.hasFocus()`, or undefined when unavailable. */
+ hasFocus: boolean | undefined
+}
+
+/**
+ * Hidden always wins: a minimized window, a background tab and a window on
+ * another desktop all report hidden, and none of them is being read.
+ *
+ * In Electron we then trust the main process over `document.hasFocus()`, which
+ * can return a stale `true` on macOS — believing it would suppress toasts (and,
+ * now, hold back reads) for a window the user cannot see.
+ *
+ * On the web `hasFocus()` is all there is. When it is unavailable we assume the
+ * user IS present: the alternative is a badge that never clears.
+ */
+export function evaluateAttention(env: AttentionEnv): boolean {
+ if (env.visibility === 'hidden') return false
+ if (env.electron) return env.nativeFocused
+ if (env.hasFocus === false) return false
+ return true
+}
+
+/** Renderer-side cache of the main window's native OS focus state, fed by
+ * `cumora.app.onFocusChange`. Optimistic default: a spurious "attentive" for
+ * half a second at boot is better than a toast storm or a stuck badge. */
+let nativeAppFocused = true
+const listeners = new Set<(attentive: boolean) => void>()
+
+/** Called by the Electron focus bridge. Notifies subscribers when it flips. */
+export function setNativeAppFocused(focused: boolean): void {
+ if (nativeAppFocused === focused) return
+ nativeAppFocused = focused
+ const attentive = isWindowAttentive()
+ for (const listener of listeners) listener(attentive)
+}
+
+/** Fires whenever attention may have changed. Returns an unsubscribe. */
+export function subscribeWindowAttention(listener: (attentive: boolean) => void): () => void {
+ listeners.add(listener)
+ const onDomChange = (): void => { listener(isWindowAttentive()) }
+ if (typeof document !== 'undefined') {
+ document.addEventListener('visibilitychange', onDomChange)
+ }
+ if (typeof window !== 'undefined') {
+ // Both edges. Listening only for `focus` would leave a subscriber that
+ // never saw attention drop, so it would never see it return either — and a
+ // badge earned while the window was away would never clear.
+ window.addEventListener('focus', onDomChange)
+ window.addEventListener('blur', onDomChange)
+ }
+ return () => {
+ listeners.delete(listener)
+ if (typeof document !== 'undefined') {
+ document.removeEventListener('visibilitychange', onDomChange)
+ }
+ if (typeof window !== 'undefined') {
+ window.removeEventListener('focus', onDomChange)
+ window.removeEventListener('blur', onDomChange)
+ }
+ }
+}
+
+/** The live answer, read from the current environment. */
+export function isWindowAttentive(): boolean {
+ if (typeof document === 'undefined') return true
+ return evaluateAttention({
+ visibility: document.visibilityState,
+ electron: isElectron,
+ nativeFocused: nativeAppFocused,
+ hasFocus: typeof document.hasFocus === 'function' ? document.hasFocus() : undefined,
+ })
+}
diff --git a/src/stores/conversations.ts b/src/stores/conversations.ts
index db911c8..245a34d 100644
--- a/src/stores/conversations.ts
+++ b/src/stores/conversations.ts
@@ -6,6 +6,8 @@ import { useApp } from '@/stores/app'
import { commitIfContextCurrent, useAuth } from '@/stores/auth'
import { useMessages } from '@/stores/messages'
import { useParticipants } from '@/stores/participants'
+import { isWindowAttentive } from '@/lib/windowAttention'
+import { isWatchingConversation } from '@/lib/watching'
interface ConversationsState {
list: Conversation[]
@@ -285,13 +287,23 @@ export function bootConversations() {
// Patch the one row this message touched. The event carries the whole
// message, so a refetch would only re-derive what we already have —
// for every conversation in the workspace, on every online client.
- const active = useApp.getState().selectedConversationId
- const isActive = e.conversationId === active
- useConversations.getState().applyIncomingMessage(e.conversationId, e.message, { read: isActive })
+ // Selected is not the same as watched — see lib/watching for the three
+ // ordinary navigations that leave a thread selected but off screen.
+ // App.tsx marks the conversation read the moment watching becomes true
+ // again, so a badge earned this way never sticks once the user is here.
+ const app = useApp.getState()
+ const watching = isWatchingConversation({
+ conversationId: e.conversationId,
+ selectedConversationId: app.selectedConversationId,
+ view: app.view,
+ mobileStack: app.mobileStack,
+ attentive: isWindowAttentive(),
+ })
+ useConversations.getState().applyIncomingMessage(e.conversationId, e.message, { read: watching })
// Still tell the server the user has seen it, so the badge stays gone
// across reloads and other devices. Local state is already correct, so
// this no longer needs to be awaited before repainting.
- if (isActive) {
+ if (watching) {
void api.markRead(e.conversationId).catch(() => { /* retried on next view */ })
}
return
diff --git a/tests/window-attention.test.ts b/tests/window-attention.test.ts
new file mode 100644
index 0000000..b61b609
--- /dev/null
+++ b/tests/window-attention.test.ts
@@ -0,0 +1,197 @@
+/**
+ * "Is the user actually looking?" — the question that decides both whether a
+ * desktop toast fires and whether an arriving message is marked read.
+ *
+ * It used to be a private helper in NotificationToasts with no tests at all,
+ * even though every notification in the product goes through it. The read path
+ * asked a different and weaker question — "is this conversation selected?" — so
+ * a window sitting behind a browser marked every arriving message read: no
+ * badge, and `POST /conversations/:id/read` moved the server cursor to NOW(),
+ * which no reload undoes. There is no unread divider in the thread to fall back
+ * on, so the user came back to no sign at all that anything had happened.
+ */
+import assert from 'node:assert/strict'
+import { readFile } from 'node:fs/promises'
+import { describe, it } from 'node:test'
+import { evaluateAttention, type AttentionEnv } from '../src/lib/windowAttention'
+import { isWatchingConversation, type WatchInputs } from '../src/lib/watching'
+
+function env(over: Partial<AttentionEnv> = {}): AttentionEnv {
+ return { visibility: 'visible', electron: false, nativeFocused: true, hasFocus: true, ...over }
+}
+
+describe('evaluateAttention', () => {
+ it('a hidden window is never attentive, whatever else claims otherwise', () => {
+ // Minimized, on another desktop, or a background browser tab. Electron can
+ // still report native focus here, and hasFocus() can still say true.
+ assert.equal(evaluateAttention(env({ visibility: 'hidden' })), false)
+ assert.equal(evaluateAttention(env({ visibility: 'hidden', electron: true, nativeFocused: true })), false)
+ assert.equal(evaluateAttention(env({ visibility: 'hidden', hasFocus: true })), false)
+ })
+
+ it('a visible Electron window behind another app is not attentive', () => {
+ // The everyday case: cumora is on screen, the user is in their browser.
+ // visibilityState is 'visible' and nothing is throttled — only native focus
+ // knows the user is elsewhere.
+ assert.equal(evaluateAttention(env({ electron: true, nativeFocused: false })), false)
+ })
+
+ it('in Electron the main process wins over a stale hasFocus', () => {
+ // document.hasFocus() can return a stale true on macOS. Believing it would
+ // suppress the toast and clear the badge for a window the user cannot see.
+ assert.equal(evaluateAttention(env({ electron: true, nativeFocused: false, hasFocus: true })), false)
+ assert.equal(evaluateAttention(env({ electron: true, nativeFocused: true, hasFocus: false })), true)
+ })
+
+ it('on the web an unfocused window is not attentive', () => {
+ assert.equal(evaluateAttention(env({ electron: false, hasFocus: false })), false)
+ })
+
+ it('assumes the user is present when there is nothing to ask', () => {
+ // No hasFocus() to consult: the alternative is a badge that never clears.
+ assert.equal(evaluateAttention(env({ hasFocus: undefined })), true)
+ assert.equal(evaluateAttention(env({ visibility: undefined, hasFocus: undefined })), true)
+ })
+
+ it('a focused, visible window is attentive on both platforms', () => {
+ assert.equal(evaluateAttention(env()), true)
+ assert.equal(evaluateAttention(env({ electron: true })), true)
+ })
+})
+
+describe('isWatchingConversation', () => {
+ function w(over: Partial<WatchInputs> = {}): WatchInputs {
+ return {
+ conversationId: 'g-1',
+ selectedConversationId: 'g-1',
+ view: 'conversations',
+ mobileStack: 'chat',
+ attentive: true,
+ ...over,
+ }
+ }
+
+ it('the ordinary case: selected, on screen, app in front', () => {
+ assert.equal(isWatchingConversation(w()), true)
+ })
+
+ it('a message for another conversation is never being watched', () => {
+ assert.equal(isWatchingConversation(w({ selectedConversationId: 'g-other' })), false)
+ assert.equal(isWatchingConversation(w({ selectedConversationId: null })), false)
+ })
+
+ it('an app in the background is not watching, however it is navigated', () => {
+ // The everyday case: cumora is on screen behind a browser, socket alive,
+ // messages arriving, nobody reading them.
+ assert.equal(isWatchingConversation(w({ attentive: false })), false)
+ })
+
+ it('desktop is not watching once the view leaves conversations', () => {
+ // DesktopApp mounts views conditionally, so ChatPane is unmounted here —
+ // the thread is not merely unfocused, it is not rendered at all.
+ for (const view of ['boards', 'documents', 'calendar', 'agents', 'me', 'shipping']) {
+ assert.equal(isWatchingConversation(w({ view })), false, `view=${view}`)
+ }
+ })
+
+ it('mobile is not watching from the list or the info overlay', () => {
+ // Swiping back only moves mobileStack; selectedConversationId stays put.
+ assert.equal(isWatchingConversation(w({ mobileStack: 'list' })), false)
+ assert.equal(isWatchingConversation(w({ mobileStack: 'info' })), false)
+ })
+
+ it('needs every condition at once, not just one of them', () => {
+ // Guard against the predicate degrading into "selected" again.
+ assert.equal(isWatchingConversation(w({ attentive: false, view: 'boards' })), false)
+ assert.equal(isWatchingConversation(w({ mobileStack: 'list', attentive: false })), false)
+ })
+})
+
+describe('subscribeWindowAttention', () => {
+ /** Minimal DOM stand-ins: record which events were wired and let us fire them. */
+ function stubDom(hasFocus: () => boolean) {
+ const handlers = new Map<string, Set<() => void>>()
+ const target = {
+ addEventListener(type: string, fn: () => void) {
+ if (!handlers.has(type)) handlers.set(type, new Set())
+ handlers.get(type)!.add(fn)
+ },
+ removeEventListener(type: string, fn: () => void) { handlers.get(type)?.delete(fn) },
+ }
+ const g = globalThis as Record<string, unknown>
+ const prevDoc = g.document
+ const prevWin = g.window
+ g.document = { ...target, visibilityState: 'visible', hasFocus }
+ g.window = target
+ return {
+ handlers,
+ fire(type: string) { for (const fn of handlers.get(type) ?? []) fn() },
+ restore() { g.document = prevDoc; g.window = prevWin },
+ }
+ }
+
+ it('listens for both edges of focus, not just the return', async () => {
+ // Only listening for `focus` would leave a subscriber that never saw
+ // attention drop — so it would never see it come back, and a badge earned
+ // while the window was away would never clear.
+ let focused = true
+ const dom = stubDom(() => focused)
+ try {
+ const mod = await import('../src/lib/windowAttention')
+ const seen: boolean[] = []
+ const off = mod.subscribeWindowAttention((a) => seen.push(a))
+
+ assert.ok(dom.handlers.has('focus'), 'no focus listener')
+ assert.ok(dom.handlers.has('blur'), 'no blur listener — attention can never be observed dropping')
+ assert.ok(dom.handlers.has('visibilitychange'), 'no visibilitychange listener')
+
+ focused = false
+ dom.fire('blur')
+ focused = true
+ dom.fire('focus')
+ assert.deepEqual(seen, [false, true], 'both edges must reach the subscriber')
+
+ off()
+ dom.fire('focus')
+ assert.deepEqual(seen, [false, true], 'unsubscribe did not detach the listeners')
+ } finally {
+ dom.restore()
+ }
+ })
+})
+
+describe('the callers that depend on it', () => {
+ // Both predicates above are pure: every test so far passes just as well
+ // against a build where the read path never calls them. These read the
+ // source, because the defect was never in the predicate — it was in who asked.
+
+ it('an arriving message is only read when the user is watching', async () => {
+ const source = await readFile(new URL('../src/stores/conversations.ts', import.meta.url), 'utf8')
+ const handler = source.slice(source.indexOf("e.type === 'message.new'"))
+ const block = handler.slice(0, handler.indexOf("e.type === 'group.pulled'"))
+
+ assert.match(block, /isWatchingConversation\(/,
+ 'incoming messages are marked read on selection alone again — an off-screen or backgrounded thread will silently clear its own badge')
+ assert.match(block, /isWindowAttentive\(\)/,
+ 'the read decision no longer consults window attention')
+ assert.doesNotMatch(block, /read: isActive/,
+ 'read is being decided by selection rather than by whether the user is watching')
+ })
+
+ it('the badge still clears the moment the user starts watching', async () => {
+ // The other half. Without it a badge earned off screen would sit there
+ // while the user stared straight at the messages.
+ const source = await readFile(new URL('../src/App.tsx', import.meta.url), 'utf8')
+ assert.match(source, /subscribeWindowAttention\(/,
+ 'App no longer tracks attention, so a badge earned off screen can never clear')
+ assert.match(source, /\[convoId, selectedConvoExists, watching\]/,
+ 'the read effect is keyed on selection again — returning to a thread you were already on would not clear its badge')
+ })
+
+ it('desktop toasts still ask the same question', async () => {
+ const source = await readFile(new URL('../src/components/NotificationToasts.tsx', import.meta.url), 'utf8')
+ assert.match(source, /isWindowAttentive\(\)/)
+ assert.match(source, /setNativeAppFocused/,
+ 'the Electron focus bridge no longer feeds the shared cache, so attention is stuck at its default')
+ })
+})