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.

Web: Swarm chats load and send straight from the backend, no machine needed (#2306)

0xken157b29783493c1
diff --git a/backend/integration/superTabBuddies.test.ts b/backend/integration/superTabBuddies.test.ts
index 7384144cb..18c4d483d 100644
--- a/backend/integration/superTabBuddies.test.ts
+++ b/backend/integration/superTabBuddies.test.ts
@@ -840,3 +840,73 @@ describe('a Buddy on its person\'s own machine outside the Swarm, through the st
expect(await a.store.otherWorkspaceMachines(db, stateA)).toEqual([])
})
})
+
+describe('the person\'s own browser, reading and writing the Swarm straight from the web (docs/specs/2026-10-30-web-swarm-direct.md)', () => {
+ // A browser signed in by a computer's QR holds a viewer session; one signed in with Autonomous holds the person's own
+ // token (`peer` here). Either is the person, as their own Mac's sign-in that relayed the web's requests until now.
+ const peerWeb: AuthUser = { ...peer, harnessSessionId: 'peer-web-session', harnessSessionKind: 'viewer' }
+ const ownerWeb: AuthUser = { ...owner, harnessSessionId: 'owner-web-session', harnessSessionKind: 'viewer' }
+ const refusal = (read: Promise<unknown>) => read.then(() => null, (error: { code?: string; status?: number; message?: string }) =>
+ ({ code: error.code, status: error.status, message: error.message }))
+
+ it('reads the Swarm list, the Swarm and its person\'s Buddy chat, and posts there, exactly as their own Mac does', async () => {
+ const f = await swarm()
+ const { chat } = await buddy(f)
+ await f.execute({ type: 'message.send', conversationId: chat, text: 'From the browser', replyTo: null, recipientIds: [] }, peerWeb)
+ await f.execute({ type: 'message.send', conversationId: chat, text: 'From the Mac', replyTo: null, recipientIds: [] }, peerMac)
+ const reads = new SwarmReads(f.store)
+ for (const signIn of [peerWeb, peer]) {
+ expect((await reads.list(signIn)).tabs.map(t => t.id)).toEqual((await reads.list(peerMac)).tabs.map(t => t.id))
+ const keys = (await reads.firstLoad(signIn, f.tab)).groups.map(g => g.key).sort()
+ expect(keys).toEqual((await reads.firstLoad(peerMac, f.tab)).groups.map(g => g.key).sort())
+ expect(keys).toContain(chat)
+ expect((await f.store.messages(signIn, f.tab, chat, {})).messages.map(m => m.text))
+ .toEqual((await f.store.messages(peerMac, f.tab, chat, {})).messages.map(m => m.text))
+ }
+ expect((await f.store.messages(peerWeb, f.tab, chat, {})).messages.map(m => m.text))
+ .toEqual(expect.arrayContaining(['From the browser', 'From the Mac']))
+ })
+
+ it('is refused another person\'s Buddy chat, a private project and another Swarm as their own Mac is, with no name', async () => {
+ const f = await swarm()
+ const { chat } = await buddy(f)
+ const hidden = (await f.execute({ type: 'project.create', name: 'Secret plan', visibility: 'private', brief: '' })).result as
+ { projectId: string; conversationId: string }
+ const task = String((await f.execute({ type: 'conversation.create', projectId: hidden.projectId, title: 'Secret task', brief: '',
+ checks: [] })).result.conversationId)
+ const madeUp = 'groups-000000000000000000000000'
+ // The owner's browser, on peer's Buddy chat.
+ const othersBuddy = await refusal(f.store.messages(ownerWeb, f.tab, chat, {}))
+ expect(othersBuddy).not.toBeNull()
+ expect(othersBuddy).toEqual(await refusal(f.store.messages(ownerWeb, f.tab, madeUp, {})))
+ expect((await new SwarmReads(f.store).firstLoad(ownerWeb, f.tab)).groups.map(g => g.key)).not.toContain(chat)
+ // peer's browser, on the owner's private project: refused as their own Mac is, and with no name. (The server says
+ // "project" here and "conversation" for an id that does not exist, for every sign-in alike; reported, not changed here.)
+ for (const id of [hidden.conversationId, task]) {
+ const refused = await refusal(f.store.messages(peerWeb, f.tab, id, {}))
+ expect(refused).toMatchObject({ code: 'NOT_FOUND', status: 404 })
+ expect(refused).toEqual(await refusal(f.store.messages(peerMac, f.tab, id, {})))
+ expect(JSON.stringify(refused)).not.toMatch(/Secret/)
+ }
+ const keys = (await new SwarmReads(f.store).firstLoad(peerWeb, f.tab)).groups.map(g => g.key)
+ for (const id of [hidden.conversationId, task]) expect(keys).not.toContain(id)
+ // Another Swarm peer is not in: refused as their own Mac is, with no name. (403 here and 404 for a Swarm that does not
+ // exist, for every sign-in alike; reported, not changed here.)
+ const other = (await f.store.create(owner, randomUUID(), 'Private Swarm', 'private')).id
+ const outside = await refusal(new SwarmReads(f.store).firstLoad(peerWeb, other))
+ expect(outside).not.toBeNull()
+ expect(outside).toEqual(await refusal(new SwarmReads(f.store).firstLoad(peerMac, other)))
+ expect(JSON.stringify(outside)).not.toContain('Private Swarm')
+ })
+
+ it('speaks as an agent only where the person\'s own Mac may, and a team sign-in is still refused', async () => {
+ const f = await swarm()
+ const { agentId } = await buddy(f)
+ for (const asAgent of [agentId, f.lead]) {
+ expect(await refusal(f.store.messages(peerWeb, f.tab, 'lead', {}, asAgent)))
+ .toEqual(await refusal(f.store.messages(peerMac, f.tab, 'lead', {}, asAgent)))
+ }
+ expect(await refusal(f.store.messages(peerWeb, f.tab, 'lead', {}, f.lead))).toMatchObject({ code: 'FORBIDDEN', status: 403 })
+ expect(await refusal(new SwarmReads(f.store).firstLoad(peerTeam, f.tab))).toMatchObject(LIMITED)
+ })
+})
diff --git a/backend/src/lib/corsOptions.test.ts b/backend/src/lib/corsOptions.test.ts
new file mode 100644
index 000000000..c4a6a65e4
--- /dev/null
+++ b/backend/src/lib/corsOptions.test.ts
@@ -0,0 +1,25 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import Fastify, { type FastifyInstance } from 'fastify'
+import cors from '@fastify/cors'
+import { CORS_OPTIONS } from './corsOptions.js'
+
+// The web signs every Swarm call with an Authorization header, so a browser asks first (a preflight) before each one
+// unless it may keep the answer (docs/specs/2026-10-30-web-swarm-direct.md, Scale).
+describe('CORS', () => {
+ let app: FastifyInstance
+ afterEach(async () => { await app?.close() })
+
+ it('lets a browser keep a preflight\'s answer for ten minutes, and still reflects only the asking origin', async () => {
+ app = Fastify()
+ await app.register(cors, CORS_OPTIONS)
+ app.post('/api/super-tabs/:tabId/commands', async () => ({ ok: true }))
+ await app.ready()
+ const res = await app.inject({ method: 'OPTIONS', url: '/api/super-tabs/tab-1/commands', headers: {
+ origin: 'https://harness.example', 'access-control-request-method': 'POST',
+ 'access-control-request-headers': 'authorization,content-type,x-autonomous-env' } })
+ expect(res.statusCode).toBe(204)
+ expect(res.headers['access-control-max-age']).toBe('600')
+ expect(res.headers['access-control-allow-origin']).toBe('https://harness.example')
+ expect(res.headers['access-control-allow-headers']).toBe('authorization,content-type,x-autonomous-env')
+ })
+})
diff --git a/backend/src/lib/corsOptions.ts b/backend/src/lib/corsOptions.ts
new file mode 100644
index 000000000..edeca0812
--- /dev/null
+++ b/backend/src/lib/corsOptions.ts
@@ -0,0 +1,14 @@
+import type { FastifyCorsOptions } from '@fastify/cors'
+
+/**
+ * The control API's CORS (server.ts). Allow all origins (reflect the request origin so credentialed requests work too).
+ * Methods + headers are reflected (allowedHeaders omitted → echoes Access-Control-Request-Headers), so any client header
+ * (Authorization, x-api-key, …) passes preflight. A browser keeps a preflight's answer for 10 minutes (the most Safari
+ * keeps): the web signs every Swarm call with Authorization, which would otherwise cost a preflight per call.
+ */
+export const CORS_OPTIONS: FastifyCorsOptions = {
+ origin: true,
+ credentials: true,
+ methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE', 'OPTIONS'],
+ maxAge: 600,
+}
diff --git a/backend/src/routes/superTabs.test.ts b/backend/src/routes/superTabs.test.ts
index 85dd973f2..ddb47336f 100644
--- a/backend/src/routes/superTabs.test.ts
+++ b/backend/src/routes/superTabs.test.ts
@@ -1,7 +1,54 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import Fastify, { type FastifyInstance } from 'fastify'
import { Prisma } from '@prisma/client'
+
+// Real Harness sessions for the sign-in tests below, minted and redeemed through lib/harnessSession.ts against in-memory
+// stores, as routes/control.test.ts does, so the real authentication and team gate run.
+const fakes = vi.hoisted(() => {
+ const redis = new Map<string, string>()
+ const sessions: Array<Record<string, unknown> & { id: string }> = []
+ const pick = (where: Record<string, unknown>) => sessions.find(s => Object.entries(where).every(([k, v]) => s[k] === v)) ?? null
+ return {
+ pub: {
+ set: vi.fn(async (key: string, value: string) => { redis.set(key, value); return 'OK' }),
+ get: vi.fn(async (key: string) => redis.get(key) ?? null),
+ multi: vi.fn(() => {
+ const ops: Array<() => unknown> = []
+ const chain = {
+ get: (key: string) => { ops.push(() => redis.get(key) ?? null); return chain },
+ del: (key: string) => { ops.push(() => (redis.delete(key) ? 1 : 0)); return chain },
+ exec: async () => ops.map(op => [null, op()]),
+ }
+ return chain
+ }),
+ },
+ prisma: {
+ harnessSession: {
+ create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {
+ const row = { id: `s${sessions.length + 1}`, ...data }; sessions.push(row); return row
+ }),
+ findUnique: vi.fn(async ({ where }: { where: Record<string, unknown> }) => pick(where)),
+ },
+ machine: {
+ findMany: vi.fn(async ({ where }: { where: Record<string, unknown> }) => where.computerId === 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
+ ? [{ machineId: 'team-mac', userId: 'owner', computerId: where.computerId, billingStatus: 'not_required', sessionKind: 'team' }] : []),
+ },
+ },
+ user: { id: 'owner', email: '[email protected]', role: 'user', autonomousEnv: 'prod' },
+ }
+})
+vi.mock('../lib/bus.js', () => ({ pub: fakes.pub }))
+vi.mock('../lib/prisma.js', () => ({ prisma: fakes.prisma, machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] } }))
+vi.mock('../services/UserService.js', () => ({
+ userService: { get: vi.fn(async (id: string) => id === fakes.user.id ? fakes.user : null) },
+ normalizeUserEmail: (email: string) => email.trim().toLowerCase(),
+ isProvisionalUserEmail: () => false,
+}))
+
import { errorHandler } from '../middlewares/errorHandler.js'
+import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'
+import { redeemHandoff, startHandoff } from '../lib/harnessSession.js'
+import type { AuthUser } from '../lib/ssoAuth.js'
import { SuperTabError } from '../superTabs/model.js'
import { HOT_BODY_LIMIT, superTabRoutes } from './superTabs.js'
@@ -98,3 +145,57 @@ describe('Super Tab body limits (roadmap 2.8)', () => {
expect(HOT_BODY_LIMIT).toBeLessThan(2 * Math.max(...sizes))
})
})
+
+// The web calls Swarm routes straight from the browser with the person's own sign-in (docs/specs/2026-10-30-web-swarm-
+// direct.md): a viewer session reaches them as the person, through the real authentication; a team sign-in is still
+// refused as the person (the store refuses it on the routes the team gate admits for its agents, superTabBuddies).
+describe('the browser\'s own sign-in on Swarm routes', () => {
+ let app: FastifyInstance
+ let viewer: string, team: string
+ const seen: Array<{ route: string; user: AuthUser }> = []
+ beforeAll(async () => {
+ viewer = (await redeemHandoff((await startHandoff(fakes.user.id, 'viewer')).code, 'Safari on iPhone'))!.token
+ team = (await redeemHandoff((await startHandoff(fakes.user.id, 'team')).code, 'MacBook Pro · Team', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'))!.token
+ app = Fastify()
+ app.setErrorHandler(errorHandler)
+ registerAuthMiddleware(app)
+ const reads = {
+ firstLoad: async (user: AuthUser) => { seen.push({ route: 'parts', user }); return { format: 2 } },
+ list: async (user: AuthUser) => { seen.push({ route: 'list', user }); return { tabs: [] } },
+ }
+ const store = { execute: async (user: AuthUser) => { seen.push({ route: 'commands', user }); return { result: { messageId: 'm1' } } } }
+ await app.register(superTabRoutes, { store: store as never, github: null, reads: reads as never, hosts: {} as never })
+ await app.ready()
+ })
+ afterAll(async () => { await app?.close() })
+ beforeEach(() => { seen.length = 0 })
+
+ const command = { operationId: 'op-web-1', command: { type: 'message.send', conversationId: 'buddy-chat', text: 'hi', replyTo: null,
+ recipientIds: [] } }
+
+ it('reads a Swarm and posts in it as the person', async () => {
+ const auth = { authorization: `Bearer ${viewer}` }
+ const read = await app.inject({ method: 'GET', url: '/api/super-tabs/tab-1/parts', headers: auth })
+ expect(read.statusCode).toBe(200)
+ const post = await app.inject({ method: 'POST', url: '/api/super-tabs/tab-1/commands', headers: auth, payload: command })
+ expect(post.statusCode).toBe(200)
+ expect(seen.map(s => s.route)).toEqual(['parts', 'commands'])
+ for (const { user } of seen) expect(user).toMatchObject({ sub: 'owner', harnessSessionKind: 'viewer' })
+ })
+
+ it('refuses a team sign-in as the person, before any Swarm is read', async () => {
+ const auth = { authorization: `Bearer ${team}` }
+ for (const url of ['/api/super-tabs/tab-1/parts', '/api/super-tabs/list']) {
+ const res = await app.inject({ method: 'GET', url, headers: auth })
+ expect(res.statusCode, url).toBe(403)
+ expect(res.json().error.code).toBe('TEAM_SESSION_LIMITED')
+ }
+ expect(seen).toEqual([])
+ })
+
+ it('refuses no sign-in at all', async () => {
+ const res = await app.inject({ method: 'POST', url: '/api/super-tabs/tab-1/commands', payload: command })
+ expect(res.statusCode).toBe(401)
+ expect(seen).toEqual([])
+ })
+})
diff --git a/backend/src/server.ts b/backend/src/server.ts
index 824199c29..0ee7161b5 100644
--- a/backend/src/server.ts
+++ b/backend/src/server.ts
@@ -1,5 +1,6 @@
import 'dotenv/config'
import cors from '@fastify/cors'
+import { CORS_OPTIONS } from './lib/corsOptions.js'
import Fastify from 'fastify'
import http from 'http'
import net from 'net'
@@ -149,14 +150,7 @@ async function start(): Promise<void> {
registerSecurityHeaders(app)
- // Allow all origins (reflect the request origin so credentialed requests work too). Methods +
- // headers are reflected (allowedHeaders omitted → echoes Access-Control-Request-Headers), so any
- // client header (Authorization, x-api-key, …) passes preflight.
- await app.register(cors, {
- origin: true,
- credentials: true,
- methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE', 'OPTIONS'],
- })
+ await app.register(cors, CORS_OPTIONS)
// Every process shares one memory of validated tokens; without it each worker asks the profile API
// for itself. Attached before anything can authenticate — the REST gate below and the socket upgrades.
diff --git a/desktop/lib/api/access_token_source.dart b/desktop/lib/api/access_token_source.dart
index fbf9e7ae6..c6b64207b 100644
--- a/desktop/lib/api/access_token_source.dart
+++ b/desktop/lib/api/access_token_source.dart
@@ -9,3 +9,18 @@ abstract interface class AccessTokenSource {
abstract interface class AccessTokenFailure implements Exception {
bool get signedOut;
}
+
+/// A token source that says which sign-in its tokens belong to: the number
+/// moves whenever someone signs in or out on this device, so a request can
+/// tell that a retry would go out as somebody else.
+abstract interface class SignInRevision {
+ int get signInRevision;
+}
+
+/// A request's sign-in ended before it could be retried: it is not sent
+/// again, as anybody.
+class SignInChanged implements Exception {
+ const SignInChanged();
+ @override
+ String toString() => 'The sign-in changed. Try again.';
+}
diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dart
index da86e4731..7675bdd7f 100644
--- a/desktop/lib/api/api_client.dart
+++ b/desktop/lib/api/api_client.dart
@@ -277,6 +277,20 @@ class ApiClient {
),
);
+ /// One Swarm call ([method] on [path], `/api/super-tabs…`) straight to the
+ /// backend with this browser's sign-in, answered whole: the web's Swarm
+ /// transport (super_tabs/backend_transport.dart) reads the envelope, as a
+ /// machine's relay reads it for a computer.
+ Future<Response<dynamic>> superTabCall(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+ }) => _dio.request<dynamic>(
+ path,
+ data: body,
+ options: Options(method: method),
+ );
+
Future<Map<String, dynamic>?> me() async {
final res = await _dio.get('/api/auth/me');
return unwrapApiResponse(res) as Map<String, dynamic>?;
diff --git a/desktop/lib/api/bearer_auth_interceptor.dart b/desktop/lib/api/bearer_auth_interceptor.dart
index 5386720af..93ff14935 100644
--- a/desktop/lib/api/bearer_auth_interceptor.dart
+++ b/desktop/lib/api/bearer_auth_interceptor.dart
@@ -14,6 +14,16 @@ class BearerAuthInterceptor extends Interceptor {
static const _tokenKey = 'bearer.token';
static const _retriedKey = 'bearer.retried';
+ static const _signInKey = 'bearer.signIn';
+
+ /// Whether someone signed in or out here since [options] went out (as the
+ /// daemon's account fence asks): its retry would then go out as another
+ /// account. A source that cannot say is taken as unchanged.
+ bool _signInMoved(RequestOptions options) => switch (_auth) {
+ final SignInRevision source =>
+ options.extra[_signInKey] != source.signInRevision,
+ _ => false,
+ };
@override
Future<void> onRequest(
@@ -21,6 +31,9 @@ class BearerAuthInterceptor extends Interceptor {
RequestInterceptorHandler handler,
) async {
try {
+ if (_auth case final SignInRevision source) {
+ options.extra[_signInKey] = source.signInRevision;
+ }
final token = await _auth.accessToken();
options.headers['authorization'] = 'Bearer $token';
options.headers['x-autonomous-env'] = autonomousEnv;
@@ -41,11 +54,25 @@ class BearerAuthInterceptor extends Interceptor {
handler.next(response);
return;
}
+ // A 401 for an account that has since signed out is not the current
+ // account's to retry: A's command must never run as B.
+ final changed = DioException(
+ requestOptions: options,
+ error: const SignInChanged(),
+ );
+ if (_signInMoved(options)) {
+ handler.reject(changed);
+ return;
+ }
try {
await _auth.accessToken(
force: true,
failedToken: options.extra[_tokenKey] as String?,
);
+ if (_signInMoved(options)) {
+ handler.reject(changed);
+ return;
+ }
options.extra[_retriedKey] = true;
// A form is read once: the retry sends a copy, as the first try did.
if (options.data case final FormData form) options.data = form.clone();
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 79614780d..2ef88cb46 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -97,6 +97,7 @@ import '../core/local_key_value_store.dart';
import '../core/harness_file_store.dart';
import '../super_tabs/attachment_upload.dart';
import '../super_tabs/avatar_upload.dart';
+import '../super_tabs/backend_transport.dart';
import '../super_tabs/client.dart';
import '../super_tabs/controller.dart';
import '../super_tabs/join_machine.dart';
@@ -1926,6 +1927,10 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
},
transport: (method, path, {body}) async {
+ // The web asks the backend itself, signed as the person in this
+ // browser (docs/specs/2026-10-30-web-swarm-direct.md): no machine of
+ // theirs needs to be online, a Team machine or a slow link in between.
+ if (viewer != null) return _webSuperTabRequest(method, path, body: body);
final target = sharedTabsTarget;
if (target == null) {
if (_teamComputer) {
@@ -1949,6 +1954,60 @@ class AppNotifier extends ChangeNotifier {
},
);
+ late final SuperTabTransport _webSuperTabs = superTabBackendTransport(
+ () => api,
+ );
+
+ /// A backend from before projects refuses `project.create` by its schema:
+ /// the person is told it needs an update, not the schema's words.
+ static SuperTabFailure? _tooOldForProjects(
+ Object? body,
+ String code,
+ String? detail,
+ int status,
+ ) {
+ final command = body is Map ? body['command'] : null;
+ if (command is! Map ||
+ command['type'] != 'project.create' ||
+ code != 'VALIDATION_ERROR' ||
+ detail?.contains('command.type') != true ||
+ detail?.contains('discriminator') != true) {
+ return null;
+ }
+ return SuperTabFailure(
+ 'UPDATE_REQUIRED',
+ 'The Swarm service needs an update before you can create a project. Your draft is saved.',
+ statusCode: status,
+ );
+ }
+
+ /// One Swarm call from the web, straight to the backend. An answer, or a
+ /// refusal, that lands after the account changed is dropped, as a relayed
+ /// one is ([superTabMachineRequest]).
+ Future<Object?> _webSuperTabRequest(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+ }) async {
+ final revision = _authRevision;
+ const changed = SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
+ final Object? value;
+ try {
+ value = await _webSuperTabs(method, path, body: body);
+ } on SuperTabFailure catch (failure) {
+ if (!_authWorkCurrent(revision)) throw changed;
+ throw _tooOldForProjects(
+ body,
+ failure.code,
+ failure.message,
+ failure.statusCode,
+ ) ??
+ failure;
+ }
+ if (!_authWorkCurrent(revision)) throw changed;
+ return value;
+ }
+
Map<String, String> _superTabNames = {};
bool _superTabsEntered = false;
@@ -1997,19 +2056,9 @@ class AppNotifier extends ChangeNotifier {
if (!_authWorkCurrent(revision)) {
return const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
}
- final body = payload['body'];
- final command = body is Map ? body['command'] : null;
- if (payload['action'] == 'backend' &&
- command is Map &&
- command['type'] == 'project.create' &&
- code == 'VALIDATION_ERROR' &&
- detail?.contains('command.type') == true &&
- detail?.contains('discriminator') == true) {
- return SuperTabFailure(
- 'UPDATE_REQUIRED',
- 'The Swarm service needs an update before you can create a project. Your draft is saved.',
- statusCode: status,
- );
+ if (payload['action'] == 'backend') {
+ final old = _tooOldForProjects(payload['body'], code, detail, status);
+ if (old != null) return old;
}
return SuperTabFailure(
code,
@@ -2018,6 +2067,24 @@ class AppNotifier extends ChangeNotifier {
);
}
+ // On the web only what acts on a machine comes here (adding it, sharing
+ // its terminal, waking it): one that cannot do it says why, never the
+ // catch-all (docs/specs/2026-10-30-web-swarm-direct.md).
+ final machine = viewer == null ? null : machineStates[machineId];
+ final name = machine?.machine.displayName;
+ if (machine != null && machine.isOffline) {
+ throw SuperTabFailure(
+ 'MACHINE_UNAVAILABLE',
+ '$name is offline. Open Harness on it, then try again.',
+ );
+ }
+ if (machine != null && machine.machine.isTeamAccount) {
+ throw SuperTabFailure(
+ 'MACHINE_UNAVAILABLE',
+ '$name runs Swarm agents for a Harness Team account, so it cannot do '
+ 'this for you. Use another of your machines.',
+ );
+ }
final Map<String, dynamic> result;
try {
result = await _conn(machineId).request(
@@ -2031,6 +2098,16 @@ class AppNotifier extends ChangeNotifier {
failure.detail,
(failure.payload['status'] as num?)?.toInt() ?? 0,
);
+ } on WsRequestTimeout {
+ if (machine == null) rethrow;
+ if (!_authWorkCurrent(revision)) {
+ throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
+ }
+ throw SuperTabFailure(
+ 'MACHINE_SLOW',
+ '$name is taking too long to answer. Its connection may be slow. '
+ 'Try again.',
+ );
}
if (!_authWorkCurrent(revision)) {
throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
@@ -9381,11 +9458,15 @@ class AppNotifier extends ChangeNotifier {
);
}
}
- // Swarm reads go through a connected machine: the moment one can serve
- // them again, the Swarm on screen reads (`SuperTabReading.readsOnConnect`).
- final served = sharedTabsTarget != null;
- if (served && !_superTabsServed) superTabs.serverAvailable();
- _superTabsServed = served;
+ // Natively, Swarm reads go through this computer's daemon: the moment it
+ // can serve them again, the Swarm on screen reads
+ // (`SuperTabReading.readsOnConnect`). The web reads the backend itself,
+ // so a machine connecting there is no reason to read.
+ if (viewer == null) {
+ final served = sharedTabsTarget != null;
+ if (served && !_superTabsServed) superTabs.serverAvailable();
+ _superTabsServed = served;
+ }
notifyListeners();
}
diff --git a/desktop/lib/super_tabs/backend_transport.dart b/desktop/lib/super_tabs/backend_transport.dart
new file mode 100644
index 000000000..232360432
--- /dev/null
+++ b/desktop/lib/super_tabs/backend_transport.dart
@@ -0,0 +1,94 @@
+import 'dart:convert';
+
+import 'package:dio/dio.dart';
+
+import '../api/access_token_source.dart';
+import '../api/api_client.dart';
+import 'client.dart';
+import 'controller.dart';
+
+/// The Swarm routes the web may call with the browser's own sign-in: the ones
+/// its screens use, and no other. The routes a machine's daemon and its agents
+/// call (hosts, starts, GitHub tokens, deliveries, terminals) are refused
+/// before anything is sent, so this transport never signs them.
+const _tab =
+ r'(?!(?:hosts|workspaces|grids|list|invitations|routing-policy|workspace-invitations)/)[A-Za-z0-9_-]+';
+const _id = r'[A-Za-z0-9_-]+';
+final _swarmRoute = RegExp(
+ '^/api/super-tabs(?:'
+ '|/list|/invitations|/routing-policy'
+ '|/$_tab/(?:parts|changes|commands|mentions|decisions|leaderboard|sharing'
+ '|routing-policy|groups|groups/$_id|join|join/preview|native'
+ '|conversations/$_id/(?:messages|catch-up|read)'
+ '|projects/$_id/(?:github|github/approve|roles/$_id)'
+ '|route-decisions/$_id|machines/$_id/removal)'
+ r')(?:\?[A-Za-z0-9_=&%-]+)?$',
+);
+
+/// The web's Swarm transport (docs/specs/2026-10-30-web-swarm-direct.md):
+/// each call goes straight to the backend, signed as the person in this
+/// browser, and is answered as a machine's relay answered it — the backend's
+/// `data`, or a [SuperTabFailure] with its code, message and status.
+SuperTabTransport superTabBackendTransport(ApiClient Function() api) =>
+ (method, path, {body}) async {
+ if ((method != 'GET' && method != 'POST') ||
+ !_swarmRoute.hasMatch(path)) {
+ throw const SuperTabFailure(
+ 'INVALID_REQUEST',
+ 'Choose a Super Tab endpoint.',
+ );
+ }
+ final Response<dynamic> response;
+ try {
+ response = await api().superTabCall(method, path, body: body);
+ } on DioException catch (error) {
+ throw _unanswered(error);
+ }
+ return _answer(response);
+ };
+
+SuperTabFailure _unanswered(DioException error) {
+ final cause = error.error;
+ if (cause is SignInChanged) {
+ return const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
+ }
+ if (cause is AccessTokenFailure && cause.signedOut) {
+ return const SuperTabFailure('SIGNED_OUT', 'Sign in to use Swarm.');
+ }
+ return const SuperTabFailure(
+ 'NETWORK',
+ 'Could not reach Harness. Check your connection.',
+ );
+}
+
+/// As `backend()` in cli/src/superTabs/wire.ts reads the backend.
+Object? _answer(Response<dynamic> response) {
+ final status = response.statusCode ?? 0;
+ var body = response.data;
+ if (body is String) {
+ try {
+ body = jsonDecode(body);
+ } catch (_) {}
+ }
+ final envelope = body is Map ? body : const {};
+ if (status == 426) {
+ throw SuperTabFailure(
+ 'UPDATE_REQUIRED',
+ SuperTabController.updateMessage,
+ statusCode: 426,
+ );
+ }
+ if (status < 200 || status >= 300 || envelope['success'] != true) {
+ final error = envelope['error'];
+ final code = error is Map ? error['code'] : envelope['code'];
+ final message = error is Map ? error['message'] : envelope['message'];
+ throw SuperTabFailure(
+ code is String && code.isNotEmpty ? code : 'BACKEND_UNAVAILABLE',
+ message is String && message.isNotEmpty
+ ? message
+ : 'Could not reach this Swarm.',
+ statusCode: status,
+ );
+ }
+ return envelope['data'];
+}
diff --git a/desktop/lib/viewer/direct_auth.dart b/desktop/lib/viewer/direct_auth.dart
index d404fc026..97da0226a 100644
--- a/desktop/lib/viewer/direct_auth.dart
+++ b/desktop/lib/viewer/direct_auth.dart
@@ -8,7 +8,7 @@ import 'direct_auth_api.dart';
/// A viewer build's SSO session — authSession.ts's `AuthSessionManager`, moved into the app because
/// a device with no harness CLI has nobody else to hold it: the tokens `/api/auth/exchange` issued,
/// kept in [AuthSession], refreshed [_refreshSkew] before they lapse, one refresh at a time.
-class DirectAuth implements AccessTokenSource {
+class DirectAuth implements AccessTokenSource, SignInRevision {
DirectAuth({required this.session, required this.api});
final AuthSession session;
@@ -19,6 +19,11 @@ class DirectAuth implements AccessTokenSource {
static const _refreshSkew = Duration(seconds: 60);
+ /// Moves with every sign-in and sign-out here: a request signed before it
+ /// moved is not retried as whoever is signed in now.
+ @override
+ int get signInRevision => _revision;
+
/// Browser adapters release their cross-tab session listener here.
void dispose() {}
diff --git a/desktop/lib/viewer/platform_auth_web.dart b/desktop/lib/viewer/platform_auth_web.dart
index 0287525d3..0be2b9c40 100644
--- a/desktop/lib/viewer/platform_auth_web.dart
+++ b/desktop/lib/viewer/platform_auth_web.dart
@@ -82,6 +82,11 @@ class BrowserAuth extends DirectAuth {
});
}
+ /// This browser's own count, which also moves when another tab changes the
+ /// account: the delegate's moves only with this tab's sign-ins.
+ @override
+ int get signInRevision => _revision;
+
@override
Future<bool> hasSession() => _run(_delegate.hasSession);
diff --git a/desktop/test/bearer_auth_interceptor_test.dart b/desktop/test/bearer_auth_interceptor_test.dart
index 3585b34ee..b18e250af 100644
--- a/desktop/test/bearer_auth_interceptor_test.dart
+++ b/desktop/test/bearer_auth_interceptor_test.dart
@@ -26,6 +26,9 @@ class _Auth implements AccessTokenSource {
class _Adapter implements HttpClientAdapter {
final seen = <String>[];
+
+ /// Runs while a request is out, before its answer arrives.
+ void Function()? whileOut;
@override
Future<ResponseBody> fetch(
RequestOptions options,
@@ -34,6 +37,8 @@ class _Adapter implements HttpClientAdapter {
) async {
final token = options.headers['authorization'] as String;
seen.add(token);
+ whileOut?.call();
+ whileOut = null;
return ResponseBody.fromString(
'{}',
token == 'Bearer renewed' ? 200 : 401,
@@ -114,4 +119,90 @@ void main() {
expect(adapter.seen, isEmpty);
},
);
+
+ group('a retry never goes out as another sign-in', () {
+ late _Switching switching;
+ late _Adapter seen;
+ late Dio signed;
+ setUp(() {
+ switching = _Switching();
+ seen = _Adapter();
+ signed = Dio(
+ BaseOptions(
+ baseUrl: 'https://fixture.invalid',
+ validateStatus: (_) => true,
+ ),
+ );
+ signed.httpClientAdapter = seen;
+ signed.interceptors.add(
+ BearerAuthInterceptor(switching, signed, autonomousEnv: 'prod'),
+ );
+ });
+ tearDown(() => signed.close());
+
+ test('A signs out and B signs in while A\'s request is out: its 401 is '
+ 'not retried with B\'s token', () async {
+ seen.whileOut = () => switching.signInAs('renewed');
+ await expectLater(
+ signed.post('/api/super-tabs/tab/commands'),
+ throwsA(
+ isA<DioException>().having(
+ (e) => e.error,
+ 'error',
+ isA<SignInChanged>(),
+ ),
+ ),
+ );
+ expect(seen.seen, ['Bearer old']);
+ });
+
+ test(
+ 'the sign-in changes during the refresh itself: not retried',
+ () async {
+ switching.duringRefresh = () => switching.signInAs('renewed');
+ await expectLater(
+ signed.post('/api/super-tabs/tab/commands'),
+ throwsA(
+ isA<DioException>().having(
+ (e) => e.error,
+ 'error',
+ isA<SignInChanged>(),
+ ),
+ ),
+ );
+ expect(seen.seen, ['Bearer old']);
+ },
+ );
+
+ test('the same sign-in renews and retries as before', () async {
+ expect((await signed.get('/api/machines')).statusCode, 200);
+ expect(seen.seen, ['Bearer old', 'Bearer renewed']);
+ });
+ });
+}
+
+/// A token source that says which sign-in is current, as DirectAuth does:
+/// asked for a token after one failed, it hands back whatever is current now.
+class _Switching implements AccessTokenSource, SignInRevision {
+ String token = 'old';
+ int revision = 0;
+ void Function()? duringRefresh;
+
+ void signInAs(String next) {
+ revision++;
+ token = next;
+ }
+
+ @override
+ int get signInRevision => revision;
+
+ @override
+ Future<String> accessToken({bool force = false, String? failedToken}) async {
+ if (failedToken != null && failedToken != token) return token;
+ if (force) {
+ duringRefresh?.call();
+ if (duringRefresh == null) token = 'renewed';
+ }
+ return token;
+ }
}
diff --git a/desktop/test/super_tab_backend_transport_test.dart b/desktop/test/super_tab_backend_transport_test.dart
new file mode 100644
index 000000000..99c3b0389
--- /dev/null
+++ b/desktop/test/super_tab_backend_transport_test.dart
@@ -0,0 +1,308 @@
+// The web's Swarm transport (docs/specs/2026-10-30-web-swarm-direct.md): the
+// browser asks the backend itself, with its own sign-in, instead of relaying
+// through one of the person's machines. Run against a real local HTTP server,
+// so the header, the body and the backend's envelope are the real ones.
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/access_token_source.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/super_tabs/backend_transport.dart';
+import 'package:harness/super_tabs/client.dart';
+import 'package:harness/super_tabs/controller.dart';
+
+import 'swarm_state_test.dart' show MemoryStore;
+
+class _Token implements AccessTokenSource, SignInRevision {
+ String token = 'browser-token';
+ Object? failure;
+ @override
+ int signInRevision = 0;
+ @override
+ Future<String> accessToken({bool force = false, String? failedToken}) async {
+ if (failure != null) throw failure!;
+ return token;
+ }
+}
+
+class _SignedOut implements AccessTokenFailure {
+ @override
+ bool get signedOut => true;
+}
+
+/// What the backend got, and what it answers next.
+class _Backend {
+ late HttpServer server;
+ final requests =
+ <
+ ({
+ String method,
+ String path,
+ Map<String, String> headers,
+ Object? body,
+ })
+ >[];
+ int status = 200;
+
+ /// Runs as each request arrives, before it is answered.
+ void Function()? onRequest;
+ Object? answer = {
+ 'success': true,
+ 'data': {'ok': 1},
+ };
+
+ Future<void> start() async {
+ server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ server.listen((request) async {
+ final text = await utf8.decoder.bind(request).join();
+ onRequest?.call();
+ requests.add((
+ method: request.method,
+ path: request.uri.toString(),
+ headers: {
+ for (final name in ['authorization', 'x-autonomous-env'])
+ name: ?request.headers.value(name),
+ },
+ body: text.isEmpty ? null : jsonDecode(text),
+ ));
+ request.response
+ ..statusCode = status
+ ..headers.contentType = ContentType.json
+ ..write(jsonEncode(answer));
+ await request.response.close();
+ });
+ }
+
+ String get url => 'http://127.0.0.1:${server.port}';
+}
+
+void main() {
+ late _Backend backend;
+ late _Token token;
+ late SuperTabTransport transport;
+
+ setUp(() async {
+ backend = _Backend();
+ await backend.start();
+ token = _Token();
+ final api = ApiClient(
+ config: AppConfig(apiBaseUrl: backend.url, autonomousEnv: 'test'),
+ session: AuthSession(storage: MemoryStore()),
+ auth: token,
+ );
+ transport = superTabBackendTransport(() => api);
+ });
+ tearDown(() => backend.server.close(force: true));
+
+ Future<SuperTabFailure> refusal(Future<Object?> call) async {
+ try {
+ await call;
+ } on SuperTabFailure catch (failure) {
+ return failure;
+ }
+ fail('expected a SuperTabFailure');
+ }
+
+ test(
+ 'a read goes to the backend signed as the browser, and answers its data',
+ () async {
+ backend.answer = {
+ 'success': true,
+ 'data': {'format': 2, 'tabs': []},
+ };
+ final value = await transport('GET', '/api/super-tabs/list?mentions=1');
+ expect(value, {'format': 2, 'tabs': []});
+ final sent = backend.requests.single;
+ expect(sent.method, 'GET');
+ expect(sent.path, '/api/super-tabs/list?mentions=1');
+ expect(sent.headers['authorization'], 'Bearer browser-token');
+ expect(sent.headers['x-autonomous-env'], 'test');
+ },
+ );
+
+ test('a command posts its body as given', () async {
+ final body = {
+ 'operationId': 'op-1',
+ 'command': {
+ 'type': 'message.send',
+ 'conversationId': 'buddy',
+ 'text': 'hi',
+ },
+ };
+ backend.answer = {
+ 'success': true,
+ 'data': {
+ 'result': {'messageId': 'm1'},
+ },
+ };
+ final value = await transport(
+ 'POST',
+ '/api/super-tabs/tab1/commands',
+ body: body,
+ );
+ expect(value, {
+ 'result': {'messageId': 'm1'},
+ });
+ expect(backend.requests.single.method, 'POST');
+ expect(backend.requests.single.path, '/api/super-tabs/tab1/commands');
+ expect(backend.requests.single.body, body);
+ });
+
+ test('a refusal keeps the backend code, message and status', () async {
+ backend
+ ..status = 403
+ ..answer = {
+ 'success': false,
+ 'error': {'code': 'FORBIDDEN', 'message': 'You are not in this Swarm.'},
+ };
+ final failure = await refusal(
+ transport('GET', '/api/super-tabs/tab1/parts'),
+ );
+ expect(failure.code, 'FORBIDDEN');
+ expect(failure.message, 'You are not in this Swarm.');
+ expect(failure.statusCode, 403);
+ });
+
+ test('426 asks for an update', () async {
+ backend
+ ..status = 426
+ ..answer = {
+ 'success': false,
+ 'error': {'code': 'UPDATE_REQUIRED', 'message': 'Update Harness.'},
+ };
+ final failure = await refusal(
+ transport('GET', '/api/super-tabs/tab1/parts'),
+ );
+ expect(failure.code, 'UPDATE_REQUIRED');
+ expect(failure.statusCode, 426);
+ });
+
+ test('a 200 that says it failed is a refusal, not data', () async {
+ backend.answer = {
+ 'success': false,
+ 'error': {'code': 'SWARM_BUSY', 'message': 'This Swarm is busy.'},
+ };
+ final failure = await refusal(
+ transport('GET', '/api/super-tabs/tab1/parts'),
+ );
+ expect(failure.code, 'SWARM_BUSY');
+ expect(failure.message, 'This Swarm is busy.');
+ });
+
+ test(
+ 'no backend at all says to check the connection, not the catch-all',
+ () async {
+ await backend.server.close(force: true);
+ final failure = await refusal(transport('GET', '/api/super-tabs/list'));
+ expect(failure.code, 'NETWORK');
+ expect(
+ failure.message,
+ 'Could not reach Harness. Check your connection.',
+ );
+ },
+ );
+
+ test('a sign-in that ended says to sign in again', () async {
+ token.failure = _SignedOut();
+ final failure = await refusal(transport('GET', '/api/super-tabs/list'));
+ expect(failure.code, 'SIGNED_OUT');
+ expect(failure.message, 'Sign in to use Swarm.');
+ expect(backend.requests, isEmpty);
+ });
+
+ // The routes a machine's daemon and its agents use (hosts, starts, GitHub
+ // tokens, deliveries) and the ones the web has no screen for never get the
+ // browser's sign-in: refused before anything is sent.
+ test('only the Swarm routes the web uses get the browser sign-in', () async {
+ for (final (method, path) in [
+ ('GET', '/api/machines'),
+ ('POST', '/api/super-tabs/../auth/logout'),
+ ('GET', 'https://elsewhere.example/api/super-tabs/list'),
+ ('DELETE', '/api/super-tabs/tab1'),
+ ('GET', '/api/super-tabs/tab1'),
+ ('GET', '/api/super-tabsx/list'),
+ ('GET', '/api/super-tabs/hosts/m1/changes'),
+ ('GET', '/api/super-tabs/hosts/changes'),
+ ('POST', '/api/super-tabs/hosts/m1/terminal'),
+ ('POST', '/api/super-tabs/hosts/m1/starts/tab1/s1/github-token'),
+ ('POST', '/api/super-tabs/tab1/github-token'),
+ ('GET', '/api/super-tabs/tab1/starts/s1'),
+ ('POST', '/api/super-tabs/tab1/agents/a1/deliveries'),
+ ('POST', '/api/super-tabs/tab1/native/ctx1'),
+ ('POST', '/api/super-tabs/tab1/terminal/r1'),
+ ('GET', '/api/super-tabs/tab1/costs'),
+ ('GET', '/api/super-tabs/workspaces'),
+ ('GET', '/api/super-tabs/grids'),
+ ]) {
+ final failure = await refusal(transport(method, path));
+ expect(failure.code, 'INVALID_REQUEST', reason: '$method $path');
+ }
+ expect(backend.requests, isEmpty);
+ });
+
+ test('every Swarm route the web uses goes to the backend', () async {
+ const routes = [
+ ('GET', '/api/super-tabs/list?mentions=1&after=abc'),
+ ('GET', '/api/super-tabs/invitations'),
+ ('GET', '/api/super-tabs/routing-policy'),
+ ('POST', '/api/super-tabs/routing-policy'),
+ ('POST', '/api/super-tabs'),
+ ('GET', '/api/super-tabs/tab1/parts'),
+ ('GET', '/api/super-tabs/tab1/changes?cursor=c%3D1'),
+ ('POST', '/api/super-tabs/tab1/commands'),
+ ('GET', '/api/super-tabs/tab1/mentions?state=waiting'),
+ ('GET', '/api/super-tabs/tab1/decisions?state=open'),
+ ('GET', '/api/super-tabs/tab1/leaderboard'),
+ ('GET', '/api/super-tabs/tab1/sharing'),
+ ('POST', '/api/super-tabs/tab1/sharing'),
+ ('GET', '/api/super-tabs/tab1/routing-policy'),
+ ('POST', '/api/super-tabs/tab1/routing-policy'),
+ ('GET', '/api/super-tabs/tab1/groups?dormant=1&projectId=p1'),
+ ('GET', '/api/super-tabs/tab1/groups/g1'),
+ ('GET', '/api/super-tabs/tab1/conversations/c1/messages?before=5'),
+ ('GET', '/api/super-tabs/tab1/conversations/c1/catch-up?after=4'),
+ ('POST', '/api/super-tabs/tab1/conversations/c1/read'),
+ ('GET', '/api/super-tabs/tab1/projects/p1/github'),
+ ('POST', '/api/super-tabs/tab1/projects/p1/github/approve'),
+ ('POST', '/api/super-tabs/tab1/projects/p1/roles/r1'),
+ ('GET', '/api/super-tabs/tab1/route-decisions/d1'),
+ ('POST', '/api/super-tabs/tab1/machines/m1/removal'),
+ ('POST', '/api/super-tabs/tab1/join'),
+ ('GET', '/api/super-tabs/tab1/join/preview'),
+ ('POST', '/api/super-tabs/tab1/native'),
+ ];
+ for (final (method, path) in routes) {
+ await transport(method, path, body: method == 'POST' ? {} : null);
+ }
+ expect(backend.requests.map((r) => '${r.method} ${r.path}'), [
+ for (final (method, path) in routes) '$method $path',
+ ]);
+ });
+
+ test('a refused call whose sign-in changed meanwhile is not retried as the '
+ 'new account, and says the account changed', () async {
+ backend
+ ..status = 401
+ ..answer = {
+ 'success': false,
+ 'error': {'code': 'UNAUTHORIZED', 'message': 'Unauthorized'},
+ }
+ ..onRequest = () {
+ token
+ ..signInRevision += 1
+ ..token = 'another-account';
+ };
+ final failure = await refusal(
+ transport('POST', '/api/super-tabs/tab1/commands', body: {'x': 1}),
+ );
+ expect(failure.code, 'ACCOUNT_CHANGED');
+ expect(backend.requests, hasLength(1));
+ expect(
+ backend.requests.single.headers['authorization'],
+ 'Bearer browser-token',
+ );
+ });
+}
diff --git a/desktop/test/super_tab_reading_workspace_test.dart b/desktop/test/super_tab_reading_workspace_test.dart
index 73413be2c..72b870f7e 100644
--- a/desktop/test/super_tab_reading_workspace_test.dart
+++ b/desktop/test/super_tab_reading_workspace_test.dart
@@ -13,6 +13,7 @@ import 'package:harness/web/shell/web_chrome.dart';
import 'super_tab_launch_test.dart'
show SuperTabFixtureConnection, SuperTabLaunchFixture, tabId;
+import 'support/web_swarm_backend.dart';
import 'swarm_state_test.dart' show MemoryStore;
/// The Swarm state reads (first loads and change reads) the fixture's machine
@@ -171,34 +172,42 @@ void main() {
});
// At the app's level: a viewer's connect also loads the machine's data and
- // its device log, whose timers a widget test would have to wait out.
- test('web: the machine connecting reads the Swarm tab at once', () async {
+ // its device log, whose timers a widget test would have to wait out. The web
+ // reads Swarm from the backend itself (docs/specs/2026-10-30-web-swarm-direct.md):
+ // a machine still connecting does not hold the tab, and its connect is no
+ // reason to read again.
+ test('web: the Swarm tab reads from the backend while the machine is still '
+ 'connecting, and its connect reads nothing more', () async {
final v = _viewer();
+ final backend = WebSwarmBackend(v.connection.server);
+ v.app.api = backend;
v.app.superTabs
..reading = webWorkspaceChrome(v.app).superTabReading
..show(tabId);
final c = await v.app.superTabs.open(tabId);
await pumpEventQueue();
- expect(c.snapshot, isNull);
- // Within the grace: loading, not the error.
expect(c.error, isNull);
- expect(c.loading, isTrue);
+ expect(c.snapshot, isNotNull);
+ final reads = backend.calls.length;
v.app.connectionStatusForTest('m', ConnectionStatus.connected);
await pumpEventQueue();
- expect(c.snapshot, isNotNull);
+ expect(backend.calls, hasLength(reads));
+ expect(_connectionReads(v.connection), 0);
v.app.dispose();
});
- test('Desktop reading: the machine connecting waits for the poll', () async {
+ test('web with Desktop reading: the Swarm loads from the backend and the '
+ 'machine is asked nothing', () async {
final v = _viewer();
+ final backend = WebSwarmBackend(v.connection.server);
+ v.app.api = backend;
final c = await v.app.superTabs.open(tabId);
await pumpEventQueue();
- expect(c.error, 'Connect one of your machines to open Swarm.');
- final reads = _connectionReads(v.connection);
+ expect(c.error, isNull);
+ expect(c.snapshot, isNotNull);
v.app.connectionStatusForTest('m', ConnectionStatus.connected);
await pumpEventQueue();
- expect(_connectionReads(v.connection), reads);
- expect(c.snapshot, isNull);
+ expect(_connectionReads(v.connection), 0);
v.app.dispose();
});
}
diff --git a/desktop/test/super_tab_web_direct_shots_test.dart b/desktop/test/super_tab_web_direct_shots_test.dart
new file mode 100644
index 000000000..52638064c
--- /dev/null
+++ b/desktop/test/super_tab_web_direct_shots_test.dart
@@ -0,0 +1,159 @@
+// Phone-width web, no machine connected at all: #openharness and the Buddy
+// chat drawn from what the browser read straight from the backend
+// (docs/specs/2026-10-30-web-swarm-direct.md), in light and dark.
+//
+// SUPER_TAB_WEB_SHOTS=<folder> writes the pictures there for the pull request.
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/pane_layout_store.dart';
+import 'package:harness/super_tabs/view.dart';
+import 'package:harness/viewer/viewer_key_store.dart';
+import 'package:harness/viewer/viewer_services.dart';
+
+import 'support/buddy_fixture.dart';
+import 'support/capture.dart';
+import 'support/super_tab_fixture.dart';
+import 'support/web_swarm_backend.dart';
+import 'swarm_state_test.dart' show MemoryStore;
+
+final shots = Platform.environment['SUPER_TAB_WEB_SHOTS'];
+const _tab = '0123456789abcdef01234567';
+const _buddyChat = 'buddy-owner-lead';
+
+ConversationServer _swarm() {
+ final server = buddySwarm()
+ ..state['id'] = _tab
+ ..state['name'] = 'openharness';
+ giveBuddy(
+ server,
+ person: 'owner',
+ id: 'sage',
+ name: 'Sage',
+ machineId: 'studio',
+ machineOwnerId: 'owner',
+ );
+ server.append('Web chats now load with no machine connected.');
+ server.messages.last['author'] = {
+ 'kind': 'agent',
+ 'id': 'lead-agent',
+ 'name': 'Lead',
+ };
+ server.append(
+ 'Can my phone read the Swarm when my Mac is asleep?',
+ conversationId: _buddyChat,
+ );
+ server.messages.last['author'] = {
+ 'kind': 'person',
+ 'id': 'owner',
+ 'name': '[email protected]',
+ };
+ buddyReply(
+ server,
+ _buddyChat,
+ 'Yes: the browser now reads it from Harness itself, signed in as you.',
+ agentId: 'sage',
+ name: 'Sage',
+ );
+ return server;
+}
+
+void main() {
+ setUpAll(() => loadCaptureFonts(shots));
+
+ for (final brightness in Brightness.values) {
+ testWidgets('phone web, no machine: #openharness and the Buddy chat in '
+ '${brightness.name}', (tester) async {
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ tester.view.devicePixelRatio = 3;
+ tester.view.physicalSize = const Size(390 * 3, 844 * 3);
+ addTearDown(tester.view.reset);
+
+ final server = _swarm();
+ final session = AuthSession(storage: MemoryStore());
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: session,
+ configStore: null,
+ // Every saved setting and Swarm view in memory: never this Mac's files.
+ paneLayoutStore: PaneLayoutStore(storage: MemoryStore()),
+ viewer: ViewerServices(
+ config: AppConfig.dev,
+ session: session,
+ keys: ViewerKeyStore(storage: MemoryStore()),
+ ),
+ );
+ final backend = WebSwarmBackend(server);
+ app.api = backend;
+ app.currentUser = const CurrentUserProfile(
+ id: 'owner',
+ email: '[email protected]',
+ );
+ expect(app.machineStates, isEmpty);
+
+ final c = await tester.runAsync(() async {
+ final c = await app.superTabs.open(_tab);
+ await c.refresh();
+ return c;
+ });
+ expect(c!.error, isNull);
+
+ final picture = GlobalKey();
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: RepaintBoundary(
+ key: picture,
+ child: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ onNewProject: () {},
+ machineName: (_) => 'Studio',
+ ),
+ ),
+ ),
+ ),
+ );
+ Future<void> show(String id, String name, String text) async {
+ await tester.runAsync(() async {
+ await c.select(id);
+ await c.loadMessages(id);
+ });
+ await tester.pumpAndSettle();
+ expect(c.error, isNull);
+ expect(find.textContaining(text), findsWidgets);
+ if (shots != null) {
+ await captureBoundary(
+ tester,
+ picture.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary,
+ shots,
+ 'web-direct-$name-${brightness.name}',
+ );
+ }
+ }
+
+ await show('lead', 'openharness', 'Web chats now load');
+ await show(_buddyChat, 'buddy', 'reads it from Harness itself');
+ expect(backend.calls, isNotEmpty);
+ // Closing the Swarm and the app stops their timers before the test ends.
+ await tester.pumpWidget(const SizedBox());
+ app.currentUser = null;
+ app.dispose();
+ await tester.pump(const Duration(seconds: 1));
+ });
+ }
+}
diff --git a/desktop/test/super_tab_web_direct_test.dart b/desktop/test/super_tab_web_direct_test.dart
new file mode 100644
index 000000000..04fadbfa6
--- /dev/null
+++ b/desktop/test/super_tab_web_direct_test.dart
@@ -0,0 +1,342 @@
+// The web reads and writes Swarm chats straight from the backend
+// (docs/specs/2026-10-30-web-swarm-direct.md): with no machine of the
+// person's at all, the Swarm list, a project chat and the Buddy chat load and
+// send; with one connected, its socket still tells the browser what changed,
+// and the read it starts goes direct too. Native Desktop is unchanged.
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/pane_layout_store.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/viewer/viewer_key_store.dart';
+import 'package:harness/viewer/viewer_services.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/buddy_fixture.dart';
+import 'support/web_swarm_backend.dart';
+import 'support/super_tab_fixture.dart';
+import 'swarm_state_test.dart' show MemoryStore;
+
+const _tab = '0123456789abcdef01234567';
+const _buddyChat = 'buddy-owner-lead';
+
+/// One of the person's machines: records what it is asked, and answers a
+/// relayed Swarm call as its daemon would.
+class _Machine extends WsConn {
+ _Machine(String id, this.server)
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: id,
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final ConversationServer server;
+ final asked = <Map<String, dynamic>>[];
+
+ /// Never answers in time, as a machine on a slow link.
+ bool slow = false;
+ @override
+ bool get isReady => true;
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type == 'super_tabs') asked.add(payload);
+ if (slow) throw WsRequestTimeout(type);
+ if (type == 'super_tabs' && payload['action'] == 'backend') {
+ return {
+ 'ok': true,
+ 'value': await server.request(
+ payload['method'] as String,
+ payload['path'] as String,
+ body: payload['body'] as Map<String, dynamic>?,
+ ),
+ };
+ }
+ return {};
+ }
+}
+
+Future<void> _until(bool Function() done, {String? what}) async {
+ final deadline = DateTime.now().add(const Duration(seconds: 10));
+ while (!done()) {
+ if (DateTime.now().isAfter(deadline)) fail('timed out waiting: $what');
+ await Future<void>.delayed(const Duration(milliseconds: 10));
+ }
+}
+
+void main() {
+ late ConversationServer server;
+ late WebSwarmBackend backend;
+ late Map<String, _Machine> machines;
+ late AppNotifier app;
+
+ setUp(() {
+ server = buddySwarm()..state['id'] = _tab;
+ giveBuddy(
+ server,
+ person: 'owner',
+ machineId: 'studio',
+ machineOwnerId: 'owner',
+ );
+ backend = WebSwarmBackend(server);
+ machines = {};
+ final session = AuthSession(storage: MemoryStore());
+ app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: session,
+ configStore: null,
+ // Every saved setting and Swarm view in memory: never this Mac's files.
+ paneLayoutStore: PaneLayoutStore(storage: MemoryStore()),
+ viewer: ViewerServices(
+ config: AppConfig.dev,
+ session: session,
+ keys: ViewerKeyStore(storage: MemoryStore()),
+ ),
+ connectionForTest: (id) => machines[id]!,
+ );
+ app.api = backend;
+ app.currentUser = const CurrentUserProfile(
+ id: 'owner',
+ email: '[email protected]',
+ );
+ });
+ tearDown(() => app.dispose());
+
+ void connectMachine(String id, {bool online = true, String? kind}) {
+ machines[id] = _Machine(id, server);
+ app.machineStates[id] =
+ MachineState(
+ Machine(
+ machineId: id,
+ authMode: MachineAuthMode.remote,
+ name: 'Studio',
+ sessionKind: kind,
+ ),
+ )
+ ..connectionStatus = online
+ ? ConnectionStatus.connected
+ : ConnectionStatus.disconnected
+ ..nodeOnline = online;
+ }
+
+ Future<SuperTabFailure> machineRefusal(String id) async {
+ try {
+ await app.superTabMachineRequest(id, {
+ 'action': 'prepareContribution',
+ 'tabId': _tab,
+ 'scope': 'swarm',
+ 'operationId': 'setup-1',
+ });
+ } on SuperTabFailure catch (failure) {
+ return failure;
+ }
+ fail('expected a SuperTabFailure');
+ }
+
+ test('with no machine at all, the Swarm list, a project chat and the Buddy '
+ 'chat load and send straight from the backend', () async {
+ expect(app.machineStates, isEmpty);
+ await app.superTabs.refreshTabs();
+ expect(app.superTabs.discoveryError, isNull);
+ expect(backend.calls, contains(startsWith('GET /api/super-tabs/list')));
+
+ final c = await app.superTabs.open(_tab);
+ await c.refresh();
+ expect(c.error, isNull);
+ expect(c.snapshot, isNotNull);
+ expect(c.snapshot!.conversation(_buddyChat), isNotNull);
+
+ expect(await c.select(_buddyChat), isTrue);
+ expect(c.error, isNull);
+ c.setDraft(_buddyChat, 'Hello from the phone');
+ final sent = await c.send();
+ expect(sent, isNotNull);
+ expect(c.error, isNull);
+ expect(
+ server.messages.where((m) => m['text'] == 'Hello from the phone'),
+ hasLength(1),
+ );
+ expect(backend.calls, contains('POST /api/super-tabs/$_tab/commands'));
+ });
+
+ test('with a machine connected, nothing goes through it: its push still '
+ 'starts a read, and that read is direct', () async {
+ connectMachine('studio');
+ app.superTabs.show(_tab);
+ final c = await app.superTabs.open(_tab);
+ await c.refresh();
+ expect(c.error, isNull);
+ final before = backend.calls.length;
+
+ server.append('A change on the server');
+ await app.handleEventForTest('studio', {
+ 'type': 'swarm_changed',
+ 'payload': {
+ 'tabId': _tab,
+ 'lastChangedAt': DateTime.now().millisecondsSinceEpoch,
+ 'parts': ['main'],
+ },
+ });
+ await _until(
+ () => backend.calls.length > before,
+ what: 'a read after the push',
+ );
+ expect(
+ machines['studio']!.asked.where((p) => p['action'] == 'backend'),
+ isEmpty,
+ );
+ });
+
+ group('an action that needs a machine says why it cannot run', () {
+ test('the machine is offline', () async {
+ connectMachine('studio', online: false);
+ final failure = await machineRefusal('studio');
+ expect(failure.code, 'MACHINE_UNAVAILABLE');
+ expect(
+ failure.message,
+ 'Studio is offline. Open Harness on it, then try again.',
+ );
+ expect(machines['studio']!.asked, isEmpty);
+ });
+
+ test('the machine runs a Harness Team account', () async {
+ connectMachine('studio', kind: 'team');
+ final failure = await machineRefusal('studio');
+ expect(failure.code, 'MACHINE_UNAVAILABLE');
+ expect(
+ failure.message,
+ 'Studio runs Swarm agents for a Harness Team account, so it cannot '
+ 'do this for you. Use another of your machines.',
+ );
+ expect(machines['studio']!.asked, isEmpty);
+ });
+
+ test('the machine does not answer in time', () async {
+ connectMachine('studio');
+ machines['studio']!.slow = true;
+ final failure = await machineRefusal('studio');
+ expect(failure.code, 'MACHINE_SLOW');
+ expect(
+ failure.message,
+ 'Studio is taking too long to answer. Its connection may be slow. '
+ 'Try again.',
+ );
+ });
+ });
+
+ group('privacy and recovery through the direct path', () {
+ test('access lost while a chat is open clears what it showed', () async {
+ server.append('Private plan');
+ final c = await app.superTabs.open(_tab);
+ await c.refresh();
+ expect(await c.select('lead'), isTrue);
+ await c.loadMessages('lead');
+ expect(c.messages('lead').map((m) => m.text), contains('Private plan'));
+
+ backend.forbidden = true;
+ await c.refresh();
+ expect(c.accessRevoked, isTrue);
+ expect(c.snapshot, isNull);
+ expect(c.messages('lead'), isEmpty);
+ });
+
+ test('an answer that lands after the account changed is dropped', () async {
+ final c = await app.superTabs.open(_tab);
+ await c.refresh();
+ backend.hold = Completer<void>();
+ final late = app.superTabs.request('GET', '/api/super-tabs/$_tab/parts');
+ app.currentUser = const CurrentUserProfile(
+ id: 'someone-else',
+ email: '[email protected]',
+ );
+ backend.hold!.complete();
+ await expectLater(
+ late,
+ throwsA(
+ isA<SuperTabFailure>().having(
+ (f) => f.code,
+ 'code',
+ 'ACCOUNT_CHANGED',
+ ),
+ ),
+ );
+ expect(app.superTabs.peek(_tab), isNull);
+ });
+
+ test('signed out, nothing is asked of the backend', () async {
+ app.currentUser = null;
+ final before = backend.calls.length;
+ await expectLater(
+ app.superTabs.request('GET', '/api/super-tabs/list'),
+ throwsA(
+ isA<SuperTabFailure>().having((f) => f.code, 'code', 'SIGNED_OUT'),
+ ),
+ );
+ expect(backend.calls, hasLength(before));
+ });
+
+ test(
+ 'a first load with no connection says so, then recovers and sends',
+ () async {
+ backend.down = true;
+ final c = await app.superTabs.open(_tab);
+ await c.refresh();
+ expect(c.loading, isFalse);
+ expect(c.snapshot, isNull);
+ expect(c.error, 'Could not reach Harness. Check your connection.');
+
+ backend.down = false;
+ await c.refresh();
+ expect(c.error, isNull);
+ expect(c.snapshot, isNotNull);
+ expect(await c.select('lead'), isTrue);
+ c.setDraft('lead', 'Back online');
+ expect(await c.send(), isNotNull);
+ expect(
+ server.messages.where((m) => m['text'] == 'Back online'),
+ hasLength(1),
+ );
+ },
+ );
+ });
+
+ test('a project the backend is too old to create says to update it, and '
+ 'nothing about its schema', () async {
+ server
+ ..refuse = {
+ 'code': 'VALIDATION_ERROR',
+ 'message': 'command.type: Invalid discriminator value. Expected machine.contribute',
+ }
+ ..refuseStatus = 400;
+ await expectLater(
+ app.superTabs.request(
+ 'POST',
+ '/api/super-tabs/$_tab/commands',
+ body: {
+ 'operationId': 'op-project',
+ 'command': {'type': 'project.create', 'name': 'Web'},
+ },
+ ),
+ throwsA(
+ isA<SuperTabFailure>()
+ .having((f) => f.code, 'code', 'UPDATE_REQUIRED')
+ .having(
+ (f) => f.message,
+ 'message',
+ 'The Swarm service needs an update before you can create a '
+ 'project. Your draft is saved.',
+ ),
+ ),
+ );
+ });
+}
diff --git a/desktop/test/super_tab_web_request_rate_test.dart b/desktop/test/super_tab_web_request_rate_test.dart
new file mode 100644
index 000000000..2265eeb04
--- /dev/null
+++ b/desktop/test/super_tab_web_request_rate_test.dart
@@ -0,0 +1,118 @@
+// Swarm requests a web client sends per minute, through a machine (before) and
+// straight to the backend (docs/specs/2026-10-30-web-swarm-direct.md): the
+// baseline for the scale line's first warning, the backend's per-person route
+// limit. One Swarm open on screen, with the web's read policy
+// (lib/web/shell/web_chrome.dart), over ten simulated minutes.
+//
+// SUPER_TAB_RATE_OUT=<file> writes the counts there for the pull request.
+import 'dart:io';
+
+import 'package:fake_async/fake_async.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/client.dart';
+import 'package:harness/super_tabs/reading.dart';
+
+import 'support/super_tab_fixture.dart';
+import 'swarm_state_test.dart' show MemoryStore;
+
+const _tab = '0123456789abcdef01234567';
+const _minutes = 10;
+
+/// As lib/web/shell/web_chrome.dart sets it.
+const _web = SuperTabReading(
+ quietPoll: Duration(seconds: 15),
+ pausesAway: true,
+ readsOnConnect: true,
+ connectGrace: Duration(seconds: 10),
+ messagesWithState: true,
+ drawsSaved: true,
+);
+
+/// Requests per minute with one Swarm open. [pushEvery]: the server says the
+/// Swarm changed this often (a busy Swarm), or never. [reconnectEvery]: a
+/// machine of the person's reconnects this often, which made the relayed web
+/// read again at once ([SuperTabClient.serverAvailable]); the direct web
+/// ignores machines.
+double _perMinute({
+ required bool direct,
+ Duration? pushEvery,
+ Duration? reconnectEvery,
+}) {
+ var calls = 0;
+ fakeAsync((time) {
+ final server = ConversationServer()..state['id'] = _tab;
+ final client = SuperTabClient(
+ transport: (method, path, {body}) {
+ calls++;
+ return server.request(method, path, body: body);
+ },
+ storage: MemoryStore(),
+ discoveryInterval: const Duration(seconds: 15),
+ )..reading = _web;
+ client.bind('owner');
+ client.show(_tab);
+ client.open(_tab);
+ time.flushMicrotasks();
+ if (pushEvery != null) client.swarmChanged(const {});
+ calls = 0;
+ var at = Duration.zero;
+ const step = Duration(seconds: 1);
+ while (at < const Duration(minutes: _minutes)) {
+ time.elapse(step);
+ at += step;
+ if (pushEvery != null && at.inSeconds % pushEvery.inSeconds == 0) {
+ server.append('change at ${at.inSeconds}s');
+ client.swarmChanged({
+ 'tabId': _tab,
+ 'lastChangedAt': at.inMilliseconds,
+ 'parts': ['main'],
+ });
+ }
+ if (!direct &&
+ reconnectEvery != null &&
+ at.inSeconds % reconnectEvery.inSeconds == 0) {
+ client.serverAvailable();
+ }
+ }
+ client.bind(null);
+ time.flushTimers(flushPeriodicTimers: false);
+ });
+ return calls / _minutes;
+}
+
+void main() {
+ final rows = <String>[];
+ tearDownAll(() {
+ final out = Platform.environment['SUPER_TAB_RATE_OUT'];
+ if (out != null) File(out).writeAsStringSync('${rows.join('\n')}\n');
+ });
+
+ void row(String name, double relay, double direct) => rows.add(
+ '$name: relay ${relay.toStringAsFixed(1)}/min, '
+ 'direct ${direct.toStringAsFixed(1)}/min',
+ );
+
+ test('a quiet Swarm: the same requests either way', () {
+ final relay = _perMinute(direct: false);
+ final direct = _perMinute(direct: true);
+ row('quiet, no pushes', relay, direct);
+ expect(direct, relay);
+ expect(direct, greaterThan(0));
+ });
+
+ test('a busy Swarm told by pushes: the same requests either way', () {
+ const every = Duration(seconds: 10);
+ final relay = _perMinute(direct: false, pushEvery: every);
+ final direct = _perMinute(direct: true, pushEvery: every);
+ row('busy, a push every 10 s', relay, direct);
+ expect(direct, relay);
+ });
+
+ test('a machine on a weak link reconnecting: fewer requests direct', () {
+ const every = Duration(seconds: 20);
+ final relay = _perMinute(direct: false, reconnectEvery: every);
+ final direct = _perMinute(direct: true, reconnectEvery: every);
+ row('quiet, a machine reconnecting every 20 s', relay, direct);
+ expect(direct, lessThan(relay));
+ });
+}
diff --git a/desktop/test/support/web_swarm_backend.dart b/desktop/test/support/web_swarm_backend.dart
new file mode 100644
index 000000000..4cea8c950
--- /dev/null
+++ b/desktop/test/support/web_swarm_backend.dart
@@ -0,0 +1,76 @@
+import 'dart:async';
+
+import 'package:dio/dio.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/super_tabs/controller.dart';
+
+import '../swarm_state_test.dart' show MemoryStore;
+import 'super_tab_fixture.dart';
+
+/// The backend, as the browser's own sign-in reaches it: each Swarm call is
+/// answered by [server] inside the backend's `{success, data|error}` envelope.
+class WebSwarmBackend extends ApiClient {
+ WebSwarmBackend(this.server)
+ : super(
+ config: AppConfig.dev,
+ session: AuthSession(storage: MemoryStore()),
+ );
+ final ConversationServer server;
+ final calls = <String>[];
+
+ /// The person lost the Swarm: every read is refused, as the backend
+ /// refuses one they may no longer read.
+ bool forbidden = false;
+
+ /// No answer at all: the browser is offline or the backend unreachable.
+ bool down = false;
+
+ /// While set, every call waits for it: a slow answer.
+ Completer<void>? hold;
+
+ @override
+ Future<Response<dynamic>> superTabCall(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+ }) async {
+ calls.add('$method $path');
+ final options = RequestOptions(path: path, method: method);
+ await hold?.future;
+ if (down) {
+ throw DioException(
+ requestOptions: options,
+ type: DioExceptionType.connectionError,
+ );
+ }
+ if (forbidden) {
+ return Response(
+ requestOptions: options,
+ statusCode: 403,
+ data: {
+ 'success': false,
+ 'error': {'code': 'FORBIDDEN', 'message': 'Forbidden'},
+ },
+ );
+ }
+ try {
+ final data = await server.request(method, path, body: body);
+ return Response(
+ requestOptions: options,
+ statusCode: 200,
+ data: {'success': true, 'data': data},
+ );
+ } on SuperTabFailure catch (failure) {
+ return Response(
+ requestOptions: options,
+ statusCode: failure.statusCode == 0 ? 400 : failure.statusCode,
+ data: {
+ 'success': false,
+ 'error': {'code': failure.code, 'message': failure.message},
+ },
+ );
+ }
+ }
+}
diff --git a/desktop/test/swarm_web_relay_team_test.dart b/desktop/test/swarm_web_relay_team_test.dart
index b6ef9726a..302bcb66b 100644
--- a/desktop/test/swarm_web_relay_team_test.dart
+++ b/desktop/test/swarm_web_relay_team_test.dart
@@ -7,6 +7,7 @@ import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
import 'package:harness/core/models.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/pane_layout_store.dart';
import 'package:harness/super_tabs/controller.dart' show SuperTabFailure;
import 'package:harness/viewer/viewer_key_store.dart';
import 'package:harness/viewer/viewer_services.dart';
@@ -49,6 +50,26 @@ class _Api extends ApiClient {
final posted = <String>[];
+ /// Swarm calls sent straight to the backend, as the web sends them.
+ final direct = <String>[];
+
+ @override
+ Future<Response<dynamic>> superTabCall(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+ }) async {
+ direct.add('$method $path');
+ return Response(
+ requestOptions: RequestOptions(path: path),
+ statusCode: 200,
+ data: {
+ 'success': true,
+ 'data': {'result': <String, dynamic>{}},
+ },
+ );
+ }
+
@override
Future<Response<dynamic>> postForm(
String path,
@@ -94,6 +115,7 @@ void main() {
config: AppConfig.dev,
authSession: session,
connectionForTest: (id) => _Daemon(id, relayed),
+ paneLayoutStore: PaneLayoutStore(storage: storage),
viewer: ViewerServices(
config: AppConfig.dev,
session: session,
@@ -133,9 +155,16 @@ void main() {
expect(_row('old').isTeamAccount, isFalse);
});
- test('on the web a Swarm post goes through the person\'s own machine, never '
- 'a Team account machine that sorts first or is selected', () async {
+ // The web sends Swarm calls straight to the backend with the person's own
+ // sign-in (docs/specs/2026-10-30-web-swarm-direct.md): no machine relays
+ // them, so a Harness Team account machine never can. Shared tabs still ask
+ // one of the person's own machines, never the Team one.
+ test('on the web a Swarm post goes straight to the backend, through no '
+ 'machine: not a Team account machine that sorts first or is selected, '
+ 'nor the person\'s own', () async {
web();
+ final api = _Api();
+ app.api = api;
// The Team account on the person's Mac: its daemon signs in with a team
// session, which the server refuses to act as the person.
online(_row('a-team', sessionKind: 'team', hostMachineId: 'own-mac'));
@@ -144,7 +173,8 @@ void main() {
expect(app.sharedTabsTarget?.machine.machineId, 'own-mac');
await post();
- expect(relayed, ['own-mac']);
+ expect(api.direct, ['POST /api/super-tabs/tab/commands']);
+ expect(relayed, isEmpty);
});
/// The desktop app on a computer: its own machine is the one it asks.
@@ -161,12 +191,15 @@ void main() {
app.machineStates[local.machineId]!.localOnly = true;
}
- test('natively a Swarm post goes through this computer\'s own machine', () async {
- native(_row('here', sessionKind: 'computer'));
- expect(app.sharedTabsTarget?.machine.machineId, 'here');
- await post();
- expect(relayed, ['here']);
- });
+ test(
+ 'natively a Swarm post goes through this computer\'s own machine',
+ () async {
+ native(_row('here', sessionKind: 'computer'));
+ expect(app.sharedTabsTarget?.machine.machineId, 'here');
+ await post();
+ expect(relayed, ['here']);
+ },
+ );
test('natively on a computer switched to a Harness Team account nothing is '
'sent, and the app says this computer cannot send it', () async {
@@ -180,31 +213,32 @@ void main() {
throwsA(
isA<SuperTabFailure>()
.having((f) => f.code, 'code', 'MACHINE_UNAVAILABLE')
- .having((f) => f.message, 'message', contains('This computer runs Swarm agents')),
+ .having(
+ (f) => f.message,
+ 'message',
+ contains('This computer runs Swarm agents'),
+ ),
),
);
expect(relayed, isEmpty);
});
- test('on the web with only a Team account machine online nothing is sent, '
- 'and the app says no machine of the person\'s is online', () async {
- web();
- online(_row('a-team', sessionKind: 'team', hostMachineId: 'own-mac'));
- app.selectedMachineId = 'a-team';
+ test(
+ 'on the web with only a Team account machine online the post still '
+ 'goes to the backend, and nothing goes through the Team machine',
+ () async {
+ web();
+ final api = _Api();
+ app.api = api;
+ online(_row('a-team', sessionKind: 'team', hostMachineId: 'own-mac'));
+ app.selectedMachineId = 'a-team';
- expect(app.sharedTabsTarget, isNull);
- await expectLater(
- post(),
- throwsA(
- isA<SuperTabFailure>().having(
- (f) => f.code,
- 'code',
- 'MACHINE_UNAVAILABLE',
- ),
- ),
- );
- expect(relayed, isEmpty);
- });
+ expect(app.sharedTabsTarget, isNull);
+ await post();
+ expect(api.direct, ['POST /api/super-tabs/tab/commands']);
+ expect(relayed, isEmpty);
+ },
+ );
group('on a computer switched to a Harness Team account', () {
late _Api api;
@@ -225,11 +259,14 @@ void main() {
app.api = api = _Api();
}
- test('a file is sent from this computer\'s own machine as before', () async {
- computer('computer');
- await upload();
- expect(api.posted, ['/api/super-tabs/tab/attachments']);
- });
+ test(
+ 'a file is sent from this computer\'s own machine as before',
+ () async {
+ computer('computer');
+ await upload();
+ expect(api.posted, ['/api/super-tabs/tab/attachments']);
+ },
+ );
test('a file is refused here, plainly, and never sent', () async {
computer('team');
@@ -244,21 +281,24 @@ void main() {
expect(api.posted, isEmpty);
});
- test('a profile picture is refused here, plainly, and never sent', () async {
- computer('team');
- await expectLater(
- app.superTabs.avatarUpload(
- tabId: 'tab',
- png: Uint8List.fromList([1, 2, 3]),
- ),
- throwsA(
- isA<SuperTabFailure>()
- .having((f) => f.code, 'code', 'MACHINE_UNAVAILABLE')
- .having((f) => f.message, 'message', plainly),
- ),
- );
- expect(api.posted, isEmpty);
- });
+ test(
+ 'a profile picture is refused here, plainly, and never sent',
+ () async {
+ computer('team');
+ await expectLater(
+ app.superTabs.avatarUpload(
+ tabId: 'tab',
+ png: Uint8List.fromList([1, 2, 3]),
+ ),
+ throwsA(
+ isA<SuperTabFailure>()
+ .having((f) => f.code, 'code', 'MACHINE_UNAVAILABLE')
+ .having((f) => f.message, 'message', plainly),
+ ),
+ );
+ expect(api.posted, isEmpty);
+ },
+ );
test('a shared-tabs read is refused plainly too, and never sent', () async {
computer('team');
diff --git a/docs/specs/2026-10-30-web-swarm-direct.md b/docs/specs/2026-10-30-web-swarm-direct.md
new file mode 100644
index 000000000..e117e4a2d
--- /dev/null
+++ b/docs/specs/2026-10-30-web-swarm-direct.md
@@ -0,0 +1,178 @@
+# Web Swarm chats straight from the backend
+
+Status: approved by the Lead and built in #2306. Requested by Huy (10-30).
+
+## Problem
+
+On the web (the Desktop app built for the browser, also used on phones), every Swarm call goes through one of the
+person's connected machines: `superTabs.transport` in `desktop/lib/state/app_state.dart` sends `super_tabs` /
+`action: backend` to the machine `sharedTabsTarget` picks, and that machine's daemon calls `/api/super-tabs/...`
+with its own sign-in (`cli/src/superTabs/service.ts`, `ownerRequest`). With no machine of the person's online, only
+Team-account machines, or a slow link, the web shows "Connect one of your machines to open Swarm" or the catch-all
+"Could not refresh this conversation" (`controller.dart` `_readFailure`), even though the backend could answer the
+browser directly.
+
+Finding that changes the brief's premise: the phone app does **not** call Swarm JSON routes directly today. It relays
+through a machine exactly like the web (`mobile/lib/state/app_state.dart` `swarmRequest` → `_swarmRequestVia`). Only
+chat file uploads and avatars go direct with the person's own sign-in (`ApiClient.uploadSwarmAttachment`,
+`uploadSwarmAvatar`), on both phone and web. This spec reuses that direct-upload token model for every Swarm JSON
+call on the web. The phone app is out of scope and can follow the same way later.
+
+## What changes
+
+On the web only (`viewer != null`), `superTabs.transport` calls the backend directly through the app's existing
+`ApiClient` (`viewer.auth`, `BearerAuthInterceptor`): the same method, path and body the relay sent, the backend's
+`{success, data, error}` envelope read as `wire.ts backend()` reads it (data on success; `error.code`,
+`error.message` and the HTTP status as a `SuperTabFailure`; 426 as `UPDATE_REQUIRED`). Every Swarm screen goes
+through that one transport, so chats, the chat list, threads, mentions, decisions, invitations, read marks, reactions,
+commands (posts, Buddy chat) all go direct without per-screen changes.
+
+Native Desktop (macOS, Windows, Linux) is unchanged: it keeps calling its own local daemon.
+
+### Calls that go direct on the web
+
+Everything `SuperTabClient.transport` sends: `GET`/`POST /api/super-tabs/**` (list, parts, conversations,
+messages, threads, mentions, decisions, invitations, leaderboard, costs, commands). Uploads and avatars already go
+direct and stay as they are.
+
+### Calls that still need a machine (they act on that machine, not on the Swarm's data)
+
+`superTabMachineRequest` with `prepareContribution` (adding a machine or a Buddy machine), `prepareNative`
+(terminal sharing), `wake`, `teamSetupCheck` / `teamSetupDecline` / `teamSetup`; `sharedTabs` (`agent_messages`,
+tabs shared with other accounts) and `tabActivity` (`tab_activity`); terminals and files on disk. These stay on the
+machine they name. When it cannot answer, the web says why instead of the catch-all:
+
+| Situation | Text (Naming System wording) |
+|---|---|
+| The named machine is offline | "{machine} is offline. Open Harness on it, then try again." |
+| It is a Harness Team machine | "{machine} runs Swarm agents for a Harness Team account, so it cannot do this for you. Use another of your machines." |
+| No answer within the timeout | "{machine} is taking too long to answer. Its connection may be slow. Try again." |
+| No machine of the person's online (sharedTabs, tab activity) | "None of your machines is online." (as today) |
+
+A direct Swarm read that fails without a backend answer (no network, timeout) becomes
+`SuperTabFailure('NETWORK', 'Could not reach Harness. Check your connection.')`, so `_readFailure` shows that
+instead of "Could not refresh this conversation". The catch-all stays only for errors that are neither.
+
+### Machine gating removed on the web
+
+`_onConnectionStatus` calls `superTabs.serverAvailable()` when a machine first becomes able to serve Swarm reads
+(`sharedTabsTarget != null`). On the web the backend always serves them, so the Swarm reads on sign-in and on the
+browser coming back online, not on a machine connecting. The machine-connect trigger stays for native.
+
+### Authentication, CORS, CSRF
+
+- Routes: the transport signs only the Swarm routes the web's screens call (list, invitations, routing policy, create;
+ per Swarm: parts, changes, commands, mentions, decisions, leaderboard, sharing, routing policy, groups, conversations'
+ messages, catch-up and read marks, project GitHub and roles, route decisions, machine removal, join, terminal
+ sharing). Host, start, GitHub token, delivery and terminal routes are refused before anything is sent.
+- Token: the browser's own sign-in, which the web already sends on every other direct call (desk, machines, uploads):
+ an Autonomous SSO access token, or a Harness `viewer` session after a QR sign-in. `registerAuthMiddleware` accepts
+ both on every control route. Swarm routes treat the caller as the signed-in person; the only session-kind check in
+ `backend/src/superTabs` is for `team` sessions (`store.ts`, `routes/superTabs.ts personOnly`), and a browser never
+ holds one (team sessions are minted only for a machine's daemon, `lib/teamSession.ts`). So the browser has exactly
+ the person's access, the same the relaying machine's `computer` session had. No daemon or Team-account credential
+ is in the browser, before or after.
+- CORS: which origins are let in is unchanged; only `Access-Control-Max-Age: 600` is added (Scale, below). The server
+ already reflects the origin (`server.ts`, `lib/corsOptions.ts`); requests carry `Authorization: Bearer` from
+ the app's own storage, which another origin cannot read. No route is added and none accepts weaker auth.
+- CSRF: N/A because the control API authenticates only by the bearer header, never by cookie
+ (`authMiddleware.ts bearerToken`); a cross-site form or link carries no credential.
+- Backend change: none expected. Step 2 adds a backend route test that a `viewer` session reads a Swarm and posts a
+ command exactly as a `computer` session does, a person outside the Swarm or Buddy chat is refused alike, and a
+ `team` session is still refused. If that test shows a gap, the fix is in the route auth and reported here first.
+
+### Caching and offline
+
+Unchanged in kind, with one gap left for a follow-up (below). The web's saved Swarm views (`SuperTabSavedViews`, browser storage) are already claimed per
+account, forgotten when another account signs in on that browser or the account leaves, and cleared by Settings ▸
+Account ▸ Clear now. In-memory state is per account generation (`SuperTabClient.request` drops answers that land
+after an account change; `superTabMachineRequest` the same by `_authRevision`). Offline: reads fail with the network
+text above and retry on the existing poll; posts stay in the composer with their operation id, as now.
+
+What a sign-out on the web leaves in browser storage today (each keyed by account, so another account signing in never
+reads them through the app, but they stay on a shared browser). Follow-up: clear them on a web sign-out.
+- `super_tab.<account>.<swarm>`: each Swarm's unsent composer drafts per conversation, its selection and what is expanded;
+- `super_tab.launch.<account>.<tab>.<conversation>`: an unsent New Harness or New Project draft;
+- `super_tab.hidden.<account>`: the Swarms hidden on this browser;
+- `super_tab.personal.<account>`: the Swarm last chosen in the switcher.
+
+A 401 retry never goes out as another account (security review of 0993e291d): the bearer interceptor records which
+sign-in each request went out under (`SignInRevision`, moving with every sign-in and sign-out, and in a browser with
+another tab's too) and refuses the retry when it has moved, as the daemon's account fence does; the Swarm call then says
+the account changed.
+
+Live updates: the browser hears `swarm_changed` only on its sockets to the backend, one per machine
+(`lib/webAccountPushes.ts`). With no machine at all there is no socket, so the web reads on its 15 s timer instead
+(the existing fallback). Correct, just slower; adding an account socket for the browser is a separate change.
+
+## Design (docs/feature-design-rules.md)
+
+Reviewed revision: 0993e291d Reviewers: the two security reviews of #2306 (sign-in and access checks; browser data and
+sign-out on shared machines), no critical or important findings; their minor ones are fixed in the next revision.
+
+1. **Growth:** N/A because nothing new is stored: no records, fields or caches. The saved views keep their existing
+ lifecycle (above).
+2. **Concurrency:** N/A because no new state is written. The server's per-Swarm write path is unchanged. On the
+ client one build has one transport: the web always goes direct, native always to the local daemon. There is no
+ fallback from direct to relay, so a call never goes both ways. A command repeated after a lost answer carries the
+ same operation id as before, so the server applies it once.
+3. **Read cost:** the same requests the relay sent (same paths, bodies and answers: a `parts` read and its
+ changes-since reads as today); the server loads the same. What goes away is the WebSocket round trip through the
+ machine and its daemon's work. Test: the web transport sends exactly the method, path and body it is given, and
+ nothing else.
+4. **Scale:** at 10x people on the web, the backend sees the same Swarm requests it sees today through daemons (the
+ relay already counted them for the same person in the route rate limit), now from browsers instead of daemons.
+ Daemon socket traffic drops. The first warning is the per-person route rate limit (`ROUTE_RATE_LIMIT_PER_PERSON_*`
+ 429s for `/api/super-tabs`) and the Swarm route p95 in route latency logs. Both are already measured.
+ Measured (`desktop/test/super_tab_web_request_rate_test.dart`, the web's read policy, one Swarm on screen, ten
+ simulated minutes): quiet 24.7 requests/min through a machine and 24.7 direct; a push every 10 s 33.3 and 33.3; a
+ machine reconnecting every 20 s 29.5 through it and 24.7 direct (no read on reconnect any more). Against the default
+ limits (15,000/person/min, 50/caller/s) a busy web client uses about 0.2% of its minute, about 450x headroom.
+ Each of these is signed with an Authorization header, so a browser sends a CORS preflight before it, which would
+ double the requests on the wire; `Access-Control-Max-Age: 600` (`backend/src/lib/corsOptions.ts`, the most Safari
+ keeps) lets it keep that answer for 10 minutes, so it is one preflight per route per 10 minutes instead.
+5. **Compatibility:** client-only. An old web bundle still relays through a machine, and the daemon keeps its
+ `action: backend` (the phone app and old web bundles use it). A new web bundle against any server from the last
+ months works, because these routes already accept the person's sign-in. The relay's `machine.contribute` retry
+ with `maxAgents: 16` is for servers from before the limit was raised. Today's server takes up to 1024 (`commands.ts` `maxAgents`), so the direct path
+ does not need it. Readers of `MACHINE_UNAVAILABLE` (`controller.dart:2852`, `launch.dart:751`) still get it for
+ machine-only calls. `NETWORK` is new, and its only reader is `_readFailure`, which shows its message.
+6. **Migration and rollback:** no data migration. Deploy is the web bundle alone. Rollback is the previous web bundle,
+ which relays again. Nothing new was stored, so it has nothing to misread. No production restore is needed: no data
+ changes (owner's check not required).
+7. **Audience:** the server enforces it in the same route handlers and checked reads (`SwarmReads`, store
+ `canReadGroup` and the Buddy chat's person-only rule), whichever client calls. Copies of private data: the
+ browser's in-memory controller (dropped on account change by generation), the saved views in browser storage
+ (claimed per account, cleared on Clear now), the browser's HTTP log (`attachHttpLog`: method, path and status only,
+ no headers or bodies; paths hold Swarm and conversation ids, no content). Removed: the relaying machine's daemon no longer handles the person's
+ Swarm answers on the web. Notifications, mentions and shares are unchanged.
+8. **Identity:** each web Swarm call runs as the signed-in person, with the browser's own sign-in. Never a machine's
+ or the Team account's. Missing or expired sign-in: the backend answers 401, and the app's existing sign-in flow
+ takes over. Nothing falls back to a machine.
+9. **Failure:** backend unreachable → "Could not reach Harness. Check your connection." with a bounded retry on the
+ existing poll (no stuck Loading). Access lost (403/404) → the existing `accessRevoked` path clears the view, as
+ today. Account changed mid-request → the answer is dropped (`ACCOUNT_CHANGED`). A machine-only action whose machine
+ cannot answer → the specific text in the table above. 426 → "Update Harness".
+10. **Platforms:** web on desktop and phone browsers changes. Native macOS, Windows and Linux are unchanged (local
+ daemon). The phone app is unchanged (still relays) and is a follow-up.
+
+## Tests (step 2, test first)
+
+Desktop (`desktop/test`, fakes at the HTTP level, real `SuperTabClient`/controller):
+- Web with no machine at all: the chat list, `#openharness` parts, a thread and the Buddy chat load. A post and a
+ Buddy chat post send their command with the operation id. No `super_tabs` frame goes to any machine.
+- The web transport sends the given method, path and body, unwraps `data`, and maps `{error}` and status to
+ `SuperTabFailure` (403 FORBIDDEN → access revoked and cleared; 426 → update required).
+- Access revoked while a chat is open: cached rows cleared, an in-flight answer that lands after is dropped.
+- Account changed during a read: the answer is dropped, and the new account's state is untouched.
+- A failed first read (network) shows the network text, then recovers on the next poll and the view works.
+- Machine-only action on the web: offline machine, Team machine and a timeout each show their own text, never the
+ catch-all.
+- Native: the transport still goes to the local daemon (unchanged behaviour, regression).
+
+Backend (`routes/superTabs.test.ts` or `superTabs` suite): a `viewer` session reads and posts like a `computer`
+session; the Buddy chat and another project's ids are refused alike, with no title leak; a `team` session is still
+refused.
+
+Real app: light and dark screenshots of phone-width web loading `#openharness` and the Buddy chat with no machine
+connected.