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
Batch Z: New messages line and server read marks (#2131), Codex skips its update screen (#2111) (#2144)
0xken15ed1864e0b94f
diff --git a/backend/integration/superTabReadMarks.test.ts b/backend/integration/superTabReadMarks.test.tsnew file mode 100644index 000000000..00c827d5d--- /dev/null+++ b/backend/integration/superTabReadMarks.test.ts@@ -0,0 +1,162 @@+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, 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 * as parts from '../src/superTabs/parts/index.js'+import { swarmTransaction } from '../src/superTabs/cache.js'+import { guardedWrite } from '../src/superTabs/parts/write.js'+import { SwarmReads } from '../src/superTabs/read/service.js'+import { HostReads } from '../src/superTabs/read/host.js'+import type { Conversation, 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 clock = NOW+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 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_read_marks_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' } })+ const store = new SuperTabStore(db, () => clock)+ 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 = [owner, peer, outsider].find(u => `Bearer ${u.sub}` === 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, { now: () => clock }),+ hosts: new HostReads(store, { now: () => clock }) })+ await app.ready()+})+afterAll(async () => {+ await app?.close()+ await db?.$disconnect()+ await replica?.stop()+})++/** A Swarm in parts: a public conversation with 100 messages, and a private project's conversation only its owner reads. */+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 web = s.group('Web')+ const secretGroup = s.group('Secret work', secret)+ s.edit(state => {+ state.conversations.find(c => c.id === web)!.lastMessageSequence = 100+ state.conversations.find(c => c.id === secretGroup)!.lastMessageSequence = 50+ })+ const tabId = `tab-${randomUUID()}`+ await writeLegacySwarm(db, { state: { ...structuredClone(s.state), id: tabId } as SuperTabState, revision: 3 })+ const report = await migrateSwarm(db, tabId, { now: () => MIGRATED })+ if (!report.ok) throw new Error(report.error)+ return { tabId, web, secretGroup }+}++const call = async (method: 'GET' | 'POST', url: string, as: AuthUser, payload?: unknown) => {+ const response = await app.inject({ method, url, headers: { authorization: `Bearer ${as.sub}` }, ...(payload ? { payload } : {}) })+ return { status: response.statusCode, body: response.json() as { data: any; error?: { code: string } } }+}+const mark = (tabId: string, conversationId: string, sequence: number, as: AuthUser = owner, query = '') =>+ call('POST', `/api/super-tabs/${tabId}/conversations/${conversationId}/read${query}`, as, { sequence })+const firstLoad = async (tabId: string, as: AuthUser) => (await call('GET', `/api/super-tabs/${tabId}/parts`, as)).body.data+const marksOf = async (tabId: string, as: AuthUser) => (await firstLoad(tabId, as)).derived.readMarks as Record<string, number> | undefined++describe('read marks (one per person and conversation)', () => {+ it('keeps the person\'s mark and gives it back in their own read only', async () => {+ const s = await scene()+ expect(await mark(s.tabId, s.web, 40)).toMatchObject({ status: 200, body: { data: { sequence: 40 } } })+ expect(await marksOf(s.tabId, owner)).toEqual({ [s.web]: 40 })+ // Another reader of the same conversation never sees it: no read receipts.+ expect(await marksOf(s.tabId, peer)).toEqual({})+ await mark(s.tabId, s.web, 70, peer)+ expect(await marksOf(s.tabId, peer)).toEqual({ [s.web]: 70 })+ expect(await marksOf(s.tabId, owner)).toEqual({ [s.web]: 40 })+ })++ it('never moves a mark back, whichever device writes last', async () => {+ const s = await scene()+ await mark(s.tabId, s.web, 60)+ expect((await mark(s.tabId, s.web, 20)).body.data).toEqual({ sequence: 60 })+ expect(await marksOf(s.tabId, owner)).toEqual({ [s.web]: 60 })+ // Devices racing on a conversation read for the first time: the highest wins and one row is kept.+ const other = await scene()+ await Promise.all([30, 90, 45, 10, 80].map(n => mark(other.tabId, other.web, n)))+ expect(await marksOf(other.tabId, owner)).toEqual({ [other.web]: 90 })+ expect(await db.superTabReadMark.count({ where: { tabId: other.tabId } })).toBe(1)+ })++ it('stops at the conversation\'s newest message', async () => {+ const s = await scene()+ expect((await mark(s.tabId, s.web, 5_000)).body.data).toEqual({ sequence: 100 })+ })++ it('refuses a conversation the person cannot read, and stores nothing', async () => {+ const s = await scene()+ expect((await mark(s.tabId, s.secretGroup, 10, outsider)).status).toBe(404)+ expect((await mark(s.tabId, 'no-such-group', 10, outsider)).status).toBe(404)+ expect(await db.superTabReadMark.count({ where: { tabId: s.tabId } })).toBe(0)+ })++ it('stops sending a mark once the person can no longer read its conversation', async () => {+ const s = await scene()+ await mark(s.tabId, s.web, 30, peer)+ expect(await marksOf(s.tabId, peer)).toEqual({ [s.web]: 30 })+ // The conversation becomes the owner's alone, as a private chat is (read/views.ts canReadGroup).+ await swarmTransaction(db, async tx => {+ const current = (await parts.loadActive(tx, s.tabId, { groupIds: [s.web] })).groups.find(g => g.key === s.web)!+ const data = { ...structuredClone(current.data!), audience: { people: [{ id: owner.sub, generation: 0 }] } } as Conversation+ await guardedWrite(tx, s.tabId, { op: 'update', kind: 'group', key: s.web, seen: current.version, data }, clock)+ })+ expect(await marksOf(s.tabId, peer)).toEqual({})+ expect((await mark(s.tabId, s.web, 40, peer)).status).toBe(404)+ })++ it('keeps no marks for agents', async () => {+ const s = await scene()+ expect((await mark(s.tabId, s.web, 10, owner, '?asAgentId=some-agent')).status).toBe(400)+ expect(await db.superTabReadMark.count({ where: { tabId: s.tabId } })).toBe(0)+ })++ it('sends a later read only the marks that moved since its cursor', async () => {+ const s = await scene()+ clock = NOW+ await mark(s.tabId, s.secretGroup, 10)+ // The cursor overlaps the last 30 s (read/cursor.ts), so a mark is old news to a read a minute later.+ clock = NOW + 60_000+ const cursor = (await firstLoad(s.tabId, owner)).cursor as string+ const changes = async (at: number) => {+ clock = at+ return (await call('GET', `/api/super-tabs/${s.tabId}/changes?cursor=${cursor}`, owner)).body.data.derived.readMarks+ }+ expect(await changes(NOW + 61_000)).toEqual({})+ clock = NOW + 62_000+ await mark(s.tabId, s.web, 25)+ expect(await changes(NOW + 63_000)).toEqual({ [s.web]: 25 })+ clock = NOW+ })+})diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 6dae9bdc8..164809458 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1134,6 +1134,22 @@ model SuperTabReaction {@@index([tabId, messageId])}+/// 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.+model SuperTabReadMark {+ id String @id @map("_id")+ tabId String+ personId String+ conversationId String+ sequence Int+ updatedAt DateTime++ @@index([tabId, personId, updatedAt])+ /// A mark untouched this long goes (superTabs/readMarks.ts ensureReadMarkExpiry). Declared so db push keeps the index.+ @@index([updatedAt], map: "read_mark_expiry")+}+/// A question to one person, with options and a recommendation (backend/src/superTabs/decisions.ts). Kept out of the tab/// state, as mentions are: an asking agent and the asked person read it, and the person answers it once.model SuperTabDecision {diff --git a/backend/src/lib/db/schemaRelease.ts b/backend/src/lib/db/schemaRelease.tsindex e89554612..0a6820a6e 100644--- a/backend/src/lib/db/schemaRelease.ts+++ b/backend/src/lib/db/schemaRelease.ts@@ -4,6 +4,7 @@ import { ensureProductUsageExpiry } from '../productUsage.js'import { ensureHarnessSessionExpiry } from '../ssoSession.js'import { ensureTerminalExpiry } from '../../superTabs/terminal.js'import { ensureMentionExpiry } from '../../superTabs/mentions.js'+import { ensureReadMarkExpiry } from '../../superTabs/readMarks.js'import { ensurePartExpiry } from '../../superTabs/sweeps.js'import { ensureSchema, type SchemaTarget } from './migrate.js'@@ -15,5 +16,6 @@ export async function releaseSchema(db: PrismaClient = prisma, target: SchemaTarawait ensureHarnessSessionExpiry(db)await ensureTerminalExpiry(db)await ensureMentionExpiry(db)+ await ensureReadMarkExpiry(db)await ensurePartExpiry(db)}diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 82a3c6de1..f7a2a0e4f 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -62,6 +62,9 @@ const hostChangesBody = z.object({ cursor: cursor.optional(), full: z.boolean().const startParams = tabParams.extend({ startId: id })const nativeParams = tabParams.extend({ contextId: id })const messageParams = tabParams.extend({ conversationId: id })+// A person's own read mark (superTabs/readMarks.ts): no asAgentId, since agents keep none.+const readMarkBody = z.object({ sequence: z.number().int().nonnegative().safe() }).strict()+const noQuery = z.object({}).strict()// Pages by (sequence, id) (design 4.6): `afterId`/`beforeId` go with `after`/`before`, from the previous page's `next`.const messageQuery = agentQuery.extend({ after: z.coerce.number().int().nonnegative().safe().optional(),before: z.coerce.number().int().nonnegative().safe().optional(), messageId: id.optional(), afterId: id.optional(), beforeId: id.optional(),@@ -449,6 +452,9 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suapp.get<{ Params: z.infer<typeof messageParams>; Querystring: z.infer<typeof messageQuery> }>('/api/super-tabs/:tabId/conversations/:conversationId/messages',{ preHandler: [validateParams(messageParams), validateQuery(messageQuery)] },(req, reply) => respond(reply, () => store.messages(req.user!, req.params.tabId, req.params.conversationId, req.query, req.query.asAgentId)))+ app.post<{ Params: z.infer<typeof messageParams>; Querystring: z.infer<typeof noQuery>; Body: z.infer<typeof readMarkBody> }>('/api/super-tabs/:tabId/conversations/:conversationId/read',+ { preHandler: [validateParams(messageParams), validateQuery(noQuery), validateBody(readMarkBody)] },+ (req, reply) => respond(reply, () => reads.markRead(req.user!, req.params.tabId, req.params.conversationId, req.body.sequence)))app.get<{ Params: z.infer<typeof messageParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/conversations/:conversationId/attempts',{ preHandler: [validateParams(messageParams), validateQuery(agentQuery)] },(req, reply) => respond(reply, () => store.attempts(req.user!, req.params.tabId, req.params.conversationId, req.query.asAgentId)))diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.tsindex 69bde8160..0d3316796 100644--- a/backend/src/superTabs/read/contract.ts+++ b/backend/src/superTabs/read/contract.ts@@ -72,6 +72,10 @@ 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: 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. */+ readMarks?: Record<string, number>/** 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 b256174a0..546e1fdba 100644--- a/backend/src/superTabs/read/service.ts+++ b/backend/src/superTabs/read/service.ts@@ -8,6 +8,7 @@ import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../..import { author, fail, isLeads, seenMachineIds, visibleState, type Actor, type AgentStart, type SuperTabState } from '../model.js'import { waitingMentions } from '../mentions.js'import { decisionsWaiting } from '../decisions.js'+import { readMarks, writeReadMark } from '../readMarks.js'import type { SuperTabStore } from '../store.js'import { transaction } from '../store.js'import type { CacheView } from '../cache.js'@@ -36,6 +37,16 @@ interface Read { parts: SwarmParts; actor: Actor; view: ReaderView; lastChangedAconst MACHINE_READS_MS = 15_000type MachineReads = [teamMachines: string[], otherWorkspaceMachines: string[]]+/** The reader's marks of the conversations they can read now, a dormant one read by id included: a mark never names a+ * conversation the reader has lost. Only in a person's read; nothing for an agent. */+function readableMarks(read: Read, marks: Map<string, number>): Pick<Derived, 'readMarks'> {+ if (read.actor.kind !== 'person') return {}+ const shown = new Set(read.view.parts.groups.map(g => g.key))+ const readable = (id: string) => shown.has(id)+ || read.parts.groups.some(g => g.key === id && g.dormant && canReadGroup(read.view.state, read.actor, g.data!))+ return { readMarks: Object.fromEntries([...marks].filter(([id]) => readable(id))) }+}+export class SwarmReads {private readonly db: PrismaClientprivate readonly now: () => number@@ -52,9 +63,11 @@ export class SwarmReads {async firstLoad(user: AuthUser, tabId: string, asAgentId?: string): Promise<FirstLoad> {const t0 = this.now()return this.read(user, tabId, async (tx, cached) => {- const { parts: loaded, view, lastChangedAt } = await this.load(tx, cached, user, tabId, asAgentId, t0, { includeRecentStarts: true })+ const read = await this.load(tx, cached, user, tabId, asAgentId, t0, { includeRecentStarts: true })+ const { parts: loaded, view, lastChangedAt } = readreturn { 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) }+ ...(this.options.githubApp ? { githubApp: true as const } : {}), ...view.parts,+ derived: { ...await this.withAvatars(view, t0), ...readableMarks(read, await this.marksOf(tx, tabId, read.actor)) } }})}@@ -82,10 +95,14 @@ export class SwarmReads {const changed = await readChanged(tx, cached, tabId, from.since)// A changed start whose group went dormant is read against that group, so its readers alone learn of it.const held = new Set(read.parts.groups.map(g => g.key))- const dormant = [...new Set(changed.flatMap(p => p.kind === 'start' ? [(p.data as AgentStart).request.conversationId] : []))].filter(id => !held.has(id))- if (dormant.length) read = await this.load(tx, cached, user, tabId, asAgentId, t0, { ...light, groupIds: [...mentioned, ...dormant] }, lightly)+ // So is a conversation whose read mark moved, so the mark goes only to a reader who can still read it.+ const marks = await this.marksOf(tx, tabId, read.actor, from.since)+ const unheld = [...new Set([...changed.flatMap(p => p.kind === 'start' ? [(p.data as AgentStart).request.conversationId] : []), ...marks.keys()])]+ .filter(id => !held.has(id))+ if (unheld.length) read = await this.load(tx, cached, user, tabId, asAgentId, t0, { ...light, groupIds: [...mentioned, ...unheld] }, lightly)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) }+ epoch: read.parts.visibilityEpoch, ...changesFor(read.view, changed, read.actor),+ derived: { ...await this.withAvatars(read.view, t0), ...readableMarks(read, marks) } }})}@@ -118,6 +135,20 @@ export class SwarmReads {})}+ /** Moves the person's read mark in a conversation they can read forward, never past its newest message (readMarks.ts). Only a+ * person reading as themselves has marks: an agent, or a Team session, is refused before anything is written. */+ async markRead(user: AuthUser, tabId: string, conversationId: string, sequence: number): Promise<{ sequence: number }> {+ if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)+ const { group } = await this.group(user, tabId, conversationId)+ const newest = group.data!.lastMessageSequence+ return { sequence: await writeReadMark(this.db, { tabId, personId: user.sub, conversationId, sequence: Math.min(sequence, newest), now: this.now() }) }+ }++ /** A person's own read marks (an agent has none), every one or those moved since `since`. */+ private async marksOf(tx: PrismaClient, tabId: string, actor: Actor, since?: number): Promise<Map<string, number>> {+ return actor.kind === 'person' ? readMarks(tx, tabId, actor.userId, since) : new Map()+ }+/** One project's leaderboard for a week (leaderboard/stats.ts), for the people who read the project. It sums only the* groups the reader may read, dormant ones of the kept weeks included, and never a private conversation. */async leaderboard(user: AuthUser, tabId: string, projectId: string, week?: number): Promise<Leaderboard> {diff --git a/backend/src/superTabs/readMarks.ts b/backend/src/superTabs/readMarks.tsnew file mode 100644index 000000000..ccbf478dc--- /dev/null+++ b/backend/src/superTabs/readMarks.ts@@ -0,0 +1,47 @@+/** How far each person has read each conversation: the newest message sequence they saw there, so unread state follows them+ * across devices. Marks live in SuperTabReadMark, 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 marks go only to their own reads (read/service.ts); agents have+ * none. */+import { Prisma, type PrismaClient } from '@prisma/client'+import { ensureIndex } from '../lib/db/indexes.js'+import { fail, stableId } from './model.js'++/** A mark untouched this long is removed by a TTL index; the conversation then reads as the device last saw it. */+export const READ_MARK_EXPIRY_MS = 180 * 24 * 60 * 60_000++/** Run by the singleton worker at startup, like the mention expiry. */+export async function ensureReadMarkExpiry(db: PrismaClient): Promise<void> {+ await ensureIndex(db, 'SuperTabReadMark', { key: { updatedAt: 1 }, name: 'read_mark_expiry', expireAfterSeconds: READ_MARK_EXPIRY_MS / 1000 })+}++export interface ReadMarkWrite { tabId: string; personId: string; conversationId: string; sequence: number; now: number }++/** Moves the person's mark forward to `sequence` and answers the mark as stored. An older mark never replaces a newer one:+ * the update matches only a lower mark. When another device's write lands between the update and the look after it (two+ * first writes racing to create the row, or one raising it), the update runs again; every retry follows a write that+ * raised the mark, so a few settle it. */+export async function writeReadMark(db: PrismaClient, mark: ReadMarkWrite): Promise<number> {+ const { tabId, personId, conversationId, sequence } = mark+ const id = stableId(tabId, conversationId, personId), updatedAt = new Date(mark.now)+ for (let attempt = 0; attempt < 4; attempt++) {+ const moved = await db.superTabReadMark.updateMany({ where: { id, sequence: { lt: sequence } }, data: { sequence, updatedAt } })+ if (moved.count) return sequence+ const held = await db.superTabReadMark.findUnique({ where: { id }, select: { sequence: true } })+ if (held && held.sequence >= sequence) return held.sequence+ if (held) continue+ try {+ await db.superTabReadMark.create({ data: { id, tabId, personId, conversationId, sequence, updatedAt } })+ return sequence+ } catch (error) {+ if (!(error instanceof Prisma.PrismaClientKnownRequestError) || error.code !== 'P2002') throw error+ }+ }+ return fail('READ_MARK_BUSY', 'This conversation is being marked read on another device. Try again.', 503)+}++/** The person's marks in this tab, by conversation; with `since`, only those moved at or after it. */+export async function readMarks(db: PrismaClient, tabId: string, personId: string, since?: number): Promise<Map<string, number>> {+ const rows = await db.superTabReadMark.findMany({ where: { tabId, personId, ...(since === undefined ? {} : { updatedAt: { gte: new Date(since) } }) },+ select: { conversationId: true, sequence: true } })+ return new Map(rows.map(row => [row.conversationId, row.sequence]))+}diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex 20ea33c1c..3b8c72beb 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/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts', 'integration/superTabTidy.test.ts',+ 'integration/superTabRead.test.ts', 'integration/superTabReadMarks.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/superTabHotReads.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts', 'integration/superTabCosts.test.ts','integration/harnessSharesList.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts'],diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex c094fee54..115f510ff 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -183,6 +183,17 @@ describe('creating an agent', () => {}})+ // Codex's "Update available" screen held a Swarm agent's task with no one at its terminal (Studio Codex, 2026-10-29).+ it('starts a Swarm Codex without its startup update check, and every other Codex and Swarm engine as it was', async () => {+ const extraArgsOf = async (over: Record<string, unknown>) => {+ await setup().create(request({ cwd: folder(), ...over }))+ return (vi.mocked(buildEngineLaunchArgv).mock.calls.at(-1)![1] as { extraArgs?: string[] }).extraArgs ?? []+ }+ for (const role of ['lead', 'dev'] as const) expect(await extraArgsOf({ engine: 'codex', swarmRole: role })).toEqual(expect.arrayContaining(['-c', 'check_for_update_on_startup=false']))+ expect(await extraArgsOf({ engine: 'codex' })).not.toContain('check_for_update_on_startup=false')+ expect(await extraArgsOf({ engine: 'claude', swarmRole: 'dev' })).not.toContain('check_for_update_on_startup=false')+ })+it.each(['default', 'orchestration'] as const)('writes the %s skill text and its prompt line for the project\'s mode', async mode => {const cwd = folder()await setup().create(request({ cwd, swarmRole: 'dev', swarmSkillMode: mode }))diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex 31eeda5f4..decf2d90e 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -376,7 +376,7 @@ export function createAgentCreator({// as every relaunch reads them again (`buildLaunchOverrides`). Never a Buddy's: it starts no MCP server, as a server// runs with its person's credentials and its tools are not its guard's to vet (review 3 of #2092).const machineMcp = input.swarmRole === 'buddy' ? [] : machineMcpLaunchArgs(engine, cwd)- const extraArgs = joinedInstructions(engine, [...(gridLaunch?.args ?? relay?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, native ? native.opencodeMajor : opencode ? await opencode.opencodeMajorVersion() : null) : []), ...machineMcp, ...told])+ const extraArgs = joinedInstructions(engine, [...(gridLaunch?.args ?? relay?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, native ? native.opencodeMajor : opencode ? await opencode.opencodeMajorVersion() : null) : []), ...machineMcp, ...(swarmLaunch && swarmSkill ? swarmLaunch.args(engine) : []), ...told])// The first prompt is a launch option only — never part of `extraArgs`, which the registry row// carries into a relaunch (engineLaunch.ts, `firstPrompt`).const firstPrompt = promptdiff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.tsindex 679445da0..b977bd583 100644--- a/cli/src/core/api.spec.ts+++ b/cli/src/core/api.spec.ts@@ -150,7 +150,7 @@ describe('the core API services stand on', () => {expect(createCoreApi({ ...deps, cloud }).cloud).toBe(cloud)// The Super Tab service's door, the same way.expect(core.superTabs).toBeUndefined()- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn(), inputIfScreen: vi.fn() }expect(createCoreApi({ ...deps, superTabs }).superTabs).toBe(superTabs)// The devices' way to its card requests, the same way.expect(core.superTabRequest).toBeUndefined()diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 60068d9c0..7b7b26686 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -1209,6 +1209,8 @@ export interface SwarmLaunch {mode(value: unknown): value is NonNullable<SwarmSkill['mode']>prepare(cwd: string, skill: SwarmSkill): { instructions: string }github(key: string): { env: Record<string, string>; clearEnv: string[] } | null+ /** The engine's arguments for a session the Swarm starts, never for a person's own (lib/swarmEngineArgs.ts). */+ args(engine: string): string[]}/** Fill a missing Swarm role of an older Swarm session at its restart or resume (superTabs/inCore/adoption.ts): the row@@ -1252,6 +1254,9 @@ export interface SuperTabsCore {screen(agentId: string, scrollback: number): Promise<SuperTabScreen>/** Text, then each key by its tmux name, typed into a member's terminal under the pane's write lock. */input(agentId: string, text: string, keys: string[]): Promise<SuperTabTyped>+ /** The same keys, sent only if the visible screen, read again under the pane's write lock, is exactly `screen` (superTabs/inCore/+ * terminal.ts): for a caller that read the screen earlier and must not type into a different one. */+ inputIfScreen(agentId: string, keys: string[], screen: string): Promise<SuperTabTyped>}export type SuperTabScreen = { ok: true; text: string; hold: MessageHold | null } | { ok: false; error: string }export type SuperTabTyped = { ok: true } | { ok: false; error: string }diff --git a/cli/src/core/experimentQueries.spec.ts b/cli/src/core/experimentQueries.spec.tsindex 71162d694..fd816501f 100644--- a/cli/src/core/experimentQueries.spec.ts+++ b/cli/src/core/experimentQueries.spec.ts@@ -28,7 +28,7 @@ describe('the cloud agents\' doors', () => {describe('the Super Tab service\'s door', () => {it('is the Super Tab service\'s alone, and hands its members\' waits to the core whole', async () => {- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn(), inputIfScreen: vi.fn() }const core = fakeCore({ superTabs })const both = new Set(['orchestrator', 'superTabs'])const item = { agentId: 'a1', requestId: 'supertab:x:blocked', superTab: 'Pilot', attention: 'stuck', text: 'Stuck: no key' }@@ -41,7 +41,7 @@ describe('the Super Tab service\'s door', () => {})it('hands it the Swarm cards and a Lead\'s recap the same way, to the Super Tab service alone', async () => {- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn(), inputIfScreen: vi.fn() }const core = fakeCore({ superTabs })const both = new Set(['orchestrator', 'superTabs'])const recap = { tabId: 't1', leadId: 'l1', text: 'Shipped', at: 1, none: false }@@ -58,13 +58,13 @@ describe('the Super Tab service\'s door', () => {})it('asks for Share when a Swarm host here has members to show its agents to', async () => {- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn(), inputIfScreen: vi.fn() }expect(await answerExperimentQuery(fakeCore({ superTabs }), new Set(['superTabs']), 'superTabs', 'super_tab_observers', {})).toEqual({})expect(superTabs.shareObservers).toHaveBeenCalledOnce()})it('reads and types a member\'s terminal for the Super Tab service alone, refusing what is not well formed', async () => {const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(),- screen: vi.fn(async () => ({ ok: true as const, text: 'Allow?', hold: null })), input: vi.fn(async () => ({ ok: true as const })) }+ screen: vi.fn(async () => ({ ok: true as const, text: 'Allow?', hold: null })), input: vi.fn(async () => ({ ok: true as const })), inputIfScreen: vi.fn(async () => ({ ok: true as const })) }const core = fakeCore({ superTabs }), both = new Set(['orchestrator', 'superTabs'])expect(await answerExperimentQuery(core, both, 'superTabs', 'super_tab_screen', { agentId: 'h1', scrollback: 40 })).toEqual({ ok: true, text: 'Allow?', hold: null })expect(superTabs.screen).toHaveBeenLastCalledWith('h1', 40)@@ -78,7 +78,13 @@ describe('the Super Tab service\'s door', () => {['super_tab_input', { agentId: 'h1', text: 7 }], ['super_tab_input', { agentId: 'h1', keys: [1] }], ['super_tab_input', { agentId: 'h1', keys: 'Enter' }]] as const) {expect(await answerExperimentQuery(core, both, 'superTabs', query, payload)).toEqual({ ok: false, error: 'INVALID_REQUEST' })}- for (const query of ['super_tab_screen', 'super_tab_input']) {+ expect(await answerExperimentQuery(core, both, 'superTabs', 'super_tab_input_if_screen', { agentId: 'h1', keys: ['Escape'], screen: 'Update available' })).toEqual({ ok: true })+ expect(superTabs.inputIfScreen).toHaveBeenLastCalledWith('h1', ['Escape'], 'Update available')+ for (const payload of [{ agentId: 'bad id', keys: ['Escape'], screen: 'x' }, { agentId: 'h1', keys: ['Escape'] }, { agentId: 'h1', keys: ['Escape'], screen: 7 },+ { agentId: 'h1', keys: [], screen: 'x' }, { agentId: 'h1', screen: 'x' }]) {+ expect(await answerExperimentQuery(core, both, 'superTabs', 'super_tab_input_if_screen', payload)).toEqual({ ok: false, error: 'INVALID_REQUEST' })+ }+ for (const query of ['super_tab_screen', 'super_tab_input', 'super_tab_input_if_screen']) {expect(await answerExperimentQuery(core, both, 'orchestrator', query, { agentId: 'h1' })).toEqual({ error: 'NOT_SUPER_TABS' })expect(await answerExperimentQuery(fakeCore(), both, 'superTabs', query, { agentId: 'h1' })).toEqual({ error: 'NOT_SUPER_TABS' })}diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.tsindex ccca3315c..8f684f06f 100644--- a/cli/src/core/experimentQueries.ts+++ b/cli/src/core/experimentQueries.ts@@ -27,7 +27,8 @@* (`core.superTabs`, superTabs/inCore/cards.ts), for the Super Tab service alone;* - `super_tab_observers`: members may watch an agent here, so Share must run (`core.superTabs`), for the Super Tab* service alone;- * - `super_tab_screen`, `super_tab_input`: a member's terminal read as plain text and typed into for its Lead+ * - `super_tab_screen`, `super_tab_input`, `super_tab_input_if_screen`: a member's terminal read as plain text and typed into for its Lead,+ * and keys typed there only while its screen is still the one the Service read* (`core.superTabs`, superTabs/inCore/terminal.ts), for the Super Tab service alone.* The core answers them only for the experiments (core/api.ts `EXPERIMENTS`): creating an agent or* telling the windows something is no other process's to ask. The process's side is@@ -42,7 +43,7 @@ import { nativeTurnCursorIn } from '../lib/nativeTurnObservations.js'type Payload = Record<string, unknown>type Core = Pick<CoreApi, 'agents' | 'turns' | 'clients' | 'daemon' | 'account' | 'cloud' | 'superTabs' | 'transcripts'>-const QUERIES: ReadonlySet<string> = new Set(['shown', 'close_swarm', 'keep_lead_alive', 'close_member', 'stopped', 'gone', 'creation_status', 'native_turns', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'account', 'cloud_publish', 'cloud_ask', 'cloud_unask', 'super_tab_attention', 'super_tab_cards', 'super_tab_card_recap', 'super_tab_observers', 'super_tab_screen', 'super_tab_input'])+const QUERIES: ReadonlySet<string> = new Set(['shown', 'close_swarm', 'keep_lead_alive', 'close_member', 'stopped', 'gone', 'creation_status', 'native_turns', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'account', 'cloud_publish', 'cloud_ask', 'cloud_unask', 'super_tab_attention', 'super_tab_cards', 'super_tab_card_recap', 'super_tab_observers', 'super_tab_screen', 'super_tab_input', 'super_tab_input_if_screen'])const METHODS: ReadonlySet<string> = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])const text = (value: unknown): string => (typeof value === 'string' ? value : '')@@ -179,12 +180,15 @@ export async function answerExperimentQuery(core: Core, experiments: ReadonlySetcore.superTabs.shareObservers()return {}case 'super_tab_screen':- case 'super_tab_input': {+ case 'super_tab_input':+ case 'super_tab_input_if_screen': {if (service !== 'superTabs' || !core.superTabs) return { error: 'NOT_SUPER_TABS' }- const { agentId, scrollback = 0, text: typed = '', keys = [] } = payload+ const { agentId, scrollback = 0, text: typed = '', keys = [], screen } = payloadif (!/^[A-Za-z0-9_-]{1,160}$/.test(text(agentId)) || typeof scrollback !== 'number' || typeof typed !== 'string'- || !Array.isArray(keys) || !keys.every(key => typeof key === 'string')) return { ok: false, error: 'INVALID_REQUEST' }+ || !Array.isArray(keys) || !keys.every(key => typeof key === 'string')+ || (query === 'super_tab_input_if_screen' && (typeof screen !== 'string' || !keys.length))) return { ok: false, error: 'INVALID_REQUEST' }return { ...query === 'super_tab_screen' ? await core.superTabs.screen(agentId as string, scrollback)+ : query === 'super_tab_input_if_screen' ? await core.superTabs.inputIfScreen(agentId as string, keys as string[], screen as string): await core.superTabs.input(agentId as string, typed, keys as string[]) }}case 'account': {diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 7078e61c0..d66264a60 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -897,7 +897,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {// In the core's own process Share was started with it; out of it, the master starts Share's process.shareObservers: () => { if (outOfProcess.has('sharing')) coreLink.want('sharing') },screen: (agentId, scrollback) => swarmDoors.terminal.screen(agentId, scrollback),- input: (agentId, text, keys) => swarmDoors.terminal.input(agentId, text, keys) },+ input: (agentId, text, keys) => swarmDoors.terminal.input(agentId, text, keys),+ inputIfScreen: (agentId, keys, screen) => swarmDoors.terminal.inputIfScreen(agentId, keys, screen) },// The devices' `cardsWanted`, `cardRecap` and `cardOpen`, and no other action of the Super Tab service (superTabs/inCore/cards.ts `ask`).superTabRequest: (payload) => swarmDoors.cards.ask(payload),} : {}),diff --git a/cli/src/engines/codex/launch.ts b/cli/src/engines/codex/launch.tsindex a056e5812..c49bf18af 100644--- a/cli/src/engines/codex/launch.ts+++ b/cli/src/engines/codex/launch.ts@@ -126,6 +126,15 @@ export const launch: EngineLaunch = {// sends none, and costs the whole `withinMs`.resizeRepaint: { clears: '\u001b[3J', ends: '\u001b[?2026l', withinMs: 250 },},+ /**+ * Codex asks "Update available" on a start with a newer release out, with Update now (`npm install -g`) the highlighted+ * row, and no one is at a Swarm agent's terminal to answer (Studio Codex, 2026-10-29: tasks held behind it). The+ * startup check is `check_for_update_on_startup` in config.toml's top level (0.165.0's ConfigToml), and `-c` outranks+ * the person's file, as `screen.args` does. Only for sessions the Swarm starts: a person's Codex keeps asking, and+ * updating Codex stays their choice. Codex that still shows the prompt is answered with Skip by the host+ * (superTabs/terminal.ts).+ */+ swarmArgs: ['-c', 'check_for_update_on_startup=false'],/*** Codex 0.162.1 has no setting for its attribution's text: its own line ("Generated with [Codex](…)") is an* instruction in its developer message (`<git_attribution>`), on or off by workspace. `developer_instructions` isdiff --git a/cli/src/engines/codex/screen.ts b/cli/src/engines/codex/screen.tsindex 5276eefff..42c3914e2 100644--- a/cli/src/engines/codex/screen.ts+++ b/cli/src/engines/codex/screen.ts@@ -29,6 +29,25 @@ function withCodexLabels(view: PaneView): PaneView {}}+/**+ * The key that dismisses Codex's update prompt without updating, or null unless the capture is exactly that prompt. Only+ * for the Swarm's agents (superTabs/terminal.ts), who must not wait for a person. It is Esc alone, never a row number and+ * Enter: on codex-cli 0.165.0 `0` is ignored and its Enter runs `brew upgrade` on the highlighted "Update now" (measured+ * 2026-10-29, update_prompt.rs the same in 0.164), so a Skip row misread as 0 or 1 would have updated Codex. Esc is what+ * the prompt's own footer says skips it; the capture must show that footer and exactly these three rows in this order,+ * so a misread or changed menu sends nothing and is left to the Lead.+ */+export function updateDismissKeys(capture: string): string[] | null {+ if (takeover(capture, '') !== 'update') return null+ const lines = stripAnsi(capture).replace(/\u00a0/g, ' ').split('\n').map(line => line.trim()).filter(Boolean)+ const header = lines.filter(line => /^Update available\b/.test(line))+ if (header.length !== 1) return null+ const rows = lines.filter(line => /^[›>]?\s*\d+\./.test(line)).map(line => line.replace(/^[›>]?\s*/, ''))+ const menu = rows.length === 3 && /^1\. Update now \(runs /.test(rows[0]) && rows[1] === '2. Skip' && rows[2] === '3. Skip until next version'+ const footer = /^enter\s+continue\s+·\s+esc\s+skip$/.test(lines[lines.length - 1])+ return menu && footer ? ['Escape'] : null+}+function takeover(capture: string, currentUi: string): PaneTakeover | null {const lines = stripAnsi(capture).replace(/\u00a0/g, ' ').split('\n')const bottom = lines.filter(line => line.trim()).slice(-3)diff --git a/cli/src/engines/codex/updateSkip.spec.ts b/cli/src/engines/codex/updateSkip.spec.tsnew file mode 100644index 000000000..74d222542--- /dev/null+++ b/cli/src/engines/codex/updateSkip.spec.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest'+import { CODEX_MODEL_MIGRATION, CODEX_SIGN_IN, CODEX_TRUST_PROMPT, CODEX_UPDATE_PROMPT } from '../../lib/__fixtures__/takeoverScreens.js'+import { updateDismissKeys } from './screen.js'++/** The prompt as codex-cli 0.165.0 drew it in a tmux pane (2026-10-29), where Esc was measured to skip it. */+const CODEX_UPDATE_0165 = [+ ' Update available · 0.165.0 → 99.0.0',+ ' Release notes: https://github.com/openai/codex/releases/latest',+ '',+ '› 1. Update now (runs `brew upgrade --cask codex`)',+ ' 2. Skip',+ ' 3. Skip until next version',+ '',+ ' enter continue · esc skip',+].join('\n')++// Measured on codex-cli 0.165.0 (2026-10-29): Esc leaves the prompt for the next screen without updating, while `0` is+// ignored and the Enter after it runs `brew upgrade` on the highlighted "Update now". A number plus Enter is never sent.+describe('dismissing Codex\'s update prompt', () => {+ it.each([['the prompt as 0.160 drew it', CODEX_UPDATE_PROMPT], ['the prompt as 0.165 drew it', CODEX_UPDATE_0165]])('answers %s with Esc alone', (_name, capture) => {+ expect(updateDismissKeys(capture)).toEqual(['Escape'])+ })++ it.each([+ ['a Skip row misread as 0', CODEX_UPDATE_0165.replace('2. Skip', '0. Skip')],+ ['a Skip row misread as 1', CODEX_UPDATE_0165.replace('2. Skip', '1. Skip')],+ ['another Skip row above the prompt', ` 1. Skip\n${CODEX_UPDATE_0165}`],+ ['a changed menu order', CODEX_UPDATE_0165.replace('› 1. Update now (runs `brew upgrade --cask codex`)\n 2. Skip', '› 1. Skip\n 2. Update now (runs `brew upgrade --cask codex`)')],+ ['rows in another order below the same numbers', CODEX_UPDATE_0165.replace('2. Skip\n 3. Skip until next version', '2. Skip until next version\n 3. Skip')],+ ['a missing Skip row', CODEX_UPDATE_0165.replace(' 2. Skip\n', '')],+ ['an extra row', CODEX_UPDATE_0165.replace(' 3. Skip until next version', ' 3. Skip until next version\n 4. Never ask again')],+ ['a footer that does not say Esc skips', CODEX_UPDATE_0165.replace('esc skip', 'esc quit')],+ ['no footer', CODEX_UPDATE_0165.replace('\n\n enter continue · esc skip', '')],+ ['two update prompts', `${CODEX_UPDATE_0165}\n${CODEX_UPDATE_0165}`],+ ])('sends nothing for %s: a misread screen is left to the Lead', (_name, capture) => {+ expect(updateDismissKeys(capture)).toBeNull()+ })++ it.each([+ ['trust', CODEX_TRUST_PROMPT],+ ['model', CODEX_MODEL_MIGRATION],+ ['sign-in', CODEX_SIGN_IN],+ ['composer', ' gpt-5.5 high · ~/project\n\n› Write tests\n'],+ ['the update prompt left in scrollback above the composer', `${CODEX_UPDATE_0165}\n\n› Write tests\n gpt-5.5 high · ~/project\n`],+ ])('sends nothing on %s', (_name, capture) => {+ expect(updateDismissKeys(capture)).toBeNull()+ })+})diff --git a/cli/src/engines/facets/launch.ts b/cli/src/engines/facets/launch.tsindex 1c0050500..972d67a1d 100644--- a/cli/src/engines/facets/launch.ts+++ b/cli/src/engines/facets/launch.ts@@ -287,6 +287,8 @@ export interface EngineLaunch {startup?: StartupContract/** The screen the engine's TUI runs on, where Harness chooses it; applied to every launch (kit/launchScreen.ts). */screen?: ScreenContract+ /** Arguments for a session the Swarm started, never for a person's own (lib/swarmEngineArgs.ts). */+ swarmArgs?: readonly string[]/** The instruction file Harness writes its own notes into (a harness's bootstrap, the saved APIs); else AGENTS.md. */instructionFile?: string/** The line, in that file, that has the engine read `file` too (Claude Code's `@AGENTS.md` import). */diff --git a/cli/src/lib/engineInstall.user.spec.ts b/cli/src/lib/engineInstall.user.spec.tsindex dec3e1ccf..ef3500d08 100644--- a/cli/src/lib/engineInstall.user.spec.ts+++ b/cli/src/lib/engineInstall.user.spec.ts@@ -170,7 +170,8 @@ describe('engine installation for a fresh OS user', () => {expect(result.stderr).toContain('Installing Codex')expect(result.stdout).toContain('ENGINE_READY:["argument with spaces"]')expect(Date.now() - started).toBeGreaterThanOrEqual(1500)- })+ // A deliberate 2 s sleep plus a real npm install does not fit the default 5 s on a busy CI shard (timed out at 5030 ms).+ }, 20_000)it('ends the pane rather than install a second time when the wait for the download is interrupted', async () => {const f = fixture()diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.tsindex b2bbe4cdf..ac97b353a 100644--- a/cli/src/lib/launchOverrides.spec.ts+++ b/cli/src/lib/launchOverrides.spec.ts@@ -12,6 +12,7 @@ import { GRID_CONFLICTING_ENV_VARS, type GridLaunchOverride } from './gridLaunchimport { gridLaunchInProcess } from '../testing/gridLaunchInProcess.js'import { AGENT_ATTRIBUTION_LINE, HARNESS_INSTRUCTIONS } from './agentAttribution.js'import { prepareSwarmSkill } from './swarmSkills.js'+import { swarmEngineArgs } from './swarmEngineArgs.js'import { swarmGitHubLaunch } from './swarmGitHub.js'import { writeMachineMcp } from './machineMcp.js'@@ -40,7 +41,7 @@ function deps(overrides: Partial<LaunchOverridesDeps> = {}) {// consult the config.toml of whoever is running the suite.readCodexConfig: () => null,// The Swarm on, as by default (`HARNESS_SWARM`); a test of it off leaves it out.- swarm: { prepare: prepareSwarmSkill, github: (key) => swarmGitHubLaunch(key) },+ swarm: { prepare: prepareSwarmSkill, github: (key) => swarmGitHubLaunch(key), args: swarmEngineArgs },...overrides,}return { d, calls }@@ -523,6 +524,15 @@ describe('buildLaunchOverrides — a Swarm session on the Harness GitHub App', (expect(result.overrides.clearEnv).not.toContain('GH_TOKEN')})+ it('relaunches a Swarm Codex without its startup update check, and a Codex the Swarm never started with it', async () => {+ const { d } = deps()+ const swarm = await buildLaunchOverrides(d, 'codex', { cwd: workspace(), swarmSkill: { role: 'dev', key: 'harness-codex-plain' } }, 'agent-1', () => true)+ const own = await buildLaunchOverrides(d, 'codex', { cwd: workspace() }, 'agent-1', () => true)+ if (!swarm.ok || !own.ok) throw new Error('relaunch refused')+ expect(swarm.overrides.extraArgs.join(' ')).toContain('-c check_for_update_on_startup=false')+ expect(own.overrides.extraArgs.join(' ')).not.toContain('check_for_update_on_startup')+ })+// HARNESS_SWARM=off: the core hands in no Swarm, and a session the Swarm started is not relaunched without its role.it('refuses a Swarm session with the Swarm off, before it asks or writes anything', async () => {const native = vi.fn(), dshLaunch = vi.fn()diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.tsindex 16db16025..93d4a518a 100644--- a/cli/src/lib/launchOverrides.ts+++ b/cli/src/lib/launchOverrides.ts@@ -121,6 +121,7 @@ export interface LaunchOverridesDeps {swarm?: {prepare(workspace: string, saved: SwarmSkill): { instructions: string }github(key: string): { env: Record<string, string>; clearEnv: string[] } | null+ args(engine: string): string[]}}@@ -308,6 +309,8 @@ export async function prepareLaunchOverrides(// a Buddy's (core/agents/create.ts).const machineMcp = source.swarmSkill?.role === 'buddy' ? [] : machineMcpLaunchArgs(engine, source.cwd ?? null)if (machineMcp.length) overrides = { ...overrides, extraArgs: [...overrides.extraArgs, ...machineMcp] }+ // What the Swarm adds for its own sessions (core/api.ts `SwarmLaunch.args`), in the slot `agent_create` gave it.+ if (source.swarmSkill) overrides = { ...overrides, extraArgs: [...overrides.extraArgs, ...swarm!.args(engine)] }// What Harness tells the agent rides every relaunch, in the slot `agent_create` gave it: last. Read again each// time, with the person's switches and settings as they are now.let swarmInstructions: string | undefineddiff --git a/cli/src/lib/swarmEngineArgs.spec.ts b/cli/src/lib/swarmEngineArgs.spec.tsnew file mode 100644index 000000000..39e27c126--- /dev/null+++ b/cli/src/lib/swarmEngineArgs.spec.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest'+import { swarmEngineArgs } from './swarmEngineArgs.js'++describe('what the Swarm adds to an engine\'s argv', () => {+ it('turns off Codex\'s startup update check, whose "Update available" screen holds an agent nobody is at', () => {+ expect(swarmEngineArgs('codex')).toEqual(['-c', 'check_for_update_on_startup=false'])+ })++ it('adds nothing for the other engines', () => {+ for (const engine of ['claude', 'opencode', 'gemini', 'not-an-engine']) expect(swarmEngineArgs(engine)).toEqual([])+ })++ it('hands out a copy, so a caller\'s edit never reaches the next launch', () => {+ swarmEngineArgs('codex').push('--oops')+ expect(swarmEngineArgs('codex')).toEqual(['-c', 'check_for_update_on_startup=false'])+ })+})diff --git a/cli/src/lib/swarmEngineArgs.ts b/cli/src/lib/swarmEngineArgs.tsnew file mode 100644index 000000000..c11787cd4--- /dev/null+++ b/cli/src/lib/swarmEngineArgs.ts@@ -0,0 +1,11 @@+/**+ * What the Swarm adds to an engine's argv for the agents it starts, beside the instructions it gives them+ * (lib/agentAttribution.ts) and never for a person's own session: declared as `swarmArgs` in the engine's launch+ * (engines/codex/launch.ts).+ */+import { launchContract } from '../engines/launches.js'++/** The argv for a session the Swarm started, or none. */+export function swarmEngineArgs(engine: string): string[] {+ return [...launchContract(engine)?.swarmArgs ?? []]+}diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.tsindex 8ea8d7812..fd4d49129 100644--- a/cli/src/lib/swarmSkills.spec.ts+++ b/cli/src/lib/swarmSkills.spec.ts@@ -16,7 +16,7 @@ import { notifyHookEntry } from '../engines/kit/hookSettings.js'import { messagesCommand } from '../engines/kit/messagesHook.js'/** The Swarm's relaunch preparation, as the core hands it in while the Swarm is on (lib/launchOverrides.ts `swarm`). */-const SWARM = { prepare: prepareSwarmSkill, github: () => null }+const SWARM = { prepare: prepareSwarmSkill, github: () => null, args: () => [] }const roots: string[] = []const fixture = () => { const root = mkdtempSync(join(tmpdir(), 'swarm-skills-')); roots.push(root); return root }@@ -78,6 +78,7 @@ describe('built-in Swarm skills', () => {const ask = '- When you know who decides, add ask to that needs-human (the person, 2 to 5 options, the one you recommend, what it unblocks) and keep working on your recommendation, marked provisional, until a notice says it was answered; read the answer with harness super-tab decisions --answered.\n'// The requests section (Lead's ruling for v2 G, the human leaderboard, 2026-10-27): the Lead's alone, in both modes, in a// section of its own so other groups' edits to the Lead text merge cleanly.+ const update = '- Codex\'s "Update available" screen on a worker is dismissed with Esc alone, never a number and Enter (on a misread row that runs the update) and never as a question for the owner. The host does it for Swarm agents when the screen is exactly that prompt; if one still waits on it, press Esc yourself.\n'const requests = '## Requests and Done\n- When you open a group for a person\'s request, asked in the project chat or proposed by their Buddy on their behalf, name them as its requester: requesterId on conversation.create, or conversation.requester for a group already open. It records only that they asked, never what they wrote.\n- Right after you merge a group\'s pull request, record it: conversation.merged with the group and the PR link, and mergedAt for a merge you record later. The leaderboard counts the request as shipped at the merge, even if its work is lost or cancelled afterwards. Mark a group Done only after its pull request has merged.\n\n'// Last in the Default Lead text, which has no red flags: after a blank line, ending the text.const requestsLast = `\n${requests.trimEnd()}\n`@@ -170,6 +171,7 @@ describe('built-in Swarm skills', () => {expect(text.startsWith(`---\nname: swarm-${role}\n`)).toBe(true)expect(text.split(twoHours)).toHaveLength(role === 'lead' ? 2 : 1)expect(text.split(terminal)).toHaveLength(role === 'lead' ? 2 : 1)+ expect(text.split(update)).toHaveLength(role === 'lead' ? 2 : 1)expect(text.split(overlap)).toHaveLength(role === 'lead' ? 2 : 1)expect(text.split(local)).toHaveLength(role === 'lead' ? 2 : 1)expect(text.split(plan)).toHaveLength(role === 'lead' ? 2 : 1)@@ -189,7 +191,7 @@ describe('built-in Swarm skills', () => {expect(text.split(reviewCheck)).toHaveLength(role === 'review' ? 2 : 1)expect(text.split(moveMissing)).toHaveLength(role === 'lead' ? 2 : 1)expect(text.split(thread)).toHaveLength(role === 'lead' ? 2 : 1)- expect(sha(approved(text, 'orchestration', role).replace(twoHours, '').replace(terminal, '').replace(overlap, '').replace(local, '').replace(failedStart, '').replace(mention, '').replace(lost, '').replace(checkpoint, '')+ expect(sha(approved(text, 'orchestration', role).replace(twoHours, '').replace(terminal, '').replace(update, '').replace(overlap, '').replace(local, '').replace(failedStart, '').replace(mention, '').replace(lost, '').replace(checkpoint, '').replace(limit, '').replace(digest, '').replace(decision, '').replace(ask, '').replace(requests, '').replace(shared, '').replace(report, '').replace(missingStop, '').replace(reviewCheck, '').replace(moveMissing, '').replace(thread, ''))).toBe(sha256)}@@ -209,9 +211,9 @@ describe('built-in Swarm skills', () => {})it('adds the terminal line where each Lead skill keeps work moving, right after the silent-worker rule', () => {const orchestration = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session' }).file, 'utf8')- expect(orchestration).toContain(`naming the machine owner who can answer.\n${twoHours}${lost}${limit}${digest}${terminal}- Keep each worker supplied`)+ expect(orchestration).toContain(`naming the machine owner who can answer.\n${twoHours}${lost}${limit}${digest}${terminal}${update}- Keep each worker supplied`)const plain = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session', mode: 'default' }).file, 'utf8')- expect(plain).toContain(`- A worker with active work that has said nothing for 20 minutes: ask it.\n${terminal}- A Builder or Reviewer`)+ expect(plain).toContain(`- A worker with active work that has said nothing for 20 minutes: ask it.\n${terminal}${update}- A Builder or Reviewer`)})it('adds the overlap line last in each Lead skill\'s "Route, start, assign"', () => {const orchestration = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session' }).file, 'utf8')@@ -320,6 +322,7 @@ describe('built-in Swarm skills', () => {const prepared = prepareSwarmSkill(fixture(), { role, key: 'session', mode: 'default' })const text = readFileSync(prepared.file, 'utf8')expect(text.split(terminal)).toHaveLength(role === 'lead' ? 2 : 1)+ expect(text.split(update)).toHaveLength(role === 'lead' ? 2 : 1)expect(text.split(overlap)).toHaveLength(role === 'lead' ? 2 : 1)expect(text.split(localDefault)).toHaveLength(role === 'lead' ? 2 : 1)expect(text.split(plan)).toHaveLength(role === 'lead' ? 2 : 1)@@ -339,7 +342,7 @@ describe('built-in Swarm skills', () => {expect(text.split(reviewCheck)).toHaveLength(role === 'review' ? 2 : 1)expect(text.split(moveMissing)).toHaveLength(role === 'lead' ? 2 : 1)expect(text.split(thread)).toHaveLength(role === 'lead' ? 2 : 1)- expect(sha(approved(text, 'default', role).replace(terminal, '').replace(overlap, '').replace(localDefault, '').replace(failedStart, '').replace(mention, '').replace(lost, '').replace(checkpoint, '')+ expect(sha(approved(text, 'default', role).replace(terminal, '').replace(update, '').replace(overlap, '').replace(localDefault, '').replace(failedStart, '').replace(mention, '').replace(lost, '').replace(checkpoint, '').replace(limit, '').replace(digest, '').replace(decision, '').replace(ask, '').replace(requestsLast, '').replace(sharedLast, '').replace(report, '').replace(missingStop, '').replace(reviewCheck, '').replace(moveMissing, '').replace(thread, ''))).toBe(sha256)expect(prepared.instructions).toBe(`Use the swarm-${role} skill for this session: the team process; otherwise work your usual way. Before working, read ${JSON.stringify(prepared.file)} with your file or shell tool.`)diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.tsindex a3616e0e9..7c724d583 100644--- a/cli/src/lib/swarmSkills.ts+++ b/cli/src/lib/swarmSkills.ts@@ -122,6 +122,7 @@ For large work, post the group plan and get the owner's ok before assigning; onc- A task lost to a usage limit resumes by itself in the same session when the limit resets (its wake-up says when). Hand it on at once only to another account or engine with allowance now, with its pushed branch and last progress note.- Morning digest: when a person asks for one, set the project's digest to their local time and time zone ("project.digest" with time "08:00" and timeZone "Asia/Ho_Chi_Minh"). When it wakes you, check that each pull request under Shipped is merged, then post one message to the people in the project chat.- When a worker seems stuck, read its terminal; answer prompts within its task; ask the owner before approving anything risky.+- Codex's "Update available" screen on a worker is dismissed with Esc alone, never a number and Enter (on a misread row that runs the update) and never as a question for the owner. The host does it for Swarm agents when the screen is exactly that prompt; if one still waits on it, press Esc yourself.- Keep each worker supplied: have its next group ready before it finishes, so nobody waits for you.- Cancel a duplicate, obsolete or wrong task with a reason.- When a worker finishes: reuse, keep or stop. Prefer stop unless more work is coming soon.@@ -416,6 +417,7 @@ Keep each Builder's list a few tasks deep; do the easy, self-contained parts fir- Each time you are woken, look at active work.- A worker with active work that has said nothing for 20 minutes: ask it.- When a worker seems stuck, read its terminal; answer prompts within its task; ask the owner before approving anything risky.+- Codex's "Update available" screen on a worker is dismissed with Esc alone, never a number and Enter (on a misread row that runs the update) and never as a question for the owner. The host does it for Swarm agents when the screen is exactly that prompt; if one still waits on it, press Esc yourself.- A Builder or Reviewer that has been down for 2 hours (its machine offline, its session gone, or stopped): cancel its task with the reason, route it, and assign it to another agent with what the first one left (branch, last revision, last report).- When you are told a task is lost, hand it on at once: route it and assign it to another agent, avoiding what failed (another machine if its machine died, another account or engine if it hit a usage limit). The new brief tells the successor to continue from the lost attempt's pushed branch and last result, not to start over.- A task lost to a usage limit resumes by itself in the same session when the limit resets (its wake-up says when). Hand it on at once only to another account or engine with allowance now, with its pushed branch and last progress note.diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.tsindex 3dc94defd..8b0982932 100644--- a/cli/src/services/processCoreApi.spec.ts+++ b/cli/src/services/processCoreApi.spec.ts@@ -255,7 +255,10 @@ describe('the core API a light service runs on in its own process', () => {expect(ask).toHaveBeenLastCalledWith('super_tab_screen', { agentId: 'h1', scrollback: 20 })expect(await doors.input('h1', 'yes', ['Enter'])).toEqual({ ok: true })expect(ask).toHaveBeenLastCalledWith('super_tab_input', { agentId: 'h1', text: 'yes', keys: ['Enter'] })+ expect(await doors.inputIfScreen('h1', ['Escape'], 'Update available')).toEqual({ ok: true })+ expect(ask).toHaveBeenLastCalledWith('super_tab_input_if_screen', { agentId: 'h1', keys: ['Escape'], screen: 'Update available' })ask.mockRejectedValue(new Error('gone'))+ expect(await doors.inputIfScreen('h1', ['Escape'], 'x')).toEqual({ ok: false, error: 'This machine\'s daemon could not be asked. Try again in a moment.' })expect(await doors.screen('h1', 0)).toEqual({ ok: false, error: 'This machine\'s daemon could not be asked. Try again in a moment.' })expect(await doors.input('h1', 'x', [])).toEqual({ ok: false, error: 'This machine\'s daemon could not be asked. Try again in a moment.' })ask.mockResolvedValue({ error: 'NOT_SUPER_TABS' })diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.tsindex 630d964da..bb461da82 100644--- a/cli/src/services/processCoreApi.ts+++ b/cli/src/services/processCoreApi.ts@@ -265,6 +265,7 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie// A Lead's read of a member's terminal and its typing (superTabs/inCore/terminal.ts), answered by the core.screen: (agentId, scrollback) => terminalAnswer(ask('super_tab_screen', { agentId, scrollback })) as Promise<SuperTabScreen>,input: (agentId, text, keys) => terminalAnswer(ask('super_tab_input', { agentId, text, keys })),+ inputIfScreen: (agentId, keys, screen) => terminalAnswer(ask('super_tab_input_if_screen', { agentId, keys, screen })),} satisfies SuperTabsCore,} : {}),}diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex af3331755..f3a450f61 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -982,7 +982,7 @@ describe('Super Tab waits for the Harness Pro', () => {if (offline) throw new Error('Host offline')return { status: 200, body: { success: true, data: path.includes('/hosts/') ? hostForm(rows, { tabs: ['tab'] }) : [] } }})- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn(), inputIfScreen: vi.fn() }const core = fakeCore({ dataDir: dir, superTabs, account: { backend: call },agents: { creationStatus: vi.fn(async creationId => ({ creationId, state: 'created' as const, agentId: 'harness' })), byAgent: vi.fn(() => ({ agentId: 'harness' }) as never), terminalAvailable: vi.fn(() => true) } })const open = () => { const host = new SuperTabHost(core, 'machine-1', { log: vi.fn() }); hosts.push(host); return host }@@ -1019,7 +1019,7 @@ describe('Super Tab waits for the Harness Pro', () => {agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1' } }]const call: CoreApi['account']['backend'] = vi.fn(async (_method, path) => ({ status: 200, body: { success: true, data: path.includes('/hosts/') ? hostForm(rows, { tabs: ['tab'] }) : [] } }))let here = true, clock = 0- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn(), inputIfScreen: vi.fn() }const core = fakeCore({ dataDir: dir, superTabs, account: { backend: call },agents: { byAgent: vi.fn(() => (here ? { agentId: 'harness' } : undefined) as never), terminalAvailable: vi.fn(() => true) } })const host = new SuperTabHost(core, 'machine-1', { log: vi.fn(), now: () => clock }); hosts.push(host)@@ -1629,7 +1629,7 @@ describe('the members a host lets watch its agents', () => {if (path.includes('/hosts/') && answer === null) await new Promise<void>(resolve => { answer = resolve })return { status: 200, body: { success: true, data: path.includes('/hosts/') ? hostForm(rows, { tabs: ['tab'] }) : [] } }})- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn(), inputIfScreen: vi.fn() }const core = fakeCore({ dataDir: dir, superTabs, account: { backend: call },agents: { byAgent: vi.fn(() => ({ agentId: 'harness' }) as never), terminalAvailable: vi.fn(() => true) } })const host = new SuperTabHost(core, 'machine-1', { log: vi.fn(), now: () => clock }); hosts.push(host)@@ -1674,7 +1674,7 @@ describe('the members a host lets watch its agents', () => {let rows: unknown[] = [lead(true)], clock = 0const call: CoreApi['account']['backend'] = vi.fn(async (_method, path) =>({ status: 200, body: { success: true, data: path.includes('/hosts/') ? hostForm(rows, { tabs: ['tab'] }) : [] } }))- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn(), inputIfScreen: vi.fn() }const core = fakeCore({ dataDir: dir, superTabs, account: { backend: call },agents: { byAgent: vi.fn(() => ({ agentId: 'harness' }) as never), terminalAvailable: vi.fn(() => true) } })const source = observerSource(dir, () => 'machine-1', () => clock)diff --git a/cli/src/superTabs/inCore/launch.ts b/cli/src/superTabs/inCore/launch.tsindex af7498476..9d25267bf 100644--- a/cli/src/superTabs/inCore/launch.ts+++ b/cli/src/superTabs/inCore/launch.ts@@ -4,6 +4,7 @@* work. The core is handed it while the Swarm is on, and refuses a start with a Swarm role while it is off.*/import type { SwarmLaunch } from '../../core/api.js'+import { swarmEngineArgs } from '../../lib/swarmEngineArgs.js'import { swarmGitHubLaunch } from '../../lib/swarmGitHub.js'import { isSwarmRole, isSwarmSkillMode, prepareSwarmSkill } from '../../lib/swarmSkills.js'@@ -12,4 +13,5 @@ export const SWARM_LAUNCH: SwarmLaunch = {mode: isSwarmSkillMode,prepare: prepareSwarmSkill,github: (key) => swarmGitHubLaunch(key),+ args: swarmEngineArgs,}diff --git a/cli/src/superTabs/inCore/terminal.spec.ts b/cli/src/superTabs/inCore/terminal.spec.tsindex 0868ca808..e116c8b5f 100644--- a/cli/src/superTabs/inCore/terminal.spec.ts+++ b/cli/src/superTabs/inCore/terminal.spec.ts@@ -1,6 +1,8 @@import { describe, expect, it, vi } from 'vitest'import type { RegisteredSession } from '../../lib/registry.js'import type { ScreenReading } from '../../engines/facets/screen.js'+import { AutonomousDeviceInput } from '../../core/deviceInput.js'+import { inlineSubmission } from '../../testing/inlineSubmission.js'import { createSuperTabTerminal } from './terminal.js'const session = { agentId: 'h1', engine: 'claude' } as RegisteredSession@@ -61,3 +63,123 @@ describe('a Lead reading and typing into a Swarm member\'s terminal', () => {expect(await setup().terminal.input('h1', '', [])).toEqual({ ok: false, error: 'Nothing to type.' })})})++describe('typing keys only while the screen is still the one that was read', () => {+ const PROMPT = 'Update available · 0.165.0 → 99.0.0\n› 1. Update now\n 2. Skip\n enter continue · esc skip'+ /** A pane whose screen the test changes, and a write lock the test can hold while "another writer" works. */+ function pane(first: string) {+ let screen = first, release = () => {}+ const writes: string[] = []+ const held = new Promise<void>(resolve => { release = resolve })+ const terminal = createSuperTabTerminal({+ resolve: id => id === 'h1' ? session : undefined,+ capture: async () => ({ state: 'succeeded' as const, value: screen }),+ read: async () => null,+ type: async (_id, text) => { writes.push(`text:${text}`); return true },+ key: async (_id, key) => { writes.push(`key:${key}`); return true },+ locked: async (_id, write) => { await held; return write() },+ })+ return { terminal, writes, show: (next: string) => { screen = next }, release: () => release() }+ }++ it('sends the keys once the screen, read again under the pane\'s write lock, is exactly the one given', async () => {+ const t = pane(PROMPT)+ const done = t.terminal.inputIfScreen('h1', ['Escape'], PROMPT)+ t.release()+ expect(await done).toEqual({ ok: true })+ expect(t.writes).toEqual(['key:Escape'])+ })++ it('sends nothing when another writer changed the screen while this write waited for the lock', async () => {+ const t = pane(PROMPT)+ const done = t.terminal.inputIfScreen('h1', ['Escape'], PROMPT)+ t.show('› Write tests')+ t.release()+ expect(await done).toEqual({ ok: false, error: 'The screen changed before the keys were sent; nothing was typed.' })+ expect(t.writes).toEqual([])+ })++ it('sends nothing for a screen that differs in the least, even by a trailing line', async () => {+ const t = pane(`${PROMPT}\n`)+ t.release()+ expect(await t.terminal.inputIfScreen('h1', ['Escape'], PROMPT)).toMatchObject({ ok: false })+ expect(t.writes).toEqual([])+ })++ it('says plainly when the agent or its screen is not there, or the terminal does not take a key, and types nothing for no keys', async () => {+ expect(await setup().terminal.inputIfScreen('gone', ['Escape'], 'x')).toEqual({ ok: false, error: 'The agent is not running on this machine.' })+ expect(await setup({ captured: null }).terminal.inputIfScreen('h1', ['Escape'], 'x')).toEqual({ ok: false, error: 'Could not read the terminal: pane gone' })+ const refused = setup({ captured: 'x', keyed: () => false })+ expect(await refused.terminal.inputIfScreen('h1', ['Escape'], 'x')).toEqual({ ok: false, error: 'The terminal did not take the key Escape.' })+ expect(await setup().terminal.inputIfScreen('h1', [], 'Allow? 1. Yes')).toEqual({ ok: false, error: 'Nothing to type.' })+ })+})++// In production the pane's lock is the device input's `legacyWrite`, which runs two ordinary writers at once: only the+// Swarm terminal's own mutex keeps the Lead's typed input and the host's conditional key from overlapping (review of 6c82a2cbd,+// reproduced with these real classes: the Lead's Esc cleared the prompt and the dismissal sent its Esc into the composer).+describe('the Lead\'s typed input and the host\'s conditional keys on one pane, under the real write guard', () => {+ const UPDATE = 'Update available\n› 1. Update now\n 2. Skip\n enter continue · esc skip', COMPOSER = '› '+ const flush = async () => { for (let i = 0; i < 5; i++) await new Promise(resolve => setImmediate(resolve)) }++ /** A pane that shows the update prompt until its first Esc, whose writes wait on `gate`, as a slow terminal does. */+ function realPane() {+ let screen = UPDATE, open = () => {}+ const gate = new Promise<void>(resolve => { open = resolve })+ const landed: Array<{ key: string; on: string }> = []+ const device = new AutonomousDeviceInput({+ getSession: () => session, validateRuntime: async () => true, inject: async () => true, sendKey: async () => true,+ capture: async () => '› ', submission: inlineSubmission, acquireControl: () => () => {}, legacySubmit: vi.fn(), legacyCancel: () => false,+ onDelivery: vi.fn(), onInputStatus: vi.fn(),+ })+ const terminal = createSuperTabTerminal({+ resolve: id => id === 'h1' ? session : undefined,+ capture: async () => ({ state: 'succeeded' as const, value: screen }),+ read: async () => null,+ type: async () => true,+ key: async (_id, key) => { await gate; landed.push({ key, on: screen }); if (key === 'Escape') screen = COMPOSER; return true },+ locked: (id, write) => device.legacyWrite(id, write),+ })+ return { terminal, landed, open: () => open() }+ }++ it('sends the conditional Esc into the update prompt only: the Lead\'s Esc, started first, clears it and the dismissal sends nothing', async () => {+ const t = realPane()+ const lead = t.terminal.input('h1', '', ['Escape'])+ const dismissal = t.terminal.inputIfScreen('h1', ['Escape'], UPDATE)+ await flush()+ t.open()+ expect(await lead).toEqual({ ok: true })+ expect(await dismissal).toMatchObject({ ok: false })+ expect(t.landed).toEqual([{ key: 'Escape', on: UPDATE }])+ })++ it('runs the two strictly in turn when the dismissal comes first', async () => {+ const t = realPane()+ const dismissal = t.terminal.inputIfScreen('h1', ['Escape'], UPDATE)+ const lead = t.terminal.input('h1', '', ['Escape'])+ await flush()+ t.open()+ expect(await dismissal).toEqual({ ok: true })+ expect(await lead).toEqual({ ok: true })+ // Strictly in turn: the dismissal's Esc found the prompt; the Lead's own Esc came after, as the Lead asked.+ expect(t.landed).toEqual([{ key: 'Escape', on: UPDATE }, { key: 'Escape', on: COMPOSER }])+ })++ it('goes on with the next writer after one whose write threw, and after the agent has gone while it waited', async () => {+ let thrown = false, there = true+ const terminal = createSuperTabTerminal({+ resolve: id => id === 'h1' && there ? session : undefined,+ capture: async () => ({ state: 'succeeded' as const, value: UPDATE }),+ read: async () => null, type: async () => true,+ key: async () => { if (!thrown) { thrown = true; there = false; throw new Error('pane gone') } return true },+ locked: (_id, write) => write(),+ })+ const first = terminal.input('h1', '', ['Escape'])+ const second = terminal.inputIfScreen('h1', ['Escape'], UPDATE)+ await expect(first).rejects.toThrow('pane gone')+ expect(await second).toEqual({ ok: false, error: 'The agent is not running on this machine.' })+ there = true+ expect(await terminal.inputIfScreen('h1', ['Escape'], UPDATE)).toEqual({ ok: true })+ })+})diff --git a/cli/src/superTabs/inCore/terminal.ts b/cli/src/superTabs/inCore/terminal.tsindex 42beec69a..54d8876cd 100644--- a/cli/src/superTabs/inCore/terminal.ts+++ b/cli/src/superTabs/inCore/terminal.ts@@ -26,8 +26,25 @@ export interface SuperTabTerminalDeps {/** The spec's cap; the tmux capture keeps at most 300 lines in any case. */const MAX_SCROLLBACK = 200const GONE = { ok: false as const, error: 'The agent is not running on this machine.' }+const CHANGED = { ok: false as const, error: 'The screen changed before the keys were sent; nothing was typed.' }export function createSuperTabTerminal({ resolve, capture, read, type, key, locked }: SuperTabTerminalDeps) {+ /**+ * One writer at a time per pane, among the Swarm's own: the Lead's typed input, a resumed limit's continue and the host's+ * conditional keys. The pane's `locked` guard is the device input's `legacyWrite`, which runs ordinary writers at once, so+ * on its own it cannot keep the Lead's Esc from landing between the host's read of a screen and its key (reproduced with+ * the real classes in review of 6c82a2cbd: the Lead's Esc cleared Codex's update prompt, then the dismissal's Esc went into+ * the composer, where Esc can interrupt a turn). A person typing at the same moment is not covered: they write through+ * the terminal, not through here.+ */+ const tails = new Map<string, Promise<void>>()+ function inTurn<T>(agentId: string, write: () => Promise<T>): Promise<T> {+ const run = (tails.get(agentId) ?? Promise.resolve()).then(write)+ const tail = run.then(() => {}, () => {})+ tails.set(agentId, tail)+ void tail.then(() => { if (tails.get(agentId) === tail) tails.delete(agentId) })+ return run+ }return {async screen(agentId: string, scrollback: number): Promise<SuperTabScreen> {const session = resolve(agentId)@@ -42,11 +59,32 @@ export function createSuperTabTerminal({ resolve, capture, read, type, key, lockasync input(agentId: string, text: string, keys: string[]): Promise<SuperTabTyped> {if (!resolve(agentId)) return GONEif (!text && !keys.length) return { ok: false, error: 'Nothing to type.' }- return locked(agentId, async () => {+ return inTurn(agentId, () => locked(agentId, async () => {if (text && !await type(agentId, text)) return { ok: false, error: 'The terminal did not take the text.' }for (const name of keys) if (!await key(agentId, name)) return { ok: false, error: `The terminal did not take the key ${name}.` }return { ok: true }- })+ }))+ },+ /**+ * Named keys, only while the visible screen is still exactly `screen`: it is read again in this pane's turn among the+ * Swarm's writers and under its write lock, where none of them can change it before the keys land. A caller that read the screen earlier (the host's watch,+ * which answers Codex's update prompt for an agent nobody sits at) cannot say it is still there: the Lead, or the+ * person, may have answered it in between, and a key typed then lands in the composer or the next question. What the+ * screen means is the caller's to judge; this only keeps the keys from reaching a different one.+ */+ async inputIfScreen(agentId: string, keys: string[], screen: string): Promise<SuperTabTyped> {+ if (!resolve(agentId)) return GONE+ if (!keys.length) return { ok: false, error: 'Nothing to type.' }+ return inTurn(agentId, () => locked(agentId, async () => {+ // The agent may have stopped or restarted while this waited its turn.+ const session = resolve(agentId)+ if (!session) return GONE+ const captured = await capture(session, { mode: 'visible', ansi: false })+ if (captured.state !== 'succeeded') return { ok: false, error: `Could not read the terminal: ${captured.reason}` }+ if (stripVTControlCharacters(captured.value) !== screen) return CHANGED+ for (const name of keys) if (!await key(agentId, name)) return { ok: false, error: `The terminal did not take the key ${name}.` }+ return { ok: true }+ }))},}}diff --git a/cli/src/superTabs/limitResume.spec.ts b/cli/src/superTabs/limitResume.spec.tsindex d21fbe550..1a1d29a9f 100644--- a/cli/src/superTabs/limitResume.spec.ts+++ b/cli/src/superTabs/limitResume.spec.ts@@ -23,7 +23,7 @@ function setup(options: { live?: string[]; reply?: () => { status: number; body:account: { backend },agents: { byAgent: vi.fn((id: string) => (options.live ?? ['h1']).includes(id) ? { agentId: id } as never : undefined) },superTabs: { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(async () => options.screen?.() ?? { ok: true as const, text: '❯ ', hold: null }),- input: vi.fn(async (_harnessId: string, text: string) => { steps.push(`type ${text}`); return { ok: true as const } }) },+ input: vi.fn(async (_harnessId: string, text: string) => { steps.push(`type ${text}`); return { ok: true as const } }), inputIfScreen: vi.fn() },})// The host's current assignment rows, read after the backend answered (host.ts reads its feed).const owns = vi.fn(async (tabId: string, assignmentId: string, harnessId: string) => { steps.push(`check ${tabId} ${assignmentId} ${harnessId}`); return options.owns?.() ?? true })diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.tsindex 77190f95b..8f0687080 100644--- a/cli/src/superTabs/service.spec.ts+++ b/cli/src/superTabs/service.spec.ts@@ -748,7 +748,7 @@ it('documents finished worker decisions and explains an older backend without redescribe('the Swarm cards the devices ask for', () => {function withCards() {const cards = { want: vi.fn(), open: vi.fn(), say: vi.fn(async () => true), worker: vi.fn((machineId: string, harnessId: string) => machineId === 'm2' && harnessId === 'h-r1'), recap: vi.fn(async (tabId: string, leadId: string) => ({ tabId, leadId, text: 'Shipped', at: 5, none: false })), onCards: undefined as unknown, onRecap: undefined as unknown }- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn(), inputIfScreen: vi.fn() }const core = fakeCore({ superTabs })const make = vi.fn(() => cards as never)const service = superTabService(core, { cards: make })diff --git a/cli/src/superTabs/terminal.spec.ts b/cli/src/superTabs/terminal.spec.tsindex f5957e7e1..f94a2da17 100644--- a/cli/src/superTabs/terminal.spec.ts+++ b/cli/src/superTabs/terminal.spec.ts@@ -2,6 +2,7 @@ import { readFileSync } from 'node:fs'import { describe, expect, it, vi } from 'vitest'import type { CoreApi, SuperTabScreen } from '../core/api.js'import { fakeCore } from '../testing/fakeCore.js'+import { CODEX_MODEL_MIGRATION, CODEX_SIGN_IN, CODEX_TRUST_PROMPT, CODEX_UPDATE_PROMPT } from '../lib/__fixtures__/takeoverScreens.js'import { capScreen, limitOf, modelFailing, TerminalHost, typedKeys } from './terminal.js'const row = (agentId = 'a1', harnessId = 'h1', over: Record<string, unknown> = {}) => ({ tabId: 'tab', agent: { id: agentId, harnessId, machineId: 'm1' }, ...over })@@ -21,7 +22,7 @@ function setup(options: { live?: string[]; screen?: (harnessId: string) => Superaccount: { backend },agents: { byAgent: vi.fn((id: string) => (options.live ?? ['h1']).includes(id) ? { agentId: id } as never : undefined) },superTabs: { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(),- screen: vi.fn(async (harnessId: string) => screen(harnessId)), input: vi.fn(async () => ({ ok: true as const })) },+ screen: vi.fn(async (harnessId: string) => screen(harnessId)), input: vi.fn(async () => ({ ok: true as const })), inputIfScreen: vi.fn(async () => ({ ok: true as const })) },})const host = new TerminalHost(core, 'm1', { now: () => clock, log: vi.fn() })return { core, backend, sent, host,@@ -246,6 +247,70 @@ describe('the stuck and usage-limit alerts', () => {})})+describe('dismissing Codex\'s update screen for a Swarm agent', () => {+ const update = (): SuperTabScreen => ({ ok: true, text: CODEX_UPDATE_PROMPT, hold: 'update_prompt_open' })+ const idle = (): SuperTabScreen => ({ ok: true, text: '> ', hold: null })+ const dismissed = (t: ReturnType<typeof setup>) => vi.mocked(t.core.superTabs!.inputIfScreen).mock.calls++ it('sends Esc through the core\'s if-screen door with the screen it read, types nothing itself, and raises no alert', async () => {+ const t = setup({ screen: update })+ await t.host.tick([row()])+ expect(dismissed(t)).toEqual([['h1', ['Escape'], CODEX_UPDATE_PROMPT]])+ expect(t.core.superTabs!.input).not.toHaveBeenCalled()+ t.showing(idle)+ for (let i = 0; i < 14; i++) { t.wait(15_000); await t.host.tick([row()]) }+ expect(dismissed(t)).toHaveLength(1)+ expect(t.alerts()).toEqual([])+ })++ it('answers only the agent whose screen shows it, and only a Swarm agent of this machine', async () => {+ const t = setup({ screen: harnessId => harnessId === 'h2' ? update() : idle(), live: ['h1', 'h2', 'h3'] })+ await t.host.tick([row('a1', 'h1'), row('a2', 'h2'), { tabId: 'tab', agent: { id: 'a3', harnessId: 'h3', machineId: 'other' } }])+ expect(dismissed(t)).toEqual([['h2', ['Escape'], CODEX_UPDATE_PROMPT]])+ })++ it.each([['trust', CODEX_TRUST_PROMPT, 'trust_open'], ['model', CODEX_MODEL_MIGRATION, 'model_prompt_open'],+ ['sign-in', CODEX_SIGN_IN, 'sign_in_open'], ['permission', 'Allow? 1. Yes', 'permission_open']] as const)('asks for nothing on the %s screen', async (_name, text, hold) => {+ const t = setup({ screen: () => ({ ok: true, text, hold }) })+ await t.host.tick([row()])+ expect(dismissed(t)).toEqual([])+ })++ it('asks for nothing when the update screen is misread (a Skip row as 0), and alerts as before after 3 minutes', async () => {+ const t = setup({ screen: () => ({ ok: true, text: CODEX_UPDATE_PROMPT.replace(' 2. Skip\n', ' 0. Skip\n'), hold: 'update_prompt_open' }) })+ await t.host.tick([row()])+ t.wait(180_000); await t.host.tick([row()])+ expect(dismissed(t)).toEqual([])+ expect(t.alerts()).toEqual([{ type: 'agent.alert', agentId: 'a1', alert: 'prompt', active: true }])+ })++ it('tries three times at most when the screen stays, then leaves it to the 3-minute alert', async () => {+ const t = setup({ screen: update })+ for (let i = 0; i < 12; i++) { await t.host.tick([row()]); t.wait(15_000) }+ await t.host.tick([row()])+ expect(dismissed(t)).toHaveLength(3)+ expect(t.alerts()).toEqual([{ type: 'agent.alert', agentId: 'a1', alert: 'prompt', active: true }])+ })++ it('starts the tries again for a new update screen once the old one is gone', async () => {+ const t = setup({ screen: update })+ await t.host.tick([row()])+ t.showing(idle); t.wait(15_000); await t.host.tick([row()])+ t.showing(update); t.wait(15_000); await t.host.tick([row()])+ expect(dismissed(t)).toHaveLength(2)+ })++ it('goes on watching when the core refuses, because the screen had changed or the terminal did not take the key', async () => {+ const t = setup({ screen: update })+ vi.mocked(t.core.superTabs!.inputIfScreen).mockResolvedValueOnce({ ok: false, error: 'The screen changed before the key was sent; nothing was typed.' })+ vi.mocked(t.core.superTabs!.inputIfScreen).mockRejectedValueOnce(new Error('core gone'))+ await t.host.tick([row()])+ t.wait(15_000); await t.host.tick([row()])+ t.wait(15_000); await t.host.tick([row()])+ expect(dismissed(t)).toHaveLength(3)+ })+})+describe('progress for the machine report', () => {const showing = (text: string) => (): SuperTabScreen => ({ ok: true, text, hold: null })diff --git a/cli/src/superTabs/terminal.ts b/cli/src/superTabs/terminal.tsindex de86b42a2..8c45cef9c 100644--- a/cli/src/superTabs/terminal.ts+++ b/cli/src/superTabs/terminal.ts@@ -8,7 +8,8 @@* agent's lease on its task from that (docs: swarm-never-stops, v1 liveness).*/import { createHash } from 'node:crypto'-import type { CoreApi } from '../core/api.js'+import type { CoreApi, SuperTabScreen } from '../core/api.js'+import { updateDismissKeys } from '../engines/codex/screen.js'import type { MessageHold } from '../engines/facets/screen.js'import { backend } from './host.js'import { identifier, object } from './wire.js'@@ -21,6 +22,8 @@ const SERVE_EVERY_MS = 3_000/** A screen read per agent; the 3-minute prompt wait does not need it finer. */const WATCH_EVERY_MS = 15_000const PROMPT_WAIT_MS = 3 * 60_000+/** How often Skip is typed for one stuck update screen before the 3-minute alert is left to say it did not work. */+const SKIP_TRIES = 3/** The spec's cap on what a screen read returns. */const MAX_SCREEN_BYTES = 64 * 1024/** What the screen reader says a prompt or a question is waiting on; a popup or a hidden prompt is not one. */@@ -131,7 +134,7 @@ function screenDigest(text: string): string {}type Episode = { since: number; alerted: boolean } | null-interface Watched { prompt: Episode; limit: Episode; model: Episode; retried?: number }+interface Watched { prompt: Episode; limit: Episode; model: Episode; retried?: number; skips?: number }export class TerminalHost {private nextServeAt = 0@@ -241,6 +244,7 @@ export class TerminalHost {// A screen that could not be read says nothing either way.const read = await this.core.superTabs!.screen(agent.harnessId, 0).catch(() => null)if (!read?.ok) continue+ state.skips = await this.skipUpdate(agent, read, state.skips ?? 0)const now = this.now()const digest = screenDigest(read.text), seen = this.progress.get(agent.harnessId)// A model being retried is not the agent's work moving, whatever else the screen shows meanwhile.@@ -256,6 +260,21 @@ export class TerminalHost {}}+ /** Codex's "Update available" screen on a Swarm agent's terminal, where no one will answer it and its task waits: Esc, through+ * the core's door that types only while the screen is still exactly the one read here, so a screen another writer cleared+ * meanwhile gets nothing (superTabs/inCore/terminal.ts `inputIfScreen`). Never a row number and Enter (on a misread row+ * that could run the update), and only a screen read as exactly that prompt (engines/codex/screen.ts `updateDismissKeys`).+ * After [SKIP_TRIES] the 3-minute alert takes over. Returns the tries made for this screen, none once it is gone. The held+ * task goes on by itself: the mailbox types it again once the prompt is gone. */+ private async skipUpdate(agent: Own, read: Extract<SuperTabScreen, { ok: true }>, tries: number): Promise<number> {+ const keys = read.hold === 'update_prompt_open' ? updateDismissKeys(read.text) : null+ if (!keys) return 0+ if (tries >= SKIP_TRIES) return tries+ const dismissed = await this.core.superTabs!.inputIfScreen(agent.harnessId, keys, read.text).catch(error => ({ ok: false as const, error: String(error) }))+ if (!dismissed.ok) this.log(`could not dismiss Codex's update screen for ${agent.agentId}: ${dismissed.error}`)+ return tries + 1+ }+private async episode(agent: Own, alert: 'prompt' | 'limit' | 'model', current: Episode, seen: boolean, now: number,due: (since: number) => boolean, extra: Json): Promise<Episode> {const episode = seen ? current ?? { since: now, alerted: false } : currentdiff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.tsindex 0db2f11bf..5f7dfbe59 100644--- a/cli/src/testing/fakeCore.ts+++ b/cli/src/testing/fakeCore.ts@@ -94,6 +94,6 @@ export function fakeCore(over: Overrides = {}): CoreApi {// Only a spec that gives the cloud agents doors has them, as only a core that offers them does....(over.cloud ? { cloud: Object.assign({ publish: vi.fn(), ask: vi.fn(), unask: vi.fn() }, over.cloud) } : {}),// The Super Tab service's door, likewise.- ...(over.superTabs ? { superTabs: Object.assign({ attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }, over.superTabs) } : {}),+ ...(over.superTabs ? { superTabs: Object.assign({ attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn(), inputIfScreen: vi.fn() }, over.superTabs) } : {}),}}diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 46036e167..0be3924c4 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -15,6 +15,7 @@ import 'model.dart';import 'buddy_chat.dart';import 'project_github.dart';import 'parts.dart';+import 'read_marks.dart';import 'reading.dart';import 'review_verdict.dart';@@ -1068,6 +1069,82 @@ class SuperTabController extends ChangeNotifier {await _readMessages(id);}+ /// At most this many older pages are read to reach a reader's read mark;+ /// past them the page just after the mark is read instead.+ static const _pagesToMark = 3;++ /// Whether [id]'s held messages reach back to [mark], or nothing older is+ /// left to read.+ bool heldBackTo(String id, int mark) {+ final held = _messages[id];+ return held == null ||+ held.isEmpty ||+ held.first.sequence <= mark ||+ !hasOlder(id);+ }++ /// Holds [id]'s messages back to the reader's [mark], so its first unread+ /// is among them: older pages while the mark is at most [_pagesToMark]+ /// pages back, else the page just after it alone, with the newer ones+ /// waiting for [showLatest] as under a reader scrolled up. Whether they+ /// reach it now; a read that failed throws, and nothing counts as read.+ /// A try again after one failed passes [olderPages] 0: the pages read the+ /// first time stay, and it goes straight to the page after the mark.+ Future<bool> loadBackTo(String id, int mark, {int? olderPages}) async {+ for (var page = 0; page < (olderPages ?? _pagesToMark); page++) {+ if (_disposed || heldBackTo(id, mark)) return heldBackTo(id, mark);+ await _readMessages(id, older: true);+ }+ if (_disposed || heldBackTo(id, mark)) return heldBackTo(id, mark);+ return _readAfterMark(id, mark);+ }++ /// Moves when a read back replaces what a conversation holds: a read of+ /// newer messages that set out before then would join across the gap.+ final _heldGeneration = <String, int>{};++ /// Replaces what [id] holds with the page just after [mark]; whether it+ /// did. A read of newer messages under way finishes first, and one that+ /// sets out meanwhile is dropped when it lands ([_heldGeneration]).+ Future<bool> _readAfterMark(String id, int mark) async {+ for (+ var under = _reading[(id, false)];+ under != null;+ under = _reading[(id, false)]+ ) {+ await under;+ }+ if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {+ return false;+ }+ final answer = await request('GET', '${_messagesPath(id)}?after=$mark');+ if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {+ return false;+ }+ final rows = answer['messages'] as List;+ final page = [+ for (final row in rows) SuperTabMessage.fromJson(superTabMap(row)),+ ]..sort(superTabMessageOrder);+ // Nothing after the mark: everything held is read.+ if (page.isEmpty) return true;+ if (page.any((m) => m.conversationId != id)) {+ throw const FormatException('A different conversation was returned.');+ }+ _heldGeneration[id] = (_heldGeneration[id] ?? 0) + 1;+ _rows.remove(id);+ _keepRows(id, rows);+ _messages[id] = page;+ _before[id] = SuperTabPage.of(page.first);+ if (answer['next'] != null) {+ _readingBack.add(id);+ _newer.add(id);+ _pagesBelow[id] = 1;+ }+ _viewVersion++;+ _changed();+ return true;+ }+/// Each conversation's reaction counter as its last page said it.final _reactionSeq = <String, int>{};int _loadedMessageSequence(String id) =>@@ -1077,8 +1154,25 @@ class SuperTabController extends ChangeNotifier {?.sequence ??0;- /// A reply only in its thread leaves the chat as it was: it lights its- /// thread's reply line instead ([threadUnread]).+ /// How far the reader has read [id]: the higher of the mark kept on the+ /// server, from any of their devices, and this device's own, which stands+ /// in while the server is out of reach.+ int readMark(String id) =>+ max(_readAt[id] ?? 0, snapshot?.readMarks[id] ?? 0);++ late final _serverMarks = SuperTabReadMarkSender(+ (id, sequence) => request(+ 'POST',+ '$_path/conversations/${Uri.encodeComponent(id)}/read',+ body: {'sequence': sequence},+ ),+ );++ /// Whether [group] has a message in its main stream past the reader's+ /// mark. A reply only in its thread leaves the chat as it was: it lights its+ /// thread's reply line instead ([threadUnread]). The server's newest+ /// main-stream message covers a chat not held here; an older server's+ /// newest message, and the newest held, stand in for it.bool unread(SuperTabConversation group) =>max(group.lastMainSequence ?? group.lastMessageSequence,@@ -1090,7 +1184,7 @@ class SuperTabController extends ChangeNotifier {?.sequence ??0,) >- (_readAt[group.id] ?? 0);+ readMark(group.id);void start() {if (_disposed) return;@@ -1630,14 +1724,16 @@ class SuperTabController extends ChangeNotifier {/// ([_readUnreadBuddyChats]).int unreadCount(SuperTabConversation group) {if (!unread(group)) return 0;- final readAt = _readAt[group.id] ?? 0;+ final readAt = readMark(group.id);final count = messages(group.id)- .where((m) => m.sequence > readAt && !_ownMessage(m) && m.inMainStream)+ .where((m) => m.sequence > readAt && m.inMainStream && !isOwn(m)).length;return _heldSinceRead(group) ? count : max(count, 1);}- bool _ownMessage(SuperTabMessage m) =>+ /// Whether [m] is the reader's own: written by them, not by an agent or a+ /// terminal.+ bool isOwn(SuperTabMessage m) =>!m.fromAgent && !m.fromTerminal && m.authorId == accountId;/// Whether the messages held of [group] run from its read mark (or its@@ -1646,8 +1742,7 @@ class SuperTabController extends ChangeNotifier {final held = _messages[group.id];if (held == null || held.isEmpty) return false;return held.last.sequence >= group.lastMessageSequence &&- (held.first.sequence <= (_readAt[group.id] ?? 0) ||- !hasOlder(group.id));+ (held.first.sequence <= readMark(group.id) || !hasOlder(group.id));}/// The unread messages in the reader's own Buddy chats, the PM's private@@ -1866,6 +1961,7 @@ class SuperTabController extends ChangeNotifier {}final loaded = _loadedMessageSequence(id);final last = min(through ?? loaded, loaded);+ _serverMarks.mark(id, last, kept: snapshot?.readMarks[id] ?? 0);if ((_readAt[id] ?? 0) >= last) return;_readAt[id] = last;_saveSoon();@@ -1933,7 +2029,8 @@ class SuperTabController extends ChangeNotifier {final raw = parts.state;if (_policy.adapts) {stateChanged = true;- _viewVersion++;+ // A read mark moving is the page around the view: no new copy kept.+ if (!read.marksOnly) _viewVersion++;}final next = SuperTabSnapshot.fromJson(raw);if (next.id != tabId) {@@ -2054,7 +2151,8 @@ class SuperTabController extends ChangeNotifier {/// One read of the Swarm's parts: changes since the cursor once a first load/// is held, else a first load. A reload answer, or a change read refused (the/// Swarm or the reader's access moved), reads in full at once.- Future<({bool full, bool changed, Set<String> removed})> _readParts() async {+ Future<({bool full, bool changed, bool marksOnly, Set<String> removed})>+ _readParts() async {final held = _parts;if (held != null) {try {@@ -2075,6 +2173,7 @@ class SuperTabController extends ChangeNotifier {return (full: false,changed: change.changed || refreshed,+ marksOnly: change.readMarksOnly && !refreshed,removed: change.removedGroups,);}@@ -2088,7 +2187,12 @@ class SuperTabController extends ChangeNotifier {throw const FormatException('A different Swarm was returned.');}_parts = parts;- return (full: true, changed: true, removed: const <String>{});+ return (+ full: true,+ changed: true,+ marksOnly: false,+ removed: const <String>{},+ );}/// A stub says a held group closed, not how: its data is read again by id.@@ -2380,6 +2484,9 @@ class SuperTabController extends ChangeNotifier {if (older && !hasOlder(id)) return;// A light check asks only for new messages, which wait while holding.if (light && _holding(id)) return;+ final generation = _heldGeneration[id];+ // What [id] held was replaced while newer messages were on their way.+ bool replaced() => !older && _heldGeneration[id] != generation;try {final known = _messages[id];final tail = known != null && known.isNotEmpty@@ -2450,7 +2557,10 @@ class SuperTabController extends ChangeNotifier {],};}- if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {+ if (_disposed ||+ accessRevoked ||+ snapshot?.conversation(id) == null ||+ replaced()) {return;}// A read replacing the saved page moved where earlier continues while@@ -2505,7 +2615,10 @@ class SuperTabController extends ChangeNotifier {'GET','$_path/conversations/${Uri.encodeComponent(id)}/messages?messageId=${Uri.encodeComponent(own.id)}',);- if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {+ if (_disposed ||+ accessRevoked ||+ snapshot?.conversation(id) == null ||+ replaced()) {return;}final rows = (receipt['messages'] as List)@@ -2933,6 +3046,7 @@ class SuperTabController extends ChangeNotifier {@overridevoid dispose() {_disposed = true;+ _serverMarks.dispose();_poll?.cancel();_graceEnd?.cancel();_draftSave?.cancel();diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex 86e1bf3f5..446936bfa 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -300,6 +300,11 @@ class SuperTabSnapshot {mentionsDigest = row['mentionsDigest'] as String?,decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0,decisionsDigest = row['decisionsDigest'] as String?,+ readMarks = Map.unmodifiable({+ if (row['readMarks'] case final Map marks)+ for (final MapEntry(:key, :value) in marks.entries)+ if (key is String && value is num) key: value.toInt(),+ }),buddyStarts = List.unmodifiable([for (final startin row['starts'] is List ? row['starts'] as List : const [])@@ -373,6 +378,10 @@ class SuperTabSnapshot {/// Which decisions wait, as a digest that moves when they change though the/// count may not; null from a backend before it (superTabs/decisions.ts).final String? decisionsDigest;++ /// 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;SuperTabConversation? conversation(String id) =>conversations.where((c) => c.id == id).firstOrNull;SuperTabAgent? agent(String id) =>diff --git a/desktop/lib/super_tabs/parts.dart b/desktop/lib/super_tabs/parts.dartindex 2c7d76a58..ccfc45143 100644--- a/desktop/lib/super_tabs/parts.dart+++ b/desktop/lib/super_tabs/parts.dart@@ -23,6 +23,7 @@ class SuperTabPartsChange {required this.changed,this.removedGroups = const {},this.dormantGroups = const {},+ this.readMarksOnly = false,});/// Some part or a derived value is new: what the screens draw may differ.@@ -33,6 +34,9 @@ class SuperTabPartsChange {/// Groups that left the active set: they stay readable on demand.final Set<String> dormantGroups;++ /// Only the reader's read marks moved: the page around the view, not what a saved view holds.+ final bool readMarksOnly;}/// The parts of one Swarm as this reader last saw them (section 5.1): every part by kind and key at the newest@@ -53,9 +57,12 @@ class SuperTabParts {if (answer['format'] != superTabReadFormat) {throw const FormatException('Update Harness to open this Swarm.');}+ // Read marks are held apart from the other derived values (_readMarks).+ final derived = Map.of(superTabMap(answer['derived'] ?? const {}));+ final marks = derived.remove('readMarks');final parts = SuperTabParts._(_envelope(answer['head'], live: true),- superTabMap(answer['derived'] ?? const {}),+ derived,cursor: _cursor(answer),epoch: _int(answer['epoch']),// Null for a Swarm with no part changed yet (contract.ts `ReadMeta`).@@ -71,6 +78,7 @@ class SuperTabParts {parts._seen['$kind:${part['key']}'] = _int(part['version']);}}+ parts._takeReadMarks(marks);return parts;}@@ -92,6 +100,7 @@ class SuperTabParts {}}}+ parts._takeReadMarks(json['readMarks']);return parts;}@@ -119,6 +128,23 @@ class SuperTabParts {/// again never replaces it or brings it back (section 4.4).final _seen = <String, int>{};+ /// The reader's own read marks by conversation (backend readMarks.ts), the highest each read sent: a first load+ /// sends them all, a change read only those moved since its cursor.+ final _readMarks = <String, int>{};++ /// Keeps the higher of each mark in [marks] and the one held; whether any moved.+ bool _takeReadMarks(Object? marks) {+ var moved = false;+ if (marks is! Map) return moved;+ for (final MapEntry(:key, :value) in marks.entries) {+ if (key is! String || value is! num) continue;+ if ((_readMarks[key] ?? 0) >= value) continue;+ _readMarks[key] = value.toInt();+ 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>{};@@ -164,6 +190,7 @@ class SuperTabParts {if (kind == 'groups') {_dormant.remove(key);_stale.remove(key);+ _readMarks.remove(key);removed.add(key);}} else if (kind == 'groups' && part['dormant'] == true) {@@ -190,7 +217,8 @@ class SuperTabParts {}}}- final derived = superTabMap(changes['derived'] ?? const {});+ final derived = Map.of(superTabMap(changes['derived'] ?? const {}));+ final marksMoved = _takeReadMarks(derived.remove('readMarks'));if (!const DeepCollectionEquality().equals(derived, _derived)) {_derived = derived;changed = true;@@ -199,9 +227,10 @@ class SuperTabParts {epoch = _int(changes['epoch'] ?? epoch);lastChangedAt = _int(changes['lastChangedAt'] ?? lastChangedAt);return SuperTabPartsChange(- changed: changed,+ changed: changed || marksMoved,removedGroups: removed,dormantGroups: dormant,+ readMarksOnly: marksMoved && !changed,);}@@ -279,6 +308,7 @@ class SuperTabParts {if (_derived['decisionsDigest'] case final String digest) {state['decisionsDigest'] = digest;}+ if (_readMarks.isNotEmpty) state['readMarks'] = Map.of(_readMarks);return state;}@@ -298,6 +328,7 @@ class SuperTabParts {'dormant': _dormant.values.toList(),'seen': Map<String, int>.of(_seen),'stale': _stale.toList(),+ 'readMarks': Map<String, int>.of(_readMarks),};/// [json] (from [toJson]) without what the screens never draw: agent starts carry their tasks, and projectdiff --git a/desktop/lib/super_tabs/read_marks.dart b/desktop/lib/super_tabs/read_marks.dartnew file mode 100644index 000000000..16bfe4304--- /dev/null+++ b/desktop/lib/super_tabs/read_marks.dart@@ -0,0 +1,46 @@+/// Sends the reader's read marks to the server (backend `superTabs/readMarks.ts`), so a conversation read on this+/// device reads as read on every other one. One request per conversation at a time: a higher mark asked for while+/// one is on its way goes after it, and a lower or equal one is never sent. A failed send is forgotten, so the next+/// mark asked for tries again; meanwhile this device's own mark keeps the conversation read here.+class SuperTabReadMarkSender {+ SuperTabReadMarkSender(this._send);++ /// Writes [sequence] as the mark of [conversationId]; completes once the server kept it, or throws.+ final Future<void> Function(String conversationId, int sequence) _send;++ /// The highest mark sent and kept, by conversation.+ final _sent = <String, int>{};++ /// The mark waiting for the one on its way, by conversation.+ final _next = <String, int>{};+ final _sending = <String>{};+ bool _disposed = false;++ /// Asks for [sequence] to be [conversationId]'s mark on the server, unless [kept] (what the server already+ /// holds) or a mark sent from here is as high.+ void mark(String conversationId, int sequence, {int kept = 0}) {+ if (_disposed || sequence <= kept) return;+ if (sequence <= (_sent[conversationId] ?? 0)) return;+ if (sequence <= (_next[conversationId] ?? 0)) return;+ _next[conversationId] = sequence;+ if (_sending.add(conversationId)) _drain(conversationId);+ }++ Future<void> _drain(String conversationId) async {+ while (!_disposed) {+ final sequence = _next.remove(conversationId);+ if (sequence == null) break;+ try {+ await _send(conversationId, sequence);+ if (sequence > (_sent[conversationId] ?? 0)) {+ _sent[conversationId] = sequence;+ }+ } catch (_) {+ // Offline or refused: this device's mark stands, and the next one asked for is sent afresh.+ }+ }+ _sending.remove(conversationId);+ }++ void dispose() => _disposed = true;+}diff --git a/desktop/lib/super_tabs/roles_editor.dart b/desktop/lib/super_tabs/roles_editor.dartindex e85bfb7f9..235f3068a 100644--- a/desktop/lib/super_tabs/roles_editor.dart+++ b/desktop/lib/super_tabs/roles_editor.dart@@ -57,6 +57,7 @@ Keep each Builder's list a few tasks deep; do the easy, self-contained parts fir- Each time you are woken, look at active work.- A worker with active work that has said nothing for 20 minutes: ask it.- When a worker seems stuck, read its terminal; answer prompts within its task; ask the owner before approving anything risky.+- Codex's "Update available" screen on a worker is dismissed with Esc alone, never a number and Enter (on a misread row that runs the update) and never as a question for the owner. The host does it for Swarm agents when the screen is exactly that prompt; if one still waits on it, press Esc yourself.- A Builder or Reviewer that has been down for 2 hours (its machine offline, its session gone, or stopped): cancel its task with the reason, route it, and assign it to another agent with what the first one left (branch, last revision, last report).- When you are told a task is lost, hand it on at once: route it and assign it to another agent, avoiding what failed (another machine if its machine died, another account or engine if it hit a usage limit). The new brief tells the successor to continue from the lost attempt's pushed branch and last result, not to start over.- A task lost to a usage limit resumes by itself in the same session when the limit resets (its wake-up says when). Hand it on at once only to another account or engine with allowance now, with its pushed branch and last progress note.diff --git a/desktop/lib/super_tabs/unread_line.dart b/desktop/lib/super_tabs/unread_line.dartnew file mode 100644index 000000000..bb88e7f33--- /dev/null+++ b/desktop/lib/super_tabs/unread_line.dart@@ -0,0 +1,184 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_icons.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../widgets/desktop_chrome.dart';+import 'model.dart';++/// The first message of [shown] the reader has not read, for the New messages line: in the main stream (a reply+/// that lives only in its thread is read there), from someone else, and after both the reader's read mark [mark] and+/// their own newest message in the chat, since writing in a chat reads what came before it. Null when everything is read, and+/// for a conversation the reader has never read on any device (no mark), which opens at its end as before.+String? superTabFirstUnread(+ List<SuperTabMessage> shown,+ int mark, {+ required bool Function(SuperTabMessage) own,+}) {+ if (mark <= 0) return null;+ var read = mark;+ for (final message in shown) {+ // A reply of one's own that lives only in its thread reads that thread,+ // not the chat.+ if (own(message) && message.inMainStream && message.sequence > read) {+ read = message.sequence;+ }+ }+ for (final message in shown) {+ if (message.sequence > read && message.inMainStream && !own(message)) {+ return message.id;+ }+ }+ return null;+}++/// Where each conversation's New messages line sits: decided once when the conversation is opened with its messages+/// at hand, then held while new messages arrive and the read mark moves, so the line never jumps. Leaving the+/// conversation, or Esc, forgets it.+class SuperTabUnreadLines {+ final _at = <String, String?>{};++ /// Conversations reading back to the mark before their line is placed, and those that did this visit.+ final _loading = <String>{}, _loaded = <String>{};++ /// Reads back that failed this visit, by conversation: tried again up to [_tries] times.+ final _failed = <String, int>{};+ static const _tries = 3;++ /// The line on screen, to tell whether it is scrolled out of view.+ final key = GlobalKey(debugLabel: 'New messages line');++ /// Whether the reader is scrolled away from the line, so the jump pill shows.+ bool away = false;++ /// The message [id]'s line sits above, or null.+ String? lineAt(String id) => _at[id];++ /// Decides [id]'s line from its [shown] messages once: true when this call placed a line, so the view opens at it.+ bool decide(+ String id,+ List<SuperTabMessage> shown,+ int mark, {+ required bool Function(SuperTabMessage) own,+ }) {+ if (_at.containsKey(id) || shown.isEmpty) return false;+ return (_at[id] = superTabFirstUnread(shown, mark, own: own)) != null;+ }++ /// Whether [id]'s line waits for older messages: loading, or a read back that failed and is not yet done. Nothing is+ /// followed or marked read meanwhile, and no line is placed short of the first unread.+ bool waitsForHistory(String id) =>+ _loading.contains(id) ||+ (_failed.containsKey(id) && !_loaded.contains(id));++ /// Whether [id] must first read back to the [mark] the held messages do not reach ([heldBack] false) for its line,+ /// once per visit; when true, the caller loads and then calls [historyLoaded].+ bool startHistory(+ String id,+ List<SuperTabMessage> shown,+ int mark, {+ required bool heldBack,+ }) {+ if (_at.containsKey(id) ||+ _loading.contains(id) ||+ _loaded.contains(id) ||+ (_failed[id] ?? 0) >= _tries) {+ return false;+ }+ if (heldBack || mark <= 0 || shown.isEmpty || shown.last.sequence <= mark) {+ return false;+ }+ _loading.add(id);+ return true;+ }++ /// The read back of [id] ended: [reached] the mark, or failed and may be tried again ([mayRetry]).+ void historyLoaded(String id, {required bool reached}) {+ if (!_loading.remove(id)) return;+ if (reached) {+ _loaded.add(id);+ } else {+ _failed[id] = (_failed[id] ?? 0) + 1;+ }+ }++ /// Whether a read back of [id] failed this visit: a try again reads no more older pages.+ bool retrying(String id) => _failed.containsKey(id);++ /// Whether [id]'s failed read back has tries left.+ bool mayRetry(String id) =>+ !_loaded.contains(id) && (_failed[id] ?? 0) < _tries;++ /// [id] was left: the next visit decides again.+ void forget(String? id) {+ _at.remove(id);+ _loading.remove(id);+ _loaded.remove(id);+ _failed.remove(id);+ away = false;+ }++ /// Read with Esc: no line until the next visit.+ void clear(String id) {+ _at[id] = null;+ away = false;+ }++ void reset() {+ _at.clear();+ _loading.clear();+ _loaded.clear();+ _failed.clear();+ away = false;+ }+}++/// The line above the first unread message: the accent rule and the words, so colour is never the only signal.+class SuperTabNewMessagesLine extends StatelessWidget {+ const SuperTabNewMessagesLine({super.key});++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final accent = DesktopChrome.accent;+ return Padding(+ key: const ValueKey('super-new-messages-line'),+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.panelPadding,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.panelPadding,+ 0,+ ),+ child: Semantics(+ container: true,+ label: 'New messages',+ excludeSemantics: true,+ child: Row(+ children: [+ Expanded(child: Divider(color: accent)),+ const SizedBox(width: grid.AppDesktop.controlGap),+ Text(+ 'New messages',+ style: DesktopChrome.metadata(color: accent)+ .copyWith(fontWeight: grid.AppFont.semibold),+ ),+ ],+ ),+ ),+ );+ }+}++/// Shown while the New messages line is scrolled out of view: takes the reader back to it.+class SuperTabJumpToUnread extends StatelessWidget {+ const SuperTabJumpToUnread({super.key, required this.onPressed});++ final VoidCallback onPressed;++ @override+ Widget build(BuildContext context) => FilledButton.icon(+ key: const ValueKey('super-jump-unread'),+ onPressed: onPressed,+ icon: const Icon(AppIcons.chevronUp, size: grid.AppDesktop.iconSize),+ label: const Text('Jump to first unread'),+ );+}diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 07174d97f..8e13a2f0f 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart' show kIsWeb;import 'package:flutter/material.dart';import 'package:flutter/rendering.dart'show RenderSliverMultiBoxAdaptor, SliverMultiBoxAdaptorParentData;+import 'package:flutter/scheduler.dart' show SchedulerBinding, SchedulerPhase;import 'package:flutter/services.dart';import '../shared/theme/app_icons.dart';@@ -18,6 +19,7 @@ import '../state/app_state.dart';import '../state/harness_attachments.dart';import '../state/workspace_chrome.dart';import 'chat_scroll.dart';+import 'unread_line.dart';import 'roster.dart';import 'recording_notice.dart';import 'identity.dart' show superTabPersonName;@@ -102,6 +104,7 @@ class _SuperTabViewState extends State<SuperTabView>final _latest = <String, int>{};final _following = <String, bool>{};final _newAfter = <String, int>{};+ final _unread = SuperTabUnreadLines();final _replies = <String, SuperTabMessage>{};String? _selected;int _scrollRequest = 0;@@ -239,6 +242,7 @@ class _SuperTabViewState extends State<SuperTabView>_latest.clear();_following.clear();_newAfter.clear();+ _unread.reset();_replies.clear();_jumpRequest++;_finding = null;@@ -260,6 +264,7 @@ class _SuperTabViewState extends State<SuperTabView>if (c.accessRevoked) {_replies.clear();_newAfter.clear();+ _unread.reset();}final visible =c.snapshot?.conversations.map((g) => g.id).toSet() ?? <String>{};@@ -268,7 +273,9 @@ class _SuperTabViewState extends State<SuperTabView>final firstView = !_scroll.containsKey(id);final scroll = _scroll.putIfAbsent(id,- () => SuperTabChatScroll(rows: () => _built.entries),+ () =>+ SuperTabChatScroll(rows: () => _built.entries)+ ..addListener(_checkUnreadLine),);final atEnd = scroll.hasClients? scroll.position.extentAfter < 40@@ -283,6 +290,7 @@ class _SuperTabViewState extends State<SuperTabView>}final draft = c.accessRevoked ? '' : c.draft(id);if (_selected != id) {+ _unread.forget(_selected);_scrollRequest++;_jumpingToEnd = false;// A search or a way back belongs to the conversation it started in.@@ -302,7 +310,19 @@ class _SuperTabViewState extends State<SuperTabView>}_selected = id;setState(() {});- if (firstView || (grew && atEnd)) {+ final mark = c.readMark(id), shown = _shownMessages(id);+ if (_unread.startHistory(+ id,+ shown,+ mark,+ heldBack: c.heldBackTo(id, mark),+ )) {+ _loadBackToMark(id, mark);+ } else if (_unread.waitsForHistory(id)) {+ // The line is placed once the messages reach back to the mark.+ } else if (_unread.decide(id, shown, mark, own: c.isOwn)) {+ _revealUnreadLine(id);+ } else if (firstView || (grew && atEnd)) {_followEnd(id);} else if (atEnd) {_readVisibleTailAfterFrame();@@ -394,6 +414,7 @@ class _SuperTabViewState extends State<SuperTabView>void _readToEnd(String id, int sequence) {final scroll = _scroll[id];if (c.selectedId != id ||+ _unread.waitsForHistory(id) ||!_chatIsVisible ||scroll == null ||!scroll.hasClients ||@@ -412,6 +433,87 @@ class _SuperTabViewState extends State<SuperTabView>c.readingBack(id, !following);}+ /// Reads [id]'s messages back to the reader's [mark] (bounded by the+ /// controller), then places its line.+ void _loadBackToMark(String id, int mark) {+ unawaited(+ c+ .loadBackTo(id, mark, olderPages: _unread.retrying(id) ? 0 : null)+ .then((reached) => reached, onError: (_) => false)+ .then((reached) {+ _unread.historyLoaded(id, reached: reached);+ if (!mounted) return;+ if (reached) return _changed();+ // Failed: the line waits, and the read back is tried again shortly.+ if (_unread.mayRetry(id)) {+ _historyRetry?.cancel();+ _historyRetry = Timer(_historyRetryAfter, _changed);+ }+ }),+ );+ }++ Timer? _historyRetry;+ static const _historyRetryAfter = Duration(seconds: 5);++ /// Brings [id]'s New messages line into view near the top, and stops+ /// following the end there: what came since the reader's mark is below.+ void _revealUnreadLine(String id) {+ final messageId = _unread.lineAt(id);+ if (messageId == null) return;+ _scrollRequest++;+ _jumpingToEnd = false;+ _follow(id, false);+ _target = messageId;+ _revealTarget(+ id,+ 0,+ arrived: (row) {+ unawaited(+ Scrollable.ensureVisible(row, alignment: .15).then((_) {+ _checkUnreadLine();+ }),+ );+ },+ );+ }++ /// Shows the jump pill while the reader is scrolled away from the line.+ void _checkUnreadLine() {+ final scroll = _scroll[c.selectedId];+ var away = false;+ if (_unread.lineAt(c.selectedId) != null &&+ scroll != null &&+ scroll.hasClients) {+ final line = _unread.key.currentContext;+ final top = line == null ? null : _topInList(line);+ away = top == null || top < 0 || top > scroll.position.viewportDimension;+ }+ if (away == _unread.away || !mounted) return;+ // A list settling its extent moves the position mid-layout: draw the pill+ // on the next frame then.+ if (SchedulerBinding.instance.schedulerPhase ==+ SchedulerPhase.persistentCallbacks) {+ WidgetsBinding.instance.addPostFrameCallback((_) => _checkUnreadLine());+ return;+ }+ setState(() => _unread.away = away);+ }++ /// Esc: everything loaded in the open conversation is read, line and all.+ bool _readAll() {+ final id = c.selectedId, group = c.selected;+ if (group == null || (!c.unread(group) && _unread.lineAt(id) == null)) {+ return false;+ }+ setState(() {+ _unread.clear(id);+ _newAfter.remove(id);+ });+ c.markRead(id);+ return true;+ }+void _jumpToLatest() {final id = c.selectedId;_focus.requestFocus();@@ -435,6 +537,7 @@ class _SuperTabViewState extends State<SuperTabView>_unregisterDial?.call();_dial.cancel();_litTimer?.cancel();+ _historyRetry?.cancel();_composer.dispose();_mentionIndex.dispose();_dismissedMention.dispose();@@ -2453,9 +2556,7 @@ class _SuperTabViewState extends State<SuperTabView>final latestOwn = c.messages(c.selectedId).reversed- .where(- (m) => !m.fromAgent && !m.fromTerminal && m.authorId == c.accountId,- )+ .where(c.isOwn).firstOrNull;final messages = _shownMessages(c.selectedId);final entries = superTabTranscriptEntries(messages);@@ -2486,6 +2587,8 @@ class _SuperTabViewState extends State<SuperTabView>previous?.createdAt?.toLocal(),))_date(time),+ if (message.id == _unread.lineAt(c.selectedId))+ SuperTabNewMessagesLine(key: _unread.key),// The message itself is kept in place: its// date moves above earlier ones as they come._BuiltRow(@@ -2749,6 +2852,17 @@ class _SuperTabViewState extends State<SuperTabView>),),),+ if (_unread.away && _unread.lineAt(c.selectedId) != null)+ Positioned(+ top: grid.AppDesktop.controlGap,+ left: grid.AppDesktop.panelPadding,+ right: grid.AppDesktop.panelPadding,+ child: Center(+ child: SuperTabJumpToUnread(+ onPressed: () => _revealUnreadLine(c.selectedId),+ ),+ ),+ ),if (newCount > 0 || back)Positioned(bottom: 12,@@ -3005,6 +3119,11 @@ class _SuperTabViewState extends State<SuperTabView>return KeyEventResult.handled;}}+ if (event is KeyDownEvent &&+ event.logicalKey == LogicalKeyboardKey.escape &&+ _readAll()) {+ return KeyEventResult.handled;+ }if (_focus.hasFocus &&event is KeyDownEvent &&event.logicalKey == LogicalKeyboardKey.enter &&diff --git a/desktop/test/screenshots/new-messages/unread-line-dark.png b/desktop/test/screenshots/new-messages/unread-line-dark.pngnew file mode 100644index 000000000..157d5d4bbBinary files /dev/null and b/desktop/test/screenshots/new-messages/unread-line-dark.png differdiff --git a/desktop/test/screenshots/new-messages/unread-line-light.png b/desktop/test/screenshots/new-messages/unread-line-light.pngnew file mode 100644index 000000000..4816b140eBinary files /dev/null and b/desktop/test/screenshots/new-messages/unread-line-light.png differdiff --git a/desktop/test/screenshots/new-messages/unread-pill-dark.png b/desktop/test/screenshots/new-messages/unread-pill-dark.pngnew file mode 100644index 000000000..539ef9fcdBinary files /dev/null and b/desktop/test/screenshots/new-messages/unread-pill-dark.png differdiff --git a/desktop/test/screenshots/new-messages/unread-pill-light.png b/desktop/test/screenshots/new-messages/unread-pill-light.pngnew file mode 100644index 000000000..0fea67b91Binary files /dev/null and b/desktop/test/screenshots/new-messages/unread-pill-light.png differdiff --git a/desktop/test/super_tab_load_back_test.dart b/desktop/test/super_tab_load_back_test.dartnew file mode 100644index 000000000..b3047d41c--- /dev/null+++ b/desktop/test/super_tab_load_back_test.dart@@ -0,0 +1,160 @@+import 'dart:async';++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/controller.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/super_tab_fixture.dart';++/// Reading back to a read mark many pages behind the latest (review of #2131,+/// round 2): what a poll or a failed read does meanwhile.++const _line = ValueKey('super-new-messages-line');++/// [count] messages in the Lead conversation from the Lead agent, pages of 20,+/// read up to message 5 on another device.+ConversationServer _server(int count) {+ final server = ConversationServer()..messagePage = 20;+ for (var i = 1; i <= count; i++) {+ _fromLead(server, 'Update $i');+ }+ return server..markReadElsewhere('lead', 5);+}++void _fromLead(ConversationServer server, String text) {+ server.append(text);+ server.messages.last['author'] = {+ 'kind': 'agent',+ 'id': 'lead-agent',+ 'name': 'Lead',+ };+}++/// A controller of [server] whose reads of a path containing a key of [gates]+/// wait for that gate (completing [asked]'s entry for it as they set out),+/// and whose reads of one in [fail] fail once (each in [down], every time,+/// counted in [refused]).+SuperTabController _controller(+ ConversationServer server, {+ Map<String, Completer<void>> gates = const {},+ Map<String, Completer<void>> asked = const {},+ Set<String> fail = const {},+ Set<String> down = const {},+ List<String>? refused,+}) => SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ request: (method, path, {body}) async {+ for (final MapEntry(:key, :value) in [...gates.entries]) {+ if (!path.contains(key)) continue;+ if (asked[key] case final told? when !told.isCompleted) told.complete();+ await value.future;+ }+ if (down.any(path.contains)) {+ refused?.add(path);+ throw StateError('Offline');+ }+ if (fail.any(path.contains)) {+ fail.removeWhere(path.contains);+ throw StateError('Offline');+ }+ return server.request(method, path, body: body);+ },+ save: server.save,+ pollInterval: Duration.zero,+);++void main() {+ test('a poll that set out before the read back lands after it does not '+ 'join across the gap, and newer history stays marked', () async {+ final server = _server(200);+ final gates = {'after=5': Completer<void>()};+ final asked = {'after=5': Completer<void>()};+ final c = _controller(server, gates: gates, asked: asked);+ addTearDown(c.dispose);+ await c.refresh();+ final back = c.loadBackTo('lead', 5);+ // The page after the mark is on its way; a poll sets out from the newest+ // held message meanwhile.+ await asked['after=5']!.future;+ gates['after=200'] = Completer<void>();+ asked['after=200'] = Completer<void>();+ _fromLead(server, 'Update 201');+ final poll = c.loadMessages('lead');+ await asked['after=200']!.future;+ gates['after=5']!.complete();+ await back;+ gates['after=200']!.complete();+ await poll;+ final held = c.messages('lead').map((m) => m.sequence).toList();+ expect(held.first, 6);+ expect(held, isNot(contains(201)));+ // Every held message follows the one before it: no gap inside.+ expect(held, [for (var i = 6; i < 6 + held.length; i++) i]);+ expect(c.hasNewer('lead'), isTrue);+ });++ Future<SuperTabController> show(+ WidgetTester tester,+ SuperTabController c,+ ) async {+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(c.dispose);+ return c;+ }++ testWidgets('a failed read back leaves the line unplaced and nothing '+ 'marked read, and the next read places it at the first unread', (+ tester,+ ) async {+ final server = _server(200);+ final c = await show(tester, _controller(server, fail: {'after=5'}));+ expect(find.byKey(_line), findsNothing);+ expect(c.readMark('lead'), 5);+ expect(server.readMarkPosts, isEmpty);+ // Tried again shortly, and this time the page arrives.+ await tester.pump(const Duration(seconds: 5));+ await tester.pumpAndSettle();+ expect(find.byKey(_line), findsOneWidget);+ expect(+ tester.getTopLeft(find.byKey(_line)).dy,+ lessThan(tester.getTopLeft(find.text('Update 6')).dy),+ );+ expect(c.readMark('lead'), 5);+ });++ testWidgets('a read back that keeps failing is tried three times, then '+ 'left: no line, nothing marked read', (tester) async {+ final server = _server(200);+ final refused = <String>[];+ final c = await show(+ tester,+ _controller(server, down: {'after=5'}, refused: refused),+ );+ for (var i = 0; i < 4; i++) {+ await tester.pump(const Duration(seconds: 5));+ await tester.pumpAndSettle();+ }+ expect(refused, hasLength(3));+ expect(find.byKey(_line), findsNothing);+ expect(c.readMark('lead'), 5);+ expect(server.readMarkPosts, isEmpty);+ });+}diff --git a/desktop/test/super_tab_new_messages_shots_test.dart b/desktop/test/super_tab_new_messages_shots_test.dartnew file mode 100644index 000000000..82da42163--- /dev/null+++ b/desktop/test/super_tab_new_messages_shots_test.dart@@ -0,0 +1,97 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/view.dart';++import 'box_render_preview_test.dart' show loadPreviewFonts;+import 'support/super_tab_fixture.dart';++/// Set to a folder to write the PR's screenshots there.+final shots = Platform.environment['SUPER_TAB_UNREAD_SHOTS'];++const _updates = [+ 'Reading the offline queue before the reconnect.',+ 'The reconnect keeps every queued edit in order.',+ 'Two devices editing at once settle on the newest edit.',+ 'Pushed the branch; the checks are running.',+];++/// The chat opened at its New messages line, and scrolled to the end with the+/// pill that jumps back to it.+void main() {+ setUpAll(() async {+ if (shots != null) await loadPreviewFonts();+ });++ for (final brightness in Brightness.values) {+ testWidgets('screenshots for review (${brightness.name})', (tester) async {+ final picture = GlobalKey();+ final server = ConversationServer();+ for (var i = 1; i <= 80; i++) {+ server.append('${_updates[i % _updates.length]} ($i)');+ server.messages.last['author'] = {+ 'kind': 'agent',+ 'id': 'lead-agent',+ 'name': 'Lead',+ };+ }+ server.markReadElsewhere('lead', 30);+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);+ await tester.binding.setSurfaceSize(const Size(1200, 760));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) =>+ RepaintBoundary(key: picture, child: child),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(find.byKey(const ValueKey('super-new-messages-line')), findsOne);++ Future<void> shot(String name) async {+ if (shots == null) return;+ await tester.runAsync(() async {+ final boundary =+ picture.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 1.5);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(shots!).create(recursive: true);+ await File('$shots/unread-$name-${brightness.name}.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ }++ await shot('line');+ final list = tester+ .widget<ScrollView>(+ find.byKey(const PageStorageKey('super-messages-tab-lead')),+ )+ .controller!+ .position;+ list.jumpTo(list.maxScrollExtent);+ await tester.pumpAndSettle();+ expect(find.byKey(const ValueKey('super-jump-unread')), findsOne);+ await shot('pill');+ });+ }+}diff --git a/desktop/test/super_tab_new_messages_test.dart b/desktop/test/super_tab_new_messages_test.dartnew file mode 100644index 000000000..6b5f9df19--- /dev/null+++ b/desktop/test/super_tab_new_messages_test.dart@@ -0,0 +1,318 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.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/view.dart';++import 'support/super_tab_fixture.dart';++const _line = ValueKey('super-new-messages-line');+const _jump = ValueKey('super-jump-unread');++/// [count] messages in the Lead conversation from the Lead agent.+ConversationServer _server(int count) {+ final server = ConversationServer();+ for (var i = 1; i <= count; i++) {+ _fromLead(server, 'Update $i');+ }+ return server;+}++void _fromLead(ConversationServer server, String text) {+ server.append(text);+ server.messages.last['author'] = {+ 'kind': 'agent',+ 'id': 'lead-agent',+ 'name': 'Lead',+ };+}++void main() {+ Future<SuperTabController> show(+ WidgetTester tester,+ ConversationServer server,+ ) async {+ final c = server.controller();+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(c.dispose);+ return c;+ }++ ScrollPosition scroll(WidgetTester tester) => tester+ .widget<ScrollView>(+ find.byKey(const PageStorageKey('super-messages-tab-lead')),+ )+ .controller!+ .position;++ /// Whether [finder]'s top edge is inside the message list's viewport.+ bool onScreen(WidgetTester tester, Finder finder) {+ if (finder.evaluate().isEmpty) return false;+ final list = tester.getRect(+ find.byKey(const PageStorageKey('super-messages-tab-lead')),+ );+ final top = tester.getTopLeft(finder).dy;+ return top >= list.top && top < list.bottom;+ }++ testWidgets('opens at a New messages line just above the first unread '+ 'message', (tester) async {+ final server = _server(40)..markReadElsewhere('lead', 30);+ await show(tester, server);+ expect(find.byKey(_line), findsOneWidget);+ // Words as well as colour.+ expect(+ find.descendant(+ of: find.byKey(_line),+ matching: find.text('New messages'),+ ),+ findsOneWidget,+ );+ expect(onScreen(tester, find.byKey(_line)), isTrue);+ expect(+ tester.getTopLeft(find.byKey(_line)).dy,+ lessThan(tester.getTopLeft(find.text('Update 31')).dy),+ );+ expect(+ tester.getTopLeft(find.byKey(_line)).dy,+ greaterThan(tester.getTopLeft(find.text('Update 30')).dy),+ );+ // The newest messages are below, not where the view opened.+ expect(scroll(tester).extentAfter, greaterThan(40));+ });++ testWidgets('the reader\'s own message after the mark is not unread', (+ tester,+ ) async {+ final server = _server(30)..markReadElsewhere('lead', 28);+ server.append('My own answer');+ _fromLead(server, 'After my answer');+ await show(tester, server);+ expect(+ tester.getTopLeft(find.byKey(_line)).dy,+ greaterThan(tester.getTopLeft(find.text('My own answer')).dy),+ );+ expect(+ tester.getTopLeft(find.byKey(_line)).dy,+ lessThan(tester.getTopLeft(find.text('After my answer')).dy),+ );+ });++ /// [server]'s next message as a reply in message 5's thread, [inChat] when+ /// also sent to the chat.+ void threadReply(+ ConversationServer server,+ String text, {+ bool inChat = false,+ }) {+ _fromLead(server, text);+ server.messages.last+ ..['thread'] = 'message-5'+ ..['alsoInChat'] = inChat;+ }++ testWidgets('a reply that lives only in its thread never gets the line; '+ 'one also sent to the chat does', (tester) async {+ final server = _server(30)..markReadElsewhere('lead', 30);+ threadReply(server, 'Thread-only reply');+ threadReply(server, 'Reply also in the chat', inChat: true);+ await show(tester, server);+ // The chat no longer lists the thread's own reply (its thread does).+ expect(find.text('Thread-only reply'), findsNothing);+ expect(+ tester.getTopLeft(find.byKey(_line)).dy,+ greaterThan(tester.getTopLeft(find.text('Update 30')).dy),+ );+ expect(+ tester.getTopLeft(find.byKey(_line)).dy,+ lessThan(tester.getTopLeft(find.text('Reply also in the chat')).dy),+ );+ });++ testWidgets('only thread replies past the mark: no line and no pill', (+ tester,+ ) async {+ final server = _server(30)..markReadElsewhere('lead', 30);+ threadReply(server, 'Thread-only reply');+ final c = await show(tester, server);+ expect(find.byKey(_line), findsNothing);+ scroll(tester).jumpTo(0);+ await tester.pumpAndSettle();+ expect(find.byKey(_jump), findsNothing);+ expect(c.unread(c.selected!), isFalse);+ });++ testWidgets('a conversation never read anywhere opens at its end, with no '+ 'line', (tester) async {+ await show(tester, _server(40));+ expect(find.byKey(_line), findsNothing);+ expect(scroll(tester).extentAfter, lessThan(40));+ });++ // Review of #2131, item 1: the first unread is older than the latest page.+ testWidgets('a first unread a few pages back is loaded, and the view opens '+ 'at it', (tester) async {+ final server = _server(80)..messagePage = 20;+ server.markReadElsewhere('lead', 5);+ final c = await show(tester, server);+ expect(c.messages('lead').any((m) => m.id == 'message-6'), isTrue);+ expect(onScreen(tester, find.text('Update 6')), isTrue);+ expect(+ tester.getTopLeft(find.byKey(_line)).dy,+ lessThan(tester.getTopLeft(find.text('Update 6')).dy),+ );+ // Nothing was marked read while the history loaded.+ expect(c.readMark('lead'), 5);+ });++ testWidgets('a first unread many pages back opens at its page, not the '+ 'whole history', (tester) async {+ final server = _server(200)..messagePage = 20;+ server.markReadElsewhere('lead', 5);+ final reads = <String>[];+ server.onRead = reads.add;+ final c = await show(tester, server);+ expect(onScreen(tester, find.text('Update 6')), isTrue);+ expect(+ tester.getTopLeft(find.byKey(_line)).dy,+ lessThan(tester.getTopLeft(find.text('Update 6')).dy),+ );+ // Bounded: the latest page, three back, then the page after the mark;+ // the middle of the gap is never read.+ expect(reads.where((r) => r.contains('before=121')), isEmpty);+ expect(c.messages('lead').any((m) => m.id == 'message-100'), isFalse);+ expect(c.hasNewer('lead'), isTrue);+ expect(c.readMark('lead'), 5);+ });++ // Review of #2131, item 2.+ testWidgets('the reader\'s own reply in a thread does not read the chat', (+ tester,+ ) async {+ final server = _server(30)..markReadElsewhere('lead', 28);+ server.append('My thread reply');+ server.messages.last['thread'] = 'message-5';+ await show(tester, server);+ expect(find.byKey(_line), findsOneWidget);+ expect(+ tester.getTopLeft(find.byKey(_line)).dy,+ lessThan(tester.getTopLeft(find.text('Update 29')).dy),+ );+ // Seen at the end of the list, under the line, they are read as any+ // conversation read to its end is; the line stays for this visit.+ await tester.pump(const Duration(seconds: 5));+ expect(find.byKey(_line), findsOneWidget);+ });++ testWidgets('no line when everything is read', (tester) async {+ final server = _server(10)..markReadElsewhere('lead', 10);+ await show(tester, server);+ expect(find.byKey(_line), findsNothing);+ expect(find.byKey(_jump), findsNothing);+ });++ testWidgets('the line stays where it was while new messages arrive', (+ tester,+ ) async {+ final server = _server(40)..markReadElsewhere('lead', 30);+ final c = await show(tester, server);+ _fromLead(server, 'Update 41');+ _fromLead(server, 'Update 42');+ await c.refresh();+ await tester.pumpAndSettle();+ expect(find.byKey(_line), findsOneWidget);+ expect(+ tester.getTopLeft(find.byKey(_line)).dy,+ lessThan(tester.getTopLeft(find.text('Update 31')).dy),+ );+ expect(+ tester.getTopLeft(find.byKey(_line)).dy,+ greaterThan(tester.getTopLeft(find.text('Update 30')).dy),+ );+ });++ testWidgets('scrolled away from the line, a pill jumps back to it', (+ tester,+ ) async {+ final server = _server(60)..markReadElsewhere('lead', 20);+ await show(tester, server);+ expect(find.byKey(_jump), findsNothing);+ final position = scroll(tester);+ position.jumpTo(position.maxScrollExtent);+ await tester.pumpAndSettle();+ expect(onScreen(tester, find.byKey(_line)), isFalse);+ expect(find.byKey(_jump), findsOneWidget);+ expect(find.text('Jump to first unread'), findsOneWidget);+ await tester.tap(find.byKey(_jump));+ await tester.pumpAndSettle();+ expect(onScreen(tester, find.byKey(_line)), isTrue);+ expect(find.byKey(_jump), findsNothing);+ });++ testWidgets('Esc marks the conversation read and clears the line', (+ tester,+ ) async {+ final server = _server(40)..markReadElsewhere('lead', 30);+ final c = await show(tester, server);+ expect(c.unread(c.selected!), isTrue);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(find.byKey(_line), findsNothing);+ expect(c.unread(c.selected!), isFalse);+ expect(server.readMarkPosts.last, {+ 'conversationId': 'lead',+ 'sequence': 40,+ });+ });++ testWidgets('the sidebar\'s bold follows the mark kept on the server', (+ tester,+ ) async {+ final server = _server(2);+ server.append('Elsewhere', conversationId: 'offline');+ server.messages.last['author'] = {+ 'kind': 'agent',+ 'id': 'worker',+ 'name': 'Worker',+ };+ final c = await show(tester, server);+ FontWeight? weight() => tester+ .widget<RichText>(+ find.descendant(+ of: find.byKey(const ValueKey('super-group-offline')),+ matching: find.byWidgetPredicate(+ (widget) =>+ widget is RichText &&+ widget.text.toPlainText() == 'Offline editing',+ ),+ ),+ )+ .text+ .style+ ?.fontWeight;+ await tester.tap(find.byKey(const ValueKey('super-project-toggle-lead')));+ await tester.pumpAndSettle();+ expect(weight(), grid.AppFont.semibold);+ // Read on another device.+ server.markReadElsewhere('offline', 3);+ await c.refresh();+ await tester.pumpAndSettle();+ expect(weight(), isNot(grid.AppFont.semibold));+ });+}diff --git a/desktop/test/super_tab_read_marks_test.dart b/desktop/test/super_tab_read_marks_test.dartnew file mode 100644index 000000000..f50e375cb--- /dev/null+++ b/desktop/test/super_tab_read_marks_test.dart@@ -0,0 +1,216 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/model.dart';+import 'package:harness/super_tabs/parts.dart';++import 'support/super_tab_fixture.dart';++/// A message from the Lead agent, so it is never the reader's own.+void fromLead(ConversationServer server, String text) {+ server.append(text);+ server.messages.last['author'] = {+ 'kind': 'agent',+ 'id': 'lead-agent',+ 'name': 'Lead',+ };+}++void main() {+ Future<SuperTabController> open(ConversationServer server) async {+ final c = server.controller();+ addTearDown(() async {+ await c.flush();+ c.dispose();+ });+ await c.refresh();+ return c;+ }++ test('a conversation read on another device is read here too', () async {+ final server = ConversationServer();+ fromLead(server, 'First update');+ fromLead(server, 'Second update');+ final c = await open(server);+ c.select('offline');+ expect(c.unread(c.snapshot!.conversation('lead')!), isTrue);+ server.markReadElsewhere('lead', 2);+ await c.refresh();+ expect(c.unread(c.snapshot!.conversation('lead')!), isFalse);+ expect(c.readMark('lead'), 2);+ // A later message is unread again, past the other device's mark.+ fromLead(server, 'Third update');+ await c.refresh();+ expect(c.unread(c.snapshot!.conversation('lead')!), isTrue);+ });++ test('a reply that lives only in its thread leaves the chat read; one also '+ 'sent to the chat counts once', () async {+ final server = ConversationServer()..threads = true;+ final lead = (server.state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((g) => g['id'] == 'lead');+ fromLead(server, 'Root');+ // As the threads backend keeps it: the newest message the chat shows.+ lead['lastMainSequence'] = server.revision;+ final c = await open(server);+ await c.loadMessages('lead');+ c.markRead('lead', through: 1);+ fromLead(server, 'Thread-only reply');+ server.messages.last['thread'] = 'message-1';+ await c.refresh();+ await c.loadMessages('lead');+ expect(c.unread(c.selected!), isFalse);+ expect(c.unreadCount(c.selected!), 0);+ fromLead(server, 'Also in the chat');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['alsoInChat'] = true;+ lead['lastMainSequence'] = server.revision;+ await c.refresh();+ await c.loadMessages('lead');+ expect(c.unread(c.selected!), isTrue);+ expect(c.unreadCount(c.selected!), 1);+ // The mark still moves over the thread's replies.+ c.markRead('lead');+ await pumpEventQueue();+ expect(server.readMarkPosts.last, {+ 'conversationId': 'lead',+ 'sequence': 3,+ });+ });++ test(+ 'another person\'s marks never mark the reader\'s conversations read',+ () async {+ final server = ConversationServer();+ fromLead(server, 'Update');+ final c = await open(server);+ c.select('offline');+ server.markReadElsewhere('lead', 1, reader: 'peer');+ await c.refresh();+ expect(c.unread(c.snapshot!.conversation('lead')!), isTrue);+ },+ );++ test('a chat not loaded here stays unbolded for a reply only in its '+ 'thread, past the mark another device kept', () async {+ final server = ConversationServer()..threads = true;+ final offline = (server.state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((g) => g['id'] == 'offline');+ server.append('Root', conversationId: 'offline');+ offline['lastMainSequence'] = server.revision;+ server.markReadElsewhere('offline', server.revision);+ final c = await open(server);+ // Its messages were never read on this device.+ expect(c.messages('offline'), isEmpty);+ server.append('Only in the thread.', conversationId: 'offline');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['author'] = {'kind': 'agent', 'id': 'lead-agent', 'name': 'Lead'};+ await c.refresh();+ SuperTabConversation group() => c.snapshot!.conversation('offline')!;+ expect(c.messages('offline'), isEmpty);+ expect(c.unread(group()), isFalse);+ // A reply also sent to the chat makes it bold.+ server.append('For everyone.', conversationId: 'offline');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['alsoInChat'] = true;+ offline['lastMainSequence'] = server.revision;+ await c.refresh();+ expect(c.unread(group()), isTrue);+ });++ test('reading sends the mark forward once, never a lower one', () async {+ final server = ConversationServer();+ fromLead(server, 'One');+ fromLead(server, 'Two');+ final c = await open(server);+ await c.loadMessages('lead');+ c.markRead('lead', through: 1);+ await pumpEventQueue();+ c.markRead('lead', through: 1);+ await pumpEventQueue();+ c.markRead('lead', through: 2);+ await pumpEventQueue();+ c.markRead('lead', through: 1);+ await pumpEventQueue();+ expect(server.readMarkPosts, [+ {'conversationId': 'lead', 'sequence': 1},+ {'conversationId': 'lead', 'sequence': 2},+ ]);+ });++ test('offline, this device\'s mark still reads the conversation, and the '+ 'mark is sent again on the next read', () async {+ final server = ConversationServer();+ fromLead(server, 'One');+ final c = await open(server);+ await c.loadMessages('lead');+ server.failReadMarks = true;+ c.markRead('lead', through: 1);+ await pumpEventQueue();+ expect(c.unread(c.selected!), isFalse);+ server.failReadMarks = false;+ c.markRead('lead', through: 1);+ await pumpEventQueue();+ expect(server.readMarkPosts, [+ {'conversationId': 'lead', 'sequence': 1},+ {'conversationId': 'lead', 'sequence': 1},+ ]);+ await c.refresh();+ expect(c.unread(c.selected!), isFalse);+ });++ group('the parts held on this device', () {+ Map<String, dynamic> group(+ String id,+ int version, {+ bool deleted = false,+ }) => {+ 'key': id,+ 'version': version,+ if (deleted) 'deleted': true else 'data': {'id': id},+ };+ Map<String, dynamic> load(Map<String, int> marks) => {+ 'format': superTabReadFormat,+ 'cursor': 'c1',+ 'epoch': 1,+ 'head': {'key': 'head', 'version': 1, 'data': <String, dynamic>{}},+ 'groups': [group('lead', 1), group('web', 1)],+ 'derived': {'readMarks': marks},+ };+ Map<String, dynamic> changes(+ Map<String, int> marks, {+ List<Map<String, dynamic>> groups = const [],+ }) => {+ 'format': superTabReadFormat,+ 'reload': false,+ 'cursor': 'c2',+ 'epoch': 1,+ 'head': null,+ 'groups': groups,+ 'derived': {'readMarks': marks},+ };++ test('keep the highest mark each read sent, across a restart', () {+ final parts = SuperTabParts.firstLoad(load({'lead': 4, 'web': 2}));+ // A change read sends only the marks that moved; an older copy the+ // cursor's overlap sends again never lowers one.+ expect(parts.apply(changes({'web': 9})).changed, isTrue);+ expect(parts.apply(changes({'lead': 3})).changed, isFalse);+ expect(parts.state['readMarks'], {'lead': 4, 'web': 9});+ final restored = SuperTabParts.fromJson(+ SuperTabParts.drawnOnly(parts.toJson()),+ );+ expect(restored.state['readMarks'], {'lead': 4, 'web': 9});+ });++ test('drop the mark of a conversation that is gone', () {+ final parts = SuperTabParts.firstLoad(load({'lead': 4, 'web': 2}));+ parts.apply(changes({}, groups: [group('web', 2, deleted: true)]));+ expect(parts.state['readMarks'], {'lead': 4});+ });+ });+}diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex 14fa808b1..1b59a9da1 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -79,6 +79,7 @@ class SwarmPartsBackend {'decisionsDigest','otherProjectsWork','githubApp',+ 'readMarks',}.contains(entry.key))entry.key: entry.value,};@@ -141,7 +142,7 @@ class SwarmPartsBackend {String _cursor(int tick) => 'c${tick}e$epoch';- Map<String, dynamic> _derived(Map<String, dynamic> state) => {+ Map<String, dynamic> _derived(Map<String, dynamic> state, String? reader) => {'agents': <String, dynamic>{},'machines': <String, dynamic>{},if (state['mentionsWaiting'] != null)@@ -155,6 +156,9 @@ class SwarmPartsBackend {if (state['otherProjectsWork'] != null)'otherProjectsWork': state['otherProjectsWork'],if (state['avatars'] != null) 'avatars': state['avatars'],+ // 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),};List<MapEntry<String, _HeldPart>> _ordered() =>@@ -217,7 +221,7 @@ class SwarmPartsBackend {'githubApp': state['githubApp'] ?? false,'head': _envelope('head:head', _parts['head:head']!),for (final kind in _kinds) kind: <dynamic>[],- 'derived': _derived(state),+ 'derived': _derived(state, reader),};for (final entry in _ordered()) {final kind = entry.key.substring(0, entry.key.indexOf(':'));@@ -247,7 +251,7 @@ class SwarmPartsBackend {'epoch': epoch,'head': null,for (final kind in _kinds) kind: <dynamic>[],- 'derived': _derived(state),+ 'derived': _derived(state, reader),};for (final entry in _ordered()) {if (entry.value.changedAt <= since) continue;@@ -493,6 +497,57 @@ class ConversationServer {)['lastMessageSequence'] = revision;}+ /// The read marks this device sent, in order: {conversationId, sequence}.+ final readMarkPosts = <Map<String, dynamic>>[];++ /// Every read-mark write fails, as offline.+ bool failReadMarks = false;++ /// A read mark [reader] made on another device, as the backend keeps it.+ void markReadElsewhere(+ String conversationId,+ int sequence, {+ String reader = 'owner',+ }) => _keepReadMark(conversationId, sequence, reader);++ int _keepReadMark(String conversationId, int sequence, String reader) {+ final marks =+ ((state['readMarks'] ??= <String, dynamic>{}) as Map).putIfAbsent(+ reader,+ () => <String, dynamic>{},+ ) as Map;+ final kept = max(marks[conversationId] as int? ?? 0, sequence);+ return marks[conversationId] = kept;+ }++ /// The backend's read-mark route (readMarks.ts): forward only, never past+ /// the conversation's newest message.+ Map<String, dynamic> _markRead(+ String conversationId,+ int sequence,+ String? reader,+ ) {+ readMarkPosts.add({'conversationId': conversationId, 'sequence': sequence});+ if (failReadMarks) {+ throw const SuperTabFailure('OFFLINE', 'No connection.', statusCode: 503);+ }+ final newest =+ (state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere(+ (g) => g['id'] == conversationId,+ )['lastMessageSequence']+ as int? ??+ 0;+ return {+ 'sequence': _keepReadMark(+ conversationId,+ min(sequence, newest),+ reader ?? 'owner',+ ),+ };+ }+/// The summaries of the threads [page]'s rows are in, as the backend's/// pages carry them (threads.ts).List<Map<String, dynamic>> _threads(@@ -663,6 +718,12 @@ class ConversationServer {Map<String, dynamic>? body,}) async {final reader = Zone.current[_reader] as String?;+ final read = method == 'POST'+ ? RegExp(r'/conversations/([^/]+)/read$').firstMatch(path)+ : null;+ if (read != null) {+ return _markRead(read.group(1)!, body!['sequence'] as int, reader);+ }if (method == 'POST') {posts.add(Map<String, dynamic>.from(body!));if (reject) {