The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Slack attention, wave 1: badges for what's yours, a Threads view, muted read rows (#2434)
0xken1572a220520dc1
diff --git a/backend/integration/superTabFollowedThreads.test.ts b/backend/integration/superTabFollowedThreads.test.tsnew file mode 100644index 000000000..e6a36a367--- /dev/null+++ b/backend/integration/superTabFollowedThreads.test.ts@@ -0,0 +1,481 @@+import { randomUUID } from 'node:crypto'+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import { join } from 'node:path'+import { tmpdir } from 'node:os'+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import { PrismaClient } from '@prisma/client'+import Fastify, { type FastifyInstance } from 'fastify'+import type { AuthUser } from '../src/lib/ssoAuth.js'+import { SuperTabStore } from '../src/superTabs/store.js'+import { superTabRoutes } from '../src/routes/superTabs.js'+import { errorHandler } from '../src/middlewares/errorHandler.js'+import { migrateSwarm } from '../src/superTabs/migration/migrate.js'+import * as parts from '../src/superTabs/parts/index.js'+import { swarmTransaction } from '../src/superTabs/cache.js'+import { guardedWrite } from '../src/superTabs/parts/write.js'+import { SwarmReads } from '../src/superTabs/read/service.js'+import { HostReads } from '../src/superTabs/read/host.js'+import { buddyChatId } from '../src/superTabs/buddies.js'+import { resetInboxReads } from '../src/superTabs/read/inbox.js'+import { MAX_READ_THREADS, resetThreadsReads, THREADS_READS, THREADS_WINDOW_MS } from '../src/superTabs/read/followedThreads.js'+import type { Author, Conversation, SuperTabState } from '../src/superTabs/model.js'+import { THREAD_MARK_CAP, writeThreadFollow, writeThreadMark } from '../src/superTabs/readMarks.js'+import { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'+import { NOW, outsider as outsiderActor, owner as ownerActor, peer as peerActor, swarm } from '../src/superTabs/read/fixture.test-support.js'+import { PROFILE_STAGES, profileEntry, type ProfileEntry } from './bench/profile.js'++// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.+let replica: MongoMemoryReplSet+let db: PrismaClient+let app: FastifyInstance+let store: SuperTabStore+const user = (actor: { userId: string; email: string }): AuthUser => ({ sub: actor.userId, email: actor.email, autonomousEnv: 'prod', role: 'user' })+const [owner, peer, outsider] = [ownerActor, peerActor, outsiderActor].map(user) as [AuthUser, AuthUser, AuthUser]+const ownerTeam: AuthUser = { ...owner, harnessSessionId: 'owner-team-session', harnessSessionKind: 'team' }+const signedIn = (authorization: string | undefined) =>+ authorization === 'Bearer team' ? ownerTeam : [owner, peer, outsider].find(u => `Bearer ${u.sub}` === authorization)+const MIGRATED = NOW - 60_000++beforeAll(async () => {+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })+ const uri = replica.getUri(`swarm_follows_test_${randomUUID().replaceAll('-', '_')}`)+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,+ })+ db = new PrismaClient({ datasources: { db: { url: uri } } })+ for (const each of [owner, peer, outsider]) await db.user.create({ data: { id: each.sub, externalId: `fixture-${each.sub}`, email: each.email, autonomousEnv: 'prod' } })+ await db.machine.create({ data: { machineId: 'host', userId: owner.sub, apiKey: 'fixture-only', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ store = new SuperTabStore(db)+ app = Fastify()+ app.setErrorHandler(errorHandler)+ // External SSO is replaced with fixture accounts; every permission and write below is real.+ app.addHook('onRequest', async (request, reply) => {+ const found = signedIn(request.headers.authorization)+ if (!found) return reply.code(401).send({ success: false })+ request.user = found+ })+ await app.register(superTabRoutes, { store, github: null, reads: new SwarmReads(store), hosts: new HostReads(store) })+ await app.ready()+})+afterAll(async () => {+ await app?.close()+ await db?.$disconnect()+ await replica?.stop()+})++/** A Swarm in parts: a public project ("Web", with a worker on the owner's machine), a project private to its owner+ * ("Secret work"), and peer's Buddy chat. */+async function scene(extra: (s: ReturnType<typeof swarm>) => void = () => {}) {+ const s = swarm(MIGRATED)+ s.join(peerActor)+ s.join(outsiderActor)+ const secret = s.run({ type: 'project.create', name: 'Secret', visibility: 'private', brief: '' }).projectId as string+ const open = s.run({ type: 'project.create', name: 'Open', visibility: 'public', brief: '' }).projectId as string+ const openChat = s.group('Open chat', open)+ const web = s.group('Web')+ const worker = s.add('worker-harness', web, false, ownerActor, 'host', owner.sub)+ s.run({ type: 'work.assign', conversationId: web, agentId: worker })+ const secretGroup = s.group('Secret work', secret)+ let buddyId = s.group('Peer\'s Buddy')+ s.edit(state => {+ const generation = state.people.find(p => p.id === peer.sub)!.generation+ const chat = state.conversations.find(c => c.id === buddyId)!+ buddyId = buddyChatId(chat.projectId ?? 'lead', { id: peer.sub, generation })+ Object.assign(chat, { id: buddyId, kind: 'buddy', leadId: null, agentIds: [], audience: { people: [{ id: peer.sub, generation }] } })+ })+ extra(s)+ const tabId = `tab-${randomUUID()}`+ const state = { ...structuredClone(s.state), id: tabId } as SuperTabState+ await writeLegacySwarm(db, { state, revision: 3 })+ const report = await migrateSwarm(db, tabId, { now: () => MIGRATED })+ if (!report.ok) throw new Error(report.error)+ return { tabId, web, worker, secret, secretGroup, buddyId, open, openChat }+}++const call = async (method: 'GET' | 'POST', url: string, as: AuthUser | 'team' = owner, payload?: unknown) => {+ const response = await app.inject({ method, url, headers: { authorization: `Bearer ${as === 'team' ? 'team' : as.sub}` }, ...(payload === undefined ? {} : { payload: payload as never }) })+ return { status: response.statusCode, body: response.json() as { data: any; error?: { code: string; message: string } }, headers: response.headers }+}+const inbox = (tabId: string, as: AuthUser | 'team' = owner) => call('GET', `/api/super-tabs/${tabId}/inbox`, as)+const threads = (tabId: string, as: AuthUser | 'team' = owner) => call('GET', `/api/super-tabs/${tabId}/threads`, as)+const follow = (tabId: string, conversationId: string, root: string, value: boolean | null, as: AuthUser | 'team' = owner, query = '') =>+ call('POST', `/api/super-tabs/${tabId}/conversations/${conversationId}/threads/${root}/follow${query}`, as, { follow: value })+const markThread = (tabId: string, conversationId: string, root: string, sequence: number, as: AuthUser = owner) =>+ call('POST', `/api/super-tabs/${tabId}/conversations/${conversationId}/threads/${root}/read`, as, { sequence })+const markRead = async (tabId: string, conversationId: string, sequence: number, as: AuthUser) => {+ expect((await call('POST', `/api/super-tabs/${tabId}/conversations/${conversationId}/read`, as, { sequence })).status).toBe(200)+}+const agentAuthor = (id: string): Author => ({ kind: 'agent', id, name: id, membershipGeneration: 'fixture' })+const personAuthor = (u: AuthUser): Author => ({ kind: 'person', id: u.sub, name: u.email, membershipGeneration: 'fixture' })++/** Rows stored as the store stores them: numbered after the chat's newest, the chat's counters moved as numberMessages moves+ * them for rows people read (as superTabInbox.test.ts). */+async function insert(tabId: string, conversationId: string, rows: Array<{ id?: string; text: string; author: Author; thread?: string | null;+ source?: Record<string, unknown>; recipientIds?: string[]; mentions?: string[] }>) {+ const ids: string[] = []+ await swarmTransaction(db, async tx => {+ const current = (await parts.loadActive(tx, tabId, { groupIds: [conversationId] })).groups.find(g => g.key === conversationId)!+ const data = structuredClone(current.data!) as Conversation+ for (const row of rows) {+ const sequence = (data.messageSeq ?? 0) + 1+ const id = row.id ?? `m-${randomUUID()}`+ ids.push(id)+ data.messageSeq = sequence+ if (!row.source?.recipientsOnly) {+ data.lastMessageSequence = sequence+ data.lastActivityAt = new Date().toISOString()+ if (!row.thread || row.thread === id) data.lastMainSequence = sequence+ }+ await tx.superTabMessage.create({ data: { id, tabId, conversationId, sequence, author: row.author as never, text: row.text,+ thread: row.thread === undefined ? id : row.thread, recipientIds: row.recipientIds ?? [], mentions: row.mentions ?? [],+ ...(row.source ? { source: row.source as never } : {}), createdAt: new Date() } })+ }+ await guardedWrite(tx, tabId, { op: 'update', kind: 'group', key: conversationId, seen: current.version, data }, Date.now())+ })+ return ids+}+async function editChat(tabId: string, conversationId: string, edit: (data: Conversation) => void) {+ await swarmTransaction(db, async tx => {+ const current = (await parts.loadActive(tx, tabId, { groupIds: [conversationId] })).groups.find(g => g.key === conversationId)!+ const data = structuredClone(current.data!) as Conversation+ edit(data)+ await guardedWrite(tx, tabId, { op: 'update', kind: 'group', key: conversationId, seen: current.version, data }, Date.now())+ })+}+const sequenceOf = async (id: string) => (await db.superTabMessage.findUniqueOrThrow({ where: { id } })).sequence+const newestIn = async (tabId: string, conversationId: string) =>+ (await db.superTabMessage.findFirstOrThrow({ where: { tabId, conversationId }, orderBy: { sequence: 'desc' } })).sequence+const stored = (tabId: string, threadId: string, as: AuthUser = owner) =>+ db.superTabThreadMark.findMany({ where: { tabId, threadId, personId: as.sub }, select: { sequence: true, follow: true } })+const roots = (list: any[]) => list.map(t => t.root.text)++beforeEach(() => { resetInboxReads(); resetThreadsReads() })++describe('Follow and Unfollow, kept on the person\'s thread mark', () => {+ async function threadScene() {+ const s = await scene()+ const [root] = await insert(s.tabId, s.web, [{ text: 'Web root', author: personAuthor(owner) }])+ const [, last] = await insert(s.tabId, s.web, [{ text: 'Reply 1', author: agentAuthor(s.worker), thread: root }, { text: 'Reply 2', author: agentAuthor(s.worker), thread: root }])+ const [secretRoot] = await insert(s.tabId, s.secretGroup, [{ text: 'Secret root', author: personAuthor(owner) }])+ const [buddyRoot] = await insert(s.tabId, s.buddyId, [{ text: 'Buddy root', author: personAuthor(peer) }])+ const [hiddenRoot] = await insert(s.tabId, s.web, [{ text: 'Hidden root', author: agentAuthor('hidden-agent'), source: { kind: 'note', recipientsOnly: true },+ recipientIds: [s.worker] }])+ // The chat's newest row a person reads: the hidden root moves no counter.+ return { ...s, root: root!, secretRoot: secretRoot!, buddyRoot: buddyRoot!, hiddenRoot: hiddenRoot!, top: await sequenceOf(last!) }+ }++ it('stores Follow, Unfollow and neither for the person alone, answering what it stored', async () => {+ const s = await threadScene()+ expect(await follow(s.tabId, s.web, s.root, true, peer)).toMatchObject({ status: 200, body: { data: { follow: true } } })+ // Written before the person read it anywhere: a mark of 0, which every client reads as none.+ expect(await stored(s.tabId, s.root, peer)).toEqual([{ sequence: 0, follow: true }])+ expect(await stored(s.tabId, s.root, owner)).toEqual([])+ expect((await follow(s.tabId, s.web, s.root, false, peer)).body.data).toEqual({ follow: false })+ expect(await stored(s.tabId, s.root, peer)).toEqual([{ sequence: 0, follow: false }])+ expect((await follow(s.tabId, s.web, s.root, null, peer)).body.data).toEqual({ follow: null })+ expect(await stored(s.tabId, s.root, peer)).toEqual([{ sequence: 0, follow: null }])+ expect(await db.superTabThreadMark.count({ where: { tabId: s.tabId } })).toBe(1)+ // Only true, false or null.+ expect((await call('POST', `/api/super-tabs/${s.tabId}/conversations/${s.web}/threads/${s.root}/follow`, peer, { follow: 'yes' })).status).toBe(400)+ expect((await call('POST', `/api/super-tabs/${s.tabId}/conversations/${s.web}/threads/${s.root}/follow`, peer, {})).status).toBe(400)+ })++ it('keeps the mark when a Follow is written, and the Follow when the mark moves', async () => {+ const s = await threadScene()+ const top = s.top+ await markThread(s.tabId, s.web, s.root, top - 1, peer)+ await follow(s.tabId, s.web, s.root, true, peer)+ expect(await stored(s.tabId, s.root, peer)).toEqual([{ sequence: top - 1, follow: true }])+ await markThread(s.tabId, s.web, s.root, top, peer)+ expect(await stored(s.tabId, s.root, peer)).toEqual([{ sequence: top, follow: true }])+ // The first load still sends marks as numbers, as old clients read them.+ const derived = (await call('GET', `/api/super-tabs/${s.tabId}/parts`, peer)).body.data.derived+ expect(derived.threadMarks).toEqual({ [s.web]: { [s.root]: top } })+ })++ it('settles racing first writes on one row: the highest mark and the Follow both kept', async () => {+ const s = await threadScene()+ const top = s.top+ await Promise.all([follow(s.tabId, s.web, s.root, true, peer), markThread(s.tabId, s.web, s.root, top - 1, peer), follow(s.tabId, s.web, s.root, true, peer),+ markThread(s.tabId, s.web, s.root, top, peer), follow(s.tabId, s.web, s.root, true, peer)])+ expect(await stored(s.tabId, s.root, peer)).toEqual([{ sequence: top, follow: true }])+ })++ it(`counts toward the ${THREAD_MARK_CAP} marks a person keeps, as a read that moves the mark`, async () => {+ const s = await threadScene()+ const write = (threadId: string, at: number) => writeThreadMark(db, { tabId: s.tabId, personId: owner.sub, conversationId: s.web, threadId, sequence: 1, now: at })+ for (let i = 0; i < THREAD_MARK_CAP; i++) await write(`t${i}`, NOW + i)+ // A Follow of t0 moves it, so t1 is now the least recently moved; a Follow of a new thread is one more row past the cap.+ await writeThreadFollow(db, { tabId: s.tabId, personId: owner.sub, conversationId: s.web, threadId: 't0', follow: true, now: NOW + THREAD_MARK_CAP })+ await writeThreadFollow(db, { tabId: s.tabId, personId: owner.sub, conversationId: s.web, threadId: 'followed', follow: true, now: NOW + THREAD_MARK_CAP + 1 })+ const kept = await db.superTabThreadMark.findMany({ where: { tabId: s.tabId, personId: owner.sub }, select: { threadId: true, follow: true, sequence: true } })+ expect(kept).toHaveLength(THREAD_MARK_CAP)+ expect(kept).toEqual(expect.arrayContaining([{ threadId: 't0', follow: true, sequence: 1 }, { threadId: 'followed', follow: true, sequence: 0 }]))+ expect(kept.map(k => k.threadId)).not.toContain('t1')+ }, 60_000)++ it('refuses another project\'s thread, a private chat\'s, another person\'s Buddy chat\'s, a hidden root and an unknown one alike, storing nothing', async () => {+ const s = await threadScene()+ const [reply] = await insert(s.tabId, s.web, [{ text: 'Reply 3', author: agentAuthor(s.worker), thread: s.root }])+ const refused = [+ await follow(s.tabId, s.secretGroup, s.secretRoot, true, peer),+ // The private chat's root named under a conversation the person reads.+ await follow(s.tabId, s.web, s.secretRoot, true, peer),+ await follow(s.tabId, s.buddyId, s.buddyRoot, true, outsider),+ await follow(s.tabId, s.web, s.buddyRoot, true, outsider),+ await follow(s.tabId, s.web, s.hiddenRoot, true, peer),+ // A reply is no thread's root.+ await follow(s.tabId, s.web, reply!, true, peer),+ await follow(s.tabId, s.web, 'no-such-root', true, peer),+ await follow(s.tabId, 'no-such-group', s.root, true, peer),+ ]+ expect(refused.map(r => r.status)).toEqual(refused.map(() => 404))+ expect(new Set(refused.map(r => JSON.stringify(r.body)))).toHaveLength(1)+ expect(JSON.stringify(refused)).not.toMatch(/Secret|Buddy|Hidden/)+ // A Team session, an agent and someone who left are refused too.+ expect((await follow(s.tabId, s.web, s.root, true, 'team')).status).toBe(403)+ expect((await follow(s.tabId, s.web, s.root, true, owner, `?asAgentId=${s.worker}`)).status).toBe(400)+ await store.execute(owner, s.tabId, { operationId: randomUUID(), command: { type: 'member.remove', userId: outsider.sub } })+ expect((await follow(s.tabId, s.web, s.root, true, outsider)).status).toBe(404)+ expect(await db.superTabThreadMark.count({ where: { tabId: s.tabId } })).toBe(0)+ })+})++describe('the inbox honors Follow and Unfollow', () => {+ it('never lists a thread the person unfollowed, though they are in it, and lists it again once they clear that', async () => {+ const s = await scene()+ const [root] = await insert(s.tabId, s.web, [{ text: 'Peer root', author: personAuthor(peer) }])+ await markRead(s.tabId, s.web, await sequenceOf(root!), peer)+ await insert(s.tabId, s.web, [{ text: 'Worker reply', author: agentAuthor(s.worker), thread: root }])+ expect(roots((await inbox(s.tabId, peer)).body.data.threads)).toEqual(['Peer root'])+ await follow(s.tabId, s.web, root!, false, peer)+ expect((await inbox(s.tabId, peer)).body.data.threads).toEqual([])+ await follow(s.tabId, s.web, root!, null, peer)+ expect(roots((await inbox(s.tabId, peer)).body.data.threads)).toEqual(['Peer root'])+ })++ it('lists a thread the person follows though they never wrote or were tagged there, with the same shape', async () => {+ const s = await scene()+ const [root] = await insert(s.tabId, s.web, [{ text: 'Owner root', author: personAuthor(owner) }])+ await markRead(s.tabId, s.web, await sequenceOf(root!), peer)+ await insert(s.tabId, s.web, [{ text: 'Worker reply', author: agentAuthor(s.worker), thread: root }])+ expect((await inbox(s.tabId, peer)).body.data.threads).toEqual([])+ await follow(s.tabId, s.web, root!, true, peer)+ const [thread] = (await inbox(s.tabId, peer)).body.data.threads+ expect(Object.keys(thread).sort()).toEqual(['conversationId', 'lastReplier', 'lastReplyAt', 'lastReplySequence', 'root', 'rootId', 'unreadReplies'])+ expect(thread).toMatchObject({ conversationId: s.web, rootId: root, unreadReplies: 1, lastReplier: { id: s.worker } })+ })+})++describe('a thread reply past the person\'s thread mark, though the chat\'s mark is further on', () => {+ /** Peer's thread in Web with a reply peer read; a later thread-only reply; then a main message peer reads in the chat. With+ * `opened`, peer read the thread to its first reply on some device; with `followOnly`, peer only followed it. */+ async function behindScene(opts: { opened?: boolean; followOnly?: boolean } = {}) {+ const s = await scene()+ const [root] = await insert(s.tabId, s.web, [{ text: 'Peer root', author: personAuthor(peer) }])+ await markRead(s.tabId, s.web, await sequenceOf(root!), peer)+ const [first] = await insert(s.tabId, s.web, [{ text: 'First reply', author: agentAuthor(s.worker), thread: root }])+ if (opts.opened) await markThread(s.tabId, s.web, root!, await sequenceOf(first!), peer)+ if (opts.followOnly) await follow(s.tabId, s.web, root!, true, peer)+ await insert(s.tabId, s.web, [{ text: 'Thread-only reply', author: agentAuthor(s.worker), thread: root }])+ const [main] = await insert(s.tabId, s.web, [{ text: 'Main message', author: personAuthor(owner) }])+ await markRead(s.tabId, s.web, await sequenceOf(main!), peer)+ return { ...s, root: root! }+ }++ it('counts it from the thread\'s own mark: reading the chat\'s main stream never reads a reply only in the thread', async () => {+ const s = await behindScene({ opened: true })+ const [thread] = (await inbox(s.tabId, peer)).body.data.threads+ expect(thread).toMatchObject({ conversationId: s.web, rootId: s.root, unreadReplies: 1 })+ expect(roots((await threads(s.tabId, peer)).body.data.unread)).toEqual(['Peer root'])+ expect((await threads(s.tabId, peer)).body.data.read).toEqual([])+ // Read in the thread, it is gone.+ await markThread(s.tabId, s.web, s.root, await newestIn(s.tabId, s.web), peer)+ expect((await inbox(s.tabId, peer)).body.data.threads).toEqual([])+ })++ it('keeps the chat\'s mark for a thread the person never opened, and a Follow alone is no mark', async () => {+ expect((await inbox((await behindScene()).tabId, peer)).body.data.threads).toEqual([])+ const followed = await behindScene({ followOnly: true })+ expect((await inbox(followed.tabId, peer)).body.data.threads).toEqual([])+ expect(roots((await threads(followed.tabId, peer)).body.data.read)).toEqual(['Peer root'])+ })+})++describe('a person\'s followed threads (GET /threads)', () => {+ /** Web: peer marked the chat read at its roots. "Unread" (peer's, a new reply), "Read" (peer's, read to its end), "Opened" (owner's,+ * peer opened it but is not in it), "Followed" (owner's, peer follows it and read it), "Unfollowed" (peer's, read, unfollowed),+ * "Tagged" (owner's, tags peer in a reply, read). Secret work: owner's "Secret root" with a reply, peer has a mark on it from+ * before (written directly). */+ async function followScene() {+ const s = await scene()+ const [unread, read, opened, followed, unfollowed, tagged] = await insert(s.tabId, s.web, [+ { text: 'Unread', author: personAuthor(peer) }, { text: 'Read', author: personAuthor(peer) }, { text: 'Opened', author: personAuthor(owner) },+ { text: 'Followed', author: personAuthor(owner) }, { text: 'Unfollowed', author: personAuthor(peer) }, { text: 'Tagged', author: personAuthor(owner) }])+ await markRead(s.tabId, s.web, await sequenceOf(tagged!), peer)+ for (const root of [read, opened, followed, unfollowed]) await insert(s.tabId, s.web, [{ text: 'Worker reply', author: agentAuthor(s.worker), thread: root! }])+ await insert(s.tabId, s.web, [{ text: 'Owner tags peer', author: personAuthor(owner), thread: tagged!, mentions: [peer.sub] }])+ for (const root of [read, opened, followed, unfollowed, tagged]) await markThread(s.tabId, s.web, root!, await newestIn(s.tabId, s.web), peer)+ await follow(s.tabId, s.web, followed!, true, peer)+ await follow(s.tabId, s.web, unfollowed!, false, peer)+ await insert(s.tabId, s.web, [{ text: 'New reply', author: agentAuthor(s.worker), thread: unread! }])+ const [secretRoot] = await insert(s.tabId, s.secretGroup, [{ text: 'Secret root', author: personAuthor(owner), mentions: [] }])+ await insert(s.tabId, s.secretGroup, [{ text: 'Secret reply', author: agentAuthor(s.worker), thread: secretRoot }])+ await writeThreadFollow(db, { tabId: s.tabId, personId: peer.sub, conversationId: s.secretGroup, threadId: secretRoot!, follow: true, now: Date.now() })+ return { ...s, unread: unread!, read: read!, opened: opened!, followed: followed!, unfollowed: unfollowed!, tagged: tagged! }+ }++ it('answers the inbox\'s unread threads first, then the read ones the person follows, newest reply first', async () => {+ const s = await followScene()+ const { status, body } = await threads(s.tabId, peer)+ expect(status).toBe(200)+ expect(body.data.unread).toEqual((await inbox(s.tabId, peer)).body.data.threads.map((t: any) => ({ ...t, follow: null })))+ expect(roots(body.data.unread)).toEqual(['Unread'])+ // Never the one they opened but are not in, the one they unfollowed, or the private chat's.+ expect(roots(body.data.read)).toEqual(['Tagged', 'Followed', 'Read'])+ expect(body.data.more).toBe(false)+ expect(JSON.stringify(body.data)).not.toMatch(/Secret|Opened|Unfollowed/)+ const reply = await db.superTabMessage.findFirstOrThrow({ where: { tabId: s.tabId, thread: s.followed, text: 'Worker reply' } })+ const root = await db.superTabMessage.findUniqueOrThrow({ where: { id: s.followed } })+ expect(body.data.read[1]).toEqual({ conversationId: s.web, rootId: s.followed,+ root: { id: s.followed, sequence: root.sequence, author: root.author, text: 'Followed', createdAt: root.createdAt.toISOString(), attachments: 0 },+ replies: 1, lastReplyAt: reply.createdAt.toISOString(), lastReplySequence: reply.sequence, lastReplier: reply.author, follow: true })+ expect(body.data.read.map((t: any) => t.follow)).toEqual([null, true, null])+ // Another reader's follows and marks are their own.+ expect((await threads(s.tabId, outsider)).body.data).toEqual({ unread: [], read: [], more: false })+ })++ it('lists a followed thread once it has a new reply among the unread, with its follow', async () => {+ const s = await followScene()+ await insert(s.tabId, s.web, [{ text: 'Another reply', author: agentAuthor(s.worker), thread: s.followed }])+ const { body } = await threads(s.tabId, peer)+ expect(body.data.unread.map((t: any) => [t.root.text, t.follow])).toEqual([['Followed', true], ['Unread', null]])+ expect(roots(body.data.read)).toEqual(['Tagged', 'Read'])+ })++ it('stops listing a chat\'s threads once the person can no longer read it: removed from a private chat, the project made private, out of the Swarm', async () => {+ const s = await followScene()+ // Out of this chat's audience.+ await editChat(s.tabId, s.web, data => { data.audience = { people: [{ id: owner.sub, generation: 0 }] } })+ expect((await threads(s.tabId, peer)).body.data).toEqual({ unread: [], read: [], more: false })+ await editChat(s.tabId, s.web, data => { delete data.audience })+ expect(roots((await threads(s.tabId, peer)).body.data.read)).toEqual(['Tagged', 'Followed', 'Read'])+ // A project made private without them (one with no agent's terminal in it).+ const [openRoot] = await insert(s.tabId, s.openChat, [{ text: 'Open root', author: personAuthor(peer) }])+ await insert(s.tabId, s.openChat, [{ text: 'Open reply', author: personAuthor(owner), thread: openRoot }])+ await markRead(s.tabId, s.openChat, await newestIn(s.tabId, s.openChat), peer)+ await markThread(s.tabId, s.openChat, openRoot!, await newestIn(s.tabId, s.openChat), peer)+ expect(roots((await threads(s.tabId, peer)).body.data.read)).toEqual(['Open root', 'Tagged', 'Followed', 'Read'])+ await store.execute(owner, s.tabId, { operationId: randomUUID(), command: { type: 'project.sharing', projectId: s.open, visibility: 'private', memberIds: [] } })+ expect(roots((await threads(s.tabId, peer)).body.data.read)).toEqual(['Tagged', 'Followed', 'Read'])+ expect(JSON.stringify((await threads(s.tabId, peer)).body.data)).not.toMatch(/Open/)+ await store.execute(owner, s.tabId, { operationId: randomUUID(), command: { type: 'project.sharing', projectId: s.open, visibility: 'public', memberIds: [] } })+ expect(roots((await threads(s.tabId, peer)).body.data.read)).toEqual(['Open root', 'Tagged', 'Followed', 'Read'])+ // Out of the Swarm: refused as for one that does not exist, naming nothing.+ await store.execute(owner, s.tabId, { operationId: randomUUID(), command: { type: 'member.remove', userId: peer.sub } })+ const left = await threads(s.tabId, peer)+ expect(left.status).toBe(404)+ expect(left.body.data).toBeUndefined()+ expect(JSON.stringify(left.body)).not.toMatch(/Web|Followed|Tagged/)+ })++ it('leaves out an archived chat\'s threads', async () => {+ const s = await followScene()+ await editChat(s.tabId, s.web, data => { data.archived = true })+ expect((await threads(s.tabId, peer)).body.data).toEqual({ unread: [], read: [], more: false })+ })++ it('never lists a thread whose root people cannot read, nor counts or names a reply they cannot read', async () => {+ const s = await followScene()+ const [hiddenRoot] = await insert(s.tabId, s.web, [{ text: 'Hidden root', author: agentAuthor('hidden-agent'), source: { kind: 'note', recipientsOnly: true },+ recipientIds: [s.worker], mentions: [peer.sub] }])+ await insert(s.tabId, s.web, [{ text: 'Reply under a hidden root', author: agentAuthor(s.worker), thread: hiddenRoot, mentions: [peer.sub] },+ { text: 'Hidden reply', author: agentAuthor('hidden-agent'), thread: s.read, source: { kind: 'note', recipientsOnly: true }, recipientIds: [s.worker] }])+ // A mark row for the hidden thread, as no route would write one, and a Follow of it; the chat read past both, so the+ // hidden thread would be a read one.+ await writeThreadFollow(db, { tabId: s.tabId, personId: peer.sub, conversationId: s.web, threadId: hiddenRoot!, follow: true, now: Date.now() })+ await markRead(s.tabId, s.web, await newestIn(s.tabId, s.web), peer)+ const { body } = await threads(s.tabId, peer)+ expect(roots(body.data.read)).toEqual(['Tagged', 'Followed', 'Read'])+ expect(body.data.more).toBe(false)+ expect(body.data.read.find((t: any) => t.rootId === s.read)).toMatchObject({ replies: 1, lastReplier: { id: s.worker } })+ expect(JSON.stringify(body.data)).not.toMatch(/Hidden|hidden-agent/)+ })++ it(`answers the ${MAX_READ_THREADS} read threads with the newest replies and says there are more`, async () => {+ const s = await scene()+ const many = await insert(s.tabId, s.web, Array.from({ length: MAX_READ_THREADS + 5 }, (_, i) => ({ text: `Root ${i}`, author: personAuthor(peer) })))+ await markRead(s.tabId, s.web, await sequenceOf(many.at(-1)!), peer)+ await insert(s.tabId, s.web, many.map(thread => ({ text: 'Reply', author: agentAuthor(s.worker), thread })))+ await markRead(s.tabId, s.web, await newestIn(s.tabId, s.web), peer)+ for (const root of many) await follow(s.tabId, s.web, root, true, peer)+ const { body } = await threads(s.tabId, peer)+ expect(body.data.read).toHaveLength(MAX_READ_THREADS)+ expect(body.data.more).toBe(true)+ })++ it('refuses a Team session and an agent', async () => {+ const s = await followScene()+ const team = await threads(s.tabId, 'team')+ expect(team.status).toBe(403)+ expect(JSON.stringify(team.body)).not.toMatch(/Web|Followed/)+ expect((await call('GET', `/api/super-tabs/${s.tabId}/threads?asAgentId=${s.worker}`)).status).toBe(400)+ expect((await threads(`tab-${randomUUID()}`)).status).toBe(404)+ })++ it(`allows a person ${THREADS_READS} reads of one Swarm's threads per window, then answers 429 with Retry-After`, async () => {+ const s = await followScene()+ vi.useFakeTimers({ toFake: ['Date'] })+ try {+ vi.setSystemTime(Math.ceil(Date.now() / THREADS_WINDOW_MS) * THREADS_WINDOW_MS + 1_000)+ for (let i = 0; i < THREADS_READS; i++) expect((await threads(s.tabId, peer)).status).toBe(200)+ const refused = await threads(s.tabId, peer)+ expect(refused.status).toBe(429)+ expect(refused.headers['retry-after']).toBe('9')+ expect(refused.body.error?.code).toBe('RATE_LIMITED')+ expect(JSON.stringify(refused.body)).not.toMatch(/Web|Followed/)+ // Counted apart from the inbox, per person and per Swarm.+ expect((await inbox(s.tabId, peer)).status).toBe(200)+ expect((await threads(s.tabId, owner)).status).toBe(200)+ vi.setSystemTime(Date.now() + THREADS_WINDOW_MS)+ expect((await threads(s.tabId, peer)).status).toBe(200)+ } finally { vi.useRealTimers() }+ })++ it('reads by index only and examines a bounded number of messages, whatever a thread\'s length', async () => {+ const s = await scene()+ const long = await insert(s.tabId, s.web, Array.from({ length: 70 }, (_, i) => ({ text: `Long root ${i}`, author: personAuthor(peer) })))+ for (let batch = 0; batch < 3; batch++) {+ await insert(s.tabId, s.web, Array.from({ length: 1000 }, (_, i) => ({ text: `Long reply ${batch}.${i}`, author: agentAuthor(s.worker), thread: long[i % 10]! })))+ }+ await insert(s.tabId, s.web, long.slice(10).map(thread => ({ text: 'Reply', author: agentAuthor(s.worker), thread })))+ await markRead(s.tabId, s.web, await newestIn(s.tabId, s.web), peer)+ // Read to their ends; the long threads' marks moved last, so they are among the candidates.+ const top = await newestIn(s.tabId, s.web)+ for (const root of long.toReversed()) await writeThreadMark(db, { tabId: s.tabId, personId: peer.sub, conversationId: s.web, threadId: root, sequence: top, now: Date.now() })+ await threads(s.tabId, peer)+ await db.$runCommandRaw({ profile: 0 })+ await db.$runCommandRaw({ drop: 'system.profile' }).catch(() => {})+ await db.$runCommandRaw({ create: 'system.profile', capped: true, size: 16 * 1024 * 1024 })+ await db.$runCommandRaw({ profile: 2, slowms: 0 })+ let reply: Awaited<ReturnType<typeof threads>>+ try { reply = await threads(s.tabId, peer) } finally { await db.$runCommandRaw({ profile: 0 }) }+ expect(reply.status).toBe(200)+ const rows = (await db.$runCommandRaw({ aggregate: 'system.profile', pipeline: [{ $match: { ns: { $not: { $regex: 'system\\.' } } } }, ...PROFILE_STAGES],+ cursor: {} }) as unknown as { cursor: { firstBatch: ProfileEntry[] } }).cursor.firstBatch.map(profileEntry)+ const messages = rows.filter(r => r.ns.endsWith('.SuperTabMessage'))+ expect(rows.filter(r => r.planSummary === 'COLLSCAN')).toEqual([])+ for (const r of messages) expect(r.planSummary, JSON.stringify(r)).toMatch(/^IXSCAN/)+ // The roots by id, then the candidates' newest rows in one read (60 threads, under CHATS_PER_READ).+ expect(messages.filter(r => r.op !== 'getmore').length).toBeLessThanOrEqual(3)+ // 60 candidate threads at most THREAD_SCAN rows each, never the long threads' 300.+ expect(messages.reduce((n, r) => n + (r.docsExamined ?? 0), 0)).toBeLessThan(60 * 100 + 200)+ expect(reply.body.data.read).toHaveLength(MAX_READ_THREADS)+ expect(reply.body.data.more).toBe(true)+ // A long thread's count stops at what the scan read.+ expect(reply.body.data.read.every((t: any) => t.replies <= 100)).toBe(true)+ }, 120_000)+})diff --git a/backend/integration/superTabNotAvailable.test.ts b/backend/integration/superTabNotAvailable.test.tsindex 0087ccdec..74b4dc98d 100644--- a/backend/integration/superTabNotAvailable.test.ts+++ b/backend/integration/superTabNotAvailable.test.ts@@ -82,6 +82,7 @@ function calls(tab: string, chat: string, project: string) {json('GET', 'GET /api/super-tabs/:tabId/parts', `${t}/parts?asAgentId=${MISSING}`),json('GET', 'GET /api/super-tabs/:tabId/changes', `${t}/changes?cursor=abc`),json('GET', 'GET /api/super-tabs/:tabId/inbox', `${t}/inbox`),+ json('GET', 'GET /api/super-tabs/:tabId/threads', `${t}/threads`),json('POST', 'POST /api/super-tabs/:tabId/commands', `${t}/commands`,{ operationId: op(), command: { type: 'message.send', conversationId: chat, text: 'hello', replyTo: null, recipientIds: [] } }),json('GET', 'GET /api/super-tabs/:tabId/mentions', `${t}/mentions?state=waiting`),@@ -98,6 +99,8 @@ function calls(tab: string, chat: string, project: string) {json('GET', 'GET /api/super-tabs/:tabId/conversations/:conversationId/messages', `${t}/conversations/${chat}/messages`),json('GET', 'GET /api/super-tabs/:tabId/conversations/:conversationId/catch-up', `${t}/conversations/${chat}/catch-up?after=0`),json('POST', 'POST /api/super-tabs/:tabId/conversations/:conversationId/read', `${t}/conversations/${chat}/read`, { sequence: 1 }),+ json('POST', 'POST /api/super-tabs/:tabId/conversations/:conversationId/threads/:threadId/follow', `${t}/conversations/${chat}/threads/${MISSING}/follow`,+ { follow: true }),json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/github', `${t}/projects/${project}/github`),json('POST', 'POST /api/super-tabs/:tabId/projects/:projectId/github/approve', `${t}/projects/${project}/github/approve`, { scope: 'project' }),json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/roles/:roleId', `${t}/projects/${project}/roles/${MISSING}`),diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex d234002f5..6050ded1e 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -3346,7 +3346,12 @@ describe('Lead mentions', () => {expect(rest).toEqual([])expect(mention).toEqual({ id: expect.any(String), projectId: 'lead', projectName: 'Pilot', conversationId: group, conversationTitle: 'Copy review',// The picked tag the text did not say opens it, as the server stores it (mentions.ts withTags).- messageId, leadId: lead, leadName: expect.any(String), text: `@peer ${text}`.slice(0, 200), createdAt: expect.any(String), resolvedAt: null, resolvedBy: null })+ messageId, leadId: lead, leadName: expect.any(String), text: `@peer ${text}`.slice(0, 200), createdAt: expect.any(String), resolvedAt: null, resolvedBy: null,+ threadId: null, messageSequence: expect.any(Number) })+ // Where the tagged message is in its chat, as its page numbers it: Desktop clears the red number once read past it.+ const page = await app.inject({ method: 'GET', url: `/api/super-tabs/${tab}/conversations/${group}/messages`, headers: { authorization: `Bearer ${peer.sub}` } })+ const shown = (page.json().data.messages as Array<{ id: string; sequence: number }>).find(m => m.id === messageId)+ expect(mention!.messageSequence).toBe(shown!.sequence)expect(mention!.leadName).toBe((await waiting(tab, owner)).agents.find(a => a.id === lead)!.displayName)expect(await list(tab, owner, 'waiting')).toEqual([])expect(await list(tab, peer, 'earlier')).toEqual([])@@ -3422,6 +3427,18 @@ describe('Lead mentions', () => {expect((await waiting(tab, peer)).mentionsWaiting).toBe(0)})+ it('names the thread of a tag in a thread reply, never of one also sent to the chat or under a root the person cannot read', async () => {+ const { tab, lead, group, messageId } = await tagged()+ const send = async (text: string, extra: Record<string, unknown> = {}) => (await run(tab, { type: 'message.send', conversationId: group, text,+ replyTo: messageId, recipientIds: [], mentions: [peer.sub], ...extra } as Command)).result.messageId as string+ const inThread = await send('In the thread.'), alsoSent = await send('Also in the chat.', { alsoSend: true })+ const threadOf = async () => Object.fromEntries((await list(tab, peer, 'waiting')).map(m => [m.messageId, m.threadId]))+ expect(await threadOf()).toEqual({ [messageId]: null, [inThread]: messageId, [alsoSent]: null })+ // A root nobody reads (an agent-only notice): its id never leaves, and the tag counts as the chat's.+ await db.superTabMessage.update({ where: { id: messageId }, data: { source: { kind: 'note', recipientsOnly: true }, recipientIds: [lead] } })+ expect((await threadOf())[inThread]).toBeNull()+ })+it('resolves on the person’s reply inside a thread', async () => {const { tab, group, messageId } = await tagged()await run(tab, { type: 'message.send', conversationId: group, text: 'Confirmed.', replyTo: messageId, recipientIds: [] }, peer)diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 55a3cd0d2..2ccef3e69 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1175,7 +1175,11 @@ model SuperTabThreadMark {conversationId String/// The thread's root message id.threadId String+ /// 0 on a row a Follow or Unfollow created before the person read the thread anywhere.sequence Int+ /// The person's own choice for the thread (readMarks.ts writeThreadFollow): true Follow, false Unfollow; unset or null+ /// leaves it to whether they started it, replied in it or were tagged in it. Never cleared by a read mark.+ follow Boolean?updatedAt DateTime/// A person's marks: every one (a first load, the inbox, the cap's count and oldest) or those moved since a change read'sdiff --git a/backend/src/routes/machinesBillingToken.test.ts b/backend/src/routes/machinesBillingToken.test.tsindex a4b855bbf..0e52a2ba5 100644--- a/backend/src/routes/machinesBillingToken.test.ts+++ b/backend/src/routes/machinesBillingToken.test.ts@@ -18,6 +18,10 @@ vi.mock('../services/index.js', () => ({vi.mock('../lib/prisma.js', () => ({ prisma: {}, machineAlive: {} }))vi.mock('../lib/machineAccess.js', () => ({ machinesSharedWith: vi.fn(async () => []) }))vi.mock('../lib/ssoSession.js', () => ({ ssoAccessTokenFor: m.ssoAccessTokenFor }))+// The machine routes reach the Redis bus (lib/bus.ts), which opens its clients as it is imported. With no Redis, their+// connection errors were logged after this short file had finished, and the worker closed with those logs on their way+// ("Closing rpc while onUserConsoleLog was pending", CI on #2434). Nothing here publishes, so no client is opened.+vi.mock('../lib/bus.js', () => ({}))import { machineRoutes } from './machines.js'import { errorHandler } from '../middlewares/errorHandler.js'diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex f34694a58..f8aa7b0fb 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -27,6 +27,7 @@ import { githubTokensFromEnv, type GitHubTokens } from '../github/tokens.js'import { logger } from '../utils/logger.js'import { SwarmReads } from '../superTabs/read/service.js'import { inboxWait, readInbox } from '../superTabs/read/inbox.js'+import { readFollowedThreads, threadsWait } from '../superTabs/read/followedThreads.js'import { HostReads } from '../superTabs/read/host.js'import { UPDATE_REQUIRED } from '../superTabs/read/contract.js'import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../lib/teamSession.js'@@ -68,6 +69,7 @@ const nativeParams = tabParams.extend({ contextId: id })const messageParams = tabParams.extend({ conversationId: id })// A person's own read mark (superTabs/readMarks.ts): no asAgentId, since agents keep none.const readMarkBody = z.object({ sequence: z.number().int().nonnegative().safe() }).strict()+const followBody = z.object({ follow: z.boolean().nullable() }).strict()const threadParams = messageParams.extend({ threadId: id })const noQuery = z.object({}).strict()// The reader's own catch-up (superTabs/catchUp.ts): no asAgentId, since agents read every message as it comes.@@ -126,13 +128,14 @@ const githubStartToken = z.object({ always: z.boolean().optional() }).strict()* access lost (cli superTabs/machines.ts, swarmReads.ts).*/export const NOT_AVAILABLE_ROUTES: ReadonlySet<string> = new Set([- 'GET /api/super-tabs/:tabId/parts', 'GET /api/super-tabs/:tabId/changes', 'GET /api/super-tabs/:tabId/inbox', 'POST /api/super-tabs/:tabId/commands',+ 'GET /api/super-tabs/:tabId/parts', 'GET /api/super-tabs/:tabId/changes', 'GET /api/super-tabs/:tabId/inbox', 'GET /api/super-tabs/:tabId/threads',+ 'POST /api/super-tabs/:tabId/commands','GET /api/super-tabs/:tabId/mentions', 'GET /api/super-tabs/:tabId/decisions', 'GET /api/super-tabs/:tabId/leaderboard','GET /api/super-tabs/:tabId/sharing', 'POST /api/super-tabs/:tabId/sharing', 'GET /api/super-tabs/:tabId/routing-policy','GET /api/super-tabs/:tabId/groups', 'GET /api/super-tabs/:tabId/groups/:conversationId','POST /api/super-tabs/:tabId/join', 'POST /api/super-tabs/:tabId/join/preview', 'POST /api/super-tabs/:tabId/native','GET /api/super-tabs/:tabId/conversations/:conversationId/messages', 'GET /api/super-tabs/:tabId/conversations/:conversationId/catch-up',- 'POST /api/super-tabs/:tabId/conversations/:conversationId/read',+ 'POST /api/super-tabs/:tabId/conversations/:conversationId/read', 'POST /api/super-tabs/:tabId/conversations/:conversationId/threads/:threadId/follow','GET /api/super-tabs/:tabId/projects/:projectId/github', 'POST /api/super-tabs/:tabId/projects/:projectId/github/approve','GET /api/super-tabs/:tabId/projects/:projectId/ci-load','GET /api/super-tabs/:tabId/projects/:projectId/roles/:roleId', 'GET /api/super-tabs/:tabId/route-decisions/:decisionId',@@ -461,6 +464,13 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suif (wait) return sendError(reply.header('Retry-After', String(wait)), 'Too many inbox reads. Try again in a moment.', 'RATE_LIMITED', 429)return respond(reply, () => readInbox(store, req.user!, req.params.tabId))})+ // A person's followed threads, unread first (read/followedThreads.ts): Desktop's Threads view, read as the inbox is.+ app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof noQuery> }>('/api/super-tabs/:tabId/threads',+ { preHandler: [validateParams(tabParams), validateQuery(noQuery)] }, async (req, reply) => {+ const wait = await threadsWait(req.user!, req.params.tabId)+ if (wait) return sendError(reply.header('Retry-After', String(wait)), 'Too many thread reads. Try again in a moment.', 'RATE_LIMITED', 429)+ return respond(reply, () => readFollowedThreads(store, req.user!, req.params.tabId))+ })app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof leaderboardQuery> }>('/api/super-tabs/:tabId/leaderboard',{ preHandler: [validateParams(tabParams), validateQuery(leaderboardQuery)] },(req, reply) => respond(reply, () => reads.leaderboard(req.user!, req.params.tabId, req.query.projectId, req.query.week)))@@ -566,6 +576,10 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suapp.post<{ Params: z.infer<typeof threadParams>; Querystring: z.infer<typeof noQuery>; Body: z.infer<typeof readMarkBody> }>('/api/super-tabs/:tabId/conversations/:conversationId/threads/:threadId/read',{ preHandler: [validateParams(threadParams), validateQuery(noQuery), validateBody(readMarkBody)] },(req, reply) => respond(reply, () => reads.markThreadRead(req.user!, req.params.tabId, req.params.conversationId, req.params.threadId, req.body.sequence)))+ // A person's own Follow or Unfollow of a thread, kept on its thread mark (superTabs/readMarks.ts writeThreadFollow); null clears it.+ app.post<{ Params: z.infer<typeof threadParams>; Querystring: z.infer<typeof noQuery>; Body: z.infer<typeof followBody> }>('/api/super-tabs/:tabId/conversations/:conversationId/threads/:threadId/follow',+ { preHandler: [validateParams(threadParams), validateQuery(noQuery), validateBody(followBody)] },+ (req, reply) => respond(reply, () => reads.followThread(req.user!, req.params.tabId, req.params.conversationId, req.params.threadId, req.body.follow)))app.get<{ Params: z.infer<typeof messageParams>; Querystring: z.infer<typeof catchUpQuery> }>('/api/super-tabs/:tabId/conversations/:conversationId/catch-up',{ preHandler: [validateParams(messageParams), validateQuery(catchUpQuery)] },(req, reply) => respond(reply, () => store.catchUp(req.user!, req.params.tabId, req.params.conversationId, req.query.after)))diff --git a/backend/src/superTabs/mentions.ts b/backend/src/superTabs/mentions.tsindex b86bda74b..4ecbebd0a 100644--- a/backend/src/superTabs/mentions.ts+++ b/backend/src/superTabs/mentions.ts@@ -4,9 +4,10 @@import { createHash } from 'node:crypto'import type { Prisma, PrismaClient } from '@prisma/client'import { ensureIndex } from '../lib/db/indexes.js'-import { activeWork, fail, isLeads, person, stableId, type Actor, type Conversation, type MessageDraft, type SuperTabState } from './model.js'+import { activeWork, agentOnly, fail, isLeads, person, stableId, type Actor, type Conversation, type MessageDraft, type SuperTabState } from './model.js'import { canReadGroup, groupProject, projectAgent, projectOf } from './projects.js'-import { groupsBy } from './parts/indexed.js'+import { groupsBy, readBy } from './parts/indexed.js'+import { deliveredCopies } from './pageReads.js'import { usernameOf } from './usernames.js'type Tx = Prisma.TransactionClient@@ -252,7 +253,8 @@ export function mentionsDigest(ids: string[]): string {export async function listMentions(tx: Tx, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>, now: number, open: boolean) {const tagged = await readable(tx, tabId, state, actor, now, open)const messages = tagged.length ? await tx.superTabMessage.findMany({ where: { tabId, id: { in: tagged.map(t => t.row.messageId) } },- select: { id: true, text: true, author: true } }) : []+ select: { id: true, text: true, author: true, conversationId: true, thread: true, alsoInChat: true, sequence: true } }) : []+ const threads = await threadsOf(tx, tabId, messages)return tagged.map(({ row, group }) => {const message = messages.find(m => m.id === row.messageId)const author = message?.author as { kind?: string; name?: string; displayName?: string } | undefined@@ -261,6 +263,25 @@ export async function listMentions(tx: Tx, tabId: string, state: SuperTabState,return { id: row.id, projectId: row.projectId, projectName: projectOf(state, group.projectId ?? 'lead').name,conversationId: row.conversationId, conversationTitle: group.title, messageId: row.messageId,leadId: row.authorAgentId, leadName: authorName, text: (message?.text ?? '').slice(0, 200),- createdAt: row.createdAt, resolvedAt: row.resolvedAt, resolvedBy: row.resolvedBy }+ createdAt: row.createdAt, resolvedAt: row.resolvedAt, resolvedBy: row.resolvedBy, threadId: message ? threads.get(message.id) ?? null : null,+ // Where the tagged message is in its chat: Desktop clears its red number once the reader has read past it (Slack).+ messageSequence: message?.sequence ?? null }})}++/** For each tagged message that is a thread reply only (not also sent to the chat), its thread's root: the tag belongs to the+ * thread, not the chat's main stream (Desktop counts it on Threads, as Slack does). Only a root the person may read, in the+ * tag's own conversation, roots its own thread: an agent-only or delivered-copy root reads as none, so the tag counts as the+ * chat's and no root id they cannot open leaves here. The roots by id in one read. */+async function threadsOf(tx: Tx, tabId: string, messages: Array<{ id: string; conversationId: string; thread: string | null; alsoInChat: boolean | null }>):+ Promise<Map<string, string>> {+ const replies = messages.filter(m => m.thread && m.thread !== m.id && m.alsoInChat !== true)+ if (!replies.length) return new Map()+ const found = await readBy(tx, 'SuperTabMessage', 'id', [{ $match: { _id: { $in: [...new Set(replies.map(m => m.thread!))] }, tabId } },+ { $project: { conversationId: 1, thread: 1, source: 1, recipientIds: 1 } }])+ const roots = found.map(r => ({ id: r._id as string, conversationId: r.conversationId as string, thread: r.thread, source: r.source ?? null,+ recipientIds: (r.recipientIds as string[] | undefined) ?? [] })).filter(r => r.thread === r.id && !agentOnly(r.source, r.recipientIds))+ const copies = await deliveredCopies(tx, tabId, roots)+ const shown = new Map(roots.filter(r => !copies.has(r.id)).map(r => [r.id, r.conversationId]))+ return new Map(replies.filter(m => shown.get(m.thread!) === m.conversationId).map(m => [m.id, m.thread!]))+}diff --git a/backend/src/superTabs/read/followedThreads.ts b/backend/src/superTabs/read/followedThreads.tsnew file mode 100644index 000000000..be096fcf3--- /dev/null+++ b/backend/src/superTabs/read/followedThreads.ts@@ -0,0 +1,110 @@+/**+ * A person's followed threads in one Swarm (Desktop's Threads view, as Slack's): those with replies they have not read, exactly+ * the inbox's threads (inbox.ts), then those they follow and have read, newest reply first. Both honor the person's own Follow+ * and Unfollow (readMarks.ts writeThreadFollow): an unfollowed thread is never listed, a followed one is as if they were in it.+ *+ * A read thread is listed only from the person's thread mark rows (a thread they opened on some device, or followed), in chats+ * they read now (the inbox's chats: active, unarchived, the messages read's check), most recently moved first, at most+ * READ_CANDIDATES. One is listed when they follow it, or started it, replied in it or were tagged in it (root or reply), and it+ * has a reply. Rows are those a page shows a person (inbox.ts readable): never an agent-only notice or a delivered copy.+ *+ * Cost: the inbox's reads (without the chats' latest messages); the candidates' roots by id in one read; each candidate thread's+ * newest THREAD_SCAN rows by the thread index, CHATS_PER_READ threads per read (inbox.ts perRange). `replies` counts what that+ * scan read, so a longer thread says THREAD_SCAN at most. The route allows a person THREADS_READS per THREADS_WINDOW_MS in each+ * Swarm, counted by every pod together, as the inbox's.+ */+import type { AuthUser } from '../../lib/ssoAuth.js'+import { createRateLimiter } from '../../lib/rateLimit.js'+import type { Author } from '../model.js'+import type { ThreadReply } from '../pageReads.js'+import { threadSummaries } from '../threads.js'+import { readBy } from '../parts/indexed.js'+import type { SuperTabStore } from '../store.js'+import { FIELDS, inboxRead, INBOX_READS, INBOX_WINDOW_MS, isReply, MEMBER_SCAN, newestFirst, perRange, preview, readable, row, SCAN_FIELDS, threadKey,+ type InboxMessage, type InboxThread, type Row } from './inbox.js'++/** Read threads answered, newest reply first. */+export const MAX_READ_THREADS = 30+/** Thread mark rows checked for read threads, most recently moved first: room for those the person turns out not to be in. */+export const READ_CANDIDATES = 2 * MAX_READ_THREADS+/** Rows read per candidate thread, newest first. */+export const THREAD_SCAN = MEMBER_SCAN+export const THREADS_READS = INBOX_READS+export const THREADS_WINDOW_MS = INBOX_WINDOW_MS++export interface FollowedThread {+ conversationId: string+ rootId: string+ root: InboxMessage+ /** Replies the person reads, of the thread's newest THREAD_SCAN rows. */+ replies: number+ lastReplyAt: string+ lastReplySequence: number+ /** The newest reply's author who can still read the chat, as thread summaries name them; null when none can. */+ lastReplier: Author | null+ /** The person's own choice: true Follow, null none (a followed read thread is never false). */+ follow: boolean | null+}+export interface FollowedThreads { unread: Array<InboxThread & { follow: boolean | null }>; read: FollowedThread[]; more: boolean }++export async function readFollowedThreads(store: SuperTabStore, user: AuthUser, tabId: string): Promise<FollowedThreads> {+ const db = store.db, personId = user.sub+ const { inbox, state, chats, marks, threadRows } = await inboxRead(store, user, tabId, { latest: false })+ const follows = new Map(threadRows.map(r => [threadKey(r.conversationId, r.threadId), r]))+ const unread = inbox.threads.map(t => ({ ...t, follow: follows.get(threadKey(t.conversationId, t.rootId))?.follow ?? null }))+ const listed = new Set(unread.map(t => threadKey(t.conversationId, t.rootId)))+ const groups = new Map(chats.map(g => [g.id, g]))+ const eligible = threadRows.filter(r => r.follow !== false && groups.has(r.conversationId) && !listed.has(threadKey(r.conversationId, r.threadId)))+ const candidates = eligible.slice(0, READ_CANDIDATES)+ let more = inbox.more || eligible.length > READ_CANDIDATES+ if (!candidates.length) return { unread, read: [], more }+ // Every root by its id, in one read; a root counts only in the chat its mark names, and only one the person reads.+ const found = (await readBy(db, 'SuperTabMessage', 'id', [{ $match: { _id: { $in: candidates.map(c => c.threadId) }, tabId } },+ { $project: { ...FIELDS, conversationId: 1 } }])).map(row)+ const roots = new Map((await readable(db, tabId, found.filter(m => !isReply(m)))).map(m => [threadKey(m.conversationId, m.id), m]))+ const withRoot = candidates.filter(c => roots.has(threadKey(c.conversationId, c.threadId)))+ if (!withRoot.length) return { unread, read: [], more }+ // Each thread's newest rows, the root among them in a short thread, by its thread index range.+ const scanned = await perRange(db, withRoot.map(c => [{ $match: { tabId, conversationId: c.conversationId, thread: c.threadId } },+ { $sort: { sequence: -1 } }, { $limit: THREAD_SCAN }, { $project: { ...SCAN_FIELDS, conversationId: 1 } }]))+ const byThread = new Map<string, Row[]>()+ for (const m of await readable(db, tabId, scanned.filter(isReply))) {+ const key = threadKey(m.conversationId, m.thread!)+ byThread.set(key, [...byThread.get(key) ?? [], m])+ }+ const own = (a: Pick<Author, 'kind' | 'id'>) => a.kind === 'person' && a.id === personId+ const inIt = (m: Row) => own(m.author) || m.mentions.includes(personId)+ const read: Array<FollowedThread & { at: number }> = []+ for (const c of withRoot) {+ const key = threadKey(c.conversationId, c.threadId), root = roots.get(key)!+ // Newest first, as the scan reads them.+ const replies = byThread.get(key) ?? []+ const newest = replies[0]+ if (!newest || !(c.follow === true || inIt(root) || replies.some(inIt))) continue+ // Unread by the inbox's rule but past its caps: it is not a read thread, and the inbox says there are more. A thread mark+ // counts from itself, even behind the chat's (inbox.ts behindMarks); a Follow alone (0) is none.+ const mark = marks.get(c.conversationId) ?? 0+ const seen = Math.max(c.sequence > 0 ? c.sequence : mark, replies.find(m => own(m.author))?.sequence ?? 0)+ if (mark > 0 && !own(newest.author) && replies.some(m => !own(m.author) && m.sequence > seen)) { more = true; continue }+ // Named as a page's thread summary names them: only authors who can still read the chat (threads.ts).+ const rows: ThreadReply[] = [root, ...replies.toReversed()].map(m => ({ thread: c.threadId, id: m.id, author: m.author, mentions: m.mentions,+ sequence: m.sequence, createdAt: m.createdAt, agentOnly: false, routing: false }))+ const [summary] = threadSummaries(state, groups.get(c.conversationId)!, rows)+ if (!summary) continue+ read.push({ conversationId: c.conversationId, rootId: root.id, root: preview(root), replies: summary.replies, lastReplyAt: summary.lastAt.toISOString(),+ lastReplySequence: summary.lastSequence, lastReplier: summary.authors[0] ?? null, follow: c.follow, at: summary.lastAt.getTime() })+ }+ read.sort((a, b) => newestFirst({ at: a.at, id: a.rootId }, { at: b.at, id: b.rootId }))+ if (read.length > MAX_READ_THREADS) more = true+ return { unread, read: read.slice(0, MAX_READ_THREADS).map(({ at: _at, ...thread }) => thread), more }+}++const threadsReads = createRateLimiter('swarm-threads', THREADS_WINDOW_MS, THREADS_READS)++/** Seconds a person must wait before reading this Swarm's followed threads again, or 0 when they may now (as inboxWait). */+export async function threadsWait(user: AuthUser, tabId: string, now = Date.now()): Promise<number> {+ if (await threadsReads.allows(`${user.sub}:${tabId}`, now)) return 0+ return Math.max(1, Math.ceil((THREADS_WINDOW_MS - now % THREADS_WINDOW_MS) / 1000))+}+/** Test seam: forget this process's counts. */+export const resetThreadsReads = () => threadsReads.reset()diff --git a/backend/src/superTabs/read/inbox.ts b/backend/src/superTabs/read/inbox.tsindex 72f54ae0d..c3c861776 100644--- a/backend/src/superTabs/read/inbox.ts+++ b/backend/src/superTabs/read/inbox.ts@@ -7,13 +7,16 @@* A thread is unread as Desktop marks it (desktop super_tabs/controller.dart threadUnread): the person started it, replied in* it or was tagged in it; its newest reply is someone else's; and it has replies by others after both the person's read mark* on the chat and their own newest reply there. A chat they never marked read counts as read, as Desktop opens it at its end.- * A thread the person read on any device (their thread mark, readMarks.ts) counts only replies past that mark too.+ * A thread the person read on any device (their thread mark, readMarks.ts) counts only replies past that mark too, and only that+ * mark when it is behind the chat's: reading the chat's main stream never reads a reply only in a thread (behindMarks). Their own+ * choice on that row overrides being in it: a thread they unfollowed is never listed, one they follow is as if they were in it.** Cost: every message read is bounded by an index range and a limit: the newest UNREAD_SCAN rows past the mark in at most- * THREAD_CHATS chats; the roots of the newest CANDIDATE_THREADS threads; MEMBER_SCAN rows before the mark of a thread whose- * newer rows do not show the person in it; one row (LATEST_SCAN for an older chat) at each of LATEST_CHATS chats' newest main- * message. Text is cut to PREVIEW_CHARS by the database. `more` says a cap was reached. The route allows a person- * INBOX_READS per INBOX_WINDOW_MS in each Swarm, counted by every pod together.+ * THREAD_CHATS chats; the newest UNREAD_SCAN rows past their own mark in at most BEHIND_THREADS threads; the roots of the+ * newest CANDIDATE_THREADS threads; MEMBER_SCAN rows before the mark of a thread whose newer rows do not show the person in it;+ * one row (LATEST_SCAN for an older chat) at each of LATEST_CHATS chats' newest main message. Text is cut to PREVIEW_CHARS by+ * the database. `more` says a cap was reached. The route allows a person INBOX_READS per INBOX_WINDOW_MS in each Swarm,+ * counted by every pod together.*/import type { Prisma, PrismaClient } from '@prisma/client'import type { AuthUser } from '../../lib/ssoAuth.js'@@ -23,7 +26,7 @@ import { agentOnly, author, fail, SuperTabError, type Actor, type Author, type Cimport { readConversation } from '../projects.js'import { deliveredCopies, type ThreadReply } from '../pageReads.js'import { threadSummaries } from '../threads.js'-import { readMarks, readThreadMarks } from '../readMarks.js'+import { readMarks, readThreadMarkRows, type ThreadMarkRow } from '../readMarks.js'import { readBy } from '../parts/indexed.js'import { ms } from '../parts/light.js'import type { SuperTabStore } from '../store.js'@@ -64,29 +67,29 @@ export interface InboxThread {export interface InboxLatest { conversationId: string; message: InboxMessage }export interface Inbox { threads: InboxThread[]; latest: InboxLatest[]; more: boolean }-interface Row { id: string; conversationId: string; sequence: number; author: Author; text: string; createdAt: Date; attachments: number; thread: string | null+export interface Row { id: string; conversationId: string; sequence: number; author: Author; text: string; createdAt: Date; attachments: number; thread: string | nullalsoInChat: boolean; mentions: string[]; source: unknown; recipientIds: string[] }/** A preview's fields, its text cut by the database so a long message never leaves it whole. */-const FIELDS = { sequence: 1, author: 1, text: { $substrCP: [{ $ifNull: ['$text', ''] }, 0, PREVIEW_CHARS] }, createdAt: 1, attachments: { $size: { $ifNull: ['$attachments', []] } },+export const FIELDS = { sequence: 1, author: 1, text: { $substrCP: [{ $ifNull: ['$text', ''] }, 0, PREVIEW_CHARS] }, createdAt: 1, attachments: { $size: { $ifNull: ['$attachments', []] } },thread: 1, alsoInChat: 1, mentions: 1, source: 1, recipientIds: 1 }/** A scan for unread replies: what a reply is counted, named and placed by, never its text. */-const SCAN_FIELDS = { sequence: 1, author: 1, createdAt: 1, thread: 1, mentions: 1, source: 1, recipientIds: 1 }-const row = (raw: Record<string, unknown>): Row => ({ id: raw._id as string, conversationId: raw.conversationId as string, sequence: raw.sequence as number, author: raw.author as Author,+export const SCAN_FIELDS = { sequence: 1, author: 1, createdAt: 1, thread: 1, mentions: 1, source: 1, recipientIds: 1 }+export const row = (raw: Record<string, unknown>): Row => ({ id: raw._id as string, conversationId: raw.conversationId as string, sequence: raw.sequence as number, author: raw.author as Author,text: (raw.text ?? '') as string, createdAt: new Date(ms(raw.createdAt)), attachments: typeof raw.attachments === 'number' ? raw.attachments : 0,thread: (raw.thread ?? null) as string | null, alsoInChat: raw.alsoInChat === true, mentions: (raw.mentions ?? []) as string[], source: raw.source ?? null,recipientIds: (raw.recipientIds ?? []) as string[] })-const preview = (m: Row): InboxMessage => ({ id: m.id, sequence: m.sequence, author: m.author, text: m.text,+export const preview = (m: Row): InboxMessage => ({ id: m.id, sequence: m.sequence, author: m.author, text: m.text,createdAt: m.createdAt.toISOString(), attachments: m.attachments })/** A thread reply: in a thread whose root is another row. */-const isReply = (m: Row) => !!m.thread && m.thread !== m.id+export const isReply = (m: Row) => !!m.thread && m.thread !== m.id/** A row of the chat's main stream (parts/commit.ts numberMessages): a top-level message, or a reply also sent to the chat. */const isMain = (m: Row) => !isReply(m) || m.alsoInChat-const threadKey = (conversationId: string, root: string) => `${conversationId}\u0000${root}`-const newestFirst = (a: { at: number; id: string }, b: { at: number; id: string }) => b.at - a.at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)+export const threadKey = (conversationId: string, root: string) => `${conversationId}\u0000${root}`+export const newestFirst = (a: { at: number; id: string }, b: { at: number; id: string }) => b.at - a.at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)const activity = (g: Conversation) => Date.parse(g.lastActivityAt ?? '') || 0/** `rows` by `key`, each list in the rows' order. */-function groupBy(rows: Row[], key: (m: Row) => string): Map<string, Row[]> {+export function groupBy(rows: Row[], key: (m: Row) => string): Map<string, Row[]> {const groups = new Map<string, Row[]>()for (const m of rows) {const group = groups.get(key(m))@@ -98,7 +101,7 @@ function groupBy(rows: Row[], key: (m: Row) => string): Map<string, Row[]> {/** The rows of `rows` a person reads, as a page filters them for a person (store.ts messages, readsRow): no agent-only notice,* and no task chat copy of a Lead's notice that reached the Lead (pageReads.ts deliveredCopies). */-async function readable(db: PrismaClient, tabId: string, rows: Row[]): Promise<Row[]> {+export async function readable(db: PrismaClient, tabId: string, rows: Row[]): Promise<Row[]> {const shown = rows.filter(m => !agentOnly(m.source, m.recipientIds))const copies = shown.length ? await deliveredCopies(db, tabId, shown) : new Set<string>()return shown.filter(m => !copies.has(m.id))@@ -123,7 +126,7 @@ export const CHATS_PER_READ = 100/** Runs each range's own pipeline inside one aggregate per CHATS_PER_READ ranges ($unionWith), so the reads stay few whatever* the chat count, and each range's rows are still bounded by its own index range and limit: one $in over every chat could not* bound each by its own read mark, and would walk a busy chat's history for a chat never opened. */-async function perRange(db: PrismaClient, pipelines: Prisma.InputJsonValue[][]): Promise<Row[]> {+export async function perRange(db: PrismaClient, pipelines: Prisma.InputJsonValue[][]): Promise<Row[]> {const rows: Row[] = []for (let i = 0; i < pipelines.length; i += CHATS_PER_READ) {const [first, ...rest] = pipelines.slice(i, i + CHATS_PER_READ)@@ -162,31 +165,57 @@ async function latestIn(db: PrismaClient, tabId: string, chats: Conversation[]):interface Candidate { conversationId: string; root: string; mark: number; replies: Row[]; unread: number; member: boolean; at: number; id: string }-/** The threads of `chats` the person has unread replies in (see the file's comment), from each chat's newest UNREAD_SCAN rows- * past their mark. */-async function threadsIn(db: PrismaClient, tabId: string, state: SuperTabState, chats: Conversation[], personId: string, marks: Map<string, number>,- threadMarks: Map<string, Map<string, number>>): Promise<{ threads: InboxThread[]; more: boolean }> {- if (!chats.length) return { threads: [], more: false }+/** Threads read behind their chat's mark whose rows past their own mark are read, most recently moved mark first. */+export const BEHIND_THREADS = 50++/** The thread marks behind their chat's mark, in a chat with rows past them, most recently moved first: a thread opened, then+ * the chat read further on. Reading the chat's main stream never reads a reply only in the thread, so those count from the+ * thread's own mark (as Slack). A row a Follow alone wrote (sequence 0) is no mark; an unfollowed thread is never listed. */+function behindMarks(chats: Conversation[], marks: Map<string, number>, threadRows: ThreadMarkRow[]): ThreadMarkRow[] {+ const groups = new Map(chats.map(g => [g.id, g]))+ return threadRows.filter(r => {+ const group = groups.get(r.conversationId)+ return group && r.sequence > 0 && r.follow !== false && r.sequence < (marks.get(r.conversationId) ?? 0) && group.lastMessageSequence > r.sequence+ })+}++/** The threads the person has unread replies in (see the file's comment): from each of `chats`' newest UNREAD_SCAN rows past+ * their mark, and from each thread whose own mark is behind its chat's (behindMarks: at most BEHIND_THREADS, of `readable`+ * chats) its newest UNREAD_SCAN rows past that mark, by the thread index. */+async function threadsIn(db: PrismaClient, tabId: string, state: SuperTabState, chats: Conversation[], readableChats: Conversation[], personId: string,+ marks: Map<string, number>, threadRows: ThreadMarkRow[]): Promise<{ threads: InboxThread[]; more: boolean }> {+ const behind = behindMarks(readableChats, marks, threadRows)+ if (!chats.length && !behind.length) return { threads: [], more: false }+ const held = new Map(threadRows.map(r => [threadKey(r.conversationId, r.threadId), r]))const own = (a: Pick<Author, 'kind' | 'id'>) => a.kind === 'person' && a.id === personIdconst inIt = (m: Row) => own(m.author) || m.mentions.includes(personId)- const scanned = await perRange(db, chats.map(g => newestIn(tabId, g.id, { $gt: marks.get(g.id)! }, UNREAD_SCAN + 1, SCAN_FIELDS)))+ const lagging = behind.slice(0, BEHIND_THREADS)+ const [scanned, past] = await Promise.all([perRange(db, chats.map(g => newestIn(tabId, g.id, { $gt: marks.get(g.id)! }, UNREAD_SCAN + 1, SCAN_FIELDS))),+ perRange(db, lagging.map(r => [{ $match: { tabId, conversationId: r.conversationId, thread: r.threadId, sequence: { $gt: r.sequence } } },+ { $sort: { sequence: -1 } }, { $limit: UNREAD_SCAN + 1 }, { $project: { ...SCAN_FIELDS, conversationId: 1 } }]))])const byChat = groupBy(scanned, m => m.conversationId)- // A chat whose newest UNREAD_SCAN rows do not reach its mark: older unread replies are not counted.- let more = [...byChat.values()].some(rows => rows.length > UNREAD_SCAN)- const replies = await readable(db, tabId, [...byChat.values()].flatMap(rows => rows.slice(0, UNREAD_SCAN)).filter(isReply))- // Newest first within each thread, as the scan reads them.- const byThread = groupBy(replies, m => threadKey(m.conversationId, m.thread!))+ const pastByThread = groupBy(past, m => threadKey(m.conversationId, m.thread!))+ // A chat or thread whose newest UNREAD_SCAN rows do not reach its mark: older unread replies are not counted.+ let more = behind.length > BEHIND_THREADS || [...byChat.values(), ...pastByThread.values()].some(rows => rows.length > UNREAD_SCAN)+ // Each row once, though both scans read it.+ const rowsOf = [...byChat.values(), ...pastByThread.values()].flatMap(rows => rows.slice(0, UNREAD_SCAN)).filter(isReply)+ const replies = await readable(db, tabId, [...new Map(rowsOf.map(m => [m.id, m])).values()])+ // Newest first within each thread.+ const byThread = groupBy(replies.sort((a, b) => b.sequence - a.sequence), m => threadKey(m.conversationId, m.thread!))+ const behindKeys = new Set(lagging.map(r => threadKey(r.conversationId, r.threadId)))const candidates: Candidate[] = []- for (const rows of byThread.values()) {+ for (const [key, rows] of byThread) {const newest = rows[0]!- // The person answered last: nothing in it waits for them.- if (own(newest.author)) continue+ const mark = held.get(key)+ // The person answered last: nothing in it waits for them. Nor in a thread they unfollowed, wherever they are in it.+ if (own(newest.author) || mark?.follow === false) continue// Read through the later of their own newest reply and their mark of this thread from any device.- const seen = Math.max(rows.find(m => own(m.author))?.sequence ?? 0, threadMarks.get(newest.conversationId)?.get(newest.thread!) ?? 0)+ const seen = Math.max(rows.find(m => own(m.author))?.sequence ?? 0, mark?.sequence ?? 0)const unread = rows.filter(m => !own(m.author) && m.sequence > seen).lengthif (!unread) continue- candidates.push({ conversationId: newest.conversationId, root: newest.thread!, mark: marks.get(newest.conversationId)!, replies: rows, unread,- member: rows.some(inIt), at: newest.createdAt.getTime(), id: newest.id })+ // A thread read behind its chat's mark: what is before its own mark was looked at for the person, not the chat's.+ candidates.push({ conversationId: newest.conversationId, root: newest.thread!, mark: behindKeys.has(key) ? mark!.sequence : marks.get(newest.conversationId)!,+ replies: rows, unread, member: mark?.follow === true || rows.some(inIt), at: newest.createdAt.getTime(), id: newest.id })}candidates.sort(newestFirst)if (candidates.length > CANDIDATE_THREADS) more = true@@ -208,7 +237,7 @@ async function threadsIn(db: PrismaClient, tabId: string, state: SuperTabState,const members = new Set((await readable(db, tabId, named)).map(m => threadKey(m.conversationId, m.thread!)))for (const c of unknown) if (members.has(threadKey(c.conversationId, c.root))) c.member = true}- const groups = new Map(chats.map(g => [g.id, g]))+ const groups = new Map(readableChats.map(g => [g.id, g]))const threads = withRoot.filter(c => c.member).flatMap(c => {const root = roots.get(threadKey(c.conversationId, c.root))!, group = groups.get(c.conversationId)!// Named as a page's thread summary names them: only authors who can still read the chat (threads.ts).@@ -222,8 +251,20 @@ async function threadsIn(db: PrismaClient, tabId: string, state: SuperTabState,return { threads, more }}-/** The inbox of the signed-in person: never an agent's (they have no read marks) or a Team session's (marks are the person's). */-export async function readInbox(store: SuperTabStore, user: AuthUser, tabId: string): Promise<Inbox> {+/** What one inbox read found besides the inbox, for the followed threads read (followedThreads.ts) to go on from. */+export interface InboxRead {+ inbox: Inbox+ state: SuperTabState+ /** The chats the person reads now, active and unarchived, most recently active first. */+ chats: Conversation[]+ marks: Map<string, number>+ /** Every thread mark row of the person, most recently moved first (readMarks.ts readThreadMarkRows). */+ threadRows: ThreadMarkRow[]+}++/** The inbox of the signed-in person: never an agent's (they have no read marks) or a Team session's (marks are the person's).+ * Without `latest`, the chats' latest messages are not read and `latest` is empty. */+export async function inboxRead(store: SuperTabStore, user: AuthUser, tabId: string, options: { latest: boolean }): Promise<InboxRead> {if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)const db = store.dbconst { state } = await store.readLoad(user, tabId)@@ -235,16 +276,20 @@ export async function readInbox(store: SuperTabStore, user: AuthUser, tabId: strconst marks = await readMarks(db, tabId, user.sub)// A chat never marked read counts as read: its threads wait for the person's first visit.const unread = chats.filter(g => { const mark = marks.get(g.id) ?? 0; return mark > 0 && g.lastMessageSequence > mark })- const shown = chats.slice(0, LATEST_CHATS)- // The person's thread marks: one indexed read (readMarks.ts), beside the latest messages'.+ const shown = options.latest ? chats.slice(0, LATEST_CHATS) : []+ // The person's thread marks and follows: one indexed read (readMarks.ts), beside the latest messages'.+ const threadRows = readThreadMarkRows(db, tabId, user.sub)const [latest, threaded] = await Promise.all([latestIn(db, tabId, shown),- readThreadMarks(db, tabId, user.sub).then(threadMarks => threadsIn(db, tabId, state, unread.slice(0, THREAD_CHATS), user.sub, marks, threadMarks))])+ threadRows.then(rows => threadsIn(db, tabId, state, unread.slice(0, THREAD_CHATS), chats, user.sub, marks, rows))])const threads = threaded.threads.sort((a, b) => newestFirst({ at: Date.parse(a.lastReplyAt), id: a.rootId }, { at: Date.parse(b.lastReplyAt), id: b.rootId }))- const more = chats.length > LATEST_CHATS || latest.more || unread.length > THREAD_CHATS || threaded.more || threads.length > MAX_THREADS- return { threads: threads.slice(0, MAX_THREADS), more,+ const more = (options.latest && chats.length > LATEST_CHATS) || latest.more || unread.length > THREAD_CHATS || threaded.more || threads.length > MAX_THREADS+ const inbox = { threads: threads.slice(0, MAX_THREADS), more,latest: shown.flatMap(g => { const m = latest.latest.get(g.id); return m ? [{ conversationId: g.id, message: preview(m) }] : [] }) }+ return { inbox, state, chats, marks, threadRows: await threadRows }}+export const readInbox = async (store: SuperTabStore, user: AuthUser, tabId: string): Promise<Inbox> => (await inboxRead(store, user, tabId, { latest: true })).inbox+const inboxReads = createRateLimiter('swarm-inbox', INBOX_WINDOW_MS, INBOX_READS)/** Seconds a person must wait before reading this Swarm's inbox again, or 0 when they may now. Apps read it when the changediff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.tsindex 51fbebedb..10763c3dc 100644--- a/backend/src/superTabs/read/service.ts+++ b/backend/src/superTabs/read/service.ts@@ -8,7 +8,7 @@ import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../..import { agentOnly, author, fail, groupWithoutMachines, isLeads, seenMachineIds, stableId, SuperTabError, visibleState, type Actor, type AgentStart, type SuperTabState } from '../model.js'import { mentionsDigest, swarmsWithTags, waitingMentions, waitingTagConversations } from '../mentions.js'import { decisionsWaiting } from '../decisions.js'-import { readMarks, readThreadMarks, writeReadMark, writeThreadMark } from '../readMarks.js'+import { readMarks, readThreadMarks, writeReadMark, writeThreadFollow, writeThreadMark } from '../readMarks.js'import { deliveredCopies } from '../pageReads.js'import { readBy } from '../parts/indexed.js'import type { SuperTabStore } from '../store.js'@@ -224,6 +224,21 @@ export class SwarmReads {* id, a root the person may read (not an agent-only notice, not a delivered copy) that roots its own thread. Every miss,* an unreadable conversation or project included, is the same refusal. Only a person reading as themselves has marks. */async markThreadRead(user: AuthUser, tabId: string, conversationId: string, threadId: string, sequence: number): Promise<{ sequence: number }> {+ const newest = await this.readableThread(user, tabId, conversationId, threadId)+ return { sequence: await writeThreadMark(this.db, { tabId, personId: user.sub, conversationId, threadId, sequence: Math.min(sequence, newest),+ now: this.now() }) }+ }++ /** Stores the person's Follow (true), Unfollow (false) or neither (null) of thread `threadId` (readMarks.ts writeThreadFollow),+ * checked as markThreadRead checks a thread mark: every miss is the same refusal, and only a person reading as themselves+ * follows. */+ async followThread(user: AuthUser, tabId: string, conversationId: string, threadId: string, follow: boolean | null): Promise<{ follow: boolean | null }> {+ await this.readableThread(user, tabId, conversationId, threadId)+ return { follow: await writeThreadFollow(this.db, { tabId, personId: user.sub, conversationId, threadId, follow, now: this.now() }) }+ }++ /** The newest message sequence of a conversation whose thread `threadId` the person reads (markThreadRead's checks). */+ private async readableThread(user: AuthUser, tabId: string, conversationId: string, threadId: string): Promise<number> {if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)const unavailable = () => fail('NOT_FOUND', 'This conversation is unavailable.', 404)const { state } = await this.store.readLoad(user, tabId, { groupIds: [conversationId] })@@ -239,8 +254,7 @@ export class SwarmReads {{ $project: { source: 1, recipientIds: 1, thread: 1 } }])const root = found && { id: found._id as string, source: found.source ?? null, recipientIds: (found.recipientIds as string[] | undefined) ?? [], thread: found.thread }if (!root || root.thread !== root.id || agentOnly(root.source, root.recipientIds) || (await deliveredCopies(this.db, tabId, [root])).size) unavailable()- return { sequence: await writeThreadMark(this.db, { tabId, personId: user.sub, conversationId, threadId, sequence: Math.min(sequence, newest),- now: this.now() }) }+ return newest}/** A person's own thread marks (an agent has none), every one or those moved since `since`. */diff --git a/backend/src/superTabs/readMarks.ts b/backend/src/superTabs/readMarks.tsindex c72c1f851..de1ce0648 100644--- a/backend/src/superTabs/readMarks.ts+++ b/backend/src/superTabs/readMarks.ts@@ -6,6 +6,7 @@ import { Prisma, type PrismaClient } from '@prisma/client'import { ensureIndex } from '../lib/db/indexes.js'import { fail, stableId } from './model.js'import { readBy } from './parts/indexed.js'+import { ms } from './parts/light.js'/** A mark untouched this long is removed by a TTL index; the conversation then reads as the device last saw it. */export const READ_MARK_EXPIRY_MS = 180 * 24 * 60 * 60_000@@ -69,6 +70,42 @@ export async function writeThreadMark(db: PrismaClient, mark: ThreadMarkWrite):return stored.sequence}+export interface ThreadFollowWrite { tabId: string; personId: string; conversationId: string; threadId: string; follow: boolean | null; now: number }++/** Stores the person's Follow (true), Unfollow (false) or neither (null) of one thread on its mark row, and answers it. The+ * row keeps its sequence: one written here first starts at 0, which reads as no mark (every client keeps the higher of a+ * mark and the one it holds). A Follow moves the row as a read does, so it counts toward THREAD_MARK_CAP and the 180-day+ * expiry from now, and goes with the person when they leave the Swarm (sweepThreadMarks). Two first writes racing to create+ * the row: the loser's create fails on the id and its update runs again on the winner's row. */+export async function writeThreadFollow(db: PrismaClient, write: ThreadFollowWrite): Promise<boolean | null> {+ const { tabId, personId, conversationId, threadId, follow } = write+ const id = stableId(tabId, conversationId, threadId, personId), updatedAt = new Date(write.now)+ for (let attempt = 0; attempt < 4; attempt++) {+ if ((await db.superTabThreadMark.updateMany({ where: { id }, data: { follow, updatedAt } })).count) return follow+ try {+ await db.superTabThreadMark.create({ data: { id, tabId, personId, conversationId, threadId, sequence: 0, follow, updatedAt } })+ } catch (error) {+ if (!(error instanceof Prisma.PrismaClientKnownRequestError) || error.code !== 'P2002') throw error+ continue+ }+ await capThreadMarks(db, tabId, personId)+ return follow+ }+ return fail('READ_MARK_BUSY', 'This thread is being changed on another device. Try again.', 503)+}++/** One of the person's thread mark rows: its mark, its Follow choice (null when none) and when it last moved. */+export interface ThreadMarkRow { conversationId: string; threadId: string; sequence: number; follow: boolean | null; updatedAt: number }++/** Every one of the person's thread mark rows in this tab (at most THREAD_MARK_CAP), most recently moved first, by one raw read+ * of the (tabId, personId, updatedAt) index, as readThreadMarks. The caller keeps those of conversations the reader may read. */+export async function readThreadMarkRows(db: Prisma.TransactionClient, tabId: string, personId: string): Promise<ThreadMarkRow[]> {+ const rows = await readBy(db, 'SuperTabThreadMark', 'person', [{ $match: { tabId, personId } }, { $sort: { updatedAt: -1 } },+ { $project: { _id: 0, conversationId: 1, threadId: 1, sequence: 1, follow: 1, updatedAt: 1 } }])+ return rows.map(row => ({ conversationId: row.conversationId as string, threadId: row.threadId as string, sequence: Number(row.sequence),+ follow: typeof row.follow === 'boolean' ? row.follow : null, updatedAt: ms(row.updatedAt) }))+}+/** Removes the person's least recently moved thread marks in the Swarm past THREAD_MARK_CAP, by the (tabId, personId,* updatedAt) index: it counts the person's marks and reads only the ids of those past the cap. */async function capThreadMarks(db: PrismaClient, tabId: string, personId: string): Promise<void> {diff --git a/backend/src/superTabs/threadFollow.test.ts b/backend/src/superTabs/threadFollow.test.tsnew file mode 100644index 000000000..45c01d948--- /dev/null+++ b/backend/src/superTabs/threadFollow.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from 'vitest'+import { Prisma, type PrismaClient } from '@prisma/client'+import { writeThreadFollow } from './readMarks.js'+import { SuperTabError } from './model.js'++const duplicate = () => new Prisma.PrismaClientKnownRequestError('duplicate', { code: 'P2002', clientVersion: 'test' })++/** A thread mark collection in memory, its calls logged; `race` creates the row from another device just before this one's+ * first create. The cap's reads answer one row. */+function marks(options: { race?: boolean; failCreate?: Error } = {}) {+ const rows = new Map<string, Record<string, unknown>>()+ const calls: string[] = []+ const db = {+ superTabThreadMark: {+ async updateMany({ where, data }: { where: { id: string }; data: Record<string, unknown> }) {+ calls.push('update')+ const row = rows.get(where.id)+ if (!row) return { count: 0 }+ Object.assign(row, data)+ return { count: 1 }+ },+ async create({ data }: { data: Record<string, unknown> & { id: string } }) {+ calls.push('create')+ if (options.failCreate) throw options.failCreate+ if (options.race && !rows.size) {+ rows.set(data.id, { ...data, sequence: 7, follow: null })+ throw duplicate()+ }+ rows.set(data.id, { ...data })+ },+ },+ async $runCommandRaw() { calls.push('cap-delete'); return {} },+ }+ // The cap counts by readBy (aggregateRaw): one mark, under the cap.+ Object.assign(db.superTabThreadMark, { aggregateRaw: async () => { calls.push('cap-count'); return [{ n: 1 }] } })+ return { db: db as unknown as PrismaClient, rows, calls }+}+const write = (follow: boolean | null) => ({ tabId: 'tab', personId: 'p', conversationId: 'c', threadId: 'root', follow, now: 1_000 })++describe('writeThreadFollow', () => {+ it('creates the row with no mark (0) on a first Follow, then checks the cap', async () => {+ const { db, rows, calls } = marks()+ expect(await writeThreadFollow(db, write(true))).toBe(true)+ expect([...rows.values()]).toEqual([expect.objectContaining({ sequence: 0, follow: true, threadId: 'root', updatedAt: new Date(1_000) })])+ expect(calls).toEqual(['update', 'create', 'cap-count'])+ })++ it('sets or clears the choice on a row that is there, keeping its mark', async () => {+ const { db, rows } = marks()+ await writeThreadFollow(db, write(true))+ ;[...rows.values()][0]!.sequence = 12+ expect(await writeThreadFollow(db, write(null))).toBeNull()+ expect([...rows.values()]).toEqual([expect.objectContaining({ sequence: 12, follow: null })])+ })++ it('goes on to update the row another device created first, keeping that mark', async () => {+ const { db, rows, calls } = marks({ race: true })+ expect(await writeThreadFollow(db, write(false))).toBe(false)+ expect([...rows.values()]).toEqual([expect.objectContaining({ sequence: 7, follow: false })])+ expect(calls).toEqual(['update', 'create', 'update'])+ })++ it('says a write it could not settle, and passes on any other failure', async () => {+ const busy = marks({ failCreate: duplicate() })+ await expect(writeThreadFollow(busy.db, write(true))).rejects.toBeInstanceOf(SuperTabError)+ expect(busy.calls.filter(c => c === 'create')).toHaveLength(4)+ await expect(writeThreadFollow(marks({ failCreate: new Error('connection reset') }).db, write(true))).rejects.toThrow('connection reset')+ })+})diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex e1b757f71..2a974a668 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -1,7 +1,7 @@import { defineConfig } from 'vitest/config'export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts', 'integration/superTabWorkspaces.test.ts',- 'integration/superTabRead.test.ts', 'integration/superTabReadMarks.test.ts', 'integration/superTabInbox.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts',+ 'integration/superTabRead.test.ts', 'integration/superTabReadMarks.test.ts', 'integration/superTabInbox.test.ts', 'integration/superTabFollowedThreads.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts','integration/superTabTidy.test.ts', 'integration/superTabProfile.test.ts', 'integration/superTabLegacyDrop.test.ts', 'integration/shareRaces.test.ts', 'integration/superTabIndexes.test.ts', 'integration/superTabRouteDecisions.test.ts','integration/superTabHotReads.test.ts', 'integration/swarmSweepStarts.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabMachineReports.test.ts','integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts', 'integration/superTabNotAvailable.test.ts',diff --git a/desktop/lib/shared/theme/app_theme.dart b/desktop/lib/shared/theme/app_theme.dartindex 5704f2e56..56deaf7ef 100644--- a/desktop/lib/shared/theme/app_theme.dart+++ b/desktop/lib/shared/theme/app_theme.dart@@ -253,6 +253,9 @@ abstract final class AppPalette {static Color get dangerFill =>AppTheme.pick(const Color(0xFFB3261E), const Color(0xFFC92E26));+ /// Text and marks on [dangerFill], such as a sidebar's red count.+ static const Color onDangerFill = Colors.white;+/// The accent as a *mark on a surface* — a selected row's icon, an accent/// rail — rather than a fill behind white text.///diff --git a/desktop/lib/super_tabs/attention.dart b/desktop/lib/super_tabs/attention.dartnew file mode 100644index 000000000..c8e07afe2--- /dev/null+++ b/desktop/lib/super_tabs/attention.dart@@ -0,0 +1,483 @@+import 'dart:async';+import 'dart:math';++import 'package:flutter/foundation.dart';++import 'controller.dart';+import 'decisions.dart';+import 'model.dart';+import 'notifications.dart';++/// One thread the reader follows, as the server lists it (backend+/// read/followedThreads.ts, or read/inbox.ts on a server before it): its+/// root's preview and its newest reply.+class SuperTabFollowedThread {+ SuperTabFollowedThread.fromJson(Map<String, dynamic> row)+ : conversationId = row['conversationId'] as String,+ rootId = row['rootId'] as String,+ root = superTabMap(row['root']),+ lastReplyAt = DateTime.tryParse(row['lastReplyAt'] as String? ?? ''),+ lastReplySequence = (row['lastReplySequence'] as num?)?.toInt() ?? 0,+ lastReplier = row['lastReplier'] is Map+ ? superTabMap(row['lastReplier'])+ : null,+ unreadReplies = (row['unreadReplies'] as num?)?.toInt() ?? 0,+ replies = (row['replies'] as num?)?.toInt(),+ follow = row['follow'] as bool?;++ final String conversationId, rootId;++ /// The root's preview: `id`, `sequence`, `author`, `text` (cut by the+ /// server), `createdAt`.+ final Map<String, dynamic> root;+ final DateTime? lastReplyAt;+ final int lastReplySequence, unreadReplies;++ /// How many replies it has; null in an unread entry from an older server.+ final int? replies;++ /// The reader's own Follow (true) or Unfollow (false); null when it follows+ /// from taking part (started it, replied, tagged).+ final bool? follow;+ final Map<String, dynamic>? lastReplier;++ String get key => '$conversationId/$rootId';+ String get rootText => root['text'] as String? ?? '';+ Map<String, dynamic> get rootAuthor =>+ root['author'] is Map ? superTabMap(root['author']) : const {};+}++/// What needs the reader in one Swarm, the way Slack shows it: which+/// conversations hold a tag of them (the red number), and which threads they+/// follow have replies they have not read (the Threads row and view). Tags and+/// decisions come from [SuperTabMentions] and [SuperTabDecisions]; threads+/// from the server's followed-threads read, read again when the Swarm moves,+/// at most every [quietGap] (every [openGap] while the Threads view is open).+/// One per controller.+class SuperTabAttention extends ChangeNotifier {+ SuperTabAttention._(this.controller, {DateTime Function()? now})+ : mentions = SuperTabMentions.of(controller),+ decisions = SuperTabDecisions.of(controller),+ _now = now ?? DateTime.now {+ controller.addListener(_changed);+ controller.onDispose(dispose);+ mentions.addListener(notifyListeners);+ decisions.addListener(notifyListeners);+ _changed();+ }++ /// For a test: an attention reader over [controller] with its own clock.+ @visibleForTesting+ factory SuperTabAttention.forTest(+ SuperTabController controller, {+ DateTime Function()? now,+ }) => SuperTabAttention._(controller, now: now);++ static final _all = Expando<SuperTabAttention>();+ static SuperTabAttention of(SuperTabController controller) =>+ _all[controller] ??= SuperTabAttention._(controller);++ final SuperTabController controller;+ final SuperTabMentions mentions;+ final SuperTabDecisions decisions;+ final DateTime Function() _now;++ static const quietGap = Duration(seconds: 15);+ static const openGap = Duration(seconds: 3);++ /// Followed threads with replies the reader has not read, newest reply+ /// first; and those read, newest reply first.+ List<SuperTabFollowedThread> unread = const [], read = const [];++ /// Whether a read has answered since the Swarm was opened or its audience+ /// last changed.+ bool loaded = false;+ String? error;++ /// The server keeps Follow and Unfollow; false on one before them, which+ /// lists only unread threads.+ bool followSupported = true;++ /// The server stopped short of everything (its bounds).+ bool more = false;++ /// Threads shown as new in this visit of the Threads view: they stay new+ /// until the view is left, though opening them marked them read.+ final Set<String> _newThisVisit = {};+ bool _open = false;++ /// New replies under each unread thread's root, read when the view showed+ /// it; by [SuperTabFollowedThread.key].+ final Map<String, List<SuperTabMessage>> newReplies = {};+ final Set<String> _readingReplies = {};++ /// Threads whose replies failed to read this visit: not asked again until+ /// the next one, so a failing read is not repeated on every redraw.+ final Set<String> _repliesFailed = {};++ /// Threads whose Follow is being sent.+ final Set<String> following = {};++ /// The new-reply count each thread showed when this visit first listed it+ /// as new: a thread read meanwhile comes back with none, and keeps saying+ /// what it had.+ final Map<String, int> _counts = {};++ /// A read for a change that came inside the gap, once the gap is over.+ Timer? _trailing;++ int? _epoch;+ int _lastChangedAt = -1;+ DateTime? _lastRead, _waitUntil;+ Future<void>? _loading;+ bool _dirty = false, _disposed = false;+ int _asked = 0, _shown = 0;++ String get _path =>+ '/api/super-tabs/${Uri.encodeComponent(controller.tabId)}';++ /// The red number of [conversationId]: tags of the reader in its main+ /// stream, and decisions asked of them there (an agent asking a person to+ /// decide tags them). A tag in a reply that lives only in its thread counts+ /// on Threads instead.+ ///+ /// As in Slack, a tag stops counting once the reader has read past it,+ /// answered or not; a decision once its chat is read (its row does not say+ /// which message asked). Nothing counts once access is gone.+ int mentionsIn(String conversationId) {+ if (controller.accessRevoked) return 0;+ final tags = mentions.waiting+ .where(+ (m) =>+ m.conversationId == conversationId &&+ m.threadId == null &&+ (m.messageSequence ?? _unknown) >+ controller.readMark(conversationId),+ )+ .length;+ final asked = decisions.open+ .where((d) => d.conversationId == conversationId)+ .length;+ if (asked == 0) return tags;+ final group = controller.snapshot?.conversation(conversationId);+ return tags + (group != null && controller.unread(group) ? asked : 0);+ }++ /// A tag from a server that does not say where it is: it counts until+ /// answered, past any read mark.+ static const _unknown = 1 << 52;++ /// The Threads row's number: tags of the reader inside threads they have+ /// not read past, in chats this Swarm still lists for them.+ int get threadMentions {+ final snapshot = controller.snapshot;+ if (controller.accessRevoked || snapshot == null) return 0;+ final chats = {for (final g in snapshot.conversations) g.id};+ return mentions.waiting+ .where(+ (m) =>+ m.threadId != null &&+ chats.contains(m.conversationId) &&+ (m.messageSequence ?? _unknown) >+ controller.threadReadMark(m.threadId!),+ )+ .length;+ }++ /// How many new replies [thread] shows: as many as it had when this visit+ /// first listed it new.+ int newCount(SuperTabFollowedThread thread) =>+ _counts[thread.key] ?? thread.unreadReplies;++ /// Whether a followed thread has replies the reader has not read: the+ /// Threads row is bold.+ bool get threadsUnread => unread.isNotEmpty;++ /// Whether [thread] shows as new in this visit.+ bool isNew(SuperTabFollowedThread thread) =>+ _newThisVisit.contains(thread.key) ||+ unread.any((t) => t.key == thread.key);++ /// The threads the view lists: new ones first, then the rest, each newest+ /// reply first; one read during this visit stays with the new ones.+ List<SuperTabFollowedThread> get shown {+ final fresh = <SuperTabFollowedThread>[+ ...unread,+ ...read.where((t) => _newThisVisit.contains(t.key)),+ ];+ final keys = fresh.map((t) => t.key).toSet();+ int newest(SuperTabFollowedThread a, SuperTabFollowedThread b) =>+ (b.lastReplyAt ?? DateTime(0)).compareTo(a.lastReplyAt ?? DateTime(0));+ return [+ ...fresh..sort(newest),+ ...read.where((t) => !keys.contains(t.key)),+ ];+ }++ /// The Threads view opened: reads now, and what is new stays new until+ /// [closed].+ void opened() {+ _open = true;+ _newThisVisit+ ..clear()+ ..addAll(unread.map((t) => t.key));+ _counts+ ..clear()+ ..addAll({for (final t in unread) t.key: t.unreadReplies});+ unawaited(load());+ }++ void closed() {+ _open = false;+ _trailing?.cancel();+ _trailing = null;+ _newThisVisit.clear();+ _counts.clear();+ newReplies.clear();+ _repliesFailed.clear();+ if (!_disposed) notifyListeners();+ }++ void _clear() {+ unread = read = const [];+ loaded = false;+ error = null;+ more = false;+ _newThisVisit.clear();+ _counts.clear();+ newReplies.clear();+ _readingReplies.clear();+ _repliesFailed.clear();+ _trailing?.cancel();+ _trailing = null;+ }++ void _changed() {+ if (_disposed) return;+ if (controller.accessRevoked) {+ if (loaded || unread.isNotEmpty || read.isNotEmpty) {+ _clear();+ // An answer on its way belongs to the access that is gone.+ _shown = ++_asked;+ notifyListeners();+ }+ return;+ }+ if (controller.snapshot == null) return;+ final epoch = controller.visibilityEpoch;+ if (epoch != null && epoch != _epoch) {+ final moved = _epoch != null;+ _epoch = epoch;+ if (moved) {+ // Who may read what changed: nothing read before shows until read+ // again.+ _clear();+ _shown = ++_asked;+ notifyListeners();+ _lastChangedAt = controller.lastChangedAt;+ unawaited(load());+ return;+ }+ }+ if (controller.lastChangedAt == _lastChangedAt && loaded) return;+ final now = _now();+ // Inside the gap, or waiting out a refusal: one read when it is over, so+ // the change is not lost.+ final until = [+ if (_waitUntil case final wait? when now.isBefore(wait)) wait,+ if (_lastRead case final last?) last.add(_open ? openGap : quietGap),+ ].fold<DateTime?>(null, (a, b) => a == null || b.isAfter(a) ? b : a);+ if (until != null && now.isBefore(until)) {+ // Only while something shows it (the sidebar, the Threads view).+ if (!hasListeners) return;+ _trailing ??= Timer(until.difference(now), () {+ _trailing = null;+ _changed();+ });+ return;+ }+ _trailing?.cancel();+ _trailing = null;+ _lastChangedAt = controller.lastChangedAt;+ unawaited(load());+ }++ /// Joins a read under way, and has it read once more when asked again.+ Future<void> load() {+ if (_disposed) return Future.value();+ if (_loading case final running?) {+ _dirty = true;+ return running;+ }+ return _loading = () async {+ do {+ _dirty = false;+ await _read();+ } while (_dirty && !_disposed);+ }().whenComplete(() => _loading = null);+ }++ Future<void> _read() async {+ if (controller.accessRevoked || controller.snapshot == null) return;+ final asked = ++_asked;+ final epoch = controller.visibilityEpoch;+ _lastRead = _now();+ bool current() =>+ !_disposed &&+ !controller.accessRevoked &&+ asked > _shown &&+ controller.visibilityEpoch == epoch;+ try {+ Map<String, dynamic>? answer;+ // A server before followed threads (it answered 404 once): its inbox+ // lists the unread ones, and nothing keeps Follow.+ var full = followSupported;+ if (full) {+ try {+ answer = await controller.request('GET', '$_path/threads');+ } on SuperTabFailure catch (failure) {+ if (failure.statusCode != 404) rethrow;+ full = false;+ }+ }+ answer ??= await controller.request('GET', '$_path/inbox');+ if (!current()) return;+ _shown = asked;+ final unreadRows = (full ? answer['unread'] : answer['threads']) as List;+ final readable = {+ for (final g in controller.snapshot?.conversations ?? const []) g.id,+ };+ List<SuperTabFollowedThread> rows(List list) => [+ for (final row in list)+ if (SuperTabFollowedThread.fromJson(superTabMap(row)) case final t+ // Only chats this reader still has; the server checked, and a+ // chat they lost since is not shown on its word alone.+ when readable.contains(t.conversationId))+ t,+ ];+ unread = rows(unreadRows);+ read = full ? rows(answer['read'] as List? ?? const []) : const [];+ followSupported = full;+ more = answer['more'] == true;+ error = null;+ loaded = true;+ if (_open) {+ _newThisVisit.addAll(unread.map((t) => t.key));+ for (final t in unread) {+ _counts.putIfAbsent(t.key, () => t.unreadReplies);+ }+ }+ _waitUntil = null;+ notifyListeners();+ } catch (failure) {+ if (!current()) return;+ _shown = asked;+ if (failure is SuperTabFailure && failure.statusCode == 429) {+ // Asked too often: the next change after a pause reads again.+ _waitUntil = _now().add(const Duration(seconds: 5));+ }+ error = 'Could not load threads.';+ notifyListeners();+ }+ }++ /// Reads the replies of [thread] the reader has not read, to show under its+ /// root, then marks the thread read: opening the view reads what it shows.+ Future<void> showReplies(SuperTabFollowedThread thread) async {+ if (_disposed ||+ controller.accessRevoked ||+ newReplies.containsKey(thread.key) ||+ _repliesFailed.contains(thread.key) ||+ !_readingReplies.add(thread.key)) {+ return;+ }+ final epoch = controller.visibilityEpoch;+ final seen = controller.threadReadMark(thread.rootId);+ try {+ final answer = await controller.request(+ 'GET',+ '$_path/conversations/${Uri.encodeComponent(thread.conversationId)}'+ '/messages?thread=${Uri.encodeQueryComponent(thread.rootId)}',+ );+ if (_disposed ||+ controller.accessRevoked ||+ controller.visibilityEpoch != epoch ||+ !_readingReplies.contains(thread.key)) {+ return;+ }+ final replies = [+ for (final row in answer['messages'] as List? ?? const [])+ if (SuperTabMessage.fromJson(superTabMap(row)) case final m+ when m.conversationId == thread.conversationId &&+ m.thread == thread.rootId &&+ m.threadReply &&+ m.sequence > seen)+ m,+ ]..sort(superTabMessageOrder);+ newReplies[thread.key] = replies.length > 5+ ? replies.sublist(replies.length - 5)+ : replies;+ final through = max(+ thread.lastReplySequence,+ replies.lastOrNull?.sequence ?? 0,+ );+ controller.markThreadRead(thread.conversationId, thread.rootId, through);+ notifyListeners();+ } catch (_) {+ // The thread stays unread and its root shows; the next visit tries again.+ _repliesFailed.add(thread.key);+ } finally {+ _readingReplies.remove(thread.key);+ }+ }++ /// Follows (true) or unfollows (false) [thread] on every device of the+ /// reader; false when the server did not keep it.+ Future<bool> setFollow(SuperTabFollowedThread thread, bool follow) async {+ if (_disposed ||+ controller.accessRevoked ||+ !followSupported ||+ !following.add(thread.key)) {+ return false;+ }+ notifyListeners();+ try {+ await controller.request(+ 'POST',+ '$_path/conversations/${Uri.encodeComponent(thread.conversationId)}'+ '/threads/${Uri.encodeComponent(thread.rootId)}/follow',+ body: {'follow': follow},+ );+ if (_disposed) return false;+ _lastRead = null;+ unawaited(load());+ return true;+ } catch (_) {+ return false;+ } finally {+ following.remove(thread.key);+ if (!_disposed) notifyListeners();+ }+ }++ /// The last one showing it went: no read is waited for.+ @override+ void removeListener(VoidCallback listener) {+ super.removeListener(listener);+ if (_disposed || hasListeners) return;+ _trailing?.cancel();+ _trailing = null;+ }++ @override+ void dispose() {+ if (_disposed) return;+ _disposed = true;+ _trailing?.cancel();+ _trailing = null;+ controller.removeListener(_changed);+ mentions.removeListener(notifyListeners);+ decisions.removeListener(notifyListeners);+ super.dispose();+ }+}diff --git a/desktop/lib/super_tabs/buddy_rows.dart b/desktop/lib/super_tabs/buddy_rows.dartindex d50a538a1..bae78eee8 100644--- a/desktop/lib/super_tabs/buddy_rows.dart+++ b/desktop/lib/super_tabs/buddy_rows.dart@@ -6,25 +6,33 @@ import 'buddy_chat.dart';import 'identity.dart';import 'section_heading.dart';-/// A sidebar count, such as the tags waiting in Notifications.+/// A sidebar count of what is for the reader, such as the tags waiting in+/// Notifications or in a conversation: Slack's red number, white on the+/// danger fill (5.4:1 or more in both themes, app_theme.dart dangerFill).class SuperTabCountBadge extends StatelessWidget {const SuperTabCountBadge(this.count, {super.key});final int count;@override- Widget build(BuildContext context) => Container(- constraints: const BoxConstraints(minWidth: 18),- padding: const EdgeInsets.symmetric(horizontal: grid.AppDesktop.badgeInset),- decoration: ShapeDecoration(- color: grid.AppPalette.warn.withValues(alpha: .16),- shape: const StadiumBorder(),- ),- child: Text(- countText(count),- textAlign: TextAlign.center,- style: DesktopChrome.metadata(color: grid.AppPalette.warn),- ),- );+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return Container(+ constraints: const BoxConstraints(minWidth: 18),+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.badgeInset,+ ),+ decoration: ShapeDecoration(+ color: grid.AppPalette.dangerFill,+ shape: const StadiumBorder(),+ ),+ child: Text(+ countText(count),+ textAlign: TextAlign.center,+ style: DesktopChrome.metadata(color: grid.AppPalette.onDangerFill)+ .copyWith(fontWeight: grid.AppFont.semibold),+ ),+ );+ }}/// A person's Buddy chat in a project, in the sidebar's Buddies: its Buddy's@@ -42,6 +50,7 @@ class SuperTabBuddyRow extends StatelessWidget {this.project,this.selected = false,this.unread = false,+ this.badge = 0,this.note,this.detail,this.status,@@ -54,6 +63,9 @@ class SuperTabBuddyRow extends StatelessWidget {/// The project's name, shown when the Swarm has several.final String? project;final bool selected, unread;++ /// Tags of the reader in this chat: the red number.+ final int badge;final VoidCallback? onTap;/// What hovering says: "Your Buddy · openharness".@@ -71,9 +83,10 @@ class SuperTabBuddyRow extends StatelessWidget {@overrideWidget build(BuildContext context) {- final color = onTap == null- ? DesktopChrome.muted- : DesktopChrome.foreground;+ // Muted when read, full strength when unread or open (Dee, 10-31).+ final color = onTap != null && (selected || unread)+ ? DesktopChrome.foreground+ : DesktopChrome.muted;return Padding(padding: const EdgeInsets.only(bottom: grid.AppDesktop.listRowGap),child: Material(@@ -182,6 +195,17 @@ class SuperTabBuddyRow extends StatelessWidget {),),),+ if (badge > 0)+ Padding(+ padding: const EdgeInsets.only(+ left: grid.AppDesktop.controlGap,+ ),+ child: Semantics(+ label: badge == 1 ? '1 mention' : '$badge mentions',+ excludeSemantics: true,+ child: SuperTabCountBadge(badge),+ ),+ ),SizedBox(width: _column,// Unread is drawn as a bold name and heard in words.diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 07ef2ddc7..2e14134eb 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -1224,6 +1224,28 @@ class SuperTabController extends ChangeNotifier {_saveSoon();}+ /// [root]'s thread in [conversationId] was read through [sequence] outside+ /// the thread pane (the Threads view): kept here and sent to the server,+ /// so it reads as read on every device. Nothing once access is gone.+ void markThreadRead(String conversationId, String root, int sequence) {+ if (_disposed ||+ accessRevoked ||+ sequence <= 0 ||+ snapshot?.conversation(conversationId) == null) {+ return;+ }+ _serverThreadMarks.mark(+ (conversationId, root),+ sequence,+ kept: snapshot?.threadMarks[conversationId]?[root] ?? 0,+ );+ if ((_threadSeen[root] ?? 0) >= sequence) return;+ _threadSeen.remove(root);+ _threadSeen[root] = sequence;+ _saveSoon();+ _changed();+ }+/// The root and replies of [root]'s thread in the selected conversation,/// oldest first: what its own read brought, and replies polled since.List<SuperTabMessage> threadMessages(String root) {@@ -1333,10 +1355,14 @@ class SuperTabController extends ChangeNotifier {Map<String, String> threadMentions(String conversationId, String root) =>Map.unmodifiable(_threadMentions[(conversationId, root)] ?? const {});- /// [id] picked as [token] in the open thread's reply box, while its draft- /// says it.- void threadMention(String id, String token) {- final open = openedThread;+ /// [id] picked as [token] in the open thread's reply box, or [to]'s (the+ /// Threads view), while its draft says it.+ void threadMention(+ String id,+ String token, {+ ({String conversationId, String root})? to,+ }) {+ final open = to ?? openedThread;if (open == null || accessRevoked) return;if (!containsMention(threadDraft(open.root), token)) return;(_threadMentions[(open.conversationId, open.root)] ??= {})[id] = token;@@ -1428,22 +1454,25 @@ class SuperTabController extends ChangeNotifier {}}- /// Sends the open thread's draft and files to its root; [alsoSend] shows it in the- /// main stream too. [onSending] is told when the reply is on its way, which- /// is after its files have gone up.+ /// Sends the open thread's draft and files to its root, or [to]'s (the+ /// Threads view replies without opening the thread); [alsoSend] shows it in+ /// the main stream too. [onSending] is told when the reply is on its way,+ /// which is after its files have gone up.Future<Map<String, dynamic>?> sendThreadReply({bool alsoSend = false,bool newSession = false,VoidCallback? onSending,+ ({String conversationId, String root})? to,}) async {- final open = openedThread;- if (open == null) return null;+ final open = to ?? openedThread;+ if (open == null || accessRevoked) return null;final text = threadDraft(open.root).trim();final owner = threadAttachments(open.conversationId, open.root);final files = owner.files;+ final group = snapshot?.conversation(open.conversationId);if ((text.isEmpty && files.isEmpty) ||- selected == null ||- selected!.archived ||+ group == null ||+ group.archived ||!canWrite ||uploading ||saving ||@@ -1454,7 +1483,9 @@ class SuperTabController extends ChangeNotifier {// The tags as picked when sent: the box may take new ones meanwhile.final picked = Map<String, String>.of(_threadMentions[thread] ?? const {});final (:tagged, :addressed) = _tagsSaid(picked, text);- final failure = addressed.any((id) => !selected!.agentIds.contains(id))+ // The thread's own chat: a reply from the Threads view goes to a chat+ // that may not be the one selected, or none may be.+ final failure = addressed.any((id) => !group.agentIds.contains(id))? 'A mentioned agent is no longer in this conversation. Remove its mention or choose another agent.'// Only its own session hears a session's thread (backend// routeBuddySession): another agent's tag there would be refused.@@ -1837,12 +1868,24 @@ class SuperTabController extends ChangeNotifier {/// Each conversation's reaction counter as its last page said it.final _reactionSeq = <String, int>{};- int _loadedMessageSequence(String id) =>- _messages[id]?.reversed- .where((m) => m.source['kind'] != 'update-request')- .firstOrNull- ?.sequence ??- 0;++ /// The newest message held for [id] that reading the chat reads: one in+ /// its main stream. A reply only in its thread is read in that thread, as in+ /// Slack, so the chat's mark stops short of it and the thread stays unread+ /// (backend read/inbox.ts counts replies past the chat's mark). From a+ /// server before main-stream numbers, any row, as before.+ int _loadedMessageSequence(String id) {+ final mainOnly = snapshot?.conversation(id)?.lastMainSequence != null;+ return _messages[id]?.reversed+ .where(+ (m) =>+ m.source['kind'] != 'update-request' &&+ (!mainOnly || m.inMainStream),+ )+ .firstOrNull+ ?.sequence ??+ 0;+ }/// How far the reader has read [id]: the higher of the mark kept on the/// server, from any of their devices, and this device's own, which stands@@ -4180,9 +4223,18 @@ class SuperTabController extends ChangeNotifier {await _persist();}+ /// Runs [then] when this controller is disposed: a helper that keeps a+ /// timer of its own (attention.dart) stops with it.+ void onDispose(VoidCallback then) => _onDispose.add(then);+ final _onDispose = <VoidCallback>[];+@overridevoid dispose() {_disposed = true;+ for (final then in _onDispose) {+ then();+ }+ _onDispose.clear();for (final queued in _queuedSends) {queued.result.complete(null);}diff --git a/desktop/lib/super_tabs/notifications.dart b/desktop/lib/super_tabs/notifications.dartindex 241d81c79..8aeae1433 100644--- a/desktop/lib/super_tabs/notifications.dart+++ b/desktop/lib/super_tabs/notifications.dart@@ -26,7 +26,9 @@ class SuperTabMention {leadName = row['leadName'] as String? ?? 'Lead',text = row['text'] as String? ?? '',createdAt = DateTime.tryParse(row['createdAt'] as String? ?? ''),- resolvedBy = row['resolvedBy'] as String?;+ resolvedBy = row['resolvedBy'] as String?,+ threadId = row['threadId'] as String?,+ messageSequence = (row['messageSequence'] as num?)?.toInt();final String id, projectId, projectName, conversationId, conversationTitle;final String messageId, leadName, text;@@ -36,6 +38,16 @@ class SuperTabMention {/// `reply` or `done` once it moved to Earlier; null while it waits.final String? resolvedBy;++ /// The thread's root when the tag is in a reply that lives only in its+ /// thread: it counts on Threads, not on its chat's row. Null for a tag in+ /// the main stream, and from a server before it.+ final String? threadId;++ /// The tagged message's place in its chat: the red number for it clears+ /// once the reader has read past it, as in Slack. Null from a server+ /// before it, where it counts until the tag is answered.+ final int? messageSequence;}/// Whether the menu bar's Harness menu lists the reader's tags and decisions,diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dartindex 93e4d9b8a..c5f66936c 100644--- a/desktop/lib/super_tabs/project_sidebar.dart+++ b/desktop/lib/super_tabs/project_sidebar.dart@@ -14,6 +14,7 @@ import '../terminal/terminal_theme.dart';import '../terminal/terminal_theme_store.dart';import '../widgets/desktop_chrome.dart';import '../widgets/harness_activity_mark.dart';+import 'attention.dart';import 'controller.dart';import 'identity.dart';import 'leaderboard/models_section.dart';@@ -43,6 +44,9 @@ class ProjectSidebar extends StatelessWidget {this.devicesSelected = false,this.onNotifications,this.notificationsSelected = false,+ this.attention,+ this.onThreads,+ this.threadsSelected = false,this.onOpenAgent,this.onOpenBuddyChat,this.readLocal,@@ -65,6 +69,21 @@ class ProjectSidebar extends StatelessWidget {/// The reader's tags from every project's Lead; its count is what waits.final VoidCallback? onNotifications;final bool notificationsSelected;++ /// What needs the reader, as Slack shows it: each row's red number counts+ /// only tags of them (decisions asked of them among them), and Threads is+ /// bold while a thread they follow has replies they have not read. Without+ /// it rows carry no number.+ final SuperTabAttention? attention;++ /// Opens the Threads view; no Threads row without it.+ final VoidCallback? onThreads;+ final bool threadsSelected;++ /// Whether a row other than a conversation (devices, Notifications,+ /// Threads) holds the main pane.+ bool get _paneCovered =>+ devicesSelected || notificationsSelected || threadsSelected;final ValueChanged<SuperTabAgent>? onOpenAgent;/// Opens the reader's Buddy chat in a project, by project id; the@@ -96,6 +115,7 @@ class ProjectSidebar extends StatelessWidget {bool selected = false,int badge = 0,Widget? trailing,+ bool? unread,}) => Padding(padding: const EdgeInsets.only(bottom: 2),child: Material(@@ -133,12 +153,21 @@ class ProjectSidebar extends StatelessWidget {label,maxLines: 1,overflow: TextOverflow.ellipsis,- style: DesktopChrome.control(- medium: selected,- color: onTap == null- ? DesktopChrome.muted- : DesktopChrome.foreground,- ),+ // A row that reads or not ([unread] given) is drawn as+ // conversations are: muted when read, full strength+ // and bold when not.+ style:+ DesktopChrome.control(+ medium: selected,+ color:+ onTap == null || (unread == false && !selected)+ ? DesktopChrome.muted+ : DesktopChrome.foreground,+ ).copyWith(+ fontWeight: unread == true+ ? grid.AppFont.semibold+ : null,+ ),),),),@@ -172,16 +201,23 @@ class ProjectSidebar extends StatelessWidget {String? key,}) {final project = reading?.project;- final selected =- !devicesSelected &&- !notificationsSelected &&- controller.selectedId == group.id;+ final selected = !_paneCovered && controller.selectedId == group.id;final waiting = reading == null? needsHuman(group) > 0: reading.waiting.isNotEmpty;- final unread = reading == null+ // Open, a project's row is its own chat's, as each workgroup under it+ // has its own; collapsed, it is bold for anything it hides.+ final unread =+ reading == null || controller.expandedProjects.contains(project?.id)? controller.unread(group): reading.unread.isNotEmpty;+ // A collapsed project counts the tags in the conversations it hides, as+ // Slack's collapsed section does; open, each row has its own.+ final badge = attention == null+ ? 0+ : reading == null || controller.expandedProjects.contains(project?.id)+ ? attention!.mentionsIn(group.id)+ : reading.mentions;return _drawRow(group,project: project,@@ -189,6 +225,7 @@ class ProjectSidebar extends StatelessWidget {selected: selected,waiting: waiting,unread: unread,+ badge: badge,buddyChat: reading?.buddyChat,selectedProjectId: reading?.sidebar.selectedProjectId,);@@ -220,12 +257,10 @@ class ProjectSidebar extends StatelessWidget {Widget _workgroupRow(SuperTabConversation group, _ProjectReading reading) =>_drawRow(group,- selected:- !devicesSelected &&- !notificationsSelected &&- controller.selectedId == group.id,+ selected: !_paneCovered && controller.selectedId == group.id,waiting: reading.waiting.contains(group.id),unread: reading.unread.contains(group.id),+ badge: attention?.mentionsIn(group.id) ?? 0,);Widget _drawRow(@@ -235,6 +270,7 @@ class ProjectSidebar extends StatelessWidget {required bool selected,required bool waiting,required bool unread,+ int badge = 0,SuperTabConversation? buddyChat,String? selectedProjectId,}) {@@ -246,23 +282,24 @@ class ProjectSidebar extends StatelessWidget {selected ||(project != null &&!expanded &&- !devicesSelected &&- !notificationsSelected &&+ !_paneCovered &&selectedProjectId == project.id &&controller.selectedId != buddyChat?.id);- // Unread is the name in bold and nothing else, no dot (Dee, 2026-10-29).+ // As Slack draws it (Dee, 10-31): a read row in the muted text colour, an+ // unread one at full strength and bold, no dot; the open row keeps its+ // highlight.final style = DesktopChrome.control(medium: highlighted,- color: highlighted || unread || project != null+ color: highlighted || unread? DesktopChrome.foreground: DesktopChrome.muted,).copyWith(fontWeight: unread ? grid.AppFont.semibold : null);return Padding(padding: const EdgeInsets.only(bottom: 2),- child: Material(- color: highlighted ? grid.AppSurface.selectedFill : Colors.transparent,- borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),- clipBehavior: Clip.antiAlias,+ // Hover lights the whole row, chevron included, in the selected+ // highlight's shape (Dee, 10-31): the row draws it, not each click.+ child: _RowSurface(+ selected: highlighted,// The chevron stands beside the row's own click, not inside it: the// name opens and the chevron toggles.child: Row(@@ -274,7 +311,7 @@ class ProjectSidebar extends StatelessWidget {child: InkWell(key: ValueKey(key ?? 'super-group-${group.id}'),onTap: () => onSelect(group.id),- hoverColor: grid.AppSurface.hoverFill,+ hoverColor: Colors.transparent,focusColor: grid.AppSurface.hoverFill,borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),child: Row(@@ -352,6 +389,21 @@ class ProjectSidebar extends StatelessWidget {],),),+ if (badge > 0) ...[+ const SizedBox(width: 8),+ Semantics(+ label: badge == 1+ ? '1 mention'+ : '$badge mentions',+ excludeSemantics: true,+ child: SuperTabCountBadge(+ badge,+ key: ValueKey(+ 'super-mentions-${group.id}',+ ),+ ),+ ),+ ],if (project?.isPrivate == true) ...[const SizedBox(width: 8),Tooltip(@@ -449,7 +501,8 @@ class ProjectSidebar extends StatelessWidget {child: InkWell(key: ValueKey('super-project-toggle-${project.id}'),onTap: () => controller.toggleProject(project.id),- hoverColor: grid.AppSurface.hoverFill,+ // Its row lights whole on hover (_RowSurface).+ hoverColor: Colors.transparent,focusColor: grid.AppSurface.hoverFill,borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),child: Tooltip(@@ -601,11 +654,9 @@ class ProjectSidebar extends StatelessWidget {_ => null,},selected:- chat != null &&- !devicesSelected &&- !notificationsSelected &&- controller.selectedId == chat.id,+ chat != null && !_paneCovered && controller.selectedId == chat.id,unread: chat != null && controller.unread(chat),+ badge: chat == null ? 0 : attention?.mentionsIn(chat.id) ?? 0,onTap: chat != null? () => onSelect(chat.id): controller.saving || controller.hasPendingAction@@ -733,11 +784,11 @@ class ProjectSidebar extends StatelessWidget {// Never behind "… N more": the open one, and those with// something to read or answer.kept: {- if (!devicesSelected && !notificationsSelected)- controller.selectedId,+ if (!_paneCovered) controller.selectedId,for (final group in groups)if (reading.unread.contains(group.id) ||- reading.waiting.contains(group.id))+ reading.waiting.contains(group.id) ||+ (attention?.mentionsIn(group.id) ?? 0) > 0)group.id,},more: (hidden, onTap) => _moreRow(project, hidden, onTap),@@ -769,10 +820,18 @@ class ProjectSidebar extends StatelessWidget {]..sort((a, b) => a.$1.toLowerCase().compareTo(b.$1.toLowerCase()));@override- Widget build(BuildContext context) {+ Widget build(BuildContext context) => switch (attention) {+ final attention? => ListenableBuilder(+ listenable: attention,+ builder: (context, _) => _build(context),+ ),+ null => _build(context),+ };++ Widget _build(BuildContext context) {final snapshot = controller.snapshot;final projects = snapshot?.projects ?? const <SuperTabProject>[];- final reading = _SidebarReading(controller, needsHuman);+ final reading = _SidebarReading(controller, needsHuman, attention);return Material(color: DesktopChrome.surface,child: ListView(@@ -822,6 +881,16 @@ class ProjectSidebar extends StatelessWidget {onTap: () =>showSwarmLocalModels(context, controller, app: app, now: now),),+ if (onThreads != null)+ _navigationRow(+ key: 'super-threads',+ label: 'Threads',+ icon: AppIcons.messagesSquare,+ onTap: onThreads,+ selected: threadsSelected,+ unread: attention?.threadsUnread ?? false,+ badge: attention?.threadMentions ?? 0,+ ),if (onNotifications != null)_navigationRow(key: 'super-notifications',@@ -836,6 +905,7 @@ class ProjectSidebar extends StatelessWidget {if (onNewProject != null ||onYourDevices != null ||onNotifications != null ||+ onThreads != null ||controller.isOwner ||snapshot?.localModels?.enabled == true)const SizedBox(height: 20),@@ -911,6 +981,37 @@ class ProjectSidebar extends StatelessWidget {}}+/// A sidebar row's ground: the selected fill, or the hover fill while the+/// pointer is anywhere over it, one shape across the row's whole width.+class _RowSurface extends StatefulWidget {+ const _RowSurface({required this.selected, required this.child});+ final bool selected;+ final Widget child;++ @override+ State<_RowSurface> createState() => _RowSurfaceState();+}++class _RowSurfaceState extends State<_RowSurface> {+ bool _hovered = false;++ @override+ Widget build(BuildContext context) => MouseRegion(+ onEnter: (_) => setState(() => _hovered = true),+ onExit: (_) => setState(() => _hovered = false),+ child: Material(+ color: widget.selected+ ? grid.AppSurface.selectedFill+ : _hovered+ ? grid.AppSurface.hoverFill+ : Colors.transparent,+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),+ clipBehavior: Clip.antiAlias,+ child: widget.child,+ ),+ );+}+/// A project's open conversations, newest first: the first/// [_NewestConversations.shown] and the [_NewestConversations.kept] ones, then/// a "… N more" row that shows the rest. Showing the rest lasts until the@@ -969,9 +1070,10 @@ class _NewestConversationsState extends State<_NewestConversations> {/// thousands of conversations were scanned again on every rebuild (Diego,/// 10-29).class _SidebarReading {- _SidebarReading(this.controller, this.needsHuman);+ _SidebarReading(this.controller, this.needsHuman, this.attention);final SuperTabController controller;final int Function(SuperTabConversation group) needsHuman;+ final SuperTabAttention? attention;final _projects = <String, _ProjectReading>{};_ProjectReading of(SuperTabProject project) =>@@ -1002,6 +1104,22 @@ class _ProjectReading {/// never the reader's Buddy chat, which has its own row under Buddies.Set<String> get waiting => _open.waiting;Set<String> get unread => _open.unread;++ /// Tags of the reader in the project's chat and its open workgroups: a+ /// collapsed project's number.+ late final int mentions = switch (sidebar.attention) {+ null => 0,+ final attention =>+ attention.mentionsIn(project.leadConversationId) ++ [+ for (final g in conversations)+ if (!g.closed &&+ !g.isBuddyChat &&+ g.audience == null &&+ g.id != project.leadConversationId)+ attention.mentionsIn(g.id),+ ].fold(0, (a, b) => a + b),+ };late final _open = () {final waiting = <String>{}, unread = <String>{};for (final g in conversations) {diff --git a/desktop/lib/super_tabs/reply_box.dart b/desktop/lib/super_tabs/reply_box.dartnew file mode 100644index 000000000..13618e6ad--- /dev/null+++ b/desktop/lib/super_tabs/reply_box.dart@@ -0,0 +1,182 @@+import 'package:flutter/foundation.dart' show kIsWeb;+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../shared/theme/app_icons.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_icon_button.dart';+import '../state/harness_attachments.dart';+import '../widgets/desktop_chrome.dart';+import '../widgets/new_harness_attachments.dart';+import '../widgets/new_harness_paste.dart';+import 'composer_files.dart';+import 'composer_newline.dart';+import 'controller.dart';++/// A thread's reply box, one everywhere a reply is written (the thread pane,+/// the Threads view): files dropped, pasted or attached, Enter sends and+/// ⇧Enter breaks the line, attach and the arrow at its right end. [options]+/// sits left of them, such as the pane's Also send and New session.+class SuperTabReplyBox extends StatelessWidget {+ const SuperTabReplyBox({+ super.key,+ required this.controller,+ required this.text,+ required this.focus,+ required this.files,+ required this.enabled,+ required this.writable,+ required this.busy,+ required this.error,+ required this.onEdited,+ required this.onSend,+ this.options,+ this.onKey,+ this.inputFormatters = const [],+ this.surfaceKey = const ValueKey('super-thread-composer-surface'),+ this.fieldKey = const ValueKey('super-thread-composer'),+ this.sendKey = const ValueKey('super-thread-send'),+ });++ final SuperTabController controller;+ final TextEditingController text;+ final FocusNode focus;+ final HarnessAttachments files;++ /// Whether the field takes typing; [writable] whether a reply may go now.+ final bool enabled, writable;++ /// Files going up or a message on its way: the box takes no more.+ final bool busy;+ final String? error;+ final ValueChanged<String> onEdited;+ final VoidCallback onSend;+ final Widget? options;++ /// Sees each key first, such as an open @ completion list's arrows and+ /// Enter; a non-null answer is the key's.+ final KeyEventResult? Function(KeyEvent event)? onKey;+ final List<TextInputFormatter> inputFormatters;+ final Key surfaceKey, fieldKey, sendKey;++ @override+ Widget build(BuildContext context) => NewHarnessDropZone(+ attachments: files,+ enabled: writable && !busy,+ // A folder has no bytes to attach, and its path means nothing to a+ // reader on another computer: say so, as the chat does for a browser.+ onFolders: kIsWeb+ ? null+ : (_) => reportAttachProblem(+ context,+ 'A folder can\'t be attached to a reply. Drop its files instead.',+ ),+ child: DecoratedBox(+ key: surfaceKey,+ decoration: BoxDecoration(+ color: DesktopChrome.field,+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),+ border: Border.all(color: DesktopChrome.rim),+ ),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.controlGap,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ SuperTabComposerChips(controller: controller, files: files),+ Focus(+ onKeyEvent: (_, event) {+ if (onKey?.call(event) case final handled?) return handled;+ switch (composerEnter(+ event,+ focused: focus.hasFocus,+ value: text.value,+ )) {+ case ComposerEnter.ignore:+ return KeyEventResult.ignored;+ case ComposerEnter.newline:+ insertComposerNewline(text, onEdited);+ return KeyEventResult.handled;+ case ComposerEnter.send:+ onSend();+ return KeyEventResult.handled;+ }+ },+ child: NewHarnessPasteTarget(+ attachments: files,+ enabled: writable && !busy,+ focusNode: focus,+ child: TextField(+ key: fieldKey,+ controller: text,+ focusNode: focus,+ enabled: enabled,+ minLines: 1,+ maxLines: 6,+ maxLength: kComposerMaxLength,+ inputFormatters: inputFormatters,+ keyboardType: TextInputType.multiline,+ style: DesktopChrome.text(),+ decoration: InputDecoration(+ isCollapsed: true,+ constraints: const BoxConstraints(),+ hintText: 'Reply',+ hintStyle: DesktopChrome.text(color: DesktopChrome.muted),+ contentPadding: EdgeInsets.zero,+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ disabledBorder: InputBorder.none,+ filled: false,+ counterText: '',+ ),+ onChanged: onEdited,+ ),+ ),+ ),+ if (error case final error?)+ Padding(+ padding: const EdgeInsets.only(top: grid.AppDesktop.controlGap),+ child: Text(+ error,+ key: const ValueKey('super-thread-error'),+ style: DesktopChrome.control(),+ ),+ ),+ const SizedBox(height: grid.AppDesktop.controlGap),+ Row(+ children: [+ Expanded(child: options ?? const SizedBox.shrink()),+ NewHarnessAttachButton(+ attachments: files,+ enabled: writable && !busy,+ ),+ ListenableBuilder(+ listenable: Listenable.merge([files, text]),+ builder: (context, _) => AppIconButton(+ key: sendKey,+ icon: AppIcons.arrowUp,+ tooltip: 'Send reply',+ color: DesktopChrome.accent,+ onPressed:+ writable &&+ !busy &&+ (text.text.trim().isNotEmpty || !files.isEmpty)+ ? onSend+ : null,+ ),+ ),+ ],+ ),+ ],+ ),+ ),+ ),+ );+}diff --git a/desktop/lib/super_tabs/thread_panel.dart b/desktop/lib/super_tabs/thread_panel.dartindex 9570c65fb..3bf98b570 100644--- a/desktop/lib/super_tabs/thread_panel.dart+++ b/desktop/lib/super_tabs/thread_panel.dart@@ -1,6 +1,5 @@import 'dart:async';-import 'package:flutter/foundation.dart' show kIsWeb;import 'package:flutter/material.dart';import 'package:flutter/services.dart';@@ -9,13 +8,10 @@ import '../shared/theme/app_theme.dart' as grid;import '../shared/widgets/app_icon_button.dart';import '../state/harness_attachments.dart';import '../widgets/desktop_chrome.dart';-import '../widgets/new_harness_attachments.dart';-import '../widgets/new_harness_paste.dart';import 'buddy_sessions.dart';-import 'composer_files.dart';-import 'composer_newline.dart';import 'composer_tags.dart';import 'composer_toggle.dart';+import 'reply_box.dart';import 'controller.dart';import 'jump_to_latest.dart';import 'model.dart';@@ -521,147 +517,36 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {);}- Widget _composerBox() {- final writable = _writable;- final files = _files;- final busy = _busy;- final error = c.threadComposerError(c.selectedId, widget.root);- return NewHarnessDropZone(- attachments: files,- enabled: writable && !busy,- // A folder has no bytes to attach, and its path means nothing to a- // reader on another computer: say so, as the chat does for a browser.- onFolders: kIsWeb- ? null- : (_) => reportAttachProblem(- context,- 'A folder can\'t be attached to a reply. Drop its files instead.',- ),- child: DecoratedBox(- key: const ValueKey('super-thread-composer-surface'),- decoration: BoxDecoration(- color: DesktopChrome.field,- borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),- border: Border.all(color: DesktopChrome.rim),- ),- child: Padding(- padding: const EdgeInsets.fromLTRB(- grid.AppDesktop.groupGap,- grid.AppDesktop.controlGap,- grid.AppDesktop.controlGap,- grid.AppDesktop.controlGap,- ),- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- SuperTabComposerChips(controller: c, files: files),- Focus(- onKeyEvent: (_, event) {- final composing = _composer.value.composing;- final picked =- _focus.hasFocus &&- !(composing.isValid && !composing.isCollapsed)- ? superTabCompletionKey(- event,- choices: () => _tagChoices,- index: _tagIndex.value,- move: _moveTag,- dismiss: () => _tagDismissed.value = _composer.text- .substring(0, _composer.selection.baseOffset),- )- : null;- if (picked != null) return picked;- switch (composerEnter(- event,- focused: _focus.hasFocus,- value: _composer.value,- )) {- case ComposerEnter.ignore:- return KeyEventResult.ignored;- case ComposerEnter.newline:- insertComposerNewline(_composer, _edited);- return KeyEventResult.handled;- case ComposerEnter.send:- unawaited(_send());- return KeyEventResult.handled;- }- },- child: NewHarnessPasteTarget(- attachments: files,- enabled: writable && !busy,- focusNode: _focus,- child: TextField(- key: const ValueKey('super-thread-composer'),- controller: _composer,- focusNode: _focus,- enabled: c.canWrite && c.selected?.archived == false,- minLines: 1,- maxLines: 6,- maxLength: kComposerMaxLength,- inputFormatters: [_tagBackspace],- keyboardType: TextInputType.multiline,- style: DesktopChrome.text(),- decoration: InputDecoration(- isCollapsed: true,- constraints: const BoxConstraints(),- hintText: 'Reply',- hintStyle: DesktopChrome.text(color: DesktopChrome.muted),- contentPadding: EdgeInsets.zero,- border: InputBorder.none,- enabledBorder: InputBorder.none,- focusedBorder: InputBorder.none,- disabledBorder: InputBorder.none,- filled: false,- counterText: '',- ),- onChanged: _edited,- ),- ),- ),- if (error != null)- Padding(- padding: const EdgeInsets.only(- top: grid.AppDesktop.controlGap,- ),- child: Text(- error,- key: const ValueKey('super-thread-error'),- style: DesktopChrome.control(),- ),- ),- const SizedBox(height: grid.AppDesktop.controlGap),- Row(- children: [- Expanded(child: _choices(writable)),- NewHarnessAttachButton(- attachments: files,- enabled: writable && !busy,- ),- ListenableBuilder(- listenable: files,- builder: (context, _) => AppIconButton(- key: const ValueKey('super-thread-send'),- icon: AppIcons.arrowUp,- tooltip: 'Send reply',- color: DesktopChrome.accent,- onPressed:- writable &&- !busy &&- (_composer.text.trim().isNotEmpty ||- !files.isEmpty)- ? () => unawaited(_send())- : null,- ),- ),- ],+ Widget _composerBox() => SuperTabReplyBox(+ controller: c,+ text: _composer,+ focus: _focus,+ files: _files,+ enabled: c.canWrite && c.selected?.archived == false,+ writable: _writable,+ busy: _busy,+ error: c.threadComposerError(c.selectedId, widget.root),+ onEdited: _edited,+ onSend: () => unawaited(_send()),+ options: _choices(_writable),+ // `@` in the reply: the open completion list takes its keys first.+ onKey: (event) {+ final composing = _composer.value.composing;+ return _focus.hasFocus && !(composing.isValid && !composing.isCollapsed)+ ? superTabCompletionKey(+ event,+ choices: () => _tagChoices,+ index: _tagIndex.value,+ move: _moveTag,+ dismiss: () => _tagDismissed.value = _composer.text.substring(+ 0,+ _composer.selection.baseOffset,),- ],- ),- ),- ),- );- }+ )+ : null;+ },+ inputFormatters: [_tagBackspace],+ );/// The send row's options, left of attach and send, on one line at any/// width (Scholes, 10-31): Also send names where it posts in full wherediff --git a/desktop/lib/super_tabs/threads_view.dart b/desktop/lib/super_tabs/threads_view.dartnew file mode 100644index 000000000..d9f02932e--- /dev/null+++ b/desktop/lib/super_tabs/threads_view.dart@@ -0,0 +1,661 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../widgets/desktop_chrome.dart';+import 'attention.dart';+import 'composer_tags.dart';+import '../shared/theme/app_icons.dart';+import 'controller.dart';+import 'identity.dart';+import 'message_more_menu.dart';+import 'machine_status.dart' show superTabAgo;+import 'model.dart';+import 'reply_box.dart';+import 'section_heading.dart';+import 'workgroup_name.dart';++/// How many threads with new replies read their replies when the view opens;+/// the rest show their root and count until opened.+const kThreadsShowingReplies = 10;++/// Slack's Threads view: every thread the reader follows (started, replied+/// in, tagged in, or followed by hand), those with new replies first and in+/// bold with the new replies under the root and a reply box, the rest after.+/// Showing a thread's new replies marks it read, on every device; it stays+/// new until the view is left.+class SuperTabThreadsView extends StatefulWidget {+ const SuperTabThreadsView({+ super.key,+ required this.attention,+ required this.onOpen,+ this.now = DateTime.now,+ this.machineName,+ });++ final SuperTabAttention attention;++ /// Names an agent's machine in the @ list, as the thread pane does.+ final String Function(String machineId)? machineName;++ /// Opens [rootId]'s thread in its chat [conversationId].+ final void Function(String conversationId, String rootId) onOpen;+ final DateTime Function() now;++ @override+ State<SuperTabThreadsView> createState() => _SuperTabThreadsViewState();+}++class _SuperTabThreadsViewState extends State<SuperTabThreadsView> {+ late SuperTabAttention _attention;++ @override+ void initState() {+ super.initState();+ _attention = widget.attention..opened();+ }++ @override+ void didUpdateWidget(SuperTabThreadsView old) {+ super.didUpdateWidget(old);+ if (old.attention != widget.attention) {+ old.attention.closed();+ _attention = widget.attention..opened();+ }+ }++ @override+ void dispose() {+ _attention.closed();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: _attention,+ builder: (context, _) {+ grid.AppTheme.watch(context);+ final a = _attention;+ final shown = a.shown;+ final fresh = shown.where(a.isNew).toList();+ final rest = shown.where((t) => !a.isNew(t)).toList();+ // Opening reads what it shows: the first threads with new replies.+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted) return;+ for (final thread in fresh.take(kThreadsShowingReplies)) {+ unawaited(a.showReplies(thread));+ }+ });+ return ListView(+ key: const ValueKey('super-threads-view'),+ padding: const EdgeInsets.only(bottom: grid.AppDesktop.groupGap),+ children: [+ if (a.error case final error?)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.groupGap,+ 0,+ ),+ child: Row(+ children: [+ Expanded(child: Text(error, style: DesktopChrome.control())),+ TextButton(+ onPressed: () => unawaited(a.load()),+ child: const Text('Retry'),+ ),+ ],+ ),+ ),+ if (!a.loaded && a.error == null)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.groupGap,+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ ),+ child: Text('Loading threads…', style: DesktopChrome.metadata()),+ )+ else if (a.loaded && shown.isEmpty)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.groupGap,+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ ),+ child: Text(+ 'No threads yet. Threads you start, reply in or are '+ 'tagged in show here.',+ style: DesktopChrome.metadata(),+ ),+ ),+ if (fresh.isNotEmpty) ...[+ const Padding(+ padding: EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.groupGap,+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ ),+ child: SuperTabSectionHeading('New replies', endInset: 0),+ ),+ for (final thread in fresh)+ _ThreadCard(+ key: ValueKey('super-thread-${thread.key}'),+ attention: a,+ thread: thread,+ onOpen: widget.onOpen,+ now: widget.now,+ machineName: widget.machineName,+ ),+ ],+ if (rest.isNotEmpty) ...[+ const Padding(+ padding: EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.groupGap,+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ ),+ child: SuperTabSectionHeading('Earlier', endInset: 0),+ ),+ for (final thread in rest)+ _ThreadCard(+ key: ValueKey('super-thread-${thread.key}'),+ attention: a,+ thread: thread,+ onOpen: widget.onOpen,+ now: widget.now,+ machineName: widget.machineName,+ ),+ ],+ if (a.more)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ ),+ child: Text(+ 'Older threads are not listed.',+ style: DesktopChrome.metadata(),+ ),+ ),+ ],+ );+ },+ );+}++/// One followed thread in the list: where it is, its root, its new replies+/// and a reply box while it is new, else its reply count. Follow or Unfollow+/// waits behind a quiet ⋯ that shows on hover or focus, as in Slack.+class _ThreadCard extends StatefulWidget {+ const _ThreadCard({+ super.key,+ required this.attention,+ required this.thread,+ required this.onOpen,+ required this.now,+ this.machineName,+ });++ final SuperTabAttention attention;+ final SuperTabFollowedThread thread;+ final String Function(String machineId)? machineName;+ final void Function(String conversationId, String rootId) onOpen;+ final DateTime Function() now;++ @override+ State<_ThreadCard> createState() => _ThreadCardState();+}++class _ThreadCardState extends State<_ThreadCard> {+ /// An avatar, and the column the text beside it starts at.+ static const _face = SuperTabAvatar.rowSize;+ static const _indent = _face + grid.AppDesktop.controlGap;++ late final _text = TextEditingController(+ text: _c.threadDraft(widget.thread.rootId),+ );+ final _focus = FocusNode(debugLabel: 'Threads reply');+ bool _hovered = false, _focused = false;++ // `@` in the reply box, as in the thread pane's (composer_tags.dart): the+ // choice selected, and the text before the caret where it was dismissed.+ final _tagIndex = ValueNotifier(0);+ final _tagDismissed = ValueNotifier<String?>(null);+ final _tagRows = List.generate(superTabCompletionLimit, (_) => GlobalKey());+ late final _tagBackspace = SuperTabTagBackspace(+ () => _c.threadMentions(_thread.conversationId, _thread.rootId).values,+ );++ SuperTabController get _c => widget.attention.controller;+ SuperTabFollowedThread get _thread => widget.thread;+ SuperTabSnapshot? get _snapshot => _c.snapshot;++ @override+ void dispose() {+ _text.dispose();+ _focus.dispose();+ _tagIndex.dispose();+ _tagDismissed.dispose();+ super.dispose();+ }++ /// The `@` tag typed at the caret.+ ({int start, int end, String query})? get _tagAt => superTabTagAtCaret(+ _text.value,+ dismissed: _tagDismissed.value,+ tags: _c.threadMentions(_thread.conversationId, _thread.rootId).values,+ );++ /// Who `@` offers in this reply: whom the thread's own chat offers.+ List<SuperTabComposerChoice> get _tagChoices {+ final group = _snapshot?.conversation(_thread.conversationId);+ if (!_writable || group == null) return const [];+ final at = _tagAt;+ if (at == null) return const [];+ return superTabTagChoices(+ _c,+ group,+ at.query,+ machineName: widget.machineName ?? (_) => '',+ choose: _chooseTag,+ );+ }++ void _chooseTag(String id, String name) {+ final at = _tagAt;+ if (at == null) return;+ final token = '@$name';+ final value = superTabInsertTag(_text.value, at, token);+ _c.setThreadDraft(_thread.rootId, value.text);+ _c.threadMention(id, token, to: _target);+ _text.value = value;+ _tagIndex.value = 0;+ _focus.requestFocus();+ setState(() {});+ }++ void _moveTag(int index) {+ _tagIndex.value = index;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ final row = _tagRows[index].currentContext;+ if (mounted && row != null) Scrollable.ensureVisible(row, alignment: .5);+ });+ }++ /// Where the thread is, named as the sidebar names it.+ String _place() {+ final snapshot = _snapshot;+ final group = snapshot?.conversation(_thread.conversationId);+ if (snapshot == null || group == null) return '';+ final project = snapshot.projectFor(group.id);+ if (snapshot.isProjectLead(group.id)) return '# ${project?.name ?? ''}';+ if (group.isBuddyChat) return 'Buddy · ${project?.name ?? ''}';+ final name = SuperTabWorkgroupName.plain(group);+ return project == null ? name : '# ${project.name} · $name';+ }++ /// An author as the chat names them now.+ String _name(Map<String, dynamic> author) {+ final id = author['id'] as String? ?? '';+ final recorded =+ author['displayName'] as String? ?? author['name'] as String? ?? '';+ if (author['kind'] == 'agent') {+ return _snapshot?.agentName(id, fallback: recorded) ?? recorded;+ }+ return _snapshot?.people.where((p) => p.id == id).firstOrNull?.username ??+ superTabPersonName(recorded);+ }++ Widget? _avatar(Map<String, dynamic> author) {+ final id = author['id'] as String? ?? '';+ if (author['kind'] == 'agent') {+ return switch (_snapshot?.agent(id)) {+ final agent? => SuperTabAvatar.agent(+ agent,+ name: _name(author),+ size: _face,+ engineBadge: false,+ ),+ null => null,+ };+ }+ return switch (_snapshot?.people.where((p) => p.id == id).firstOrNull) {+ final person? => SuperTabAvatar.person(person, size: _face),+ null => null,+ };+ }++ Widget _message(+ Map<String, dynamic> author,+ String text, {+ DateTime? at,+ required bool strong,+ int lines = 3,+ }) => Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SizedBox(width: _face, height: _face, child: _avatar(author)),+ const SizedBox(width: grid.AppDesktop.controlGap),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ Flexible(+ child: Text(+ _name(author),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(medium: true).copyWith(+ fontWeight: strong ? grid.AppFont.semibold : null,+ ),+ ),+ ),+ if (at != null) ...[+ const SizedBox(width: grid.AppDesktop.controlGap),+ Text(+ superTabAgo(widget.now().difference(at)),+ style: DesktopChrome.metadata(),+ ),+ ],+ ],+ ),+ Text(+ text,+ maxLines: lines,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(+ color: strong ? null : DesktopChrome.muted,+ ),+ ),+ ],+ ),+ ),+ ],+ );++ /// The thread's root, for a reply sent from here.+ ({String conversationId, String root}) get _target =>+ (conversationId: _thread.conversationId, root: _thread.rootId);++ bool get _writable =>+ _c.canWrite &&+ _snapshot?.conversation(_thread.conversationId)?.archived == false &&+ !_c.hasPendingAction;++ bool get _busy => _c.uploading || _c.saving;++ void _edited(String text) {+ _c.setThreadDraft(_thread.rootId, text);+ _tagIndex.value = 0;+ _tagDismissed.value = null;+ setState(() {});+ }++ Future<void> _send() async {+ final files = _c.threadAttachments(_thread.conversationId, _thread.rootId);+ if (!_writable || _busy || (_text.text.trim().isEmpty && files.isEmpty)) {+ return;+ }+ final root = _thread.rootId;+ _c.setThreadDraft(root, _text.text);+ await _c.sendThreadReply(+ to: _target,+ onSending: () {+ if (mounted && _c.threadDraft(root).isEmpty) _text.clear();+ },+ );+ if (mounted) setState(() {});+ }++ Future<void> _follow(bool follow) async {+ final kept = await widget.attention.setFollow(_thread, follow);+ if (!mounted || kept) return;+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(+ SnackBar(+ content: Text(+ follow ? 'Could not follow this thread.' : 'Could not unfollow.',+ ),+ ),+ );+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final a = widget.attention;+ final fresh = a.isNew(_thread);+ final replies = a.newReplies[_thread.key];+ final count = a.newCount(_thread);+ final followed = _thread.follow != false;+ final group = _snapshot?.conversation(_thread.conversationId);+ final canReply = fresh && _c.canWrite && group?.archived == false;+ // A Buddy chat's thread may need a new session (its last one ended),+ // which only the thread pane offers: a box here would be refused.+ final buddyThread = group?.isBuddyChat == true;+ final showMore = _hovered || _focused;+ return Focus(+ canRequestFocus: false,+ skipTraversal: true,+ onFocusChange: (focused) => setState(() => _focused = focused),+ child: MouseRegion(+ onEnter: (_) => setState(() => _hovered = true),+ onExit: (_) => setState(() => _hovered = false),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.controlGap,+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ Expanded(+ child: Text(+ _place(),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.metadata(),+ ),+ ),+ // Quiet until the card is pointed at or focused: the+ // replies are what the eye is for (Lead's review, 10-31).+ if (a.followSupported)+ Opacity(+ opacity: showMore ? 1 : 0,+ child: KeyedSubtree(+ key: ValueKey('super-thread-more-${_thread.key}'),+ child: SuperTabMessageMoreMenu(+ actions: [+ followed+ ? (+ label: 'Unfollow thread',+ icon: AppIcons.eyeOff,+ onPressed: () => unawaited(_follow(false)),+ )+ : (+ label: 'Follow thread',+ icon: AppIcons.bell,+ onPressed: () => unawaited(_follow(true)),+ ),+ ],+ ),+ ),+ ),+ ],+ ),+ InkWell(+ key: ValueKey('super-thread-open-${_thread.key}'),+ onTap: () =>+ widget.onOpen(_thread.conversationId, _thread.rootId),+ hoverColor: grid.AppSurface.hoverFill,+ focusColor: grid.AppSurface.hoverFill,+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ vertical: grid.AppDesktop.listRowGap,+ ),+ child: _message(+ _thread.rootAuthor,+ _thread.rootText,+ at: DateTime.tryParse(+ _thread.root['createdAt'] as String? ?? '',+ ),+ strong: fresh,+ ),+ ),+ ),+ Padding(+ padding: const EdgeInsets.only(left: _indent),+ child: fresh+ ? Text(+ count == 1 ? '1 new reply' : '$count new replies',+ style: DesktopChrome.metadata(+ color: DesktopChrome.accent,+ ).copyWith(fontWeight: grid.AppFont.semibold),+ )+ : Text(+ [+ if (_thread.replies case final n?)+ n == 1 ? '1 reply' : '$n replies',+ if (_thread.lastReplyAt case final at?)+ 'last ${superTabAgo(widget.now().difference(at))}',+ ].join(' · '),+ style: DesktopChrome.metadata(),+ ),+ ),+ if (fresh && replies != null)+ for (final reply in replies)+ Padding(+ padding: const EdgeInsets.only(+ left: _indent,+ top: grid.AppDesktop.controlGap,+ ),+ child: _message(+ reply.author,+ reply.text,+ at: reply.createdAt,+ strong: true,+ lines: 4,+ ),+ ),+ if (canReply && buddyThread)+ Padding(+ padding: const EdgeInsets.only(+ left: _indent,+ top: grid.AppDesktop.controlGap,+ ),+ child: TextButton(+ key: ValueKey('super-thread-open-reply-${_thread.key}'),+ onPressed: () =>+ widget.onOpen(_thread.conversationId, _thread.rootId),+ child: const Text('Open thread to reply'),+ ),+ ),+ if (canReply && !buddyThread)+ Padding(+ padding: const EdgeInsets.only(+ left: _indent,+ top: grid.AppDesktop.controlGap,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ // The @ list above the box, as in the thread pane.+ ListenableBuilder(+ listenable: Listenable.merge([+ _text,+ _tagIndex,+ _tagDismissed,+ ]),+ builder: (context, _) {+ final choices = _tagChoices;+ if (choices.isEmpty) return const SizedBox.shrink();+ return Padding(+ padding: const EdgeInsets.only(+ bottom: grid.AppDesktop.controlGap,+ ),+ child: SuperTabCompletionList(+ listKey: ValueKey(+ 'super-thread-completions-${_thread.key}',+ ),+ choices: choices,+ index: _tagIndex.value,+ rowKeys: _tagRows,+ ),+ );+ },+ ),+ ListenableBuilder(+ listenable: _c,+ builder: (context, _) => SuperTabReplyBox(+ controller: _c,+ text: _text,+ focus: _focus,+ files: _c.threadAttachments(+ _thread.conversationId,+ _thread.rootId,+ ),+ enabled: _c.canWrite,+ writable: _writable,+ busy: _busy,+ error: _c.threadComposerError(+ _thread.conversationId,+ _thread.rootId,+ ),+ onEdited: _edited,+ onSend: () => unawaited(_send()),+ surfaceKey: ValueKey(+ 'super-thread-reply-surface-${_thread.key}',+ ),+ fieldKey: ValueKey(+ 'super-thread-reply-${_thread.key}',+ ),+ sendKey: ValueKey('super-thread-send-${_thread.key}'),+ // `@`: the open list takes its keys first.+ onKey: (event) {+ final composing = _text.value.composing;+ return _focus.hasFocus &&+ !(composing.isValid &&+ !composing.isCollapsed)+ ? superTabCompletionKey(+ event,+ choices: () => _tagChoices,+ index: _tagIndex.value,+ move: _moveTag,+ dismiss: () => _tagDismissed.value = _text+ .text+ .substring(+ 0,+ _text.selection.baseOffset,+ ),+ )+ : null;+ },+ inputFormatters: [_tagBackspace],+ ),+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ ),+ );+ }+}diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex ab8c22c31..edcb4272a 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -34,6 +34,7 @@ import 'composer_files.dart';import 'composer_newline.dart';import 'composer_tags.dart';import 'composer_toggle.dart';+import 'attention.dart';import 'controller.dart';import 'dialog_scope.dart';import 'folder_zip.dart';@@ -54,6 +55,7 @@ import 'route_row.dart';import 'ship_row.dart';import 'terminal_row.dart';import 'thread_panel.dart';+import 'threads_view.dart';import 'work_details.dart';import 'project_sidebar.dart';import 'buddy_sessions.dart';@@ -137,6 +139,9 @@ class _SuperTabViewState extends State<SuperTabView>bool _showPullRequests = false;bool _showNotifications = false;++ /// The Threads view holds the main pane (threads_view.dart).+ bool _showThreads = false;// The message a tag opened, scrolled to once it is laid out.String? _target;// The conversation a link or tag opened at its own message this visit: its@@ -442,7 +447,8 @@ class _SuperTabViewState extends State<SuperTabView>_devicesVisible ||_terminalsVisible ||_showPullRequests ||- _showNotifications) {+ _showNotifications ||+ _showThreads) {return false;}final lifecycle = WidgetsBinding.instance.lifecycleState;@@ -1374,6 +1380,17 @@ class _SuperTabViewState extends State<SuperTabView>onNewSwarm: widget.onNewSwarm,devicesSelected: _devicesVisible,notificationsSelected: _notificationsVisible,+ attention: SuperTabAttention.of(c),+ threadsSelected: _threadsVisible,+ onThreads: () {+ _closeSidebar();+ setState(() {+ _showThreads = true;+ _showNotifications = false;+ _showPullRequests = false;+ });+ widget.onCloseTerminal?.call();+ },// On a Mac what needs the person is in the menu bar's Harness menu and on// the Dock's badge, so the sidebar keeps no Notifications row.onNotifications: superTabNoticesInMenuBar@@ -1382,6 +1399,7 @@ class _SuperTabViewState extends State<SuperTabView>_closeSidebar();setState(() {_showNotifications = true;+ _showThreads = false;_showPullRequests = false;});widget.onCloseTerminal?.call();@@ -1390,7 +1408,7 @@ class _SuperTabViewState extends State<SuperTabView>_closeSidebar();setState(() {_showPullRequests = false;- _showNotifications = false;+ _showNotifications = _showThreads = false;});(widget.onChooseAgentTerminal ?? widget.onOpenTerminal)(agent);},@@ -1398,12 +1416,12 @@ class _SuperTabViewState extends State<SuperTabView>? null: () {_closeSidebar();- setState(() => _showNotifications = false);+ setState(() => _showNotifications = _showThreads = false);widget.app!.openDevices();},needsHuman: (group) => _needsHuman(group).length,onSelect: (id) {- setState(() => _showNotifications = false);+ setState(() => _showNotifications = _showThreads = false);c.select(id);_closeSidebar();},@@ -1416,7 +1434,7 @@ class _SuperTabViewState extends State<SuperTabView>/// ([SuperTabController.buddyChatOpener]).Future<bool> _openBuddyChat(String projectId) {setState(() {- _showNotifications = false;+ _showNotifications = _showThreads = false;_showPullRequests = false;});widget.onCloseTerminal?.call();@@ -1433,6 +1451,7 @@ class _SuperTabViewState extends State<SuperTabView>widget.onCloseTerminal?.call();setState(() {_showNotifications = true;+ _showThreads = false;_showPullRequests = false;});if (request.kind != 'mention') return;@@ -1445,6 +1464,30 @@ class _SuperTabViewState extends State<SuperTabView>bool get _notificationsVisible =>_showNotifications && !_devicesVisible && !c.accessRevoked;+ /// Notifications or Threads holds the main pane, with no chat header.+ bool get _listViewHoldsThePane => _notificationsVisible || _threadsVisible;++ bool get _threadsVisible =>+ _showThreads &&+ !_showNotifications &&+ !_devicesVisible &&+ !c.accessRevoked;++ /// Opens [root]'s thread in its chat from the Threads view.+ void _openThreadFromList(String conversationId, String root) {+ if (c.accessRevoked || c.snapshot?.conversation(conversationId) == null) {+ return;+ }+ widget.onCloseTerminal?.call();+ _closeSidebar();+ setState(() {+ _showThreads = _showNotifications = false;+ _showPullRequests = false;+ });+ c.select(conversationId);+ c.openThread(root);+ }+/// [messageId] of [id], read from the pages held, then what arrived after/// them, then older pages, up to 50 (5,000 messages); null when it is not/// among them. A message newer than what was read earlier is after it, so@@ -1516,7 +1559,7 @@ class _SuperTabViewState extends State<SuperTabView>}final shownBy = _rowShowing(id, messageId) ?? messageId;setState(() {- _showNotifications = false;+ _showNotifications = _showThreads = false;_showPullRequests = false;_back = null;_target = shownBy;@@ -1903,6 +1946,8 @@ class _SuperTabViewState extends State<SuperTabView>? 'Your devices': _notificationsVisible? 'Notifications'+ : _threadsVisible+ ? 'Threads': group == null? c.snapshot?.projects.isEmpty == true? c.snapshot!.name@@ -1941,7 +1986,7 @@ class _SuperTabViewState extends State<SuperTabView>/// Whether ⋮ carries the views a wider header draws as icons.bool get _menuNamesViews =>- _phone && !_devicesVisible && !_notificationsVisible;+ _phone && !_devicesVisible && !_listViewHoldsThePane;/// How many terminals [group]'s [term] opens: its agents', and in the/// person's own Personal Swarm their panes of its project.@@ -2066,7 +2111,7 @@ class _SuperTabViewState extends State<SuperTabView>)else_title(group),- if (!_devicesVisible && !_notificationsVisible)+ if (!_devicesVisible && !_listViewHoldsThePane)?_subtitle(group),],),@@ -2074,7 +2119,7 @@ class _SuperTabViewState extends State<SuperTabView>),if (group != null &&!_devicesVisible &&- !_notificationsVisible) ...[+ !_listViewHoldsThePane) ...[fingerTarget(enabled: _phone,AppIconButton(@@ -3649,6 +3694,8 @@ class _SuperTabViewState extends State<SuperTabView>? 1: _notificationsVisible? 3+ : _threadsVisible+ ? 4: c.snapshot?.projects.isEmpty == true? 0: _terminalsVisible@@ -3676,6 +3723,13 @@ class _SuperTabViewState extends State<SuperTabView>),): const SizedBox.shrink(),+ _threadsVisible+ ? SuperTabThreadsView(+ attention: SuperTabAttention.of(c),+ onOpen: _openThreadFromList,+ machineName: widget.machineName,+ )+ : const SizedBox.shrink(),],),),diff --git a/desktop/test/super_tab_attention_shots_test.dart b/desktop/test/super_tab_attention_shots_test.dartnew file mode 100644index 000000000..8e7c5b176--- /dev/null+++ b/desktop/test/super_tab_attention_shots_test.dart@@ -0,0 +1,221 @@+import 'dart:io';++import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/attention.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/capture.dart';+import 'support/super_tab_fixture.dart';+import 'swarm_state_test.dart' show createApp;++/// Set to a folder to write the PR's attention pictures there.+final shots = Platform.environment['SUPER_TAB_ATTENTION_SHOTS'];++Map<String, dynamic> _conversation(ConversationServer server, String id) =>+ (server.state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((g) => g['id'] == id);++void _fromLead(ConversationServer server, String text, String id) {+ server.append(text, conversationId: id);+ server.messages.last['author'] = {+ 'kind': 'agent',+ 'id': 'lead-agent',+ 'name': 'Lead',+ };+}++Map<String, dynamic> _root(String id, String text, String at) => {+ 'id': id,+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'lead-agent', 'name': 'Lead'},+ 'text': text,+ 'createdAt': at,+ 'attachments': 0,+};++/// A Swarm with something for the reader: a tag in one workgroup, a decision+/// in another, plain news in a third, and threads with new replies.+ConversationServer _swarm() {+ final server = ConversationServer()..threads = true;+ server.state['projects'] = [+ projectFixture('lead', 'openharness', 'lead'),+ projectFixture('web', 'website', 'web-lead'),+ ];+ final groups = server.state['conversations'] as List;+ _conversation(server, 'offline')+ ..['projectId'] = 'lead'+ ..['number'] = 1600+ ..['title'] = 'Slack attention, wave 1';+ groups+ ..add({+ ...conversationFixture('routing', 'Routing goals piece 5'),+ 'projectId': 'lead',+ 'number': 1598,+ })+ ..add({+ ...conversationFixture('roster', 'Desktop roster'),+ 'projectId': 'lead',+ 'number': 1597,+ })+ ..add({...conversationFixture('web-lead', 'Lead'), 'projectId': 'web'});+ _fromLead(server, 'Release notes are up.', 'roster');+ server.markReadElsewhere('roster', server.revision);+ _fromLead(server, 'Mockup posted for review.', 'offline');+ server.tag('message-2', conversationId: 'offline');+ _fromLead(+ server,+ 'Heavy CI is held while the account is at its limit.',+ 'routing',+ );+ _fromLead(server, 'Which option should ship?', 'web-lead');+ server.ask(+ ['Ship it behind a flag?'],+ conversationId: 'web-lead',+ projectId: 'web',+ );+ server.tag('message-1', threadId: 'message-1');+ _fromLead(server, 'Weekly plan', 'lead');+ _fromLead(server, 'Looks right to me.', 'lead');+ server.messages.last['thread'] =+ server.messages[server.messages.length - 2]['id'];+ server.followedThreads = {+ 'unread': [+ {+ 'conversationId': 'lead',+ 'rootId': server.messages[server.messages.length - 2]['id'],+ 'root': _root(+ server.messages[server.messages.length - 2]['id'] as String,+ 'Weekly plan: badges first, then the Threads view.',+ '2026-10-31T01:00:00Z',+ ),+ 'lastReplyAt': '2026-10-31T02:00:00Z',+ 'lastReplySequence': server.revision,+ 'lastReplier': {'kind': 'agent', 'id': 'lead-agent', 'name': 'Lead'},+ 'unreadReplies': 1,+ 'follow': null,+ },+ ],+ 'read': [+ {+ 'conversationId': 'routing',+ 'rootId': 'message-old',+ 'root': _root(+ 'message-old',+ 'Should heavy CI wait while the account is at its job limit?',+ '2026-10-30T01:00:00Z',+ ),+ 'replies': 12,+ 'lastReplyAt': '2026-10-30T09:15:00Z',+ 'lastReplySequence': 4,+ 'lastReplier': null,+ 'follow': null,+ },+ ],+ 'more': false,+ };+ return server;+}++void main() {+ setUpAll(() => loadCaptureFonts(shots));++ for (final brightness in Brightness.values) {+ for (final scene in ['sidebar', 'threads', 'threads-hover', 'hover']) {+ testWidgets('attention: $scene in ${brightness.name}', (tester) async {+ if (shots == null) return;+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ tester.view.devicePixelRatio = 2;+ tester.view.physicalSize = const Size(2400, 1400);+ addTearDown(tester.view.reset);+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ final server = _swarm();+ final c = server.controller(+ initial: {+ 'tabId': 'tab',+ 'accountId': 'owner',+ 'selectedId': 'roster',+ },+ );+ await c.refresh();+ final attention = SuperTabAttention.of(c);+ await attention.mentions.load();+ await attention.decisions.load();+ await attention.load();+ c.select('roster');+ if (!c.expandedProjects.contains('lead')) c.toggleProject('lead');+ final picture = GlobalKey();+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ home: RepaintBoundary(+ key: picture,+ child: Scaffold(+ body: SuperTabView(+ controller: c,+ app: app,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ onNewProject: () {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ if (scene.startsWith('threads')) {+ await tester.tap(find.byKey(const ValueKey('super-threads')));+ await tester.pumpAndSettle();+ await tester.pumpAndSettle();+ }+ if (scene == 'threads-hover') {+ final mouse = await tester.createGesture(+ kind: PointerDeviceKind.mouse,+ );+ await mouse.addPointer(location: Offset.zero);+ await mouse.moveTo(+ tester.getCenter(+ find.text(+ 'Should heavy CI wait while the account is at its job limit?',+ ),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(mouse.removePointer);+ }+ if (scene == 'hover') {+ final mouse = await tester.createGesture(+ kind: PointerDeviceKind.mouse,+ );+ await mouse.addPointer(location: Offset.zero);+ await mouse.moveTo(+ tester.getCenter(+ find.byKey(const ValueKey('super-project-toggle-web')),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(mouse.removePointer);+ }+ await captureBoundary(+ tester,+ picture.currentContext!.findRenderObject()! as RenderRepaintBoundary,+ shots,+ 'attention-$scene-${brightness.name}',+ );+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));+ }+ }+}diff --git a/desktop/test/super_tab_attention_test.dart b/desktop/test/super_tab_attention_test.dartnew file mode 100644index 000000000..4db4e014f--- /dev/null+++ b/desktop/test/super_tab_attention_test.dart@@ -0,0 +1,1048 @@+import 'dart:async';++import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:fake_async/fake_async.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/attention.dart';+import 'package:harness/super_tabs/buddy_rows.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/project_sidebar.dart';+import 'package:harness/super_tabs/threads_view.dart';+import 'package:harness/widgets/desktop_chrome.dart';++import 'support/super_tab_fixture.dart';++/// A message from the Lead agent, never the reader's own.+void fromLead(+ ConversationServer server,+ String text, {+ String conversationId = 'lead',+}) {+ server.append(text, conversationId: conversationId);+ server.messages.last['author'] = {+ 'kind': 'agent',+ 'id': 'lead-agent',+ 'name': 'Lead',+ };+}++Map<String, dynamic> conversation(ConversationServer server, String id) =>+ (server.state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((g) => g['id'] == id);++/// One project, "web-project", whose chat is `lead` and whose workgroup is+/// `offline`.+ConversationServer projectServer() {+ final server = ConversationServer()..threads = true;+ server.state['projects'] = [projectFixture('lead', 'web-project', 'lead')];+ conversation(server, 'offline')+ ..['projectId'] = 'lead'+ ..['number'] = 12;+ return server;+}++Map<String, dynamic> preview(String id, int sequence, String text) => {+ 'id': id,+ 'sequence': sequence,+ 'author': {'kind': 'agent', 'id': 'lead-agent', 'name': 'Lead'},+ 'text': text,+ 'createdAt': '2026-10-31T01:00:00Z',+ 'attachments': 0,+};++Map<String, dynamic> unreadThread(+ String root,+ int lastReply, {+ String conversationId = 'lead',+ int unread = 1,+ String text = 'Root text',+}) => {+ 'conversationId': conversationId,+ 'rootId': root,+ 'root': preview(root, 1, text),+ 'lastReplyAt': '2026-10-31T02:00:00Z',+ 'lastReplySequence': lastReply,+ 'lastReplier': {'kind': 'agent', 'id': 'lead-agent', 'name': 'Lead'},+ 'unreadReplies': unread,+ 'follow': null,+};++Map<String, dynamic> readThread(+ String root,+ int lastReply, {+ String conversationId = 'lead',+ String text = 'Older root',+ bool? follow,+}) => {+ 'conversationId': conversationId,+ 'rootId': root,+ 'root': preview(root, 1, text),+ 'replies': 3,+ 'lastReplyAt': '2026-10-30T02:00:00Z',+ 'lastReplySequence': lastReply,+ 'lastReplier': null,+ 'follow': follow,+};++/// A controller for a widget test, closed by [close] inside the test so no+/// save is left pending.+Future<SuperTabController> openHere(ConversationServer server) async {+ final c = server.controller();+ await c.refresh();+ return c;+}++Future<void> close(WidgetTester tester, SuperTabController c) async {+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+}++Future<SuperTabController> open(ConversationServer server) async {+ final c = server.controller();+ addTearDown(() async {+ await c.flush();+ c.dispose();+ });+ await c.refresh();+ return c;+}++/// Lets the tag, decision and thread reads the last state read set off+/// answer.+Future<void> settle(SuperTabController c) async {+ for (var i = 0; i < 5; i++) {+ await pumpEventQueue();+ }+}++Future<void> pumpSidebar(+ WidgetTester tester,+ SuperTabController c,+ SuperTabAttention attention, {+ Brightness brightness = Brightness.dark,+ bool threadsSelected = false,+}) async {+ await tester.binding.setSurfaceSize(const Size(300, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: ListenableBuilder(+ listenable: c,+ builder: (context, _) => ProjectSidebar(+ controller: c,+ onAddAgent: (_) {},+ needsHuman: (_) => 0,+ onSelect: c.select,+ attention: attention,+ onThreads: () {},+ threadsSelected: threadsSelected,+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+}++Finder inRow(String key, Finder finder) =>+ find.descendant(of: find.byKey(ValueKey(key)), matching: finder);++Text rowText(WidgetTester tester, String key, String text) =>+ tester.widget<Text>(inRow(key, find.text(text)));++void main() {+ group('the red number counts only what is for the reader', () {+ testWidgets('a tag in the chat counts on its row; a tag in a thread on '+ 'Threads; a decision on its row; plain unread is bold with no '+ 'number', (tester) async {+ final server = projectServer();+ server.followedThreads = {'unread': [], 'read': [], 'more': false};+ fromLead(server, 'Plain news', conversationId: 'offline');+ server.tag('message-1', conversationId: 'offline');+ server.tag('message-1', conversationId: 'offline', threadId: 'message-1');+ server.ask(['Ship it?'], conversationId: 'offline');+ fromLead(server, 'Plain news in the project chat');+ final c = await openHere(server);+ final attention = SuperTabAttention.of(c);+ await attention.mentions.load();+ await attention.decisions.load();+ c.toggleProject('lead');+ await pumpSidebar(tester, c, attention);+ // The workgroup: one tag in its chat and one decision, not the tag in+ // its thread.+ expect(+ inRow('super-group-offline', find.byType(SuperTabCountBadge)),+ findsOneWidget,+ );+ expect(inRow('super-group-offline', find.text('2')), findsOneWidget);+ // Threads carries the tag inside a thread.+ expect(inRow('super-threads', find.text('1')), findsOneWidget);+ // The project chat: unread, nothing for the reader, so no number.+ expect(+ inRow('super-group-lead', find.byType(SuperTabCountBadge)),+ findsNothing,+ );+ expect(+ rowText(tester, 'super-group-lead', 'web-project').style?.fontWeight,+ grid.AppFont.semibold,+ );+ await close(tester, c);+ });++ testWidgets('a collapsed project counts the tags of the workgroups it '+ 'hides', (tester) async {+ final server = projectServer();+ server.followedThreads = {'unread': [], 'read': [], 'more': false};+ fromLead(server, 'News', conversationId: 'offline');+ server.tag('message-1', conversationId: 'offline');+ server.tag('message-1');+ final c = await openHere(server);+ final attention = SuperTabAttention.of(c);+ await attention.mentions.load();+ await pumpSidebar(tester, c, attention);+ expect(inRow('super-group-lead', find.text('2')), findsOneWidget);+ c.toggleProject('lead');+ await tester.pumpAndSettle();+ expect(inRow('super-group-lead', find.text('1')), findsOneWidget);+ expect(inRow('super-group-offline', find.text('1')), findsOneWidget);+ await close(tester, c);+ });+ });++ group('read rows are muted, unread rows full strength and bold', () {+ for (final brightness in Brightness.values) {+ testWidgets('in $brightness', (tester) async {+ final server = projectServer();+ server.followedThreads = {+ 'unread': [unreadThread('message-1', 2)],+ 'read': [],+ 'more': false,+ };+ // A second workgroup, open on screen, so the project's row is+ // neither selected nor unread.+ (server.state['conversations'] as List).add({+ ...conversationFixture('open', 'Open now'),+ 'projectId': 'lead',+ 'number': 13,+ });+ fromLead(server, 'Read news');+ server.markReadElsewhere('lead', server.revision);+ fromLead(server, 'Unread news', conversationId: 'offline');+ final c = await openHere(server);+ final attention = SuperTabAttention.of(c);+ await attention.load();+ c.select('open');+ if (!c.expandedProjects.contains('lead')) c.toggleProject('lead');+ await pumpSidebar(tester, c, attention, brightness: brightness);+ final read = rowText(tester, 'super-group-lead', 'web-project');+ expect(read.style?.color, DesktopChrome.muted);+ expect(read.style?.fontWeight, isNot(grid.AppFont.semibold));+ final unread = tester.widget<Text>(+ find+ .descendant(+ of: find.byKey(const ValueKey('super-group-offline')),+ matching: find.byType(Text),+ )+ .first,+ );+ expect(unread.style?.color, DesktopChrome.foreground);+ expect(unread.style?.fontWeight, grid.AppFont.semibold);+ // Threads: a followed thread has new replies.+ final threads = rowText(tester, 'super-threads', 'Threads');+ expect(threads.style?.color, DesktopChrome.foreground);+ expect(threads.style?.fontWeight, grid.AppFont.semibold);+ await close(tester, c);+ });+ }++ testWidgets('Threads is muted with nothing new', (tester) async {+ final server = projectServer();+ server.followedThreads = {+ 'unread': [],+ 'read': [readThread('message-1', 2)],+ 'more': false,+ };+ final c = await openHere(server);+ final attention = SuperTabAttention.of(c);+ await attention.load();+ await pumpSidebar(tester, c, attention);+ final threads = rowText(tester, 'super-threads', 'Threads');+ expect(threads.style?.color, DesktopChrome.muted);+ expect(threads.style?.fontWeight, isNot(grid.AppFont.semibold));+ await close(tester, c);+ });+ });++ testWidgets('a project row lights whole on hover, chevron included, as wide '+ 'as its selected highlight', (tester) async {+ final server = projectServer();+ server.followedThreads = {'unread': [], 'read': [], 'more': false};+ final c = await openHere(server);+ final attention = SuperTabAttention.of(c);+ c.select('offline');+ await pumpSidebar(tester, c, attention);+ final toggle = find.byKey(const ValueKey('super-project-toggle-lead'));+ final groundFinder = find+ .ancestor(of: toggle, matching: find.byType(Material))+ .first;+ Material ground() => tester.widget<Material>(groundFinder);+ expect(ground().color, Colors.transparent);+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ addTearDown(mouse.removePointer);+ await mouse.addPointer(location: Offset.zero);+ await mouse.moveTo(tester.getCenter(toggle));+ await tester.pumpAndSettle();+ // The whole row's ground, the one that holds the chevron too.+ expect(ground().color, grid.AppSurface.hoverFill);+ await mouse.moveTo(+ tester.getCenter(inRow('super-group-lead', find.text('web-project'))),+ );+ await tester.pumpAndSettle();+ expect(ground().color, grid.AppSurface.hoverFill);+ final hovered = tester.getRect(groundFinder);+ expect(hovered.right, greaterThanOrEqualTo(tester.getRect(toggle).right));+ c.select('lead');+ await tester.pumpAndSettle();+ expect(ground().color, grid.AppSurface.selectedFill);+ expect(tester.getRect(groundFinder), hovered);+ await close(tester, c);+ });++ group('review of 99b8018', () {+ test('a thread read during the visit keeps its new-reply count after '+ 'the list is read again', () async {+ final server = projectServer();+ server.followedThreads = {+ 'unread': [unreadThread('message-1', 3, unread: 2)],+ 'read': [],+ 'more': false,+ };+ final c = await open(server);+ final attention = SuperTabAttention.of(c)..opened();+ await attention.load();+ final thread = attention.shown.single;+ expect(attention.newCount(thread), 2);+ // Read now: the server lists it among the read ones, with no count.+ server.followedThreads = {+ 'unread': [],+ 'read': [readThread('message-1', 3)],+ 'more': false,+ };+ await attention.load();+ final reloaded = attention.shown.single;+ expect(attention.isNew(reloaded), isTrue);+ expect(attention.newCount(reloaded), 2);+ attention.closed();+ expect(attention.newCount(reloaded), 0);+ });++ test('a change inside the gap is read once the gap is over, and the '+ 'wait stops with the controller', () {+ fakeAsync((async) {+ var now = DateTime(2026, 10, 31, 9);+ final server = projectServer();+ server.followedThreads = {'unread': [], 'read': [], 'more': false};+ final c = server.controller();+ unawaited(c.refresh());+ async.flushMicrotasks();+ final attention = SuperTabAttention.forTest(c, now: () => now);+ // On screen, as the sidebar shows it.+ void shown() {}+ attention.addListener(shown);+ async.flushMicrotasks();+ final reads = server.threadListReads.length;+ expect(reads, greaterThan(0));+ // A change 5 s after the read: inside the 15 s gap.+ now = now.add(const Duration(seconds: 5));+ async.elapse(const Duration(seconds: 5));+ fromLead(server, 'News');+ unawaited(c.refresh());+ async.flushMicrotasks();+ expect(server.threadListReads.length, reads);+ // The gap ends: the change is read without another one.+ now = now.add(const Duration(seconds: 11));+ async.elapse(const Duration(seconds: 11));+ expect(server.threadListReads.length, reads + 1);+ // Another change in the next gap, then the controller goes.+ now = now.add(const Duration(seconds: 1));+ fromLead(server, 'More');+ unawaited(c.refresh());+ async.flushMicrotasks();+ expect(async.pendingTimers, isNotEmpty);+ // Nothing shows it any more: nothing is waited for.+ attention.removeListener(shown);+ expect(async.pendingTimers, isEmpty);+ attention.addListener(shown);+ fromLead(server, 'Again');+ unawaited(c.refresh());+ async.flushMicrotasks();+ expect(async.pendingTimers, isNotEmpty);+ unawaited(c.flush());+ async.flushMicrotasks();+ c.dispose();+ expect(async.pendingTimers, isEmpty);+ async.elapse(const Duration(seconds: 30));+ expect(server.threadListReads.length, reads + 1);+ expect(attention.unread, isEmpty);+ });+ });++ test('no red number once access is gone, nor for a tag in a chat the '+ 'Swarm no longer lists', () async {+ final server = projectServer();+ server.followedThreads = {'unread': [], 'read': [], 'more': false};+ server.tag('message-1', threadId: 'message-1', messageSequence: 2);+ server.tag(+ 'message-9',+ conversationId: 'gone',+ threadId: 'message-9',+ messageSequence: 2,+ );+ server.tag('message-1', conversationId: 'offline', messageSequence: 2);+ var revoked = false;+ final c = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ request: (method, path, {body}) {+ if (revoked &&+ (path.contains('/parts') || path.contains('/changes'))) {+ throw const SuperTabFailure(+ 'FORBIDDEN',+ 'No access.',+ statusCode: 403,+ );+ }+ return server.request(method, path, body: body);+ },+ save: server.save,+ pollInterval: Duration.zero,+ );+ addTearDown(() async {+ await c.flush();+ c.dispose();+ });+ await c.refresh();+ final attention = SuperTabAttention.of(c);+ await attention.mentions.load();+ // The tag in a chat the Swarm does not list counts nowhere.+ expect(attention.threadMentions, 1);+ expect(attention.mentionsIn('offline'), 1);+ // The moment access is gone, before anything is cleared.+ c.accessRevoked = true;+ expect(attention.threadMentions, 0);+ expect(attention.mentionsIn('offline'), 0);+ c.accessRevoked = false;+ revoked = true;+ fromLead(server, 'After access went');+ await c.refresh();+ expect(c.accessRevoked, isTrue);+ expect(attention.threadMentions, 0);+ expect(attention.mentionsIn('offline'), 0);+ });++ test('a tag stops counting once the reader has read past it, answered '+ 'or not; a decision once its chat is read', () async {+ final server = projectServer();+ server.followedThreads = {'unread': [], 'read': [], 'more': false};+ fromLead(server, 'Please look', conversationId: 'offline');+ server.tag(+ 'message-1',+ conversationId: 'offline',+ messageSequence: server.revision,+ );+ server.ask(['Ship it?'], conversationId: 'offline');+ final c = await open(server);+ final attention = SuperTabAttention.of(c);+ await attention.mentions.load();+ await attention.decisions.load();+ expect(attention.mentionsIn('offline'), 2);+ // Read on another device, past the tagged message.+ server.markReadElsewhere('offline', server.revision);+ await c.refresh();+ expect(attention.mentions.waiting, hasLength(1));+ expect(attention.mentionsIn('offline'), 0);+ // A tag in a thread clears once the thread is read past it.+ server.tag(+ 'message-1',+ threadId: 'message-1',+ messageSequence: server.revision,+ );+ await c.refresh();+ await attention.mentions.load();+ expect(attention.threadMentions, 1);+ server.markThreadReadElsewhere('lead', 'message-1', server.revision);+ await c.refresh();+ expect(attention.threadMentions, 0);+ });+ });++ group('the Threads list', () {+ test('lists threads with new replies first, then the rest; showing one '+ 'reads its new replies and marks it read on every device', () async {+ final server = projectServer();+ fromLead(server, 'Root');+ fromLead(server, 'Old reply');+ server.messages.last['thread'] = 'message-1';+ fromLead(server, 'New reply');+ server.messages.last['thread'] = 'message-1';+ server.followedThreads = {+ 'unread': [unreadThread('message-1', 3)],+ 'read': [readThread('message-9', 7, follow: true)],+ 'more': false,+ };+ conversation(server, 'lead')['lastMainSequence'] = 1;+ server.markThreadReadElsewhere('lead', 'message-1', 2);+ final c = await open(server);+ final attention = SuperTabAttention.of(c)..opened();+ await attention.load();+ expect(attention.shown.map((t) => t.rootId), ['message-1', 'message-9']);+ expect(attention.isNew(attention.shown.first), isTrue);+ expect(attention.isNew(attention.shown.last), isFalse);+ await attention.showReplies(attention.shown.first);+ expect(attention.newReplies['lead/message-1']!.map((m) => m.text), [+ 'New reply',+ ]);+ expect(server.threadMarkPosts.last, {+ 'conversationId': 'lead',+ 'root': 'message-1',+ 'sequence': 3,+ });+ // Read now, it stays new until the view is left.+ server.followedThreads = {+ 'unread': [],+ 'read': [readThread('message-1', 3), readThread('message-9', 7)],+ 'more': false,+ };+ await attention.load();+ expect(attention.isNew(attention.shown.first), isTrue);+ attention.closed();+ expect(attention.shown.every((t) => !attention.isNew(t)), isTrue);+ });++ test('Unfollow is kept on the server and the list read again', () async {+ final server = projectServer();+ server.followedThreads = {+ 'unread': [],+ 'read': [readThread('message-9', 7)],+ 'more': false,+ };+ final c = await open(server);+ final attention = SuperTabAttention.of(c);+ await attention.load();+ final reads = server.threadListReads.length;+ expect(await attention.setFollow(attention.read.single, false), isTrue);+ await pumpEventQueue();+ expect(server.followPosts.single, {+ 'conversationId': 'lead',+ 'root': 'message-9',+ 'follow': false,+ });+ expect(server.threadListReads.length, greaterThan(reads));+ });++ test('a server before followed threads lists the inbox\'s unread ones '+ 'and offers no Follow', () async {+ final server = projectServer()+ ..inbox = {+ 'threads': [unreadThread('message-1', 3)],+ 'latest': [],+ 'more': false,+ };+ final c = await open(server);+ final attention = SuperTabAttention.of(c);+ await attention.load();+ expect(attention.unread.single.rootId, 'message-1');+ expect(attention.followSupported, isFalse);+ expect(+ await attention.setFollow(attention.unread.single, false),+ isFalse,+ );+ expect(server.followPosts, isEmpty);+ // It does not ask the missing route again.+ await attention.load();+ expect(+ server.threadListReads.where((p) => p.endsWith('/threads')),+ hasLength(1),+ );+ });++ test('a thread in a chat the reader no longer has is not listed', () async {+ final server = projectServer();+ server.followedThreads = {+ 'unread': [unreadThread('message-1', 3, conversationId: 'elsewhere')],+ 'read': [readThread('message-2', 3, conversationId: 'gone')],+ 'more': false,+ };+ final c = await open(server);+ final attention = SuperTabAttention.of(c);+ await attention.load();+ expect(attention.loaded, isTrue);+ expect(attention.shown, isEmpty);+ });++ test(+ 'access lost clears the list, and an answer on its way is dropped',+ () async {+ final server = projectServer();+ server.followedThreads = {+ 'unread': [unreadThread('message-1', 3)],+ 'read': [],+ 'more': false,+ };+ var revoked = false;+ final c = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ request: (method, path, {body}) {+ if (revoked &&+ (path.contains('/parts') || path.contains('/changes'))) {+ throw const SuperTabFailure(+ 'FORBIDDEN',+ 'No access.',+ statusCode: 403,+ );+ }+ return server.request(method, path, body: body);+ },+ save: server.save,+ pollInterval: Duration.zero,+ );+ addTearDown(() async {+ await c.flush();+ c.dispose();+ });+ await c.refresh();+ final attention = SuperTabAttention.of(c);+ await attention.load();+ expect(attention.unread, hasLength(1));+ server.holdThreadLists = Completer<void>();+ final late = attention.load();+ await pumpEventQueue();+ // The Swarm refuses the reader: their access is gone.+ revoked = true;+ fromLead(server, 'After access went');+ await c.refresh();+ expect(c.accessRevoked, isTrue);+ expect(attention.unread, isEmpty);+ expect(attention.loaded, isFalse);+ server.holdThreadLists!.complete();+ await late;+ expect(attention.unread, isEmpty);+ expect(attention.threadsUnread, isFalse);+ },+ );++ test('an answer from before the audience changed is dropped, and the '+ 'list is read again', () async {+ final server = projectServer();+ server.followedThreads = {+ 'unread': [unreadThread('message-1', 3)],+ 'read': [],+ 'more': false,+ };+ final c = await open(server);+ final attention = SuperTabAttention.of(c);+ await attention.load();+ final first = server.holdThreadLists = Completer<void>();+ final stale = attention.load();+ await pumpEventQueue();+ // Who may read what changes: the next state read reloads under a new+ // epoch, which clears the list and asks for it again.+ server.parts.epoch++;+ await c.refresh();+ await settle(c);+ expect(attention.unread, isEmpty);+ // The read asked before the change answers with the old list, while+ // the one asked after it is still out.+ final second = server.holdThreadLists = Completer<void>();+ first.complete();+ await settle(c);+ expect(attention.unread, isEmpty);+ expect(attention.loaded, isFalse);+ second.complete();+ await stale;+ await settle(c);+ expect(attention.loaded, isTrue);+ expect(attention.unread, hasLength(1));+ });++ test(+ 'a failed first read shows the failure, and a later read recovers',+ () async {+ final server = projectServer()..failThreadLists = true;+ server.followedThreads = {+ 'unread': [unreadThread('message-1', 3)],+ 'read': [],+ 'more': false,+ };+ final c = await open(server);+ final attention = SuperTabAttention.of(c);+ await attention.load();+ expect(attention.loaded, isFalse);+ expect(attention.error, isNotNull);+ server.failThreadLists = false;+ await attention.load();+ expect(attention.error, isNull);+ expect(attention.loaded, isTrue);+ expect(attention.threadsUnread, isTrue);+ },+ );++ test('asked too often, it waits before reading again, even with the '+ 'Threads view open', () async {+ var now = DateTime(2026, 10, 31, 9);+ final server = projectServer()+ ..failThreadLists = true+ ..threadListStatus = 429;+ server.followedThreads = {'unread': [], 'read': [], 'more': false};+ final c = await open(server);+ final attention = SuperTabAttention.forTest(c, now: () => now);+ addTearDown(attention.dispose);+ // The view open reads every few seconds as the Swarm moves.+ attention.opened();+ await settle(c);+ expect(attention.error, isNotNull);+ final reads = server.threadListReads.length;+ server.failThreadLists = false;+ // Past the open view's pace, short of the wait the refusal asked for.+ now = now.add(const Duration(seconds: 4));+ fromLead(server, 'More');+ await c.refresh();+ await settle(c);+ expect(server.threadListReads.length, reads);+ now = now.add(const Duration(seconds: 2));+ fromLead(server, 'More again');+ await c.refresh();+ await settle(c);+ expect(server.threadListReads.length, reads + 1);+ expect(attention.error, isNull);+ });+ });++ test('reading a chat leaves a reply that lives only in its thread unread: '+ 'the chat\'s mark stops at its newest main-stream message', () async {+ final server = projectServer();+ fromLead(server, 'Root');+ conversation(server, 'lead')['lastMainSequence'] = 1;+ fromLead(server, 'Reply only in the thread');+ server.messages.last['thread'] = 'message-1';+ final c = await open(server);+ await c.loadMessages('lead');+ c.markRead('lead');+ await pumpEventQueue();+ expect(server.readMarkPosts.last, {+ 'conversationId': 'lead',+ 'sequence': 1,+ });+ });++ testWidgets('the Threads view shows new replies under their root with a '+ 'reply box, the rest after, and Unfollow', (tester) async {+ final server = projectServer();+ fromLead(server, 'Root');+ fromLead(server, 'Fresh reply');+ server.messages.last['thread'] = 'message-1';+ conversation(server, 'lead')['lastMainSequence'] = 1;+ server.followedThreads = {+ 'unread': [unreadThread('message-1', 2, text: 'Root')],+ 'read': [readThread('message-7', 5, text: 'Settled question')],+ 'more': false,+ };+ final c = await openHere(server);+ final attention = SuperTabAttention.of(c);+ await attention.load();+ String? opened;+ await tester.binding.setSurfaceSize(const Size(700, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabThreadsView(+ attention: attention,+ onOpen: (id, root) => opened = '$id/$root',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(find.text('New replies'), findsOneWidget);+ expect(find.text('Earlier'), findsOneWidget);+ expect(+ tester.getTopLeft(find.text('Root')).dy,+ lessThan(tester.getTopLeft(find.text('Settled question')).dy),+ );+ expect(find.text('Fresh reply'), findsOneWidget);+ expect(find.text('1 new reply'), findsOneWidget);+ expect(+ find.byKey(const ValueKey('super-thread-reply-lead/message-1')),+ findsOneWidget,+ );+ expect(+ find.byKey(const ValueKey('super-thread-reply-lead/message-7')),+ findsNothing,+ );+ expect(server.threadMarkPosts.last['root'], 'message-1');+ await tester.tap(find.text('Root'));+ expect(opened, 'lead/message-1');+ // The reply box is the thread pane's own: attach and the arrow send.+ final box = find.byKey(+ const ValueKey('super-thread-reply-surface-lead/message-1'),+ );+ expect(+ find.descendant(of: box, matching: find.byTooltip('Send reply')),+ findsOneWidget,+ );+ expect(find.text('Send'), findsNothing);+ await tester.enterText(+ find.byKey(const ValueKey('super-thread-reply-lead/message-1')),+ 'On it',+ );+ await tester.pump();+ await tester.tap(+ find.byKey(const ValueKey('super-thread-send-lead/message-1')),+ );+ await tester.pumpAndSettle();+ final sent = server.posts.last['command'] as Map;+ expect(sent['type'], 'message.send');+ expect(sent['conversationId'], 'lead');+ expect(sent['replyTo'], 'message-1');+ expect(sent['text'], 'On it');+ Opacity more(String key) => tester.widget<Opacity>(+ find+ .ancestor(+ of: find.byKey(ValueKey('super-thread-more-$key')),+ matching: find.byType(Opacity),+ )+ .first,+ );+ // Unfollow is quiet: its ⋯ shows only while the card is pointed at, or+ // focused (the reply box focused shows its card's).+ expect(more('lead/message-1').opacity, 1);+ FocusManager.instance.primaryFocus?.unfocus();+ await tester.pumpAndSettle();+ expect(find.text('Unfollow'), findsNothing);+ expect(more('lead/message-7').opacity, 0);+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ addTearDown(mouse.removePointer);+ await mouse.addPointer(location: Offset.zero);+ await mouse.moveTo(tester.getCenter(find.text('Settled question')));+ await tester.pumpAndSettle();+ expect(more('lead/message-7').opacity, 1);+ expect(more('lead/message-1').opacity, 0);+ await tester.tap(+ find.descendant(+ of: find.byKey(const ValueKey('super-thread-more-lead/message-7')),+ matching: find.byTooltip('More'),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.text('Unfollow thread'));+ await tester.pumpAndSettle();+ expect(server.followPosts.single['follow'], isFalse);+ await close(tester, c);+ });++ testWidgets('a read workgroup with a tag of the reader is never behind '+ '"… N more"', (tester) async {+ final server = projectServer();+ server.followedThreads = {'unread': [], 'read': [], 'more': false};+ final groups = server.state['conversations'] as List;+ // Nine newer workgroups than "offline" (number 12), all read.+ for (var n = 20; n < 29; n++) {+ groups.add({+ ...conversationFixture('g$n', 'Work $n'),+ 'projectId': 'lead',+ 'number': n,+ });+ }+ fromLead(server, 'Please look', conversationId: 'offline');+ // From a server that does not say where the tag is: it counts until+ // answered, though the chat is read.+ server.tag('message-1', conversationId: 'offline');+ server.markReadElsewhere('offline', server.revision);+ final c = await openHere(server);+ final attention = SuperTabAttention.of(c);+ await attention.mentions.load();+ expect(c.unread(c.snapshot!.conversation('offline')!), isFalse);+ c.toggleProject('lead');+ await pumpSidebar(tester, c, attention);+ expect(+ find.byKey(const ValueKey('super-project-more-lead')),+ findsOneWidget,+ );+ expect(find.byKey(const ValueKey('super-group-offline')), findsOneWidget);+ expect(inRow('super-group-offline', find.text('1')), findsOneWidget);+ await close(tester, c);+ });++ testWidgets('a thread in the reader\'s Buddy chat offers Open thread to '+ 'reply, not a box its ended session would refuse', (tester) async {+ final server = projectServer();+ (server.state['conversations'] as List).add({+ ...conversationFixture('buddy-owner-lead', "owner's Buddy"),+ 'kind': 'buddy',+ 'projectId': 'lead',+ 'buddyOwnerId': 'owner',+ });+ server.followedThreads = {+ 'unread': [+ unreadThread(+ 'message-1',+ 2,+ conversationId: 'buddy-owner-lead',+ text: 'Plan the week',+ ),+ ],+ 'read': [],+ 'more': false,+ };+ final c = await openHere(server);+ final attention = SuperTabAttention.of(c);+ await attention.load();+ String? opened;+ await tester.binding.setSurfaceSize(const Size(700, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabThreadsView(+ attention: attention,+ onOpen: (id, root) => opened = '$id/$root',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(+ find.byKey(+ const ValueKey('super-thread-reply-buddy-owner-lead/message-1'),+ ),+ findsNothing,+ );+ await tester.tap(find.text('Open thread to reply'));+ expect(opened, 'buddy-owner-lead/message-1');+ await close(tester, c);+ });++ group('tags from the Threads view (merge check of 67c32a3)', () {+ /// Kestrel is an agent of "offline", not of "lead"; "offline" has a+ /// thread at message-1 with a new reply.+ ConversationServer tagged() {+ final server = projectServer();+ server.state['agents'] = [+ {+ 'id': 'kestrel',+ 'name': 'Builder',+ 'displayName': 'Kestrel',+ 'machineId': 'host',+ 'harnessId': 'session',+ 'contributorId': 'owner',+ 'configuration': {'engine': 'codex'},+ },+ ];+ conversation(server, 'offline')['agentIds'] = ['kestrel'];+ fromLead(server, 'Root', conversationId: 'offline');+ fromLead(server, 'Reply', conversationId: 'offline');+ server.messages.last['thread'] = 'message-1';+ conversation(server, 'offline')['lastMainSequence'] = 1;+ server.followedThreads = {+ 'unread': [+ unreadThread('message-1', 2, conversationId: 'offline', text: 'Root'),+ ],+ 'read': [],+ 'more': false,+ };+ return server;+ }++ test('a reply tagging an agent of the thread\'s own chat goes, whichever '+ 'chat is selected', () async {+ final server = tagged();+ final c = await open(server);+ c.select('lead');+ const to = (conversationId: 'offline', root: 'message-1');+ c.setThreadDraft('message-1', '@Kestrel please look');+ c.threadMention('kestrel', '@Kestrel', to: to);+ expect(c.threadMentions('offline', 'message-1'), {'kestrel': '@Kestrel'});+ await c.sendThreadReply(to: to);+ expect(c.operationError, isNull);+ final sent = server.posts.last['command'] as Map;+ expect(sent['conversationId'], 'offline');+ expect(sent['replyTo'], 'message-1');+ expect(sent['recipientIds'], ['kestrel']);+ });++ testWidgets('the Threads view\'s box offers @ as the thread pane does: '+ 'whom the thread\'s chat offers, Backspace takes a tag whole, and the '+ 'reply carries it', (tester) async {+ final server = tagged();+ final c = await openHere(server);+ c.select('lead');+ final attention = SuperTabAttention.of(c);+ await attention.load();+ await tester.binding.setSurfaceSize(const Size(700, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabThreadsView(+ attention: attention,+ onOpen: (_, _) {},+ machineName: (_) => 'Studio',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ final field = find.byKey(+ const ValueKey('super-thread-reply-offline/message-1'),+ );+ final picker = find.byKey(+ const ValueKey('super-thread-completions-offline/message-1'),+ );+ await tester.tap(field);+ await tester.enterText(field, '@Kes');+ await tester.pumpAndSettle();+ expect(picker, findsOneWidget);+ expect(+ find.descendant(of: picker, matching: find.textContaining('Kestrel')),+ findsWidgets,+ );+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(picker, findsNothing);+ expect(tester.widget<TextField>(field).controller!.text, '@Kestrel ');+ expect(c.threadMentions('offline', 'message-1'), {'kestrel': '@Kestrel'});+ // Backspace into the tag takes it whole.+ await tester.sendKeyEvent(LogicalKeyboardKey.backspace);+ await tester.sendKeyEvent(LogicalKeyboardKey.backspace);+ await tester.pumpAndSettle();+ expect(tester.widget<TextField>(field).controller!.text, '');+ // Picked again and sent: the reply carries the tag.+ await tester.enterText(field, '@Kes');+ await tester.pumpAndSettle();+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ await tester.enterText(field, '@Kestrel please look');+ await tester.pumpAndSettle();+ await tester.tap(+ find.byKey(const ValueKey('super-thread-send-offline/message-1')),+ );+ await tester.pumpAndSettle();+ final sent = server.posts.last['command'] as Map;+ expect(sent['conversationId'], 'offline');+ expect(sent['recipientIds'], ['kestrel']);+ await close(tester, c);+ });+ });+}diff --git a/desktop/test/super_tab_sidebar_cleanup_test.dart b/desktop/test/super_tab_sidebar_cleanup_test.dartindex 78e2e0078..19c5fba6c 100644--- a/desktop/test/super_tab_sidebar_cleanup_test.dart+++ b/desktop/test/super_tab_sidebar_cleanup_test.dart@@ -78,18 +78,21 @@ Future<void> closeSwarm(WidgetTester tester, SuperTabController c) async {}void main() {- testWidgets(- 'on a Mac the top reads New project, Your devices, Your models: what '- 'needs the person is in the menu bar and on the Dock instead',- (tester) async {- final c = await showSwarm(tester);- expect(topRows(tester), ['New project', 'Your devices', 'Your models']);- expect(find.byKey(const ValueKey('super-notifications')), findsNothing);- expect(tester.takeException(), isNull);- await closeSwarm(tester, c);- },- variant: TargetPlatformVariant.only(TargetPlatform.macOS),- );+ testWidgets('on a Mac the top reads New project, Your devices, Your models, '+ 'Threads: the tags and decisions waiting are in the menu bar and on the '+ 'Dock instead', (tester) async {+ final c = await showSwarm(tester);+ // Threads stays: the threads a person follows are not in the menu bar.+ expect(topRows(tester), [+ 'New project',+ 'Your devices',+ 'Your models',+ 'Threads',+ ]);+ expect(find.byKey(const ValueKey('super-notifications')), findsNothing);+ expect(tester.takeException(), isNull);+ await closeSwarm(tester, c);+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));testWidgets('with no menu-bar list to carry them, Notifications stays last with its '@@ -100,6 +103,7 @@ void main() {'New project','Your devices','Your models',+ 'Threads','Notifications3',]);await closeSwarm(tester, c);diff --git a/desktop/test/super_tab_sidebar_rows_test.dart b/desktop/test/super_tab_sidebar_rows_test.dartindex 6af9c6e85..25c064ad0 100644--- a/desktop/test/super_tab_sidebar_rows_test.dart+++ b/desktop/test/super_tab_sidebar_rows_test.dart@@ -248,10 +248,16 @@ void main() {await controller.select('offline');await controller.refresh();await tester.pumpAndSettle();- expect(weightOf(tester, project, 'Pilot'), grid.AppFont.semibold);+ // Open, the project's row is its own chat's, as in Slack: only the+ // workgroup with news is bold (Dee, 10-31).+ expect(weightOf(tester, project, 'Pilot'), isNot(grid.AppFont.semibold));expect(weightOf(tester, g1, name), grid.AppFont.semibold);expect(unreadDot(project), findsNothing);expect(unreadDot(g1), findsNothing);+ // Collapsed, it is bold for what it hides.+ await tester.tap(toggle);+ await tester.pumpAndSettle();+ expect(weightOf(tester, project, 'Pilot'), grid.AppFont.semibold);await close(tester, controller);},);@@ -274,9 +280,13 @@ void main() {await controller.select('offline');await controller.refresh();await tester.pumpAndSettle();- expect(spoken(tester, project), contains('Unread messages'));+ expect(spoken(tester, project), isNot(contains('Unread messages')));expect(spoken(tester, g1), contains('Unread messages'));expect(spoken(tester, g2), isNot(contains('Unread messages')));+ // Collapsed, the project is heard as unread for what it hides.+ await tester.tap(toggle);+ await tester.pumpAndSettle();+ expect(spoken(tester, project), contains('Unread messages'));semantics.dispose();await close(tester, controller);},diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex bb6773565..1cbea88ac 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -488,6 +488,30 @@ class ConversationServer {var failLeaderboardReads = 0;// The reader's tags, newest last, answered by GET .../mentions?state=.final mentions = <Map<String, dynamic>>[];++ /// The followed-threads read's answer (backend read/followedThreads.ts):+ /// `{unread, read, more}`; null answers 404, as a server before it does,+ /// and the inbox ([inbox]) is read instead.+ Map<String, dynamic>? followedThreads;++ /// The inbox read's answer (backend read/inbox.ts): `{threads, latest,+ /// more}`; null answers 404.+ Map<String, dynamic>? inbox;++ /// Every followed-threads and inbox read, by path.+ final threadListReads = <String>[];++ /// While set, followed-threads reads wait for it: an answer that arrives+ /// late.+ Completer<void>? holdThreadLists;++ /// Followed-threads reads fail as offline, or with [threadListStatus].+ bool failThreadLists = false;+ int threadListStatus = 503;++ /// The Follow and Unfollow writes, in order: {conversationId, root, follow}.+ final followPosts = <Map<String, dynamic>>[];+ bool failFollows = false;// Decisions asked of the reader, newest last, answered by GET .../decisions?state=.final decisions = <Map<String, dynamic>>[];// How many times a decisions list was read (open and answered each count).@@ -907,6 +931,25 @@ class ConversationServer {? RegExp(r'/conversations/([^/]+)/threads/([^/]+)/read$').firstMatch(path): null;+ final follow = method == 'POST'+ ? RegExp(r'/conversations/([^/]+)/threads/([^/]+)/follow$')+ .firstMatch(path)+ : null;+ if (follow != null) {+ followPosts.add({+ 'conversationId': Uri.decodeComponent(follow.group(1)!),+ 'root': Uri.decodeComponent(follow.group(2)!),+ 'follow': body!['follow'],+ });+ if (failFollows) {+ throw const SuperTabFailure(+ 'OFFLINE',+ 'No connection.',+ statusCode: 503,+ );+ }+ return {'follow': body['follow']};+ }if (threadRead != null) {return _markThreadRead(Uri.decodeComponent(threadRead.group(1)!),@@ -1392,6 +1435,25 @@ class ConversationServer {return jsonDecode(jsonEncode(_catchUp(id, after)))as Map<String, dynamic>;}+ if (uri.pathSegments.last == 'threads' ||+ uri.pathSegments.last == 'inbox') {+ threadListReads.add(path);+ if (holdThreadLists case final hold?) await hold.future;+ if (failThreadLists) {+ throw SuperTabFailure(+ 'OFFLINE',+ 'No connection.',+ statusCode: threadListStatus,+ );+ }+ final answer = uri.pathSegments.last == 'threads'+ ? followedThreads+ : inbox;+ if (answer == null) {+ throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);+ }+ return jsonDecode(jsonEncode(answer)) as Map<String, dynamic>;+ }if (uri.pathSegments.last == 'mentions') {mentionReads++;if (mentionsMissing) {@@ -1562,9 +1624,13 @@ class ConversationServer {String text = 'Please confirm the release.',String createdAt = '2026-10-24T05:00:00Z',String? leadId,+ String? threadId,+ int? messageSequence,}) {mentions.add({'leadId': ?leadId,+ 'threadId': ?threadId,+ 'messageSequence': ?messageSequence,'id': 'mention-${mentions.length + 1}','projectId': 'lead','projectName': 'web-project',