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.

Remove Swarm collaboration's last code: prompt scopes, tab channels, phone views (#1165)

Dee6d9b787dd664
diff --git a/.github/assets/swarm-collaboration/README.md b/.github/assets/swarm-collaboration/README.md
deleted file mode 100644
index 0fe6279ca..000000000
--- a/.github/assets/swarm-collaboration/README.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# Swarm collaboration
-
-Flutter widget renders with synthetic account and conversation data, September 28, 2026.
-
-- `settings.png`: Settings → Experimental, with all switches off by default and saved to the account. The creature card explains that its collection and progress are saved too.
-- `conversation.png`: the current tab's peers, correlated question and answer, and return delivery state.
-
-Regenerate using `CHANNEL_RENDER_DIR=/tmp/harness-channel-review` with the desktop
-`swarm_settings_test.dart` and `channel_workspace_test.dart` widget tests.
diff --git a/.github/assets/swarm-collaboration/conversation.png b/.github/assets/swarm-collaboration/conversation.png
deleted file mode 100644
index f168a587b..000000000
Binary files a/.github/assets/swarm-collaboration/conversation.png and /dev/null differ
diff --git a/.github/assets/swarm-collaboration/settings.png b/.github/assets/swarm-collaboration/settings.png
deleted file mode 100644
index 9a874301f..000000000
Binary files a/.github/assets/swarm-collaboration/settings.png and /dev/null differ
diff --git a/README.md b/README.md
index 4d26ae55c..22552e3f1 100644
--- a/README.md
+++ b/README.md
@@ -73,8 +73,8 @@ for workloads, slow tails, connection failures and raw data.
In the workspace, a **harness** is one running session of an agent such as Codex
or Claude Code, with its own conversation and working context. A **tab** groups
harnesses. Use **New Harness** to start one and **New Tab** to group work.
-Enable **Settings → Experimental → Tab collaboration** to let their agents
-consult peers in the same tab; it is off by default.
+Turn on **Agent Messages** for a tab (its chat icon, or right-click the tab) to let its
+agents message each other with `harness send`; it is off by default.
The Store offers **harnesses** with instructions, tools, and optional viewers for
specific crafts. Install a harness, then start it in your workspace. See the
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index ed262b46e..954490642 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -750,19 +750,6 @@ model Desk {
@@map("desks")
}
-/// Routing only; channel messages and member capabilities stay on the host daemon.
-/// A deterministic _id makes concurrent claims atomic using MongoDB's built-in
-/// unique primary index. This never changes the format of the shared desk.
-model TabChannel {
- id String @id @map("_id") @db.ObjectId
- userId String
- tabId String
- hostMachineId String
- createdAt DateTime @default(now())
-
- @@map("tab_channels")
-}
-
/// Agent Messages, per tab (docs/design/2026-10-10-agent-messages.md): whether the harnesses in one desk tab
/// may message each other. Absence means off. Kept beside the desk, never in its tab JSON: a backend pod that
/// has not upgraded drops a tab whose JSON it does not know (lib/desk.ts parseTabs). A deterministic _id makes
@@ -779,16 +766,6 @@ model AgentMessageTab {
@@map("agent_message_tabs")
}
-/// Explicit account opt-in for automatic swarm collaboration; absence means off.
-model TabChannelSettings {
- id String @id @map("_id") @db.ObjectId
- userId String
- enabled Boolean @default(false)
- revision Int @default(0)
-
- @@map("tab_channel_settings")
-}
-
/// Explicit account opt-ins; missing choices stay off. Each write changes one feature.
model ExperimentalSettings {
id String @id @map("_id") @db.ObjectId
diff --git a/backend/src/config/env.ts b/backend/src/config/env.ts
index b68bce844..0e6d8852d 100644
--- a/backend/src/config/env.ts
+++ b/backend/src/config/env.ts
@@ -17,9 +17,6 @@ const envSchema = z.object({
// Same MongoDB (and database) as the agent-manager — backend owns `users` +
// `machines`; reads `managers`/`machine_nodes` via raw queries when needed.
DATABASE_URL: z.string().default('mongodb://localhost:27017/harness?replicaSet=rs0'),
- // Module availability only. Each account must separately opt in in Experimental;
- // no settings record means OFF. False disables the whole module for operators.
- HARNESS_CHANNELS: z.string().default('true').transform(v => v === 'true'),
// Redis for the cross-instance data bus. Behind a load balancer an agent's web socket and its
// manager socket may land on different backend instances; Redis pub/sub bridges them
diff --git a/backend/src/lib/tabChannels.ts b/backend/src/lib/tabChannels.ts
deleted file mode 100644
index 1d9d9e392..000000000
--- a/backend/src/lib/tabChannels.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { createHash } from 'node:crypto'
-import { Prisma } from '@prisma/client'
-import { prisma } from './prisma.js'
-import { parseTabs } from './desk.js'
-
-/** This address is independent of pane order, focus and which app is open. */
-export const tabChannelId = (userId: string, tabId: string): string =>
- createHash('sha256').update(JSON.stringify([userId, tabId])).digest('hex').slice(0, 24)
-
-export async function readTabChannelSettings(userId: string) {
- const row = await prisma.tabChannelSettings.findUnique({ where: { id: tabChannelId(userId, 'settings') } })
- if (row && row.userId !== userId) throw new Error('Channel settings identity mismatch')
- return { enabled: row?.enabled === true, revision: row?.revision ?? 0 }
-}
-
-export async function setTabChannelSettings(userId: string, enabled: boolean) {
- const id = tabChannelId(userId, 'settings')
- const data = { enabled, revision: { increment: 1 } }
- let row
- try {
- row = await prisma.tabChannelSettings.upsert({ where: { id },
- create: { id, userId, enabled, revision: 1 }, update: data })
- } catch (error) {
- if (!(error instanceof Prisma.PrismaClientKnownRequestError) || error.code !== 'P2002') throw error
- row = await prisma.tabChannelSettings.update({ where: { id }, data })
- }
- return { enabled: row.enabled, revision: row.revision }
-}
-
-export async function readTabChannels(userId: string) {
- const settings = await readTabChannelSettings(userId)
- // Reading the experiment while OFF never registers a host or touches the desk.
- if (!settings.enabled) return { enabled: false, settingsRevision: settings.revision, revision: 0, tabs: [] }
- const [desk, machines] = await Promise.all([
- prisma.desk.findUnique({ where: { userId } }),
- prisma.machine.findMany({ where: { userId }, select: { machineId: true } }),
- ])
- const owned = new Set(machines.map(m => m.machineId))
- const tabs = await Promise.all(parseTabs(desk?.tabs).map(async tab => {
- // Shared observation panes are not participants, even when shown beside
- // owned agents. Runtime discovery on each host filters ordinary shells.
- const panes = tab.panes.filter(p => owned.has(p.machineId))
- const id = tabChannelId(userId, tab.id)
- let channel = await prisma.tabChannel.findUnique({ where: { id } })
- if (!channel && panes.length) {
- try {
- channel = await prisma.tabChannel.create({ data: { id, userId, tabId: tab.id, hostMachineId: panes[0].machineId } })
- } catch (error) {
- if (!(error instanceof Prisma.PrismaClientKnownRequestError) || error.code !== 'P2002') throw error
- channel = await prisma.tabChannel.findUnique({ where: { id } })
- if (!channel) throw error
- }
- }
- if (channel && (channel.userId !== userId || channel.tabId !== tab.id)) throw new Error('Channel routing identity mismatch')
- return { ...tab, panes, ...(channel ? { channelHost: channel.hostMachineId } : {}) }
- }))
- return { enabled: true, settingsRevision: settings.revision, revision: desk?.revision ?? 0, tabs }
-}
diff --git a/backend/src/routes/tabChannels.test.ts b/backend/src/routes/tabChannels.test.ts
deleted file mode 100644
index caf77a156..000000000
--- a/backend/src/routes/tabChannels.test.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import Fastify, { type FastifyInstance } from 'fastify'
-import { Prisma } from '@prisma/client'
-const mocks = vi.hoisted(() => ({
- prisma: { desk: { findUnique: vi.fn() }, machine: { findMany: vi.fn() }, tabChannel: { findUnique: vi.fn(), create: vi.fn() },
- tabChannelSettings: { findUnique: vi.fn(), upsert: vi.fn(), update: vi.fn() } },
- auth: vi.fn(),
- publish: vi.fn(),
-}))
-vi.mock('../lib/prisma.js', () => ({ prisma: mocks.prisma }))
-vi.mock('../lib/bus.js', () => ({ publishDeskChanged: mocks.publish }))
-vi.mock('../lib/ssoAuth.js', async original => ({ ...await original<typeof import('../lib/ssoAuth.js')>(), authenticateAccessToken: mocks.auth }))
-import { tabChannelRoutes } from './tabChannels.js'
-import { tabChannelId } from '../lib/tabChannels.js'
-import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'
-import { errorHandler } from '../middlewares/errorHandler.js'
-
-describe('isolated tab-channel routing', () => {
- let app: FastifyInstance
- const tab = { id: 'device', name: 'Device', panes: [{ machineId: 'shared', agentId: 'observer' }, { machineId: 'm1', agentId: 'mobile' }, { machineId: 'm2', agentId: 'firmware' }] }
- beforeEach(async () => {
- vi.resetAllMocks()
- mocks.auth.mockResolvedValue({ sub: 'owner', email: '[email protected]', role: 'user', autonomousEnv: 'prod' })
- mocks.prisma.tabChannelSettings.findUnique.mockResolvedValue({ userId: 'owner', enabled: true, revision: 1 })
- mocks.prisma.tabChannelSettings.upsert.mockImplementation(async ({ create }) => create)
- mocks.publish.mockResolvedValue(0)
- mocks.prisma.desk.findUnique.mockResolvedValue({ revision: 8, tabs: [tab] })
- mocks.prisma.machine.findMany.mockResolvedValue([{ machineId: 'm1' }, { machineId: 'm2' }])
- mocks.prisma.tabChannel.findUnique.mockResolvedValue(null)
- mocks.prisma.tabChannel.create.mockImplementation(async ({ data }) => data)
- app = Fastify(); app.setErrorHandler(errorHandler); registerAuthMiddleware(app, mocks.auth)
- await app.register(tabChannelRoutes); await app.ready()
- })
- afterEach(async () => app.close())
- const read = () => app.inject({ method: 'GET', url: '/api/tab-channels', headers: { authorization: 'Bearer fixture' } })
-
- it('requires authentication', async () => {
- const result = await app.inject({ method: 'GET', url: '/api/tab-channels' })
- expect(result.statusCode).toBe(401)
- expect(mocks.prisma.desk.findUnique).not.toHaveBeenCalled()
- })
- it('claims one owned host, excludes observation panes and preserves the existing desk format', async () => {
- const before = structuredClone(tab)
- const result = await read()
- expect(result.statusCode).toBe(200)
- expect(result.json().data).toEqual({ enabled: true, settingsRevision: 1, revision: 8, tabs: [{ ...tab, panes: tab.panes.slice(1), channelHost: 'm1' }] })
- expect(mocks.prisma.machine.findMany).toHaveBeenCalledWith({ where: { userId: 'owner' }, select: { machineId: true } })
- expect(mocks.prisma.tabChannel.create).toHaveBeenCalledWith({ data: { id: tabChannelId('owner', 'device'), userId: 'owner', tabId: 'device', hostMachineId: 'm1' } })
- expect(tab).toEqual(before)
- expect(tab).not.toHaveProperty('channelHost')
- })
- it('retains the original ledger host after its agent leaves', async () => {
- mocks.prisma.tabChannel.findUnique.mockResolvedValue({ userId: 'owner', tabId: 'device', hostMachineId: 'm1' })
- mocks.prisma.desk.findUnique.mockResolvedValue({ revision: 9, tabs: [{ ...tab, panes: [tab.panes[2]] }] })
- expect((await read()).json().data.tabs[0].channelHost).toBe('m1')
- expect(mocks.prisma.tabChannel.create).not.toHaveBeenCalled()
- })
- it('uses the winner of a concurrent claim without replacing its host', async () => {
- mocks.prisma.tabChannel.findUnique.mockResolvedValueOnce(null).mockResolvedValueOnce({ userId: 'owner', tabId: 'device', hostMachineId: 'm2' })
- mocks.prisma.tabChannel.create.mockRejectedValue(new Prisma.PrismaClientKnownRequestError('duplicate', { code: 'P2002', clientVersion: 'fixture' }))
- expect((await read()).json().data.tabs[0].channelHost).toBe('m2')
- expect(tabChannelId('another-user', 'device')).not.toBe(tabChannelId('owner', 'device'))
- })
- it('does not create a channel host for empty tabs or tabs containing only shared views', async () => {
- mocks.prisma.machine.findMany.mockResolvedValue([])
- expect((await read()).json().data.tabs[0]).toEqual({ ...tab, panes: [] })
- expect(mocks.prisma.tabChannel.create).not.toHaveBeenCalled()
- })
- it('defaults off without creating settings, reading tabs or registering hosts', async () => {
- mocks.prisma.tabChannelSettings.findUnique.mockResolvedValue(null)
- expect((await read()).json().data).toEqual({ enabled: false, settingsRevision: 0, revision: 0, tabs: [] })
- const settings = await app.inject({ method: 'GET', url: '/api/tab-channels/settings', headers: { authorization: 'Bearer fixture' } })
- expect(settings.json().data).toEqual({ enabled: false, revision: 0 })
- expect(mocks.prisma.tabChannelSettings.upsert).not.toHaveBeenCalled()
- expect(mocks.prisma.desk.findUnique).not.toHaveBeenCalled()
- expect(mocks.prisma.tabChannel.create).not.toHaveBeenCalled()
- })
- it('saves only an explicit authenticated boolean and invalidates the account daemons', async () => {
- const request = (body: unknown, auth = true) => app.inject({ method: 'PATCH', url: '/api/tab-channels/settings',
- headers: auth ? { authorization: 'Bearer fixture' } : {}, payload: body as object })
- expect((await request({ enabled: true }, false)).statusCode).toBe(401)
- expect((await request({ enabled: 'true' })).statusCode).toBe(400)
- expect(mocks.prisma.tabChannelSettings.upsert).not.toHaveBeenCalled()
- expect((await request({ enabled: true })).json().data).toEqual({ enabled: true, revision: 1 })
- expect(mocks.prisma.tabChannelSettings.upsert).toHaveBeenCalledWith(expect.objectContaining({
- where: { id: tabChannelId('owner', 'settings') }, create: expect.objectContaining({ userId: 'owner', enabled: true }),
- }))
- expect(mocks.publish).toHaveBeenCalledWith('owner', { revision: 0 })
- expect((await request({ enabled: false })).json().data.enabled).toBe(false)
- })
-})
diff --git a/backend/src/routes/tabChannels.ts b/backend/src/routes/tabChannels.ts
deleted file mode 100644
index 1dcef9372..000000000
--- a/backend/src/routes/tabChannels.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import type { FastifyInstance } from 'fastify'
-import { z } from 'zod'
-import { readTabChannels, readTabChannelSettings, setTabChannelSettings } from '../lib/tabChannels.js'
-import { publishDeskChanged } from '../lib/bus.js'
-import { validateBody } from '../middlewares/validation.js'
-import { sendSuccess } from '../utils/response.js'
-
-/** Separate from /api/desk: old clients and rolling backend upgrades keep the
- * exact same tab document. This endpoint exposes routing, never conversations. */
-export async function tabChannelRoutes(app: FastifyInstance): Promise<void> {
- app.get('/api/tab-channels/settings', async (req, reply) => {
- sendSuccess(reply, await readTabChannelSettings(req.user!.sub))
- })
- app.patch<{ Body: { enabled: boolean } }>('/api/tab-channels/settings', {
- preHandler: validateBody(z.object({ enabled: z.boolean() }).strict()),
- }, async (req, reply) => {
- const userId = req.user!.sub
- const settings = await setTabChannelSettings(userId, req.body.enabled)
- // Reuse the existing account invalidation transport without changing desk data.
- void publishDeskChanged(userId, { revision: 0 })
- sendSuccess(reply, settings)
- })
- app.get('/api/tab-channels', async (req, reply) => {
- sendSuccess(reply, await readTabChannels(req.user!.sub))
- })
-}
diff --git a/backend/src/server.ts b/backend/src/server.ts
index f356b2029..8a569b8ec 100644
--- a/backend/src/server.ts
+++ b/backend/src/server.ts
@@ -16,7 +16,6 @@ import { deviceKeyRoutes } from './routes/deviceKeys.js'
import { qrSignInRoutes } from './routes/qrSignIn.js'
import { deskRoutes } from './routes/desk.js'
import { connectorRoutes } from './routes/connectors.js'
-import { tabChannelRoutes } from './routes/tabChannels.js'
import { agentMessagesRoutes } from './routes/agentMessages.js'
import { zooRoutes } from './routes/zoo.js'
import { experimentalSettingsRoutes } from './routes/experimentalSettings.js'
@@ -180,7 +179,6 @@ async function start(): Promise<void> {
await app.register(deviceKeyRoutes) // the account's device key log: signing in is what trusts a device
await app.register(deskRoutes) // the account's tabs, the same on every computer (lib/desk.ts)
await app.register(connectorRoutes) // sign-in to GitHub, Slack, Google… for local agents (lib/connectorGateway.ts)
- if (env.HARNESS_CHANNELS) await app.register(tabChannelRoutes)
await app.register(agentMessagesRoutes) // which tabs' harnesses may message each other (lib/agentMessages.ts)
await app.register(experimentalSettingsRoutes, { daemons: DAEMONS })
// Availability is separate from opt-in: every account starts off, and its collection is retained.
diff --git a/cli/AGENTS.md b/cli/AGENTS.md
index 49f185be7..dac907d27 100644
--- a/cli/AGENTS.md
+++ b/cli/AGENTS.md
@@ -33,7 +33,7 @@ they show as `harnessd`, `harnessd-core` and `harnessd-<process>` (`src/harnessd
| models | grid, local models, the Model Manager | on demand: once grid is in use here (a managed grid, saved grid pictures, local models), or on a models request |
| updater | checks, downloads and stages a new build (`src/services/updaterProcess.ts`) | by the master, for the installed copy only |
| devices | the dials, the window bridges, the fleet, the voice router, the Wi-Fi device | on demand: once there is a device |
-| orchestrator, teams (with Tab collaboration), sharing, memory, router | the experiments | on demand: on a request, or saved state at start |
+| orchestrator, messages (Agent Messages), sharing, memory, router | the experiments | on demand: on a request, or saved state at start |
`HARNESSD_SERVICES` names a subset to run in their own processes, by service or by process.
`HARNESSD_SERVICES=none` runs every service in the core's process, for debugging or a quick way back. How
diff --git a/cli/README.md b/cli/README.md
index fbd50cf4f..b15dbda7c 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -30,7 +30,7 @@ Windows is not supported.
## Agent Messages
-Harnesses in the same tab can message each other once **Agent Messages** is on for that tab (⇄ on the tab;
+Harnesses in the same tab can message each other once **Agent Messages** is on for that tab (the chat icon on the tab;
off by default). An agent runs, in its own pane:
```bash
diff --git a/cli/ci-test-durations.json b/cli/ci-test-durations.json
index 6b25422a1..e10e5b058 100644
--- a/cli/ci-test-durations.json
+++ b/cli/ci-test-durations.json
@@ -57,8 +57,6 @@
"src/machinesCommand.spec.ts": 5800,
"src/orchestrator/service.spec.ts": 2700,
"src/remoteCommand.spec.ts": 1400,
- "src/scripts/install.spec.ts": 10100,
- "src/teams/remote.spec.ts": 20500,
- "src/teams/transport.spec.ts": 8200
+ "src/scripts/install.spec.ts": 10100
}
}
diff --git a/cli/e2e/agentMessages.e2e.ts b/cli/e2e/agentMessages.e2e.ts
index f484bcc10..ae81301c6 100644
--- a/cli/e2e/agentMessages.e2e.ts
+++ b/cli/e2e/agentMessages.e2e.ts
@@ -33,7 +33,7 @@ async function create(d: IsolatedDaemon, client: LocalClient, folder: string, en
return agent?.sessionId && agent.status === 'active' ? agent : null
}, 60_000, 500)
}
-const starts = (d: IsolatedDaemon) => [...d.log().matchAll(/\[harnessd\] service teams started/g)].length
+const starts = (d: IsolatedDaemon) => [...d.log().matchAll(/\[harnessd\] service messages started/g)].length
const statusOf = async (client: LocalClient, id: string) => {
const history = await client.request<{ messages?: Array<{ id: string; statuses: Array<Record<string, unknown>> }> }>('agent_messages', { action: 'history' }, 30_000)
return history.messages?.find((m) => m.id === id)?.statuses[0] ?? null
@@ -65,14 +65,14 @@ describe('Agent Messages, end to end', () => {
expect(starts(d), 'an experiment no one used').toBe(0)
expect(await client.request('agent_messages', { action: 'history' }, 40_000)).toMatchObject({ messages: [] })
expect(starts(d)).toBe(1)
- await until('Agent Messages to connect', () => d.log().includes('[services] collaboration connected') || null, 30_000, 200)
+ await until('Agent Messages to connect', () => d.log().includes('[services] messages connected') || null, 30_000, 200)
expect(d.coresStarted()).toBe(1)
client.close()
})
it('its saved state turns it on as the daemon starts', async () => {
const d = await fresh((daemon) => mkdirSync(join(daemon.dataDir, 'agent-messages'), { recursive: true }))
- await until('Agent Messages to start for its saved state', () => d.log().includes('[services] collaboration connected') || null, 30_000, 200)
+ await until('Agent Messages to start for its saved state', () => d.log().includes('[services] messages connected') || null, 30_000, 200)
expect(starts(d)).toBe(1)
})
diff --git a/cli/e2e/endurance.e2e.ts b/cli/e2e/endurance.e2e.ts
index a590498f8..8390de4c9 100644
--- a/cli/e2e/endurance.e2e.ts
+++ b/cli/e2e/endurance.e2e.ts
@@ -84,10 +84,10 @@ const PROBES: Record<string, { type: string; payload: Record<string, unknown> }>
models: { type: 'models_list', payload: {} },
devices: { type: 'harness_devices_list', payload: {} },
orchestrator: { type: 'orchestrator', payload: { action: 'list' } },
- teams: { type: 'agent_messages', payload: { action: 'history' } },
+ messages: { type: 'agent_messages', payload: { action: 'history' } },
}
/** The service names a process's comings and goings are logged under (`[services] <name> connected`). */
-const LINKS: Record<string, string> = { 'engine-claude': 'engine-claude', 'engine-codex': 'engine-codex', search: 'search', viewers: 'viewers', edge: 'monitor', gateway: 'gateway', models: 'models', devices: 'devices', orchestrator: 'orchestrator', teams: 'teams', sharing: 'sharing' }
+const LINKS: Record<string, string> = { 'engine-claude': 'engine-claude', 'engine-codex': 'engine-codex', search: 'search', viewers: 'viewers', edge: 'monitor', gateway: 'gateway', models: 'models', devices: 'devices', orchestrator: 'orchestrator', messages: 'messages', sharing: 'sharing' }
const down = (answer: Record<string, unknown>) => answer.error === 'SERVICE_UNAVAILABLE' || answer.error === 'SERVICE_FAILED' || answer.error === 'GATEWAY_UNAVAILABLE' || answer.error === 'ENGINE_UNAVAILABLE' || answer.error === 'ENGINE_STALE_REPLY' || answer.error === 'ENGINE_BUSY'
const acceptable = (name: string, answer: Record<string, unknown>): boolean => answer.error === undefined
@@ -242,7 +242,7 @@ async function deskLoop(d: IsolatedDaemon, agentIds: string[], deadline: () => b
if (drawn.length) window.send('terminal_ack', { streamId, lastSeq: drawn[drawn.length - 1].seq })
}
const service = Object.keys(PROBES)[Math.floor(rand() * Object.keys(PROBES).length)]
- if (rand() < 0.4 && !['orchestrator', 'teams'].includes(service)) await ask(window, service)
+ if (rand() < 0.4 && !['orchestrator', 'messages'].includes(service)) await ask(window, service)
forget(window)
await sleep(2_000)
}
diff --git a/cli/e2e/services.e2e.ts b/cli/e2e/services.e2e.ts
index fbdaa86e1..18773b7ff 100644
--- a/cli/e2e/services.e2e.ts
+++ b/cli/e2e/services.e2e.ts
@@ -2,7 +2,7 @@
* A failing service never takes the core down, proven on the real daemon: every service made to fail as
* it starts, and services made to fail on every call, while a client starts an agent, the agent binds,
* messages become turns that start and end, and the daemon restarts. Both ways a service runs: in a
- * process of its own (the default for search, the viewers with the Store, the teams, models and the edge
+ * process of its own (the default for search, the viewers with the Store, Agent Messages, models and the edge
* host's workspaces, usage, monitor and project readers, harnessd/services.ts), and inside the core's
* process (`HARNESSD_SERVICES=none`, and always for the fleet), where the core's host guards it
* (core/serviceHost.ts).
@@ -53,7 +53,7 @@ const IN_THE_CORE = { HARNESSD_SERVICES: 'none' }
/** A master quick to give up on a service that keeps failing as it starts. */
const QUICK_TO_PARK = { HARNESSD_SERVICE_PARK_CRASHES: '3', HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200', HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000' }
/** The processes the services run in by default, and what makes every one of them fail as it starts. The
- * experiments' (the teams', the orchestrator's) start only once they are on: e2e/experiments.e2e.ts. */
+ * experiments' (Agent Messages', the orchestrator's) start only once they are on: e2e/experiments.e2e.ts. */
const SERVICE_PROCESSES = ['search', 'viewers', 'edge', 'models'] as const
// Follow the host inventory: leaving the newly extracted shell alive kept edge running, so the old
// fixture waited forever for a crash loop it no longer caused (E2E run 37659523605).
@@ -224,21 +224,17 @@ describe('a failing service never takes the core down', () => {
client.close()
})
- it('with the teams in the core failing on every call, or not starting at all, messages are written and every turn reaches the client', async () => {
- for (const faults of ['teams.prepare,teams.started,teams.raw,teams.forget', 'teams']) {
- daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: faults, ...IN_THE_CORE } })
- const d = daemon
- onTestFailed(() => { console.log(`---- daemon log (${faults})\n${d.log().split('\n').slice(-80).join('\n')}`) })
- await d.start()
- const client = await LocalClient.connect(d)
- const agentId = await boundAgent(d, client, `teams-${faults.length}`)
- for (let i = 1; i <= 3; i++) await turn(client, agentId, `with the teams failing ${i}`)
- expect(d.log()).toContain(faults === 'teams' ? '[services] teams did not start' : '[services] teams.prepare failed')
- expect(d.coresStarted()).toBe(1)
- client.close()
- await d.close()
- daemon = undefined
- }
+ it('with Agent Messages in the core not starting at all, messages are written and every turn reaches the client', async () => {
+ daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'messages', ...IN_THE_CORE } })
+ const d = daemon
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-80).join('\n')}`) })
+ await d.start()
+ const client = await LocalClient.connect(d)
+ const agentId = await boundAgent(d, client, 'messages-off')
+ for (let i = 1; i <= 3; i++) await turn(client, agentId, `with Agent Messages failing ${i}`)
+ expect(d.log()).toContain('[services] messages did not start')
+ expect(d.coresStarted()).toBe(1)
+ client.close()
})
it('a search request that fails in the core before search is switched off answers that request, and the next one too', async () => {
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index 31a60d792..93151d127 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -190,7 +190,7 @@ const EDGE: RegExp[] = [
/^engines\/(claude|codex)\/(normalize|normalizer|subagent|subagentStats|rollout|lastTurn|live|attach)\.ts$/,
/^lib\/(normalize|transcriptReader)\.ts$/, /^lib\/sessionSearch\/externals\/(claude|codex)\.ts$/,
/^engines\/(runtime|(claude|codex)\/runtimeProfile)\.ts$/, /^lib\/runtimeProfile\.ts$/,
- /^gateway\//, /^lib\/e2ee\//, /^cable\//, /^device\//, /^lib\/autonomous-device\//, /^sharing\//, /^teams\//, /^orchestrator\//, /^services\//,
+ /^gateway\//, /^lib\/e2ee\//, /^cable\//, /^device\//, /^lib\/autonomous-device\//, /^sharing\//, /^orchestrator\//, /^services\//,
/^lib\/grid(Attach|Credentials|Derive|Ensure|Envelope|Exec|FleetRpc|Handoff|Install|McpUrl|Models|ModelsPayload|Picture|Presence|Reader|Target|Wake)\.ts$/,
/^lib\/localModels\.ts$/,
// The grid and saved-API launch builders are models': the core asks it for a launch (ModelsPort.gridLaunch) and keeps
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 07d0a78cc..90cb2b8df 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -4059,6 +4059,6 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()
await dispatch({ type: 'message', payload: { content: 'hi', agentId: 'a1' } }, 'local:app', 'local')
expect(onMessage).toHaveBeenCalledWith('a1', 'hi')
await dispatch({ type: 'message', payload: { content: 'task in A', agentId: 'a1', tabId: 'swarm-a' } }, 'local:app', 'local')
- expect(onMessage).toHaveBeenLastCalledWith('a1', 'task in A', undefined, 'swarm-a')
+ expect(onMessage).toHaveBeenLastCalledWith('a1', 'task in A')
})
})
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 52fb1efaa..6f3f4a037 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -1,5 +1,5 @@
import type { PurgeAgentService } from './lib/purgeAgentService.js'
-import { SHARE_REQUESTS, TEAMS_REQUESTS, type Asker, type LocalWindows, type WindowSurface, type BackendNotice, type GatewayEvents, type GatewayPort, type ModelsPort, type RemoteClient, type RemoteRole, type RemoteTransport } from './core/api.js'
+import { MESSAGES_REQUESTS, SHARE_REQUESTS, type Asker, type LocalWindows, type WindowSurface, type BackendNotice, type GatewayEvents, type GatewayPort, type ModelsPort, type RemoteClient, type RemoteRole, type RemoteTransport } from './core/api.js'
import { ServiceUnavailableError } from './core/serviceHost.js'
import { countWindows } from './lib/windowSurfaces.js'
import type { ViewerStreams } from './core/viewerStreams.js'
@@ -45,8 +45,8 @@ export { isLocalClientId, type DownTransport }
/** Requests one local connection may queue before the daemon is ready (see `openRequests`). The app
* sends a handful on connect; hundreds is a client looping, not a person. */
const MAX_REQUESTS_BEFORE_READY = 256
-/** The teams' requests, which the frame log leaves out: they carry what agents ask each other. */
-const TEAM_REQUESTS: ReadonlySet<string> = new Set(TEAMS_REQUESTS)
+/** Agent Messages' requests, which the frame log leaves out: they carry what agents say to each other. */
+const MESSAGE_REQUESTS: ReadonlySet<string> = new Set(MESSAGES_REQUESTS)
/** Share's requests, which the frame log leaves out as well: they carry who a harness is shared with. */
const SHARE_REQUEST_TYPES: ReadonlySet<string> = new Set(SHARE_REQUESTS)
@@ -107,7 +107,7 @@ export class BackendSocket {
onCommanderJoin: (() => void) | null = null
/** Called only when commander presence crosses zero; drives the disposable recap-worker grace. */
onCommanderPresenceChanged: ((connected: boolean) => void) | null = null
- /** Cancels an agent's turn, for the teams and the orchestrator (cli.ts binds core/turns/cancel.ts). */
+ /** Cancels an agent's turn, for the orchestrator (cli.ts binds core/turns/cancel.ts). */
onCancel: ((sessionId: string) => void) | null = null
/** Takes a `cancel` frame, a turn interrupted with C-c (cli.ts binds core/turns/cancel.ts). */
cancelProvider: ((payload: Record<string, unknown>) => void) | null = null
@@ -189,7 +189,7 @@ export class BackendSocket {
* (services/orchestrator.ts, through its port). One that throws costs it that frame, never the apps. */
onFrameSent: ((frame: Frame) => void) | null = null
/** The account's notices the backend announces (`desk_changed`, …), for the experiments that hear them
- * (Tab collaboration reads its tab channels again), as well as the windows here. */
+ * (Agent Messages reads its tabs again), as well as the windows here. */
onAccountNotice: ((notice: BackendNotice) => void) | null = null
/**
* Called on `agent_retarget` — cli.ts re-execs an EXISTING agent's pane against a different grid,
@@ -222,9 +222,9 @@ export class BackendSocket {
| { ok: false; error: string; detail?: string }
>) | null = null
/** Called when the web/device sends chat input to an agent terminal. */
- onMessage: ((sessionId: string, content: string, deliveryId?: string, tabId?: string) => void) | null = null
+ onMessage: ((sessionId: string, content: string, deliveryId?: string) => void) | null = null
/** Takes a `message` frame: text a person typed for an agent, into its pane (cli.ts binds core/input.ts).
- * The teams and the orchestrator deliver through `onMessage` above. */
+ * Agent Messages and the orchestrator deliver through `onMessage` above. */
messageProvider: ((payload: Record<string, unknown>) => void) | null = null
/** Answers `agent_update` through its last argument, before the windows hear of the change: a rename, a
* model and effort, or an app opening the agent (cli.ts binds core/agents/update.ts). */
@@ -740,7 +740,7 @@ export class BackendSocket {
private emitReply(connId: string, type: string, requestId: unknown, payload: Record<string, unknown>): void {
const resultType = rpcResultType(type)
// Before the E2EE wrap: an RPC reply is only readable here.
- if (env.LOG_FRAMES && !TEAM_REQUESTS.has(type) && !ROUTE_COMMAND_TYPES.has(type) && !type.startsWith('viewer_') && type !== 'phone_pair' && type !== 'api_connections' && type !== 'connectors' && type !== 'orchestrator' && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })
+ if (env.LOG_FRAMES && !MESSAGE_REQUESTS.has(type) && !ROUTE_COMMAND_TYPES.has(type) && !type.startsWith('viewer_') && type !== 'phone_pair' && type !== 'api_connections' && type !== 'connectors' && type !== 'orchestrator' && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })
if (this.localClients.has(connId)) {
this.sendTo(connId, { type: resultType, payload: { requestId, ...payload } })
return
@@ -799,7 +799,7 @@ export class BackendSocket {
// actually asked for rather than as an opaque __e2e envelope.
// Terminal frames contain raw keystrokes, paste text and screen bytes after
// unwrap. Never pass them to the frame logger, even in diagnostic mode.
- if (env.LOG_FRAMES && !TEAM_REQUESTS.has(type) && !ROUTE_COMMAND_TYPES.has(type) && !type.startsWith('terminal_') && !type.startsWith('viewer_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && type !== 'orchestrator' && type !== 'api_connections' && type !== 'connectors' && type !== 'phone_pair' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) {
+ if (env.LOG_FRAMES && !MESSAGE_REQUESTS.has(type) && !ROUTE_COMMAND_TYPES.has(type) && !type.startsWith('terminal_') && !type.startsWith('viewer_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && type !== 'orchestrator' && type !== 'api_connections' && type !== 'connectors' && type !== 'phone_pair' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) {
logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)
}
const reply = (t: string, rid: unknown, p: Record<string, unknown>): void => this.emitReply(connId, t, rid, p)
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 6841ba9bf..f9e7b0db4 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -137,7 +137,7 @@ Machine:
harness search <words> find the conversation on this computer that said them: every turn of
every harness, live or stopped (--limit=N, --json)
harness send <name> "text" from an agent's pane: message a teammate in this tab, when Agent Messages
- are on there (⇄ on the tab); \`harness send\` alone lists who is here
+ are on there (the tab's chat icon); \`harness send\` alone lists who is here
harness machines delete <id> remove ANOTHER machine (refuses this one; use \`harness logout\`)
harness remote from a Harness terminal tile: open a terminal on another of your machines and move this tile to it
harness version print the installed version (v${VERSION})
diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.md
index bb5229d41..27332bc1d 100644
--- a/cli/src/core/AGENTS.md
+++ b/cli/src/core/AGENTS.md
@@ -58,8 +58,7 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE
in this process. `serviceLinks.ts`: services in their own processes. `viewersLink.ts`: what the core
keeps of the viewers when they run in theirs. `viewerStreams.ts`: a client's viewer stream and rendered
frames, handed to the viewers, and refused at once while they are down. `workspacesLink.ts`: what the core tells workspaces in
- theirs. `teamsLink.ts`: every change to the teams' prompt scopes, kept until their process has it once Tab
- collaboration is on, which of its deliveries may be written, and the scopes' own two questions.
+ theirs. `messagesLink.ts`: which of Agent Messages' deliveries may be written, as its process last said.
`monitorLink.ts`: the monitor's port, asked of its process. `recapsLink.ts`: the recaps in their process,
told each turn's lifecycle and never waited on, and read back from what they last said
(`turns/recaps.ts` is the core's whole side of them). `storeLink.ts`: what the Store in its
diff --git a/cli/src/core/agentQueries.ts b/cli/src/core/agentQueries.ts
index db373ec51..a7cc6bb03 100644
--- a/cli/src/core/agentQueries.ts
+++ b/cli/src/core/agentQueries.ts
@@ -1,7 +1,7 @@
import { usageTargetKey, usageTarget, validUsageTarget } from '../lib/agentUsageWire.js'
/**
* What a service in its own process may ask the core of the agents (`service_query`, core/serviceLinks.ts)
- * when it has no link module of its own to answer it (the viewers, workspaces and the teams do):
+ * when it has no link module of its own to answer it (the viewers and workspaces do):
* - `agents`: every agent, live then stopped, with the name the apps show for it (search indexes them);
* - `live`: the live agents, as `CoreApi.agents.live` answers in the core's process (the project readers);
* - `advertised`: the live agents the apps are shown (the monitor samples them).
diff --git a/cli/src/core/agents/bind.spec.ts b/cli/src/core/agents/bind.spec.ts
index bc4935210..2b7702624 100644
--- a/cli/src/core/agents/bind.spec.ts
+++ b/cli/src/core/agents/bind.spec.ts
@@ -76,7 +76,6 @@ function setup(over: Partial<BindDeps> = {}) {
announceSession: vi.fn(),
stoppedAgents: { save: vi.fn(), finishResume: vi.fn(), get: vi.fn(() => null) },
syncRecapPool: vi.fn(),
- teams: { forget: vi.fn() },
input: { forget: vi.fn() },
deviceInput: { forget: vi.fn() },
homes: { copilot: '/copilot', grok: '/grok', agy: '/agy' },
@@ -739,7 +738,6 @@ describe('binding a running process to its session', () => {
run.bySession.set('r', previous)
vi.mocked(run.deps.registry.register).mockReturnValue({ entry: agent({ sessionId: 'r' }), ...meta({ isNew: true }) } as never)
await run.binding.bindObservedAgent(observed({ resumeSessionId: 'r' } as Partial<DiscoveredTerminalAgent>))
- expect(run.deps.teams.forget).toHaveBeenCalledWith('old')
expect(run.deps.input.forget).toHaveBeenCalledWith('old')
expect(run.deps.deviceInput.forget).toHaveBeenCalledWith('old')
expect(run.deps.announceSession).toHaveBeenCalledWith(previous)
diff --git a/cli/src/core/agents/bind.ts b/cli/src/core/agents/bind.ts
index 3e30feeea..8a2454f0d 100644
--- a/cli/src/core/agents/bind.ts
+++ b/cli/src/core/agents/bind.ts
@@ -24,7 +24,6 @@ import { findLiveSession, findResumedTranscript } from '../../lib/sessionRepair.
import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'
import { conversationKey, type ConversationOwners } from './conversationOwners.js'
import type { DiscoveredTerminalAgent } from '../../lib/terminalAgentDiscovery.js'
-import type { SwarmPromptScopes } from '../../teams/promptScope.js'
/** Between session-binding attempts for a process whose engine store is not resolvable yet. */
const REPAIR_RETRY_MS = 60_000
@@ -65,7 +64,6 @@ export interface BindDeps {
announceSession: (session: RegisteredSession) => void
stoppedAgents: Pick<StoppedAgentStore, 'save' | 'finishResume' | 'get'>
syncRecapPool: () => void
- teams: Pick<SwarmPromptScopes, 'forget'>
input: Pick<SessionInputController, 'forget'>
deviceInput: Pick<AutonomousDeviceInput, 'forget'>
/** Where Copilot, Grok and agy keep their sessions. */
@@ -75,7 +73,7 @@ export interface BindDeps {
}
export function createBinding({
- registry, mirror, forgetSession, clients, attachSession, announceSession, stoppedAgents, syncRecapPool, teams,
+ registry, mirror, forgetSession, clients, attachSession, announceSession, stoppedAgents, syncRecapPool,
input, deviceInput, homes, owners,
}: BindDeps) {
/**
@@ -411,7 +409,6 @@ export function createBinding({
})
if (!result || !result.isNew) return
if (previousOwner && previousOwner.agentId !== result.entry.agentId) {
- teams.forget(previousOwner.agentId)
input.forget(previousOwner.agentId)
deviceInput.forget(previousOwner.agentId)
announceSession(previousOwner)
diff --git a/cli/src/core/agents/discovery.spec.ts b/cli/src/core/agents/discovery.spec.ts
index 110faab0d..efab9f87e 100644
--- a/cli/src/core/agents/discovery.spec.ts
+++ b/cli/src/core/agents/discovery.spec.ts
@@ -46,7 +46,6 @@ function setup(over: Partial<DiscoveryDeps> = {}) {
syncRecapPool: vi.fn(),
attachSession: vi.fn(async () => true),
invalidateTerminalControl: vi.fn(),
- teams: { forget: vi.fn() },
input: { forget: vi.fn() },
deviceInput: { forget: vi.fn() },
questionWatcher: { stop: vi.fn() },
@@ -217,7 +216,6 @@ describe('discovery', () => {
const exited = row({ resumeOnly: true } as Partial<RegisteredSession>)
await run.handlers.onDormant(exited, 'engine exited')
expect(run.deps.invalidateTerminalControl).toHaveBeenCalledWith('a1')
- expect(run.deps.teams.forget).toHaveBeenCalledWith('a1')
expect(run.deps.input.forget).toHaveBeenCalledWith('a1')
expect(run.deps.deviceInput.forget).toHaveBeenCalledWith('a1')
expect(run.deps.questionWatcher.stop).toHaveBeenCalledWith('s1')
diff --git a/cli/src/core/agents/discovery.ts b/cli/src/core/agents/discovery.ts
index 736265e07..2022b9e9e 100644
--- a/cli/src/core/agents/discovery.ts
+++ b/cli/src/core/agents/discovery.ts
@@ -19,7 +19,6 @@ import type { SessionInputController } from '../../lib/sessionInput.js'
import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'
import type { DiscoveredTerminalAgent } from '../../lib/terminalAgentDiscovery.js'
import { bypassPermissionActive, permissionModeFromArgv, tmuxPaneState } from '../../lib/tmux.js'
-import type { SwarmPromptScopes } from '../../teams/promptScope.js'
export interface DiscoveryDeps {
registry: Pick<typeof registry,
@@ -33,7 +32,6 @@ export interface DiscoveryDeps {
syncRecapPool: () => void
attachSession: (session: RegisteredSession) => Promise<boolean>
invalidateTerminalControl: (agentId: string) => void
- teams: Pick<SwarmPromptScopes, 'forget'>
input: Pick<SessionInputController, 'forget'>
deviceInput: Pick<AutonomousDeviceInput, 'forget'>
questionWatcher: Pick<QuestionWatcher, 'stop'>
@@ -47,7 +45,7 @@ export interface DiscoveryDeps {
export function createDiscoveryHandlers({
registry, attachDsh, forgetSession, announceSession, bindObservedAgent, syncRecapPool, attachSession,
- invalidateTerminalControl, teams, input, deviceInput, questionWatcher, stopHeartbeat, retainExitedSession,
+ invalidateTerminalControl, input, deviceInput, questionWatcher, stopHeartbeat, retainExitedSession,
stoppedAgents, restoreDegraded,
}: DiscoveryDeps) {
const onDiscovered = async (observed: DiscoveredTerminalAgent): Promise<void> => {
@@ -183,7 +181,6 @@ export function createDiscoveryHandlers({
const onDormant = async (agent: RegisteredSession, reason: string): Promise<void> => {
if (!agent.active || agent.launch?.state === 'held') return
invalidateTerminalControl(agent.agentId)
- teams.forget(agent.agentId)
input.forget(agent.agentId)
deviceInput.forget(agent.agentId)
if (agent.sessionId) {
diff --git a/cli/src/core/agents/forget.spec.ts b/cli/src/core/agents/forget.spec.ts
index 146bb28e4..11e5a4e08 100644
--- a/cli/src/core/agents/forget.spec.ts
+++ b/cli/src/core/agents/forget.spec.ts
@@ -28,7 +28,6 @@ function setup() {
runtimeProfiles: { forget: vi.fn() },
watcher: { removeSession: vi.fn(async () => {}) },
stopHeartbeat: vi.fn(),
- teams: { forget: vi.fn() },
input: { forget: vi.fn() },
deviceInput: { forget: vi.fn() },
detachDsh: vi.fn(),
@@ -55,7 +54,6 @@ function expectLetGo(deps: ForgetDeps, sessionId: string, agentId: string) {
expect(deps.runtimeProfiles.forget).toHaveBeenCalledWith(sessionId)
expect(deps.watcher.removeSession).toHaveBeenCalledWith(sessionId)
expect(deps.stopHeartbeat).toHaveBeenCalledWith(sessionId)
- expect(deps.teams.forget).toHaveBeenCalledWith(agentId)
expect(deps.input.forget).toHaveBeenCalledWith(agentId)
expect(deps.deviceInput.forget).toHaveBeenCalledWith(agentId)
expect(deps.mirror.forget).toHaveBeenCalledWith(sessionId)
@@ -181,8 +179,8 @@ describe('forgetting a session', () => {
it('clears agent-keyed input after binding revalidation has already released the session index', () => {
const { deps } = setup()
vi.mocked(deps.registry.resolve).mockReturnValue(undefined)
- const pending = ['teams', 'input', 'deviceInput'].map(() => new Map([['a1', 'queued'], ['other', 'keep']]))
- for (const [index, key] of (['teams', 'input', 'deviceInput'] as const).entries()) {
+ const pending = ['input', 'deviceInput'].map(() => new Map([['a1', 'queued'], ['other', 'keep']]))
+ for (const [index, key] of (['input', 'deviceInput'] as const).entries()) {
deps[key].forget = id => { pending[index]!.delete(id) }
}
createForgetSession(deps)('s1', { force: true, keepAgent: true, agentId: 'a1' })
diff --git a/cli/src/core/agents/forget.ts b/cli/src/core/agents/forget.ts
index d62d584ac..e157cca8d 100644
--- a/cli/src/core/agents/forget.ts
+++ b/cli/src/core/agents/forget.ts
@@ -16,7 +16,6 @@ import type { RegisteredSession, registry } from '../../lib/registry.js'
import type { RuntimeProfileManager } from '../../lib/runtimeProfile.js'
import type { SessionInputController } from '../../lib/sessionInput.js'
import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'
-import type { SwarmPromptScopes } from '../../teams/promptScope.js'
import type { Watcher } from '../../watcher/watcher.js'
import type { SessionNormalizers } from '../transcripts/normalizers.js'
import type { RelaunchMarks } from '../transcripts/relaunch.js'
@@ -44,7 +43,6 @@ export interface ForgetDeps {
runtimeProfiles: Pick<RuntimeProfileManager, 'forget'>
watcher: Pick<Watcher, 'removeSession'>
stopHeartbeat: (sessionId: string) => void
- teams: Pick<SwarmPromptScopes, 'forget'>
input: Pick<SessionInputController, 'forget'>
deviceInput: Pick<AutonomousDeviceInput, 'forget'>
detachDsh: (agentId: string) => void
@@ -56,7 +54,7 @@ export interface ForgetDeps {
export function createForgetSession({
registry, stoppedAgents, syncRecapPool, normalizers, forgetAttach, turnStartedAt, neverFoldedHistory, replayedFirstTurn, relaunchMarks,
- clearAgyIdleWatch, cursorDiscovery, cursorSubagents, runtimeProfiles, watcher, stopHeartbeat, teams, input,
+ clearAgyIdleWatch, cursorDiscovery, cursorSubagents, runtimeProfiles, watcher, stopHeartbeat, input,
deviceInput, detachDsh, mirror, clients, dataDir, onRemoved, owners,
}: ForgetDeps) {
/** Release a mutable session binding, or remove the process-owned agent everywhere. */
@@ -116,7 +114,6 @@ export function createForgetSession({
runtimeProfiles.forget(sessionId)
void watcher.removeSession(sessionId)
stopHeartbeat(sessionId)
- teams.forget(announceId)
input.forget(announceId)
deviceInput.forget(announceId)
if (!opts.keepAgent) { detachDsh(announceId); onRemoved?.(announceId) }
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index 38c339f46..d50a9ce84 100644
--- a/cli/src/core/api.spec.ts
+++ b/cli/src/core/api.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { projectDisplayName, type RegisteredSession } from '../lib/registry.js'
-import { CONVERSATIONS_OFF, ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, DEVICES_FALLBACKS, emptyPorts, LANE_OFF, LONG_ANSWERS, MODELS_OFF, STORE_OFF, MODELS_REQUESTS, MONITOR_OFF, OBSERVER_KEY_OFF, ORCHESTRATOR_FALLBACKS, RECAPS_FALLBACKS, resolveAgent, SHARING_FALLBACKS, TEAMS_FALLBACKS, TERMINALS_OFF, WIFI_FALLBACKS, WIFI_OFF, type CoreApiDeps } from './api.js'
+import { CONVERSATIONS_OFF, ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, DEVICES_FALLBACKS, emptyPorts, LANE_OFF, LONG_ANSWERS, MODELS_OFF, STORE_OFF, MODELS_REQUESTS, MONITOR_OFF, OBSERVER_KEY_OFF, ORCHESTRATOR_FALLBACKS, RECAPS_FALLBACKS, resolveAgent, SHARING_FALLBACKS, MESSAGES_FALLBACKS, TERMINALS_OFF, WIFI_FALLBACKS, WIFI_OFF, type CoreApiDeps } from './api.js'
import { FAIL, readFallback } from './serviceHost.js'
const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession
@@ -241,14 +241,12 @@ describe('the core API services stand on', () => {
() => WIFI_OFF.streams([])]) expect(call()).toBeUndefined()
})
- it('falls back, when the teams fail, to an undo that has nothing to undo, and holds no pane for a team', () => {
- const undo = TEAMS_FALLBACKS.prepare as () => void
- expect(undo()).toBeUndefined()
- expect(TEAMS_FALLBACKS.canWrite).toBe(false)
+ it('falls back, when Agent Messages fails, to writing none of its deliveries', () => {
+ expect(MESSAGES_FALLBACKS.canWrite).toBe(false)
})
it('starts with every port empty: a service fills its own when it starts', () => {
- expect(emptyPorts()).toEqual({ usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, teams: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null })
+ expect(emptyPorts()).toEqual({ usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, messages: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null })
expect(emptyPorts()).not.toBe(emptyPorts())
})
@@ -287,7 +285,7 @@ describe('the core API services stand on', () => {
})
it('gives a service that reads no backend an unavailable answer, and no notice to hear', async () => {
- expect(await ACCOUNT_BACKEND_OFF.backend('GET', '/api/tab-channels')).toEqual({ status: 503, body: { error: 'SERVICE_UNAVAILABLE' } })
+ expect(await ACCOUNT_BACKEND_OFF.backend('GET', '/api/agent-messages')).toEqual({ status: 503, body: { error: 'SERVICE_UNAVAILABLE' } })
expect(ACCOUNT_BACKEND_OFF.onNotice(() => {})()).toBeUndefined()
})
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index cf3d75ac6..814ac51e1 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -40,7 +40,6 @@ import type { StoppedAgentStore } from '../lib/stoppedAgents.js'
import type { TerminalBinaryClear } from '../lib/terminalBinary.js'
import { VIEWER_UP_TYPES } from '../lib/viewerFrames.js'
import type { RouteAnswer } from '../localWsServer.js'
-import type { SwarmPromptScopes } from '../teams/promptScope.js'
import type { DeviceInputStatus } from './deviceInput.js'
import { FAIL, later, readFallback, ServiceUnavailableError, type PortFallbacks } from './serviceHost.js'
@@ -179,12 +178,12 @@ export interface CoreApi {
recent(agentId: string, n: number): Promise<RecentTurn[]>
/** The person's own last questions to a live agent, newest first. */
asks(agentId: string): Promise<string[]>
- /** Deliver text into a live agent under a delivery id of the caller's own, as the Wi-Fi device, a team
- * and the orchestrator deliver their turns: one path for the three. What becomes of it is heard through
+ /** Deliver text into a live agent under a delivery id of the caller's own, as the Wi-Fi device, Agent
+ * Messages and the orchestrator deliver their turns: one path for the three. What becomes of it is heard through
* `onDelivery`, under the same id. */
deliver(agentId: string, text: string, deliveryId: string): void
/** Take back a delivery not yet being written: true when it was, and it never will be; false for one
- * the agent's pane is already taking. Answered at once, as the teams and the orchestrator read it in
+ * the agent's pane is already taking. Answered at once, as the orchestrator reads it in
* line: in a service's own process the core is asked and the answer cannot wait, so it is false there,
* and a delivery the core did take back is then heard `rejected` (`cancelled`). */
cancelDelivery(deliveryId: string): boolean
@@ -235,7 +234,7 @@ export interface CoreApi {
* until the first one lands. */
machineName(): string | null
/** A read or write of the account's backend, signed in by the core (`proxyBackend`): an experiment's
- * account-wide settings (Tab collaboration's tab channels). A failure is an answer: 502, 504, 401. */
+ * account-wide settings (Agent Messages' tabs). A failure is an answer: 502, 504, 401. */
backend(method: string, path: string, body?: unknown): Promise<{ status: number; body: Record<string, unknown> }>
/** Hear the account's changes the backend announces (`desk_changed`, …). Returns how to stop hearing. */
onNotice(listener: (notice: BackendNotice) => void): () => void
@@ -533,9 +532,9 @@ export const SHARE_REQUESTS = [
'harness_share_comments', 'harness_share_comment_post', 'harness_share_comment_remove',
] as const
-/** Agent Messages (services/collaboration.ts, messages/service.ts), in the slot Tab collaboration had: from
- * `harness send` in an agent's pane, from the owner's other machines and from the windows. */
-export const TEAMS_REQUESTS = ['agent_messages'] as const
+/** Agent Messages (services/messages.ts, messages/service.ts): from `harness send` in an agent's pane, from the
+ * owner's other machines and from the windows. */
+export const MESSAGES_REQUESTS = ['agent_messages'] as const
/**
* The experiments: services that cost nothing until they are on (docs/design/2026-10-06-core-boundary-next.md,
@@ -552,9 +551,8 @@ export const TEAMS_REQUESTS = ['agent_messages'] as const
*/
export const EXPERIMENTS: Readonly<Record<string, { requests: readonly string[]; state: readonly string[] }>> = {
orchestrator: { requests: ORCHESTRATOR_REQUESTS, state: ['orchestrator/*.json'] },
- // Agent Messages, beside the prompt scopes in the teams' process (harnessd/services.ts). Its history and
- // waiting deliveries: a message was sent from here or delivered to an agent here.
- collaboration: { requests: TEAMS_REQUESTS, state: ['agent-messages'] },
+ // Agent Messages. Its history and waiting deliveries: a message was sent from here or delivered to an agent here.
+ messages: { requests: MESSAGES_REQUESTS, state: ['agent-messages'] },
// Its invitations and links: a harness was shared from here.
sharing: { requests: SHARE_REQUESTS, state: ['harness-shares.json', 'harness-collaboration.json'] },
// Request-only, on from its first request until the daemon stops: another machine's Memories pane asks, and
@@ -809,35 +807,14 @@ export interface WorkspacesPort {
/** What the core gets when workspaces fails: branches keep their names and nothing is swept. */
export const WORKSPACES_FALLBACKS: PortFallbacks<WorkspacesPort> = { nameBranches: undefined, sweepUnused: undefined }
-/** The prompt scopes whole: the core's calls, which team a prompt belongs to, recorded as a message is
- * written, as a turn starts (from its hook or its transcript), as it is typed into a scoped terminal, and
- * forgotten with its agent; and the team a prompt came from (`current`), which an agent's answer to a
- * team's question moves back (`replied`). In the core's process the teams service's own; in their own,
- * core/teamsLink.ts. */
-export type PromptScopes = Pick<SwarmPromptScopes, 'prepare' | 'started' | 'raw' | 'forget' | 'current' | 'replied'>
-
-/** The core's calls into the teams: the prompt scopes' records, and whether a team's delivery still holds
- * the agent's pane, asked in line as its turn is written (core/input.ts). */
-export type TeamsPort = Pick<PromptScopes, 'prepare' | 'started' | 'raw' | 'forget'> & {
+/** The core's call into Agent Messages: whether one of its typed deliveries (a `team:` id) may still be written,
+ * asked in line as it is written (core/input.ts). */
+export interface MessagesPort {
canWrite(deliveryId: string): boolean
}
-/** What the core gets when the teams fail: the prompt is written with no team recorded for it, and a team's
- * delivery holds no pane (it waits, unwritten). */
-export const TEAMS_FALLBACKS: PortFallbacks<TeamsPort> = { prepare: () => {}, started: undefined, raw: undefined, forget: undefined, canWrite: false }
-
-
-/** A change to the prompt scopes, as the core tells the teams' own process (core/teamsLink.ts,
- * services/teamsProcess.ts): numbered within one core's life, stamped with when it happened, and
- * given to the process in order, once. `raw` bytes travel as base64. */
-export type TeamsEvent = { seq: number; core: string; at: number; agentId: string } & (
- | { kind: 'prepare'; text: string; tabId?: string; deliveryId?: string }
- | { kind: 'unprepare'; of: number }
- | { kind: 'started'; text: string; source: 'hook' | 'transcript'; engine?: string }
- | { kind: 'raw'; bytes: string; tabId?: string; pasted: boolean }
- | { kind: 'forget' }
- | { kind: 'replied'; teamId: string; questionId: string }
-)
+/** What the core gets when Agent Messages fails: none of its deliveries may be written (each waits, unwritten). */
+export const MESSAGES_FALLBACKS: PortFallbacks<MessagesPort> = { canWrite: false }
/** What a delivered turn answers: delivered, or refused with the machine's name and a reason a person can read. */
export type SendResult = { ok: true } | { ok: false; machine: string; reason: string }
@@ -1324,7 +1301,7 @@ export interface CorePorts {
viewers: ViewersPort | null
models: ModelsPort | null
workspaces: WorkspacesPort | null
- teams: TeamsPort | null
+ messages: MessagesPort | null
devices: DevicesPort | null
wifi: WifiPort | null
monitor: MonitorPort | null
@@ -1334,7 +1311,7 @@ export interface CorePorts {
}
export function emptyPorts(): CorePorts {
- return { usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, teams: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null }
+ return { usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, messages: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null }
}
export interface CoreApiDeps {
diff --git a/cli/src/core/deliveries.spec.ts b/cli/src/core/deliveries.spec.ts
index 9458afabf..1fcdb97c1 100644
--- a/cli/src/core/deliveries.spec.ts
+++ b/cli/src/core/deliveries.spec.ts
@@ -80,16 +80,16 @@ describe('delivered turns', () => {
})
it('remembers the makers of the last deliveries only, a delivery made again as the newest', () => {
- const { deps, deliveries } = setup({ deliverers: new Set(['orchestrator', 'teams']) })
+ const { deps, deliveries } = setup({ deliverers: new Set(['orchestrator', 'messages']) })
deliveries.answer('orchestrator', 'deliver', { agentId: 'a', text: 't', deliveryId: 'first' })
- deliveries.answer('teams', 'deliver', { agentId: 'a', text: 't', deliveryId: 'second' })
+ deliveries.answer('messages', 'deliver', { agentId: 'a', text: 't', deliveryId: 'second' })
// Made again: the newest now, and by its new maker.
- deliveries.answer('teams', 'deliver', { agentId: 'a', text: 't', deliveryId: 'first' })
+ deliveries.answer('messages', 'deliver', { agentId: 'a', text: 't', deliveryId: 'first' })
for (let i = 0; i < KEPT_DELIVERERS - 1; i++) deliveries.answer('orchestrator', 'deliver', { agentId: 'a', text: 't', deliveryId: `d${i}` })
deps.tell.mockClear()
deliveries.settled(event('second'))
deliveries.settled(event('first'))
- expect(deps.tell.mock.calls).toEqual([['teams', event('first')]])
+ expect(deps.tell.mock.calls).toEqual([['messages', event('first')]])
})
it('holds what is delivered before the core\'s input is wired, writes it in order once it is, and the rest as it comes', () => {
diff --git a/cli/src/core/deliveries.ts b/cli/src/core/deliveries.ts
index 2529dafba..ff60c51bf 100644
--- a/cli/src/core/deliveries.ts
+++ b/cli/src/core/deliveries.ts
@@ -1,6 +1,6 @@
/**
* Delivered turns: text a feature writes into an agent under a delivery id of its own, and what becomes of
- * it. The Wi-Fi device, the teams and the orchestrator each deliver their turns this way, one path for the
+ * it. The Wi-Fi device, Agent Messages and the orchestrator each deliver their turns this way, one path for the
* three (docs/design/2026-10-06-core-boundary-next.md, "Experimental features: move only"). It is what
* lets a feature that delivers turns run in a process of its own: before, each was a slot on the socket
* (`onMessage`, `onCancelOrchestratorMessage`, `orchestratorDelivery`, `teamDelivery`) that only code in
@@ -15,7 +15,7 @@ import type { CoreApi, TurnDelivery } from './api.js'
type Payload = Record<string, unknown>
-/** The most deliveries held while the core starts: a teams' mailbox resumes a few at most. */
+/** The most deliveries held while the core starts: Agent Messages' mailbox resumes a few at most. */
export const HELD_DELIVERIES = 1_000
/** The most deliveries whose maker is remembered: past it the oldest is forgotten, and what becomes of it
@@ -43,8 +43,8 @@ export function createDeliveries(deps: DeliveriesDeps) {
/** Which process made each delivery, oldest first. */
const makers = new Map<string, string>()
/**
- * What was delivered before the core's input was wired (`ready`), in order. A teams' mailbox resumes its
- * queue on a timer as soon as it starts, in the core's process or in its own, and the socket held such a
+ * What was delivered before the core's input was wired (`ready`), in order. Agent Messages' mailbox resumes
+ * its queue on a timer as soon as it starts, in the core's process or in its own, and the socket held such a
* turn back with "Agent input is not ready" until then; dropped, it would read as written and never be.
*/
let held: Array<{ agentId: string; text: string; deliveryId: string }> | null = []
diff --git a/cli/src/core/experimentQueries.spec.ts b/cli/src/core/experimentQueries.spec.ts
index 06142b648..5fbc0460d 100644
--- a/cli/src/core/experimentQueries.spec.ts
+++ b/cli/src/core/experimentQueries.spec.ts
@@ -61,9 +61,9 @@ describe('what an experiment in its own process may ask of the core', () => {
it('reads and writes the account\'s backend under /api/, signed in by the core, and nothing else', async () => {
const backend = vi.fn(async () => ({ status: 200, body: { success: true, data: { tabs: [] } } }))
const core = fakeCore({ account: { backend } })
- expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'backend', { method: 'PATCH', path: '/api/tab-channels/settings', body: { enabled: true } }))
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'backend', { method: 'PATCH', path: '/api/agent-messages/tabs/t1', body: { enabled: true } }))
.toEqual({ status: 200, body: { success: true, data: { tabs: [] } } })
- expect(backend).toHaveBeenCalledWith('PATCH', '/api/tab-channels/settings', { enabled: true })
+ expect(backend).toHaveBeenCalledWith('PATCH', '/api/agent-messages/tabs/t1', { enabled: true })
for (const bad of [{ method: 'TRACE', path: '/api/x' }, { method: 'GET', path: '/auth/token' }, { method: 'GET' }]) {
expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'backend', bad)).toEqual({ error: 'INVALID_REQUEST' })
}
diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.ts
index 6da4ddaae..281976256 100644
--- a/cli/src/core/experimentQueries.ts
+++ b/cli/src/core/experimentQueries.ts
@@ -10,7 +10,7 @@
* - `windows`: a change notice for every window on this computer (`orchestrator_changed`);
* - `daemon`: how an agent's shell reaches this daemon, for the prompts the experiment writes;
* - `backend`: a read or write of the account's backend under `/api/`, signed in by the core, which holds the
- * sign-in (Tab collaboration's tab channels);
+ * sign-in (Agent Messages' tabs);
* - `observer_key`: this machine's public key, or its signature on a welcome to one observer of one share, by
* the gateway, which holds the identity (Share's owner);
* - `observer_send`: a frame Share sealed for one of its observers, to the relay through the gateway.
diff --git a/cli/src/core/experiments.spec.ts b/cli/src/core/experiments.spec.ts
index 41da18ae1..f21ddc64d 100644
--- a/cli/src/core/experiments.spec.ts
+++ b/cli/src/core/experiments.spec.ts
@@ -10,7 +10,7 @@ describe('the experiments on as the core starts', () => {
afterEach(() => rmSync(dataDir, { recursive: true, force: true }))
it('finds saved state by path, or by a file of its kind in its folder', () => {
- expect(stateIsThere(dataDir, ['teams'])).toBe(false)
+ expect(stateIsThere(dataDir, ['agent-messages'])).toBe(false)
expect(stateIsThere(dataDir, ['orchestrator/*.json'])).toBe(false)
mkdirSync(join(dataDir, 'orchestrator'))
// A folder made by a look, with no project in it, is not a project.
@@ -18,8 +18,8 @@ describe('the experiments on as the core starts', () => {
expect(stateIsThere(dataDir, ['orchestrator/*.json'])).toBe(false)
writeFileSync(join(dataDir, 'orchestrator', `${'a'.repeat(32)}.json`), '{}')
expect(stateIsThere(dataDir, ['orchestrator/*.json'])).toBe(true)
- mkdirSync(join(dataDir, 'teams'))
- expect(stateIsThere(dataDir, ['nothing', 'teams'])).toBe(true)
+ mkdirSync(join(dataDir, 'agent-messages'))
+ expect(stateIsThere(dataDir, ['nothing', 'agent-messages'])).toBe(true)
expect(stateIsThere(dataDir, [])).toBe(false)
})
@@ -30,9 +30,9 @@ describe('the experiments on as the core starts', () => {
const want = vi.fn()
const woken = wakeExperiments({
dataDir,
- experiments: { orchestrator: { state: ['orchestrator/*.json'] }, sharing: { state: ['harness-shares.json'] }, teams: { state: ['teams'] } },
+ experiments: { orchestrator: { state: ['orchestrator/*.json'] }, sharing: { state: ['harness-shares.json'] }, messages: { state: ['agent-messages'] } },
// Share runs in the core's process here: it is started there, not asked for.
- outOfProcess: new Set(['orchestrator', 'teams']),
+ outOfProcess: new Set(['orchestrator', 'messages']),
want,
})
expect(woken).toEqual(['orchestrator'])
@@ -68,21 +68,20 @@ describe('the experiments on as the core starts', () => {
}
})
- it('asks for an experiment after doing what it must not miss, and tells each experiment in its own process the account\'s notices', () => {
+ it('asks for an experiment, and tells each experiment in its own process the account\'s notices', () => {
const order: string[] = []
const notify = vi.fn(() => true)
const hooks = createExperimentHooks({
- want: (service) => order.push(`want ${service}`), notify, outOfProcess: new Set(['collaboration']), experiments: ['orchestrator', 'collaboration'],
- onWant: { collaboration: () => order.push('keep the scopes') },
+ want: (service) => order.push(`want ${service}`), notify, outOfProcess: new Set(['messages']), experiments: ['orchestrator', 'messages'],
})
- hooks.want('collaboration')
+ hooks.want('messages')
hooks.want('orchestrator')
- expect(order).toEqual(['keep the scopes', 'want collaboration', 'want orchestrator'])
+ expect(order).toEqual(['want messages', 'want orchestrator'])
const heard = vi.fn()
hooks.onNotice(heard)
hooks.notice({ type: 'desk_changed', revision: 5 })
expect(heard).toHaveBeenCalledWith({ type: 'desk_changed', revision: 5 })
- expect(notify.mock.calls).toEqual([['collaboration', { type: 'service_event', payload: { kind: 'notice', notice: { type: 'desk_changed', revision: 5 } } }]])
+ expect(notify.mock.calls).toEqual([['messages', { type: 'service_event', payload: { kind: 'notice', notice: { type: 'desk_changed', revision: 5 } } }]])
createExperimentHooks({ want: vi.fn(), notify, outOfProcess: new Set(), experiments: [] }).want('x')
})
})
diff --git a/cli/src/core/experiments.ts b/cli/src/core/experiments.ts
index 73b186497..f9d0ef198 100644
--- a/cli/src/core/experiments.ts
+++ b/cli/src/core/experiments.ts
@@ -39,8 +39,8 @@ export function wakeExperiments(options: {
/**
* The account's notices the backend announces (`desk_changed`, …), for the experiments that hear them: each
- * listener in this process (`core.account.onNotice`), guarded, and each experiment's process (`tell`). Tab
- * collaboration reads its tab channels again at `desk_changed`, as the socket did before it left.
+ * listener in this process (`core.account.onNotice`), guarded, and each experiment's process (`tell`). Agent
+ * Messages reads its tabs again at `desk_changed`.
*/
export function createAccountNotices(tell: (notice: BackendNotice) => void, log: (line: string) => void = (line) => console.warn(line)) {
const listeners = new Set<(notice: BackendNotice) => void>()
@@ -59,26 +59,21 @@ export function createAccountNotices(tell: (notice: BackendNotice) => void, log:
}
/**
- * What the core does for the experiments as a whole: ask the master for one (`want`), first doing what that
- * experiment must not miss from then on (`onWant`: the teams' scopes kept from the moment teams is on), and
- * hand the account's notices to the listeners here and to each experiment in its own process.
+ * What the core does for the experiments as a whole: ask the master for one (`want`), and hand the account's
+ * notices to the listeners here and to each experiment in its own process.
*/
export function createExperimentHooks(deps: {
want: (service: string) => void
notify: (service: string, frame: { type: string; payload: Record<string, unknown> }) => boolean
outOfProcess: ReadonlySet<string>
experiments: Iterable<string>
- onWant?: Readonly<Record<string, () => void>>
log?: (line: string) => void
}) {
const notices = createAccountNotices((notice) => {
for (const name of deps.experiments) if (deps.outOfProcess.has(name)) deps.notify(name, { type: 'service_event', payload: { kind: 'notice', notice } })
}, deps.log)
return {
- want(service: string): void {
- if (deps.onWant && Object.hasOwn(deps.onWant, service)) deps.onWant[service]()
- deps.want(service)
- },
+ want: deps.want,
onNotice: notices.onNotice,
notice: notices.notice,
}
diff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.ts
index 34c091e4d..dc38ae191 100644
--- a/cli/src/core/input.spec.ts
+++ b/cli/src/core/input.spec.ts
@@ -54,9 +54,8 @@ function deps(over: Partial<InputDeps> = {}) {
keyTerminalAction: vi.fn(async (id: string, key: string) => { calls.push(`key ${id} ${key}`); return ok }),
pinTerminalControl: vi.fn(() => () => { calls.push('unpin') }),
},
- teams: {
- prepare: vi.fn(() => () => {}),
- delivery: vi.fn((event: SessionInputDelivery) => { calls.push(`teams delivery ${event.deliveryId}`) }),
+ deliveries: {
+ settled: vi.fn((event: SessionInputDelivery) => { calls.push(`delivery settled ${event.deliveryId}`) }),
canWrite: vi.fn(() => true),
},
device: () => device,
@@ -82,24 +81,22 @@ const delivery = (deliveryId: string) => ({ deliveryId }) as unknown as SessionI
describe('the session input controller\'s dependencies', () => {
afterEach(() => vi.restoreAllMocks())
- it('scopes a prompt, finds a session and checks its pane through what it was given', async () => {
+ it('finds a session and checks its pane through what it was given', async () => {
const { deps: given } = deps()
const wired = sessionInputDeps(given, () => lock([]))
- wired.beforeSubmit!('a1', 'hello', 'tab', 'd1')
- expect(given.teams.prepare).toHaveBeenCalledWith('a1', 'hello', 'tab', 'd1')
expect(wired.getSession('s1')?.agentId).toBe('a1')
expect(wired.validateRuntime).toBe(given.terminal.validateTerminal)
expect(wired.capture).toBe(given.terminal.captureTerminal)
expect(await wired.beforeTeamWrite!(agents.get('a1')!)).toBeNull()
})
- it('tells the device of a delivery first, then the teams; the teams alone without a device', () => {
+ it('tells the device of a delivery first, then its caller; its caller alone without a device', () => {
const one = deps()
sessionInputDeps(one.deps, () => lock([])).onDelivery!(delivery('d1'))
- expect(one.calls).toEqual(['device delivery d1', 'teams delivery d1'])
+ expect(one.calls).toEqual(['device delivery d1', 'delivery settled d1'])
const two = deps({ device: () => undefined })
sessionInputDeps(two.deps, () => lock([])).onDelivery!(delivery('d2'))
- expect(two.calls).toEqual(['teams delivery d2'])
+ expect(two.calls).toEqual(['delivery settled d2'])
})
it('writes and keys through the device\'s pane lock', async () => {
@@ -286,7 +283,7 @@ describe('the session input controller\'s dependencies', () => {
run.setPane(null)
expect(await wired.injectTeam!('a1', 'hi', 'd1')).toEqual({ state: 'failed', dispatch: 'not_started', reason: 'team_waiting_unavailable' })
run.setPane(READY_PANE)
- vi.mocked(run.deps.teams.canWrite).mockReturnValueOnce(false)
+ vi.mocked(run.deps.deliveries.canWrite).mockReturnValueOnce(false)
expect(await wired.injectTeam!('a1', 'hi', 'd1')).toEqual({ state: 'failed', dispatch: 'not_started', reason: 'team_waiting_control' })
expect(await wired.injectTeam!('a1', 'hi', 'd1')).toBe(ok)
expect(run.calls.filter((call) => call.startsWith('submit'))).toEqual(['submit a1 hi'])
@@ -435,13 +432,13 @@ describe('createInput', () => {
const inputs = createInput(deps().deps)
const submit = vi.spyOn(inputs.input, 'submit').mockImplementation(() => {})
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
- inputs.submitAgent('s1', 'hello', 'd1', 'tab')
+ inputs.submitAgent('s1', 'hello', 'd1')
inputs.submitAgent('cc', '/loop fix it')
inputs.submitAgent('nobody', 'hi')
expect(submit.mock.calls).toEqual([
- ['a1', 'hello', 'd1', 'tab'],
- ['cc', 'fix it', undefined, undefined],
- ['nobody', 'hi', undefined, undefined],
+ ['a1', 'hello', 'd1'],
+ ['cc', 'fix it', undefined],
+ ['nobody', 'hi', undefined],
])
expect(log.mock.calls.flat().filter((line) => String(line).includes('slash-command adapted'))).toHaveLength(1)
})
@@ -450,24 +447,23 @@ describe('createInput', () => {
describe('message', () => {
afterEach(() => vi.restoreAllMocks())
- it('writes what a person typed into the agent the frame names, in the tab it names', () => {
+ it('writes what a person typed into the agent the frame names, and reads no tab an older window still names', () => {
const inputs = createInput(deps().deps)
const submit = vi.spyOn(inputs.input, 'submit').mockImplementation(() => {})
vi.spyOn(console, 'log').mockImplementation(() => {})
inputs.messageRequest({ content: 'hello', agentId: 's1', tabId: 'swarm-a' })
- expect(submit.mock.calls).toEqual([['a1', 'hello', undefined, 'swarm-a']])
+ expect(submit.mock.calls).toEqual([['a1', 'hello', undefined]])
})
- it('names the agent by agent id or session id, takes a tab only in a tab id\'s shape, and drops a frame with no text or no agent', () => {
+ it('names the agent by agent id or session id, and drops a frame with no text or no agent', () => {
const submit = vi.fn()
const message = createMessageRequest(submit)
message({ content: 'hi', agentId: 'a1', sessionId: 's1' })
message({ content: 'hi', sessionId: 's1' })
message({ content: 'in a tab', agentId: 'a1', tabId: 'swarm-a' })
- message({ content: 'not a tab', agentId: 'a1', tabId: '../../etc' })
message({ content: '', agentId: 'a1' })
message({ content: 'nobody to type into' })
- expect(submit.mock.calls).toEqual([['a1', 'hi'], ['s1', 'hi'], ['a1', 'in a tab', undefined, 'swarm-a'], ['a1', 'not a tab']])
+ expect(submit.mock.calls).toEqual([['a1', 'hi'], ['s1', 'hi'], ['a1', 'in a tab']])
})
})
@@ -483,9 +479,9 @@ describe('every route a message takes to a pane', () => {
['the phone, through the relay\'s message frame', 'a1', (inputs) => inputs.messageRequest({ sessionId: 's1', content: 'from the phone', tabId: 'tab-1' }),
(run) => expect(run.deps.clients.send).toHaveBeenCalledWith(expect.objectContaining({ type: 'error', agentId: 'a1', payload: { message: asking } }))],
['the orchestrator', 'a1', (inputs) => inputs.submitAgent('a1', 'from the orchestrator', 'orchestrator-1'),
- (run) => expect(run.deps.teams.delivery).toHaveBeenCalledWith(refused('orchestrator-1', 'permission_open'))],
- ['a team', 'a1', (inputs) => inputs.submitAgent('a1', 'from a team', 'team:1'),
- (run) => expect(run.deps.teams.delivery).toHaveBeenCalledWith(refused('team:1', 'team_waiting_user'))],
+ (run) => expect(run.deps.deliveries.settled).toHaveBeenCalledWith(refused('orchestrator-1', 'permission_open'))],
+ ['Agent Messages', 'a1', (inputs) => inputs.submitAgent('a1', 'from a teammate', 'team:1'),
+ (run) => expect(run.deps.deliveries.settled).toHaveBeenCalledWith(refused('team:1', 'team_waiting_user'))],
['the Device, to Claude Code', 'a1', (inputs) => inputs.deviceInput.submit('a1', 'from the device', 'device-1'),
(run) => expect(run.device.inputStatus).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'device-1', phase: 'waiting_for_user' }))],
['the Device, to an engine it queues for', 'cc', (inputs) => inputs.deviceInput.submit('cc', 'from the device', 'device-2'),
diff --git a/cli/src/core/input.ts b/cli/src/core/input.ts
index 62310c0a2..a4382d12f 100644
--- a/cli/src/core/input.ts
+++ b/cli/src/core/input.ts
@@ -1,11 +1,11 @@
/**
- * Input: everything the core writes into an agent's pane. Messages, team turns and keys go through one
+ * Input: everything the core writes into an agent's pane. Messages, delivered turns and keys go through one
* controller (`SessionInputController`, a per-pane queue while a turn is busy); the Harness device's own
* route (`AutonomousDeviceInput`) owns the pane writer lock, and every write from the controller takes it
* first (`legacyWrite`), so a person answering on a device and the core never interleave in one pane.
*
* Moved verbatim out of `runForeground` (the core boundary, step 5: docs/design/2026-10-03-harnessd.md);
- * what it reaches in the registry, the terminal, the teams and device features and the clients is passed
+ * what it reaches in the registry, the terminal, the deliveries and device features and the clients is passed
* in. The two controllers' dependencies are built by `sessionInputDeps` and `deviceInputDeps`, each given
* the other controller lazily: each one calls into the other.
*/
@@ -35,13 +35,11 @@ export interface InputDeps {
resolve: (id: string) => RegisteredSession | undefined
byAgent: (agentId: string) => RegisteredSession | undefined
terminal: Pick<TerminalControl, 'captureTerminal' | 'validateTerminal' | 'submitTerminalAction' | 'keyTerminalAction' | 'pinTerminalControl'>
- /** The teams and orchestrator features. */
- teams: {
- /** Before a paste: record where the prompt came from (the teams' prompt scopes, `ports.teams`). */
- prepare: (agentId: string, content: string, tabId?: string, deliveryId?: string) => () => void
- /** A delivery settled: the orchestrator hears of it, then the team. */
- delivery: (event: SessionInputDelivery) => void
- /** Whether a team delivery still holds control of its pane. */
+ /** The turns delivered under a caller's own id (core/deliveries.ts): the Wi-Fi device's, Agent Messages', the orchestrator's. */
+ deliveries: {
+ /** A delivery settled: its caller hears of it. */
+ settled: (event: SessionInputDelivery) => void
+ /** Whether Agent Messages still wants one of its typed (`team:`) deliveries written. */
canWrite: (deliveryId: string) => boolean
}
/** The Wi-Fi device's service, wherever it runs (core/wifi.ts). */
@@ -59,11 +57,11 @@ export interface InputDeps {
/**
* The one way a message reaches an agent's pane: a person's from the app or the phone (the relay hands
- * the phone's over as the same `message` frame), the orchestrator's, a team's, and the Device's alike.
+ * the phone's over as the same `message` frame), the orchestrator's, Agent Messages', and the Device's alike.
* The pane is read right before the paste, by the caller that holds the pane's write lock, and nothing
* is typed into a dialog, a menu or a view a message does not belong in (messageHold.ts): the reason
* comes back instead, with nothing written. `hold` adds a caller's own check of the same reading (a
- * team's, which waits for a draft too). The pane is read again once the text is in, right before its
+ * delivery from Agent Messages, which waits for a draft too). The pane is read again once the text is in, right before its
* Enter: a dialog opened in between (a long or multi-line paste waits up to 1.5 s for the engine to take
* it, mid-turn) keeps the Enter from being pressed, which would answer it, and the text waits in the
* composer, unsent (sessionInput.ts says so). A list of suggestions opened by the message itself is no
@@ -115,17 +113,16 @@ export function sessionInputDeps(
deps: InputDeps,
deviceInput: () => Pick<AutonomousDeviceInput, 'legacyWrite'>,
): SessionInputDeps {
- const { resolve, terminal, teams, device, clients, agentIdFor, commandcode, emit } = deps
+ const { resolve, terminal, deliveries, device, clients, agentIdFor, commandcode, emit } = deps
const { captureTerminal, validateTerminal, keyTerminalAction } = terminal
const writeMessage = messageWriter(deps)
return {
- beforeSubmit: (id, text, tabId, deliveryId) => teams.prepare(id, text, tabId, deliveryId),
readScreen: deps.readScreen,
submission: deps.submission,
getSession: (id) => resolve(id),
onDelivery: (event) => {
device()?.delivery(event)
- teams.delivery(event)
+ deliveries.settled(event)
},
beforeTeamWrite: async session => {
const capture = await captureTerminal(session.agentId)
@@ -135,11 +132,11 @@ export function sessionInputDeps(
validateRuntime: validateTerminal,
// Typed into the pane as it stands, a draft or a running turn included, under the pane's write lock.
inject: (id, text) => deviceInput().legacyWrite(id, () => writeMessage(id, text)),
- // A team's turn waits for a ready composer, and for its delivery to still hold the pane.
+ // An Agent Messages turn waits for a ready composer, and for its mailbox to still want it written.
injectTeam: (id, text, deliveryId) => deviceInput().legacyWrite(id, async () => {
if (!resolve(id)) return terminalActionNotStarted('team_waiting_unavailable')
return writeMessage(id, text, (session, screen) => (screen ? screen.teamHold : 'team_waiting_unavailable')
- ?? (teams.canWrite(deliveryId) ? null : 'team_waiting_control'))
+ ?? (deliveries.canWrite(deliveryId) ? null : 'team_waiting_control'))
}),
sendKey: (id, key) => deviceInput().legacyWrite(id, () => keyTerminalAction(id, key)),
capture: captureTerminal,
@@ -213,7 +210,7 @@ export function createInput(deps: InputDeps) {
releaseInput()
}
}
- const submitAgent = (id: string, content: string, deliveryId?: string, tabId?: string): void => {
+ const submitAgent = (id: string, content: string, deliveryId?: string): void => {
const record = resolve(id)
const sessionId = record?.sessionId ?? id
const engine = record?.engine ?? 'claude'
@@ -226,31 +223,27 @@ export function createInput(deps: InputDeps) {
console.log(`[msg] ${sid(sessionId)} slash-command adapted for engine=${engine}`)
}
console.log(`[msg] ${sid(sessionId)} recv · engine=${engine} · bytes=${Buffer.byteLength(adapted, 'utf8')}`)
- input.submit(record?.agentId ?? sessionId, adapted, deliveryId, tabId)
+ input.submit(record?.agentId ?? sessionId, adapted, deliveryId)
}
const messageRequest = createMessageRequest(submitAgent)
return { input, deviceInput, acquireTerminalControl, submitAgent, messageRequest }
}
/**
- * Takes a `message` frame: text a person typed for an agent, into its pane, in the tab's scope when the
- * frame names one. Nothing is answered: the transcript lines the text produces drive the turn back to
- * every window (mirror-all), with no synthetic events here.
+ * Takes a `message` frame: text a person typed for an agent, into its pane. Nothing is answered: the
+ * transcript lines the text produces drive the turn back to every window (mirror-all), with no synthetic
+ * events here. A `tabId` an older window still sends is not read.
*
* Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md).
*/
-/** A tab's id as Tab collaboration takes it (teams/model.ts `Id`): a message from a tab is in its swarm's scope. */
-const TAB_ID = /^[A-Za-z0-9_-]{1,128}$/
-
-export function createMessageRequest(submit: (id: string, content: string, deliveryId?: string, tabId?: string) => void) {
+export function createMessageRequest(submit: (id: string, content: string) => void) {
return (payload: Record<string, unknown>): void => {
const content = payload.content as string | undefined
const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)
if (!content || !target) return
// From the relay this is only reached sealed: text typed into an agent is never taken from the relay
// in the clear.
- if (typeof payload.tabId === 'string' && TAB_ID.test(payload.tabId)) submit(target, content, undefined, payload.tabId)
- else submit(target, content)
+ submit(target, content)
}
}
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 78b61df3d..f479e265e 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -157,7 +157,7 @@ import { createEngineHooks, installEngineHooks, installOpencodePluginBeforeSpawn
import { createCursorDiscovery } from './engines/cursorDiscovery.js'
import { createCursorTaskHooks, loadPendingCursorTasks } from './engines/cursorTasks.js'
import { databaseHistory, hermesDb } from './transcripts/databaseHistory.js'
-import { CONNECTORS_REQUESTS, MEMORY_REQUESTS, ROUTER_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type TeamsPort, type WindowFocus } from './api.js'
+import { CONNECTORS_REQUESTS, MEMORY_REQUESTS, ROUTER_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, MESSAGES_FALLBACKS, MESSAGES_REQUESTS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type WindowFocus } from './api.js'
import { createServiceHost, testFaults } from './serviceHost.js'
import { startStalls } from './stall.js'
import { createServiceLinks, type ServiceLinks } from './serviceLinks.js'
@@ -178,7 +178,7 @@ import { answerExperimentQuery, createForExperiment } from './experimentQueries.
import { createOrchestratorLink } from './orchestratorLink.js'
import { daemonCommand } from '../lib/daemonCommand.js'
import { KNOWN_SERVICES, masterRunsEngineRuntime, masterRunsLiveEngines, servicesTheMasterRuns } from '../harnessd/services.js'
-import { createTeamsLink, teamsOutOfProcess } from './teamsLink.js'
+import { createMessagesLink } from './messagesLink.js'
import { createDevicesLink } from './devicesLink.js'
import { CORE_EXIT_STOP, CORE_EXIT_UPDATE, PROBE_COMMAND } from '../harnessd/protocol.js'
import { localSocketPath, refuseServedDataFolder, type LocalSocketServer } from '../lib/localSocket.js'
@@ -739,7 +739,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
gridModelsChanged: () => { void backendRef?.pushGridModels() },
privateGridName: async () => backendRef?.gridName() ?? null,
machineName: () => backendRef?.machineName() ?? null,
- // An experiment's account-wide settings (Tab collaboration's tab channels), signed in by this core.
+ // An experiment's account-wide settings (Agent Messages' tabs), signed in by this core.
backend: (method, path, body) => proxyBackend(method, path, body),
onNotice: (listener) => experimentHooks.onNotice(listener),
dshInstallStatus: (status) => backendRef?.send({ type: 'dsh_install_status', payload: status }),
@@ -918,13 +918,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
backend.useWifi(wifiCore.fromGateway)
const gatewayOps = gateway.ops
daemonBoot.openRequests = () => backend.openRequests()
- const teams: TeamsPort = {
- prepare: (...args) => ports.teams?.prepare(...args) ?? (() => {}),
- started: (...args) => ports.teams?.started(...args),
- raw: (...args) => ports.teams?.raw(...args),
- forget: (agentId) => ports.teams?.forget(agentId),
- canWrite: (deliveryId) => ports.teams?.canWrite(deliveryId) ?? false,
- }
// This machine's viewers, served to a client over its connection by the viewers (core/viewerStreams.ts).
backend.viewerStreams = createViewerStreams(() => ports.viewers, (connId, type, payload) => backend.sendViewerFrame(connId, type, payload))
@@ -976,7 +969,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
return { kind: client.role === 'device' ? 'device' : 'web', name: label }
},
streamingAvailable: tmuxBackend != null,
- onScopedInput: (id, bytes, tabId, pasted) => teams.raw(id, bytes, tabId, pasted),
diagnostic: (event, fields) => console.log(`[terminal-stream] ${event}`, fields),
// The keystroke prewarm (grid-reads-without-waking issue 03): typing into a pane whose agent runs on
// a sleeping grid starts that grid while the person types. Here, in the daemon's own input path, so
@@ -1117,12 +1109,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
resolve: (id) => registry.resolve(id),
byAgent: (agentId) => registry.byAgent(agentId),
terminal: terminalControl,
- teams: {
- prepare: (id, text, tabId, deliveryId) => teams.prepare(id, text, tabId, deliveryId),
- delivery: (event) => {
- deliveries.settled(event)
- },
- canWrite: (deliveryId) => teams.canWrite(deliveryId),
+ deliveries: {
+ settled: (event) => deliveries.settled(event),
+ // Whether Agent Messages still wants one of its typed deliveries written (core/messagesLink.ts).
+ canWrite: (deliveryId) => ports.messages?.canWrite(deliveryId) ?? false,
},
device: () => wifiCore.feed,
clients: backend,
@@ -1233,13 +1223,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {
{ call: (type, payload, waitMs) => serviceLinks.call('viewers', type, payload, waitMs), buffered: () => serviceLinks.buffered('viewers') })
// How the core tells workspaces in their own process what to do, and answers them (core/workspacesLink.ts).
const workspacesLink = createWorkspacesLink(coreApi, (frame) => serviceLinks.notify('workspaces', frame), forgetAgentProject)
- // Tab collaboration and teams, an experiment: the prompt scopes and the teams beside them, both in its process
- // or both in this one (core/teamsLink.ts), which keeps the scopes' changes from the moment it is on.
- const teamsOut = teamsOutOfProcess(outOfProcess)
- const teamsLink = createTeamsLink({ notify: (frame) => serviceLinks.notify('teams', frame), off: true })
+ // Agent Messages in its own process: which of its deliveries may be written, as it last said (core/messagesLink.ts).
+ const messagesLink = createMessagesLink()
// An experiment asked for, and the account's notices for those that hear them (core/experiments.ts).
const experimentHooks = createExperimentHooks({ want: (service) => coreLink.want(service), notify: (service, frame) => serviceLinks.notify(service, frame),
- outOfProcess, experiments, onWant: { collaboration: () => teamsLink.on() } })
+ outOfProcess, experiments })
backend.onAccountNotice = (notice) => experimentHooks.notice(notice)
// What the Store in its own process tells the core: an install's progress, and that what is installed changed (core/storeLink.ts).
const storeLink = createStoreLink(coreApi, invalidateInstalledDsh, (type, payload) => serviceLinks.call('store', type, payload))
@@ -1287,7 +1275,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
: service === 'workspaces' ? workspacesLink.answer(query, payload)
: service === 'store' ? storeLink.answer(query, payload)
: service === 'models' ? modelsLink.answer(query, payload)
- : service === 'teams' || service === 'collaboration' ? teamsLink.answer(query, payload)
+ : service === 'messages' ? messagesLink.answer(query, payload)
: service === 'devices' ? devicesLink.answer(query, payload)
: service === 'wifi' ? wifiLink.answer(query, payload)
: service === 'handoff' ? answerConversationQuery(coreApi, query, payload, authority)
@@ -1310,7 +1298,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (service === 'search') { searchGeneration++; externalResumes?.wake() }
if (service === 'usage') usageLink.connected()
if (service === 'gateway') gatewayLink?.connected()
- if (service === 'teams') teamsLink.on()
if (service === 'devices') devicesLink.connected()
if (service === 'wifi') wifiCore.started(appVoiceFocus ?? null)
devicesWake.connected(service)
@@ -1338,8 +1325,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
})
serviceLinksRef = serviceLinks
// A request a service declared goes to it: in its own process, or in this one (core/serviceHost.ts).
- backend.serviceRouter = (type, payload, asker, reply) => (teamsOut && teamsLink.route(type, payload, asker, reply))
- || serviceLinks.route(type, payload, asker, reply) || serviceHost.route(type, payload, asker, reply)
+ backend.serviceRouter = (type, payload, asker, reply) => serviceLinks.route(type, payload, asker, reply) || serviceHost.route(type, payload, asker, reply)
// The connection that asked closed: the services abort what it asked, wherever they run.
backend.onConnectionClosed = (connId) => { serviceLinks.closeConnection(connId); serviceHost.closeConnection(connId) }
// Session search (services/search.ts): in this process, or in its own (services/searchProcess.ts),
@@ -1373,10 +1359,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (outOfProcess.has('sharing')) ports.sharing = createSharingLink({ call: (type, payload) => serviceLinks.call('sharing', type, payload), notify: (frame) => serviceLinks.notify('sharing', frame) })
else serviceHost.start('sharing', inline!.startSharing, coreApi, SHARING_FALLBACKS, SHARE_REQUESTS)
backend.observers = { receive: (connId, type, payload) => ports.sharing?.observer(connId, type, payload), closeAll: () => ports.sharing?.linkDown() }
- // Tab collaboration and teams (services/collaboration.ts): in their own process, or in this one behind the
- // service host's guard (a fault there costs no message its write), the prompt scopes the service's own.
- if (teamsOut) ports.teams = teamsLink.scopes
- else serviceHost.start('teams', inline!.startTeamsInCore, coreApi, TEAMS_FALLBACKS, TEAMS_REQUESTS)
+ // Agent Messages (services/messages.ts): in its own process once it is on, or in this one behind the service
+ // host's guard (a fault there costs no message its write).
+ if (outOfProcess.has('messages')) ports.messages = messagesLink.port
+ else serviceHost.start('messages', inline!.startMessagesInCore, coreApi, MESSAGES_FALLBACKS, MESSAGES_REQUESTS)
// The harnesses installed here, and installing, updating and removing one (services/store.ts): in this
// process, or beside the viewers in theirs (services/storeProcess.ts).
if (outOfProcess.has('store')) ports.store = storeLink.port
@@ -1477,7 +1463,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
search: sessionSearch,
turnStartedAt,
input,
- teams,
deviceInput,
submission: submissions,
device: () => wifiCore.feed,
@@ -1513,7 +1498,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
runtimeProfiles,
watcher,
stopHeartbeat,
- teams,
input,
deviceInput,
detachDsh,
@@ -1531,7 +1515,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// A terminal is never the dial's business, and `syncSession` forces that for it anyway.
announceSession: session => announceSession(session, { device: false }),
invalidateTerminalControl,
- forgetInput: agentId => { forgetRestartRevision(agentId); teams.forget(agentId); input.forget(agentId); deviceInput.forget(agentId) },
+ forgetInput: agentId => { forgetRestartRevision(agentId); input.forget(agentId); deviceInput.forget(agentId) },
detachDsh,
syncRecapPool,
warn: (message, error) => console.warn(message, error),
@@ -1551,7 +1535,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
announceSession,
stoppedAgents,
syncRecapPool,
- teams,
input,
deviceInput,
homes: { copilot: env.COPILOT_HOME, grok: env.GROK_HOME, agy: env.AGY_HOME },
@@ -1571,7 +1554,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
syncRecapPool,
attachSession,
invalidateTerminalControl,
- teams,
input,
deviceInput,
questionWatcher,
@@ -1745,7 +1727,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
onAdmissionStop: attach.holdAdmissionStop,
captureAdmissionStop: attach.captureAdmissionStop,
onRegistered: handleRegistered,
- onPromptSubmitted: (id, text) => teams.started(id, text, 'hook', registry.byAgent(id)?.engine),
onSessionEnd: engineHooks.onSessionEnd,
// What the engines' own hooks say about a turn (core/turns/turnHooks.ts).
onTurnStart: turnHooks.onTurnStart,
@@ -2470,10 +2451,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
backend.forkProvider = launches.fork
const submitAgent = inputs.submitAgent
- backend.onMessage = (id, content, deliveryId, tabId) => submitAgent(id, content, deliveryId, tabId)
+ backend.onMessage = (id, content, deliveryId) => submitAgent(id, content, deliveryId)
backend.messageProvider = inputs.messageRequest
backend.onCancelOrchestratorMessage = id => input.cancelDelivery(id)
- deliveries.ready() // The input is wired: what was delivered meanwhile (a teams' queue resuming) is written now.
+ deliveries.ready() // The input is wired: what was delivered meanwhile (Agent Messages' queue resuming) is written now.
// Keep the log file under its cap. This daemon writes it through an inherited stdout fd, so a size
// check on a timer is the only place that can see it grow — `prepareLogFile` at spawn time alone
diff --git a/cli/src/core/messagesLink.spec.ts b/cli/src/core/messagesLink.spec.ts
new file mode 100644
index 000000000..67965bd02
--- /dev/null
+++ b/cli/src/core/messagesLink.spec.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest'
+import { createMessagesLink } from './messagesLink.js'
+
+describe('Agent Messages in its own process, as the core keeps it', () => {
+ it('says a delivery may be written only while the process last said so, and not past when it said', () => {
+ let clock = 1_000
+ const link = createMessagesLink(() => clock)
+ expect(link.port.canWrite('team:d1')).toBe(false)
+ expect(link.answer('writable', { deliveries: { 'team:d1': 1_000 + 3_000, 'team:d2': 'soon' } })).toEqual({})
+ expect(link.port.canWrite('team:d1')).toBe(true)
+ expect(link.port.canWrite('team:d2')).toBe(false)
+ clock += 3_000
+ expect(link.port.canWrite('team:d1')).toBe(false)
+ link.answer('writable', { deliveries: { 'team:d1': 99_999 } })
+ expect(link.port.canWrite('team:d1')).toBe(true)
+ // A report replaces the last whole.
+ link.answer('writable', {})
+ expect(link.port.canWrite('team:d1')).toBe(false)
+ })
+
+ it('answers no other question, and reads the real clock by default', () => {
+ const link = createMessagesLink()
+ expect(link.answer('agents', {})).toEqual({ error: 'UNKNOWN_QUERY' })
+ link.answer('writable', { deliveries: { 'team:d1': Date.now() + 60_000 } })
+ expect(link.port.canWrite('team:d1')).toBe(true)
+ })
+})
diff --git a/cli/src/core/messagesLink.ts b/cli/src/core/messagesLink.ts
new file mode 100644
index 000000000..f60ed935c
--- /dev/null
+++ b/cli/src/core/messagesLink.ts
@@ -0,0 +1,27 @@
+/**
+ * Agent Messages in its own process, as the core sees it (`HARNESSD_SERVICES=messages`; the process's side is
+ * services/messagesProcess.ts): which of its typed deliveries may be written now.
+ *
+ * The core asks in line, as it writes a `team:` delivery into an idle agent's pane (core/input.ts), and never
+ * calls into the process or waits on it for that. The process tells the core instead (`writable`): each
+ * delivery it still wants written, until a deadline a few seconds off, told again while it may. A process that
+ * stops telling, hung or gone, leaves none writable, and a delivery waits rather than being written against
+ * its mailbox's word.
+ */
+import type { MessagesPort } from './api.js'
+
+export function createMessagesLink(now: () => number = Date.now) {
+ /** Each delivery the process says may be written now, and until when. */
+ let writable = new Map<string, number>()
+ const port: MessagesPort = { canWrite: (deliveryId) => (writable.get(deliveryId) ?? 0) > now() }
+ return {
+ port,
+ /** The core's answers to the process's questions (core/serviceLinks.ts `answer`, for `messages`). */
+ answer(query: string, payload: Record<string, unknown>): Record<string, unknown> {
+ if (query !== 'writable') return { error: 'UNKNOWN_QUERY' }
+ const reported = payload.deliveries && typeof payload.deliveries === 'object' ? payload.deliveries as Record<string, unknown> : {}
+ writable = new Map(Object.entries(reported).flatMap(([id, until]) => (typeof until === 'number' ? [[id, until] as const] : [])))
+ return {}
+ },
+ }
+}
diff --git a/cli/src/core/teamsLink.spec.ts b/cli/src/core/teamsLink.spec.ts
deleted file mode 100644
index 7daf20219..000000000
--- a/cli/src/core/teamsLink.spec.ts
+++ /dev/null
@@ -1,257 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import type { TeamsEvent } from './api.js'
-import { createTeamsLink, KEPT_BYTES, KEPT_EVENTS, teamsOutOfProcess } from './teamsLink.js'
-
-const TEAM_A = 'a'.repeat(32)
-const TEAM_B = 'b'.repeat(32)
-
-function setup(over: Partial<Parameters<typeof createTeamsLink>[0]> = {}) {
- const sent: TeamsEvent[] = []
- let connected = true
- const lines: string[] = []
- let clock = 1_000
- const link = createTeamsLink({
- notify: vi.fn((frame) => { if (connected) sent.push((frame.payload as { event: TeamsEvent }).event); return connected }),
- now: () => clock,
- newId: () => 'core-1',
- log: (line) => lines.push(line),
- ...over,
- })
- return {
- link, scopes: link.scopes, sent, lines,
- down: () => { connected = false },
- up: () => { connected = true },
- tick: (ms: number) => { clock += ms },
- hello: (payload: Record<string, unknown>) => link.answer('hello', payload) as { core: string; reset: boolean; base: number; events: TeamsEvent[] },
- ack: (applied: number, scopes: Record<string, string | null> = {}, core = 'core-1') => link.answer('ack', { core, applied, scopes }),
- }
-}
-
-describe('the teams\' prompt scopes in their own process, as the core keeps them', () => {
- afterEach(() => vi.restoreAllMocks())
-
- it('a write gets its undo at once, never a fault, whether or not the process is there', () => {
- const { scopes, sent, down, hello } = setup()
- down()
- const undo = scopes.prepare('agent-1', 'hello team', 'tab-1', 'team:delivery')
- expect(typeof undo).toBe('function')
- undo()
- expect(sent).toEqual([])
- // Kept for the process all the same: the write and its undo, in order.
- expect(hello({ core: null }).events).toEqual([
- { kind: 'prepare', agentId: 'agent-1', text: 'hello team', tabId: 'tab-1', deliveryId: 'team:delivery', seq: 1, core: 'core-1', at: 1_000 },
- { kind: 'unprepare', agentId: 'agent-1', of: 1, seq: 2, core: 'core-1', at: 1_000 },
- ])
- })
-
- it('tells the process every change, numbered in order and stamped with when it happened', () => {
- const { scopes, sent, tick } = setup()
- scopes.started('agent-1', 'hello team', 'hook', 'claude')
- tick(5)
- scopes.started('agent-1', 'from the transcript')
- scopes.raw('agent-1', new Uint8Array([104, 105, 13]), 'tab-1')
- scopes.raw('agent-1', new TextEncoder().encode('pasted'), 'tab-1', true)
- scopes.replied('agent-1', TEAM_A, TEAM_B)
- scopes.forget('agent-1')
- expect(sent.map(({ seq, kind, at }) => [seq, kind, at])).toEqual([
- [1, 'started', 1_000], [2, 'started', 1_005], [3, 'raw', 1_005], [4, 'raw', 1_005], [5, 'replied', 1_005], [6, 'forget', 1_005],
- ])
- expect(sent[0]).toMatchObject({ text: 'hello team', source: 'hook', engine: 'claude' })
- expect(sent[1]).toMatchObject({ source: 'transcript' })
- expect(sent[2]).toMatchObject({ bytes: Buffer.from('hi\r').toString('base64'), tabId: 'tab-1', pasted: false })
- expect(sent[3]).toMatchObject({ bytes: Buffer.from('pasted').toString('base64'), pasted: true })
- expect(sent[4]).toMatchObject({ teamId: TEAM_A, questionId: TEAM_B })
- })
-
- it('answers an agent\'s team as the process reported it, and none while a change to it is on its way', () => {
- const { scopes, ack } = setup()
- expect(scopes.current('agent-1')).toBeNull()
- scopes.prepare('agent-1', 'hello team', 'tab-1')
- scopes.started('agent-1', 'hello team', 'hook')
- // Not yet applied by the process: no team rather than a stale one.
- expect(scopes.current('agent-1')).toBeNull()
- expect(ack(2, { 'agent-1': TEAM_A })).toEqual({ kept: true })
- expect(scopes.current('agent-1')).toBe(TEAM_A)
- // Writes and keys move no team: the answer stands.
- scopes.prepare('agent-1', 'next', 'tab-2')
- scopes.raw('agent-1', new Uint8Array([97]))
- expect(scopes.current('agent-1')).toBe(TEAM_A)
- scopes.started('agent-1', 'next', 'hook')
- expect(scopes.current('agent-1')).toBeNull()
- // A report from before that start is not the agent's team now.
- ack(4, { 'agent-1': TEAM_A })
- expect(scopes.current('agent-1')).toBeNull()
- ack(5, { 'agent-1': TEAM_B })
- expect(scopes.current('agent-1')).toBe(TEAM_B)
- })
-
- it('forgets an agent the process reports with no team', () => {
- const { scopes, ack } = setup()
- scopes.started('agent-1', 'hello', 'hook')
- ack(1, { 'agent-1': TEAM_A })
- scopes.forget('agent-1')
- ack(2, { 'agent-1': null })
- expect(scopes.current('agent-1')).toBeNull()
- })
-
- it('takes the report for an agent that was only written to: whatever team it had stands', () => {
- const { scopes, ack } = setup()
- scopes.prepare('agent-2', 'a message', 'tab-1')
- ack(1, { 'agent-2': TEAM_A })
- expect(scopes.current('agent-2')).toBe(TEAM_A)
- })
-
- it('ignores what another core\'s process acknowledges, and acknowledgements that say nothing', () => {
- const { link, scopes, ack } = setup()
- scopes.started('agent-1', 'hello', 'hook')
- expect(ack(1, { 'agent-1': TEAM_A }, 'core-0')).toEqual({ kept: false })
- expect(link.answer('ack', { core: 'core-1' })).toEqual({ kept: false })
- expect(scopes.current('agent-1')).toBeNull()
- expect(link.answer('ack', { core: 'core-1', applied: 1, scopes: 'nothing' })).toEqual({ kept: true })
- expect(scopes.current('agent-1')).toBeNull()
- })
-
- it('gives a process that reconnects exactly the events it lacks', () => {
- const { scopes, hello, ack, down, up } = setup()
- scopes.prepare('agent-1', 'one', 'tab-1')
- scopes.started('agent-1', 'one', 'hook')
- ack(1)
- down()
- scopes.prepare('agent-1', 'two', 'tab-1')
- up()
- // It applied the second event before its connection dropped, without saying so yet.
- const answer = hello({ core: 'core-1', applied: 2 })
- expect(answer).toMatchObject({ core: 'core-1', reset: false, base: 2 })
- expect(answer.events.map((event) => event.seq)).toEqual([3])
- })
-
- it('starts a new process over, with everything this side still holds', () => {
- const { scopes, hello, ack } = setup()
- scopes.started('agent-1', 'one', 'hook')
- ack(1, { 'agent-1': TEAM_A })
- scopes.prepare('agent-2', 'two', 'tab-1')
- expect(scopes.current('agent-1')).toBe(TEAM_A)
- const answer = hello({ core: null, applied: 0 })
- expect(answer).toMatchObject({ reset: true, base: 1 })
- expect(answer.events.map((event) => event.seq)).toEqual([2])
- // What the old process knew went with it: no team, not the one it had.
- expect(scopes.current('agent-1')).toBeNull()
- // With nothing held, it starts after the last event this core numbered.
- ack(2)
- expect(hello({ core: 'core-0', applied: 7 })).toEqual({ core: 'core-1', reset: true, base: 2, events: [] })
- })
-
- it('starts over a process that claims more than this core said, or missed events this side could not keep', () => {
- const { scopes, hello, lines, down, ack } = setup({ keptEvents: 3 })
- scopes.started('agent-1', 'one', 'hook')
- expect(hello({ core: 'core-1', applied: 5 })).toMatchObject({ reset: true, base: 0 })
- ack(1)
- down()
- for (let n = 0; n < 5; n++) scopes.raw('agent-1', new Uint8Array([97 + n]))
- expect(lines).toEqual(['[teams] kept 3 events or 16777216 bytes for the teams process; it will start over when it is back'])
- const answer = hello({ core: 'core-1', applied: 1 })
- expect(answer).toMatchObject({ reset: true, base: 3 })
- expect(answer.events.map((event) => event.seq)).toEqual([4, 5, 6])
- // Said once an outage: the next one says it again.
- for (let n = 0; n < 4; n++) scopes.raw('agent-1', new Uint8Array([97]))
- expect(lines).toHaveLength(2)
- })
-
- it('keeps events by size as well as by number, and lets go of what the process has', () => {
- const { scopes, hello, ack, down } = setup({ keptBytes: 2_000 })
- down()
- scopes.prepare('agent-1', 'x'.repeat(1_500), 'tab-1')
- scopes.prepare('agent-1', 'y'.repeat(1_500), 'tab-1')
- expect(hello({ core: null }).events.map((event) => event.seq)).toEqual([2])
- ack(2)
- expect(hello({ core: 'core-1', applied: 2 })).toMatchObject({ reset: false, events: [] })
- })
-
- it('keeps nothing for a process no one asked for, and everything from the moment teams is on', () => {
- const { link, scopes, sent, hello } = setup({ off: true })
- const undo = scopes.prepare('agent-1', 'typed while teams was off', 'tab-1')
- undo()
- scopes.started('agent-1', 'typed while teams was off', 'hook')
- expect(sent).toEqual([])
- expect(hello({ core: null }).events).toEqual([])
- link.on()
- scopes.forget('agent-1')
- expect(sent.map((event) => [event.seq, event.kind])).toEqual([[1, 'forget']])
- })
-
- it('says a team\'s delivery may be written only while the process last said so, and not past when it said', () => {
- const { link, scopes, tick } = setup()
- expect(scopes.canWrite('team:d1')).toBe(false)
- expect(link.answer('writable', { deliveries: { 'team:d1': 1_000 + 3_000, 'team:d2': 'soon' } })).toEqual({})
- expect(scopes.canWrite('team:d1')).toBe(true)
- expect(scopes.canWrite('team:d2')).toBe(false)
- tick(3_000)
- expect(scopes.canWrite('team:d1')).toBe(false)
- link.answer('writable', { deliveries: { 'team:d1': 99_999 } })
- expect(scopes.canWrite('team:d1')).toBe(true)
- // A report replaces the last whole.
- link.answer('writable', {})
- expect(scopes.canWrite('team:d1')).toBe(false)
- })
-
- it('answers the scopes\' own questions, from the apps and from the teams beside them, as it did while they were away', () => {
- const { link, scopes, ack, sent } = setup()
- scopes.prepare('agent-1', 'hello team', 'tab-1')
- scopes.started('agent-1', 'hello team', 'hook')
- ack(2, { 'agent-1': TEAM_A })
- const replies: Array<Record<string, unknown>> = []
- const owner = { owner: true }
- expect(link.route('team_delivery', { action: 'prompt_scope', agentId: 'agent-1' }, owner, (r) => replies.push(r))).toBe(true)
- expect(link.route('team_delivery', { action: 'prompt_replied', agentId: 'agent-1', teamId: TEAM_A, questionId: TEAM_B }, owner, (r) => replies.push(r))).toBe(true)
- expect(link.route('team_delivery', { action: 'prompt_scope', agentId: 'agent-1' }, { owner: false }, (r) => replies.push(r))).toBe(true)
- expect(link.route('team_delivery', { action: 'prompt_scope', agentId: '../x' }, owner, (r) => replies.push(r))).toBe(true)
- expect(link.route('team_delivery', { action: 'prompt_replied', agentId: 'agent-1', teamId: 'nope', questionId: TEAM_B }, owner, (r) => replies.push(r))).toBe(true)
- expect(link.route('team_delivery', { action: 'prompt_replied', agentId: 'agent-1', teamId: TEAM_A }, owner, (r) => replies.push(r))).toBe(true)
- expect(replies).toEqual([
- { teamId: TEAM_A },
- { ok: true },
- { error: 'OWNER_REQUIRED', detail: 'Team communication requires an owner connection.' },
- { error: 'INVALID_REQUEST', detail: 'agentId: Invalid' },
- { error: 'INVALID_REQUEST', detail: 'teamId: Invalid' },
- { error: 'INVALID_REQUEST', detail: 'questionId: Invalid' },
- ])
- expect(sent.at(-1)).toMatchObject({ kind: 'replied', teamId: TEAM_A, questionId: TEAM_B })
- // Every other request goes on to the teams.
- expect(link.route('team_delivery', { action: 'send' }, owner, (r) => replies.push(r))).toBe(false)
- expect(link.route('team', { action: 'prompt_scope' }, owner, (r) => replies.push(r))).toBe(false)
- // The same two, asked by the teams beside the scopes.
- expect(link.answer('team_scope', { agentId: 'agent-2' })).toEqual({ teamId: null })
- expect(link.answer('team_replied', { agentId: 'agent-1', teamId: TEAM_A, questionId: TEAM_B })).toEqual({ ok: true })
- })
-
- it('refuses a question it does not know', () => {
- expect(setup().link.answer('agents', {})).toEqual({ error: 'UNKNOWN_QUERY' })
- })
-
- it('numbers its events within a life of its own, on the clock, by default', () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- const events: TeamsEvent[] = []
- const link = createTeamsLink({ notify: (frame) => { events.push((frame.payload as { event: TeamsEvent }).event); return true }, keptEvents: 1 })
- link.scopes.forget('agent-1')
- link.scopes.forget('agent-2')
- expect(events[0].core).toMatch(/^[0-9a-f-]{36}$/)
- expect(Math.abs(events[0].at - Date.now())).toBeLessThan(5_000)
- expect(warn).toHaveBeenCalledWith(expect.stringContaining('[teams] kept 1 events'))
- expect(KEPT_EVENTS).toBe(10_000)
- expect(KEPT_BYTES).toBe(16 * 1024 * 1024)
- })
-
- it('runs the scopes and the teams beside them in one process or both in the core\'s, and says so when named apart', () => {
- const log = vi.fn()
- expect(teamsOutOfProcess(new Set(['search', 'teams', 'collaboration']), log)).toBe(true)
- expect(teamsOutOfProcess(new Set(['search']), log)).toBe(false)
- expect(log).not.toHaveBeenCalled()
- const apart = new Set(['search', 'collaboration'])
- expect(teamsOutOfProcess(apart, log)).toBe(false)
- expect([...apart]).toEqual(['search'])
- expect(log).toHaveBeenCalledWith(expect.stringContaining('one process or none'))
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- expect(teamsOutOfProcess(new Set(['teams']))).toBe(false)
- expect(warn).toHaveBeenCalledOnce()
- })
-})
diff --git a/cli/src/core/teamsLink.ts b/cli/src/core/teamsLink.ts
deleted file mode 100644
index 72363c98a..000000000
--- a/cli/src/core/teamsLink.ts
+++ /dev/null
@@ -1,192 +0,0 @@
-/**
- * The teams' prompt scopes in their own process, as the core sees them (`HARNESSD_SERVICES=teams`; the
- * process's side is services/teamsProcess.ts).
- *
- * A message's write needs one thing from the scopes at once: the undo that `prepare` returns, for a
- * write that fails. Here the core makes that itself, so a write never calls into the process or waits
- * on it, and nothing on this side can throw: teams can never cost a message its write (part 16).
- *
- * Every change (a message prepared or taken back, a prompt started, keys typed into a scoped terminal,
- * an agent forgotten, a question answered) is an event, numbered within this core's life and kept here
- * until the process says it has it. So none is lost to a process that is down, hung or restarting, and
- * the process applies each exactly once, in order:
- * - Each time it connects, it says which core it last heard from and the last event it applied
- * (`hello`). The answer is the events it lacks.
- * - Or the answer tells it to start over: when it is new, when this core is (after a restart, as the
- * scopes in the core's own process did), or when it missed events this side could no longer keep.
- * Starting over loses no event this side still holds; what the old state knew goes, and fails
- * closed.
- *
- * The socket's team features read an agent's scope back (`current`). The process reports each agent's
- * scope as it acknowledges events (`ack`), and the core answers from that report. While a change to an
- * agent's scope is on its way to the process, or after the process started over, the answer is null:
- * no team, never a wrong one. That is the fallback while the process is down, too.
- *
- * Teams is an experiment (core/api.ts `EXPERIMENTS`): its process runs only once it is on. Until then
- * (`off`), nothing is kept for it, and nothing it would read is said: the core keeps no journal for a process
- * no one asked for (`on`, once it is asked for or connects). The rest of what the core keeps of it:
- * - which of its deliveries may be written now (`canWrite`, asked in line as a team's turn is written,
- * core/input.ts), as the process last reported them (`writable`); none before, so a team's turn waits;
- * - the two `team_delivery` questions about the scopes themselves (`prompt_scope`, `prompt_replied`), which
- * the core answered while the scopes' process was down and still does (`route`), and the same two asked
- * by the process itself for its teams (`team_scope`, `team_replied`).
- */
-import { randomUUID } from 'node:crypto'
-import type { PromptScopes, TeamsEvent } from './api.js'
-import type { ServiceFrame } from './serviceLinks.js'
-
-/** The most events kept for a process that has not taken them, and their rough size: past either, the
- * oldest go, and the process starts over when it is back. Typing for half an hour fits. */
-export const KEPT_EVENTS = 10_000
-export const KEPT_BYTES = 16 * 1024 * 1024
-
-export interface TeamsLinkOptions {
- /** Tell the teams' process something (core/serviceLinks.ts `notify`, for `teams`). */
- notify(frame: ServiceFrame): boolean
- now?: () => number
- newId?: () => string
- log?: (line: string) => void
- keptEvents?: number
- keptBytes?: number
- /** Teams is not on yet: nothing is kept for its process until `on`. */
- off?: boolean
-}
-
-type Change = TeamsEvent extends infer E ? E extends TeamsEvent ? Omit<E, 'seq' | 'core' | 'at'> : never : never
-
-export function createTeamsLink(options: TeamsLinkOptions) {
- const now = options.now ?? Date.now
- const log = options.log ?? ((line: string) => console.warn(line))
- const keptEvents = options.keptEvents ?? KEPT_EVENTS
- const keptBytes = options.keptBytes ?? KEPT_BYTES
- /** This core's life: a process that heard another core's events starts over. */
- const core = (options.newId ?? randomUUID)()
- let seq = 0
- /** The last event the process said it applied. */
- let acked = 0
- /** Every event the process has not acknowledged, oldest first, and their rough size. */
- const journal: Array<{ event: TeamsEvent; size: number }> = []
- let journalBytes = 0
- let dropping = false
- /** Each agent's team as the process last reported it; only those with one. */
- const reported = new Map<string, string>()
- /** The last event that could move an agent's team: until the process has it, the team is unknown. */
- const moved = new Map<string, number>()
- /** Whether teams is on: its process asked for, or connected. */
- let active = options.off !== true
- /** Each delivery the process says may be written now, and until when. */
- let writable = new Map<string, number>()
-
- const record = (change: Change, movesScope: boolean): number => {
- if (!active) return 0
- const event = { ...change, seq: ++seq, core, at: now() } as TeamsEvent
- const size = 256 + ('text' in event ? event.text.length : 0) + ('bytes' in event ? event.bytes.length : 0)
- journal.push({ event, size })
- journalBytes += size
- while (journal.length > keptEvents || journalBytes > keptBytes) {
- journalBytes -= journal.shift()!.size
- if (!dropping) log(`[teams] kept ${keptEvents} events or ${keptBytes} bytes for the teams process; it will start over when it is back`)
- dropping = true
- }
- if (movesScope) moved.set(change.agentId, event.seq)
- options.notify({ type: 'service_event', payload: { kind: 'event', event } })
- return event.seq
- }
-
- const scopes: PromptScopes & { canWrite(deliveryId: string): boolean } = {
- prepare: (agentId, text, tabId, deliveryId) => {
- const of = record({ kind: 'prepare', agentId, text, tabId, deliveryId }, false)
- return () => { if (of) record({ kind: 'unprepare', agentId, of }, false) }
- },
- started: (agentId, text, source = 'transcript', engine) => { record({ kind: 'started', agentId, text, source, engine }, true) },
- raw: (agentId, bytes, tabId, pasted = false) => {
- record({ kind: 'raw', agentId, bytes: Buffer.from(bytes).toString('base64'), tabId, pasted }, false)
- },
- forget: (agentId) => { record({ kind: 'forget', agentId }, true) },
- replied: (agentId, teamId, questionId) => { record({ kind: 'replied', agentId, teamId, questionId }, true) },
- current: (agentId) => ((moved.get(agentId) ?? 0) > acked ? null : reported.get(agentId) ?? null),
- canWrite: (deliveryId) => (writable.get(deliveryId) ?? 0) > now(),
- }
-
- const agentOf = (value: unknown): string | null => (typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value) ? value : null)
- const operationOf = (value: unknown): string | null => (typeof value === 'string' && /^[a-f0-9]{32}$/.test(value) ? value : null)
- /** A scope's own question, answered here: `{ teamId }` for `prompt_scope`, the reply taken for `prompt_replied`. */
- const scopeAnswer = (action: unknown, payload: Record<string, unknown>): Record<string, unknown> => {
- const agentId = agentOf(payload.agentId)
- if (!agentId) return { error: 'INVALID_REQUEST', detail: 'agentId: Invalid' }
- if (action === 'prompt_scope') return { teamId: scopes.current(agentId) }
- const teamId = operationOf(payload.teamId), questionId = operationOf(payload.questionId)
- if (!teamId || !questionId) return { error: 'INVALID_REQUEST', detail: `${teamId ? 'questionId' : 'teamId'}: Invalid` }
- scopes.replied(agentId, teamId, questionId)
- return { ok: true }
- }
-
- /** The process connected: the events it lacks, or everything this side holds and a fresh start. */
- const hello = (payload: Record<string, unknown>): Record<string, unknown> => {
- const theirs = payload.core === core && typeof payload.applied === 'number' ? payload.applied : null
- const first = journal[0]?.event.seq
- const reset = theirs === null || theirs > seq || (first !== undefined && first > theirs + 1)
- if (reset) reported.clear()
- dropping = false
- const base = reset ? (first ?? seq + 1) - 1 : theirs
- return { core, reset, base, events: journal.filter((entry) => entry.event.seq > base).map((entry) => entry.event) }
- }
-
- /** The process applied every event up to `applied`, and says where each agent it touched stands. */
- const ack = (payload: Record<string, unknown>): Record<string, unknown> => {
- if (payload.core !== core || typeof payload.applied !== 'number') return { kept: false }
- const applied = payload.applied
- acked = Math.max(acked, applied)
- while (journal.length && journal[0].event.seq <= acked) journalBytes -= journal.shift()!.size
- const teams = payload.scopes && typeof payload.scopes === 'object' ? payload.scopes as Record<string, unknown> : {}
- for (const [agentId, teamId] of Object.entries(teams)) {
- // A report older than the agent's last move is not its team: the newer one is on its way.
- if ((moved.get(agentId) ?? 0) > applied) continue
- if (typeof teamId === 'string') reported.set(agentId, teamId)
- else { reported.delete(agentId); moved.delete(agentId) }
- }
- return { kept: true }
- }
-
- return {
- scopes,
- /** Teams is on: keep everything for its process from now on. */
- on(): void { active = true },
- /** The core's answers to the teams' questions (core/serviceLinks.ts `answer`, for `teams`). */
- answer(query: string, payload: Record<string, unknown>): Record<string, unknown> {
- if (query === 'hello') return hello(payload)
- if (query === 'ack') return ack(payload)
- if (query === 'team_scope') return scopeAnswer('prompt_scope', payload)
- if (query === 'team_replied') return scopeAnswer('prompt_replied', payload)
- if (query === 'writable') {
- const reported = payload.deliveries && typeof payload.deliveries === 'object' ? payload.deliveries as Record<string, unknown> : {}
- writable = new Map(Object.entries(reported).flatMap(([id, until]) => (typeof until === 'number' ? [[id, until] as const] : [])))
- return {}
- }
- return { error: 'UNKNOWN_QUERY' }
- },
- /** A `team_delivery` question about the scopes themselves, answered here as it was while the scopes'
- * process was down: false for every other request, which goes to the teams' process. */
- route(type: string, payload: Record<string, unknown>, asker: { owner: boolean }, reply: (result: Record<string, unknown>) => void): boolean {
- if (type !== 'team_delivery' || (payload.action !== 'prompt_scope' && payload.action !== 'prompt_replied')) return false
- reply(asker.owner ? scopeAnswer(payload.action, payload) : { error: 'OWNER_REQUIRED', detail: 'Team communication requires an owner connection.' })
- return true
- },
- }
-}
-
-export type TeamsLink = ReturnType<typeof createTeamsLink>
-
-/**
- * Whether Tab collaboration runs in its own process: the prompt scopes (`teams`) and the teams beside them
- * (`collaboration`) both, or both in the core's. Named apart (`HARNESSD_SERVICES=collaboration`), they would
- * be two mailboxes on one folder: both run in the core's process then, and it says so.
- */
-export function teamsOutOfProcess(outOfProcess: Set<string>, log: (line: string) => void = (line) => console.warn(line)): boolean {
- if (outOfProcess.has('teams') !== outOfProcess.has('collaboration')) {
- log('[services] the prompt scopes and the teams run in one process or none: both run in this one')
- outOfProcess.delete('teams')
- outOfProcess.delete('collaboration')
- }
- return outOfProcess.has('teams')
-}
diff --git a/cli/src/core/turns/funnel.spec.ts b/cli/src/core/turns/funnel.spec.ts
index 1707ea51b..2573cce0e 100644
--- a/cli/src/core/turns/funnel.spec.ts
+++ b/cli/src/core/turns/funnel.spec.ts
@@ -27,7 +27,6 @@ function setup(engine = 'claude', over: Partial<FunnelDeps> = {}) {
search: { touch: vi.fn(log('search')) },
turnStartedAt: new Map(),
input: { onTurnStarted: vi.fn(log('input started')), onTurnEnded: vi.fn(log('input ended')) },
- teams: { started: vi.fn(log('teams started')) },
deviceInput: { onTurnStarted: vi.fn(log('deviceInput started')), onTurnEnded: vi.fn(log('deviceInput ended')) },
submission: inlineSubmission,
device: () => ({ turnStarted: vi.fn(log('device started')), turnEnded: vi.fn(log('device ended')), stream: vi.fn(log('device stream')) }),
@@ -42,12 +41,11 @@ function setup(engine = 'claude', over: Partial<FunnelDeps> = {}) {
describe('the event funnel', () => {
afterEach(() => vi.restoreAllMocks())
- it('carries on past a teams or device service that throws: every consumer after it still gets the event', () => {
+ it('carries on past a device service that throws: every consumer after it still gets the event', () => {
vi.spyOn(console, 'log').mockImplementation(() => {})
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
const boom = (what: string) => vi.fn(() => { throw new Error(`${what} unplugged`) })
const { funnel, calls } = setup('claude', {
- teams: { started: boom('teams') },
device: () => ({ turnStarted: boom('device'), turnEnded: boom('device'), stream: boom('device') }),
})
funnel('s1', [started(), text(), ended()])
@@ -60,7 +58,7 @@ describe('the event funnel', () => {
'mirror',
])
// Once a minute per consumer: the devices failed three times and said so once.
- expect(error.mock.calls.map(([line]) => line)).toEqual(['[funnel] teams failed · teams unplugged', '[funnel] devices failed · device unplugged'])
+ expect(error.mock.calls.map(([line]) => line)).toEqual(['[funnel] devices failed · device unplugged'])
})
@@ -70,7 +68,7 @@ describe('the event funnel', () => {
funnel('s1', [started(), text(), ended()])
expect(calls).toEqual([
'send turn_started', 'search',
- 'input started', 'teams started', 'deviceInput started', 'device started', 'heartbeat', 'questions start', 'questions pre-turn',
+ 'input started', 'deviceInput started', 'device started', 'heartbeat', 'questions start', 'questions pre-turn',
'send text_delta',
'send turn_ended', 'search',
'device ended', 'deviceInput ended', 'input ended', 'questions stop',
@@ -82,7 +80,7 @@ describe('the event funnel', () => {
vi.spyOn(console, 'log').mockImplementation(() => {})
const { funnel, calls, deps } = setup()
funnel('s1', [started()], { resumed: true })
- // Not a turn starting now: the teams do not count it, and a dialog already up belongs to it.
+ // Not a turn starting now: a dialog already up belongs to it.
expect(calls).toEqual([
'send turn_started', 'search',
'input started', 'deviceInput started', 'device started', 'heartbeat', 'questions start',
@@ -94,11 +92,10 @@ describe('the event funnel', () => {
expect(vi.mocked(deps.mirror.ingest).mock.calls[0][2]).toEqual({ replay: true })
})
- it('re-reads a transcript as history: no team count, and nothing streamed to the device', () => {
+ it('re-reads a transcript as history: nothing streamed to the device', () => {
vi.spyOn(console, 'log').mockImplementation(() => {})
const { funnel, calls, deps } = setup()
funnel('s1', [started(), ended()], { replay: true })
- expect(calls).not.toContain('teams started')
expect(calls).not.toContain('device stream')
expect(calls).toContain('questions pre-turn')
const end = vi.mocked(deps.clients.send).mock.calls[1][0] as Record<string, any>
@@ -168,7 +165,7 @@ describe('the event funnel', () => {
const { funnel, calls } = setup('claude', { search: null, device: () => undefined })
funnel('s1', [started(), ended()])
expect(calls).toEqual([
- 'send turn_started', 'input started', 'teams started', 'deviceInput started', 'heartbeat', 'questions start', 'questions pre-turn',
+ 'send turn_started', 'input started', 'deviceInput started', 'heartbeat', 'questions start', 'questions pre-turn',
'send turn_ended', 'deviceInput ended', 'input ended', 'questions stop',
'mirror',
])
@@ -220,12 +217,12 @@ describe('a consumer outside the core', () => {
outside('devices', () => { throw new Error('serial port gone') })
at += 10_000
outside('devices', () => { throw 'still gone' })
- outside('teams', () => { ran.push('teams') })
+ outside('recaps', () => { ran.push('recaps') })
at += 60_000
outside('devices', () => { throw 'back and gone again' })
at += 60_001
outside('devices', () => { throw new Error('once more') })
- expect(ran).toEqual(['teams'])
+ expect(ran).toEqual(['recaps'])
expect(lines).toEqual([
'[funnel] devices failed · serial port gone',
'[funnel] devices failed · back and gone again · 1 more since',
@@ -235,8 +232,8 @@ describe('a consumer outside the core', () => {
it('reports to the error log by default', () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
- outsideConsumers()('teams', () => { throw new Error('x') })
- expect(error).toHaveBeenCalledWith('[funnel] teams failed · x')
+ outsideConsumers()('devices', () => { throw new Error('x') })
+ expect(error).toHaveBeenCalledWith('[funnel] devices failed · x')
error.mockRestore()
})
diff --git a/cli/src/core/turns/funnel.ts b/cli/src/core/turns/funnel.ts
index c78e69b65..7e460aab5 100644
--- a/cli/src/core/turns/funnel.ts
+++ b/cli/src/core/turns/funnel.ts
@@ -1,6 +1,6 @@
/**
* The event funnel: the one place a session's live events fan out from, to the app, search, input, the
- * teams, the device's input, the device service, the heartbeat, the question watcher and the recaps. The
+ * device's input, the device service, the heartbeat, the question watcher and the recaps. The
* order is exact and it matters: per event, the frame goes to the app before anything acts on it; the
* recaps hear the whole batch after the loop; the device stream comes last and never on a replay.
*
@@ -23,7 +23,6 @@ import type { QuestionWatcher } from '../../lib/questionController.js'
import type { RegisteredSession } from '../../lib/registry.js'
import type { SessionInputController } from '../../lib/sessionInput.js'
import type { TurnActivity } from '../../lib/turnActivity.js'
-import type { SwarmPromptScopes } from '../../teams/promptScope.js'
type Events = ReturnType<CursorNormalizer['ingest']>
type EmitOptions = { resumed?: boolean; replay?: boolean }
@@ -47,7 +46,6 @@ export interface FunnelDeps {
search: { touch(sessionId: string): void } | null | undefined
turnStartedAt: Map<string, number>
input: Pick<SessionInputController, 'onTurnStarted' | 'onTurnEnded'>
- teams: Pick<SwarmPromptScopes, 'started'>
deviceInput: Pick<AutonomousDeviceInput, 'onTurnStarted' | 'onTurnEnded'>
/** Which engines take a message typed mid-turn into their own queue (their declared submission policy). */
submission: Pick<SubmissionReader, 'policy'>
@@ -62,7 +60,7 @@ export interface FunnelDeps {
type OutsideConsumers = (consumer: string, call: () => void) => void
/**
- * A consumer outside the core — the teams and the device service — answers for itself: one that
+ * A consumer outside the core — the device service — answers for itself: one that
* throws is logged, at most once a minute per consumer and with how many were not, and every consumer
* after it still gets the event. The heartbeat, the question watcher and the recaps must not miss a
* turn because a device was unplugged mid-call. The services on the boundary are guarded the same way
@@ -96,7 +94,7 @@ export function outsideConsumers(options: {
/** The funnel itself, over what it feeds. */
export function funnelFor({
- bySession, tokenUsage, agentIdFor, turnActivity, isSubagentSession, clients, search, turnStartedAt, input, teams,
+ bySession, tokenUsage, agentIdFor, turnActivity, isSubagentSession, clients, search, turnStartedAt, input,
deviceInput, submission, device, startHeartbeat, questionWatcher, mirror, outside = outsideConsumers(),
}: FunnelDeps) {
return (sessionId: string, events: Events, opts?: EmitOptions): void => {
@@ -134,7 +132,6 @@ export function funnelFor({
turnStartedAt.set(sessionId, Date.now())
console.log(`[turn] ${sid(sessionId)} started · engine=${bySession(sessionId)?.engine ?? 'claude'} · bytes=${Buffer.byteLength(event.payload.userMessage, 'utf8')}`)
input.onTurnStarted(agentIdFor(sessionId), event.payload.userMessage)
- if (!opts?.resumed && !opts?.replay) outside('teams', () => teams.started(agentId, event.payload.userMessage, 'transcript', bySession(sessionId)?.engine))
deviceInput.onTurnStarted(agentId, event.payload.userMessage)
outside('devices', () => device()?.turnStarted(agentId))
startHeartbeat(sessionId)
diff --git a/cli/src/engines/kit/storePool.spec.ts b/cli/src/engines/kit/storePool.spec.ts
index b6b95e2a6..725db181f 100644
--- a/cli/src/engines/kit/storePool.spec.ts
+++ b/cli/src/engines/kit/storePool.spec.ts
@@ -418,7 +418,7 @@ async function stopFixture() {
forgetAttach: vi.fn(), turnStartedAt: new Map(), neverFoldedHistory: new Set(), replayedFirstTurn: new Set(),
clearAgyIdleWatch: vi.fn(), cursorDiscovery: { remove: vi.fn() }, cursorSubagents: { forget: vi.fn() },
runtimeProfiles: { forget: vi.fn() }, watcher: { removeSession: vi.fn(async () => {}) },
- stopHeartbeat: vi.fn(), teams: { forget: vi.fn() }, input: { forget: vi.fn() }, deviceInput: { forget: vi.fn() },
+ stopHeartbeat: vi.fn(), input: { forget: vi.fn() }, deviceInput: { forget: vi.fn() },
detachDsh: vi.fn(), mirror: { forget: vi.fn() }, clients: { send: vi.fn(), sendCommander: vi.fn() },
dataDir: process.env.ADAPTER_DATA_DIR!,
})
diff --git a/cli/src/engines/otherIdentity.golden.spec.ts b/cli/src/engines/otherIdentity.golden.spec.ts
index 962475c8e..87dc1da5a 100644
--- a/cli/src/engines/otherIdentity.golden.spec.ts
+++ b/cli/src/engines/otherIdentity.golden.spec.ts
@@ -236,7 +236,7 @@ describe('where the core finds the other engines\' conversations', () => {
} as never,
mirror: { inheritSummary: () => {} }, forgetSession: () => {}, clients: { send: () => {} }, attachSession: async () => true,
announceSession: () => {}, stoppedAgents: { save: () => {}, finishResume: () => {}, get: () => null } as never, syncRecapPool: () => {},
- teams: { forget: () => {} } as never, input: { forget: () => {} } as never, deviceInput: { forget: () => {} } as never,
+ input: { forget: () => {} } as never, deviceInput: { forget: () => {} } as never,
homes: { copilot: home('.copilot'), grok: home('.grok'), agy: home('.gemini', 'antigravity-cli') },
})
const observed = (engine: string, over: Record<string, unknown>) => ({
diff --git a/cli/src/harnessd/processName.spec.ts b/cli/src/harnessd/processName.spec.ts
index bb9941c7b..5e6ed37aa 100644
--- a/cli/src/harnessd/processName.spec.ts
+++ b/cli/src/harnessd/processName.spec.ts
@@ -73,7 +73,7 @@ describe('namedNode', () => {
expect(namedNode(node, 'harnessd-core', runtime, { fs: crossDevice.fs, platform: 'darwin', log })).toBe(node)
expect(namedNode(node, 'harnessd-core', runtime, { fs: crossDevice.fs, platform: 'darwin', log })).toBe(node)
const readOnly = memFs({ [node]: { dev: 1, ino: 7 } }, { mkdir: 'EROFS' as unknown as Error })
- expect(namedNode(node, 'harnessd-teams', runtime, { fs: readOnly.fs, platform: 'darwin' })).toBe(node)
+ expect(namedNode(node, 'harnessd-messages', runtime, { fs: readOnly.fs, platform: 'darwin' })).toBe(node)
expect(log.mock.calls.map(([line]) => line)).toEqual([
'[harnessd] harnessd runs as node (no node binary)',
'[harnessd] harnessd-core runs as node (EXDEV)',
diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.ts
index 830e2d09a..7199c722c 100644
--- a/cli/src/harnessd/services.spec.ts
+++ b/cli/src/harnessd/services.spec.ts
@@ -314,7 +314,7 @@ describe('ServiceSupervisor', () => {
})
it('starts an experiment\'s process only once the core asks for one of its services, and keeps it like any other', () => {
- const experiment: ServiceSpec = { name: 'experiments', services: ['orchestrator', 'teams'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true }
+ const experiment: ServiceSpec = { name: 'experiments', services: ['orchestrator', 'messages'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true }
const supervisor = make([search, experiment])
supervisor.start()
expect(children.map((child) => child.spec.name)).toEqual(['search'])
@@ -322,12 +322,12 @@ describe('ServiceSupervisor', () => {
supervisor.want('search')
supervisor.want('nobody')
expect(children).toHaveLength(1)
- supervisor.want('teams')
+ supervisor.want('messages')
expect(latest('experiments').env.HARNESSD_SERVICE).toBe('experiments')
// Asked again, while it runs or after it crashed: the master's to restart, once.
supervisor.want('orchestrator')
latest('experiments').exit(1)
- supervisor.want('teams')
+ supervisor.want('messages')
expect(children.filter((child) => child.spec.name === 'experiments')).toHaveLength(1)
vi.advanceTimersByTime(1_000)
expect(children.filter((child) => child.spec.name === 'experiments')).toHaveLength(2)
@@ -337,7 +337,7 @@ describe('ServiceSupervisor', () => {
it('starts every process on demand a core too old to ask for it would never ask for, and stops one never started at once', () => {
const experiment: ServiceSpec = { name: 'orchestrator', services: ['orchestrator'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true }
const devices: ServiceSpec = { name: 'devices', services: ['devices', 'wifi'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true, askedSince: 4 }
- const idle: ServiceSpec = { ...experiment, name: 'teams', services: ['teams'] }
+ const idle: ServiceSpec = { ...experiment, name: 'messages', services: ['messages'] }
// A core of protocol 3 asks for the experiments, not for the devices: theirs starts as it binds.
const three = make([search, experiment, devices])
three.start()
@@ -361,10 +361,10 @@ describe('ServiceSupervisor', () => {
never.start()
expect(never.status()[0].state).toBe('off')
never.unasked(2)
- expect(children.map((child) => child.spec.name)).toEqual(['orchestrator', 'devices', 'teams'])
+ expect(children.map((child) => child.spec.name)).toEqual(['orchestrator', 'devices', 'messages'])
// One running then is stopped and started with the others, and waits to be asked for again.
never.stop(vi.fn())
- latest('teams').exit(0)
+ latest('messages').exit(0)
never.start()
expect(never.status()[0].state).toBe('off')
})
@@ -467,7 +467,7 @@ describe('ServiceSupervisor', () => {
})
describe('which services the core leaves to its master', () => {
- const known = ['search', 'viewers', 'workspaces', 'teams']
+ const known = ['search', 'viewers', 'workspaces', 'messages']
const supervised = { HARNESSD_SUPERVISED: '1', HARNESSD_SERVICE_TOKEN: 'token' }
it('is what the master says it runs, told in a form a core from before the list reads too', () => {
@@ -484,7 +484,7 @@ describe('which services the core leaves to its master', () => {
expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(specs, 42) }, known)]).toEqual(['search', 'workspaces'])
expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv([], 42) }, known)]).toEqual([])
// What the master says wins over whatever HARNESSD_SERVICES the core inherited; names it does not know are its own.
- expect([...servicesTheMasterRuns({ ...supervised, [SERVICE_PROCESSES_ENV]: ' teams, nothing ', HARNESSD_SERVICES: 'search' }, known)]).toEqual(['teams'])
+ expect([...servicesTheMasterRuns({ ...supervised, [SERVICE_PROCESSES_ENV]: ' messages, nothing ', HARNESSD_SERVICES: 'search' }, known)]).toEqual(['messages'])
})
it('under a master too old to say, is what HARNESSD_SERVICES names, and nothing when it names none: never every service', () => {
diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.ts
index 53ea0cfca..0c3859dff 100644
--- a/cli/src/harnessd/services.ts
+++ b/cli/src/harnessd/services.ts
@@ -393,10 +393,9 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {
// The router (services/routerProcess.ts), an experiment: started at its first request. A few decisions in
// flight, each one bounded Jev answer.
router: { services: ['router'], heapLimitMiB: 128, rssLimitMiB: 384, onDemand: true },
- // Tab collaboration and teams, an experiment: the prompt scopes, a few drafts and fingerprints per agent, and
- // beside them the teams, their mailbox and the tab channels (services/collaborationProcess.ts), each on its
- // own link to the core. Started only once it is on (core/api.ts `EXPERIMENTS`).
- teams: { services: ['teams', 'collaboration'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true },
+ // Agent Messages (services/messagesProcess.ts), an experiment: its mailbox, history and the account's tabs
+ // with Agent Messages on. Started only once it is on (core/api.ts `EXPERIMENTS`).
+ messages: { services: ['messages'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true },
// Share, an experiment (services/sharingProcess.ts): its invitations, its observers' sessions and their
// ciphers; the headless Chrome it captures a shared viewer in is a process of its own, outside this budget.
sharing: { services: ['sharing'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true },
@@ -498,7 +497,7 @@ export function masterRunsEngineRuntime(env: NodeJS.ProcessEnv, parentPid: numbe
* run itself: what the master says it runs (`serviceProcessesEnv`), never what this build would choose.
* A master too old to say runs exactly the services `HARNESSD_SERVICES` names, as every master did; a
* core that worked it out from its own default instead took every service for out of process under a
- * released master that ran none, and answered search, the viewers, workspaces and the teams
+ * released master that ran none, and answered search, the viewers, workspaces and the experiments
* SERVICE_UNAVAILABLE until the master restarted (e2e/releaseRehearsal.e2e.ts). None without a master.
*/
export function servicesTheMasterRuns(env: NodeJS.ProcessEnv, known: readonly string[]): Set<string> {
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index 0c0adf040..ba0055755 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -166,7 +166,7 @@ export interface HookServerHandlers {
* local write, so CSRF-guarded like a rename. */
onDeskOps?: (body: unknown) => Promise<PairOutcome>
/** GET /api/agent-messages — which tabs have Agent Messages on (docs/design/2026-10-10-agent-messages.md),
- * proxied like the desk: the window draws each tab's ⇄ from it without starting the experiment's process. */
+ * proxied like the desk: the window draws each tab's chat icon from it without starting the experiment's process. */
onAgentMessagesRead?: () => Promise<PairOutcome>
/** PATCH /api/agent-messages/tabs/:tabId — turn Agent Messages on or off for one tab; a local write, so
* CSRF-guarded like the desk's ops. */
diff --git a/cli/src/lib/controlTranscript.spec.ts b/cli/src/lib/controlTranscript.spec.ts
index 184bf4642..078500844 100644
--- a/cli/src/lib/controlTranscript.spec.ts
+++ b/cli/src/lib/controlTranscript.spec.ts
@@ -286,7 +286,7 @@ it('preserves a repaired parent through Stop and the final real forget archive',
forgetAttach: vi.fn(), turnStartedAt: new Map(), neverFoldedHistory: new Set(), replayedFirstTurn: new Set(),
clearAgyIdleWatch: vi.fn(), cursorDiscovery: { remove: vi.fn() }, cursorSubagents: { forget: vi.fn() },
runtimeProfiles: { forget: vi.fn() }, watcher: { removeSession: vi.fn(async () => {}) },
- stopHeartbeat: vi.fn(), teams: { forget: vi.fn() }, input: { forget: vi.fn() }, deviceInput: { forget: vi.fn() },
+ stopHeartbeat: vi.fn(), input: { forget: vi.fn() }, deviceInput: { forget: vi.fn() },
detachDsh: vi.fn(), mirror: { forget: vi.fn() }, clients: { send: vi.fn(), sendCommander: vi.fn() },
dataDir: join(root, 'ADAPTER_DATA_DIR') })
const stop = createStopAgentService({ registry, stoppedAgents: stopped, restartJobs: new AgentRestartCoordinator(),
diff --git a/cli/src/lib/sessionInput.spec.ts b/cli/src/lib/sessionInput.spec.ts
index a6528eefb..a4de43935 100644
--- a/cli/src/lib/sessionInput.spec.ts
+++ b/cli/src/lib/sessionInput.spec.ts
@@ -84,14 +84,13 @@ describe('SessionInputController', () => {
it('typed but its Enter withheld, as something opened: never pressed later, and the person told where the text is', async () => {
const withheld: TerminalActionResult = { state: 'unknown', dispatch: 'possibly_executed', reason: 'enter_withheld:permission_open' }
- const onError = vi.fn(), onSubmitted = vi.fn(), sendKey = vi.fn(async () => true), forget = vi.fn(), onDelivery = vi.fn()
+ const onError = vi.fn(), onSubmitted = vi.fn(), sendKey = vi.fn(async () => true), onDelivery = vi.fn()
vi.useFakeTimers()
const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session('claude'), validateRuntime: async () => true,
- inject: async () => withheld, sendKey, onError, onSubmitted, onDelivery, beforeSubmit: () => forget, beforeTeamWrite: async () => null })
+ inject: async () => withheld, sendKey, onError, onSubmitted, onDelivery, beforeTeamWrite: async () => null })
controller.submit('s1', 'a message from the app')
await vi.advanceTimersByTimeAsync(30_000)
expect(onError).toHaveBeenCalledWith('s1', 'Claude Code asked for permission just as your message was typed, so it was not sent; it waits in Claude Code\'s prompt. Answer the request in the app or in its terminal, then press Enter in its terminal to send the message, or clear it there.')
- expect(forget).toHaveBeenCalled()
expect(onSubmitted).not.toHaveBeenCalled()
expect(sendKey).not.toHaveBeenCalled()
// With a receipt: refused with the reason; a team's, without telling a person.
@@ -205,18 +204,6 @@ describe('SessionInputController', () => {
})
- it('retains the submitted swarm through the input queue and records it only at dispatch', async () => {
- const beforeSubmit = vi.fn(() => vi.fn())
- const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session('cursor'), validateRuntime: async () => true,
- inject: async () => true, sendKey: async () => true, beforeSubmit, onError: vi.fn() })
- controller.setTurnOpen('s1', true)
- controller.submit('s1', 'task from A', undefined, 'swarm-a')
- expect(beforeSubmit).not.toHaveBeenCalled()
- controller.onTurnEnded('s1')
- await vi.waitFor(() => expect(beforeSubmit).toHaveBeenCalledWith('h1', 'task from A', 'swarm-a'))
- controller.forget('s1')
- })
-
it.each(['team_waiting_draft', 'team_waiting_user', 'team_waiting_idle'])('team input preserves the composer on %s', async reason => {
const inject = vi.fn(async () => true), sendKey = vi.fn(async () => true), onDelivery = vi.fn()
const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session('cursor'), validateRuntime: async () => true,
diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.ts
index 7884efcd3..7a24a3053 100644
--- a/cli/src/lib/sessionInput.ts
+++ b/cli/src/lib/sessionInput.ts
@@ -72,7 +72,6 @@ export interface SessionInputDelivery {
}
interface QueuedInput {
- tabId?: string
deliveryId?: string
content: string
bytes: number
@@ -109,8 +108,6 @@ export interface SessionInputDeps {
/** A team-only preflight at the actual write boundary. A reason proves no paste occurred. */
beforeTeamWrite?: (session: RegisteredSession) => Promise<string | null>
onDelivery?: (event: SessionInputDelivery) => void
- /** Record origin at the actual write boundary, after all queue/preflight checks. */
- beforeSubmit?: (agentId: string, content: string, tabId?: string, deliveryId?: string) => (() => void)
getSession: (sessionId: string) => RegisteredSession | undefined
validateRuntime: (session: RegisteredSession) => Promise<boolean>
/** Boolean is retained for direct controller tests and legacy embedders. Production returns dispatch evidence. */
@@ -260,7 +257,7 @@ export class SessionInputController {
return false
}
- submit(sessionId: string, content: string, deliveryId?: string, tabId?: string): void {
+ submit(sessionId: string, content: string, deliveryId?: string): void {
const session = this.controlSession(sessionId)
if (!session) {
this.delivery(sessionId, deliveryId, 'rejected', 'agent_gone')
@@ -273,7 +270,7 @@ export class SessionInputController {
|| (deliveryId && (state.deliveryId || state.dispatching || state.turnOpen || state.awaitingFingerprint || state.settling))
|| (!this.typesWhileBusy(session.engine) && (state.turnOpen || state.awaitingFingerprint || state.settling))) {
console.log(`[inject] ${sid(sessionId)} queued · engine=${session.engine} · depth=${state.queue.length + 1}`)
- this.enqueue(sessionId, state, content, deliveryId, tabId)
+ this.enqueue(sessionId, state, content, deliveryId)
return
}
this.delivery(sessionId, deliveryId, 'queued')
@@ -285,7 +282,7 @@ export class SessionInputController {
// agent as it is by then, which a restart in between may have changed.
// With nothing in flight the write starts at once, so a cancel or a control request that follows
// the submit sees it, as before.
- const write = (): Promise<void> => this.inject(sessionId, this.controlSession(sessionId) ?? session, content, deliveryId, tabId)
+ const write = (): Promise<void> => this.inject(sessionId, this.controlSession(sessionId) ?? session, content, deliveryId)
const running = state.writes ? state.writes.then(write, write) : write()
const settled: Promise<void> = running.catch(() => {}).then(() => { if (state.writes === settled) state.writes = undefined })
state.writes = settled
@@ -477,7 +474,7 @@ export class SessionInputController {
}
/** Preserve the established injection path for every caller that opts out of receipts. */
- private async injectLegacy(sessionId: string, session: RegisteredSession, content: string, tabId?: string): Promise<void> {
+ private async injectLegacy(sessionId: string, session: RegisteredSession, content: string): Promise<void> {
const state = this.state(sessionId)
if (!(await this.deps.validateRuntime(session))) {
console.warn(`[inject] ${sid(sessionId)} abort · engine=${session.engine} · process not running`)
@@ -501,7 +498,6 @@ export class SessionInputController {
// would corrupt it into a run-on prompt anyway, which is worse and harder to notice.
await this.deps.sendKey(session.agentId, 'C-u')
}
- const forgetScope = this.deps.beforeSubmit?.(session.agentId, content, tabId)
const delivery = await this.injectWhenLeased(() => this.deps.inject(session.agentId, content),
() => this.controlSession(session.agentId) !== undefined)
const accepted = typeof delivery === 'boolean'
@@ -510,13 +506,11 @@ export class SessionInputController {
const withheld = enterWithheldReason(delivery)
if (withheld) {
// Typed, its Enter not pressed: never pressed later either, which would send it into whatever is open.
- forgetScope?.()
console.warn(`[inject] ${sid(sessionId)} typed, not sent · engine=${session.engine} · ${withheld} opened before Enter`)
this.deps.onError(sessionId, messageWithheldText(session.engine, withheld))
return
}
if (!accepted) {
- forgetScope?.()
const held = heldBack(delivery)
if (held) {
console.warn(`[inject] ${sid(sessionId)} not typed · engine=${session.engine} · ${held}`)
@@ -537,13 +531,13 @@ export class SessionInputController {
this.armSubmitCheck(sessionId, session, state)
}
- private async inject(sessionId: string, session: RegisteredSession, content: string, deliveryId?: string, tabId?: string): Promise<void> {
+ private async inject(sessionId: string, session: RegisteredSession, content: string, deliveryId?: string): Promise<void> {
const state = this.state(sessionId)
if (!deliveryId) {
// A local submission keeps its original scheduling. Overlap removes our ability
// to attribute a later terminal turn to the lamp; it must not block local input.
this.finishDelivery(sessionId, state, 'unknown', 'prompt_mismatch')
- return this.injectLegacy(sessionId, session, content, tabId)
+ return this.injectLegacy(sessionId, session, content)
}
state.deliveryId = deliveryId
state.deliveryFingerprint = undefined
@@ -581,12 +575,10 @@ export class SessionInputController {
}
if (state.cancelled || this.states.get(sessionId) !== state) return
state.writing = true
- const forgetScope = this.deps.beforeSubmit?.(session.agentId, content, tabId, deliveryId)
const delivery = await this.injectWhenLeased(() => (deliveryId.startsWith('team:') && this.deps.injectTeam
? this.deps.injectTeam(session.agentId, content, deliveryId) : this.deps.inject(session.agentId, content)),
() => !state.cancelled && this.states.get(sessionId) === state)
state.writing = false
- if (delivery === false || (typeof delivery !== 'boolean' && delivery.dispatch === 'not_started')) forgetScope?.()
if (state.cancelled || this.states.get(sessionId) !== state) return
if (typeof delivery !== 'boolean' && delivery.state === 'failed' && delivery.dispatch === 'not_started' && delivery.reason.startsWith('team_waiting_')) {
this.finishDelivery(sessionId, state, 'rejected', delivery.reason)
@@ -595,7 +587,6 @@ export class SessionInputController {
const withheld = enterWithheldReason(delivery)
if (withheld) {
// Typed, its Enter not pressed: never pressed later either, which would send it into whatever is open.
- forgetScope?.()
console.warn(`[inject] ${sid(sessionId)} typed, not sent · engine=${session.engine} · ${withheld} opened before Enter`)
this.finishDelivery(sessionId, state, 'rejected', 'enter_withheld')
if (!deliveryId.startsWith('team:')) this.deps.onError(sessionId, messageWithheldText(session.engine, withheld))
@@ -605,7 +596,7 @@ export class SessionInputController {
if (held) {
console.warn(`[inject] ${sid(sessionId)} not typed · engine=${session.engine} · ${held}`)
this.finishDelivery(sessionId, state, 'rejected', held)
- // A team's turn is automatic, and its team hears of the refusal; anyone else's is a person's to see.
+ // An Agent Messages turn is automatic, and its mailbox hears of the refusal; anyone else's is a person's to see.
if (!deliveryId.startsWith('team:')) this.deps.onError(sessionId, messageHoldText(session.engine, held))
return
}
@@ -878,10 +869,10 @@ export class SessionInputController {
if (!next.deliveryId?.startsWith('team:')) this.deps.onError(sessionId, 'This harness is no longer available.')
return
}
- void this.inject(sessionId, session, next.content, next.deliveryId, next.tabId)
+ void this.inject(sessionId, session, next.content, next.deliveryId)
}
- private enqueue(sessionId: string, state: InputState, content: string, deliveryId?: string, tabId?: string): void {
+ private enqueue(sessionId: string, state: InputState, content: string, deliveryId?: string): void {
const bytes = Buffer.byteLength(content, 'utf8')
const queuedBytes = state.queue.reduce((sum, item) => sum + item.bytes, 0)
if (state.queue.length >= MAX_QUEUE_ITEMS || queuedBytes + bytes > MAX_QUEUE_BYTES) {
@@ -889,7 +880,7 @@ export class SessionInputController {
if (!deliveryId?.startsWith('team:')) this.deps.onError(sessionId, 'This agent already has too many queued messages. Try again after the current operation finishes.')
return
}
- state.queue.push({ content, bytes, expiresAt: Date.now() + ITEM_TTL_MS, deliveryId, tabId })
+ state.queue.push({ content, bytes, expiresAt: Date.now() + ITEM_TTL_MS, deliveryId })
this.delivery(sessionId, deliveryId, 'queued')
}
diff --git a/cli/src/lib/stopAgentService.spec.ts b/cli/src/lib/stopAgentService.spec.ts
index 80c7e3104..33e184f93 100644
--- a/cli/src/lib/stopAgentService.spec.ts
+++ b/cli/src/lib/stopAgentService.spec.ts
@@ -54,7 +54,7 @@ it.each(['forget', 'checkpoint'] as const)('retains a captured Pi resume path th
forgetAttach: vi.fn(), turnStartedAt: new Map(), neverFoldedHistory: new Set(), replayedFirstTurn: new Set(),
clearAgyIdleWatch: vi.fn(), cursorDiscovery: { remove: vi.fn() }, cursorSubagents: { forget: vi.fn() },
runtimeProfiles: { forget: vi.fn() }, watcher: { removeSession: vi.fn(async () => {}) },
- stopHeartbeat: vi.fn(), teams: { forget: vi.fn() }, input: { forget: vi.fn() }, deviceInput: { forget: vi.fn() },
+ stopHeartbeat: vi.fn(), input: { forget: vi.fn() }, deviceInput: { forget: vi.fn() },
detachDsh: vi.fn(), mirror: { forget: vi.fn() }, clients: { send: vi.fn(), sendCommander: vi.fn() },
dataDir: env.ADAPTER_DATA_DIR,
})
diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.ts
index 85e1b7588..627a33330 100644
--- a/cli/src/lib/terminalStreamManager.spec.ts
+++ b/cli/src/lib/terminalStreamManager.spec.ts
@@ -120,26 +120,16 @@ describe('TerminalStreamManager', () => {
expect((result.payload.engines as Array<{ id: string }>).map((row) => row.id)).toEqual([...ENGINES])
})
- it('records the origin only for accepted input from the owning stream, before writing bytes', async () => {
- const onScopedInput = vi.fn(() => expect(stream.writes).toHaveLength(0))
- await manager.stop()
- manager = newManager({ onScopedInput })
+ it('asks no window for the tab its input came from, and still writes input from an older one that names it', async () => {
await manager.handleFrame('web-1', 'terminal_open', {
requestId: 'scoped', protocolVersion: 3, agentId: 'agent-1', cols: 100, rows: 30,
})
const ready = sent.findLast(f => f.type === 'terminal_ready')!.payload
- expect(ready.swarmInput).toBe(true)
+ expect(ready).not.toHaveProperty('swarmInput')
const frame = { kind: TerminalBinaryKind.input, streamId: String(ready.streamId), seq: 0,
bytes: Buffer.from('hello\r'), compressed: false, tabId: 'swarm-a' }
- await manager.handleBinary('wrong-owner', frame)
- expect(onScopedInput).not.toHaveBeenCalled()
- await manager.handleBinary('web-1', { ...frame, seq: 2 })
- expect(onScopedInput).not.toHaveBeenCalled()
await manager.handleBinary('web-1', frame)
- expect(onScopedInput).toHaveBeenCalledWith('agent-1', frame.bytes, 'swarm-a', false)
expect(stream.writes).toEqual([frame.bytes])
- await manager.handleBinary('web-1', frame)
- expect(onScopedInput).toHaveBeenCalledOnce()
})
it('uses the same generic path for every current engine', async () => {
diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.ts
index 1775db305..c4e6a5d1a 100644
--- a/cli/src/lib/terminalStreamManager.ts
+++ b/cli/src/lib/terminalStreamManager.ts
@@ -174,7 +174,6 @@ export interface TerminalStreamManagerDeps {
* grid-reads-without-waking issue 03), which is why it lives here, below every client that types.
*/
onInput?: (agentId: string) => void
- onScopedInput?: (agentId: string, bytes: Uint8Array, tabId: string | undefined, pasted: boolean) => void
}
function sizeFrom(payload: FramePayload): TerminalStreamSize | null {
@@ -333,10 +332,10 @@ export class TerminalStreamManager {
return
}
if (frame.kind === TerminalBinaryKind.paste) {
- await this.paste(state, frame.bytes, frame.tabId)
+ await this.paste(state, frame.bytes)
return
}
- await this.input(state, frame.seq, frame.bytes, frame.tabId)
+ await this.input(state, frame.seq, frame.bytes)
}
private capabilities(connId: string, requestId: unknown): void {
@@ -347,7 +346,6 @@ export class TerminalStreamManager {
available: this.deps.streamingAvailable,
features: {
rawInput: !this.deps.readOnly,
- swarmInput: !this.deps.readOnly,
resize: !this.deps.readOnly,
mouse: !this.deps.readOnly,
keyframe: true,
@@ -579,7 +577,6 @@ export class TerminalStreamManager {
// True for a watcher too: the client draws output and withholds input, exactly as it does
// for an observer's stream. See the `takeover: false` branch above.
readOnly: this.deps.readOnly === true || watching,
- swarmInput: !this.deps.readOnly,
...(heldBy ? { heldBy } : {}),
})) {
await this.closeStream(state, 'backend disconnected', false)
@@ -626,7 +623,7 @@ export class TerminalStreamManager {
else if (state.outputPaused) this.armStallTimer(state)
}
- private async input(state: ActiveStream, inputSeq: number, bytes: Uint8Array, tabId?: string): Promise<void> {
+ private async input(state: ActiveStream, inputSeq: number, bytes: Uint8Array): Promise<void> {
if (!Number.isSafeInteger(inputSeq) || inputSeq !== state.lastInputSeq + 1 || bytes.length === 0 || bytes.length > INPUT_MAX_BYTES) {
// Nothing here reached the pty, and `lastInputSeq` is deliberately left where it was. Say what
// WOULD have been accepted: a client whose counter has drifted (a frame it dropped on its own
@@ -648,7 +645,6 @@ export class TerminalStreamManager {
state.lastInputSeq = inputSeq
state.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MS
this.tookInput(state)
- this.deps.onScopedInput?.(state.agentId, bytes, tabId, false)
// Not awaited. `writeRaw` hands its `send-keys` to the control client's FIFO synchronously, so
// keystroke order is already fixed by the time it returns its promise — and the seq above is
// spent, so the next frame cannot race this one. Awaiting the reply held the whole local
@@ -712,7 +708,7 @@ export class TerminalStreamManager {
* (TERMINAL_*_PASTE_MAX_*_BYTES in terminalBinary.ts) — anything over that never decodes into a
* frame at all, so there is nothing left to check here.
*/
- private async paste(state: ActiveStream, bytes: Uint8Array, tabId?: string): Promise<void> {
+ private async paste(state: ActiveStream, bytes: Uint8Array): Promise<void> {
if (bytes.length === 0) return
let text: string
try {
@@ -723,7 +719,6 @@ export class TerminalStreamManager {
}
state.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MS
this.tookInput(state)
- this.deps.onScopedInput?.(state.agentId, bytes, tabId, true)
const result = await state.handle.pasteRaw(text)
if (result.state !== 'succeeded') {
this.sendError(state.connId, 'TERMINAL_PASTE_FAILED', { streamId: state.streamId, message: result.reason })
diff --git a/cli/src/messages/command.ts b/cli/src/messages/command.ts
index 2d5af095c..6c348c7c2 100644
--- a/cli/src/messages/command.ts
+++ b/cli/src/messages/command.ts
@@ -23,7 +23,7 @@ export const SEND_USAGE = `harness send — message your teammates in this tab
harness send <name>[,<name>] "text" message one or more teammates
harness send <name> --text-file PATH a longer message, from a file
-Run it in your own harness pane. Agent Messages must be on in the tab (⇄ on the tab).
+Run it in your own harness pane. Agent Messages must be on in the tab (the chat icon on the tab).
Use --json for structured output.`
export interface SendArgs { names: string[]; text: string; json: boolean }
diff --git a/cli/src/messages/mailbox.ts b/cli/src/messages/mailbox.ts
index aca53da4e..f274cba75 100644
--- a/cli/src/messages/mailbox.ts
+++ b/cli/src/messages/mailbox.ts
@@ -58,7 +58,7 @@ export interface MailboxDeps {
text(delivery: LocalDelivery, message: Message): string
/** A delivery changed; the store is saved after. */
changed(status: DeliveryStatus, delivery: LocalDelivery): void
- /** Whether a typed attempt may be written changed: the teams' process tells the core. */
+ /** Whether a typed attempt may be written changed: its process tells the core (services/messagesProcess.ts). */
writable?(): void
now?(): number
}
diff --git a/cli/src/messages/rpc.ts b/cli/src/messages/rpc.ts
index ad3fc7535..b07da5b69 100644
--- a/cli/src/messages/rpc.ts
+++ b/cli/src/messages/rpc.ts
@@ -1,7 +1,7 @@
/**
* One `agent_messages` request to a machine's daemon, through this daemon's own local socket: to another of the
- * owner's machines the daemon carries it over the paired E2EE relay (localWsServer `machine_select`), as Swarm's
- * team requests went. `harness send` reaches its own daemon the same way.
+ * owner's machines the daemon carries it over the paired E2EE relay (localWsServer `machine_select`). `harness
+ * send` reaches its own daemon the same way.
*/
import { randomBytes } from 'node:crypto'
import { existsSync } from 'node:fs'
diff --git a/cli/src/messages/service.spec.ts b/cli/src/messages/service.spec.ts
index 2afd10eb7..12b03bd1f 100644
--- a/cli/src/messages/service.spec.ts
+++ b/cli/src/messages/service.spec.ts
@@ -225,7 +225,8 @@ describe('from the owner\'s other machines', () => {
t.deliveryEvent({ deliveryId: t.delivered.at(-1)![2], sessionId: 'api', state: 'rejected', reason: 'team_waiting_idle' })
}
expect(await t.ask({ action: 'deliver', message: { ...incoming(), id: 'mzzzzzzz' } }, OWNER_REMOTE)).toMatchObject({ error: 'MAILBOX_FULL' })
- })
+ // Five hundred deliveries, each saved to disk: about five seconds on a busy machine.
+ }, 30_000)
it('refuses a message for an agent outside the sender\'s tabs, and one that is not a message', async () => {
const t = setup()
diff --git a/cli/src/messages/service.ts b/cli/src/messages/service.ts
index dc6191c25..73022c960 100644
--- a/cli/src/messages/service.ts
+++ b/cli/src/messages/service.ts
@@ -1,7 +1,7 @@
/**
* Agent Messages (docs/design/2026-10-10-agent-messages.md): harnesses in a tab with Agent Messages on message
* each other with `harness send`. This is the whole service, on the core's API, in the core's process or in its
- * own (services/collaboration.ts, services/collaborationProcess.ts):
+ * own (services/messages.ts, services/messagesProcess.ts):
* - `send`: from `harness send` in an agent's pane, over this machine's socket. The pane names the sender.
* - `deliver`, `status`, `who`: from the owner's other machines, over the paired relay.
* - `history`: the windows' log of a tab.
@@ -250,7 +250,7 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
if (!await directory.refresh()) throw new MessageError('DIRECTORY_UNAVAILABLE', 'Harness could not read which tabs have Agent Messages on. Try again in a moment.')
const me = { machineId: self(), agentId: session.agentId }
const peers = directory.peers(me)
- if (!directory.tabsOf(me).length) throw new MessageError('MESSAGES_OFF', 'Agent Messages are off in this tab. The person turns them on with ⇄ on the tab.')
+ if (!directory.tabsOf(me).length) throw new MessageError('MESSAGES_OFF', 'Agent Messages are off in this tab. The person turns them on with the chat icon on the tab, or the tab\'s right-click menu.')
await learnNames(peers, true)
const mates = peers.map(teammate)
const names = (Array.isArray(payload.to) ? payload.to : typeof payload.to === 'string' ? payload.to.split(',') : [])
diff --git a/cli/src/messages/wire.ts b/cli/src/messages/wire.ts
index 5c42bcb05..3240d0877 100644
--- a/cli/src/messages/wire.ts
+++ b/cli/src/messages/wire.ts
@@ -1,6 +1,6 @@
/**
* Agent Messages' frames as the relay carries them between the owner's machines (lib/e2ee/applicationFrames.ts):
- * sealed both ways, as Swarm's team frames were. They carry what agents say to each other.
+ * sealed both ways. They carry what agents say to each other.
*/
export const AGENT_MESSAGES_REQUEST_TYPES: ReadonlySet<string> = new Set(['agent_messages'])
export const AGENT_MESSAGES_RESULT_TYPES: ReadonlySet<string> = new Set(['agent_messages_result'])
diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.ts
index 42036511b..17e5acdc4 100644
--- a/cli/src/serviceProcess.ts
+++ b/cli/src/serviceProcess.ts
@@ -42,8 +42,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M
['connectors', async () => (await import('./services/connectorsProcess.js')).runConnectorsService],
['recaps', async () => (await import('./services/recapsProcess.js')).runRecapsService],
['store', async () => (await import('./services/storeProcess.js')).runStoreService],
- ['teams', async () => (await import('./services/teamsProcess.js')).runTeamsService],
- ['collaboration', async () => (await import('./services/collaborationProcess.js')).runCollaborationService],
+ ['messages', async () => (await import('./services/messagesProcess.js')).runMessagesService],
['sharing', async () => (await import('./services/sharingProcess.js')).runSharingService],
['orchestrator', async () => (await import('./services/orchestratorProcess.js')).runOrchestratorService],
['memory', async () => (await import('./services/memoryProcess.js')).runMemoryService],
diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.md
index 84f9e0c43..a9f24f861 100644
--- a/cli/src/services/AGENTS.md
+++ b/cli/src/services/AGENTS.md
@@ -59,7 +59,7 @@ that process. A process per risk, not per feature (`SERVICE_HOSTS` in `src/harne
| `models` | models | grid's installs, downloads and commands | on demand |
| `devices` | devices, wifi | the dials' serial ports, the fleet's lane, the voice router's worker, the Wi-Fi device | on demand |
| `orchestrator` | orchestrator | an experiment | on demand |
-| `teams` | teams, collaboration | an experiment: Agent Messages (`collaboration`) beside the prompt scopes | on demand |
+| `messages` | messages | an experiment: Agent Messages | on demand |
| `sharing` | sharing | an experiment: Share | on demand |
| `memory` | memory | an experiment: Memories across machines | on demand |
| `router` | router | an experiment: where ⌘B sends a task, decided by Jev | on demand |
@@ -172,12 +172,6 @@ master too old to run it starts it beside itself, still in its own process (`src
what the core reads back in line it reads from what they last said of each session.
`e2e/recapsProcess.e2e.ts` proves turns end on time with them killed, hung or slow, and
`e2e/recapsCompat.e2e.ts` that the dial and the windows hear the same cards and recaps as before.
-- State built from every change must get every change exactly once. The teams show how
- (`src/services/teamsProcess.ts`, `src/core/teamsLink.ts`): the core numbers each change and keeps it
- until the process acknowledges it; on each connection the process says what it applied and gets
- what it lacks, or starts over. A value the core reads back synchronously is answered from what the
- process last reported, and is "unknown" (the fallback) while a change to it is on its way.
- `e2e/teamsProcess.e2e.ts` proves it.
## On demand
@@ -231,12 +225,10 @@ To add one:
it there when `HARNESSD_SERVICES` keeps it in (`serviceHost.serve`, or `start` with a port).
Removing one is deleting those. A port the core calls in line (the orchestrator's `roleOf`) is answered
-from what the process last reported (`src/core/orchestratorLink.ts`), as the viewers' are. Tab collaboration
-(`src/services/collaboration.ts`, beside the prompt scopes in the teams' process) shows the rest: whether a
-team's turn may still be written, which the core asks as it writes it, is reported for a few seconds at a
-time, so a process that stops reporting leaves none writable (`collaborationProcess.ts`, `core/teamsLink.ts`);
-a cancel its mailbox reads in line is asked of the core first (`takingBack`); and the core keeps nothing for
-the scopes until the experiment is on.
+from what the process last reported (`src/core/orchestratorLink.ts`), as the viewers' are. Agent Messages
+(`src/services/messages.ts`) shows the rest: whether one of its typed deliveries may still be written, which
+the core asks as it writes it, is reported for a few seconds at a time, so a process that stops reporting
+leaves none writable (`messagesProcess.ts`, `core/messagesLink.ts`).
## Do not
diff --git a/cli/src/services/collaboration.spec.ts b/cli/src/services/collaboration.spec.ts
deleted file mode 100644
index 1365781c8..000000000
--- a/cli/src/services/collaboration.spec.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { mkdtempSync, rmSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { emptyPorts, TEAMS_REQUESTS } from '../core/api.js'
-import { fakeCore } from '../testing/fakeCore.js'
-
-/**
- * Agent Messages in Swarm's slot: the service is messages/service.ts's to prove (messages/service.spec.ts); here,
- * that the slot starts it and keeps its contract with the core.
- */
-const made = vi.hoisted(() => ({ calls: [] as string[], options: [] as unknown[] }))
-vi.mock('../messages/service.js', () => ({
- startAgentMessages: (_core: unknown, options: unknown) => {
- made.options.push(options)
- return {
- requests: { agent_messages: async () => ({ ok: true }) },
- canWrite: (id: string) => id === 'team:msg:yes',
- start: () => made.calls.push('start'),
- stop: () => made.calls.push('stop'),
- }
- },
-}))
-
-import { startCollaboration, startTeamsInCore, TEAMS_REQUESTS as REEXPORTED } from './collaboration.js'
-
-describe('Agent Messages in the collaboration slot', () => {
- let dir: string
- beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'collab-')); made.calls.length = 0; made.options.length = 0 })
- afterEach(() => rmSync(dir, { recursive: true, force: true }))
-
- it('answers the one request the core routes to it', () => {
- expect(TEAMS_REQUESTS).toEqual(['agent_messages'])
- expect(REEXPORTED).toBe(TEAMS_REQUESTS)
- })
-
- it('starts Agent Messages with the options it was given', () => {
- const service = startCollaboration(fakeCore({ dataDir: dir }), { dataDir: dir })
- expect(made.options).toEqual([{ dataDir: dir }])
- expect(service.canWrite('team:msg:yes')).toBe(true)
- startCollaboration(fakeCore({ dataDir: dir }))
- expect(made.options.at(-1)).toEqual({})
- })
-
- it('in the core\'s process: starts at once, answers whether a delivery may be written, and records no scopes', async () => {
- const ports = emptyPorts()
- const requests = startTeamsInCore(fakeCore({ dataDir: dir }), ports)
- expect(made.calls).toEqual(['start'])
- expect(await requests.agent_messages!({ action: 'history' }, { local: true, owner: true })).toEqual({ ok: true })
- expect(ports.teams!.canWrite('team:msg:yes')).toBe(true)
- expect(ports.teams!.canWrite('team:msg:no')).toBe(false)
- // The core still records each prompt's scope here; nothing reads it now.
- const undo = ports.teams!.prepare('a1', 'text')
- undo()
- ports.teams!.started!('a1', 'text', 'hook')
- ports.teams!.raw!('a1', Buffer.from('x'))
- ports.teams!.forget!('a1')
- ;(ports.teams as unknown as { stop(): void }).stop()
- expect(made.calls).toEqual(['start', 'stop'])
- startTeamsInCore(fakeCore({ dataDir: dir }), emptyPorts(), { dataDir: dir })
- expect(made.options.at(-1)).toEqual({ dataDir: dir })
- })
-})
diff --git a/cli/src/services/collaboration.ts b/cli/src/services/collaboration.ts
deleted file mode 100644
index 0c8df0712..000000000
--- a/cli/src/services/collaboration.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * Agent Messages (`collaboration`), an experiment: harnesses in a tab with Agent Messages on message each other
- * with `harness send` (messages/service.ts, docs/design/2026-10-10-agent-messages.md). It replaced Swarm
- * collaboration in the same slot, the teams' process, and keeps that slot's contract with the core: its typed
- * deliveries go through `core.turns.deliver` under `team:` ids, which the core writes only into an idle,
- * empty composer, and the core asks in line whether one may still be written (`canWrite`). So the core did not
- * change for it.
- * - The `agent_messages` request: `harness send` in an agent's pane, the owner's other machines, the windows.
- * - In the core's process (`HARNESSD_SERVICES=none`) it starts here, at once; in the teams' own process,
- * services/collaborationProcess.ts starts the same service.
- */
-import type { CoreApi, CorePorts, ServiceRequests } from '../core/api.js'
-import { startAgentMessages, type AgentMessages, type MessagesOptions } from '../messages/service.js'
-
-/** The requests Agent Messages answers, declared in core/api.ts for the core to route. */
-export { TEAMS_REQUESTS } from '../core/api.js'
-
-export type TeamsOptions = MessagesOptions
-export type Teams = AgentMessages
-
-export function startCollaboration(core: CoreApi, options: TeamsOptions = {}): Teams {
- return startAgentMessages(core, options)
-}
-
-/**
- * Agent Messages in the core's process (`HARNESSD_SERVICES=none`). The core still records each prompt's swarm
- * scope into this port (core/input.ts, turns/funnel.ts) until that plumbing is removed: nothing reads it now.
- */
-export function startTeamsInCore(core: CoreApi, ports: CorePorts, options: TeamsOptions = {}): ServiceRequests {
- const messages = startCollaboration(core, options)
- ports.teams = Object.assign({
- prepare: () => () => {}, started: () => {}, raw: () => {}, forget: () => {},
- canWrite: (deliveryId: string) => messages.canWrite(deliveryId),
- }, { stop: () => messages.stop() })
- messages.start()
- return messages.requests
-}
diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.ts
index cc7546cf3..10a8f3a4c 100644
--- a/cli/src/services/inline.spec.ts
+++ b/cli/src/services/inline.spec.ts
@@ -14,7 +14,7 @@ import { startDevices } from './devices.js'
import { startHandoff } from './handoff.js'
import * as inline from './inline.js'
import { startModels } from './models.js'
-import { startTeamsInCore } from './collaboration.js'
+import { startMessagesInCore } from './messages.js'
import { startMonitor } from './monitor.js'
import { startOrchestrator } from './orchestrator.js'
import { startProjects } from './projects.js'
@@ -32,6 +32,6 @@ import { startWorkspaces } from './workspaces.js'
describe('the services the core runs in its own process only when they do not run in theirs', () => {
it('are their own starts, unchanged: the same services either way', () => {
- expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startConnectors, startDevices, startHandoff, startGateway, startMemory, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startRouter, startSearch, startSharing, startShell, startStoreInCore, startTeamsInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })
+ expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startConnectors, startDevices, startHandoff, startGateway, startMemory, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startRouter, startSearch, startSharing, startShell, startStoreInCore, startMessagesInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })
})
})
diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.ts
index 2f080ab18..36329b644 100644
--- a/cli/src/services/inline.ts
+++ b/cli/src/services/inline.ts
@@ -25,8 +25,8 @@ export { startMemory } from './memory.js'
export { startConnectors } from './connectors.js'
export { startDevices } from './devices.js'
export { startHandoff } from './handoff.js'
+export { startMessagesInCore } from './messages.js'
export { startModels } from './models.js'
-export { startTeamsInCore } from './collaboration.js'
export { startMonitor } from './monitor.js'
export { startOrchestrator } from './orchestrator.js'
export { startProjects } from './projects.js'
diff --git a/cli/src/services/messages.spec.ts b/cli/src/services/messages.spec.ts
new file mode 100644
index 000000000..e12aa628c
--- /dev/null
+++ b/cli/src/services/messages.spec.ts
@@ -0,0 +1,50 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { emptyPorts, MESSAGES_REQUESTS } from '../core/api.js'
+import { fakeCore } from '../testing/fakeCore.js'
+
+/**
+ * Agent Messages in the core's process: the service is messages/service.ts's to prove (messages/service.spec.ts);
+ * here, that it starts and keeps its contract with the core.
+ */
+const made = vi.hoisted(() => ({ calls: [] as string[], options: [] as unknown[] }))
+vi.mock('../messages/service.js', () => ({
+ startAgentMessages: (_core: unknown, options: unknown) => {
+ made.options.push(options)
+ return {
+ requests: { agent_messages: async () => ({ ok: true }) },
+ canWrite: (id: string) => id === 'team:msg:yes',
+ start: () => made.calls.push('start'),
+ stop: () => made.calls.push('stop'),
+ }
+ },
+}))
+
+import { MESSAGES_REQUESTS as REEXPORTED, startMessagesInCore } from './messages.js'
+
+describe('Agent Messages in the core\'s process', () => {
+ let dir: string
+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'messages-')); made.calls.length = 0; made.options.length = 0 })
+ afterEach(() => rmSync(dir, { recursive: true, force: true }))
+
+ it('answers the one request the core routes to it', () => {
+ expect(MESSAGES_REQUESTS).toEqual(['agent_messages'])
+ expect(REEXPORTED).toBe(MESSAGES_REQUESTS)
+ })
+
+ it('starts at once with the options it was given, and answers whether a delivery may be written', async () => {
+ const ports = emptyPorts()
+ const requests = startMessagesInCore(fakeCore({ dataDir: dir }), ports)
+ expect(made.calls).toEqual(['start'])
+ expect(made.options).toEqual([{}])
+ expect(await requests.agent_messages!({ action: 'history' }, { local: true, owner: true })).toEqual({ ok: true })
+ expect(ports.messages!.canWrite('team:msg:yes')).toBe(true)
+ expect(ports.messages!.canWrite('team:msg:no')).toBe(false)
+ ;(ports.messages as unknown as { stop(): void }).stop()
+ expect(made.calls).toEqual(['start', 'stop'])
+ startMessagesInCore(fakeCore({ dataDir: dir }), emptyPorts(), { dataDir: dir })
+ expect(made.options.at(-1)).toEqual({ dataDir: dir })
+ })
+})
diff --git a/cli/src/services/messages.ts b/cli/src/services/messages.ts
new file mode 100644
index 000000000..a9ca7887a
--- /dev/null
+++ b/cli/src/services/messages.ts
@@ -0,0 +1,22 @@
+/**
+ * Agent Messages (`messages`), an experiment: harnesses in a tab with Agent Messages on message each other with
+ * `harness send` (messages/service.ts, docs/design/2026-10-10-agent-messages.md). Its typed deliveries go
+ * through `core.turns.deliver` under `team:` ids, which the core writes only into an idle, empty composer, and
+ * the core asks in line whether one may still be written (`canWrite`).
+ * - The `agent_messages` request: `harness send` in an agent's pane, the owner's other machines, the windows.
+ * - In the core's process (`HARNESSD_SERVICES=none`) it starts here, at once; in its own process,
+ * services/messagesProcess.ts starts the same service.
+ */
+import type { CoreApi, CorePorts, ServiceRequests } from '../core/api.js'
+import { startAgentMessages, type MessagesOptions } from '../messages/service.js'
+
+/** The requests Agent Messages answers, declared in core/api.ts for the core to route. */
+export { MESSAGES_REQUESTS } from '../core/api.js'
+
+/** Agent Messages in the core's process (`HARNESSD_SERVICES=none`): its port is whether a delivery may be written. */
+export function startMessagesInCore(core: CoreApi, ports: CorePorts, options: MessagesOptions = {}): ServiceRequests {
+ const messages = startAgentMessages(core, options)
+ ports.messages = Object.assign({ canWrite: (deliveryId: string) => messages.canWrite(deliveryId) }, { stop: () => messages.stop() })
+ messages.start()
+ return messages.requests
+}
diff --git a/cli/src/services/collaborationProcess.spec.ts b/cli/src/services/messagesProcess.spec.ts
similarity index 94%
rename from cli/src/services/collaborationProcess.spec.ts
rename to cli/src/services/messagesProcess.spec.ts
index 5f8afbb4a..b42eb093a 100644
--- a/cli/src/services/collaborationProcess.spec.ts
+++ b/cli/src/services/messagesProcess.spec.ts
@@ -1,8 +1,8 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { CoreApi } from '../core/api.js'
import type { RegisteredSession } from '../lib/registry.js'
-import type { TeamsOptions, Teams } from './collaboration.js'
-import { AGENTS_FRESH_MS, runCollaborationService, WATCHED, WRITABLE_EVERY_MS, WRITABLE_FOR_MS } from './collaborationProcess.js'
+import type { AgentMessages, MessagesOptions } from '../messages/service.js'
+import { AGENTS_FRESH_MS, runMessagesService, WATCHED, WRITABLE_EVERY_MS, WRITABLE_FOR_MS } from './messagesProcess.js'
import type { CoreConnection, ServiceProcessOptions } from './process.js'
// The real default reaches a real socket: never in a test.
@@ -12,19 +12,19 @@ const OWNER = { local: true, owner: true }
const flush = async () => { for (let i = 0; i < 5; i++) await new Promise((settle) => setTimeout(settle, 0)) }
const agent = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/w', displayName: agentId, terminalAvailable: true }) as unknown as RegisteredSession
-describe('Agent Messages in the teams\' own process', () => {
+describe('Agent Messages in its own process', () => {
afterEach(() => vi.clearAllMocks())
const setup = () => {
let options: ServiceProcessOptions | null = null
let api: CoreApi | null = null
- let given: TeamsOptions | undefined
+ let given: MessagesOptions | undefined
let clock = 10_000
const timers: Array<{ run: () => void; ms: number; cleared: boolean }> = []
const writable = new Set<string>()
const calls: string[] = []
const stop = vi.fn()
- const service = runCollaborationService({
+ const service = runMessagesService({
dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',
run: (o) => { options = o; return { stop } },
now: () => clock,
@@ -40,7 +40,7 @@ describe('Agent Messages in the teams\' own process', () => {
canWrite: (id) => writable.has(id),
start: () => calls.push('start'),
stop: () => calls.push('stop'),
- } satisfies Teams
+ } satisfies AgentMessages
},
})
return { options: options!, api: () => api!, given: () => given!, writable, timers, calls, service, stop, tick: (ms: number) => { clock += ms }, now: () => clock }
@@ -58,7 +58,7 @@ describe('Agent Messages in the teams\' own process', () => {
it('starts once it knows the agents and the daemon, and answers on the agents as each request starts', async () => {
const { options, calls } = setup()
- expect(options).toMatchObject({ name: 'collaboration', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
+ expect(options).toMatchObject({ name: 'messages', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
const link = core({ shown: { agents: [agent('a1')] }, daemon: { command: `'node' 'cli.js'`, port: 18473, machineId: 'm' } })
options.onConnected!(link.connection)
await flush()
@@ -215,7 +215,7 @@ describe('Agent Messages in the teams\' own process', () => {
const { runServiceProcess } = await import('./process.js')
const writable = new Set(['team:d1'])
let api: CoreApi | null = null
- const process = runCollaborationService({
+ const process = runMessagesService({
dataDir: '/data', socketPath: '/s', machineId: 'm', token: 't',
start: (given) => {
api = given
@@ -236,7 +236,7 @@ describe('Agent Messages in the teams\' own process', () => {
it('starts the real service when given none', async () => {
const { runServiceProcess } = await import('./process.js')
- runCollaborationService({ dataDir: '/data-that-is-not-there', socketPath: '/s', machineId: 'm', token: 't' }).stop()
+ runMessagesService({ dataDir: '/data-that-is-not-there', socketPath: '/s', machineId: 'm', token: 't' }).stop()
expect(vi.mocked(runServiceProcess).mock.calls.at(-1)![0].requests.agent_messages).toBeTypeOf('function')
})
})
diff --git a/cli/src/services/collaborationProcess.ts b/cli/src/services/messagesProcess.ts
similarity index 85%
rename from cli/src/services/collaborationProcess.ts
rename to cli/src/services/messagesProcess.ts
index 89e7e61cf..abc0ddcb2 100644
--- a/cli/src/services/collaborationProcess.ts
+++ b/cli/src/services/messagesProcess.ts
@@ -1,6 +1,6 @@
/**
- * Agent Messages in the teams' own process (`harness __service teams,collaboration`): an experiment, started only
- * once it is on (core/api.ts `EXPERIMENTS`). The same service as in the core's process (services/collaboration.ts,
+ * Agent Messages in its own process (`harness __service messages`): an experiment, started only once it is on
+ * (core/api.ts `EXPERIMENTS`). The same service as in the core's process (services/messages.ts,
* messages/service.ts), on the core's API as a process reaches it (services/processCoreApi.ts), and what a mailbox
* in another process needs besides:
* - The core asks in line, as it writes a typed delivery, whether it may still be written. This process tells the
@@ -11,7 +11,7 @@
* mailbox reads them and they are a second old.
*/
import type { BackendNotice, DaemonAddress } from '../core/api.js'
-import { startCollaboration } from './collaboration.js'
+import { startAgentMessages } from '../messages/service.js'
import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
import { agentsIn, daemonIn, processCoreApi, type ShownAgent } from './processCoreApi.js'
import { turnsLink } from './turnsLink.js'
@@ -27,7 +27,7 @@ export const WATCHED = 1_000
/** How old the agents it read may be before its mailbox's next look asks again. */
export const AGENTS_FRESH_MS = 1_000
-export interface CollaborationServiceOptions {
+export interface MessagesServiceOptions {
dataDir: string
socketPath: string
machineId: string
@@ -35,13 +35,13 @@ export interface CollaborationServiceOptions {
/** Swapped in tests for one that does not touch the real socket or process. */
run?: typeof runServiceProcess
/** Swapped in tests for a service that keeps nothing on disk and polls no account. */
- start?: typeof startCollaboration
+ start?: typeof startAgentMessages
now?: () => number
setTimer?: (run: () => void, ms: number) => unknown
clearTimer?: (timer: unknown) => void
}
-export function runCollaborationService(options: CollaborationServiceOptions): ServiceProcess {
+export function runMessagesService(options: MessagesServiceOptions): ServiceProcess {
const now = options.now ?? Date.now
const setTimer = options.setTimer ?? ((run, ms) => { const timer = setInterval(run, ms); timer.unref?.(); return timer })
const clearTimer = options.clearTimer ?? ((timer) => clearInterval(timer as ReturnType<typeof setInterval>))
@@ -76,7 +76,7 @@ export function runCollaborationService(options: CollaborationServiceOptions): S
let told = ''
let ticking: unknown = null
- const base = processCoreApi(options.dataDir, 'collaboration', {
+ const base = processCoreApi(options.dataDir, 'messages', {
// Read in line by its mailbox's timer too: a copy a second old is asked for again, for its next look.
live: () => { if (now() - readAt > AGENTS_FRESH_MS) void readAgents(); return live },
ask, deliveries, daemon: () => daemon,
@@ -98,36 +98,36 @@ export function runCollaborationService(options: CollaborationServiceOptions): S
cancelDelivery: () => false,
},
}
- const build = () => (options.start ?? startCollaboration)(api, { dataDir: options.dataDir, changed: () => tell() })
- let collaboration = build()
+ const build = () => (options.start ?? startAgentMessages)(api, { dataDir: options.dataDir, changed: () => tell() })
+ let messages = build()
/** The machine the running service was started under, and whether it was. */
let builtFor: string | null = null
let started = false
/**
* The service, started, for the machine this daemon serves as now. One started under another machine goes
- * and a new one starts: a sign-in starts a new core under the account's machine, and the teams it ran
- * inside used to go with the core they ran in, which this process outlives.
+ * and a new one starts: a sign-in starts a new core under the account's machine, and what the service
+ * keeps is that machine's, while this process outlives the core it started under.
*/
const current = () => {
const machine = daemon?.machineId() ?? null
- if (machine === null) return collaboration
+ if (machine === null) return messages
if (started && builtFor !== machine) {
- collaboration.stop()
- collaboration = build()
+ messages.stop()
+ messages = build()
started = false
}
if (!started) {
started = true
builtFor = machine
- collaboration.start()
+ messages.start()
}
- return collaboration
+ return messages
}
/** Tell the core which deliveries may be written now, when that changed or is due again; keep telling while any may. */
function tell(): void {
const until = now() + WRITABLE_FOR_MS
- const writable = [...handed].filter((id) => collaboration.canWrite(id))
+ const writable = [...handed].filter((id) => messages.canWrite(id))
const said = JSON.stringify(writable)
if (said !== told || writable.length) {
told = said
@@ -138,7 +138,7 @@ export function runCollaborationService(options: CollaborationServiceOptions): S
}
const service = (options.run ?? runServiceProcess)({
- name: 'collaboration',
+ name: 'messages',
socketPath: options.socketPath,
machineId: options.machineId,
token: options.token,
@@ -147,7 +147,7 @@ export function runCollaborationService(options: CollaborationServiceOptions): S
},
onEvent: (payload) => {
if (deliveries.heard(payload)) { tell(); return }
- // Heard once the service runs for a known machine: the channels it would read are that machine's.
+ // Heard once the service runs for a known machine: the tabs it would read are that machine's.
if (started && payload.kind === 'notice' && payload.notice && typeof payload.notice === 'object') {
for (const listener of noticeListeners) listener(payload.notice as BackendNotice)
}
@@ -168,7 +168,7 @@ export function runCollaborationService(options: CollaborationServiceOptions): S
stop: () => {
if (ticking) clearTimer(ticking)
ticking = null
- collaboration.stop()
+ messages.stop()
return service.stop()
},
}
diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.ts
index fe3ea2d3e..b101bb53b 100644
--- a/cli/src/services/processCoreApi.spec.ts
+++ b/cli/src/services/processCoreApi.spec.ts
@@ -88,7 +88,7 @@ describe('the core API a light service runs on in its own process', () => {
expect(api.turns.cancelDelivery('d1')).toBe(false)
expect(api.daemon).toMatchObject({ command: 'harness', port: 0 })
expect(api.daemon.machineId()).toBe('')
- expect(await api.account.backend('GET', '/api/tab-channels')).toEqual({ status: 503, body: { error: 'SERVICE_UNAVAILABLE' } })
+ expect(await api.account.backend('GET', '/api/agent-messages')).toEqual({ status: 503, body: { error: 'SERVICE_UNAVAILABLE' } })
expect(api.account.onNotice(() => {})()).toBeUndefined()
})
@@ -96,11 +96,11 @@ describe('the core API a light service runs on in its own process', () => {
let answer: Record<string, unknown> | Error = { status: 200, body: { success: true } }
const ask = vi.fn(async () => { if (answer instanceof Error) throw answer; return answer })
const listeners: Array<(notice: never) => void> = []
- const api = processCoreApi('/data', 'collaboration', { ask, onNotice: (listener) => { listeners.push(listener as never); return () => {} } })
- expect(await api.account.backend('PATCH', '/api/tab-channels/settings', { enabled: true })).toEqual({ status: 200, body: { success: true } })
- expect(ask).toHaveBeenLastCalledWith('backend', { method: 'PATCH', path: '/api/tab-channels/settings', body: { enabled: true } })
- await api.account.backend('GET', '/api/tab-channels')
- expect(ask).toHaveBeenLastCalledWith('backend', { method: 'GET', path: '/api/tab-channels' })
+ const api = processCoreApi('/data', 'messages', { ask, onNotice: (listener) => { listeners.push(listener as never); return () => {} } })
+ expect(await api.account.backend('PATCH', '/api/agent-messages/tabs/t1', { enabled: true })).toEqual({ status: 200, body: { success: true } })
+ expect(ask).toHaveBeenLastCalledWith('backend', { method: 'PATCH', path: '/api/agent-messages/tabs/t1', body: { enabled: true } })
+ await api.account.backend('GET', '/api/agent-messages')
+ expect(ask).toHaveBeenLastCalledWith('backend', { method: 'GET', path: '/api/agent-messages' })
answer = { error: 'INVALID_REQUEST' }
expect(await api.account.backend('GET', '/nope')).toEqual({ status: 502, body: { error: 'INVALID_REQUEST' } })
answer = { status: 200 }
diff --git a/cli/src/services/teamsProcess.spec.ts b/cli/src/services/teamsProcess.spec.ts
deleted file mode 100644
index bb2f19e98..000000000
--- a/cli/src/services/teamsProcess.spec.ts
+++ /dev/null
@@ -1,237 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import type { PromptScopes, TeamsEvent } from '../core/api.js'
-import { channelTeamId } from '../teams/promptScope.js'
-import { runServiceProcess, type CoreConnection, type ServiceProcessOptions } from './process.js'
-import { KEPT_UNDOS, runTeamsService } from './teamsProcess.js'
-
-// The real default reaches a real socket and this process's own channel: never in a test.
-vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))
-
-const TEAM = channelTeamId('tab-1')
-const OTHER = channelTeamId('tab-2')
-const Q = 'c'.repeat(32)
-const T0 = 1_000_000
-
-/** An event of `core-1`, as the core numbers and stamps it. */
-const ev = (seq: number, change: Record<string, unknown>, at = T0): TeamsEvent =>
- ({ agentId: 'agent-1', ...change, seq, core: 'core-1', at }) as TeamsEvent
-const flush = () => new Promise((done) => setTimeout(done, 0))
-
-describe('the teams\' prompt scopes in their own process', () => {
- afterEach(() => vi.clearAllMocks())
-
- const setup = (over: Partial<Parameters<typeof runTeamsService>[0]> = {}) => {
- let options: ServiceProcessOptions | null = null
- const service = { stop: vi.fn() }
- const lines: string[] = []
- const handle = runTeamsService({
- dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',
- run: (given) => { options = given; return service },
- log: (line) => lines.push(line),
- ...over,
- })
- return { options: options!, service, handle, lines }
- }
- /** A core that answers `hello` with `answer`, and records every acknowledgement. */
- const connection = (answer: Record<string, unknown> | (() => Promise<Record<string, unknown>>) = { core: 'core-1', reset: true, base: 0, events: [] }) => {
- const query = vi.fn((name: string, _payload?: Record<string, unknown>) => name === 'hello'
- ? (typeof answer === 'function' ? answer() : Promise.resolve(answer))
- : Promise.resolve({ kept: true }))
- const acks = () => query.mock.calls.filter(([name]) => name === 'ack').map(([, payload]) => payload)
- const hellos = () => query.mock.calls.filter(([name]) => name === 'hello').map(([, payload]) => payload)
- return { core: { query } satisfies CoreConnection, query, acks, hellos }
- }
- /** Connected, and caught up with `events`. */
- const synced = async (options: ServiceProcessOptions, events: TeamsEvent[] = []) => {
- const core = connection({ core: 'core-1', reset: true, base: 0, events })
- options.onConnected!(core.core)
- await flush()
- return core
- }
-
- it('reaches the core as `teams`, through the socket and token it was given, and answers the apps nothing', () => {
- const { options } = setup()
- expect(options).toMatchObject({ name: 'teams', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
- expect(options.requests).toEqual({})
- })
-
- it('first asks for what it lacks, applies it, then says where each agent stands', async () => {
- const { options } = setup()
- const core = await synced(options, [
- ev(1, { kind: 'prepare', text: 'hello team', tabId: 'tab-1' }),
- ev(2, { kind: 'started', text: 'hello team', source: 'hook', engine: 'claude' }),
- ])
- expect(core.hellos()).toEqual([{ core: null, applied: 0 }])
- expect(core.acks()).toEqual([{ core: 'core-1', applied: 2, scopes: { 'agent-1': TEAM } }])
- })
-
- it('applies what comes next in order, once: skips what it has, and asks again for what went missing', async () => {
- const { options } = setup()
- const core = await synced(options, [ev(1, { kind: 'prepare', text: 'hello team', tabId: 'tab-1' })])
- // Already applied, from another core, not a numbered event, or not an event at all: nothing to do.
- options.onEvent!({ kind: 'event', event: ev(1, { kind: 'prepare', text: 'hello team', tabId: 'tab-1' }) })
- options.onEvent!({ kind: 'event', event: { ...ev(2, { kind: 'forget' }), core: 'core-0' } })
- options.onEvent!({ kind: 'event', event: { ...ev(2, { kind: 'forget' }), seq: 'two' } })
- options.onEvent!({ kind: 'event' })
- options.onEvent!({ kind: 'touch', sessionId: 's1' })
- options.onEvent!({ kind: 'event', event: ev(2, { kind: 'started', text: 'hello team', source: 'hook' }) })
- await flush()
- expect(core.acks().at(-1)).toEqual({ core: 'core-1', applied: 2, scopes: { 'agent-1': TEAM } })
- // The fourth before the third: ask the core again, from where it is.
- options.onEvent!({ kind: 'event', event: ev(4, { kind: 'forget' }) })
- await flush()
- expect(core.hellos().at(-1)).toEqual({ core: 'core-1', applied: 2 })
- })
-
- it('applies nothing before its first question is answered: the answer brings it all', async () => {
- const { options } = setup()
- let answer: (value: Record<string, unknown>) => void = () => {}
- const core = connection(() => new Promise((done) => { answer = done }))
- options.onConnected!(core.core)
- options.onEvent!({ kind: 'event', event: ev(1, { kind: 'prepare', text: 'early', tabId: 'tab-1' }) })
- answer({ core: 'core-1', reset: true, base: 0, events: [ev(1, { kind: 'prepare', text: 'early', tabId: 'tab-1' }), ev(2, { kind: 'started', text: 'early', source: 'hook' })] })
- await flush()
- expect(core.acks()).toEqual([{ core: 'core-1', applied: 2, scopes: { 'agent-1': TEAM } }])
- })
-
- it('ignores an answer it cannot use: an older connection\'s, or one that says nothing', async () => {
- const { options } = setup()
- let older: (value: Record<string, unknown>) => void = () => {}
- options.onConnected!(connection(() => new Promise((done) => { older = done })).core)
- const current = connection({ core: 'core-1' })
- options.onConnected!(current.core)
- older({ core: 'core-1', reset: true, base: 0, events: [] })
- for (const answer of [{ core: 'core-1', base: 0 }, { core: 'core-1', events: [] }, { base: 0, events: [] }]) {
- options.onConnected!(connection(answer).core)
- }
- options.onConnected!(connection(async () => { throw new Error('the core went away') }).core)
- await flush()
- // Never caught up: what comes is not applied.
- options.onEvent!({ kind: 'event', event: ev(1, { kind: 'forget' }) })
- expect(current.acks()).toEqual([])
- })
-
- it('applies a replay only from where it stands: out of place and foreign events are not its', async () => {
- const { options } = setup()
- const core = await synced(options, [
- null as unknown as TeamsEvent,
- ev(1, { kind: 'prepare', text: 'one', tabId: 'tab-1' }),
- { ...ev(2, { kind: 'started', text: 'one', source: 'hook' }), core: 'core-0' },
- ev(3, { kind: 'started', text: 'one', source: 'hook' }),
- ])
- expect(core.acks()).toEqual([{ core: 'core-1', applied: 1, scopes: { 'agent-1': null } }])
- })
-
- it('takes back a write that failed, so the prompt it would have scoped finds no team', async () => {
- const { options } = setup()
- const core = await synced(options, [
- ev(1, { kind: 'prepare', text: 'never written', tabId: 'tab-1' }),
- ev(2, { kind: 'unprepare', of: 1 }),
- // An undo for a write it never saw, or saw taken back already, does nothing.
- ev(3, { kind: 'unprepare', of: 1 }),
- ev(4, { kind: 'unprepare', of: 99 }),
- ev(5, { kind: 'started', text: 'never written', source: 'hook' }),
- ])
- expect(core.acks()).toEqual([{ core: 'core-1', applied: 5, scopes: { 'agent-1': null } }])
- })
-
- it('keeps a bounded number of undos', async () => {
- const { options } = setup()
- const writes = Array.from({ length: KEPT_UNDOS + 1 }, (_, n) => ev(n + 1, { kind: 'prepare', text: `m${n}`, tabId: 'tab-1', agentId: `agent-${n}` }))
- const core = await synced(options, [...writes, ev(KEPT_UNDOS + 2, { kind: 'unprepare', of: 1, agentId: 'agent-0' })])
- expect(core.acks()[0]).toMatchObject({ applied: KEPT_UNDOS + 2 })
- })
-
- it('applies each event at the time it happened, so a replay ages as the original would have', async () => {
- const minute = 60_000
- const { options } = setup()
- const core = await synced(options, [
- ev(1, { kind: 'prepare', text: 'quick', tabId: 'tab-1', agentId: 'quick' }, T0),
- ev(2, { kind: 'started', text: 'quick', source: 'hook', agentId: 'quick' }, T0 + minute),
- ev(3, { kind: 'prepare', text: 'slow', tabId: 'tab-2', agentId: 'slow' }, T0),
- ev(4, { kind: 'started', text: 'slow', source: 'hook', agentId: 'slow' }, T0 + 6 * minute),
- ])
- // Past five minutes, a message is no longer matched to the prompt that starts.
- expect(core.acks()).toEqual([{ core: 'core-1', applied: 4, scopes: { quick: TEAM, slow: null } }])
- })
-
- it('reads keys typed into a scoped terminal, and answers to a team\'s question', async () => {
- const { options } = setup()
- const question = `team:${OTHER}:${Q}:question`
- const core = await synced(options, [
- ev(1, { kind: 'raw', bytes: Buffer.from('typed\r').toString('base64'), tabId: 'tab-1', pasted: false }),
- ev(2, { kind: 'started', text: 'typed', source: 'hook' }),
- ev(3, { kind: 'prepare', text: 'a question', deliveryId: question, agentId: 'asked' }),
- ev(4, { kind: 'started', text: 'a question', source: 'transcript', agentId: 'asked' }),
- ])
- expect(core.acks().at(-1)).toMatchObject({ scopes: { 'agent-1': TEAM, asked: OTHER } })
- options.onEvent!({ kind: 'event', event: ev(5, { kind: 'replied', teamId: OTHER, questionId: Q, agentId: 'asked' }) })
- options.onEvent!({ kind: 'event', event: ev(6, { kind: 'forget' }) })
- await flush()
- expect(core.acks().at(-1)).toEqual({ core: 'core-1', applied: 6, scopes: { asked: null, 'agent-1': null } })
- })
-
- it('starts over when the core says so, and goes on from where the core says', async () => {
- const { options } = setup()
- const first = await synced(options, [ev(1, { kind: 'prepare', text: 'hello', tabId: 'tab-1' })])
- expect(first.acks()).toHaveLength(1)
- // The same core, reconnected: nothing lost, nothing over.
- const again = connection({ core: 'core-1', reset: false, base: 1, events: [ev(2, { kind: 'started', text: 'hello', source: 'hook' })] })
- options.onConnected!(again.core)
- await flush()
- expect(again.hellos()).toEqual([{ core: 'core-1', applied: 1 }])
- expect(again.acks()).toEqual([{ core: 'core-1', applied: 2, scopes: { 'agent-1': TEAM } }])
- // A new core: the old scopes go.
- const fresh = connection({ core: 'core-2', reset: true, base: 0, events: [{ ...ev(1, { kind: 'started', text: 'hello', source: 'hook' }), core: 'core-2' }] })
- options.onConnected!(fresh.core)
- await flush()
- expect(fresh.hellos()).toEqual([{ core: 'core-1', applied: 2 }])
- expect(fresh.acks()).toEqual([{ core: 'core-2', applied: 1, scopes: { 'agent-1': null } }])
- })
-
- it('goes on past an event it cannot apply, and one of a kind it does not know', async () => {
- const { options, lines } = setup()
- const core = await synced(options, [
- ev(1, { kind: 'prepare', tabId: 'tab-1' }),
- ev(2, { kind: 'newer-kind' }),
- ev(3, { kind: 'forget' }),
- ])
- expect(lines).toEqual([expect.stringMatching(/^\[teams\] event 1 could not be applied · /)])
- expect(core.acks()).toEqual([{ core: 'core-1', applied: 3, scopes: { 'agent-1': null } }])
- const thrown = setup({ scopes: () => ({ ...fakeScopes(), forget: () => { throw 'gone' } }) })
- await synced(thrown.options, [ev(1, { kind: 'forget' })])
- expect(thrown.lines).toEqual(['[teams] event 1 could not be applied · gone'])
- })
-
- it('says how far it got once per burst, and shrugs off a core that went away', async () => {
- const { options } = setup()
- const core = await synced(options)
- for (let seq = 1; seq <= 3; seq++) options.onEvent!({ kind: 'event', event: ev(seq, { kind: 'raw', bytes: 'YQ==', tabId: 'tab-1', pasted: false }) })
- await flush()
- expect(core.acks()).toHaveLength(2)
- expect(core.acks()[1]).toEqual({ core: 'core-1', applied: 3, scopes: { 'agent-1': null } })
- core.query.mockImplementation(async () => { throw new Error('the core went away') })
- options.onEvent!({ kind: 'event', event: ev(4, { kind: 'forget' }) })
- await flush()
- })
-
- it('stops its connection when stopped', () => {
- const { handle, service } = setup()
- handle.stop()
- expect(service.stop).toHaveBeenCalledOnce()
- })
-
- it('runs as a real service process by default, logging on the console', async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- runTeamsService({ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
- const options = vi.mocked(runServiceProcess).mock.calls.at(-1)![0]
- expect(options).toMatchObject({ name: 'teams', socketPath: '/data/daemon-1.sock' })
- await synced(options, [ev(1, { kind: 'started', source: 'hook' })])
- expect(warn).toHaveBeenCalledWith(expect.stringContaining('[teams] event 1 could not be applied'))
- warn.mockRestore()
- })
-})
-
-function fakeScopes(): PromptScopes {
- return { prepare: () => () => {}, started: () => {}, raw: () => {}, forget: () => {}, replied: () => {}, current: () => null }
-}
diff --git a/cli/src/services/teamsProcess.ts b/cli/src/services/teamsProcess.ts
deleted file mode 100644
index 151a74138..000000000
--- a/cli/src/services/teamsProcess.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-/**
- * The teams' prompt scopes in their own process (`harness __service teams`, with `HARNESSD_SERVICES=teams`).
- *
- * The same scopes as in the core's process (teams/promptScope.ts), fed the core's changes as numbered
- * events (core/teamsLink.ts) and applied here in order, exactly once:
- * - An event this process already has is skipped.
- * - One that arrives too early (the one before it went missing) makes it ask the core again.
- * - Each connection starts by telling the core the last event it applied. The core answers with the
- * events it lacks, or tells it to start over.
- *
- * Each event is applied at the time it happened, so one replayed later ages as it would have: a message
- * stays matchable for the same five minutes. After applying events, the process tells the core where
- * each agent it touched stands. That is what the socket's team features read back.
- */
-import type { PromptScopes, TeamsEvent } from '../core/api.js'
-import { SwarmPromptScopes } from '../teams/promptScope.js'
-import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
-
-export interface TeamsServiceOptions {
- dataDir: string
- socketPath: string
- machineId: string
- token: string
- /** Swapped in tests for one that does not touch the real socket or process. */
- run?: typeof runServiceProcess
- /** Swapped in tests for scopes they can watch; given the clock to read. */
- scopes?: (now: () => number) => PromptScopes
- log?: (line: string) => void
-}
-
-/** The most undos kept for writes that may yet fail. A write fails within seconds; these are minutes. */
-export const KEPT_UNDOS = 1_024
-
-export function runTeamsService(options: TeamsServiceOptions): ServiceProcess {
- const log = options.log ?? ((line: string) => console.warn(line))
- const make = options.scopes ?? ((now: () => number) => new SwarmPromptScopes(now))
- /** The time of the event being applied: every call into the scopes is made from one. */
- let clock = 0
- const now = (): number => clock
- let scopes = make(now)
- /** The core whose events the scopes hold, and the last of them applied. */
- let core: string | null = null
- let applied = 0
- let connection: CoreConnection | null = null
- /** The connection whose first question is answered: events may be applied as they come on it. */
- let synced: CoreConnection | null = null
- /** Each prepared write's undo, by its event: an unprepare names the write it takes back. */
- const undos = new Map<number, () => void>()
- const touched = new Set<string>()
- let acking = false
-
- /** One event, in its place: counted as applied even when it cannot be, so the stream goes on. */
- const apply = (event: TeamsEvent): void => {
- applied = event.seq
- clock = event.at
- try {
- switch (event.kind) {
- case 'prepare':
- undos.set(event.seq, scopes.prepare(event.agentId, event.text, event.tabId, event.deliveryId))
- if (undos.size > KEPT_UNDOS) undos.delete(undos.keys().next().value!)
- break
- case 'unprepare': {
- const undo = undos.get(event.of)
- undos.delete(event.of)
- undo?.()
- break
- }
- case 'started': scopes.started(event.agentId, event.text, event.source, event.engine); break
- case 'raw': scopes.raw(event.agentId, Buffer.from(event.bytes, 'base64'), event.tabId, event.pasted); break
- case 'forget': scopes.forget(event.agentId); break
- case 'replied': scopes.replied(event.agentId, event.teamId, event.questionId); break
- // A kind a newer core says: nothing this process knows how to do.
- default: break
- }
- touched.add(event.agentId)
- } catch (error) {
- log(`[teams] event ${event.seq} could not be applied · ${error instanceof Error ? error.message : String(error)}`)
- }
- }
-
- /** Tell the core how far this process got, and where each agent it touched stands; once per burst. */
- const acknowledge = (via: CoreConnection): void => {
- if (acking) return
- acking = true
- queueMicrotask(() => {
- acking = false
- const report = Object.fromEntries([...touched].map((agentId) => [agentId, scopes.current(agentId)]))
- touched.clear()
- void via.query('ack', { core, applied, scopes: report }).catch(() => {})
- })
- }
-
- /** Ask the core for what this process lacks, and apply it before anything new. */
- const sync = (via: CoreConnection): void => {
- synced = null
- void via.query('hello', { core, applied }).then((answer) => {
- if (connection !== via || typeof answer.core !== 'string' || typeof answer.base !== 'number' || !Array.isArray(answer.events)) return
- if (answer.reset === true) {
- scopes = make(now)
- undos.clear()
- }
- core = answer.core
- applied = answer.base
- for (const event of answer.events as TeamsEvent[]) if (event?.core === core && event.seq === applied + 1) apply(event)
- synced = via
- acknowledge(via)
- }, () => {})
- }
-
- const run = options.run ?? runServiceProcess
- const service = run({
- name: 'teams',
- socketPath: options.socketPath,
- machineId: options.machineId,
- token: options.token,
- // The apps ask teams nothing here: the team features answer them in the core's socket.
- requests: {},
- onEvent: (payload) => {
- const event = payload.event as TeamsEvent | undefined
- if (payload.kind !== 'event' || !synced || event?.core !== core || typeof event.seq !== 'number' || event.seq <= applied) return
- // The one before it never came: ask the core again rather than skip it.
- if (event.seq !== applied + 1) { sync(synced); return }
- apply(event)
- acknowledge(synced)
- },
- onConnected: (via) => {
- connection = via
- sync(via)
- },
- })
- return { stop: () => service.stop() }
-}
diff --git a/cli/src/teams/promptScope.spec.ts b/cli/src/teams/promptScope.spec.ts
deleted file mode 100644
index efde85827..000000000
--- a/cli/src/teams/promptScope.spec.ts
+++ /dev/null
@@ -1,211 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { channelTeamId, SwarmPromptScopes } from './promptScope.js'
-
-const agent = 'same-session'
-const a = channelTeamId('swarm-a'), b = channelTeamId('swarm-b')
-const bytes = (text: string): Uint8Array => Buffer.from(text)
-
-describe('prompt swarm origin', () => {
- it('pins typed work to A while B receives typing and queued work in the same session', () => {
- const scopes = new SwarmPromptScopes()
- scopes.raw(agent, bytes('help with frontend\r'), 'swarm-a')
- scopes.started(agent, 'help with frontend', 'hook')
- expect(scopes.current(agent)).toBe(a)
- scopes.raw(agent, bytes('help with backend\r'), 'swarm-b')
- scopes.raw(agent, bytes('a third draft'), 'swarm-a')
- expect(scopes.current(agent)).toBe(a)
- scopes.started(agent, 'help with backend', 'hook')
- expect(scopes.current(agent)).toBe(b)
- // Watcher catches up after B's hook: neither older event can move it back to A.
- scopes.started(agent, 'help with frontend')
- scopes.started(agent, 'help with backend')
- expect(scopes.current(agent)).toBe(b)
- })
-
- it('uses the submitting pane after a draft moves, handles split UTF-8 and bracketed pastes', () => {
- const scopes = new SwarmPromptScopes()
- const utf8 = bytes('café')
- scopes.raw(agent, utf8.slice(0, 4), 'swarm-a')
- scopes.raw(agent, utf8.slice(4), 'swarm-a')
- scopes.raw(agent, bytes('\x1b[200~\nsecond line\x1b[201~'), 'swarm-a')
- scopes.raw(agent, bytes('\r'), 'swarm-b')
- scopes.started(agent, 'café\nsecond line', 'hook')
- expect(scopes.current(agent)).toBe(b)
- })
-
- it('keeps the origin of prompts broken with the app’s ⇧⏎ and ⌥⏎ line keys', () => {
- const scopes = new SwarmPromptScopes()
- scopes.raw(agent, bytes('a\x1b[13;2ub\r'), 'swarm-a')
- scopes.started(agent, 'a\nb', 'hook', 'claude')
- expect(scopes.current(agent)).toBe(a)
- // A paste, two ⇧⏎, then text, each key arriving as its own write.
- for (const chunk of ['\x1b[200~pasted code\x1b[201~', '\x1b[13;2u', '\x1b', '[13;2u', 'explain it', '\r']) scopes.raw(agent, bytes(chunk), 'swarm-b')
- scopes.started(agent, 'pasted code\n\nexplain it', 'hook', 'claude')
- expect(scopes.current(agent)).toBe(b)
- scopes.raw(agent, bytes('c\x1b\rd\r'), 'swarm-a')
- scopes.started(agent, 'c\nd', 'hook', 'codex')
- expect(scopes.current(agent)).toBe(a)
- // Under LNM the app sends Return as \r\n, so ⌥⏎ arrives as \x1b\r\n: still one line break.
- scopes.raw(agent, bytes('e\x1b\r\nf\r\n'), 'swarm-b')
- scopes.started(agent, 'e\nf', 'hook', 'codex')
- expect(scopes.current(agent)).toBe(b)
- })
-
- it('ignores SGR mouse reports from clicking into or scrolling the pane', () => {
- const scopes = new SwarmPromptScopes()
- // Recorded shape: click to focus (split press/release), a wheel burst, then ⌥⏎ lines.
- for (const chunk of ['\x1b[<0;12;34M', '\x1b[<0;12;34m', '\x1b[<65;40;20M'.repeat(19), '\x1b', '[<64;4', '0;20M', '\x1b\r', '\x1b\r', 'ok', '\r']) scopes.raw(agent, bytes(chunk), 'swarm-a')
- scopes.started(agent, '\n\nok', 'hook', 'claude')
- expect(scopes.current(agent)).toBe(a)
- scopes.raw(agent, bytes('x\x1b[<0;12M\r'), 'swarm-b') // A malformed report is not a mouse event.
- scopes.started(agent, 'x', 'hook', 'claude')
- expect(scopes.current(agent)).toBeNull()
- })
-
- it('still fails closed on ⌥⌫ and on other CSI keys that share the ⇧⏎ prefix', () => {
- const scopes = new SwarmPromptScopes()
- scopes.raw(agent, bytes('one two\x1b\x7f\r'), 'swarm-a')
- scopes.started(agent, 'one ', 'hook', 'claude')
- expect(scopes.current(agent)).toBeNull()
- scopes.raw(agent, bytes('word\x1b[1;5D\r'), 'swarm-a')
- scopes.started(agent, 'word', 'hook', 'claude')
- expect(scopes.current(agent)).toBeNull()
- // Pasted escapes reach the engine literally; they are not line keys.
- scopes.raw(agent, bytes('\x1b[200~x\x1b[13;2uy\x1b\rz\x1b[201~\r'), 'swarm-a')
- scopes.started(agent, 'x\ny\nz', 'hook', 'claude')
- expect(scopes.current(agent)).toBeNull()
- // A lone Esc followed later by Return is not ⌥⏎: the draft must not become 'hello\n…'.
- scopes.raw(agent, bytes('hello\x1b'), 'swarm-a')
- scopes.raw(agent, bytes('\r'), 'swarm-a')
- scopes.raw(agent, bytes('next\r'), 'swarm-a')
- scopes.started(agent, 'hello\nnext', 'hook', 'claude')
- expect(scopes.current(agent)).toBeNull()
- })
-
- it('keeps the team when the prompt\'s hook is heard after the transcript started it', () => {
- // The hook gives the daemon 500 ms and the engine goes on, so the turn can be read first. The late hook
- // used to find its message taken and read as no team (e2e/teamsProcess.e2e.ts with the real hook).
- const scopes = new SwarmPromptScopes()
- scopes.prepare(agent, 'hello from the alpha tab', 'swarm-a')
- scopes.started(agent, 'hello from the alpha tab')
- scopes.started(agent, 'hello from the alpha tab', 'hook', 'claude')
- expect(scopes.current(agent)).toBe(a)
- // Two prompts read before either hook: neither late hook moves the scope.
- scopes.prepare(agent, 'first', 'swarm-a')
- scopes.prepare(agent, 'second', 'swarm-b')
- scopes.started(agent, 'first')
- scopes.started(agent, 'second')
- scopes.started(agent, 'first', 'hook')
- scopes.started(agent, 'second', 'hook')
- expect(scopes.current(agent)).toBe(b)
- // Each start is acknowledged once: the same text sent again is a prompt of its own.
- scopes.prepare(agent, 'first', 'swarm-a')
- scopes.started(agent, 'first', 'hook')
- expect(scopes.current(agent)).toBe(a)
- })
-
- it('matches native accepted text instead of treating permission keys as prompts', () => {
- const scopes = new SwarmPromptScopes()
- scopes.raw(agent, bytes('1\r'), 'swarm-b')
- scopes.raw(agent, bytes('ask a peer\r'), 'swarm-a')
- scopes.started(agent, 'ask a peer')
- expect(scopes.current(agent)).toBe(a)
- scopes.raw(agent, bytes('2\r'), 'swarm-b')
- expect(scopes.current(agent)).toBe(a)
- })
-
- it('fails closed on unknown editor state, native outside input and ambiguous identical queues', () => {
- const scopes = new SwarmPromptScopes()
- scopes.raw(agent, bytes('\x1b[A\r'), 'swarm-a')
- scopes.started(agent, 'a prompt recalled from native history')
- expect(scopes.current(agent)).toBeNull()
- scopes.prepare(agent, 'same text', 'swarm-a')
- scopes.prepare(agent, 'same text', 'swarm-b')
- scopes.started(agent, 'same text')
- expect(scopes.current(agent)).toBeNull()
- scopes.started(agent, 'entered in an external terminal')
- expect(scopes.current(agent)).toBeNull()
- })
-
- it('never attributes a recalled prompt in B to identical pending text from A', () => {
- const scopes = new SwarmPromptScopes()
- scopes.prepare(agent, 'same text', 'swarm-a')
- scopes.raw(agent, bytes('\x1b[A\r'), 'swarm-b')
- scopes.started(agent, 'same text', 'hook')
- expect(scopes.current(agent)).toBeNull()
- scopes.raw(agent, bytes('a fresh prompt\r'), 'swarm-b')
- scopes.started(agent, 'a fresh prompt', 'hook')
- expect(scopes.current(agent)).toBe(b)
- })
-
- it('pins structured queued prompts and peer continuations; a roster notice never retargets work', () => {
- const scopes = new SwarmPromptScopes()
- scopes.prepare(agent, 'human task', 'swarm-a')
- scopes.started(agent, 'human task')
- scopes.prepare(agent, 'membership B', undefined, `team:${b}:${'1'.repeat(32)}:intro`)
- scopes.started(agent, 'membership B')
- expect(scopes.current(agent)).toBe(a)
- scopes.prepare(agent, 'peer answer', undefined, `team:${b}:${'2'.repeat(32)}:answer`)
- scopes.started(agent, '<pasted_content id="abcd">\npeer answer\n</pasted_content id="abcd">', 'transcript', 'claude')
- expect(scopes.current(agent)).toBe(b)
- })
-
- it('does not retain revoked, expired or forgotten prompt origins', () => {
- let now = 0
- const scopes = new SwarmPromptScopes(() => now)
- scopes.prepare(agent, 'not written', 'swarm-a')()
- scopes.started(agent, 'not written')
- expect(scopes.current(agent)).toBeNull()
- scopes.prepare(agent, 'stale', 'swarm-a')
- now += 300_001
- scopes.started(agent, 'stale')
- expect(scopes.current(agent)).toBeNull()
- scopes.prepare(agent, 'valid', 'swarm-a')
- scopes.started(agent, 'valid')
- scopes.forget(agent)
- expect(scopes.current(agent)).toBeNull()
- })
-
- it('returns to the original task’s swarm after answering an incoming peer question', () => {
- const scopes = new SwarmPromptScopes(), question = '3'.repeat(32)
- scopes.prepare(agent, 'original A task', 'swarm-a')
- scopes.started(agent, 'original A task', 'hook')
- scopes.prepare(agent, 'question from B', undefined, `team:${b}:${question}:question`)
- scopes.started(agent, 'question from B', 'hook')
- expect(scopes.current(agent)).toBe(b)
- scopes.replied(agent, b, question)
- expect(scopes.current(agent)).toBe(a)
- scopes.started(agent, 'question from B') // Late transcript must not undo the return.
- expect(scopes.current(agent)).toBe(a)
- scopes.prepare(agent, 'a new B task', 'swarm-b')
- scopes.started(agent, 'a new B task', 'hook')
- scopes.replied(agent, b, question) // Retrying an old reply cannot retarget new work.
- expect(scopes.current(agent)).toBe(b)
- })
-
- it('prefers literal submitted text and does not interpret another engine’s paste syntax', () => {
- const scopes = new SwarmPromptScopes()
- const wrapped = '<pasted_content id="abcd">\ninner\n</pasted_content id="abcd">'
- scopes.prepare(agent, 'inner', 'swarm-a')
- scopes.prepare(agent, wrapped, 'swarm-b')
- scopes.started(agent, wrapped, 'hook', 'claude')
- expect(scopes.current(agent)).toBe(b)
- scopes.started(agent, wrapped, 'hook', 'codex')
- expect(scopes.current(agent)).toBeNull()
- })
-
- it('keeps large chunked pastes bounded and never mistakes an oversized draft for a known prompt', () => {
- const scopes = new SwarmPromptScopes(), text = 'code example '.repeat(8192)
- scopes.raw(agent, bytes('\x1b[200~'), 'swarm-a')
- for (let offset = 0; offset < text.length; offset += 8192) scopes.raw(agent, bytes(text.slice(offset, offset + 8192)), 'swarm-a')
- scopes.raw(agent, bytes('\x1b[201~\r'), 'swarm-a')
- scopes.started(agent, text)
- expect(scopes.current(agent)).toBe(a)
- scopes.raw(agent, bytes('x'.repeat(300_000)), 'swarm-b', true)
- scopes.raw(agent, bytes('\r'), 'swarm-b')
- scopes.started(agent, '', 'hook') // A bounded native hook clears scope even before transcript fallback.
- expect(scopes.current(agent)).toBeNull()
- scopes.started(agent, 'x'.repeat(300_000))
- expect(scopes.current(agent)).toBeNull()
- })
-})
diff --git a/cli/src/teams/promptScope.ts b/cli/src/teams/promptScope.ts
deleted file mode 100644
index 45695e7ab..000000000
--- a/cli/src/teams/promptScope.ts
+++ /dev/null
@@ -1,181 +0,0 @@
-import { createHash } from 'node:crypto'
-import { StringDecoder } from 'node:string_decoder'
-
-/** A tab's swarm id, as Swarm collaboration named it (its service is gone; the core still records scopes). */
-export const channelTeamId = (tabId: string): string => createHash('sha256').update(`harness-channel-v1:${tabId}`).digest('hex').slice(0, 32)
-
-const LIMIT = 64
-const TTL = 5 * 60_000
-const MAX_TEXT = 256 * 1024
-const fingerprint = (text: string): string => createHash('sha256').update(text.replace(/\r\n/g, '\n').trim()).digest('hex')
-const promptText = (text: string): string => /^\s*<pasted_content id="([a-f0-9]+)">\r?\n([\s\S]*)\r?\n<\/pasted_content id="\1">\s*$/.exec(text)?.[2] ?? text
-
-interface Submission { hash: string | null; teamId: string | null; expires: number; introduction: boolean; questionId?: string }
-interface State {
- draft: string[]
- cursor: number
- known: boolean
- decoder: StringDecoder
- escape: string
- paste: boolean
- submissions: Submission[]
- observedHooks: string[]
- /** Prompts the transcript started before their hook was heard (see `started`). */
- observedStarts: string[]
- current: string | null
- question: string | null
- returns: Map<string, { teamId: string | null; question: string | null }>
-}
-
-/** Origin belongs to a submitted prompt, never to focus or the most recent keystroke.
- * Raw input is only evidence: it must match the prompt the engine actually accepts.
- * Unrecognised editor operations, ambiguous equal prompts and missing provenance fail closed.
- * No terminal bytes are changed, and no prompt text is persisted. */
-export class SwarmPromptScopes {
- private states = new Map<string, State>()
- constructor(private readonly now: () => number = Date.now) {}
- private state(agentId: string): State {
- let state = this.states.get(agentId)
- if (!state) {
- state = { draft: [], cursor: 0, known: true, decoder: new StringDecoder('utf8'), escape: '', paste: false,
- submissions: [], observedHooks: [], observedStarts: [], current: null, question: null, returns: new Map() }
- this.states.set(agentId, state)
- }
- state.submissions = state.submissions.filter(s => s.expires > this.now())
- return state
- }
- current(agentId: string): string | null { return this.states.get(agentId)?.current ?? null }
- forget(agentId: string): void { this.states.delete(agentId) }
- replied(agentId: string, teamId: string, questionId: string): void {
- const state = this.states.get(agentId), key = `${teamId}/${questionId}`
- if (!state || state.question !== key) return
- const previous = state.returns.get(key)
- state.returns.delete(key)
- state.current = previous?.teamId ?? null
- state.question = previous?.question ?? null
- }
-
- /** Called at the actual structured-message write, including queued peer deliveries. */
- prepare(agentId: string, text: string, tabId?: string, deliveryId?: string): () => void {
- const delivery = /^team:([a-f0-9]{32}):([a-f0-9]{32}):(intro|question|answer|consult)$/.exec(deliveryId ?? '')
- const state = this.state(agentId)
- const submission: Submission = { hash: fingerprint(text), teamId: delivery?.[1] ?? (tabId ? channelTeamId(tabId) : null),
- introduction: delivery?.[3] === 'intro', expires: this.now() + TTL,
- ...(delivery?.[3] === 'question' ? { questionId: delivery[2] } : {}) }
- state.submissions.push(submission)
- if (state.submissions.length > LIMIT) state.submissions.shift()
- return () => { state.submissions = state.submissions.filter(s => s !== submission) }
- }
-
- /** Native prompt hooks run before tools. Transcript starts are the fallback and acknowledge
- * already handled hooks without moving scope backwards when the watcher is delayed.
- *
- * And the other way round: a hook can be heard after the transcript started its prompt. The hook gives
- * the daemon 500 ms to answer (hook/notify.mjs) and the engine goes on while the daemon is still
- * matching the hook to its process, so the turn is often on disk first. Taken as a second start of the
- * same prompt, the hook found its message already taken and read as no team: every message from a tab
- * lost its team (e2e/teamsProcess.e2e.ts, once the engines ran the real hook). Each start now
- * acknowledges the other, whichever comes first. */
- started(agentId: string, text: string, source: 'hook' | 'transcript' = 'transcript', engine?: string): void {
- const state = this.state(agentId)
- const hashes = [fingerprint(text)]
- if (engine === 'claude') hashes.push(fingerprint(promptText(text)))
- const heard = source === 'transcript' ? state.observedHooks : state.observedStarts
- const acknowledged = heard.findIndex(hash => hashes.includes(hash))
- if (acknowledged >= 0) { heard.splice(acknowledged, 1); return }
- // Prefer the exact text. A user can literally type Claude's paste-wrapper syntax,
- // and another engine does not attach Claude's envelope semantics to that text.
- const hash = hashes.find(hash => state.submissions.some(s => s.hash === hash)) ?? hashes[0]
- const matches = state.submissions.filter(s => s.hash === hash || s.hash === null)
- state.submissions = state.submissions.filter(s => s.hash !== hash && s.hash !== null)
- // Two identical pending messages can be reordered/edited by an engine's own queue.
- // There is no evidence for which origin won; never choose the first or latest swarm.
- if (matches.length !== 1 || matches[0].hash === null) { state.current = null; state.question = null; state.returns.clear() }
- else if (!matches[0].introduction) {
- const submission = matches[0]
- if (submission.questionId) {
- const key = `${submission.teamId}/${submission.questionId}`
- if (state.question !== key) {
- if (state.returns.size >= LIMIT) state.returns.clear()
- state.returns.set(key, { teamId: state.current, question: state.question })
- }
- state.question = key
- } else { state.question = null; state.returns.clear() }
- state.current = submission.teamId
- }
- const observed = source === 'hook' ? state.observedHooks : state.observedStarts
- observed.push(hash)
- if (observed.length > LIMIT) observed.shift()
- }
-
- raw(agentId: string, bytes: Uint8Array, tabId?: string, pasted = false): void {
- const state = this.state(agentId)
- const insert = (text: string): void => {
- if (!state.known) return
- const chars = [...text]
- if (state.draft.length + chars.length > MAX_TEXT) { state.known = false; state.draft = []; return }
- // Keystrokes append in constant time; a large atomic paste avoids spread-argument limits.
- if (chars.length <= 8192) state.draft.splice(state.cursor, 0, ...chars)
- else state.draft = [...state.draft.slice(0, state.cursor), ...chars, ...state.draft.slice(state.cursor)]
- state.cursor += chars.length
- }
- if (pasted) {
- if (bytes.length > MAX_TEXT) { state.known = false; state.draft = []; return }
- insert(Buffer.from(bytes).toString('utf8')); return
- }
- // The app writes each line key as one string, so ⌥⏎ (and its \n under LNM) is only
- // recognised within this call; a lone Esc followed later by Return fails closed.
- let escaped = false, metaReturn = false
- for (const char of state.decoder.write(Buffer.from(bytes))) {
- if (metaReturn) { metaReturn = false; if (char === '\n') continue }
- if (state.escape) {
- state.escape += char
- if (state.escape === '\x1b[200~') { state.paste = true; state.escape = ''; continue }
- if (state.escape === '\x1b[201~') { state.paste = false; state.escape = ''; continue }
- // The app sends ⇧⏎ as CSI-u and ⌥⏎ as Meta+Return; engines read both as a line break.
- // Inside a paste the engine receives those bytes literally, so they fail closed there.
- if (state.escape === '\x1b[13;2u' && !state.paste) { state.escape = ''; insert('\n'); continue }
- if (state.escape === '\x1b\r' && escaped && !state.paste) { state.escape = ''; insert('\n'); metaReturn = true; continue }
- // SGR mouse reports (focus clicks, wheel) never type text. If a click did move the engine's
- // caret, the draft stops matching the accepted prompt, which still fails closed.
- if (state.escape.startsWith('\x1b[<') && !state.paste) {
- if (/^\x1b\[<[\d;]*$/.test(state.escape) && state.escape.length < 32) continue
- if (/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(state.escape)) { state.escape = ''; continue }
- }
- if (['\x1b', '\x1b[', '\x1b[1', '\x1b[13', '\x1b[13;', '\x1b[13;2', '\x1b[2', '\x1b[20', '\x1b[200', '\x1b[201', '\x1b[3', '\x1bO'].includes(state.escape)) continue
- const sequence = state.escape
- state.escape = ''
- if (sequence === '\x1b[D') state.cursor = Math.max(0, state.cursor - 1)
- else if (sequence === '\x1b[C') state.cursor = Math.min(state.draft.length, state.cursor + 1)
- else if (sequence === '\x1b[H' || sequence === '\x1bOH') state.cursor = 0
- else if (sequence === '\x1b[F' || sequence === '\x1bOF') state.cursor = state.draft.length
- else if (sequence === '\x1b[3~') state.draft.splice(state.cursor, 1)
- // ⌥⌫ (\x1b\x7f) fails closed too: engines may disagree on word boundaries.
- else { state.known = false; state.draft = [] }
- continue
- }
- if (char === '\x1b') { state.escape = char; escaped = true; continue }
- if (state.paste) { insert(char); continue }
- if (char === '\r') {
- if (state.known && state.draft.length) this.prepare(agentId, state.draft.join(''), tabId)
- else if (!state.known) {
- // A recalled/edited prompt might equal an older pending prompt. Retain the uncertainty
- // until the engine accepts input; matching that older text alone would assign its swarm.
- state.submissions.push({ hash: null, teamId: null, introduction: false, expires: this.now() + TTL })
- if (state.submissions.length > LIMIT) state.submissions.shift()
- }
- state.draft = []; state.cursor = 0; state.known = true
- } else if (char === '\x03') {
- state.draft = []; state.cursor = 0; state.known = true
- } else if (char === '\x7f' || char === '\b') {
- if (state.cursor > 0) state.draft.splice(--state.cursor, 1)
- } else if (char === '\x01') state.cursor = 0
- else if (char === '\x05') state.cursor = state.draft.length
- else if (char === '\x15') { state.draft.splice(0, state.cursor); state.cursor = 0 }
- else if (char === '\x0b') state.draft.splice(state.cursor)
- else if (char === '\n') insert(char)
- else if (char < ' ' || char === '\x7f') { state.known = false; state.draft = [] }
- else insert(char)
- }
- }
-}
diff --git a/desktop/lib/terminal/terminal_session.dart b/desktop/lib/terminal/terminal_session.dart
index ffbdc66de..494fbb500 100644
--- a/desktop/lib/terminal/terminal_session.dart
+++ b/desktop/lib/terminal/terminal_session.dart
@@ -150,10 +150,6 @@ class TerminalSession extends ChangeNotifier {
final TerminalFrameSender send;
final TerminalBinarySender sendBinary;
- /// Set by the view receiving input. Capture it with the bytes, before any async send.
- String? inputTabId;
- String? _bufferedInputTabId;
- bool _swarmInput = false;
final Duration resyncTimeout;
final bool readOnly;
@@ -568,7 +564,6 @@ class TerminalSession extends ChangeNotifier {
// Which kind of stream came back. A watcher renders the terminal and
// may not type into it; the band says who has it and offers to ask.
watching = payload['readOnly'] == true;
- _swarmInput = payload['swarmInput'] == true;
// The claim is spent here: from now on this session holds the lease,
// and every later open of its own rests on holding it rather than on a
// gesture nobody has made since. See [takeover].
@@ -1019,13 +1014,12 @@ class TerminalSession extends ChangeNotifier {
/// the injection from there: it adapts slash commands to the pane's engine and retries the
/// submit Enter. A client typing bytes can do neither — which is exactly how Codex ended up
/// holding a composed line unsent, its Enter arriving in the same read as the text.
- Future<bool> sendComposerText(String text, {String? tabId}) async {
+ Future<bool> sendComposerText(String text) async {
if (!acceptsInput) return false;
final content = text.trimRight();
if (content.trim().isEmpty) return false;
return send('message', {
'content': content,
- 'tabId': ?(tabId ?? inputTabId),
'agentId': agentId,
'mode': 'auto',
});
@@ -1048,7 +1042,7 @@ class TerminalSession extends ChangeNotifier {
///
/// The caller must check [MachineState.terminalPasteRawAvailable] first: an older CLI does not know
/// this binary kind at all, so sending it there would silently go nowhere.
- Future<bool> pasteText(String text, {String? tabId}) async {
+ Future<bool> pasteText(String text) async {
if (!acceptsInput) return false;
// Forwarded verbatim, including a stray 0x03 — same as _onTerminalOutput/sendComposerText.
if (text.isEmpty) return false;
@@ -1057,7 +1051,6 @@ class TerminalSession extends ChangeNotifier {
final generation = _generation;
final frame = TerminalBinaryFrame(
kind: TerminalBinaryKind.paste,
- tabId: _swarmInput ? (tabId ?? inputTabId) : null,
streamId: currentStreamId,
// Unused server-side (a paste is one self-contained unit, not part of the ordered keystroke
// stream `input`'s seq guards) — kept at 0 rather than threading a second counter for a field
@@ -1223,11 +1216,6 @@ class TerminalSession extends ChangeNotifier {
void _onTerminalOutput(String data) {
if (!acceptsInput || data.isEmpty) return;
- final origin = _swarmInput ? inputTabId : null;
- if (_inputBytes.isNotEmpty && _bufferedInputTabId != origin) {
- unawaited(_flushInput());
- }
- _bufferedInputTabId = origin;
final bytes = utf8.encode(data);
final isBoundary =
data.contains('\r') ||
@@ -1272,7 +1260,6 @@ class TerminalSession extends ChangeNotifier {
return;
}
final bytes = List<int>.from(_inputBytes);
- final origin = _bufferedInputTabId;
_inputBytes.clear();
_lastInputFlushAt = inputClockForTest();
final currentStreamId = streamId;
@@ -1307,7 +1294,6 @@ class TerminalSession extends ChangeNotifier {
final end = min(offset + kInputFrameMaxBytes, bytes.length);
final frame = TerminalBinaryFrame(
kind: TerminalBinaryKind.input,
- tabId: origin,
streamId: currentStreamId,
seq: _inputSeq++,
bytes: Uint8List.fromList(bytes.sublist(offset, end)),
diff --git a/desktop/lib/widgets/terminal_composer.dart b/desktop/lib/widgets/terminal_composer.dart
index 312645101..f535d9cc7 100644
--- a/desktop/lib/widgets/terminal_composer.dart
+++ b/desktop/lib/widgets/terminal_composer.dart
@@ -23,13 +23,11 @@ class TerminalComposer extends StatefulWidget {
required this.session,
required this.focusNode,
this.inputEnabled = true,
- this.tabId,
});
final TerminalSession session;
final FocusNode focusNode;
final bool inputEnabled;
- final String? tabId;
@override
State<TerminalComposer> createState() => _TerminalComposerState();
@@ -101,7 +99,7 @@ class _TerminalComposerState extends State<TerminalComposer> {
if (text.isEmpty) return;
_sending = true;
try {
- if (!await widget.session.sendComposerText(text, tabId: widget.tabId)) {
+ if (!await widget.session.sendComposerText(text)) {
return;
}
_controller.clear();
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index 9c5c24f7a..5b73a86e0 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -405,9 +405,6 @@ class _TerminalPanelState extends State<TerminalPanel>
@override
void didUpdateWidget(TerminalPanel oldWidget) {
super.didUpdateWidget(oldWidget);
- if (widget.visible && (_focusNode.hasFocus || _composerFocus.hasFocus)) {
- widget.session.inputTabId = widget.paneLocation?.$1;
- }
if (!identical(oldWidget.notifier, widget.notifier)) {
oldWidget.notifier.modelStarts.removeListener(_onModelStartsChanged);
widget.notifier.modelStarts.addListener(_onModelStartsChanged);
@@ -756,7 +753,6 @@ class _TerminalPanelState extends State<TerminalPanel>
/// Typing in the composer focuses the tile, exactly like clicking into the terminal does.
void _handleComposerFocusChange() {
if (_composerFocus.hasFocus) {
- widget.session.inputTabId = widget.paneLocation?.$1;
widget.onRendererFocus?.call();
}
}
@@ -764,7 +760,6 @@ class _TerminalPanelState extends State<TerminalPanel>
void _handleFocusChange() {
_syncCursorBlink();
if (_focusNode.hasFocus) {
- widget.session.inputTabId = widget.paneLocation?.$1;
widget.onRendererFocus?.call();
}
}
@@ -1738,7 +1733,6 @@ class _TerminalPanelState extends State<TerminalPanel>
/// clipboard than this one — see `MachineState.isLocalMachine`.
Future<void> _paste() async {
final target = widget.session;
- final origin = widget.paneLocation?.$1;
final streamId = target.streamId;
bool stillOwnsPaste() =>
mounted &&
@@ -1769,7 +1763,7 @@ class _TerminalPanelState extends State<TerminalPanel>
final machine = widget.notifier.stateOf(target.machineId);
_controller.clearSelection();
if (machine != null && machine.terminalPasteRawAvailable) {
- await target.pasteText(text, tabId: origin);
+ await target.pasteText(text);
} else {
target.terminal.paste(text);
}
@@ -1842,7 +1836,6 @@ class _TerminalPanelState extends State<TerminalPanel>
/// platform's exact one: Linux reserves Ctrl-V for the terminal program and pastes with
/// Ctrl-Shift-V.
KeyEventResult _onTerminalKey(FocusNode node, KeyEvent event) {
- widget.session.inputTabId = widget.paneLocation?.$1;
if (_passageId != null && event.logicalKey == LogicalKeyboardKey.escape) {
if (event is KeyDownEvent) _closePassage();
return KeyEventResult.handled;
@@ -2412,7 +2405,6 @@ class _TerminalPanelState extends State<TerminalPanel>
ColoredBox(
color: grid.AppPalette.windowBg,
child: TerminalComposer(
- tabId: widget.paneLocation?.$1,
session: session,
focusNode: _composerFocus,
inputEnabled: !widget.readOnly,
diff --git a/desktop/test/harness_attachments_test.dart b/desktop/test/harness_attachments_test.dart
index d7d947504..c5873be4f 100644
--- a/desktop/test/harness_attachments_test.dart
+++ b/desktop/test/harness_attachments_test.dart
@@ -42,13 +42,13 @@ class _RecordingSession extends TerminalSession {
}
@override
- Future<bool> pasteText(String text, {String? tabId}) async {
+ Future<bool> pasteText(String text) async {
calls.add('paste:$text');
return true;
}
@override
- Future<bool> sendComposerText(String text, {String? tabId}) async {
+ Future<bool> sendComposerText(String text) async {
calls.add('send:$text');
return true;
}
diff --git a/desktop/test/route_send_test.dart b/desktop/test/route_send_test.dart
index d8accc070..c00d6b95d 100644
--- a/desktop/test/route_send_test.dart
+++ b/desktop/test/route_send_test.dart
@@ -28,7 +28,7 @@ class _Pane extends TerminalSession {
bool get acceptsInput => true;
@override
- Future<bool> sendComposerText(String text, {String? tabId}) async {
+ Future<bool> sendComposerText(String text) async {
typed.add(text);
return true;
}
diff --git a/desktop/test/swarm_prompt_scope_test.dart b/desktop/test/swarm_prompt_scope_test.dart
deleted file mode 100644
index 5de010284..000000000
--- a/desktop/test/swarm_prompt_scope_test.dart
+++ /dev/null
@@ -1,122 +0,0 @@
-import 'dart:convert';
-import 'dart:typed_data';
-
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/terminal/terminal_binary.dart';
-import 'package:harness/terminal/terminal_session.dart';
-
-void main() {
- const stream = '00112233-4455-6677-8899-aabbccddeeff';
- late TerminalSession session;
- late List<TerminalBinaryFrame> frames;
- late List<({String type, Map<String, dynamic> payload})> messages;
-
- setUp(() {
- frames = [];
- messages = [];
- session = TerminalSession(
- machineId: 'machine',
- agentId: 'shared-session',
- agentName: 'Codex',
- engineId: 'codex',
- now: () => DateTime(2026, 9, 28),
- send: (type, payload) async {
- messages.add((type: type, payload: payload));
- return true;
- },
- sendBinary: (frame) async {
- frames.add(frame);
- return true;
- },
- );
- });
- tearDown(() => session.dispose());
-
- Future<void> ready({bool scoped = true}) async {
- await session.open(initialCols: 100, initialRows: 30);
- await session.handleFrame('terminal_ready', {
- 'requestId': messages.single.payload['requestId'],
- 'protocolVersion': 3,
- 'streamId': stream,
- 'agentId': 'shared-session',
- 'swarmInput': scoped,
- });
- await session.handleBinary(
- TerminalBinaryFrame(
- kind: TerminalBinaryKind.keyframe,
- streamId: stream,
- seq: 0,
- bytes: Uint8List(0),
- compressed: false,
- cols: 100,
- rows: 30,
- ),
- );
- }
-
- test('a shared session captures each view’s origin before coalescing and async sends', () async {
- await ready();
- session.inputTabId = 'swarm-a';
- session.terminal.textInput('first');
- session.terminal.textInput(' second');
- session.inputTabId = 'swarm-b';
- session.terminal.textInput(' third');
- session.inputTabId =
- 'swarm-c'; // Looking elsewhere never retargets pending bytes.
- await Future<void>.delayed(const Duration(milliseconds: 20));
- final input = frames
- .where((frame) => frame.kind == TerminalBinaryKind.input)
- .toList();
- expect(input.map((frame) => frame.tabId), [
- 'swarm-a',
- 'swarm-a',
- 'swarm-b',
- ]);
- expect(
- input.map((frame) => utf8.decode(frame.bytes)).join(),
- 'first second third',
- );
- expect(input.map((frame) => frame.seq), [0, 1, 2]);
- });
-
- test('composer and delayed clipboard submissions carry their explicit source pane', () async {
- await ready();
- session.inputTabId = 'swarm-b';
- await session.sendComposerText('task from A', tabId: 'swarm-a');
- expect(messages.last.payload, containsPair('tabId', 'swarm-a'));
- await session.pasteText('clipboard from A', tabId: 'swarm-a');
- expect(frames.last.tabId, 'swarm-a');
- expect(session.inputTabId, 'swarm-b');
- });
-
- test('older daemons receive the original binary format', () async {
- await ready(scoped: false);
- session.inputTabId = 'swarm-a';
- session.terminal.textInput('hello');
- await Future<void>.delayed(const Duration(milliseconds: 20));
- expect(
- frames.where((f) => f.kind == TerminalBinaryKind.input).single.tabId,
- isNull,
- );
- });
-
- test('scoped local input matches the CLI wire fixture and rejects truncated metadata', () {
- final encoded = encodeTerminalLocal(
- TerminalBinaryFrame(
- kind: TerminalBinaryKind.input,
- streamId: stream,
- seq: 3,
- bytes: Uint8List.fromList(utf8.encode('xin chào\r')),
- compressed: false,
- tabId: 'swarm-a',
- ),
- )!;
- expect(
- encoded.map((b) => b.toRadixString(16).padLeft(2, '0')).join(),
- '4854524c010102000000002a00112233445566778899aabbccddeeff000000000000000307737761726d2d6178696e206368c3a06f0d',
- );
- expect(decodeTerminalLocal(encoded)?.tabId, 'swarm-a');
- encoded[36] = 129;
- expect(decodeTerminalLocal(encoded), isNull);
- });
-}
diff --git a/docs/agent-teams-live-verification.md b/docs/agent-teams-live-verification.md
deleted file mode 100644
index 222407ff0..000000000
--- a/docs/agent-teams-live-verification.md
+++ /dev/null
@@ -1,66 +0,0 @@
-# Native Team verification — September 27, 2026
-
-> **Replaced** on October 10, 2026 by [Agent Messages](design/2026-10-10-agent-messages.md): `harness send` between harnesses in a tab. Kept as the record of Swarm collaboration; `harness team` and `harness channel` no longer exist.
-
-Status: **The complete Claude → Codex/Grok → Claude acceptance passed.** Grok's login was
-renewed by the user before the full run. The fixture exited successfully and recorded
-`passed: true` and `fullAcceptance: true`.
-
-The approved test used disposable project directories, a separate tmux server, the actual
-Claude Code 2.1.283, Codex 0.154.0, and Grok 1.0.34 binaries, the production session-input controller,
-the production transcript normalizers, the real local daemon WebSocket, and durable Team
-records. Claude was not given either peer project's contents. Each peer's `FACT.txt` held a
-different new random string known to the test verifier.
-
-| Evidence | Recorded value |
-| --- | --- |
-| Team | `7fda3704c78f71fd272019b8c482b945` |
-| Question to Grok | `11111111111111111111111111111111` |
-| Question to Codex | `22222222222222222222222222222222` |
-| Asking member | Claude |
-| Addressed members | Grok and Codex |
-| Question text | What is the exact content of your FACT.txt? |
-| Grok's explicit agent reply | `GROK_FACT_29d8f96797908344` |
-| Codex's explicit agent reply | `CODEX_FACT_e85e3f8ae7796361` |
-| Claude's `RESULT.txt` | Both exact values, one per line |
-| Question states | Both `answered` |
-| Question receipts | Both `received`; Grok read its inbox, Codex replied to the delivered question |
-| Return receipts | Both `received` through Claude's `wait` commands |
-| Introduction receipts | All three reached `started`; Grok and Claude later reached `received` |
-| Observed Grok turns | 2 started, 2 ended |
-| Observed Codex turns | 3 started, 3 ended |
-| Observed Claude turns | 2 started; output written during the second turn |
-| Fixture cleanup | Servers stopped; dedicated Grok socket and copied Codex/Grok authentication files absent |
-| Full three-engine acceptance | `true` |
-
-Each answer was attributed to the addressed agent and correlated with its original question.
-Claude's observed tool calls asked both peers, waited for their correlated answers, then
-used `printf` to write both values into `RESULT.txt` and read the result back. No tool call
-read either peer's directory. This demonstrates continuation of the original task. The test
-ended once that artifact and its corresponding explicit answers were verified; it did not
-wait for Claude's final conversational response. No existing user session was connected or
-restarted, and no release was deployed.
-
-The local evidence bundle is at
-`/private/var/folders/4c/lq3h60sn5l53hs3s21nzpqzw0000gn/T/harness-team-native-hxn1ml/evidence.json`.
-The raw provider conversations remain in their disposable project/session locations. This
-document intentionally contains no authentication tokens or membership keys.
-
-Earlier diagnostic runs exposed a Codex empty-composer detection issue and Claude paste-envelope
-attribution issue. Both were fixed with regression tests based on the observed terminal/transcript forms.
-The complete Team/input/encryption regression run after those fixes passed 96 tests, and the
-CLI plus native-test script passed typechecking. The full live run used both fixes: every
-introduction was attributed to a matching native turn. The remaining manual UI and physical
-remote-device verification limits are listed in [the operating guide](agent-teams.md#verification-status).
-
-To reproduce the full run with authorized provider usage and working provider logins:
-
-```sh
-cd cli
-HARNESS_TEAM_LIVE=1 npx tsx scripts/team-native-e2e.ts
-```
-
-The earlier two-engine diagnostic also passed, with evidence at
-`/private/var/folders/4c/lq3h60sn5l53hs3s21nzpqzw0000gn/T/harness-team-native-Y2OPl4/evidence.json`.
-`HARNESS_TEAM_ENGINES=codex,claude` selects that partial mode; its evidence reports
-`fullAcceptance: false` and does not replace the complete three-engine gate.
diff --git a/docs/agent-teams.md b/docs/agent-teams.md
deleted file mode 100644
index fb1d86c32..000000000
--- a/docs/agent-teams.md
+++ /dev/null
@@ -1,268 +0,0 @@
-# Agent teams
-
-> **Replaced** on October 10, 2026 by [Agent Messages](design/2026-10-10-agent-messages.md): `harness send` between harnesses in a tab. Kept as the record of Swarm collaboration; `harness team` and `harness channel` no longer exist.
-
-Implementation and operating guide, September 27, 2026. Verification limits are recorded below.
-
-## Default experience: swarm tabs
-
-The default UI now uses [swarm tabs](tab-channels.md), September 28, 2026.
-Existing tab membership replaces manual team setup. Settings → Experimental → Swarm
-collaboration is off by default. Once enabled, agents consult peers in their tab
-automatically. Questions stay inside the tab; cross-swarm requests and Cmd+Shift+A
-are deferred. The conversation view shows shared history. The protocol
-below also supports standalone teams managed through the advanced CLI.
-
-Agents retain their own engine, context, repository, and session. For example, mobile
-asks the daemon agent which endpoint returns daemon state, that agent explicitly
-replies, and the answer returns to mobile so it can continue its task. The durable
-ledger records delivery separately from a correlated answer.
-
-## Contract (team.v1)
-
-1. **Ownership.** One machine daemon owns a team's roster and exchange ledger. Members are
- addressed by stable `(machineId, agentId)`; a display name, window, pane index, or vendor
- conversation ID is never a routing address. Multiple teams can include the same agent.
-2. **Scope.** Standalone teams explicitly connect members; tab channels derive them from the saved desk. An agent's membership capability only
- grants reads and communication inside that team, including answers for that member. Team
- management remains an owner operation. All participants run under the person's existing
- Harness authority; membership is not an OS sandbox between same-user processes.
-3. **Transport.** The daemon exposes `team` and `team_delivery` RPCs over existing local and
- paired E2EE machine transports. Remote bodies, member capabilities, replies, and ledgers
- never travel as plaintext through the backend. Shared observation connections cannot write.
- No new cloud database, service, or model subscription is needed.
-4. **Engine boundary.** Shell commands are the universal adapter. A team introduction teaches
- existing agents `members`, `ask`, `inbox`, `reply`, and `status` without restarting engines,
- rewriting their settings, or reading another engine's private conversation. Claude, Codex,
- Grok, and other shell-capable agents use the same protocol. Ordinary terminal shells cannot
- be automatic answering members. An MCP adapter could wrap these operations later; this
- implementation uses the CLI and does not install vendor-specific tools or settings.
-5. **Durability.** Reserve every team, question, answer, and delivery before external effects.
- Persist privately and atomically. A repeated operation ID with the same content returns the
- existing record; conflicting reuse fails. A daemon restart never blindly repeats an
- uncertain terminal submission. Queued-but-unsent work can resume. Corrupt state is preserved
- and reported, not treated as an empty successful team.
-6. **Delivery.** Use bounded, per-session serialization. Never send interrupt/cancel keys or
- overwrite a human draft. Wait while a member is working, presenting a permission/question
- dialog, has a draft, or is unavailable. Recheck at the actual write boundary. Distinguish
- queued, delivered, started, rejected, and unknown. Terminal submission and turn completion
- cannot constitute an answer.
-7. **Answers.** Only an explicit, correlated `reply` answers a question. An answer carries its
- author, timestamp, text, and optional evidence references. Duplicate identical replies are
- harmless; conflicting replies and replies by the wrong member fail. Answers are peer
- context, never a replacement for the user's instructions or permission to deploy/publish.
-8. **Continuation.** A question defaults to asynchronous delivery. The asking agent can keep
- working; a separate tracked answer delivery resumes it when safe. A bounded `wait` reads the
- ledger and inbox. Incoming questions break the wait so the agent can answer them, avoiding
- mutual-wait deadlocks. Reading/claiming an inbox item suppresses an unsent terminal notice.
- A retrieved answer suppresses an unsent continuation notice.
-9. **Bounds.** Limit roster size, text/evidence sizes, outstanding requests, and retained
- exchanges. Requests have deadlines and optional parent question IDs with bounded depth.
- No automatic broadcasts, model polls, or endless agent reply loops. Pause holds new sends
- and withdraws queued terminal writes; resume only releases known-unsent work.
-10. **Failure.** Offline, unpaired, busy, draft, expired, cancelled, and uncertain states are
- visible and actionable. Cancellation stops unsent notices, never interrupts an agent's
- unrelated task. Late answers remain attributable but do not automatically resume cancelled
- or expired work. Closing UI, timing out a poll, and losing an RPC reply do not cancel or
- resend work. Retry uses the original operation ID.
-11. **Clients.** Desktop and browser share the existing Flutter workspace. Mobile presents the
- same roster and exchanges through its daemon connection. CLI provides readable output,
- structured JSON, and a terminal conversation view. All clients reconstruct from daemon
- state and ignore older revisions. Controls explain old-daemon incompatibility.
-12. **Verification.** Exercise real cross-engine question → reply → continuation in isolated
- sessions; test restart, duplicate requests, wrong-member replies, busy/draft/dialog safety,
- cancellation, expiry, deadlock avoidance, remote encryption, and UI reconnect/keyboard and
- visual behavior. Synthetic transcripts and green unit tests alone do not establish live
- engine support. Never use the person's ongoing sessions as disposable test fixtures.
-
-## Components
-
-`cli/src/teams/` owns the protocol model, private ledger, participant mailboxes, command
-adapter, prompts, and tests. `BackendSocket` supplies the existing authenticated transport
-and registry. The existing session-input controller supplies serialized terminal writes,
-with a team-only preflight that preserves drafts and dialogs. Remote delivery uses the
-existing machine relay; each destination owns and deduplicates its local terminal receipts.
-
-Team UI is a projection of the ledger. It retains operation IDs across uncertain replies,
-shows question state separately from delivery state, and keeps the user's draft while
-refreshing. Standalone team membership is independent of pane visibility and can span paired machines. Tab channels follow saved tab membership instead.
-Capabilities remain in private daemon records and the relevant member's introduction; they
-are omitted from public snapshots, RPC frame logs, and ordinary UI. The selected agent's own
-conversation and shell commands include its key, so connecting a member shares that team's
-context with the member's existing engine/provider. Removing a member revokes its key. Adding
-the same session again creates a new membership and key; old exchanges remain attributable.
-
-## Advanced standalone teams
-
-The main desktop/web and phone entries open tab channels. Standalone teams remain
-available through the CLI for explicit groups that do not follow tab membership.
-Their original creation/editing widgets remain in the implementation for compatibility
-and tests; the default channel view has no creation form or human question composer.
-
-Standalone team creation sends the selected agents introductions. Pausing holds
-known-unsent deliveries, membership edits change the explicit roster, and archiving
-retains the record while cancelling pending work. Tab channel membership instead
-follows the saved desk and permits already-started exchanges to finish after departure;
-see the channel guide for that extension and its backend activation.
-
-The CLI is also a complete client. `harness team --help` lists commands. For example, create
-`team.json` using actual machine and agent IDs from the sessions you intend to connect:
-
-```json
-{
- "id": "ad185a5b4dc24492bc1c080681efdb32",
- "name": "Build Harness",
- "members": [
- {"machineId": "YOUR_MACHINE_ID", "agentId": "DAEMON_AGENT_ID", "name": "daemons", "role": "Daemon protocol and APIs"},
- {"machineId": "YOUR_MACHINE_ID", "agentId": "MOBILE_AGENT_ID", "name": "mobile", "role": "Phone client and mobile UX"}
- ]
-}
-```
-
-```sh
-harness team create --file team.json --json
-harness team --team ad185a5b4dc24492bc1c080681efdb32 members
-harness team --team ad185a5b4dc24492bc1c080681efdb32 watch
-```
-
-`watch` is a read-only TUI: use Up/Down or j/k to select an exchange, r to refresh, q or Esc
-to close. In redirected output, use `get --json` instead. Pass `--machine MACHINE_ID` when
-the team belongs to another paired machine. `--port` selects a different local daemon.
-
-Agents use the exact command prefix in their introduction. It includes the owner machine,
-team, and private member key, so `ask daemons 'Which endpoint returns daemon state?'`
-automatically identifies the sender. `reply QUESTION_ID 'The endpoint is …' --evidence
-'path/to/file.ts:42'` records the answer. Use `--text-file PATH` for multiline text. `inbox`
-reads pending questions and recent answers; `wait QUESTION_ID --seconds 30` yields incoming
-questions first and never cancels a request on timeout. The owner CLI can initiate an ask
-with `--from MEMBER_ID`; `members` provides membership IDs, which differ from agent IDs.
-
-For an uncertain create, ask, or add, reuse its operation ID and identical content. CLI
-errors include `operationId`; keep it as `id` in a create/add JSON file or use `ask --id`.
-The UI retains these attempts and offers **Check connection**, **Check send**, or
-**Check teammate**, including after closing and reopening the workspace in the same app
-session. After restarting the app, inspect the ledger before creating a replacement.
-
-## Protocol and recovery
-
-`team` requests carry an `action`, `requestId`, and (except list/create/capabilities)
-`teamId`. A member supplies `memberKey`; owner connections omit it. The transport returns
-`team_result` with the matching request ID and either a result or `{error, detail}`.
-`capabilities` returns `protocol: "team.v1"`. Team snapshots contain a monotonic revision
-and omit membership keys. `team_delivery` is the owner-to-destination RPC for runtime
-inspection, submission, status, hold/release, cancellation, and inbox consumption.
-
-An agent ask is a payload such as:
-
-```json
-{
- "action": "ask",
- "teamId": "ad185a5b4dc24492bc1c080681efdb32",
- "memberKey": "PRIVATE_MEMBER_KEY",
- "id": "2c9a4efb568e41aeb15791672d35d875",
- "to": "daemons",
- "text": "Which endpoint returns daemon state?",
- "context": "I am implementing the phone's daemon list.",
- "ttlMs": 900000
-}
-```
-
-`reply` uses `questionId`, `text`, and optional `evidence: [...]`. Only the addressed member
-can answer as that agent. An owner reply also names `memberId` and is attributed to the
-user. A late answer is retained, with `late: true`, without automatically continuing expired
-or cancelled work. `notify: false` on an ask permits explicit inbox/status retrieval without
-an answer notification. `parentId` links a follow-up to an exchange involving the sender.
-
-Delivery states are observations, separate from question state. **Queued** can mean busy,
-offline, draft, permission dialog, or temporary input queue pressure. **Agent accepted input**
-means a matching turn was observed, not that the question was answered. **Read in inbox**
-means the member retrieved the record. **Delivery unconfirmed** means it might have reached
-the terminal: inspect that member or have it read `inbox`/`status`; do not invent a new ID and
-resend. Reading suppresses a notice only if it has not already been pasted. The final write
-guard rechecks the receipt and captured terminal state; it cannot make a physical keyboard
-and terminal paste atomic.
-
-The owner stores private records under the daemon data directory's `teams/` tree. Each
-destination stores its own private delivery records there. Directories are mode 0700 and
-records 0600, written by atomic rename with file and directory synchronization on Unix.
-After a restart, known-unsent notices resume; uncertain writes remain uncertain. Corrupt
-files produce an error and remain intact for recovery. No background retention deletion is
-performed. Back up the team state before manual repair; deleting receipts can remove the
-evidence that prevents a duplicate delivery.
-
-Bounds are explicit: 100 retained teams per owner, 32 retained memberships and 500 exchanges
-per team, 8 pending questions per sender, 30 questions per minute per team, and at most four
-questions in a parent chain. Question/context fields each allow 8,000 characters; answers
-16,000; evidence 16 references of at most 1,024 characters each. Terminal notices fit 24 KB
-and link to the full ledger text when excerpted. Question deadlines default to 15 minutes
-and range from 10 seconds to 24 hours. Introductions and answer notices expire after 24 hours.
-Each destination retains at most 10,000 delivery records and accepts at most 32 queued or
-submitted notices per agent. Archive retains history and therefore does not reclaim these
-limits. Exhaustion is an explicit error, not silent history loss.
-
-## Verification status
-
-Implemented: daemon protocol and recovery, encrypted relay framing, queued terminal input,
-CLI/TUI, desktop/web workspace, and the self-contained mobile client. No existing user
-session has been connected, restarted, or used as a test fixture. No release has been deployed.
-
-Automated checks exercise durable replay, conflicting IDs, wrong-member replies, explicit
-human attribution, late answers, removal/rejoin, pause/cancel/expiry races, draft/dialog/busy
-safety, queue pressure, inbox consumption, and mutual-wait handling. Transport tests use a
-real loopback WebSocket server. Relay tests perform actual pairing and encrypted round trips
-with team bodies and capabilities, including replay rejection. A two-daemon fixture
-(`cli/src/teams/remote.spec.ts`) also drives the full question → explicit reply → continuation
-path through real local WebSocket APIs, `RemoteRelayPool`, and `BackendSocket` instances.
-It pairs disposable client identities, routes the recipient's reply through its own local
-daemon back to the owner, checks duplicate-reply suppression, and asserts that bodies and
-membership keys are absent from relay-visible frames. Only the cloud's opaque routing and
-agent terminal behavior are simulated. This passed locally; it does not establish behavior
-on physical remote machines or at model providers.
-
-CLI typechecking and builds passed. The full CLI suite passed 4,911 tests, with one unrelated
-Hermes hook fixture failure (missing temporary registry file); that test passed when rerun
-in isolation. The focused Team/input/encryption run passed 123 tests; both TUI tests passed
-after the final roster-layout improvement. The additional complete paired-relay fixture
-passed. Desktop regression tests passed (82 tests before the final additional encryption case); final Team
-and encryption tests passed (18 tests). Phone Team/controller/event/encryption tests passed
-(17 tests). Static analysis of the changed desktop and phone code passed. Widget
-checks cover 320/390-pixel phone widths, desktop narrow/wide layouts, active theme variants,
-large terminal fonts, explicit Connect, keyboard close, refresh, and preserved drafts.
-Rendered desktop and phone fixtures were visually inspected. Screen-reader interaction and
-physical native keyboard/IME behavior have not been manually exercised.
-
-Normal macOS debug and web production builds succeeded. The macOS artifact is
-`desktop/build/macos/Build/Products/Debug/Harness.app`; web output is `desktop/build/web`.
-No Android/iOS release build or browser-device interaction test was performed.
-
-**The complete live Claude/Codex/Grok acceptance passed.** After explicit user approval and
-renewing Grok's login, the native test drove Claude Code 2.1.283, Codex 0.154.0, and Grok 1.0.34
-in disposable tmux sessions. Claude asked each peer for a different random value in its private
-fixture file. Both peers explicitly replied through the daemon, and Claude retrieved the
-correlated answers and wrote both exact values into `RESULT.txt`. Question and return receipts
-became `received`; all three introductions were attributed to matching native turns. The fixture
-exited successfully and removed its copied authentication files. See the
-[live verification record](agent-teams-live-verification.md) for identifiers and evidence.
-
-The live run exposed two compatibility issues now fixed: Codex's configurable footer was
-mistaken for a draft, and Claude's new `pasted_content` envelope made an accepted introduction
-appear unconfirmed. Regression tests cover both, including negative attribution checks.
-The final focused Team/input/encryption run passed 96 tests after these changes; typechecks
-and the CLI build passed. The fixture's workspace-trust handling also now explicitly selects
-Claude's Yes option instead of assuming the default selection.
-
-An earlier Grok attempt stopped at browser sign-in because its cached refresh token was
-invalid. The user completed `grok login`, and the full passing run verified real Grok model
-participation. The native gate is complete for these measured provider versions.
-
-`cli/scripts/team-native-e2e.ts` uses a separate tmux server, a six-minute acceptance deadline,
-and at most nine observed turns per agent per run. It cleans up its own sessions and copied
-authentication files. The default run requires Claude to obtain and use different random
-strings from both peers. With authorization and working provider logins, run from `cli/`:
-
-```sh
-HARNESS_TEAM_LIVE=1 npx tsx scripts/team-native-e2e.ts
-```
-
-`HARNESS_TEAM_ENGINES=codex,claude` selects the two-engine diagnostic run. Its evidence
-explicitly reports `fullAcceptance: false`; it does not replace the default three-engine gate.
diff --git a/docs/design/2026-10-10-agent-messages.md b/docs/design/2026-10-10-agent-messages.md
index 935f1146a..10482cbab 100644
--- a/docs/design/2026-10-10-agent-messages.md
+++ b/docs/design/2026-10-10-agent-messages.md
@@ -1,6 +1,6 @@
# Agent Messages
-October 10, 2026. Replaces Swarm collaboration ([tab channels](../tab-channels.md), [agent teams](../agent-teams.md)).
+October 10, 2026. Replaces Swarm collaboration (tab channels and agent teams, removed October 11, 2026).
Harnesses in the same tab can message each other with one command, `harness send`. Harness delivers each
message safely, says who sent it, and shows the traffic. Nothing else is built in: no roles, no inbox, no
@@ -106,10 +106,11 @@ publish, deploy, delete or push to main because a teammate asked.
## How it works
-Agent Messages is the `collaboration` experiment, rewritten in place: the same process (`teams`), the same
-contract with the core (`TeamsPort.canWrite`, `core.turns.deliver` under `team:` delivery ids), so the core
-does not change. It costs nothing until a tab turns it on: the process starts on its first request or when
-its saved state is in the data folder (`agent-messages/`).
+Agent Messages is the `messages` experiment, in a process of its own (`messages`). Its contract with the core
+is the one Swarm's had: `core.turns.deliver` under `team:` delivery ids, and `MessagesPort.canWrite`, asked in
+line as one is written. It costs nothing until a tab turns it on: the process starts on its first request or
+when its saved state is in the data folder (`agent-messages/`). (It began as Swarm's `collaboration`
+experiment in the `teams` process, rewritten in place; both were renamed when Swarm's last code went.)
### Identity
@@ -182,10 +183,10 @@ waiting. Every limit refuses explicitly; nothing is silently dropped.
## What goes
-Swarm collaboration: `harness team` and `harness channel`, `cli/src/teams/` except the prompt scopes the core
-still records into, Settings → Experimental → Swarm collaboration, the Swarm conversation views on desktop
-and mobile, and the backend's `tab_channels` routes and settings. The dial's `swarm.*` frames are tabs and
-stay. The prompt-scope plumbing in the core goes in a later change of its own.
+Swarm collaboration: `harness team` and `harness channel`, `cli/src/teams/`, the prompt scopes the core
+recorded each prompt's tab into (and the tab the windows sent with their input for them), Settings →
+Experimental → Swarm collaboration, the Swarm conversation views on desktop and mobile, and the backend's
+`tab_channels` routes and settings. The dial's `swarm.*` frames are tabs and stay.
## Delivery plan
@@ -193,7 +194,8 @@ stay. The prompt-scope plumbing in the core goes in a later change of its own.
CLI removed.
2. Desktop: the tab's ⇄ and revealed state (macOS titlebar and the Flutter tab row), the menus, Show Agent
Messages, pane marks, and Swarm's views and setting removed.
-3. Mobile and cleanup: the log on the phone, the backend's `tab_channels`, the core's prompt scopes.
+3. Cleanup: the phone's Swarm views, the backend's `tab_channels`, the core's prompt scopes. The phone shows
+ no message log: the owner dropped it (October 11, 2026).
## Verification
diff --git a/docs/tab-channels.md b/docs/tab-channels.md
deleted file mode 100644
index 66d65b59e..000000000
--- a/docs/tab-channels.md
+++ /dev/null
@@ -1,208 +0,0 @@
-# Swarm collaboration
-
-> **Replaced** on October 10, 2026 by [Agent Messages](design/2026-10-10-agent-messages.md): `harness send` between harnesses in a tab. Kept as the record of Swarm collaboration; `harness team` and `harness channel` no longer exist.
-
-September 28, 2026. This is the experimental A2A experience, off by default; the underlying
-[team protocol](agent-teams.md) also remains available through the CLI.
-
-## User experience
-
-A swarm groups harnesses. Its existing harness panes supply membership;
-there is no separate team creation, role form, recipient picker, or Connect step.
-Agents in different engines and on paired machines can participate in the same swarm.
-Ordinary terminals and shared observation sessions do not become answering peers.
-The swarm's shared conversation uses a swarm-scoped channel. The CLI and protocol keep
-the `channel` name; the interface calls the group a swarm and its history a conversation.
-
-Enable **Settings → Experimental → Swarm collaboration** to try it. This is an
-explicit account preference, stored independently from the desk. Missing preferences
-mean OFF. Opening Settings only reads the choice. The switch is enabled only after
-the saved choice is loaded, and changes are acknowledged by the daemon/backend.
-
-When enabled and a swarm contains at least two recognized agents, the daemon provides each agent
-its scoped commands at a safe input boundary. The agent reads current members and
-shared history, chooses a relevant peer when its task needs help, asks, and continues
-with the correlated answer. A message goes to its recipient; reading shared history
-does not notify all participants or start model work. Introductions, questions, and
-continuations can use the participants' existing model subscriptions.
-
-Agents discover relevant peers and consult automatically within their swarm. There is no
-consult shortcut or recipient picker. Cross-swarm requests and Cmd+Shift+A are deferred.
-Busy, draft, permission-dialog, offline, and uncertain delivery states use the existing
-durable mailbox; an uncertain retry keeps the same operation ID.
-
-Press **Cmd+Shift+P**, type **Swarm conversation**, and press Enter to read the roster and
-exchange history, inspect return delivery, open a participant, cancel a question,
-or pause/resume collaboration. The history contains actual peer questions, replies,
-and delivery states, not full terminal transcripts. Opening and closing the view only reads state.
-Mobile provides **Swarms** from machine views and **Swarm conversation** from the terminal.
-
-Turning the experiment off prevents new automatic swarm input and new questions.
-Known-unsent work and history are retained. Existing model turns are not interrupted.
-Daemons start with swarm delivery disabled, reconcile the saved preference on account
-invalidation and a 15-second poll, and hold deliveries when the directory cannot be read.
-The receiver also checks the gate immediately before writing to an agent. Re-enabling
-may resume unexpired pending deliveries; a per-swarm pause remains in effect.
-
-## Membership and lifetime
-
-The saved desk, rather than the active window or focus, supplies membership.
-Renaming, reordering, zooming, switching swarms, and closing the app do not move the
-channel's ledger or restart an exchange. Removing a pane stops that membership from
-discovering shared history or starting new questions. Its existing exchanges may
-finish and return their answers. Rejoining creates a fresh membership capability;
-old requests stay attributable. Closing a swarm removes its active memberships while
-retaining history on the host. Closing a history dialog leaves membership unchanged.
-
-A harness shown in multiple swarms has a separate capability and roster in each.
-The app includes the input view’s swarm ID with terminal bytes and composed prompts.
-Coalescing and asynchronous sends preserve that ID; switching views never changes
-the scope of an accepted prompt. The daemon matches submissions to native prompt
-hooks (Claude, Codex and Grok), with transcript turn starts as the fallback.
-Queued prompts acquire their scope when accepted, not when another pane gains focus.
-
-Before consulting peers, agents use `harness team context --agent <agent-id>` on
-their own machine. It returns the scoped command for the current task. The swarm
-host also checks that origin before member discovery, history, inbox reads or new
-questions, including when the harness and host are on different machines. Roster
-introductions do not change task scope. Replies and status remain bound to their
-existing exchange. An incoming question temporarily uses its own swarm; after the
-recipient replies, its previous task’s scope is restored. Retrying an old reply
-cannot change the scope of a newer user prompt.
-
-Raw input is evidence, not an alternative terminal editor: Harness forwards every
-byte unchanged and requires the accepted prompt text to match. Native history
-recall, unsupported editing sequences, identical pending prompts, missing client
-metadata and daemon restarts can leave origin unverified. In that case peer
-consultation is refused; the agent continues independently. A composed prompt from
-the swarm’s message box provides explicit origin. Pending matches are bounded to
-64 per harness and expire after five minutes; prompt text is never persisted by
-this mechanism. No origin is inferred from focus or the last introduction.
-Oversized hook payloads still announce the prompt with unavailable text, clearing
-earlier scope before tools run rather than dropping the entire hook notification.
-
-Binary origin metadata uses a negotiated flag inside the authenticated payload.
-Updated clients preserve the original binary format when talking to an older
-daemon. The daemon and client both need this update to attribute ordinary typing.
-
-This attribution is an incremental fix, not a task-lifetime capability. Automatic
-Codex goal continuations can lose their origin, and a delayed tool invocation can
-resolve a newer prompt's current scope. Native prompt hooks also precede final
-provider acceptance. The [communication design review](research/2026-09-28-swarm-communication/design-review.md)
-and its reproductions document these remaining adapter and authorization gaps;
-the proposed task-bound protocol is not implemented by this change.
-
-The first owned machine chosen for a channel remains its host after panes move or
-leave. If that machine is offline, requests wait or report unavailable; the system
-does not invent another host and duplicate the ledger. Automatic host migration is
-not implemented. Daemons reconcile saved membership on desk-change notifications and
-a 15-second poll, with fresh reads for new asks/consults. They keep known-unsent queues
-and pending replies across restarts. An unavailable directory never clears membership
-or causes a silent global fallback.
-
-## Swarm boundaries
-
-Member discovery and questions stay inside the named swarm. A member capability from one
-swarm cannot inspect or message a different swarm. Cross-swarm request actions are not
-available in this release, even with an explicit cross-channel flag. If no local peer
-fits, the agent continues independently or explains the missing context.
-
-This is a collaboration scope, not an OS sandbox between same-user processes. Like
-other CLI commands, the advanced owner/team interface uses the user's local or paired
-machine authority. Agents are instructed to keep using their supplied scoped commands.
-
-Code answers are instructed to name their repository, worktree, branch/commit, and
-relevant uncommitted changes. There is no automatic checkout, merge, or file transfer;
-the asking agent uses the answer within its existing task and permissions.
-
-## Components and activation
-
-- `backend/src/lib/tabChannels.ts`, `routes/tabChannels.ts`, and the separate
- `tab_channels` collection store only `(user, tab, host machine)` routing metadata.
- The existing desk JSON, routes, and collections retain their format. A deterministic
- MongoDB `_id` makes simultaneous host claims converge; ownership filters exclude
- shared observation panes.
-- `tab_channel_settings` stores the explicit account preference, defaulting to false
- when absent. Authenticated GET/PATCH `/api/tab-channels/settings` read and update it.
- A setting change uses the existing account invalidation transport; desk data is untouched.
-- Generate the updated Prisma client and deploy the updated backend, CLI, and app.
- Module routes are available by default, while actual collaboration remains OFF
- until the user opts in. Operators can set **`HARNESS_CHANNELS=false`** to disable the
- module completely. Older or disabled servers produce an explicit unsupported message.
- No existing database or account setting was changed during development.
-- `cli/src/teams/channels.ts` reads that directory and reconciles local ledgers. The
- existing `team.v1` RPC and paired E2EE carry member capabilities and message bodies;
- the backend never stores them. `channelCommand.ts` exposes the human/owner CLI.
-- Desktop/web use the same controller and channel view. Mobile keeps its self-contained
- controller copy. `harness team ... members`, `history`, `ask`, `inbox`, `reply`, and
- `wait` are the scoped shell adapter used by Claude, Codex, Grok, and other engines.
-
-```sh
-harness channel --help
-harness channel list --json
-harness channel --tab TAB_ID history --json
-```
-
-The existing bounds apply: 100 retained ledgers per host, 500 exchanges per ledger,
-8 outstanding questions per sender, 30 new questions per minute per ledger, and four
-questions in a follow-up chain. A swarm channel allows 32 current and 512 retained
-memberships, and 500 retained consult instructions. No retention deletion or automatic host failover is performed.
-
-## Verification
-
-Tests cover default-off behavior, explicit opt-in persistence, safe disable/re-enable,
-recipient restarts, failed directory reads, concurrent settings changes, automatic
-registration, swarm isolation, shared history, removal/rejoin,
-closed swarms, stale membership, idempotent consults, rejected cross-swarm requests,
-pause/resume, skipped shells, read-only views, inactive cross-swarm shortcuts,
-and desktop/mobile rendering. The two-daemon fixture exercises actual local WebSockets,
-pairing, encrypted relays, explicit replies, and continuation; cloud routing and agent
-terminal responses are synthetic. Backend tests cover auth, owned-machine filtering,
-concurrent host claims, retained hosts, and compatibility with the existing desk routes.
-
-Prompt-origin regressions cover a session in two swarms, queued input and delayed
-transcript events, encrypted routing between machines, returns after peer replies,
-unsupported editor operations, oversized input, and old-daemon wire compatibility.
-The native hook recordings in
-[`swarm-prompt-hooks.json`](../cli/src/lib/__fixtures__/swarm-prompt-hooks.json)
-come from Claude 2.1.283, Codex 0.154.0, and Grok 1.0.34 on 2026-09-28. Each probe
-used an isolated profile and a synthetic prompt blocked before any model call.
-
-Prompt-origin fix validation on 2026-09-28 passed:
-
-- CLI typecheck and build; complete CLI suite: 7,169 passed, 37 opt-in tests skipped.
-- Desktop terminal, composer and protocol checks: 101 passed; mobile: 86 passed.
- Changed Dart files passed analysis.
-- Real tmux 3.5a: 9 passed, 9 unavailable/not-applicable rows skipped. Discovery ran
- Claude 2.1.283, Codex 0.154.0, OpenCode 1.18.32, Pi 0.85.1,
- Hermes 0.18.0 (upstream 1d8946b4, local 7e8f50a1), and Grok 1.0.34 (3736acbc8658),
- plus lifecycle, literal input, and Grok executable-alias checks. No paid model
- acceptance test was run.
-
-Original swarm release integration validation passed:
-
-- Backend and CLI TypeScript checks, Prisma client generation, and builds.
-- Backend routing and desk compatibility: 19 tests.
-- Complete CLI suite with two workers: 7,141 passed, 37 opt-in tests skipped.
-- Real tmux 3.5a suite: 9 passed, 9 unavailable/not-applicable rows skipped.
- Installed Claude, Codex, OpenCode, Pi, Hermes, and Grok discovery ran, plus lifecycle,
- literal input, and Grok executable-alias checks. These checks send no model tasks.
-- Desktop settings, conversation, keyboard, and encryption checks: 82 tests.
- The final Settings pair was rerun after preserving the existing switch order.
-- Mobile conversation/controller and encryption checks: 18 tests.
-- Changed desktop/mobile Dart files passed analysis. macOS debug and browser release builds passed.
-
-The initial concurrent CLI run exposed two timing-sensitive existing checks; their targeted
-rerun and the complete two-worker run passed. The existing CLI build warning in
-`dsh/verdict.spec.ts` is unrelated to this feature. Paid model acceptance was not rerun.
-
-The Settings switch was rendered with real fonts at widths 390/1100. Conversation renders
-were inspected at desktop widths 390/1280 and phone width 390, using synthetic data.
-Review screenshots are committed under `.github/assets/swarm-collaboration/`.
-Local build outputs are `backend/dist`, `cli/dist`,
-`desktop/build/macos/Build/Products/Debug/Harness.app`, and `desktop/build/web`.
-
-The earlier [Claude/Codex/Grok live test](agent-teams-live-verification.md) verified the
-underlying delivery protocol. The swarm-channel prompts and automatic membership have not
-been rerun against paid live models. No production server, installed CLI, or ongoing
-user agent was changed or used as a fixture for this extension.
diff --git a/mobile/lib/e2ee/envelope.dart b/mobile/lib/e2ee/envelope.dart
index dec9e889d..2c7a96ea1 100644
--- a/mobile/lib/e2ee/envelope.dart
+++ b/mobile/lib/e2ee/envelope.dart
@@ -16,8 +16,6 @@ const int e2eVersion = 1;
const Set<String> encryptedDownTypes = {
'harness_devices_list',
'harness_device_settings',
- 'team',
- 'team_delivery',
'message',
'question_response',
'agents_list',
diff --git a/mobile/lib/phone/agents_page.dart b/mobile/lib/phone/agents_page.dart
index 6be851b68..5b63da586 100644
--- a/mobile/lib/phone/agents_page.dart
+++ b/mobile/lib/phone/agents_page.dart
@@ -21,7 +21,6 @@ import 'phone_navigation.dart';
import 'phone_sheet.dart';
import 'phone_status.dart';
import 'status_pill.dart';
-import 'team_page.dart';
/// One machine's agents. A tap opens that agent full screen, and it is the only one open.
class AgentsPage extends StatelessWidget {
@@ -103,17 +102,6 @@ class AgentsPage extends StatelessWidget {
context,
title: machine.machine.displayName,
actions: [
- if (linked)
- PhoneSheetAction(
- icon: LucideIcons.users300,
- label: 'Swarms',
- chevron: true,
- onTap: () => Navigator.of(context).push(
- phoneRoute(
- (_) => TeamPage(notifier: notifier, machineId: machineId),
- ),
- ),
- ),
PhoneSheetAction(
icon: LucideIcons.refreshCw300,
label: 'Reload harnesses',
diff --git a/mobile/lib/phone/machine_actions.dart b/mobile/lib/phone/machine_actions.dart
index b5cb9954b..3ba40b404 100644
--- a/mobile/lib/phone/machine_actions.dart
+++ b/mobile/lib/phone/machine_actions.dart
@@ -10,7 +10,6 @@ import 'phone_navigation.dart';
import 'phone_sheet.dart';
import 'phone_status.dart';
import 'unlink_machine.dart';
-import 'team_page.dart';
/// A machine that wants its password opens the form for it. One that is linked opens a sheet of
/// what can be done TO it — reload its agents, re-enter its password, unlink this phone.
@@ -37,14 +36,6 @@ void openMachineActions(
context,
title: machine.machine.displayName,
actions: [
- PhoneSheetAction(
- icon: LucideIcons.users300,
- label: 'Swarms',
- chevron: true,
- onTap: () => Navigator.of(context).push(
- phoneRoute((_) => TeamPage(notifier: notifier, machineId: machineId)),
- ),
- ),
PhoneSheetAction(
icon: LucideIcons.refreshCw300,
label: 'Reload harnesses',
diff --git a/mobile/lib/phone/team_page.dart b/mobile/lib/phone/team_page.dart
deleted file mode 100644
index f0bf3f53d..000000000
--- a/mobile/lib/phone/team_page.dart
+++ /dev/null
@@ -1,648 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter/material.dart';
-
-import '../state/app_state.dart';
-import '../teams/team_controller.dart';
-import 'desk_groups.dart';
-import 'phone_header.dart';
-import 'phone_navigation.dart';
-import 'tty.dart';
-
-class PhoneTeamCandidate {
- const PhoneTeamCandidate({
- required this.machineId,
- required this.agentId,
- required this.name,
- required this.engine,
- required this.available,
- });
- final String machineId, agentId, name, engine;
- final bool available;
- String get key => '$machineId/$agentId';
-}
-
-class TeamPage extends StatelessWidget {
- const TeamPage({
- super.key,
- required this.notifier,
- required this.machineId,
- this.tabId,
- this.agentId,
- });
- final AppNotifier notifier;
- final String machineId;
- final String? tabId, agentId;
- @override
- Widget build(BuildContext context) => ListenableBuilder(
- listenable: notifier,
- builder: (context, _) => tabId == null
- ? Scaffold(
- body: SafeArea(
- child: Column(
- children: [
- const PhoneHeader(title: 'Swarms'),
- Expanded(
- child: ListView(
- children: [
- if (notifier.deskTabs.isEmpty)
- Padding(
- padding: const EdgeInsets.all(16),
- child: Text(
- 'Add harnesses to a swarm so their agents can collaborate.',
- style: Tty.of(context).style(),
- ),
- ),
- for (final tab in notifier.deskTabs)
- TextButton(
- onPressed: () => Navigator.of(context).push(
- phoneRoute(
- (_) => TeamPage(
- notifier: notifier,
- machineId: machineId,
- tabId: tab.id,
- ),
- ),
- ),
- child: Text(
- deskTabName(tab, null),
- style: Tty.of(context).style(),
- ),
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- )
- : PhoneTeamView(
- key: ValueKey(tabId),
- controller: notifier.channelController(tabId!, machineId),
- machineName:
- notifier.stateOf(machineId)?.machine.displayName ?? 'Machine',
- candidates: const [],
- onOpen: (machine, agent) =>
- openAgent(context, notifier, machine, agent),
- ),
- );
-}
-
-/// A projection of the daemon ledger; leaving the page stops only its read subscription.
-class PhoneTeamView extends StatefulWidget {
- const PhoneTeamView({
- super.key,
- required this.controller,
- required this.machineName,
- required this.candidates,
- required this.onOpen,
- });
- final TeamController controller;
- final String machineName;
- final List<PhoneTeamCandidate> candidates;
- final void Function(String machineId, String agentId) onOpen;
- @override
- State<PhoneTeamView> createState() => _PhoneTeamViewState();
-}
-
-class _PhoneTeamViewState extends State<PhoneTeamView> {
- TeamController get model => widget.controller;
- bool creating = false;
- late final name = TextEditingController(text: model.newName);
- late final description = TextEditingController(text: model.newDescription);
- late final question = TextEditingController(text: model.draft);
- late Tty tty;
- @override
- void initState() {
- super.initState();
- creating = model.pendingCreate;
- model.addListener(changed);
- model.watch();
- }
-
- void changed() {
- if (!mounted) return;
- if (question.text != model.draft) {
- question.value = TextEditingValue(
- text: model.draft,
- selection: TextSelection.collapsed(offset: model.draft.length),
- );
- }
- if (model.team != null) creating = false;
- setState(() {});
- }
-
- @override
- void dispose() {
- model.removeListener(changed);
- model.unwatch();
- name.dispose();
- description.dispose();
- question.dispose();
- super.dispose();
- }
-
- Widget action(String label, VoidCallback? onTap, {Key? key}) => TextButton(
- key: key,
- style: TextButton.styleFrom(
- foregroundColor: tty.text,
- textStyle: tty.style(),
- alignment: Alignment.centerLeft,
- minimumSize: Size(44, tty.tapRow),
- padding: EdgeInsets.symmetric(horizontal: tty.cell),
- shape: const RoundedRectangleBorder(),
- ),
- onPressed: onTap,
- child: Text('[ $label ]'),
- );
- Widget text(String value, {bool faint = false}) => SelectableText(
- value,
- style: tty.style(color: faint ? tty.faint : tty.text),
- );
- Widget gap() => SizedBox(height: tty.row);
- Widget field(
- TextEditingController controller,
- String label,
- ValueChanged<String> onChanged, {
- int lines = 1,
- bool readOnly = false,
- Key? key,
- }) => TextField(
- key: key,
- controller: controller,
- style: tty.style(),
- minLines: lines,
- maxLines: lines + 2,
- readOnly: readOnly,
- decoration: InputDecoration(
- labelText: label,
- labelStyle: tty.style(color: tty.faint),
- filled: false,
- enabledBorder: UnderlineInputBorder(
- borderSide: BorderSide(color: tty.dim),
- ),
- focusedBorder: UnderlineInputBorder(
- borderSide: BorderSide(color: tty.text),
- ),
- ),
- onChanged: onChanged,
- );
- String memberName(dynamic id) {
- final member = model.members.where((m) => m['id'] == id).firstOrNull;
- final runtime = member?['runtime'] as Map?;
- if (model.isChannel && runtime?['name'] is String) {
- return runtime!['name'] as String;
- }
- return member?['name'] as String? ?? 'choose';
- }
-
- String alias(String name) {
- var value = name
- .replaceAll(RegExp(r'[^a-zA-Z0-9_-]+'), '-')
- .replaceAll(RegExp(r'^-+|-+$'), '');
- if (value.isEmpty) value = 'teammate';
- if (value.length > 30) value = value.substring(0, 30);
- final base = value;
- var n = 2;
- final used = [
- ...model.newMembers.values,
- ...model.members.where((m) => m['enabled'] != false),
- ];
- while (used.any(
- (m) => m['name'].toString().toLowerCase() == value.toLowerCase(),
- )) {
- value = '$base-${n++}';
- }
- return value;
- }
-
- Future<void> editMember(
- Map<String, dynamic> member, {
- bool adding = false,
- }) async {
- final alias = TextEditingController(text: member['name'] as String? ?? '');
- final role = TextEditingController(text: member['role'] as String? ?? '');
- final result = await showModalBottomSheet<String>(
- context: context,
- isScrollControlled: true,
- backgroundColor: tty.ground,
- shape: const RoundedRectangleBorder(),
- builder: (context) => SafeArea(
- child: Padding(
- padding: EdgeInsets.fromLTRB(
- 16,
- 16,
- 16,
- MediaQuery.viewInsetsOf(context).bottom + 16,
- ),
- child: SingleChildScrollView(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- text(adding ? 'Connect teammate' : 'Edit teammate'),
- gap(),
- field(alias, 'Team name', (_) {}),
- field(role, 'Knows about', (_) {}, lines: 2),
- gap(),
- action(
- adding ? 'Connect' : 'Save',
- () => Navigator.pop(context, 'save'),
- ),
- if (!adding && !creating && member['enabled'] != false)
- action(
- 'Remove from team',
- () => Navigator.pop(context, 'remove'),
- ),
- action('Back', () => Navigator.pop(context)),
- ],
- ),
- ),
- ),
- ),
- );
- if (mounted && result != null) {
- final updated = {
- ...member,
- 'name': alias.text.trim(),
- 'role': role.text.trim(),
- };
- if (adding) {
- await model.addMember(updated);
- } else if (creating) {
- model.newMembers['${member['machineId']}/${member['agentId']}'] =
- updated;
- setState(() {});
- } else {
- await model.act('member', {
- 'member': {
- ...updated,
- 'enabled': result != 'remove' && member['enabled'] != false,
- },
- });
- }
- }
- alias.dispose();
- role.dispose();
- }
-
- Future<void> chooseMember(bool source) async {
- final selected = await showModalBottomSheet<String>(
- context: context,
- backgroundColor: tty.ground,
- shape: const RoundedRectangleBorder(),
- builder: (context) => SafeArea(
- child: ListView(
- shrinkWrap: true,
- children: [
- for (final m in model.members)
- if (m['enabled'] != false && (source || m['id'] != model.from))
- action('@${m['name']}', () => Navigator.pop(context, m['id'])),
- ],
- ),
- ),
- );
- if (!mounted || selected == null) return;
- setState(() {
- if (source) {
- model.from = selected;
- if (model.to == selected) model.to = null;
- } else {
- model.to = selected;
- }
- });
- }
-
- Future<void> addMember() async {
- if (model.pendingAdd) {
- await model.addMember();
- return;
- }
- final candidates = widget.candidates
- .where(
- (c) =>
- c.available &&
- !model.members.any(
- (m) =>
- m['enabled'] != false &&
- m['machineId'] == c.machineId &&
- m['agentId'] == c.agentId,
- ),
- )
- .toList();
- final selected = await showModalBottomSheet<PhoneTeamCandidate>(
- context: context,
- backgroundColor: tty.ground,
- shape: const RoundedRectangleBorder(),
- builder: (context) => SafeArea(
- child: ListView(
- shrinkWrap: true,
- children: [
- if (candidates.isEmpty)
- Padding(
- padding: const EdgeInsets.all(16),
- child: text('No additional harnesses available.'),
- ),
- for (final c in candidates)
- action(
- '${c.name} · ${c.engine}',
- () => Navigator.pop(context, c),
- ),
- ],
- ),
- ),
- );
- if (!mounted || selected == null) return;
- await editMember({
- 'machineId': selected.machineId,
- 'agentId': selected.agentId,
- 'name': alias(selected.name),
- 'role': selected.name,
- }, adding: true);
- }
-
- List<Widget> home() => [
- text('Teams on ${widget.machineName}', faint: true),
- gap(),
- text(
- 'Connect existing harnesses. Questions and answers return to the agents doing the work.',
- ),
- gap(),
- action(
- 'New team',
- model.operating ? null : () => setState(() => creating = true),
- key: const Key('phone-team-new'),
- ),
- if (model.loading) text('Reading teams…', faint: true),
- if (!model.loading && model.teams.isEmpty)
- text('No teams yet.', faint: true),
- for (final team in model.teams)
- action(
- '${team['name']} · ${team['pending']} waiting',
- () => unawaited(model.select(team['id'] as String)),
- ),
- ];
- List<Widget> create() => [
- field(
- name,
- 'Team name',
- (v) => model.newName = v,
- readOnly: model.pendingCreate,
- ),
- field(
- description,
- 'What you are building',
- (v) => model.newDescription = v,
- readOnly: model.pendingCreate,
- ),
- gap(),
- text(
- 'Choose at least two existing harnesses. Connect sends each one its team introduction.',
- faint: true,
- ),
- gap(),
- for (final c in widget.candidates) ...[
- action(
- '${model.newMembers.containsKey(c.key) ? 'x' : ' '} ${c.name} · ${c.engine}',
- model.pendingCreate || model.operating || !c.available
- ? null
- : () => setState(() {
- if (model.newMembers.remove(c.key) == null) {
- model.newMembers[c.key] = {
- 'machineId': c.machineId,
- 'agentId': c.agentId,
- 'name': alias(c.name),
- 'role': c.name,
- };
- }
- }),
- key: ValueKey('phone-team-candidate-${c.agentId}'),
- ),
- if (model.newMembers[c.key] case final member?)
- action(
- '@${member['name']} · edit role',
- model.pendingCreate ? null : () => editMember(member),
- ),
- ],
- gap(),
- action(
- model.pendingCreate
- ? 'Check connection'
- : 'Connect ${model.newMembers.length} teammates',
- model.operating ||
- (!model.pendingCreate &&
- (model.newMembers.length < 2 || model.newName.trim().isEmpty))
- ? null
- : () => unawaited(model.create()),
- key: const Key('phone-team-connect'),
- ),
- action(
- 'Back',
- model.operating ? null : () => setState(() => creating = false),
- ),
- ];
- List<Widget> detail() => [
- if (!model.isChannel)
- action(
- 'All teams',
- model.operating ? null : () => unawaited(model.select(null)),
- ),
- if (model.team == null)
- text(model.isChannel ? 'Reading swarm…' : 'Reading team…')
- else ...[
- text(
- '${model.isChannel ? 'Swarm conversation · ' : ''}${model.team!['state']} · ${model.members.where((m) => m['enabled'] != false).length} harnesses',
- faint: true,
- ),
- if (model.isChannel)
- text('This swarm only · membership follows the swarm.', faint: true),
- Wrap(
- children: [
- if (model.team!['state'] != 'archived')
- action(
- model.active ? 'Pause' : 'Resume',
- model.operating
- ? null
- : () =>
- unawaited(model.act(model.active ? 'pause' : 'resume')),
- ),
- if (!model.isChannel && model.team!['state'] != 'archived')
- action(
- model.pendingAdd ? 'Check teammate' : 'Add teammate',
- model.operating ? null : addMember,
- ),
- if (!model.isChannel && model.team!['state'] == 'paused')
- action(
- 'Archive',
- model.operating ? null : () => unawaited(model.act('archive')),
- ),
- ],
- ),
- gap(),
- text(
- model.isChannel ? 'Harnesses in this swarm' : 'Teammates',
- faint: true,
- ),
- for (final m in model.members) ...[
- action(
- '${model.isChannel ? memberName(m['id']) : '@${m['name']}'} · ${m['enabled'] == false ? 'removed' : (m['runtime'] as Map?)?['engine'] ?? 'offline'}',
- () => widget.onOpen(m['machineId'] as String, m['agentId'] as String),
- ),
- if ((m['role'] as String? ?? '').isNotEmpty)
- text(m['role'] as String, faint: true),
- if (!model.isChannel)
- action(
- 'Edit @${m['name']}',
- model.operating || model.team!['state'] == 'archived'
- ? null
- : () => editMember(m),
- ),
- ],
- gap(),
- text('Exchanges', faint: true),
- if (model.exchanges.isEmpty) text('No questions yet.', faint: true),
- for (final e in model.exchanges) ...[
- action(
- '${(e['fromPeer'] as Map?)?['name'] ?? memberName(e['from'])} → ${(e['toPeer'] as Map?)?['name'] ?? memberName(e['to'])} · ${e['state']}',
- () => setState(
- () => model.selectedExchange = model.selectedExchange == e['id']
- ? null
- : e['id'],
- ),
- ),
- if (model.selectedExchange == e['id']) ...conversation(e),
- ],
- if (!model.isChannel) ...[
- gap(),
- text('Ask a teammate'),
- Wrap(
- children: [
- action(
- 'From @${memberName(model.from)}',
- model.pendingAsk ? null : () => chooseMember(true),
- ),
- action(
- 'To @${memberName(model.to)}',
- model.pendingAsk ? null : () => chooseMember(false),
- ),
- ],
- ),
- field(
- question,
- 'What do you need to know?',
- (v) {
- model.draft = v;
- setState(() {});
- },
- lines: 3,
- readOnly: model.pendingAsk,
- key: const Key('phone-team-question'),
- ),
- gap(),
- text(
- 'The exchange records that you requested this. The answer returns to @${memberName(model.from)}.',
- faint: true,
- ),
- action(
- model.pendingAsk ? 'Check send' : 'Ask',
- model.operating ||
- !model.active ||
- (!model.pendingAsk &&
- (model.draft.trim().isEmpty ||
- model.to == null ||
- model.to == model.from))
- ? null
- : () => unawaited(model.ask()),
- key: const Key('phone-team-ask'),
- ),
- ],
- ],
- ];
- List<Widget> conversation(Map<String, dynamic> e) {
- final answer = (e['answer'] as Map?)?.cast<String, dynamic>();
- final fromName = (e['fromPeer'] as Map?)?['name'] ?? memberName(e['from']);
- return [
- text(
- '${e['origin'] == 'owner' ? 'Requested by you' : 'Agent question'} · ${teamDeliveryLabel((e['delivery'] as Map?)?.cast<String, dynamic>())}',
- faint: true,
- ),
- gap(),
- text(e['text'] as String),
- if ((e['context'] as String? ?? '').isNotEmpty)
- text(e['context'] as String, faint: true),
- gap(),
- if (answer == null)
- text('Waiting for an explicit answer.', faint: true)
- else ...[
- text(
- '${answer['late'] == true ? 'Late answer' : 'Answer'}${answer['origin'] == 'owner' ? ' supplied by you' : ''}',
- faint: true,
- ),
- gap(),
- text(answer['text'] as String),
- for (final ref in answer['evidence'] as List? ?? [])
- text(ref.toString(), faint: true),
- gap(),
- text(
- answer['late'] == true
- ? 'Retained for reference; no automatic continuation.'
- : 'Return to $fromName: ${teamDeliveryLabel((e['continuation'] as Map?)?.cast<String, dynamic>())}',
- faint: true,
- ),
- ],
- if (e['state'] == 'pending')
- action(
- 'Cancel question',
- model.operating
- ? null
- : () => unawaited(
- model.act('cancel', {
- 'questionId': e['questionId'] ?? e['id'],
- if (e['teamId'] != null) 'teamId': e['teamId'],
- }),
- ),
- ),
- gap(),
- ];
- }
-
- @override
- Widget build(BuildContext context) {
- tty = Tty.of(context);
- return Scaffold(
- backgroundColor: tty.ground,
- body: SafeArea(
- child: Column(
- children: [
- PhoneHeader(
- title: creating
- ? 'Connect a team'
- : model.team?['name'] as String? ??
- (model.isChannel ? 'Swarm conversation' : 'Team'),
- trailing: [action('Refresh', () => unawaited(model.refresh()))],
- ),
- Expanded(
- child: RefreshIndicator(
- onRefresh: model.refresh,
- child: ListView(
- padding: const EdgeInsets.fromLTRB(16, 0, 16, 24),
- children: [
- if (model.error case final error?) ...[
- Semantics(liveRegion: true, child: text(error)),
- gap(),
- ],
- ...(creating
- ? create()
- : model.selectedId == null && !model.isChannel
- ? home()
- : detail()),
- ],
- ),
- ),
- ),
- ],
- ),
- ),
- );
- }
-}
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index d2b933bd6..25fb8d1bf 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -47,7 +47,6 @@ import 'phone_status.dart';
import 'settings_page.dart';
import 'session_work_page.dart';
import 'terminal_action_column.dart';
-import 'team_page.dart';
import 'terminal_chrome_scroll.dart';
import 'terminal_input_dock.dart';
import 'terminal_search.dart';
@@ -1003,11 +1002,10 @@ class _TerminalPageState extends State<TerminalPage>
/// that question, as its answer or not at all. Nothing is echoed when it lands: the words appear
/// in the prompt, and a tap is felt. Only what went wrong is said (see [_flash]).
Future<bool> _deliverVoice(String text) async {
- final origin = widget.notifier.activeSwarmId;
final session = await _sessionForInput();
if (session == null) return false;
if (_questionWatcher?.view != null) return _answerByVoice(session, text);
- final sent = await session.sendComposerText(text, tabId: origin);
+ final sent = await session.sendComposerText(text);
// After the send is acknowledged, never before: a tap felt first would be a promise.
if (sent && mounted) HapticFeedback.lightImpact();
return sent;
@@ -1035,8 +1033,7 @@ class _TerminalPageState extends State<TerminalPage>
/// A voice take while the agent's question is open: it answers the question or it is not sent.
Future<bool> _answerByVoice(TerminalSession session, String text) async {
final view = _questionWatcher?.view;
- final origin = widget.notifier.activeSwarmId;
- if (view == null) return session.sendComposerText(text, tabId: origin);
+ if (view == null) return session.sendComposerText(text);
if (!view.answerable || view.multi) {
_flash('✗ answer on screen', error: true);
return false;
@@ -1052,7 +1049,7 @@ class _TerminalPageState extends State<TerminalPage>
if (match.rest case final rest?) {
Timer(const Duration(milliseconds: 900), () {
if (!mounted || _questionWatcher?.view != null) return;
- unawaited(session.sendComposerText(rest, tabId: origin));
+ unawaited(session.sendComposerText(rest));
});
}
return true;
@@ -1882,9 +1879,6 @@ class _TerminalPageState extends State<TerminalPage>
: pane == null || session == null
? _Attaching(key: _skeletonKey)
: TerminalPanel(
- tabId: widget
- .notifier
- .activeSwarmId,
key: ValueKey(pane.id),
notifier: widget.notifier,
session: session,
@@ -2349,21 +2343,6 @@ class _TerminalPageState extends State<TerminalPage>
// the computers are a row in Settings.
PhoneSheetSection(
actions: [
- PhoneSheetAction(
- icon: LucideIcons.users300,
- label: 'Swarm conversation',
- chevron: true,
- onTap: () => Navigator.of(context).push(
- phoneRoute(
- (_) => TeamPage(
- notifier: widget.notifier,
- machineId: widget.machineId,
- tabId: widget.notifier.activeDeskTabId,
- agentId: widget.agentId,
- ),
- ),
- ),
- ),
// In the sample: the way back out, where a person looks for "what else can I do".
if (SampleMode.maybeOf(context) case final sample?)
PhoneSheetAction(
diff --git a/mobile/lib/phone/welcome/how_it_works.dart b/mobile/lib/phone/welcome/how_it_works.dart
index 93f234cc2..db3054fe5 100644
--- a/mobile/lib/phone/welcome/how_it_works.dart
+++ b/mobile/lib/phone/welcome/how_it_works.dart
@@ -27,10 +27,10 @@ class HowItWorksPage extends StatelessWidget {
'They keep going when you close the app.',
),
(
- 'Swarm',
+ 'Tab',
'A group of harnesses, shown together in the workspace. Add a harness to '
- 'include it. With Swarm collaboration enabled in Experimental settings, '
- 'their agents can consult peers in the same swarm.',
+ 'include it. With Agent Messages on for it, its agents can message each '
+ 'other.',
),
(
'Project',
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 4d3179c57..aa8986cad 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -6,7 +6,6 @@ import 'package:xterm/xterm.dart' show Terminal;
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
-import '../teams/team_controller.dart';
import '../api/api_client.dart';
import '../viewer/direct_auth_api.dart';
import '../viewer/direct_link.dart';
@@ -1530,14 +1529,6 @@ class AppNotifier extends ChangeNotifier {
currentUser = null;
machines = [];
machineStates.clear();
- for (final controller in _teamControllers.values) {
- controller.dispose();
- }
- _teamControllers.clear();
- for (final controller in _channelControllers.values) {
- controller.dispose();
- }
- _channelControllers.clear();
// ⚠️ The warm-start cache is this account's machine ids, so it goes with the
// session. Left behind, the next launch would dial the previous account's
// machines before its own fetch could say they are not its own — reaching
@@ -3969,50 +3960,6 @@ class AppNotifier extends ChangeNotifier {
}
}
- final _teamControllers = <String, TeamController>{};
- final _channelControllers = <String, TeamController>{};
- TeamController channelController(String tabId, String gatewayMachineId) =>
- _channelControllers.putIfAbsent(tabId, () {
- late final TeamController controller;
- controller = TeamController(
- channelTabId: tabId,
- request: (payload) => teamRequest(
- controller.team?['machineId'] as String? ?? gatewayMachineId,
- payload,
- ),
- );
- return controller;
- });
- TeamController teamController(String machineId) =>
- _teamControllers.putIfAbsent(
- machineId,
- () => TeamController(
- request: (payload) => teamRequest(machineId, payload),
- ),
- );
-
- Future<Map<String, dynamic>> teamRequest(
- String machineId,
- Map<String, dynamic> payload,
- ) async {
- try {
- return await _conn(
- machineId,
- ).request('team', payload: payload, timeout: const Duration(seconds: 35));
- } on WsRequestFailure catch (e) {
- throw TeamRequestError(
- e.code == 'UNSUPPORTED'
- ? 'Update Harness on this machine to use agent collaboration.'
- : e.toString(),
- uncertain: const {
- 'UNCONFIRMED',
- 'DISCONNECTED',
- 'TEAM_UNAVAILABLE',
- }.contains(e.code),
- );
- }
- }
-
/// The Git choices [path] offers, read ON the machine that owns it.
///
/// ⚠️ **The phone never looks at a repository itself, and could not.** The
@@ -6405,14 +6352,6 @@ class AppNotifier extends ChangeNotifier {
@override
void dispose() {
- for (final controller in _teamControllers.values) {
- controller.dispose();
- }
- _teamControllers.clear();
- for (final controller in _channelControllers.values) {
- controller.dispose();
- }
- _channelControllers.clear();
_disposed = true;
_closedHistory.clear();
_stopAccountTimers();
diff --git a/mobile/lib/teams/team_controller.dart b/mobile/lib/teams/team_controller.dart
deleted file mode 100644
index f4577a91e..000000000
--- a/mobile/lib/teams/team_controller.dart
+++ /dev/null
@@ -1,404 +0,0 @@
-import 'dart:async';
-import 'dart:math';
-
-import 'package:flutter/foundation.dart';
-
-typedef TeamRequest = Future<Map<String, dynamic>> Function(
- Map<String, dynamic>,
-);
-
-String teamOperationId() {
- final random = Random.secure();
- return List.generate(
- 16,
- (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'),
- ).join();
-}
-
-class TeamRequestError implements Exception {
- const TeamRequestError(this.message, {this.uncertain = false});
- final String message;
- final bool uncertain;
- @override
- String toString() => message;
-}
-
-List<Map<String, dynamic>> teamRows(dynamic value) => [
- for (final row in value is List ? value : const [])
- if (row is Map) Map<String, dynamic>.from(row),
-];
-
-/// A view of daemon-owned work. Closing Team only releases its read subscription.
-/// Uncertain operations and drafts belong here, so reopening cannot duplicate a send.
-class TeamController extends ChangeNotifier {
- TeamController({
- required this.request,
- this.channelTabId,
- this.pollInterval = const Duration(seconds: 3),
- });
- final TeamRequest request;
- final String? channelTabId;
- bool get isChannel => channelTabId != null || team?['channel'] != null;
- final Duration pollInterval;
- List<Map<String, dynamic>> teams = [];
- Map<String, dynamic>? team;
- String? selectedId, error;
- bool loading = true, operating = false;
- String draft = '', newName = 'Build together', newDescription = '';
- String? from, to, selectedExchange;
- final Map<String, Map<String, dynamic>> newMembers = {};
- Map<String, dynamic>? _createAttempt;
- final _askAttempts = <String, Map<String, dynamic>>{};
- final _addAttempts = <String, Map<String, dynamic>>{};
- final _consultAttempts = <String, Map<String, dynamic>>{};
- final _consultFlights = <String, Future<String>>{};
- final _drafts =
- <String, ({String text, String? from, String? to, String? exchange})>{};
- Timer? _timer;
- int _readers = 0, _epoch = 0;
- bool _disposed = false;
- Future<void>? _refresh;
- bool get pendingCreate => _createAttempt != null;
- bool get pendingAsk => _askAttempts.containsKey(selectedId);
- bool get pendingAdd => _addAttempts.containsKey(selectedId);
- List<Map<String, dynamic>> get members => teamRows(team?['members']);
- List<Map<String, dynamic>> get exchanges {
- final rows = [...teamRows(team?['exchanges']).reversed];
- if (isChannel) {
- rows.sort(
- (a, b) => ((b['createdAt'] as num?) ?? 0).compareTo(
- (a['createdAt'] as num?) ?? 0,
- ),
- );
- }
- return rows;
- }
-
- bool get active => team?['state'] == 'active';
-
- void _notify() {
- if (!_disposed) notifyListeners();
- }
-
- void watch() {
- if (_disposed || _readers++ > 0) return;
- unawaited(refresh());
- _timer = Timer.periodic(pollInterval, (_) => unawaited(refresh()));
- }
-
- void unwatch() {
- if (_readers > 0) _readers--;
- if (_readers == 0) {
- _timer?.cancel();
- _timer = null;
- }
- }
-
- void changed() {
- if (_readers > 0) unawaited(refresh());
- }
-
- Future<Map<String, dynamic>> _call(Map<String, dynamic> payload) async {
- final result = await request(payload);
- if (result['error'] != null) {
- throw TeamRequestError(
- result['detail']?.toString() ?? result['error'].toString(),
- uncertain: const {
- 'UNCONFIRMED',
- 'DISCONNECTED',
- 'TEAM_UNAVAILABLE',
- }.contains(result['error']),
- );
- }
- return result;
- }
-
- Future<void> refresh() =>
- _refresh ??= _read().whenComplete(() => _refresh = null);
- Future<void> _read() async {
- final epoch = _epoch, id = selectedId;
- try {
- final result = await _call({
- 'action': channelTabId != null
- ? 'channel_get'
- : id == null
- ? 'list'
- : 'get',
- if (channelTabId != null) 'tabId': channelTabId else 'teamId': ?id,
- });
- if (_disposed || epoch != _epoch) return;
- if (channelTabId != null) {
- selectedId = (result['team'] as Map?)?['id'] as String?;
- _apply(result['team']);
- error = null;
- } else if (id == null) {
- teams = teamRows(result['teams']);
- final faults = teamRows(result['errors']);
- error = faults.isEmpty
- ? null
- : faults.map((f) => f['detail']).join('\n');
- } else {
- _apply(result['team']);
- error = null;
- }
- } catch (e) {
- if (!_disposed && epoch == _epoch) error = e.toString();
- }
- if (!_disposed && epoch == _epoch) {
- loading = false;
- _notify();
- }
- }
-
- void _apply(dynamic value) {
- if (_disposed || value is! Map || value['id'] != selectedId) return;
- if (team?['id'] == value['id'] &&
- (team?['revision'] as num? ?? 0) > (value['revision'] as num? ?? 0)) {
- return;
- }
- team = Map<String, dynamic>.from(value);
- if (isChannel && selectedExchange == null && exchanges.isNotEmpty) {
- selectedExchange = exchanges.first['id'] as String?;
- }
- final enabled = members.where((m) => m['enabled'] != false).toList();
- if (!enabled.any((m) => m['id'] == from)) {
- from = enabled.firstOrNull?['id'] as String?;
- }
- if (!enabled.any((m) => m['id'] == to) || from == to) {
- to = enabled.where((m) => m['id'] != from).firstOrNull?['id'] as String?;
- }
- }
-
- Future<void> select(String? id) async {
- if (selectedId case final current?) {
- _drafts[current] = (
- text: draft,
- from: from,
- to: to,
- exchange: selectedExchange,
- );
- }
- _epoch++;
- selectedId = id;
- team = null;
- final saved = _drafts[id];
- draft = saved?.text ?? '';
- from = saved?.from;
- to = saved?.to;
- selectedExchange = saved?.exchange;
- error = null;
- loading = true;
- _notify();
- // A slow reply for the previous team must not hold up the newly selected one.
- await _read();
- }
-
- void edit() => _notify();
-
- /// The caller captures tab and agent before any await. Retries retain that
- /// instruction's identity, even after focus changes or the view is closed.
- Future<String> consult(String machineId, String agentId) {
- final key = '$machineId/$agentId';
- return _consultFlights[key] ??= _consult(machineId, agentId, key)
- .whenComplete(() {
- _consultFlights.remove(key);
- });
- }
-
- Future<String> _consult(String machineId, String agentId, String key) async {
- if (channelTabId == null) return 'Choose a swarm first.';
- final attempt = _consultAttempts.putIfAbsent(
- key,
- () => {
- 'action': 'channel_consult',
- 'tabId': channelTabId,
- 'id': teamOperationId(),
- 'from': {'machineId': machineId, 'agentId': agentId},
- },
- );
- try {
- final result = await _call(attempt);
- if (_disposed) return 'Swarm instruction sent.';
- _consultAttempts.remove(key);
- error = null;
- final receipt = (result['consultation'] as Map?)?['receipt'] as Map?;
- _notify();
- return 'Consult swarm · ${teamDeliveryLabel(receipt?.cast<String, dynamic>())}';
- } catch (e) {
- if (e is TeamRequestError && !e.uncertain) _consultAttempts.remove(key);
- final message =
- '$e${_consultAttempts.containsKey(key) ? ' Retry consult to check the same instruction.' : ''}';
- if (!_disposed) {
- error = message;
- _notify();
- }
- return message;
- }
- }
-
- Future<void> create() async {
- if (operating) return;
- _createAttempt ??= {
- 'action': 'create',
- 'id': teamOperationId(),
- 'name': newName.trim(),
- 'description': newDescription.trim(),
- 'members': newMembers.values
- .map((m) => Map<String, dynamic>.from(m))
- .toList(),
- };
- operating = true;
- error = null;
- _notify();
- try {
- final result = await _call(_createAttempt!);
- if (_disposed) return;
- final created = result['team'] as Map;
- selectedId = created['id'] as String;
- _epoch++;
- _apply(created);
- _createAttempt = null;
- newMembers.clear();
- loading = false;
- } catch (e) {
- if (e is TeamRequestError && !e.uncertain) _createAttempt = null;
- error =
- '$e${_createAttempt != null ? '\nCheck connection retries this same team.' : ''}';
- } finally {
- operating = false;
- _notify();
- }
- }
-
- Future<void> ask() async {
- if (operating ||
- selectedId == null ||
- (!pendingAsk &&
- (draft.trim().isEmpty ||
- from == null ||
- to == null ||
- from == to))) {
- return;
- }
- final id = selectedId!;
- final attempt = _askAttempts.putIfAbsent(
- id,
- () => {
- 'action': 'ask',
- 'teamId': id,
- 'id': teamOperationId(),
- 'from': from,
- 'to': to,
- 'text': draft.trim(),
- },
- );
- operating = true;
- error = null;
- _notify();
- try {
- final result = await _call(attempt);
- if (_disposed) return;
- if (id == selectedId) {
- selectedExchange = (result['exchange'] as Map)['id'] as String;
- draft = '';
- } else if (_drafts[id] case final saved?) {
- _drafts[id] = (
- text: '',
- from: saved.from,
- to: saved.to,
- exchange: (result['exchange'] as Map)['id'] as String,
- );
- }
- _askAttempts.remove(id);
- await _read();
- } catch (e) {
- if (e is TeamRequestError && !e.uncertain) _askAttempts.remove(id);
- error =
- '$e${_askAttempts.containsKey(id) ? '\nCheck send uses the same question ID.' : ''}';
- } finally {
- operating = false;
- _notify();
- }
- }
-
- Future<void> addMember([Map<String, dynamic>? member]) async {
- if (operating || selectedId == null || (!pendingAdd && member == null)) {
- return;
- }
- final id = selectedId!;
- final attempt = _addAttempts.putIfAbsent(
- id,
- () => {
- 'action': 'add_member',
- 'teamId': id,
- 'member': {...member!, 'id': teamOperationId()},
- },
- );
- operating = true;
- error = null;
- _notify();
- try {
- final result = await _call(attempt);
- if (_disposed) return;
- if (id == selectedId) _apply(result['team']);
- _addAttempts.remove(id);
- } catch (e) {
- if (e is TeamRequestError && !e.uncertain) _addAttempts.remove(id);
- error =
- '$e${_addAttempts.containsKey(id) ? '\nCheck teammate retries this same membership.' : ''}';
- } finally {
- operating = false;
- _notify();
- }
- }
-
- Future<void> act(
- String action, [
- Map<String, dynamic> values = const {},
- ]) async {
- if (operating || selectedId == null) return;
- final id = selectedId;
- operating = true;
- error = null;
- _notify();
- try {
- final result = await _call({'action': action, 'teamId': id, ...values});
- if (!_disposed && id == selectedId) {
- _apply(result['team']);
- await _read();
- }
- } catch (e) {
- error = e.toString();
- } finally {
- operating = false;
- _notify();
- }
- }
-
- @override
- void dispose() {
- _disposed = true;
- _epoch++;
- _timer?.cancel();
- super.dispose();
- }
-}
-
-String teamDeliveryLabel(Map<String, dynamic>? receipt) =>
- switch (receipt?['state']) {
- 'pending' => 'Waiting to deliver',
- 'queued' =>
- receipt?['reason'] == 'team_waiting_draft'
- ? 'Waiting for draft'
- : receipt?['reason'] == 'team_waiting_user'
- ? 'Waiting for user'
- : 'Queued',
- 'submitted' => 'Confirming delivery',
- 'delivered' => 'Delivered',
- 'started' => 'Agent accepted input',
- 'received' => 'Read in inbox',
- 'unknown' => 'Delivery unconfirmed',
- 'rejected' => 'Delivery failed',
- 'cancelled' => 'Notice cancelled',
- _ => 'Not sent',
- };
diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dart
index 13826c34f..1b5dd55b6 100644
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@ -142,10 +142,6 @@ class TerminalSession extends ChangeNotifier {
final TerminalFrameSender send;
final TerminalBinarySender sendBinary;
- /// Set by the view receiving input. Capture it with the bytes, before any async send.
- String? inputTabId;
- String? _bufferedInputTabId;
- bool _swarmInput = false;
final Duration resyncTimeout;
/// Forces a fresh transport dial (see `WsConn.forceReconnect`) — called once when the very first
@@ -616,7 +612,6 @@ class TerminalSession extends ChangeNotifier {
// The daemon's answer to a polite open on a terminal somebody else holds: it opened, it
// renders, and it may not type. See [watching].
watching = payload['readOnly'] == true;
- _swarmInput = payload['swarmInput'] == true;
heldBy = watching
? TerminalClientDescriptor.fromJson(payload['heldBy'])
: null;
@@ -1100,13 +1095,12 @@ class TerminalSession extends ChangeNotifier {
/// blind. Set and cleared by the page; null the rest of the time.
Future<bool> Function(String text)? voiceDeliver;
- Future<bool> sendComposerText(String text, {String? tabId}) async {
+ Future<bool> sendComposerText(String text) async {
if (!acceptsInput) return false;
final content = text.trimRight();
if (content.trim().isEmpty) return false;
return send('message', {
'content': content,
- 'tabId': ?(tabId ?? inputTabId),
'agentId': agentId,
'mode': 'auto',
});
@@ -1129,7 +1123,7 @@ class TerminalSession extends ChangeNotifier {
///
/// The caller must check [MachineState.terminalPasteRawAvailable] first: an older CLI does not know
/// this binary kind at all, so sending it there would silently go nowhere.
- Future<bool> pasteText(String text, {String? tabId}) async {
+ Future<bool> pasteText(String text) async {
if (!acceptsInput) return false;
// Forwarded verbatim, including a stray 0x03 — same as _onTerminalOutput/sendComposerText.
if (text.isEmpty) return false;
@@ -1138,7 +1132,6 @@ class TerminalSession extends ChangeNotifier {
final generation = _generation;
final frame = TerminalBinaryFrame(
kind: TerminalBinaryKind.paste,
- tabId: _swarmInput ? (tabId ?? inputTabId) : null,
streamId: currentStreamId,
// Unused server-side (a paste is one self-contained unit, not part of the ordered keystroke
// stream `input`'s seq guards) — kept at 0 rather than threading a second counter for a field
@@ -1305,11 +1298,6 @@ class TerminalSession extends ChangeNotifier {
void _onTerminalOutput(String data) {
if (!acceptsInput || data.isEmpty) return;
data = _spendArmedControl(data);
- final origin = _swarmInput ? inputTabId : null;
- if (_inputBytes.isNotEmpty && _bufferedInputTabId != origin) {
- unawaited(_flushInput());
- }
- _bufferedInputTabId = origin;
final bytes = utf8.encode(data);
final isBoundary =
data.contains('\r') ||
@@ -1354,7 +1342,6 @@ class TerminalSession extends ChangeNotifier {
return;
}
final bytes = List<int>.from(_inputBytes);
- final origin = _bufferedInputTabId;
_inputBytes.clear();
_lastInputFlushAt = DateTime.now();
final currentStreamId = streamId;
@@ -1389,7 +1376,6 @@ class TerminalSession extends ChangeNotifier {
final end = min(offset + kInputFrameMaxBytes, bytes.length);
final frame = TerminalBinaryFrame(
kind: TerminalBinaryKind.input,
- tabId: origin,
streamId: currentStreamId,
seq: _inputSeq++,
bytes: Uint8List.fromList(bytes.sublist(offset, end)),
diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dart
index 3e7fab43d..cc2685dc5 100644
--- a/mobile/lib/widgets/terminal_panel.dart
+++ b/mobile/lib/widgets/terminal_panel.dart
@@ -39,7 +39,6 @@ class TerminalPanel extends StatefulWidget {
/// Only the focused page may claim keyboard focus on mount/rebuild.
final bool focused;
final bool visible;
- final String? tabId;
/// True while the software keyboard is mid-animation and the pane's height is
/// still a moving target.
@@ -100,7 +99,6 @@ class TerminalPanel extends StatefulWidget {
required this.session,
required this.focused,
this.visible = true,
- this.tabId,
this.settling = false,
this.focusRequest = 0,
this.scrollback,
@@ -224,9 +222,6 @@ class _TerminalPanelState extends State<TerminalPanel>
@override
void didUpdateWidget(TerminalPanel oldWidget) {
super.didUpdateWidget(oldWidget);
- if (widget.visible && _focusNode.hasFocus) {
- widget.session.inputTabId = widget.tabId;
- }
if (oldWidget.jumpToEndRequest != widget.jumpToEndRequest) _jumpToEnd();
if (!identical(oldWidget.session, widget.session)) {
_previewCancellation?.cancel();
@@ -458,7 +453,6 @@ class _TerminalPanelState extends State<TerminalPanel>
}
void _handleFocusChange() {
- if (_focusNode.hasFocus) widget.session.inputTabId = widget.tabId;
_syncCursorBlink();
}
@@ -820,7 +814,6 @@ class _TerminalPanelState extends State<TerminalPanel>
/// is the one hook that runs BEFORE its shortcut map (terminal_view.dart), so
/// this is where the binding has to be replaced rather than added.
KeyEventResult _onTerminalKey(FocusNode node, KeyEvent event) {
- widget.session.inputTabId = widget.tabId;
if (event is! KeyDownEvent) return KeyEventResult.ignored;
if (event.logicalKey != LogicalKeyboardKey.keyV) {
return KeyEventResult.ignored;
diff --git a/mobile/test/channel_controller_test.dart b/mobile/test/channel_controller_test.dart
deleted file mode 100644
index 4c10fe758..000000000
--- a/mobile/test/channel_controller_test.dart
+++ /dev/null
@@ -1,93 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness_mobile/teams/team_controller.dart';
-
-import 'support/team_fixture.dart';
-
-void main() {
- test(
- 'channel history opens directly and only reads its pinned tab',
- () async {
- final calls = <Map<String, dynamic>>[];
- final controller = TeamController(
- channelTabId: 'device',
- request: (p) async {
- calls.add(p);
- return {
- 'team': {
- ...teamFixture(),
- 'channel': {'tabId': 'device'},
- },
- };
- },
- );
- addTearDown(controller.dispose);
- controller.watch();
- await controller.refresh();
- controller.unwatch();
- expect(calls, [
- {'action': 'channel_get', 'tabId': 'device'},
- ]);
- expect(controller.isChannel, isTrue);
- expect(controller.selectedExchange, questionId);
- },
- );
-
- test(
- 'uncertain consult retries the same source and joins repeated keypresses',
- () async {
- final calls = <Map<String, dynamic>>[];
- final pending = Completer<Map<String, dynamic>>();
- final controller = TeamController(
- channelTabId: 'device',
- request: (p) {
- calls.add(p);
- if (calls.length == 1) return pending.future;
- return Future.value({
- 'consultation': {
- 'receipt': {'state': 'queued'},
- },
- });
- },
- );
- addTearDown(controller.dispose);
- final first = controller.consult('host', 'mobile');
- final repeated = controller.consult('host', 'mobile');
- expect(identical(first, repeated), isTrue);
- pending.completeError(TimeoutException('Lost reply'));
- expect(await first, contains('same instruction'));
- await controller.consult('host', 'mobile');
- expect(calls[1], calls[0]);
- expect(calls[0]['tabId'], 'device');
- expect(calls[0]['from'], {'machineId': 'host', 'agentId': 'mobile'});
- await controller.consult('host', 'firmware');
- expect(calls[2]['id'], isNot(calls[0]['id']));
- expect(calls.map((p) => p['action']), everyElement('channel_consult'));
- },
- );
-
- test(
- 'a definitive channel refusal does not leave an uncertain instruction',
- () async {
- final ids = <String>[];
- final controller = TeamController(
- channelTabId: 'single',
- request: (p) async {
- ids.add(p['id'] as String);
- return {
- 'error': 'NO_PEERS',
- 'detail': 'Add another agent to this swarm.',
- };
- },
- );
- addTearDown(controller.dispose);
- expect(
- await controller.consult('host', 'mobile'),
- contains('Add another agent'),
- );
- await controller.consult('host', 'mobile');
- expect(ids.toSet(), hasLength(2));
- },
- );
-}
diff --git a/mobile/test/channel_page_test.dart b/mobile/test/channel_page_test.dart
deleted file mode 100644
index fc9e15bae..000000000
--- a/mobile/test/channel_page_test.dart
+++ /dev/null
@@ -1,78 +0,0 @@
-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_mobile/phone/team_page.dart';
-import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
-import 'package:harness_mobile/teams/team_controller.dart';
-
-import 'support/real_fonts.dart';
-import 'support/team_fixture.dart';
-
-void main() {
- setUpAll(loadRealFonts);
- testWidgets('phone channel follows its tab with read-only history', (
- tester,
- ) async {
- tester.view.devicePixelRatio = 1;
- tester.view.physicalSize = const Size(390, 844);
- addTearDown(tester.view.reset);
- final calls = <Map<String, dynamic>>[];
- final model = TeamController(
- channelTabId: 'devices',
- request: (p) async {
- calls.add(p);
- return {
- 'team': {
- ...teamFixture(),
- 'name': 'Device',
- 'channel': {'tabId': 'devices'},
- },
- };
- },
- );
- final capture = GlobalKey();
- await tester.pumpWidget(
- RepaintBoundary(
- key: capture,
- child: MaterialApp(
- debugShowCheckedModeBanner: false,
- theme: grid.buildAppTheme(brightness: Brightness.dark),
- home: PhoneTeamView(
- controller: model,
- machineName: 'Mac',
- candidates: const [],
- onOpen: (_, _) {},
- ),
- ),
- ),
- );
- await tester.pumpAndSettle();
- expect(find.text('Device'), findsOneWidget);
- expect(find.byKey(const Key('phone-team-new')), findsNothing);
- expect(find.byKey(const Key('phone-team-question')), findsNothing);
- expect(calls.map((p) => p['action']), everyElement('channel_get'));
- expect(find.text('[ Ask outside this swarm ]'), findsNothing);
- await tester.ensureVisible(find.textContaining('Use GET /api/daemons.'));
- await tester.pumpAndSettle();
- expect(tester.takeException(), isNull);
- final output = Platform.environment['CHANNEL_RENDER_DIR'];
- if (output != null) {
- await tester.runAsync(() async {
- final boundary =
- capture.currentContext!.findRenderObject()!
- as RenderRepaintBoundary;
- final image = await boundary.toImage();
- final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
- await Directory(output).create(recursive: true);
- await File('$output/channel-phone-390.png')
- .writeAsBytes(bytes!.buffer.asUint8List());
- image.dispose();
- });
- }
- await tester.pumpWidget(const SizedBox());
- model.dispose();
- });
-}
diff --git a/mobile/test/e2ee/strict_down_test.dart b/mobile/test/e2ee/strict_down_test.dart
index 7a5f1b77a..2ac8ff9e2 100644
--- a/mobile/test/e2ee/strict_down_test.dart
+++ b/mobile/test/e2ee/strict_down_test.dart
@@ -46,25 +46,18 @@ Future<RelaySessionCrypto> _session(Map<String, Object> features) async {
}
void main() {
- test('team capabilities and peer content are always sealed', () async {
+ test('what a person types for an agent is always sealed', () async {
for (final features in [
<String, Object>{},
<String, Object>{'strictDown': 1},
]) {
final session = await _session(features);
- for (final type in ['team', 'team_delivery']) {
- final out = session.wrapOutgoing({
- 'type': type,
- 'payload': {
- 'requestId': 'team-1',
- 'memberKey': 'private-capability',
- 'text': 'private-question',
- },
- });
- expect(isWrapped(out['payload']), isTrue, reason: type);
- expect(jsonEncode(out), isNot(contains('private-capability')));
- expect(jsonEncode(out), isNot(contains('private-question')));
- }
+ final out = session.wrapOutgoing({
+ 'type': 'message',
+ 'payload': {'agentId': 'a1', 'content': 'private-question'},
+ });
+ expect(isWrapped(out['payload']), isTrue);
+ expect(jsonEncode(out), isNot(contains('private-question')));
}
});
diff --git a/mobile/test/encrypted_down_types_test.dart b/mobile/test/encrypted_down_types_test.dart
index 58bc06d2f..4cb4206d7 100644
--- a/mobile/test/encrypted_down_types_test.dart
+++ b/mobile/test/encrypted_down_types_test.dart
@@ -65,7 +65,7 @@ void main() {
...machineRequests,
...namesIn(frames, 'FLEET_REQUESTS'),
...namesIn(cli('sharing/protocol.ts'), 'SHARE_REQUEST_TYPES'),
- ...namesIn(cli('teams/wire.ts'), 'TEAM_REQUEST_TYPES'),
+ ...namesIn(cli('messages/wire.ts'), 'AGENT_MESSAGES_REQUEST_TYPES'),
...namesIn(cli('lib/viewerFrames.ts'), 'VIEWER_DOWN_TYPES'),
};
});
diff --git a/mobile/test/swarm_prompt_scope_test.dart b/mobile/test/swarm_prompt_scope_test.dart
deleted file mode 100644
index 36a39f544..000000000
--- a/mobile/test/swarm_prompt_scope_test.dart
+++ /dev/null
@@ -1,121 +0,0 @@
-import 'dart:convert';
-import 'dart:typed_data';
-
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness_mobile/terminal/terminal_binary.dart';
-import 'package:harness_mobile/terminal/terminal_session.dart';
-
-void main() {
- const stream = '00112233-4455-6677-8899-aabbccddeeff';
- late TerminalSession session;
- late List<TerminalBinaryFrame> frames;
- late List<({String type, Map<String, dynamic> payload})> messages;
-
- setUp(() {
- frames = [];
- messages = [];
- session = TerminalSession(
- machineId: 'machine',
- agentId: 'shared-session',
- agentName: 'Codex',
- engineId: 'codex',
- send: (type, payload) async {
- messages.add((type: type, payload: payload));
- return true;
- },
- sendBinary: (frame) async {
- frames.add(frame);
- return true;
- },
- );
- });
- tearDown(() => session.dispose());
-
- Future<void> ready({bool scoped = true}) async {
- await session.open(initialCols: 100, initialRows: 30);
- await session.handleFrame('terminal_ready', {
- 'requestId': messages.single.payload['requestId'],
- 'protocolVersion': 3,
- 'streamId': stream,
- 'agentId': 'shared-session',
- 'swarmInput': scoped,
- });
- await session.handleBinary(
- TerminalBinaryFrame(
- kind: TerminalBinaryKind.keyframe,
- streamId: stream,
- seq: 0,
- bytes: Uint8List(0),
- compressed: false,
- cols: 100,
- rows: 30,
- ),
- );
- }
-
- test('a shared session captures each view’s origin before coalescing and async sends', () async {
- await ready();
- session.inputTabId = 'swarm-a';
- session.terminal.textInput('first');
- session.terminal.textInput(' second');
- session.inputTabId = 'swarm-b';
- session.terminal.textInput(' third');
- session.inputTabId =
- 'swarm-c'; // Looking elsewhere never retargets pending bytes.
- await Future<void>.delayed(const Duration(milliseconds: 20));
- final input = frames
- .where((frame) => frame.kind == TerminalBinaryKind.input)
- .toList();
- expect(input.map((frame) => frame.tabId), [
- 'swarm-a',
- 'swarm-a',
- 'swarm-b',
- ]);
- expect(
- input.map((frame) => utf8.decode(frame.bytes)).join(),
- 'first second third',
- );
- expect(input.map((frame) => frame.seq), [0, 1, 2]);
- });
-
- test('composer and delayed clipboard submissions carry their explicit source pane', () async {
- await ready();
- session.inputTabId = 'swarm-b';
- await session.sendComposerText('task from A', tabId: 'swarm-a');
- expect(messages.last.payload, containsPair('tabId', 'swarm-a'));
- await session.pasteText('clipboard from A', tabId: 'swarm-a');
- expect(frames.last.tabId, 'swarm-a');
- expect(session.inputTabId, 'swarm-b');
- });
-
- test('older daemons receive the original binary format', () async {
- await ready(scoped: false);
- session.inputTabId = 'swarm-a';
- session.terminal.textInput('hello');
- await Future<void>.delayed(const Duration(milliseconds: 20));
- expect(
- frames.where((f) => f.kind == TerminalBinaryKind.input).single.tabId,
- isNull,
- );
- });
-
- test('scoped local input matches the CLI wire fixture and rejects truncated metadata', () {
- final encoded = encodeTerminalLocal(
- TerminalBinaryFrame(
- kind: TerminalBinaryKind.input,
- streamId: stream,
- seq: 3,
- bytes: Uint8List.fromList(utf8.encode('xin chào\r')),
- compressed: false,
- tabId: 'swarm-a',
- ),
- )!;
- expect(
- encoded.map((b) => b.toRadixString(16).padLeft(2, '0')).join(),
- '4854524c010102000000002a00112233445566778899aabbccddeeff000000000000000307737761726d2d6178696e206368c3a06f0d',
- );
- expect(decodeTerminalLocal(encoded)?.tabId, 'swarm-a');
- encoded[36] = 129;
- expect(decodeTerminalLocal(encoded), isNull);
- });
-}
diff --git a/mobile/test/team_controller_test.dart b/mobile/test/team_controller_test.dart
deleted file mode 100644
index dac3124ee..000000000
--- a/mobile/test/team_controller_test.dart
+++ /dev/null
@@ -1,176 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness_mobile/teams/team_controller.dart';
-
-import 'support/team_fixture.dart';
-
-void main() {
- test('watch and reopen only read; stopping a view stops polling', () async {
- final calls = <Map<String, dynamic>>[];
- final controller = TeamController(
- request: (p) async {
- calls.add(p);
- return {'teams': []};
- },
- );
- addTearDown(controller.dispose);
- controller.watch();
- await controller.refresh();
- controller.unwatch();
- controller.watch();
- await controller.refresh();
- controller.unwatch();
- expect(calls.map((p) => p['action']), everyElement('list'));
- expect(calls.length, 2);
- });
- test(
- 'uncertain creation retries its original ID and original roster',
- () async {
- final calls = <Map<String, dynamic>>[];
- final controller = TeamController(
- request: (p) async {
- calls.add(p);
- if (calls.length == 1) throw TimeoutException('Connection lost');
- return {
- 'team': {...teamFixture(), 'id': p['id']},
- };
- },
- );
- addTearDown(controller.dispose);
- controller.newMembers['one'] = {
- 'machineId': 'host',
- 'agentId': 'one',
- 'name': 'one',
- };
- await controller.create();
- expect(controller.pendingCreate, isTrue);
- controller.newName = 'Edited after timeout';
- controller.newMembers.clear();
- await controller.create();
- expect(calls[1], calls[0]);
- expect(controller.pendingCreate, isFalse);
- },
- );
- test(
- 'uncertain ask retries one question; a definitive refusal permits editing',
- () async {
- final sends = <Map<String, dynamic>>[];
- final controller = TeamController(
- request: (p) async {
- if (p['action'] == 'get') return {'team': teamFixture()};
- sends.add(p);
- if (sends.length == 1) throw TimeoutException('Lost acknowledgement');
- if (sends.length == 3) throw const TeamRequestError('Team paused');
- return {
- 'exchange': {'id': p['id']},
- };
- },
- );
- addTearDown(controller.dispose);
- await controller.select(teamId);
- controller.draft = 'Which endpoint?';
- await controller.ask();
- expect(controller.pendingAsk, isTrue);
- controller.draft = 'Different draft';
- await controller.ask();
- expect(sends[1], sends[0]);
- expect(controller.draft, isEmpty);
- controller.draft = 'New question';
- await controller.ask();
- expect(controller.pendingAsk, isFalse);
- expect(controller.draft, 'New question');
- expect(sends[2]['id'], isNot(sends[0]['id']));
- },
- );
- test(
- 'late refresh cannot replace a newer revision or another team',
- () async {
- final stale = Completer<Map<String, dynamic>>();
- var reads = 0;
- final controller = TeamController(
- request: (p) async {
- reads++;
- if (reads == 2) return stale.future;
- return {'team': teamFixture(id: p['teamId'] as String, revision: 4)};
- },
- );
- addTearDown(controller.dispose);
- await controller.select(teamId);
- controller.draft = 'Keep this draft';
- final slow = controller.refresh();
- await controller.select(otherTeamId);
- stale.complete({'team': teamFixture(revision: 99)});
- await slow;
- expect(controller.team?['id'], otherTeamId);
- await controller.select(teamId);
- expect(controller.draft, 'Keep this draft');
- controller.team!['revision'] = 9;
- await controller.refresh();
- expect(controller.team?['revision'], 9);
- },
- );
- test(
- 'a send completed after changing teams clears only its own saved draft',
- () async {
- final sent = Completer<Map<String, dynamic>>();
- final controller = TeamController(
- request: (p) async => p['action'] == 'ask'
- ? sent.future
- : {'team': teamFixture(id: p['teamId'] as String)},
- );
- addTearDown(controller.dispose);
- await controller.select(teamId);
- controller.draft = 'Sent draft';
- final sending = controller.ask();
- await controller.select(otherTeamId);
- controller.draft = 'Unrelated draft';
- sent.complete({
- 'exchange': {'id': questionId},
- });
- await sending;
- expect(controller.draft, 'Unrelated draft');
- await controller.select(teamId);
- expect(controller.draft, isEmpty);
- expect(controller.selectedExchange, questionId);
- },
- );
- test(
- 'adding a teammate reconciles an uncertain membership with the same ID',
- () async {
- final additions = <Map<String, dynamic>>[];
- final controller = TeamController(
- request: (p) async {
- if (p['action'] == 'add_member') {
- additions.add(p);
- if (additions.length == 1) throw TimeoutException('Lost reply');
- }
- return {'team': teamFixture()};
- },
- );
- addTearDown(controller.dispose);
- await controller.select(teamId);
- await controller.addMember({
- 'machineId': 'host',
- 'agentId': 'firmware',
- 'name': 'firmware',
- });
- expect(controller.pendingAdd, isTrue);
- await controller.addMember();
- expect(additions[1], additions[0]);
- expect(controller.pendingAdd, isFalse);
- },
- );
- test(
- 'disposal ignores a delayed response and never cancels daemon work',
- () async {
- final pending = Completer<Map<String, dynamic>>();
- final controller = TeamController(request: (p) => pending.future);
- final loading = controller.select(teamId);
- controller.dispose();
- pending.complete({'team': teamFixture()});
- await loading;
- expect(controller.team, isNull);
- },
- );
-}
diff --git a/mobile/test/team_page_test.dart b/mobile/test/team_page_test.dart
deleted file mode 100644
index 056375af1..000000000
--- a/mobile/test/team_page_test.dart
+++ /dev/null
@@ -1,149 +0,0 @@
-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_mobile/phone/team_page.dart';
-import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
-import 'package:harness_mobile/teams/team_controller.dart';
-
-import 'support/real_fonts.dart';
-import 'support/team_fixture.dart';
-
-const candidates = [
- PhoneTeamCandidate(
- machineId: 'host',
- agentId: 'mobile-session',
- name: 'Mobile',
- engine: 'claude',
- available: true,
- ),
- PhoneTeamCandidate(
- machineId: 'host',
- agentId: 'daemon-session',
- name: 'Daemons',
- engine: 'codex',
- available: true,
- ),
-];
-void main() {
- setUpAll(loadRealFonts);
- testWidgets(
- 'phone connects only after explicit selection and keeps sends correlated',
- (tester) async {
- final calls = <Map<String, dynamic>>[];
- final model = TeamController(
- request: (p) async {
- calls.add(p);
- if (p['action'] == 'list') return {'teams': []};
- if (p['action'] == 'create') {
- return {
- 'team': {...teamFixture(answered: false), 'id': p['id']},
- };
- }
- return {
- 'team': {...teamFixture(answered: false), 'id': modelId(calls)},
- };
- },
- );
- await tester.pumpWidget(
- MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.dark),
- home: PhoneTeamView(
- controller: model,
- machineName: 'Mac',
- candidates: candidates,
- onOpen: (_, _) {},
- ),
- ),
- );
- addTearDown(() async {
- await tester.pumpWidget(const SizedBox());
- model.dispose();
- });
- await tester.pumpAndSettle();
- await tester.tap(find.byKey(const Key('phone-team-new')));
- await tester.pumpAndSettle();
- for (final id in ['mobile-session', 'daemon-session']) {
- final candidate = find.byKey(ValueKey('phone-team-candidate-$id'));
- await tester.ensureVisible(candidate);
- await tester.tap(candidate);
- await tester.pumpAndSettle();
- }
- expect(calls.map((p) => p['action']), everyElement('list'));
- final connect = find.byKey(const Key('phone-team-connect'));
- await tester.ensureVisible(connect);
- await tester.tap(connect);
- await tester.pumpAndSettle();
- expect(calls.where((p) => p['action'] == 'create'), hasLength(1));
- expect(
- calls.firstWhere((p) => p['action'] == 'create')['members'],
- hasLength(2),
- );
- expect(tester.takeException(), isNull);
- },
- );
-
- for (final width in [320.0, 390.0]) {
- testWidgets('phone shows the answer and continuation at width $width', (
- tester,
- ) async {
- tester.view.devicePixelRatio = 1;
- tester.view.physicalSize = Size(width, 844);
- addTearDown(tester.view.reset);
- final calls = <Map<String, dynamic>>[];
- final model = TeamController(
- request: (p) async {
- calls.add(p);
- return {'team': teamFixture()};
- },
- );
- await model.select(teamId);
- model.selectedExchange = questionId;
- final key = GlobalKey();
- await tester.pumpWidget(
- RepaintBoundary(
- key: key,
- child: MaterialApp(
- debugShowCheckedModeBanner: false,
- theme: grid.buildAppTheme(brightness: Brightness.dark),
- home: PhoneTeamView(
- controller: model,
- machineName: 'Mac',
- candidates: candidates,
- onOpen: (_, _) {},
- ),
- ),
- ),
- );
- addTearDown(() async {
- await tester.pumpWidget(const SizedBox());
- model.dispose();
- });
- await tester.pumpAndSettle();
- await tester.ensureVisible(find.textContaining('Agent question'));
- await tester.pumpAndSettle();
- expect(find.textContaining('Use GET /api/daemons.'), findsOneWidget);
- expect(find.textContaining('Waiting for draft'), findsOneWidget);
- expect(calls.every((p) => p['action'] == 'get'), isTrue);
- expect(tester.takeException(), isNull);
- final output = Platform.environment['HARNESS_TEAM_CAPTURE_DIR'];
- if (output != null) {
- await tester.runAsync(() async {
- final boundary =
- key.currentContext!.findRenderObject()! as RenderRepaintBoundary;
- final image = await boundary.toImage(pixelRatio: 1);
- final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
- await Directory(output).create(recursive: true);
- await File('$output/phone-team-${width.toInt()}.png')
- .writeAsBytes(bytes!.buffer.asUint8List());
- image.dispose();
- });
- }
- });
- }
-}
-
-String modelId(List<Map<String, dynamic>> calls) =>
- calls.firstWhere((p) => p['action'] == 'create')['id'] as String;