The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
import 'core/app_version.dart';
import 'dart:async';
import 'measurement/product_runtime_health.dart';
import 'measurement/speed_marks.dart';
import 'dart:ui' show AppExitResponse;
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart'
show kIsWeb, LicenseEntry, LicenseRegistry, LicenseEntryWithLineBreaks;
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_web_plugins/url_strategy.dart';
import 'core/crash_log.dart';
import 'core/desktop_window.dart';
import 'core/linux_app_image.dart';
import 'core/runtime_platform.dart';
import 'core/test_run.dart';
import 'core/windows_status_tray.dart';
import 'settings/settings_screen.dart';
import 'settings/settings_section.dart';
import 'screens/login_screen.dart';
import 'screens/swarm_menu_bus.dart';
import 'state/app_state.dart';
import 'stats/stats_lifecycle.dart';
import 'viewer/viewer_services.dart';
import 'ws/terminal_transport_plugin.dart';
import 'shared/theme/app_theme.dart' as grid;
import 'shared/theme/appearance_prefs_store.dart';
import 'terminal/terminal_font_store.dart';
import 'widgets/bootstrapping_screen.dart';
import 'widgets/layout_palette.dart';
import 'widgets/environment_preflight_screen.dart';
import 'widgets/environment_setup_screen.dart';
import 'widgets/export_logs_dialog.dart';
import 'widgets/in_window_menu_bar.dart';
import 'widgets/setup_tour.dart';
import 'widgets/sign_in_step.dart';
import 'widgets/transient_menus.dart';
import 'core/startup.dart';
import 'logging/app_log.dart';
import 'logging/install.dart';
import 'shortcuts/app_keymap.dart';
import 'shortcuts/keymap_native.dart';
import 'shortcuts/keyboard_practice.dart';
import 'widgets/shortcuts_sheet.dart';
import 'widgets/new_device_notice.dart';
import 'widgets/shared_tab_notice.dart';
import 'widgets/update_notice.dart';
import 'widgets/window_chrome.dart';
import 'sharing/shared_agent_location.dart';
import 'sharing/shared_agent_page.dart';
import 'viewer/viewer_link_incomplete.dart';
import 'viewer/viewer_location.dart';
import 'viewer/viewer_page.dart';
/// The screen an app puts up once someone is signed in — the desktop's swarm of
/// panes, or the phone's one-agent-at-a-time shell. It is the only thing the two
/// entry points disagree about; everything below is shared.
typedef AuthenticatedScreenBuilder = Widget Function(AppNotifier app);
/// What a host draws around every screen of the app, sign-in included. The
/// desktop draws nothing; a browser build stands its store bar over the app.
typedef AppFrameBuilder = Widget Function(Widget app);
/// Everything both entry points do before their first frame: file logs, the
/// crash log, the keyboard config, the saved appearance, and the native window
/// where there is one.
///
/// Lives here rather than in `main.dart` so every screen up to sign-in has one
/// definition of what precedes it. `../mobile` carries its own vendored copy of
/// this file — it depended on this package until it was made standalone — so a
/// change here that belongs on the phone too has to be carried across; the two
/// trees are otherwise byte-identical outside `lib/phone/` and `lib/p2p/`.
Future<void> startHarness({
required AuthenticatedScreenBuilder authenticatedScreen,
/// See [AppFrameBuilder]; none leaves the app unframed.
AppFrameBuilder? frame,
/// A viewer build's second wire to each machine (see
/// [TerminalTransportPlugin]); the desktop passes none.
TerminalTransportPluginFactory? transportPlugins,
}) async {
speedMarks.start();
if (!kIsWeb) ProductRuntimeHealth.launched();
// Share links and OAuth own the browser URL. Flutter's default hash routing would
// erase the share's pinned identity on the first navigation or window resize.
if (kIsWeb) setUrlStrategy(null);
WidgetsFlutterBinding.ensureInitialized();
LicenseRegistry.addLicense(bundledFontLicenses);
harnessTransportPlugins = transportPlugins;
// Before anything else can fail. The file sinks come first so CrashLog's own
// install has somewhere to mirror to — see CrashLog.record.
installFileLogs();
CrashLog.install();
appLog.info('app', 'launched');
final keymap = AppKeymap(store: kIsWeb ? null : AppKeymap.fileStore());
// Keyboard configuration has its own file and watchers. It can load beside
// the appearance, but both must be ready before the window becomes usable.
await Future.wait([loadPersistedSettings(), keymap.start()]);
speedMarks.launch('settings loaded');
// Match macOS repaints the app when the computer's own setting flips.
appearancePrefsStore.followSystemBrightness();
// Apply the saved palette to native chrome as well as the Flutter theme.
await configureDesktopWindow(palette: appearancePrefsStore.value.palette);
speedMarks.launch('window configured');
runApp(
ProviderScope(
child: HarnessApp(
keymap: keymap,
authenticatedScreen: authenticatedScreen,
frame: frame,
),
),
);
// After the first frame is on its way: a launcher entry is not worth
// holding the window up for.
unawaited(registerAppImageLauncher());
}
class HarnessApp extends StatelessWidget {
const HarnessApp({
super.key,
this.keymap,
required this.authenticatedScreen,
this.frame,
this.deferFirstScreen,
});
/// Whether the first frame draws only the window colour, leaving the app
/// state and the screen to the next frame (task #3563). Null: on, except in
/// widget tests, which expect the screen on their first pump, and on the web,
/// which this change did not measure.
final bool? deferFirstScreen;
final AppKeymap? keymap;
final AuthenticatedScreenBuilder authenticatedScreen;
final AppFrameBuilder? frame;
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: Listenable.merge([appearancePrefsStore, terminalFontStore]),
builder: (context, _) => _app(appearancePrefsStore.value),
);
}
Widget _app(AppearancePrefs prefs) {
grid.AppTheme.palette.value = prefs.palette;
// Also the brightness `AppPalette.windowBg` resolves against: the
// placeholder of the first frame is drawn before `_GridTokenScope` (inside
// the deferred shell) would set it, and a light palette must not flash dark.
grid.AppTheme.brightness.value = prefs.palette.brightness;
return MaterialApp(
title: 'Harness',
// OAuth callback paths are consumed by the sign-in adapter during boot.
initialRoute: '/',
themeAnimationDuration: Duration.zero,
// Flutter's DEBUG ribbon stays on a debug build: it is how a locally built
// app is told apart from the installed release at a glance (owner,
// 2026-09-16). It never appears in a release build whatever this says.
// A preview capture that wants a clean corner passes
// `--dart-define=HARNESS_CLEAN_PREVIEW=true` instead of turning it off
// for everyone. Not on Windows, where the corner it covers is the window's
// close button.
debugShowCheckedModeBanner:
!RuntimePlatform.isWindows &&
!const bool.fromEnvironment('HARNESS_CLEAN_PREVIEW'),
// The design system's own `buildAppTheme` — see the note where a second,
// hand-written `ThemeData` used to shadow it, in `lib/theme/app_theme.dart`.
// The chosen palette owns the appearance; platform text scaling remains
// available to app controls.
theme: grid.buildAppTheme(brightness: prefs.palette.brightness),
highContrastTheme: grid.buildAppTheme(
brightness: prefs.palette.brightness,
highContrast: true,
),
// Desktop forms respect the platform's text size. Fixed-grid terminal
// surfaces own their no-scaling boundary alongside terminal zoom.
builder: (context, child) {
Widget shell() {
final app = child ?? const SizedBox.shrink();
final framed = frame?.call(app) ?? app;
return _GridTokenScope(
child: keymap == null
? framed
: KeymapProvider(keymap: keymap!, child: framed),
);
}
return deferFirstScreen ?? !(kUnderTest || kIsWeb)
? _AfterFirstFrame(build: shell)
: shell();
},
home: StatsLifecycle(
child: RootShell(authenticatedScreen: authenticatedScreen),
),
);
}
}
/// Draws only the window's own colour on the first frame, then [build] on the
/// next one (task #3563).
///
/// The app state (its bootstrap starts when it is first read), the menu and
/// device strips, the keymap and the screen are built inside [build]. The
/// first frame no longer waits for them: its mark moves from ~82 ms to ~55 ms
/// after the window is configured, and the boot screen is on screen about
/// 10 ms earlier than before, because the next frame starts straight after
/// this one. The window colour matches the screen's, so nothing flashes.
class _AfterFirstFrame extends StatefulWidget {
const _AfterFirstFrame({required this.build});
final Widget Function() build;
@override
State<_AfterFirstFrame> createState() => _AfterFirstFrameState();
}
class _AfterFirstFrameState extends State<_AfterFirstFrame> {
bool _ready = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
setState(() => _ready = true);
speedMarks.launch('first screen built');
WidgetsBinding.instance.addPostFrameCallback(
(_) => speedMarks.launch('first screen painted'),
);
});
}
@override
Widget build(BuildContext context) {
if (!_ready) {
return ColoredBox(
key: const Key('first-frame-placeholder'),
color: grid.AppPalette.windowBg,
);
}
return widget.build();
}
}
/// Carries Grid's design tokens past this app's `const` chrome.
///
/// A `const` widget is reference-identical across its parent's rebuild, so a
/// top-down rebuild never reaches one — it would keep the palette it first
/// mounted with. [grid.BrightnessScope] marks the ones that called
/// `AppTheme.watch` dirty directly, across that boundary.
///
/// Set from the palette rather than read from `Theme.of(context)`: the palette
/// is where light or dark is chosen, and [HarnessApp] builds the theme from the
/// same value, so the two cannot disagree.
class _GridTokenScope extends StatelessWidget {
const _GridTokenScope({required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
grid.AppTheme.brightness.value = grid.AppTheme.palette.value.brightness;
return grid.BrightnessScope(child: child);
}
}
/// The licenses page's entries for the fonts this app bundles.
Stream<LicenseEntry> bundledFontLicenses() async* {
yield LicenseEntryWithLineBreaks([
'Roboto Mono',
], await rootBundle.loadString('assets/fonts/roboto-mono/OFL.txt'));
// Nerd Fonts' MIT terms, then the glyph sets it collects and their licenses.
for (final file in const [
'LICENSE',
'NOTICE',
'CC-BY-4.0.txt',
'Apache-2.0.txt',
'OFL.txt',
]) {
yield LicenseEntryWithLineBreaks(
['Symbols Nerd Font Mono'],
await rootBundle.loadString('assets/fonts/symbols-nerd-font-mono/$file'),
);
}
}
/// Carries "Check for Updates…" from the macOS application menu into Dart.
///
/// The item is installed natively (MainFlutterWindow.swift) so the rest of the
/// menu bar keeps coming from the nib; all this side does is act on the tap.
const _appMenuChannel = MethodChannel('harness/app_menu');
class RootShell extends ConsumerStatefulWidget {
const RootShell({super.key, required this.authenticatedScreen});
final AuthenticatedScreenBuilder authenticatedScreen;
@override
ConsumerState<RootShell> createState() => _RootShellState();
}
class _RootShellState extends ConsumerState<RootShell>
with WidgetsBindingObserver {
bool _menuDialogOpen = false;
/// Whether the workspace is the window's screen: it then owns what AppKit
/// hands to Flutter ([_handSignedOutKeymap] otherwise).
bool _home = false;
/// Before a workspace (signed out), AppKit's File menu keeps ⌘W for Close
/// Tab, which is off there, so Settings over the sign-in page never hears
/// it. Hand AppKit the keymap with Close Tab's keys alone going to Flutter:
/// ⌘, ⌘H and ⌘M stay with the menu. Also on leaving the workspace, whose
/// keymap handed Flutter every key.
void _handSignedOutKeymap() {
if (!mounted) return;
final keymap = KeymapTheme.of(context, listen: false);
if (keymap == null) return;
unawaited(
swarmMenuBus
.send(
'keymapState',
nativeKeymapSnapshot(keymap, inputOnly: const {'swarm.close'}),
)
.catchError((Object _) {}),
);
}
SharedAgentLocation? _sharedLocation;
@override
void initState() {
super.initState();
if (kIsWeb) _sharedLocation = SharedAgentLocation.parse(Uri.base);
WidgetsBinding.instance.addObserver(this);
_appMenuChannel.setMethodCallHandler(_onAppMenu);
// The Windows tab strip's ☰ is built below this shell, so it dispatches
// through the sink instead of a callback threaded through three
// constructors (desktop/design/windows-app-menu.md).
appMenuActionSink = runAppMenuAction;
// Available from startup, including sign-in and setup.
if (RuntimePlatform.isWindows && !kUnderTest) windowsStatusTray.install();
}
@override
void dispose() {
flushAppLog();
WidgetsBinding.instance.removeObserver(this);
_appMenuChannel.setMethodCallHandler(null);
appMenuActionSink = null;
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state != AppLifecycleState.resumed) flushAppLog();
}
@override
Future<AppExitResponse> didRequestAppExit() async {
final app = ref.read(appStateProvider);
app.productRuntimeHealth?.cleanExit();
// A sign-in still waiting on the browser or a phone ends with the app: its
// CLI would otherwise wait on, holding the lock the next sign-in needs.
if (app.canCancelLogin) app.cancelLogin();
// Save the final arrangement, with a bound so an unavailable disk cannot
// trap the user in the app. Input and tab switching never wait for disk.
try {
await app.flushPaneLayout().timeout(
const Duration(seconds: 1),
onTimeout: () {},
);
} finally {
flushAppLog(durable: true);
}
return AppExitResponse.exit;
}
Future<void> _onAppMenu(MethodCall call) async {
await runAppMenuAction(call.method);
}
/// Runs one app-menu action.
///
/// The macOS native menu reports over `harness/app_menu`; the in-window menu bar
/// ([InWindowMenuBar]) fires the same strings directly, so one switch serves
/// every platform.
Future<void> runAppMenuAction(String action) async {
if (!mounted) return;
switch (action) {
case 'settings':
final app = ref.read(appStateProvider);
if (!_home) _handSignedOutKeymap();
await _menuDialog(
() => showSettingsScreen(
context,
app,
initialSection: kIsWeb
? SettingsSection.privacy
: SettingsSection.experimental,
source: 'setup_menu',
),
);
case 'checkForUpdates':
final app = ref.read(appStateProvider);
await _menuDialog(() => checkForUpdatesAndShowResult(context, app));
case 'exportLogs':
await _menuDialog(() => showExportLogsDialog(context));
case 'showLayout':
if (advanceLayoutPalette()) return;
await _menuDialog(
() => showLayoutPalette(context, ref.read(appStateProvider)),
);
case 'showShortcuts':
await _menuDialog(() => showShortcutsSheet(context));
case 'keyboardPractice':
await _menuDialog(() => showKeyboardPractice(context));
case 'welcomeTour':
// Over the setup tour it would be the same slides twice.
if (ref.read(appStateProvider).setupTourShowing) return;
await _menuDialog(() => showWelcomeTour(context));
case 'showAbout':
// macOS shows AppKit's standard About panel; the Linux bar's row lands
// here, with the version the Linux release stamps beside the binary.
final version = await runningAppVersion();
if (!mounted) return;
await _menuDialog(
() async => showAboutDialog(
context: context,
applicationName: 'Harness',
applicationVersion: version,
),
);
case 'increaseTerminalFontSize':
await terminalFontStore.increaseSize();
case 'decreaseTerminalFontSize':
await terminalFontStore.decreaseSize();
case 'resetTerminalFontSize':
await terminalFontStore.reset();
}
}
Future<void> _menuDialog(Future<void> Function() action) async {
if (_menuDialogOpen || ModalRoute.isCurrentOf(context) == false) return;
// Reserve before the first frame too: held menu shortcuts can arrive
// before the new dialog has changed the route's current state.
_menuDialogOpen = true;
// An open dropdown is an overlay above every route: close it, or its rows
// stay live over the dialog (Sign out behind Check for Updates).
dismissTransientMenus();
try {
await action();
} finally {
_menuDialogOpen = false;
}
}
@override
Widget build(BuildContext context) {
final app = ref.watch(appStateProvider);
return ListenableBuilder(
listenable: app,
builder: (context, _) {
Widget screen;
switch (app.status) {
case AppStatus.bootstrapping:
// `bootstrapping` covers two unrelated moments: the app starting
// cold, and a sign-in the user just began. The second keeps
// LoginScreen, which carries the wait as a state of its own
// button; swapping the window for a separate screen there was a
// hard cut in the middle of a flow, and it is why that button's
// spinner was almost never seen.
//
// ⚠️ Keyed on `signingIn`, NOT on `pendingAuthorizeUrl`. The URL
// only exists for the middle stretch of the flow — the CLI has to
// start before it can print one, and it is cleared again while
// the post-login restore is still running — so keying on it blew
// the user's own screen away twice per sign-in: once on the click
// and again on success.
screen = app.signingIn
? LoginScreen(notifier: app)
: BootstrappingScreen(statusMessage: app.bootStatusMessage);
case AppStatus.checkingEnvironment:
screen = EnvironmentPreflightScreen(
readiness: app.environmentReadiness,
);
case AppStatus.preparingEnvironment:
screen = EnvironmentSetupScreen(notifier: app);
case AppStatus.unauthenticated:
screen = LoginScreen(notifier: app);
case AppStatus.authenticated:
final viewerLocation = kIsWeb
? ViewerLocation.parse(Uri.base)
: null;
screen = viewerLocation != null
? ViewerPage(app: app, location: viewerLocation)
: kIsWeb && ViewerLocation.isRoute(Uri.base)
? ViewerLinkIncomplete(location: Uri.base)
: widget.authenticatedScreen(app);
}
// A fresh computer's unattended install runs under the welcome tour,
// whatever the status says meanwhile, until the tour opens Harness.
final touring = app.setupTourShowing;
if (touring) screen = SetupTourScreen(app: app);
// Every signed-out desktop launch requires an account before opening
// the workspace, including computers that already have Harness.
final signInStep = !touring && app.signInStepShowing;
if (signInStep) screen = SignInStepScreen(app: app);
// Preserve the fragment pin while dialogs navigate; an OAuth callback can restore it later.
if (kIsWeb) _sharedLocation ??= SharedAgentLocation.parse(Uri.base);
final shared = _sharedLocation;
if (shared != null) {
screen = SharedAgentPage(app: app, location: shared);
}
// Only the home shell carries its own drag handle and traffic-light
// clearance (the rail's head). Every other screen fills the window
// with a centred card, so the strip goes over it here, once, instead
// of inside each of them.
final home =
app.status == AppStatus.authenticated && !touring && !signInStep;
if (_home && !home) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => _handSignedOutKeymap(),
);
}
_home = home;
final framed = home ? screen : FullWindowScreen(child: screen);
// The band takes a row of its own rather than floating over one. As an
// overlay it landed on the rail's head — covering the wordmark and the
// three buttons beside it, which is the one strip of this window that
// must stay reachable.
// Device bands, most urgent first: a removal (red before neutral), a key that joined and left,
// a new device, a held computer id. The mobile app stacks them in the same order. They are
// the workspace's: a shared harness (`/s/…`, web only) is someone's session, not the place
// to review your own devices.
final deviceBands = home && shared == null;
return Column(
children: [
// The app's commands as a menu strip. Linux always (on GNOME it
// is the title bar); macOS carries them in its native menu bar and
// renders nothing. Windows draws a ☰ in the workspace tab strip
// instead, but the screens before it — sign-in, setup, the tour —
// have no tab strip, so they keep the strip until the workspace is
// up.
if (!RuntimePlatform.isWindows || !home)
InWindowMenuBar(onAction: runAppMenuAction),
if (app.hasAvailableUpdate &&
!touring &&
!signInStep &&
app.status != AppStatus.bootstrapping &&
app.status != AppStatus.checkingEnvironment &&
app.status != AppStatus.preparingEnvironment)
UpdateNotice(notifier: app),
if (app.visibleDeviceRemovals.isNotEmpty && deviceBands)
DeviceRemovalNoticeBand(notifier: app),
if (app.departedDevices.isNotEmpty && deviceBands)
DeviceDepartedNoticeBand(notifier: app),
if (app.newDevices.isNotEmpty && deviceBands)
NewDeviceNotice(notifier: app),
if (app.deviceConflict != null && deviceBands)
DeviceConflictNoticeBand(notifier: app),
if (deviceBands)
ListenableBuilder(
listenable: app.sharedTabs,
builder: (_, _) => SharedTabNotice.hasWork(app)
? SharedTabNotice(notifier: app)
: const SizedBox.shrink(),
),
Expanded(child: framed),
],
);
},
);
}
}