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.

Keep Swarm teammates' read-only terminal views alive and explain when one is not shared (#1627)

Jacob Pham477fc7048d40
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index e7626af41..63906622e 100644
--- a/cli/src/core/api.spec.ts
+++ b/cli/src/core/api.spec.ts
@@ -196,7 +196,7 @@ describe('the core API services stand on', () => {
expect(createCoreApi({ ...deps, cloud }).cloud).toBe(cloud)
// The Super Tab service's door, the same way.
expect(core.superTabs).toBeUndefined()
- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn() }
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }
expect(createCoreApi({ ...deps, superTabs }).superTabs).toBe(superTabs)
// The devices' way to its card requests, the same way.
expect(core.superTabRequest).toBeUndefined()
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index b4746a2e5..d2c8761a3 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -1182,6 +1182,10 @@ export interface SuperTabsCore {
cards(items: SwarmCard[]): void
/** What one Lead last said, pushed when the recap on a Harness Pro's screen moved on. */
cardRecap(recap: LeadRecap): void
+ /** Members may watch an agent of this machine's: Share must run to invite them (superTabs/observers.ts). Its saved
+ * state wakes it only as the core starts, so a machine that joined a Swarm while running never invited anyone and
+ * each member's pane read "must be online" (River on a contributed machine, 2026-10-23). */
+ shareObservers(): void
}
/** What the cloud service answers the core: done, or why not, in words a person reads. */
diff --git a/cli/src/core/experimentQueries.spec.ts b/cli/src/core/experimentQueries.spec.ts
index 0c0afbd1c..e5fadad49 100644
--- a/cli/src/core/experimentQueries.spec.ts
+++ b/cli/src/core/experimentQueries.spec.ts
@@ -28,7 +28,7 @@ describe('the cloud agents\' doors', () => {
describe('the Super Tab service\'s door', () => {
it('is the Super Tab service\'s alone, and hands its members\' waits to the core whole', async () => {
- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn() }
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }
const core = fakeCore({ superTabs })
const both = new Set(['orchestrator', 'superTabs'])
const item = { agentId: 'a1', requestId: 'supertab:x:blocked', superTab: 'Pilot', attention: 'stuck', text: 'Stuck: no key' }
@@ -41,7 +41,7 @@ describe('the Super Tab service\'s door', () => {
})
it('hands it the Swarm cards and a Lead\'s recap the same way, to the Super Tab service alone', async () => {
- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn() }
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }
const core = fakeCore({ superTabs })
const both = new Set(['orchestrator', 'superTabs'])
const recap = { tabId: 't1', leadId: 'l1', text: 'Shipped', at: 1, none: false }
@@ -51,11 +51,17 @@ describe('the Super Tab service\'s door', () => {
expect(superTabs.cards).toHaveBeenLastCalledWith([])
expect(await answerExperimentQuery(core, both, 'superTabs', 'super_tab_card_recap', { recap })).toEqual({})
expect(superTabs.cardRecap).toHaveBeenLastCalledWith(recap)
- for (const query of ['super_tab_cards', 'super_tab_card_recap']) {
+ for (const query of ['super_tab_cards', 'super_tab_card_recap', 'super_tab_observers']) {
expect(await answerExperimentQuery(core, both, 'orchestrator', query, {})).toEqual({ error: 'NOT_SUPER_TABS' })
expect(await answerExperimentQuery(fakeCore(), both, 'superTabs', query, {})).toEqual({ error: 'NOT_SUPER_TABS' })
}
})
+
+ it('asks for Share when a Swarm host here has members to show its agents to', async () => {
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }
+ expect(await answerExperimentQuery(fakeCore({ superTabs }), new Set(['superTabs']), 'superTabs', 'super_tab_observers', {})).toEqual({})
+ expect(superTabs.shareObservers).toHaveBeenCalledOnce()
+ })
})
describe('what an experiment in its own process may ask of the core', () => {
diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.ts
index cc32d53bd..d967d35dd 100644
--- a/cli/src/core/experimentQueries.ts
+++ b/cli/src/core/experimentQueries.ts
@@ -22,7 +22,9 @@
* - `super_tab_attention`: the Super Tab members here waiting on a person (`core.superTabs`,
* core/superTabAttention.ts), for the Super Tab service alone;
* - `super_tab_cards`, `super_tab_card_recap`: the Swarms' cards and a Lead's last message for the Harness Pro
- * (`core.superTabs`, core/superTabCards.ts), for the Super Tab service alone.
+ * (`core.superTabs`, core/superTabCards.ts), for the Super Tab service alone;
+ * - `super_tab_observers`: members may watch an agent here, so Share must run (`core.superTabs`), for the Super Tab
+ * service alone.
* The core answers them only for the experiments (core/api.ts `EXPERIMENTS`): creating an agent or
* telling the windows something is no other process's to ask. The process's side is
* services/processCoreApi.ts. Agent Messages, an experiment until 2026-10-12, asks a few of the same and is
@@ -36,7 +38,7 @@ import { nativeTurnCursorIn } from '../lib/nativeTurnObservations.js'
type Payload = Record<string, unknown>
type Core = Pick<CoreApi, 'agents' | 'turns' | 'clients' | 'daemon' | 'account' | 'cloud' | 'superTabs' | 'transcripts'>
-const QUERIES: ReadonlySet<string> = new Set(['shown', 'close_swarm', 'stopped', 'gone', 'creation_status', 'native_turns', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'account', 'cloud_publish', 'cloud_ask', 'cloud_unask', 'super_tab_attention', 'super_tab_cards', 'super_tab_card_recap'])
+const QUERIES: ReadonlySet<string> = new Set(['shown', 'close_swarm', 'stopped', 'gone', 'creation_status', 'native_turns', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'account', 'cloud_publish', 'cloud_ask', 'cloud_unask', 'super_tab_attention', 'super_tab_cards', 'super_tab_card_recap', 'super_tab_observers'])
const METHODS: ReadonlySet<string> = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
const text = (value: unknown): string => (typeof value === 'string' ? value : '')
@@ -150,6 +152,10 @@ export async function answerExperimentQuery(core: Core, experiments: ReadonlySet
else core.superTabs.cardRecap(payload.recap as never)
return {}
}
+ case 'super_tab_observers':
+ if (service !== 'superTabs' || !core.superTabs) return { error: 'NOT_SUPER_TABS' }
+ core.superTabs.shareObservers()
+ return {}
case 'account': {
const known = await core.account.identity()
return known ? { ...known } : { error: 'ACCOUNT_UNAVAILABLE' }
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 7327297ab..9a3162d1d 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -870,7 +870,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const coreApi = createCoreApi({
nativeTurns: async (agentId, cursor) => nativeTurns.read(agentId, cursor),
cloud: cloudDoors,
- superTabs: { attention: (items) => superTabWaits.attention(items), cards: (items) => superTabCards.cards(items), cardRecap: (recap) => superTabCards.recap(recap) },
+ superTabs: { attention: (items) => superTabWaits.attention(items), cards: (items) => superTabCards.cards(items), cardRecap: (recap) => superTabCards.recap(recap),
+ // In the core's own process Share was started with it; out of it, the master starts Share's process.
+ shareObservers: () => { if (outOfProcess.has('sharing')) coreLink.want('sharing') } },
// The devices' `cardsWanted`, `cardRecap` and `cardOpen`, and no other action of the Super Tab service (core/superTabCards.ts `ask`).
superTabRequest: (payload) => superTabCards.ask(payload),
cloudRows: () => (cloudAgents?.dialRows() ?? []) as unknown as RegisteredSession[],
diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.ts
index c7df12e60..3c8ccabe0 100644
--- a/cli/src/services/processCoreApi.spec.ts
+++ b/cli/src/services/processCoreApi.spec.ts
@@ -227,9 +227,11 @@ describe('the core API a light service runs on in its own process', () => {
const recap = { tabId: 't1', leadId: 'l1', text: 'Shipped', at: 1, none: false }
doors.cards([])
doors.cardRecap(recap)
+ doors.shareObservers()
await new Promise((resolve) => setTimeout(resolve, 0))
expect(ask).toHaveBeenCalledWith('super_tab_cards', { items: [] })
expect(ask).toHaveBeenCalledWith('super_tab_card_recap', { recap })
+ expect(ask).toHaveBeenCalledWith('super_tab_observers', {})
})
it('acts on the core for an experiment: agents made, turns stopped and delivered, windows told, each asked', async () => {
diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.ts
index b28317fb2..ac3b1fceb 100644
--- a/cli/src/services/processCoreApi.ts
+++ b/cli/src/services/processCoreApi.ts
@@ -243,6 +243,7 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie
// The Swarm cards, whole each time they change, and one Lead's recap (core/superTabCards.ts).
cards: (items) => { void ask('super_tab_cards', { items }).catch(() => {}) },
cardRecap: (recap) => { void ask('super_tab_card_recap', { recap }).catch(() => {}) },
+ shareObservers: () => { void ask('super_tab_observers', {}).catch(() => {}) },
} satisfies SuperTabsCore,
} : {}),
}
diff --git a/cli/src/services/sharing.ts b/cli/src/services/sharing.ts
index d90452b5c..3b7678c03 100644
--- a/cli/src/services/sharing.ts
+++ b/cli/src/services/sharing.ts
@@ -61,7 +61,7 @@ export function startSharing(core: CoreApi, ports: CorePorts, options: SharingOp
const viewers = options.viewers ?? new SharedViewerPool(viewerPage(core))
const superTabs = observerSource(core.dataDir, () => core.daemon.machineId())
const owner = new HarnessShareOwner({
- derivedGrants: superTabs.current,
+ derivedGrants: superTabs.known,
allowsGrant: superTabs.allows,
machineId: () => core.daemon.machineId(),
key: {
diff --git a/cli/src/sharing/owner.spec.ts b/cli/src/sharing/owner.spec.ts
index 79a942f47..30e8e030e 100644
--- a/cli/src/sharing/owner.spec.ts
+++ b/cli/src/sharing/owner.spec.ts
@@ -301,6 +301,30 @@ describe('owner authority and read-only observation', () => {
expect(frames.at(-1)).toMatchObject({ id: 'observer:new', type: 'observer_closed' })
})
+ it('keeps Swarm invitations while no roster is in force, and withdraws one only when its member leaves', async () => {
+ await owner.stop()
+ rosters.mockResolvedValue(null)
+ const carol = { agentId: 'agent', email: '[email protected]', tab: 'super:tab', name: 'api', engine: 'codex' }
+ let known: Array<typeof carol> | null = [carol]
+ owner = new HarnessShareOwner({ machineId: () => machineId, identity, grants: store, rosters,
+ derivedGrants: () => known, resolveAgent: id => agents.get(id), send, publish, terminals: {} as TerminalBackendCoordinator })
+ await derive()
+ expect(publish.mock.calls.map(c => c[0])).toEqual(['PUT'])
+ // The host stalled: its roster lapsed. Neither the clock's derivation nor a nudge withdraws or sends anything again.
+ known = null
+ await vi.advanceTimersByTimeAsync(3000); await owner.sync()
+ expect(await derive()).toEqual({ invited: 0, revoked: 0 })
+ known = [carol]
+ await vi.advanceTimersByTimeAsync(3000); await owner.sync()
+ expect(publish.mock.calls.map(c => c[0])).toEqual(['PUT'])
+ expect(carolOf().revoked).toBe(false)
+ // A roster in force that no longer lists her is a real change: withdrawn at the next tick.
+ known = []
+ await vi.advanceTimersByTimeAsync(1000); await owner.sync()
+ expect(carolOf().revoked).toBe(true)
+ expect(publish.mock.calls.map(c => c[0])).toEqual(['PUT', 'DELETE'])
+ })
+
it('derives a grant for every other account in the tab, publishes it, and lets that observer watch', async () => {
holding(tab())
expect(await derive()).toEqual({ invited: 2, revoked: 0 })
diff --git a/cli/src/sharing/owner.ts b/cli/src/sharing/owner.ts
index cbef973c7..33fccdf2e 100644
--- a/cli/src/sharing/owner.ts
+++ b/cli/src/sharing/owner.ts
@@ -40,7 +40,9 @@ export interface ShareOwnerDeps {
/** The shared tabs' rosters this computer verified against their pins, and the account signed in here, which the
* observers each tab wants are derived from (`harness_share_rosters`); null when either cannot be read. */
rosters?: () => Promise<{ accountId: string; rosters: Roster[]; consent: ReadonlySet<string> } | null>
- derivedGrants?: () => Array<Omit<DerivedGrant, 'ownerPublicKey'>>
+ /** The Swarm observers this machine's host wants, or null while no roster of its is in force (superTabs/observers.ts
+ * `known`): their invitations are then kept as they are, neither withdrawn nor sent again. */
+ derivedGrants?: () => Array<Omit<DerivedGrant, 'ownerPublicKey'>> | null
allowsGrant?: (grant: HarnessGrant) => boolean
now?: () => number
}
@@ -78,7 +80,10 @@ export class HarnessShareOwner {
// Derived again every 30 s: the renewals fall due, and a roster change whose nudge never came is caught here. A
// refused grant is tried again at most hourly from here: up to 256 of them every 30 s would hammer the backend.
// One already waiting to run makes another pointless; it publishes what waits as it ends.
- const signature = JSON.stringify(this.deps.derivedGrants?.() ?? [])
+ // A roster no longer in force is no change of membership: deriving from it withdrew every Swarm invitation and
+ // sent it again a moment later (superTabs/observers.ts `OBSERVER_VALID_MS`).
+ const derived = this.deps.derivedGrants?.()
+ const signature = derived === null ? derivedSignature : JSON.stringify(derived ?? [])
const changed = signature !== derivedSignature
derivedSignature = signature
if ((++ticks % 30 === 0 || changed) && this.derivesQueued === 0) void this.derive(this.now() - HOUR).catch(ignore)
@@ -270,10 +275,13 @@ export class HarnessShareOwner {
const source = await this.deps.rosters?.().catch(() => null)
if (!source && !this.deps.derivedGrants) return { invited: 0, revoked: 0 }
const machineId = this.deps.machineId()
- const legacy = source ? rosterGrants(source.rosters, { machineId, accountId: source.accountId }, source.consent)
- : this.deps.grants.all().filter(g => g.machineId === machineId && g.tab && !g.tab.startsWith('super:') && !g.revoked)
- .map(g => ({ agentId: g.agentId, email: g.recipientEmail, tab: g.tab!, name: g.name, engine: g.engine }))
- const wanted = [...legacy, ...this.deps.derivedGrants?.() ?? []]
+ // What is held of one kind, kept as it is when what decides that kind cannot be read now.
+ const kept = (swarm: boolean) => this.deps.grants.all()
+ .filter(g => g.machineId === machineId && g.tab && g.tab.startsWith('super:') === swarm && !g.revoked)
+ .map(g => ({ agentId: g.agentId, email: g.recipientEmail, tab: g.tab!, name: g.name, engine: g.engine }))
+ const legacy = source ? rosterGrants(source.rosters, { machineId, accountId: source.accountId }, source.consent) : kept(false)
+ const derived = this.deps.derivedGrants?.()
+ const wanted = [...legacy, ...derived === null ? kept(true) : derived ?? []]
// Asked only when there is something to grant: in Share's own process each ask goes to the gateway.
const key = wanted.length ? await this.ownerPublicKey().catch(() => null) : ''
// Without this machine's key (its gateway is down) nothing new can be published, but a member who left must still
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index cbe8b5c87..a0370e5a5 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -7,6 +7,7 @@ import type { CoreApi, TurnDelivery } from '../core/api.js'
import { fakeCore } from '../testing/fakeCore.js'
import { backend, swarmRoleFor, hostJournalFile, SuperTabHost } from './host.js'
import { retainedHarnesses, retentionFile } from './retention.js'
+import { observerSource } from './observers.js'
const roots: string[] = []
const hosts: SuperTabHost[] = []
@@ -555,7 +556,7 @@ describe('Super Tab waits for the Harness Pro', () => {
if (offline) throw new Error('Host offline')
return { status: 200, body: { success: true, data: path.includes('/hosts/') ? rows : [] } }
})
- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn() }
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }
const core = fakeCore({ dataDir: dir, superTabs, account: { backend: call },
agents: { creationStatus: vi.fn(async creationId => ({ creationId, state: 'created' as const, agentId: 'harness' })), byAgent: vi.fn(() => ({ agentId: 'harness' }) as never), terminalAvailable: vi.fn(() => true) } })
const open = () => { const host = new SuperTabHost(core, 'machine-1', { log: vi.fn() }); hosts.push(host); return host }
@@ -592,7 +593,7 @@ describe('Super Tab waits for the Harness Pro', () => {
agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1' } }]
const call: CoreApi['account']['backend'] = vi.fn(async (_method, path) => ({ status: 200, body: { success: true, data: path.includes('/hosts/') ? rows : [] } }))
let here = true, clock = 0
- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn() }
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }
const core = fakeCore({ dataDir: dir, superTabs, account: { backend: call },
agents: { byAgent: vi.fn(() => (here ? { agentId: 'harness' } : undefined) as never), terminalAvailable: vi.fn(() => true) } })
const host = new SuperTabHost(core, 'machine-1', { log: vi.fn(), now: () => clock }); hosts.push(host)
@@ -910,6 +911,52 @@ it('rechecks authoritative native absence before retrying a lost acknowledgement
expect(t.close).toHaveBeenLastCalledWith({ agentId: 'harness' })
})
+describe('the members a host lets watch its agents', () => {
+ it('keeps them watching through a 3 s roster read, wakes Share once, and lets a removed member go at once', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'super-tab-host-')); roots.push(dir)
+ const member = { tabId: 'tab', agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1', name: 'River' },
+ observers: [{ email: '[email protected]', userId: 'peer' }] }
+ let rows: unknown[] = [member], clock = 0, answer: (() => void) | null = null
+ const call: CoreApi['account']['backend'] = vi.fn(async (_method, path) => {
+ // The roster read takes 3 s when asked to (seen up to 2.8 s, 2026-10-23); everything else answers at once.
+ if (path.includes('/hosts/') && answer === null) await new Promise<void>(resolve => { answer = resolve })
+ return { status: 200, body: { success: true, data: path.includes('/hosts/') ? rows : [] } }
+ })
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }
+ const core = fakeCore({ dataDir: dir, superTabs, account: { backend: call },
+ agents: { byAgent: vi.fn(() => ({ agentId: 'harness' }) as never), terminalAvailable: vi.fn(() => true) } })
+ const host = new SuperTabHost(core, 'machine-1', { log: vi.fn(), now: () => clock }); hosts.push(host)
+ const source = observerSource(dir, () => 'machine-1', () => clock)
+ const peer = { tab: 'super:tab', agentId: 'harness', recipientEmail: '[email protected]' } as never
+ const read = async () => { const reading = host.tick(); await vi.waitFor(() => expect(answer).not.toBeNull()); answer!(); await reading; answer = null }
+ await read()
+ expect(source.allows(peer)).toBe(true)
+ // The next read is asked a second later and answers 3 s after that: the roster in force never lapses meanwhile.
+ for (let i = 0; i < 4; i++) {
+ clock += 1_000
+ const reading = host.tick()
+ await vi.waitFor(() => expect(answer).not.toBeNull())
+ clock += 3_000
+ expect(source.allows(peer)).toBe(true)
+ expect(source.known()).toHaveLength(1)
+ answer!(); await reading; answer = null
+ }
+ expect(superTabs.shareObservers).toHaveBeenCalledOnce()
+ // Removed from the Swarm: the very next answer takes the view away and tells Share everyone left.
+ rows = []
+ clock += 1_000; await read(); clock += 201
+ expect(source.allows(peer)).toBe(false)
+ expect(source.known()).toEqual([])
+ // A host that stops publishes nobody, in force: Share withdraws the invitations rather than keeping them.
+ rows = [member]
+ clock += 1_000; await read(); clock += 201
+ expect(source.known()).toHaveLength(1)
+ host.stop(); clock += 201
+ expect(source.known()).toEqual([])
+ expect(superTabs.shareObservers).toHaveBeenCalledOnce()
+ })
+})
+
describe('adding the machine its own Lead runs on to the Swarm', () => {
function joining() {
const dir = mkdtempSync(join(tmpdir(), 'super-tab-join-')); roots.push(dir)
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index 2920de9fe..0c923083f 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -1,4 +1,4 @@
-import { publishObservers } from './observers.js'
+import { OBSERVER_VALID_MS, publishObservers } from './observers.js'
import { ContributedMachines } from './machines.js'
import { retainContributions } from './retention.js'
import { configurationObservation } from './configuration.js'
@@ -136,6 +136,8 @@ export class SuperTabHost {
private readonly log: (message: string) => void
private retentionError: string | null = null
private readonly observers: typeof publishObservers
+ /** Share was asked to run once a roster here first named someone to show an agent to. */
+ private shareWoken = false
private readonly attachedFiles: typeof attachedFiles
private readonly prepareContribution: typeof prepareContribution
/** Per tab the roster marks, the add in progress or when the next may run. */
@@ -237,7 +239,9 @@ export class SuperTabHost {
this.native?.stop()
this.machines?.stop()
this.authorized.clear()
- try { this.observers(this.core.dataDir, this.machineId, [], 0) } catch { /* The old snapshot expires. */ }
+ // An empty roster in force, which Share reads as everyone gone and withdraws their invitations; a lapsed one
+ // would only pause their views (superTabs/observers.ts `known`).
+ try { this.observers(this.core.dataDir, this.machineId, [], this.now() + OBSERVER_VALID_MS) } catch { /* The old snapshot expires. */ }
// Signed out or another machine: this host's alerts are no longer anyone's. A core that is gone heard nothing, and
// the next host's first roster replaces them anyway.
if (this.attention !== null && this.attention !== '[]') {
@@ -437,7 +441,6 @@ export class SuperTabHost {
return this.core.turns.leaseDeliveries('superTabs', Object.fromEntries(this.authorized))
}
private async poll(): Promise<void> {
- const requestedAt = this.now()
const data = await backend(this.core, 'GET', `/api/super-tabs/hosts/${this.machineId}`)
if (this.stopped) return
if (!Array.isArray(data)) throw new Error('Invalid Super Tab host roster.')
@@ -452,7 +455,9 @@ export class SuperTabHost {
if (message !== this.retentionError) this.log(message)
this.retentionError = message
}
- this.observers(this.core.dataDir, this.machineId, data, requestedAt + 2500)
+ // Valid from this answer until the next is due, slow reads included, so it never lapses between two reads.
+ this.observers(this.core.dataDir, this.machineId, data, this.now() + OBSERVER_VALID_MS)
+ this.wakeShare(data)
this.publishAttention(data)
this.joinSwarms(data)
// Recovery can wait on a native receipt. Run it beside leases, so another worker's input
@@ -602,6 +607,12 @@ export class SuperTabHost {
/** Hands the core this roster's waits when they changed (or on the first roster). A failed roster read changes
* nothing: a network blip does not close an alert. */
+ private wakeShare(rows: unknown[]): void {
+ if (this.shareWoken || !rows.some(row => Array.isArray((row as { observers?: unknown }).observers)
+ && ((row as { observers: unknown[] }).observers.length > 0))) return
+ this.shareWoken = true
+ this.core.superTabs?.shareObservers()
+ }
private publishAttention(rows: unknown[]): void {
// A harness the core's live list misses for a moment (a process-side snapshot between reads, a restart of its
// terminal) keeps its wait for 3 s: closing and raising it again would alert twice for the same wait.
diff --git a/cli/src/superTabs/observers.spec.ts b/cli/src/superTabs/observers.spec.ts
index 3a9d082ee..e79e64e5d 100644
--- a/cli/src/superTabs/observers.spec.ts
+++ b/cli/src/superTabs/observers.spec.ts
@@ -6,7 +6,7 @@ import { b64e, newEphemeral, newIdentity } from '../lib/e2ee/core.js'
import { recipientHandshake } from '../sharing/crypto.js'
import { HarnessGrantStore } from '../sharing/grants.js'
import { HarnessShareOwner } from '../sharing/owner.js'
-import { observerSnapshotFile, observerSource, publishObservers } from './observers.js'
+import { OBSERVER_VALID_MS, observerSnapshotFile, observerSource, publishObservers } from './observers.js'
it('expires session authority and closes an existing encrypted terminal observer after removal', async () => {
const dir = mkdtempSync(join(tmpdir(), 'super-observer-')), key = newIdentity()
@@ -48,3 +48,26 @@ it('expires session authority and closes an existing encrypted terminal observer
expect(source.current()).toEqual([])
} finally { await owner.stop(); rmSync(dir, { recursive: true, force: true }) }
})
+
+it('tells a lapsed roster apart from one in force that names nobody, and accepts no roster valid for longer', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'super-observer-'))
+ let now = 1_000_000
+ const source = observerSource(dir, () => 'machine', () => now)
+ const rows = [{ tabId: 'tab', agent: { machineId: 'machine', harnessId: 'native', name: 'Builder', configuration: {} },
+ observers: [{ email: '[email protected]' }] }]
+ try {
+ expect(source.known()).toBeNull()
+ publishObservers(dir, 'machine', rows, now + OBSERVER_VALID_MS); now += 201
+ expect(source.known()).toEqual([{ tab: 'super:tab', agentId: 'native', email: '[email protected]', name: 'Builder', engine: null }])
+ // Read again after the cache's 200 ms, a moment before it lapses: still in force.
+ now += OBSERVER_VALID_MS - 202
+ expect(source.known()).toHaveLength(1)
+ now += 1
+ expect(source.known()).toBeNull()
+ expect(source.current()).toEqual([])
+ publishObservers(dir, 'machine', [], now + OBSERVER_VALID_MS); now += 201
+ expect(source.known()).toEqual([])
+ publishObservers(dir, 'machine', rows, now + OBSERVER_VALID_MS + 1000); now += 201
+ expect(source.known()).toBeNull()
+ } finally { rmSync(dir, { recursive: true, force: true }) }
+})
diff --git a/cli/src/superTabs/observers.ts b/cli/src/superTabs/observers.ts
index 769a0c504..fe24bff81 100644
--- a/cli/src/superTabs/observers.ts
+++ b/cli/src/superTabs/observers.ts
@@ -8,6 +8,15 @@ const PREFIX = 'super:'
export function superTabOf(grant: Pick<HarnessGrant, 'tab'>): string | null {
return grant.tab?.startsWith(PREFIX) ? grant.tab.slice(PREFIX.length) : null
}
+/** How long a published roster authorizes its observers, counted from the roster read that answered: the host's
+ * refresh cadence (superTabs/host.ts reads the roster each second) plus a margin for a slow read. It was 2.5 s from
+ * the moment a read was ASKED, while the roster read took 1 to 2.8 s: measured 2026-10-23 on MacBookPro2021, the
+ * snapshot lapsed 4 times in 30 s, every lapse closed each member's view ("Reconnecting · View only", reloading
+ * forever) and withdrew and sent again every invitation, which told each member's apps to read their machine lists
+ * again about 1.5 times a second. A removed member still loses the view at the next answer, which no longer lists
+ * them, and the backend checks membership again for every observer connection (routes/harnessShares.ts). */
+export const OBSERVER_REFRESH_MS = 1_000, OBSERVER_SLOW_READ_MS = 10_000
+export const OBSERVER_VALID_MS = OBSERVER_REFRESH_MS + OBSERVER_SLOW_READ_MS
export function observerSnapshotFile(dataDir: string, machineId: string) {
return join(dataDir, 'super-tabs', `observers-${machineId}.json`)
}
@@ -31,7 +40,7 @@ export function publishObservers(dataDir: string, machineId: string, rows: unkno
}
export function observerSource(dataDir: string, machine: () => string, now = Date.now) {
let readAt = -Infinity, id = '', until = 0, wanted: Wanted[] = []
- const current = (): Wanted[] => {
+ const read = (): Wanted[] => {
const machineId = machine(), time = now()
if (time - readAt >= 200 || machineId !== id) {
id = machineId; readAt = time; until = 0; wanted = []
@@ -39,7 +48,7 @@ export function observerSource(dataDir: string, machine: () => string, now = Dat
const raw = readFileSync(observerSnapshotFile(dataDir, machineId), 'utf8')
if (raw.length <= 4 * 1024 * 1024) {
const saved = object(JSON.parse(raw))
- if (saved.machineId === machineId && typeof saved.until === 'number' && saved.until <= time + 3000 && Array.isArray(saved.wanted)) {
+ if (saved.machineId === machineId && typeof saved.until === 'number' && saved.until <= time + OBSERVER_VALID_MS + 500 && Array.isArray(saved.wanted)) {
until = saved.until
wanted = saved.wanted.filter(w => {
const value = object(w)
@@ -50,10 +59,17 @@ export function observerSource(dataDir: string, machine: () => string, now = Dat
}
} catch { /* An unavailable or partially replaced authority file withholds viewing. */ }
}
- return time < until ? wanted : []
+ return wanted
}
+ const live = () => now() < until
+ const current = (): Wanted[] => { const rows = read(); return live() ? rows : [] }
return {
current,
+ /** What the host's last roster wants, or null when no roster is in force (its host stalled, or the file cannot be
+ * read): that says nothing about who is a member, so Share keeps the invitations it holds rather than withdrawing
+ * and sending them all again. Viewing is still withheld meanwhile (`allows`). A host that stops publishes an
+ * empty roster that is in force, which does withdraw them. */
+ known: (): Wanted[] | null => { const rows = read(); return live() ? rows : null },
allows: (grant: HarnessGrant): boolean => !superTabOf(grant) || current().some(w =>
w.tab === grant.tab && w.agentId === grant.agentId && w.email === grant.recipientEmail),
}
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 1faa4cf9d..5323337c4 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -502,7 +502,7 @@ it('documents finished worker decisions and explains an older backend without re
describe('the Swarm cards the devices ask for', () => {
function withCards() {
const cards = { want: vi.fn(), open: vi.fn(), recap: vi.fn(async (tabId: string, leadId: string) => ({ tabId, leadId, text: 'Shipped', at: 5, none: false })), onCards: undefined as unknown, onRecap: undefined as unknown }
- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn() }
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }
const core = fakeCore({ superTabs })
const make = vi.fn(() => cards as never)
const service = superTabService(core, { cards: make })
diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.ts
index 43cac6f63..b354c10d7 100644
--- a/cli/src/testing/fakeCore.ts
+++ b/cli/src/testing/fakeCore.ts
@@ -94,6 +94,6 @@ export function fakeCore(over: Overrides = {}): CoreApi {
// Only a spec that gives the cloud agents doors has them, as only a core that offers them does.
...(over.cloud ? { cloud: Object.assign({ publish: vi.fn(), ask: vi.fn(), unask: vi.fn() }, over.cloud) } : {}),
// The Super Tab service's door, likewise.
- ...(over.superTabs ? { superTabs: Object.assign({ attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn() }, over.superTabs) } : {}),
+ ...(over.superTabs ? { superTabs: Object.assign({ attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }, over.superTabs) } : {}),
}
}
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 09354833c..0346881a4 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -41,9 +41,14 @@ class SuperTabAgent {
machineId = _text(row, 'machineId'),
harnessId = _text(row, 'harnessId'),
contributorId = _text(row, 'contributorId'),
+ machineOwnerId =
+ row['machineOwnerId'] as String? ?? _text(row, 'contributorId'),
role = row['role'] as String?,
configuration = Map.unmodifiable(superTabMap(row['configuration']));
final String id, projectId, name, machineId, harnessId, contributorId;
+
+ /// The account whose computer runs it; a contributor may run agents on a computer another account shared with them.
+ final String machineOwnerId;
// Keep the legacy default for callers while allowing group-based roster ownership.
final bool hasProjectId;
final String? displayName;
diff --git a/desktop/lib/super_tabs/terminal_unavailable.dart b/desktop/lib/super_tabs/terminal_unavailable.dart
new file mode 100644
index 000000000..4bece7cc7
--- /dev/null
+++ b/desktop/lib/super_tabs/terminal_unavailable.dart
@@ -0,0 +1,51 @@
+import '../state/app_state.dart';
+import 'machine_status.dart';
+import 'model.dart';
+
+/// What a pane says when this account's machine list has no terminal for a member.
+const superTabTerminalOffline =
+ 'The shared terminal is not available yet. Its execution machine must be online.';
+
+/// Why a member's terminal cannot be shown here, as a person reads it.
+///
+/// A member on another account's computer is shown read-only only through the invitation that computer sends each
+/// Swarm member (cli/src/superTabs/observers.ts): until it arrives, that computer is missing from this account's
+/// machine list, which said nothing about it being offline. Seen 2026-10-23: River on a collaborator's computer,
+/// working, read "must be online" to every other member.
+String superTabTerminalUnavailable({
+ required SuperTabSnapshot? snapshot,
+ required SuperTabAgent agent,
+ required String? accountId,
+ required MachineState? machine,
+ DateTime? now,
+}) {
+ final ownerId = agent.machineOwnerId;
+ if (snapshot == null || ownerId == accountId) return superTabTerminalOffline;
+ final owner =
+ snapshot.people.where((p) => p.id == ownerId).firstOrNull?.email ??
+ 'its owner';
+ final row = snapshot.machines
+ .where((m) => m['machineId'] == agent.machineId)
+ .firstOrNull;
+ final computer =
+ machine?.machine.displayName ?? row?['name'] as String? ?? 'a computer';
+ final name = snapshot.agentName(agent.id);
+ final where = '$name runs on $computer, $owner’s computer';
+ if (_swarmOffline(row, now ?? DateTime.now())) {
+ return '$where, which is offline. Its terminal shows here once that computer is back.';
+ }
+ return '$where. Its terminal is not shared with you yet: Harness there shares it with Swarm members '
+ 'once it is up to date and running. Ask $owner to update and restart Harness, then Retry.';
+}
+
+/// Whether the Swarm last heard from this machine long enough ago to call it offline. A machine the Swarm does not
+/// list is not called offline: what is known of it then is only that this account cannot see it.
+bool _swarmOffline(Map<String, dynamic>? row, DateTime now) {
+ if (row == null) return false;
+ final observation = row['observation'];
+ final at = observation is Map ? observation['receivedAt'] : null;
+ final age = at is num
+ ? now.difference(DateTime.fromMillisecondsSinceEpoch(at.toInt()))
+ : null;
+ return superTabMachineStatus(age: age) == SuperTabMachineStatus.offline;
+}
diff --git a/desktop/lib/super_tabs/workspace.dart b/desktop/lib/super_tabs/workspace.dart
index e8473391a..44c9ef152 100644
--- a/desktop/lib/super_tabs/workspace.dart
+++ b/desktop/lib/super_tabs/workspace.dart
@@ -11,6 +11,7 @@ import 'dialog_scope.dart';
import 'model.dart';
import 'pane.dart';
import 'sharing.dart';
+import 'terminal_unavailable.dart';
import 'view.dart';
/// Keeps the app's one native canvas alive in the group's middle area.
@@ -199,9 +200,14 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
machine = app.stateOf(agent.machineId);
}
if (machine?.agents.any((a) => a.id == agent.harnessId) != true) {
- throw const SuperTabFailure(
+ throw SuperTabFailure(
'TERMINAL_UNAVAILABLE',
- 'The shared terminal is not available yet. Its execution machine must be online.',
+ superTabTerminalUnavailable(
+ snapshot: controller.snapshot,
+ agent: agent,
+ accountId: controller.accountId,
+ machine: machine,
+ ),
);
}
if (!current()) return;
diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dart
index 3c22178d2..68476ec9c 100644
--- a/desktop/test/super_tab_launch_test.dart
+++ b/desktop/test/super_tab_launch_test.dart
@@ -13,6 +13,7 @@ import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/super_tabs/launch.dart';
import 'package:harness/super_tabs/client.dart';
import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/ws/local_cli_discovery.dart';
import 'package:harness/ws/ws_conn.dart';
import 'support/super_tab_fixture.dart';
@@ -342,6 +343,7 @@ class SuperTabLaunchFixture {
SuperTabLaunchFixture({
bool local = false,
SuperTabFixtureConnection Function(MemoryStore)? connectionFactory,
+ LocalCliDiscovery? discovery,
}) {
connection =
connectionFactory?.call(store) ??
@@ -350,6 +352,7 @@ class SuperTabLaunchFixture {
store: store,
connectionForTest: (_) => connection,
connected: true,
+ localCliDiscovery: discovery,
);
app.machineStates['m']!
..localOnly = true
@@ -366,11 +369,20 @@ class SuperTabLaunchFixture {
);
app.markSuperTabDraft(app.activeSwarmId);
- addTearDown(app.dispose);
+ addTearDown(dispose);
}
final store = MemoryStore();
late final AppNotifier app;
late final SuperTabFixtureConnection connection;
+ bool _disposed = false;
+
+ /// Once. A widget test whose app read a machine list must call it itself: Flutter checks for pending timers (the
+ /// list's safety net) before tear-downs run.
+ void dispose() {
+ if (_disposed) return;
+ _disposed = true;
+ app.dispose();
+ }
Future<NewHarnessController> box({
String engine = 'codex',
diff --git a/desktop/test/super_tab_teammate_terminal_test.dart b/desktop/test/super_tab_teammate_terminal_test.dart
new file mode 100644
index 000000000..6c36682af
--- /dev/null
+++ b/desktop/test/super_tab_teammate_terminal_test.dart
@@ -0,0 +1,390 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/sharing/shared_harness_panel.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/terminal_unavailable.dart';
+import 'package:harness/super_tabs/workspace.dart';
+import 'package:harness/widgets/pane_grid.dart';
+import 'package:harness/ws/local_cli_discovery.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
+import 'swarm_state_test.dart' show MemoryStore;
+
+/// The daemon's machine list, scripted: this computer, and the teammate's once its invitation arrives.
+class _Machines extends ApiClient {
+ _Machines()
+ : super(
+ config: AppConfig.dev,
+ session: AuthSession(storage: MemoryStore()),
+ );
+ List<Machine> list = const [_own];
+ int reads = 0;
+ @override
+ Future<List<Machine>> machines() async {
+ reads++;
+ return list;
+ }
+}
+
+class _Discovery extends LocalCliDiscovery {
+ _Discovery() : super(config: AppConfig.dev);
+ @override
+ Future<String?> computerId() async => null;
+ @override
+ Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>
+ null;
+}
+
+const _own = Machine(
+ machineId: 'm',
+ authMode: MachineAuthMode.remote,
+ name: 'Test host',
+);
+const _computer = 'MacBooks-MacBook-Pro-9';
+
+SharedHarness _invite(int day) => SharedHarness(
+ id: 'share-river',
+ agentId: 'river-native',
+ name: 'Builder',
+ engine: 'claude',
+ expiresAt: DateTime.utc(2026, 11, day),
+ ownerPublicKey: 'DEys/M3p0/VLAiDGLRit4jGJ49PGHZm6eZchm6cYrVo=',
+);
+
+/// The teammate's computer as an invitation lists it: shared, with River's terminal to watch.
+Machine _teammate(int day) => Machine(
+ machineId: 'mate',
+ authMode: MachineAuthMode.remote,
+ name: _computer,
+ isShared: true,
+ ownerName: 'Scholes',
+ status: 'running',
+ sharedHarnesses: [_invite(day)],
+);
+
+/// A Swarm where River runs on scholes' computer, contributed by scholes, and this account is another member.
+Future<(SuperTabLaunchFixture, _Machines, SuperTabController)> _swarm({
+ Duration lastHeard = const Duration(seconds: 5),
+}) async {
+ final f = SuperTabLaunchFixture(discovery: _Discovery());
+ final api = _Machines();
+ f.app.api = api;
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ final state = f.connection.server.state;
+ (state['people'] as List).add({
+ 'id': 'scholes',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ });
+ state['machines'] = [
+ {
+ 'machineId': 'mate',
+ 'name': _computer,
+ 'observation': {
+ 'receivedAt': DateTime.now().subtract(lastHeard).millisecondsSinceEpoch,
+ },
+ },
+ ];
+ state['agents'] = [
+ {
+ 'id': 'river',
+ 'name': 'Builder',
+ 'displayName': 'River',
+ 'machineId': 'mate',
+ 'harnessId': 'river-native',
+ 'contributorId': 'scholes',
+ 'machineOwnerId': 'scholes',
+ 'configuration': {'engine': 'claude'},
+ },
+ ];
+ (state['conversations'] as List)[0]['agentIds'] = ['river'];
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ return (f, api, c);
+}
+
+/// Set to a folder to write the workgroup pane as a picture, for a review: `SUPER_TAB_TEAMMATE_SHOTS=/tmp/shots`.
+final _shots = Platform.environment['SUPER_TAB_TEAMMATE_SHOTS'];
+final _picture = GlobalKey();
+
+Future<void> _show(WidgetTester tester, SuperTabLaunchFixture f) async {
+ await tester.binding.setSurfaceSize(const Size(1280, 800));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: RepaintBoundary(
+ key: _picture,
+ child: Scaffold(
+ body: ListenableBuilder(
+ listenable: f.app,
+ builder: (_, _) => SuperTabWorkspace(
+ app: f.app,
+ canvas: PaneGrid(notifier: f.app, swarmMode: true),
+ onAddAgent: (_) {},
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+}
+
+Future<void> _shoot(WidgetTester tester, String name) async {
+ final directory = _shots;
+ if (directory == null) return;
+ await tester.runAsync(() async {
+ final boundary =
+ _picture.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ final image = await boundary.toImage();
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(directory).create(recursive: true);
+ await File('$directory/$name.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+}
+
+Future<void> _settle(WidgetTester tester) async {
+ for (var i = 0; i < 20; i++) {
+ await tester.pump(const Duration(milliseconds: 50));
+ }
+}
+
+Future<void> _close(
+ WidgetTester tester,
+ SuperTabLaunchFixture f,
+ SuperTabController c,
+) async {
+ await tester.pumpWidget(const SizedBox());
+ // A shared panel's connection gives its socket 2 s to close.
+ await tester.pump(const Duration(seconds: 3));
+ await c.flush();
+ f.app.superTabs.dispose();
+ f.dispose();
+ await tester.pump();
+}
+
+void main() {
+ setUpAll(() async {
+ if (_shots != null) await loadPreviewFonts();
+ });
+ group('why a member’s terminal is unavailable', () {
+ SuperTabSnapshot snapshot({int? receivedAt, bool ownerListed = true}) =>
+ SuperTabSnapshot.fromJson({
+ 'version': 1,
+ 'id': tabId,
+ 'name': 'Pilot',
+ 'ownerId': 'owner',
+ 'people': [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ if (ownerListed)
+ {
+ 'id': 'scholes',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ },
+ ],
+ 'agents': [
+ {
+ 'id': 'river',
+ 'name': 'Builder',
+ 'displayName': 'River',
+ 'machineId': 'mate',
+ 'harnessId': 'river-native',
+ 'contributorId': 'scholes',
+ 'machineOwnerId': 'scholes',
+ 'configuration': {'engine': 'claude'},
+ },
+ {
+ 'id': 'mine',
+ 'name': 'Builder',
+ 'machineId': 'm',
+ 'harnessId': 'mine-native',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'codex'},
+ },
+ ],
+ 'machines': [
+ {
+ 'machineId': 'mate',
+ 'name': _computer,
+ if (receivedAt != null) 'observation': {'receivedAt': receivedAt},
+ },
+ ],
+ 'conversations': const [],
+ 'invitations': const [],
+ });
+ final now = DateTime.utc(2026, 10, 23, 4, 11);
+ String reason(SuperTabSnapshot s, String agentId) =>
+ superTabTerminalUnavailable(
+ snapshot: s,
+ agent: s.agent(agentId)!,
+ accountId: 'owner',
+ machine: null,
+ now: now,
+ );
+
+ test('names a teammate’s computer and account and what they can do, '
+ 'never that an online computer must be online', () {
+ final text = reason(
+ snapshot(
+ receivedAt: now
+ .subtract(const Duration(seconds: 4))
+ .millisecondsSinceEpoch,
+ ),
+ 'river',
+ );
+ expect(
+ text,
+ 'River runs on $_computer, [email protected]’s computer. Its '
+ 'terminal is not shared with you yet: Harness there shares it with '
+ 'Swarm members once it is up to date and running. Ask '
+ '[email protected] to update and restart Harness, then Retry.',
+ );
+ expect(text, isNot(contains('must be online')));
+ });
+
+ test('says a teammate’s computer is offline only when the Swarm stopped '
+ 'hearing from it', () {
+ final silent = now
+ .subtract(const Duration(minutes: 3))
+ .millisecondsSinceEpoch;
+ expect(
+ reason(snapshot(receivedAt: silent), 'river'),
+ 'River runs on $_computer, [email protected]’s computer, which is '
+ 'offline. Its terminal shows here once that computer is back.',
+ );
+ expect(reason(snapshot(), 'river'), contains('which is offline'));
+ });
+
+ test('keeps the original message for this account’s own computer and '
+ 'never shows an internal id for an unknown owner', () {
+ expect(reason(snapshot(), 'mine'), superTabTerminalOffline);
+ final unknown = reason(snapshot(ownerListed: false), 'river');
+ expect(unknown, contains('its owner’s computer'));
+ expect(unknown, isNot(contains('scholes')));
+ expect(
+ superTabTerminalUnavailable(
+ snapshot: null,
+ agent: snapshot().agent('river')!,
+ accountId: 'owner',
+ machine: null,
+ ),
+ superTabTerminalOffline,
+ );
+ });
+
+ test(
+ 'reads a legacy agent without its machine owner as its contributor’s',
+ () {
+ final legacy = SuperTabAgent.fromJson({
+ 'id': 'old',
+ 'name': 'Builder',
+ 'machineId': 'm',
+ 'harnessId': 'h',
+ 'contributorId': 'owner',
+ 'configuration': const <String, dynamic>{},
+ });
+ expect(legacy.machineOwnerId, 'owner');
+ },
+ );
+ });
+
+ testWidgets(
+ 'a teammate’s agent without an invitation says why and how to fix it, '
+ 'and Retry shows its read-only terminal once the invitation arrives',
+ (tester) async {
+ final (f, api, c) = await _swarm();
+ await _show(tester, f);
+ c.selectTerminal('lead', 'river');
+ await _settle(tester);
+ await _shoot(tester, 'teammate-without-invitation');
+ expect(find.textContaining('must be online'), findsNothing);
+ expect(
+ find.textContaining('[email protected]’s computer'),
+ findsOneWidget,
+ );
+ expect(find.text('Retry'), findsOneWidget);
+ expect(find.byType(SharedHarnessPanel), findsNothing);
+
+ api.list = [_own, _teammate(21)];
+ await tester.tap(find.text('Retry'));
+ await _settle(tester);
+ expect(find.textContaining('not shared with you yet'), findsNothing);
+ expect(find.byType(SharedHarnessPanel), findsOneWidget);
+ final pane = f.app.panes.single;
+ expect(pane.sharedHarness?.id, 'share-river');
+ expect(pane.inputContext, isNull);
+ // Read-only: no input grant was asked for on another account's computer.
+ expect(
+ f.connection.calls.where(
+ (call) =>
+ (call.$2['path'] as String?)?.endsWith('/native') == true ||
+ call.$2['action'] == 'prepareNative',
+ ),
+ isEmpty,
+ );
+ await _close(tester, f, c);
+ },
+ );
+
+ testWidgets(
+ 'a teammate’s read-only terminal stays the same connection across '
+ 'machine-list refreshes, renewed invitations included',
+ (tester) async {
+ final (f, api, c) = await _swarm();
+ api.list = [_own, _teammate(21)];
+ await f.app.refreshMachines();
+ await _show(tester, f);
+ c.selectTerminal('lead', 'river');
+ await _settle(tester);
+ final panel = tester.state(find.byType(SharedHarnessPanel));
+ final pane = f.app.panes.single;
+ // The storm seen 2026-10-23: a machine list re-read about 1.5 times a second, each with a renewed invitation.
+ for (var day = 22; day < 30; day++) {
+ api.list = [_own, _teammate(day)];
+ expect(await f.app.refreshMachines(), isTrue);
+ await tester.pump(const Duration(milliseconds: 700));
+ }
+ await _settle(tester);
+ expect(api.reads, greaterThanOrEqualTo(9));
+ expect(tester.state(find.byType(SharedHarnessPanel)), same(panel));
+ expect(f.app.panes.single, same(pane));
+ expect(find.text('Retry'), findsNothing);
+ await _close(tester, f, c);
+ },
+ );
+
+ testWidgets(
+ 'this account’s own computer without the agent keeps its original message',
+ (tester) async {
+ final (f, _, c) = await _swarm();
+ final state = f.connection.server.state;
+ (state['agents'] as List).first
+ ..['machineId'] = 'm'
+ ..['harnessId'] = 'gone-native'
+ ..['contributorId'] = 'owner'
+ ..['machineOwnerId'] = 'owner';
+ await c.refresh();
+ await _show(tester, f);
+ c.selectTerminal('lead', 'river');
+ await _settle(tester);
+ expect(find.text(superTabTerminalOffline), findsOneWidget);
+ expect(find.text('Retry'), findsOneWidget);
+ await _close(tester, f, c);
+ },
+ );
+}
diff --git a/desktop/test/swarm_state_test.dart b/desktop/test/swarm_state_test.dart
index 86872278d..d3aeb5fb2 100644
--- a/desktop/test/swarm_state_test.dart
+++ b/desktop/test/swarm_state_test.dart
@@ -11,6 +11,7 @@ import 'package:harness/state/swarm_catalog.dart';
import 'package:harness/state/swarm.dart';
import 'package:harness/state/terminal_pane.dart';
import 'package:harness/terminal/terminal_session.dart';
+import 'package:harness/ws/local_cli_discovery.dart';
import 'package:harness/ws/ws_conn.dart';
class MemoryStore implements LocalKeyValueStore {
@@ -33,12 +34,14 @@ AppNotifier createApp({
WsConn Function(String)? connectionForTest,
bool connected = false,
ProductMeasurement? productMeasurement,
+ LocalCliDiscovery? localCliDiscovery,
}) {
final app = AppNotifier(
config: AppConfig.dev,
authSession: AuthSession(),
configStore: null,
connectionForTest: connectionForTest,
+ localCliDiscovery: localCliDiscovery,
productMeasurement: productMeasurement,
paneLayoutStore: store == null ? null : PaneLayoutStore(storage: store),
)..hasNavigationRail = false;