The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(os): a computer set up from the phone signs in and pairs on a slow Wi-Fi (#2737)
Bubu-Dudu-52hz9523a7dbb6a6
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex b7423b306..915ae5e7d 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -1,4 +1,5 @@#!/usr/bin/env node+import './lib/connectWait.js'import './config/startHome.js'import './config/loadEnv.js'import { runDevicesCommand } from './devices/client.js'diff --git a/cli/src/entry.ts b/cli/src/entry.tsindex 82702a525..713495271 100644--- a/cli/src/entry.ts+++ b/cli/src/entry.ts@@ -13,6 +13,7 @@** Nothing heavy may be imported statically here: it would be evaluated by every process.*/+import './lib/connectWait.js'import { fileURLToPath } from 'node:url'const [, , command, name] = process.argvdiff --git a/cli/src/leanCoreEntry.ts b/cli/src/leanCoreEntry.tsindex d583efbdb..b80d1ea48 100644--- a/cli/src/leanCoreEntry.ts+++ b/cli/src/leanCoreEntry.ts@@ -17,6 +17,7 @@* update runs it. Without it this core cannot know the CLI, and dies before it beats: its master then* starts it from cli.js (harnessd/leanServices.ts).*/+import './lib/connectWait.js'import { LEAN_CORE_SCRIPT_ENV } from './harnessd/protocol.js'const [, , command] = process.argvdiff --git a/cli/src/leanEntry.ts b/cli/src/leanEntry.tsindex d48fc9918..db8075012 100644--- a/cli/src/leanEntry.ts+++ b/cli/src/leanEntry.ts@@ -10,6 +10,7 @@* (masterProcess.ts `startMasterFromBundle`) and starts the services from it. The core has an entry of* its own, built apart (leanCoreEntry.ts), and the CLI always runs from cli.js.*/+import './lib/connectWait.js'import { fileURLToPath } from 'node:url'const [, , command, name] = process.argvdiff --git a/cli/src/lib/connectWait.ts b/cli/src/lib/connectWait.tsnew file mode 100644index 000000000..24467fff6--- /dev/null+++ b/cli/src/lib/connectWait.ts@@ -0,0 +1,12 @@+import { setDefaultAutoSelectFamilyAttemptTimeout } from 'node:net'++/**+ * How long each address of a host is tried before the next, for every connection this process opens, `fetch` included.+ * Node's 250 ms gave up on both of the backend's IPv4 addresses over a slow Wi-Fi (a ping of 324 ms on 2026-11-02),+ * and `fetch` failed with no reason but "fetch failed": about one call in ten on the Dell, the sign-in of a computer+ * set up from the phone two seconds after it joined the Wi-Fi (MSI, 2026-11-03), and the Swarm reads of Add your+ * computers. With 2 s, 0 in 60 failed on the same Wi-Fi. Imported first by each entry, before anything connects.+ */+export const CONNECT_ATTEMPT_MS = 2_000++setDefaultAutoSelectFamilyAttemptTimeout(CONNECT_ATTEMPT_MS)diff --git a/cli/src/lib/harnessDefaults.spec.ts b/cli/src/lib/harnessDefaults.spec.tsindex 1186e5c5e..6066a3141 100644--- a/cli/src/lib/harnessDefaults.spec.ts+++ b/cli/src/lib/harnessDefaults.spec.ts@@ -55,3 +55,12 @@ it("keeps the model a package pins, with the launch's approvals, and adds no eff// An empty name is no choice: the default applies.expect(JSON.parse(freshHarnessEnvironment('opencode', { OPENCODE_CONFIG_CONTENT: '{"model":""}' }).OPENCODE_CONFIG_CONTENT!).model).toBe(DEFAULT_HARNESS_MODEL)})++it('pins no model on Harness OS: OpenCode starts on its own free model there, with the approvals', () => {+ const mcp = { harnessd: { type: 'local', command: ['harness', 'pair', 'mcp'] } }+ const result = JSON.parse(freshHarnessEnvironment('opencode', { OPENCODE_CONFIG_CONTENT: JSON.stringify({ mcp }) }, false, 'auto', true).OPENCODE_CONFIG_CONTENT!)+ expect(result).toEqual({ mcp, permission: 'allow' })+ expect(JSON.parse(freshHarnessEnvironment('opencode', {}, false, 'ask', true).OPENCODE_CONFIG_CONTENT!)).toEqual({ permission: 'ask' })+ // Every other computer keeps the default.+ expect(JSON.parse(freshHarnessEnvironment('opencode', {}, false, 'auto', false).OPENCODE_CONFIG_CONTENT!).model).toBe(DEFAULT_HARNESS_MODEL)+})diff --git a/cli/src/lib/harnessDefaults.ts b/cli/src/lib/harnessDefaults.tsindex cbaae76df..3554d3cd5 100644--- a/cli/src/lib/harnessDefaults.ts+++ b/cli/src/lib/harnessDefaults.ts@@ -1,4 +1,5 @@import type { AgentEngine } from '../engines/types.js'+import { existsSync } from 'node:fs'export const DEFAULT_HARNESS_ENGINE = 'opencode' as constexport const DEFAULT_HARNESS_MODEL = 'opencode/muse-spark-1.3-contributor-free'@@ -31,16 +32,24 @@ function withoutPackageModel(env: Record<string, string>): Record<string, stringreturn { ...env, OPENCODE_CONFIG_CONTENT: JSON.stringify(config) }}+/** Whether this is a Harness OS computer: its updater is there (services/osDevice.ts reads it the same way). */+export function onHarnessOs(): boolean {+ return process.env.HARNESS_OS === '1' || existsSync('/usr/lib/harness-os/live_update.py')+}+/** Fresh own-provider launches only. Restores, explicit model routes and a package's own model keep their choices. */export function freshHarnessEnvironment(engine: AgentEngine, env: Record<string, string> = {},- explicitRoute = false, permissionMode = DEFAULT_HARNESS_PERMISSION): Record<string, string> {+ explicitRoute = false, permissionMode = DEFAULT_HARNESS_PERMISSION, harnessOs = onHarnessOs()): Record<string, string> {if (engine !== DEFAULT_HARNESS_ENGINE) return envif (explicitRoute) return withoutPackageModel(env)const config = JSON.parse(env.OPENCODE_CONFIG_CONTENT || '{}')// A package that names its own model keeps it. Memories reads a person's whole message history, so it// pins a free model whose provider keeps nothing and trains on nothing (store/agents/memories/harness.json)// rather than the default above, whose terms let its maker train on what it is sent.- if (typeof config.model === 'string' && config.model) {+ // Harness OS pins none (owner, 2026-11-03): OpenCode starts on upstream's own free model there, as its+ // skel config does since the pinned Muse Spark Free answered "Model is unavailable". Every other computer+ // keeps the default above.+ if ((typeof config.model === 'string' && config.model) || harnessOs) {return { ...env, OPENCODE_CONFIG_CONTENT: JSON.stringify({ ...config, permission: opencodePermission(config, permissionMode) }) }}const modelId = DEFAULT_HARNESS_MODEL.split('/')[1]!diff --git a/mobile/lib/phone/add_device/add_device_page.dart b/mobile/lib/phone/add_device/add_device_page.dartindex 97b89c9e0..a8ceeee0f 100644--- a/mobile/lib/phone/add_device/add_device_page.dart+++ b/mobile/lib/phone/add_device/add_device_page.dart@@ -253,11 +253,39 @@ class _AddDevicePageState extends State<AddDevicePage> {/// How long the device gets to join the Wi-Fi, sign in and show up in the account.static const _comeOnline = Duration(seconds: 75);+ /// How long Android looks for the device's hotspot before it answers `unavailable`+ /// (MainActivity.kt `requestNetwork`).+ static const _hotspotSearch = Duration(seconds: 120);++ /// The wait on screen now, for its bar and the time left under it: when it ends and how long it+ /// is. Null when nothing is being waited out. Each wait ends in an answer, so nobody waits for+ /// ever (owner, 2026-11-03: a computer that joined the Wi-Fi but did not sign in left the phone on+ /// a spinner for minutes, then said it was not chosen).+ DateTime? _waitUntil;+ Duration _waitFor = Duration.zero;+ Timer? _tick;++ void _countdown(Duration span) {+ _waitFor = span;+ _waitUntil = DateTime.now().add(span);+ _tick?.cancel();+ _tick = Timer.periodic(const Duration(seconds: 1), (_) {+ if (mounted) setState(() {});+ });+ }++ void _stopCountdown() {+ _tick?.cancel();+ _tick = null;+ _waitUntil = null;+ }+AppNotifier get _app => widget.notifier;@overridevoid dispose() {_poll?.cancel();+ _tick?.cancel();_backWatch?.cancel();unawaited(_hotspot.leave());_ssid.dispose();@@ -269,6 +297,8 @@ class _AddDevicePageState extends State<AddDevicePage> {void _show(_Step step, {String error = ''}) {if (!mounted) return;+ // A wait belongs to the page it was started on; any other page, or an answer, ends it.+ if (step != _step || error.isNotEmpty) _stopCountdown();setState(() {_step = step;_error = error;@@ -354,6 +384,8 @@ class _AddDevicePageState extends State<AddDevicePage> {// one came back "This ticket was already used or has expired".if (_ticketSent && !await _freshTicket()) return;if (SetupHotspot.joinsByItself) {+ // Back for a device that did not come online: as long as Android looks for its hotspot.+ if (_retrying) _countdown(_hotspotSearch);// The same device again once it has started: only its own name in Android's list.final joined = await _hotspot.join(// Back after a locked setup that did not come online: the same device, on setup.py's@@ -368,9 +400,16 @@ class _AddDevicePageState extends State<AddDevicePage> {});}if (joined.state == 'unavailable') {+ final ssid = _ssid.text.trim();_show(_Step.join,- error: 'Intern 3 was not chosen. Check it is plugged in and nearby: its Wi-Fi is named "Harness-…".',+ // After every wait: the device neither came online nor came back. Said as an end, with+ // what to do, not as a hotspot the person failed to pick.+ error: _retrying+ ? 'Intern 3 did not come online${ssid.isEmpty ? '' : ' on "$ssid"'}, and its Wi-Fi '+ '"Harness-…" did not come back. It may be on the Wi-Fi without being signed in: '+ 'check its screen, then tap Try again.'+ : 'Intern 3 was not chosen. Check it is plugged in and nearby: its Wi-Fi is named "Harness-…".',);return;}@@ -397,6 +436,7 @@ class _AddDevicePageState extends State<AddDevicePage> {_poll?.cancel();_device = info;_retrying = false;+ _stopCountdown();if (info['locked'] == true) {_secret.clear();final protocol = (info['protocol'] as num?)?.toInt() ?? 1;@@ -752,9 +792,9 @@ class _AddDevicePageState extends State<AddDevicePage> {void _wait(String ssid) {_show(_Step.waiting);// A locked one starts first: its disk opens, then the system, then the Wi-Fi and the sign-in.- final deadline = DateTime.now().add(- _lockedSetup ? _comeOnline * 2 : _comeOnline,- );+ final span = _lockedSetup ? _comeOnline * 2 : _comeOnline;+ final deadline = DateTime.now().add(span);+ _countdown(span);_poll?.cancel();_poll = Timer.periodic(const Duration(seconds: 3), (_) async {if (!mounted || _step != _Step.waiting) return;@@ -886,11 +926,16 @@ class _AddDevicePageState extends State<AddDevicePage> {say('Open Settings ▸ Wi-Fi on this phone and choose "Harness-…". Then come back here.',),- if (_retrying) ...[+ if (_retrying && _error.isEmpty) ...[const SizedBox(height: 12),say(- 'Intern 3 is still trying the Wi-Fi. Its hotspot comes back within a minute.',+ 'Intern 3 did not come online yet. Looking for its Wi-Fi "Harness-…" again: if a '+ 'try failed, it says why there.',),+ if (_waitUntil != null) ...[+ const SizedBox(height: 12),+ _WaitBar(until: _waitUntil!, span: _waitFor),+ ],],if (_unlocked) ...[const SizedBox(height: 12),@@ -1148,7 +1193,10 @@ class _AddDevicePageState extends State<AddDevicePage> {onPressed: () => unawaited(_join()),)else ...[- const Center(child: CircularProgressIndicator(strokeWidth: 2)),+ if (_waitUntil != null)+ _WaitBar(until: _waitUntil!, span: _waitFor)+ else+ const Center(child: CircularProgressIndicator(strokeWidth: 2)),const SizedBox(height: 20),// Not waiting out the whole wait: back to the device now. Once it has given up on the// Wi-Fi (in under a minute) its hotspot is back, and its Wi-Fi list comes up with why.@@ -1190,3 +1238,31 @@ class _AddDevicePageState extends State<AddDevicePage> {? 'Good signal': 'Weak signal';}++/// A wait that ends: a bar filling up to [until]. No time under it (owner, 2026-11-03): the bar+/// alone says it is going and that it ends.+class _WaitBar extends StatelessWidget {+ const _WaitBar({required this.until, required this.span});++ final DateTime until;+ final Duration span;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ final left = until.difference(DateTime.now());+ final done = span.inMilliseconds == 0+ ? 1.0+ : (1 - left.inMilliseconds / span.inMilliseconds).clamp(0.0, 1.0);+ return ClipRRect(+ key: const Key('add-device-wait-bar'),+ borderRadius: BorderRadius.circular(3),+ child: LinearProgressIndicator(+ value: done,+ minHeight: 6,+ color: tty.green,+ backgroundColor: tty.green.withValues(alpha: 0.18),+ ),+ );+ }+}diff --git a/mobile/lib/phone/link_page.dart b/mobile/lib/phone/link_page.dartindex a34456071..e310a287f 100644--- a/mobile/lib/phone/link_page.dart+++ b/mobile/lib/phone/link_page.dart@@ -100,9 +100,17 @@ class _LinkPageState extends State<LinkPage> {if (machine == null || closed) {_leaving = true;navigator.maybePop();+ return;}+ // Waiting for its key, or done waiting: the page swaps between the wait and the form.+ final awaiting = machine.awaitingKey;+ if (awaiting != _awaiting) setState(() => _awaiting = awaiting);}+ /// What [build] last drew: the wait for the machine's key ([MachineState.awaitingKey]).+ late bool _awaiting =+ widget.notifier.stateOf(widget.machineId)?.awaitingKey ?? false;+@overrideWidget build(BuildContext context) {AppTheme.watch(context);@@ -128,7 +136,11 @@ class _LinkPageState extends State<LinkPage> {alignment: Alignment.centerRight,child: PhoneSettingsButton(notifier: widget.notifier),),- if (machine != null)+ // Its key not in the account's log yet: it comes in by itself, so no QR and no password+ // are asked for — only once the wait has run out ([MachineState.keyAwaitLimit]).+ if (machine != null && machine.awaitingKey)+ Expanded(child: _AwaitingKey(name: machine.machine.displayName))+ else if (machine != null)Expanded(child: UnlockComputer(notifier: widget.notifier,@@ -148,3 +160,42 @@ class _LinkPageState extends State<LinkPage> {);}}++/// While [name]'s key is not in the account's device log yet ([MachineState.awaitingKey]): what+/// the password form would have stood for, said as the wait it is. It goes by itself, to the+/// agents once the key lands, to the form if it never does.+class _AwaitingKey extends StatelessWidget {+ const _AwaitingKey({required this.name});++ final String name;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ return ListView(+ key: const Key('link-awaiting-key'),+ padding: const EdgeInsets.fromLTRB(Tty.origin, 12, Tty.origin, 24),+ children: [+ Text(+ 'Connecting to $name',+ style: tty.style(size: 24, weight: FontWeight.w600),+ ),+ const SizedBox(height: 12),+ Text(+ '$name is setting up its secure link to your account. It opens here by itself in a '+ 'moment: nothing to scan or type.',+ style: tty.style(size: TtySize.row, color: tty.faint),+ ),+ const SizedBox(height: 24),+ ClipRRect(+ borderRadius: BorderRadius.circular(3),+ child: LinearProgressIndicator(+ minHeight: 6,+ color: tty.green,+ backgroundColor: tty.green.withValues(alpha: 0.18),+ ),+ ),+ ],+ );+ }+}diff --git a/mobile/lib/phone/machines_tab.dart b/mobile/lib/phone/machines_tab.dartindex d8a7c1cc5..068daa3c6 100644--- a/mobile/lib/phone/machines_tab.dart+++ b/mobile/lib/phone/machines_tab.dart@@ -317,7 +317,10 @@ class _Body extends StatelessWidget {? 'nothing running': '$count harness${count == 1 ? '' : 'es'}',),- PhoneMachineStatus.connecting => (tty.faint, 'one moment…'),+ PhoneMachineStatus.connecting => (+ tty.faint,+ state.awaitingKey ? 'setting up its secure link…' : 'one moment…',+ ),PhoneMachineStatus.needsPassword => (tty.yellow,'tap to unlock: scan its code',diff --git a/mobile/lib/phone/phone_status.dart b/mobile/lib/phone/phone_status.dartindex 1bb955c10..7e95e783a 100644--- a/mobile/lib/phone/phone_status.dart+++ b/mobile/lib/phone/phone_status.dart@@ -31,7 +31,13 @@ PhoneMachineStatus phoneMachineStatusOf(MachineState machine) {// fail. The password is worth asking for once there is something to give it to, which is what the// desktop's "Offline · Link required" already says.if (machine.nodeOnline == false) return PhoneMachineStatus.offline;- if (machine.needsLink) return PhoneMachineStatus.needsPassword;+ // Its key not in the account's log yet ([MachineState.awaitingKey]): late, not locked. It comes+ // in by itself once the key lands; only a wait that runs out asks for its password.+ if (machine.needsLink) {+ return machine.awaitingKey+ ? PhoneMachineStatus.connecting+ : PhoneMachineStatus.needsPassword;+ }final answering =machine.connectionStatus == ConnectionStatus.connected &&machine.agentLoadStatus != AgentLoadStatus.loading;diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex bf0d48d1a..8f5b06e0e 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -307,6 +307,23 @@ class MachineState {// connect. The CLI owns E2EE entirely now; this is just "is trust established yet", not a// crypto/pairing state the app has any data for.bool needsLink = false;++ /// When this machine was first refused while the account's device key log named no key for it:+ /// a computer that signed in a moment ago and has not put its key in yet, not one to pair by+ /// hand. Null otherwise ([AppNotifier] `_awaitMachineKey`).+ DateTime? keyAwaitedSince;++ /// How long a machine with no key in the log is shown as connecting before its password form.+ static const keyAwaitLimit = Duration(minutes: 3);++ /// Refused only because its key is not in the log yet, and not for long: the screen says it is+ /// connecting, never "locked" (owner, 2026-11-03: Intern 3, set up from this very phone, sat on+ /// Unlock with a QR and a password it never needed, while its slow Wi-Fi kept its key out).+ bool get awaitingKey =>+ needsLink &&+ keyAwaitedSince != null &&+ DateTime.now().difference(keyAwaitedSince!) < keyAwaitLimit;+List<Agent> agents = [];/// True while [agents] came from the last run's cache rather than from this@@ -2425,6 +2442,8 @@ class AppNotifier extends ChangeNotifier {_forgetAllTrustSettles();_stopDeafPoll();_groupSyncedAt.clear();+ _keyWatch?.cancel();+ _keyWatch = null;}void _onLocalFailure(String machineId, int code, String reason) {@@ -2464,6 +2483,7 @@ class AppNotifier extends ChangeNotifier {machine.needsLink = true;machine.agentLoadStatus = AgentLoadStatus.needsLink;launchMeasurement?.waiting(LaunchWait.locked);+ unawaited(_awaitMachineKey(machine));// …unless the log already vouches for it and this phone's key is new to it: then the machine// has only not read that key yet — see [_redialOnceVouched].unawaited(_redialOnceVouched(machine.machine.machineId));@@ -2603,6 +2623,50 @@ class AppNotifier extends ChangeNotifier {}}+ /// Re-reads the log while a machine waits for its key to land ([MachineState.awaitingKey]), in+ /// case its `device_keys_changed` reaches nobody, and turns the machine to its password form once+ /// the wait is over. Null while no machine waits.+ Timer? _keyWatch;++ @visibleForTesting+ Duration keyWatchEvery = const Duration(seconds: 10);++ /// A machine just refused for want of trust ([_markNeedsLink]) whose key the log does not hold:+ /// most likely one that signed in a moment ago and has not put its key in yet (its daemon could+ /// not reach the backend: Intern 3 on a slow Wi-Fi, 2026-11-03). It reads as connecting, and the+ /// log is read again until the key lands ([_redialNewlyTrusted] dials it then) or+ /// [MachineState.keyAwaitLimit] runs out. A machine whose key the log holds refused this phone+ /// for another reason: its password form, as before.+ Future<void> _awaitMachineKey(MachineState machine) async {+ final machineId = machine.machine.machineId;+ if (_deviceLog == null || await _holdsMachineKey(machineId)) return;+ if (_disposed || !machine.needsLink) return;+ // Kept across refusals: the wait is from the first, not reset by every redial.+ machine.keyAwaitedSince ??= DateTime.now();+ _keyWatch ??= Timer.periodic(keyWatchEvery, (_) => _watchAwaitedKeys());+ notifyListeners();+ }++ void _watchAwaitedKeys() {+ var waiting = false;+ for (final state in machineStates.values) {+ if (state.keyAwaitedSince == null) continue;+ if (!state.needsLink) {+ state.keyAwaitedSince = null;+ continue;+ }+ if (state.awaitingKey) waiting = true;+ }+ if (waiting) {+ unawaited(_deviceLog?.refresh());+ } else {+ _keyWatch?.cancel();+ _keyWatch = null;+ }+ // Every tick: the one past the limit is what turns a machine from connecting to locked.+ if (!_disposed) notifyListeners();+ }+/// Dial [machineId] again from scratch: a refused connection is closed for good, so it is closed/// and replaced.void _redial(String machineId) {@@ -2690,6 +2754,7 @@ class AppNotifier extends ChangeNotifier {_swarmRefused.remove(machineId);_refreshDeviceLogAfterReconnect();machine.needsLink = false;+ machine.keyAwaitedSince = null;// Let in: a later refusal is a new story ([_redialOnceVouched], [_settleTrust])._vouchedRedials.remove(machineId);_forgetTrustSettle(machineId);diff --git a/mobile/test/phone_awaiting_key_test.dart b/mobile/test/phone_awaiting_key_test.dartnew file mode 100644index 000000000..c579792e4--- /dev/null+++ b/mobile/test/phone_awaiting_key_test.dart@@ -0,0 +1,45 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/phone/phone_status.dart';+import 'package:harness_mobile/state/app_state.dart';++/// Intern 3, set up from this phone on a slow Wi-Fi (2026-11-03): refused because its key was not+/// in the account's log yet. Late, not locked — until the wait runs out.+void main() {+ MachineState refused() =>+ MachineState(+ const Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ name: 'Harness-EE07',+ ),+ )+ ..nodeOnline = true+ ..needsLink = true;++ test('a machine whose key has not landed reads as connecting', () {+ final machine = refused()..keyAwaitedSince = DateTime.now();+ expect(machine.awaitingKey, isTrue);+ expect(phoneMachineStatusOf(machine), PhoneMachineStatus.connecting);+ });++ test('the wait runs out: its password form', () {+ final machine = refused()+ ..keyAwaitedSince = DateTime.now().subtract(MachineState.keyAwaitLimit);+ expect(machine.awaitingKey, isFalse);+ expect(phoneMachineStatusOf(machine), PhoneMachineStatus.needsPassword);+ });++ test('a refusal with its key in the log is locked at once', () {+ final machine = refused();+ expect(machine.awaitingKey, isFalse);+ expect(phoneMachineStatusOf(machine), PhoneMachineStatus.needsPassword);+ });++ test('linked, it waits for nothing', () {+ final machine = refused()+ ..keyAwaitedSince = DateTime.now()+ ..needsLink = false;+ expect(machine.awaitingKey, isFalse);+ });+}diff --git a/os/build.sh b/os/build.shindex f66f86798..9781c0ba4 100644--- a/os/build.sh+++ b/os/build.sh@@ -55,6 +55,9 @@ EOF# Use the same source-versioned identity as its update-channel package. An ISO# installation should not immediately be offered this identical build again.python3 tools/build-package.py --runtime "$RUNTIME_DIR" --compositor "$COMPOSITOR_DIR" --output "$BUILD_DIR/repo" --development+# The newest OpenCode Arch has now, not the snapshot's: pacman reads this build's repository first.+# Only the image takes it; an OS update never changes OpenCode (installer.py IgnorePkg).+OPENCODE_PACKAGE=$(python3 tools/opencode_package.py --output "$BUILD_DIR/repo" ${HARNESS_OS_OPENCODE_VERSION:+--version "$HARNESS_OS_OPENCODE_VERSION"})PROFILE_ARGS=(--profile "$PROFILE" --platform "$PLATFORM")if [[ $PLATFORM == apple-t2 ]]; then[[ -n ${HARNESS_OS_T2_BUNDLE:-} ]] || { echo 'Prepare the pinned T2 kernel bundle first.' >&2; exit 1; }@@ -63,7 +66,10 @@ fipython3 tools/configure-boot-profile.py "${PROFILE_ARGS[@]}"REPO_PACKAGES=("$BUILD_DIR/repo/"*.pkg.tar.gz)if [[ $PLATFORM == apple-t2 ]]; then+ # OpenCode's among them.REPO_PACKAGES+=("$BUILD_DIR/repo/"*.pkg.tar.zst)+else+ REPO_PACKAGES+=("$OPENCODE_PACKAGE")firepo-add "$BUILD_DIR/repo/harness-build.db.tar.gz" "${REPO_PACKAGES[@]}"if [[ $PLATFORM == pc ]]; thendiff --git a/os/installer.py b/os/installer.pyindex e1d2dde75..fcf8cf60e 100644--- a/os/installer.py+++ b/os/installer.py@@ -656,8 +656,11 @@ def install_image(config, source, target, progress, resources):write(target, RECOVERY_CONF, recovery_conf(recovery_uuid, platform['kernel'], platform['parameters']))lock = json.loads((target / 'usr/share/harness-os/lock.json').read_text())snapshot = lock['arch_snapshot']+ # IgnorePkg: OpenCode stays the one this image brought (tools/opencode_package.py), newer than its+ # snapshot's; a system update to a later snapshot never changes it (owner, 2026-11-03).write(target, '/etc/pacman.conf','[options]\nArchitecture = auto\nCheckSpace\nSigLevel = Required DatabaseOptional\nLocalFileSigLevel = Optional\n'+ 'IgnorePkg = opencode\n'+ ''.join(f'[{repo}]\nServer = https://archive.archlinux.org/repos/{snapshot}/$repo/os/$arch\n' for repo in ['core', 'extra']))# Retain network configuration explicitly, not the live user's home or credentials.networks = Path('/etc/NetworkManager/system-connections')diff --git a/os/platforms/orangepi-4pro/install-session.sh b/os/platforms/orangepi-4pro/install-session.shindex ca7f1db13..e8aba904f 100755--- a/os/platforms/orangepi-4pro/install-session.sh+++ b/os/platforms/orangepi-4pro/install-session.sh@@ -63,7 +63,6 @@ cat > "$T/etc/skel/.config/opencode/opencode.json" <<'EOF'{"$schema": "https://opencode.ai/config.json","autoupdate": false,- "model": "opencode/muse-spark-1.3-contributor-free","permission": {"external_directory": { "/usr/share/harness-os/*": "allow" },"read": { "/usr/share/harness-os/*": "allow" },diff --git a/os/root/etc/skel/.config/opencode/opencode.json b/os/root/etc/skel/.config/opencode/opencode.jsonindex 7383abedf..b0113fbf9 100644--- a/os/root/etc/skel/.config/opencode/opencode.json+++ b/os/root/etc/skel/.config/opencode/opencode.json@@ -1,7 +1,6 @@{"$schema": "https://opencode.ai/config.json","update": "disable",- "model": "opencode/muse-spark-1.3-contributor-free","permissions": [{ "action": "external_directory", "resource": "/usr/share/harness-os/*", "effect": "allow" },{ "action": "read", "resource": "/usr/share/harness-os/*", "effect": "allow" },diff --git a/os/setup.py b/os/setup.pyindex a4e31a3ee..85665396a 100644--- a/os/setup.py+++ b/os/setup.py@@ -65,6 +65,11 @@ USER = 'me'HOME = Path('/home') / USERSESSION = HOME / '.harness/auth/session.json'COMPUTER_ID = HOME / '.harness/computer-id'+# A sign-in the backend did not answer is tried this many times in all, this many seconds apart.+SIGN_IN_ATTEMPTS = 4+SIGN_IN_PAUSE = 5+# `harness login --ticket` answers that trying again cannot change (cli.ts ticketSignIn).+FINAL_SIGN_IN = ('TICKET_INVALID', 'ALREADY_SIGNED_IN')HOTSPOT = 'harness-setup'ADDRESS = '10.42.0.1'PORT = 80@@ -160,7 +165,13 @@ def hotspot_name(device=None):def signed_in():- return SESSION.is_file()+ """A session the CLI has not marked signed out (cli authSession.ts readAuthSession). A sign-in the+ backend refused stays on disk with its mark, and a computer signed in by that alone took no+ ticket: the Dell, 2026-11-03, said signed in to the phone with an account it could not use."""+ try:+ return not json.loads(SESSION.read_text()).get('signedOut')+ except (OSError, ValueError, AttributeError):+ return Falsedef rows(*args, wait=3):@@ -369,7 +380,18 @@ def sign_in(ticket):FROM_PHONE.touch()except OSError:pass- ok, message = run_sign_in(ticket)+ # A computer that joined the Wi-Fi a moment ago may not reach the backend on its first try: the MSI's+ # sign-in failed with "fetch failed" two seconds after it joined (2026-11-03), and the phone was left+ # with a computer on the Wi-Fi and signed out. A refused ticket is final, and so is a computer signed in.+ for attempt in range(SIGN_IN_ATTEMPTS):+ if attempt:+ log(f'sign-in failed ({message}); trying again')+ time.sleep(SIGN_IN_PAUSE)+ ok, message, again = run_sign_in(ticket)+ if ok or not again:+ break+ # A try whose answer was lost may have signed in all the same: the next then hears ALREADY_SIGNED_IN.+ ok = ok or signed_in()if not ok:FROM_PHONE.unlink(missing_ok=True)return ok, message@@ -380,6 +402,8 @@ def sign_in(ticket):def run_sign_in(ticket):+ """(signed in, why not, whether trying again may help): only the backend's answer about the ticket+ or this computer is final; one that never arrived is not."""try:result = subprocess.run(['/usr/bin/runuser', '-u', USER, '--', '/usr/bin/harness', 'login', '--json','--ticket=' + ticket],@@ -388,16 +412,17 @@ def run_sign_in(ticket):PATH='/usr/local/bin:/usr/bin:/bin',XDG_RUNTIME_DIR=f'/run/user/{pwd.getpwnam(USER).pw_uid}'))except (OSError, KeyError, subprocess.TimeoutExpired) as error:- return False, str(error)+ return False, str(error), Trueif result.returncode == 0:- return True, ''- message = ''+ return True, '', False+ message, code = '', ''for line in result.stdout.splitlines():try:- message = json.loads(line).get('message') or message+ answer = json.loads(line)+ message, code = answer.get('message') or message, answer.get('code') or codeexcept (ValueError, AttributeError):pass- return False, message or result.stderr.strip()[-200:] or 'The sign-in failed.'+ return False, message or result.stderr.strip()[-200:] or 'The sign-in failed.', code not in FINAL_SIGN_INdef join(request, networks, device):diff --git a/os/tests/hardware_update_guest.py b/os/tests/hardware_update_guest.pyindex c3dadeaba..c274612bd 100644--- a/os/tests/hardware_update_guest.py+++ b/os/tests/hardware_update_guest.py@@ -387,7 +387,9 @@ def update(lock, folder, baseline):assert re.findall(r'^\[([^]]+)\]', config, re.M) == ['options', 'core', 'extra']policy = run('pacman-conf', 'SigLevel')assert 'PackageRequired' in policy and 'PackageTrustedOnly' in policy and 'TrustAll' not in policy- assert not re.search(r'^\s*(IgnorePkg|IgnoreGroup|NoUpgrade)\s*=', config, re.M)+ # OpenCode alone stays the image's (installer.py): every other package is fully upgraded.+ assert re.findall(r'^\s*IgnorePkg\s*=.*$', config, re.M) == ['IgnorePkg = opencode']+ assert not re.search(r'^\s*(IgnoreGroup|NoUpgrade)\s*=', config, re.M)verify_metadata(lock, folder, fetch=True)before_checkpoints = {p.parent.name for p in Path('/.snapshots').glob('*/checkpoint.json')}# Use the real API and every normal transaction hook. Never invoke DKMS ordiff --git a/os/tests/test_package.py b/os/tests/test_package.pyindex ab697291f..ae749921d 100644--- a/os/tests/test_package.py+++ b/os/tests/test_package.py@@ -37,10 +37,10 @@ class PackageIdentity(unittest.TestCase):self.assertIn('Super+n', (destination / 'usr/share/harness-os/guide.md').read_text())settings = json.loads((config / 'opencode.json').read_text())self.assertEqual(settings['update'], 'disable')- # One free Zen model that answers with tools (upstream's Exo Free default fails every- # tool call with "Endpoint is unavailable"); providers and instructions stay upstream's.- self.assertEqual(settings['model'], 'opencode/muse-spark-1.3-contributor-free')- self.assertFalse(set(settings) & {'provider', 'providers', 'instructions'})+ # No model of its own (owner, 2026-11-03): OpenCode starts on whatever free model upstream+ # defaults to. The pinned Muse Spark Free answered "Model is unavailable". Providers and+ # instructions stay upstream's too.+ self.assertFalse(set(settings) & {'model', 'small_model', 'provider', 'providers', 'instructions'})self.assertEqual(settings['permissions'], [{'action': 'external_directory', 'resource': '/usr/share/harness-os/*', 'effect': 'allow'},{'action': 'read', 'resource': '/usr/share/harness-os/*', 'effect': 'allow'},diff --git a/os/tests/test_setup.py b/os/tests/test_setup.pyindex 8566023dc..2ac7fce4e 100644--- a/os/tests/test_setup.py+++ b/os/tests/test_setup.py@@ -259,18 +259,80 @@ class FromPhone(unittest.TestCase):marker = Path(folder) / 'set-up-from-phone'with patch.object(setup, 'FROM_PHONE', marker), patch.object(setup, 'signed_in', return_value=False), \patch.object(setup, 'as_user') as as_user:- with patch.object(setup, 'run_sign_in', side_effect=lambda t: (marker.exists(), '')):+ with patch.object(setup, 'run_sign_in', side_effect=lambda t: (marker.exists(), '', False)):self.assertEqual(setup.sign_in('t'), (True, ''))self.assertTrue(marker.exists())# Online in the account only with its daemon, which no screen session may start.as_user.assert_called_once_with('systemctl', '--user', 'start', 'harness-daemon', timeout=150)marker.unlink()- with patch.object(setup, 'run_sign_in', return_value=(False, 'used')):+ with patch.object(setup, 'run_sign_in', return_value=(False, 'used', False)) as run:self.assertEqual(setup.sign_in('t'), (False, 'used'))+ run.assert_called_once()self.assertFalse(marker.exists())as_user.assert_called_once()+class SignedIn(unittest.TestCase):+ def test_a_session_marked_signed_out_is_no_sign_in(self):+ with tempfile.TemporaryDirectory() as folder:+ session = Path(folder) / 'session.json'+ with patch.object(setup, 'SESSION', session):+ self.assertFalse(setup.signed_in())+ session.write_text(json.dumps(dict(accessToken='a')))+ self.assertTrue(setup.signed_in())+ # The Dell, 2026-11-03: refused at its refresh, kept on disk, and the phone's ticket skipped for it.+ session.write_text(json.dumps(dict(accessToken='a', signedOut=dict(reason='refresh-refused'))))+ self.assertFalse(setup.signed_in())+ session.write_text('{')+ self.assertFalse(setup.signed_in())+++class SignInAgain(unittest.TestCase):+ """The MSI, 2026-11-03: its sign-in two seconds after it joined the Wi-Fi never reached the backend."""++ def sign_in(self, answers, signed_in=False):+ with tempfile.TemporaryDirectory() as folder, \+ patch.object(setup, 'FROM_PHONE', Path(folder) / 'set-up-from-phone'), \+ patch.object(setup, 'signed_in', side_effect=[False, signed_in]), \+ patch.object(setup, 'as_user'), patch.object(setup, 'log'), \+ patch.object(setup.time, 'sleep') as sleep, \+ patch.object(setup, 'run_sign_in', side_effect=answers) as run:+ return setup.sign_in('t'), run.call_count, sleep.call_count++ def test_a_backend_not_reached_is_tried_again(self):+ unreached = (False, 'Could not reach the backend: fetch failed', True)+ self.assertEqual(self.sign_in([unreached, unreached, (True, '', False)]), ((True, ''), 3, 2))++ def test_it_gives_up_after_its_tries(self):+ unreached = (False, 'fetch failed', True)+ self.assertEqual(self.sign_in([unreached] * setup.SIGN_IN_ATTEMPTS),+ ((False, 'fetch failed'), setup.SIGN_IN_ATTEMPTS, setup.SIGN_IN_ATTEMPTS - 1))++ def test_a_refused_ticket_is_not_tried_again(self):+ self.assertEqual(self.sign_in([(False, 'This ticket was already used or has expired.', False)]),+ ((False, 'This ticket was already used or has expired.'), 1, 0))++ def test_a_lost_answer_that_signed_in_counts(self):+ answers = [(False, 'timed out', True), (False, 'This computer is already signed in.', False)]+ self.assertEqual(self.sign_in(answers, signed_in=True), ((True, 'This computer is already signed in.'), 2, 1))+++class RunSignIn(unittest.TestCase):+ def run_it(self, completed):+ with patch.object(setup.subprocess, 'run', return_value=completed), \+ patch.object(setup.pwd, 'getpwnam', return_value=Account()):+ return setup.run_sign_in('t')++ def test_only_the_backends_answer_about_the_ticket_is_final(self):+ def answered(code, message):+ return result(1, json.dumps(dict(type='result', status='error', code=code, message=message)) + '\n')+ self.assertEqual(self.run_it(answered('TICKET_INVALID', 'used')), (False, 'used', False))+ self.assertEqual(self.run_it(answered('ALREADY_SIGNED_IN', 'in')), (False, 'in', False))+ self.assertEqual(self.run_it(answered('BACKEND_ERROR', 'fetch failed')), (False, 'fetch failed', True))+ self.assertEqual(self.run_it(result(1, '', 'crashed')), (False, 'crashed', True))+ self.assertEqual(self.run_it(result(0)), (True, '', False))++class Account:pw_uid, pw_gid = 1000, 1000diff --git a/os/tests/vm.py b/os/tests/vm.pyindex e95219417..dffcc3aea 100644--- a/os/tests/vm.py+++ b/os/tests/vm.py@@ -641,7 +641,7 @@ def check_first_use(vm, user, folder, installed=False):version, _ = vm.command(user('/usr/bin/opencode --version'))(folder / 'bundled-opencode-version.txt').write_text(version)defaults = json.loads(vm.read_file('/home/me/.config/opencode/opencode.json'))- assert defaults.get('model') == 'opencode/muse-spark-1.3-contributor-free', 'The image must start on the pinned free model'+ assert 'model' not in defaults, 'The image must start on upstream\'s own free model'assert not set(defaults) & {'provider', 'providers'}, 'The image must retain upstream provider defaults'assert defaults.get('update') == 'disable', 'The packaged agent must remain managed by system updates'if installed:diff --git a/os/tools/opencode_package.py b/os/tools/opencode_package.pynew file mode 100644index 000000000..54e016b8a--- /dev/null+++ b/os/tools/opencode_package.py@@ -0,0 +1,65 @@+#!/usr/bin/env python3+"""The newest Arch OpenCode, for one ISO build: its version, and its package verified for the image.++The image's Arch snapshot is fixed (lock.json `arch_snapshot`), and its OpenCode was too: 2.0.21 from+2026/10/01 while Arch had 2.2.5. An image takes the newest OpenCode Arch has when it is built instead+(owner, 2026-11-03), through the build's own repository, which pacman reads before the snapshot's+(build.sh). Only an image: an OS update never changes OpenCode (installer.py `IgnorePkg`), so a+computer keeps the one its image brought until it is installed again.++The package is Arch's own, signed by its packager, and checked against the build's keyring.+"""+import argparse+import json+from pathlib import Path+import re+import shutil+import subprocess+import sys+from urllib.request import Request, urlopen++LATEST = 'https://archlinux.org/packages/extra/x86_64/opencode/json/'+# Every version Arch ever had, under the name pacman gives it.+ARCHIVE = 'https://archive.archlinux.org/packages/o/opencode/'+VERSION = re.compile(r'\d+(?:\.\d+)*-\d+')+AGENT = {'User-Agent': 'Harness-OS-Build/1'}+++def latest_version():+ """Arch's current OpenCode, as `2.2.5-1`."""+ with urlopen(Request(LATEST, headers=AGENT), timeout=30) as response:+ info = json.load(response)+ version = f"{info['pkgver']}-{info['pkgrel']}"+ if info.get('epoch') not in (None, 0, '0') or not VERSION.fullmatch(version):+ raise ValueError('Unexpected OpenCode version: ' + version)+ return version+++def package_name(version):+ return f'opencode-{version}-x86_64.pkg.tar.zst'+++def fetch(version, output):+ """[version]'s package and its signature in [output], the signature verified."""+ if not VERSION.fullmatch(version):+ raise ValueError('Use a full package version, such as 2.2.5-1.')+ output.mkdir(parents=True, exist_ok=True)+ package = output / package_name(version)+ for path in (package, package.with_name(package.name + '.sig')):+ with urlopen(Request(ARCHIVE + path.name, headers=AGENT), timeout=300) as response, path.open('wb') as handle:+ shutil.copyfileobj(response, handle)+ # Its words on stderr: stdout is the package path alone, for build.sh to read.+ subprocess.run(['pacman-key', '--verify', str(package) + '.sig', str(package)], check=True, stdout=sys.stderr)+ return package+++def main():+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument('--output', type=Path, required=True, help='the build repository to put it in')+ parser.add_argument('--version', help="a version to take instead of Arch's newest")+ args = parser.parse_args()+ print(fetch(args.version or latest_version(), args.output))+++if __name__ == '__main__':+ main()