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.

Harness web: connect page, web E2EE hardening, and a searchable, phone-ready Hub (#1037)

Jacob Phamb19f9955d2cb
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0b65aff02..10067be66 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -157,6 +157,12 @@ jobs:
/docs/images/
/mobile/pubspec.lock
/backend/src/lib/communityContract.ts
+ /mobile/lib/p2p/terminal_p2p_plugin.dart
+ /mobile/lib/p2p/terminal_p2p_link.dart
+ /mobile/lib/p2p/terminal_p2p_policy.dart
+ /mobile/lib/ws/terminal_transport_plugin.dart
+ /mobile/lib/ws/relay_codec.dart
+ /mobile/lib/e2ee/relay_session_crypto.dart
/.gitattributes
/.gitignore
/.gitmodules
diff --git a/.gitignore b/.gitignore
index fac6749c0..849beed6e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -119,3 +119,4 @@ mobile/docs/
work/experience-evidence/
mobile/OTA.md
mobile/scripts/ota-ios.sh
+.playwright-mcp
diff --git a/backend/src/routes/community.test.ts b/backend/src/routes/community.test.ts
index 6b327b7b2..9d156c6e3 100644
--- a/backend/src/routes/community.test.ts
+++ b/backend/src/routes/community.test.ts
@@ -6,8 +6,10 @@ type Query = { where?: Record<string, unknown>; select?: Record<string, boolean>
const db = vi.hoisted(() => {
function matches(row: Row, where: Record<string, unknown> = {}): boolean {
return Object.entries(where).every(([key, value]) => {
+ if (key === 'OR') return (value as Record<string, unknown>[]).some(branch => matches(row, branch))
if (value && typeof value === 'object' && !(value instanceof Date)) {
const filter = value as Record<string, unknown>
+ if ('contains' in filter) return typeof row[key] === 'string' && (row[key] as string).toLowerCase().includes((filter.contains as string).toLowerCase())
if ('in' in filter) return (filter.in as unknown[]).includes(row[key])
if ('gt' in filter) return (row[key] as Date) > (filter.gt as Date)
if ('isSet' in filter || 'not' in filter) return (!filter.isSet || row[key] !== undefined) && (!('not' in filter) || row[key] !== filter.not)
@@ -228,6 +230,16 @@ describe('persistent social actions', () => {
expect((await call('POST', `harnesses/${starter}/comments`, 'alice', payload)).statusCode).toBe(200)
expect((await call('POST', `harnesses/${starter}/comments`, 'alice', { ...payload, body: ' ' })).statusCode).toBe(400)
})
+ it('searches publications on the server, case-insensitively, within the feed filters', async () => {
+ await publish('alice', { ...sample, title: 'Lantern room' }); await publish('bob', { ...sample, title: 'Orbit study', description: 'Planets in a lantern light' })
+ const search = async (query: string, token?: string) => (await call('GET', `harnesses?${query}`, token)).json().data.harnesses.map((row: { title: string }) => row.title)
+ expect(await search('q=LANTERN')).toEqual(expect.arrayContaining(['Lantern room', 'Orbit study']))
+ expect(await search('q=lantern')).toHaveLength(2)
+ expect(await search('q=lantern&mine=true', 'alice')).toEqual(['Lantern room'])
+ expect(await search('q=nothing-like-this')).toEqual([])
+ expect((await call('GET', 'harnesses?q=')).statusCode).toBe(400)
+ expect((await call('GET', `harnesses?q=${'x'.repeat(81)}`)).statusCode).toBe(400)
+ })
it('follows real creators and filters the following feed', async () => {
await publish('alice'); await publish('bob')
expect((await call('PUT', 'creators/alice/follow', 'bob', { following: true })).statusCode).toBe(200)
diff --git a/backend/src/routes/community.ts b/backend/src/routes/community.ts
index 8c957ae51..3eb84ceb9 100644
--- a/backend/src/routes/community.ts
+++ b/backend/src/routes/community.ts
@@ -26,6 +26,13 @@ function withCoverPath<T extends { id: string; cover: string | null }>(row: T):
const { cover, ...rest } = row
return { ...rest, ...(cover ? { cover: `/api/community/harnesses/${row.id}/cover` } : {}) }
}
+const searchMaxChars = 80
+/** The fields a reader searches by. TODO(BE): an unanchored match scans the environment's publications; move to an Atlas Search index once the feed outgrows that. */
+const searchFields = ['title', 'description', 'authorName', 'category', 'engine', 'harnessId'] as const
+function searchWhere(q?: string) {
+ if (!q) return {}
+ return { OR: searchFields.map(field => ({ [field]: { contains: q, mode: 'insensitive' as const } })) }
+}
const params = z.object({ id: identifier })
const file = z.object({
path: z.string().regex(communityPathPattern).refine(path =>
@@ -98,13 +105,13 @@ async function publication(id: string, autonomousEnv: string) {
export async function communityRoutes(app: FastifyInstance): Promise<void> {
app.addHook('onSend', async (_req, reply) => { reply.header('Cache-Control', 'no-store') })
- const feedQuery = z.object({ cursor: z.string().uuid().optional(), following: z.enum(['true', 'false']).optional(), mine: z.enum(['true', 'false']).optional() }).strict()
+ const feedQuery = z.object({ cursor: z.string().uuid().optional(), following: z.enum(['true', 'false']).optional(), mine: z.enum(['true', 'false']).optional(), q: z.string().trim().min(1).max(searchMaxChars).optional() }).strict()
app.get<{ Querystring: z.infer<typeof feedQuery> }>('/api/community/harnesses', { preHandler: validateQuery(feedQuery) }, async (req, reply) => {
const autonomousEnv = environment(req)
if ((req.query.following === 'true' || req.query.mine === 'true') && !req.user) return sendError(reply, 'Sign in to see your harnesses and creators you follow.', 'UNAUTHORIZED', 401)
const follows = req.user ? await prisma.communityFollow.findMany({ where: { autonomousEnv, userId: req.user.sub }, select: { authorId: true } }) : []
const rows = await prisma.communityHarness.findMany({
- where: { autonomousEnv, deletedAt: null, ...(req.query.following === 'true' ? { authorId: { in: follows.map(row => row.authorId) } } : {}), ...(req.query.mine === 'true' ? { authorId: req.user!.sub } : {}) },
+ where: { autonomousEnv, deletedAt: null, ...(req.query.following === 'true' ? { authorId: { in: follows.map(row => row.authorId) } } : {}), ...(req.query.mine === 'true' ? { authorId: req.user!.sub } : {}), ...searchWhere(req.query.q) },
select: { id: true, title: true, description: true, category: true, engine: true, harnessId: true, authorId: true, authorName: true, forkedFrom: true, createdAt: true },
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], take: 31,
...(req.query.cursor ? { cursor: { id: req.query.cursor }, skip: 1 } : {}),
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index 475c2796a..b568083b0 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -141,8 +141,19 @@ origin-local storage; only the OAuth transaction is in session storage.
Each relay connection also negotiates a WebRTC data channel to the machine
(`web/p2p/`, the phone's `../mobile/lib/p2p` on the browser's own
`RTCPeerConnection` — no `flutter_webrtc`, so native builds gain no plugin);
-terminal frames take it when it is up and fall back to the relay. Keep
-`terminal_p2p_{plugin,link,policy}.dart` in step with the phone's copies.
+terminal frames take it when it is up and fall back to the relay. Those files,
+the transport interface and the E2EE session are copies of the phone's (mobile
+stays a standalone package); `test/p2p/mobile_parity_test.dart` fails until a
+change is carried to both. The browser's E2EE is pure Dart on the UI thread,
+and that is fine: sealing plus opening a 4 KiB frame measured 316 µs under
+dart2js `-O4`, 282 µs on the Dart VM and 479 µs as `-O4` WASM (Node 24,
+2026-10-06) — `flutter test --platform chrome` compiles unoptimized and reads
+~40× slower, so do not judge it there. WASM is not worth adopting for speed.
+System notifications in a browser use its Notification API
+(`web/notify/browser_system_notifier.dart`, picked by `notify/browser_notifier.dart`):
+the same Settings switch, one per agent by `tag`, a click focuses the tab and
+opens the agent. A phone's browser cannot construct one (service workers only),
+which reads as unavailable.
Shared sessions use `ObserverRelayCodec` and `/api/observer-ws`, verifying the
owner and permitting only observation and authenticated comments. `/s/:id#key=…`
opens `SharedAgentPage` without restoring the visitor's workspace. Public links
diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dart
index b5f29c693..86ffd0c98 100644
--- a/desktop/lib/e2ee/envelope.dart
+++ b/desktop/lib/e2ee/envelope.dart
@@ -9,9 +9,11 @@ import 'primitives.dart';
const int e2eVersion = 1;
-/// Frames this client must send as ciphertext — core.ts `ENCRYPTED_DOWN_TYPES`. test/e2ee/ holds it
-/// to the CLI's own list, because a type missing here fails nowhere: the frame simply leaves in the
-/// clear, and for terminal_* the relay then drops it as TERMINAL_FRAME_REJECTED.
+/// Frames this client must send as ciphertext — the machine's `encryptDownFrame` rule
+/// (applicationFrames.ts: core.ts `ENCRYPTED_DOWN_TYPES` and the request sets beside it).
+/// test/e2ee/ holds it to that whole rule, because a type missing here fails nowhere: the frame
+/// simply leaves in the clear and the machine answers E2EE_REQUIRED (for terminal_* the relay
+/// drops it as TERMINAL_FRAME_REJECTED).
const Set<String> encryptedDownTypes = {
'harness_devices_list',
'harness_device_settings',
@@ -102,6 +104,29 @@ const Set<String> encryptedDownTypes = {
'p2p_ice_candidate',
'p2p_abort',
'p2p_promote',
+ // The rest of what the machine requires sealed: its rule is `encryptDownFrame`
+ // (cli/src/lib/e2ee/applicationFrames.ts), the set above OR the sets named beside
+ // it (`git_pull_request` is above, beside `git_project_info`). These are listed
+ // before anything sends them.
+ 'agent_purge',
+ 'agent_worktree_delete',
+ 'agents_cleanup_preview',
+ 'viewer_request',
+ 'viewer_data',
+ 'viewer_ack',
+ 'viewer_end',
+ 'viewer_close',
+ 'pair_watch',
+ 'pair_journal',
+ 'pair_read',
+ 'pair_list',
+ 'pair_answer',
+ 'pair_send',
+ 'pair_stop',
+ 'pair_start',
+ 'pair_pause',
+ 'pair_resume',
+ 'pair_plate_get',
};
/// Requests an older CLI took in the clear and a current one refuses unsealed — applicationFrames.ts
diff --git a/desktop/lib/e2ee/relay_session_crypto.dart b/desktop/lib/e2ee/relay_session_crypto.dart
index 513490892..2bfeea27d 100644
--- a/desktop/lib/e2ee/relay_session_crypto.dart
+++ b/desktop/lib/e2ee/relay_session_crypto.dart
@@ -83,7 +83,14 @@ class RelaySessionCrypto {
/// Takes the machine's `e2e_welcome`; true once the session is usable. False means the machine
/// did not prove it holds the identity this app pinned for it, or the welcome did not open.
+ ///
+ /// ⚠️ **One welcome per session.** Once one has made the session usable, any other is refused
+ /// and changes nothing. A welcome is signed but not fresh: the relay can hand the same one back
+ /// at any time, and taking it again reset the group key to the one it carried — undoing every
+ /// `e2e_rekey` since, which is how the machine locks out a client it revoked. That client still
+ /// holds the old key, and could then write into this session's view.
Future<bool> handleWelcome(Map<String, dynamic> payload) async {
+ if (ready) return false;
try {
final adapterEphPub = _bytesField(payload, 'ephPub');
final sig = _bytesField(payload, 'sig');
@@ -119,10 +126,16 @@ class RelaySessionCrypto {
/// Takes an `e2e_rekey` — the machine rotated its group key, which it does when it revokes a
/// client. False when it does not open.
+ ///
+ /// ⚠️ Held to the same replay window as every other frame under [_s2c]: the machine seals a
+ /// rekey with the very counter its pairwise frames take (manager.ts `rotateGroupKey`), so one
+ /// seen before is one replayed. Unchecked, the relay could hand back an OLD rekey after a newer
+ /// one and roll the group key back to one a revoked client still holds.
bool handleRekey(Map<String, dynamic> payload) {
final s2c = _s2c;
final n = payload['n'], enc = payload['enc'];
if (s2c == null || n is! int || enc is! String || enc.isEmpty) return false;
+ if (!_s2cRecv.allows(n)) return false;
try {
final opened = aeadOpen(s2c, n, utf8Bytes('e2e-rekey'), b64d(enc));
final next = opened == null ? null : jsonObjectOf(opened);
@@ -132,6 +145,7 @@ class RelaySessionCrypto {
}
_groupKey = b64d(groupKey);
_epoch = epoch;
+ _s2cRecv.commit(n);
return true;
} on FormatException {
return false;
diff --git a/desktop/lib/notify/browser_notifier.dart b/desktop/lib/notify/browser_notifier.dart
new file mode 100644
index 000000000..09f1268de
--- /dev/null
+++ b/desktop/lib/notify/browser_notifier.dart
@@ -0,0 +1,6 @@
+/// The browser's notifier in a browser build, none anywhere else — picked at
+/// compile time, so native builds never compile `lib/web/`.
+library;
+
+export 'browser_notifier_none.dart'
+ if (dart.library.js_interop) '../web/notify/browser_system_notifier.dart';
diff --git a/desktop/lib/notify/browser_notifier_none.dart b/desktop/lib/notify/browser_notifier_none.dart
new file mode 100644
index 000000000..62ad65e1a
--- /dev/null
+++ b/desktop/lib/notify/browser_notifier_none.dart
@@ -0,0 +1,4 @@
+import 'system_notifications.dart';
+
+/// Outside a browser there is no browser notifier.
+SystemNotifier browserSystemNotifier() => const NoSystemNotifier();
diff --git a/desktop/lib/notify/system_notifications.dart b/desktop/lib/notify/system_notifications.dart
index db3737339..0aa0c33fa 100644
--- a/desktop/lib/notify/system_notifications.dart
+++ b/desktop/lib/notify/system_notifications.dart
@@ -8,6 +8,7 @@ import 'package:flutter/services.dart';
import 'agent_alerts.dart';
import 'alert_sounds.dart';
+import 'browser_notifier.dart';
/// Whether an agent's news is ALSO handed to the operating system, so it reaches
/// somebody whose window is behind their editor, on another desktop, or minimised.
@@ -55,6 +56,10 @@ abstract class SystemNotifier {
/// what the platform does.
bool get clickOpensAgent;
+ /// Where a person who said no turns notifications back on — Settings shows
+ /// it under a switch that is on but [NotificationPermission.denied].
+ String get deniedAdvice;
+
/// Ask for permission if it has not been asked, and say what the answer is.
Future<NotificationPermission> authorize();
@@ -84,6 +89,10 @@ class NoSystemNotifier implements SystemNotifier {
@override
bool get clickOpensAgent => false;
+ @override
+ String get deniedAdvice =>
+ 'Allow it in System Settings ▸ Notifications ▸ Harness.';
+
@override
Future<NotificationPermission> authorize() async =>
NotificationPermission.unavailable;
@@ -122,6 +131,10 @@ class MacSystemNotifier implements SystemNotifier {
@override
bool get clickOpensAgent => true;
+ @override
+ String get deniedAdvice =>
+ 'Allow it in System Settings ▸ Notifications ▸ Harness.';
+
@override
Future<NotificationPermission> authorize() => _ask('authorize', null);
@@ -211,6 +224,10 @@ class LinuxSystemNotifier implements SystemNotifier {
@override
bool get clickOpensAgent => false;
+ @override
+ String get deniedAdvice =>
+ 'Allow it in System Settings ▸ Notifications ▸ Harness.';
+
@override
Future<NotificationPermission> authorize() async {
try {
@@ -276,7 +293,7 @@ class LinuxSystemNotifier implements SystemNotifier {
/// The notifier for the platform this build runs on.
SystemNotifier platformSystemNotifier() {
- if (kIsWeb) return const NoSystemNotifier();
+ if (kIsWeb) return browserSystemNotifier();
if (Platform.isMacOS) return MacSystemNotifier();
if (Platform.isLinux) return LinuxSystemNotifier();
return const NoSystemNotifier();
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 111f75ffc..e154997ac 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -6325,11 +6325,16 @@ class _SwarmScreenState extends State<SwarmScreen> {
machine.connectionStatus == ConnectionStatus.connected,
);
- bool get _browserMachineSetupReady =>
+ /// The inventory has answered, and answered for now: loaded, not loading,
+ /// not stale, no error. What the account HAS, independent of what is open.
+ bool get _machineInventorySettled =>
app.machineInventoryLoaded &&
!app.machinesLoading &&
!app.machinesAreStale &&
- app.machineListError == null &&
+ app.machineListError == null;
+
+ bool get _browserMachineSetupReady =>
+ _machineInventorySettled &&
!app.machineStates.values.any(
(machine) =>
!machine.machine.isShared &&
@@ -6345,8 +6350,48 @@ class _SwarmScreenState extends State<SwarmScreen> {
_search == null &&
_routeIsCurrent;
+ /// No computer of the account's is connected, and none is on its way: the
+ /// inventory has answered, and every one is missing, offline or waiting to
+ /// be linked — what the host's [WorkspaceChrome.firstMachine] is for.
+ bool get _needsFirstConnection =>
+ _machineInventorySettled &&
+ !_hasConnectedBrowserMachine &&
+ !app.machineStates.values.any(
+ (machine) =>
+ !machine.machine.isShared &&
+ !machine.needsLink &&
+ machine.nodeOnline != false &&
+ (machine.connectionStatus == ConnectionStatus.connecting ||
+ machine.connectionStatus == ConnectionStatus.reconnecting),
+ );
+
+ /// The host's connect-a-computer page over the whole workspace — tabs synced
+ /// from the account's desk would otherwise show panes for computers this
+ /// browser cannot reach yet. Null when not needed, and for a host without one.
+ Widget? _firstConnection(BuildContext context) {
+ final page = widget.chrome?.firstMachine;
+ if (page == null || !_needsFirstConnection) return null;
+ return ColoredBox(
+ color: grid.AppPalette.swarmTabBar,
+ child: Center(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.all(24),
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 760),
+ child: page(context),
+ ),
+ ),
+ ),
+ );
+ }
+
void _maybeInitialBrowserMachines() {
if (_browserMachineSetupHandled) return;
+ // A host with a connect page never covers it with the machine picker.
+ if (widget.chrome?.firstMachine != null) {
+ _browserMachineSetupHandled = true;
+ return;
+ }
if (_hasConnectedBrowserMachine) {
_browserMachineSetupHandled = true;
return;
@@ -7200,6 +7245,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
),
),
+ if (_firstConnection(context)
+ case final connect?)
+ Positioned.fill(child: connect),
],
),
),
diff --git a/desktop/lib/settings/sections/alerts_card.dart b/desktop/lib/settings/sections/alerts_card.dart
index 7f57590de..4aa20021b 100644
--- a/desktop/lib/settings/sections/alerts_card.dart
+++ b/desktop/lib/settings/sections/alerts_card.dart
@@ -85,6 +85,7 @@ class AlertsCard extends StatelessWidget {
controlSemanticLabel: 'Desktop notifications',
detail: _systemDetail(
clickOpensAgent: system.notifier.clickOpensAgent,
+ deniedAdvice: system.notifier.deniedAdvice,
on: system.store.value,
permission: system.permission.value,
),
@@ -108,6 +109,7 @@ class AlertsCard extends StatelessWidget {
/// can do nothing has to say why, or it reads as broken.
String _systemDetail({
required bool clickOpensAgent,
+ required String deniedAdvice,
required bool on,
required NotificationPermission permission,
}) {
@@ -117,8 +119,7 @@ String _systemDetail({
if (!on) return base;
return switch (permission) {
NotificationPermission.denied =>
- 'Harness is not allowed to post notifications. Allow it in System '
- 'Settings ▸ Notifications ▸ Harness.',
+ 'Harness is not allowed to post notifications. $deniedAdvice',
NotificationPermission.unavailable =>
'Notifications cannot be posted from this build or this computer. The '
'on-screen banner still works.',
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 808cee1db..cd4008499 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -118,6 +118,7 @@ import '../notify/system_notifications.dart' as notify_system;
import 'account_devices.dart';
import '../viewer/device_log.dart' show DevLogHead;
import '../viewer/device_log_sync.dart';
+import '../viewer/removed_machines.dart';
import '../e2ee/bytes.dart' show b64e;
import '../viewer/device_history.dart' show DeviceLogHistory;
@@ -4490,6 +4491,7 @@ class AppNotifier extends ChangeNotifier {
Future<void> _finishBootstrapSignedIn() async {
final revision = _authRevision;
if (!_authWorkCurrent(revision)) return;
+ _localSeatFollowed = false;
// Which sign-in this app is under is the device log's to know before anything below can read it
// (a restored pane, the dial, the pool, a connection's push): synchronous, ahead of the first await.
// A sign-in by hand just now is `fresh`; a stored session (the app opening) is not.
@@ -4514,6 +4516,7 @@ class AppNotifier extends ChangeNotifier {
// Every exit below clears the message: a boot superseded by a sign-out/sign-in mid-way (the
// `_authWorkCurrent` returns) used to leave "Starting local service…" on a screen nothing would
// ever repaint.
+ await _identifyBeforeLayout(revision);
await _restorePaneLayout(claimOnAttach: true);
_armLaunchClaimExpiry();
if (!_authWorkCurrent(revision)) {
@@ -4548,18 +4551,18 @@ class AppNotifier extends ChangeNotifier {
// independent of machine discovery and must not delay work — and a guest
// has no profile to load.
if (signedIn) unawaited(_loadProfile());
- // The desk too: tabs from the other computers appear as intent, like the
- // restored ones, and attach as their machines answer. It is the ACCOUNT's
- // desk (`Desk{userId}`), so a guest has none — asking for one would earn a
- // 401 on every poll for a document that cannot exist.
- if (signedIn) _deskEnsure(revision);
// The account's device key log: this app's key joins it (an existing sign-in too, from before
// the log existed), and every machine it names is trusted with no password.
if (signedIn) {
if (_deviceLog case final log?) {
// Which sign-in by hand this log's marks belong to is the log's own (minted at the start of
// this boot by `beginSignIn`), never the profile's id — nothing to wait for.
- unawaited(log.register().whenComplete(_syncPendingDevices));
+ unawaited(
+ log.register().whenComplete(() {
+ unawaited(_syncPendingDevices());
+ unawaited(_rereadRemovedMachines());
+ }),
+ );
} else {
// A desktop build: the daemon's own copy says which devices are still waiting to be seen.
unawaited(_syncPendingDevices());
@@ -4574,8 +4577,11 @@ class AppNotifier extends ChangeNotifier {
if (!_authWorkCurrent(revision)) return;
// The account may have changed while this window was closed — see
// [_followLocalMachineId]. Done AFTER the list, which is what says which id
- // this computer is served under now.
- await _followLocalMachineId(revision);
+ // this computer is served under now. The desk follows it: tabs from the
+ // other computers appear as intent and attach as their machines answer. It
+ // is the ACCOUNT's desk (`Desk{userId}`), so a guest has none — asking for
+ // one would earn a 401 on every poll for a document that cannot exist.
+ await _followLocalMachineIdThenDesk(revision);
if (_authWorkCurrent(revision)) notifyListeners();
}
@@ -4848,6 +4854,23 @@ class AppNotifier extends ChangeNotifier {
return load;
}
+ /// Who signed in, before the saved tabs are restored (see
+ /// [PaneLayoutStore.restorableFor]). A browser is the window anyone may sign
+ /// in on, and it has no daemon to wait for, so this costs one request there;
+ /// a native build reaches the profile through its daemon and keeps restoring
+ /// first. Unknown — the request failed — restores as before.
+ Future<void> _identifyBeforeLayout(int revision) async {
+ if (viewer == null || !signedIn) return;
+ try {
+ final me = await api.me();
+ if (me != null && _authWorkCurrent(revision)) {
+ currentUser = CurrentUserProfile.fromMe(me);
+ }
+ } catch (_) {
+ /* Unknown: the profile load after boot tries again. */
+ }
+ }
+
Future<void> _readProfile(int revision) async {
try {
final me = await api.me();
@@ -6543,6 +6566,13 @@ class AppNotifier extends ChangeNotifier {
/// exactly one more follows it. A bulk rename pushes once per machine;
/// without this each push would be its own pair of requests. A timer tick
/// that finds a read open has nothing to add and is dropped.
+ /// Read the machine list again quietly — no loading state, the rows on
+ /// screen stay — as a missed `machines_changed` push would. For a screen
+ /// waiting on a computer this window has no connection to hear that push
+ /// through: an account with none connected yet (the browser's connect page).
+ Future<void> rereadMachines() =>
+ _rereadMachinesInBackground(pushed: false);
+
Future<void> _rereadMachinesInBackground({required bool pushed}) async {
if (_disposed || status != AppStatus.authenticated) return;
if (_sharingDiscoveryBusy) {
@@ -6623,6 +6653,50 @@ class AppNotifier extends ChangeNotifier {
_offlineRetryTimers.remove(machineId)?.cancel();
}
+ /// Dials [machineId] now instead of at the link retry's next tick. A machine
+ /// that trusts this device through the account's device key log answers with
+ /// no password at all. True once it is connected; false when it still wants
+ /// this device linked (a CLI from before the log, or a log that does not name
+ /// this device yet), or has not answered within [timeout].
+ Future<bool> connectTrusted(
+ String machineId, {
+ Duration timeout = const Duration(seconds: 12),
+ }) async {
+ final state = machineStates[machineId];
+ if (state == null || state.machine.isShared) return false;
+ final done = Completer<bool>();
+ var dialed = false;
+ void settle() {
+ final now = machineStates[machineId];
+ if (done.isCompleted) return;
+ if (now == null) return done.complete(false);
+ final status = now.connectionStatus;
+ if (status == ConnectionStatus.connected && !now.needsLink) {
+ return done.complete(true);
+ }
+ if (status == ConnectionStatus.connecting ||
+ status == ConnectionStatus.reconnecting) {
+ dialed = true;
+ } else if (dialed && now.needsLink) {
+ done.complete(false);
+ }
+ }
+
+ addListener(settle);
+ final timer = Timer(timeout, () {
+ if (!done.isCompleted) done.complete(false);
+ });
+ try {
+ await _pool?.closeMachine(machineId);
+ if (machineStates[machineId] case final current?) _connectMachine(current);
+ settle();
+ return await done.future;
+ } finally {
+ timer.cancel();
+ removeListener(settle);
+ }
+ }
+
void _startLinkRetry(String machineId) {
if (_linkRetryTimers.containsKey(machineId)) return;
_linkRetryTimers[machineId] = Timer.periodic(offlineRetryInterval, (_) {
@@ -6953,6 +7027,7 @@ class AppNotifier extends ChangeNotifier {
newDevices.clear();
departedDevices.clear();
deviceRemovals.clear();
+ removedMachines = const {};
_queuedDeviceNotices.clear();
deviceConflict = null;
_dismissedConflict = null;
@@ -7007,6 +7082,7 @@ class AppNotifier extends ChangeNotifier {
onChanged: () {
devicesRevision++;
unawaited(_syncPendingDevices());
+ unawaited(_rereadRemovedMachines());
unawaited(_redialPinnedMachines());
if (!_disposed) notifyListeners();
},
@@ -7014,6 +7090,25 @@ class AppNotifier extends ChangeNotifier {
services.links.deviceLog = log;
}
+ /// Viewer builds only: machines the account's device key log took out and gave no new key since,
+ /// by the seq of the removal (`viewer/removed_machines.dart`). The connect page says such a machine
+ /// was removed rather than offline — it is signed out, and opening Harness on it will not bring it
+ /// back.
+ Map<String, int> removedMachines = const {};
+
+ Future<void> _rereadRemovedMachines() async {
+ final keys = viewer?.keys;
+ if (keys == null) return;
+ try {
+ final next = removedMachinesOf(await keys.deviceLog());
+ if (_disposed || mapEquals(next, removedMachines)) return;
+ removedMachines = next;
+ notifyListeners();
+ } catch (_) {
+ // Unreadable now; the next change to the log reads it again.
+ }
+ }
+
/// What the device log announced while the app was not yet signed in (starting up): the log has
/// already recorded it as announced, so it is said once the app is authenticated — never lost to the
/// startup order, and dropped only when the person is signed out.
@@ -7895,9 +7990,9 @@ class AppNotifier extends ChangeNotifier {
}
if (signedIn && currentUser == null) unawaited(_loadProfile());
// A boot that found the daemon still connecting finishes THROUGH here (see
- // `_loadProfile`), so the desk is joined here as well — once.
+ // `_loadProfile`), so the local id is followed and the desk joined here as
+ // well — once, after the list, as the boot does.
if (signedIn) {
- _deskEnsure(revision);
// The first boot's read may have found nothing to say yet (or been dropped); read again —
// until one has succeeded.
if (!_pendingBootReadDone) unawaited(_syncPendingDevices());
@@ -7905,6 +8000,8 @@ class AppNotifier extends ChangeNotifier {
try {
if (!await refreshMachines() || !_authWorkCurrent(revision)) return;
if (!automatic) _lastError = null;
+ if (!_localSeatFollowed) await _followLocalMachineIdThenDesk(revision);
+ if (signedIn) _deskEnsure(revision);
} catch (error) {
if (!_authWorkCurrent(revision)) return;
_reportMachineLoadError(error, automatic: automatic);
@@ -14348,10 +14445,28 @@ class AppNotifier extends ChangeNotifier {
/// answered the first read with an error, not with a desk.
void _deskEnsure(int authRevision) {
if (workspaceEnabled?.call() == false) return;
+ if (!_localSeatFollowed) return;
if (_desk.enabled || _deskJoining != null) return;
unawaited(_deskStart(authRevision));
}
+ /// Whether this sign-in has followed this computer's machine id
+ /// ([_followLocalMachineId]) — re-seated the tiles this window made while
+ /// signed out, which sit on the computer's own id. The desk is not joined
+ /// before: its seed is every local tab it lacks, and a tab still on that id
+ /// landed on the ACCOUNT's desk naming a machine nothing serves, opening on
+ /// every window of it as "This machine isn't available" — a new user's first
+ /// sign-in on the desktop did exactly that.
+ bool _localSeatFollowed = false;
+
+ /// [_followLocalMachineId], then the desk it was holding back.
+ Future<void> _followLocalMachineIdThenDesk(int revision) async {
+ await _followLocalMachineId(revision);
+ if (!_authWorkCurrent(revision)) return;
+ _localSeatFollowed = true;
+ if (signedIn) _deskEnsure(revision);
+ }
+
Future<void> _deskJoin(int authRevision) async {
// Edits remain available while the first read is pending. Remember the
// existing desk tabs now so its eventual reply cannot undo a rename,
@@ -14854,6 +14969,7 @@ class AppNotifier extends ChangeNotifier {
? savedActive!
: saved.last.id,
monitorHarnesses: _monitorHarnesses,
+ owner: currentUser?.id,
),
);
}
@@ -14890,8 +15006,16 @@ class AppNotifier extends ChangeNotifier {
final revision = _layoutRevision;
final authRevision = _authRevision;
final savedProfile = await store.loadMachineProfile();
- final saved = await store.loadSwarms();
- final known = await store.loadMonitorHarnesses(saved);
+ final loaded = await store.loadSwarms();
+ // Another account's tabs and history — a browser someone else signed in
+ // on — are not this one's to see: start from an empty desk instead.
+ final foreign =
+ loaded != null &&
+ !PaneLayoutStore.restorableFor(loaded, currentUser?.id);
+ final saved = foreign ? null : loaded;
+ final known = foreign
+ ? const <(String, String)>[]
+ : await store.loadMonitorHarnesses(saved);
if (!_authWorkCurrent(authRevision)) return;
// This window's own choice, never the desk's. No saved choice — a window
// that never picked one — is All machines.
diff --git a/desktop/lib/state/pane_layout_store.dart b/desktop/lib/state/pane_layout_store.dart
index 69d4a9d9c..bb9178757 100644
--- a/desktop/lib/state/pane_layout_store.dart
+++ b/desktop/lib/state/pane_layout_store.dart
@@ -261,10 +261,23 @@ class PaneLayoutStore {
return result;
}
+ /// Whether [layout] may be restored for [account].
+ ///
+ /// A browser is shared by whoever signs in on it, and the tabs it saved are
+ /// the last account's: their names and harness history must not open under
+ /// another one, nor be seeded into its desk. A layout from before owners were
+ /// recorded, or a sign-in whose account is not known yet, keeps the old
+ /// behaviour; a known account never takes another account's tabs.
+ static bool restorableFor(Map<String, dynamic> layout, String? account) {
+ final owner = layout['owner'];
+ return owner is! String || account == null || owner == account;
+ }
+
Future<void> saveSwarms(
List<Swarm> swarms,
String activeId, {
Iterable<(String, String)> monitorHarnesses = const [],
+ String? owner,
}) {
// Capture each request before yielding, but keep only the latest snapshot
// while a write is pending. Holding a navigation key must not queue a full
@@ -272,6 +285,7 @@ class PaneLayoutStore {
try {
_pendingSwarmSnapshot = jsonEncode({
'version': 1,
+ 'owner': ?owner,
'activeId': activeId,
'swarms': swarms.map((s) => s.toJson()).toList(),
'monitorHarnesses': [
diff --git a/desktop/lib/state/workspace_chrome.dart b/desktop/lib/state/workspace_chrome.dart
index c27e009c6..d45e54988 100644
--- a/desktop/lib/state/workspace_chrome.dart
+++ b/desktop/lib/state/workspace_chrome.dart
@@ -64,8 +64,14 @@ class WorkspaceChrome {
this.compactTabs,
this.compactFooter,
this.compactBelow = 0,
+ this.firstMachine,
});
+ /// Shown over the workspace while none of the account's computers is
+ /// connected, instead of opening the machine picker unasked. Null keeps the
+ /// picker.
+ final Widget Function(BuildContext context)? firstMachine;
+
final double Function(BuildContext context) leadingWidth;
final Widget Function(BuildContext context, WorkspaceCommands commands)
leading;
diff --git a/desktop/lib/viewer/removed_machines.dart b/desktop/lib/viewer/removed_machines.dart
new file mode 100644
index 000000000..6f73645ed
--- /dev/null
+++ b/desktop/lib/viewer/removed_machines.dart
@@ -0,0 +1,29 @@
+import 'dart:math';
+
+import 'device_log.dart';
+
+/// The machines the account's device key log took out and has not let back in under a new key, each
+/// with the seq of its latest removal — read from this app's stored copy of the log
+/// (`ViewerKeyStore.deviceLog`). Only the entries that copy keeps (the newest few dozen) are seen, so
+/// this is a hint for what a list says about a machine, never a reason to trust or distrust one: the
+/// log itself already unpinned it.
+Map<String, int> removedMachinesOf(Object? stored) {
+ if (stored is! Map) return const {};
+ final state = DevLogState.fromJson(stored['state']);
+ if (state == null) return const {};
+ final keyed = {
+ for (final m in state.active.values)
+ if (m.kind == 'machine') m.machineId,
+ };
+ final removed = <String, int>{};
+ // A removal applied while the log was frozen is kept apart from the chained tail.
+ for (final list in [stored['recent'], stored['looseRemoved']]) {
+ if (list is! List) continue;
+ for (final e in list.map(DevLogEntry.parse).whereType<DevLogEntry>()) {
+ if (e.op != 'remove' || e.kind != 'machine') continue;
+ if (e.machineId.isEmpty || keyed.contains(e.machineId)) continue;
+ removed[e.machineId] = max(removed[e.machineId] ?? 0, e.seq);
+ }
+ }
+ return removed;
+}
diff --git a/desktop/lib/web/notify/browser_system_notifier.dart b/desktop/lib/web/notify/browser_system_notifier.dart
new file mode 100644
index 000000000..f4ad7a117
--- /dev/null
+++ b/desktop/lib/web/notify/browser_system_notifier.dart
@@ -0,0 +1,113 @@
+import 'dart:js_interop';
+import 'dart:js_interop_unsafe';
+
+import 'package:web/web.dart' as web;
+
+import '../../notify/system_notifications.dart';
+
+/// The notifier a browser build uses — see `notify/browser_notifier.dart`.
+SystemNotifier browserSystemNotifier() => BrowserSystemNotifier();
+
+/// The browser's own notifications (the Notification API): the web build's
+/// third channel beside the banner and the sound, as `UNUserNotificationCenter`
+/// is on macOS. Posted only while the tab is not in front, like everywhere.
+///
+/// One per agent, under the same id the desktop uses, as the notification's
+/// `tag`: the browser replaces an agent's last one instead of stacking them.
+/// A click brings this tab forward and opens that agent.
+///
+/// A phone's browser offers the API but posts only through a service worker,
+/// so constructing a notification throws there: that reads as
+/// [NotificationPermission.unavailable], and the banner keeps doing the job.
+class BrowserSystemNotifier implements SystemNotifier {
+ BrowserSystemNotifier({this.icon = 'icons/icon-192.png'});
+
+ /// Relative to the page's base, which serves the bundle's own icons.
+ final String icon;
+
+ final _shown = <String, web.Notification>{};
+ void Function(String machineId, String agentId)? _onTap;
+
+ @override
+ bool get supported => globalContext.has('Notification');
+
+ @override
+ bool get clickOpensAgent => true;
+
+ @override
+ String get deniedAdvice =>
+ "Allow notifications for this site in the browser's site settings.";
+
+ @override
+ Future<NotificationPermission> authorize() async {
+ if (!supported) return NotificationPermission.unavailable;
+ final current = _read(web.Notification.permission);
+ if (current != NotificationPermission.unknown) return current;
+ try {
+ return _read((await web.Notification.requestPermission().toDart).toDart);
+ } catch (_) {
+ return NotificationPermission.unknown;
+ }
+ }
+
+ @override
+ Future<NotificationPermission> show({
+ required String id,
+ required String title,
+ required String body,
+ required String machineId,
+ required String agentId,
+ }) async {
+ if (!supported) return NotificationPermission.unavailable;
+ final permission = _read(web.Notification.permission);
+ if (permission != NotificationPermission.granted) return permission;
+ try {
+ _shown.remove(id)?.close();
+ final notification = web.Notification(
+ title,
+ web.NotificationOptions(body: body, tag: id, icon: icon),
+ );
+ notification
+ ..onclick = ((web.Event _) {
+ web.window.focus();
+ _close(id, notification);
+ final handler = _onTap;
+ if (handler != null && machineId.isNotEmpty && agentId.isNotEmpty) {
+ handler(machineId, agentId);
+ }
+ }).toJS
+ ..onclose = ((web.Event _) => _forget(id, notification)).toJS;
+ _shown[id] = notification;
+ return NotificationPermission.granted;
+ } catch (_) {
+ return NotificationPermission.unavailable;
+ }
+ }
+
+ @override
+ Future<void> withdraw(String id) async {
+ final notification = _shown[id];
+ if (notification != null) _close(id, notification);
+ }
+
+ @override
+ set onTap(void Function(String machineId, String agentId)? handler) =>
+ _onTap = handler;
+
+ void _close(String id, web.Notification notification) {
+ _forget(id, notification);
+ notification.close();
+ }
+
+ /// Only if [notification] is still the one under [id]: a replaced one
+ /// closing late must not take its successor out of the map.
+ void _forget(String id, web.Notification notification) {
+ if (identical(_shown[id], notification)) _shown.remove(id);
+ }
+
+ static NotificationPermission _read(String value) => switch (value) {
+ 'granted' => NotificationPermission.granted,
+ 'denied' => NotificationPermission.denied,
+ _ => NotificationPermission.unknown,
+ };
+}
diff --git a/desktop/lib/web/onboarding/web_first_machine.dart b/desktop/lib/web/onboarding/web_first_machine.dart
new file mode 100644
index 000000000..63b7d1dc4
--- /dev/null
+++ b/desktop/lib/web/onboarding/web_first_machine.dart
@@ -0,0 +1,248 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../../shared/theme/app_icons.dart';
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../shared/widgets/command_row.dart';
+import '../../state/app_state.dart';
+import '../../widgets/desktop_chrome.dart';
+import '../../widgets/link_another_machine_dialog.dart'
+ show kLinkServerInstallCommand, kLinkServerLoginCommand;
+import '../../widgets/web_download_button.dart';
+import 'web_your_computers.dart';
+
+/// What a browser shows while none of the account's computers is connected,
+/// in place of the workspace — which used to open the machine picker: a search
+/// box with `@` in it, Harnesses/Agents/Store tabs that could do nothing, and
+/// two lines of help.
+///
+/// The account's computers first, if it has any ([WebYourComputers]): one
+/// waiting on this browser connects right here. Then both ways to set one up,
+/// side by side: the app for a desktop, the CLI for a server. Either signs in
+/// on that computer, which then appears here on its own; the workspace takes
+/// over the moment one connects.
+class WebFirstMachine extends StatefulWidget {
+ const WebFirstMachine({
+ super.key,
+ required this.app,
+ this.openPage = openInNewTab,
+ });
+
+ final AppNotifier app;
+
+ /// How the download page opens; tests pass a recorder.
+ final Future<bool> Function(Uri uri) openPage;
+
+ /// How often the page asks for the machine list while it waits. A computer
+ /// signing in is announced to the account's other windows over their
+ /// connections to its machines — and this one has none yet, so nothing
+ /// would tell it before the five-minute safety net.
+ static const watchEvery = Duration(seconds: 4);
+
+ @override
+ State<WebFirstMachine> createState() => _WebFirstMachineState();
+}
+
+class _WebFirstMachineState extends State<WebFirstMachine> {
+
+ String? _copied;
+ Timer? _copiedReset;
+ late final Timer _watch;
+
+ @override
+ void initState() {
+ super.initState();
+ _watch = Timer.periodic(
+ WebFirstMachine.watchEvery,
+ (_) => unawaited(widget.app.rereadMachines()),
+ );
+ }
+
+ @override
+ void dispose() {
+ _watch.cancel();
+ _copiedReset?.cancel();
+ super.dispose();
+ }
+
+ Future<void> _copy(String command) async {
+ await Clipboard.setData(ClipboardData(text: command));
+ if (!mounted) return;
+ setState(() => _copied = command);
+ _copiedReset?.cancel();
+ _copiedReset = Timer(const Duration(seconds: 2), () {
+ if (mounted) setState(() => _copied = null);
+ });
+ }
+
+ Widget _command(String command) => CommandRow(
+ command: command,
+ copied: _copied == command,
+ onCopy: () => unawaited(_copy(command)),
+ );
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final email = widget.app.currentUser?.email;
+ final account = email == null || email.isEmpty ? 'this account' : email;
+ final options = [
+ _Option(
+ icon: AppIcons.laptop,
+ title: 'Desktop app',
+ detail: 'On a Mac or Linux desktop. Open it and sign in as $account.',
+ children: [
+ FilledButton.icon(
+ onPressed: () => widget.openPage(WebDownloadButton.uri),
+ icon: const Icon(AppIcons.download, size: 16),
+ label: const Text('Download app'),
+ ),
+ ],
+ ),
+ _Option(
+ icon: AppIcons.squareTerminal,
+ title: 'Command line',
+ detail:
+ 'On a server, or anywhere you prefer a terminal. Run these there, '
+ 'and sign in as $account:',
+ children: [
+ _command(kLinkServerInstallCommand),
+ const SizedBox(height: 8),
+ _command(kLinkServerLoginCommand),
+ ],
+ ),
+ ];
+ final hasComputers = WebYourComputers.listed(widget.app).isNotEmpty;
+ return LayoutBuilder(
+ builder: (context, constraints) {
+ final sideBySide = constraints.maxWidth >= 640;
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Semantics(
+ header: true,
+ child: Text(
+ hasComputers ? 'Connect your computer' : 'Connect a computer',
+ textAlign: TextAlign.center,
+ style: grid.AppType.display(color: DesktopChrome.foreground),
+ ),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ hasComputers
+ ? 'Your harnesses run on your computers. Connect this '
+ 'browser to one to start.'
+ : 'Your harnesses run on a computer of yours. Set one up '
+ 'and it appears here by itself.',
+ textAlign: TextAlign.center,
+ style: DesktopChrome.text(color: DesktopChrome.muted),
+ ),
+ const SizedBox(height: 28),
+ if (hasComputers) ...[
+ WebYourComputers(app: widget.app),
+ const SizedBox(height: 18),
+ Text(
+ 'Or set up another computer',
+ style: DesktopChrome.heading(),
+ ),
+ const SizedBox(height: 12),
+ ],
+ sideBySide
+ ? IntrinsicHeight(
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(child: options.first),
+ const SizedBox(width: 16),
+ Expanded(child: options.last),
+ ],
+ ),
+ )
+ : Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ options.first,
+ const SizedBox(height: 16),
+ options.last,
+ ],
+ ),
+ const SizedBox(height: 24),
+ const Center(child: _Waiting()),
+ ],
+ );
+ },
+ );
+ }
+}
+
+/// One way in: what it is for, and what to do.
+class _Option extends StatelessWidget {
+ const _Option({
+ required this.icon,
+ required this.title,
+ required this.detail,
+ required this.children,
+ });
+
+ final IconData icon;
+ final String title;
+ final String detail;
+ final List<Widget> children;
+
+ @override
+ Widget build(BuildContext context) => Container(
+ padding: const EdgeInsets.all(20),
+ decoration: BoxDecoration(
+ color: DesktopChrome.field,
+ border: Border.all(color: DesktopChrome.rim),
+ borderRadius: BorderRadius.circular(DesktopChrome.dialogRadius),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ Icon(icon, size: 18, color: DesktopChrome.foreground),
+ const SizedBox(width: 10),
+ Text(title, style: DesktopChrome.heading()),
+ ],
+ ),
+ const SizedBox(height: 8),
+ Text(detail, style: DesktopChrome.text(color: DesktopChrome.muted)),
+ const SizedBox(height: 16),
+ ...children,
+ ],
+ ),
+ );
+}
+
+/// The workspace replaces this page when a computer connects; until then it
+/// says so, so the page does not read as finished.
+class _Waiting extends StatelessWidget {
+ const _Waiting();
+
+ @override
+ Widget build(BuildContext context) => Semantics(
+ liveRegion: true,
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ SizedBox.square(
+ dimension: 12,
+ child: CircularProgressIndicator(
+ strokeWidth: 1.5,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ const SizedBox(width: 10),
+ Text(
+ 'Waiting for your computer…',
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ ),
+ );
+}
diff --git a/desktop/lib/web/onboarding/web_your_computers.dart b/desktop/lib/web/onboarding/web_your_computers.dart
new file mode 100644
index 000000000..8898a4377
--- /dev/null
+++ b/desktop/lib/web/onboarding/web_your_computers.dart
@@ -0,0 +1,224 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../../core/models.dart';
+import '../../shared/theme/app_icons.dart';
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../state/app_state.dart';
+import '../../widgets/desktop_chrome.dart';
+import '../../widgets/machine_picker_form.dart';
+
+/// The account's computers this browser is not connected to. One waiting on
+/// this browser connects with a click — a computer trusts the account's other
+/// devices through its device key log, so there is no password to type — and
+/// one that does not answer says so and offers another try; one that is
+/// offline says what to do on it.
+///
+/// What used to open was the machine picker itself — a search box with `@` in
+/// it and tabs for harnesses and agents a browser with no computer cannot use.
+class WebYourComputers extends StatefulWidget {
+ const WebYourComputers({super.key, required this.app});
+
+ final AppNotifier app;
+
+ /// The ones to list: the account's own, not those shared with it, one per name
+ /// ([newestOfEachName]).
+ static List<MachineState> listed(AppNotifier app) => newestOfEachName([
+ for (final state in app.machineStates.values)
+ if (!state.machine.isShared) state,
+ ], app.removedMachines);
+
+ /// A computer set up again (its Harness data wiped, a reinstall) comes back
+ /// under a new id and leaves the old record behind, offline for good, under
+ /// the same name — and once its key is removed from the account it can never
+ /// come back. So of the machines sharing a name, the removed ones are left
+ /// out while any other is there, and otherwise only the latest removed is
+ /// kept: the one to sign in on again. [removed] is
+ /// [AppNotifier.removedMachines].
+ static List<MachineState> newestOfEachName(
+ List<MachineState> states,
+ Map<String, int> removed,
+ ) {
+ int? removedAt(MachineState s) => removed[s.machine.machineId];
+ final byName = <String, List<MachineState>>{};
+ for (final s in states) {
+ (byName[s.machine.displayName] ??= []).add(s);
+ }
+ bool kept(MachineState s) {
+ final at = removedAt(s);
+ if (at == null) return true;
+ final peers = byName[s.machine.displayName]!;
+ if (peers.any((p) => removedAt(p) == null)) return false;
+ return peers.every((p) => p == s || removedAt(p)! < at);
+ }
+
+ return [
+ for (final s in states)
+ if (kept(s)) s,
+ ];
+ }
+
+ @override
+ State<WebYourComputers> createState() => _WebYourComputersState();
+}
+
+class _WebYourComputersState extends State<WebYourComputers> {
+ /// The computer being dialed, and the ones the last try did not reach.
+ String? _trying;
+ final _failed = <String>{};
+
+ Future<void> _connect(String machineId) async {
+ setState(() {
+ _trying = machineId;
+ _failed.remove(machineId);
+ });
+ final connected = await widget.app.connectTrusted(machineId);
+ if (!mounted) return;
+ setState(() {
+ _trying = null;
+ if (!connected) _failed.add(machineId);
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (final state in WebYourComputers.listed(widget.app)) ...[
+ _ComputerRow(
+ app: widget.app,
+ state: state,
+ failed: _failed.contains(state.machine.machineId),
+ trying: _trying == state.machine.machineId,
+ onConnect: () => unawaited(_connect(state.machine.machineId)),
+ ),
+ const SizedBox(height: 10),
+ ],
+ ],
+ );
+ }
+}
+
+/// Where a computer stands with this browser.
+enum ComputerLinkState {
+ removed,
+ offline,
+ linking,
+ connecting,
+ failed,
+ ready,
+ idle,
+}
+
+ComputerLinkState computerLinkState(
+ AppNotifier app,
+ MachineState state, {
+ bool failed = false,
+ bool trying = false,
+}) {
+ final id = state.machine.machineId;
+ // Taken out of the account: it was signed out, and opening Harness on it
+ // will not bring it back — only signing in there again will.
+ if (app.removedMachines.containsKey(id) &&
+ state.connectionStatus != ConnectionStatus.connected) {
+ return ComputerLinkState.removed;
+ }
+ if (state.nodeOnline == false) return ComputerLinkState.offline;
+ if (app.pendingMachineLink(id) != null) return ComputerLinkState.linking;
+ if (trying ||
+ state.connectionStatus == ConnectionStatus.connecting ||
+ state.connectionStatus == ConnectionStatus.reconnecting) {
+ return ComputerLinkState.connecting;
+ }
+ if (failed) return ComputerLinkState.failed;
+ return state.needsLink ? ComputerLinkState.ready : ComputerLinkState.idle;
+}
+
+class _ComputerRow extends StatelessWidget {
+ const _ComputerRow({
+ required this.app,
+ required this.state,
+ required this.failed,
+ required this.trying,
+ required this.onConnect,
+ });
+
+ final AppNotifier app;
+ final MachineState state;
+ final bool failed;
+ final bool trying;
+ final VoidCallback onConnect;
+
+ @override
+ Widget build(BuildContext context) {
+ final link = computerLinkState(app, state, failed: failed, trying: trying);
+ final status = switch (link) {
+ ComputerLinkState.removed =>
+ 'Removed from your account. Sign in to Harness on it to add it back.',
+ ComputerLinkState.offline =>
+ 'Offline. Open Harness on it, or run harness start there.',
+ ComputerLinkState.linking => machineLinkProgress(
+ app.machineLinkStage(state.machine.machineId),
+ ),
+ ComputerLinkState.connecting => 'Connecting…',
+ ComputerLinkState.failed =>
+ "Couldn't connect. Check Harness is running on it, then try again.",
+ ComputerLinkState.ready => 'Ready to connect to this browser.',
+ ComputerLinkState.idle => 'Not connected yet.',
+ };
+ final busy =
+ link == ComputerLinkState.linking ||
+ link == ComputerLinkState.connecting;
+ return Container(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+ decoration: BoxDecoration(
+ color: DesktopChrome.field,
+ border: Border.all(color: DesktopChrome.rim),
+ borderRadius: BorderRadius.circular(DesktopChrome.dialogRadius),
+ ),
+ child: Row(
+ children: [
+ Icon(
+ link == ComputerLinkState.offline ||
+ link == ComputerLinkState.removed
+ ? AppIcons.monitorOff
+ : AppIcons.laptop,
+ size: 18,
+ color: DesktopChrome.foreground,
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ state.machine.displayName,
+ style: DesktopChrome.text(medium: true),
+ ),
+ Semantics(
+ liveRegion: true,
+ child: Text(status, style: DesktopChrome.metadata()),
+ ),
+ ],
+ ),
+ ),
+ if (busy)
+ SizedBox.square(
+ dimension: 14,
+ child: CircularProgressIndicator(
+ strokeWidth: 1.5,
+ color: DesktopChrome.muted,
+ ),
+ )
+ else if (link == ComputerLinkState.ready)
+ FilledButton(onPressed: onConnect, child: const Text('Connect'))
+ else if (link == ComputerLinkState.failed)
+ FilledButton(onPressed: onConnect, child: const Text('Try again')),
+ ],
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/web/shell/web_chrome.dart b/desktop/lib/web/shell/web_chrome.dart
index a62868bc1..d52a78e1c 100644
--- a/desktop/lib/web/shell/web_chrome.dart
+++ b/desktop/lib/web/shell/web_chrome.dart
@@ -1,5 +1,6 @@
import '../../state/app_state.dart';
import '../../state/workspace_chrome.dart';
+import '../onboarding/web_first_machine.dart';
import '../footer/web_footer_bar.dart';
import '../tabs/web_tab_switcher.dart';
import 'web_app_menu.dart';
@@ -24,4 +25,5 @@ WorkspaceChrome webWorkspaceChrome(AppNotifier app) => WorkspaceChrome(
WebTabSwitcher(app: app, commands: commands),
compactFooter: (context, footer) => WebFooterBar(footer: footer),
compactBelow: kWebCompactBelow,
+ firstMachine: (context) => WebFirstMachine(app: app),
);
diff --git a/desktop/lib/widgets/machine_picker_form.dart b/desktop/lib/widgets/machine_picker_form.dart
index 36f589e7b..22d87085b 100644
--- a/desktop/lib/widgets/machine_picker_form.dart
+++ b/desktop/lib/widgets/machine_picker_form.dart
@@ -25,6 +25,14 @@ import 'terminal_text_action.dart';
enum MachinePickerFormKind { connect, rename, password, delete, app, cli }
+/// What a password link in progress is doing, for anything that shows it — this
+/// form, and whatever lists the machine beside it.
+String machineLinkProgress(String? stage) => switch (stage) {
+ 'deriving_key' => 'Checking password…',
+ 'exchanging' || 'verifying' => 'Verifying the link…',
+ _ => 'Connecting…',
+};
+
/// An editor in the resource preview, not another route or machine picker.
/// Pending writes belong to AppNotifier and survive leaving this editor.
class MachinePickerForm extends StatefulWidget {
@@ -461,13 +469,9 @@ class MachinePickerFormState extends State<MachinePickerForm> {
label == 'Show' || label == 'Hide' ? 'visibility' : label;
String get _progress => switch (widget.kind) {
- MachinePickerFormKind.connect => switch (app.machineLinkStage(
- widget.machineId!,
- )) {
- 'deriving_key' => 'Checking password…',
- 'exchanging' || 'verifying' => 'Verifying the link…',
- _ => 'Connecting…',
- },
+ MachinePickerFormKind.connect => machineLinkProgress(
+ app.machineLinkStage(widget.machineId!),
+ ),
MachinePickerFormKind.delete => 'Deleting…',
_ => 'Saving…',
};
diff --git a/desktop/lib/widgets/web_download_button.dart b/desktop/lib/widgets/web_download_button.dart
index ef57ba51e..61a62684b 100644
--- a/desktop/lib/widgets/web_download_button.dart
+++ b/desktop/lib/widgets/web_download_button.dart
@@ -35,6 +35,17 @@ class WebDownloadButton extends StatelessWidget {
);
static const _text = 'Download app';
+ /// Filled like Share when [prominent], a step brighter under the pointer;
+ /// otherwise bare, with the bar's recessed well under the pointer.
+ static Color backgroundFor({required bool prominent, required bool hovered}) {
+ if (prominent) {
+ return hovered
+ ? grid.AppPalette.accentHover
+ : WorkspaceShareButton.backgroundFor(true);
+ }
+ return hovered ? grid.AppSurface.recessHover : Colors.transparent;
+ }
+
static double widthOf(BuildContext context) =>
workspaceBarTextSizeOf(context, _text).width +
workspaceBarCellSizeOf(context).width * 2;
@@ -48,10 +59,10 @@ class WebDownloadButton extends StatelessWidget {
child: WorkspaceBarControl(
label: 'Download app',
onPressed: () => open(uri),
- builder: (context, emphasized) => ColoredBox(
- color: prominent
- ? WorkspaceShareButton.backgroundFor(true)
- : Colors.transparent,
+ // Hover lifts the fill; the label keeps its weight. Turning bold under
+ // the pointer reflowed the word and read as a glitch, not a response.
+ builder: (context, hovered) => ColoredBox(
+ color: backgroundFor(prominent: prominent, hovered: hovered),
child: SizedBox(
width: widthOf(context),
height: workspaceBarControlHeight(context),
@@ -62,7 +73,7 @@ class WebDownloadButton extends StatelessWidget {
color: prominent
? WorkspaceShareButton.foregroundFor(true)
: grid.AppPalette.textPrimary,
- emphasized: emphasized,
+ emphasized: prominent,
),
),
),
diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dart
index c30e3bfdf..f0f5c3bce 100644
--- a/desktop/lib/ws/ws_conn.dart
+++ b/desktop/lib/ws/ws_conn.dart
@@ -478,6 +478,10 @@ class WsConn {
return;
case 'e2e_welcome':
if (_directObserver) return;
+ // One per session (see `RelaySessionCrypto.handleWelcome`): another once this one is up
+ // is the relay repeating itself — not the machine failing to prove who it is, which is
+ // what refusing the peer below would take it for.
+ if (_ready) return;
final verified = await codec.handleWelcome(payload);
if (_closing || !identical(_codec, codec)) return;
if (verified) {
diff --git a/desktop/test/connect_trusted_test.dart b/desktop/test/connect_trusted_test.dart
new file mode 100644
index 000000000..84e0e21d7
--- /dev/null
+++ b/desktop/test/connect_trusted_test.dart
@@ -0,0 +1,73 @@
+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';
+
+/// Connecting with no password: the machine is dialed now, and the answer is
+/// read off its socket — connected, or refused again as needing a link.
+void main() {
+ late AppNotifier app;
+ late MachineState mac;
+
+ setUp(() {
+ app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+ const machine = Machine(
+ machineId: 'mac',
+ name: 'Mac',
+ authMode: MachineAuthMode.remote,
+ );
+ app.machines.add(machine);
+ mac = app.machineStates['mac'] = MachineState(machine)
+ ..nodeOnline = true
+ ..needsLink = true;
+ });
+
+ tearDown(() => app.dispose());
+
+ void socket(ConnectionStatus status, {required bool needsLink}) {
+ mac
+ ..connectionStatus = status
+ ..needsLink = needsLink;
+ app.notifyListeners();
+ }
+
+ test('a machine that trusts this device connects', () async {
+ final answer = app.connectTrusted('mac');
+ socket(ConnectionStatus.connecting, needsLink: true);
+ socket(ConnectionStatus.connected, needsLink: false);
+
+ expect(await answer, isTrue);
+ });
+
+ test('one that refuses again still wants its password', () async {
+ final answer = app.connectTrusted('mac');
+ socket(ConnectionStatus.connecting, needsLink: true);
+ socket(ConnectionStatus.disconnected, needsLink: true);
+
+ expect(await answer, isFalse);
+ });
+
+ test('the refusal from before this dial is not the answer', () async {
+ final answer = app.connectTrusted(
+ 'mac',
+ timeout: const Duration(milliseconds: 50),
+ );
+ // Still the old refusal: nothing has been dialed yet.
+ socket(ConnectionStatus.disconnected, needsLink: true);
+ var settled = false;
+ answer.then((_) => settled = true);
+ await Future<void>.delayed(Duration.zero);
+ expect(settled, isFalse);
+
+ expect(await answer, isFalse); // the timeout
+ });
+
+ test('an unknown machine is not connected', () async {
+ expect(await app.connectTrusted('nowhere'), isFalse);
+ });
+}
diff --git a/desktop/test/desktop_account_transition_test.dart b/desktop/test/desktop_account_transition_test.dart
index a48b1ed9f..c2f827917 100644
--- a/desktop/test/desktop_account_transition_test.dart
+++ b/desktop/test/desktop_account_transition_test.dart
@@ -46,6 +46,28 @@ class _Api extends ApiClient {
Future<Map<String, dynamic>?> me() async => null;
}
+/// An account desk that records what this window sends it.
+class _DeskApi extends _Api {
+ final ops = <Map<String, dynamic>>[];
+ final _tabs = <Object?>[];
+ var _revision = 0;
+
+ Map<String, dynamic> get _doc => {'revision': _revision, 'tabs': _tabs};
+
+ @override
+ Future<Map<String, dynamic>?> desk() async => _doc;
+
+ @override
+ Future<Map<String, dynamic>?> deskOps(List<Map<String, dynamic>> sent) async {
+ ops.addAll(sent);
+ for (final op in sent) {
+ if (op['op'] == 'seed') _tabs.addAll(op['tabs'] as List);
+ }
+ _revision++;
+ return _doc;
+ }
+}
+
class _Desktop extends AppNotifier {
_Desktop(this.storage, this.loginFixture)
: super(
@@ -310,6 +332,48 @@ void main() {
},
);
+ test(
+ "a tab made signed out reaches the desk on the account's machine id",
+ () async {
+ final app = _Desktop(MemoryStore(), _Login())..signedIn = false;
+ addTearDown(app.dispose);
+ final desk = _DeskApi();
+ app.api = desk;
+ await app.refreshMachines();
+ app.adoptSessionForTest(
+ TerminalSession(
+ machineId: 'computer-local',
+ agentId: 'guest-agent',
+ agentName: 'Guest',
+ engineId: 'codex',
+ send: (_, _) async => true,
+ sendBinary: (_) async => true,
+ )..streamId = 'guest',
+ );
+ app.renameSwarm(app.activeSwarmId, 'Made signed out');
+ await app.flushPaneLayout();
+
+ await app.login();
+ await _settle();
+
+ final seeded = [
+ for (final op in desk.ops)
+ if (op['op'] == 'seed') ...(op['tabs'] as List).cast<Map>(),
+ ];
+ final onDesk = {
+ for (final tab in seeded)
+ for (final pane in (tab['panes'] as List).cast<Map>())
+ pane['machineId'],
+ };
+ expect(onDesk, isNot(contains('computer-local')));
+ expect(onDesk, contains('account-local'));
+ expect(
+ app.allPanes.map((pane) => pane.machineId),
+ everyElement('account-local'),
+ );
+ },
+ );
+
test('failed guest sign-in keeps the local workspace available', () async {
final app = _Desktop(MemoryStore(), _Login()..fail = true)
..signedIn = false;
diff --git a/desktop/test/e2ee/encrypted_down_types_test.dart b/desktop/test/e2ee/encrypted_down_types_test.dart
index 79ff2e323..346fbc61f 100644
--- a/desktop/test/e2ee/encrypted_down_types_test.dart
+++ b/desktop/test/e2ee/encrypted_down_types_test.dart
@@ -43,6 +43,14 @@ void main() {
};
}
+ /// `PLATE_REQUEST` is one type, not a set: `encryptDownFrame` compares it with `===`.
+ String plateRequest(String relay) {
+ final match = RegExp(r"export const PLATE_REQUEST = '([a-z0-9_]+)'")
+ .firstMatch(relay);
+ if (match == null) throw StateError('could not find PLATE_REQUEST');
+ return match[1]!;
+ }
+
late Set<String> core, machineRequests, unwrapped;
setUpAll(() {
core = namesIn(cli('lib/e2ee/core.ts'), 'ENCRYPTED_DOWN_TYPES');
@@ -60,6 +68,7 @@ void main() {
...machineRequests,
...namesIn(frames, 'FLEET_REQUESTS'),
...namesIn(relay, 'PAIR_REQUESTS'),
+ plateRequest(relay),
...namesIn(cli('sharing/protocol.ts'), 'SHARE_REQUEST_TYPES'),
...namesIn(cli('teams/wire.ts'), 'TEAM_REQUEST_TYPES'),
...namesIn(cli('lib/viewerFrames.ts'), 'VIEWER_DOWN_TYPES'),
@@ -75,6 +84,27 @@ void main() {
expect(encryptedDownTypes.difference(unwrapped), isEmpty);
});
+ test('the rule read is the one the machine applies', () {
+ // A new set joined to encryptDownFrame would go unread above: fail until
+ // it is added there too.
+ final rule = cli('lib/e2ee/applicationFrames.ts');
+ final from = rule.indexOf('export const encryptDownFrame');
+ final body = rule.substring(from, rule.indexOf('\nexport ', from + 1));
+ final named = RegExp(r'\b([A-Z][A-Z_]+)\b')
+ .allMatches(body)
+ .map((m) => m[1]);
+ expect(named.toSet(), {
+ 'MACHINE_REQUESTS',
+ 'FLEET_REQUESTS',
+ 'SHARE_REQUEST_TYPES',
+ 'VIEWER_DOWN_TYPES',
+ 'PAIR_REQUESTS',
+ 'PLATE_REQUEST',
+ 'TEAM_REQUEST_TYPES',
+ });
+ expect(body, contains('isEncryptedDownType(type)'));
+ });
+
test('a machine request this client sends is sealed', () {
expect(machineRequests, contains('git_pull_request'));
// Any quoted use outside the list itself counts as sending it.
diff --git a/desktop/test/e2ee/machine_session.dart b/desktop/test/e2ee/machine_session.dart
new file mode 100644
index 000000000..ce01d9990
--- /dev/null
+++ b/desktop/test/e2ee/machine_session.dart
@@ -0,0 +1,161 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:harness/e2ee/bytes.dart';
+import 'package:harness/e2ee/envelope.dart';
+import 'package:harness/e2ee/keys.dart';
+import 'package:harness/e2ee/primitives.dart';
+import 'package:harness/e2ee/terminal_cipher.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+
+const machineId = 'machine-1';
+const streamId = '11111111-1111-4111-8111-111111111111';
+
+/// The machine's end of one E2EE session, as `manager.ts` runs it: `onHello` answers a client's
+/// hello with a signed welcome, then frames go up under the pairwise key (`wrapTarget`,
+/// `wrapRpcReply`), the group key (`wrapUp`) or the binary terminal key (`wrapTerminalBinary`),
+/// and `rotateGroupKey` sends a rekey on the pairwise counter.
+class MachineSession {
+ MachineSession._(this.identity, this.eph, this.webEphPub, this.keys);
+
+ final E2eeIdentity identity;
+ final Ephemeral eph;
+ final Uint8List webEphPub;
+ final SessionKeys keys;
+
+ Uint8List groupKey = Uint8List.fromList(List.filled(32, 7));
+ String epoch = 'e1';
+
+ /// 0 was the welcome.
+ int s2cCounter = 1;
+ int groupCounter = 0;
+ int terminalCounter = 0;
+
+ late final Uint8List terminalS2c = deriveTerminalBinaryKey(keys.s2c);
+ late final Uint8List terminalC2s = deriveTerminalBinaryKey(keys.c2s);
+
+ /// The machine answering [hello] (a client's `e2e_hello` frame).
+ static Future<MachineSession> answer(
+ Map<String, dynamic> hello, {
+ E2eeIdentity? identity,
+ }) async {
+ final payload = hello['payload'] as Map<String, dynamic>;
+ final webEphPub = b64d(payload['ephPub'] as String);
+ final eph = await Ephemeral.generate();
+ return MachineSession._(
+ identity ?? await E2eeIdentity.generate(),
+ eph,
+ webEphPub,
+ sessionKeys(eph, webEphPub, machineId, webEphPub, eph.pub),
+ );
+ }
+
+ /// The `e2e_welcome` payload; [initial] replaces what it seals when given.
+ Future<Map<String, dynamic>> welcome({
+ Map<String, Object?> features = const {'terminalP2p': 1, 'strictDown': 1},
+ Map<String, Object?>? initial,
+ }) async {
+ final sig = await identity.sign(
+ lvCat(['e2e-welcome-v1', machineId, webEphPub, eph.pub]),
+ );
+ final enc = aeadSeal(
+ keys.s2c,
+ 0,
+ utf8Bytes('e2e-welcome'),
+ utf8Bytes(
+ jsonEncode(
+ initial ??
+ {
+ 'groupKey': b64e(groupKey),
+ 'epoch': epoch,
+ 'features': features,
+ },
+ ),
+ ),
+ );
+ return {
+ 'webEphPub': b64e(webEphPub),
+ 'ephPub': b64e(eph.pub),
+ 'sig': b64e(sig),
+ 'enc': b64e(enc),
+ };
+ }
+
+ /// A connection-targeted frame under the pairwise key.
+ Map<String, dynamic> target(
+ String type,
+ Map<String, Object?> payload, {
+ int? n,
+ }) => {
+ 'type': type,
+ 'payload': wrapPayload(
+ keys.s2c,
+ 'p',
+ n ?? s2cCounter++,
+ type,
+ null,
+ payload,
+ ),
+ };
+
+ /// A broadcast frame under the group key.
+ Map<String, dynamic> group(
+ String type,
+ Map<String, Object?> payload, {
+ String? dbSessionId,
+ int? n,
+ }) => {
+ 'type': type,
+ 'dbSessionId': ?dbSessionId,
+ 'payload': wrapPayload(
+ groupKey,
+ 'g',
+ n ?? groupCounter++,
+ type,
+ dbSessionId,
+ payload,
+ epoch: epoch,
+ ),
+ };
+
+ /// `rotateGroupKey`: a new group key and epoch, told to this session on its pairwise counter.
+ Map<String, dynamic> rekey(Uint8List nextKey, String nextEpoch) {
+ groupKey = nextKey;
+ epoch = nextEpoch;
+ groupCounter = 0;
+ final n = s2cCounter++;
+ final enc = aeadSeal(
+ keys.s2c,
+ n,
+ utf8Bytes('e2e-rekey'),
+ utf8Bytes(jsonEncode({'groupKey': b64e(nextKey), 'epoch': nextEpoch})),
+ );
+ return {'enc': b64e(enc), 'n': n};
+ }
+
+ /// Terminal output sealed for the relay (HTRM).
+ Uint8List terminal(String text, {int seq = 0, int? counter}) =>
+ sealTerminalBinary(
+ terminalS2c,
+ counter ?? terminalCounter++,
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.output,
+ streamId: streamId,
+ seq: seq,
+ bytes: utf8Bytes(text),
+ compressed: false,
+ ),
+ )!;
+
+ /// A frame the client sent down, opened; null when it was not sealed to this session.
+ Map<String, dynamic>? openDown(Map<String, dynamic> frame) {
+ final payload = frame['payload'];
+ if (payload is! Map || !isWrapped(payload)) return null;
+ return unwrapPayload(
+ keys.c2s,
+ payload['__e2e'] as Map<String, dynamic>,
+ frame['type'] as String,
+ null,
+ );
+ }
+}
diff --git a/desktop/test/e2ee/relay_session_crypto_test.dart b/desktop/test/e2ee/relay_session_crypto_test.dart
new file mode 100644
index 000000000..afda35624
--- /dev/null
+++ b/desktop/test/e2ee/relay_session_crypto_test.dart
@@ -0,0 +1,575 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness/e2ee/bytes.dart';
+import 'package:harness/e2ee/envelope.dart';
+import 'package:harness/e2ee/keys.dart';
+import 'package:harness/e2ee/primitives.dart';
+import 'package:harness/e2ee/relay_session_crypto.dart';
+import 'package:harness/e2ee/replay_window.dart';
+import 'package:harness/e2ee/terminal_cipher.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/viewer/e2ee_relay_codec.dart';
+import 'package:harness/viewer/viewer_key_store.dart';
+
+import '../support/memory_key_value_store.dart';
+import 'machine_session.dart';
+
+/// The phone's end of a session against the machine's ([MachineSession]): what it lets through,
+/// and — the point of it — what it refuses from a relay that replays, reorders or forges.
+void main() {
+ late E2eeIdentity phone;
+ late E2eeIdentity machineIdentity;
+
+ setUpAll(() async {
+ phone = await E2eeIdentity.generate();
+ machineIdentity = await E2eeIdentity.generate();
+ });
+
+ Future<RelaySessionCrypto> client() => RelaySessionCrypto.start(
+ machineId: machineId,
+ identity: phone,
+ peerPub: machineIdentity.pub,
+ );
+
+ /// A session both ends have agreed.
+ Future<(RelaySessionCrypto, MachineSession)> agreed({
+ Map<String, Object?> features = const {'terminalP2p': 1, 'strictDown': 1},
+ }) async {
+ final session = await client();
+ final machine = await MachineSession.answer(
+ session.helloFrame(),
+ identity: machineIdentity,
+ );
+ expect(
+ await session.handleWelcome(await machine.welcome(features: features)),
+ isTrue,
+ );
+ return (session, machine);
+ }
+
+ group('the hello', () {
+ test('names this phone and is signed by it', () async {
+ final session = await client();
+ final hello = session.helloFrame();
+ expect(hello['type'], 'e2e_hello');
+ final payload = hello['payload'] as Map<String, dynamic>;
+ expect(b64d(payload['identityPub'] as String), phone.pub);
+ expect(
+ await verifySignature(
+ phone.pub,
+ lvCat(['e2e-hello-v1', machineId, b64d(payload['ephPub'] as String)]),
+ b64d(payload['sig'] as String),
+ ),
+ isTrue,
+ );
+ expect(session.ready, isFalse);
+ expect(session.terminalP2pVersion, 0);
+ });
+ });
+
+ group('the welcome', () {
+ test('from the pinned machine makes the session usable', () async {
+ final (session, _) = await agreed();
+ expect(session.ready, isTrue);
+ expect(session.terminalP2pVersion, 1);
+ expect(session.strictDown, isTrue);
+ });
+
+ test('features it does not understand read as none', () async {
+ final (session, _) = await agreed(
+ features: {'terminalP2p': '1', 'strictDown': true},
+ );
+ expect(session.terminalP2pVersion, 0);
+ expect(session.strictDown, isFalse);
+ });
+
+ test('signed by any other machine is refused', () async {
+ final session = await client();
+ final impostor = await MachineSession.answer(session.helloFrame());
+ expect(await session.handleWelcome(await impostor.welcome()), isFalse);
+ expect(session.ready, isFalse);
+ });
+
+ test('with a field missing, mangled or not opening is refused', () async {
+ final session = await client();
+ final machine = await MachineSession.answer(
+ session.helloFrame(),
+ identity: machineIdentity,
+ );
+ final good = await machine.welcome();
+ for (final bad in <Map<String, dynamic>>[
+ {...good}..remove('ephPub'),
+ {...good, 'sig': ''},
+ {...good, 'enc': 7},
+ {...good, 'ephPub': '!!not base64!!'},
+ {...good, 'enc': b64e(List.filled(40, 1))},
+ {...good, 'ephPub': b64e(List.filled(31, 1))},
+ ]) {
+ expect(await session.handleWelcome(bad), isFalse, reason: '$bad');
+ }
+ for (final initial in <Map<String, Object?>>[
+ {'epoch': 'e1'},
+ {'groupKey': b64e(List.filled(32, 1))},
+ {'groupKey': '', 'epoch': 'e1'},
+ {'groupKey': b64e(List.filled(32, 1)), 'epoch': ''},
+ ]) {
+ expect(
+ await session.handleWelcome(await machine.welcome(initial: initial)),
+ isFalse,
+ reason: '$initial',
+ );
+ }
+ expect(session.ready, isFalse);
+ });
+
+ test(
+ 'a signed welcome over a malformed key is refused, not thrown',
+ () async {
+ final session = await client();
+ final hello = session.helloFrame()['payload'] as Map<String, dynamic>;
+ final webEphPub = b64d(hello['ephPub'] as String);
+ final shortKey = List.filled(31, 9);
+ final sig = await machineIdentity.sign(
+ lvCat(['e2e-welcome-v1', machineId, webEphPub, shortKey]),
+ );
+ expect(
+ await session.handleWelcome({
+ 'ephPub': b64e(shortKey),
+ 'sig': b64e(sig),
+ 'enc': b64e(List.filled(40, 1)),
+ }),
+ isFalse,
+ );
+ expect(session.ready, isFalse);
+ },
+ );
+
+ // ⚠️ A welcome is signed, but nothing in it is fresh: the relay can hand the same one back at
+ // any time. Taken twice, it reset the group key to the one it carried, undoing the rekey the
+ // machine sent when it revoked a client — and that client still holds the old key.
+ test('a second one, even a genuine replay, changes nothing', () async {
+ final (session, machine) = await agreed();
+ final welcome = await machine.welcome();
+ final oldKey = Uint8List.fromList(machine.groupKey);
+ expect(
+ session.handleRekey(
+ machine.rekey(Uint8List.fromList(List.filled(32, 9)), 'e2'),
+ ),
+ isTrue,
+ );
+
+ expect(await session.handleWelcome(welcome), isFalse);
+
+ // Still on the rotated key: the machine's next broadcast opens…
+ expect(
+ session.unwrapIncoming(machine.group('text_delta', {'text': 'fresh'})),
+ isNotNull,
+ );
+ // …and one sealed under the revoked key, by whoever still holds it, does not.
+ final forged = {
+ 'type': 'text_delta',
+ 'payload': wrapPayload(oldKey, 'g', 99, 'text_delta', null, {
+ 'text': 'forged',
+ }, epoch: 'e1'),
+ };
+ expect(session.unwrapIncoming(forged), isNull);
+ });
+ });
+
+ group('rekey', () {
+ test('rotates the group key the broadcasts open under', () async {
+ final (session, machine) = await agreed();
+ expect(
+ session.handleRekey(
+ machine.rekey(Uint8List.fromList(List.filled(32, 3)), 'e2'),
+ ),
+ isTrue,
+ );
+ final clear = session.unwrapIncoming(machine.group('done', {'ok': true}));
+ expect(clear!['payload'], {'ok': true});
+ });
+
+ test('before the session is up, or malformed, is refused', () async {
+ final session = await client();
+ expect(session.handleRekey({'n': 1, 'enc': 'x'}), isFalse);
+ final (live, machine) = await agreed();
+ final good = machine.rekey(Uint8List.fromList(List.filled(32, 3)), 'e2');
+ for (final bad in <Map<String, dynamic>>[
+ {'n': '1', 'enc': good['enc']},
+ {'n': good['n'], 'enc': ''},
+ {'n': good['n'], 'enc': '%%%'},
+ {'n': good['n'] + 1, 'enc': good['enc']},
+ {'n': -1, 'enc': good['enc']},
+ ]) {
+ expect(live.handleRekey(bad), isFalse, reason: '$bad');
+ }
+ expect(live.handleRekey(good), isTrue);
+ });
+
+ test('a rekey that opens but says nothing usable is refused', () async {
+ final (session, machine) = await agreed();
+ final n = machine.s2cCounter++;
+ final enc = aeadSeal(
+ machine.keys.s2c,
+ n,
+ utf8Bytes('e2e-rekey'),
+ utf8Bytes(jsonEncode({'groupKey': '', 'epoch': 'e2'})),
+ );
+ expect(session.handleRekey({'n': n, 'enc': b64e(enc)}), isFalse);
+ });
+
+ // ⚠️ The machine seals a rekey on its pairwise counter, so it is replay-checked like any frame
+ // there. Unchecked, an OLD rekey handed back after a newer one rolled the group key back to
+ // one a client revoked in between still holds.
+ test('an old one handed back after a newer one is refused', () async {
+ final (session, machine) = await agreed();
+ final first = machine.rekey(Uint8List.fromList(List.filled(32, 4)), 'e2');
+ final revokedKnows = Uint8List.fromList(machine.groupKey);
+ final second = machine.rekey(
+ Uint8List.fromList(List.filled(32, 5)),
+ 'e3',
+ );
+ expect(session.handleRekey(first), isTrue);
+ expect(session.handleRekey(second), isTrue);
+
+ expect(session.handleRekey(first), isFalse);
+ expect(session.handleRekey(second), isFalse);
+
+ final forged = {
+ 'type': 'text_delta',
+ 'payload': wrapPayload(revokedKnows, 'g', 50, 'text_delta', null, {
+ 'text': 'forged',
+ }, epoch: 'e2'),
+ };
+ expect(session.unwrapIncoming(forged), isNull);
+ expect(
+ session.unwrapIncoming(machine.group('text_delta', {'text': 'real'})),
+ isNotNull,
+ );
+ });
+ });
+
+ group('frames up from the machine', () {
+ test('one never sealed passes as it is', () async {
+ final (session, _) = await agreed();
+ final frame = {
+ 'type': 'node_status',
+ 'payload': {'online': true},
+ };
+ expect(session.unwrapIncoming(frame), same(frame));
+ expect(session.unwrapIncoming({'type': 'x'}), isNotNull);
+ });
+
+ test('a sealed one opens once, in any order, within the window', () async {
+ final (session, machine) = await agreed();
+ final a = machine.target('agents_list_result', {'agents': []});
+ final b = machine.target('agents_list_result', {
+ 'agents': [1],
+ });
+ expect(session.unwrapIncoming(b)!['payload'], {
+ 'agents': [1],
+ });
+ expect(session.unwrapIncoming(a)!['payload'], {'agents': []});
+ // Replayed: both refused.
+ expect(session.unwrapIncoming(a), isNull);
+ expect(session.unwrapIncoming(b), isNull);
+ });
+
+ test('one from before the window is refused', () async {
+ final (session, machine) = await agreed();
+ final stale = machine.target('x', {'n': 1});
+ machine.s2cCounter += e2eeReplayWindowSize + 10;
+ expect(session.unwrapIncoming(machine.target('x', {'n': 2})), isNotNull);
+ expect(session.unwrapIncoming(stale), isNull);
+ });
+
+ test('a sealed one relabelled as another type is refused', () async {
+ final (session, machine) = await agreed();
+ final frame = machine.target('session_get_result', {'text': 'secret'});
+ expect(
+ session.unwrapIncoming({...frame, 'type': 'agents_list_result'}),
+ isNull,
+ );
+ // The genuine one still opens: a refusal spends nothing.
+ expect(session.unwrapIncoming(frame), isNotNull);
+ });
+
+ test('an envelope of the wrong shape is refused, not thrown', () async {
+ final (session, machine) = await agreed();
+ final good = machine.target('x', {'a': 1});
+ final env = (good['payload'] as Map)['__e2e'] as Map<String, dynamic>;
+ for (final bad in <Map<String, dynamic>>[
+ {
+ 'type': 'x',
+ 'payload': {'__e2e': 'not a map'},
+ },
+ {'type': 7, 'payload': good['payload']},
+ {
+ 'type': 'x',
+ 'payload': {
+ '__e2e': {...env, 'n': '1'},
+ },
+ },
+ {
+ 'type': 'x',
+ 'payload': {
+ '__e2e': {...env, 'ct': '%%%'},
+ },
+ },
+ {
+ 'type': 'x',
+ 'payload': {
+ '__e2e': {...env, 'v': '1'},
+ },
+ },
+ {
+ 'type': 'x',
+ 'payload': {
+ '__e2e': {
+ ...env,
+ 'ct': b64e([1, 2]),
+ },
+ },
+ },
+ ]) {
+ expect(session.unwrapIncoming(bad), isNull, reason: '$bad');
+ }
+ });
+
+ test('a sealed one before the welcome is refused', () async {
+ final session = await client();
+ final machine = await MachineSession.answer(session.helloFrame());
+ expect(session.unwrapIncoming(machine.target('x', {})), isNull);
+ expect(session.unwrapIncoming(machine.group('x', {})), isNull);
+ });
+
+ test('a broadcast opens once, for its epoch and its session', () async {
+ final (session, machine) = await agreed();
+ final first = machine.group('user_message', {
+ 'text': 'hi',
+ }, dbSessionId: 's1');
+ final second = machine.group('user_message', {
+ 'text': 'there',
+ }, dbSessionId: 's1');
+ expect(session.unwrapIncoming(first)!['payload'], {'text': 'hi'});
+ expect(session.unwrapIncoming(second)!['payload'], {'text': 'there'});
+ // Replayed, or reordered behind a later one: broadcasts only ever move forward.
+ expect(session.unwrapIncoming(first), isNull);
+ // Moved to another conversation: its AAD says otherwise.
+ final third = machine.group('user_message', {
+ 'text': 'x',
+ }, dbSessionId: 's1');
+ expect(session.unwrapIncoming({...third, 'dbSessionId': 's2'}), isNull);
+ // From an epoch this session is not on.
+ machine.epoch = 'e9';
+ expect(session.unwrapIncoming(machine.group('x', {})), isNull);
+ });
+ });
+
+ group('frames down to the machine', () {
+ test(
+ 'a sealed type goes sealed, on a counter the machine can open',
+ () async {
+ final (session, machine) = await agreed();
+ final one = session.wrapOutgoing({
+ 'type': 'terminal_input',
+ 'payload': {'data': 'ls'},
+ });
+ final two = session.wrapOutgoing({
+ 'type': 'terminal_input',
+ 'payload': {'data': 'pwd'},
+ });
+ expect(machine.openDown(one), {'data': 'ls'});
+ expect(machine.openDown(two), {'data': 'pwd'});
+ expect(
+ ((one['payload'] as Map)['__e2e'] as Map)['n'],
+ lessThan(((two['payload'] as Map)['__e2e'] as Map)['n'] as int),
+ );
+ },
+ );
+
+ test('a type the relay may read goes as it is', () async {
+ final (session, _) = await agreed();
+ final frame = {
+ 'type': 'machine_select',
+ 'payload': {'machineId': 'm'},
+ };
+ expect(session.wrapOutgoing(frame), same(frame));
+ expect(session.wrapOutgoing({'type': 1}), isNotNull);
+ });
+
+ test('before the session is up nothing is sealed', () async {
+ final session = await client();
+ final frame = {'type': 'terminal_input', 'payload': {}};
+ expect(session.wrapOutgoing(frame), same(frame));
+ });
+ });
+
+ group('terminal bytes', () {
+ TerminalBinaryFrame input(String text) => TerminalBinaryFrame(
+ kind: TerminalBinaryKind.input,
+ streamId: streamId,
+ seq: 1,
+ bytes: utf8Bytes(text),
+ compressed: false,
+ );
+
+ test('are sealed only once the session is up', () async {
+ final session = await client();
+ expect(session.encryptTerminal(input('x')), isNull);
+ expect(session.decryptTerminal(Uint8List(40)), isNull);
+ });
+
+ test('go down on their own key and counter', () async {
+ final (session, machine) = await agreed();
+ final first = session.encryptTerminal(input('a'))!;
+ final second = session.encryptTerminal(input('b'))!;
+ final opened1 = openTerminalBinary(machine.terminalC2s, first)!;
+ final opened2 = openTerminalBinary(machine.terminalC2s, second)!;
+ expect(utf8.decode(opened1.frame.bytes), 'a');
+ expect(opened2.counter, opened1.counter + 1);
+ // Not under the JSON frames' key: the two never share a nonce.
+ expect(openTerminalBinary(machine.keys.c2s, first), isNull);
+ });
+
+ test('a frame too big to seal takes no counter', () async {
+ final (session, machine) = await agreed();
+ final huge = TerminalBinaryFrame(
+ kind: TerminalBinaryKind.input,
+ streamId: streamId,
+ seq: 1,
+ bytes: Uint8List(terminalLocalMaxPayloadBytes + 1),
+ compressed: false,
+ );
+ expect(session.encryptTerminal(huge), isNull);
+ final next = session.encryptTerminal(input('after'))!;
+ expect(openTerminalBinary(machine.terminalC2s, next)!.counter, 0);
+ });
+
+ test('come up once each, in any order', () async {
+ final (session, machine) = await agreed();
+ final a = machine.terminal('first');
+ final b = machine.terminal('second');
+ expect(utf8.decode(session.decryptTerminal(b)!.bytes), 'second');
+ expect(utf8.decode(session.decryptTerminal(a)!.bytes), 'first');
+ expect(session.decryptTerminal(a), isNull);
+ expect(session.decryptTerminal(b), isNull);
+ });
+
+ test('a flipped byte anywhere is refused', () async {
+ final (session, machine) = await agreed();
+ final sealed = machine.terminal('secret');
+ for (final at in [0, 4, 5, 7, 12, 17, 20, sealed.length - 1]) {
+ final bad = Uint8List.fromList(sealed)..[at] ^= 0x01;
+ expect(session.decryptTerminal(bad), isNull, reason: 'byte $at');
+ }
+ expect(session.decryptTerminal(sealed), isNotNull);
+ });
+ });
+
+ group('as the relay codec', () {
+ test('branch and pull-request history waits for encryption', () async {
+ final session = await client();
+ final codec = E2eeRelayCodec(session);
+ final request = {
+ 'type': 'git_pull_request',
+ 'payload': {'agentId': 'hn', 'history': true, 'offset': 4},
+ };
+ expect(codec.encodeFrame(request), isNull);
+
+ final machine = await MachineSession.answer(
+ codec.helloFrame(),
+ identity: machineIdentity,
+ );
+ expect(await codec.handleWelcome(await machine.welcome()), isTrue);
+ final sealed = codec.encodeFrame(request)!;
+ expect(isWrapped(sealed['payload']), isTrue);
+ expect(machine.openDown(sealed), request['payload']);
+ });
+
+ test('holds a sealed or strict frame until the session is up', () async {
+ final session = await client();
+ final codec = E2eeRelayCodec(session);
+ expect(codec.helloFrame()['type'], 'e2e_hello');
+ expect(
+ codec.encodeFrame({'type': 'terminal_input', 'payload': {}}),
+ isNull,
+ );
+ expect(codec.encodeFrame({'type': 'dsh_install', 'payload': {}}), isNull);
+ expect(
+ codec.encodeFrame({'type': 'machine_select', 'payload': {}}),
+ isNotNull,
+ );
+ final machine = await MachineSession.answer(
+ codec.helloFrame(),
+ identity: machineIdentity,
+ );
+ // A codec's hello is fixed for its session — the same ephemeral each time it is asked.
+ expect(
+ (codec.helloFrame()['payload'] as Map)['ephPub'],
+ (session.helloFrame()['payload'] as Map)['ephPub'],
+ );
+ expect(await codec.handleWelcome(await machine.welcome()), isTrue);
+ expect(codec.terminalP2pVersion, 1);
+ final sealed = codec.encodeFrame({
+ 'type': 'dsh_install',
+ 'payload': {'url': 'u'},
+ })!;
+ expect(machine.openDown(sealed), {'url': 'u'});
+ expect(
+ codec.handleRekey(
+ machine.rekey(Uint8List.fromList(List.filled(32, 2)), 'e2'),
+ ),
+ isTrue,
+ );
+ expect(codec.decodeFrame(machine.target('x', {'a': 1}))!['payload'], {
+ 'a': 1,
+ });
+ });
+
+ test('turns loopback terminal frames into relay ones and back', () async {
+ final (session, machine) = await agreed();
+ final codec = E2eeRelayCodec(session);
+ final local = encodeTerminalLocal(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.input,
+ streamId: streamId,
+ seq: 3,
+ bytes: utf8Bytes('echo hi'),
+ compressed: false,
+ ),
+ )!;
+ final wire = codec.encodeBinary(local)!;
+ expect(
+ utf8.decode(openTerminalBinary(machine.terminalC2s, wire)!.frame.bytes),
+ 'echo hi',
+ );
+ expect(codec.encodeBinary(Uint8List.fromList([1, 2, 3])), isNull);
+
+ final back = codec.decodeBinary(machine.terminal('hi'))!;
+ expect(utf8.decode(decodeTerminalLocal(back)!.bytes), 'hi');
+ expect(codec.decodeBinary(Uint8List(8)), isNull);
+ });
+
+ test('a machine this phone never linked gets no codec at all', () async {
+ final keys = ViewerKeyStore(storage: MemoryKeyValueStore());
+ final codecs = viewerRelayCodecs(keys);
+ expect(await codecs('never-linked'), isNull);
+ await keys.pin(machineId, machineIdentity.pub);
+ final codec = await codecs(machineId);
+ expect(codec, isA<E2eeRelayCodec>());
+ // Pinned to exactly that machine: its welcome opens the session, another's does not.
+ final machine = await MachineSession.answer(
+ codec!.helloFrame(),
+ identity: machineIdentity,
+ );
+ expect(await codec.handleWelcome(await machine.welcome()), isTrue);
+ final other = await codecs(machineId);
+ final impostor = await MachineSession.answer(other!.helloFrame());
+ expect(await other.handleWelcome(await impostor.welcome()), isFalse);
+ });
+ });
+}
diff --git a/desktop/test/p2p/mobile_parity_test.dart b/desktop/test/p2p/mobile_parity_test.dart
new file mode 100644
index 000000000..1110c53c2
--- /dev/null
+++ b/desktop/test/p2p/mobile_parity_test.dart
@@ -0,0 +1,41 @@
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+
+/// Files the web build carries as copies of the phone's (`../mobile`, a
+/// standalone package by design): desktop path → mobile path.
+///
+/// ⚠️ A fix made to one side only fails nowhere else. That is how the web's
+/// E2EE went months without the phone's one-welcome and rekey-replay fixes.
+/// Here a drift fails until the change is carried across — or, if the two are
+/// meant to differ now, until the file leaves this list on purpose.
+const _copies = {
+ 'lib/web/p2p/terminal_p2p_plugin.dart': 'lib/p2p/terminal_p2p_plugin.dart',
+ 'lib/web/p2p/terminal_p2p_link.dart': 'lib/p2p/terminal_p2p_link.dart',
+ 'lib/web/p2p/terminal_p2p_policy.dart': 'lib/p2p/terminal_p2p_policy.dart',
+ 'lib/ws/terminal_transport_plugin.dart':
+ 'lib/ws/terminal_transport_plugin.dart',
+ 'lib/ws/relay_codec.dart': 'lib/ws/relay_codec.dart',
+ 'lib/e2ee/relay_session_crypto.dart': 'lib/e2ee/relay_session_crypto.dart',
+};
+
+/// The phone's package name is the only difference a copy is allowed.
+String _asDesktop(String mobileSource) =>
+ mobileSource.replaceAll('package:harness_mobile/', 'package:harness/');
+
+void main() {
+ for (final MapEntry(key: desktop, value: mobile) in _copies.entries) {
+ test('$desktop matches the phone\'s $mobile', () {
+ final phone = File('../mobile/$mobile');
+ if (!phone.existsSync()) {
+ throw StateError('${phone.path} missing — run from desktop/ in the monorepo');
+ }
+ expect(
+ File(desktop).readAsStringSync(),
+ _asDesktop(phone.readAsStringSync()),
+ reason: 'carry the change to both copies (or drop the pair from '
+ 'test/p2p/mobile_parity_test.dart if they are meant to differ)',
+ );
+ });
+ }
+}
diff --git a/desktop/test/profile_startup_test.dart b/desktop/test/profile_startup_test.dart
index 4d6c0d391..5e69d2cc7 100644
--- a/desktop/test/profile_startup_test.dart
+++ b/desktop/test/profile_startup_test.dart
@@ -17,6 +17,10 @@ class _Api extends ApiClient {
final profiles = <Completer<Map<String, dynamic>?>>[];
final lists = <Completer<List<Machine>>>[];
+ /// No desk here: these tests are about the profile and the machine list.
+ @override
+ Future<Map<String, dynamic>?> desk() async => null;
+
@override
Future<Map<String, dynamic>?> me() {
final result = Completer<Map<String, dynamic>?>();
diff --git a/desktop/test/support/memory_key_value_store.dart b/desktop/test/support/memory_key_value_store.dart
new file mode 100644
index 000000000..42f6c7784
--- /dev/null
+++ b/desktop/test/support/memory_key_value_store.dart
@@ -0,0 +1,16 @@
+import 'package:harness/core/local_key_value_store.dart';
+
+/// A [LocalKeyValueStore] that keeps everything in [values], for tests that
+/// must not touch `~/.harness` or browser storage.
+class MemoryKeyValueStore implements LocalKeyValueStore {
+ final Map<String, String> values = {};
+
+ @override
+ Future<String?> read(String key) async => values[key];
+
+ @override
+ Future<void> write(String key, String value) async => values[key] = value;
+
+ @override
+ Future<void> delete(String key) async => values.remove(key);
+}
diff --git a/desktop/test/system_notifications_test.dart b/desktop/test/system_notifications_test.dart
index 081e341aa..eee496b35 100644
--- a/desktop/test/system_notifications_test.dart
+++ b/desktop/test/system_notifications_test.dart
@@ -57,6 +57,9 @@ class _Recorder implements SystemNotifier {
@override
bool get supported => isSupported;
+ @override
+ String get deniedAdvice => 'Allow it where the recorder says.';
+
@override
bool get clickOpensAgent => true;
@@ -728,7 +731,13 @@ void main() {
await pump(tester, system);
await tester.tap(find.byKey(const Key('settings-desktop-notifications')));
await tester.pumpAndSettle();
- expect(find.textContaining('System Settings'), findsOneWidget);
+ // The platform's own advice: System Settings on a Mac, the site's
+ // settings in a browser.
+ expect(
+ find.textContaining('Allow it where the recorder says.'),
+ findsOneWidget,
+ );
+ expect(MacSystemNotifier().deniedAdvice, contains('System Settings'));
});
testWidgets('no row where there is no notifier to switch', (tester) async {
diff --git a/desktop/test/viewer/removed_machines_test.dart b/desktop/test/viewer/removed_machines_test.dart
new file mode 100644
index 000000000..b61617fe0
--- /dev/null
+++ b/desktop/test/viewer/removed_machines_test.dart
@@ -0,0 +1,106 @@
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/e2ee/bytes.dart';
+import 'package:harness/viewer/device_log.dart';
+import 'package:harness/viewer/removed_machines.dart';
+
+String _key(int n) => b64e(Uint8List(32)..fillRange(0, 32, n));
+
+const _old = '3ebf380400004000800000000000000a';
+const _mac = '6674db5700004000800000000000000b';
+
+Map<String, Object?> _entry(
+ int seq,
+ String op,
+ String kind,
+ int key,
+ String machineId,
+) => DevLogEntry(
+ v: devLogVersion,
+ acct: 'acct',
+ seq: seq,
+ prev: devLogZeroHash,
+ op: op,
+ pub: _key(key),
+ kind: kind,
+ machineId: machineId,
+ label: 'MacBookPro2021.local',
+ at: 1,
+ signer: _key(key),
+ sig: b64e(Uint8List(64)),
+).toJson();
+
+Map<String, Object?> _stored({
+ required List<Map<String, Object?>> recent,
+ Map<String, DevLogMember> active = const {},
+ List<Map<String, Object?>> loose = const [],
+}) => {
+ 'state': DevLogState(
+ acct: 'acct',
+ head: DevLogHead(recent.length, devLogZeroHash),
+ hashes: const [],
+ active: active,
+ removed: const [],
+ ).toJson(),
+ 'recent': recent,
+ 'looseRemoved': loose,
+};
+
+void main() {
+ test('a machine whose key was removed, with its latest removal', () {
+ final removed = removedMachinesOf(
+ _stored(
+ recent: [
+ _entry(1, 'add', 'machine', 1, _old),
+ _entry(2, 'add', 'machine', 2, _mac),
+ _entry(3, 'remove', 'machine', 1, _old),
+ _entry(4, 'remove', 'machine', 2, _mac),
+ _entry(5, 'remove', 'viewer', 3, ''),
+ ],
+ ),
+ );
+
+ expect(removed, {_old: 3, _mac: 4});
+ });
+
+ test('one signed in again under a new key is not removed', () {
+ final removed = removedMachinesOf(
+ _stored(
+ recent: [
+ _entry(1, 'add', 'machine', 1, _mac),
+ _entry(2, 'remove', 'machine', 1, _mac),
+ _entry(3, 'add', 'machine', 2, _mac),
+ ],
+ active: {
+ _key(2): DevLogMember(
+ pub: _key(2),
+ kind: 'machine',
+ machineId: _mac,
+ label: 'MacBookPro2021.local',
+ addedAt: 1,
+ seq: 3,
+ ),
+ },
+ ),
+ );
+
+ expect(removed, isEmpty);
+ });
+
+ test('a removal made while the log was frozen counts too', () {
+ final removed = removedMachinesOf(
+ _stored(
+ recent: const [],
+ loose: [_entry(7, 'remove', 'machine', 1, _mac)],
+ ),
+ );
+
+ expect(removed, {_mac: 7});
+ });
+
+ test('no log yet: nothing removed', () {
+ expect(removedMachinesOf(null), isEmpty);
+ expect(removedMachinesOf({'recent': []}), isEmpty);
+ });
+}
diff --git a/desktop/test/web/browser_system_notifier_test.dart b/desktop/test/web/browser_system_notifier_test.dart
new file mode 100644
index 000000000..337da4334
--- /dev/null
+++ b/desktop/test/web/browser_system_notifier_test.dart
@@ -0,0 +1,162 @@
+@TestOn('browser')
+library;
+
+import 'dart:js_interop';
+import 'dart:js_interop_unsafe';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/notify/system_notifications.dart';
+import 'package:harness/web/notify/browser_system_notifier.dart';
+
+/// Headless Chrome will not grant notifications, so the page's `Notification`
+/// is swapped for a fake that records what the notifier asked of it.
+void _installFakeNotification({
+ required String permission,
+ bool throws = false,
+}) {
+ globalContext.callMethod<JSAny?>(
+ 'eval'.toJS,
+ '''
+ window.__realNotification ??= window.Notification;
+ window.__shown = [];
+ window.__permission = '$permission';
+ window.Notification = class {
+ constructor(title, options) {
+ if ($throws) throw new TypeError('Illegal constructor');
+ this.title = title;
+ this.options = options;
+ this.closed = false;
+ window.__shown.push(this);
+ }
+ close() { this.closed = true; }
+ static get permission() { return window.__permission; }
+ static requestPermission() {
+ window.__permission = 'granted';
+ return Promise.resolve('granted');
+ }
+ };
+ '''
+ .toJS,
+ );
+}
+
+JSArray<JSObject> get _shown => globalContext['__shown'] as JSArray<JSObject>;
+
+JSObject _shownAt(int index) => _shown.toDart[index];
+
+String _string(JSObject object, String path) {
+ JSObject target = object;
+ final parts = path.split('.');
+ for (final part in parts.take(parts.length - 1)) {
+ target = target[part] as JSObject;
+ }
+ return (target[parts.last] as JSString).toDart;
+}
+
+bool _closed(JSObject notification) =>
+ (notification['closed'] as JSBoolean).toDart;
+
+void _click(JSObject notification) =>
+ (notification['onclick'] as JSFunction).callAsFunction(
+ notification,
+ JSObject(),
+ );
+
+Future<NotificationPermission> _show(
+ BrowserSystemNotifier notifier, {
+ String id = 'harness-agent:m1/a1',
+ String title = 'GroupMe',
+ String body = 'is waiting for you',
+}) => notifier.show(
+ id: id,
+ title: title,
+ body: body,
+ machineId: 'm1',
+ agentId: 'a1',
+);
+
+void main() {
+ tearDown(() {
+ globalContext.callMethod<JSAny?>(
+ 'eval'.toJS,
+ 'if (window.__realNotification) window.Notification = window.__realNotification;'
+ .toJS,
+ );
+ });
+
+ test('the browser build posts through the browser', () {
+ expect(platformSystemNotifier(), isA<BrowserSystemNotifier>());
+ final notifier = BrowserSystemNotifier();
+ expect(notifier.supported, isTrue);
+ expect(notifier.clickOpensAgent, isTrue);
+ expect(notifier.deniedAdvice, contains('site settings'));
+ });
+
+ test('asks once when nobody has, and reads an answer already given', () async {
+ _installFakeNotification(permission: 'default');
+ expect(
+ await BrowserSystemNotifier().authorize(),
+ NotificationPermission.granted,
+ );
+
+ _installFakeNotification(permission: 'denied');
+ expect(
+ await BrowserSystemNotifier().authorize(),
+ NotificationPermission.denied,
+ );
+ });
+
+ test('posts nothing without permission', () async {
+ _installFakeNotification(permission: 'denied');
+
+ expect(await _show(BrowserSystemNotifier()), NotificationPermission.denied);
+ expect(_shown.length, 0);
+ });
+
+ test('one per agent: the next replaces the last', () async {
+ _installFakeNotification(permission: 'granted');
+ final notifier = BrowserSystemNotifier();
+
+ expect(await _show(notifier, body: 'finished'), NotificationPermission.granted);
+ await _show(notifier, body: 'is waiting for you');
+
+ expect(_shown.length, 2);
+ expect(_closed(_shownAt(0)), isTrue);
+ expect(_closed(_shownAt(1)), isFalse);
+ expect(_string(_shownAt(1), 'title'), 'GroupMe');
+ expect(_string(_shownAt(1), 'options.body'), 'is waiting for you');
+ expect(_string(_shownAt(1), 'options.tag'), 'harness-agent:m1/a1');
+ });
+
+ test('a click opens its agent and closes the notification', () async {
+ _installFakeNotification(permission: 'granted');
+ final notifier = BrowserSystemNotifier();
+ final opened = <String>[];
+ notifier.onTap = (machineId, agentId) => opened.add('$machineId/$agentId');
+
+ await _show(notifier);
+ _click(_shownAt(0));
+
+ expect(opened, ['m1/a1']);
+ expect(_closed(_shownAt(0)), isTrue);
+ });
+
+ test('withdraw takes it down once the agent is seen', () async {
+ _installFakeNotification(permission: 'granted');
+ final notifier = BrowserSystemNotifier();
+
+ await _show(notifier);
+ await notifier.withdraw('harness-agent:m1/a1');
+
+ expect(_closed(_shownAt(0)), isTrue);
+ });
+
+ test("a phone's browser, which only posts from a service worker", () async {
+ _installFakeNotification(permission: 'granted', throws: true);
+
+ expect(
+ await _show(BrowserSystemNotifier()),
+ NotificationPermission.unavailable,
+ );
+ });
+}
diff --git a/desktop/test/web/browser_workspace_test.dart b/desktop/test/web/browser_workspace_test.dart
index 4c8baa5e7..97560a497 100644
--- a/desktop/test/web/browser_workspace_test.dart
+++ b/desktop/test/web/browser_workspace_test.dart
@@ -17,6 +17,7 @@ import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/app_state.dart';
import 'package:harness/state/grid_pictures.dart';
import 'package:harness/terminal/terminal_font_store.dart';
+import 'package:harness/web/shell/web_chrome.dart';
import 'package:harness/widgets/web_download_button.dart';
import 'package:harness/widgets/swarm_switcher.dart';
import 'package:web/web.dart' as web;
@@ -54,7 +55,11 @@ MachineState _startupMachine(
return state;
}
-Future<void> _mountStartup(WidgetTester tester, _StartupApp app) async {
+Future<void> _mountStartup(
+ WidgetTester tester,
+ _StartupApp app, {
+ bool web = false,
+}) async {
app.currentUser = const CurrentUserProfile(email: '[email protected]');
final selected = app.selectedMachineId;
app.newSwarm(newTabPage: true);
@@ -65,7 +70,10 @@ Future<void> _mountStartup(WidgetTester tester, _StartupApp app) async {
await tester.pumpWidget(
MaterialApp(
theme: grid.buildAppTheme(brightness: Brightness.dark),
- home: SwarmScreen(notifier: app),
+ home: SwarmScreen(
+ notifier: app,
+ chrome: web ? webWorkspaceChrome(app) : null,
+ ),
),
);
await tester.pump(const Duration(milliseconds: 200));
@@ -151,6 +159,47 @@ void main() {
});
}
+ group('a browser with no computer connected', () {
+ Future<void> settle(WidgetTester tester, _StartupApp app) async {
+ app.inventoryLoaded = true;
+ app.notifyListeners();
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pump();
+ }
+
+ Future<void> unmount(WidgetTester tester, _StartupApp app) async {
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox.shrink());
+ app.dispose();
+ }
+
+ testWidgets('says how to connect one, not a search box', (tester) async {
+ final app = _StartupApp();
+ await _mountStartup(tester, app, web: true);
+ await settle(tester, app);
+
+ expect(find.byType(SwarmSearchResults), findsNothing);
+ expect(find.text('Connect a computer'), findsOneWidget);
+ expect(find.text('Download app'), findsWidgets);
+ expect(find.text('harness login'), findsOneWidget);
+ await unmount(tester, app);
+ });
+
+ testWidgets('one waiting to be linked connects from the same page', (
+ tester,
+ ) async {
+ final app = _StartupApp();
+ _startupMachine(app, 'server', needsLink: true);
+ await _mountStartup(tester, app, web: true);
+ await settle(tester, app);
+
+ expect(find.byType(SwarmSearchResults), findsNothing);
+ expect(find.text('Connect your computer'), findsOneWidget);
+ expect(find.widgetWithText(FilledButton, 'Connect'), findsOneWidget);
+ await unmount(tester, app);
+ });
+ });
+
testWidgets('first visit offers machines once after discovery is complete', (
tester,
) async {
diff --git a/desktop/test/web/web_download_button_test.dart b/desktop/test/web/web_download_button_test.dart
index 220391e45..b8c7256f1 100644
--- a/desktop/test/web/web_download_button_test.dart
+++ b/desktop/test/web/web_download_button_test.dart
@@ -1,6 +1,7 @@
@TestOn('browser')
library;
+import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/widgets/web_download_button.dart';
@@ -56,4 +57,55 @@ void main() {
expect(fill(), WorkspaceShareButton.backgroundFor(true));
expect(ink(), WorkspaceShareButton.foregroundFor(true));
});
+
+ for (final prominent in [true, false]) {
+ testWidgets(
+ 'hover lifts the ${prominent ? 'fill' : 'well'}, never the weight',
+ (tester) async {
+ Color fill() => tester
+ .widget<ColoredBox>(
+ find.descendant(
+ of: find.byType(WebDownloadButton),
+ matching: find.byType(ColoredBox),
+ ),
+ )
+ .color;
+ FontWeight? weight() =>
+ tester.widget<Text>(find.text('Download app')).style?.fontWeight;
+
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Center(child: WebDownloadButton(prominent: prominent)),
+ ),
+ );
+ final resting = weight();
+ expect(resting, prominent ? FontWeight.bold : FontWeight.normal);
+ expect(
+ fill(),
+ WebDownloadButton.backgroundFor(prominent: prominent, hovered: false),
+ );
+
+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await mouse.addPointer(location: Offset.zero);
+ addTearDown(mouse.removePointer);
+ await mouse.moveTo(tester.getCenter(find.byType(WebDownloadButton)));
+ await tester.pump();
+
+ expect(
+ fill(),
+ WebDownloadButton.backgroundFor(prominent: prominent, hovered: true),
+ );
+ expect(
+ fill(),
+ isNot(
+ WebDownloadButton.backgroundFor(
+ prominent: prominent,
+ hovered: false,
+ ),
+ ),
+ );
+ expect(weight(), resting);
+ },
+ );
+ }
}
diff --git a/desktop/test/web_first_machine_test.dart b/desktop/test/web_first_machine_test.dart
new file mode 100644
index 000000000..4af6ecb30
--- /dev/null
+++ b/desktop/test/web_first_machine_test.dart
@@ -0,0 +1,305 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.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_icons.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/web/onboarding/web_first_machine.dart';
+import 'package:harness/web/onboarding/web_your_computers.dart';
+import 'package:harness/widgets/machine_picker_form.dart';
+import 'package:harness/widgets/link_another_machine_dialog.dart'
+ show kLinkServerInstallCommand, kLinkServerLoginCommand;
+import 'package:harness/widgets/web_download_button.dart';
+
+/// A password link under way, at its first stage.
+class _Linking extends AppNotifier {
+ _Linking()
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+
+ @override
+ Future<String?>? pendingMachineLink(String machineId) =>
+ Completer<String?>().future;
+
+ @override
+ String? machineLinkStage(String machineId) => 'deriving_key';
+}
+
+/// Counts the quiet machine-list reads the page makes while it waits.
+class _Watching extends AppNotifier {
+ _Watching()
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+
+ var reads = 0;
+
+ @override
+ Future<void> rereadMachines() async => reads++;
+}
+
+/// Dialing with no password: [trusted] says how the computer answers.
+class _Dialing extends AppNotifier {
+ _Dialing({required this.trusted})
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+
+ final bool trusted;
+ final dialed = <String>[];
+
+ @override
+ Future<bool> connectTrusted(String machineId, {Duration? timeout}) async {
+ dialed.add(machineId);
+ return trusted;
+ }
+}
+
+void main() {
+ late AppNotifier app;
+ late List<Uri> opened;
+
+ setUp(() {
+ app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ )..currentUser = const CurrentUserProfile(email: '[email protected]');
+ opened = [];
+ });
+
+ tearDown(() => app.dispose());
+
+ Future<void> mount(WidgetTester tester, {double width = 900}) async {
+ tester.view.physicalSize = Size(width, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SingleChildScrollView(
+ child: WebFirstMachine(
+ app: app,
+ openPage: (uri) async {
+ opened.add(uri);
+ return true;
+ },
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ testWidgets('names the account to sign in with, both ways in', (
+ tester,
+ ) async {
+ await mount(tester);
+
+ expect(find.text('Connect a computer'), findsOneWidget);
+ expect(find.textContaining('[email protected]'), findsNWidgets(2));
+ expect(find.text(kLinkServerInstallCommand), findsOneWidget);
+ expect(find.text(kLinkServerLoginCommand), findsOneWidget);
+ expect(find.text('Waiting for your computer…'), findsOneWidget);
+ });
+
+ testWidgets('Download app opens the download page', (tester) async {
+ await mount(tester);
+
+ await tester.tap(find.text('Download app'));
+
+ expect(opened, [WebDownloadButton.uri]);
+ });
+
+ testWidgets('a command copies to the clipboard', (tester) async {
+ final copied = <String>[];
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (call) async {
+ if (call.method == 'Clipboard.setData') {
+ copied.add((call.arguments as Map)['text'] as String);
+ }
+ return null;
+ },
+ );
+
+ await mount(tester);
+ // The command itself is selectable text; the row's copy mark takes the tap.
+ await tester.tap(find.byIcon(AppIcons.copy).at(1));
+ await tester.pump();
+
+ expect(copied, [kLinkServerLoginCommand]);
+ await tester.pump(const Duration(seconds: 3));
+ });
+
+ void addWaitingComputer(AppNotifier on) {
+ const machine = Machine(
+ machineId: 'mac',
+ name: 'MacBookPro2021.local',
+ authMode: MachineAuthMode.remote,
+ );
+ on.machines.add(machine);
+ on.machineStates['mac'] = MachineState(machine)
+ ..nodeOnline = true
+ ..needsLink = true;
+ }
+
+ testWidgets('a computer that trusts this browser connects with a click', (
+ tester,
+ ) async {
+ app.dispose();
+ app = _Dialing(trusted: true); // tearDown disposes it
+ addWaitingComputer(app);
+ await mount(tester);
+
+ expect(find.text('Connect your computer'), findsOneWidget);
+ expect(find.text('Or set up another computer'), findsOneWidget);
+ await tester.tap(find.widgetWithText(FilledButton, 'Connect'));
+ await tester.pump();
+
+ expect((app as _Dialing).dialed, ['mac']);
+ expect(find.byType(MachinePickerForm), findsNothing);
+ });
+
+ testWidgets('one that does not answer says so and offers another try', (
+ tester,
+ ) async {
+ app.dispose();
+ app = _Dialing(trusted: false);
+ addWaitingComputer(app);
+ await mount(tester);
+
+ await tester.tap(find.widgetWithText(FilledButton, 'Connect'));
+ await tester.pump();
+
+ expect(find.byType(MachinePickerForm), findsNothing, reason: 'no password');
+ expect(find.textContaining("Couldn't connect"), findsOneWidget);
+ await tester.tap(find.widgetWithText(FilledButton, 'Try again'));
+ await tester.pump();
+ expect((app as _Dialing).dialed, ['mac', 'mac']);
+ });
+
+ testWidgets('keeps asking for the machine list while it waits', (
+ tester,
+ ) async {
+ app.dispose();
+ app = _Watching();
+ await mount(tester);
+
+ await tester.pump(WebFirstMachine.watchEvery * 3);
+
+ expect((app as _Watching).reads, 3);
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pump(WebFirstMachine.watchEvery * 2);
+ expect((app as _Watching).reads, 3, reason: 'stops with the page');
+ });
+
+ void addComputer(String id, {bool online = false}) {
+ final machine = Machine(
+ machineId: id,
+ name: 'MacBookPro2021.local',
+ authMode: MachineAuthMode.remote,
+ );
+ app.machines.add(machine);
+ app.machineStates[id] = MachineState(machine)
+ ..nodeOnline = online
+ ..needsLink = online;
+ }
+
+ testWidgets('a computer taken out of the account says to sign in on it', (
+ tester,
+ ) async {
+ addComputer('mac');
+ app.removedMachines = {'mac': 23};
+ await mount(tester);
+
+ expect(find.textContaining('Removed from your account'), findsOneWidget);
+ expect(find.textContaining('Offline'), findsNothing);
+ expect(find.widgetWithText(FilledButton, 'Connect'), findsNothing);
+ });
+
+ testWidgets('a computer set up again shows once, as it is now', (
+ tester,
+ ) async {
+ addComputer('before');
+ addComputer('now', online: true);
+ app.removedMachines = {'before': 20};
+ await mount(tester);
+
+ expect(find.text('MacBookPro2021.local'), findsOneWidget);
+ expect(find.widgetWithText(FilledButton, 'Connect'), findsOneWidget);
+ });
+
+ test('of removed ones sharing a name, only the latest removal is kept', () {
+ addComputer('yesterday');
+ addComputer('today');
+ final listed = WebYourComputers.newestOfEachName(
+ app.machineStates.values.toList(),
+ {'yesterday': 20, 'today': 23},
+ );
+
+ expect([for (final s in listed) s.machine.machineId], ['today']);
+ });
+
+ testWidgets('an offline computer says what to do on it', (tester) async {
+ const machine = Machine(
+ machineId: 'mac',
+ name: 'MacBookPro2021.local',
+ authMode: MachineAuthMode.remote,
+ );
+ app.machines.add(machine);
+ app.machineStates['mac'] = MachineState(machine)..nodeOnline = false;
+ await mount(tester);
+
+ expect(find.textContaining('Offline'), findsOneWidget);
+ expect(find.widgetWithText(FilledButton, 'Connect'), findsNothing);
+ });
+
+ testWidgets('a link in progress reads the same in the row as in the form', (
+ tester,
+ ) async {
+ final linking = _Linking();
+ const machine = Machine(
+ machineId: 'mac',
+ name: 'MacBookPro2021.local',
+ authMode: MachineAuthMode.remote,
+ );
+ linking.machines.add(machine);
+ final state = linking.machineStates['mac'] = MachineState(machine)
+ ..nodeOnline = true
+ ..needsLink = true;
+
+ expect(
+ computerLinkState(linking, state, failed: true),
+ ComputerLinkState.linking,
+ );
+ app.dispose();
+ app = linking; // tearDown disposes it
+ await mount(tester);
+
+ expect(find.text('Checking password…'), findsOneWidget);
+ expect(find.widgetWithText(FilledButton, 'Connect'), findsNothing);
+ });
+
+ testWidgets('stacks the two ways in on a narrow window', (tester) async {
+ await mount(tester, width: 420);
+
+ expect(tester.takeException(), isNull);
+ final app = tester.getTopLeft(find.text('Desktop app'));
+ final cli = tester.getTopLeft(find.text('Command line'));
+ expect(cli.dy, greaterThan(app.dy));
+ });
+}
diff --git a/desktop/test/workspace_account_lifecycle_test.dart b/desktop/test/workspace_account_lifecycle_test.dart
index 465a440e8..1418b79b6 100644
--- a/desktop/test/workspace_account_lifecycle_test.dart
+++ b/desktop/test/workspace_account_lifecycle_test.dart
@@ -263,6 +263,99 @@ void main() {
}
}
+ group('a browser shared by two accounts', () {
+ String layout({String? owner}) => jsonEncode({
+ 'version': 1,
+ 'owner': ?owner,
+ 'activeId': 'theirs',
+ 'swarms': [
+ {
+ 'id': 'theirs',
+ 'name': 'GroupMe',
+ 'panes': [
+ {'machineId': 'their-mac', 'agentId': 'their-agent'},
+ ],
+ },
+ ],
+ 'monitorHarnesses': [
+ ['their-mac', 'their-agent'],
+ ],
+ });
+
+ WorkspaceAccountFixture signedInAs(
+ String account, {
+ required String saved,
+ }) {
+ final app = WorkspaceAccountFixture(
+ MemoryStore()..values['swarm_layout_v1'] = saved,
+ WorkspaceAccountLogin(),
+ );
+ app.currentUser = CurrentUserProfile.fromMe({
+ 'user': {'id': account, 'email': '[email protected]'},
+ });
+ return app;
+ }
+
+ test('another account\'s tabs and history do not open', () async {
+ final app = signedInAs('new-account', saved: layout(owner: 'old-account'));
+ addTearDown(app.dispose);
+
+ await app.restorePaneLayoutForTest();
+
+ expect(app.swarms.map((s) => s.name), isNot(contains('GroupMe')));
+ expect(app.allPanes, isEmpty);
+ expect(app.hasOpenedHarness('their-mac', 'their-agent'), isFalse);
+ });
+
+ test('the same account gets its tabs back', () async {
+ final app = signedInAs('old-account', saved: layout(owner: 'old-account'));
+ addTearDown(app.dispose);
+
+ await app.restorePaneLayoutForTest();
+
+ expect(app.swarms.map((s) => s.name), contains('GroupMe'));
+ expect(app.hasOpenedHarness('their-mac', 'their-agent'), isTrue);
+ });
+
+ test('a layout saved before owners were recorded still opens', () async {
+ final app = signedInAs('any-account', saved: layout());
+ addTearDown(app.dispose);
+
+ await app.restorePaneLayoutForTest();
+
+ expect(app.swarms.map((s) => s.name), contains('GroupMe'));
+ });
+
+ test('a saved layout names the account it belongs to', () async {
+ final storage = MemoryStore();
+ final app = WorkspaceAccountFixture(storage, WorkspaceAccountLogin());
+ addTearDown(app.dispose);
+ app.currentUser = CurrentUserProfile.fromMe({
+ 'user': {'id': 'new-account', 'email': '[email protected]'},
+ });
+
+ await arrangeAccountWorkspace(app);
+
+ final saved = jsonDecode(storage.values['swarm_layout_v1']!) as Map;
+ expect(saved['owner'], 'new-account');
+ });
+
+ test('signing in finds out who it is before restoring', () async {
+ final storage = MemoryStore()
+ ..values['swarm_layout_v1'] = layout(owner: 'old-account');
+ final app = WorkspaceAccountFixture(storage, WorkspaceAccountLogin());
+ addTearDown(app.dispose);
+ await app.logout();
+
+ // The fixture's backend answers `fixture-account`.
+ await app.login();
+
+ expect(app.currentUser?.id, 'fixture-account');
+ expect(app.swarms.map((s) => s.name), isNot(contains('GroupMe')));
+ expect(app.hasOpenedHarness('their-mac', 'their-agent'), isFalse);
+ });
+ });
+
for (final cancel in [false, true]) {
test(
'sign-in ${cancel ? 'can be cancelled while waiting for' : 'waits for'} expired terminal cleanup',
diff --git a/desktop/test/workspace_first_connection_test.dart b/desktop/test/workspace_first_connection_test.dart
new file mode 100644
index 000000000..52b4428d8
--- /dev/null
+++ b/desktop/test/workspace_first_connection_test.dart
@@ -0,0 +1,119 @@
+import 'package:flutter/material.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/screens/swarm_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/workspace_chrome.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+
+class _App extends AppNotifier {
+ _App() : super(config: AppConfig.dev, authSession: AuthSession(), configStore: null);
+
+ bool loaded = false;
+ @override
+ bool get machineInventoryLoaded => loaded;
+}
+
+const _connectPage = Key('connect-page');
+
+/// A host with a connect page (the browser's) shows it over the workspace
+/// while no computer is connected, and never opens the machine picker unasked.
+void main() {
+ Future<_App> mount(
+ WidgetTester tester, {
+ MachineState Function(_App app)? machine,
+ }) async {
+ final app = _App();
+ app.currentUser = const CurrentUserProfile(email: '[email protected]');
+ machine?.call(app);
+ app.newSwarm(newTabPage: true);
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ chrome: WorkspaceChrome(
+ leadingWidth: (_) => 0,
+ leading: (_, _) => const SizedBox(),
+ firstMachine: (_) => const SizedBox(key: _connectPage),
+ ),
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ app.loaded = true;
+ app.notifyListeners();
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pump();
+ return app;
+ }
+
+ MachineState Function(_App) computer({
+ bool needsLink = false,
+ bool? online = true,
+ ConnectionStatus status = ConnectionStatus.disconnected,
+ }) => (app) {
+ const machine = Machine(
+ machineId: 'mac',
+ name: 'Mac',
+ authMode: MachineAuthMode.remote,
+ );
+ app.machines.add(machine);
+ return app.machineStates['mac'] = MachineState(machine)
+ ..needsLink = needsLink
+ ..nodeOnline = online
+ ..connectionStatus = status;
+ };
+
+ Future<void> unmount(WidgetTester tester, _App app) async {
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox.shrink());
+ app.dispose();
+ }
+
+ testWidgets('no computer at all: the connect page, no picker', (
+ tester,
+ ) async {
+ final app = await mount(tester);
+
+ expect(find.byKey(_connectPage), findsOneWidget);
+ expect(find.byType(SwarmSearchResults), findsNothing);
+ await unmount(tester, app);
+ });
+
+ testWidgets('one waiting to be linked: the connect page, no picker', (
+ tester,
+ ) async {
+ final app = await mount(tester, machine: computer(needsLink: true));
+
+ expect(find.byKey(_connectPage), findsOneWidget);
+ expect(find.byType(SwarmSearchResults), findsNothing);
+ await unmount(tester, app);
+ });
+
+ testWidgets('one coming online: no page flashes over it', (tester) async {
+ final app = await mount(
+ tester,
+ machine: computer(status: ConnectionStatus.connecting),
+ );
+
+ expect(find.byKey(_connectPage), findsNothing);
+ await unmount(tester, app);
+ });
+
+ testWidgets('one connected: the workspace itself', (tester) async {
+ final app = await mount(
+ tester,
+ machine: computer(status: ConnectionStatus.connected),
+ );
+
+ expect(find.byKey(_connectPage), findsNothing);
+ await unmount(tester, app);
+ });
+}
diff --git a/scripts/record-ci-validation.py b/scripts/record-ci-validation.py
index f74f16343..bc8842297 100644
--- a/scripts/record-ci-validation.py
+++ b/scripts/record-ci-validation.py
@@ -34,9 +34,12 @@ SOURCE_INPUTS = {
"process": (".github/", "scripts/", "desktop/scripts/", ".gitattributes", ".gitignore", ".gitmodules", "Makefile"),
# VM tests also read CLI protocol definitions, shared layout fixtures,
# daemon metadata and store catalog/artwork, including docs/images posters,
- # and the Hub's publication rules that desktop/lib/community/hub_contract.dart mirrors.
+ # the Hub's publication rules that desktop/lib/community/hub_contract.dart mirrors, and the
+ # phone's P2P/E2EE sources the web's copies are checked against (test/p2p/mobile_parity_test.dart).
"desktop": (".github/", "scripts/", "desktop/", "cli/", "tests/", "daemons/", "store/", "docs/images/",
"mobile/pubspec.lock", "backend/src/lib/communityContract.ts",
+ "mobile/lib/p2p/terminal_p2p_plugin.dart", "mobile/lib/p2p/terminal_p2p_link.dart", "mobile/lib/p2p/terminal_p2p_policy.dart",
+ "mobile/lib/ws/terminal_transport_plugin.dart", "mobile/lib/ws/relay_codec.dart", "mobile/lib/e2ee/relay_session_crypto.dart",
".gitattributes", ".gitignore", ".gitmodules", "Makefile"),
}
CHECKOUT_STEP = "Verify declared source checkout"
diff --git a/website/src/app/hub/community.module.css b/website/src/app/hub/community.module.css
index 89f2fd2a3..a81d2007d 100644
--- a/website/src/app/hub/community.module.css
+++ b/website/src/app/hub/community.module.css
@@ -5,17 +5,30 @@
.page button:disabled{opacity:.45;cursor:wait}
.wrap{width:84%;max-width:1712px;margin:0 auto}
.bar{display:flex;align-items:center;gap:26px;min-height:80px;padding:22px 0}
-.brand{font-weight:600;font-size:25px;letter-spacing:-1px;margin-right:auto}
+.brand{font-weight:600;font-size:25px;letter-spacing:-1px;margin-right:22px}
.hubWord{font-weight:400;color:#999;letter-spacing:-.7px}
.feedIntro{margin-bottom:40px;color:#777}.feedIntro h1{font-size:28px;font-weight:400;color:#242424;margin-bottom:8px}
.cardSocial{display:flex;gap:18px;margin-top:12px;color:#888;font-size:12px}.cardSocial button,.cardSocial a{display:inline-flex;align-items:center;gap:6px}.cardSocial svg{height:14px;width:14px}
.creator{font-style:normal;font-size:10px;color:#777;background:#f4f4f2;padding:2px 5px}
.reply{padding-left:20px}.replyContext{display:block;color:#999;font-size:11px;margin-bottom:5px}
.page .replyButton{font-size:11px;color:#888;margin-top:8px;text-decoration:underline;text-underline-offset:3px}
-.nav{display:flex;align-items:center;gap:26px;color:#777;font-size:15px}
-.nav a,.nav button{display:inline-flex;align-items:center;gap:5px;white-space:nowrap}
+.nav,.barActions{display:flex;align-items:center;gap:26px;color:#777;font-size:15px}
+.barActions{gap:22px;margin-left:auto}
+.nav a,.barActions a,.barActions button{display:inline-flex;align-items:center;gap:5px;white-space:nowrap}
.nav [aria-current=page]{color:#242424}
-.nav svg{width:17px;height:17px}
+.nav svg,.barActions svg{width:17px;height:17px}
+.nav a:hover,.barActions>a:not(.primary):hover,.barActions button:hover{color:#242424}
+.page .barActions .primary{padding:8px 16px}
+.searchField{display:flex;align-items:center;gap:8px;width:min(280px,52vw);height:36px;padding:0 6px 0 12px;border:1px solid #e4e4e1;background:#fafaf9;transition:border-color .15s,background-color .15s;animation:searchOpen .18s ease-out}
+.searchField:focus-within{border-color:#242424;background:#fff}
+.searchField input{flex:1;min-width:0;height:100%;border:0;background:transparent;outline:0;color:#242424;font-size:14px}
+.searchField input::placeholder{color:#999}
+.searchField input::-webkit-search-cancel-button{-webkit-appearance:none;appearance:none}
+.page .searchField button{padding:4px;color:#999}
+.page .searchField button:hover{color:#242424}
+.searchField svg{width:16px;height:16px;flex-shrink:0}
+@keyframes searchOpen{from{width:36px;opacity:.5}}
+@media(prefers-reduced-motion:reduce){.searchField{animation:none}}
.feed{padding-top:49px;padding-bottom:100px}
.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:76px 16px}
.card{min-width:0;display:block}
@@ -25,8 +38,6 @@
.card p{font-size:15px;line-height:1.4;color:#777;margin-top:2px}
.card small{display:block;color:#888;font-size:13px;margin-top:9px}
.card:hover h2{color:#6c6c6c}
-.search{display:flex;align-items:center;gap:18px;margin:0 0 36px;background:#f7f7f7;padding:14px 18px}
-.search input{flex:1;min-width:0;border:0;background:transparent;outline-offset:5px}
.icon{display:inline-flex;align-items:center;justify-content:center;padding:8px;min-width:32px;min-height:32px}
.icon svg{width:17px;height:17px}
.notice{font-size:13px;color:#777;margin:0 0 30px;line-height:1.6}
@@ -106,16 +117,17 @@
.manage{margin-top:38px;font-size:12px;color:#777}
.manage button{text-decoration:underline;text-underline-offset:3px}
@media(min-width:1900px){.viewer iframe{height:780px}}
-@media(max-width:1100px){.wrap{width:90%}.nav{gap:20px}.chat{padding-left:22px}.actions{gap:13px}.identity h1{font-size:22px}.viewer iframe{height:640px}}
-@media(max-width:760px){.wrap{width:92%}.bar{gap:15px;min-height:70px}.nav{font-size:13px;gap:16px}.brand{font-size:23px}.feed{padding-top:30px}.grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:50px 14px}.split{grid-template-columns:1fr;gap:35px;min-height:0}.chat{padding:0}.detailHead{flex-wrap:wrap;gap:20px}.actions{margin-left:auto}.viewer iframe{height:590px}.forkColumns,.publishForm{grid-template-columns:1fr;gap:25px}.fork h1,.publish h1{font-size:32px}}
-@media(max-width:480px){.nav{gap:15px}.nav .openApp{display:none}.grid{grid-template-columns:1fr;gap:44px}.actions{width:100%;margin-left:0;gap:22px}.actions .primary{margin-left:auto}.identity h1{font-size:23px}.viewer iframe{height:510px}.page input,.page textarea,.page select{font-size:16px}.fork{padding-top:25px}.bar .brand{font-size:21px}.bar{gap:10px}.publishForm{gap:25px}}
+@media(max-width:1100px){.wrap{width:90%}.nav{gap:20px}.barActions{gap:18px}.chat{padding-left:22px}.actions{gap:13px}.identity h1{font-size:22px}.viewer iframe{height:640px}}
+@media(max-width:760px){.wrap{width:92%}.feed{padding-top:22px}.grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:44px 14px}.split{grid-template-columns:1fr;gap:28px;min-height:0}.chat{padding:0}.detail{padding-top:16px;padding-bottom:50px}.back{margin-bottom:14px}.detailHead{flex-wrap:wrap;gap:16px;margin-bottom:22px}.actions{margin-left:auto}.viewer iframe{height:590px}.forkColumns,.publishForm{grid-template-columns:1fr;gap:25px}.fork h1,.publish h1{font-size:32px}.page input,.page textarea,.page select{font-size:16px}}
+@media(max-width:480px){.grid{grid-template-columns:1fr;gap:36px}.actions{width:100%;margin-left:0;gap:22px}.actions .primary{margin-left:auto}.identity h1{font-size:23px}.viewer iframe{height:510px;height:min(560px,68svh)}.fork{padding-top:20px}.publish{padding-top:24px}.fork h1,.publish h1{font-size:28px}.publishForm{gap:25px}}
.tags{display:inline-flex;gap:5px;flex-wrap:wrap;align-items:center}
.tags>span{display:inline-block;background:#f3f3f1;color:#747471;font:10px/1.5 Arial,Helvetica,sans-serif;padding:3px 7px;border-radius:3px;white-space:nowrap}
.cardMeta{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:12px}
.cardMeta small{margin:0}
.handoff{display:inline-flex;flex-direction:column;align-items:flex-start;gap:9px}
.filesReview{margin:30px 0}.filesReview summary{cursor:pointer;font-size:14px}.fileRow{display:flex;align-items:center;gap:12px;margin:10px 0;font-size:12px}.fileRow code{flex:1;overflow-wrap:anywhere}.fileRow button{text-decoration:underline;color:#777}.importActions{margin:24px 0;background:#f7f7f5;padding:22px}.importActions p{color:#777;font-size:13px;margin-top:8px}
-@media(max-width:760px){.bar{flex-wrap:wrap}.bar .brand{width:100%;margin-bottom:4px}.nav{gap:16px;flex-wrap:wrap}.nav .openApp{display:none}}
+/* Phones: one sticky glass bar. Brand and actions on the first row, the tabs under them, and an open search across its own row. */
+@media(max-width:760px){.topbar{position:sticky;top:0;z-index:20;background:rgba(255,255,255,.82);-webkit-backdrop-filter:saturate(180%) blur(18px);backdrop-filter:saturate(180%) blur(18px);box-shadow:0 1px 0 rgba(36,36,36,.07)}.bar{flex-wrap:wrap;gap:0 16px;min-height:0;padding:4px 0 0}.bar .brand{font-size:21px;margin-right:auto}.barActions{display:contents;font-size:14px}.barActions>a,.barActions>button{order:1}.page .barActions .primary{min-height:34px;padding:6px 14px}.barActions .openApp{display:none}.nav{order:2;width:100%;gap:24px;font-size:14px}.nav a{position:relative;min-height:42px}.nav [aria-current=page]:after{content:'';position:absolute;left:0;right:0;bottom:0;height:2px;background:#242424}.barActions>.searchField{order:3;width:100%;margin:4px 0 10px;animation:none}}
.handoffHelp{font-size:11px;color:#888;max-width:220px;line-height:1.6}
.handoffHelp a{text-decoration:underline;text-underline-offset:3px}
.fork details{margin-top:32px;color:#777;font-size:13px}
diff --git a/website/src/app/hub/components/Feed.tsx b/website/src/app/hub/components/Feed.tsx
index c4d52909e..b627858f9 100644
--- a/website/src/app/hub/components/Feed.tsx
+++ b/website/src/app/hub/components/Feed.tsx
@@ -1,12 +1,12 @@
'use client';
-import { useState } from 'react';
import Link from 'next/link';
-import { Heart, MessageCircle, Search, X } from 'lucide-react';
+import { Heart, MessageCircle } from 'lucide-react';
import { starterHarnesses } from '@/lib/community/starters';
import type { HarnessSummary } from '@/lib/community/types';
import { Header, SignIn } from './Header';
import { HarnessTags } from './HarnessTags';
import { useFeed, type Stats } from './useFeed';
+import { useFeedSearch } from './useFeedSearch';
import styles from '../community.module.css';
/** One harness in the grid: its cover, introduction, tags, likes and comments. */
@@ -24,19 +24,19 @@ function FeedCard({ item, stats, onLike }: { item: HarnessSummary; stats?: Stats
</article>;
}
+/** Starters are the website's own, so they are matched here; publications are matched by the server. */
const matches = (item: HarnessSummary, query: string) => `${item.title} ${item.description} ${item.authorName} ${item.category} ${item.engine} ${item.harnessName || ''}`.toLowerCase().includes(query.toLowerCase());
-export default function Feed({ following = false, mine = false }: { following?: boolean; mine?: boolean }) {
- const { posts, follows, stats, cursor, error, likeError, signedOut, busy, more, load, like } = useFeed({ following, mine });
- const [query, setQuery] = useState(''), [search, setSearch] = useState(false);
+export default function Feed({ following = false, mine = false, initialQuery = '' }: { following?: boolean; mine?: boolean; initialQuery?: string }) {
+ const search = useFeedSearch(initialQuery), query = search.term;
+ const { posts, follows, stats, cursor, error, likeError, signedOut, busy, more, load, like } = useFeed({ following, mine, query });
// Starters follow the last page: drawn sooner, every page loaded while scrolling would land above
// them. A search or a failed page shows them at once: there is nothing to scroll past.
const starters = mine || (cursor && !query && !error) ? [] : following ? starterHarnesses.filter(item => follows.includes(item.authorId)) : starterHarnesses;
- const visible = [...posts, ...starters].filter(item => matches(item, query));
- return <><Header following={following} mine={mine} onSearch={() => { setSearch(value => !value); setQuery(''); }} />
+ const visible = [...posts, ...starters.filter(item => matches(item, query))];
+ return <><Header tab={mine ? 'yours' : following ? 'following' : 'explore'} search={{ value: search.query, onChange: search.setQuery, onClear: search.clear }} />
<main className={`${styles.wrap} ${styles.feed}`}>
{mine && <div className={styles.feedIntro}><h1>Your harnesses</h1><p>See what people like, join the conversation, and share your next version.</p></div>}
- {search && <div className={styles.search}><Search size={17} /><input autoFocus type="search" aria-label="Search harnesses" placeholder="Find a harness, creator, or idea" value={query} onChange={event => setQuery(event.target.value)} /><button className={styles.icon} aria-label="Close search" onClick={() => { setSearch(false); setQuery(''); }}><X /></button></div>}
{error && <p className={styles.notice} role="status">{error}<button onClick={() => void load()}>Retry</button></p>}
{likeError && <p className={styles.notice} role="status">{likeError}</p>}
{signedOut && <SignIn action={following ? 'see creators you follow' : 'join the Hub'} />}
diff --git a/website/src/app/hub/components/Header.tsx b/website/src/app/hub/components/Header.tsx
index 41a06e9fc..b88f7f91c 100644
--- a/website/src/app/hub/components/Header.tsx
+++ b/website/src/app/hub/components/Header.tsx
@@ -1,24 +1,36 @@
'use client';
import Link from 'next/link';
-import { ArrowUpRight, Search } from 'lucide-react';
+import { ArrowUpRight } from 'lucide-react';
import { rememberHubReturn } from '@/lib/community/session';
+import { SearchField, type SearchFieldProps } from './SearchField';
import { useSignedIn } from './useSignedIn';
import styles from '../community.module.css';
-export function Header({ following = false, mine = false, onSearch }: { following?: boolean; mine?: boolean; onSearch?: () => void }) {
+/** One way out to the app: sign in (and come back) while signed out, open it once signed in. */
+function AccountLink({ signedIn }: { signedIn: boolean | null }) {
+ if (signedIn === null) return null;
+ if (!signedIn) return <a href="/" onClick={rememberHubReturn}>Sign in</a>;
+ return <a href="/" className={styles.openApp}>Open Harness <ArrowUpRight /></a>;
+}
+
+export type HubTab = 'explore' | 'following' | 'yours';
+
+/** The Hub's bar. `tab` marks the feed being read; a harness, fork or publish page marks none. */
+export function Header({ tab, search }: { tab?: HubTab; search?: SearchFieldProps }) {
const signedIn = useSignedIn();
- return <header className={`${styles.wrap} ${styles.bar}`}>
+ return <header className={styles.topbar}><div className={`${styles.wrap} ${styles.bar}`}>
<Link className={styles.brand} href="/hub">Harness <span className={styles.hubWord}>Hub</span></Link>
<nav className={styles.nav} aria-label="Harness community">
- <Link href="/hub" aria-current={!following && !mine ? 'page' : undefined}>Explore</Link>
- <Link href="/hub/following" aria-current={following ? 'page' : undefined}>Following</Link>
- {signedIn && <Link href="/hub/yours" aria-current={mine ? 'page' : undefined}>Yours</Link>}
- {onSearch && <button onClick={onSearch} aria-label="Search harnesses"><Search /></button>}
- <Link href="/hub/publish">Publish</Link>
- {signedIn === false && <a href="/" onClick={rememberHubReturn}>Sign in</a>}
- <a href="/" className={styles.openApp}>Open Harness <ArrowUpRight /></a>
+ <Link href="/hub" aria-current={tab === 'explore' ? 'page' : undefined}>Explore</Link>
+ <Link href="/hub/following" aria-current={tab === 'following' ? 'page' : undefined}>Following</Link>
+ {signedIn && <Link href="/hub/yours" aria-current={tab === 'yours' ? 'page' : undefined}>Yours</Link>}
</nav>
- </header>;
+ <div className={styles.barActions}>
+ {search && <SearchField {...search} />}
+ <Link className={styles.primary} href="/hub/publish">Publish</Link>
+ <AccountLink signedIn={signedIn} />
+ </div>
+ </div></header>;
}
export function SignIn({ action = 'join the conversation' }: { action?: string }) {
diff --git a/website/src/app/hub/components/SearchField.tsx b/website/src/app/hub/components/SearchField.tsx
new file mode 100644
index 000000000..0c44a9645
--- /dev/null
+++ b/website/src/app/hub/components/SearchField.tsx
@@ -0,0 +1,40 @@
+'use client';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { Search, X } from 'lucide-react';
+import { searchMaxChars } from '@/lib/community/search';
+import styles from '../community.module.css';
+
+export type SearchFieldProps = { value: string; onChange: (value: string) => void; onClear: () => void };
+
+const typing = (target: EventTarget | null) => target instanceof HTMLElement && (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName));
+
+/** `/` anywhere outside a field opens the search, as on most sites with one. */
+function useSlashShortcut(onSlash: () => void) {
+ useEffect(() => {
+ const listener = (event: KeyboardEvent) => {
+ if (event.key !== '/' || event.metaKey || event.ctrlKey || event.altKey || typing(event.target)) return;
+ event.preventDefault(); onSlash();
+ };
+ window.addEventListener('keydown', listener);
+ return () => window.removeEventListener('keydown', listener);
+ }, [onSlash]);
+}
+
+/**
+ * The Hub's search: an icon that opens into a field in the bar, focused when the reader opens it (not
+ * when a page arrives with `?q=`). Escape clears it, then closes it.
+ */
+export function SearchField({ value, onChange, onClear }: SearchFieldProps) {
+ const [open, setOpen] = useState(!!value);
+ const input = useRef<HTMLInputElement>(null);
+ const reveal = useCallback(() => { setOpen(true); input.current?.focus(); }, []);
+ useSlashShortcut(reveal);
+ if (!open) return <button type="button" onClick={reveal} aria-label="Search harnesses"><Search /></button>;
+ const escape = () => { if (value) onClear(); else setOpen(false); };
+ return <form role="search" className={styles.searchField} onSubmit={event => event.preventDefault()}>
+ <Search aria-hidden />
+ <input ref={input} autoFocus={!value} type="search" aria-label="Search harnesses" placeholder="Search harnesses and creators" maxLength={searchMaxChars} value={value}
+ onChange={event => onChange(event.target.value)} onKeyDown={event => { if (event.key === 'Escape') escape(); }} onBlur={() => { if (!value) setOpen(false); }} />
+ {value && <button type="button" aria-label="Clear search" onMouseDown={event => event.preventDefault()} onClick={() => { onClear(); input.current?.focus(); }}><X /></button>}
+ </form>;
+}
diff --git a/website/src/app/hub/components/community.spec.tsx b/website/src/app/hub/components/community.spec.tsx
index 3ede2376c..50bfd30d6 100644
--- a/website/src/app/hub/components/community.spec.tsx
+++ b/website/src/app/hub/components/community.spec.tsx
@@ -44,9 +44,15 @@ describe('community navigation', () => {
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Search harnesses' }));
fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'orbit' } });
+ // Publications are searched by the server, across every page; the starters are matched here.
+ await waitFor(() => expect(request).toHaveBeenLastCalledWith('harnesses?q=orbit'));
expect(screen.getByRole('link', { name: 'Open A little perspective' })).toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Open Blue hour' })).not.toBeInTheDocument();
- await waitFor(() => expect(request).toHaveBeenCalled());
+ expect(window.location.search).toBe('?q=orbit');
+ fireEvent.keyDown(screen.getByRole('searchbox'), { key: 'Escape' });
+ await waitFor(() => expect(request).toHaveBeenLastCalledWith('harnesses?'));
+ expect(window.location.search).toBe('');
+ expect(screen.getByRole('link', { name: 'Open Blue hour' })).toBeInTheDocument();
});
it('draws the starters after the last page, so paging never lands above them', async () => {
request.mockResolvedValueOnce({ harnesses: [{ ...sample, id: 'first' }], nextCursor: 'next-page', following: [], stats: {}, signedIn: true });
@@ -54,10 +60,13 @@ describe('community navigation', () => {
await screen.findByRole('button', { name: 'More harnesses' });
expect(screen.queryByRole('link', { name: 'Open Blue hour' })).not.toBeInTheDocument();
// A search finds them at once: there is nothing to scroll past.
+ request.mockResolvedValueOnce({ harnesses: [], nextCursor: null, following: [], stats: {}, signedIn: true });
fireEvent.click(screen.getByRole('button', { name: 'Search harnesses' }));
fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'melody' } });
- expect(screen.getByRole('link', { name: 'Open Blue hour' })).toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', { name: 'Close search' }));
+ await screen.findByRole('link', { name: 'Open Blue hour' });
+ request.mockResolvedValueOnce({ harnesses: [{ ...sample, id: 'first' }], nextCursor: 'next-page', following: [], stats: {}, signedIn: true });
+ fireEvent.click(screen.getByRole('button', { name: 'Clear search' }));
+ await waitFor(() => expect(screen.queryByRole('link', { name: 'Open Blue hour' })).not.toBeInTheDocument());
request.mockResolvedValueOnce({ harnesses: [{ ...sample, id: 'second', title: 'Second' }], nextCursor: null, following: [], stats: {}, signedIn: true });
fireEvent.click(screen.getByRole('button', { name: 'More harnesses' }));
await screen.findByRole('link', { name: 'Open Blue hour' });
diff --git a/website/src/app/hub/components/useFeed.ts b/website/src/app/hub/components/useFeed.ts
index 2d25e5e24..a9cc6559c 100644
--- a/website/src/app/hub/components/useFeed.ts
+++ b/website/src/app/hub/components/useFeed.ts
@@ -8,9 +8,10 @@ type FeedResult = { harnesses: HarnessSummary[]; nextCursor: string | null; foll
/**
* One feed's pages, their likes and comment counts, and the reader's likes. Pages load as `more`
- * scrolls into view; a newer load supersedes an older one, and a sign-in or sign-out reloads.
+ * scrolls into view; a newer load supersedes an older one, and a sign-in, a sign-out or a new search
+ * (`query`, matched by the server across every publication) reloads.
*/
-export function useFeed({ following, mine }: { following: boolean; mine: boolean }) {
+export function useFeed({ following, mine, query }: { following: boolean; mine: boolean; query: string }) {
const [posts, setPosts] = useState<HarnessSummary[]>([]), [follows, setFollows] = useState<string[]>([]);
const [stats, setStats] = useState<Record<string, Stats>>({}), [signedIn, setSignedIn] = useState(false);
const [cursor, setCursor] = useState<string | null>(null);
@@ -21,7 +22,7 @@ export function useFeed({ following, mine }: { following: boolean; mine: boolean
const requestId = ++generation.current;
loading.current = true; setBusy(true); setError(''); setSignedOut(false);
try {
- const params = new URLSearchParams(); if (following) params.set('following', 'true'); if (mine) params.set('mine', 'true'); if (after) params.set('cursor', after);
+ const params = new URLSearchParams(); if (following) params.set('following', 'true'); if (mine) params.set('mine', 'true'); if (query) params.set('q', query); if (after) params.set('cursor', after);
const result = await communityRequest<FeedResult>(`harnesses?${params}`);
if (requestId !== generation.current) return;
setPosts(previous => after ? [...previous, ...result.harnesses.filter(item => !previous.some(p => p.id === item.id))] : result.harnesses);
@@ -32,7 +33,7 @@ export function useFeed({ following, mine }: { following: boolean; mine: boolean
if (e instanceof CommunityError && e.status === 401) setSignedOut(true);
else setError('Community posts are temporarily unavailable. You can still explore and fork the starter projects.');
} finally { if (requestId === generation.current) { loading.current = false; setBusy(false); } }
- }, [following, mine]);
+ }, [following, mine, query]);
useEffect(() => {
void load(); const reload = () => { void load(); };
window.addEventListener('storage', reload); window.addEventListener('harness-session', reload);
diff --git a/website/src/app/hub/components/useFeedSearch.ts b/website/src/app/hub/components/useFeedSearch.ts
new file mode 100644
index 000000000..623bc08cd
--- /dev/null
+++ b/website/src/app/hub/components/useFeedSearch.ts
@@ -0,0 +1,24 @@
+'use client';
+import { useEffect, useState } from 'react';
+
+const settleMs = 250;
+
+/**
+ * What the reader is typing, and the settled term the feed asks the server for. The term is kept in
+ * the page's `?q=`, so a search can be shared and survives a reload; clearing takes effect at once.
+ */
+export function useFeedSearch(initial = '') {
+ const [query, setQuery] = useState(initial), [term, setTerm] = useState(initial);
+ useEffect(() => {
+ const timer = setTimeout(() => setTerm(query.trim()), settleMs);
+ return () => clearTimeout(timer);
+ }, [query]);
+ useEffect(() => {
+ const url = new URL(window.location.href);
+ if (term) url.searchParams.set('q', term);
+ else url.searchParams.delete('q');
+ if (url.href !== window.location.href) window.history.replaceState(window.history.state, '', url);
+ }, [term]);
+ const clear = () => { setQuery(''); setTerm(''); };
+ return { query, setQuery, term, clear };
+}
diff --git a/website/src/app/hub/following/page.tsx b/website/src/app/hub/following/page.tsx
index 7c0fb7597..4e6205ffa 100644
--- a/website/src/app/hub/following/page.tsx
+++ b/website/src/app/hub/following/page.tsx
@@ -1,2 +1,4 @@
+import { searchFromParams } from '@/lib/community/search';
import Feed from '../components/Feed';
-export default function FollowingPage() { return <Feed following />; }
+type Props = { searchParams: Promise<{ q?: string | string[] }> };
+export default async function FollowingPage({ searchParams }: Props) { return <Feed following initialQuery={await searchFromParams(searchParams)} />; }
diff --git a/website/src/app/hub/page.tsx b/website/src/app/hub/page.tsx
index e94e7b38b..2178bc9e8 100644
--- a/website/src/app/hub/page.tsx
+++ b/website/src/app/hub/page.tsx
@@ -1,2 +1,4 @@
+import { searchFromParams } from '@/lib/community/search';
import Feed from './components/Feed';
-export default function ExplorePage() { return <Feed />; }
+type Props = { searchParams: Promise<{ q?: string | string[] }> };
+export default async function ExplorePage({ searchParams }: Props) { return <Feed initialQuery={await searchFromParams(searchParams)} />; }
diff --git a/website/src/app/hub/yours/page.tsx b/website/src/app/hub/yours/page.tsx
index 94a7d529f..975844ddf 100644
--- a/website/src/app/hub/yours/page.tsx
+++ b/website/src/app/hub/yours/page.tsx
@@ -1,2 +1,4 @@
+import { searchFromParams } from '@/lib/community/search';
import Feed from '../components/Feed';
-export default function YoursPage() { return <Feed mine />; }
+type Props = { searchParams: Promise<{ q?: string | string[] }> };
+export default async function YoursPage({ searchParams }: Props) { return <Feed mine initialQuery={await searchFromParams(searchParams)} />; }
diff --git a/website/src/lib/community/search.ts b/website/src/lib/community/search.ts
new file mode 100644
index 000000000..7cd880a20
--- /dev/null
+++ b/website/src/lib/community/search.ts
@@ -0,0 +1,8 @@
+/** The longest feed search the backend accepts (`q` on GET /api/community/harnesses). */
+export const searchMaxChars = 80;
+
+/** The search a page was opened with, from its `?q=`. */
+export async function searchFromParams(searchParams: Promise<{ q?: string | string[] }>): Promise<string> {
+ const { q } = await searchParams;
+ return typeof q === 'string' ? q.trim().slice(0, searchMaxChars) : '';
+}