The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(desktop): web Buddy-chat posts never relay through a Harness Team account machine (#2161)
0xken1515168dc8d458
diff --git a/backend/integration/superTabBuddies.test.ts b/backend/integration/superTabBuddies.test.tsindex 7d7d4ecc4..c2f550781 100644--- a/backend/integration/superTabBuddies.test.ts+++ b/backend/integration/superTabBuddies.test.ts@@ -22,6 +22,13 @@ let replica: MongoMemoryReplSetlet db: PrismaClientconst owner: AuthUser = { sub: '300000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }const peer: AuthUser = { sub: '300000000000000000000002', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const watcher: AuthUser = { sub: '300000000000000000000003', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+// peer's sign-ins (lib/teamSession.ts): their own Mac's daemon, which relays their web app's Swarm requests, and the daemon+// of the Harness Team account on that Mac, a second macOS user signed in to peer's account with a team session.+const PEER_COMPUTER = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', PEER_TEAM_COMPUTER = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'+const peerMac: AuthUser = { ...peer, harnessSessionId: 'peer-mac-session', harnessSessionKind: 'computer', harnessComputerId: PEER_COMPUTER }+const peerTeam: AuthUser = { ...peer, harnessSessionId: 'peer-team-session', harnessSessionKind: 'team', harnessComputerId: PEER_TEAM_COMPUTER }+const LIMITED = { code: 'TEAM_SESSION_LIMITED', status: 403 }const config = { engine: 'claude', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }beforeAll(async () => {@@ -32,10 +39,13 @@ beforeAll(async () => {env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,})db = new PrismaClient({ datasources: { db: { url: uri } } })- for (const user of [owner, peer]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`, email: user.email, autonomousEnv: user.autonomousEnv } })+ for (const user of [owner, peer, watcher]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`, email: user.email, autonomousEnv: user.autonomousEnv } })for (const [machineId, user] of [['owner-mac', owner], ['peer-mac', peer]] as const) {- await db.machine.create({ data: { machineId, userId: user.sub, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ await db.machine.create({ data: { machineId, userId: user.sub, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote',+ ...(machineId === 'peer-mac' ? { computerId: PEER_COMPUTER, sessionKind: 'computer' } : {}) } })}+ await db.machine.create({ data: { machineId: 'peer-team', userId: peer.sub, computerId: PEER_TEAM_COMPUTER, sessionKind: 'team', hostMachineId: 'peer-mac',+ apiKey: 'fixture-peer-team', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })})afterAll(async () => {await db?.$disconnect()@@ -405,3 +415,52 @@ describe('a person\'s Buddy chat before any Buddy, and the PM\'s private lines (expect((await f.store.messages(peer, f.tab, chat!, {})).messages.map(m => m.text)).toEqual(['First.', 'Second.'])})})++describe('a person\'s post in their Buddy chat from the web (phone bug, 10-29)', () => {+ // The web app relays a person's Swarm requests through one of their online machines. Through their own Mac it is theirs;+ // through their Team account it was refused ("A team sign-in can only run Swarm agents on its own machine"), so the app+ // never relays through one now (desktop sharedTabsTarget), and the gate stays as it is.+ const post = (chat: string, text: string) => ({ type: 'message.send' as const, conversationId: chat, text, replyTo: null, recipientIds: [] })+ const stored = (f: Awaited<ReturnType<typeof swarm>>, chat: string) => db.superTabMessage.findMany({ where: { tabId: f.tab, conversationId: chat } })+ const delivered = async (f: Awaited<ReturnType<typeof swarm>>, chat: string) =>+ (await db.superTabDelivery.findMany({ where: { tabId: f.tab, conversationId: chat } })).map(d => d.agentId)++ it('is accepted through their own Mac\'s sign-in and delivered to their Buddy alone', async () => {+ const f = await swarm()+ const { chat, agentId } = await buddy(f)+ await f.execute(post(chat, 'From my phone'), peerMac)+ expect(await delivered(f, chat)).toEqual([agentId])+ expect((await f.store.messages(peer, f.tab, chat, {}, agentId)).messages.at(-1)).toMatchObject({ text: 'From my phone',+ author: expect.objectContaining({ kind: 'person', id: peer.sub }) })+ })++ it('is refused to their Team account\'s sign-in, as them or as their Buddy on their Mac, and nothing is stored or delivered', async () => {+ const f = await swarm()+ const { chat, agentId } = await buddy(f)+ const before = (await stored(f, chat)).length+ await expect(f.execute(post(chat, 'As the person'), peerTeam)).rejects.toMatchObject(LIMITED)+ await expect(f.execute(post(chat, 'As the Buddy'), peerTeam, agentId)).rejects.toMatchObject(LIMITED)+ await expect(f.store.messages(peerTeam, f.tab, chat, {})).rejects.toMatchObject(LIMITED)+ expect((await stored(f, chat)).length).toBe(before)+ expect(await delivered(f, chat)).toEqual([])+ })++ it('is nobody else\'s: the Swarm owner, the PM and a viewer are refused alike, told nothing about the chat', async () => {+ const f = await swarm()+ const invitation = await f.execute({ type: 'invite.create', email: watcher.email, role: 'viewer', conversationId: 'lead' })+ await f.execute({ type: 'invite.accept', inviteId: invitation.result.inviteId as string }, watcher)+ const { chat } = await buddy(f)+ const before = (await stored(f, chat)).length+ const refusal = (conversation: string, user: AuthUser, asAgentId?: string) => f.execute(post(conversation, 'Not mine'), user, asAgentId)+ .then(() => null, (error: Error & { code?: string; status?: number }) => ({ code: error.code, status: error.status, message: error.message }))+ for (const [user, asAgentId] of [[owner, undefined], [owner, f.lead], [watcher, undefined]] as const) {+ // Refused exactly as for a chat that does not exist (a viewer, for being one), naming neither peer nor the chat.+ const answer = await refusal(chat, user, asAgentId)+ expect(answer).not.toBeNull()+ expect(answer).toEqual(await refusal('ffffffffffffffffffffffff', user, asAgentId))+ expect(answer!.message).not.toMatch(/peer|Buddy/i)+ }+ expect((await stored(f, chat)).length).toBe(before)+ expect(await delivered(f, chat)).toEqual([])+ })+})diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dartindex ca9b096ad..376e41fea 100644--- a/desktop/lib/core/models.dart+++ b/desktop/lib/core/models.dart@@ -151,6 +151,11 @@ class Machine {/// Set when another account shares this whole machine with this one; null for the account's own.final MachineShare? machineShare;+ /// How its computer signed in on its last connect, as the machine list says+ /// (`team` for a Harness Team account, `computer` otherwise, null when an+ /// older backend sends none).+ final String? sessionKind;+const Machine({required this.machineId,this.apiKey = '',@@ -164,8 +169,14 @@ class Machine {this.sharedHarnesses = const [],this.status,this.machineShare,+ this.sessionKind,});+ /// A Harness Team account's machine: the account's, but its daemon signs in+ /// with a team session, which the server never lets act as the person. The+ /// person's own Swarm requests never go through it.+ bool get isTeamAccount => sessionKind == 'team';+/// Another account's machine, shared with this one: this account is a guest there, with its own space and/// harnesses; the machine is managed (renamed, removed, shared on) by its owner alone.bool get isSharedMachine => machineShare != null;@@ -214,6 +225,7 @@ class Machine {machineShare: j['share'] is Map? MachineShare.fromJson(Map<String, dynamic>.from(j['share'] as Map)): null,+ sessionKind: j['sessionKind'] as String?,);Machine copyWith({String? name}) => Machine(@@ -229,6 +241,7 @@ class Machine {sharedHarnesses: sharedHarnesses,status: status,machineShare: machineShare,+ sessionKind: sessionKind,);}diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 5d1844a47..e6b1d0620 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1733,16 +1733,25 @@ class AppNotifier extends ChangeNotifier {late final tabActivity = TabActivityReader(request: sharedTabs.request);/// The machine [sharedTabs] asks: this computer natively; on the web one of- /// the account's own online machines, never a shared one.+ /// the account's own online machines, never a shared one. Never a Harness+ /// Team account's, here either (a computer switched with `harness team on`):+ /// its daemon relays under a team sign-in, which the server refuses to let+ /// speak as the person ("A team sign-in can only run Swarm agents on its own+ /// machine", every Buddy-chat post from a phone, 10-29), so nothing is sent.MachineState? get sharedTabsTarget {- if (viewer == null) return localMachineState;- final owned = ownedActionMachine;- if (owned != null && !owned.belongsToOtherAccount && !owned.isOffline) {- return owned;+ if (viewer == null) {+ final here = localMachineState;+ return here == null || here.machine.isTeamAccount ? null : here;}+ bool asks(MachineState machine) =>+ !machine.belongsToOtherAccount &&+ !machine.machine.isTeamAccount &&+ !machine.isOffline;+ final owned = ownedActionMachine;+ if (owned != null && asks(owned)) return owned;MachineState? best;for (final machine in machineStates.values) {- if (machine.belongsToOtherAccount || machine.isOffline) continue;+ if (!asks(machine)) continue;if (machine.connectionStatus != ConnectionStatus.connected) continue;if (best == null ||machine.machine.machineId.compareTo(best.machine.machineId) < 0) {@@ -1845,6 +1854,15 @@ class AppNotifier extends ChangeNotifier {transport: (method, path, {body}) async {final target = sharedTabsTarget;if (target == null) {+ if (viewer == null &&+ localMachineState?.machine.isTeamAccount == true) {+ throw const SuperTabFailure(+ 'MACHINE_UNAVAILABLE',+ 'This computer runs Swarm agents for a Harness Team account, so '+ 'it cannot send your own Swarm messages. Open Swarm on another '+ 'of your machines.',+ );+ }throw const SuperTabFailure('MACHINE_UNAVAILABLE','Connect one of your machines to open Swarm.',diff --git a/desktop/test/swarm_web_relay_team_test.dart b/desktop/test/swarm_web_relay_team_test.dartnew file mode 100644index 000000000..d024f97f1--- /dev/null+++ b/desktop/test/swarm_web_relay_team_test.dart@@ -0,0 +1,175 @@+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/super_tabs/controller.dart' show SuperTabFailure;+import 'package:harness/viewer/viewer_key_store.dart';+import 'package:harness/viewer/viewer_services.dart';+import 'package:harness/ws/ws_conn.dart';++import 'swarm_state_test.dart' show MemoryStore;++/// One machine's daemon, recording the Swarm requests the app relays through+/// it. Nothing leaves the test.+class _Daemon extends WsConn {+ _Daemon(String machineId, this.relayed)+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: machineId,+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );++ final List<String> relayed;++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ if (type == 'super_tabs') relayed.add(machineId);+ return {'value': <String, dynamic>{}};+ }+}++/// The machine list as the server sends it (MachineService toOwner): a Harness+/// Team account's machine carries `sessionKind: team` and the Mac it lives on.+Machine _row(String id, {String? sessionKind, String? hostMachineId}) =>+ Machine.fromJson({+ 'machineId': id,+ 'authMode': 'remote',+ 'name': id,+ 'sessionKind': ?sessionKind,+ 'hostMachineId': ?hostMachineId,+ });++void main() {+ late List<String> relayed;+ late AppNotifier app;++ /// A browser signed in to the person's account (the web app on a phone).+ void web() {+ relayed = [];+ final storage = MemoryStore();+ final session = AuthSession(storage: storage);+ app = AppNotifier(+ config: AppConfig.dev,+ authSession: session,+ connectionForTest: (id) => _Daemon(id, relayed),+ viewer: ViewerServices(+ config: AppConfig.dev,+ session: session,+ keys: ViewerKeyStore(storage: storage),+ ),+ );+ addTearDown(app.dispose);+ }++ void online(Machine machine) {+ app.machines = [...app.machines, machine];+ app.machineStates[machine.machineId] = MachineState(machine)+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected;+ }++ // The Buddy-chat post the web app sends (a person's message in their chat).+ Future<Object?> post() => app.superTabs.transport(+ 'POST',+ '/api/super-tabs/tab/commands',+ body: {+ 'operationId': 'op-1',+ 'command': {+ 'type': 'message.send',+ 'conversationId': 'buddy-chat',+ 'text': 'hi',+ },+ },+ );++ test('the machine list marks a Harness Team account machine', () {+ expect(+ _row('t', sessionKind: 'team', hostMachineId: 'mac').isTeamAccount,+ isTrue,+ );+ expect(_row('c', sessionKind: 'computer').isTeamAccount, isFalse);+ 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 {+ web();+ // 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'));+ online(_row('own-mac', sessionKind: 'computer'));+ app.selectedMachineId = 'a-team';++ expect(app.sharedTabsTarget?.machine.machineId, 'own-mac');+ await post();+ expect(relayed, ['own-mac']);+ });++ /// The desktop app on a computer: its own machine is the one it asks.+ void native(Machine local) {+ relayed = [];+ app = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ connectionForTest: (id) => _Daemon(id, relayed),+ );+ addTearDown(app.dispose);+ online(local);+ 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 on a computer switched to a Harness Team account nothing is '+ 'sent, and the app says this computer cannot send it', () async {+ // `harness team on`: this computer's daemon now signs in as the team.+ native(_row('here', sessionKind: 'team'));+ online(_row('elsewhere', sessionKind: 'computer'));++ expect(app.sharedTabsTarget, isNull);+ await expectLater(+ post(),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'MACHINE_UNAVAILABLE')+ .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';++ expect(app.sharedTabsTarget, isNull);+ await expectLater(+ post(),+ throwsA(+ isA<SuperTabFailure>().having(+ (f) => f.code,+ 'code',+ 'MACHINE_UNAVAILABLE',+ ),+ ),+ );+ expect(relayed, isEmpty);+ });+}