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 2: Activity, jump to unread, mark all read, unread filter, per-chat notifications (#2450 #2451) (#2453)
0xken15329f66de55f0
diff --git a/backend/integration/superTabActivity.test.ts b/backend/integration/superTabActivity.test.tsnew file mode 100644index 000000000..466b9835a--- /dev/null+++ b/backend/integration/superTabActivity.test.ts@@ -0,0 +1,330 @@+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 } 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 { SwarmReads } from '../src/superTabs/read/service.js'+import { HostReads } from '../src/superTabs/read/host.js'+import { buddyChatId, openSwarmBuddyChat } from '../src/superTabs/buddies.js'+import { ACTIVITY_EXPIRY_MS, ACTIVITY_READS, resetActivityReads, sweepActivity } from '../src/superTabs/activity.js'+import { CHAT_SETTING_DEFAULT_KEEP_MS, sweepChatSettings } from '../src/superTabs/chatSettings.js'+import type { Command, SuperTabState } from '../src/superTabs/model.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'++// 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_activity_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()+})+beforeEach(() => resetActivityReads())++/** A Swarm in parts: a public chat ("Web", with a worker on the owner's machine), a project shared with the owner alone+ * ("Secret work"), a public project the owner can make private later ("Open chat"), and peer's Buddy chat. */+async function scene() {+ 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 }] } })+ })+ let swarmBuddy = ''+ s.edit(state => { swarmBuddy = openSwarmBuddyChat(state, state.people.find(p => p.id === peer.sub)!).id })+ 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, swarmBuddy }+}++const run = async (tabId: string, command: Command, as: AuthUser = owner, asAgentId?: string) =>+ (await store.execute(as, tabId, { operationId: randomUUID(), command }, asAgentId)) as { result: Record<string, unknown> }+const send = async (tabId: string, conversationId: string, text: string, as: AuthUser = owner, replyTo: string | null = null, asAgentId?: string) =>+ (await run(tabId, { type: 'message.send', conversationId, text, replyTo, recipientIds: [] }, as, asAgentId)).result.messageId as string+const react = (tabId: string, conversationId: string, messageId: string, on: boolean, as: AuthUser = owner, emoji: 'thumbs_up' | 'check' = 'thumbs_up', asAgentId?: string) =>+ run(tabId, { type: 'message.react', conversationId, messageId, emoji, on }, as, asAgentId)+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 activity = (tabId: string, as: AuthUser | 'team' = owner) => call('GET', `/api/super-tabs/${tabId}/activity`, as)+const items = async (tabId: string, as: AuthUser = owner) => {+ const answer = await activity(tabId, as)+ expect(answer.status).toBe(200)+ return answer.body.data.items as any[]+}+const derived = async (tabId: string, as: AuthUser) => (await call('GET', `/api/super-tabs/${tabId}/parts`, as)).body.data.derived+const notify = (tabId: string, conversationId: string, value: unknown, as: AuthUser | 'team' = owner) =>+ call('POST', `/api/super-tabs/${tabId}/conversations/${conversationId}/notifications`, as, { notify: value })++describe('Activity: replies to a person\'s messages', () => {+ it('lists a reply by someone else in the person\'s thread, newest first, with who wrote it and where', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.web, 'Owner root')+ const reply = await send(s.tabId, s.web, 'Peer answers', peer, root)+ const agentReply = await send(s.tabId, s.web, 'Worker answers', owner, root, s.worker)+ const list = await items(s.tabId)+ expect(list.map(i => [i.kind, i.messageId, i.text, i.actor.kind])).toEqual([['reply', agentReply, 'Worker answers', 'agent'], ['reply', reply, 'Peer answers', 'person']])+ expect(list[1]).toMatchObject({ conversationId: s.web, conversationTitle: 'Web', threadId: root, actor: { id: peer.sub, name: expect.any(String) }, read: false, emoji: null })+ expect(list[0].actor.name).toBe('worker-harness')+ expect(typeof list[0].messageSequence).toBe('number')+ // Nothing for the person who replied, and nothing for a reply in one's own thread.+ expect(await items(s.tabId, peer)).toEqual([])+ await send(s.tabId, s.web, 'Owner adds', owner, root)+ expect((await items(s.tabId)).length).toBe(2)+ })++ it('tells the author of the message replied to as well as the thread\'s, once each', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.web, 'Owner root')+ const peerReply = await send(s.tabId, s.web, 'Peer answers', peer, root)+ const outsiderReply = await send(s.tabId, s.web, 'Outsider answers peer', outsider, peerReply)+ expect((await items(s.tabId, peer)).map(i => i.messageId)).toEqual([outsiderReply])+ expect((await items(s.tabId)).map(i => i.messageId)).toEqual([outsiderReply, peerReply])+ })++ it('lists nothing for a top-level message, or for a message of another person\'s chat', async () => {+ const s = await scene()+ await send(s.tabId, s.web, 'Top level by peer', peer)+ expect(await items(s.tabId)).toEqual([])+ })+})++describe('Activity: reactions to a person\'s messages', () => {+ it('lists a reaction by someone else, removes it with the reaction, and never one\'s own', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.web, 'Owner root')+ await react(s.tabId, s.web, root, true, owner)+ expect(await items(s.tabId)).toEqual([])+ await react(s.tabId, s.web, root, true, peer)+ await react(s.tabId, s.web, root, true, owner, 'check', s.worker)+ const list = await items(s.tabId)+ expect(list.map(i => [i.kind, i.emoji, i.actor.kind, i.text])).toEqual([['reaction', 'check', 'agent', 'Owner root'], ['reaction', 'thumbs_up', 'person', 'Owner root']])+ // The same reaction again keeps one row.+ await react(s.tabId, s.web, root, true, peer)+ expect((await items(s.tabId)).length).toBe(2)+ await react(s.tabId, s.web, root, false, peer)+ expect((await items(s.tabId)).map(i => i.emoji)).toEqual(['check'])+ })++ it('drops a reaction by someone who left the Swarm', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.web, 'Owner root')+ await react(s.tabId, s.web, root, true, outsider)+ expect((await items(s.tabId)).length).toBe(1)+ await run(s.tabId, { type: 'member.remove', userId: outsider.sub })+ expect(await items(s.tabId)).toEqual([])+ })+})++describe('Activity: only what the person can read now', () => {+ it('drops a row of a chat the person lost, and lists it again only with access', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.openChat, 'Peer root', peer)+ await send(s.tabId, s.openChat, 'Owner answers', owner, root)+ await react(s.tabId, s.openChat, root, true, outsider)+ expect((await items(s.tabId, peer)).length).toBe(2)+ // The owner makes the project private to themselves: peer can no longer read the chat, and its rows say nothing.+ await run(s.tabId, { type: 'project.sharing', projectId: s.open, visibility: 'private', memberIds: [] })+ const answer = await activity(s.tabId, peer)+ expect(answer.body.data).toEqual({ items: [], more: false })+ expect(JSON.stringify(answer.body)).not.toContain('Open chat')+ await run(s.tabId, { type: 'project.sharing', projectId: s.open, visibility: 'public', memberIds: [] })+ expect((await items(s.tabId, peer)).length).toBe(2)+ })++ it('is the reader\'s alone: another member, an outsider of the Swarm and a Team session read none of it', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.web, 'Owner root')+ await send(s.tabId, s.web, 'Peer answers', peer, root)+ expect(await items(s.tabId, outsider)).toEqual([])+ expect((await activity(s.tabId, 'team')).status).toBe(403)+ await run(s.tabId, { type: 'member.remove', userId: outsider.sub })+ expect((await activity(s.tabId, outsider)).status).toBeGreaterThanOrEqual(403)+ // A Swarm id that is not one, and another Swarm's, are refused alike.+ expect((await activity(`tab-${randomUUID()}`)).status).toBe(404)+ })++ it('keeps a Buddy chat\'s replies to its person', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.buddyId, 'Peer asks their Buddy', peer)+ await db.superTabActivity.create({ data: { id: `fixture-${randomUUID()}`, tabId: s.tabId, personId: owner.sub, kind: 'reply', conversationId: s.buddyId,+ messageId: root, threadId: root, actorKind: 'person', actorId: peer.sub, emoji: null, createdAt: new Date(), readAt: null } })+ // A row naming a chat the reader cannot read (here, written by hand) is refused like any other: no title leaks.+ const answer = await activity(s.tabId, owner)+ expect(answer.body.data.items).toEqual([])+ expect(JSON.stringify(answer.body)).not.toContain('Buddy')+ })+})++describe('Activity in a person\'s one Buddy chat', () => {+ it('drops a reply in a project session\'s thread once the person no longer reads that project (review of the main merge)', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.swarmBuddy, 'Peer asks their Buddy about Open', peer)+ // A reply in the Open project's session thread, marked with its project as a session writes it (buddySessions.ts).+ const reply = `m-${randomUUID()}`+ const sequence = (await db.superTabMessage.findUniqueOrThrow({ where: { id: root } })).sequence + 1+ await db.superTabMessage.create({ data: { id: reply, tabId: s.tabId, conversationId: s.swarmBuddy, sequence, text: 'Open session answers',+ author: { kind: 'agent', id: 'buddy-session', name: 'Buddy', membershipGeneration: 'fixture' } as never, thread: root, recipientIds: [],+ mentions: [], buddySession: true, buddyProject: s.open, createdAt: new Date() } })+ await db.superTabActivity.create({ data: { id: `fixture-${randomUUID()}`, tabId: s.tabId, personId: peer.sub, kind: 'reply',+ conversationId: s.swarmBuddy, messageId: reply, threadId: root, actorKind: 'agent', actorId: 'buddy-session', emoji: null,+ createdAt: new Date(), readAt: null } })+ expect((await items(s.tabId, peer)).map(i => i.text)).toEqual(['Open session answers'])+ // The owner makes Open private to themselves: peer no longer reads it, and its session's reply leaves their Activity.+ await run(s.tabId, { type: 'project.sharing', projectId: s.open, visibility: 'private', memberIds: [] })+ const answer = await activity(s.tabId, peer)+ expect(answer.body.data).toEqual({ items: [], more: false })+ expect(JSON.stringify(answer.body)).not.toContain('Open session answers')+ })+})++describe('Activity: read state and its digest', () => {+ it('moves the digest when a row comes, and when it is read; marks read on every device', async () => {+ const s = await scene()+ const before = (await derived(s.tabId, owner)).activityDigest+ expect(typeof before).toBe('string')+ const root = await send(s.tabId, s.web, 'Owner root')+ await send(s.tabId, s.web, 'Peer answers', peer, root)+ const after = (await derived(s.tabId, owner)).activityDigest+ expect(after).not.toBe(before)+ // Another person's digest does not move.+ expect((await derived(s.tabId, outsider)).activityDigest).toBe(before)+ const [item] = await items(s.tabId)+ const marked = await call('POST', `/api/super-tabs/${s.tabId}/activity/read`, owner, { through: item.createdAt })+ expect(marked).toMatchObject({ status: 200, body: { data: { marked: 1 } } })+ expect((await items(s.tabId))[0].read).toBe(true)+ expect((await derived(s.tabId, owner)).activityDigest).toBe(before)+ expect((await call('POST', `/api/super-tabs/${s.tabId}/activity/read`, owner, { through: 'yesterday' })).status).toBe(400)+ expect((await call('POST', `/api/super-tabs/${s.tabId}/activity/read`, 'team', { through: item.createdAt })).status).toBe(403)+ })++ it('is read at most ACTIVITY_READS times per window by one person', async () => {+ const s = await scene()+ for (let i = 0; i < ACTIVITY_READS; i++) expect((await activity(s.tabId)).status).toBe(200)+ const refused = await activity(s.tabId)+ expect(refused.status).toBe(429)+ expect(Number(refused.headers['retry-after'])).toBeGreaterThan(0)+ })++ it('sweeps rows past their expiry', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.web, 'Owner root')+ await send(s.tabId, s.web, 'Peer answers', peer, root)+ // The sweep is every Swarm's: this one's rows are what is checked.+ await sweepActivity(db, Date.now())+ expect(await db.superTabActivity.count({ where: { tabId: s.tabId } })).toBe(1)+ expect(await sweepActivity(db, Date.now() + ACTIVITY_EXPIRY_MS + 1000)).toBeGreaterThanOrEqual(1)+ expect(await db.superTabActivity.count({ where: { tabId: s.tabId } })).toBe(0)+ })+})++describe('Chat notification settings', () => {+ it('keeps the person\'s setting, sends it in their reads alone, and keeps no row for the default', async () => {+ const s = await scene()+ expect(await notify(s.tabId, s.web, 'mentions')).toMatchObject({ status: 200, body: { data: { notify: 'mentions' } } })+ expect(await db.superTabChatSetting.count({ where: { tabId: s.tabId } })).toBe(0)+ expect(await notify(s.tabId, s.web, 'muted')).toMatchObject({ status: 200, body: { data: { notify: 'muted' } } })+ expect((await derived(s.tabId, owner)).chatSettings).toEqual({ [s.web]: 'muted' })+ expect((await derived(s.tabId, peer)).chatSettings).toBeUndefined()+ // A change read sends a setting moved since its cursor.+ const first = (await call('GET', `/api/super-tabs/${s.tabId}/parts`, owner)).body.data+ await notify(s.tabId, s.web, 'all')+ const changes = (await call('GET', `/api/super-tabs/${s.tabId}/changes?cursor=${encodeURIComponent(first.cursor)}`, owner)).body.data+ expect(changes.derived.chatSettings).toEqual({ [s.web]: 'all' })+ // Back to the default: the row stays, so other devices learn of it.+ await notify(s.tabId, s.web, 'mentions')+ expect((await derived(s.tabId, owner)).chatSettings).toEqual({ [s.web]: 'mentions' })+ })++ it('refuses a chat the person cannot read like one that does not exist, a Team session, and a value it does not know', async () => {+ const s = await scene()+ const hidden = await notify(s.tabId, s.secretGroup, 'muted', peer)+ const missing = await notify(s.tabId, 'no-such-chat', 'muted', peer)+ const buddy = await notify(s.tabId, s.buddyId, 'muted', owner)+ expect([hidden.status, missing.status, buddy.status]).toEqual([404, 404, 404])+ expect(hidden.body.error).toEqual(missing.body.error)+ expect(buddy.body.error).toEqual(missing.body.error)+ expect((await notify(s.tabId, s.web, 'muted', 'team')).status).toBe(403)+ expect((await notify(s.tabId, s.web, 'loud')).status).toBe(400)+ expect(await db.superTabChatSetting.count({ where: { tabId: s.tabId } })).toBe(0)+ })++ it('stops sending a setting of a chat the person lost', async () => {+ const s = await scene()+ await notify(s.tabId, s.openChat, 'muted', peer)+ expect((await derived(s.tabId, peer)).chatSettings).toEqual({ [s.openChat]: 'muted' })+ await run(s.tabId, { type: 'project.sharing', projectId: s.open, visibility: 'private', memberIds: [] })+ expect((await derived(s.tabId, peer)).chatSettings).toBeUndefined()+ })++ it('sweeps default rows after a week, and the rows of people who left', async () => {+ const s = await scene()+ await notify(s.tabId, s.web, 'muted', peer)+ await notify(s.tabId, s.web, 'muted', outsider)+ await notify(s.tabId, s.openChat, 'muted')+ await notify(s.tabId, s.openChat, 'mentions')+ await run(s.tabId, { type: 'member.remove', userId: outsider.sub })+ const rows = () => db.superTabChatSetting.findMany({ where: { tabId: s.tabId }, select: { personId: true, notify: true }, orderBy: { personId: 'asc' } })+ // The sweep is every Swarm's: this one's rows are what is checked.+ await sweepChatSettings(db, Date.now())+ expect(await rows()).toEqual([{ personId: owner.sub, notify: 'mentions' }, { personId: peer.sub, notify: 'muted' }])+ await sweepChatSettings(db, Date.now() + CHAT_SETTING_DEFAULT_KEEP_MS + 1000)+ expect((await db.superTabChatSetting.findMany({ where: { tabId: s.tabId }, select: { personId: true, notify: true } }))).toEqual([{ personId: peer.sub, notify: 'muted' }])+ })+})diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 22b62e3e8..299cb43e5 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1155,6 +1155,47 @@ model SuperTabReaction {/// How far one person has read one conversation (superTabs/readMarks.ts): the newest message sequence they have seen there./// Kept out of the tab state so a read never wakes other readers, and read only by that person's own clients. The id is/// derived from all three, so one row per person and conversation; it only ever moves forward.+/// A person's Activity row (superTabs/activity.ts): a reply to their message or a reaction to it, for them alone.+model SuperTabActivity {+ id String @id @map("_id")+ tabId String+ /// Whom the row is for: the author of the message replied or reacted to.+ personId String+ /// reply | reaction+ kind String+ conversationId String+ /// The reply, or the message reacted to.+ messageId String+ /// The reply's thread root, or the reacted message's thread.+ threadId String?+ /// person | agent+ actorKind String+ actorId String+ emoji String?+ createdAt DateTime+ /// When the person saw it, on any device; unset while unread.+ readAt DateTime?++ /// A person's rows, newest first: the list and the digest.+ @@index([tabId, personId, createdAt])+ /// The sweep's rows past their expiry (activity.ts sweepActivity); no TTL option, which the app user cannot set (#2238).+ @@index([createdAt])+}+/// A person's notification setting for one chat (superTabs/chatSettings.ts): all | mentions | muted. Their own, never shown to others.+model SuperTabChatSetting {+ id String @id @map("_id")+ tabId String+ personId String+ conversationId String+ /// all | mentions | muted; mentions is the default, kept a week so other devices learn of the change.+ notify String+ updatedAt DateTime++ /// A person's settings: every one (a first load) or those moved since a change read's cursor; the cap's count.+ @@index([tabId, personId, updatedAt])+ /// The sweep's default rows untouched for a week (chatSettings.ts sweepChatSettings).+ @@index([updatedAt])+}model SuperTabReadMark {id String @id @map("_id")tabId Stringdiff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex baf1f79e7..baa0c8b1f 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -28,6 +28,8 @@ 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 { activityWait } from '../superTabs/activity.js'+import { NOTIFY_LEVELS } from '../superTabs/chatSettings.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'@@ -74,6 +76,8 @@ 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 notifyBody = z.object({ notify: z.enum(NOTIFY_LEVELS) }).strict()+const activityReadBody = z.object({ through: z.string().datetime() }).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.@@ -475,6 +479,16 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suif (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))})+ // A person's Activity (superTabs/activity.ts): replies to their messages and reactions to them, read when its digest moves.+ app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof noQuery> }>('/api/super-tabs/:tabId/activity',+ { preHandler: [validateParams(tabParams), validateQuery(noQuery)] }, async (req, reply) => {+ const wait = await activityWait(req.user!, req.params.tabId)+ if (wait) return sendError(reply.header('Retry-After', String(wait)), 'Too many Activity reads. Try again in a moment.', 'RATE_LIMITED', 429)+ return respond(reply, () => reads.activity(req.user!, req.params.tabId))+ })+ app.post<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof noQuery>; Body: z.infer<typeof activityReadBody> }>('/api/super-tabs/:tabId/activity/read',+ { preHandler: [validateParams(tabParams), validateQuery(noQuery), validateBody(activityReadBody)] },+ (req, reply) => respond(reply, () => reads.markActivityRead(req.user!, req.params.tabId, req.body.through)))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)))@@ -593,6 +607,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 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)))+ // A person's own notification setting for a chat (superTabs/chatSettings.ts): all, mentions or muted.+ app.post<{ Params: z.infer<typeof messageParams>; Querystring: z.infer<typeof noQuery>; Body: z.infer<typeof notifyBody> }>('/api/super-tabs/:tabId/conversations/:conversationId/notifications',+ { preHandler: [validateParams(messageParams), validateQuery(noQuery), validateBody(notifyBody)] },+ (req, reply) => respond(reply, () => reads.setChatNotify(req.user!, req.params.tabId, req.params.conversationId, req.body.notify)))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/activity.ts b/backend/src/superTabs/activity.tsnew file mode 100644index 000000000..531583272--- /dev/null+++ b/backend/src/superTabs/activity.ts@@ -0,0 +1,194 @@+/**+ * A person's Activity in one Swarm (Desktop's Activity view, as Slack's): replies to their messages and reactions to them.+ * Tags and decisions have their own rows (mentions.ts, decisions.ts); Desktop merges the three.+ *+ * A row is written when it happens, in the command's own transaction (store.ts): a thread reply whose root a person wrote, by+ * anyone else, and a reaction to a person's message by anyone else. Removing the reaction removes its row. Rows live in+ * SuperTabActivity, never in the tab state, so writing one wakes no other reader and an older backend reads and writes a tab+ * that has them.+ *+ * Reads go only to the person the row is for, and only for what they can read now: the chat by the messages read's check+ * (canReadGroup, a quiet chat read by id as tags are), the message as a page shows it to a person (never an agent-only notice+ * or a delivered copy), and a reactor still in the Swarm.+ *+ * Growth: the hourly sweep deletes rows older than ACTIVITY_EXPIRY_MS (sweepActivity); a list reads the newest ACTIVITY_LIST.+ */+import { createHash } from 'node:crypto'+import type { Prisma, PrismaClient } from '@prisma/client'+import type { AuthUser } from '../lib/ssoAuth.js'+import { createRateLimiter } from '../lib/rateLimit.js'+import { agentOnly, isLeads, stableId, type Actor, type Author, type Conversation, type MessageDraft, type SuperTabState } from './model.js'+import { canReadGroup, projectOf } from './projects.js'+import { groupsBy, readBy } from './parts/indexed.js'+import { usernameOf } from './usernames.js'+import { FIELDS, readable, row as messageRow, type Row } from './read/inbox.js'++type Tx = Prisma.TransactionClient+/** A row goes this long after it was made, as a tag does (mentions.ts MENTION_EXPIRY_MS). */+export const ACTIVITY_EXPIRY_MS = 30 * 24 * 60 * 60_000+/** Rows one list reads, newest first; `more` says there were others. */+export const ACTIVITY_LIST = 200+/** Unread rows the digest covers, newest first. */+export const ACTIVITY_DIGEST_ROWS = 200+/** Rows one sweep deletes at most, in batches; the rest wait for the next hour. */+export const ACTIVITY_SWEEP = 20_000+const SWEEP_BATCH = 1_000++export type ActivityKind = 'reply' | 'reaction'+/** Mongo omits unset fields, so `readAt: null` alone would miss a row written without it. */+const unread: Prisma.SuperTabActivityWhereInput = { OR: [{ readAt: null }, { readAt: { isSet: false } }] }+const own = (author: { kind?: string; id?: string } | undefined, personId: string) => author?.kind === 'person' && author.id === personId++/** Activity rows for the thread replies among `messages`: one for the person who wrote the thread's root and one for the person+ * who wrote the message replied to, unless they wrote the reply. A notice for agents alone is nobody's activity, and a root or+ * quoted message counts only in the reply's own chat. Those messages by id in one read. */+export async function writeReplyActivity(tx: Tx, tabId: string, messages: MessageDraft[], now: number): Promise<void> {+ const replies = messages.filter(m => m.thread && m.thread !== m.id && !agentOnly(m.source ?? null, m.recipients))+ if (!replies.length) return+ const ids = [...new Set(replies.flatMap(m => [m.thread!, ...(m.replyTo ? [m.replyTo] : [])]))]+ // By id through its index, as a plain $in (parts/indexed.ts): Prisma's `in` plans slowly.+ const found = new Map((await readBy(tx, 'SuperTabMessage', 'id', [{ $match: { _id: { $in: ids }, tabId } }, { $project: { conversationId: 1, author: 1 } }]))+ .map(r => [r._id as string, { conversationId: r.conversationId as string, author: r.author }]))+ const data = replies.flatMap(m => {+ const people = new Set([m.thread!, m.replyTo].flatMap(target => {+ const row = target ? found.get(target) : undefined+ const by = row?.author as { kind?: string; id?: string } | undefined+ return row && row.conversationId === m.conversationId && by?.kind === 'person' && by.id && !own(m.author, by.id) ? [by.id] : []+ }))+ return [...people].map(personId => ({ id: stableId(tabId, 'reply', m.id, personId), tabId, personId, kind: 'reply', conversationId: m.conversationId,+ messageId: m.id, threadId: m.thread!, actorKind: m.author.kind, actorId: m.author.id, emoji: null, createdAt: new Date(now), readAt: null }))+ })+ if (data.length) await tx.superTabActivity.createMany({ data })+}++/** The row of the reaction `reactionId`, for the person who wrote the message, unless they reacted themselves: written when the+ * reaction is added, removed when it is. */+export async function writeReactionActivity(tx: Tx, write: { tabId: string; reactionId: string; conversationId: string; messageId: string+ actor: { kind: 'person' | 'agent'; id: string }; emoji: string; on: boolean; now: number }): Promise<void> {+ const id = stableId(write.tabId, 'reaction', write.reactionId)+ if (!write.on) return void await tx.superTabActivity.deleteMany({ where: { id } })+ const message = await tx.superTabMessage.findFirst({ where: { id: write.messageId, tabId: write.tabId }, select: { author: true, thread: true } })+ const by = message?.author as { kind?: string; id?: string } | undefined+ if (by?.kind !== 'person' || !by.id || (write.actor.kind === 'person' && write.actor.id === by.id)) return+ await tx.superTabActivity.upsert({ where: { id }, update: {}, create: { id, tabId: write.tabId, personId: by.id, kind: 'reaction',+ conversationId: write.conversationId, messageId: write.messageId, threadId: message?.thread ?? null, actorKind: write.actor.kind,+ actorId: write.actor.id, emoji: write.emoji, createdAt: new Date(write.now), readAt: null } })+}++/** A digest of which of the person's rows are unread, moving when one is written, read or removed: a client reads its list+ * again when it moves, never on a timer. It carries no count and no chat: only that something changed. */+export async function activityDigest(tx: Tx, tabId: string, personId: string, now: number): Promise<string> {+ const rows = await tx.superTabActivity.findMany({ where: { tabId, personId, createdAt: { gt: new Date(now - ACTIVITY_EXPIRY_MS) }, ...unread },+ orderBy: { createdAt: 'desc' }, take: ACTIVITY_DIGEST_ROWS, select: { id: true } })+ return createHash('sha256').update(rows.map(r => r.id).sort().join('\n')).digest('base64url').slice(0, 16)+}++export interface ActivityItem {+ id: string+ kind: ActivityKind+ conversationId: string+ conversationTitle: string+ projectName: string+ /** The reply, or the message reacted to. */+ messageId: string+ /** Where the message is in its chat. */+ messageSequence: number+ /** The thread the message is in, when it is a reply that lives only there; null for one in the chat's main stream. */+ threadId: string | null+ actor: { kind: 'person' | 'agent'; id: string; name: string }+ emoji: string | null+ /** The reply's text, or the reacted message's, cut by the database. */+ text: string+ createdAt: string+ read: boolean+}++/** The person's own unexpired rows, newest first, those they can read now (see the file's comment). */+export async function listActivity(db: PrismaClient, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>, now: number):+ Promise<{ items: ActivityItem[]; more: boolean }> {+ const rows = await db.superTabActivity.findMany({ where: { tabId, personId: actor.userId, createdAt: { gt: new Date(now - ACTIVITY_EXPIRY_MS) } },+ orderBy: { createdAt: 'desc' }, take: ACTIVITY_LIST + 1 })+ const more = rows.length > ACTIVITY_LIST+ const listed = rows.slice(0, ACTIVITY_LIST)+ if (!listed.length) return { items: [], more }+ const groups = new Map(state.conversations.map(c => [c.id, c]))+ const missing = [...new Set(listed.map(r => r.conversationId))].filter(id => !groups.has(id))+ if (missing.length) {+ // A quiet chat by id through its index (parts/indexed.ts), as tags read theirs (mentions.ts readable).+ for (const row of await groupsBy(db, 'key', [{ $match: { tabId, deleted: false, key: { $in: missing } } }, { $project: { _id: 0, key: 1, data: 1 } }])) {+ groups.set(row.key as string, row.data as unknown as Conversation)+ }+ }+ const present = (kind: string, id: string) => kind === 'person' ? state.people.some(p => p.id === id) : state.agents.some(a => a.id === id)+ const kept = listed.filter(r => {+ const group = groups.get(r.conversationId)+ // A reaction by someone no longer here drops out, as its count does (reactions.ts reactionCounts).+ return group && !isLeads(group) && canReadGroup(state, actor, group) && (r.kind !== 'reaction' || present(r.actorKind, r.actorId))+ })+ if (!kept.length) return { items: [], more }+ const found = (await readBy(db, 'SuperTabMessage', 'id', [{ $match: { _id: { $in: [...new Set(kept.map(r => r.messageId))] }, tabId } },+ { $project: { ...FIELDS, conversationId: 1 } }])).map(messageRow)+ // As a page filters rows (read/inbox.ts readable), Buddy-session rows included: against the state with the quiet chats read+ // by id above, since a chat the state does not hold reads nothing.+ const held = new Set(state.conversations.map(c => c.id))+ const withQuiet: SuperTabState = { ...state, conversations: [...state.conversations, ...[...groups.values()].filter(g => !held.has(g.id))] }+ const messages = new Map((await readable(db, tabId, found, withQuiet)).map(m => [m.id, m]))+ const items = kept.flatMap(r => {+ const message = messages.get(r.messageId)+ // The message must still be in the chat the row names, and be one the person reads; a reaction's must still be theirs.+ if (!message || message.conversationId !== r.conversationId || (r.kind === 'reaction' && !own(message.author, actor.userId))) return []+ const group = groups.get(r.conversationId)!+ return [{ id: r.id, kind: r.kind as ActivityKind, conversationId: r.conversationId, conversationTitle: group.title,+ projectName: projectOf(state, group.projectId ?? 'lead').name, messageId: r.messageId, messageSequence: message.sequence,+ threadId: threadOf(message), actor: { kind: r.actorKind as 'person' | 'agent', id: r.actorId, name: actorName(state, r.actorKind, r.actorId, message, r.kind) },+ emoji: r.emoji ?? null, text: message.text, createdAt: r.createdAt.toISOString(), read: !!r.readAt }]+ })+ return { items, more }+}++/** A reply that lives only in its thread names its root; a top-level message or one also sent to the chat names none. */+const threadOf = (m: Row) => m.thread && m.thread !== m.id && !m.alsoInChat ? m.thread : null++/** A person by their username, as everywhere in the Swarm; an agent by its name, or the reply's author name when it left. */+function actorName(state: SuperTabState, kind: string, id: string, message: Row, rowKind: string): string {+ if (kind === 'person') return usernameOf(state, id) ?? 'Someone'+ const agent = state.agents.find(a => a.id === id) as { displayName?: string | null; name?: string } | undefined+ const author = rowKind === 'reply' ? message.author as Author & { displayName?: string } : undefined+ return agent?.displayName ?? agent?.name ?? author?.displayName ?? author?.name ?? 'An agent'+}++/** Marks the person's rows made at or before `through` read, on every device. Only their own. */+export async function markActivityRead(db: PrismaClient, tabId: string, personId: string, through: number, now: number): Promise<number> {+ const moved = await db.superTabActivity.updateMany({ where: { tabId, personId, createdAt: { lte: new Date(through) }, ...unread },+ data: { readAt: new Date(now) } })+ return moved.count+}++/** The hourly sweep (sweeps.ts): deletes rows older than ACTIVITY_EXPIRY_MS by the age index, in batches. No TTL index: the app+ * user may not set one on an index `db push` built (#2238), as thread marks. */+export async function sweepActivity(db: PrismaClient, now: number): Promise<number> {+ let deleted = 0+ const before = { $date: new Date(now - ACTIVITY_EXPIRY_MS).toISOString() }+ while (deleted < ACTIVITY_SWEEP) {+ const rows = await readBy(db, 'SuperTabActivity', 'age', [{ $match: { createdAt: { $lt: before } } }, { $limit: SWEEP_BATCH }, { $project: { _id: 1 } }])+ if (rows.length) {+ const reply = await db.$runCommandRaw({ delete: 'SuperTabActivity', deletes: [{ q: { _id: { $in: rows.map(r => r._id as string) } }, limit: 0 }] }) as { n?: number }+ deleted += Number(reply.n ?? 0)+ }+ if (rows.length < SWEEP_BATCH) break+ }+ return deleted+}++/** Activity reads a person may make in one Swarm per window, as the inbox's (read/inbox.ts INBOX_READS). */+export const ACTIVITY_READS = 10+export const ACTIVITY_WINDOW_MS = 10_000+const activityReads = createRateLimiter('swarm-activity', ACTIVITY_WINDOW_MS, ACTIVITY_READS)++/** Seconds a person must wait before reading this Swarm's Activity again, or 0 when they may now (as inboxWait). */+export async function activityWait(user: AuthUser, tabId: string, now = Date.now()): Promise<number> {+ if (await activityReads.allows(`${user.sub}:${tabId}`, now)) return 0+ return Math.max(1, Math.ceil((ACTIVITY_WINDOW_MS - now % ACTIVITY_WINDOW_MS) / 1000))+}+/** Test seam: forget this process's counts. */+export const resetActivityReads = () => activityReads.reset()diff --git a/backend/src/superTabs/chatSettings.ts b/backend/src/superTabs/chatSettings.tsnew file mode 100644index 000000000..b9ac7e8ae--- /dev/null+++ b/backend/src/superTabs/chatSettings.ts@@ -0,0 +1,85 @@+/**+ * A person's notification setting for each chat (Slack's channel notification settings): `all` new messages, `mentions` only+ * (the default, what Desktop did before) or `muted`. Kept per person on the server so it follows them to every device, in+ * SuperTabChatSetting, never in the tab state: writing one wakes no other reader, and an older backend reads and writes a tab+ * that has them. A person's settings go only to their own reads (read/service.ts), for the chats they can read now.+ *+ * Growth: a row back at the default is kept CHAT_SETTING_DEFAULT_KEEP_MS so a device that polls learns of the change, then the+ * hourly sweep deletes it, as it deletes the rows of people no longer in the Swarm and of Swarms that are gone. A person keeps+ * at most CHAT_SETTING_CAP rows in one Swarm.+ */+import { Prisma, type PrismaClient } from '@prisma/client'+import { fail, stableId } from './model.js'+import { readBy } from './parts/indexed.js'++export const NOTIFY_LEVELS = ['all', 'mentions', 'muted'] as const+export type NotifyLevel = (typeof NOTIFY_LEVELS)[number]+export const DEFAULT_NOTIFY: NotifyLevel = 'mentions'+/** A row back at the default stays this long, then the sweep deletes it. */+export const CHAT_SETTING_DEFAULT_KEEP_MS = 7 * 24 * 60 * 60_000+/** The most rows one person keeps in one Swarm: a new one past it is refused. */+export const CHAT_SETTING_CAP = 2_000+/** Swarms one sweep checks for rows of people no longer there. */+export const CHAT_SETTING_SWARMS = 500+const SWEEP_BATCH = 1_000++export interface ChatSettingWrite { tabId: string; personId: string; conversationId: string; notify: NotifyLevel; now: number }++/** Stores the person's setting for one chat and answers it. Two first writes racing: the loser's create fails on the id and+ * its update runs again on the winner's row, so the last write wins. */+export async function writeChatSetting(db: PrismaClient, write: ChatSettingWrite): Promise<NotifyLevel> {+ const { tabId, personId, conversationId, notify } = write+ const id = stableId(tabId, conversationId, personId, 'notify'), updatedAt = new Date(write.now)+ for (let attempt = 0; attempt < 4; attempt++) {+ if ((await db.superTabChatSetting.updateMany({ where: { id }, data: { notify, updatedAt } })).count) return notify+ // Nothing to keep: a chat at the default needs no row.+ if (notify === DEFAULT_NOTIFY) return notify+ if (await db.superTabChatSetting.count({ where: { tabId, personId } }) >= CHAT_SETTING_CAP) {+ fail('TOO_MANY_CHAT_SETTINGS', 'You have set notifications for too many chats in this Swarm. Set some back to Mentions only first.', 400)+ }+ try {+ await db.superTabChatSetting.create({ data: { id, tabId, personId, conversationId, notify, updatedAt } })+ return notify+ } catch (error) {+ if (!(error instanceof Prisma.PrismaClientKnownRequestError) || error.code !== 'P2002') throw error+ }+ }+ return fail('CHAT_SETTING_BUSY', 'This chat is being changed on another device. Try again.', 503)+}++/** The person's settings in this tab, by conversation; with `since`, only those moved at or after it. The caller keeps those+ * of conversations the reader may read. */+export async function readChatSettings(db: Prisma.TransactionClient, tabId: string, personId: string, since?: number): Promise<Map<string, NotifyLevel>> {+ const rows = await db.superTabChatSetting.findMany({ where: { tabId, personId, ...(since === undefined ? {} : { updatedAt: { gte: new Date(since) } }) },+ select: { conversationId: true, notify: true } })+ return new Map(rows.flatMap(r => (NOTIFY_LEVELS as readonly string[]).includes(r.notify) ? [[r.conversationId, r.notify as NotifyLevel] as const] : []))+}++async function deleteWhere(db: PrismaClient, q: Record<string, unknown>): Promise<number> {+ const reply = await db.$runCommandRaw({ delete: 'SuperTabChatSetting', deletes: [{ q: q as Prisma.InputJsonObject, limit: 0 }] }) as { n?: number }+ return Number(reply.n ?? 0)+}++/** The hourly sweep (sweeps.ts): deletes default rows untouched for CHAT_SETTING_DEFAULT_KEEP_MS by the age index, then checks+ * up to CHAT_SETTING_SWARMS Swarms with rows: a Swarm whose row is gone loses all of them, a person no longer in its+ * `memberIds` theirs. A Swarm row without `memberIds` is skipped, never read as having no members. */+export async function sweepChatSettings(db: PrismaClient, now: number): Promise<{ expired: number; lost: number }> {+ let expired = 0+ const before = { $date: new Date(now - CHAT_SETTING_DEFAULT_KEEP_MS).toISOString() }+ for (;;) {+ const rows = await readBy(db, 'SuperTabChatSetting', 'age', [{ $match: { updatedAt: { $lt: before } } }, { $match: { notify: DEFAULT_NOTIFY } },+ { $limit: SWEEP_BATCH }, { $project: { _id: 1 } }])+ if (rows.length) expired += await deleteWhere(db, { _id: { $in: rows.map(r => r._id as string) } })+ if (rows.length < SWEEP_BATCH) break+ }+ // Settings are few (one per chat a person set by hand): their Swarms in one grouped read.+ const tabs = await db.superTabChatSetting.aggregateRaw({ pipeline: [{ $group: { _id: '$tabId' } }, { $sort: { _id: 1 } }, { $limit: CHAT_SETTING_SWARMS }] }) as unknown as+ Array<{ _id: string }>+ let lost = 0+ for (const { _id: tabId } of tabs) {+ const [row] = await readBy(db, 'SuperTab', 'id', [{ $match: { _id: tabId } }, { $project: { memberIds: 1 } }])+ if (!row) lost += await deleteWhere(db, { tabId })+ else if (Array.isArray(row.memberIds)) lost += await deleteWhere(db, { tabId, personId: { $nin: row.memberIds as string[] } })+ }+ return { expired, lost }+}diff --git a/backend/src/superTabs/parts/indexed.ts b/backend/src/superTabs/parts/indexed.tsindex 5b510ca80..e50d304cd 100644--- a/backend/src/superTabs/parts/indexed.ts+++ b/backend/src/superTabs/parts/indexed.ts@@ -80,6 +80,10 @@ export const NAMED_INDEX = {},/** A page's thread summaries, by root id (pageReads.ts pageThreads). */SuperTabThread: { id: { _id: 1 } },+ /** `age`: Activity rows past their expiry (activity.ts sweepActivity). */+ SuperTabActivity: { age: { createdAt: 1 } },+ /** `age`: chat settings back at the default, untouched for a week (chatSettings.ts sweepChatSettings). */+ SuperTabChatSetting: { age: { updatedAt: 1 } },} as constexport type NamedCollection = keyof typeof NAMED_INDEXexport type NamedIndex<C extends NamedCollection> = keyof typeof NAMED_INDEX[C] & stringdiff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.tsindex 574a6fb03..205951eb1 100644--- a/backend/src/superTabs/read/contract.ts+++ b/backend/src/superTabs/read/contract.ts@@ -79,6 +79,9 @@ export interface Derived {decisionsWaiting?: number/** A person only: a digest of which decisions are open, moving when they change though the count may not. */decisionsDigest?: string+ /** A person only: a digest of which of their Activity rows are unread (activity.ts), moving when one is written, read or+ * removed. No count and no chat: the client reads its list again when it moves. Absent from an older backend. */+ activityDigest?: string/** A person only: their own read marks (readMarks.ts), the newest message sequence read by conversation. A first load has* every one of the conversations it holds; a changes read only those moved since its cursor, kept by the client as the* higher of the two. Never another person's. */@@ -87,6 +90,10 @@ export interface Derived {* Like `readMarks`: a first load has those of the conversations it holds, a changes read those moved since its cursor.* Absent when there are none, and from an older backend. Never another person's. */threadMarks?: Record<string, Record<string, number>>+ /** A person only: their own notification setting by conversation (chatSettings.ts), `all`, `mentions` or `muted`. Like+ * `readMarks`: a first load has every one of the conversations it holds (a chat with none is at `mentions`), a changes read+ * those moved since its cursor. Absent when there are none, and from an older backend. Never another person's. */+ chatSettings?: Record<string, 'all' | 'mentions' | 'muted'>/** Present, and false, only in a Swarm Harness Team accounts are not tried in yet (machines.ts teamAccountSwarm): this* Mac's daemon and Desktop then offer no team account for it. Absent is every older backend's "yes". */teamAccounts?: falsediff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.tsindex 61019d110..329844537 100644--- a/backend/src/superTabs/read/service.ts+++ b/backend/src/superTabs/read/service.ts@@ -9,6 +9,8 @@ import { agentOnly, author, fail, groupForBuddy, isLeads, seenMachineIds, stableimport { mentionsDigest, swarmsWithTags, waitingMentions, waitingTagConversations } from '../mentions.js'import { decisionsWaiting } from '../decisions.js'import { readMarks, readThreadMarks, writeReadMark, writeThreadFollow, writeThreadMark } from '../readMarks.js'+import { activityDigest, listActivity, markActivityRead, type ActivityItem } from '../activity.js'+import { readChatSettings, writeChatSetting, type NotifyLevel } from '../chatSettings.js'import { deliveredCopies } from '../pageReads.js'import { readBy } from '../parts/indexed.js'import type { SuperTabStore } from '../store.js'@@ -49,12 +51,14 @@ function readableGroups(read: Read): Set<string> {/** The reader's marks of the conversations and threads they can read now: a mark never names a conversation the reader has* lost. Only in a person's read; nothing for an agent. A read with no thread marks says none (`threadMarks` absent). */-function readableMarks(read: Read, marks: Map<string, number>, threads: Map<string, Map<string, number>>): Pick<Derived, 'readMarks' | 'threadMarks'> {+function readableMarks(read: Read, marks: Map<string, number>, threads: Map<string, Map<string, number>>, settings: Map<string, NotifyLevel> = new Map()):+ Pick<Derived, 'readMarks' | 'threadMarks' | 'chatSettings'> {if (read.actor.kind !== 'person') return {}const readable = readableGroups(read)const threadMarks = Object.fromEntries([...threads].filter(([id]) => readable.has(id)).map(([id, held]) => [id, Object.fromEntries(held)]))+ const chatSettings = Object.fromEntries([...settings].filter(([id]) => readable.has(id)))return { readMarks: Object.fromEntries([...marks].filter(([id]) => readable.has(id))),- ...(Object.keys(threadMarks).length ? { threadMarks } : {}) }+ ...(Object.keys(threadMarks).length ? { threadMarks } : {}), ...(Object.keys(chatSettings).length ? { chatSettings } : {}) }}/** A change poll's light base (parts/light.ts): the same for every reader of a Swarm, so one load per stamp serves them all. */@@ -95,7 +99,7 @@ export class SwarmReads {return { format: READ_FORMAT, tabId, cursor: cursorFor(t0, loaded.visibilityEpoch), serverTime: t0, lastChangedAt, epoch: loaded.visibilityEpoch,...(this.options.githubApp ? { githubApp: true as const } : {}), ...view.parts,derived: { ...await this.withAvatars(view, t0), ...readableMarks(read, await this.marksOf(tx, tabId, read.actor),- await this.threadMarksOf(tx, tabId, read.actor)) } }+ await this.threadMarksOf(tx, tabId, read.actor), await this.settingsOf(tx, tabId, read.actor)) } }})}@@ -143,10 +147,11 @@ export class SwarmReads {if ('reload' in from) { await this.load(tx, cached, user, tabId, asAgentId, t0, {}, async () => base); return from }// Without asAgentId the reader is a person (store.ts actor), whose marks moved since the cursor go out with this reply.const person = asAgentId ? null : user.sub- const [changed, tagged, marks, threadMarks] = await Promise.all([readChanged(tx, cached, tabId, from.since),+ const [changed, tagged, marks, threadMarks, settings] = await Promise.all([readChanged(tx, cached, tabId, from.since),person ? waitingTagConversations(tx, tabId, person, t0) : [],person ? readMarks(tx, tabId, person, from.since) : new Map<string, number>(),- person ? readThreadMarks(tx, tabId, person, from.since) : new Map<string, Map<string, number>>()])+ person ? readThreadMarks(tx, tabId, person, from.since) : new Map<string, Map<string, number>>(),+ person ? readChatSettings(tx, tabId, person, from.since) : new Map<string, NotifyLevel>()])// Starts: only unfinished ones whole in the base, then the poll's own.const extra = await this.pollStarts(tx, cached, tabId, base, changed)// Each reader's own conversations, held one by one (cachedReads.ts readLightGroups): those of their waiting tags, which@@ -155,12 +160,12 @@ export class SwarmReads {// moved, so the mark goes only to a reader who can still read it.const held = new Set(base.groups.map(g => g.key))const named = [...new Set([...tagged, ...[...changed.filter(p => p.kind === 'start'), ...extra].map(p => (p.data as AgentStart).request.conversationId),- ...marks.keys(), ...threadMarks.keys()])].filter(id => !held.has(id))+ ...marks.keys(), ...threadMarks.keys(), ...settings.keys()])].filter(id => !held.has(id))const read = await this.load(tx, cached, user, tabId, asAgentId, t0, {},async () => withStarts(withGroups(base, await readLightGroups(tx, cached, tabId, named)), extra))return { format: READ_FORMAT, reload: false, cursor: cursorFor(t0, read.parts.visibilityEpoch), serverTime: t0, lastChangedAt: read.lastChangedAt,epoch: read.parts.visibilityEpoch, ...changesFor(read.view, changed, read.actor),- derived: { ...await this.withAvatars(read.view, t0), ...readableMarks(read, marks, threadMarks) } }+ derived: { ...await this.withAvatars(read.view, t0), ...readableMarks(read, marks, threadMarks, settings) } }})}@@ -257,6 +262,41 @@ export class SwarmReads {return newest}+ /** A person's own chat settings (an agent has none), every one or those moved since `since`. */+ private async settingsOf(tx: PrismaClient, tabId: string, actor: Actor, since?: number): Promise<Map<string, NotifyLevel>> {+ return actor.kind === 'person' ? readChatSettings(tx, tabId, actor.userId, since) : new Map()+ }++ /** Stores the person's notification setting for a conversation they can read (chatSettings.ts), checked as a read mark is:+ * every miss is the same refusal, and only a person reading as themselves has settings. */+ async setChatNotify(user: AuthUser, tabId: string, conversationId: string, notify: NotifyLevel): Promise<{ notify: NotifyLevel }> {+ if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)+ await this.group(user, tabId, conversationId)+ return { notify: await writeChatSetting(this.db, { tabId, personId: user.sub, conversationId, notify, now: this.now() }) }+ }++ /** The person's Activity in this Swarm (activity.ts): replies to their messages and reactions to them, those they can read+ * now. A person reading as themselves only. */+ async activity(user: AuthUser, tabId: string): Promise<{ items: ActivityItem[]; more: boolean }> {+ if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)+ const { state } = await this.store.readLoad(user, tabId)+ const actor = await this.store.actor(this.db, user, state)+ author(state, actor)+ if (actor.kind !== 'person') return fail('FORBIDDEN', 'Only a person has Activity.', 403)+ return await listActivity(this.db, tabId, state, actor, this.now())+ }++ /** Marks the person's Activity made at or before `through` read on every device, never past now. */+ async markActivityRead(user: AuthUser, tabId: string, through: string): Promise<{ marked: number }> {+ if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)+ const { state } = await this.store.readLoad(user, tabId)+ const actor = await this.store.actor(this.db, user, state)+ author(state, actor)+ if (actor.kind !== 'person') return fail('FORBIDDEN', 'Only a person has Activity.', 403)+ const now = this.now()+ return { marked: await markActivityRead(this.db, tabId, actor.userId, Math.min(Date.parse(through), now), now) }+ }+/** A person's own thread marks (an agent has none), every one or those moved since `since`. */private async threadMarksOf(tx: PrismaClient, tabId: string, actor: Actor, since?: number): Promise<Map<string, Map<string, number>>> {return actor.kind === 'person' ? readThreadMarks(tx, tabId, actor.userId, since) : new Map()@@ -347,13 +387,14 @@ export class SwarmReads {const actor = await this.store.actor(tx, user, state, asAgentId)const [[teamMachines, otherWorkspaceMachines, machineVersions], counts, newest] = await Promise.all([this.machineLookups(state),- actor.kind === 'person' ? Promise.all([waitingMentions(tx, tabId, state, actor, t0), decisionsWaiting(tx, tabId, state, actor)]) : undefined,+ actor.kind === 'person' ? Promise.all([waitingMentions(tx, tabId, state, actor, t0), decisionsWaiting(tx, tabId, state, actor),+ activityDigest(tx, tabId, actor.userId, t0)]) : undefined,readLastChangedAt(tx, cached, tabId),])return { parts: loaded, actor, lastChangedAt: newest,view: readerView(loaded, actor, t0, { teamMachines, otherWorkspaceMachines, machineVersions, teamAccountsIdle: this.store.teamAccountsIdle,...(counts ? { mentionsWaiting: counts[0].count, mentionsDigest: counts[0].digest, decisionsWaiting: counts[1].count,- decisionsDigest: counts[1].digest } : {}) }, state) }+ decisionsDigest: counts[1].digest, activityDigest: counts[2] } : {}) }, state) }}/** Which of the Swarm's machines are signed in as a team account, and which serve another Workspace's Swarm too (store.ts): thediff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.tsindex 9ad8d04fd..b4f815116 100644--- a/backend/src/superTabs/read/views.ts+++ b/backend/src/superTabs/read/views.ts@@ -48,6 +48,8 @@ export interface ReadExtras {decisionsWaiting?: number/** Which ones they are, as a digest (decisions.ts). */decisionsDigest?: string+ /** Which of their Activity rows are unread, as a digest (activity.ts). */+ activityDigest?: string}const HEAD_FIELDS = ['version', 'id', 'name', 'project', 'projects', 'leadsConversationId', 'ownerId', 'environment',@@ -147,6 +149,7 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:...(actor.kind === 'person' && extras.mentionsDigest !== undefined ? { mentionsDigest: extras.mentionsDigest } : {}),...(actor.kind === 'person' && extras.decisionsWaiting !== undefined ? { decisionsWaiting: extras.decisionsWaiting } : {}),...(actor.kind === 'person' && extras.decisionsDigest !== undefined ? { decisionsDigest: extras.decisionsDigest } : {}),+ ...(actor.kind === 'person' && extras.activityDigest !== undefined ? { activityDigest: extras.activityDigest } : {}),...(teamAccountSwarm(state) ? {} : { teamAccounts: false as const }),threadSessions: true as const,sessionsFromChat: true as const,diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex a7d8f3461..9aa260b28 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -1,3 +1,4 @@+import { writeReactionActivity, writeReplyActivity } from './activity.js'import { expireRemovals, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, slotCounter, machineTeamWork, preparableStart, readingOnly, recordAgentPresence, removalPreview, startPreparing, storedObservation, swarmGridRow, teamAccountRequired, teamWorkRefusal, type MachineObservation } from './machines.js'import { readingClearsSuspensions, suspendedEngines } from './engineHealth.js'import { BUDDY_OWN_MACHINE_REFUSAL } from './buddyContract.js'@@ -1599,8 +1600,9 @@ export class SuperTabStore {const leadAt = (state: SuperTabState) => state.conversations.find(c => c.id === ledId)?.leadAction?.atif (ledId && leadAt(effects.state) !== undefined && leadAt(effects.state) !== leadAt(original)) await dropHeldTags(tx, tabId, ledId, context.now)await writeMentions(tx, tabId, effects.state, effects.messages, context.now)+ await writeReplyActivity(tx, tabId, effects.messages, context.now)if (command.type === 'mention.done') await markDone(tx, tabId, command.mentionId, context.mention!.personId, context.now)- if (command.type === 'message.react') await this.writeReaction(tx, tabId, actor, command)+ if (command.type === 'message.react') await this.writeReaction(tx, tabId, actor, command, context.now)if (context.avatarUpload) {// Conflicts with a concurrent use of the same picture: only one command can take it.const taken = await tx.superTabAttachment.updateMany({ where: { tabId, id: context.avatarUpload.id, purpose: AVATAR_PURPOSE, ...unused },@@ -1961,10 +1963,13 @@ export class SuperTabStore {}/** Writes or removes the actor's reaction row. The same reaction twice keeps one row: its id is derived. */- private async writeReaction(tx: Transaction, tabId: string, actor: Actor, command: ReactCommand) {+ private async writeReaction(tx: Transaction, tabId: string, actor: Actor, command: ReactCommand, now: number) {const id = reactionId(tabId, actor, command)- if (!command.on) return void await tx.superTabReaction.deleteMany({ where: { id } })const actorId = actor.kind === 'person' ? actor.userId : actor.agentId+ // The message author's Activity row goes and comes with the reaction (activity.ts).+ await writeReactionActivity(tx, { tabId, reactionId: id, conversationId: command.conversationId, messageId: command.messageId,+ actor: { kind: actor.kind, id: actorId }, emoji: command.emoji, on: command.on, now })+ if (!command.on) return void await tx.superTabReaction.deleteMany({ where: { id } })await tx.superTabReaction.upsert({ where: { id }, update: {}, create: { id, tabId, conversationId: command.conversationId,messageId: command.messageId, actorKind: actor.kind, actorId, emoji: command.emoji } })}diff --git a/backend/src/superTabs/sweeps.ts b/backend/src/superTabs/sweeps.tsindex ba4d6d78e..c5603c297 100644--- a/backend/src/superTabs/sweeps.ts+++ b/backend/src/superTabs/sweeps.ts@@ -9,6 +9,8 @@ import { listNamedIndexes, readBy } from './parts/indexed.js'import { autonomousEnvironments } from '../lib/autonomousEnvironment.js'import { expireEvidence } from './evidence/store.js'import { sweepThreadMarks } from './readMarks.js'+import { sweepActivity } from './activity.js'+import { sweepChatSettings } from './chatSettings.js'/** Parts whose key is never used twice (conversations, starts, projects' progress) lose their tombstone at `purgeAt`.* A person, agent or machine can come back under the same key, so its tombstone is kept for good, compacted to its@@ -154,10 +156,29 @@ export async function threadMarks(db: PrismaClient, now: number) {}}+/** The Activity and chat setting sweeps (activity.ts, chatSettings.ts), each failure said and kept to itself, as thread marks. */+export async function activityRows(db: PrismaClient, now: number) {+ try {+ return { expired: await sweepActivity(db, now) }+ } catch (error) {+ logger.warn('[swarm-sweeps] activity failed', { error: error instanceof Error ? error.message : String(error) })+ return { failed: true as const }+ }+}+export async function chatSettings(db: PrismaClient, now: number) {+ try {+ return await sweepChatSettings(db, now)+ } catch (error) {+ logger.warn('[swarm-sweeps] chat settings failed', { error: error instanceof Error ? error.message : String(error) })+ return { failed: true as const }+ }+}+/** One pass of every sweep (spec, Archive). Each part it changes is a guarded write, so a command in between wins. */export async function sweepSwarms(db: PrismaClient, now = Date.now()) {return { slept: await sleepQuietGroups(db, now), startsExpired: await expireStarts(db, now), invitationsExpired: await expireInvitations(db, now),- tombstonesCompacted: await compactTombstones(db, now), evidenceExpired: await expireEvidence(db, now), threadMarks: await threadMarks(db, now) }+ tombstonesCompacted: await compactTombstones(db, now), evidenceExpired: await expireEvidence(db, now), threadMarks: await threadMarks(db, now),+ activity: await activityRows(db, now), chatSettings: await chatSettings(db, now) }}/** Runs the sweeps every hour in the singleton worker. `finishWorkspaceRemovals` finishes Workspace removals whose Swarm removalsdiff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex e900f702a..991ae8c19 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/superTabFollowedThreads.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/superTabActivity.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_icons.dart b/desktop/lib/shared/theme/app_icons.dartindex 4d898d94d..f65e0aec4 100644--- a/desktop/lib/shared/theme/app_icons.dart+++ b/desktop/lib/shared/theme/app_icons.dart@@ -38,6 +38,7 @@ abstract final class AppIcons {static const arrowDown = LucideIcons.arrowDown400;static const arrowUpRight = LucideIcons.arrowUpRight400;static const bell = LucideIcons.bell400;+ static const bellOff = LucideIcons.bellOff400;static const bellRing = LucideIcons.bellRing400;static const book = LucideIcons.book400;static const bookOpen = LucideIcons.bookOpen400;diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex fe115088f..9045f29d0 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -104,7 +104,7 @@ import '../super_tabs/controller.dart';import '../super_tabs/join_machine.dart';import '../super_tabs/identity.dart' show superTabMachineName;import '../super_tabs/view_store.dart';-import '../super_tabs/notifications.dart' show superTabMentionNotice;+import '../super_tabs/notifications.dart' show superTabChatNotice, superTabMentionNotice;import '../measurement/setup_preference_store.dart';import '../devices/device_hosts.dart';import '../stats/harness_stats.dart';@@ -1227,6 +1227,7 @@ class AppNotifier extends ChangeNotifier {// Account and inventory replies belong to the session that requested them.// Signing out invalidates them before asynchronous connection cleanup.int _authRevision = 0;+/// Cancels work across account changes, independently of measurement preferences.int get accountGeneration => _authRevision;Future<void>? _profileInFlight;@@ -1871,6 +1872,7 @@ class AppNotifier extends ChangeNotifier {): uploadAvatarWith(() => api)(tabId: tabId, png: png),onMention: superTabMentionNotice(systemNotifications),+ onChatMessage: superTabChatNotice(systemNotifications),onTagCounts: notifyListeners,onNotices: notifyListeners,discoveryInterval: kUnderTest ? Duration.zero : const Duration(seconds: 15),@@ -2224,13 +2226,17 @@ class AppNotifier extends ChangeNotifier {'reason': reason,'tabId': ?tabId,});- appLog.info('super-tabs', 'team account offer ($reason): ${answer['state']}');+ appLog.info(+ 'super-tabs',+ 'team account offer ($reason): ${answer['state']}',+ );if (answer['state'] == 'wanted') {// The start check runs once for each daemon process, so a restart// with the explanation still open must not show it again: once a// launch at start. A join, a contribution or the machine row's Set up// is the person asking, and always explains.- if (reason != 'startup' || !_teamStartExplained) _teamSetupAsks.add(reason);+ if (reason != 'startup' || !_teamStartExplained)+ _teamSetupAsks.add(reason);if (reason == 'startup') _teamStartExplained = true;}return true;@@ -2260,7 +2266,10 @@ class AppNotifier extends ChangeNotifier {// a restart, and counting it as one asked without end (re-check of// #1790); the first identity read after an unknown one is taken as the// same process.- final restarted = daemon != null && _teamOfferDaemon != null && daemon != _teamOfferDaemon;+ final restarted =+ daemon != null &&+ _teamOfferDaemon != null &&+ daemon != _teamOfferDaemon;if (!_teamOfferStarted || restarted) {_teamOfferRetry?.cancel();_teamOfferRetry = null;@@ -4048,8 +4057,7 @@ class AppNotifier extends ChangeNotifier {final captured = tab.panes.where((p) =>- identical(p, pane) ||- p.viewsAgent(pane.machineId, pane.agentId),+ identical(p, pane) || p.viewsAgent(pane.machineId, pane.agentId),).toList();return _afterCloseGuards(@@ -4918,7 +4926,10 @@ class AppNotifier extends ChangeNotifier {: AgentPrefetch(log: (line) => appLog.info('setup', line))),windowsSelfInstall =windowsSelfInstall ??- (RuntimePlatform.isWindows && kReleaseMode && !kUnderTest && !kViewerMode+ (RuntimePlatform.isWindows &&+ kReleaseMode &&+ !kUnderTest &&+ !kViewerMode? WindowsSelfInstall(): null),_exitApp = exitApp ?? exit,@@ -8986,8 +8997,7 @@ class AppNotifier extends ChangeNotifier {refreshAfter = true;} else {status = wasGuest ? AppStatus.authenticated : AppStatus.unauthenticated;- _lastError =- error is PhoneSignInException && error.code == 'EXPIRED'+ _lastError = error is PhoneSignInException && error.code == 'EXPIRED'? _approvalRanOut: error.toString();_lastErrorRetryable = true;@@ -10448,10 +10458,11 @@ class AppNotifier extends ChangeNotifier {/// The [attempt]th ask of [remoteOfflineRetryDelays], then the next once it answered, until/// [_stopOfflineRetry] takes its timer away.void _scheduleRemoteOfflinePoll(String machineId, int attempt) {- final delay = remoteOfflineRetryDelays[min(- attempt,- remoteOfflineRetryDelays.length - 1,- )];+ final delay =+ remoteOfflineRetryDelays[min(+ attempt,+ remoteOfflineRetryDelays.length - 1,+ )];late final Timer timer;timer = Timer(delay, () async {await _pollOfflineMachine(machineId);@@ -15470,8 +15481,8 @@ class AppNotifier extends ChangeNotifier {// person (an engine Windows cannot start as asked).'ENGINE_LAUNCH_REFUSED' =>detail != null && detail.isNotEmpty- ? detail- : 'This engine cannot start on $machine. Nothing was started.',+ ? detail+ : 'This engine cannot start on $machine. Nothing was started.','CODEX_CLI_TOO_OLD' =>detail ??'The installed Codex CLI on $machine is too old for Auto approvals. '@@ -15589,13 +15600,21 @@ class AppNotifier extends ChangeNotifier {final made = creation._worktreeMadeHere;if (made == null) return;creation._worktreeMadeHere = null;- if (creation._preparedFolder == made.folder) creation._preparedFolder = null;+ if (creation._preparedFolder == made.folder)+ creation._preparedFolder = null;try {- if (!await discardLocalWorktree(made.folder, keepBranch: made.keepBranch)) {+ if (!await discardLocalWorktree(+ made.folder,+ keepBranch: made.keepBranch,+ )) {appLog.info('worktree', 'kept after cancel: ${made.folder}');}} catch (error) {- appLog.warn('worktree', 'not removed after cancel: ${made.folder}', error: error);+ appLog.warn(+ 'worktree',+ 'not removed after cancel: ${made.folder}',+ error: error,+ );}}@@ -16803,7 +16822,10 @@ class AppNotifier extends ChangeNotifier {final resuming = attempt.agent?.isStopped == true;if (resuming && machine.connectionStatus != ConnectionStatus.connected) {final connected = await connectTrusted(machineId);- if (!_restartCurrent(attempt, beforeSend: !attempt.awaitingConfirmation)) {+ if (!_restartCurrent(+ attempt,+ beforeSend: !attempt.awaitingConfirmation,+ )) {return const RestartAgentResult(error: 'The harness changed while connecting. Select it again.',retryable: false,@@ -16854,8 +16876,11 @@ class AppNotifier extends ChangeNotifier {}}_measurementResumes.remove(measurementKey)?.call(ProductOutcome.failed);- return RestartAgentResult(error: _restartFailure(code, detail, resuming: resuming));+ return RestartAgentResult(+ error: _restartFailure(code, detail, resuming: resuming),+ );}+final unknown = RestartAgentResult(error: resuming? 'Still waiting for the Open response. Select the harness again to check status.'@@ -17014,15 +17039,16 @@ class AppNotifier extends ChangeNotifier {}) => code == 'PTY_HOST_UNAVAILABLE'// Its detail is written for the log.? 'Harness could not open a terminal on this machine. Run harness start on it, then try again.'- : detail is String && detail.isNotEmpty &&- !const {- 'IDENTITY_UNAVAILABLE',- 'CWD_NOT_FOUND',- 'SESSION_FOLDER_GONE',- 'GRID_CREDENTIAL_REQUIRED',- 'ENGINE_NOT_INSTALLED',- 'ENGINE_UNAVAILABLE',- }.contains(code)+ : detail is String &&+ detail.isNotEmpty &&+ !const {+ 'IDENTITY_UNAVAILABLE',+ 'CWD_NOT_FOUND',+ 'SESSION_FOLDER_GONE',+ 'GRID_CREDENTIAL_REQUIRED',+ 'ENGINE_NOT_INSTALLED',+ 'ENGINE_UNAVAILABLE',+ }.contains(code)? detail: switch (code) {'ENGINE_LAUNCH_REFUSED' =>@@ -17037,12 +17063,9 @@ class AppNotifier extends ChangeNotifier {'RESUME_UNAVAILABLE' => 'The saved conversation is unavailable. The harness can still be started fresh.','RESUME_SESSION_MISMATCH' => 'The harness came back on a different conversation. The saved one is still kept.','RESUME_FAILED' => 'The harness did not come back. Its output and conversation are kept.',- 'IDENTITY_UNAVAILABLE' =>- 'The saved conversation could not be verified. Check that its agent account and project are still available, then retry. You can also start a new harness; the saved one is kept.',- 'CWD_NOT_FOUND' || 'SESSION_FOLDER_GONE' =>- 'The project folder is unavailable. Restore it, then retry, or start a new harness in another folder.',- 'GRID_CREDENTIAL_REQUIRED' =>- 'Reconnect the model provider in Models, then retry. Your saved conversation is kept.',+ 'IDENTITY_UNAVAILABLE' => 'The saved conversation could not be verified. Check that its agent account and project are still available, then retry. You can also start a new harness; the saved one is kept.',+ 'CWD_NOT_FOUND' || 'SESSION_FOLDER_GONE' => 'The project folder is unavailable. Restore it, then retry, or start a new harness in another folder.',+ 'GRID_CREDENTIAL_REQUIRED' => 'Reconnect the model provider in Models, then retry. Your saved conversation is kept.','ENGINE_NOT_INSTALLED' || 'ENGINE_UNAVAILABLE' =>'Install this agent on the computer, then retry.',_ =>@@ -17286,11 +17309,8 @@ class AppNotifier extends ChangeNotifier {required Duration timeout,}) async {try {- return await _conn(machineId).request(- type,- payload: payload,- timeout: timeout,- );+ return await _conn(machineId)+ .request(type, payload: payload, timeout: timeout);} on WsRequestFailure catch (failure) {return {...failure.payload, 'error': failure.code};}@@ -19944,8 +19964,7 @@ class AppNotifier extends ChangeNotifier {}}bool closesWithPane(TerminalPane candidate) =>- candidate == pane ||- candidate.viewsAgent(pane.machineId, pane.agentId);+ candidate == pane || candidate.viewsAgent(pane.machineId, pane.agentId);if (tab.kind == 'harness' &&tab.panes.every(closesWithPane) &&!_activeAgentCreations.any((attempt) => attempt._targetId == tab.id)) {diff --git a/desktop/lib/super_tabs/activity.dart b/desktop/lib/super_tabs/activity.dartnew file mode 100644index 000000000..54f989bc5--- /dev/null+++ b/desktop/lib/super_tabs/activity.dart@@ -0,0 +1,407 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++import 'controller.dart';+import 'decisions.dart';+import 'model.dart';+import 'notifications.dart';++/// One reply to the reader's message, or one reaction to it, as the server+/// lists it (backend superTabs/activity.ts).+class SuperTabActivityItem {+ SuperTabActivityItem.fromJson(Map<String, dynamic> row)+ : id = row['id'] as String,+ kind = row['kind'] == 'reaction'+ ? SuperTabActivityKind.reaction+ : SuperTabActivityKind.reply,+ conversationId = row['conversationId'] as String,+ conversationTitle = row['conversationTitle'] as String? ?? '',+ projectName = row['projectName'] as String? ?? '',+ messageId = row['messageId'] as String,+ messageSequence = (row['messageSequence'] as num?)?.toInt() ?? 0,+ threadId = row['threadId'] as String?,+ actor = superTabMap(row['actor']),+ emoji = row['emoji'] as String?,+ text = row['text'] as String? ?? '',+ createdAt = DateTime.tryParse(row['createdAt'] as String? ?? ''),+ read = row['read'] == true;++ final String id, conversationId, conversationTitle, projectName, messageId;+ final SuperTabActivityKind kind;+ final int messageSequence;++ /// The thread a reply that lives only there is in; null in the main stream.+ final String? threadId;++ /// `kind` (person | agent), `id` and `name`, named by the server.+ final Map<String, dynamic> actor;++ /// The reaction (`thumbs_up`, `check`, …); null for a reply.+ final String? emoji;++ /// The reply's text, or the reacted message's.+ final String text;+ final DateTime? createdAt;+ final bool read;++ String get actorName => actor['name'] as String? ?? 'Someone';+ String? get actorId => actor['id'] as String?;+ bool get byAgent => actor['kind'] == 'agent';++ SuperTabActivityItem _asRead() =>+ SuperTabActivityItem.fromJson({..._json, 'read': true});++ Map<String, dynamic> get _json => {+ 'id': id,+ 'kind': kind.name,+ 'conversationId': conversationId,+ 'conversationTitle': conversationTitle,+ 'projectName': projectName,+ 'messageId': messageId,+ 'messageSequence': messageSequence,+ 'threadId': threadId,+ 'actor': actor,+ 'emoji': emoji,+ 'text': text,+ 'createdAt': createdAt?.toIso8601String(),+ 'read': read,+ };+}++enum SuperTabActivityKind { reply, reaction }++/// What the Activity view lists, as Slack's tabs: everything, or one kind.+enum SuperTabActivityFilter { all, decisions, mentions, replies, reactions }++/// The reader's Activity in one Swarm (Slack's Activity): decisions asked of+/// them and their tags ([SuperTabDecisions], [SuperTabMentions]), with the+/// replies to their messages and the reactions to them, read from the server+/// when its digest moves or the view opens — never on a timer. Rows the view+/// showed are marked read on every device when it is left, as the Threads+/// view reads what it shows. One per controller.+class SuperTabActivity extends ChangeNotifier {+ SuperTabActivity._(this.controller)+ : mentions = SuperTabMentions.of(controller),+ decisions = SuperTabDecisions.of(controller) {+ controller.addListener(_changed);+ controller.onDispose(dispose);+ mentions.addListener(notifyListeners);+ decisions.addListener(notifyListeners);+ _changed();+ }++ @visibleForTesting+ factory SuperTabActivity.forTest(SuperTabController controller) =>+ SuperTabActivity._(controller);++ static final _all = Expando<SuperTabActivity>();+ static SuperTabActivity of(SuperTabController controller) =>+ _all[controller] ??= SuperTabActivity._(controller);++ final SuperTabController controller;+ final SuperTabMentions mentions;+ final SuperTabDecisions decisions;++ /// Replies and reactions, newest first, in chats this Swarm still lists.+ List<SuperTabActivityItem> items = const [];+ bool loaded = false, more = false;+ String? error;++ /// False on a server before Activity (it answered 404): replies and+ /// reactions are not listed, and nothing is asked again.+ bool supported = true;++ SuperTabActivityFilter filter = SuperTabActivityFilter.all;+ bool _open = false;++ /// Rows shown as unread in this visit: they stay bold until the view is+ /// left, though reading them on another device cleared them.+ final Set<String> _newThisVisit = {};++ String? _digest;+ int? _epoch;+ Future<void>? _loading;+ bool _dirty = false, _disposed = false;+ int _asked = 0, _shown = 0;+ DateTime? _waitUntil;+ Timer? _retry;++ String get _path =>+ '/api/super-tabs/${Uri.encodeComponent(controller.tabId)}';++ /// Whether [item] shows bold.+ bool isUnread(SuperTabActivityItem item) =>+ !item.read || _newThisVisit.contains(item.id);++ /// Whether [mention] shows bold: waiting and not read past, as its chat's+ /// red number counts it (attention.dart).+ bool mentionUnread(SuperTabMention mention) =>+ mention.resolvedBy == null &&+ (mention.messageSequence ?? (1 << 52)) >+ (mention.threadId == null+ ? controller.readMark(mention.conversationId)+ : controller.threadReadMark(mention.threadId!));++ /// The Activity row's red number: what is the reader's own to answer, as+ /// Notifications counted it (their tags and decisions), and replies to them+ /// not yet seen. Reactions only make the row bold, as in Slack.+ int get count {+ final snapshot = controller.snapshot;+ if (controller.accessRevoked || snapshot == null) return 0;+ return snapshot.mentionsWaiting ++ snapshot.decisionsWaiting ++ items+ .where((i) => i.kind == SuperTabActivityKind.reply && !i.read)+ .length;+ }++ /// Whether the Activity row is bold: anything unread in it.+ bool get unread => count > 0 || items.any((i) => !i.read);++ /// The view opened: reads now; what is unread stays bold until [closed].+ void opened() {+ _open = true;+ _newThisVisit+ ..clear()+ ..addAll(items.where((i) => !i.read).map((i) => i.id));+ unawaited(load());+ unawaited(mentions.load());+ }++ /// The view was left: what it showed is read on every device.+ void closed() {+ if (!_open) return;+ _open = false;+ _newThisVisit.clear();+ // The view is going away while this runs (its dispose): what listens is+ // told after the frame's teardown, never during it.+ scheduleMicrotask(() {+ if (_disposed) return;+ unawaited(_markShownRead());+ notifyListeners();+ });+ }++ void setFilter(SuperTabActivityFilter value) {+ if (filter == value) return;+ filter = value;+ notifyListeners();+ }++ Future<void> _markShownRead() async {+ final newest = items+ .where((i) => !i.read)+ .map((i) => i.createdAt)+ .whereType<DateTime>()+ .fold<DateTime?>(null, (a, b) => a == null || b.isAfter(a) ? b : a);+ if (newest == null || !supported || controller.accessRevoked) return;+ final epoch = controller.visibilityEpoch;+ // Shown read at once; the server's answer is the next read's.+ items = [+ for (final i in items)+ if (!i.read && !i.createdAt!.isAfter(newest)) i._asRead() else i,+ ];+ notifyListeners();+ try {+ await controller.request(+ 'POST',+ '$_path/activity/read',+ body: {'through': newest.toUtc().toIso8601String()},+ );+ } catch (_) {+ // Unread again on the next read; nothing else to do.+ if (!_disposed && controller.visibilityEpoch == epoch) {+ _digest = null;+ }+ }+ }++ void _clear() {+ items = const [];+ loaded = false;+ more = false;+ error = null;+ _newThisVisit.clear();+ _retry?.cancel();+ _retry = null;+ }++ void _changed() {+ if (_disposed) return;+ if (controller.accessRevoked) {+ if (loaded || items.isNotEmpty || error != null) {+ _clear();+ // An answer on its way belongs to the access that is gone.+ _shown = ++_asked;+ _digest = null;+ notifyListeners();+ }+ return;+ }+ final snapshot = controller.snapshot;+ if (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;+ _digest = null;+ notifyListeners();+ }+ }+ // A server before Activity sends no digest: nothing to read.+ final digest = snapshot.activityDigest;+ if (digest == null || !supported) return;+ if (digest == _digest && loaded) return;+ _digest = digest;+ unawaited(load());+ }++ /// Joins a read under way, and has it read once more when asked again.+ Future<void> load() {+ if (_disposed || !supported) 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;+ if (_waitUntil case final wait? when DateTime.now().isBefore(wait)) {+ // Asked too often: one read when the wait is over, no more.+ _retry ??= Timer(wait.difference(DateTime.now()), () {+ _retry = null;+ unawaited(load());+ });+ return;+ }+ final asked = ++_asked;+ final epoch = controller.visibilityEpoch;+ bool current() =>+ !_disposed &&+ !controller.accessRevoked &&+ asked > _shown &&+ controller.visibilityEpoch == epoch;+ try {+ final answer = await controller.request('GET', '$_path/activity');+ if (!current()) return;+ _shown = asked;+ final readable = {+ for (final g in controller.snapshot?.conversations ?? const []) g.id,+ };+ items = [+ for (final row in answer['items'] as List? ?? const [])+ if (SuperTabActivityItem.fromJson(superTabMap(row)) case final i+ // Only chats this reader still has; a chat lost since is not+ // shown on the server's word alone.+ when readable.contains(i.conversationId))+ i,+ ];+ more = answer['more'] == true;+ loaded = true;+ error = null;+ _waitUntil = null;+ if (_open) {+ _newThisVisit.addAll(items.where((i) => !i.read).map((i) => i.id));+ }+ notifyListeners();+ } catch (failure) {+ if (!current()) return;+ _shown = asked;+ if (failure is SuperTabFailure && failure.statusCode == 404) {+ // A server before Activity: tags and decisions still show.+ supported = false;+ loaded = true;+ error = null;+ notifyListeners();+ return;+ }+ if (failure is SuperTabFailure && failure.statusCode == 429) {+ _waitUntil = DateTime.now().add(const Duration(seconds: 5));+ }+ // The digest is read again on its next move, or by Retry.+ _digest = null;+ loaded = true;+ error = 'Could not load activity.';+ notifyListeners();+ }+ }++ @override+ void dispose() {+ if (_disposed) return;+ _disposed = true;+ _retry?.cancel();+ controller.removeListener(_changed);+ mentions.removeListener(notifyListeners);+ decisions.removeListener(notifyListeners);+ super.dispose();+ }+}++/// A system notice for each new message in a chat set to All new messages+/// ([SuperTabNotify.all]), as Slack's channel setting does: when the chat's+/// newest main-stream message moves past what the reader has read, and the+/// chat is not the one open. The first look at a chat is not news. One per+/// controller.+class SuperTabChatNotices {+ SuperTabChatNotices._(this.controller) {+ controller.addListener(_changed);+ controller.onDispose(_dispose);+ _changed();+ }++ static final _all = Expando<SuperTabChatNotices>();+ static SuperTabChatNotices of(SuperTabController controller) =>+ _all[controller] ??= SuperTabChatNotices._(controller);++ final SuperTabController controller;++ /// Told with the chat and how far it now goes.+ void Function(SuperTabConversation group, int sequence)? onMessage;++ final _seen = <String, int>{};+ int? _epoch;+ bool _disposed = false;++ void _changed() {+ if (_disposed) return;+ final snapshot = controller.snapshot;+ if (controller.accessRevoked || snapshot == null) {+ _seen.clear();+ return;+ }+ if (controller.visibilityEpoch != _epoch) {+ // Who may read what changed: start over, telling nothing.+ _epoch = controller.visibilityEpoch;+ _seen.clear();+ }+ for (final group in snapshot.conversations) {+ final top = group.lastMainSequence ?? group.lastMessageSequence;+ final before = _seen[group.id];+ _seen[group.id] = top;+ if (before == null || top <= before) continue;+ if (controller.notifyOf(group.id) != SuperTabNotify.all) continue;+ if (controller.selectedId == group.id) continue;+ if (top <= controller.readMark(group.id)) continue;+ onMessage?.call(group, top);+ }+ }++ void _dispose() {+ _disposed = true;+ controller.removeListener(_changed);+ }+}diff --git a/desktop/lib/super_tabs/activity_view.dart b/desktop/lib/super_tabs/activity_view.dartnew file mode 100644index 000000000..3a546a4aa--- /dev/null+++ b/desktop/lib/super_tabs/activity_view.dart@@ -0,0 +1,413 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../widgets/desktop_chrome.dart';+import 'activity.dart';+import 'decisions_view.dart';+import 'identity.dart';+import 'machine_status.dart' show superTabAgo;+import 'notifications.dart';+import 'profile_model.dart';+import 'section_heading.dart';++/// Slack's Activity, where Notifications was (Lead, 10-31): decisions asked+/// of the reader first, then one list, newest first, of their tags, the+/// replies to their messages and the reactions to them. Unread rows are bold;+/// a click opens the message where it is. Filters show one kind.+class SuperTabActivityView extends StatefulWidget {+ const SuperTabActivityView({+ super.key,+ required this.activity,+ required this.onOpenMention,+ required this.onOpenMessage,+ this.now = DateTime.now,+ });+ final SuperTabActivity activity;+ final ValueChanged<SuperTabMention> onOpenMention;++ /// Opens a reply or the reacted message: chat, message.+ final void Function(String conversationId, String messageId) onOpenMessage;+ final DateTime Function() now;++ @override+ State<SuperTabActivityView> createState() => _SuperTabActivityViewState();+}++/// One row of the merged list: a tag, or a reply or reaction.+typedef _Entry = ({+ DateTime at,+ SuperTabMention? mention,+ SuperTabActivityItem? item,+});++class _SuperTabActivityViewState extends State<SuperTabActivityView> {+ final _marking = <String>{};+ late SuperTabActivity _activity = widget.activity;++ @override+ void initState() {+ super.initState();+ _activity.opened();+ }++ @override+ void didUpdateWidget(SuperTabActivityView old) {+ super.didUpdateWidget(old);+ if (old.activity != widget.activity) {+ _activity.closed();+ _activity = widget.activity..opened();+ }+ }++ @override+ void dispose() {+ _activity.closed();+ super.dispose();+ }++ Future<void> _done(SuperTabMention mention) async {+ setState(() => _marking.add(mention.id));+ await _activity.mentions.done(mention);+ if (mounted) setState(() => _marking.remove(mention.id));+ }++ List<_Entry> _entries() {+ final a = _activity;+ final filter = a.filter;+ final mentions =+ filter == SuperTabActivityFilter.all ||+ filter == SuperTabActivityFilter.mentions;+ bool kind(SuperTabActivityItem i) => switch (filter) {+ SuperTabActivityFilter.all => true,+ SuperTabActivityFilter.replies => i.kind == SuperTabActivityKind.reply,+ SuperTabActivityFilter.reactions =>+ i.kind == SuperTabActivityKind.reaction,+ _ => false,+ };+ final epoch = DateTime.fromMillisecondsSinceEpoch(0);+ return [+ if (mentions)+ for (final m in [...a.mentions.waiting, ...a.mentions.earlier])+ (at: m.createdAt ?? epoch, mention: m, item: null),+ for (final i in a.items)+ if (kind(i)) (at: i.createdAt ?? epoch, mention: null, item: i),+ ]..sort((x, y) => y.at.compareTo(x.at));+ }++ Widget _filters() {+ Widget tab(SuperTabActivityFilter value, String label) {+ final selected = _activity.filter == value;+ return Padding(+ padding: const EdgeInsets.only(right: grid.AppDesktop.menuInset),+ child: Material(+ color: selected ? grid.AppSurface.selectedFill : Colors.transparent,+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ key: ValueKey('super-activity-filter-${value.name}'),+ onTap: () => _activity.setFilter(value),+ hoverColor: grid.AppSurface.hoverFill,+ child: Semantics(+ selected: selected,+ button: true,+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.controlGap,+ vertical: grid.AppDesktop.menuInset,+ ),+ child: Text(+ label,+ style: DesktopChrome.control(+ medium: selected,+ color: selected ? null : DesktopChrome.muted,+ ),+ ),+ ),+ ),+ ),+ ),+ );+ }++ return Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.groupGap,+ 0,+ ),+ child: Wrap(+ children: [+ tab(SuperTabActivityFilter.all, 'All'),+ tab(SuperTabActivityFilter.decisions, 'Decisions'),+ tab(SuperTabActivityFilter.mentions, 'Mentions'),+ tab(SuperTabActivityFilter.replies, 'Replies'),+ tab(SuperTabActivityFilter.reactions, 'Reactions'),+ ],+ ),+ );+ }++ Widget _empty(String text) => Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ ),+ child: Text(text, style: DesktopChrome.metadata()),+ );++ Widget _face({String? personId, String? agentId, required String name}) {+ final snapshot = _activity.controller.snapshot;+ final person = personId == null+ ? null+ : snapshot?.people.where((p) => p.id == personId).firstOrNull;+ if (person != null) return SuperTabAvatar.person(person, size: 24);+ final agent = agentId == null ? null : snapshot?.agent(agentId);+ if (agent != null) {+ return SuperTabAvatar.agent(agent, name: name, size: 24);+ }+ return const SizedBox(width: 24);+ }++ Widget _row({+ required Key key,+ required Widget face,+ required String title,+ required String place,+ required String text,+ required DateTime? at,+ required bool unread,+ required VoidCallback onTap,+ Widget? trailing,+ }) => Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.controlGap,+ vertical: grid.AppDesktop.listRowGap,+ ),+ child: Material(+ color: Colors.transparent,+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ key: key,+ onTap: onTap,+ hoverColor: grid.AppSurface.hoverFill,+ focusColor: grid.AppSurface.hoverFill,+ child: Semantics(+ label: unread ? 'Unread' : null,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.controlGap,+ ),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Padding(+ padding: const EdgeInsets.only(+ right: grid.AppDesktop.controlGap,+ top: grid.AppDesktop.listRowGap,+ ),+ child: face,+ ),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ Flexible(+ child: Text(+ title,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style:+ DesktopChrome.control(+ color: unread ? null : DesktopChrome.muted,+ ).copyWith(+ fontWeight: unread+ ? grid.AppFont.semibold+ : null,+ ),+ ),+ ),+ if (at != null) ...[+ const SizedBox(width: 8),+ Text(+ superTabAgo(widget.now().difference(at)),+ style: DesktopChrome.metadata(),+ ),+ ],+ ],+ ),+ Text(+ place,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.metadata(),+ ),+ const SizedBox(height: 2),+ Text(+ text,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(+ color: unread ? null : DesktopChrome.muted,+ ),+ ),+ ],+ ),+ ),+ ?trailing,+ ],+ ),+ ),+ ),+ ),+ ),+ );++ Widget _mentionRow(SuperTabMention mention) {+ final c = _activity.controller;+ final hidden = c.snapshot?.conversation(mention.conversationId);+ // An old Chat with PM an older server still sends opens the project's+ // chat, and is named so; every other place by its title.+ final place = hidden == null || !c.hiddenByBuddies(hidden)+ ? mention.conversationTitle+ : '#${c.snapshot?.projects.where((p) => p.id == mention.projectId).firstOrNull?.name ?? mention.projectName}';+ final person = c.snapshot?.people+ .where((p) => p.id == mention.leadId)+ .firstOrNull;+ final author = person?.username ?? mention.leadName;+ final waiting = mention.resolvedBy == null;+ return _row(+ key: ValueKey('super-mention-${mention.id}'),+ face: _face(+ personId: mention.leadId,+ agentId: mention.leadId,+ name: mention.leadName,+ ),+ title: '$author tagged you',+ place: '${mention.projectName} · $place',+ text: mention.text,+ at: mention.createdAt,+ unread: _activity.mentionUnread(mention),+ onTap: () => widget.onOpenMention(mention),+ trailing: waiting+ ? Padding(+ padding: const EdgeInsets.only(left: grid.AppDesktop.controlGap),+ child: TextButton(+ onPressed: _marking.contains(mention.id)+ ? null+ : () => unawaited(_done(mention)),+ child: const Text('Mark done'),+ ),+ )+ : null,+ );+ }++ Widget _itemRow(SuperTabActivityItem item) {+ final name = item.actorName;+ final glyph = SuperTabReactionEmoji.of(item.emoji)?.glyph ?? '';+ return _row(+ key: ValueKey('super-activity-${item.id}'),+ face: _face(+ personId: item.byAgent ? null : item.actorId,+ agentId: item.byAgent ? item.actorId : null,+ name: name,+ ),+ title: item.kind == SuperTabActivityKind.reply+ ? '$name replied to your message'+ : '$name reacted $glyph to your message',+ place: '${item.projectName} · ${item.conversationTitle}',+ text: item.text,+ at: item.createdAt,+ unread: _activity.isUnread(item),+ onTap: () => widget.onOpenMessage(item.conversationId, item.messageId),+ );+ }++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: _activity,+ builder: (context, _) {+ grid.AppTheme.watch(context);+ final a = _activity;+ final filter = a.filter;+ final decisions =+ filter == SuperTabActivityFilter.all ||+ filter == SuperTabActivityFilter.decisions;+ final entries = filter == SuperTabActivityFilter.decisions+ ? const <_Entry>[]+ : _entries();+ final error = a.error ?? a.mentions.error;+ return ListView(+ key: const ValueKey('super-activity-list'),+ padding: const EdgeInsets.only(bottom: grid.AppDesktop.groupGap),+ children: [+ _filters(),+ if (error != null)+ 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());+ unawaited(a.mentions.load());+ },+ child: const Text('Retry'),+ ),+ ],+ ),+ ),+ if (decisions) SuperTabDecisionList(decisions: a.decisions),+ if (filter != SuperTabActivityFilter.decisions) ...[+ if (filter == SuperTabActivityFilter.all)+ const Padding(+ padding: EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.groupGap,+ grid.AppDesktop.groupGap,+ grid.AppDesktop.menuInset,+ ),+ child: SuperTabSectionHeading('Activity', endInset: 0),+ ),+ if (entries.isEmpty)+ _empty(switch (filter) {+ SuperTabActivityFilter.mentions => 'Nobody tagged you yet.',+ SuperTabActivityFilter.replies =>+ a.supported+ ? 'No replies to your messages yet.'+ : 'Update the server to see replies here.',+ SuperTabActivityFilter.reactions =>+ a.supported+ ? 'No reactions to your messages yet.'+ : 'Update the server to see reactions here.',+ _ => 'Nothing yet.',+ }),+ for (final e in entries)+ if (e.mention case final mention?)+ _mentionRow(mention)+ else+ _itemRow(e.item!),+ if (a.more) _empty('Older activity is not shown.'),+ ],+ ],+ );+ },+ );+}diff --git a/desktop/lib/super_tabs/attention.dart b/desktop/lib/super_tabs/attention.dartindex c8e07afe2..ba0e1604a 100644--- a/desktop/lib/super_tabs/attention.dart+++ b/desktop/lib/super_tabs/attention.dart@@ -146,6 +146,8 @@ class SuperTabAttention extends ChangeNotifier {/// which message asked). Nothing counts once access is gone.int mentionsIn(String conversationId) {if (controller.accessRevoked) return 0;+ // A muted chat never counts (Slack); its tags stay listed in Activity.+ if (controller.notifyOf(conversationId) == SuperTabNotify.muted) return 0;final tags = mentions.waiting.where((m) =>@@ -160,7 +162,7 @@ class SuperTabAttention extends ChangeNotifier {.length;if (asked == 0) return tags;final group = controller.snapshot?.conversation(conversationId);- return tags + (group != null && controller.unread(group) ? asked : 0);+ return tags + (group != null && controller.unreadShown(group) ? asked : 0);}/// A tag from a server that does not say where it is: it counts untildiff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dartindex 9db512377..2bb6b6193 100644--- a/desktop/lib/super_tabs/client.dart+++ b/desktop/lib/super_tabs/client.dart@@ -8,6 +8,7 @@ import '../core/local_key_value_store.dart';import 'account_keys.dart';import 'attachment_upload.dart';import 'avatar_upload.dart';+import 'activity.dart';import 'controller.dart';import 'decisions.dart';import 'model.dart';@@ -35,6 +36,7 @@ class SuperTabClient {this.onTabs,this.onSelection,this.onMention,+ this.onChatMessage,this.onTagCounts,this.onNotices,this.upload = refuseUpload,@@ -67,6 +69,11 @@ class SuperTabClient {/// A new tag of the reader in Swarm `tabId`.final void Function(String tabId, SuperTabMention mention)? onMention;+ /// A new message in a chat the reader set to All new messages+ /// ([SuperTabChatNotices]), with the Swarm, the chat and how far it goes.+ final void Function(String tabId, SuperTabConversation group, int sequence)?+ onChatMessage;+/// The waiting tags of a Swarm that is not open changed ([waitingTags]).final void Function()? onTagCounts;@@ -766,6 +773,10 @@ class SuperTabClient {..onArrived = onMention == null? null: (mention) => onMention!(id, mention);+ if (onChatMessage case final told?) {+ SuperTabChatNotices.of(controller).onMessage = (group, sequence) =>+ told(id, group, sequence);+ }if (onNotices case final changed?) {SuperTabMentions.of(controller).addListener(changed);SuperTabDecisions.of(controller).addListener(changed);diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 78b4b079b..c5e362ccb 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -192,6 +192,7 @@ class SuperTabController extends ChangeNotifier {);devicesSelected = initial['devicesSelected'] == true;projectsGroupOpen = initial['projectsGroupOpen'] as bool? ?? true;+ unreadOnly = initial['unreadOnly'] == true;machinesGroupOpen = initial['machinesGroupOpen'] as bool? ?? true;buddiesGroupOpen = initial['buddiesGroupOpen'] as bool? ?? true;modelsGroupOpen = initial['modelsGroupOpen'] as bool? ?? true;@@ -2207,6 +2208,7 @@ class SuperTabController extends ChangeNotifier {}accessRevoked = true;devicesSelected = false;+ _forgetAttention();error = message;snapshot = null;_parts = null;@@ -2243,6 +2245,7 @@ class SuperTabController extends ChangeNotifier {'statusFolded': _statusFolded.toList(),'devicesSelected': devicesSelected,'projectsGroupOpen': projectsGroupOpen,+ 'unreadOnly': unreadOnly,'machinesGroupOpen': machinesGroupOpen,'buddiesGroupOpen': buddiesGroupOpen,'modelsGroupOpen': modelsGroupOpen,@@ -2692,7 +2695,10 @@ class SuperTabController extends ChangeNotifier {/// lines among them, for the Swarm badge.int get buddyUnread => [for (final project in snapshot?.projects ?? const <SuperTabProject>[])- if (buddyChat(project.id) case final chat?) unreadCount(chat),+ // A muted chat never counts (Slack).+ if (buddyChat(project.id) case final chat?+ when notifyOf(chat.id) != SuperTabNotify.muted)+ unreadCount(chat),].fold(0, (a, b) => a + b);/// Reads each Buddy chat whose count is still open ([_countOpen]), page by@@ -2905,6 +2911,137 @@ class SuperTabController extends ChangeNotifier {return true;}+ /// The reader's notification setting for [id] (backend chatSettings.ts):+ /// the one being sent, else the server's, else Mentions only.+ SuperTabNotify notifyOf(String id) =>+ _notifySending[id] ??+ _notifyKept[id]?.$1 ??+ snapshot?.chatSettings[id] ??+ SuperTabNotify.mentions;++ /// Settings sent and not yet seen back in a read, newest choice per chat.+ final _notifySending = <String, SuperTabNotify>{};+ int _notifyAsked = 0;++ /// Whether [group] shows as unread in the sidebar: unread, and not muted.+ /// A muted chat stays listed, greyed, and never counts (Slack).+ bool unreadShown(SuperTabConversation group) =>+ notifyOf(group.id) != SuperTabNotify.muted && unread(group);++ /// Keeps [level] for [id] on every device of the reader. Shown at once;+ /// false, and the old setting back, when the server did not keep it. A+ /// later choice for the same chat wins over an earlier one still on its way.+ Future<bool> setNotify(String id, SuperTabNotify level) async {+ if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {+ return false;+ }+ final asked = ++_notifyAsked;+ final epoch = visibilityEpoch;+ _notifySending[id] = level;+ _changed();+ var kept = false;+ try {+ final answer = await request(+ 'POST',+ '$_path/conversations/${Uri.encodeComponent(id)}/notifications',+ body: {'notify': level.name},+ );+ return kept = SuperTabNotify.parse(answer['notify'] as String?) == level;+ } catch (_) {+ return false;+ } finally {+ // Only the newest choice for this chat settles it; a read since+ // carries the server's, which [notifyOf] reads once this is gone.+ if (!_disposed && asked == _notifyAsked) {+ _notifySending.remove(id);+ if (kept && !accessRevoked && visibilityEpoch == epoch) {+ _notifyKept[id] = (level, _readSerial);+ }+ _changed();+ }+ }+ }++ /// Settings the server answered for, until a read carries them: without+ /// it a chat would flick back to the last read's setting meanwhile.+ /// With the number of the newest read started when the answer came: a+ /// read started after it carries the setting, and replaces it.+ final _notifyKept = <String, (SuperTabNotify, int)>{};++ /// Reads started, in order ([_read]).+ int _readSerial = 0;++ /// The one Mark all read that waits for its Undo, if any.+ SuperTabMarkAll? _markAll;++ /// How long Mark all read waits before the marks go to the server: read+ /// marks never move back there, so Undo works by not sending them yet.+ static const markAllHold = Duration(seconds: 6);++ /// Marks every chat of this Swarm the sidebar shows unread as read (Slack's+ /// Shift+Esc): at once on this device, on the server once [markAllHold]+ /// passes without [SuperTabMarkAll.undo]. Null when nothing is unread. A+ /// second one sends the first's marks before it starts.+ SuperTabMarkAll? markAllRead() {+ final snapshot = this.snapshot;+ if (_disposed || accessRevoked || snapshot == null) return null;+ _markAll?._commit();+ final before = <String, int?>{}, through = <String, int>{};+ for (final group in snapshot.conversations) {+ if (group.dormant || !unreadShown(group)) continue;+ final top = max(+ group.lastMainSequence ?? group.lastMessageSequence,+ _loadedMessageSequence(group.id),+ );+ before[group.id] = _readAt[group.id];+ through[group.id] = top;+ _readAt[group.id] = max(_readAt[group.id] ?? 0, top);+ }+ if (through.isEmpty) return null;+ final epoch = visibilityEpoch;+ late final SuperTabMarkAll held;+ held = _markAll = SuperTabMarkAll._(+ count: through.length,+ commit: () {+ if (_markAll == held) _markAll = null;+ if (_disposed || accessRevoked || visibilityEpoch != epoch) return;+ for (final MapEntry(key: id, value: top) in through.entries) {+ if (snapshot.conversation(id) == null) continue;+ _serverMarks.mark(id, top, kept: this.snapshot?.readMarks[id] ?? 0);+ }+ },+ undo: () {+ if (_markAll == held) _markAll = null;+ if (_disposed) return;+ for (final MapEntry(key: id, value: was) in before.entries) {+ // Only what this Mark all read moved: a chat read since keeps it.+ if (_readAt[id] != through[id]) continue;+ if (was == null) {+ _readAt.remove(id);+ } else {+ _readAt[id] = was;+ }+ }+ _saveSoon();+ _changed();+ },+ hold: markAllHold,+ );+ _saveSoon();+ _changed();+ return held;+ }++ /// The sidebar lists only chats with something unread (and the open one):+ /// Slack's unread filter, kept on this computer.+ bool unreadOnly = false;++ void toggleUnreadOnly() {+ unreadOnly = !unreadOnly;+ _saveSoon();+ _changed();+ }+/// A visible transcript passes the boundary it displayed. The loaded messages/// are authoritative: snapshots can arrive either before or after their tail.void markRead(String id, {int? through}) {@@ -2933,6 +3070,7 @@ class SuperTabController extends ChangeNotifier {// An adapting read that changes nothing redraws nothing: on a phone each// redraw of the whole tab is a long frame, every poll.final quiet = _policy.adapts && snapshot != null;+ final serial = ++_readSerial;final before = _shown;var stateChanged = false;loading = snapshot == null;@@ -3002,6 +3140,7 @@ class SuperTabController extends ChangeNotifier {throw const FormatException('A different Swarm was returned.');}snapshot = next;+ _notifyKept.removeWhere((_, kept) => kept.$2 < serial);final allowed = next.conversations.map((c) => c.id).toSet();// What this device keeps of a group goes with the group itself (a// tombstone), not when a read leaves it out: a closed group is out of@@ -3428,6 +3567,7 @@ class SuperTabController extends ChangeNotifier {const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) {accessRevoked = true;devicesSelected = false;+ _forgetAttention();snapshot = null;_parts = null;_messages.clear();@@ -4288,10 +4428,22 @@ class SuperTabController extends ChangeNotifier {}Future<void> flush() async {+ // Closing or changing account is no Undo: held marks go now.+ _markAll?._commit();_draftSave?.cancel();await _persist();}+ /// Access went: a held Mark all read sends nothing, and settings on their+ /// way or answered belong to the access that is gone.+ void _forgetAttention() {+ _markAll?._cancel();+ _markAll = null;+ _notifySending.clear();+ _notifyKept.clear();+ _notifyAsked++;+ }+/// 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);@@ -4299,6 +4451,8 @@ class SuperTabController extends ChangeNotifier {@overridevoid dispose() {+ // Closing the Swarm is no Undo: the held marks go before anything stops.+ _markAll?._commit();_disposed = true;for (final then in _onDispose) {then();@@ -4326,3 +4480,45 @@ class SuperTabController extends ChangeNotifier {super.dispose();}}++/// One Mark all read waiting for its Undo ([SuperTabController.markAllRead]).+class SuperTabMarkAll {+ SuperTabMarkAll._({+ required this.count,+ required void Function() commit,+ required void Function() undo,+ required Duration hold,+ }) : _onCommit = commit,+ _onUndo = undo {+ _timer = Timer(hold, _commit);+ }++ /// How many chats it marked read.+ final int count;+ final void Function() _onCommit, _onUndo;+ late final Timer _timer;+ bool _done = false;++ /// Whether its marks went to the server, or it was undone or dropped.+ bool get done => _done;++ /// Puts every chat it marked back as it was, if the marks are not sent yet.+ void undo() {+ if (_done) return;+ _done = true;+ _timer.cancel();+ _onUndo();+ }++ void _commit() {+ if (_done) return;+ _done = true;+ _timer.cancel();+ _onCommit();+ }++ void _cancel() {+ _done = true;+ _timer.cancel();+ }+}diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex ddb03439a..c8c415be3 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -521,6 +521,13 @@ class SuperTabSnapshot {mentionsDigest = row['mentionsDigest'] as String?,decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0,decisionsDigest = row['decisionsDigest'] as String?,+ activityDigest = row['activityDigest'] as String?,+ chatSettings = Map.unmodifiable({+ if (row['chatSettings'] case final Map settings)+ for (final MapEntry(:key, :value) in settings.entries)+ if (key is String && value is String)+ key: SuperTabNotify.parse(value),+ }),readMarks = Map.unmodifiable({if (row['readMarks'] case final Map marks)for (final MapEntry(:key, :value) in marks.entries)@@ -624,6 +631,14 @@ class SuperTabSnapshot {/// count may not; null from a backend before it (superTabs/decisions.ts).final String? decisionsDigest;+ /// Which of the reader's Activity rows are unread (replies to them, reactions to their messages), as a digest+ /// that moves when one comes or is read; null from a backend before Activity (superTabs/activity.ts).+ final String? activityDigest;++ /// The reader's own notification setting by conversation (backend chatSettings.ts); a chat not listed is at+ /// [SuperTabNotify.mentions]. Never another person's.+ final Map<String, SuperTabNotify> chatSettings;+/// The reader's own read marks kept on the server (backend readMarks.ts): the newest message sequence read, by/// conversation, on any of their devices. Never another person's.final Map<String, int> readMarks;@@ -1204,3 +1219,17 @@ String? superTabRepositoryUrl(String? remote) {}return address;}++/// A person's notification setting for one chat, as Slack's channel settings: every new message, only tags of+/// them (the default, what Desktop did before), or muted: greyed, never bold, never counting.+enum SuperTabNotify {+ all,+ mentions,+ muted;++ static SuperTabNotify parse(String? value) => switch (value) {+ 'all' => all,+ 'muted' => muted,+ _ => mentions,+ };+}diff --git a/desktop/lib/super_tabs/notifications.dart b/desktop/lib/super_tabs/notifications.dartindex 8aeae1433..c91d9d27e 100644--- a/desktop/lib/super_tabs/notifications.dart+++ b/desktop/lib/super_tabs/notifications.dart@@ -74,6 +74,18 @@ void Function(String tabId, SuperTabMention mention)? superTabMentionNotice(mention: (tabId: tabId, mentionId: mention.id),);+/// What tells the person about a new message in a chat they set to All new+/// messages: the operating system, on Desktop only, as tags are. The chat's+/// newest message is not read for it; the notice names the chat.+void Function(String tabId, SuperTabConversation group, int sequence)?+superTabChatNotice(SystemNotifications system, {bool web = kIsWeb}) => web+ ? null+ : (tabId, group, sequence) => system.postNotice(+ id: 'harness-chat:$tabId:${group.id}:$sequence',+ title: group.title,+ body: 'New messages',+ );+/// The reader's tags in one Swarm: Waiting and Earlier, read from the backend/// when the count or the digest of which tags wait moves (or, from a backend/// without the digest, whenever the Swarm changes while a tag waits). One perdiff --git a/desktop/lib/super_tabs/parts.dart b/desktop/lib/super_tabs/parts.dartindex e3737700d..85b325878 100644--- a/desktop/lib/super_tabs/parts.dart+++ b/desktop/lib/super_tabs/parts.dart@@ -61,6 +61,7 @@ class SuperTabParts {final derived = Map.of(superTabMap(answer['derived'] ?? const {}));final marks = derived.remove('readMarks');final threadMarks = derived.remove('threadMarks');+ final chatSettings = derived.remove('chatSettings');final parts = SuperTabParts._(_envelope(answer['head'], live: true),derived,@@ -81,6 +82,7 @@ class SuperTabParts {}parts._takeReadMarks(marks);parts._takeThreadMarks(threadMarks);+ parts._takeChatSettings(chatSettings);return parts;}@@ -104,6 +106,7 @@ class SuperTabParts {}parts._takeReadMarks(json['readMarks']);parts._takeThreadMarks(json['threadMarks']);+ parts._takeChatSettings(json['chatSettings']);return parts;}@@ -169,6 +172,25 @@ class SuperTabParts {return moved;}+ /// The reader's own notification setting by conversation (backend chatSettings.ts): `all`, `mentions` or `muted`.+ /// A first load sends every one, a change read those moved since its cursor; the newest wins, and a setting goes+ /// with its conversation.+ final _chatSettings = <String, String>{};++ /// Keeps each setting in [settings] the server knows; whether any moved.+ bool _takeChatSettings(Object? settings) {+ var moved = false;+ if (settings is! Map) return moved;+ for (final MapEntry(:key, :value) in settings.entries) {+ if (key is! String || value is! String) continue;+ if (!const {'all', 'mentions', 'muted'}.contains(value)) continue;+ if (_chatSettings[key] == value) continue;+ _chatSettings[key] = value;+ moved = true;+ }+ return moved;+ }+/// Dormant groups held with their data from before a stub closed them: a read by id at the stub's version is/// their current data.final _stale = <String>{};@@ -224,6 +246,7 @@ class SuperTabParts {_stale.remove(key);_readMarks.remove(key);_threadMarks.remove(key);+ _chatSettings.remove(key);removed.add(key);}} else if (kind == 'groups' && part['dormant'] == true) {@@ -254,7 +277,9 @@ class SuperTabParts {final readMarksMoved = _takeReadMarks(derived.remove('readMarks'));// Both run: one moving never skips the other.final marksMoved =- _takeThreadMarks(derived.remove('threadMarks')) | readMarksMoved;+ _takeThreadMarks(derived.remove('threadMarks')) |+ _takeChatSettings(derived.remove('chatSettings')) |+ readMarksMoved;if (!const DeepCollectionEquality().equals(derived, _derived)) {_derived = derived;changed = true;@@ -344,6 +369,9 @@ class SuperTabParts {if (_derived['decisionsDigest'] case final String digest) {state['decisionsDigest'] = digest;}+ if (_derived['activityDigest'] case final String digest) {+ state['activityDigest'] = digest;+ }// Sent only where the server does not try Harness Team accounts yet.if (_derived['teamAccounts'] == false) state['teamAccounts'] = false;// Sent by a server that takes a thread reply's New session.@@ -353,6 +381,9 @@ class SuperTabParts {// And one that gives each person one Buddy for the whole Swarm.if (_derived['swarmBuddy'] == true) state['swarmBuddy'] = true;if (_readMarks.isNotEmpty) state['readMarks'] = Map.of(_readMarks);+ if (_chatSettings.isNotEmpty) {+ state['chatSettings'] = Map.of(_chatSettings);+ }if (_threadMarks.isNotEmpty) {state['threadMarks'] = {for (final MapEntry(:key, :value) in _threadMarks.entries)@@ -379,6 +410,7 @@ class SuperTabParts {'seen': Map<String, int>.of(_seen),'stale': _stale.toList(),'readMarks': Map<String, int>.of(_readMarks),+ 'chatSettings': Map<String, String>.of(_chatSettings),'threadMarks': {for (final MapEntry(:key, :value) in _threadMarks.entries)key: Map<String, int>.of(value),diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dartindex f2e4b4bcd..f2c41f7ed 100644--- a/desktop/lib/super_tabs/project_sidebar.dart+++ b/desktop/lib/super_tabs/project_sidebar.dart@@ -7,6 +7,7 @@ import 'package:flutter/services.dart';import '../core/machine_resources.dart';import '../shared/theme/app_icons.dart';import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_icon_button.dart';import '../shared/theme/appearance_prefs_store.dart';import '../state/app_state.dart';import '../state/harness_activity.dart';@@ -14,6 +15,7 @@ import '../terminal/terminal_theme.dart';import '../terminal/terminal_theme_store.dart';import '../widgets/desktop_chrome.dart';import '../widgets/harness_activity_mark.dart';+import 'activity.dart';import 'attention.dart';import 'controller.dart';import 'identity.dart';@@ -61,6 +63,7 @@ class ProjectSidebar extends StatelessWidget {this.onNotifications,this.notificationsSelected = false,this.attention,+ this.activity,this.onThreads,this.threadsSelected = false,this.onOpenAgent,@@ -82,10 +85,15 @@ class ProjectSidebar extends StatelessWidget {final VoidCallback? onYourDevices;final bool devicesSelected;- /// The reader's tags from every project's Lead; its count is what waits.+ /// Opens the Activity view (Slack's Activity): decisions asked of the+ /// reader, tags of them, replies to them and reactions to their messages.final VoidCallback? onNotifications;final bool notificationsSelected;+ /// What the Activity row counts and whether it is bold; without it the+ /// row counts the tags and decisions waiting, as Notifications did.+ final SuperTabActivity? activity;+/// 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@@ -225,7 +233,7 @@ class ProjectSidebar extends StatelessWidget {// has its own; collapsed, it is bold for anything it hides.final unread =reading == null || controller.expandedProjects.contains(project?.id)- ? controller.unread(group)+ ? controller.unreadShown(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.@@ -309,12 +317,15 @@ class ProjectSidebar extends StatelessWidget {// 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.+ // A muted chat stays listed, greyed, never bold (Slack); the open one+ // keeps its highlight.+ final muted = controller.notifyOf(group.id) == SuperTabNotify.muted;final style = DesktopChrome.control(medium: highlighted,- color: highlighted || unread+ color: highlighted || (unread && !muted)? DesktopChrome.foreground: DesktopChrome.muted,- ).copyWith(fontWeight: unread ? grid.AppFont.semibold : null);+ ).copyWith(fontWeight: unread && !muted ? grid.AppFont.semibold : null);return Padding(padding: const EdgeInsets.only(bottom: 2),// Hover lights the whole row, chevron included, in the selected@@ -435,6 +446,20 @@ class ProjectSidebar extends StatelessWidget {),),],+ if (muted) ...[+ const SizedBox(width: 8),+ Tooltip(+ message: 'Muted',+ child: Icon(+ AppIcons.bellOff,+ key: ValueKey(+ 'super-muted-${group.id}',+ ),+ size: 14,+ color: DesktopChrome.muted,+ ),+ ),+ ],if (project?.isPrivate == true) ...[const SizedBox(width: 8),Tooltip(@@ -646,7 +671,9 @@ class ProjectSidebar extends StatelessWidget {final listed = [for (final project in projects)if (reading.of(project) case final read- when read.buddyChat != null || controller.canWrite)+ when (read.buddyChat != null || controller.canWrite) &&+ (!controller.unreadOnly ||+ (read.buddyChat != null && _keptByFilter(read.buddyChat!))))read,];return [for (final read in listed) _buddy(read, named: listed.length > 1)];@@ -686,7 +713,7 @@ class ProjectSidebar extends StatelessWidget {},selected:chat != null && !_paneCovered && controller.selectedId == chat.id,- unread: chat != null && controller.unread(chat),+ unread: chat != null && controller.unreadShown(chat),badge: chat == null ? 0 : attention?.mentionsIn(chat.id) ?? 0,onTap: chat != null? () => onSelect(chat.id)@@ -706,6 +733,10 @@ class ProjectSidebar extends StatelessWidget {const key = SuperTabController.kSwarmBuddyKey;final chat = controller.buddyChat(key);if (chat == null && !controller.canWrite) return null;+ // The unread filter keeps it only with something unread, or open.+ if (controller.unreadOnly && (chat == null || !_keptByFilter(chat))) {+ return null;+ }final agent = controller.buddy(key);final busy = controller.saving || controller.hasPendingAction;return _drawRow(@@ -718,7 +749,8 @@ class ProjectSidebar extends StatelessWidget {!notificationsSelected &&controller.selectedId == chat.id,waiting: false,- unread: chat != null && controller.unread(chat),+ // Muted, it is greyed and never bold, as every chat (_drawRow).+ unread: chat != null && controller.unreadShown(chat),trailing: agent == null ? null : _buddyMark(agent),onTap: chat == null ? () => _openBuddyChat(key) : null,tappable: chat != null || !busy,@@ -751,24 +783,12 @@ class ProjectSidebar extends StatelessWidget {/// A project's open conversations, newest first: the most recently created/// has the highest number, and one without a number predates numbering.- List<SuperTabConversation> _newestFirst(_ProjectReading reading) {- final project = reading.project;- final groups = reading.conversations- .where(- (g) =>- g.id != project.leadConversationId &&- !g.isBuddyChat &&- !controller.hiddenByBuddies(g) &&- !g.closed,- )- .toList();- // A stable sort keeps the backend's order among unnumbered ones.- mergeSort(- groups,- compare: (a, b) => (b.number ?? 0).compareTo(a.number ?? 0),- );- return groups;- }+ List<SuperTabConversation> _newestFirst(_ProjectReading reading) =>+ superTabOpenWorkgroups(+ controller,+ reading.project,+ reading.conversations,+ );/// The "… N more" row under a project's newest conversations.Widget _moreRow(SuperTabProject project, int hidden, VoidCallback onTap) =>@@ -815,7 +835,7 @@ class ProjectSidebar extends StatelessWidget {List<Widget> _workgroups(_ProjectReading reading) {final project = reading.project;- final groups = _newestFirst(reading);+ final groups = _newestFirst(reading).where(_keptByFilter).toList();return groups.isEmpty? [Padding(@@ -856,13 +876,30 @@ class ProjectSidebar extends StatelessWidget {];}+ /// Whether the unread filter keeps [read]'s project: its chat or an open+ /// workgroup is unread or tags the reader, or the open chat is in it.+ bool _hasUnread(_ProjectReading read) =>+ (!_paneCovered && read.sidebar.selectedProjectId == read.project.id) ||+ read.unread.isNotEmpty ||+ read.mentions > 0 ||+ (read.lead != null && controller.unreadShown(read.lead!));++ /// Whether the unread filter keeps [group]'s row.+ bool _keptByFilter(SuperTabConversation group) =>+ !controller.unreadOnly ||+ (!_paneCovered && controller.selectedId == group.id) ||+ controller.unreadShown(group) ||+ (attention?.mentionsIn(group.id) ?? 0) > 0;+/// Every project with its workgroups, by name from A to Z.List<(String, Widget)> _channels(SuperTabSnapshot? snapshot,_SidebarReading reading,) => [for (final project in snapshot?.projects ?? const <SuperTabProject>[])- if (reading.of(project) case final read when read.lead != null)+ if (reading.of(project) case final read+ when read.lead != null &&+ (!controller.unreadOnly || _hasUnread(read)))(project.name,Column(@@ -880,12 +917,12 @@ class ProjectSidebar extends StatelessWidget {]..sort((a, b) => a.$1.toLowerCase().compareTo(b.$1.toLowerCase()));@override- Widget build(BuildContext context) => switch (attention) {- final attention? => ListenableBuilder(- listenable: attention,+ Widget build(BuildContext context) => switch ([?attention, ?activity]) {+ final List<Listenable> sources when sources.isNotEmpty => ListenableBuilder(+ listenable: Listenable.merge(sources),builder: (context, _) => _build(context),),- null => _build(context),+ _ => _build(context),};Widget _build(BuildContext context) {@@ -941,6 +978,20 @@ class ProjectSidebar extends StatelessWidget {onTap: () =>showSwarmLocalModels(context, controller, app: app, now: now),),+ // Slack's Activity, where Notifications was (Lead, 10-31): one row.+ if (onNotifications != null)+ _navigationRow(+ key: 'super-activity',+ label: 'Activity',+ icon: AppIcons.bell,+ onTap: onNotifications,+ selected: notificationsSelected,+ unread: activity?.unread ?? false,+ badge:+ activity?.count ??+ (snapshot?.mentionsWaiting ?? 0) ++ (snapshot?.decisionsWaiting ?? 0),+ ),if (onThreads != null)_navigationRow(key: 'super-threads',@@ -951,17 +1002,6 @@ class ProjectSidebar extends StatelessWidget {unread: attention?.threadsUnread ?? false,badge: attention?.threadMentions ?? 0,),- if (onNotifications != null)- _navigationRow(- key: 'super-notifications',- label: 'Notifications',- icon: AppIcons.bell,- onTap: onNotifications,- selected: notificationsSelected,- badge:- (snapshot?.mentionsWaiting ?? 0) +- (snapshot?.decisionsWaiting ?? 0),- ),if (onNewProject != null ||onYourDevices != null ||onNotifications != null ||@@ -971,6 +1011,18 @@ class ProjectSidebar extends StatelessWidget {const SizedBox(height: 20),SuperTabSectionHeading('Projects',+ // Slack's unread filter: only chats with something unread.+ actions: [+ AppIconButton(+ key: const ValueKey('super-unread-only'),+ icon: AppIcons.listFilter,+ selected: controller.unreadOnly,+ tooltip: controller.unreadOnly+ ? 'Show all chats'+ : 'Show unread chats only',+ onPressed: controller.toggleUnreadOnly,+ ),+ ],onAdd: controller.canWrite ? onNewProject : null,addTooltip: 'New project',endInset: 0,@@ -1189,8 +1241,57 @@ class _ProjectReading {for (final g in conversations) {if (g.closed || g.isBuddyChat || g.audience != null) continue;if (sidebar.needsHuman(g) > 0) waiting.add(g.id);- if (sidebar.controller.unread(g)) unread.add(g.id);+ if (sidebar.controller.unreadShown(g)) unread.add(g.id);}return (waiting: waiting, unread: unread);}();}++/// A project's open workgroups as the sidebar lists them, newest first: the+/// most recently created has the highest number, and one without a number+/// predates numbering.+List<SuperTabConversation> superTabOpenWorkgroups(+ SuperTabController controller,+ SuperTabProject project, [+ List<SuperTabConversation>? conversations,+]) {+ final groups = (conversations ?? controller.projectConversations(project.id))+ .where(+ (g) =>+ g.id != project.leadConversationId &&+ !g.isBuddyChat &&+ !controller.hiddenByBuddies(g) &&+ !g.closed,+ )+ .toList();+ // A stable sort keeps the backend's order among unnumbered ones.+ mergeSort(+ groups,+ compare: (a, b) => (b.number ?? 0).compareTo(a.number ?? 0),+ );+ return groups;+}++/// The chats in the order the sidebar lists them, for Option+Shift+Down and+/// Up (Slack's next unread): the reader's one Buddy chat (`# buddy`, first+/// under Projects), each project from A to Z, its chat then its open+/// workgroups newest first, then the reader's project Buddy chats.+List<String> superTabSidebarOrder(SuperTabController controller) {+ final snapshot = controller.snapshot;+ if (snapshot == null) return const [];+ final projects = [...snapshot.projects]+ ..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));+ return [+ if (controller.oneBuddy)+ if (controller.buddyChat(SuperTabController.kSwarmBuddyKey)+ case final chat?)+ chat.id,+ for (final project in projects) ...[+ if (snapshot.conversation(project.leadConversationId) != null)+ project.leadConversationId,+ for (final group in superTabOpenWorkgroups(controller, project)) group.id,+ ],+ for (final project in projects)+ if (controller.buddyChat(project.id) case final chat?) chat.id,+ ];+}diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 62b45ca05..6d3513886 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -35,6 +35,8 @@ import 'composer_files.dart';import 'composer_newline.dart';import 'composer_tags.dart';import 'composer_toggle.dart';+import 'activity.dart';+import 'activity_view.dart';import 'attention.dart';import 'controller.dart';import 'dialog_scope.dart';@@ -634,6 +636,93 @@ class _SuperTabViewState extends State<SuperTabView>}/// Esc: everything loaded in the open conversation is read, line and all.+ /// Keeps the reader's notification setting for [id]; says so when the+ /// server did not keep it.+ Future<void> _setNotify(String id, SuperTabNotify level) async {+ if (await c.setNotify(id, level) || !mounted || c.accessRevoked) return;+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(+ const SnackBar(+ content: Text('Could not change notifications. Try again.'),+ ),+ );+ }++ /// Slack's Shift+Esc: every chat read, with an Undo while the marks wait.+ bool _markAllRead() {+ final held = c.markAllRead();+ if (held == null) return false;+ setState(() {+ _unread.clear(c.selectedId);+ _newAfter.remove(c.selectedId);+ });+ final messenger = ScaffoldMessenger.maybeOf(context);+ messenger+ ?..hideCurrentSnackBar()+ ..showSnackBar(+ SnackBar(+ key: const ValueKey('super-mark-all-toast'),+ duration: SuperTabController.markAllHold,+ content: Text(+ held.count == 1+ ? 'Marked 1 chat read'+ : 'Marked ${held.count} chats read',+ ),+ action: SnackBarAction(label: 'Undo', onPressed: held.undo),+ ),+ );+ return true;+ }++ /// Slack's Option+Shift+Down and Up: the next or previous chat with+ /// something unread, in the sidebar's order, skipping muted ones. At either+ /// end nothing moves.+ bool _jumpUnread(int step) {+ final snapshot = c.snapshot;+ if (snapshot == null || c.accessRevoked) return false;+ final order = superTabSidebarOrder(c);+ var at = order.indexOf(c.selectedId);+ if (at < 0) at = step > 0 ? -1 : order.length;+ for (var i = at + step; i >= 0 && i < order.length; i += step) {+ final group = snapshot.conversation(order[i]);+ if (group == null || !c.unreadShown(group)) continue;+ widget.onCloseTerminal?.call();+ setState(() {+ _showNotifications = _showThreads = false;+ _showPullRequests = false;+ });+ unawaited(c.select(group.id));+ return true;+ }+ return false;+ }++ /// The Swarm's own keys, heard from anywhere in it that leaves them.+ KeyEventResult _attentionKey(FocusNode node, KeyEvent event) {+ if (event is! KeyDownEvent) return KeyEventResult.ignored;+ final keys = HardwareKeyboard.instance;+ if (keys.isControlPressed || keys.isMetaPressed) {+ return KeyEventResult.ignored;+ }+ if (event.logicalKey == LogicalKeyboardKey.escape &&+ keys.isShiftPressed &&+ !keys.isAltPressed) {+ _markAllRead();+ return KeyEventResult.handled;+ }+ if (keys.isAltPressed && keys.isShiftPressed) {+ final step = switch (event.logicalKey) {+ LogicalKeyboardKey.arrowDown => 1,+ LogicalKeyboardKey.arrowUp => -1,+ _ => 0,+ };+ if (step != 0) {+ _jumpUnread(step);+ return KeyEventResult.handled;+ }+ }+ return KeyEventResult.ignored;+ }+bool _readAll() {final id = c.selectedId, group = c.selected;if (group == null || (!c.unread(group) && _unread.lineAt(id) == null)) {@@ -1485,6 +1574,7 @@ class _SuperTabViewState extends State<SuperTabView>devicesSelected: _devicesVisible,notificationsSelected: _notificationsVisible,attention: SuperTabAttention.of(c),+ activity: SuperTabActivity.of(c),threadsSelected: _threadsVisible,onThreads: () {_closeSidebar();@@ -1495,19 +1585,17 @@ class _SuperTabViewState extends State<SuperTabView>});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- ? null- : () {- _closeSidebar();- setState(() {- _showNotifications = true;- _showThreads = false;- _showPullRequests = false;- });- widget.onCloseTerminal?.call();- },+ // Activity on every platform (Lead, 10-31): the Mac's menu bar and Dock+ // still say what waits, and the sidebar lists it as Slack does.+ onNotifications: () {+ _closeSidebar();+ setState(() {+ _showNotifications = true;+ _showThreads = false;+ _showPullRequests = false;+ });+ widget.onCloseTerminal?.call();+ },onOpenAgent: (agent) {_closeSidebar();setState(() {@@ -2049,7 +2137,7 @@ class _SuperTabViewState extends State<SuperTabView>final name = _devicesVisible? 'Your devices': _notificationsVisible- ? 'Notifications'+ ? 'Activity': _threadsVisible? 'Threads': group == null@@ -2387,6 +2475,30 @@ class _SuperTabViewState extends State<SuperTabView>),],],+ // The reader's own setting for this chat, kept on every device+ // (Slack's channel notifications); a viewer has one too.+ SubmenuButton(+ key: const ValueKey('super-notify-menu'),+ menuChildren: [+ for (final (level, label) in const [+ (SuperTabNotify.all, 'All new messages'),+ (SuperTabNotify.mentions, 'Mentions only'),+ (SuperTabNotify.muted, 'Muted'),+ ])+ MenuItemButton(+ key: ValueKey('super-notify-${level.name}'),+ leadingIcon: SizedBox(+ width: 16,+ child: c.notifyOf(group.id) == level+ ? const Icon(AppIcons.check, size: 14)+ : null,+ ),+ onPressed: () => unawaited(_setNotify(group.id, level)),+ child: Text(label),+ ),+ ],+ child: const Text('Notifications'),+ ),// Until all of the project's closed groups are read, it may have// archived ones: the list reads them when it opens.if (!c.dormantLoaded(group.projectId) ||@@ -3562,6 +3674,7 @@ class _SuperTabViewState extends State<SuperTabView>if (picked != null) return picked;if (event is KeyDownEvent &&event.logicalKey == LogicalKeyboardKey.escape &&+ !HardwareKeyboard.instance.isShiftPressed &&_readAll()) {return KeyEventResult.handled;}@@ -3842,152 +3955,125 @@ class _SuperTabViewState extends State<SuperTabView>unawaited(c.select(id));},);- return Stack(- children: [- ExcludeFocus(- excluding: chatCovered,- child: SuperTabPaneLayout(- storage: widget.app?.localStore,- onLeave: _leaveResize,- left: narrow ? null : _sidebar(),- // An open thread takes the roster's side, as in Slack.- right: !showRoster ? null : thread ?? roster,- rightDefault: thread == null- ? SuperTabPaneLayout.rightWidth- : SuperTabPaneLayout.threadWidth,- center: Column(- children: [- _header(c.selected, narrow, showRoster),- Expanded(- child: IndexedStack(- index: _devicesVisible- ? 1- : _notificationsVisible- ? 3- : _threadsVisible- ? 4- : c.snapshot?.projects.isEmpty == true- ? 0- : _terminalsVisible- ? 1- : _showPullRequests- ? 2- : 0,- children: [- _conversation(narrow),- terminal ?? const SizedBox.shrink(),- _showPullRequests- ? SuperTabPullRequests(- controller: c,- app: widget.app,- visible: !_terminalsVisible,- )- : const SizedBox.shrink(),- _notificationsVisible- ? SuperTabNotifications(- mentions: SuperTabMentions.of(c),- onOpen: (mention) =>- unawaited(_openMention(mention)),- leading: SuperTabDecisionList(- decisions: SuperTabDecisions.of(c),- ),- )- : const SizedBox.shrink(),- _threadsVisible- ? SuperTabThreadsView(- attention: SuperTabAttention.of(c),- onOpen: _openThreadFromList,- machineName: widget.machineName,- )- : const SizedBox.shrink(),- ],- ),- ),- ],- ),- ),- ),- if (threadDrawer)- Positioned.fill(- child: BlockSemantics(- child: GestureDetector(- onTap: c.closeThread,- child: ColoredBox(- color: grid.AppDesktop.veil(Theme.of(context).brightness),- child: Align(- alignment: Alignment.centerRight,- child: GestureDetector(- // A click inside the thread stays there.- onTap: () {},- child: SizedBox(- width: SuperTabPaneLayout.drawerWidth(- constraints.maxWidth,- max: SuperTabPaneLayout.threadWidth,- ),- child: thread,- ),+ return Focus(+ canRequestFocus: false,+ skipTraversal: true,+ onKeyEvent: _attentionKey,+ child: Stack(+ children: [+ ExcludeFocus(+ excluding: chatCovered,+ child: SuperTabPaneLayout(+ storage: widget.app?.localStore,+ onLeave: _leaveResize,+ left: narrow ? null : _sidebar(),+ // An open thread takes the roster's side, as in Slack.+ right: !showRoster ? null : thread ?? roster,+ rightDefault: thread == null+ ? SuperTabPaneLayout.rightWidth+ : SuperTabPaneLayout.threadWidth,+ center: Column(+ children: [+ _header(c.selected, narrow, showRoster),+ Expanded(+ child: IndexedStack(+ index: _devicesVisible+ ? 1+ : _notificationsVisible+ ? 3+ : _threadsVisible+ ? 4+ : c.snapshot?.projects.isEmpty == true+ ? 0+ : _terminalsVisible+ ? 1+ : _showPullRequests+ ? 2+ : 0,+ children: [+ _conversation(narrow),+ terminal ?? const SizedBox.shrink(),+ _showPullRequests+ ? SuperTabPullRequests(+ controller: c,+ app: widget.app,+ visible: !_terminalsVisible,+ )+ : const SizedBox.shrink(),+ _notificationsVisible+ ? SuperTabActivityView(+ activity: SuperTabActivity.of(c),+ onOpenMention: (mention) =>+ unawaited(_openMention(mention)),+ onOpenMessage: (id, messageId) =>+ unawaited(_openMessage(id, messageId)),+ )+ : const SizedBox.shrink(),+ _threadsVisible+ ? SuperTabThreadsView(+ attention: SuperTabAttention.of(c),+ onOpen: _openThreadFromList,+ machineName: widget.machineName,+ )+ : const SizedBox.shrink(),+ ],),),- ),+ ],),),),- if (!showRoster && _rosterOpen && !threadDrawer)- Positioned.fill(- child: BlockSemantics(- child: FocusScope(- autofocus: true,- onKeyEvent: (_, event) {- if (event is KeyDownEvent &&- event.logicalKey == LogicalKeyboardKey.escape) {- _closeRoster();- return KeyEventResult.handled;- }- return KeyEventResult.ignored;- },+ if (threadDrawer)+ Positioned.fill(+ child: BlockSemantics(child: GestureDetector(- onTap: _closeRoster,+ onTap: c.closeThread,child: ColoredBox(color: grid.AppDesktop.veil(Theme.of(context).brightness),child: Align(alignment: Alignment.centerRight,- child: SizedBox(- width: SuperTabPaneLayout.drawerWidth(- constraints.maxWidth,+ child: GestureDetector(+ // A click inside the thread stays there.+ onTap: () {},+ child: SizedBox(+ width: SuperTabPaneLayout.drawerWidth(+ constraints.maxWidth,+ max: SuperTabPaneLayout.threadWidth,+ ),+ child: thread,),- child: roster,),),),),),),- ),- if (narrow && _sidebarOpen)- Positioned.fill(- child: BlockSemantics(- child: FocusScope(- autofocus: true,- onKeyEvent: (_, event) {- if (event is KeyDownEvent &&- event.logicalKey == LogicalKeyboardKey.escape) {- _closeSidebar();- return KeyEventResult.handled;- }- return KeyEventResult.ignored;- },- child: GestureDetector(- onTap: _closeSidebar,- child: ColoredBox(- color: grid.AppDesktop.veil(Theme.of(context).brightness),- child: Align(- alignment: Alignment.centerLeft,- child: SizedBox(- width: 240,- child: Material(- color: DesktopChrome.surface,- elevation: 8,- child: _sidebar(),+ if (!showRoster && _rosterOpen && !threadDrawer)+ Positioned.fill(+ child: BlockSemantics(+ child: FocusScope(+ autofocus: true,+ onKeyEvent: (_, event) {+ if (event is KeyDownEvent &&+ event.logicalKey == LogicalKeyboardKey.escape) {+ _closeRoster();+ return KeyEventResult.handled;+ }+ return KeyEventResult.ignored;+ },+ child: GestureDetector(+ onTap: _closeRoster,+ child: ColoredBox(+ color: grid.AppDesktop.veil(+ Theme.of(context).brightness,+ ),+ child: Align(+ alignment: Alignment.centerRight,+ child: SizedBox(+ width: SuperTabPaneLayout.drawerWidth(+ constraints.maxWidth,+ ),+ child: roster,),),),@@ -3995,8 +4081,43 @@ class _SuperTabViewState extends State<SuperTabView>),),),- ),- ],+ if (narrow && _sidebarOpen)+ Positioned.fill(+ child: BlockSemantics(+ child: FocusScope(+ autofocus: true,+ onKeyEvent: (_, event) {+ if (event is KeyDownEvent &&+ event.logicalKey == LogicalKeyboardKey.escape) {+ _closeSidebar();+ return KeyEventResult.handled;+ }+ return KeyEventResult.ignored;+ },+ child: GestureDetector(+ onTap: _closeSidebar,+ child: ColoredBox(+ color: grid.AppDesktop.veil(+ Theme.of(context).brightness,+ ),+ child: Align(+ alignment: Alignment.centerLeft,+ child: SizedBox(+ width: 240,+ child: Material(+ color: DesktopChrome.surface,+ elevation: 8,+ child: _sidebar(),+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ ],+ ),);},);diff --git a/desktop/test/super_tab_activity_test.dart b/desktop/test/super_tab_activity_test.dartnew file mode 100644index 000000000..c6ec73544--- /dev/null+++ b/desktop/test/super_tab_activity_test.dart@@ -0,0 +1,728 @@+import 'dart:async';++import 'package:fake_async/fake_async.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/activity.dart';+import 'package:harness/super_tabs/activity_view.dart';+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/model.dart';+import 'package:harness/super_tabs/parts.dart';+import 'package:harness/super_tabs/project_sidebar.dart';+import 'package:harness/super_tabs/view.dart';+import 'package:harness/super_tabs/workgroup_name.dart';+import 'package:harness/widgets/desktop_chrome.dart';++import 'super_tab_attention_test.dart'+ show close, conversation, fromLead, inRow, openHere, projectServer, rowText;+import 'support/buddy_fixture.dart';+import 'support/super_tab_fixture.dart';++Map<String, dynamic> reply(+ String id, {+ String conversationId = 'lead',+ bool read = false,+ String createdAt = '2026-10-31T03:00:00.000Z',+}) => {+ 'id': id,+ 'kind': 'reply',+ 'conversationId': conversationId,+ 'conversationTitle': 'Chat $conversationId',+ 'projectName': 'web-project',+ 'messageId': 'm-$id',+ 'messageSequence': 4,+ 'threadId': 'root',+ 'actor': {'kind': 'person', 'id': 'peer', 'name': 'peer'},+ 'emoji': null,+ 'text': 'Reply $id',+ 'createdAt': createdAt,+ 'read': read,+};++Map<String, dynamic> reaction(String id, {bool read = false}) => {+ ...reply(id, read: read),+ 'kind': 'reaction',+ 'emoji': 'check',+ 'text': 'My message',+};++Future<SuperTabController> open(ConversationServer server) async {+ final c = server.controller();+ addTearDown(() async {+ await c.flush();+ c.dispose();+ });+ await c.refresh();+ return c;+}++Future<void> settle() async {+ for (var i = 0; i < 6; i++) {+ await pumpEventQueue();+ }+}++Future<void> pumpSidebar(+ WidgetTester tester,+ SuperTabController c, {+ Brightness brightness = Brightness.dark,+}) async {+ await tester.binding.setSurfaceSize(const Size(320, 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: SuperTabAttention.of(c),+ activity: SuperTabActivity.of(c),+ onNotifications: () {},+ onThreads: () {},+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+}++void main() {+ group('the read model keeps the reader\'s chat settings', () {+ Map<String, dynamic> load(Map<String, dynamic> derived) => {+ 'format': superTabReadFormat,+ 'tabId': 'tab',+ 'cursor': 'c1',+ 'epoch': 1,+ 'lastChangedAt': 1,+ 'head': {+ 'key': 'head',+ 'version': 1,+ 'changedAt': 1,+ 'data': {+ 'id': 'tab',+ 'name': 'Swarm',+ 'ownerId': 'owner',+ 'projects': <dynamic>[],+ 'invitations': <dynamic>[],+ },+ },+ 'groups': [+ {+ 'key': 'lead',+ 'version': 1,+ 'changedAt': 1,+ 'data': conversationFixture('lead', 'Lead'),+ },+ ],+ 'derived': derived,+ };++ test('a change read without them keeps them; a moved one replaces it; '+ 'the conversation gone takes it', () {+ final parts = SuperTabParts.firstLoad(+ load({+ 'activityDigest': 'd1',+ 'chatSettings': {'lead': 'muted', 'gone': 'loud'},+ }),+ );+ expect(parts.state['chatSettings'], {'lead': 'muted'});+ expect(parts.state['activityDigest'], 'd1');+ var change = parts.apply({+ 'cursor': 'c2',+ 'derived': {'activityDigest': 'd2'},+ });+ expect(parts.state['chatSettings'], {'lead': 'muted'});+ expect(parts.state['activityDigest'], 'd2');+ change = parts.apply({+ 'cursor': 'c3',+ 'derived': {+ 'activityDigest': 'd2',+ 'chatSettings': {'lead': 'all'},+ },+ });+ expect(change.changed, isTrue);+ expect(parts.state['chatSettings'], {'lead': 'all'});+ // Kept on this device and read back.+ final back = SuperTabParts.fromJson(parts.toJson());+ expect(back.state['chatSettings'], {'lead': 'all'});+ parts.apply({+ 'cursor': 'c4',+ 'groups': [+ {'key': 'lead', 'version': 2, 'changedAt': 4, 'deleted': true},+ ],+ });+ expect(parts.state['chatSettings'], isNull);+ // A setting the app does not know reads as the default.+ expect(SuperTabNotify.parse('muted'), SuperTabNotify.muted);+ expect(SuperTabNotify.parse('all'), SuperTabNotify.all);+ expect(SuperTabNotify.parse('loud'), SuperTabNotify.mentions);+ });+ });++ group('per-chat notification setting', () {+ test('shows at once, is kept on the server, and a failure puts the old '+ 'setting back', () async {+ final server = projectServer();+ final c = await open(server);+ expect(c.notifyOf('offline'), SuperTabNotify.mentions);+ server.holdNotify = Completer();+ final kept = c.setNotify('offline', SuperTabNotify.muted);+ expect(c.notifyOf('offline'), SuperTabNotify.muted);+ server.holdNotify!.complete();+ expect(await kept, isTrue);+ expect(server.notifyPosts.last, {+ 'conversationId': 'offline',+ 'notify': 'muted',+ });+ // Still muted until a read carries it, and after.+ expect(c.notifyOf('offline'), SuperTabNotify.muted);+ await c.refresh();+ expect(c.snapshot!.chatSettings['offline'], SuperTabNotify.muted);+ expect(c.notifyOf('offline'), SuperTabNotify.muted);+ server.failNotify = true;+ expect(await c.setNotify('offline', SuperTabNotify.all), isFalse);+ expect(c.notifyOf('offline'), SuperTabNotify.muted);+ });++ test('another device\'s change wins once a read carries it', () async {+ final server = projectServer();+ final c = await open(server);+ await c.setNotify('offline', SuperTabNotify.muted);+ await c.refresh();+ (server.state['chatSettings'] as Map)['owner']['offline'] = 'all';+ server.revision++;+ await c.refresh();+ expect(c.notifyOf('offline'), SuperTabNotify.all);+ });++ test(+ 'access lost while a setting is on its way: nothing of it stays',+ () async {+ final server = projectServer();+ final c = await open(server);+ server.holdNotify = Completer();+ final kept = c.setNotify('offline', SuperTabNotify.muted);+ expect(c.notifyOf('offline'), SuperTabNotify.muted);+ c.revokeAccess('Removed from this Swarm.');+ // At once, not when the answer comes.+ expect(c.notifyOf('offline'), SuperTabNotify.mentions);+ server.holdNotify!.complete();+ await kept;+ expect(c.notifyOf('offline'), SuperTabNotify.mentions);+ },+ );++ test('a muted chat is never unread in the sidebar and its tags never '+ 'count', () async {+ final server = projectServer();+ fromLead(server, 'News', conversationId: 'offline');+ server.tag('message-1', conversationId: 'offline');+ final c = await open(server);+ final attention = SuperTabAttention.of(c);+ await attention.mentions.load();+ final group = c.snapshot!.conversation('offline')!;+ expect(c.unreadShown(group), isTrue);+ expect(attention.mentionsIn('offline'), 1);+ await c.setNotify('offline', SuperTabNotify.muted);+ expect(c.unread(group), isTrue);+ expect(c.unreadShown(group), isFalse);+ expect(attention.mentionsIn('offline'), 0);+ });+ });++ group('Mark all read (Shift+Esc) holds its write for Undo', () {+ test('marks every unread chat here at once, sends nothing until the hold '+ 'ends, then sends each', () {+ fakeAsync((async) {+ final server = projectServer();+ fromLead(server, 'One');+ fromLead(server, 'Two', conversationId: 'offline');+ late SuperTabController c;+ c = server.controller();+ unawaited(c.refresh());+ async.flushMicrotasks();+ final groups = c.snapshot!.conversations;+ expect(groups.where(c.unreadShown).length, 2);+ final held = c.markAllRead()!;+ expect(held.count, 2);+ expect(groups.where(c.unreadShown), isEmpty);+ async.elapse(const Duration(seconds: 5));+ expect(server.readMarkPosts, isEmpty);+ async.elapse(const Duration(seconds: 2));+ async.flushMicrotasks();+ expect(server.readMarkPosts.map((p) => p['conversationId']).toSet(), {+ 'lead',+ 'offline',+ });+ unawaited(c.flush());+ async.flushMicrotasks();+ c.dispose();+ });+ });++ test('Undo puts each chat back as it was and sends nothing', () {+ fakeAsync((async) {+ final server = projectServer();+ fromLead(server, 'One', conversationId: 'offline');+ final c = server.controller();+ unawaited(c.refresh());+ async.flushMicrotasks();+ final group = c.snapshot!.conversation('offline')!;+ final held = c.markAllRead()!;+ expect(c.unreadShown(group), isFalse);+ held.undo();+ expect(c.unreadShown(group), isTrue);+ async.elapse(const Duration(seconds: 10));+ async.flushMicrotasks();+ expect(server.readMarkPosts, isEmpty);+ expect(c.markAllRead(), isNotNull);+ unawaited(c.flush());+ async.flushMicrotasks();+ c.dispose();+ });+ });++ test('access lost during the hold sends nothing; closing the Swarm sends '+ 'the marks', () {+ fakeAsync((async) {+ final server = projectServer();+ fromLead(server, 'One', conversationId: 'offline');+ final c = server.controller();+ unawaited(c.refresh());+ async.flushMicrotasks();+ c.markAllRead();+ c.revokeAccess('Removed from this Swarm.');+ async.elapse(const Duration(seconds: 10));+ async.flushMicrotasks();+ expect(server.readMarkPosts, isEmpty);+ c.dispose();++ final again = projectServer();+ fromLead(again, 'One', conversationId: 'offline');+ final d = again.controller();+ unawaited(d.refresh());+ async.flushMicrotasks();+ d.markAllRead();+ d.dispose();+ async.flushMicrotasks();+ expect(again.readMarkPosts.map((p) => p['conversationId']), [+ 'offline',+ ]);+ });+ });++ test(+ 'a muted chat is left as it is; nothing unread gives nothing',+ () async {+ final server = projectServer();+ fromLead(server, 'One', conversationId: 'offline');+ final c = await open(server);+ await c.setNotify('offline', SuperTabNotify.muted);+ expect(c.markAllRead(), isNull);+ },+ );+ });++ group('next unread chat follows the sidebar\'s order', () {+ test('projects A to Z, each chat then its newest workgroups first, then '+ 'Buddy chats', () async {+ final server = projectServer();+ (server.state['projects'] as List).add(+ projectFixture('alpha', 'alpha', 'alpha-chat'),+ );+ (server.state['conversations'] as List)+ ..add({+ ...conversationFixture('alpha-chat', 'alpha'),+ 'projectId': 'alpha',+ })+ ..add({+ ...conversationFixture('newer', 'Newer'),+ 'projectId': 'lead',+ 'number': 20,+ });+ final c = await open(server);+ expect(superTabSidebarOrder(c), [+ 'alpha-chat',+ 'lead',+ 'newer',+ 'offline',+ ]);+ });+ });++ group('Activity: replies and reactions to the reader', () {+ test('reads when its digest moves, not again for the same digest, and '+ 'keeps only chats this Swarm lists', () async {+ final server = projectServer();+ server.state['activityDigest'] = 'd1';+ server.activity = {+ 'items': [reply('r1'), reply('r2', conversationId: 'other-swarm-chat')],+ 'more': false,+ };+ final c = await open(server);+ final activity = SuperTabActivity.of(c);+ await settle();+ expect(server.activityReads, hasLength(1));+ expect(activity.items.map((i) => i.id), ['r1']);+ expect(activity.count, 1);+ await c.refresh();+ await settle();+ expect(server.activityReads, hasLength(1));+ server.state['activityDigest'] = 'd2';+ server.revision++;+ await c.refresh();+ await settle();+ expect(server.activityReads, hasLength(2));+ });++ test('a server before Activity (404) asks once; tags and decisions still '+ 'count', () async {+ final server = projectServer();+ server.state['activityDigest'] = 'd1';+ server.state['mentionsWaiting'] = 2;+ server.activity = null;+ final c = await open(server);+ final activity = SuperTabActivity.of(c);+ await settle();+ expect(activity.supported, isFalse);+ expect(activity.count, 2);+ server.state['activityDigest'] = 'd2';+ server.revision++;+ await c.refresh();+ await settle();+ expect(server.activityReads, hasLength(1));+ });++ test(+ 'a failed first read says so, and a later digest recovers it',+ () async {+ final server = projectServer();+ server.state['activityDigest'] = 'd1';+ server.activityStatus = 503;+ server.activity = {+ 'items': [reply('r1')],+ 'more': false,+ };+ final c = await open(server);+ final activity = SuperTabActivity.of(c);+ await settle();+ expect(activity.error, isNotNull);+ expect(activity.items, isEmpty);+ server.activityStatus = 0;+ // The next change of the Swarm reads it again, though its digest+ // did not move.+ fromLead(server, 'Something else changed');+ await c.refresh();+ await settle();+ expect(activity.error, isNull);+ expect(activity.items.map((i) => i.id), ['r1']);+ },+ );++ test(+ 'access lost: rows go at once and an answer on its way is dropped',+ () async {+ final server = projectServer();+ server.state['activityDigest'] = 'd1';+ server.activity = {+ 'items': [reply('r1')],+ 'more': false,+ };+ final c = await open(server);+ final activity = SuperTabActivity.of(c);+ await settle();+ expect(activity.items, hasLength(1));+ server.holdActivity = Completer();+ unawaited(activity.load());+ await pumpEventQueue();+ c.revokeAccess('Removed from this Swarm.');+ expect(activity.items, isEmpty);+ expect(activity.count, 0);+ server.holdActivity!.complete();+ await settle();+ expect(activity.items, isEmpty);+ },+ );++ test(+ 'a read that answers after the Swarm\'s audience moved is dropped',+ () async {+ final server = projectServer();+ server.state['activityDigest'] = 'd1';+ server.activity = {+ 'items': [reply('r1')],+ 'more': false,+ };+ final c = await open(server);+ final activity = SuperTabActivity.of(c);+ await settle();+ server.holdActivity = Completer();+ unawaited(activity.load());+ await pumpEventQueue();+ server.parts.epoch++;+ server.revision++;+ server.activity = {'items': <dynamic>[], 'more': false};+ await c.refresh();+ // Every state shown from here: the old answer must never show.+ final shown = <List<String>>[];+ activity.addListener(+ () => shown.add([for (final i in activity.items) i.id]),+ );+ server.holdActivity!.complete();+ await settle();+ expect(activity.items, isEmpty);+ expect(shown.where((ids) => ids.contains('r1')), isEmpty);+ },+ );++ test(+ 'leaving the view marks what it showed read, bold until then',+ () async {+ final server = projectServer();+ server.state['activityDigest'] = 'd1';+ server.activity = {+ 'items': [reply('r1'), reaction('x1', read: true)],+ 'more': false,+ };+ final c = await open(server);+ final activity = SuperTabActivity.of(c);+ await settle();+ activity.opened();+ await settle();+ final r1 = activity.items.firstWhere((i) => i.id == 'r1');+ expect(activity.isUnread(r1), isTrue);+ expect(activity.unread, isTrue);+ activity.closed();+ await settle();+ expect(+ server.activityReadPosts.single['through'],+ '2026-10-31T03:00:00.000Z',+ );+ expect(activity.items.every((i) => i.read), isTrue);+ expect(activity.count, 0);+ },+ );+ });++ group('All new messages tells the system about each new message', () {+ test('only for a chat set to all, not on the first look, not the open '+ 'chat', () async {+ final server = projectServer();+ final c = await open(server);+ final told = <(String, int)>[];+ SuperTabChatNotices.of(c).onMessage = (g, s) => told.add((g.id, s));+ fromLead(server, 'Before', conversationId: 'offline');+ await c.refresh();+ expect(told, isEmpty);+ await c.setNotify('offline', SuperTabNotify.all);+ fromLead(server, 'After', conversationId: 'offline');+ await c.refresh();+ expect(told.map((t) => t.$1), ['offline']);+ fromLead(server, 'In the project chat');+ await c.refresh();+ expect(told.map((t) => t.$1), ['offline']);+ });+ });++ group('sidebar', () {+ for (final brightness in Brightness.values) {+ testWidgets('Activity takes Notifications\' place; a muted chat is '+ 'greyed with its mark and no number ($brightness)', (tester) async {+ final server = projectServer();+ fromLead(server, 'News', conversationId: 'offline');+ server.tag('message-1', conversationId: 'offline');+ final c = await openHere(server);+ await SuperTabAttention.of(c).mentions.load();+ c.toggleProject('lead');+ await c.setNotify('offline', SuperTabNotify.muted);+ await pumpSidebar(tester, c, brightness: brightness);+ expect(find.text('Notifications'), findsNothing);+ expect(inRow('super-activity', find.text('Activity')), findsOneWidget);+ expect(inRow('super-activity', find.text('1')), findsOneWidget);+ expect(+ find.byKey(const ValueKey('super-muted-offline')),+ findsOneWidget,+ );+ expect(+ inRow('super-group-offline', find.byType(SuperTabCountBadge)),+ findsNothing,+ );+ // The workgroup's name, drawn in the row's style.+ final name = tester.widget<SuperTabWorkgroupName>(+ find.descendant(+ of: find.byKey(const ValueKey('super-group-offline')),+ matching: find.byType(SuperTabWorkgroupName),+ ),+ );+ expect(name.style.color, DesktopChrome.muted);+ expect(name.style.fontWeight, isNot(grid.AppFont.semibold));+ await close(tester, c);+ });+ }++ testWidgets('the unread filter lists only unread chats and the open one, '+ 'and hides muted ones', (tester) async {+ final server = projectServer();+ (server.state['conversations'] as List)+ ..add({+ ...conversationFixture('quiet', 'Quiet'),+ 'projectId': 'lead',+ 'number': 13,+ })+ ..add({+ ...conversationFixture('hushed', 'Hushed'),+ 'projectId': 'lead',+ 'number': 14,+ });+ fromLead(server, 'Read');+ server.markReadElsewhere('lead', server.revision);+ fromLead(server, 'News', conversationId: 'offline');+ fromLead(server, 'Hushed news', conversationId: 'hushed');+ final c = await openHere(server);+ c.toggleProject('lead');+ await c.setNotify('hushed', SuperTabNotify.muted);+ await pumpSidebar(tester, c);+ expect(find.byKey(const ValueKey('super-group-quiet')), findsOneWidget);+ await tester.tap(find.byKey(const ValueKey('super-unread-only')));+ await tester.pumpAndSettle();+ expect(c.unreadOnly, isTrue);+ expect(find.byKey(const ValueKey('super-group-offline')), findsOneWidget);+ expect(find.byKey(const ValueKey('super-group-quiet')), findsNothing);+ expect(find.byKey(const ValueKey('super-group-hushed')), findsNothing);+ await close(tester, c);+ });+ });++ group('Activity view', () {+ testWidgets('lists tags, replies and reactions newest first, filters one '+ 'kind, and opens a row at its message', (tester) async {+ final server = projectServer();+ server.state['activityDigest'] = 'd1';+ server.activity = {+ 'items': [+ reply('r1', createdAt: '2026-10-31T05:00:00.000Z'),+ reaction('x1', read: true),+ ],+ 'more': false,+ };+ final c = await openHere(server);+ final activity = SuperTabActivity.of(c);+ await tester.runAsync(settle);+ final opened = <(String, String)>[];+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabActivityView(+ activity: activity,+ onOpenMention: (_) {},+ onOpenMessage: (id, m) => opened.add((id, m)),+ now: () => DateTime.utc(2026, 10, 31, 6),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(find.text('peer replied to your message'), findsOneWidget);+ expect(find.text('peer reacted ✅ to your message'), findsOneWidget);+ await tester.tap(+ find.byKey(const ValueKey('super-activity-filter-reactions')),+ );+ await tester.pumpAndSettle();+ expect(find.text('peer replied to your message'), findsNothing);+ await tester.tap(+ find.byKey(const ValueKey('super-activity-filter-replies')),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-activity-r1')));+ expect(opened, [('lead', 'm-r1')]);+ await close(tester, c);+ expect(server.activityReadPosts, isNotEmpty);+ });+ });++ group('the one # buddy row (#2447) follows the same rules', () {+ Future<SuperTabController> show(+ WidgetTester tester,+ ConversationServer server,+ ) async {+ await tester.binding.setSurfaceSize(const Size(1280, 800));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final c = server.controller(account: 'peer');+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Kens-MacBook',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ return c;+ }++ final buddyRow = find.byKey(const ValueKey('super-swarm-buddy'));+ Text buddyName(WidgetTester tester) => tester.widget<Text>(+ find.descendant(of: buddyRow, matching: find.text('buddy')),+ );++ testWidgets('muted: greyed with its mark, never bold; first in the next '+ 'unread order', (tester) async {+ final server = oneBuddySwarm();+ giveSwarmBuddy(server);+ server.append('A word from Wren', conversationId: 'swarm-buddy-peer');+ final c = await show(tester, server);+ expect(superTabSidebarOrder(c).first, 'swarm-buddy-peer');+ expect(buddyName(tester).style?.fontWeight, grid.AppFont.semibold);+ await c.setNotify('swarm-buddy-peer', SuperTabNotify.muted);+ await tester.pumpAndSettle();+ expect(buddyName(tester).style?.color, DesktopChrome.muted);+ expect(buddyName(tester).style?.fontWeight, isNot(grid.AppFont.semibold));+ expect(+ find.byKey(const ValueKey('super-muted-swarm-buddy-peer')),+ findsOneWidget,+ );+ expect(+ c.unreadShown(c.snapshot!.conversation('swarm-buddy-peer')!),+ isFalse,+ );+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ });++ testWidgets('the unread filter keeps it only while it has something '+ 'unread', (tester) async {+ final server = oneBuddySwarm();+ giveSwarmBuddy(server);+ final c = await show(tester, server);+ expect(buddyRow, findsOneWidget);+ c.toggleUnreadOnly();+ await tester.pumpAndSettle();+ expect(buddyRow, findsNothing);+ server.append('A word from Wren', conversationId: 'swarm-buddy-peer');+ await c.refresh();+ await tester.pumpAndSettle();+ expect(buddyRow, findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ });+ });+}diff --git a/desktop/test/super_tab_attention_wave2_test.dart b/desktop/test/super_tab_attention_wave2_test.dartnew file mode 100644index 000000000..11aff35f2--- /dev/null+++ b/desktop/test/super_tab_attention_wave2_test.dart@@ -0,0 +1,391 @@+import 'dart:io';++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:flutter/services.dart';+import 'package:harness/super_tabs/activity.dart';+import 'package:harness/super_tabs/attention.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/model.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 wave 2 pictures there.+final shots = Platform.environment['SUPER_TAB_ATTENTION_SHOTS'];++final shotsOn = shots != null;++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;+}++Map<String, dynamic> _item(+ String id,+ String kind,+ String chat,+ String title,+ String text,+ String at, {+ String? emoji,+ bool read = false,+}) => {+ 'id': id,+ 'kind': kind,+ 'conversationId': chat,+ 'conversationTitle': title,+ 'projectName': 'openharness',+ 'messageId': 'message-1',+ 'messageSequence': 1,+ 'threadId': null,+ 'actor': {'kind': 'agent', 'id': 'lead-agent', 'name': 'Lead'},+ 'emoji': emoji,+ 'text': text,+ 'createdAt': at,+ 'read': read,+};++/// The attention Swarm with Activity rows, and Desktop roster muted.+ConversationServer _wave2() {+ final server = _swarm();+ server.state['activityDigest'] = 'd1';+ server.activity = {+ 'items': [+ _item(+ 'r1',+ 'reply',+ 'offline',+ 'Slack attention, wave 1',+ 'Fixed in 3f2a1c, ready again.',+ '2026-10-31T10:50:00.000Z',+ ),+ _item(+ 'x1',+ 'reaction',+ 'routing',+ 'Routing goals piece 5',+ 'Merged after the combined CI.',+ '2026-10-31T09:00:00.000Z',+ emoji: 'check',+ read: true,+ ),+ ],+ 'more': false,+ };+ _fromLead(server, 'Muted chatter.', 'roster');+ server.state['chatSettings'] = {+ 'owner': {'roster': 'muted'},+ };+ return server;+}++Future<(SuperTabController, GlobalKey)> _show(+ WidgetTester tester,+ Brightness brightness, {+ String selected = 'web-lead',+}) async {+ 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 = _wave2();+ final c = server.controller(+ initial: {'tabId': 'tab', 'accountId': 'owner', 'selectedId': selected},+ );+ await c.refresh();+ final attention = SuperTabAttention.of(c);+ await attention.mentions.load();+ await attention.decisions.load();+ await attention.load();+ await SuperTabActivity.of(c).load();+ await c.select(selected);+ 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();+ return (c, picture);+}++Future<void> _done(WidgetTester tester, SuperTabController c) async {+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+}++Future<void> _keys(+ WidgetTester tester,+ List<LogicalKeyboardKey> held,+ LogicalKeyboardKey key,+) async {+ for (final k in held) {+ await tester.sendKeyDownEvent(k);+ }+ await tester.sendKeyEvent(key);+ for (final k in held.reversed) {+ await tester.sendKeyUpEvent(k);+ }+ await tester.pumpAndSettle();+}++void main() {+ setUpAll(() => loadCaptureFonts(shots));++ group('in the real Swarm view', () {+ testWidgets(+ 'Option+Shift+Down opens the next unread chat in sidebar order, '+ 'skipping the muted one; Up goes back',+ (tester) async {+ final (c, _) = await _show(tester, Brightness.dark, selected: 'lead');+ // Sidebar order: openharness (lead, offline 1600, routing 1598, roster+ // 1597 muted), then website (web-lead).+ final order = [+ for (final id in ['lead', 'offline', 'routing', 'roster', 'web-lead'])+ if (c.unreadShown(c.snapshot!.conversation(id)!)) id,+ ];+ expect(order, isNot(contains('roster')));+ await tester.tap(find.byKey(const ValueKey('super-group-lead')));+ await tester.pumpAndSettle();+ await _keys(tester, [+ LogicalKeyboardKey.altLeft,+ LogicalKeyboardKey.shiftLeft,+ ], LogicalKeyboardKey.arrowDown);+ expect(c.selectedId, 'offline');+ await _keys(tester, [+ LogicalKeyboardKey.altLeft,+ LogicalKeyboardKey.shiftLeft,+ ], LogicalKeyboardKey.arrowDown);+ expect(c.selectedId, 'routing');+ await _keys(tester, [+ LogicalKeyboardKey.altLeft,+ LogicalKeyboardKey.shiftLeft,+ ], LogicalKeyboardKey.arrowDown);+ // The muted Desktop roster is passed over.+ expect(c.selectedId, 'web-lead');+ await _keys(tester, [+ LogicalKeyboardKey.altLeft,+ LogicalKeyboardKey.shiftLeft,+ ], LogicalKeyboardKey.arrowUp);+ expect(c.selectedId, 'routing');+ await _done(tester, c);+ },+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),+ );++ testWidgets('Shift+Esc marks every chat read with an Undo toast; Undo puts '+ 'them back', (tester) async {+ final (c, _) = await _show(tester, Brightness.dark);+ final unread = c.snapshot!.conversations.where(c.unreadShown).length;+ expect(unread, greaterThan(1));+ await tester.tap(find.byKey(const ValueKey('super-group-web-lead')));+ await tester.pumpAndSettle();+ await _keys(tester, [+ LogicalKeyboardKey.shiftLeft,+ ], LogicalKeyboardKey.escape);+ expect(c.snapshot!.conversations.where(c.unreadShown), isEmpty);+ expect(+ find.byKey(const ValueKey('super-mark-all-toast')),+ findsOneWidget,+ );+ await tester.tap(find.text('Undo'));+ await tester.pumpAndSettle();+ expect(c.snapshot!.conversations.where(c.unreadShown).length, unread);+ await _done(tester, c);+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));++ testWidgets(+ 'the chat menu\'s Notifications sets Muted, and the row greys',+ (tester) async {+ final (c, _) = await _show(+ tester,+ Brightness.dark,+ selected: 'offline',+ );+ await tester.tap(find.byKey(const ValueKey('super-group-options')));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-notify-menu')));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-notify-muted')));+ await tester.pumpAndSettle();+ expect(c.notifyOf('offline'), SuperTabNotify.muted);+ expect(+ find.byKey(const ValueKey('super-muted-offline')),+ findsOneWidget,+ );+ await _done(tester, c);+ },+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),+ );+ });++ for (final brightness in Brightness.values) {+ for (final scene in ['sidebar', 'activity', 'filter', 'menu', 'toast']) {+ testWidgets('wave 2: $scene in ${brightness.name}', (tester) async {+ if (!shotsOn) return;+ final (c, picture) = await _show(tester, brightness);+ switch (scene) {+ case 'activity':+ await tester.tap(find.byKey(const ValueKey('super-activity')));+ await tester.pumpAndSettle();+ case 'filter':+ await tester.tap(find.byKey(const ValueKey('super-unread-only')));+ await tester.pumpAndSettle();+ case 'menu':+ await tester.tap(find.byKey(const ValueKey('super-group-options')));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-notify-menu')));+ await tester.pumpAndSettle();+ case 'toast':+ await tester.tap(+ find.byKey(const ValueKey('super-group-web-lead')),+ );+ await tester.pumpAndSettle();+ await _keys(tester, [+ LogicalKeyboardKey.shiftLeft,+ ], LogicalKeyboardKey.escape);+ }+ if (scene == 'menu') {+ // The menu is a route of its own, outside the screen's boundary.+ await captureWindow(tester, shots, 'wave2-$scene-${brightness.name}');+ } else {+ await captureBoundary(+ tester,+ picture.currentContext!.findRenderObject()!+ as RenderRepaintBoundary,+ shots,+ 'wave2-$scene-${brightness.name}',+ );+ }+ await _done(tester, c);+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));+ }+ }+}diff --git a/desktop/test/super_tab_buddies_test.dart b/desktop/test/super_tab_buddies_test.dartindex 12d939bd0..ef1f5042c 100644--- a/desktop/test/super_tab_buddies_test.dart+++ b/desktop/test/super_tab_buddies_test.dart@@ -10,6 +10,7 @@ import 'package:harness/widgets/harness_activity_mark.dart';import 'package:harness/super_tabs/buddies.dart' show kBuddyEngineRefusals;import 'package:harness/super_tabs/buddy_machines.dart' show kBuddyNoMachine;import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/decisions_view.dart';import 'package:harness/super_tabs/view.dart';import 'support/buddy_fixture.dart';@@ -1494,10 +1495,16 @@ void main() {final server = buddySwarm();server.ask(['Ship it?']);final c = await show(tester, server);- await tester.tap(find.byKey(const ValueKey('super-notifications')));+ await tester.tap(find.byKey(const ValueKey('super-activity')));await tester.pumpAndSettle();- expect(find.text('Decisions'), findsOneWidget);+ expect(+ find.descendant(+ of: find.byType(SuperTabDecisionList),+ matching: find.text('Decisions'),+ ),+ findsOneWidget,+ );expect(find.text('Ship it?'), findsOneWidget);await close(tester, c);},@@ -1520,7 +1527,7 @@ void main() {'a tag from the old Chat with PM is placed in the project chat and opens it',(tester) async {final (_, c) = await withHistory(tester);- await tester.tap(find.byKey(const ValueKey('super-notifications')));+ await tester.tap(find.byKey(const ValueKey('super-activity')));await tester.pumpAndSettle();expect(find.textContaining('Chat with PM'), findsNothing);diff --git a/desktop/test/super_tab_buddy_chat_counts_test.dart b/desktop/test/super_tab_buddy_chat_counts_test.dartindex 9c954f7f7..9c904cdb2 100644--- a/desktop/test/super_tab_buddy_chat_counts_test.dart+++ b/desktop/test/super_tab_buddy_chat_counts_test.dart@@ -397,7 +397,7 @@ void main() {(tester) async {final c = await show(tester, riverSwarm());Future<void> shortcutOverNotifications() async {- await tester.tap(find.byKey(const ValueKey('super-notifications')));+ await tester.tap(find.byKey(const ValueKey('super-activity')));await tester.pumpAndSettle();expect(find.text('Message your Buddy'), findsNothing);// What ⇧⌘K runs (openActiveBuddyChat).@@ -439,7 +439,7 @@ void main() {tester,) async {final c = await show(tester, pmChatSwarm());- await tester.tap(find.byKey(const ValueKey('super-notifications')));+ await tester.tap(find.byKey(const ValueKey('super-activity')));await tester.pumpAndSettle();expect(find.text('Message your Buddy'), findsNothing);diff --git a/desktop/test/super_tab_decisions_test.dart b/desktop/test/super_tab_decisions_test.dartindex 1465fcbcb..a07621291 100644--- a/desktop/test/super_tab_decisions_test.dart+++ b/desktop/test/super_tab_decisions_test.dart@@ -7,6 +7,7 @@ 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/controller.dart';+import 'package:harness/super_tabs/decisions_view.dart';import 'package:harness/super_tabs/decisions.dart';import 'package:harness/super_tabs/model.dart';import 'package:harness/super_tabs/view.dart';@@ -91,8 +92,7 @@ Future<SuperTabController> showView(return c;}-Finder notificationsEntry() =>- find.byKey(const ValueKey('super-notifications'));+Finder notificationsEntry() => find.byKey(const ValueKey('super-activity'));Finder option(String id, int index) =>find.byKey(ValueKey('super-decision-$id-$index'));Finder letPmDecide(String id) =>@@ -241,7 +241,13 @@ void main() {);await tester.tap(notificationsEntry());await tester.pumpAndSettle();- expect(find.text('Decisions'), findsOneWidget);+ expect(+ find.descendant(+ of: find.byType(SuperTabDecisionList),+ matching: find.text('Decisions'),+ ),+ findsOneWidget,+ );expect(find.text('Wren asked 2 questions · web-project · Lead'),findsOneWidget,diff --git a/desktop/test/super_tab_mentions_test.dart b/desktop/test/super_tab_mentions_test.dartindex 4d844f21b..56c050f7a 100644--- a/desktop/test/super_tab_mentions_test.dart+++ b/desktop/test/super_tab_mentions_test.dart@@ -213,8 +213,7 @@ Future<void> showText(),);-Finder notificationsEntry() =>- find.byKey(const ValueKey('super-notifications'));+Finder notificationsEntry() => find.byKey(const ValueKey('super-activity'));void main() {setUpAll(() async {@@ -597,15 +596,14 @@ void main() {await tester.pumpAndSettle();final waiting = find.byKey(const ValueKey('super-mention-mention-2'));final earlier = find.byKey(const ValueKey('super-mention-mention-1'));- expect(find.text('Waiting'), findsOneWidget);- expect(find.text('Earlier'), findsOneWidget);+ // Activity is one list, newest first (Slack); the waiting tag is newer.expect(tester.getTopLeft(waiting).dy,lessThan(tester.getTopLeft(earlier).dy),);for (final text in ['web-project · Lead',- 'Wren',+ 'Wren tagged you','Ship it?','3 min ago',]) {@@ -676,7 +674,7 @@ void main() {);// The name they go by now, though they were tagged under another.expect(- find.descendant(of: row, matching: find.text('deedee')),+ find.descendant(of: row, matching: find.text('deedee tagged you')),findsOneWidget,);});@@ -693,7 +691,6 @@ void main() {await tester.tap(find.text('Mark done'));await tester.pumpAndSettle();expect(find.text('Mark done'), findsNothing);- expect(find.text('Nothing waiting for you.'), findsOneWidget);expect(find.byKey(const ValueKey('super-mention-mention-1')),findsOneWidget,@@ -768,7 +765,7 @@ void main() {find.text('This message is too far back to open.'),findsOneWidget,);- expect(find.text('Waiting'), findsOneWidget);+ expect(find.byKey(const ValueKey('super-activity-list')), findsOneWidget);expect(c.selectedId, isNot('group'));});@@ -951,7 +948,7 @@ void main() {find.byKey(const ValueKey('super-message-message-100')).hitTestable(),findsOneWidget,);- expect(find.text('Waiting'), findsNothing);+ expect(find.byKey(const ValueKey('super-activity-list')), findsNothing);});});diff --git a/desktop/test/super_tab_menu_bar_notices_test.dart b/desktop/test/super_tab_menu_bar_notices_test.dartindex 805bb6008..06e5bb74e 100644--- a/desktop/test/super_tab_menu_bar_notices_test.dart+++ b/desktop/test/super_tab_menu_bar_notices_test.dart@@ -8,6 +8,7 @@ import 'package:harness/notify/system_notifications.dart';import 'package:harness/state/status_menu.dart';import 'package:harness/super_tabs/controller.dart' show SuperTabFailure;import 'package:harness/super_tabs/decisions.dart';+import 'package:harness/super_tabs/activity_view.dart';import 'package:harness/super_tabs/notifications.dart';import 'package:harness/super_tabs/view.dart';@@ -363,7 +364,7 @@ void main() {await tester.pumpAndSettle();expect(c.selectedId, 'lead');expect(c.noticeRequest, isNull);- expect(find.byType(SuperTabNotifications), findsNothing);+ expect(find.byType(SuperTabActivityView), findsNothing);expect(find.text('Please confirm the release.'), findsWidgets);await close(tester, view);});@@ -375,7 +376,7 @@ void main() {final c = view.controller;c.openNotice('decision', 'decision-1');await tester.pumpAndSettle();- expect(find.byType(SuperTabNotifications), findsOneWidget);+ expect(find.byType(SuperTabActivityView), findsOneWidget);expect(find.text('Ship it behind a flag?'), findsOneWidget);expect(c.noticeRequest, isNull);await close(tester, view);diff --git a/desktop/test/super_tab_project_status_test.dart b/desktop/test/super_tab_project_status_test.dartindex 13470761f..827cbe735 100644--- a/desktop/test/super_tab_project_status_test.dart+++ b/desktop/test/super_tab_project_status_test.dart@@ -8,6 +8,7 @@ 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/controller.dart';+import 'package:harness/super_tabs/decisions_view.dart';import 'package:harness/super_tabs/model.dart';import 'package:harness/super_tabs/project_status_card.dart';import 'package:harness/super_tabs/view.dart';@@ -299,8 +300,15 @@ void main() {await tester.tap(answer('decision-1'));await tester.pumpAndSettle();- // The Notifications page, with the decision's own option buttons.- expect(find.text('Decisions'), findsOneWidget);+ // The Activity page (Notifications' place), with the decision's own+ // option buttons.+ expect(+ find.descendant(+ of: find.byType(SuperTabDecisionList),+ matching: find.text('Decisions'),+ ),+ findsOneWidget,+ );expect(find.byKey(const ValueKey('super-decision-decision-1-0')),findsOneWidget,diff --git a/desktop/test/super_tab_sidebar_cleanup_test.dart b/desktop/test/super_tab_sidebar_cleanup_test.dartindex 19c5fba6c..9677678f3 100644--- a/desktop/test/super_tab_sidebar_cleanup_test.dart+++ b/desktop/test/super_tab_sidebar_cleanup_test.dart@@ -78,36 +78,22 @@ Future<void> closeSwarm(WidgetTester tester, SuperTabController c) async {}void main() {- 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 '- 'count',- (tester) async {+ // Slack's Activity takes Notifications' place on every platform, above+ // Threads (Lead, 10-31): on a Mac too, beside the menu bar and the Dock.+ for (final platform in [TargetPlatform.macOS, TargetPlatform.linux]) {+ testWidgets('the top reads New project, Your devices, Your models, '+ 'Activity with its count, Threads', (tester) async {final c = await showSwarm(tester);expect(topRows(tester), ['New project','Your devices','Your models',+ 'Activity3','Threads',- 'Notifications3',]);+ expect(find.text('Notifications'), findsNothing);+ expect(tester.takeException(), isNull);await closeSwarm(tester, c);- },- variant: TargetPlatformVariant.only(TargetPlatform.linux),- );+ }, variant: TargetPlatformVariant.only(platform));+ }}diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex 04176b08b..b91a5873f 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -87,6 +87,8 @@ class SwarmPartsBackend {'githubApp','readMarks','threadMarks',+ 'chatSettings',+ 'activityDigest','teamAccounts','threadSessions','sessionsFromChat',@@ -177,6 +179,13 @@ class SwarmPartsBackend {// The reader's own read marks alone, as backend readMarks.ts sends them.if ((state['readMarks'] as Map?)?[reader ?? 'owner'] case final Map marks)'readMarks': Map<String, dynamic>.from(marks),+ // Their own Activity digest and chat settings (backend activity.ts,+ // chatSettings.ts): every setting on every read, which the app keeps.+ if (state['activityDigest'] != null)+ 'activityDigest': state['activityDigest'],+ if ((state['chatSettings'] as Map?)?[reader ?? 'owner'] case final Map set+ when set.isNotEmpty)+ 'chatSettings': Map<String, dynamic>.from(set),// Their own thread marks alone, by conversation, absent when none.if ((state['threadMarks'] as Map?)?[reader ?? 'owner'] case final Map markswhen marks.isNotEmpty)@@ -475,6 +484,21 @@ class ConversationServer {final commandResult = <String, dynamic>{};final posts = <Map<String, dynamic>>[];+ /// Notification settings sent (backend chatSettings.ts), in order; while+ /// [failNotify], each is refused as if offline; [holdNotify] keeps each+ /// waiting.+ final notifyPosts = <Map<String, dynamic>>[];+ bool failNotify = false;+ Completer<void>? holdNotify;++ /// The Activity list answered (backend activity.ts); null answers 404, as a+ /// server before it. [activityStatus], when not 0, fails each read with it.+ Map<String, dynamic>? activity = {'items': <dynamic>[], 'more': false};+ int activityStatus = 0;+ Completer<void>? holdActivity;+ final activityReads = <String>[];+ final activityReadPosts = <Map<String, dynamic>>[];+/// Refuses the next lead.start with this code and message, as the backend/// refuses a machine that cannot take the Product Manager (leadStart.ts).Map<String, String>? leadRefusal;@@ -939,6 +963,29 @@ class ConversationServer {? RegExp(r'/conversations/([^/]+)/threads/([^/]+)/follow$').firstMatch(path): null;+ final notify = method == 'POST'+ ? RegExp(r'/conversations/([^/]+)/notifications$').firstMatch(path)+ : null;+ if (notify != null) {+ final id = Uri.decodeComponent(notify.group(1)!);+ notifyPosts.add({'conversationId': id, 'notify': body!['notify']});+ if (holdNotify case final hold?) await hold.future;+ if (failNotify) {+ throw const SuperTabFailure(+ 'OFFLINE',+ 'No connection.',+ statusCode: 503,+ );+ }+ final settings = (state['chatSettings'] ??= <String, dynamic>{}) as Map;+ ((settings[reader ?? 'owner'] ??= <String, dynamic>{}) as Map)[id] =+ body['notify'];+ return {'notify': body['notify']};+ }+ if (method == 'POST' && path.endsWith('/activity/read')) {+ activityReadPosts.add(Map<String, dynamic>.from(body!));+ return {'marked': 1};+ }if (follow != null) {followPosts.add({'conversationId': Uri.decodeComponent(follow.group(1)!),@@ -1470,6 +1517,24 @@ class ConversationServer {}return jsonDecode(jsonEncode(answer)) as Map<String, dynamic>;}+ if (uri.pathSegments.last == 'activity') {+ activityReads.add(path);+ // Worked out when asked, as a server does: a slow answer is the one+ // it had then.+ final asked = activity;+ if (holdActivity case final hold?) await hold.future;+ if (activityStatus != 0) {+ throw SuperTabFailure(+ 'OFFLINE',+ 'No connection.',+ statusCode: activityStatus,+ );+ }+ if (asked == null) {+ throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);+ }+ return jsonDecode(jsonEncode(asked)) as Map<String, dynamic>;+ }if (uri.pathSegments.last == 'mentions') {mentionReads++;if (mentionsMissing) {diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dartindex 8141ecb10..8a24800ae 100644--- a/mobile/lib/swarm/model.dart+++ b/mobile/lib/swarm/model.dart@@ -528,6 +528,12 @@ class SuperTabSnapshot {mentionsDigest = row['mentionsDigest'] as String?,decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0,decisionsDigest = row['decisionsDigest'] as String?,+ activityDigest = row['activityDigest'] as String?,+ chatSettings = Map.unmodifiable({+ if (row['chatSettings'] case final Map settings)+ for (final MapEntry(:key, :value) in settings.entries)+ if (key is String && value is String) key: value,+ }),teamAccounts = row['teamAccounts'] != false,readMarks = Map.unmodifiable({if (row['readMarks'] case final Map marks)@@ -625,6 +631,14 @@ class SuperTabSnapshot {/// count may not; null from a backend before it (superTabs/decisions.ts).final String? decisionsDigest;+ /// Which of the reader's Activity rows are unread, as a digest (backend superTabs/activity.ts); null from a backend+ /// before it. Read as the desktop's model reads it; the phone shows no Activity yet.+ final String? activityDigest;++ /// The reader's own notification setting by conversation, `all`, `mentions` or `muted` (backend chatSettings.ts).+ /// Read as the desktop's model reads it; the phone does not apply it yet.+ final Map<String, String> chatSettings;+/// False only where the server does not try Harness Team accounts yet/// (backend read/contract.ts `teamAccounts`), as on the desktop.final bool teamAccounts;diff --git a/mobile/lib/swarm/parts.dart b/mobile/lib/swarm/parts.dartindex e3737700d..85b325878 100644--- a/mobile/lib/swarm/parts.dart+++ b/mobile/lib/swarm/parts.dart@@ -61,6 +61,7 @@ class SuperTabParts {final derived = Map.of(superTabMap(answer['derived'] ?? const {}));final marks = derived.remove('readMarks');final threadMarks = derived.remove('threadMarks');+ final chatSettings = derived.remove('chatSettings');final parts = SuperTabParts._(_envelope(answer['head'], live: true),derived,@@ -81,6 +82,7 @@ class SuperTabParts {}parts._takeReadMarks(marks);parts._takeThreadMarks(threadMarks);+ parts._takeChatSettings(chatSettings);return parts;}@@ -104,6 +106,7 @@ class SuperTabParts {}parts._takeReadMarks(json['readMarks']);parts._takeThreadMarks(json['threadMarks']);+ parts._takeChatSettings(json['chatSettings']);return parts;}@@ -169,6 +172,25 @@ class SuperTabParts {return moved;}+ /// The reader's own notification setting by conversation (backend chatSettings.ts): `all`, `mentions` or `muted`.+ /// A first load sends every one, a change read those moved since its cursor; the newest wins, and a setting goes+ /// with its conversation.+ final _chatSettings = <String, String>{};++ /// Keeps each setting in [settings] the server knows; whether any moved.+ bool _takeChatSettings(Object? settings) {+ var moved = false;+ if (settings is! Map) return moved;+ for (final MapEntry(:key, :value) in settings.entries) {+ if (key is! String || value is! String) continue;+ if (!const {'all', 'mentions', 'muted'}.contains(value)) continue;+ if (_chatSettings[key] == value) continue;+ _chatSettings[key] = value;+ moved = true;+ }+ return moved;+ }+/// Dormant groups held with their data from before a stub closed them: a read by id at the stub's version is/// their current data.final _stale = <String>{};@@ -224,6 +246,7 @@ class SuperTabParts {_stale.remove(key);_readMarks.remove(key);_threadMarks.remove(key);+ _chatSettings.remove(key);removed.add(key);}} else if (kind == 'groups' && part['dormant'] == true) {@@ -254,7 +277,9 @@ class SuperTabParts {final readMarksMoved = _takeReadMarks(derived.remove('readMarks'));// Both run: one moving never skips the other.final marksMoved =- _takeThreadMarks(derived.remove('threadMarks')) | readMarksMoved;+ _takeThreadMarks(derived.remove('threadMarks')) |+ _takeChatSettings(derived.remove('chatSettings')) |+ readMarksMoved;if (!const DeepCollectionEquality().equals(derived, _derived)) {_derived = derived;changed = true;@@ -344,6 +369,9 @@ class SuperTabParts {if (_derived['decisionsDigest'] case final String digest) {state['decisionsDigest'] = digest;}+ if (_derived['activityDigest'] case final String digest) {+ state['activityDigest'] = digest;+ }// Sent only where the server does not try Harness Team accounts yet.if (_derived['teamAccounts'] == false) state['teamAccounts'] = false;// Sent by a server that takes a thread reply's New session.@@ -353,6 +381,9 @@ class SuperTabParts {// And one that gives each person one Buddy for the whole Swarm.if (_derived['swarmBuddy'] == true) state['swarmBuddy'] = true;if (_readMarks.isNotEmpty) state['readMarks'] = Map.of(_readMarks);+ if (_chatSettings.isNotEmpty) {+ state['chatSettings'] = Map.of(_chatSettings);+ }if (_threadMarks.isNotEmpty) {state['threadMarks'] = {for (final MapEntry(:key, :value) in _threadMarks.entries)@@ -379,6 +410,7 @@ class SuperTabParts {'seen': Map<String, int>.of(_seen),'stale': _stale.toList(),'readMarks': Map<String, int>.of(_readMarks),+ 'chatSettings': Map<String, String>.of(_chatSettings),'threadMarks': {for (final MapEntry(:key, :value) in _threadMarks.entries)key: Map<String, int>.of(value),