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.

Focus first arrival and make resume failures recoverable (#1461)

Deeb669fe5d654a
diff --git a/backend/src/analytics/productHealth.test.ts b/backend/src/analytics/productHealth.test.ts
index 6c4eb1d58..37263dd03 100644
--- a/backend/src/analytics/productHealth.test.ts
+++ b/backend/src/analytics/productHealth.test.ts
@@ -87,3 +87,12 @@ it('suppresses sparse labels, distinguishes missing from zero, and matures first
expect(data.daily[0].requestReconciliation[0]).toMatchObject({ starts: 4, outcomes: 2, difference: 2 })
expect(data.daily[1].firstWorkRetention[0].denominator).toBeNull()
})
+
+it('reports first-run activation only against its own observed episode denominator', () => {
+ const row = (metric: string, value: number) => ({ dayUtc: new Date('2026-10-20'), metric: `health_desktop_${metric}`, value })
+ const report = dailyProductHealth([row('first_run_started', 10), row('first_run_ready', 9),
+ row('first_run_work', 8), row('first_run_response', 7), row('first_run_response_under_1m', 6)], new Date('2026-10-21'))
+ expect(report.daily[0].firstRun).toMatchObject({ started: 10, ready: 9, work: 8, response: 7, responsePercent: 70, mature: false })
+ expect(dailyProductHealth([row('collector_days', 5)], new Date('2026-10-23')).daily[0].firstRun.responsePercent).toBeNull()
+ expect(dailyProductHealth([row('first_run_started', 1), row('first_run_response', 2)], new Date('2026-10-23')).daily[0].firstRun.responsePercent).toBeNull()
+})
diff --git a/backend/src/analytics/productHealth.ts b/backend/src/analytics/productHealth.ts
index ecbc43e6e..60d5a3662 100644
--- a/backend/src/analytics/productHealth.ts
+++ b/backend/src/analytics/productHealth.ts
@@ -56,6 +56,7 @@ export function dailyProductHealth(rows: Row[], now: Date) {
waitBuckets: Object.fromEntries(['first_work', 'first_response'].flatMap(step => ['under_1m', '1m_to_5m', 'over_5m'].map(bucket => [`${step}_${bucket}`, c[`${prefix}_${step}_${bucket}`] ?? null]))),
definition: 'Locally deduplicated episodes, not a joined per-person funnel. Stages can cross UTC days; no daily conversion ratio is inferred.',
})),
+ firstRun: firstRunActivation(c, Date.parse(day) + 2 * 86400000 <= Date.parse(today)),
firstWorkRetention: [1, 7, 28].map(lag => {
const mature = Date.parse(day) + (lag + 1) * 86400000 <= Date.parse(today)
const denominator = c.health_cli_first_interactive_work ?? null
@@ -84,3 +85,23 @@ export function dailyProductHealth(rows: Row[], now: Date) {
privacy: 'Fixed aggregate totals; no identity or content joins. Sparse margins require 20 collector observations, which are not 20 distinct people. No guarantee of anonymity is inferred from that threshold.',
} }
}
+
+/** All stages belong to the start day of one first-arrival app episode. A routine app
+ * launch never enrolls; retries in that episode do not add another denominator. */
+export function firstRunActivation(c: Record<string, number>, mature: boolean) {
+ const started = c.health_desktop_first_run_started ?? null
+ const response = started === null ? null : c.health_desktop_first_run_response ?? 0
+ return {
+ started,
+ ready: started === null ? null : c.health_desktop_first_run_ready ?? 0,
+ work: started === null ? null : c.health_desktop_first_run_work ?? 0,
+ response,
+ responsePercent: started && response !== null && response <= started
+ ? Math.round(1000 * response / started) / 10 : null,
+ responseUnder1m: c.health_desktop_first_run_response_under_1m ?? null,
+ response1mTo5m: c.health_desktop_first_run_response_1m_to_5m ?? null,
+ responseOver5m: c.health_desktop_first_run_response_over_5m ?? null,
+ mature,
+ definition: 'Consented first-arrival app episodes reaching a live response in the opened harness, within the same app run and at most 24 hours. Counts belong to the start day; retries share its denominator. Not unique people, all installs, task completion or a cross-restart 24-hour cohort. Immature days and delivery loss are provisional.',
+ }
+}
diff --git a/backend/src/types/productHealthContract.ts b/backend/src/types/productHealthContract.ts
index 7aedd6a7d..d902c6b2c 100644
--- a/backend/src/types/productHealthContract.ts
+++ b/backend/src/types/productHealthContract.ts
@@ -32,6 +32,10 @@ export const HEALTH_MEASURES = [
// 50 ms or more by its longest phase, and one per collector day whose sampled frames included one over 250 ms.
// The Desktop counts them only once its CLI's report proxy has said it knows them.
'frame_slow_wait', 'frame_slow_build', 'frame_slow_raster', 'frame_long_collector',
+ // Vocabulary 5: first-arrival app episodes, scoped to the harness opened by onboarding.
+ 'first_run_started', 'first_run_ready', 'first_run_work', 'first_run_response',
+ 'first_run_response_under_1m', 'first_run_response_1m_to_5m', 'first_run_response_over_5m',
+ 'shared_invites_sent', 'shared_invites_refused',
] as const
// Delivery attempts, including retries; separate from the cross-surface app measures.
export const CLI_REPORT_FAILURES = ['invalid', 'too_large', 'auth', 'rate_limited', 'timeout', 'unreachable',
diff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.ts
index ef2a91380..960252a70 100644
--- a/backend/src/types/productUsage.ts
+++ b/backend/src/types/productUsage.ts
@@ -80,7 +80,7 @@ export const PRODUCT_USAGE_PHONE_SCREEN_METRICS = PRODUCT_USAGE_PHONE_SCREENS.fl
* `phone_offer_away_waited` / `_finished`: the card for a person back after five minutes or more away, to a harness
* that waited on them or finished meanwhile; vocabulary 4. docs/design/2026-10-20-desktop-phone-conversion.md. */
export const PRODUCT_USAGE_DESKTOP_FLOWS = ['phone_offer', 'phone_offer_after_work', 'phone_offer_away_waited',
- 'phone_offer_away_finished'] as const
+ 'phone_offer_away_finished', 'share_invite', 'share_accept'] as const
/** Each time Add Phone opens on a computer, by its way in: that card (`offer`), the title bar's phone, Harness ▸
* Add Phone… (`menu`, or a key bound to it on macOS), the account menu, the Machines picker, or the command
* (`> add phone`, a key bound to it elsewhere). Which way in, nothing else. */
diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.ts
index b10883163..8cda70dd1 100644
--- a/cli/src/hookServer.spec.ts
+++ b/cli/src/hookServer.spec.ts
@@ -551,7 +551,7 @@ describe('account Experimental settings proxy', () => {
const newer = { ...body, counters: { ...body.counters, health_desktop_frame_slow_wait: 2, health_desktop_PRIVATE_CANARY: 1 } }
const kept = await post(newer)
expect(kept.status).toBe(200)
- expect(kept.headers.get('x-harness-usage-vocabulary')).toBe('4')
+ expect(kept.headers.get('x-harness-usage-vocabulary')).toBe('5')
expect(send).toHaveBeenCalledExactlyOnceWith({ ...body,
counters: { ...body.counters, health_desktop_frame_slow_wait: 2, health_desktop_report_unknown_metric: 1 } })
expect(JSON.stringify(send.mock.calls)).not.toContain('PRIVATE_CANARY')
@@ -564,7 +564,7 @@ describe('account Experimental settings proxy', () => {
] as const) {
const response = await post(refused, h)
expect(response.status).toBe('x-adapter-local' in h ? 400 : 403)
- expect(response.headers.get('x-harness-usage-vocabulary')).toBe('4')
+ expect(response.headers.get('x-harness-usage-vocabulary')).toBe('5')
expect(await response.text()).not.toContain('PRIVATE_CANARY')
}
expect(send).toHaveBeenCalledOnce()
diff --git a/cli/src/lib/appProductUsageReport.spec.ts b/cli/src/lib/appProductUsageReport.spec.ts
index be28b55cd..5c2aa8c4c 100644
--- a/cli/src/lib/appProductUsageReport.spec.ts
+++ b/cli/src/lib/appProductUsageReport.spec.ts
@@ -84,8 +84,8 @@ it('drops names this contract does not know yet, says so once, and refuses every
]) expect(appProductUsageReport(refused), JSON.stringify(refused)).toBeUndefined()
})
-it('announces vocabulary 4, the revision whose frame-phase and Add Phone names a Desktop waits for', () => {
- expect(APP_USAGE_VOCABULARY).toBe(4)
+it('announces vocabulary 5 including first-arrival, invite and existing Add Phone names', () => {
+ expect(APP_USAGE_VOCABULARY).toBe(5)
for (const measure of ['frame_slow_wait', 'frame_slow_build', 'frame_slow_raster', 'frame_long_collector']) {
expect(appProductUsageReport({ ...native, counters: { [`health_desktop_${measure}`]: 1 } })).toBeDefined()
}
diff --git a/cli/src/lib/appProductUsageReport.ts b/cli/src/lib/appProductUsageReport.ts
index b232a576a..36893981a 100644
--- a/cli/src/lib/appProductUsageReport.ts
+++ b/cli/src/lib/appProductUsageReport.ts
@@ -7,8 +7,9 @@ import { PRODUCT_USAGE_ADD_PHONE_METRICS, PRODUCT_USAGE_METRICS, PRODUCT_USAGE_U
* (`ui_desktop_phone_offer_*`) and the ways Add Phone opened (`ui_desktop_add_phone_*`). 4: the card offered
* after work or after time away (`ui_desktop_phone_offer_after_work_*`, `ui_desktop_phone_offer_away_*`). The
* Desktop sends a name newer than revision 1 only once a proxy has announced it, so an older CLI never sees one.
+ * 5: first-arrival episodes and shared-tab invitation outcomes.
* Raise it with each name the Desktop gates on it (`ProductHealthMeasure.vocabulary`, `ProductFlow.vocabulary`). */
-export const APP_USAGE_VOCABULARY = 4
+export const APP_USAGE_VOCABULARY = 5
export const APP_USAGE_VOCABULARY_HEADER = 'x-harness-usage-vocabulary'
// hn's counts reach the daemon's own queue only through hn's `product_observe`; no app can file them.
diff --git a/cli/src/lib/productHealthContract.ts b/cli/src/lib/productHealthContract.ts
index 7aedd6a7d..d902c6b2c 100644
--- a/cli/src/lib/productHealthContract.ts
+++ b/cli/src/lib/productHealthContract.ts
@@ -32,6 +32,10 @@ export const HEALTH_MEASURES = [
// 50 ms or more by its longest phase, and one per collector day whose sampled frames included one over 250 ms.
// The Desktop counts them only once its CLI's report proxy has said it knows them.
'frame_slow_wait', 'frame_slow_build', 'frame_slow_raster', 'frame_long_collector',
+ // Vocabulary 5: first-arrival app episodes, scoped to the harness opened by onboarding.
+ 'first_run_started', 'first_run_ready', 'first_run_work', 'first_run_response',
+ 'first_run_response_under_1m', 'first_run_response_1m_to_5m', 'first_run_response_over_5m',
+ 'shared_invites_sent', 'shared_invites_refused',
] as const
// Delivery attempts, including retries; separate from the cross-surface app measures.
export const CLI_REPORT_FAILURES = ['invalid', 'too_large', 'auth', 'rate_limited', 'timeout', 'unreachable',
diff --git a/cli/src/lib/productUsageContract.ts b/cli/src/lib/productUsageContract.ts
index ef2a91380..960252a70 100644
--- a/cli/src/lib/productUsageContract.ts
+++ b/cli/src/lib/productUsageContract.ts
@@ -80,7 +80,7 @@ export const PRODUCT_USAGE_PHONE_SCREEN_METRICS = PRODUCT_USAGE_PHONE_SCREENS.fl
* `phone_offer_away_waited` / `_finished`: the card for a person back after five minutes or more away, to a harness
* that waited on them or finished meanwhile; vocabulary 4. docs/design/2026-10-20-desktop-phone-conversion.md. */
export const PRODUCT_USAGE_DESKTOP_FLOWS = ['phone_offer', 'phone_offer_after_work', 'phone_offer_away_waited',
- 'phone_offer_away_finished'] as const
+ 'phone_offer_away_finished', 'share_invite', 'share_accept'] as const
/** Each time Add Phone opens on a computer, by its way in: that card (`offer`), the title bar's phone, Harness ▸
* Add Phone… (`menu`, or a key bound to it on macOS), the account menu, the Machines picker, or the command
* (`> add phone`, a key bound to it elsewhere). Which way in, nothing else. */
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index d40648d27..98014cae2 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -238,7 +238,12 @@ The native desktop target uses the CLI for cloud access and SSO tokens:
opens normally. A server-rejected session requires sign-in again; saved local work
and running harnesses survive behind the page. A temporary network outage keeps
an already signed-in workspace available.
- Agent downloads still run during setup; first-arrival agents wait for an account.
+ Agent downloads still run during setup; first arrival waits for an account and opens one
+ recent usable conversation, or one configured agent with an editable, unsent starter task.
+ A person with no configured agent gets OpenCode alone. Failed opening offers explicit recovery;
+ it never starts again in a later empty tab. An uncertain start keeps its receipt and checks status.
+ The first-run draft also uses the local pane's composer; it is never sent into an installing
+ agent's terminal automatically. Other agents and tabs remain available through the usual controls.
The page does not change while the browser is open: the same option reopens its page,
and another option cancels and switches. Failures and cancellation keep the required
page visible. The workspace account menu is `widgets/account_menu.dart`
diff --git a/desktop/integration_test/first_run_native_test.dart b/desktop/integration_test/first_run_native_test.dart
new file mode 100644
index 000000000..be6c1c0bd
--- /dev/null
+++ b/desktop/integration_test/first_run_native_test.dart
@@ -0,0 +1,182 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:integration_test/integration_test.dart';
+import 'package:window_manager/window_manager.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/test_run.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/theme/color_palette.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/first_arrival.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/terminal/terminal_session.dart';
+import 'package:harness/widgets/terminal_panel.dart';
+import 'package:harness/widgets/workspace_machine_prompt.dart';
+
+import '../test/support/capture.dart';
+
+/// Real native rendering and input with synthetic transport only. Never opens a
+/// daemon, reads provider credentials, or submits a task to a real agent.
+void main() {
+ if (!kUnderTest) throw StateError('Requires FLUTTER_TEST=1');
+ IntegrationTestWidgetsFlutterBinding.ensureInitialized();
+ final captures = Platform.environment['HARNESS_FIRST_RUN_CAPTURES'];
+ final oldPalette = grid.AppTheme.palette.value;
+ final oldBrightness = grid.AppTheme.brightness.value;
+ tearDownAll(() {
+ grid.AppTheme.palette.value = oldPalette;
+ grid.AppTheme.brightness.value = oldBrightness;
+ });
+ setUpAll(() async {
+ await loadCaptureFonts(captures);
+ await windowManager.ensureInitialized();
+ await windowManager.setSize(const Size(1000, 700));
+ await windowManager.show();
+ await windowManager.focus();
+ });
+
+ testWidgets(
+ 'native first-run recovery keeps retry and a fresh start reachable',
+ (tester) async {
+ var retried = 0, fresh = 0, opened = 0;
+ for (final brightness in [Brightness.light, Brightness.dark]) {
+ grid.AppTheme.palette.value = brightness == Brightness.light
+ ? HarnessPalette.paper
+ : HarnessPalette.graphite;
+ grid.AppTheme.brightness.value = brightness;
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: Scaffold(
+ body: Center(
+ child: SizedBox(
+ width: 640,
+ child: WorkspaceMachinePrompt(
+ loading: false,
+ recovery: 'The saved conversation could not be opened. Your project and history are kept.',
+ onRetry: () => retried++,
+ onStartNew: () => fresh++,
+ onChoose: () => opened++,
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await captureWindow(tester, captures, 'recovery-${brightness.name}');
+ await tester.tap(find.text('Try again'));
+ await tester.tap(find.text('Start a new harness'));
+ await tester.tap(find.text('Open harnesses'));
+ expect(tester.takeException(), isNull);
+ }
+ expect([retried, fresh, opened], [2, 2, 2]);
+ await tester.pumpWidget(const SizedBox.shrink());
+ },
+ );
+
+ testWidgets(
+ 'native local first task is editable and remains unsent until Enter',
+ (tester) async {
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+ const machine = Machine(
+ machineId: 'fixture',
+ name: 'This computer',
+ authMode: MachineAuthMode.self,
+ );
+ app.machines = [machine];
+ app.machineStates['fixture'] = MachineState(machine)..localOnly = true;
+ final sent = <String>[];
+ var submitted = 0;
+ Object? request;
+ final session = TerminalSession(
+ machineId: 'fixture',
+ agentId: 'first',
+ agentName: 'First task',
+ engineId: 'codex',
+ client: const TerminalClientDescriptor(
+ kind: 'desktop',
+ name: 'Fixture',
+ ),
+ send: (type, payload) async {
+ if (type == 'terminal_open') request = payload['requestId'];
+ if (type == 'message') sent.add(payload['content'] as String);
+ return true;
+ },
+ sendBinary: (_) async => true,
+ );
+ const stream = '00112233-4455-6677-8899-aabbccddeeff';
+ await session.open(initialCols: 100, initialRows: 28);
+ await session.handleFrame('terminal_ready', {
+ 'requestId': request,
+ 'protocolVersion': 3,
+ 'streamId': stream,
+ 'agentId': 'first',
+ });
+ await session.handleBinary(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: stream,
+ seq: 0,
+ bytes: Uint8List.fromList(
+ utf8.encode('Codex\n\nReady for your first task.\n'),
+ ),
+ compressed: false,
+ cols: 100,
+ rows: 28,
+ ),
+ );
+ for (final brightness in [Brightness.light, Brightness.dark]) {
+ grid.AppTheme.palette.value = brightness == Brightness.light
+ ? HarnessPalette.paper
+ : HarnessPalette.graphite;
+ grid.AppTheme.brightness.value = brightness;
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: Scaffold(
+ body: TerminalPanel(
+ notifier: app,
+ session: session,
+ focused: true,
+ composerVisible: true,
+ firstTask: FirstArrival.starterTask,
+ onFirstTaskSubmitted: () => submitted++,
+ onToggleComposer: () {},
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text(FirstArrival.starterTask), findsOneWidget);
+ expect(sent, isEmpty);
+ expect(submitted, 0);
+ await captureWindow(tester, captures, 'first-task-${brightness.name}');
+ }
+ await tester.enterText(
+ find.byType(TextField),
+ 'Make a page with a blue background.',
+ );
+ expect(sent, isEmpty);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(sent, ['Make a page with a blue background.']);
+ expect(submitted, 1);
+ await tester.pumpWidget(const SizedBox.shrink());
+ session.dispose();
+ app.dispose();
+ },
+ );
+}
diff --git a/desktop/lib/agent_messages/shared_tabs.dart b/desktop/lib/agent_messages/shared_tabs.dart
index 1b0e20a87..7c73dc0ea 100644
--- a/desktop/lib/agent_messages/shared_tabs.dart
+++ b/desktop/lib/agent_messages/shared_tabs.dart
@@ -3,6 +3,7 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import '../ws/ws_conn.dart';
+import '../measurement/product_measurement.dart';
import 'shared_tabs_model.dart';
typedef SharedTabsRequest = Future<Map<String, dynamic>> Function(
@@ -124,6 +125,7 @@ class SharedTabsController extends ChangeNotifier {
required this.foreground,
this.onActivity,
this.messagesSwitch,
+ this.measurement,
}) {
_switchKnown = messagesSwitch?.value;
messagesSwitch?.addListener(_switchChanged);
@@ -131,6 +133,7 @@ class SharedTabsController extends ChangeNotifier {
}
final SharedTabsRequest request;
+ final ProductMeasurement? measurement;
final ValueListenable<bool> foreground;
final void Function(SharedActivity activity)? onActivity;
@@ -377,8 +380,45 @@ class SharedTabsController extends ChangeNotifier {
Map<String, dynamic> payload,
) async {
final account = _account;
+ final flow = switch (action) {
+ 'share_invite' => ProductFlow.shareInvite,
+ 'share_accept' => ProductFlow.shareAccept,
+ _ => null,
+ };
+ final finish = flow == null ? null : measurement?.begin(flow);
try {
- return await _ask(action, payload);
+ final answer = await _ask(action, payload);
+ if (account != _account || _disposed) {
+ finish?.call(ProductOutcome.cancelled);
+ return answer;
+ }
+ if (action == 'share_invite') {
+ final sent = answer['invited'];
+ final refused = answer['refused'];
+ measurement?.sharedInvites(
+ sent: sent is List ? sent.length : 0,
+ refused: refused is List ? refused.length : 0,
+ );
+ finish?.call(
+ sent is! List
+ ? ProductOutcome.unknown
+ : sent.isEmpty
+ ? ProductOutcome.failed
+ : ProductOutcome.ok,
+ );
+ } else {
+ finish?.call(
+ answer['pending'] == true
+ ? ProductOutcome.unknown
+ : answer['sharedTabId'] is String
+ ? ProductOutcome.ok
+ : ProductOutcome.unknown,
+ );
+ }
+ return answer;
+ } catch (_) {
+ finish?.call(ProductOutcome.failed);
+ rethrow;
} finally {
if (account == _account && !_disposed) unawaited(refresh());
}
diff --git a/desktop/lib/measurement/product_health_contract.dart b/desktop/lib/measurement/product_health_contract.dart
index 31c6684a8..9f8fcdfb9 100644
--- a/desktop/lib/measurement/product_health_contract.dart
+++ b/desktop/lib/measurement/product_health_contract.dart
@@ -72,7 +72,16 @@ enum ProductHealthMeasure {
frameSlowWait('frame_slow_wait'),
frameSlowBuild('frame_slow_build'),
frameSlowRaster('frame_slow_raster'),
- frameLongCollector('frame_long_collector');
+ frameLongCollector('frame_long_collector'),
+ firstRunStarted('first_run_started'),
+ firstRunReady('first_run_ready'),
+ firstRunWork('first_run_work'),
+ firstRunResponse('first_run_response'),
+ firstRunResponseUnder1m('first_run_response_under_1m'),
+ firstRunResponse1mTo5m('first_run_response_1m_to_5m'),
+ firstRunResponseOver5m('first_run_response_over_5m'),
+ sharedInvitesSent('shared_invites_sent'),
+ sharedInvitesRefused('shared_invites_refused');
const ProductHealthMeasure(this.wire);
final String wire;
@@ -88,6 +97,15 @@ enum ProductHealthMeasure {
frameSlowBuild ||
frameSlowRaster ||
frameLongCollector => 2,
+ firstRunStarted ||
+ firstRunReady ||
+ firstRunWork ||
+ firstRunResponse ||
+ firstRunResponseUnder1m ||
+ firstRunResponse1mTo5m ||
+ firstRunResponseOver5m ||
+ sharedInvitesSent ||
+ sharedInvitesRefused => 5,
_ => 1,
};
}
diff --git a/desktop/lib/measurement/product_measurement.dart b/desktop/lib/measurement/product_measurement.dart
index 4b1387013..eff10aeab 100644
--- a/desktop/lib/measurement/product_measurement.dart
+++ b/desktop/lib/measurement/product_measurement.dart
@@ -31,6 +31,8 @@ enum ProductFlow {
// The Add Phone card (widgets/phone_offer_card.dart), offered once per computer: begun when it is on
// screen, ok by its Add Phone, cancelled by its ×, unknown when it goes another way.
phoneOffer('phone_offer'),
+ shareInvite('share_invite'),
+ shareAccept('share_accept'),
// The same card offered once to a computer that never had it, after one of its own harnesses
// finished a turn (`AppNotifier._offerPhoneAfterWork`): counted apart, so the two offers read apart.
phoneOfferAfterWork('phone_offer_after_work'),
@@ -58,6 +60,7 @@ enum ProductFlow {
/// queue for that answer instead of being skipped ([ProductMeasurement]).
int get vocabulary => switch (this) {
phoneOffer => 3,
+ shareInvite || shareAccept => 5,
phoneOfferAfterWork || phoneOfferAwayWaited || phoneOfferAwayFinished => 4,
_ => 1,
};
@@ -147,6 +150,11 @@ class ProductMeasurement extends ChangeNotifier {
final _countedOn = <ProductHealthMeasure, String>{};
final _funnelSeen = <String, Set<ProductHealthMeasure>>{};
final _funnelStarted = <String, DateTime>{};
+ DateTime? _firstRunAt;
+ bool _firstRunRequested = false;
+ (String, String)? _firstRunTarget;
+ final _firstRunStages = <String>{};
+ bool _setupShown = false;
final _expires = <Object, DateTime>{};
final _expire = <Object, void Function(ProductOutcome)>{};
int get choiceRevision => _revision;
@@ -294,6 +302,10 @@ class ProductMeasurement extends ChangeNotifier {
_enabled = null;
return;
}
+ // Initial preference loading must not omit an eligible first arrival.
+ // Keep only its eligibility/current harness, never pre-consent work or responses.
+ final firstRunPending = _revision < 0 && _firstRunRequested;
+ final firstRunTarget = firstRunPending ? _firstRunTarget : null;
if (revision != _revision || !enabled) {
_accountEpoch++;
_clear('ui');
@@ -323,6 +335,12 @@ class ProductMeasurement extends ChangeNotifier {
_setup.clear();
_setupMissing.clear();
}
+ if (firstRunPending && sharing) {
+ firstRunStarted();
+ if (firstRunTarget case final target?) {
+ firstRunReady(target.$1, target.$2);
+ }
+ }
notifyListeners();
}
@@ -340,6 +358,10 @@ class ProductMeasurement extends ChangeNotifier {
if (channel == 'ui') {
_coverageDay = null;
_countedOn.clear();
+ _firstRunAt = null;
+ _firstRunRequested = false;
+ _firstRunTarget = null;
+ _firstRunStages.clear();
}
}
@@ -513,12 +535,100 @@ class ProductMeasurement extends ChangeNotifier {
);
}
+ /// One first-arrival episode in this app run. Retries share its denominator;
+ /// routine launches never call this. Targets stay in RAM and are never reported.
+ void firstRunStarted() {
+ if (!healthEnabled ||
+ _disposed ||
+ _account == null ||
+ _firstRunAt != null ||
+ accountOptOutPending) {
+ return;
+ }
+ if (_enabled == null && _revision < 0) {
+ _firstRunRequested = true;
+ return;
+ }
+ if (!sharing) return;
+ _firstRunRequested = false;
+ _firstRunAt = _now().toUtc();
+ _firstRunStage('started');
+ }
+
+ /// Counts acknowledged invitation results, never addresses, tab ids or invite ids.
+ void sharedInvites({required int sent, required int refused}) {
+ if (!healthEnabled || !sharing || _disposed) return;
+ _coverage();
+ final day = _now().toUtc().toIso8601String().substring(0, 10);
+ for (final (name, count) in [('sent', sent), ('refused', refused)]) {
+ for (var i = 0; i < count.clamp(0, 1000); i++) {
+ _count('ui', day, 'health_desktop_shared_invites_$name');
+ }
+ }
+ }
+
+ void firstRunReady(String machineId, String? agentId) {
+ if ((_firstRunAt == null && !_firstRunRequested) || agentId == null) return;
+ _firstRunTarget = (machineId, agentId);
+ _firstRunStage('ready');
+ }
+
+ void firstRunWork(String machineId, String agentId) {
+ if (_firstRunTarget == (machineId, agentId)) _firstRunStage('work');
+ }
+
+ void firstRunResponse(String machineId, String agentId) {
+ if (_firstRunTarget != (machineId, agentId) ||
+ !_firstRunStages.contains('work') ||
+ _firstRunStages.contains('response')) {
+ return;
+ }
+ _firstRunStage('response');
+ final start = _firstRunAt;
+ if (start == null || !_firstRunStages.contains('response')) return;
+ final seconds = _now().toUtc().difference(start).inSeconds;
+ _firstRunStage(
+ 'response_${seconds < 60
+ ? 'under_1m'
+ : seconds < 300
+ ? '1m_to_5m'
+ : 'over_5m'}',
+ );
+ }
+
+ void _firstRunStage(String stage) {
+ final start = _firstRunAt;
+ if (!healthEnabled || !sharing || _disposed || start == null) return;
+ final elapsed = _now().toUtc().difference(start);
+ if (elapsed.isNegative ||
+ elapsed > const Duration(hours: 24) ||
+ !_firstRunStages.add(stage)) {
+ return;
+ }
+ _coverage();
+ _count(
+ 'ui',
+ start.toIso8601String().substring(0, 10),
+ 'health_desktop_first_run_$stage',
+ );
+ }
+
+ /// Called only when setup is actually visible. A successful readiness probe
+ /// on a normal launch is not an impression of setup.
+ void setupShown() {
+ _setupShown = true;
+ milestone(ProductHealthMeasure.funnelSetupSeen);
+ }
+
+ void setupHidden() => _setupShown = false;
+
/// The proxy revision ([proxyVocabulary]) that forwards [metric]: the Add
/// Phone card's flow and the ways Add Phone opened are 3, the card offered
- /// after work or after time away 4, everything else this queue holds is 1 (a
- /// health measure newer than 1 is never queued before the proxy has named
- /// it, [health]).
+ /// after work or after time away 4, and first-run/invite counters 5. Other
+ /// health measures use [health] to wait for support before counting.
static int _vocabularyOf(String metric) {
+ if (metric.startsWith('health_desktop_first_run_') ||
+ metric.startsWith('health_desktop_shared_invites_')) return 5;
for (final flow in _newerFlows) {
if (metric.startsWith('ui_desktop_${flow.wire}_')) return flow.vocabulary;
}
@@ -550,7 +660,7 @@ class ProductMeasurement extends ChangeNotifier {
}
void _observeSetupFacts() {
- if (_setupFacts.isNotEmpty) milestone(ProductHealthMeasure.funnelSetupSeen);
+ if (_setupShown) milestone(ProductHealthMeasure.funnelSetupSeen);
if (!_setupAllowed && !sharing) return;
for (final entry in _setupFacts.entries) {
if (!entry.key.beforeSignIn || entry.key == ProductFlow.signIn) continue;
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 44738ada8..78fb5ed1b 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -150,6 +150,7 @@ import '../orchestrator/orchestrator_launcher.dart';
import '../orchestrator/orchestrator_workspace.dart';
import '../state/workspace_learning.dart';
import '../state/workspace_onboarding.dart';
+import '../state/first_arrival.dart';
import '../state/workspace_chrome.dart';
import '../widgets/key_hints.dart';
import '../daemons/daemon_brain.dart';
@@ -526,9 +527,25 @@ class _SwarmScreenState extends State<SwarmScreen> {
loading: app.machinesLoading,
preparing: _hasNewHarnessMachine,
preparingText: app.firstArrival.running
- ? 'Opening your agents…'
+ ? 'Opening your harness…'
: 'Preparing your harness…',
- onChoose: () => unawaited(_openMachines()),
+ recovery: app.firstArrival.error,
+ checkingStatus: app.firstArrival.checkingStatus,
+ onRetry: app.firstArrival.canRetry
+ ? _retryFirstArrival
+ : null,
+ onStartNew: app.firstArrival.canRetry &&
+ !app.firstArrival.checkingStatus
+ ? _startFreshAfterArrival
+ : null,
+ onChoose: () {
+ if (app.firstArrival.needsRecovery) {
+ app.firstArrival.dismiss();
+ _runShortcut('harnesses.list');
+ } else {
+ unawaited(_openMachines());
+ }
+ },
),
if (recent != null) ...[
const SizedBox(height: 56),
@@ -573,6 +590,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
(!app.activeSwarm.isSuperTab || app.activeSwarm.superTabId == null) &&
_newHarness == null &&
_search == null &&
+ !app.firstArrival.needsRecovery &&
!_pickingFolder &&
_hasNewHarnessMachine;
@@ -582,6 +600,31 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.localMachineState != null ||
widget.chrome?.newHarnessMachine?.call() != null;
+ Future<void> _retryFirstArrival() async {
+ final tab = app.activeSwarmId;
+ final work = app.firstArrival.retry(
+ app,
+ stillCurrent: () => mounted && app.activeSwarmId == tab &&
+ _newHarness == null && _search == null && !_pickingFolder,
+ );
+ setState(() {});
+ await work;
+ if (mounted) setState(() {});
+ }
+
+ void _startFreshAfterArrival() {
+ final arrival = app.firstArrival;
+ final session = arrival.selectedSession;
+ final engine = arrival.selectedEngine;
+ arrival.dismiss();
+ unawaited(_newAgent(
+ machineId: app.localMachineState?.machine.machineId,
+ folder: session?.cwd,
+ engine: engine,
+ task: session == null ? FirstArrival.starterTask : null,
+ ));
+ }
+
void _scheduleWelcomeComposer() {
if (_welcomeEntryScheduled || !_canShowWelcomeComposer) return;
_welcomeEntryScheduled = true;
@@ -600,7 +643,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_search == null &&
!_pickingFolder,
);
- // Says "Opening your agents…" while it works.
+ // Says "Opening your harness…" while it works.
if (mounted) setState(() {});
if (await arriving) return;
if (!_canShowWelcomeComposer || app.activeSwarmId != tab) return;
@@ -611,6 +654,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
);
} finally {
_welcomeEntryScheduled = false;
+ if (mounted) setState(() {});
// Switching tabs while defaults load must schedule the new page too.
if (mounted && app.activeSwarmId != tab) _scheduleWelcomeComposer();
}
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 727bac1f7..ff73acc70 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1153,6 +1153,8 @@ class AppNotifier extends ChangeNotifier {
// Account and inventory replies belong to the session that requested them.
// Signing out invalidates them before asynchronous connection cleanup.
int _authRevision = 0;
+ /// Cancels work across account changes, independently of measurement preferences.
+ int get accountGeneration => _authRevision;
Future<void>? _profileInFlight;
bool _authWorkCurrent(int revision) =>
@@ -1251,7 +1253,7 @@ class AppNotifier extends ChangeNotifier {
readiness.plan.any((item) => item.requiresTerminal);
/// A computer new to Harness builds its first workspace behind the welcome tour, once signed in
- /// and ready, so the agents have started and OpenCode's task is typed by the time the tour hands
+ /// and ready, so one harness and its editable task are ready when the tour hands
/// over: OpenCode's own first start took about 12 s after the tour had ended (fresh macOS VM,
/// 2026-10-09). The workspace joins this run when it appears ([FirstArrival.run]).
///
@@ -1655,6 +1657,7 @@ class AppNotifier extends ChangeNotifier {
/// frames reach only a computer's own windows, so the browser reads on open,
/// after its actions and every 60 s in front.
late final sharedTabs = SharedTabsController(
+ measurement: productMeasurement,
request: (payload) {
final target = sharedTabsTarget;
if (target == null) {
@@ -14046,8 +14049,9 @@ class AppNotifier extends ChangeNotifier {
String? swarmId,
HarnessPlacement? placement,
TakeOver? takeOver,
+ AgentCreationAttempt? attempt,
}) async {
- final attempt = AgentCreationAttempt();
+ final creation = attempt ?? AgentCreationAttempt();
final error = await _create(
machineId,
{
@@ -14060,9 +14064,9 @@ class AppNotifier extends ChangeNotifier {
},
swarmId: swarmId,
placement: placement,
- attempt: attempt,
+ attempt: creation,
);
- return (error: error, refusal: error == null ? null : attempt.refusal);
+ return (error: error, refusal: error == null ? null : creation.refusal);
}
Future<String?> _create(
@@ -15475,13 +15479,29 @@ class AppNotifier extends ChangeNotifier {
retryable: false,
);
}
+ final resuming = attempt.agent?.isStopped == true;
+ if (resuming && machine.connectionStatus != ConnectionStatus.connected) {
+ final connected = await connectTrusted(machineId);
+ if (!_restartCurrent(attempt, beforeSend: !attempt.awaitingConfirmation)) {
+ return const RestartAgentResult(
+ error: 'The harness changed while connecting. Select it again.',
+ retryable: false,
+ );
+ }
+ if (!connected) {
+ return RestartAgentResult(
+ error: machine.needsLink
+ ? 'Connect this computer in Machines, then open the saved harness again.'
+ : 'This computer is not connected. Bring it online and try again. Your saved conversation is kept.',
+ );
+ }
+ }
var checking = attempt.awaitingConfirmation;
if (!checking) {
attempt._id = _newCreationId();
attempt._startedRevision = machine._agentRevision;
}
attempt._awaitingConfirmation = true;
- final resuming = attempt.agent?.isStopped == true;
final measurementKey = _turnActivityKey(machineId, agentId);
if (resuming &&
!checking &&
@@ -15500,6 +15520,21 @@ class AppNotifier extends ChangeNotifier {
ProductFlow.resumeRecovery,
);
}
+ RestartAgentResult refused(String code, Object? detail) {
+ attempt._awaitingConfirmation = false;
+ if (resuming && code == 'AGENT_BUSY') {
+ final live = machine.agents.where((a) => a.id == agentId).firstOrNull;
+ if (live?.terminalAvailable == true &&
+ live?.sessionId == attempt.agent?.sessionId &&
+ live?.launchState != 'failed' &&
+ live?.launchState != 'starting') {
+ _agentRestarts.remove((machineId, agentId));
+ return const RestartAgentResult();
+ }
+ }
+ _measurementResumes.remove(measurementKey)?.call(ProductOutcome.failed);
+ return RestartAgentResult(error: _restartFailure(code, detail, resuming: resuming));
+ }
final unknown = RestartAgentResult(
error: resuming
? 'Still waiting for the Open response. Select the harness again to check status.'
@@ -15531,6 +15566,15 @@ class AppNotifier extends ChangeNotifier {
payload: {'creationId': attempt._id, 'agentId': agentId},
);
}
+ } on WsRequestFailure catch (failure) {
+ // Refusals travel as exceptions in WsConn, not successful reply maps.
+ // Treating every exception as a lost reply left a rejected resume on
+ // "Check status" forever, hiding both its cause and the retry action.
+ result = {
+ ...failure.payload,
+ 'error': failure.code,
+ 'detail': ?failure.detail,
+ };
} catch (_) {
return unknown;
}
@@ -15556,11 +15600,7 @@ class AppNotifier extends ChangeNotifier {
].contains(code)) {
return unknown;
}
- attempt._awaitingConfirmation = false;
- _measurementResumes.remove(measurementKey)?.call(ProductOutcome.failed);
- return RestartAgentResult(
- error: _restartFailure(code, result['detail'], resuming: resuming),
- );
+ return refused(code, result['detail']);
}
switch (result['state']) {
case 'pending':
@@ -15581,15 +15621,7 @@ class AppNotifier extends ChangeNotifier {
case 'failed':
final failure = result['failure'];
if (failure is! Map || failure['code'] is! String) return unknown;
- attempt._awaitingConfirmation = false;
- _measurementResumes.remove(measurementKey)?.call(ProductOutcome.failed);
- return RestartAgentResult(
- error: _restartFailure(
- failure['code'] as String,
- failure['detail'],
- resuming: resuming,
- ),
- );
+ return refused(failure['code'] as String, failure['detail']);
case 'created':
case null:
break;
@@ -15661,7 +15693,15 @@ class AppNotifier extends ChangeNotifier {
}) => code == 'PTY_HOST_UNAVAILABLE'
// Its detail is written for the log.
? 'Harness could not open a terminal on this machine. Run harness start on it, then try again.'
- : detail is String && detail.isNotEmpty
+ : detail is String && detail.isNotEmpty &&
+ !const {
+ 'IDENTITY_UNAVAILABLE',
+ 'CWD_NOT_FOUND',
+ 'SESSION_FOLDER_GONE',
+ 'GRID_CREDENTIAL_REQUIRED',
+ 'ENGINE_NOT_INSTALLED',
+ 'ENGINE_UNAVAILABLE',
+ }.contains(code)
? detail
: switch (code) {
'ENGINE_LAUNCH_REFUSED' =>
@@ -15676,6 +15716,14 @@ class AppNotifier extends ChangeNotifier {
'RESUME_UNAVAILABLE' => 'The saved conversation is unavailable. The harness can still be started fresh.',
'RESUME_SESSION_MISMATCH' => 'The harness came back on a different conversation. The saved one is still kept.',
'RESUME_FAILED' => 'The harness did not come back. Its output and conversation are kept.',
+ 'IDENTITY_UNAVAILABLE' =>
+ 'The saved conversation could not be verified. Check that its agent account and project are still available, then retry. You can also start a new harness; the saved one is kept.',
+ 'CWD_NOT_FOUND' || 'SESSION_FOLDER_GONE' =>
+ 'The project folder is unavailable. Restore it, then retry, or start a new harness in another folder.',
+ 'GRID_CREDENTIAL_REQUIRED' =>
+ 'Reconnect the model provider in Models, then retry. Your saved conversation is kept.',
+ 'ENGINE_NOT_INSTALLED' || 'ENGINE_UNAVAILABLE' =>
+ 'Install this agent on the computer, then retry.',
_ =>
resuming
? 'Could not open this harness: $code'
@@ -20262,6 +20310,8 @@ class AppNotifier extends ChangeNotifier {
_eventAgentId(machine, event, payload),
)) {
productMeasurement.milestone(ProductHealthMeasure.funnelFirstResponse);
+ final id = _eventAgentId(machine, event, payload);
+ if (id != null) productMeasurement.firstRunResponse(machineId, id);
}
if (reportedActivity == null &&
event['replay'] != true &&
@@ -20833,6 +20883,7 @@ class AppNotifier extends ChangeNotifier {
if (type == 'turn_started' && event['replay'] != true) {
machine.liveTurnAgents.add(agentId);
productMeasurement.milestone(ProductHealthMeasure.funnelFirstWork);
+ productMeasurement.firstRunWork(machineId, agentId);
_measurementResumes
.remove(_turnActivityKey(machineId, agentId))
?.call(ProductOutcome.ok);
diff --git a/desktop/lib/state/first_arrival.dart b/desktop/lib/state/first_arrival.dart
index 34e2ac2ca..8896b6373 100644
--- a/desktop/lib/state/first_arrival.dart
+++ b/desktop/lib/state/first_arrival.dart
@@ -4,20 +4,14 @@ import 'dart:io';
import 'package:flutter/foundation.dart';
import '../core/local_key_value_store.dart';
-import '../core/models.dart';
import '../core/permission_modes.dart';
import '../core/project_folder.dart';
import '../logging/app_log.dart';
-import '../terminal/terminal_session.dart';
import 'app_state.dart';
import 'harness_placement.dart';
-import 'pane_preset.dart';
import 'session_content_search.dart';
import 'swarm_navigation.dart';
-import 'terminal_pane.dart';
-/// One Claude Code or Codex conversation on this computer that Harness did not start, and that
-/// nothing is running: what the first workspace opens for someone who already uses those agents.
@immutable
class ArrivalSession {
const ArrivalSession({
@@ -27,87 +21,72 @@ class ArrivalSession {
required this.lastAt,
this.title = '',
});
-
final String engine, sessionId, cwd, title;
final DateTime lastAt;
-
- @override
- String toString() => '$engine:$sessionId';
}
-/// What the first workspace opens: [tabs] of conversations to resume, or a single tab of [fresh]
-/// agents in a new project. Empty opens nothing, and the person gets the New Harness box.
+/// One recent conversation or one fresh agent. Opening a workspace never submits a task.
@immutable
class FirstArrivalPlan {
const FirstArrivalPlan({this.tabs = const [], this.fresh = const []});
-
final List<List<ArrivalSession>> tabs;
-
- /// Engines started side by side in one new project, in pane order.
final List<String> fresh;
-
bool get isEmpty => tabs.isEmpty && fresh.isEmpty;
-
- /// OpenCode leads a fresh tab with the starter task typed into its box, not sent.
- bool get typesStarterTask => fresh.isNotEmpty && fresh.first == 'opencode';
-
- @override
- String toString() => 'FirstArrivalPlan(tabs: $tabs, fresh: $fresh)';
+ bool get typesStarterTask => fresh.isNotEmpty;
}
-/// The first workspace on a computer new to Harness (the owner's onboarding, 2026-10-08): no
-/// empty box asking what to type, but agents already open.
-///
-/// Someone with no agent at all (setup downloaded OpenCode, Codex and Claude Code) gets one tab with
-/// OpenCode full height on the left, a starter task typed into its box but not sent, and Codex and
-/// Claude Code stacked on the right, each on its own sign-in. Someone who already uses Claude Code or
-/// Codex gets their recent conversations that nothing is running ("open the recent ones that are NOT
-/// running so we can bring them into harness without interrupting user work"), most recent first by
-/// last activity, as ⌘P and the ⌘T recents order them: the latest of each agent in the first tab, so
-/// both agents show side by side, and the next three in a second, mixing the agents where it can.
-/// Someone with an agent but no conversations gets a fresh pane on each agent they have.
-///
-/// It runs once: [begin] marks a computer that is setting up the Harness CLI for the first time,
-/// and the mark is spent when the workspace has opened, or found the person's desk already full.
+/// One useful harness on a computer new to Harness. Failed preparation stays recoverable;
+/// it must not silently spend onboarding or start again in an unrelated empty tab.
class FirstArrival {
FirstArrival(this._storage, {DateTime Function()? now})
: _now = now ?? DateTime.now;
static const key = 'first_arrival_v1';
-
- /// Typed into OpenCode's box for someone with no agent, so the first thing they see is not a
- /// blank they have to fill (the owner: "most people don't know what to type").
- static const starterTask = "make a small web page that shows today's date";
-
- /// How far back a conversation counts as recent: the welcome page's window.
+ static const starterTask = "Make a small web page that shows today's date.";
static const window = Duration(days: 30);
-
final LocalKeyValueStore? _storage;
final DateTime Function() _now;
-
- /// `new` (setup downloaded the agents), `agents` (the computer had one), `done`, or null.
String? _state;
bool _running = false;
Future<void>? _beginning;
+ Future<bool>? _inFlight;
+ String? _error;
+ ArrivalSession? _selectedSession;
+ String? _selectedEngine;
+ FirstArrivalPlan? _plan;
+ AgentCreationAttempt? _attempt;
+ String? _preparedFolder;
+ String? _selectedMachine;
- /// Whether the next empty workspace is this computer's first.
bool get pending => !_running && (_state == 'new' || _state == 'agents');
-
- /// Opening the first workspace now.
bool get running => _running;
+ bool get needsRecovery =>
+ !_running &&
+ ((_state?.startsWith('retry:') ?? false) ||
+ (_state?.startsWith('check:') ?? false));
+ bool get canRetry =>
+ needsRecovery &&
+ (!(_state?.startsWith('check:') ?? false) || _attempt != null);
+ bool get checkingStatus => _attempt?.awaitingConfirmation == true;
+ String? get error => needsRecovery
+ ? _error ??
+ (canRetry
+ ? 'Your first harness could not be opened. Try again or start a new harness.'
+ : 'The earlier start is not confirmed. Open harnesses to check whether it is running.')
+ : null;
+ ArrivalSession? get selectedSession => _selectedSession;
+ String? get selectedEngine => _selectedSession?.engine ?? _selectedEngine;
- /// Reads the mark once signed in. After a [begin] this launch, what it settled stands.
Future<void> restore() async {
if (_beginning case final beginning?) return beginning;
_state = await _read();
}
- /// Setup is putting the Harness CLI on a computer that never had it. [downloads] says it is also
- /// downloading the agents, because the computer had none. A mark already spent stays spent.
void begin({required bool downloads}) {
_beginning ??= () async {
- if (await _read() == 'done') {
- _state = 'done';
+ final previous = await _read();
+ if (previous == 'done' || (previous?.contains(':') ?? false)) {
+ _state = previous;
return;
}
_state = downloads ? 'new' : 'agents';
@@ -115,13 +94,20 @@ class FirstArrival {
}();
}
- void _finish() {
- if (_state == 'done') return;
+ /// The person chose another way into the workspace. Never reopen onboarding behind them.
+ void dismiss() {
_state = 'done';
+ _error = null;
unawaited(_write('done'));
}
- static void _log(String line) => appLog.info('onboarding', line);
+ Future<bool> retry(AppNotifier app, {bool Function()? stillCurrent}) {
+ if (_inFlight case final work?) return work;
+ if (!canRetry) return Future.value(false);
+ _state = _state!.split(':').last;
+ _error = null;
+ return run(app, stillCurrent: stillCurrent);
+ }
Future<String?> _read() async {
try {
@@ -135,119 +121,195 @@ class FirstArrival {
try {
await _storage?.write(key, value);
} catch (_) {
- // A mark that could not be saved costs at most a second first workspace, never this one.
+ /* Local convenience only. */
}
}
- /// Opens the first workspace. True when it opened at least one pane; false leaves the empty tab
- /// to the New Harness box, as on any later launch. Runs once, whatever happens: a first workspace
- /// that turned up later, on some unrelated empty tab, would surprise more than none at all.
- ///
- /// [stillCurrent] says the person has not taken over meanwhile (opened the New Harness box or
- /// search); it is asked before each pane, and so is whether they are still on a tab this is
- /// filling.
- ///
- /// A second call while one is under way joins it: the app starts it behind the welcome tour, and
- /// the workspace waits for that one when it appears.
Future<bool> run(
AppNotifier app, {
bool Function()? stillCurrent,
Duration machineWait = const Duration(seconds: 30),
Duration indexWait = const Duration(seconds: 15),
- Duration starterWait = const Duration(minutes: 3),
- // As long as a create waits for an agent's download beside setup (`agentPrefetchWait`).
Duration installWait = const Duration(minutes: 10),
}) {
- if (_inFlight case final inFlight?) return inFlight;
+ if (_inFlight case final work?) return work;
if (!pending) return Future.value(false);
- final run = _run(
+ final work = _run(
app,
stillCurrent: stillCurrent,
machineWait: machineWait,
indexWait: indexWait,
- starterWait: starterWait,
installWait: installWait,
);
- _inFlight = run;
- return run.whenComplete(() => _inFlight = null);
+ _inFlight = work;
+ return work.whenComplete(() => _inFlight = null);
}
- Future<bool>? _inFlight;
-
Future<bool> _run(
AppNotifier app, {
bool Function()? stillCurrent,
required Duration machineWait,
required Duration indexWait,
- required Duration starterWait,
required Duration installWait,
}) async {
_running = true;
- final started = _now();
- // The tabs this fills, fixed once the first pane is about to open: behind the welcome tour the
- // desk is still being read and its tab can be replaced before then (a run that pinned it at the
- // start gave up on an existing user's sessions, fresh macOS VM, 2026-10-09).
- final tabs = <String>{};
+ final state = _state!;
+ final generation = app.accountGeneration;
+ var opened = false;
+ String? tab;
bool current() =>
+ _state != 'done' &&
+ app.signedIn &&
+ app.accountGeneration == generation &&
(stillCurrent?.call() ?? true) &&
- (tabs.isEmpty || tabs.contains(app.activeSwarmId));
- var opened = false;
- bool stop(String why) {
- _log('first arrival: stopped, $why');
+ (tab == null || app.activeSwarmId == tab);
+ bool fail(String message) {
+ _error = message;
+ _state = '${checkingStatus ? 'check' : 'retry'}:$state';
+ unawaited(_write(_state!));
return false;
}
try {
- // Someone whose account already has a desk elsewhere keeps it.
- if (app.allPanes.isNotEmpty) return stop('the desk already has panes');
+ if (!current() || app.allPanes.isNotEmpty) {
+ dismiss();
+ return false;
+ }
+ app.productMeasurement.firstRunStarted();
final machine = await _localMachine(app, machineWait);
- if (machine == null) return stop('this computer never answered');
- if (!current()) return stop('the person took over');
+ if (!current()) {
+ dismiss();
+ return false;
+ }
+ if (machine == null) {
+ return fail(
+ 'This computer has not connected yet. Try again when it is connected.',
+ );
+ }
final machineId = machine.machine.machineId;
- // The conversation index and installed engines are independent. A new
- // computer may still be indexing: do not put its engine probe behind it.
+ if (_selectedMachine != null && _selectedMachine != machineId) {
+ return fail(
+ 'The computer changed. Choose a harness on the computer you want to use.',
+ );
+ }
final (sessions, _) = await (
recentSessions(app, machineId, budget: indexWait),
app.probeEngines(machineId),
).wait;
+ if (!current() || app.allPanes.isNotEmpty) {
+ dismiss();
+ return false;
+ }
final installed = {
for (final engine in const ['claude', 'codex', 'opencode'])
if (machine.engines[engine]?.installed == true) engine,
};
- final plan = planFirstArrival(
- newUser: _state == 'new',
+ final signedOut = {
+ for (final engine in const ['claude', 'codex'])
+ if (machine.engines[engine]?.signedIn == false) engine,
+ };
+ final plan = _plan ??= planFirstArrival(
+ newUser: state == 'new',
sessions: sessions,
installed: installed,
- signedOut: {
+ signedOut: signedOut,
+ signedIn: {
for (final engine in const ['claude', 'codex'])
- if (machine.engines[engine]?.signedIn == false) engine,
+ if (machine.engines[engine]?.signedIn == true) engine,
},
);
- _log(
- 'first arrival: $plan after ${_now().difference(started).inMilliseconds} ms '
- '(${sessions.length} recent, installed $installed)',
+ if (plan.isEmpty) {
+ _plan = null;
+ return fail('Choose an agent to start your first harness.');
+ }
+ _selectedMachine = machineId;
+ if (_attempt?.awaitingConfirmation != true) {
+ _attempt = AgentCreationAttempt(holdWait: installWait);
+ }
+ tab = app.activeSwarmId;
+ String? failure;
+ if (plan.tabs.isNotEmpty) {
+ final session = plan.tabs.single.single;
+ _selectedSession = session;
+ final result = await app.resumeConversation(
+ machineId,
+ engine: session.engine,
+ folder: session.cwd,
+ sessionId: session.sessionId,
+ name: session.title.isEmpty ? null : session.title,
+ swarmId: tab,
+ placement: HarnessPlacement.currentTab,
+ attempt: _attempt,
+ );
+ failure = result.error;
+ } else {
+ _selectedSession = null;
+ final engine = plan.fresh.single;
+ _selectedEngine = engine;
+ final folder = _preparedFolder ??= await app.prepareLocalProjectFolder(
+ ProjectFolderRequest.generated(
+ label: externalEngineName(engine),
+ at: _now(),
+ task: starterTask,
+ ),
+ label: externalEngineName(engine),
+ );
+ if (!current() || app.allPanes.isNotEmpty) {
+ dismiss();
+ return false;
+ }
+ failure = await app.createAgent(
+ machineId,
+ engine: engine,
+ folder: folder,
+ permissionMode: kDefaultPermissionMode,
+ swarmId: tab,
+ placement: HarnessPlacement.currentTab,
+ attempt: _attempt,
+ );
+ }
+ if (!current()) {
+ dismiss();
+ return false;
+ }
+ if (failure != null) return fail(failure);
+ final panes = app.swarms.where((s) => s.id == tab).firstOrNull?.panes;
+ final createdId = _attempt?.agentId;
+ final pane = panes
+ ?.where(
+ (p) =>
+ p.machineId == machineId &&
+ (createdId == null
+ ? panes.length == 1
+ : p.agentId == createdId),
+ )
+ .firstOrNull;
+ if (pane == null) {
+ return fail('The harness has not opened yet. Try again to check it.');
+ }
+ if (plan.typesStarterTask) {
+ // An editable Flutter draft, not keystrokes sent to a terminal that may still be signing in.
+ pane.firstTask = starterTask;
+ pane.composerVisible = true;
+ }
+ app.focusPane(pane.id, reveal: true);
+ app.productMeasurement.firstRunReady(machineId, pane.agentId);
+ opened = true;
+ dismiss();
+ return true;
+ } catch (_) {
+ if (!current()) {
+ dismiss();
+ return false;
+ }
+ return fail(
+ 'Your first harness could not be opened. Try again or choose another agent.',
);
- if (plan.isEmpty) return stop('nothing to open');
- if (app.allPanes.isNotEmpty) return stop('the desk already has panes');
- if (!current()) return stop('the person took over');
- tabs.add(app.activeSwarmId);
- opened = plan.fresh.isNotEmpty
- ? await _openFresh(
- app,
- machineId,
- plan,
- starterWait,
- installWait,
- current,
- )
- : await _openSessions(app, machineId, plan.tabs, tabs, current);
- return opened;
} finally {
_running = false;
- _finish();
- _log(
- 'first arrival: ${opened ? 'opened' : 'opened nothing'} in '
- '${_now().difference(started).inMilliseconds} ms',
+ appLog.info(
+ 'onboarding',
+ 'first arrival: ${opened ? 'opened one harness' : 'opened nothing'}',
);
}
}
@@ -265,10 +327,6 @@ class FirstArrival {
}
}
- /// This computer's Claude Code and Codex conversations from the last [window] that nothing is
- /// running and whose folder is still here, most recent first. Asked like the welcome page asks
- /// (`session_search` with a time and no words), but given longer: on a computer Harness has just
- /// reached, the index is still reading every transcript for the first time.
Future<List<ArrivalSession>> recentSessions(
AppNotifier app,
String machineId, {
@@ -286,260 +344,56 @@ class FirstArrival {
limit: 30,
budget: budget,
);
- return sessionsFromHits(hits ?? const [], folderExists: _folderExists);
- }
-
- static bool _folderExists(String path) {
- try {
- return path.isNotEmpty && Directory(path).existsSync();
- } catch (_) {
- return false;
- }
- }
-
- Future<bool> _openSessions(
- AppNotifier app,
- String machineId,
- List<List<ArrivalSession>> plan,
- Set<String> tabs,
- bool Function() current,
- ) async {
- // The first tab is the empty one the person is looking at; the second a new one.
- final firstTab = app.activeSwarmId;
- var opened = false;
- for (final (index, tab) in plan.indexed) {
- String? tabId = index == 0 ? firstTab : null;
- Future<bool> resume(ArrivalSession session) async {
- if (!current()) return false;
- final before = {for (final tab in app.swarms) tab.id};
- final (:error, :refusal) = await app.resumeConversation(
- machineId,
- engine: session.engine,
- folder: session.cwd,
- sessionId: session.sessionId,
- name: session.title.isEmpty ? null : session.title,
- swarmId: tabId,
- placement: tabId == null
- ? HarnessPlacement.newTab
- : HarnessPlacement.currentTab,
- );
- if (error != null) {
- // Started since it was listed, or its folder went: the rest still open.
- _log('first arrival: $session not opened: ${refusal ?? error}');
+ return sessionsFromHits(
+ hits ?? const [],
+ folderExists: (path) {
+ try {
+ return path.isNotEmpty && Directory(path).existsSync();
+ } catch (_) {
return false;
}
- // The new tab is the one that was not there before, whichever tab is in front now.
- tabId ??= app.swarms
- .map((tab) => tab.id)
- .where((id) => !before.contains(id))
- .firstOrNull;
- if (tabId != null) tabs.add(tabId!);
- return true;
- }
-
- // One at a time until one has the tab, then the rest together, so one slow first start
- // (Codex's took 9.4 s on a fresh Mac) holds back nothing beside it.
- var rest = tab;
- var placed = false;
- while (rest.isNotEmpty && !placed) {
- placed = await resume(rest.first);
- rest = rest.skip(1).toList();
- }
- if (!placed || tabId == null) continue;
- opened = true;
- for (final wave in oneOfEachEngine(rest)) {
- await Future.wait([for (final session in wave) resume(session)]);
- }
- _arrange(
- app,
- tabId!,
- tab,
- // A resumed agent learns its session id once its transcript is found, which can be after
- // this; until then it carries the title it was opened with as its name.
- (agent, session) =>
- agent.sessionId == session.sessionId ||
- (session.title.isNotEmpty &&
- agent.engine == session.engine &&
- agent.name == session.title),
- );
- }
- if (!opened) return false;
- if (current()) _show(app, firstTab);
- return true;
- }
-
- Future<bool> _openFresh(
- AppNotifier app,
- String machineId,
- FirstArrivalPlan plan,
- Duration starterWait,
- Duration installWait,
- bool Function() current,
- ) async {
- final String folder;
- try {
- folder = await app.prepareLocalProjectFolder(
- ProjectFolderRequest.generated(
- label: externalEngineName(plan.fresh.first),
- at: _now(),
- task: plan.typesStarterTask ? starterTask : null,
- ),
- label: externalEngineName(plan.fresh.first),
- );
- } catch (error) {
- _log('first arrival: no project folder: $error');
- return false;
- }
- final tabId = app.activeSwarmId;
- Future<void> start(String engine) async {
- if (!current()) return;
- final error = await app.createAgent(
- machineId,
- engine: engine,
- folder: folder,
- permissionMode: kDefaultPermissionMode,
- swarmId: tabId,
- placement: HarnessPlacement.currentTab,
- // Setup is often still downloading the agent, and the machine then holds the harness
- // until it is installed and starts it by itself. Asked once, this was told so, opened
- // nothing, and the three harnesses started with no pane anywhere: the first workspace
- // was an empty tab with "Harnesses 3" under it (a fresh Ubuntu VM, 2026-10-12).
- attempt: AgentCreationAttempt(holdWait: installWait),
- );
- if (error != null) _log('first arrival: $engine not started: $error');
- // OpenCode the full height on the left, the other two stacked on the right. Applied as soon
- // as the third pane is in, not before: adding a pane resets the tab's layout for that count.
- if (plan.fresh.length == 3 &&
- app.activeSwarmId == tabId &&
- app.panes.length == 3) {
- app.setPreset(3, PanePreset.mainLeft);
- }
- }
-
- // The lead first, so it has the first place; the others together, so Codex's slow first start
- // does not hold Claude Code back. Never two of one engine at once ([oneOfEachEngine]); the plan
- // has each engine once.
- await start(plan.fresh.first);
- await Future.wait([for (final engine in plan.fresh.skip(1)) start(engine)]);
- _arrange(app, tabId, plan.fresh, (agent, engine) => agent.engine == engine);
- final panes = app.swarms.where((tab) => tab.id == tabId).firstOrNull?.panes;
- if (panes == null || panes.isEmpty) return false;
- if (current()) _show(app, tabId);
- final lead = panes.first;
- if (plan.typesStarterTask && _engineOf(app, lead) == plan.fresh.first) {
- unawaited(
- typeWhenReady(
- lead,
- starterTask,
- wait: starterWait,
- // Still OpenCode in that pane: a failed start leaves a shell there.
- still: () => _engineOf(app, lead) == plan.fresh.first,
- ).then(
- (typed) => _log(
- typed
- ? 'first arrival: starter task typed into ${plan.fresh.first}'
- : 'first arrival: ${plan.fresh.first} never showed its box; nothing typed',
- ),
- ),
- );
- }
- return true;
- }
-
- static Agent? _agentOf(AppNotifier app, TerminalPane pane) => app
- .stateOf(pane.machineId)
- ?.agents
- .where((agent) => agent.id == pane.agentId)
- .firstOrNull;
-
- static String? _engineOf(AppNotifier app, TerminalPane pane) =>
- _agentOf(app, pane)?.engine;
-
- /// Puts [tabId]'s panes in [order]: panes started together land in the order they answered.
- /// A pane [matches] no entry for stays where it is.
- static void _arrange<T>(
- AppNotifier app,
- String tabId,
- List<T> order,
- bool Function(Agent agent, T entry) matches,
- ) {
- if (app.activeSwarmId != tabId) return;
- for (var slot = 0; slot < order.length; slot++) {
- final panes = app.panes;
- if (slot >= panes.length) return;
- final wanted = panes.skip(slot).where((pane) {
- final agent = _agentOf(app, pane);
- return agent != null && matches(agent, order[slot]);
- }).firstOrNull;
- if (wanted != null && wanted.id != panes[slot].id) {
- app.reorderPane(wanted.id, panes[slot].id);
- }
- }
- }
-
- void _show(AppNotifier app, String tabId) {
- if (app.activeSwarmId != tabId &&
- app.swarms.any((tab) => tab.id == tabId)) {
- app.selectSwarm(tabId);
- }
- final first = app.swarms
- .where((tab) => tab.id == tabId)
- .firstOrNull
- ?.panes
- .firstOrNull;
- if (first != null) app.focusPane(first.id);
- }
-
- /// Types [text] into [pane]'s agent once its own screen is up, without Enter: the person reads
- /// it, changes it or sends it. Typed, not pasted, so the agent's box shows the words rather than a
- /// paste marker. Gives up after [wait]: an agent still installing in its pane must not have the
- /// words land in its installer.
- static Future<bool> typeWhenReady(
- TerminalPane pane,
- String text, {
- Duration wait = const Duration(minutes: 3),
- Duration poll = const Duration(milliseconds: 500),
- bool Function(String screen) ready = openCodeReady,
- bool Function()? still,
- }) async {
- final deadline = DateTime.now().add(wait);
- bool usable(TerminalSession? session) =>
- session != null &&
- session == pane.session &&
- session.acceptsInput &&
- (still?.call() ?? true);
- while (DateTime.now().isBefore(deadline)) {
- if (still?.call() == false) return false;
- final session = pane.session;
- if (usable(session) && ready(_screen(session!))) {
- // A moment for the box to take focus after its first frame.
- await Future<void>.delayed(const Duration(milliseconds: 800));
- if (!usable(session) || !ready(_screen(session))) continue;
- session.terminal.textInput(text);
- return true;
- }
- await Future<void>.delayed(poll);
- }
- return false;
+ },
+ );
}
+}
- static String _screen(TerminalSession session) {
- final buffer = session.terminal.buffer;
- final lines = <String>[];
- final start = buffer.height - session.terminal.viewHeight;
- for (var row = start < 0 ? 0 : start; row < buffer.height; row++) {
- lines.add(buffer.lines[row].toString());
- }
- return lines.join('\n');
+/// Prefer one recent usable conversation, then one signed-in engine. A person with no
+/// configured agent gets OpenCode alone; optional provider sign-ins can happen after first work.
+FirstArrivalPlan planFirstArrival({
+ required bool newUser,
+ required List<ArrivalSession> sessions,
+ required Set<String> installed,
+ Set<String> signedOut = const {},
+ Set<String> signedIn = const {},
+}) {
+ final usable =
+ sessions
+ .where(
+ (s) =>
+ installed.contains(s.engine) && !signedOut.contains(s.engine),
+ )
+ .toList()
+ ..sort((a, b) => b.lastAt.compareTo(a.lastAt));
+ if (usable.isNotEmpty) {
+ return FirstArrivalPlan(
+ tabs: [
+ [usable.first],
+ ],
+ );
}
-
- /// OpenCode's home screen: the key hints under its prompt box ("tab agents ctrl+p commands",
- /// OpenCode 1.18) or its placeholder. Phrases only OpenCode prints, so a shell or another agent's
- /// screen never passes.
- static bool openCodeReady(String screen) {
- final text = screen.toLowerCase().replaceAll(RegExp(r'\s+'), ' ');
- return text.contains('ctrl+p commands') || text.contains('ask anything');
+ final ready = [
+ for (final engine in const ['claude', 'codex'])
+ if (installed.contains(engine) && !signedOut.contains(engine)) engine,
+ ];
+ final engine =
+ ready.where(signedIn.contains).firstOrNull ?? ready.firstOrNull;
+ if (engine != null) return FirstArrivalPlan(fresh: [engine]);
+ if (newUser ||
+ installed.contains('opencode') ||
+ installed.any(signedOut.contains)) {
+ return const FirstArrivalPlan(fresh: ['opencode']);
}
+ return const FirstArrivalPlan();
}
/// Recent conversations from a `session_search` answer: Claude Code and Codex only, Harness's own
@@ -570,87 +424,3 @@ List<ArrivalSession> sessionsFromHits(
sessions.sort((a, b) => b.lastAt.compareTo(a.lastAt));
return sessions;
}
-
-/// [sessions] in waves that never start two of one engine at once: the daemon names an agent's tmux
-/// session after its engine and the millisecond, and two Claude Code resumes started together
-/// collided ("duplicate session", fresh macOS VM, 2026-10-09).
-List<List<ArrivalSession>> oneOfEachEngine(List<ArrivalSession> sessions) {
- final waves = <List<ArrivalSession>>[];
- for (final session in sessions) {
- final wave = waves
- .where((wave) => wave.every((other) => other.engine != session.engine))
- .firstOrNull;
- if (wave != null) {
- wave.add(session);
- } else {
- waves.add([session]);
- }
- }
- return waves;
-}
-
-/// The owner's rules (2026-10-08). Conversations first: the latest Claude Code and the latest Codex
-/// side by side, or the two latest of the one agent there is, then the next three in a second tab,
-/// with both agents in it when both have one left. Without conversations, someone setup gave the
-/// three agents gets them in one tab, OpenCode first; someone with agents gets a fresh pane on each
-/// of Claude Code and Codex they have, or on OpenCode when that is all they have.
-///
-/// Claude Code or Codex installed but none of them signed in ([signedOut]) is someone who has not
-/// used them yet: OpenCode leads with the starter task, their agents beside it on their sign-in, so a
-/// first result never waits on an account (a fresh Mac with Codex from npm, 2026-10-09: the only pane
-/// was Codex's sign-in, which sent the person to a browser).
-FirstArrivalPlan planFirstArrival({
- required bool newUser,
- required List<ArrivalSession> sessions,
- required Set<String> installed,
- Set<String> signedOut = const {},
-}) {
- if (sessions.isNotEmpty) return FirstArrivalPlan(tabs: recentTabs(sessions));
- if (newUser) {
- return const FirstArrivalPlan(fresh: ['opencode', 'codex', 'claude']);
- }
- final fresh = [
- for (final engine in const ['claude', 'codex'])
- if (installed.contains(engine)) engine,
- ];
- if (fresh.isNotEmpty && fresh.every(signedOut.contains)) {
- return FirstArrivalPlan(fresh: ['opencode', ...fresh.reversed]);
- }
- if (fresh.isNotEmpty) return FirstArrivalPlan(fresh: fresh);
- if (installed.contains('opencode')) {
- return const FirstArrivalPlan(fresh: ['opencode']);
- }
- return const FirstArrivalPlan();
-}
-
-/// [sessions] into at most two tabs of two and three, by the rules on [planFirstArrival].
-List<List<ArrivalSession>> recentTabs(List<ArrivalSession> sessions) {
- final sorted = [...sessions]..sort((a, b) => b.lastAt.compareTo(a.lastAt));
- if (sorted.isEmpty) return const [];
- final latest = <String, ArrivalSession>{};
- for (final session in sorted) {
- latest.putIfAbsent(session.engine, () => session);
- }
- final first = latest.length >= 2
- ? (latest.values.take(2).toList()
- ..sort((a, b) => b.lastAt.compareTo(a.lastAt)))
- : sorted.take(2).toList();
- final rest = [
- for (final session in sorted)
- if (!first.contains(session)) session,
- ];
- final second = rest.take(3).toList();
- if (second.length == 3 &&
- second.every((session) => session.engine == second.first.engine)) {
- final other = rest
- .skip(3)
- .where((session) => session.engine != second.first.engine)
- .firstOrNull;
- if (other != null) {
- second
- ..[2] = other
- ..sort((a, b) => b.lastAt.compareTo(a.lastAt));
- }
- }
- return [first, if (second.isNotEmpty) second];
-}
diff --git a/desktop/lib/state/terminal_pane.dart b/desktop/lib/state/terminal_pane.dart
index 367fd59fc..0775ba626 100644
--- a/desktop/lib/state/terminal_pane.dart
+++ b/desktop/lib/state/terminal_pane.dart
@@ -164,6 +164,9 @@ class TerminalPane {
/// pane pays a network round trip per keystroke. Off by default, and remembered, so the choice
/// survives a restart the way the rest of the layout does.
bool composerVisible = false;
+
+ /// First-arrival suggestion, local to this view and never part of the shared layout.
+ String? firstTask;
}
/// A tile as it survives a restart: intent only, never the session.
diff --git a/desktop/lib/widgets/environment_setup_screen.dart b/desktop/lib/widgets/environment_setup_screen.dart
index 044f2303c..342ae2e04 100644
--- a/desktop/lib/widgets/environment_setup_screen.dart
+++ b/desktop/lib/widgets/environment_setup_screen.dart
@@ -40,8 +40,17 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
bool _actionWasAvailable = false;
bool _detailsOpen = false;
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) widget.notifier.productMeasurement.setupShown();
+ });
+ }
+
@override
void dispose() {
+ widget.notifier.productMeasurement.setupHidden();
_copyTimer?.cancel();
_scroll.dispose();
_primaryFocus.dispose();
diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dart
index d973bb10e..fe75fc147 100644
--- a/desktop/lib/widgets/pane_grid.dart
+++ b/desktop/lib/widgets/pane_grid.dart
@@ -1886,6 +1886,10 @@ class _PaneContent extends StatelessWidget {
visible: visible,
compactHeader: swarmMode,
composerVisible: pane.composerVisible,
+ firstTask: pane.firstTask,
+ onFirstTaskSubmitted: pane.firstTask == null
+ ? null
+ : () => pane.firstTask = '',
// Launch progress/failure describes the engine, not permission to
// type into its terminal. Connection and control ownership still
// gate input independently in TerminalPanel/TerminalSession.
diff --git a/desktop/lib/widgets/setup_tour.dart b/desktop/lib/widgets/setup_tour.dart
index 660538afd..f24d87982 100644
--- a/desktop/lib/widgets/setup_tour.dart
+++ b/desktop/lib/widgets/setup_tour.dart
@@ -789,6 +789,14 @@ class SetupTourScreen extends StatefulWidget {
}
class _SetupTourScreenState extends State<SetupTourScreen> {
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) widget.app.productMeasurement.setupShown();
+ });
+ }
+
late final SetupProgressTracker _progress = SetupProgressTracker(
setup: widget.app,
readiness: () => widget.app.environmentReadiness,
@@ -803,6 +811,7 @@ class _SetupTourScreenState extends State<SetupTourScreen> {
@override
void dispose() {
_progress.dispose();
+ widget.app.productMeasurement.setupHidden();
super.dispose();
}
diff --git a/desktop/lib/widgets/terminal_composer.dart b/desktop/lib/widgets/terminal_composer.dart
index b1778efee..acef2340e 100644
--- a/desktop/lib/widgets/terminal_composer.dart
+++ b/desktop/lib/widgets/terminal_composer.dart
@@ -25,12 +25,16 @@ class TerminalComposer extends StatefulWidget {
required this.session,
required this.focusNode,
this.inputEnabled = true,
+ this.initialText = '',
+ this.onSubmitted,
this.onPasteNonText,
});
final TerminalSession session;
final FocusNode focusNode;
final bool inputEnabled;
+ final String initialText;
+ final VoidCallback? onSubmitted;
final Future<void> Function()? onPasteNonText;
@override
@@ -38,7 +42,9 @@ class TerminalComposer extends StatefulWidget {
}
class _TerminalComposerState extends State<TerminalComposer> {
- final TextEditingController _controller = TextEditingController();
+ late final TextEditingController _controller = TextEditingController(
+ text: widget.initialText,
+ );
@override
void initState() {
@@ -107,6 +113,7 @@ class _TerminalComposerState extends State<TerminalComposer> {
return;
}
_controller.clear();
+ widget.onSubmitted?.call();
} finally {
_sending = false;
}
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index 089d5c208..c86fe0a03 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -173,8 +173,10 @@ class TerminalPanel extends StatefulWidget {
/// same, but never retakes a terminal another client holds.
final bool focusByUser;
- /// Whether this tile's composer textbox is showing. Only consulted for a remote machine.
+ /// Whether this tile's composer is showing, for a remote machine or a first-run draft.
final bool composerVisible;
+ final String? firstTask;
+ final VoidCallback? onFirstTaskSubmitted;
final bool readOnly;
final TerminalNotice? notice;
@@ -204,6 +206,8 @@ class TerminalPanel extends StatefulWidget {
this.focusRequest = 0,
this.focusByUser = true,
this.composerVisible = false,
+ this.firstTask,
+ this.onFirstTaskSubmitted,
this.readOnly = false,
this.notice,
this.onToggleComposer,
@@ -548,7 +552,8 @@ class _TerminalPanelState extends State<TerminalPanel>
/// one, which is what puts it on the loopback transport.
bool get _showsComposer {
final machineState = widget.notifier.stateOf(widget.session.machineId);
- return machineState?.isLocalMachine != true && widget.composerVisible;
+ return (machineState?.isLocalMachine != true || widget.firstTask != null) &&
+ widget.composerVisible;
}
/// The composer refuses focus while it is disabled, which it is until the stream goes live. When
@@ -2439,7 +2444,7 @@ class _TerminalPanelState extends State<TerminalPanel>
),
// The grip is shown whether or not the box is: collapsed, it is the only way back.
if (!widget.compactHeader &&
- remote &&
+ (remote || widget.firstTask != null) &&
widget.onToggleComposer != null)
ColoredBox(
color: chromeFill,
@@ -2455,6 +2460,8 @@ class _TerminalPanelState extends State<TerminalPanel>
child: TerminalComposer(
session: session,
focusNode: _composerFocus,
+ initialText: widget.firstTask ?? '',
+ onSubmitted: widget.onFirstTaskSubmitted,
inputEnabled: !widget.readOnly && !session.readOnly,
onPasteNonText: _paste,
),
diff --git a/desktop/lib/widgets/workspace_machine_prompt.dart b/desktop/lib/widgets/workspace_machine_prompt.dart
index f80f3b290..4e4f94511 100644
--- a/desktop/lib/widgets/workspace_machine_prompt.dart
+++ b/desktop/lib/widgets/workspace_machine_prompt.dart
@@ -12,6 +12,10 @@ class WorkspaceMachinePrompt extends StatelessWidget {
required this.onChoose,
this.preparing = false,
this.preparingText = 'Preparing your harness…',
+ this.recovery,
+ this.onRetry,
+ this.onStartNew,
+ this.checkingStatus = false,
});
final bool loading;
@@ -20,6 +24,9 @@ class WorkspaceMachinePrompt extends StatelessWidget {
/// What [preparing] says: the first workspace on a new computer opens agents instead.
final String preparingText;
+ final String? recovery;
+ final VoidCallback? onRetry, onStartNew;
+ final bool checkingStatus;
@override
Widget build(BuildContext context) {
@@ -30,7 +37,7 @@ class WorkspaceMachinePrompt extends StatelessWidget {
Semantics(
header: true,
child: Text(
- 'Harness anything',
+ recovery != null ? 'Open your first harness' : 'Harness anything',
textAlign: TextAlign.center,
style: grid.AppType.display(color: DesktopChrome.foreground),
),
@@ -39,16 +46,40 @@ class WorkspaceMachinePrompt extends StatelessWidget {
Semantics(
liveRegion: true,
child: Text(
- preparing
- ? preparingText
- : loading
- ? 'Finding your machines…'
- : 'Choose a machine to start a new harness.',
+ recovery ??
+ (preparing
+ ? preparingText
+ : loading
+ ? 'Finding your machines…'
+ : 'Choose a machine to start a new harness.'),
textAlign: TextAlign.center,
style: DesktopChrome.text(color: DesktopChrome.muted),
),
),
- if (!preparing) ...[
+ if (recovery != null) ...[
+ const SizedBox(height: 24),
+ Wrap(
+ spacing: 12,
+ runSpacing: 12,
+ alignment: WrapAlignment.center,
+ children: [
+ if (onRetry != null)
+ FilledButton(
+ onPressed: onRetry,
+ child: Text(checkingStatus ? 'Check status' : 'Try again'),
+ ),
+ if (onStartNew != null)
+ OutlinedButton(
+ onPressed: onStartNew,
+ child: const Text('Start a new harness'),
+ ),
+ TextButton(
+ onPressed: onChoose,
+ child: const Text('Open harnesses'),
+ ),
+ ],
+ ),
+ ] else if (!preparing) ...[
const SizedBox(height: 24),
FilledButton(
onPressed: onChoose,
diff --git a/desktop/test/agent_pause_state_test.dart b/desktop/test/agent_pause_state_test.dart
index 8d5e40b5f..799a7e2ec 100644
--- a/desktop/test/agent_pause_state_test.dart
+++ b/desktop/test/agent_pause_state_test.dart
@@ -41,6 +41,92 @@ void main() {
});
tearDown(() => app.dispose());
+ test(
+ 'opening an offline saved harness reconnects before sending its resume',
+ () async {
+ final machine = app.stateOf('m')!;
+ machine.agents = [Agent.fromJson((inventory()['agents'] as List).single)];
+ machine.connectionStatus = ConnectionStatus.disconnected;
+ final resume = app.resumeAgent('m', 'a0');
+ await Future<void>.delayed(Duration.zero);
+ expect(connection.requests, isEmpty);
+ machine.connectionStatus = ConnectionStatus.connected;
+ app.notifyListeners();
+ await Future<void>.delayed(Duration.zero);
+ expect(connection.types, ['agent_resume']);
+ connection.restartReplies.single.complete(
+ restartReceipt(
+ connection.requests.single['creationId'] as String,
+ sessionId: source.sessionId,
+ ),
+ );
+ expect((await resume).error, isNull);
+ },
+ );
+
+ test('a refusal in a durable receipt also opens the already resumed conversation', () async {
+ app.stateOf('m')!.agents = [
+ Agent.fromJson((inventory()['agents'] as List).single),
+ ];
+ final resume = app.resumeAgent('m', 'a0');
+ app.stateOf('m')!.agents = [source];
+ connection.restartReplies.single.complete({
+ 'creationId': connection.requests.single['creationId'],
+ 'state': 'failed',
+ 'failure': {'code': 'AGENT_BUSY'},
+ });
+ expect((await resume).error, isNull);
+ });
+
+ test(
+ 'a thrown resume refusal is actionable and a retry starts a new receipt',
+ () async {
+ app.stateOf('m')!.agents = [
+ Agent.fromJson((inventory()['agents'] as List).single),
+ ];
+ final first = app.resumeAgent('m', 'a0');
+ final original = connection.requests.last['creationId'];
+ connection.restartReplies.last.completeError(
+ const WsRequestFailure(
+ responseType: 'agent_resume_result',
+ code: 'IDENTITY_UNAVAILABLE',
+ detail: 'identity check failed',
+ ),
+ );
+ expect((await first).error, contains('could not be verified'));
+ expect(app.restartAttempt('m', 'a0').awaitingConfirmation, isFalse);
+ final retry = app.resumeAgent('m', 'a0');
+ expect(connection.requests.last['creationId'], isNot(original));
+ expect(connection.checks, isEmpty);
+ connection.restartReplies.last.complete(
+ restartReceipt(
+ connection.requests.last['creationId'] as String,
+ sessionId: source.sessionId,
+ ),
+ );
+ expect((await retry).error, isNull);
+ },
+ );
+
+ test(
+ 'a busy refusal opens a concurrently resumed copy of the same conversation',
+ () async {
+ app.stateOf('m')!.agents = [
+ Agent.fromJson((inventory()['agents'] as List).single),
+ ];
+ final first = app.resumeAgent('m', 'a0');
+ app.stateOf('m')!.agents = [source];
+ connection.restartReplies.last.completeError(
+ const WsRequestFailure(
+ responseType: 'agent_resume_result',
+ code: 'AGENT_BUSY',
+ ),
+ );
+ expect((await first).error, isNull);
+ expect(connection.requests, hasLength(1));
+ },
+ );
+
test('thirty pause/resume cycles preserve identity and issue one command per transition', () async {
for (var cycle = 0; cycle < 30; cycle++) {
connection.inventory = Completer<Map<String, dynamic>>()
diff --git a/desktop/test/first_arrival_test.dart b/desktop/test/first_arrival_test.dart
index 6434d2432..5776e8700 100644
--- a/desktop/test/first_arrival_test.dart
+++ b/desktop/test/first_arrival_test.dart
@@ -7,6 +7,11 @@ import 'package:harness/core/local_key_value_store.dart';
import 'package:harness/core/models.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/first_arrival.dart';
+import 'package:harness/core/engine_availability.dart';
+import 'package:harness/core/project_folder.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:harness/state/pane_arrangement.dart';
+import 'package:harness/state/terminal_pane.dart';
import 'package:harness/state/session_content_search.dart';
import 'package:harness/state/swarm_navigation.dart';
@@ -22,11 +27,24 @@ class _MemoryStore implements LocalKeyValueStore {
class _PreparingApp extends AppNotifier {
_PreparingApp()
- : super(config: AppConfig.dev, authSession: AuthSession(), configStore: null);
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
final engineCheck = Completer<void>();
+ int generation = 0;
+ @override
+ int get accountGeneration => generation;
bool probing = false;
- final local = MachineState(const Machine(machineId: 'local', name: 'Mac', authMode: MachineAuthMode.self));
+ final local = MachineState(
+ const Machine(
+ machineId: 'local',
+ name: 'Mac',
+ authMode: MachineAuthMode.self,
+ ),
+ );
@override
MachineState get localMachineState => local;
@override
@@ -43,13 +61,71 @@ class _PreparingArrival extends FirstArrival {
final index = Completer<List<ArrivalSession>>();
bool searching = false;
@override
- Future<List<ArrivalSession>> recentSessions(AppNotifier app, String machineId,
- {required Duration budget}) {
+ Future<List<ArrivalSession>> recentSessions(
+ AppNotifier app,
+ String machineId, {
+ required Duration budget,
+ }) {
searching = true;
return index.future;
}
}
+class _OpeningApp extends _PreparingApp {
+ _OpeningApp() {
+ machineStates['local'] = local;
+ local.engines.replace([
+ const EngineAvailability(
+ engine: 'codex',
+ installed: true,
+ signedIn: true,
+ ),
+ ]);
+ }
+ final starts = <({String engine, String? folder, String? prompt})>[];
+ String? refusal;
+ int folders = 0;
+ @override
+ Future<void> probeEngines(String machineId, {bool force = false}) async {}
+ @override
+ Future<String> prepareLocalProjectFolder(
+ ProjectFolderRequest request, {
+ String label = 'harness',
+ }) async {
+ folders++;
+ return '/work/first-task';
+ }
+
+ @override
+ Future<String?> createAgent(
+ String machineId, {
+ required String engine,
+ required String? folder,
+ ProjectFolderRequest? projectFolder,
+ bool bypassPermission = true,
+ String? permissionMode,
+ String? codexHome,
+ String? dsh,
+ GridModel? model,
+ String? prompt,
+ String? name,
+ String? agent,
+ String? swarmId,
+ String? swarmRole,
+ String? swarmSkillMode,
+ PaneSplitRequest? split,
+ AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
+ }) async {
+ starts.add((engine: engine, folder: folder, prompt: prompt));
+ if (refusal != null) return refusal;
+ activeSwarm.panes.add(
+ TerminalPane(id: 1, machineId: machineId, agentId: 'first'),
+ );
+ return null;
+ }
+}
+
final _base = DateTime(2026, 10, 8, 12);
/// A conversation last active [minutesAgo] minutes before noon.
@@ -95,220 +171,72 @@ SessionContentHit _hit(
);
void main() {
- group('recentTabs', () {
- test(
- 'both agents: the latest of each side by side, then the next three',
- () {
- final tabs = recentTabs([
- _s('claude', 'c1', 1),
- _s('claude', 'c2', 2),
- _s('claude', 'c3', 3),
- _s('codex', 'x1', 4),
- _s('claude', 'c4', 5),
- _s('codex', 'x2', 6),
- _s('claude', 'c5', 7),
- ]);
- expect(_ids(tabs), [
- ['c1', 'x1'],
- // c2, c3 and c4 are all Claude Code: the third gives way to the latest Codex left.
- ['c2', 'c3', 'x2'],
- ]);
- },
- );
-
- test('the first tab is ordered by activity whichever agent leads', () {
- final tabs = recentTabs([
- _s('claude', 'c1', 9),
- _s('codex', 'x1', 1),
- _s('codex', 'x2', 2),
- ]);
- expect(_ids(tabs), [
- ['x1', 'c1'],
- ['x2'],
- ]);
- });
-
- test(
- 'the second tab keeps its own order when it already mixes the agents',
- () {
- final tabs = recentTabs([
- _s('claude', 'c1', 1),
- _s('codex', 'x1', 2),
- _s('codex', 'x2', 3),
- _s('claude', 'c2', 4),
- _s('codex', 'x3', 5),
- _s('claude', 'c3', 6),
- ]);
- expect(_ids(tabs), [
- ['c1', 'x1'],
- ['x2', 'c2', 'x3'],
- ]);
- },
- );
-
- test('one agent only: its two most recent, then the next three', () {
- final tabs = recentTabs([
- for (var i = 1; i <= 7; i++) _s('codex', 'x$i', i),
- ]);
- expect(_ids(tabs), [
- ['x1', 'x2'],
- ['x3', 'x4', 'x5'],
- ]);
- });
-
- test('a few conversations fill what they can', () {
- expect(_ids(recentTabs([_s('claude', 'c1', 1)])), [
- ['c1'],
- ]);
- expect(_ids(recentTabs([_s('claude', 'c1', 1), _s('codex', 'x1', 2)])), [
- ['c1', 'x1'],
- ]);
- expect(_ids(recentTabs(const [])), isEmpty);
- });
-
- test(
- 'order in, order out: an unsorted list is sorted by last activity',
- () {
- final tabs = recentTabs([
- _s('claude', 'c3', 30),
- _s('claude', 'c1', 10),
- _s('claude', 'c2', 20),
- ]);
- expect(_ids(tabs), [
- ['c1', 'c2'],
- ['c3'],
- ]);
- },
- );
- });
-
- test('never starts two of one engine at once', () {
- final waves = oneOfEachEngine([
- _s('claude', 'c1', 1),
- _s('claude', 'c2', 2),
- _s('codex', 'x1', 3),
- _s('claude', 'c3', 4),
- ]);
- expect(_ids(waves), [
- ['c1', 'x1'],
- ['c2'],
- ['c3'],
- ]);
- expect(oneOfEachEngine(const []), isEmpty);
- });
-
group('planFirstArrival', () {
- test('conversations win, whatever is installed', () {
+ test('opens only the most recent usable conversation', () {
final plan = planFirstArrival(
newUser: false,
- sessions: [_s('claude', 'c1', 1)],
- installed: const {'claude', 'codex', 'opencode'},
+ sessions: [
+ _s('claude', 'old', 9),
+ _s('codex', 'new', 1),
+ _s('claude', 'next', 2),
+ ],
+ installed: {'claude', 'codex', 'opencode'},
);
expect(_ids(plan.tabs), [
- ['c1'],
+ ['new'],
]);
expect(plan.fresh, isEmpty);
});
-
- test(
- 'a new user gets OpenCode, Codex and Claude Code, OpenCode typed into',
- () {
- final plan = planFirstArrival(
- newUser: true,
- sessions: const [],
- installed: const {},
- );
- expect(plan.fresh, ['opencode', 'codex', 'claude']);
- expect(plan.typesStarterTask, isTrue);
- },
- );
-
- test('agents but no conversations: a fresh pane on each of Claude Code and Codex', () {
- expect(
- planFirstArrival(
- newUser: false,
- sessions: const [],
- installed: const {'claude', 'codex', 'opencode'},
- ).fresh,
- ['claude', 'codex'],
+ test('does not select history for a missing or signed-out agent', () {
+ final plan = planFirstArrival(
+ newUser: false,
+ sessions: [_s('claude', 'unavailable', 1), _s('codex', 'ready', 2)],
+ installed: {'codex'},
+ signedOut: {'claude'},
);
+ expect(_ids(plan.tabs), [
+ ['ready'],
+ ]);
+ });
+ test('a new setup opens OpenCode alone with an unsent suggestion', () {
+ final plan = planFirstArrival(newUser: true, sessions: [], installed: {});
+ expect(plan.fresh, ['opencode']);
+ expect(plan.typesStarterTask, isTrue);
+ });
+ test('prefers a configured agent to an unknown credential', () {
expect(
planFirstArrival(
newUser: false,
- sessions: const [],
- installed: const {'codex'},
+ sessions: [],
+ installed: {'claude', 'codex'},
+ signedIn: {'codex'},
).fresh,
['codex'],
);
- final claude = planFirstArrival(
- newUser: false,
- sessions: const [],
- installed: const {'claude'},
- );
- expect(claude.fresh, ['claude']);
- expect(claude.typesStarterTask, isFalse);
});
-
- test(
- 'agents nobody has signed in to: OpenCode leads, they sit beside it',
- () {
- final codex = planFirstArrival(
- newUser: false,
- sessions: const [],
- installed: const {'codex'},
- signedOut: const {'codex'},
- );
- expect(codex.fresh, ['opencode', 'codex']);
- expect(codex.typesStarterTask, isTrue);
- expect(
- planFirstArrival(
- newUser: false,
- sessions: const [],
- installed: const {'claude', 'codex'},
- signedOut: const {'claude', 'codex'},
- ).fresh,
- ['opencode', 'codex', 'claude'],
- );
- // One signed in is enough to start on: no OpenCode.
- expect(
- planFirstArrival(
- newUser: false,
- sessions: const [],
- installed: const {'claude', 'codex'},
- signedOut: const {'codex'},
- ).fresh,
- ['claude', 'codex'],
- );
- // Their conversations still come first.
- expect(
- planFirstArrival(
- newUser: false,
- sessions: [_s('codex', 'x1', 1)],
- installed: const {'codex'},
- signedOut: const {'codex'},
- ).fresh,
- isEmpty,
- );
- },
- );
-
- test('OpenCode alone gets OpenCode with the starter task', () {
+ test('a fresh configured agent also gets an editable suggestion', () {
final plan = planFirstArrival(
newUser: false,
- sessions: const [],
- installed: const {'opencode'},
+ sessions: [],
+ installed: {'claude', 'codex'},
);
- expect(plan.fresh, ['opencode']);
+ expect(plan.fresh, ['claude']);
expect(plan.typesStarterTask, isTrue);
});
-
- test('nothing to open leaves the New Harness box', () {
+ test('unconfigured providers leave one OpenCode harness', () {
expect(
planFirstArrival(
newUser: false,
- sessions: const [],
- installed: const {},
- ).isEmpty,
+ sessions: [],
+ installed: {'claude', 'codex'},
+ signedOut: {'claude', 'codex'},
+ ).fresh,
+ ['opencode'],
+ );
+ });
+ test('no available engine has an explicit recovery path', () {
+ expect(
+ planFirstArrival(newUser: false, sessions: [], installed: {}).isEmpty,
isTrue,
);
});
@@ -334,23 +262,103 @@ void main() {
});
group('FirstArrival', () {
+ test('an account change during preparation prevents the launch', () async {
+ final app = _OpeningApp();
+ addTearDown(app.dispose);
+ final arrival = _PreparingArrival(_MemoryStore())
+ ..begin(downloads: false);
+ await arrival.restore();
+ final opening = arrival.run(app);
+ await Future<void>.delayed(Duration.zero);
+ app.generation++;
+ arrival.index.complete([]);
+ expect(await opening, isFalse);
+ expect(app.starts, isEmpty);
+ });
+
+ test(
+ 'loading the initial sharing preference does not cancel onboarding',
+ () async {
+ final app = _OpeningApp();
+ addTearDown(app.dispose);
+ final arrival = _PreparingArrival(_MemoryStore())
+ ..begin(downloads: false);
+ await arrival.restore();
+ final opening = arrival.run(app);
+ await Future<void>.delayed(Duration.zero);
+ app.productMeasurement.savedChoice({'enabled': true, 'revision': 0});
+ arrival.index.complete([]);
+ expect(await opening, isTrue);
+ expect(app.starts, hasLength(1));
+ },
+ );
+
+ test(
+ 'opens one fresh harness with a local draft and no submitted prompt',
+ () async {
+ final app = _OpeningApp();
+ addTearDown(app.dispose);
+ final arrival = _PreparingArrival(_MemoryStore())
+ ..begin(downloads: false);
+ await arrival.restore();
+ arrival.index.complete([]);
+ expect(await arrival.run(app), isTrue);
+ expect(app.starts, [
+ (engine: 'codex', folder: '/work/first-task', prompt: null),
+ ]);
+ expect(app.allPanes.single.firstTask, FirstArrival.starterTask);
+ expect(app.allPanes.single.composerVisible, isTrue);
+ expect(arrival.pending, isFalse);
+ expect(arrival.needsRecovery, isFalse);
+ },
+ );
+ test('a failed launch retries in its prepared project and does not run later by itself', () async {
+ final app = _OpeningApp()..refusal = 'Install Codex, then retry.';
+ addTearDown(app.dispose);
+ final arrival = _PreparingArrival(_MemoryStore())
+ ..begin(downloads: false);
+ await arrival.restore();
+ arrival.index.complete([]);
+ expect(await arrival.run(app), isFalse);
+ expect(arrival.error, 'Install Codex, then retry.');
+ expect(await arrival.run(app), isFalse);
+ expect(app.starts, hasLength(1));
+ app.refusal = null;
+ expect(await arrival.retry(app), isTrue);
+ expect(app.folders, 1);
+ expect(app.starts.map((s) => s.folder), [
+ '/work/first-task',
+ '/work/first-task',
+ ]);
+ });
+
test('the index and engine check start together and both finish before planning', () async {
final app = _PreparingApp();
addTearDown(app.dispose);
- final arrival = _PreparingArrival(_MemoryStore())..begin(downloads: false);
+ final arrival = _PreparingArrival(_MemoryStore())
+ ..begin(downloads: false);
await arrival.restore();
final opening = arrival.run(app);
await Future<void>.delayed(Duration.zero);
expect(arrival.searching, isTrue);
- expect(app.probing, isTrue, reason: 'a slow index must not delay the engine check');
+ expect(
+ app.probing,
+ isTrue,
+ reason: 'a slow index must not delay the engine check',
+ );
var finished = false;
opening.then((_) => finished = true);
arrival.index.complete([]);
await Future<void>.delayed(Duration.zero);
- expect(finished, isFalse, reason: 'do not infer no installed engines while the probe is pending');
+ expect(
+ finished,
+ isFalse,
+ reason: 'do not infer no installed engines while the probe is pending',
+ );
app.engineCheck.complete();
expect(await opening, isFalse); // No installed engines or conversations.
expect(arrival.pending, isFalse);
+ expect(arrival.needsRecovery, isTrue);
});
// Production order: setup's begin runs before the signed-in restore.
@@ -385,22 +393,30 @@ void main() {
},
);
- test('spends the mark when the computer never answers, so it never fires later', () async {
- final store = _MemoryStore();
- final arrival = FirstArrival(store)..begin(downloads: true);
- await arrival.restore();
- final app = AppNotifier(
- config: AppConfig.dev,
- authSession: AuthSession(),
- configStore: null,
- );
- addTearDown(app.dispose);
- expect(await arrival.run(app, machineWait: Duration.zero), isFalse);
- expect(arrival.pending, isFalse);
- await Future<void>.delayed(Duration.zero);
- expect(store.values[FirstArrival.key], 'done');
- expect(await arrival.run(app, machineWait: Duration.zero), isFalse);
- });
+ test(
+ 'a failed first connection stays recoverable without auto-retrying',
+ () async {
+ final store = _MemoryStore();
+ final arrival = FirstArrival(store)..begin(downloads: true);
+ await arrival.restore();
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+ addTearDown(app.dispose);
+ expect(await arrival.run(app, machineWait: Duration.zero), isFalse);
+ expect(arrival.pending, isFalse);
+ await Future<void>.delayed(Duration.zero);
+ expect(store.values[FirstArrival.key], 'retry:new');
+ expect(arrival.needsRecovery, isTrue);
+ final restored = FirstArrival(store);
+ await restored.restore();
+ expect(restored.pending, isFalse);
+ expect(restored.canRetry, isTrue);
+ expect(await arrival.run(app, machineWait: Duration.zero), isFalse);
+ },
+ );
test('a second call joins the run under way', () async {
final arrival = FirstArrival(_MemoryStore())..begin(downloads: true);
@@ -421,7 +437,12 @@ void main() {
final joined = arrival.run(app);
expect(await Future.wait([first, joined]), [false, false]);
expect(arrival.running, isFalse);
- expect(await arrival.run(app), isFalse, reason: 'spent');
+ expect(
+ await arrival.run(app),
+ isFalse,
+ reason: 'retry requires an explicit action',
+ );
+ expect(arrival.canRetry, isTrue);
});
test('the person taking over first stops it and spends the mark', () async {
@@ -445,29 +466,14 @@ void main() {
});
});
- test("OpenCode's home screen is recognised by its prompt hints", () {
- expect(
- FirstArrival.openCodeReady('Installing OpenCode… about 10 s'),
- isFalse,
- );
- expect(FirstArrival.openCodeReady(''), isFalse);
- expect(
- FirstArrival.openCodeReady(
- ' Build · claude-sonnet\n ctrl+p commands',
- ),
- isTrue,
- );
- expect(FirstArrival.openCodeReady('Ask anything... "Fix a TODO"'), isTrue);
- // Another agent's or a shell's screen never passes.
- expect(
- FirstArrival.openCodeReady(
- '? for shortcuts shift+tab to cycle /agents',
- ),
- isFalse,
- );
- expect(
- FirstArrival.openCodeReady('admin@mac ~ % ls table stable'),
- isFalse,
- );
+ test('an uncertain start restored without its receipt is inspected, never relaunched', () async {
+ final store = _MemoryStore()..values[FirstArrival.key] = 'check:new';
+ final arrival = FirstArrival(store);
+ await arrival.restore();
+ expect(arrival.needsRecovery, isTrue);
+ expect(arrival.canRetry, isFalse);
+ expect(arrival.error, contains('not confirmed'));
+ arrival.dismiss();
+ expect(arrival.needsRecovery, isFalse);
});
}
diff --git a/desktop/test/product_health_test.dart b/desktop/test/product_health_test.dart
index c4029f341..08370472a 100644
--- a/desktop/test/product_health_test.dart
+++ b/desktop/test/product_health_test.dart
@@ -63,6 +63,149 @@ void main() {
return all;
}
+ test('a first arrival waits for initial consent without observing earlier work', () async {
+ usage.firstRunStarted();
+ usage.firstRunReady('m', 'a');
+ usage.firstRunWork('m', 'a');
+ usage.firstRunResponse('m', 'a');
+ await usage.flush();
+ usage.proxyVocabulary = 5;
+ await usage.flush();
+ expect(totals()['health_desktop_first_run_started'], 1);
+ expect(totals()['health_desktop_first_run_ready'], 1);
+ expect(totals()['health_desktop_first_run_response'], isNull);
+ usage.firstRunWork('m', 'a');
+ usage.firstRunResponse('m', 'a');
+ await usage.flush();
+ expect(totals()['health_desktop_first_run_response'], 1);
+ });
+
+ test('an initial opt-out discards pending first-arrival eligibility', () async {
+ usage.firstRunStarted();
+ usage.firstRunReady('m', 'a');
+ choice = {'enabled': false, 'revision': 0};
+ await usage.flush();
+ choice = {'enabled': true, 'revision': 1};
+ await usage.flush();
+ usage.proxyVocabulary = 5;
+ usage.firstRunWork('m', 'a');
+ usage.firstRunResponse('m', 'a');
+ await usage.flush();
+ expect(totals().keys.where((name) => name.contains('first_run')), isEmpty);
+ });
+
+ test('first-run response follows only the opened harness and never counts retries twice', () async {
+ await usage.flush();
+ usage.proxyVocabulary = 5;
+ usage.firstRunStarted();
+ usage.firstRunStarted();
+ usage.firstRunReady('PRIVATE_MACHINE', 'PRIVATE_AGENT');
+ usage.firstRunWork('OTHER_MACHINE', 'PRIVATE_AGENT');
+ usage.firstRunResponse('PRIVATE_MACHINE', 'PRIVATE_AGENT');
+ await usage.flush();
+ expect(totals()['health_desktop_first_run_response'], isNull);
+ usage.firstRunWork('PRIVATE_MACHINE', 'PRIVATE_AGENT');
+ now = now.add(const Duration(seconds: 45));
+ usage.firstRunResponse('PRIVATE_MACHINE', 'PRIVATE_AGENT');
+ usage.firstRunResponse('PRIVATE_MACHINE', 'PRIVATE_AGENT');
+ await usage.flush();
+ expect(totals()['health_desktop_first_run_started'], 1);
+ expect(totals()['health_desktop_first_run_ready'], 1);
+ expect(totals()['health_desktop_first_run_work'], 1);
+ expect(totals()['health_desktop_first_run_response'], 1);
+ expect(totals()['health_desktop_first_run_response_under_1m'], 1);
+ expect(jsonEncode(reports), isNot(contains('PRIVATE')));
+ });
+
+ test('first-run counters wait for vocabulary 5 while version 4 still sends phone offers', () async {
+ await usage.flush();
+ usage.proxyVocabulary = 4;
+ usage.begin(ProductFlow.phoneOfferAfterWork)(ProductOutcome.ok);
+ usage.firstRunStarted();
+ usage.firstRunReady('m', 'a');
+ usage.firstRunWork('m', 'a');
+ usage.firstRunResponse('m', 'a');
+ await usage.flush();
+ expect(totals().keys.where((name) => name.contains('first_run')), isEmpty);
+ expect(totals()['ui_desktop_phone_offer_after_work_ok'], 1);
+ usage.proxyVocabulary = 5;
+ await usage.flush();
+ expect(totals()['health_desktop_first_run_started'], 1);
+ expect(totals()['health_desktop_first_run_response'], 1);
+ });
+
+ test('invite counters wait for vocabulary 5', () async {
+ await usage.flush();
+ usage.proxyVocabulary = 4;
+ usage.begin(ProductFlow.shareInvite)(ProductOutcome.ok);
+ usage.begin(ProductFlow.shareAccept)(ProductOutcome.ok);
+ usage.sharedInvites(sent: 2, refused: 1);
+ await usage.flush();
+ expect(totals().keys.where((name) => name.contains('share')), isEmpty);
+ usage.proxyVocabulary = 5;
+ await usage.flush();
+ expect(totals()['ui_desktop_share_invite_ok'], 1);
+ expect(totals()['ui_desktop_share_accept_ok'], 1);
+ expect(totals()['health_desktop_shared_invites_sent'], 2);
+ expect(totals()['health_desktop_shared_invites_refused'], 1);
+ });
+
+ test('first-run stages cross midnight on their start day and stop after 24 hours', () async {
+ await usage.flush();
+ usage.proxyVocabulary = 5;
+ now = DateTime.utc(2026, 10, 14, 23, 59);
+ usage.firstRunStarted();
+ usage.firstRunReady('m', 'a');
+ now = now.add(const Duration(minutes: 2));
+ usage.firstRunWork('m', 'a');
+ usage.firstRunResponse('m', 'a');
+ await usage.flush();
+ expect(
+ reports
+ .where(
+ (r) => (r['counters'] as Map).containsKey(
+ 'health_desktop_first_run_response',
+ ),
+ )
+ .single['day'],
+ '2026-10-14',
+ );
+ expect(totals()['health_desktop_first_run_response_1m_to_5m'], 1);
+ now = now.add(const Duration(days: 2));
+ usage.firstRunReady('m', 'another');
+ usage.firstRunWork('m', 'another');
+ await usage.flush();
+ expect(totals()['health_desktop_first_run_work'], 1);
+ });
+
+ test('opt-out and account changes discard the first-run target and queued counts', () async {
+ await usage.flush();
+ usage.firstRunStarted();
+ usage.firstRunReady('PRIVATE_MACHINE', 'PRIVATE_AGENT');
+ usage.savedChoice({'enabled': false, 'revision': 1});
+ choice = {'enabled': true, 'revision': 2};
+ usage.savedChoice(choice);
+ usage.proxyVocabulary = 5;
+ usage.firstRunWork('PRIVATE_MACHINE', 'PRIVATE_AGENT');
+ usage.firstRunResponse('PRIVATE_MACHINE', 'PRIVATE_AGENT');
+ await usage.flush();
+ expect(totals().keys.where((name) => name.contains('first_run')), isEmpty);
+ });
+
+ test('normal readiness probes do not say setup was shown', () async {
+ await usage.flush();
+ usage.setupFacts({
+ ProductFlow.setup: 'ready',
+ ProductFlow.setupHarness: 'ready',
+ });
+ await usage.flush();
+ expect(totals()['health_desktop_funnel_setup_seen'], isNull);
+ usage.setupShown();
+ usage.setupShown();
+ await usage.flush();
+ expect(totals()['health_desktop_funnel_setup_seen'], 1);
+ });
+
test('connection observations restart cleanly after off/on with the same machine', () async {
await usage.flush();
final connections = ProductConnections(usage);
@@ -268,7 +411,10 @@ void main() {
);
// A launch's first frame is its heavy workspace restore: not a sample
// (frames 1–59 are not sampled; the 60th is).
- runtime.framesForTest([frame(900), for (var i = 1; i < 59; i++) frame(5)]);
+ runtime.framesForTest([
+ frame(900),
+ for (var i = 1; i < 59; i++) frame(5),
+ ]);
// Minimised, then shown: the first frame back is the catch-up, and would
// otherwise be the 60th, the sampled one.
runtime.lifecycleChanged(AppLifecycleState.hidden);
@@ -279,7 +425,10 @@ void main() {
runtime.framesForTest([for (var i = 0; i < 120; i++) frame(400)]);
// Visible but without focus (inactive) still counts: a person sees it.
lifecycle = AppLifecycleState.inactive;
- runtime.framesForTest([frame(700), for (var i = 0; i < 60; i++) frame(5)]);
+ runtime.framesForTest([
+ frame(700),
+ for (var i = 0; i < 60; i++) frame(5),
+ ]);
await usage.flush();
expect(totals()['health_desktop_frame_under_16ms'], 2);
expect(totals()['health_desktop_frame_over_250ms'], isNull);
diff --git a/desktop/test/shared_tabs_controller_test.dart b/desktop/test/shared_tabs_controller_test.dart
index caa740c2c..d51028f06 100644
--- a/desktop/test/shared_tabs_controller_test.dart
+++ b/desktop/test/shared_tabs_controller_test.dart
@@ -1,4 +1,7 @@
import 'dart:async';
+import 'dart:convert';
+
+import 'package:harness/measurement/product_measurement.dart';
import 'package:fake_async/fake_async.dart';
import 'package:flutter/foundation.dart';
@@ -47,6 +50,63 @@ SharedTabsController make(SharedTabsRequest r, {void Function(SharedActivity)? o
SharedTabsController(request: r, foreground: front ?? ValueNotifier(true), onActivity: onActivity);
void main() {
+ test('invite measurement counts acknowledgements without addresses or ids and separates pending acceptance', () async {
+ final reports = <Map<String, dynamic>>[];
+ final usage = ProductMeasurement(
+ surface: 'desktop',
+ automatic: false,
+ context: ProductUsageContext(
+ release: '1.2.3',
+ platform: 'macos',
+ production: true,
+ ),
+ sendSetup: (_) async => {'accepted': true},
+ );
+ usage.account(
+ 'PRIVATE_ACCOUNT',
+ choice: () async => {'enabled': true, 'revision': 0},
+ send: (report) async {
+ reports.add(jsonDecode(jsonEncode(report)));
+ return {'accepted': true};
+ },
+ );
+ await usage.flush();
+ usage.proxyVocabulary = 5;
+ var pending = true;
+ final c = SharedTabsController(
+ foreground: ValueNotifier(true),
+ measurement: usage,
+ request: (p) async => switch (p['action']) {
+ 'share_invite' => {
+ 'invited': ['PRIVATE_1', 'PRIVATE_2'],
+ 'refused': ['PRIVATE_3'],
+ },
+ 'share_accept' => {'sharedTabId': 'PRIVATE_TAB', 'pending': pending},
+ _ => shares(),
+ },
+ );
+ await c.act('share_invite', {
+ 'emails': ['PRIVATE_1', 'PRIVATE_2', 'PRIVATE_3'],
+ });
+ await c.act('share_accept', {'inviteId': 'PRIVATE_INVITE'});
+ pending = false;
+ await c.act('share_accept', {'inviteId': 'PRIVATE_INVITE'});
+ await usage.flush();
+ final totals = <String, int>{};
+ for (final r in reports) {
+ for (final e in (r['counters'] as Map).entries) {
+ totals[e.key as String] = (totals[e.key] ?? 0) + (e.value as int);
+ }
+ }
+ expect(totals['health_desktop_shared_invites_sent'], 2);
+ expect(totals['health_desktop_shared_invites_refused'], 1);
+ expect(totals['ui_desktop_share_accept_unknown'], 1);
+ expect(totals['ui_desktop_share_accept_ok'], 1);
+ expect(jsonEncode(reports), isNot(contains('PRIVATE')));
+ c.dispose();
+ usage.dispose();
+ });
+
test("reads shares, and a member's desk tab is derived from its shared tab id (R1)", () async {
final c = make((p) async => shares(rosters: [roster()]));
await c.refresh();
diff --git a/desktop/test/terminal_composer_test.dart b/desktop/test/terminal_composer_test.dart
index cc48aecc5..2de2c8f59 100644
--- a/desktop/test/terminal_composer_test.dart
+++ b/desktop/test/terminal_composer_test.dart
@@ -101,6 +101,7 @@ Widget _host(
TerminalSession session, {
bool visible = true,
VoidCallback? onToggle,
+ String? firstTask,
}) => MaterialApp(
home: Scaffold(
body: SizedBox(
@@ -111,6 +112,7 @@ Widget _host(
session: session,
focused: true,
composerVisible: visible,
+ firstTask: firstTask,
onToggleComposer: onToggle ?? () {},
),
),
@@ -137,6 +139,26 @@ double _contrast(Color a, Color b) {
}
void main() {
+ testWidgets(
+ 'a local first harness has an editable suggestion and sends nothing on opening',
+ (tester) async {
+ final sent = <String>[];
+ final app = _notifier(local: true);
+ final session = await _liveSession(sent);
+ await tester.pumpWidget(
+ _host(app, session, firstTask: 'Make a date page.'),
+ );
+ await tester.pump();
+ expect(find.byType(TerminalComposer), findsOneWidget);
+ expect(find.text('Make a date page.'), findsOneWidget);
+ expect(sent, isEmpty);
+ await tester.enterText(find.byType(TextField), 'My own first task');
+ expect(sent, isEmpty);
+ await tester.pumpWidget(const SizedBox.shrink());
+ session.dispose();
+ app.dispose();
+ },
+ );
group('composer clipboard paste', () {
String? clipboard;
Future<Object?> Function()? checkClipboard;
diff --git a/docs/product-measurement.md b/docs/product-measurement.md
index c4d6254a5..4a2ab21e8 100644
--- a/docs/product-measurement.md
+++ b/docs/product-measurement.md
@@ -123,6 +123,43 @@ app episodes, can cross UTC days, and do not establish a joined signup conversio
cohorts use explicit composer messages; terminal keystrokes and automatic work remain unclassified.
Weekly bins cover completed weeks from installations that report again, so non-returners can be missing.
+Desktop's focused first arrival has its own population, separate from those routine app sessions.
+`health_desktop_first_run_started` enrolls one consented first-arrival episode in the current app
+run. `first_run_ready`, `first_run_work` and `first_run_response` count opening its harness, a live
+turn on that harness and a live text response after that turn. Other harnesses, replayed history
+and repeated retry clicks cannot advance it. The response also has `under_1m`, `1m_to_5m` and
+`over_5m` buckets, measured from first arrival after sign-in. All stages are attributed to the
+episode's start UTC day, for at most 24 hours and only while the same app run and sharing choice
+remain active. The machine/agent pair stays in RAM and never enters a report.
+If the account preference is still loading, enrollment waits for its initial confirmation;
+work and responses before that confirmation are not collected. An opt-out discards the
+pending eligibility, and preference loading never cancels the user's harness.
+
+The daily report's `health.daily[].firstRun.responsePercent` is
+`100 × first_run_response / first_run_started`. Show the numerator and denominator alongside it,
+and treat an incomplete follow-up day as provisional. This is first-session activation, not
+unique people, install-to-signup conversion, completed tasks or a cross-restart 24-hour cohort.
+There is no historical baseline for these new counters. The existing `firstLaunchCohorts`
+24-hour response rate remains a separate, comparable historical measure: its first measured
+launches also include existing users who updated. Do not compare the two percentages directly.
+Version comparisons are descriptive; small samples, rollout mix and report loss can change them.
+
+The setup milestone now comes from a rendered setup screen or tour, rather than every readiness
+probe. It still counts observed setup episodes, not deduplicated installations. Signed-out setup
+totals and signed-in totals cannot be joined or subtracted to infer individual sign-in conversion.
+
+Shared-tab invitation actions have `ui_desktop_share_invite_*` and `ui_desktop_share_accept_*`
+outcomes and wait buckets. A batch invitation also counts the acknowledged `shared_invites_sent`
+and `shared_invites_refused` under `health_desktop_`, by list length only. An acceptance waiting for
+trust confirmation is unknown until a later confirmed action; an acknowledgement alone does not
+prove the invited person worked. These are action/result counts, not unique recipients or a joined
+referral funnel. No addresses, invitation ids or tab ids are reported.
+
+These first-arrival and invitation counters wait in the bounded RAM queue until the local CLI
+advertises usage vocabulary 5. Publish backend vocabulary support before the CLI and Desktop;
+an older proxy must never receive names it would reject. Turning sharing off or changing accounts
+discards the episode and its queued counts. A close or crash can still lose unsent counters.
+
Native Desktop observes main-frame/first-frame viewer loading, updater apply acknowledgements and
the next observed version, explicit versus automatic connections, and resume-to-observed-work.
Known-unlinked native Desktop retry probes do not start additional automatic connection