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 G: #2048 #2051 #2053 #2024 (#2054)
0xken15319da2c7284d
diff --git a/backend/integration/superTabHotReads.test.ts b/backend/integration/superTabHotReads.test.tsindex ad01b75ba..e12a24930 100644--- a/backend/integration/superTabHotReads.test.ts+++ b/backend/integration/superTabHotReads.test.ts@@ -15,6 +15,7 @@ import { HostReads } from '../src/superTabs/read/host.js'import { SwarmReads } from '../src/superTabs/read/service.js'import { cursorFor } from '../src/superTabs/read/cursor.js'import { lastChangedAt } from '../src/superTabs/parts/index.js'+import { swarmReadCache } from '../src/superTabs/cache.js'import type { SuperTabState } from '../src/superTabs/model.js'import { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'import { NOW, outsider, owner as ownerActor, peer, swarm } from '../src/superTabs/read/fixture.test-support.js'@@ -51,9 +52,9 @@ afterAll(async () => {/** A Swarm on two machines of the owner's: a Lead, and on the other a worker with running work, finished work, and OTHERS quiet conversations,* closed deliveries of other messages to other agents, and open decisions in other conversations. */-async function scene(edit: (s: ReturnType<typeof swarm>) => void = () => {}) {- const [machineId, leadMachine] = [`m-${randomUUID().slice(0, 8)}`, `l-${randomUUID().slice(0, 8)}`]- for (const id of [machineId, leadMachine]) {+async function scene({ sharedMachine, edit }: { sharedMachine?: string; edit?: (s: ReturnType<typeof swarm>) => void } = {}) {+ const [machineId, leadMachine] = [sharedMachine ?? `m-${randomUUID().slice(0, 8)}`, `l-${randomUUID().slice(0, 8)}`]+ for (const id of sharedMachine ? [leadMachine] : [machineId, leadMachine]) {await db.machine.create({ data: { machineId: id, userId: owner.sub, apiKey: 'fixture-only', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })}const s = swarm(MIGRATED)@@ -65,7 +66,7 @@ async function scene(edit: (s: ReturnType<typeof swarm>) => void = () => {}) {s.run({ type: 'work.assign', conversationId: web, agentId: worker })const done = s.group('Done work')const quiet = Array.from({ length: OTHERS }, (_, i) => s.group(`Quiet ${i}`))- edit(s)+ edit?.(s)s.edit(state => {state.conversations.find(c => c.id === done)!.assignment = { ...state.conversations.find(c => c.id === web)!.assignment!, id: 'old-work', status: 'done' }})@@ -113,6 +114,43 @@ function reads(entries: ProfileEntry[], collection: string, fields: string[], no}const plan = (rows: ProfileEntry[]) => rows.map(r => ({ plan: r.planSummary, docsExamined: r.docsExamined, keysExamined: r.keysExamined, returned: r.nreturned }))+/** Timestamp scans match only tabId; the indexed wake query also bounds changedAt and hostMachineIds. */+function timestampScans(entries: ProfileEntry[]) {+ return entries.filter(e => /^Swarm(Head|Member|Agent|Group|Machine|Start|Progress)$/.test(e.command?.aggregate as string))+ .flatMap(e => {+ const match = (e.command?.pipeline as Array<{ $match?: { tabId?: { $in?: string[] } } }>)?.[0]?.$match+ return match?.tabId?.$in && Object.keys(match).length === 1 ? [{ collection: e.command!.aggregate, ids: match.tabId.$in }] : []+ })+}++it('batches cold host timestamp misses across Swarms and leaves warm timestamps out of the batch', async () => {+ const a = await scene(), b = await scene({ sharedMachine: a.machineId })+ for (const s of [a, b]) swarmReadCache()!.drop(s.tabId)+ const hosts = new HostReads(store, { now: () => Date.now() })+ const expected = await lastChangedAt(db, [a.tabId, b.tabId])+ const cold = await profiled(async () => {+ const concurrent = await Promise.all([hosts.changes(owner, a.machineId, { full: true }), hosts.changes(owner, a.machineId, { full: true })])+ for (const result of concurrent) expect(new Map(result.tabs.map(t => [t.tabId, t.lastChangedAt]))).toEqual(expected)+ })+ expect(timestampScans(cold)).toHaveLength(7)+ for (const scan of timestampScans(cold)) expect(new Set(scan.ids)).toEqual(new Set([a.tabId, b.tabId]))+ expect(timestampScans(await profiled(() => hosts.changes(owner, a.machineId, { full: true })))).toEqual([])++ const c = await scene({ sharedMachine: a.machineId })+ swarmReadCache()!.drop(c.tabId)+ const mixed = timestampScans(await profiled(() => hosts.changes(owner, a.machineId, { full: true })))+ expect(mixed).toHaveLength(7)+ for (const scan of mixed) expect(scan.ids).toEqual([c.tabId])++ const direct = new HostReads(new SuperTabStore(db, () => clock, null, { readCache: null }))+ const uncached = await profiled(async () => {+ expect((await direct.changes(owner, a.machineId, { full: true })).tabs)+ .toEqual((await hosts.changes(owner, a.machineId, { full: true })).tabs)+ })+ expect(timestampScans(uncached)).toHaveLength(7)+ for (const scan of timestampScans(uncached)) expect(new Set(scan.ids)).toEqual(new Set([a.tabId, b.tabId, c.tabId]))+})+it('reuses the host timestamp at the same stamp, including a repeated wake with a held etag', async () => {const s = await scene()const hosts = new HostReads(store, { now: () => Date.now() })@@ -124,13 +162,7 @@ it('reuses the host timestamp at the same stamp, including a repeated wake withexpect(second.tabs).toEqual(first.tabs.map(tab => ({ tabId: tab.tabId, etag: tab.etag,lastChangedAt: tab.lastChangedAt, unchanged: true })))})- const scans = entries.filter(e => /^Swarm(Head|Member|Agent|Group|Machine|Start|Progress)$/.test(e.command?.aggregate as string))- .filter(e => {- const match = (e.command?.pipeline as Array<{ $match?: { tabId?: { $in?: unknown } } }>)?.[0]?.$match- // Timestamp scans match only tabId; the host's indexed wake query also bounds changedAt and hostMachineIds.- return match?.tabId?.$in && Object.keys(match).length === 1- })- expect(scans.map(e => e.command?.aggregate)).toEqual([])+ expect(timestampScans(entries)).toEqual([])// A committed change invalidates the timestamp along with the host inputs; a cold/direct read agrees.clock = Date.now()@@ -266,8 +298,8 @@ describe('which machines take teammates\' work is read once per 15 s per Swarm',describe('the owner\'s grid poll', () => {it('reads each Swarm\'s head and only the people of those with Local models, never their groups, agents, machines or starts', async () => {- const off = await scene(s => s.edit(state => { delete state.localModels }))- const on = await scene(s => s.join(peer))+ const off = await scene({ edit: s => s.edit(state => { delete state.localModels }) })+ const on = await scene({ edit: s => s.join(peer) })let grids: Awaited<ReturnType<SuperTabStore['hostGrids']>> = []const entries = await profiled(async () => { grids = await store.hostGrids(owner) })expect(grids.filter(g => g.tabId === off.tabId)).toEqual([])@@ -283,7 +315,7 @@ describe('the owner\'s grid poll', () => {})it('leaves out someone removed from a Swarm with Local models', async () => {- const s = await scene(s => { s.join(peer); s.join(outsider) })+ const s = await scene({ edit: s => { s.join(peer); s.join(outsider) } })clock = Date.now()await store.execute(owner, s.tabId, { operationId: randomUUID(), command: { type: 'member.remove', userId: outsider.userId } })expect(await db.swarmMember.findFirst({ where: { tabId: s.tabId, key: outsider.userId }, select: { deleted: true } })).toEqual({ deleted: true })diff --git a/backend/src/superTabs/cachedReads.ts b/backend/src/superTabs/cachedReads.tsindex b480010f5..935e0ae59 100644--- a/backend/src/superTabs/cachedReads.ts+++ b/backend/src/superTabs/cachedReads.ts@@ -75,6 +75,19 @@ export async function readLastChangedAt(db: Db, view: CacheView, tabId: string):return view.get(tabId, 'lastChangedAt', 'main', async () => (await store.lastChangedAt(db, [tabId])).get(tabId) ?? null)}+/** The same per-Swarm entries, with this read's misses collected into one seven-kind query (also without a cache). */+export async function readLastChangedAts(db: Db, view: CacheView, tabIds: string[]): Promise<Map<string, number | null>> {+ const missing: string[] = []+ let batch: Promise<Map<string, number>> | undefined+ return new Map(await Promise.all(tabIds.map(async tabId => [tabId, await view.get(tabId, 'lastChangedAt', 'main', () => {+ missing.push(tabId)+ // get starts miss loaders synchronously. Defer the query one microtask so every miss joins before it starts;+ // hits and entries already loading at this stamp never enter the batch.+ batch ??= Promise.resolve().then(() => store.lastChangedAt(db, missing))+ return batch.then(newest => newest.get(tabId) ?? null)+ })] as const)))+}+/** The Swarm's parts changed after `since` (parts/load.ts loadChanged): from the held feed when it reaches back that far, else read. */export async function readChanged(db: Db, view: CacheView, tabId: string, since: number): Promise<Part[]> {const direct = async () => (await store.loadChanged(db, [tabId], new Date(since))).get(tabId) ?? []diff --git a/backend/src/superTabs/native.test.ts b/backend/src/superTabs/native.test.tsnew file mode 100644index 000000000..b8fb7b763--- /dev/null+++ b/backend/src/superTabs/native.test.ts@@ -0,0 +1,118 @@+import { describe, expect, it } from 'vitest'+import type { Prisma } from '@prisma/client'+import { isLeads, type Agent, type SuperTabState } from './model.js'+import { revokeConditions } from './native.js'+import { canReadAgent, canReadGroup, ownSession, projectsOf, watchClosed } from './projects.js'+import { outsider, owner, peer, richSwarm } from './read/fixture.test-support.js'++/** The revocations as main computed them before item 7 (Diego, 2026-10-28), every check rebuilt on every command: the+ * reference the shortcut must match exactly. */+function everyCheck(before: SuperTabState, after: SuperTabState): Prisma.SuperTabNativeContextWhereInput[] {+ const conditions: Prisma.SuperTabNativeContextWhereInput[] = []+ for (const member of before.people) {+ const current = after.people.find(p => p.id === member.id)+ if (!current || current.generation !== member.generation || (current.role === 'viewer' && member.role !== 'viewer')) conditions.push({ userId: member.id })+ }+ for (const target of before.agents) {+ const current = after.agents.find(a => a.id === target.id)+ if (!current || current.harnessId !== target.harnessId) conditions.push({ agentId: target.id })+ }+ const session = (a: Agent) => `${a.machineId}\n${a.harnessId}\n${a.machineOwnerId}`+ const now = new Map(after.agents.map(a => [session(a), a]))+ const watchers = (state: SuperTabState, target: Agent) => state.people.map(p => ({ kind: 'person' as const, userId: p.id, email: p.email }))+ .filter(actor => canReadAgent(state, actor, target) && (!watchClosed(state, target) || ownSession(actor, target)))+ for (const target of before.agents) {+ const still = now.get(session(target))+ const is = new Set(still ? watchers(after, still).map(actor => actor.userId) : [])+ const lost = watchers(before, target).filter(actor => !is.has(actor.userId)).map(actor => actor.userId)+ if (lost.length) conditions.push({ agentId: target.id, userId: { in: lost } })+ }+ for (const group of before.conversations) {+ const current = after.conversations.find(c => c.id === group.id)+ if (!current || (current.archived && !group.archived)) conditions.push({ conversationId: group.id })+ else if (!isLeads(current)) {+ for (const member of after.people) {+ const reader = { kind: 'person' as const, userId: member.id, email: member.email }+ if (canReadGroup(before, reader, group) && !canReadGroup(after, reader, current)) conditions.push({ conversationId: group.id, userId: member.id })+ }+ const removed = group.agentIds.filter(id => !current.agentIds.includes(id))+ if (removed.length) conditions.push({ conversationId: group.id, agentId: { in: removed } })+ }+ }+ return conditions+}++describe('which terminals a commit revokes (item 7: only what changed access is checked)', () => {+ // Peer reads the Swarm's public project and is listed on Secret, so every change below takes something from someone.+ function swarm() {+ const s = richSwarm()+ s.edit(state => { project(state, s.secret).members.push({ id: peer.userId, generation: person(state, peer.userId).generation }) })+ const before = structuredClone(s.state)+ return { s, before, revokes: (change: (after: SuperTabState) => void) => {+ const after = structuredClone(before)+ change(after)+ return { got: revokeConditions(before, after), expected: everyCheck(before, after) }+ } }+ }+ const project = (state: SuperTabState, id: string) => projectsOf(state).find(p => p.id === id)!+ const group = (state: SuperTabState, id: string) => state.conversations.find(c => c.id === id)!+ const target = (state: SuperTabState, id: string) => state.agents.find(a => a.id === id)!+ const person = (state: SuperTabState, id: string) => state.people.find(p => p.id === id)!++ it('revokes nothing for a command that changes no access, such as a message', () => {+ const { s, before } = swarm()+ expect(revokeConditions(before, structuredClone(before))).toEqual({ conditions: [], watchersLost: [] })+ const posted = structuredClone(before)+ const web = group(posted, s.web)+ web.messageSeq = (web.messageSeq ?? 0) + 1+ web.lastMessageSequence = web.messageSeq+ web.lastActivityAt = new Date(0).toISOString()+ project(posted, 'lead').progress = { ...project(posted, 'lead').progress!, since: 2 }+ expect(revokeConditions(before, posted).conditions).toEqual([])+ })++ const changes: Array<[string, (after: SuperTabState, ids: ReturnType<typeof swarm>) => void]> = [+ ['a person leaves', after => { after.people = after.people.filter(p => p.id !== peer.userId) }],+ ['a person rejoins (a new generation)', after => { person(after, peer.userId).generation = 'again' }],+ ['a person becomes a viewer', after => { person(after, outsider.userId).role = 'viewer' }],+ ['an agent leaves', (after, { s }) => { after.agents = after.agents.filter(a => a.id !== s.worker) }],+ ['an agent gets a replacement terminal', (after, { s }) => { target(after, s.worker).harnessId = 'replacement' }],+ ['an agent moves to another machine', (after, { s }) => { target(after, s.worker).machineId = 'elsewhere' }],+ ['an agent\'s machine changes hands', (after, { s }) => { target(after, s.worker).machineOwnerId = 'someone-else' }],+ ['an agent turns confidential', (after, { s }) => { target(after, s.worker).confidential = true }],+ ['an agent moves project', (after, { s }) => { target(after, s.worker).projectId = s.secret }],+ ['a project turns private', after => { project(after, 'lead').visibility = 'private' }],+ ['a project drops a member', (after, { s }) => { project(after, s.secret).members = [] }],+ ['a project changes owner', (after, { s }) => { project(after, s.secret).ownerId = outsider.userId }],+ ['a project\'s Lead conversation changes', after => { project(after, 'lead').leadConversationId = 'gone' }],+ ['a Lead is replaced', after => { group(after, 'lead').leadId = null }],+ ['a group is archived', (after, { s }) => { group(after, s.web).archived = true }],+ ['a group is deleted', (after, { s }) => { after.conversations = after.conversations.filter(c => c.id !== s.web) }],+ ['a group turns private', (after, { s }) => { group(after, s.web).audience = { people: [] } }],+ ['an agent leaves a group', (after, { s }) => { group(after, s.web).agentIds = [] }],+ ['a group moves project', (after, { s }) => { group(after, s.web).projectId = s.secret }],+ ]+ it.each(changes)('revokes exactly what every check revokes when %s', (_, change) => {+ const ids = swarm()+ const { got, expected } = ids.revokes(after => change(after, ids))+ expect(expected.length).toBeGreaterThan(0)+ expect(got.conditions).toEqual(expected)+ })++ // A conversation's kind alone decides who reads it: every person reads the Leads conversation, but as a project group only+ // that project's readers do. A Buddy chat's kind narrows only what agents read, and no agent reader is checked here.+ it('revokes exactly what every check revokes when only a conversation\'s kind changes', () => {+ const ids = swarm()+ const leads = ids.before.conversations.find(isLeads)!+ leads.projectId = ids.s.secret+ const { got, expected } = ids.revokes(after => { delete group(after, leads.id).kind })+ expect(expected).toEqual([{ conversationId: leads.id, userId: outsider.userId }])+ expect(got.conditions).toEqual(expected)+ })++ it('names those who lost an agent, once, for the observers too', () => {+ const ids = swarm()+ const { got } = ids.revokes(after => { target(after, ids.s.worker).confidential = true })+ expect(got.watchersLost).toEqual([{ agentId: ids.s.worker, personIds: [owner.userId, peer.userId, outsider.userId] }])+ })+})diff --git a/backend/src/superTabs/native.ts b/backend/src/superTabs/native.tsindex fe736e931..a8a60f75c 100644--- a/backend/src/superTabs/native.ts+++ b/backend/src/superTabs/native.ts@@ -5,7 +5,7 @@ import type { AuthUser } from '../lib/ssoAuth.js'import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../lib/teamSession.js'import { activeWork, agent, appendPullRequestUrls, author, conversation, fail, isLeads, stableId, SuperTabError,type Actor, type Agent, type Author, type Conversation, type SuperTabState } from './model.js'-import { canReadGroup, groupProject, readConversation, watchersLost } from './projects.js'+import { accessInputs, canReadGroup, groupProject, readConversation, watchersLost } from './projects.js'import { mayDrive } from './terminal.js'import { noteProjectReports } from './projectUpdates.js'import { numberMessages, type Touch } from './parts/commit.js'@@ -259,23 +259,43 @@ export class SuperTabNativeStore {/** Removal followed by rejoining must not revive an old terminal binding. Only what this change ended is revoked: what* ended earlier was revoked by the change that ended it, and no context opens without access (open; validate checks it* again at every use). Most commands change no access and read nothing here: rebuilding every viewer and every member- * outside every private conversation on each command kept prod Mongo busy (2026-10-28). */+ * outside every private conversation on each command kept prod Mongo busy (2026-10-28). Returns those who lost sight of+ * an agent (watchersLost), for the observers to check again. */export async function revokeNativeContexts(tx: Transaction, before: SuperTabState, after: SuperTabState) {+ const { conditions, watchersLost } = revokeConditions(before, after)+ if (conditions.length) {+ const where = { tabId: before.id, revoked: false, OR: conditions }+ const revoked = await tx.superTabNativeContext.findMany({ where, select: { id: true } })+ await tx.superTabNativeContext.updateMany({ where, data: { revoked: true } })+ if (revoked.length) await tx.superTabDelivery.updateMany({ where: { tabId: before.id,+ nativeContextId: { in: revoked.map(r => r.id) }, status: { in: ['queued', 'claimed', 'uncertain'] } },+ data: { status: 'cancelled', holdReason: null, holdSince: null } })+ }+ return watchersLost+}++/** Which contexts a commit revokes, and who lost sight of which agent. A command that changes no access input checks+ * nothing: rebuilding every check on each one cost a 480-group Swarm about 5 ms of every command (item 7, 2026-10-28). */+export function revokeConditions(before: SuperTabState, after: SuperTabState) {const conditions: Prisma.SuperTabNativeContextWhereInput[] = []+ if (accessInputs(before) === accessInputs(after)) return { conditions, watchersLost: [] }+ const people = new Map(after.people.map(p => [p.id, p])), agents = new Map(after.agents.map(a => [a.id, a]))+ const groups = new Map(after.conversations.map(c => [c.id, c]))for (const member of before.people) {- const current = after.people.find(p => p.id === member.id)+ const current = people.get(member.id)if (!current || current.generation !== member.generation || (current.role === 'viewer' && member.role !== 'viewer')) conditions.push({ userId: member.id })}// A removed agent's contexts, and those of an agent given a replacement terminal: they name the old terminal, and its// waiting turns are cancelled with them, so a claim racing the change conflicts on their rows (rule b).for (const target of before.agents) {- const current = after.agents.find(a => a.id === target.id)+ const current = agents.get(target.id)if (!current || current.harnessId !== target.harnessId) conditions.push({ agentId: target.id })}// Those who may no longer watch an agent, such as everyone but its machine's owner once it reads private chats.- for (const { agentId, personIds } of watchersLost(before, after)) conditions.push({ agentId, userId: { in: personIds } })+ const lost = watchersLost(before, after)+ for (const { agentId, personIds } of lost) conditions.push({ agentId, userId: { in: personIds } })for (const group of before.conversations) {- const current = after.conversations.find(c => c.id === group.id)+ const current = groups.get(group.id)if (!current || (current.archived && !group.archived)) conditions.push({ conversationId: group.id })// No terminal opens in the Leads conversation (open), so it holds no context to revoke.else if (!isLeads(current)) {@@ -287,12 +307,5 @@ export async function revokeNativeContexts(tx: Transaction, before: SuperTabStatif (removed.length) conditions.push({ conversationId: group.id, agentId: { in: removed } })}}- if (conditions.length) {- const where = { tabId: before.id, revoked: false, OR: conditions }- const revoked = await tx.superTabNativeContext.findMany({ where, select: { id: true } })- await tx.superTabNativeContext.updateMany({ where, data: { revoked: true } })- if (revoked.length) await tx.superTabDelivery.updateMany({ where: { tabId: before.id,- nativeContextId: { in: revoked.map(r => r.id) }, status: { in: ['queued', 'claimed', 'uncertain'] } },- data: { status: 'cancelled', holdReason: null, holdSince: null } })- }+ return { conditions, watchersLost: lost }}diff --git a/backend/src/superTabs/projects.test.ts b/backend/src/superTabs/projects.test.tsindex b495077c5..ea08fbd68 100644--- a/backend/src/superTabs/projects.test.ts+++ b/backend/src/superTabs/projects.test.ts@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto'import { describe, expect, it } from 'vitest'import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'import { createSuperTab, SuperTabError, visibleState, type Actor, type MessageDraft } from './model.js'-import { canReadAgent, canWatchAgent, markConfidential, projectOf, projectsOf, readConversation, skillModeOf, skillSetOf, watchersLost, watchingNarrowed } from './projects.js'+import { canReadAgent, canWatchAgent, markConfidential, projectOf, projectsOf, readConversation, skillModeOf, skillSetOf, watchersLost } from './projects.js'import { mayDrive } from './terminal.js'const owner: Actor = { kind: 'person', userId: 'owner', email: '[email protected]' }@@ -580,7 +580,7 @@ describe('whether a commit narrows who may watch a terminal', () => {const builder = f.add('lead', 'builder', false)expect(canWatchAgent(f.state, peer, f.state.agents.find(a => a.id === builder)!)).toBe(true)const before = structuredClone(f.state)- return { f, builder, before, narrowed: () => watchingNarrowed(before, f.state) }+ return { f, builder, before, narrowed: () => watchersLost(before, f.state).length > 0 }}it('is narrowed when a session turns confidential, whatever the command, and not when it becomes its project’s Lead', () => {diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.tsindex 663627054..3ff1cc629 100644--- a/backend/src/superTabs/projects.ts+++ b/backend/src/superTabs/projects.ts@@ -205,7 +205,7 @@ export function canWatchAgent(state: SuperTabState, actor: Actor, target: Agent,/** Who could watch an agent's terminal before a commit and cannot after it (canWatchAgent, by the session the observer relay* watches: machine, harness and machine owner): a person left, the agent left, its project stopped being shared with them,* or the session turned confidential, by whatever command. Each such agent, with the people who lost it. Its observer- * sockets then check again (watchingNarrowed), and those people's terminals on it are revoked (native.ts). */+ * sockets then check again (store.ts accessChanged), and those people's terminals on it are revoked (native.ts). */export function watchersLost(before: SuperTabState, after: SuperTabState): Array<{ agentId: string; personIds: string[] }> {const session = (a: Agent) => `${a.machineId}\n${a.harnessId}\n${a.machineOwnerId}`const now = new Map(after.agents.map(a => [session(a), a]))@@ -225,8 +225,15 @@ export function watchersLost(before: SuperTabState, after: SuperTabState): Array})}-/** Whether a commit narrows who may watch any agent's terminal (watchersLost). */-export const watchingNarrowed = (before: SuperTabState, after: SuperTabState): boolean => watchersLost(before, after).length > 0+/** Everything that decides who reads a conversation and who watches a terminal (canReadGroup, canWatchAgent and the+ * terminals native.ts revokes): when two states give the same text, no access changed between them. Messages, statuses and+ * checks, most commands, change none of it. The Swarm's owner counts only once PRIVATE_VISIBLE_TO_OWNERS is true; it is+ * kept so that turning it on cannot skip a revocation. */+export const accessInputs = (state: SuperTabState): string => JSON.stringify([state.ownerId,+ state.people.map(p => [p.id, p.generation, p.role]),+ projectsOf(state).map(p => [p.id, p.visibility, p.ownerId, p.members, p.leadConversationId]),+ state.agents.map(a => [a.id, a.machineId, a.harnessId, a.machineOwnerId, a.projectId, a.confidential]),+ state.conversations.map(c => [c.id, c.kind, c.projectId, c.leadId, c.archived, c.agentIds, c.audience])])/** The only actors a confidential session admits: the person whose machine runs it, or the session itself. */export const ownSession = (actor: Actor, target: Agent): boolean =>diff --git a/backend/src/superTabs/read/host.ts b/backend/src/superTabs/read/host.tsindex ce4dd9346..837fc4d4e 100644--- a/backend/src/superTabs/read/host.ts+++ b/backend/src/superTabs/read/host.ts@@ -12,7 +12,7 @@ import { machineBillingAllowsDataPlane } from '../../lib/billingState.js'import { fail, type AgentStart, type SuperTabState } from '../model.js'import { GrantReads, type SuperTabStore } from '../store.js'import type { CacheView } from '../cache.js'-import { readLastChangedAt, readMachines } from '../cachedReads.js'+import { readLastChangedAts, readMachines } from '../cachedReads.js'import { retryTransient } from '../retry.js'import * as parts from '../parts/index.js'import type { MachineData, Part } from '../parts/index.js'@@ -67,12 +67,14 @@ export class HostReads {const full = 'reload' in fromconst woken = full ? null : await this.woken(tx, ids, machineId, from.since)const tabs = []- const cached = await this.store.view(woken ? ids.filter(id => woken.has(id)) : ids)+ const answered = woken ? ids.filter(id => woken.has(id)) : ids+ const cached = await this.store.view(answered)+ const newest = await readLastChangedAts(tx, cached, answered)for (const tabId of ids) {if (woken && !woken.has(tabId)) continue// A wake can repeat while the cursor overlaps the same change. Share the timestamp at the read's stamp instead// of scanning every part kind again before the unchanged-etag shortcut.- const lastChangedAt = await readLastChangedAt(tx, cached, tabId), held = request.held?.[tabId]+ const lastChangedAt = newest.get(tabId) ?? null, held = request.held?.[tabId]// The etag is the rows' hash and then the signature of what they were built from. A matching signature answers// 'unchanged' from version columns alone. Never on a full read: grants and billing live outside the parts.const inputs = await cached.get(tabId, 'host:inputs', 'main', () => this.inputs(tx, tabId))diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 51d717eeb..085434fd3 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -18,7 +18,7 @@ import { randomBytes } from 'node:crypto'import type { Readable } from 'node:stream'import { logger } from '../utils/logger.js'import { retryTransient } from './retry.js'-import { canReadAgent, canReadGroup, canWatchAgent, groupProject, ledProject, projectOf, projectsOf, agentProjectId, readConversation, roleVersion, skillModeOf, watchingNarrowed, type ProjectVisibility } from './projects.js'+import { canReadAgent, canReadGroup, canWatchAgent, groupProject, ledProject, projectOf, projectsOf, agentProjectId, readConversation, roleVersion, skillModeOf, type ProjectVisibility } from './projects.js'import { bindSession, makeProjectPrivate } from './sessionScope.js'import { confidentialSessions, otherRegistrations, recordConfidential } from './confidential.js'import { answersRequest, dirtyGroups, noteProjectReports, projectUpdateRequest, UNANSWERED_REQUEST_MS } from './projectUpdates.js'@@ -1067,7 +1067,7 @@ export class SuperTabStore {if (command.type === 'project.sharing' && command.visibility === 'private') {await makeProjectPrivate(tx, effects.state, command.projectId)}- await revokeNativeContexts(tx, original, effects.state)+ const watchersLost = await revokeNativeContexts(tx, original, effects.state)// Rule (b) for claims (design D10): a change to who a conversation's deliveries may reach writes those delivery rows,// so a claim of one conflicts with it. An archived conversation, or one its receiver left, ends them: kept for a// reopening, 6 of the 9 deliveries prod watch found stuck for days on 2026-10-28 waited in archived groups, unread.@@ -1188,7 +1188,7 @@ export class SuperTabStore {}if (command.type === 'project.delete' || command.type.startsWith('project.role')) await this.writeRoleTexts(tx, tabId, effects.state, command)if (effects.terminal) await this.writeTerminal(tx, tabId, effects.terminal, context.now)- if (this.hooks.accessChanged && watchingNarrowed(original, effects.state)) {+ if (this.hooks.accessChanged && watchersLost.length) {const told = this.hooks.accessChangedafterCommit(tx, () => told(tabId))}@@ -1618,12 +1618,13 @@ export class SuperTabStore {* this, so the 16 tasks a release's update outage lost kept their agents busy for good. */private async endRuns(tx: Transaction, tabId: string, before: SuperTabState, after: SuperTabState) {const ended = new Set<string>()+ const earlier = new Map(before.conversations.map(c => [c.id, c])), later = new Map(after.conversations.map(c => [c.id, c]))for (const group of after.conversations) {- const now = group.assignment, was = before.conversations.find(c => c.id === group.id)?.assignment+ const now = group.assignment, was = earlier.get(group.id)?.assignmentif (now && !activeWork(group) && (now.id !== was?.id || now.status !== was.status)) ended.add(now.id)}for (const group of before.conversations.filter(activeWork)) {- const changed = after.conversations.find(c => c.id === group.id)+ const changed = later.get(group.id)if (!changed || !activeWork(changed) || changed.assignment!.id !== group.assignment!.id) ended.add(group.assignment!.id)}await this.releaseRuns(tx, tabId, [...ended])diff --git a/cli/src/lib/productUsageSignals.spec.ts b/cli/src/lib/productUsageSignals.spec.tsindex b6f63fc9d..fa886bf4c 100644--- a/cli/src/lib/productUsageSignals.spec.ts+++ b/cli/src/lib/productUsageSignals.spec.ts@@ -6,6 +6,7 @@ import { failureKind, launchErrorCode, messageReceipt, storeErrorCode, productObimport type { MessageOutcome } from './sessionInput.js'import { LAUNCH_ERROR_CODES, PRODUCT_USAGE_AUTOMATIC_ACTIONS, PRODUCT_USAGE_FLOWS, PRODUCT_USAGE_METRICS, PRODUCT_USAGE_SETUP_METRICS } from './productUsageContract.js'import { AUTOMATIC_POLL_ACTIONS, HEALTH_MEASURES } from './productHealthContract.js'+import { searchRequests } from '../services/search.js'it('separates automated polling, tool and app RPCs without inspecting error objects or content', () => {const emit = vi.fn()@@ -363,6 +364,22 @@ it.each([expect(names.filter(name => name.startsWith('request_') && name.endsWith('_error_other'))).toEqual([])})+// 2026-10-28: 2,225 history page reads from macOS CLI 0.4.97 were `other`, about 12 a minute: a Desktop list re-reading,+// every 5 seconds, a conversation this computer's index no longer held. Its two refusals, as session_tail answers them.+it.each([+ [{}, 'invalid', 'invalid'],+ [{ sessionId: 'gone-session' }, 'invalid', 'not_found'],+])('counts a history page read refused for %o as %s (%s in detail), not `other`', async (payload, kind, detail) => {+ const index = { search: () => { throw new Error('not searched') }, tail: async () => null }+ const reply = await searchRequests(index as never).session_tail(payload, { local: false, owner: true, connection: 'c' })+ const emit = vi.fn()+ productUsageRequest('session_tail', emit, () => 0, 'app')(reply.error, reply.state, false)+ const names: string[] = emit.mock.calls.flat()+ expect(names).toEqual(expect.arrayContaining(['history_page_failed', `history_page_error_${kind}`,+ `request_automatic_history_page_error_${detail}`]))+ expect(names.filter(name => name.endsWith('_error_other'))).toEqual([])+})+it('keeps every refusal a Store install or update can answer in the code list', () => {const codes = new Set<string>()for (const path of ['../dsh/install.ts', '../dsh/update.ts', '../dsh/lock.ts', '../dsh/service.ts', '../services/store.ts']) {diff --git a/cli/src/lib/productUsageSignals.ts b/cli/src/lib/productUsageSignals.tsindex b1b902990..3b0067b54 100644--- a/cli/src/lib/productUsageSignals.ts+++ b/cli/src/lib/productUsageSignals.ts@@ -18,8 +18,11 @@ const setup = new Set(['TMUX_UNAVAILABLE', 'PTY_HOST_UNAVAILABLE', 'TMUX_TOO_OLDconst auth = new Set(['UNAUTHORIZED', 'AUTH_REQUIRED', 'LOGIN_REQUIRED', 'OWNER_REQUIRED', 'E2EE_REQUIRED'])const unavailable = new Set(['SERVICE_UNAVAILABLE', 'SERVICE_FAILED', 'GRID_UNAVAILABLE', 'API_UNAVAILABLE','UNSUPPORTED', 'UNSUPPORTED_ON_REMOTE', 'TIMEOUT', 'NATIVE_UNAVAILABLE'])+// A history page read for no session, or one this computer's index does not hold (services/search.ts): until+// 2026-10-28 both were `other`, 2,225 that day, a Desktop list re-reading a conversation that had left the index.const invalid = new Set(['INVALID_ENGINE', 'INVALID_CWD', 'CWD_NOT_FOUND', 'INVALID_GRID', 'INVALID_DSH', 'INVALID_SWARM_ROLE',- 'INVALID_MODEL', 'INVALID_PERMISSION_MODE', 'INVALID_CREATION_ID', 'INVALID_PROJECT_SOURCE', 'WORKTREE_BUSY'])+ 'INVALID_MODEL', 'INVALID_PERMISSION_MODE', 'INVALID_CREATION_ID', 'INVALID_PROJECT_SOURCE', 'WORKTREE_BUSY',+ 'BAD_SESSION', 'NOT_INDEXED'])/** A Store install's or update's own refusals (dsh/install.ts, dsh/update.ts), by kind. Until 2026-10-28 every one was* `other`: that day's 11 failed installs, all on Windows, said nothing of why. For the Store's requests only, so a* create's or a resume's totals keep their meaning. Its busy and not-installed refusals are named with the others'. */@@ -215,7 +218,7 @@ export function productUsageRequest(type: string, emit: (metric: ProductUsageMet// A Store install's or update's, whatever its kind: the 11 Windows installs of 2026-10-28 were `other`, and// nothing said which refusal. Its family adds up to `store_install_failed` (or `store_update_failed`).if (store) count(`error_code_${storeErrorCode(error)}`)- detail(`error_${failure ? failure : error === 'TIMEOUT' ? 'timeout' : typeof error === 'string' && ['AGENT_NOT_FOUND', 'SESSION_NOT_FOUND', 'NOT_FOUND', 'NOT_INSTALLED'].includes(error) ? 'not_found' : typeof error === 'string' && ['DELETE_IN_PROGRESS', 'WORKTREE_BUSY', 'BUSY', 'DSH_BUSY'].includes(error) ? 'conflict' : kind}`)+ detail(`error_${failure ? failure : error === 'TIMEOUT' ? 'timeout' : typeof error === 'string' && ['AGENT_NOT_FOUND', 'SESSION_NOT_FOUND', 'NOT_FOUND', 'NOT_INSTALLED', 'NOT_INDEXED'].includes(error) ? 'not_found' : typeof error === 'string' && ['DELETE_IN_PROGRESS', 'WORKTREE_BUSY', 'BUSY', 'DSH_BUSY'].includes(error) ? 'conflict' : kind}`)} else if (state === 'pending' || state === 'preparing' || state === 'starting') { count('pending'); detail('pending') }else if (state === 'unconfirmed' || state === 'unavailable' || state === 'cancelled') { count('unknown'); detail(state === 'cancelled' ? 'cancelled' : 'unknown') }else if (!['create', 'resume', 'restart', 'fork'].includes(action) || hasAgent || state === 'created') { count('ok'); detail('ok') }diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.tsindex b132adefc..ee08e947d 100644--- a/cli/src/superTabs/machines.spec.ts+++ b/cli/src/superTabs/machines.spec.ts@@ -1085,6 +1085,55 @@ describe('contributed machine executor', () => {['Swarm start start is waiting: Waiting for the launched engine.']])})+ // Diego's Mac, 2026-10-28: 410 connect timeouts on the reading in two days, and every one dropped that Swarm's starts+ // for the pass with nothing in the log, until the backend's deadline failed them.+ describe('a reading the backend did not take', () => {+ const failReading = (f: ReturnType<typeof fixture>, error: () => unknown) => f.backend.mockImplementation(async (_core, method, path) =>+ path.includes('/hosts/host/changes') ? hostForm([], { pools: [f.pool] }) : method === 'POST' && path.includes('/machines/') ? Promise.reject(error()) : { revision: 1 })++ it('is logged once per error, again when it changes or clears, and the waiting start is still launched', async () => {+ const f = fixture()+ failReading(f, () => new Error('Connect Timeout Error'))+ await f.machine.tick()+ f.advance(); await f.machine.tick()+ expect(f.start).toHaveBeenCalledTimes(2)+ failReading(f, () => new SuperTabHostError('VALIDATION_ERROR', 'Invalid request body', 400))+ f.advance(); await f.machine.tick()+ f.advance(); await f.machine.tick()+ expect(f.start).toHaveBeenCalledTimes(4)+ failReading(f, () => new SuperTabHostError('BACKEND_UNAVAILABLE', 'Could not reach this Super Tab.', 503))+ f.advance(); await f.machine.tick()+ expect(f.start).toHaveBeenCalledTimes(5)+ f.backend.mockImplementation(async (_core, _method, path) => path.includes('/hosts/host/changes') ? hostForm([], { pools: [f.pool] }) : { revision: 1 })+ f.advance(); await f.machine.tick()+ f.advance(); await f.machine.tick()+ expect(f.start).toHaveBeenCalledTimes(7)+ expect(f.log.mock.calls).toEqual([+ ['Could not send this machine\'s reading to Swarm tab: Connect Timeout Error'],+ ['Could not send this machine\'s reading to Swarm tab: Invalid request body'],+ ['Could not send this machine\'s reading to Swarm tab: Could not reach this Super Tab.'],+ ['This machine\'s reading reached Swarm tab again.']])+ })++ it('is logged, and the waiting start still launched, when the local daemon cannot be opened', async () => {+ const f = fixture()+ f.open.mockRejectedValueOnce(new Error('The Harness daemon is not running.'))+ await f.machine.tick()+ expect(f.start).toHaveBeenCalledOnce()+ expect(f.log.mock.calls).toEqual([['Could not send this machine\'s reading to Swarm tab: The Harness daemon is not running.']])+ })++ it('launches nothing when the refusal says this machine lost access to that Swarm', async () => {+ for (const [code, status] of [['CONTRIBUTION_REVOKED', 403], ['HOST_UNAVAILABLE', 403], ['NOT_FOUND', 404], ['UNAUTHORIZED', 401]] as const) {+ const f = fixture()+ failReading(f, () => new SuperTabHostError(code, 'Read the current machine contribution.', status))+ await f.machine.tick()+ expect(f.start).not.toHaveBeenCalled()+ expect(f.log.mock.calls).toEqual([['Could not send this machine\'s reading to Swarm tab: Read the current machine contribution.']])+ }+ })+ })+describe('a start this machine cannot run', () => {const failures = (f: ReturnType<typeof fixture>) => f.backend.mock.calls.filter(c => c[1] === 'POST' && c[2] === '/api/super-tabs/hosts/host/starts/tab/start').map(c => c[3] as { operationId: string; command: { type: string; error?: string } }).filter(body => body.command.type === 'agent.startFailed')diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.tsindex ebf9a14b3..83f4c8fc1 100644--- a/cli/src/superTabs/machines.ts+++ b/cli/src/superTabs/machines.ts@@ -135,6 +135,9 @@ const CLEANING_WAIT = 'Waiting for this machine to finish cleaning up this Swarm/** A pool's starts this host launches: its agents', and its Buddies', which the backend lists apart so that a host from before* Buddies never launches one as a Builder (backend read/hostRows.ts). */const startsOf = (row: Record<string, unknown>) => [...list(row.starts), ...list(row.buddyStarts)]+/** The backend's answer that this machine may no longer act in the Swarm: signed out, its contribution revoked or its host+ * unavailable (backend store.ts observeMachine), or the Swarm gone. */+const lostAccess = (error: unknown) => error instanceof SuperTabHostError && [401, 403, 404].includes(error.status)export class ContributedMachines {private stopped = false@@ -161,6 +164,8 @@ export class ContributedMachines {private readonly toolCache = new Map<string, { value: boolean | null; detail?: string; until: number }>()/** Per waiting start, why it was last not started, so the log says it once per reason, not every pass. */private readonly waiting = new Map<string, string>()+ /** Per tab, why its last reading did not reach the backend, so the log says it once per error and once when it clears. */+ private readonly readingFailures = new Map<string, string>()/** Per waiting start, since when this machine has refused it without a break. */private readonly refusedSince = new Map<string, number>()/** The starts this machine launched whose creation the daemon is still carrying out (fetch, worktree, engine), as its@@ -265,6 +270,18 @@ export class ContributedMachines {this.waiting.set(startId, reason)this.log(`Swarm start ${startId} is waiting: ${reason}`)}+ /** Diego's Mac, 2026-10-28: 410 reading timeouts in two days, none of them in the log. */+ private noteReading(tabId: string, error: unknown) {+ const was = this.readingFailures.get(tabId)+ if (error === null) {+ if (was !== undefined) { this.readingFailures.delete(tabId); this.log(`This machine's reading reached Swarm ${tabId} again.`) }+ return+ }+ const reason = error instanceof Error ? error.message : String(error)+ if (was === reason) return+ this.readingFailures.set(tabId, reason)+ this.log(`Could not send this machine's reading to Swarm ${tabId}: ${reason}`)+ }/** One pass at a time, one [MACHINE_POLL_MS] after the last began (or a beat after one that failed). */tick(): Promise<void> {if (this.stopped || this.deps.now() < this.next) return Promise.resolve()@@ -305,13 +322,14 @@ export class ContributedMachines {private async poll(began: number) {const where = { dataDir: this.core.dataDir, port: this.core.daemon.port, machineId: this.machineId }const pools = list((await this.sources.feed.current(POOLS_FRESH_MS)).pools).filter(row => identifier(row.tabId) && object(row.machine).machineId === this.machineId && identifier(object(row.machine).generation))- if (this.stopped || pools.length === 0) { this.published.clear(); this.lastSent.clear(); this.waiting.clear(); return }+ if (this.stopped || pools.length === 0) { this.published.clear(); this.lastSent.clear(); this.waiting.clear(); this.readingFailures.clear(); return }const pendingIds = new Set(pools.flatMap(row => startsOf(row).map(start => start.id)))for (const id of this.waiting.keys()) if (!pendingIds.has(id)) this.waiting.delete(id)for (const id of this.refusedSince.keys()) if (!pendingIds.has(id)) this.refusedSince.delete(id)for (const id of this.preparing) if (!pendingIds.has(id)) this.preparing.delete(id)for (const tab of this.published.keys()) if (!pools.some(row => row.tabId === tab)) this.published.delete(tab)for (const tab of this.lastSent.keys()) if (!pools.some(row => row.tabId === tab)) this.lastSent.delete(tab)+ for (const tab of this.readingFailures.keys()) if (!pools.some(row => row.tabId === tab)) this.readingFailures.delete(tab)const privacy = this.privacy()// A model run or stopped for a Swarm, or an API shared with it, is sent on this pass, not on the next beat: the// machine's panel waited up to 15 s more for it (2026-10-26). Files only, so a pass with nothing new asks nobody.@@ -349,6 +367,7 @@ export class ContributedMachines {const last = this.published.get(String(row.tabId))// A model still starting is read again every pass until the grid lists it, so the panel shows it live at once.if (!last || last.signature !== signature || last.starting || began - last.at >= MACHINE_HEARTBEAT_MS) {+ try {local ??= await this.deps.open(where)// The existing usage reader owns its provider cache. Raw responses and// account credentials never leave this machine.@@ -461,8 +480,15 @@ export class ContributedMachines {}}this.published.set(String(row.tabId), { at: began, signature, starting: !!localModels?.some(m => m.starting) })- } catch (error) { this.failed = true; throw error }- finally { this.sending.delete(String(row.tabId)) }+ } finally { this.sending.delete(String(row.tabId)) }+ this.noteReading(String(row.tabId), null)+ } catch (error) {+ this.failed = true+ this.noteReading(String(row.tabId), error)+ // Only a refusal that this machine lost access to the Swarm stops its starts; a timeout, a 5xx or a reading the+ // backend would not validate says nothing about the starts, which keep their own receipts (Diego's Mac, 2026-10-28).+ if (lostAccess(error)) throw error+ }}this.repairTrust ??= createSwarmCloneTrustRepair(this.core, this.deps.now)try { await this.repairTrust(row) }diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex ccc296b7f..e0e883b56 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -14171,10 +14171,28 @@ class AppNotifier extends ChangeNotifier {String sessionId, {int? beforeTurn,int? maxChars,+ }) async {+ final reply = await readSessionTailReply(+ machineId,+ sessionId,+ beforeTurn: beforeTurn,+ maxChars: maxChars,+ );+ return reply == null || reply['error'] != null ? null : reply;+ }++ /// [readSessionTail]'s reply with its refusal kept (`NOT_INDEXED`: the+ /// machine's index no longer holds the session). Null when the machine did+ /// not answer.+ Future<Map<String, dynamic>?> readSessionTailReply(+ String machineId,+ String sessionId, {+ int? beforeTurn,+ int? maxChars,}) async {if (!searchableMachineIds.contains(machineId)) return null;try {- final reply = await _conn(machineId).request(+ return await _conn(machineId).request('session_tail',payload: {'sessionId': sessionId,@@ -14183,8 +14201,6 @@ class AppNotifier extends ChangeNotifier {},timeout: const Duration(seconds: 4),);- if (reply['error'] != null) return null;- return reply;} catch (_) {return null;}diff --git a/desktop/lib/state/session_activity.dart b/desktop/lib/state/session_activity.dartindex 351e956b7..9d2a3d0f3 100644--- a/desktop/lib/state/session_activity.dart+++ b/desktop/lib/state/session_activity.dart@@ -20,6 +20,11 @@ class SessionActivityController extends ChangeNotifier {final AppNotifier app;final _external = <String, SessionActivity>{};++ /// Rows whose machine said its index no longer holds the conversation: not+ /// read again until the rows on screen change. Re-read every 5 seconds, one+ /// such row was 2,225 failed reads on its computer in an evening (2026-10-28).+ final _notHeld = <String>{};Map<String, SwarmDestination> _rows = const {};Map<String, SessionActivity> _last = const {};Timer? _timer;@@ -67,6 +72,8 @@ class SessionActivityController extends ChangeNotifier {if (!changed) return;_revision++;_external.removeWhere((id, _) => !next.containsKey(id));+ // A conversation that came back to the index shows again.+ _notHeld.clear();_timer?.cancel();if (next.values.any((row) => row.external != null)) {_timer = Timer.periodic(const Duration(seconds: 5), (_) => refresh());@@ -89,7 +96,9 @@ class SessionActivityController extends ChangeNotifier {final revision = _revision;try {await Future.wait([- for (final row in _rows.values.where((row) => row.external != null))+ for (final row in _rows.values.where(+ (row) => row.external != null && !_notHeld.contains(row.id),+ ))_readExternal(row, revision),]);} finally {@@ -104,13 +113,18 @@ class SessionActivityController extends ChangeNotifier {}Future<void> _readExternal(SwarmDestination row, int revision) async {- final reply = await app.readSessionTail(+ final reply = await app.readSessionTailReply(row.machineId!,row.external!.sessionId,maxChars: 1000,);if (_disposed || revision != _revision) return;- if (reply == null) {+ if (reply?['error'] == 'NOT_INDEXED') {+ _notHeld.add(row.id);+ _external[row.id] = (at: read(row).at, status: null);+ return;+ }+ if (reply == null || reply['error'] != null) {// A failed read cannot keep claiming work is still in progress._external[row.id] = (at: read(row).at, status: HarnessActivity.unknown);return;diff --git a/desktop/test/session_activity_test.dart b/desktop/test/session_activity_test.dartindex 8fcee6db8..2d8d7eca2 100644--- a/desktop/test/session_activity_test.dart+++ b/desktop/test/session_activity_test.dart@@ -4,6 +4,8 @@ import 'package:harness/core/models.dart';import 'package:harness/notify/alert_sounds.dart';import 'package:harness/state/harness_activity.dart';import 'package:harness/state/session_activity.dart';+import 'package:harness/state/session_content_search.dart';+import 'package:harness/state/swarm_navigation.dart' show SwarmDestination;import 'package:harness/state/swarm_search.dart';import 'package:harness/widgets/desktop_chrome.dart';import 'package:harness/widgets/harness_activity_mark.dart';@@ -168,6 +170,66 @@ void main() {);}+ // 2026-10-28: one row like this, re-read every 5 seconds, was 2,225 failed+ // history reads on its computer in an evening.+ testWidgets(+ 'a conversation its computer no longer holds is not re-read until the list changes',+ (tester) async {+ final reads = <String>[];+ final connection = TailConnection(+ const {},+ tail: (payload) {+ final session = payload['sessionId'] as String;+ reads.add(session);+ return session == 'gone'+ ? {'error': 'NOT_INDEXED', 'sessionId': session}+ : {+ 'lastAt': 0,+ 'external': {'open': false},+ 'rows': <Object>[],+ 'total': 0,+ 'hasMore': false,+ };+ },+ );+ final app = createApp(+ connected: true,+ connectionForTest: (_) => connection,+ );+ addTearDown(app.dispose);+ SwarmDestination row(String session) {+ final hit = SessionContentHit.fromJson('m', {+ 'agentId': '',+ 'sessionId': session,+ 'engine': 'claude',+ 'field': 'name',+ 'snippet': '',+ 'external': {'title': session, 'cwd': '/work/api'},+ })!;+ return externalSessionDestination(hit, hit.external!);+ }++ final gone = row('gone'), held = row('held');+ final activity = SessionActivityController(app);+ activity.watch([gone, held]);+ await tester.pump();+ expect(reads, ['gone', 'held']);++ await tester.pump(const Duration(seconds: 30));+ expect(reads.where((s) => s == 'gone'), hasLength(1));+ expect(reads.where((s) => s == 'held'), hasLength(7));+ expect(activity.read(gone).status, isNull);++ // A changed list asks once more: a conversation that came back shows.+ activity.watch([gone]);+ await tester.pump();+ expect(reads.where((s) => s == 'gone'), hasLength(2));+ await tester.pump(const Duration(seconds: 30));+ expect(reads.where((s) => s == 'gone'), hasLength(2));+ activity.dispose();+ },+ );+test('managed sessions read current activity independently of their ranking snapshot', () async {final app = createApp(connected: true);addTearDown(app.dispose);