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.

Revert "mobile: an opt-in setting to hold the connection while off screen"

bubu-dudu7fb4ffd0f942
diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xml
index 18f7a4ff9..45e4e68c6 100644
--- a/mobile/android/app/src/main/AndroidManifest.xml
+++ b/mobile/android/app/src/main/AndroidManifest.xml
@@ -23,13 +23,6 @@
microphone is the only permission it needs. -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-feature android:name="android.hardware.microphone" android:required="false" />
- <!-- Holding the machine socket open while the app is in another app's shadow: without a
- foreground service Android freezes the process (~30s on a Pixel 8 Pro), the backend's
- liveness ping goes unanswered, and coming back costs a full redial. `dataSync` is the
- type that fits — and the one Android 14 caps at six hours a day, which is why the hold
- expires on its own. See AwakeService.kt. -->
- <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
- <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<application
android:label="Harness"
android:name="${applicationName}"
@@ -56,11 +49,6 @@
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
- <!-- Not exported: nothing outside the app has any business holding this. -->
- <service
- android:name=".AwakeService"
- android:exported="false"
- android:foregroundServiceType="dataSync" />
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
diff --git a/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/AwakeService.kt b/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/AwakeService.kt
deleted file mode 100644
index 20e5bc69c..000000000
--- a/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/AwakeService.kt
+++ /dev/null
@@ -1,125 +0,0 @@
-package ai.autonomous.harness.android
-
-import android.app.Notification
-import android.app.NotificationChannel
-import android.app.NotificationManager
-import android.app.PendingIntent
-import android.app.Service
-import android.content.Intent
-import android.content.pm.ServiceInfo
-import android.os.Build
-import android.os.Handler
-import android.os.IBinder
-import android.os.Looper
-
-/**
- * Keeps this process out of Android's freezer while the app is in another app's shadow, so the
- * machine socket survives being switched away from.
- *
- * WHY THIS EXISTS AT ALL. A backgrounded app becomes a "cached" process, and Android freezes cached
- * processes — measured on a Pixel 8 Pro at around 30 seconds. A frozen process runs no code, so it
- * cannot answer the backend's liveness ping, and the backend drops a client that has been silent
- * past its deadline (`CLIENT_IDLE_DEADLINE_MS` in `backend/src/lib/hub.ts`). Coming back then costs
- * a full redial: socket, machine select, E2EE handshake, desk read, terminal re-attach. A process
- * holding a foreground service is not cached, so none of that happens.
- *
- * WHAT IT COSTS. A notification, for as long as the hold lasts. That is not a design choice — it is
- * the bargain Android offers for running while out of sight, and there is no version of this without
- * it. The channel is IMPORTANCE_LOW so it never makes a sound, and the hold is taken only on the way
- * out and dropped on the way back, so the notification is gone whenever the app is on screen.
- *
- * WHY THE HOLD EXPIRES. [EXTRA_LIMIT_MS] stops this outliving its purpose. The complaint it answers
- * is switching apps for a minute; a phone put in a pocket for the afternoon does not need its socket
- * held, and holding it anyway would burn the `dataSync` allowance Android 14 caps at six hours a day
- * — with the notification sitting there the whole time. Past the limit the service lets go, the app
- * is frozen like any other, and coming back costs the ordinary reconnect it always did.
- */
-class AwakeService : Service() {
- private val handler = Handler(Looper.getMainLooper())
- private var expiry: Runnable? = null
-
- override fun onBind(intent: Intent?): IBinder? = null
-
- override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
- // Promoted before anything else: Android gives a started service a few seconds to call this and
- // kills the app with an ANR-like crash if it does not.
- promote()
- // A second hold replaces the first one's clock rather than adding to it.
- expiry?.let(handler::removeCallbacks)
- val limitMs = intent?.getLongExtra(EXTRA_LIMIT_MS, DEFAULT_LIMIT_MS) ?: DEFAULT_LIMIT_MS
- val stop = Runnable { stopSelf() }
- expiry = stop
- handler.postDelayed(stop, limitMs)
- // Deliberately NOT sticky. Android restarting this on its own would put the notification back
- // with no app awake to release it.
- return START_NOT_STICKY
- }
-
- override fun onDestroy() {
- expiry?.let(handler::removeCallbacks)
- expiry = null
- super.onDestroy()
- }
-
- private fun promote() {
- channel()
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
- startForeground(NOTIFICATION_ID, notification(), ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
- } else {
- startForeground(NOTIFICATION_ID, notification())
- }
- }
-
- private fun channel() {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
- val manager = getSystemService(NotificationManager::class.java) ?: return
- if (manager.getNotificationChannel(CHANNEL_ID) != null) return
- val channel = NotificationChannel(
- CHANNEL_ID,
- "Staying connected",
- // Low, not MIN: a MIN channel is collapsed into the status bar without a line in the shade,
- // which reads as the app hiding what it is doing. Low is silent but says so plainly.
- NotificationManager.IMPORTANCE_LOW,
- )
- channel.description =
- "Shown while Harness holds your machine connection open in the background."
- channel.setShowBadge(false)
- manager.createNotificationChannel(channel)
- }
-
- private fun notification(): Notification {
- val open = PendingIntent.getActivity(
- this,
- 0,
- Intent(this, MainActivity::class.java),
- PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
- )
- val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- Notification.Builder(this, CHANNEL_ID)
- } else {
- @Suppress("DEPRECATION") Notification.Builder(this)
- }
- return builder
- .setContentTitle("Harness is connected")
- .setContentText("Keeping your machine reachable while you are in another app")
- // A platform icon: the app ships no monochrome notification drawable, and a launcher mipmap
- // used here is drawn as a white blob on anything since Lollipop.
- .setSmallIcon(android.R.drawable.stat_notify_sync)
- .setContentIntent(open)
- .setOngoing(true)
- // No timestamp: "3 minutes ago" on a notice about right now reads as a stale one.
- .setShowWhen(false)
- .build()
- }
-
- companion object {
- const val ACTION_HOLD = "ai.autonomous.harness.android.HOLD"
- const val EXTRA_LIMIT_MS = "limitMs"
-
- /** Long enough for an errand in another app, short enough not to outlive one. */
- const val DEFAULT_LIMIT_MS = 10L * 60L * 1000L
-
- private const val CHANNEL_ID = "harness_awake"
- private const val NOTIFICATION_ID = 0x48524E53
- }
-}
diff --git a/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt b/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt
index aab58b2b4..a0c4ad7da 100644
--- a/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt
+++ b/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt
@@ -1,6 +1,5 @@
package ai.autonomous.harness.android
-import android.content.Intent
import android.os.Build
import android.provider.Settings
import io.flutter.embedding.android.FlutterActivity
@@ -26,49 +25,5 @@ class MainActivity : FlutterActivity() {
)
)
}
-
- // `harness/awake` — hold the process out of Android's freezer while the app is off screen, so
- // the machine socket is still there on the way back (Dart: `lib/core/background_hold.dart`).
- MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "harness/awake")
- .setMethodCallHandler { call, result ->
- when (call.method) {
- "hold" -> result.success(hold(call.argument<Int>("limitMs")))
- "release" -> { releaseHold(); result.success(true) }
- else -> result.notImplemented()
- }
- }
- }
-
- /** True when the hold was taken. False is a normal answer, not an error — see below. */
- private fun hold(limitMs: Int?): Boolean {
- val intent = Intent(this, AwakeService::class.java).setAction(AwakeService.ACTION_HOLD)
- if (limitMs != null && limitMs > 0) {
- intent.putExtra(AwakeService.EXTRA_LIMIT_MS, limitMs.toLong())
- }
- return try {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) startForegroundService(intent)
- else startService(intent)
- true
- } catch (e: Exception) {
- // ⚠️ **Swallowed on purpose, and this is the one place it can happen.** Since Android 12 a
- // foreground service may not be STARTED from the background, and the answer to "is this app
- // in the background yet" belongs to the system, not to us: Dart asks on its way out, which is
- // `onPause` — an activity still visible, and so still allowed — but a hold taken a moment too
- // late throws `ForegroundServiceStartNotAllowedException`. Losing the hold means the socket
- // drops and is redialled, which is exactly what happened before this existed. Crashing the app
- // over it would be the far worse failure.
- false
- }
- }
-
- // ⚠️ `stopService`, not a RELEASE intent. Sending an intent would START the service in order to
- // tell it to stop — which means a release with nothing to release leaves a service behind for a
- // moment, one that never called `startForeground`. Stopping something not running is a no-op.
- private fun releaseHold() {
- try {
- stopService(Intent(this, AwakeService::class.java))
- } catch (e: Exception) {
- // Nothing to release, or the service is already gone.
- }
}
}
diff --git a/mobile/lib/core/background_hold.dart b/mobile/lib/core/background_hold.dart
deleted file mode 100644
index 25d810df1..000000000
--- a/mobile/lib/core/background_hold.dart
+++ /dev/null
@@ -1,117 +0,0 @@
-import 'package:flutter/foundation.dart';
-import 'package:flutter/services.dart';
-
-import 'harness_file_store.dart';
-import 'local_key_value_store.dart';
-
-/// Whether the app keeps its machine connection alive while it is in another
-/// app's shadow — off unless the person asks for it.
-///
-/// WHAT IT FIXES. Switching to another app and back used to cost a reconnect.
-/// Android makes a backgrounded app a "cached" process and freezes cached
-/// processes — measured on a Pixel 8 Pro at around 30 seconds. A frozen process
-/// runs no code, so it cannot answer the backend's liveness ping, and the
-/// backend drops a client that has gone quiet past its deadline
-/// (`CLIENT_IDLE_DEADLINE_MS`, `backend/src/lib/hub.ts`). Coming back then costs
-/// the whole chain again: dial, machine select, E2EE handshake, desk read,
-/// terminal re-attach. Android exempts a process holding a foreground service
-/// from the freezer, so with this on none of that happens.
-///
-/// ⚠️ **WHY IT IS A SETTING AND NOT SIMPLY THE BEHAVIOUR.** Running while out of
-/// sight costs a notification the person cannot dismiss — that is Android's
-/// bargain, not our choice, and there is no version of this feature without it.
-/// A notification nobody asked for, appearing every time they leave the app, is
-/// worse than the reconnect it saves for somebody who never noticed the
-/// reconnect. So it defaults off and says what it costs.
-///
-/// ⚠️ **Android only.** iOS does not offer this bargain at all: a backgrounded
-/// app is suspended, and no entitlement short of a real background mode (audio,
-/// location, VoIP) changes that. [available] is false there and the row is not
-/// drawn, rather than a switch that would quietly do nothing.
-class BackgroundHoldStore extends ValueNotifier<bool> {
- BackgroundHoldStore({LocalKeyValueStore? storage, MethodChannel? channel})
- : _storage = storage ?? HarnessFileStore.shared,
- _channel = channel ?? const MethodChannel(_channelName),
- super(false);
-
- static const _key = 'background_hold';
- static const _channelName = 'harness/awake';
-
- /// How long ONE hold may last, handed to the service so it expires by itself.
- ///
- /// ⚠️ **A hold has to end even if nothing releases it.** The complaint this
- /// answers is an errand in another app; a phone put in a pocket for the
- /// afternoon does not need its socket held, and holding it anyway would sit on
- /// the `dataSync` allowance Android 14 caps at six hours a day — with the
- /// notification showing the whole time — and then be cut off by the system
- /// mid-afternoon anyway. Past this the app is frozen like any other and the
- /// ordinary reconnect takes over, which is what used to happen at 30 seconds.
- static const limit = Duration(minutes: 10);
-
- final LocalKeyValueStore _storage;
- final MethodChannel _channel;
-
- /// Whether this platform offers the bargain at all — see the note above.
- bool get available =>
- !kIsWeb && defaultTargetPlatform == TargetPlatform.android;
-
- Future<void> load() async {
- if (!available) return;
- try {
- value = await _storage.read(_key) == 'on';
- } on Exception {
- // The default stands for this run.
- }
- }
-
- Future<void> setEnabled(bool enabled) async {
- if (!available || enabled == value) return;
- value = enabled;
- // Turned off while a hold is live — the app is on screen, so there is
- // normally nothing to drop, but a hold left running would keep its
- // notification until its own clock ran out.
- if (!enabled) await release();
- try {
- await _storage.write(_key, enabled ? 'on' : 'off');
- } on Exception {
- // Kept in memory for this run.
- }
- }
-
- /// Asks the OS to keep this process running. Called on the way OUT of the
- /// foreground, and a no-op when the setting is off.
- ///
- /// ⚠️ **Must be asked while the app is still visible.** Since Android 12 a
- /// foreground service may not be STARTED from the background, so this belongs
- /// to `inactive` — the activity paused but still on screen — and not to
- /// `paused`, which is one step too late. The native side answers false rather
- /// than throwing when the system refuses; see MainActivity.kt.
- Future<bool> hold() async {
- if (!available || !value) return false;
- try {
- final taken = await _channel.invokeMethod<bool>('hold', {
- 'limitMs': limit.inMilliseconds,
- });
- return taken ?? false;
- } on PlatformException {
- return false;
- } on MissingPluginException {
- return false;
- }
- }
-
- /// Lets go, and takes the notification with it. Safe to call with no hold
- /// outstanding, which is the common case.
- Future<void> release() async {
- if (!available) return;
- try {
- await _channel.invokeMethod<bool>('release');
- } on PlatformException {
- // Nothing to release.
- } on MissingPluginException {
- // Nothing to release.
- }
- }
-}
-
-final backgroundHoldStore = BackgroundHoldStore();
diff --git a/mobile/lib/core/startup.dart b/mobile/lib/core/startup.dart
index b3997350e..8513bebd5 100644
--- a/mobile/lib/core/startup.dart
+++ b/mobile/lib/core/startup.dart
@@ -7,7 +7,6 @@ import '../shared/theme/appearance_prefs_store.dart';
import '../stats/harness_stats.dart';
import '../terminal/terminal_font_store.dart';
import '../terminal/terminal_theme_store.dart';
-import 'background_hold.dart';
import 'device_name.dart';
/// Every preference that has to be in place BEFORE the first frame.
@@ -29,7 +28,6 @@ Future<void> loadPersistedSettings({
HarnessStats? stats,
VoiceLanguageStore? voiceLanguage,
PhoneNameStore? phoneName,
- BackgroundHoldStore? backgroundHold,
}) async {
// What the OS calls this phone, asked now so it is on hand by the first
// `terminal_open`; not awaited — a slow answer must not hold the first frame,
@@ -77,14 +75,5 @@ Future<void> loadPersistedSettings({
// The person's own name for this phone; read late, the first terminal it
// took would introduce it by the OS's name instead.
StartupTrace.time('prefs.phoneName', (phoneName ?? phoneNameStore).load),
- // Read before the first frame like the rest, and for a sharper reason than
- // flicker: the shell asks this store on the very first time the app leaves
- // the foreground, which can be seconds after launch. Loaded late, that first
- // switch away would be read as "off" and drop the connection the person had
- // turned the setting on to keep.
- StartupTrace.time(
- 'prefs.backgroundHold',
- (backgroundHold ?? backgroundHoldStore).load,
- ),
]);
}
diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dart
index 033f16c67..0eaf9f3e9 100644
--- a/mobile/lib/phone/phone_shell.dart
+++ b/mobile/lib/phone/phone_shell.dart
@@ -2,7 +2,6 @@ import 'dart:async';
import 'package:flutter/material.dart';
-import 'package:harness_mobile/core/background_hold.dart';
import 'package:harness_mobile/state/app_state.dart';
import '../p2p/phone_terminal_p2p.dart';
@@ -63,8 +62,6 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
- _lifecycle =
- WidgetsBinding.instance.lifecycleState ?? AppLifecycleState.resumed;
final notices = widget.notifier.agentNotices.system;
notices.opened.addListener(_openNoticedAgent);
// Signed in is the first moment a notice could be worth anything, so it is
@@ -75,9 +72,7 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
- widget.notifier.agentNotices.system.opened.removeListener(
- _openNoticedAgent,
- );
+ widget.notifier.agentNotices.system.opened.removeListener(_openNoticedAgent);
_linkedMachineId.dispose();
_openAgentRequest.dispose();
for (final controller in _heroControllers.values) {
@@ -169,35 +164,8 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
/// start; the WebSocket underneath it was not, so a phone coming back sat through a backoff that
/// had already climbed to its 30s ceiling — the machine list saying "Connecting…" at somebody
/// who was looking straight at it, with a network that would have answered at once.
- /// The lifecycle state as of the last callback, so the step OUT of the
- /// foreground can be told apart from the one back into it.
- ///
- /// ⚠️ **Both directions pass through `inactive`** — resumed → inactive →
- /// hidden → paused going away, and the same list backwards coming home. The
- /// hold below is taken on `inactive` because it is the last moment Android
- /// still allows it; without this guard it would be taken a second time on the
- /// way in, a few milliseconds before being released, and the notification
- /// would flash on every return.
- AppLifecycleState _lifecycle = AppLifecycleState.resumed;
-
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
- final was = _lifecycle;
- _lifecycle = state;
- // Leaving the foreground: ask the OS to keep this process running, so the
- // machine socket is still there on the way back rather than being redialled.
- // A no-op unless the person turned it on — see [BackgroundHoldStore].
- if (state != AppLifecycleState.resumed) {
- if (was == AppLifecycleState.resumed) {
- unawaited(backgroundHoldStore.hold());
- }
- } else {
- // Back on screen, so the hold has nothing left to protect and its
- // notification would only be clutter. Released on every resume, not just
- // the ones that took a hold: the service expires on its own clock, and a
- // release with nothing to release is a no-op.
- unawaited(backgroundHoldStore.release());
- }
if (state == AppLifecycleState.paused) {
// The other half of the resume below: work that only makes sense in
// front of somebody stops here. The sockets are not touched — the OS
diff --git a/mobile/lib/phone/settings_page.dart b/mobile/lib/phone/settings_page.dart
index 65ce02929..65fc98e55 100644
--- a/mobile/lib/phone/settings_page.dart
+++ b/mobile/lib/phone/settings_page.dart
@@ -5,7 +5,6 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:harness_mobile/core/app_version.dart';
-import 'package:harness_mobile/core/background_hold.dart';
import 'package:harness_mobile/core/device_name.dart';
import 'package:harness_mobile/shared/widgets/app_dialog.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
@@ -129,17 +128,6 @@ class _Body extends StatelessWidget {
buildStatsSettingsRow(context, notifier),
],
),
- // Android only, and the row is absent rather than disabled elsewhere —
- // see [BackgroundHoldStore.available].
- if (backgroundHoldStore.available) ...[
- const SettingsCaption('Connection'),
- SettingsGroup(children: [_BackgroundHoldRow()]),
- const SettingsNote(
- 'Android only runs an app that is out of sight if it shows a '
- 'notification, so one appears while you are in another app. The hold '
- 'lets go by itself after ten minutes.',
- ),
- ],
const SettingsCaption('Terminal'),
SettingsGroup(
children: [
@@ -429,40 +417,6 @@ class _TerminalThemeRow extends StatelessWidget {
);
}
-/// Whether to keep the machine connection alive while the app is off screen.
-///
-/// ⚠️ **The detail says what it costs, not what it does.** "Stay connected" already
-/// says what it does; what somebody cannot guess is that saying yes puts a
-/// notification in their status bar every time they leave the app. A switch whose
-/// price is only discovered after flipping it is a switch people turn on once and
-/// then hunt for. See [BackgroundHoldStore] for why the price is not ours to waive.
-class _BackgroundHoldRow extends StatelessWidget {
- @override
- Widget build(BuildContext context) => ValueListenableBuilder<bool>(
- valueListenable: backgroundHoldStore,
- builder: (context, enabled, _) {
- AppTheme.watch(context);
- return SettingsRow(
- title: 'Stay connected in the background',
- detail: enabled
- ? 'Shows a notification while you are in another app'
- : 'Switching apps reconnects after about 30 seconds',
- leading: Icon(
- LucideIcons.plug300,
- size: 18,
- color: AppPalette.textSecondary,
- ),
- trailing: Switch.adaptive(
- value: enabled,
- onChanged: (value) =>
- unawaited(backgroundHoldStore.setEnabled(value)),
- ),
- onTap: () => unawaited(backgroundHoldStore.setEnabled(!enabled)),
- );
- },
- );
-}
-
/// The app's palette — the six [HarnessPalette] choices the desktop lays out as swatch cards.
///
/// A sheet of names rather than a grid of previews, and the difference is the screen: the desktop's