Skip to content

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.

Merge batch 11-04 b1532: #2962 #2961 #2959 (#2972)

0xken1578712a7973cb
diff --git a/backend/integration/superTabFollowedThreads.test.ts b/backend/integration/superTabFollowedThreads.test.ts
index 9768fb794..d4a46002b 100644
--- a/backend/integration/superTabFollowedThreads.test.ts
+++ b/backend/integration/superTabFollowedThreads.test.ts
@@ -560,6 +560,72 @@ describe('a person\'s followed threads (GET /threads)', () => {
expect(reply.body.data.read).toHaveLength(MAX_READ_THREADS)
expect(reply.body.data.more).toBe(true)
}, 120_000)
+
+ // Ken's scan of 11-04 (task #2768): the unread threads' member check read each thread's newest 100 rows before the mark in
+ // one $or branch per thread, and long threads sent it to one $unionWith branch per thread. It reads their summaries now.
+ /** Web: 60 roots of the owner's; the first 10 hold 300 worker replies. Peer replied early in every third thread (i % 3 == 0)
+ * and is tagged early in the next (i % 3 == 1); in a long thread both are more than 100 rows before the mark. Peer read the
+ * chat, then each thread got one new worker reply. */
+ async function memberScene() {
+ const s = await scene()
+ const roots = await insert(s.tabId, s.web, Array.from({ length: 60 }, (_, i) => ({ text: `Member root ${i}`, author: personAuthor(owner) })))
+ await insert(s.tabId, s.web, roots.flatMap((thread, i) => i % 3 === 0 ? [{ text: `Peer early ${i}`, author: personAuthor(peer), thread }]
+ : i % 3 === 1 ? [{ text: `Tags peer ${i}`, author: personAuthor(owner), thread, mentions: [peer.sub] }] : []))
+ for (let batch = 0; batch < 3; batch++) {
+ await insert(s.tabId, s.web, Array.from({ length: 1000 }, (_, i) => ({ text: `History ${batch}.${i}`, author: agentAuthor(s.worker), thread: roots[i % 10]! })))
+ }
+ await markRead(s.tabId, s.web, await newestIn(s.tabId, s.web), peer)
+ await insert(s.tabId, s.web, roots.map(thread => ({ text: 'New reply', author: agentAuthor(s.worker), thread })))
+ return { ...s, roots, member: roots.filter((_, i) => i % 3 !== 2) }
+ }
+
+ it('counts the person in a thread they wrote or were tagged in long before their mark, once the Swarm\'s summaries are backfilled', async () => {
+ const s = await memberScene()
+ // Before the backfill: each thread's newest 100 rows before the mark, as before, so a long thread's early rows are not seen.
+ const long = new Set(s.roots.slice(0, 10))
+ const before = (await threads(s.tabId, peer)).body.data
+ expect(before.unread.map((t: any) => t.rootId).sort()).toEqual(s.member.filter(r => !long.has(r)).sort())
+ await backfillThreads(db, Date.now())
+ resetThreadsReads()
+ const after = (await threads(s.tabId, peer)).body.data
+ expect(after.unread.map((t: any) => t.rootId).sort()).toEqual([...s.member].sort())
+ // Every thread listed before is listed the same way after.
+ expect(after.unread.filter((t: any) => !long.has(t.rootId))).toEqual(before.unread)
+ }, 120_000)
+
+ it('learns whether the person is in each unread thread from its summary, in one read, never from its messages', async () => {
+ const s = await memberScene()
+ await backfillThreads(db, Date.now())
+ const { reply, rows } = await profiledThreads(s.tabId)
+ const messages = rows.filter(r => r.ns.endsWith('.SuperTabMessage')), summaries = rows.filter(r => r.ns.endsWith('.SuperTabThread'))
+ console.info(`threads cost, 60 unread candidates (10 of 300 rows): ${rows.filter(r => r.op !== 'getmore').length} reads\n` +
+ rows.map(r => ` ${r.ns.split('.').at(-1)} ${r.op} ${(r.planSummary ?? '').slice(0, 80)} docs=${r.docsExamined ?? 0}`).join('\n'))
+ expect(rows.filter(r => r.planSummary === 'COLLSCAN')).toEqual([])
+ // No message read by the thread index: the chat's rows past the mark, and the 60 roots by id.
+ expect(messages.filter(r => /thread/.test(r.planSummary ?? '')), JSON.stringify(messages)).toEqual([])
+ expect(messages.reduce((n, r) => n + (r.docsExamined ?? 0), 0)).toBeLessThanOrEqual(2 * 61)
+ // The 60 candidates' summaries in one read by id, one small row each.
+ expect(summaries.filter(r => r.op !== 'getmore')).toHaveLength(1)
+ expect(summaries[0]!.planSummary).toMatch(/^IXSCAN \{ _id: 1 \}/)
+ expect(summaries.reduce((n, r) => n + (r.docsExamined ?? 0), 0)).toBeLessThanOrEqual(60)
+ expect(reply.body.data.unread).toHaveLength(s.member.length)
+ }, 120_000)
+
+ it('keeps reading a Swarm Buddy chat\'s rows to learn whether the person is in a thread: its summary cannot hide a lost project\'s row', async () => {
+ let chat = ''
+ const s = await scene(f => f.edit(state => { chat = openSwarmBuddyChat(state, state.people.find(p => p.id === peer.sub)!).id }))
+ const [root] = await insert(s.tabId, chat, [{ text: 'Buddy root', author: agentAuthor('peer-buddy') }])
+ // Peer's own reply in a session of the Secret project, which they do not read: it must not make them a member.
+ await insert(s.tabId, chat, [{ text: 'Secret session words', author: personAuthor(peer), thread: root!, buddySession: true, buddyProject: s.secret }])
+ await markRead(s.tabId, chat, await newestIn(s.tabId, chat), peer)
+ await insert(s.tabId, chat, [{ text: 'Buddy reply', author: agentAuthor('peer-buddy'), thread: root! }])
+ expect((await threads(s.tabId, peer)).body.data.unread).toEqual([])
+ await backfillThreads(db, Date.now())
+ resetThreadsReads()
+ expect((await threads(s.tabId, peer)).body.data.unread).toEqual([])
+ resetInboxReads()
+ expect((await inbox(s.tabId, peer)).body.data.threads).toEqual([])
+ })
})
describe('a thread the person is tagged in, in a chat they never opened (GET /threads)', () => {
diff --git a/backend/src/superTabs/pageReads.ts b/backend/src/superTabs/pageReads.ts
index a35e73566..166be500f 100644
--- a/backend/src/superTabs/pageReads.ts
+++ b/backend/src/superTabs/pageReads.ts
@@ -335,7 +335,7 @@ const BACKFILL_CHECK_MS = 60_000
const backfilled = new Map<string, { done: boolean; at: number }>()
/** Whether the Swarm's thread summaries are backfilled (threadBackfill.ts), as this process read it in the last minute. */
-async function threadsBackfilled(tx: Transaction, tabId: string): Promise<boolean> {
+export async function threadsBackfilled(tx: Transaction, tabId: string): Promise<boolean> {
const known = backfilled.get(tabId), now = Date.now()
if (known && now - known.at < BACKFILL_CHECK_MS) return known.done
const done = !!await tx.superTabThreadBackfill.findUnique({ where: { id: tabId }, select: { id: true } })
diff --git a/backend/src/superTabs/read/inbox.ts b/backend/src/superTabs/read/inbox.ts
index 2b56e1269..2b5f086e8 100644
--- a/backend/src/superTabs/read/inbox.ts
+++ b/backend/src/superTabs/read/inbox.ts
@@ -13,7 +13,8 @@
*
* Cost: every message read is bounded by an index range and a limit: the newest UNREAD_SCAN rows past the mark in at most
* THREAD_CHATS chats; the newest UNREAD_SCAN rows past their own mark in at most BEHIND_THREADS threads; the roots of the
- * newest CANDIDATE_THREADS threads; MEMBER_SCAN rows before the mark of a thread whose newer rows do not show the person in it;
+ * newest CANDIDATE_THREADS threads; the summaries of the threads whose newer rows do not show the person in it, by root id in
+ * one read (namedInThreads; a Swarm Buddy chat's, or any before the Swarm's backfill, MEMBER_SCAN rows before the mark each);
* one row (LATEST_SCAN for an older chat) at each of LATEST_CHATS chats' newest main message. Text is cut to PREVIEW_CHARS by
* the database. `more` says a cap was reached. The route allows a person INBOX_READS per INBOX_WINDOW_MS in each Swarm,
* counted by every pod together.
@@ -24,7 +25,8 @@ import { createRateLimiter } from '../../lib/rateLimit.js'
import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../../lib/teamSession.js'
import { agentOnly, author, fail, SuperTabError, type Actor, type Author, type Conversation, type SuperTabState } from '../model.js'
import { readConversation } from '../projects.js'
-import { deliveredCopies, type ThreadReply } from '../pageReads.js'
+import { deliveredCopies, threadsAcross, threadsBackfilled, type ThreadReply } from '../pageReads.js'
+import { isSwarmBuddyChat } from '../buddies.js'
import { threadSummaries } from '../threads.js'
import { sessionReadsRow } from '../buddySessions.js'
import { readMarks, readThreadMarkRows, type ThreadMarkRow } from '../readMarks.js'
@@ -193,6 +195,39 @@ export async function newestInThreads(db: PrismaClient, tabId: string, ranges: T
return rows
}
+/**
+ * The threads of `threads` the person wrote in or was tagged in, in rows a page shows them, as threadKey(conversationId, thread).
+ * Read from the threads' summaries (pageReads.ts threadsAcross): one small row per thread by root id in one read, whatever its
+ * length, holding each author's newest row and every person's first tag with what a reader skips marked, so a row of theirs any
+ * distance back counts, as the Threads view counts it. It read each thread's newest MEMBER_SCAN rows before the mark, one $or
+ * branch per thread and one $unionWith branch past the cap: the threads route's slowest read in Ken's scan of 11-04 (task #2768).
+ * A Swarm Buddy chat's threads still read those rows before `sequence`: its summary cannot tell a row of a project its person
+ * lost (buddySessions.ts lostProjectRow), which they no longer read. So does a Swarm whose summaries are not backfilled yet
+ * (threadBackfill.ts): its summaries would come from every row of the threads (threadFacet), unbounded.
+ */
+export async function namedInThreads(db: PrismaClient, tabId: string, state: SuperTabState,
+ threads: ReadonlyArray<{ conversationId: string; thread: string; sequence: number }>, personId: string): Promise<Set<string>> {
+ const named = new Set<string>()
+ if (!threads.length) return named
+ const ready = await threadsBackfilled(db, tabId)
+ const scan = new Set(state.conversations.filter(g => !ready || isSwarmBuddyChat(g)).map(g => g.id))
+ const scanned = threads.filter(t => scan.has(t.conversationId)), summed = threads.filter(t => !scan.has(t.conversationId))
+ if (summed.length) {
+ const chatOf = new Map(summed.map(t => [t.thread, t.conversationId]))
+ for (const m of await threadsAcross(db, tabId, summed.map(t => ({ conversationId: t.conversationId, root: t.thread })))) {
+ if (!m.agentOnly && ((m.author.kind === 'person' && m.author.id === personId) || m.mentions.includes(personId))) {
+ named.add(threadKey(chatOf.get(m.thread)!, m.thread))
+ }
+ }
+ }
+ if (scanned.length) {
+ const rows = await newestInThreads(db, tabId, scanned.map(t => ({ conversationId: t.conversationId, thread: t.thread, sequence: { $lte: t.sequence } })),
+ MEMBER_SCAN, personId)
+ for (const m of await readable(db, tabId, rows, state)) named.add(threadKey(m.conversationId, m.thread!))
+ }
+ return named
+}
+
/** Up to `limit` rows of one chat, newest first, in its (sequence, id) index range. */
const newestIn = (tabId: string, conversationId: string, sequence: Record<string, number>, limit: number, fields: Record<string, unknown>): Prisma.InputJsonValue[] =>
[{ $match: { tabId, conversationId, sequence } }, { $sort: { sequence: -1, _id: -1 } }, { $limit: limit }, { $project: { ...fields, conversationId: 1 } }] as Prisma.InputJsonValue[]
@@ -282,12 +317,10 @@ async function threadsIn(db: PrismaClient, tabId: string, state: SuperTabState,
const roots = new Map((await readable(db, tabId, found.filter(m => !isReply(m)), state)).map(m => [threadKey(m.conversationId, m.id), m]))
const withRoot = picked.filter(c => roots.has(threadKey(c.conversationId, c.root)))
for (const c of withRoot) if (inIt(roots.get(threadKey(c.conversationId, c.root))!)) c.member = true
- // The rest: did the person write or get tagged before their mark? Each thread's newest MEMBER_SCAN rows there, by its thread
- // index range; only the rows that name them come back.
+ // The rest: did the person write or get tagged in it before? From the threads' summaries, in one read (namedInThreads).
const unknown = withRoot.filter(c => !c.member)
if (unknown.length) {
- const named = await newestInThreads(db, tabId, unknown.map(c => ({ conversationId: c.conversationId, thread: c.root, sequence: { $lte: c.mark } })), MEMBER_SCAN, personId)
- const members = new Set((await readable(db, tabId, named, state)).map(m => threadKey(m.conversationId, m.thread!)))
+ const members = await namedInThreads(db, tabId, state, unknown.map(c => ({ conversationId: c.conversationId, thread: c.root, sequence: c.mark })), personId)
for (const c of unknown) if (members.has(threadKey(c.conversationId, c.root))) c.member = true
}
const groups = new Map(readableChats.map(g => [g.id, g]))
diff --git a/backend/src/superTabs/read/threadMarkSeeds.ts b/backend/src/superTabs/read/threadMarkSeeds.ts
index 91b7753e4..3ac65592a 100644
--- a/backend/src/superTabs/read/threadMarkSeeds.ts
+++ b/backend/src/superTabs/read/threadMarkSeeds.ts
@@ -12,7 +12,8 @@
*
* Cost: read at most SEED_ROWS indexed rows and retain at most SEED_SCAN replies. Main rows do not spend the reply
* budget, but the row ceiling bounds database work. Roots and marks are fetched for at most SEED_SCAN candidate threads;
- * at most SEED_THREADS unknown memberships use MEMBER_SCAN look-back rows each, and at most SEED_THREADS marks are written.
+ * at most SEED_THREADS unknown memberships are read from their threads' summaries in one read (inbox.ts namedInThreads), and at
+ * most SEED_THREADS marks are written.
* Any unhandled range or thread holds the chat mark before it. A later request can advance it; clients may defer that
* request until another message arrives. Privacy and membership checks below still apply before a mark is written.
*/
@@ -22,7 +23,7 @@ import { stableId, type Author, type SuperTabState } from '../model.js'
import { seedThreadMark, writeReadMark } from '../readMarks.js'
import { markActivityChatRead } from '../activity.js'
import { readBy } from '../parts/indexed.js'
-import { BEHIND_THREADS, groupBy, isReply, MEMBER_SCAN, newestInThreads, readable, row, SCAN_FIELDS, UNREAD_SCAN, type Row } from './inbox.js'
+import { BEHIND_THREADS, groupBy, isReply, namedInThreads, readable, row, SCAN_FIELDS, threadKey, UNREAD_SCAN, type Row } from './inbox.js'
/** Thread replies of the range one chat read looks at, from the old mark upward. */
export const SEED_SCAN = 5 * UNREAD_SCAN
@@ -86,13 +87,12 @@ export async function seedThreadMarks(db: PrismaClient, input: SeedInput): Promi
const roots = new Map((await readable(db, tabId, found.filter(m => !isReply(m)), state)).map(m => [m.id, m]))
const withRoot = open.filter(thread => roots.has(thread))
const member = new Set(withRoot.filter(thread => held.get(thread)?.follow === true || inIt(roots.get(thread)!) || threads.get(thread)!.some(inIt)))
- // The rest: did the person write or get tagged before the old mark? Each thread's newest MEMBER_SCAN rows there, by its
- // thread index range; only the rows that name them come back.
+ // The rest: did the person write or get tagged in it before? From the threads' summaries, in one read (inbox.ts namedInThreads).
const unknown = withRoot.filter(thread => !member.has(thread))
if (unknown.length) {
if (unknown.length > SEED_THREADS) holdBefore(unknown[SEED_THREADS]!)
- const named = await newestInThreads(db, tabId, unknown.slice(0, SEED_THREADS).map(thread => ({ conversationId, thread, sequence: { $lte: old } })), MEMBER_SCAN, personId)
- for (const m of await readable(db, tabId, named, state)) member.add(m.thread!)
+ const named = await namedInThreads(db, tabId, state, unknown.slice(0, SEED_THREADS).map(thread => ({ conversationId, thread, sequence: old })), personId)
+ for (const thread of unknown.slice(0, SEED_THREADS)) if (named.has(threadKey(conversationId, thread))) member.add(thread)
}
const eligible = withRoot.filter(t => member.has(t))
if (eligible.length > SEED_THREADS) holdBefore(eligible[SEED_THREADS]!)
diff --git a/cli/src/team/autoSetup.spec.ts b/cli/src/team/autoSetup.spec.ts
index 616b90533..8cfb8dcbd 100644
--- a/cli/src/team/autoSetup.spec.ts
+++ b/cli/src/team/autoSetup.spec.ts
@@ -279,3 +279,48 @@ describe('the Harness Team account, set up on its own', () => {
}
})
})
+
+describe('a half-finished setup is repaired, not taken for done (#2765, Darren-MacBook)', () => {
+ it('with the account but no daemon, Set up runs setup again; the automatic moments ask for nothing', async () => {
+ const missing = vi.fn(async () => ['daemon'] as const)
+ const f = fake({ accountExists: vi.fn(async () => true), missing } as Partial<AutoSetupDeps>)
+ for (const reason of ['startup', 'join', 'contribute'] as const) {
+ expect(await f.auto.offer(reason, async () => true), reason).toEqual({ state: 'incomplete' })
+ }
+ expect(f.deps.setup).not.toHaveBeenCalled()
+ // Desktop's explanation first, then the person's Set up: the repair runs.
+ expect(await f.auto.offer('manual', async () => true, true)).toEqual({ state: 'wanted' })
+ expect(await f.auto.offer('manual')).toEqual({ state: 'started' })
+ await f.auto.settled()
+ expect(f.deps.setup).toHaveBeenCalledTimes(1)
+ })
+
+ it('a remembered cancel or failure does not stop Set up from repairing', async () => {
+ const f = fake({ accountExists: vi.fn(async () => true), missing: async () => ['daemon'] } as Partial<AutoSetupDeps>)
+ f.setDecision({ state: 'failed', at: 1_000_000 - 1 })
+ expect(await f.auto.offer('manual')).toEqual({ state: 'started' })
+ })
+
+ it('status names what is missing, for the machine row', async () => {
+ const daemon = fake({ accountExists: vi.fn(async () => true), missing: async () => ['daemon'] } as Partial<AutoSetupDeps>)
+ expect(await daemon.auto.status()).toEqual({ state: 'incomplete', missing: ['daemon'], detail: 'the team daemon is not running' })
+ const privacy = fake({ accountExists: vi.fn(async () => true), missing: async () => ['privacy'] } as Partial<AutoSetupDeps>)
+ expect(await privacy.auto.status()).toEqual({ state: 'incomplete', missing: ['privacy'], detail: 'its privacy check has not passed' })
+ const both = fake({ accountExists: vi.fn(async () => true), missing: async () => ['daemon', 'privacy'] } as Partial<AutoSetupDeps>)
+ expect((await both.auto.status()).detail).toBe('the team daemon is not running, and its privacy check has not passed')
+ })
+
+ it('with every part in place it is done: exists, and nothing runs', async () => {
+ const f = fake({ accountExists: vi.fn(async () => true), missing: async () => [] } as Partial<AutoSetupDeps>)
+ expect(await f.auto.offer('manual')).toEqual({ state: 'exists' })
+ expect(await f.auto.status()).toEqual({ state: 'exists' })
+ expect(f.deps.setup).not.toHaveBeenCalled()
+ })
+
+ it('a part it cannot read counts as missing, so Set up can still repair it', async () => {
+ const f = fake({ accountExists: vi.fn(async () => true), missing: async () => { throw new Error('launchctl timed out') } } as Partial<AutoSetupDeps>)
+ expect(await f.auto.status()).toMatchObject({ state: 'incomplete', missing: ['daemon'] })
+ expect(await f.auto.offer('manual')).toEqual({ state: 'started' })
+ })
+})
+
diff --git a/cli/src/team/autoSetup.ts b/cli/src/team/autoSetup.ts
index af89b6ca1..50792a4a8 100644
--- a/cli/src/team/autoSetup.ts
+++ b/cli/src/team/autoSetup.ts
@@ -24,6 +24,7 @@ import { readFileSync, renameSync, writeFileSync, mkdirSync, rmSync } from 'node
import { dirname, join } from 'node:path'
import type { AuthSession } from '../lib/authSession.js'
import type { TeamConfig } from './config.js'
+import type { TeamCommandDeps } from './command.js'
import { TEAM_USER, teamLayout } from './layout.js'
export interface TeamSetupDecision {
@@ -57,11 +58,21 @@ export const AUTO_SETUP_RETRY_MS = 24 * 60 * 60_000
/** `no-prompt`: Linux with no administrator prompt to show (no desktop session): run `harness team setup` in a terminal. */
export type AutoSetupState = 'unsupported' | 'signed-out' | 'dedicated' | 'running' | 'exists' | 'declined' | 'waiting' | 'not-shared'
- | 'no-prompt' | 'wanted' | 'started'
+ | 'no-prompt' | 'wanted' | 'started' | 'incomplete'
+
+/** A part of the Harness Team account besides the account itself that setup makes (#2765): its daemon (the service
+ * file and the job loaded), and its privacy check passed (the team daemon's own report). */
+export type TeamPart = 'daemon' | 'privacy'
+const PART_WORDS: Record<TeamPart, string> = { daemon: 'the team daemon is not running', privacy: 'its privacy check has not passed' }
+/** What [missing] says, as one sentence part: "the team daemon is not running, and its privacy check has not passed". */
+export const missingDetail = (missing: readonly TeamPart[]): string => missing.map((part) => PART_WORDS[part]).join(', and ')
/** What [TeamAutoSetup.status] answers. `detail`: a failed setup's own sentence, at most 300 characters. While it runs,
* `step`: the step it is on (./command.ts `progress`), once one is said, and `elapsedMs`: how long it has run. */
-export interface TeamSetupStatus { state: 'none' | 'running' | 'exists' | 'declined' | 'failed'; detail?: string; step?: string; elapsedMs?: number }
+export interface TeamSetupStatus { state: 'none' | 'running' | 'exists' | 'declined' | 'failed' | 'incomplete'; detail?: string; step?: string
+ elapsedMs?: number
+ /** `incomplete`: the account is there, these parts are not (Set up repairs them). */
+ missing?: TeamPart[] }
/** The moment the person is at this Mac: they joined a Swarm, added this Mac to one, or opened the app (`startup`); or
* they asked for it (`manual`: Desktop's explanation was accepted, or the machine row's Set up button). */
@@ -73,6 +84,8 @@ export interface AutoSetupDeps {
session(): AuthSession | null
readConfig(): TeamConfig | null
accountExists(user: string): Promise<boolean>
+ /** The parts besides the account that are not in place (#2765); none told, none counted (older callers, specs). */
+ missing?(): Promise<readonly TeamPart[]>
readDecision(): TeamSetupDecision | null
writeDecision(decision: TeamSetupDecision): void
/** `harness team setup --json`, as this account: its exit code and the JSON it answered (null when it said none).
@@ -118,8 +131,12 @@ export class TeamAutoSetup {
if (!session) return 'signed-out'
if (session.kind === 'team') return 'dedicated'
if (this.running) return 'running'
- if (deps.readConfig() || await deps.accountExists(TEAM_USER)) return 'exists'
- if (reason !== 'manual') {
+ if (deps.readConfig() || await deps.accountExists(TEAM_USER)) {
+ // Done only when every part is there (#2765: an account with no daemon answered "already set up", and nothing
+ // repaired it). A part missing is repaired only when the person asks (Set up): no password is asked for on its own.
+ if (!(await this.missing()).length) return 'exists'
+ if (reason !== 'manual') return 'incomplete'
+ } else if (reason !== 'manual') {
const decision = deps.readDecision()
if (decision?.state === 'declined') return 'declined'
if (decision?.state === 'failed' && deps.now() - decision.at < AUTO_SETUP_RETRY_MS && deps.now() >= decision.at) return 'waiting'
@@ -144,12 +161,21 @@ export class TeamAutoSetup {
if (this.running) {
return { state: 'running', ...(this.step ? { step: this.step } : {}), elapsedMs: Math.max(0, deps.now() - this.startedAt) }
}
- if (deps.readConfig() || await deps.accountExists(TEAM_USER)) return { state: 'exists' }
+ if (deps.readConfig() || await deps.accountExists(TEAM_USER)) {
+ const missing = await this.missing()
+ return missing.length ? { state: 'incomplete', missing: [...missing], detail: missingDetail(missing) } : { state: 'exists' }
+ }
const decision = deps.readDecision()
if (!decision) return { state: 'none' }
return { state: decision.state, ...(decision.state === 'failed' && decision.detail ? { detail: decision.detail } : {}) }
}
+ /** The parts not in place. One it cannot read counts as missing, the daemon, so Set up can still repair it. */
+ private async missing(): Promise<readonly TeamPart[]> {
+ if (!this.deps.missing) return []
+ try { return await this.deps.missing() } catch { return ['daemon'] }
+ }
+
/** "Not now" in Desktop's explanation: not offered again on its own, as a cancelled prompt is not. */
decline(): void {
this.deps.writeDecision({ state: 'declined', at: this.deps.now() })
@@ -207,6 +233,20 @@ function missingEngines(result: Record<string, unknown> | null): string[] {
})
}
+/**
+ * What is not in place of an existing Harness Team account (#2765), as `harness team status` reads it (./command.ts): the
+ * daemon, when no job of its label runs; privacy, when the team daemon's own report does not say its check passed.
+ */
+export async function teamMissingParts(deps: Pick<TeamCommandDeps, 'readConfig' | 'jobState' | 'readStatus'>, platform: NodeJS.Platform):
+ Promise<TeamPart[]> {
+ const layout = teamLayout(platform)
+ if (!layout) return []
+ const config = deps.readConfig()
+ const job = await deps.jobState(config?.label ?? layout.service.label)
+ const report = deps.readStatus(config?.statusFile ?? layout.statusFile)
+ return [...job.pid === null ? ['daemon' as const] : [], ...report?.privacy?.passed === true ? [] : ['privacy' as const]]
+}
+
/** The owner's daemon's own: this account's sign-in and data folder, and `harness team setup --json` run in this process. */
export async function realTeamAutoSetup(dataDir: string, log: (line: string) => void): Promise<TeamAutoSetup> {
const [{ readAuthSession }, { readTeamConfig }, { runGuestCommand }, { teamAccountExists }, { adminPromptShows }] = await Promise.all([
@@ -218,6 +258,12 @@ export async function realTeamAutoSetup(dataDir: string, log: (line: string) =>
readConfig: () => readTeamConfig(),
// The platform's own account database: getent on Linux, id on a Mac.
accountExists: teamAccountExists(runGuestCommand),
+ // Read only: the job's state and the team daemon's report, as `harness team status` reads them, never as root.
+ missing: async () => {
+ const { teamCommandDeps } = await import('./deps.js')
+ const refuse = async (): Promise<never> => { throw new Error('reading the parts changes nothing') }
+ return teamMissingParts(teamCommandDeps({ stopDaemon: refuse, startDaemon: refuse }), process.platform)
+ },
readDecision: () => readTeamSetupDecision(file),
writeDecision: (decision) => writeTeamSetupDecision(file, decision),
setup: async (progress) => {
diff --git a/cli/src/team/script.spec.ts b/cli/src/team/script.spec.ts
index 9bfd2b8be..235e823ea 100644
--- a/cli/src/team/script.spec.ts
+++ b/cli/src/team/script.spec.ts
@@ -880,3 +880,31 @@ describe('Linux', () => {
})
})
})
+
+describe("the macOS root script trusts no PATH of the owner's (#2765)", () => {
+ it.each([
+ ['setup', () => buildSetupScript(input())],
+ // Security review 2: removal runs as root too, with sudo in the owner's terminal, which keeps their PATH.
+ ['removal', () => buildRemoveScript({ user: 'harnessteam', home: '/Users/harnessteam', ownerHome: OWNER_HOME })],
+ ])('the %s script pins PATH to system folders before its first command', (_, build) => {
+ const lines = build().split('\n')
+ const pin = lines.indexOf('PATH=/usr/sbin:/usr/bin:/sbin:/bin; export PATH')
+ expect(pin).toBeGreaterThan(0)
+ // Only the shell's own settings come before it.
+ expect(lines.slice(0, pin).filter((l) => l && !l.startsWith('#'))).toEqual(['set -eu'])
+ })
+
+ it.runIf(process.platform === 'darwin')('checks that / is root\'s with a GNU stat first on the PATH (micromamba)', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'team-path-'))
+ try {
+ // GNU stat's -f means the file system, and prints no owner: what Darren-MacBook's PATH put first.
+ writeFileSync(join(dir, 'stat'), '#!/bin/sh\nprintf \' File: "%s"\\n ID: 0 Namelen: 255 Type: apfs\\n\' "$3"\n', { mode: 0o755 })
+ const script = buildSetupScript(input())
+ const head = script.slice(0, script.indexOf('\n[ "$(id -u)" = 0 ] || die "run as root"'))
+ const run = spawnSync('/bin/sh', ['-c', `${head}\nowned_by_root /\necho checked`], { encoding: 'utf8', env: { ...process.env, PATH: `${dir}:${process.env.PATH}` } })
+ expect(run.stderr).toBe('')
+ expect(run.stdout.trim()).toBe('checked')
+ } finally { rmSync(dir, { recursive: true, force: true }) }
+ })
+})
+
diff --git a/cli/src/team/script.ts b/cli/src/team/script.ts
index 7559f98c2..7fe548589 100644
--- a/cli/src/team/script.ts
+++ b/cli/src/team/script.ts
@@ -311,6 +311,9 @@ export function buildSetupScript(input: SetupScriptInput): string {
'# Harness Team account setup (cli/src/team/script.ts), run once as root behind the macOS administrator prompt.',
'# Running it again repairs what is there; `harness team remove` undoes it.',
'set -eu',
+ // Root runs only the system's own tools, never the owner's PATH: a micromamba GNU stat first on it read / as not root's
+ // (#2765, Darren-MacBook), and a tool ahead of the system's would run as root. The Linux scripts pin it the same way.
+ 'PATH=/usr/sbin:/usr/bin:/sbin:/bin; export PATH',
'umask 022',
'cd /',
`die() { printf 'harness: %s\\n' "$1" >&2; exit "\${2:-1}"; }`,
@@ -496,6 +499,9 @@ export function buildRemoveScript(input: RemoveScriptInput): string {
'# for the administrator prompt\'s own process, or for a LaunchDaemon, and refuses them (eDSPermissionError); it',
'# asks it for a terminal app. When it refuses, the team daemon runs again and nothing else has changed.',
'set -eu',
+ // As setup's: sudo in the owner's terminal keeps their PATH (macOS sudoers has no secure_path), and a tool ahead of the
+ // system's would run as root, or a GNU stat would hand pkill a wrong user id (security review 2 of #2765).
+ 'PATH=/usr/sbin:/usr/bin:/sbin:/bin; export PATH',
'cd /',
`die() { printf 'harness: %s\\n' "$1" >&2; exit "\${2:-1}"; }`,
`say() { printf 'harness: %s\\n' "$1"; }`,
diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dart
index 54709b834..e750fd057 100644
--- a/desktop/lib/super_tabs/client.dart
+++ b/desktop/lib/super_tabs/client.dart
@@ -450,6 +450,9 @@ class SuperTabClient {
_tagCounts.clear();
_tagDigests.clear();
_owners = const {};
+ _listed = const {};
+ _listAnswers = 0;
+ _listAsked.clear();
_tagsSeen.clear();
_listMentions = true;
discoveryError = null;
@@ -578,6 +581,7 @@ class SuperTabClient {
discoveryError = null;
_owners = owners;
_listed = tabs.keys.toSet();
+ _listAnswers++;
final hidden = Set<String>.unmodifiable({..._hidden, ..._creating});
onTabs!(tabs.values.toList(), hidden);
// Every page read: a Swarm not listed is no longer this account's.
@@ -612,14 +616,36 @@ class SuperTabClient {
});
}
- /// The Swarms the last list read that answered named.
+ /// The Swarms the last list read that answered named, and how many list
+ /// reads have answered for this account.
Set<String> _listed = const {};
-
- /// Whether the account's list still names Swarm [id], read afresh (or
- /// joining a read under way): a Swarm refuses a read while its backend
- /// restarts, and only the list says it is gone. Throws when the list cannot
- /// be read, or the account changed meanwhile.
+ int _listAnswers = 0;
+
+ /// When each Swarm last asked for the list ([_stillListed]), and how many
+ /// list reads had answered then.
+ final _listAsked = <String, ({DateTime at, int answers})>{};
+
+ /// Whether the account's list still names Swarm [id]: a Swarm refuses a
+ /// read while its backend restarts, and only the list says it is gone.
+ /// Throws when the list cannot be read, or the account changed meanwhile.
+ ///
+ /// A restart refuses every read for a while, so the list is read for a
+ /// Swarm at most once a minute (task #2767). Within that minute the answer
+ /// is the latest list that answered since this Swarm asked, whoever read it
+ /// (discovery too); with none, it is unknown.
Future<bool> _stillListed(String id) async {
+ final now = clock.now();
+ final asked = _listAsked[id];
+ if (asked != null && now.difference(asked.at) < kSwarmListRecheckEvery) {
+ if (_listAnswers == asked.answers) {
+ throw const SuperTabFailure(
+ 'LIST_UNREAD',
+ 'The Swarm list has not answered since it was asked.',
+ );
+ }
+ return _listed.contains(id);
+ }
+ _listAsked[id] = (at: now, answers: _listAnswers);
final generation = _generation;
await refreshTabs();
if (generation != _generation) {
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 7c1c875e6..dd4588078 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -177,6 +177,10 @@ const kSwarmPushSafetyNet = Duration(seconds: 60);
/// often; a change to one asks for a read at once (`SuperTabClient`).
const kSwarmDiscoverySafetyNet = Duration(minutes: 2);
+/// While a Swarm's reads are refused, the account's Swarm list is read for it
+/// at most this often to learn whether it is gone (task #2767).
+const kSwarmListRecheckEvery = Duration(minutes: 1);
+
/// The files waiting in a Swarm's boxes: by conversation, and by a thread's
/// conversation and root.
typedef SuperTabKeptFiles = ({
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index a8b739e90..d45a05902 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -1529,6 +1529,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
name: name,
problem: problem,
setUpTeam: setUpTeam,
+ setUpTeamLabel: superTabTeamSetupAction(_teamSetup),
owner: person,
contributor: contributor,
shared: shared,
@@ -2027,7 +2028,13 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
: null,
onSetUpTeam: view.setUpTeam
? () async {
- await showTeamAccountSetup(context, widget.app!);
+ await showTeamAccountSetup(
+ context,
+ widget.app!,
+ missing: _teamSetup?.state == 'incomplete'
+ ? _teamSetup?.detail ?? ''
+ : null,
+ );
await _readTeamSetup();
}
: null,
@@ -2643,6 +2650,7 @@ class _MachineView {
required this.tip,
this.problem,
this.setUpTeam = false,
+ this.setUpTeamLabel = 'Set up',
this.apiModels = const [],
this.localModels = const [],
});
@@ -2652,6 +2660,9 @@ class _MachineView {
/// Its [problem] is this Mac's, its own person looking: no Harness Team account yet, which they can set up here.
final bool setUpTeam;
+ /// Its button's word: Repair for an account that is there with a part missing (#2765), else Set up.
+ final String setUpTeamLabel;
+
/// Its one line when teammates' agents cannot run there ([superTabTeammatesPaused]); null otherwise.
final String? problem;
final SuperTabPerson? owner;
@@ -2736,11 +2747,20 @@ String? superTabTeamSetupLine(({String state, String? detail})? setup) {
'setup failed: $detail',
'failed' => 'setup failed',
'running' => 'setting up',
+ // The account is there, a part of it is not (cli/src/team/autoSetup.ts `missingDetail`, #2765).
+ 'incomplete' when detail != null && detail.isNotEmpty =>
+ 'Harness Team is not finished ($detail)',
+ 'incomplete' => 'Harness Team is not finished',
_ => null,
};
return why == null ? null : "Teammates' agents paused: $why";
}
+/// The row's button for this Mac's own setup: Repair when the account is there but a part of it is not (#2765), else
+/// Set up.
+String superTabTeamSetupAction(({String state, String? detail})? setup) =>
+ setup?.state == 'incomplete' ? 'Repair' : 'Set up';
+
/// One engine's allowance on a machine: its mark and remaining share on the row, its windows on hover.
class _Allowance {
const _Allowance({
@@ -2962,7 +2982,7 @@ class _MachineLine extends StatelessWidget {
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
alignment: Alignment.centerLeft,
),
- child: const Text('Set up'),
+ child: Text(view.setUpTeamLabel),
),
],
);
diff --git a/desktop/lib/super_tabs/team_account_setup.dart b/desktop/lib/super_tabs/team_account_setup.dart
index 811dbc8a4..ee4860567 100644
--- a/desktop/lib/super_tabs/team_account_setup.dart
+++ b/desktop/lib/super_tabs/team_account_setup.dart
@@ -21,12 +21,14 @@ Future<void> showTeamAccountSetup(
AppNotifier app, {
bool asked = false,
String? operatingSystem,
+ String? missing,
}) => showAppDialog<void>(
context: context,
barrierDismissible: false,
builder: (context) => _TeamAccountSetup(
app: app,
asked: asked,
+ missing: missing,
words: _Words.of(operatingSystem ?? RuntimePlatform.operatingSystem),
),
);
@@ -141,6 +143,14 @@ class _Words {
static const _computerLead =
'This computer joined a Swarm, so it needs Harness Team before you go on.';
+ /// The dialog's title when it repairs (#2765): "Repair Harness Team on this Mac".
+ String get repairTitle => title.replaceFirst('Set up', 'Repair');
+
+ /// What it says first when it repairs: what is missing, and that Repair runs the setup again.
+ String unfinished(String missing) => missing.isEmpty
+ ? 'Harness Team is not finished on $here. Repair runs its setup again.'
+ : 'Harness Team is not finished on $here: $missing. Repair runs its setup again.';
+
/// Once Remove was refused: Not now is the way on, and it says so instead
/// of asking for Remove again.
String get notNowWhy =>
@@ -253,12 +263,17 @@ class _TeamAccountSetup extends StatefulWidget {
required this.app,
required this.asked,
required this.words,
+ this.missing,
});
final AppNotifier app;
final bool asked;
final _Words words;
+ /// The account is there and these parts are not (cli/src/team/autoSetup.ts `missingDetail`, #2765): the dialog
+ /// repairs instead of setting up. Empty for a part it could not name.
+ final String? missing;
+
@override
State<_TeamAccountSetup> createState() => _TeamAccountSetupState();
}
@@ -309,9 +324,10 @@ class _TeamAccountSetupState extends State<_TeamAccountSetup> {
final muted = body.copyWith(color: Theme.of(context).hintColor);
final outcome = _outcome;
final words = widget.words;
+ final missing = widget.missing;
return AlertDialog(
key: const Key('team-account-setup'),
- title: Text(words.title),
+ title: Text(missing == null ? words.title : words.repairTitle),
content: SizedBox(
width: 420,
child: outcome != null
@@ -324,7 +340,10 @@ class _TeamAccountSetupState extends State<_TeamAccountSetup> {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Text(words.account, style: body),
+ Text(
+ missing == null ? words.account : words.unfinished(missing),
+ style: body,
+ ),
const SizedBox(height: 12),
Text(words.prompt, style: body),
const SizedBox(height: 12),
@@ -353,7 +372,7 @@ class _TeamAccountSetupState extends State<_TeamAccountSetup> {
FilledButton(
key: const Key('team-account-setup-continue'),
onPressed: _busy ? null : _continue,
- child: const Text('Continue'),
+ child: Text(missing == null ? 'Continue' : 'Repair'),
),
],
);
@@ -541,6 +560,16 @@ class _TeamAccountSetupLockState extends State<TeamAccountSetupLock> {
case 'declined':
_show(_LockStep.cancelled, _words.cancelled);
return;
+ // It ended with the account there and a part not (#2765): said, and Try again repairs it.
+ case 'incomplete':
+ final missing = setup?.detail?.trim();
+ _show(
+ _LockStep.retry,
+ missing == null || missing.isEmpty
+ ? 'Setup ended, but Harness Team is not finished. Try again.'
+ : 'Setup ended, but Harness Team is not finished: ${_sentence(missing)} Try again.',
+ );
+ return;
case 'running':
final since = _since;
setState(() {
diff --git a/desktop/test/super_tab_swarm_switcher_test.dart b/desktop/test/super_tab_swarm_switcher_test.dart
index 73671717f..e6170f7bd 100644
--- a/desktop/test/super_tab_swarm_switcher_test.dart
+++ b/desktop/test/super_tab_swarm_switcher_test.dart
@@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:io';
+import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/models.dart';
@@ -56,6 +57,10 @@ class _Backend {
/// While set, the account's Swarm list fails so.
Object? listFailure;
+ /// How many times the account's Swarm list was asked for, failed reads
+ /// included.
+ int listReads = 0;
+
/// While true, this computer's Harness is restarting (a CLI update): every
/// request to it fails as its dropped socket does.
bool daemonRestarting = false;
@@ -98,6 +103,7 @@ class _Backend {
}) async {
final uri = Uri.parse(path);
if (uri.path == '/api/super-tabs/list') {
+ listReads++;
if (listFailure case final failure?) throw failure;
return {
'tabs': [
@@ -1037,6 +1043,145 @@ void main() {
await fallBackToPersonal(app, alpha);
expect(_shown(app, tab), personal);
});
+
+ group('re-reads the list at most once a minute (task #2767)', () {
+ late DateTime now;
+ late AppNotifier app;
+ late _Backend backend;
+ late SuperTabController alpha;
+
+ /// One poll of Alpha, its refusal's list check and all, then [later].
+ Future<void> poll({Duration later = const Duration(seconds: 10)}) async {
+ await alpha.refresh();
+ await _settle();
+ now = now.add(later);
+ }
+
+ Future<void> under(Future<void> Function() body) {
+ now = DateTime.utc(2026, 11, 4, 5);
+ return withClock(Clock(() => now), () async {
+ (app, backend, _, alpha) = await shown();
+ await body();
+ });
+ }
+
+ test('refusals within a minute read the list once, the first of them '
+ 'failing; a refusal after the minute reads it again', () {
+ return under(() async {
+ backend.listFailure = dropped;
+ backend.stateReadFailure = refusals.last;
+ final before = backend.listReads;
+ await poll();
+ expect(backend.listReads - before, 1);
+ backend.listFailure = null;
+ for (final refusal in [...refusals, ...refusals]) {
+ backend.stateReadFailure = refusal;
+ await poll();
+ }
+ expect(
+ backend.listReads - before,
+ 1,
+ reason: 'five refusals in 50 seconds read the list once',
+ );
+ expect(alpha.accessRevoked, isFalse);
+ now = now.add(const Duration(seconds: 10));
+ await poll();
+ expect(backend.listReads - before, 2);
+ expect(alpha.accessRevoked, isFalse);
+ expect(alpha.snapshot?.name, 'Alpha');
+ });
+ });
+
+ test('a list read within the minute that leaves the Swarm out takes it '
+ 'away at the next refusal, reading the list no more', () {
+ return under(() async {
+ backend.stateReadFailure = refusals.first;
+ await poll();
+ expect(alpha.accessRevoked, isFalse);
+ final reads = backend.listReads;
+ backend.tabs.removeWhere((t) => t['id'] == 'alpha');
+ // This computer's own discovery reads the list meanwhile.
+ await app.superTabs.refreshTabs();
+ await _settle();
+ await poll();
+ expect(alpha.accessRevoked, isTrue);
+ expect(backend.listReads, reads + 1, reason: 'the discovery read');
+ });
+ });
+
+ test('a list that answered before the refusal asked never takes the '
+ 'Swarm away', () {
+ return under(() async {
+ // The last list that answered, already without Alpha, is older
+ // than the ask, whose own read fails; another read within the
+ // minute is not made.
+ backend.tabs.removeWhere((t) => t['id'] == 'alpha');
+ await app.superTabs.refreshTabs();
+ await _settle();
+ now = now.add(const Duration(seconds: 1));
+ backend.listFailure = dropped;
+ backend.stateReadFailure = refusals.last;
+ await poll();
+ await poll();
+ expect(alpha.accessRevoked, isFalse);
+ expect(alpha.snapshot?.name, 'Alpha');
+ });
+ });
+
+ test('each Swarm has its own minute', () {
+ return under(() async {
+ final beta = await app.superTabs.open('beta');
+ await beta.refresh();
+ await _settle();
+ backend.stateReadFailure = refusals.last;
+ final before = backend.listReads;
+ await poll(later: Duration.zero);
+ await beta.refresh();
+ await _settle();
+ expect(backend.listReads - before, 2);
+ await poll(later: Duration.zero);
+ await beta.refresh();
+ await _settle();
+ expect(backend.listReads - before, 2);
+ });
+ });
+
+ test('another account signed in within the minute reads the list '
+ "afresh: the last account's ask never answers it", () {
+ now = DateTime.utc(2026, 11, 4, 5);
+ return withClock(Clock(() => now), () async {
+ final backend = _Backend()
+ ..add('alpha', 'Alpha', members: ['owner', 'mate']);
+ final app = _computer(backend, MemoryStore());
+ await app.superTabs.refreshTabs();
+ final owners = await app.superTabs.open('alpha');
+ await owners.refresh();
+ await _settle();
+ // The owner's refusal asks, and the list answers with Alpha.
+ backend.stateReadFailure = refusals.last;
+ await owners.refresh();
+ await _settle();
+ expect(owners.accessRevoked, isFalse);
+
+ now = now.add(const Duration(seconds: 10));
+ app.currentUser = const CurrentUserProfile(
+ id: 'mate',
+ email: '[email protected]',
+ );
+ backend.account = 'mate';
+ backend.listFailure = dropped;
+ await _settle();
+ // Mate's list has not answered yet: a refusal is no reason to
+ // take Alpha away.
+ final reads = backend.listReads;
+ final mates = await app.superTabs.open('alpha');
+ await mates.refresh();
+ await _settle();
+ expect(mates.accessRevoked, isFalse);
+ expect(backend.listReads, greaterThan(reads));
+ });
+ });
+ });
});
test('a failure to add this computer says so in the tab Personal was '
diff --git a/desktop/test/team_account_offer_test.dart b/desktop/test/team_account_offer_test.dart
index 6569cbdec..2a316e639 100644
--- a/desktop/test/team_account_offer_test.dart
+++ b/desktop/test/team_account_offer_test.dart
@@ -5,6 +5,8 @@ import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/models.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/super_tabs/machines.dart'
+ show superTabTeamSetupAction, superTabTeamSetupLine;
import 'package:harness/super_tabs/team_account_setup.dart';
import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
@@ -477,6 +479,70 @@ void main() {
'account, Harness Team. They cannot read your files or use your GitHub login. '
'They use this computer\'s Claude Code and Codex subscriptions, so nobody signs in again.';
+ testWidgets(
+ 'a half-made account: the dialog says what is missing and offers Repair, which runs setup again (#2765)',
+ (tester) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => showTeamAccountSetup(
+ context,
+ app,
+ operatingSystem: 'macos',
+ missing: 'the team daemon is not running',
+ ),
+ child: const Text('open'),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('open'));
+ await tester.pumpAndSettle();
+ expect(find.text('Repair Harness Team on this Mac'), findsOneWidget);
+ expect(
+ find.text(
+ 'Harness Team is not finished on this Mac: the team daemon is not running. Repair runs its setup again.',
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('Continue'), findsNothing);
+ expect(
+ find.text('Harness Team is already set up on this Mac.'),
+ findsNothing,
+ );
+ daemon.answer = {'ok': true, 'state': 'started'};
+ await tester.tap(find.byKey(const Key('team-account-setup-continue')));
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const Key('team-account-setup-outcome')),
+ findsOneWidget,
+ );
+ expect(
+ daemon.asked
+ .where((p) => p['action'] == 'teamSetup')
+ .map((p) => p['reason']),
+ ['manual'],
+ );
+ },
+ );
+
+ test('the machine row names the missing part and offers Repair (#2765)', () {
+ expect(
+ superTabTeamSetupLine((
+ state: 'incomplete',
+ detail: 'the team daemon is not running',
+ )),
+ "Teammates' agents paused: Harness Team is not finished (the team daemon is not running)",
+ );
+ expect(
+ superTabTeamSetupAction((state: 'incomplete', detail: 'x')),
+ 'Repair',
+ );
+ expect(superTabTeamSetupAction((state: 'failed', detail: null)), 'Set up');
+ expect(superTabTeamSetupAction(null), 'Set up');
+ });
+
testWidgets('on a Mac the dialog says what it always said', (tester) async {
await open(tester);
expect(shown(tester), [
diff --git a/docs/plans/2026-11-04-swarm-list-recheck-cap-plan.md b/docs/plans/2026-11-04-swarm-list-recheck-cap-plan.md
new file mode 100644
index 000000000..69f03868a
--- /dev/null
+++ b/docs/plans/2026-11-04-swarm-list-recheck-cap-plan.md
@@ -0,0 +1,41 @@
+# A refused Swarm re-reads the Swarm list at most once a minute: plan
+
+> Way of working: this plan's Engineer implements it task by task, test first (test-driven-development), in one pull
+> request. No subagents, no execution handoff.
+
+**Goal:** Since #2913, Desktop re-reads the account's Swarm list each time a Swarm's read is refused (FORBIDDEN or
+NOT_FOUND) to decide whether the Swarm is gone. A backend refusing every read for a while (a restart) then gets one list
+read per refused read. Cap it at one list read per Swarm per minute, and still close the Swarm as soon as a list that
+answered leaves it out.
+
+**Architecture:** The cap lives in `SuperTabClient._stillListed(id)`, the controller's `stillListed` hook. The client
+remembers when it last read the list for Swarm `id`. Within a minute of that, it reads nothing and answers from the
+latest list that answered, whoever read it (its own discovery reads count), as long as that list answered after the
+Swarm's last ask: "not listed" closes the Swarm at once, "listed" keeps it. If no list has answered since that ask, the
+answer is unknown and the Swarm stays open. After a minute, the next refusal reads the list again. Signing in as
+another account forgets these answers.
+
+**Tech Stack:** Dart/Flutter (`desktop/lib/super_tabs/client.dart`), flutter_test with the Swarm switcher test's fake
+backend and `package:clock`.
+
+**Spec:** Task #2767 (follow-up to #2647, approved by River when #2913 was reviewed).
+
+## Global Constraints
+
+- Fails safe: a cached answer only closes a Swarm when a list read that answered for this account, after the ask,
+ leaves it out. Anything unknown keeps it open, as in #2913.
+- Desktop tests use a memory store and a fake sign-in; nothing signs the Mac's CLI out.
+
+## Review Focus
+
+- A cached "not listed" can never come from an older list (one read before the Swarm was joined, or another account's).
+- The cap is per Swarm, and a list read that failed still starts the minute.
+
+## Task 1: the cap
+
+**Files:** `desktop/lib/super_tabs/client.dart`, `desktop/test/super_tab_swarm_switcher_test.dart`.
+- [ ] Failing tests, using the fake backend that refuses reads: many refusals within a minute read the list once, the
+ first one failing to read; a refusal after a minute reads it again; a discovery read that drops the Swarm closes it
+ at the next refusal, with no further list read; a list that answered before the ask never closes it.
+- [ ] `_stillListed` keeps the time of each Swarm's last ask and the time of the last list that answered, and both are
+ forgotten on an account change.
diff --git a/docs/plans/2026-11-04-team-setup-repair-plan.md b/docs/plans/2026-11-04-team-setup-repair-plan.md
new file mode 100644
index 000000000..eb03b5edd
--- /dev/null
+++ b/docs/plans/2026-11-04-team-setup-repair-plan.md
@@ -0,0 +1,59 @@
+# Team setup repairs a half-finished setup Implementation Plan
+
+> **For agentic workers:** Written by the writing-plans skill as the project's instructions adapt it (Engineer role).
+> The Engineer implements it task by task, test first, in this session; the pull request's two security reviews are the
+> independent reviews. No execution handoff.
+
+**Goal:** On a Mac with the Harness Team account but no team daemon (or no passed privacy check), Set up repairs it
+instead of answering "already set up"; the macOS root script no longer trusts the owner's PATH; the machine row and the
+Set up dialog name the missing part and offer Repair.
+
+**Architecture:** `TeamAutoSetup` (cli/src/team/autoSetup.ts) counts setup complete only when the account exists and
+nothing is `missing` (a new dep: the daemon's service file and launchd job, and the team daemon's privacy report, read
+as `harness team status` reads them). With the account but a part missing, `manual` (Set up) runs the setup script
+again, which is rerunnable; the automatic moments (`startup`, `join`, `contribute`) answer `incomplete` and ask for no
+password. `status` answers `{ state: 'incomplete', missing, detail }`. `buildSetupScript` (cli/src/team/script.ts) pins
+`PATH=/usr/sbin:/usr/bin:/sbin:/bin` right after `set -eu`, as the Linux scripts do, so a GNU `stat` (micromamba) ahead
+on the owner's PATH no longer breaks `owned_by_root`. Desktop: `superTabTeamSetupLine` says what is missing, the row's
+button reads Repair, and the dialog opened from it says what is missing and offers Repair; the setup lock reads
+`incomplete` after a run as unfinished.
+
+**Tech Stack:** TypeScript (CLI), vitest; Dart/Flutter (Desktop), flutter_test.
+
+**Spec:** task #2765's brief (Scholes, Darren-MacBook, 11-04); #2921/#2937's step markers.
+
+## Global Constraints
+
+- Two independent security reviews (setup runs as root).
+- Never run real osascript, sudo, dscl or team setup: AdminDeps and AutoSetupDeps fakes only.
+- People's own environments are not changed.
+
+## Review Focus
+
+- A part missing never makes an automatic moment ask for the password: only Set up (manual) repairs.
+- A complete setup (account, daemon loaded, privacy passed) still answers `exists`, and runs nothing.
+- The PATH pin comes before any command the script runs, and every tool the script needs is in those folders.
+- Windows keeps its own script; Linux scripts already pin PATH.
+
+## Design
+
+N/A for storage: nothing new is stored. Failure: a part that cannot be read counts as missing and is said; the repair is
+the rerunnable setup script, so a repair that fails is said as setup failures are.
+
+### Task 1: Setup counts its parts, and Set up repairs (autoSetup.ts)
+
+- [ ] Failing tests (autoSetup.spec.ts): account without daemon → `manual` starts setup; `startup` answers `incomplete`
+ without setup; `status` names the missing part; account, daemon and privacy all there → `exists`, nothing runs.
+- [ ] Implement; run.
+
+### Task 2: The root script pins a system-only PATH (script.ts)
+
+- [ ] Failing tests (script.spec.ts): PATH is pinned before the first command; on macOS a GNU-style `stat` first on the
+ PATH does not fail the owner check of `/`.
+- [ ] Implement; run.
+
+### Task 3: The row and the dialog name the missing part (Desktop)
+
+- [ ] Failing tests: `superTabTeamSetupLine` for `incomplete`; the dialog opened with a missing part says it and offers
+ Repair.
+- [ ] Implement; run; Desktop guard tests.
diff --git a/docs/plans/2026-11-04-thread-member-check-plan.md b/docs/plans/2026-11-04-thread-member-check-plan.md
new file mode 100644
index 000000000..0ef3c5b8b
--- /dev/null
+++ b/docs/plans/2026-11-04-thread-member-check-plan.md
@@ -0,0 +1,68 @@
+# Thread member check from summaries: implementation plan
+
+> Implemented by its Engineer task by task, test first (project instructions, Engineer role). No per-task review: the
+> review step on the pull request is the one independent review.
+
+**Goal:** The threads route (GET /api/super-tabs/:tabId/threads) and the inbox stop reading each candidate thread's
+history to learn whether the person is in it, so their cost no longer grows with thread length and count (task #2768,
+Ken's production scan of 11-04: the `$or` of `{tabId, conversationId, thread, sequence: {$lte}}` branches, 762 slow
+in 2 h, and the per-thread `$unionWith` fallback, 70 slow).
+
+**Finding:** the slow shape is not `pageReads.ts threadFacet` or `threadsAcross`. It is `read/inbox.ts
+newestInThreads` called with `sequence: {$lte: mark}` and `namedBy`: the member check. It runs in `threadsIn` (the
+inbox, which the threads route reads first) for every unread thread the person is not visibly in, and in
+`read/threadMarkSeeds.ts moveChatMark` when a chat read moves the mark. Each call reads up to `max(100, 100 × N / 4)`
+history rows in one `$or` of N branches, and past that cap it reads again with one `$unionWith` branch per thread.
+
+**Architecture:** a new `inbox.ts namedInThreads` answers "which of these threads did the person write in or get tagged
+in, in rows a page shows them" from the threads' summaries (`pageReads.ts threadsAcross`): one read of
+`SuperTabThread` by `_id`, one small row per thread, whatever its length. A summary keeps each author's newest row and
+every person's first tag, with what each reader skips marked (`agentOnly`), so the answer is the old one without the
+100-row look-back. A Swarm Buddy chat's threads keep the message scan, as followed threads do: its summary cannot tell
+a row of a project its person lost (`buddySessions.ts lostProjectRow`). A Swarm not backfilled yet falls back to
+`threadFacet`, as pages do, until the worker marks it.
+
+**Tech Stack:** TypeScript, Prisma `aggregateRaw`, MongoDB profiler in integration tests, vitest.
+
+**Spec:** task #2768 brief.
+
+## Global Constraints
+
+- No production access: Ken's numbers are the before; local profiler counts are in the pull request.
+- No index change: `SuperTabThread` is read by `_id`.
+- No env switch. Audience unchanged: the candidates, roots and their checks are the same; only how membership is
+ learned changes.
+- Answers: identical, except a thread the person wrote in or was tagged in more than 100 rows before their mark now
+ counts as one they are in (the look-back cap), as the Threads view's read threads already do since #2889.
+
+## Review Focus
+
+- The membership answer: own rows and tags in rows a page shows the person, agent-only and delivered copies left out.
+- The Swarm Buddy chat exception, and the not-yet-backfilled fallback.
+- The profiler test's bounds and that it fails on main.
+
+## Design
+
+- growth: N/A because nothing new is stored.
+- concurrency: N/A because it is a read.
+- read cost: one `SuperTabThread` read by `_id` for at most CANDIDATE_THREADS (inbox) or SEED_THREADS (mark seeds)
+ roots, in place of up to 100 rows per thread plus a union.
+- scale: 10× threads is 10× small summary rows by `_id`; the first warning is docs examined on `SuperTabThread`.
+- compatibility: N/A because the answer shape is unchanged.
+- migration + rollback: N/A because there is no data change; rollback restores the scan.
+- audience: the server enforces it: membership only decides which readable threads are listed.
+- identity: N/A.
+- failure: a missing summary counts as not in the thread, as a thread with no rows did.
+- platforms: N/A (backend only).
+
+## Task 1: Member check from summaries
+
+**Files:** `backend/src/superTabs/read/inbox.ts`, `backend/src/superTabs/read/threadMarkSeeds.ts`,
+`backend/integration/superTabFollowedThreads.test.ts`
+
+- [ ] Failing integration test: a chat of 60 threads, 10 of them 300 rows long, where the person wrote or was tagged
+ in some and not others, each with an unread reply past the chat mark: the threads read lists the same threads as
+ before, reads no message by the thread index, and reads the summaries once by `_id`.
+- [ ] Failing test: a person who replied 150 rows back is in the thread.
+- [ ] Implement `namedInThreads`; use it in `threadsIn` and `moveChatMark`; run the followed threads, threads, inbox
+ and read-mark integration tests and the backend unit suite.