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.

Merge batch 11-02 b2210: #2617 #2621 #2610 (#2629)

0xken159d15f21685dd
diff --git a/cli/src/device/deviceLink.spec.ts b/cli/src/device/deviceLink.spec.ts
index 04ba6b8af..5d28a5edc 100644
--- a/cli/src/device/deviceLink.spec.ts
+++ b/cli/src/device/deviceLink.spec.ts
@@ -24,7 +24,7 @@ const CLOUD = 'cloud-machine'
type Frame = Record<string, unknown>
/** The fake backend's device socket: what the lane sent, and a way to send it frames. */
-async function fakeDeviceWs(opts: { refuseToken?: string } = {}) {
+async function fakeDeviceWs(opts: { refuseToken?: string; late?: (frame: Frame, nth: number) => number } = {}) {
const received: Frame[] = []
const tokens: string[] = []
let socket: WebSocket | null = null
@@ -40,13 +40,17 @@ async function fakeDeviceWs(opts: { refuseToken?: string } = {}) {
await new Promise<void>((resolve) => wss.once('listening', () => resolve()))
const listeners = new Set<(frame: Frame) => void>()
const sockets: WebSocket[] = []
+ const heard: Record<string, number> = {}
wss.on('connection', (ws) => {
socket = ws
sockets.push(ws)
ws.on('message', (raw) => {
const frame = JSON.parse(raw.toString()) as Frame
- received.push(frame)
- for (const listener of listeners) listener(frame)
+ const seen = (heard[String(frame.type)] = (heard[String(frame.type)] ?? 0) + 1)
+ const take = () => { received.push(frame); for (const listener of listeners) listener(frame) }
+ // A loaded machine hands the server a frame some time after the lane sent it: `late` says how long, per frame.
+ const wait = opts.late?.(frame, seen) ?? 0
+ if (wait > 0) setTimeout(take, wait); else take()
})
})
const port = (wss.address() as { port: number }).port
@@ -97,8 +101,8 @@ afterEach(async () => {
for (const server of servers.splice(0)) await server.close()
})
-async function lane(over: { refuseToken?: string; auth?: { accessToken(options?: { force?: boolean; failedToken?: string }): Promise<string> }; welcome?: boolean; now?: () => number; linked?: Set<string>; handshakeMs?: number; renewEveryMs?: number } = {}) {
- const server = await fakeDeviceWs({ refuseToken: over.refuseToken })
+async function lane(over: { refuseToken?: string; late?: (frame: Frame, nth: number) => number; auth?: { accessToken(options?: { force?: boolean; failedToken?: string }): Promise<string> }; welcome?: boolean; now?: () => number; linked?: Set<string>; handshakeMs?: number; renewEveryMs?: number } = {}) {
+ const server = await fakeDeviceWs({ refuseToken: over.refuseToken, late: over.late })
servers.push(server)
const seal = fakeSeal()
const lines: string[] = []
@@ -1337,7 +1341,8 @@ describe('a sign-in refresh that fails while the lane dials', () => {
it('tries again after a reconnect whose token read fails once: a second socket within the backoff', async () => {
const auth = { accessToken: vi.fn(async () => 'token-1') }
- const { link, server, lines } = await lane({ auth })
+ // The second watch frame reaches the server 400 ms after the lane is ready, as one does on a loaded machine.
+ const { link, server, lines } = await lane({ auth, late: (frame, nth) => frame.type === 'machines_watch' && nth === 2 ? 400 : 0 })
await link.online()
// The network blips: the backend drops the socket, and the refresh the reconnect needs fails once.
auth.accessToken.mockRejectedValueOnce(new Error('UNAVAILABLE: the sign-in could not be refreshed'))
@@ -1346,7 +1351,10 @@ describe('a sign-in refresh that fails while the lane dials', () => {
expect(link.status()).toBe('idle')
// 1 s for the first try, 2 s for the next: well inside 5 s.
await until('the second socket', () => server.sockets.length === 2 && link.status() === 'ready', 5_000)
- expect(server.received.filter((frame) => frame.type === 'machines_watch')).toHaveLength(2)
+ // Ready does not mean the server has the frame yet: count once it holds the second one.
+ const watches = () => server.received.filter((frame) => frame.type === 'machines_watch')
+ await until('the second watch frame', () => watches().length >= 2)
+ expect(watches()).toHaveLength(2)
}, 12_000)
it('stops trying once the dial is unplugged during the wait', async () => {
diff --git a/desktop/lib/settings/sections/account_section.dart b/desktop/lib/settings/sections/account_section.dart
index a021a0055..a680920c8 100644
--- a/desktop/lib/settings/sections/account_section.dart
+++ b/desktop/lib/settings/sections/account_section.dart
@@ -83,9 +83,8 @@ class AccountSection extends StatelessWidget {
? 'Your Harness sign-in in this browser.'
: 'Your Harness sign-in on this computer.',
child: SingleChildScrollView(
- // Only the browser's reading, which draws a kept view at once, says
- // it keeps Super Tabs; Desktop's, drawn once confirmed and another
- // account's forgotten at sign-in, leaves its page as it was.
+ // Only the browser's reading says it keeps Super Tabs. Desktop's, with
+ // another account's forgotten at sign-in, leaves its page as it was.
child:
notifier.superTabs.reading.drawsSaved &&
!notifier.superTabs.reading.confirmsSaved
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 227015fe4..40d66b929 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -130,6 +130,7 @@ import 'harness_share_status.dart';
import 'desk_sync.dart';
import 'machine_profile.dart';
import 'pane_layout_store.dart';
+import 'profile_cache.dart';
import 'terminal_pane.dart';
import 'device_visit.dart';
import 'started_children.dart';
@@ -6650,7 +6651,24 @@ class AppNotifier extends ChangeNotifier {
await _store?.saveEnvironment(value);
}
+ /// How long into startup each step finished, in ms, for the log line and for tests. Task #2169.
+ @visibleForTesting
+ Map<String, int> get startupTimings => Map.unmodifiable(_startupTimings);
+ final _startupTimings = <String, int>{};
+ final _startupClock = Stopwatch();
+ void _markStartup(String step) {
+ if (_startupClock.isRunning) _startupTimings[step] = _startupClock.elapsedMilliseconds;
+ }
+
+ /// Set by any install during this boot: what the CLI said before it is out of date.
+ bool _installedThisBoot = false;
+
Future<void> bootstrap() async {
+ _startupTimings.clear();
+ _startupClock
+ ..reset()
+ ..start();
+ _installedThisBoot = false;
final localFixture = localManualFixture;
if (localFixture != null) {
_bootstrapLocalManual(localFixture);
@@ -6685,8 +6703,20 @@ class AppNotifier extends ChangeNotifier {
if (!_selfInstallUnavailable) {
_startUpdateChecking();
}
+ // Beside the tool probe, as neither waits on the other (task #2169). A fresh computer has no CLI yet: a check that
+ // fails is asked again after. One from before a sign-out or an install says nothing about now.
+ final askedAt = _authRevision;
+ final early = cliLogin.checkStatus().then<CliAuthStatus?>((status) {
+ _markStartup('signed-in check');
+ return status;
+ }).catchError((Object _) => null);
final environmentReady = await _prepareEnvironment();
+ _markStartup('tools');
if (!environmentReady) return;
+ await _continueAfterEnvironmentReady(
+ early: _installedThisBoot || askedAt != _authRevision ? null : early,
+ );
+ return;
}
await _continueAfterEnvironmentReady();
} catch (error, stack) {
@@ -6862,6 +6892,7 @@ class AppNotifier extends ChangeNotifier {
bool quiet = false,
}) async {
final provisioner = environmentProvisioner ?? EnvironmentProvisioner();
+ if (install) _installedThisBoot = true;
final result = await provisioner.ensureReady(
onProgress: (value) {
_measureSetup(value);
@@ -6900,7 +6931,7 @@ class AppNotifier extends ChangeNotifier {
/// What `bootstrap()` does right after the environment is confirmed ready — pulled out so
/// [recheckEnvironmentStep] can reach the same destination without repeating `bootstrap()`'s config
/// load and update-check startup, which already ran on the launch that got stuck here.
- Future<void> _continueAfterEnvironmentReady() async {
+ Future<void> _continueAfterEnvironmentReady({Future<CliAuthStatus?>? early}) async {
agentPrefetch?.setupRunning = false;
final revision = _authRevision;
if (!_authWorkCurrent(revision)) return;
@@ -6916,9 +6947,12 @@ class AppNotifier extends ChangeNotifier {
// refreshes it itself. This app never reads, stores, or refreshes a token of its own; it just
// asks the CLI whether this computer is currently signed in.
try {
- final authStatus = await cliLogin.checkStatus();
+ final authStatus = await early ?? await cliLogin.checkStatus();
+ _markStartup('signed-in check');
if (!_authWorkCurrent(revision)) return;
signedIn = authStatus.loggedIn;
+ await _useKeptProfile(authStatus, revision);
+ if (!_authWorkCurrent(revision)) return;
if (!authStatus.loggedIn) {
currentUser = null;
// Viewers keep their own login screen. Desktop can prepare the saved
@@ -7184,6 +7218,15 @@ class AppNotifier extends ChangeNotifier {
// `_authWorkCurrent` returns) used to leave "Starting local service…" on a screen nothing would
// ever repaint.
await _identifyBeforeLayout(revision);
+ _ensurePool();
+ // The daemon check starts beside the restores, as neither waits on the other (task #2169). The window opens once both
+ // have answered, so the tiles are there for it, as before.
+ Object? daemonFailure;
+ var daemonFailed = false;
+ final daemon = ensureCliDaemonReady().then<void>((_) => _markStartup('daemon')).catchError((Object error) {
+ daemonFailed = true;
+ daemonFailure = error;
+ });
await _restorePaneLayout(claimOnAttach: true);
_armLaunchClaimExpiry();
if (!_authWorkCurrent(revision)) {
@@ -7192,14 +7235,14 @@ class AppNotifier extends ChangeNotifier {
}
await dial.restore();
await firstArrival.restore();
+ _markStartup('saved tabs');
if (!_authWorkCurrent(revision)) {
_bootStatusMessage = null;
return;
}
- _ensurePool();
- try {
- await ensureCliDaemonReady();
- } catch (error) {
+ await daemon;
+ if (daemonFailed) {
+ final error = daemonFailure;
_bootStatusMessage = null;
if (!_authWorkCurrent(revision)) return;
status = AppStatus.authenticated;
@@ -7214,6 +7257,9 @@ class AppNotifier extends ChangeNotifier {
// the saved session gone) — that already routed to the login screen, so don't clobber it.
if (status == AppStatus.unauthenticated) return;
status = AppStatus.authenticated;
+ _markStartup('window');
+ appLog.info('startup', startupLogLine(_startupTimings));
+ _startupClock.stop();
notifyListeners();
// The CLI has confirmed daemon readiness. Display-name/avatar metadata is
// independent of machine discovery and must not delay work — and a guest
@@ -7359,6 +7405,10 @@ class AppNotifier extends ChangeNotifier {
signedIn = false;
_signInStep = true;
currentUser = null;
+ _provenMachineId = null;
+ _keptProfileId = null;
+ _profileConfirmed = false;
+ unawaited(_profileCache.clear());
if (banner != null) {
_lastError = banner;
_lastErrorRetryable = true;
@@ -7535,12 +7585,69 @@ class AppNotifier extends ChangeNotifier {
final me = await api.me();
if (me != null && _authWorkCurrent(revision)) {
currentUser = CurrentUserProfile.fromMe(me);
+ _profileConfirmed = true;
}
} catch (_) {
/* Unknown: the profile load after boot tries again. */
}
}
+ /// The machine id `harness auth status` named at this boot: what a kept profile is checked against ([ProfileCache]).
+ String? _provenMachineId;
+ late final _profileCache = ProfileCache(_paneLayout?.storage);
+
+ /// The account the kept profile showing now names, if one is: a server answer for another account clears it.
+ String? _keptProfileId;
+
+ /// Whether the server has answered who is signed in during this run. A kept profile shows until it has, and it is asked again
+ /// when the backend returns, as a person with no profile at all is. Security review of #2617.
+ bool _profileConfirmed = false;
+
+ /// The last profile, when the CLI's session is the one it was read under; otherwise it goes (task #2169). A viewer has no CLI
+ /// session to prove it, and reads its profile before the layout instead ([_identifyBeforeLayout]).
+ Future<void> _useKeptProfile(CliAuthStatus authStatus, int revision) async {
+ if (viewer != null) return;
+ final machineId = authStatus.loggedIn ? authStatus.machineId : null;
+ _provenMachineId = machineId;
+ _keptProfileId = null;
+ _profileConfirmed = false;
+ final kept = machineId == null ? null : await _profileCache.read(machineId);
+ if (!_authWorkCurrent(revision)) return;
+ if (kept == null) {
+ await _profileCache.clear();
+ return;
+ }
+ _keptProfileId = kept.id;
+ currentUser = kept;
+ notifyListeners();
+ }
+
+ /// Keeps what the server just answered, only where it can't name another account later: a machine id proves the account only
+ /// while everything under it is that account's. Someone can sign in as another in a terminal while the answer is on its way,
+ /// so an answer naming another account than the record goes, and a first record waits for the CLI to name the machine still.
+ Future<void> _keepProfile(CurrentUserProfile profile, int revision) async {
+ final machineId = _provenMachineId;
+ if (machineId == null) return;
+ final kept = _keptProfileId;
+ if (kept != null && kept != profile.id) {
+ _provenMachineId = null;
+ _keptProfileId = null;
+ await _profileCache.clear();
+ return;
+ }
+ if (kept == null) {
+ final CliAuthStatus still;
+ try {
+ still = await cliLogin.checkStatus();
+ } catch (_) {
+ return;
+ }
+ if (!_authWorkCurrent(revision) || !still.loggedIn || still.machineId != machineId) return;
+ _keptProfileId = profile.id;
+ }
+ await _profileCache.write(machineId, profile);
+ }
+
Future<void> _readProfile(int revision) async {
try {
final me = await api.me();
@@ -7549,6 +7656,8 @@ class AppNotifier extends ChangeNotifier {
}
if (me != null) {
currentUser = CurrentUserProfile.fromMe(me);
+ _profileConfirmed = true;
+ if (currentUser case final profile?) unawaited(_keepProfile(profile, revision));
// A sign-in by hand: the device log keeps which account it was made to.
if (currentUser!.id case final id?)
unawaited(_deviceLog?.signedInAs(id));
@@ -7655,7 +7764,7 @@ class AppNotifier extends ChangeNotifier {
appLog.info('daemon', 'backend ${online ? 'online' : 'offline'}');
if (online && wasOffline && status == AppStatus.authenticated) {
if (refetch && !machinesRefreshing) unawaited(retryMachines());
- if (currentUser == null) unawaited(_loadProfile());
+ if (!_profileConfirmed) unawaited(_loadProfile());
_deskEnsure(_authRevision);
// A daemon whose backend was away answered the last read with an error.
if (_desk.enabled) unawaited(agentMessages.refresh());
@@ -7888,6 +7997,10 @@ class AppNotifier extends ChangeNotifier {
cliLogin.cancel();
_sessionExpired = true;
currentUser = null;
+ _provenMachineId = null;
+ _keptProfileId = null;
+ _profileConfirmed = false;
+ unawaited(_profileCache.clear());
signingIn = false;
pendingAuthorizeUrl = null;
final previousMachineId = localMachineState?.machine.machineId;
@@ -9285,6 +9398,10 @@ class AppNotifier extends ChangeNotifier {
final becomesGuest = viewer == null && localManualFixture == null;
if (!becomesGuest) status = AppStatus.unauthenticated;
currentUser = null;
+ _provenMachineId = null;
+ _keptProfileId = null;
+ _profileConfirmed = false;
+ unawaited(_profileCache.clear());
notifyListeners();
// Clear saved credentials alongside connection cleanup. A new login must
// wait for both, otherwise the old logout can delete its fresh session.
@@ -12077,7 +12194,7 @@ class AppNotifier extends ChangeNotifier {
if (!_authWorkCurrent(revision) || status == AppStatus.unauthenticated) {
return;
}
- if (signedIn && currentUser == null) unawaited(_loadProfile());
+ if (signedIn && !_profileConfirmed) unawaited(_loadProfile());
// A boot that found the daemon still connecting finishes THROUGH here (see
// `_loadProfile`), so the local id is followed and the desk joined here as
// well — once, after the list, as the boot does.
@@ -23065,3 +23182,8 @@ String machineSelectErrorText(String code, String machine) => switch (code) {
'The subscription for $machine has ended. Renew it to use it again.',
_ => 'Could not connect to $machine. Try again in a moment.',
};
+
+/// The startup stopwatch as its log line: each step, in the order it finished.
+String startupLogLine(Map<String, int> timings) => timings.entries
+ .map((step) => '${step.key} after ${step.value} ms')
+ .join(', ');
diff --git a/desktop/lib/state/profile_cache.dart b/desktop/lib/state/profile_cache.dart
new file mode 100644
index 000000000..90b05c74e
--- /dev/null
+++ b/desktop/lib/state/profile_cache.dart
@@ -0,0 +1,77 @@
+import 'dart:convert';
+
+import '../core/local_key_value_store.dart';
+import '../core/models.dart';
+
+/// The last profile of the account signed in here, so the app opens as them with no wait (task #2169). It is kept with the
+/// machine id it was read under, and read only under that id: a machine row has one owner, and a new sign-in's session has no
+/// machine id until its own is resolved, so a match proves the same account with no network. The server's answer always
+/// replaces it. Anything unreadable reads as none, which is the wait there was before.
+class ProfileCache {
+ ProfileCache(this._storage);
+
+ final LocalKeyValueStore? _storage;
+ static const key = 'signed_in_profile_v1';
+
+ Future<CurrentUserProfile?> read(String machineId) async {
+ final storage = _storage;
+ if (storage == null) return null;
+ try {
+ final stored = await storage.read(key);
+ if (stored == null) return null;
+ final value = jsonDecode(stored);
+ if (value is! Map || value['machineId'] != machineId) return null;
+ final (id, email, name, avatar) = (
+ value['id'],
+ value['email'],
+ value['name'],
+ value['avatarUrl'],
+ );
+ if (id is! String || id.isEmpty || email is! String || email.isEmpty) {
+ return null;
+ }
+ if (name is! String? || avatar is! String?) return null;
+ return CurrentUserProfile(
+ id: id,
+ email: email,
+ name: name,
+ avatarUrl: avatar,
+ );
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// One at a time, in the order asked: a sign-out's clear never lands before a write already on its way.
+ Future<void> _last = Future.value();
+ Future<void> _inOrder(Future<void> Function() step) =>
+ _last = _last.then((_) => step());
+
+ Future<void> write(String machineId, CurrentUserProfile profile) =>
+ _inOrder(() async {
+ final id = profile.id;
+ if (id == null || id.isEmpty) return;
+ try {
+ await _storage?.write(
+ key,
+ jsonEncode({
+ 'machineId': machineId,
+ 'id': id,
+ 'email': profile.email,
+ 'name': profile.name,
+ 'avatarUrl': profile.avatarUrl,
+ }),
+ );
+ } catch (_) {
+ /* Only the next open's wait depends on it. */
+ }
+ });
+
+ Future<void> clear() => _inOrder(() async {
+ try {
+ await _storage?.delete(key);
+ } catch (_) {
+ /* A record left behind is read only under its own machine id. */
+ }
+ });
+}
diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dart
index 2bb6b6193..4ea001207 100644
--- a/desktop/lib/super_tabs/client.dart
+++ b/desktop/lib/super_tabs/client.dart
@@ -367,6 +367,11 @@ class SuperTabClient {
/// still protects its Product Managers, without reading anything more.
final _closedSnapshots = <String, SuperTabSnapshot>{};
+ /// The files waiting to go in Swarms let go, for their next controllers: in
+ /// memory for this account, and for the newest [_keptFilesSwarms] alone.
+ final _keptFiles = <String, SuperTabKeptFiles>{};
+ static const _keptFilesSwarms = 8;
+
/// How many times each Swarm was closed here: an open a close overtook
/// stops before it makes a controller.
final _closes = <String, int>{};
@@ -464,6 +469,7 @@ class SuperTabClient {
_controllers.clear();
_loaded.clear();
_closedSnapshots.clear();
+ _keptFiles.clear();
_closes.clear();
if (account != null &&
onTabs != null &&
@@ -683,6 +689,16 @@ class SuperTabClient {
final loaded = _loaded.remove(id);
// One that has read nothing yet keeps what the last close kept.
if (loaded?.snapshot case final snapshot?) _closedSnapshots[id] = snapshot;
+ if (loaded != null) {
+ final kept = loaded.keptFiles;
+ _keptFiles.remove(id);
+ if (kept.chats.isNotEmpty || kept.threads.isNotEmpty) {
+ _keptFiles[id] = kept;
+ if (_keptFiles.length > _keptFilesSwarms) {
+ _keptFiles.remove(_keptFiles.keys.first);
+ }
+ }
+ }
loaded?.dispose();
if (loaded != null) unawaited(loaded.flush().catchError((Object _) {}));
// Still reading its saved state: that open stops ([_open]).
@@ -728,6 +744,7 @@ class SuperTabClient {
)
..away = _isAway(id)
..pushUntil = _pushUntil;
+ if (_keptFiles.remove(id) case final kept?) controller.adoptFiles(kept);
var seenChange = (
lastChangedAt: -1,
mentionsWaiting: -1,
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 6f6356af3..9a79bedb7 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -172,6 +172,13 @@ const kSwarmPushSafetyNet = Duration(seconds: 60);
/// often; a change to one asks for a read at once (`SuperTabClient`).
const kSwarmDiscoverySafetyNet = Duration(minutes: 2);
+/// The files waiting in a Swarm's boxes: by conversation, and by a thread's
+/// conversation and root.
+typedef SuperTabKeptFiles = ({
+ Map<String, List<HarnessAttachment>> chats,
+ Map<(String, String), List<HarnessAttachment>> threads,
+});
+
class SuperTabController extends ChangeNotifier {
SuperTabController({
required this.tabId,
@@ -250,6 +257,32 @@ class SuperTabController extends ChangeNotifier {
if (key is String && value is num) _threadSeen[key] = value.toInt();
}
}
+ if (initial['openThread'] case {
+ 'conversationId': final String conversation,
+ 'root': final String root,
+ }) {
+ openedThread = (conversationId: conversation, root: root);
+ _reopenThread = true;
+ _threadUnshown = true;
+ }
+ if (initial['threadDrafts'] case final Map saved) {
+ for (final MapEntry(key: root, value: draft) in saved.entries) {
+ if (root is! String || draft is! Map) continue;
+ final conversation = draft['conversationId'], text = draft['text'];
+ if (conversation is! String || text is! String || text.isEmpty) {
+ continue;
+ }
+ _threadDrafts[root] = text;
+ _threadDraftConversations[root] = conversation;
+ if (draft['mentions'] case final Map mentions) {
+ final tags = {
+ for (final MapEntry(:key, :value) in mentions.entries)
+ if (key is String && value is String) key: value,
+ };
+ if (tags.isNotEmpty) _threadMentions[(conversation, root)] = tags;
+ }
+ }
+ }
final refused = initial['refused'];
if (refused is Map) {
for (final MapEntry(:key, :value) in refused.entries) {
@@ -720,12 +753,32 @@ class SuperTabController extends ChangeNotifier {
final _threadBefore = <String, Map<String, dynamic>>{};
final _threadDrafts = <String, String>{};
+ /// Which conversation each draft in [_threadDrafts] is for, so what this
+ /// computer keeps of it goes when that conversation does.
+ final _threadDraftConversations = <String, String>{};
+
/// The people and agents picked with `@` in each thread's reply box, by its
/// conversation and root, as [_mentions] holds the chat's own.
final _threadMentions = <(String, String), Map<String, String>>{};
/// The thread open beside the chat.
({String conversationId, String root})? openedThread;
+
+ /// A thread restored open, whose replies its first read of the Swarm brings.
+ bool _reopenThread = false;
+
+ /// A thread restored open whose pane has not been on screen: the read mark
+ /// is the account's on every device, and this controller may be open with
+ /// nothing shown, so nothing counts as read until [threadPaneShown].
+ bool _threadUnshown = false;
+
+ /// The pane of the open thread is on screen.
+ void threadPaneShown() {
+ if (!_threadUnshown) return;
+ _threadUnshown = false;
+ if (openedThread case final open?) _seeThread(open.root);
+ }
+
final _attachments = <String, HarnessAttachments>{};
/// The files waiting to go with the next reply of each thread, by its
@@ -957,6 +1010,34 @@ class SuperTabController extends ChangeNotifier {
HarnessAttachments attachments(String id) =>
_attachments.putIfAbsent(id, () => _newFiles(id, id));
+ /// The files waiting to go, for the next controller of this Swarm: bytes are
+ /// never saved, so the running app hands them on ([SuperTabClient.release]).
+ /// Nothing once access has gone.
+ SuperTabKeptFiles get keptFiles => (
+ chats: {
+ if (!accessRevoked)
+ for (final MapEntry(key: id, value: files) in _attachments.entries)
+ if (!files.isEmpty) id: files.files,
+ },
+ threads: {
+ if (!accessRevoked)
+ for (final MapEntry(key: thread, value: files)
+ in _threadAttachments.entries)
+ if (!files.isEmpty) thread: files.files,
+ },
+ );
+
+ /// Takes the files the last controller of this Swarm left ([keptFiles]). The
+ /// first read lets go of those for a conversation no longer read.
+ void adoptFiles(SuperTabKeptFiles kept) {
+ for (final MapEntry(key: id, value: files) in kept.chats.entries) {
+ attachments(id).add(files);
+ }
+ for (final MapEntry(key: thread, value: files) in kept.threads.entries) {
+ threadAttachments(thread.$1, thread.$2).add(files);
+ }
+ }
+
/// The files waiting to go with the next reply of [root]'s thread in
/// [conversationId]. Like [attachments], they stay in memory, and they are
/// forgotten with the thread when access to the conversation goes.
@@ -1260,6 +1341,7 @@ class SuperTabController extends ChangeNotifier {
}
void _seeThread(String root) {
+ if (_threadUnshown) return;
final open = openedThread;
final last = max(
(open == null ? null : _threads[open.conversationId]?[root])
@@ -1387,8 +1469,10 @@ class SuperTabController extends ChangeNotifier {
void openThread(String root) {
if (accessRevoked) return;
openedThread = (conversationId: selectedId, root: root);
+ _threadUnshown = false;
_pruneThreadFiles();
_seeThread(root);
+ _saveSoon();
_changed();
unawaited(loadThread());
}
@@ -1397,12 +1481,24 @@ class SuperTabController extends ChangeNotifier {
if (openedThread == null) return;
openedThread = null;
_pruneThreadFiles();
+ _saveSoon();
_changed();
}
String threadDraft(String root) => _threadDrafts[root] ?? '';
- void setThreadDraft(String root, String text) {
- _threadDrafts[root] = text;
+ void setThreadDraft(String root, String text, {String? conversationId}) {
+ // Removed first, so the newest is last and the cap in [_localState] keeps it.
+ _threadDrafts.remove(root);
+ if (text.isEmpty) {
+ _threadDraftConversations.remove(root);
+ } else {
+ _threadDrafts[root] = text;
+ _threadDraftConversations[root] =
+ conversationId ??
+ (openedThread?.root == root ? openedThread!.conversationId : null) ??
+ _threadDraftConversations[root] ??
+ selectedId;
+ }
// A tag the text no longer says is no longer picked.
for (final MapEntry(key: thread, value: tags) in _threadMentions.entries) {
if (thread.$2 == root) {
@@ -1410,6 +1506,7 @@ class SuperTabController extends ChangeNotifier {
}
}
_threadMentions.removeWhere((_, tags) => tags.isEmpty);
+ _saveSoon();
}
/// The tags picked in the reply box of [root]'s thread in [conversationId].
@@ -1585,6 +1682,7 @@ class SuperTabController extends ChangeNotifier {
// Only a draft still holding what went: more may have been typed since.
if (_threadDrafts[open.root]?.trim() == text) {
_threadDrafts.remove(open.root);
+ _threadDraftConversations.remove(open.root);
_threadMentions.remove(thread);
}
onSending?.call();
@@ -1630,6 +1728,7 @@ class SuperTabController extends ChangeNotifier {
}
} else {
_threadDrafts[root] = text;
+ _threadDraftConversations[root] = conversationId;
if (refused.mentions.isNotEmpty) {
_threadMentions[(conversationId, root)] = refused.mentions;
}
@@ -2180,8 +2279,9 @@ class SuperTabController extends ChangeNotifier {
/// Draws a [savedView] kept from an earlier visit while the first read is
/// on its way, and holds its parts: the first read asks only for what
- /// changed since, and replaces it. With [SuperTabReading.confirmsSaved] it
- /// only holds them, for that read to draw. One for another Swarm, one too
+ /// changed since, and replaces it. With [SuperTabReading.confirmsSaved] and
+ /// not [SuperTabReading.drawsSavedAtOnce] it only holds them, for that read
+ /// to draw. One for another Swarm, one too
/// old for its cursor, one that no longer parses, or one after a read has
/// landed or been refused, draws nothing.
void drawSaved(Map<String, dynamic> view) {
@@ -2207,7 +2307,7 @@ class SuperTabController extends ChangeNotifier {
];
final messages = rows.map(SuperTabMessage.fromJson).toList();
final changedAt = (view['lastChangedAt'] as num).toInt();
- if (_policy.confirmsSaved) {
+ if (_policy.confirmsSaved && !_policy.drawsSavedAtOnce) {
// Held for the first read to start from, drawn once it answers; the
// conversation it showed is read beside it.
_parts = parts;
@@ -2288,6 +2388,7 @@ class SuperTabController extends ChangeNotifier {
_forgetAttention();
error = message;
snapshot = null;
+ _showingSaved = false;
_parts = null;
_messages.clear();
_staleHeld.clear();
@@ -2340,6 +2441,21 @@ class SuperTabController extends ChangeNotifier {
'threadSeen': Map<String, int>.fromEntries(
_threadSeen.entries.skip(max(0, _threadSeen.length - 500)),
),
+ if (openedThread case final open?)
+ 'openThread': {'conversationId': open.conversationId, 'root': open.root},
+ // ponytail: the newest 500, as threadSeen.
+ if (_threadDrafts.isNotEmpty)
+ 'threadDrafts': {
+ for (final MapEntry(key: root, value: text)
+ in _threadDrafts.entries.skip(max(0, _threadDrafts.length - 500)))
+ if (_threadDraftConversations[root] case final conversation?)
+ root: {
+ 'conversationId': conversation,
+ 'text': text,
+ if (_threadMentions[(conversation, root)] case final tags?)
+ 'mentions': Map<String, String>.of(tags),
+ },
+ },
if (_pending != null) 'pending': _pending,
if (_sendOrder.isNotEmpty) 'sendOrder': List<String>.of(_sendOrder),
if (_refused.isNotEmpty || _queuedSends.isNotEmpty)
@@ -3255,6 +3371,7 @@ class SuperTabController extends ChangeNotifier {
..._mentions.keys,
..._readAt.keys,
..._refused.keys,
+ ..._threadDraftConversations.values,
].any(removed.contains) ||
expandedProjects.any(
(id) => !next.projects.any((project) => project.id == id),
@@ -3266,6 +3383,12 @@ class SuperTabController extends ChangeNotifier {
_forgetThreads(allowed.contains);
_rows.removeWhere((id, _) => !allowed.contains(id));
_drafts.removeWhere((id, _) => removed.contains(id));
+ _threadDrafts.removeWhere(
+ (root, _) => removed.contains(_threadDraftConversations[root]),
+ );
+ _threadDraftConversations.removeWhere(
+ (_, conversation) => removed.contains(conversation),
+ );
_attachments.removeWhere((id, files) {
if (allowed.contains(id)) return false;
files.dispose();
@@ -3287,6 +3410,11 @@ class SuperTabController extends ChangeNotifier {
}
selectedId = _shownFor(selectedId);
if (localAccessChanged) _saveSoon();
+ if (_reopenThread) {
+ _reopenThread = false;
+ // Still open: a conversation this read leaves out closed it above.
+ unawaited(loadThread());
+ }
// A new store holds no closed groups yet, nor one a saved view drew:
// the open projects read theirs.
if (read.full || stateReads == 1) {
@@ -3756,6 +3884,7 @@ class SuperTabController extends ChangeNotifier {
devicesSelected = false;
_forgetAttention();
snapshot = null;
+ _showingSaved = false;
_parts = null;
_messages.clear();
_staleHeld.clear();
diff --git a/desktop/lib/super_tabs/reading.dart b/desktop/lib/super_tabs/reading.dart
index fd5682b1d..f6c54a753 100644
--- a/desktop/lib/super_tabs/reading.dart
+++ b/desktop/lib/super_tabs/reading.dart
@@ -17,6 +17,7 @@ class SuperTabReading {
this.messagesWithState = false,
this.drawsSaved = false,
this.confirmsSaved = false,
+ this.drawsSavedAtOnce = false,
});
/// Desktop's: a first open asks for the state and the open conversation at
@@ -31,6 +32,7 @@ class SuperTabReading {
messagesWithState: true,
drawsSaved: true,
confirmsSaved: true,
+ drawsSavedAtOnce: true,
);
/// Null keeps a full read every poll. Otherwise, once the open conversation
@@ -92,11 +94,17 @@ class SuperTabReading {
/// (`SuperTabSavedViews`).
final bool drawsSaved;
- /// With [drawsSaved], true holds a saved view's parts for the first read
- /// to start from but draws them only once that read has answered, so a
- /// conversation the reader lost since is never on screen.
+ /// With [drawsSaved], true is Desktop's way with saved views: read before the
+ /// first read, for it to start from, and forgetting only another account's.
final bool confirmsSaved;
+ /// With [confirmsSaved], true draws the saved view as soon as it is read,
+ /// and false holds it until the first read has answered. Views are kept per
+ /// account and another account's is forgotten at sign-in, so what draws is
+ /// this account's own. A conversation it lost since shows until that first
+ /// read answers, as on the web (Dee, task #2169).
+ final bool drawsSavedAtOnce;
+
/// Whether the poll adapts at all; false is Desktop's fixed period.
bool get adapts => quietPoll != null || pausesAway;
}
diff --git a/desktop/lib/super_tabs/threads_view.dart b/desktop/lib/super_tabs/threads_view.dart
index c7869d4c7..ec834ac98 100644
--- a/desktop/lib/super_tabs/threads_view.dart
+++ b/desktop/lib/super_tabs/threads_view.dart
@@ -278,7 +278,11 @@ class _ThreadCardState extends State<_ThreadCard> {
if (at == null) return;
final token = '@$name';
final value = superTabInsertTag(_text.value, at, token);
- _c.setThreadDraft(_thread.rootId, value.text);
+ _c.setThreadDraft(
+ _thread.rootId,
+ value.text,
+ conversationId: _thread.conversationId,
+ );
_c.threadMention(id, token, to: _target);
_text.value = value;
_tagIndex.value = 0;
@@ -400,7 +404,11 @@ class _ThreadCardState extends State<_ThreadCard> {
bool get _busy => _c.uploading || _c.saving;
void _edited(String text) {
- _c.setThreadDraft(_thread.rootId, text);
+ _c.setThreadDraft(
+ _thread.rootId,
+ text,
+ conversationId: _thread.conversationId,
+ );
_tagIndex.value = 0;
_tagDismissed.value = null;
setState(() {});
@@ -412,7 +420,7 @@ class _ThreadCardState extends State<_ThreadCard> {
return;
}
final root = _thread.rootId;
- _c.setThreadDraft(root, _text.text);
+ _c.setThreadDraft(root, _text.text, conversationId: _thread.conversationId);
await _c.sendThreadReply(
to: _target,
onSending: () {
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index de6985b73..f936a62e1 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -456,10 +456,12 @@ class _SuperTabViewState extends State<SuperTabView>
advance(0);
}
- bool get _chatIsVisible {
+ bool get _chatIsVisible => !_chatCovered && _viewIsVisible;
+
+ /// A person can see this Swarm's chat area, whatever covers the chat itself.
+ bool get _viewIsVisible {
if (!mounted ||
!_viewEnabled ||
- _chatCovered ||
c.accessRevoked ||
_devicesVisible ||
_terminalsVisible ||
@@ -492,6 +494,12 @@ class _SuperTabViewState extends State<SuperTabView>
final sequence = c.messages(id).lastOrNull?.sequence ?? 0;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && !_jumpingToEnd) _readToEnd(id, sequence);
+ // A thread restored open counts as read only once its pane is seen.
+ if (mounted &&
+ c.openedThread?.conversationId == c.selectedId &&
+ _viewIsVisible) {
+ c.threadPaneShown();
+ }
});
// Widget updates already have a frame in progress. Reuse it so routine
// polling does not request an otherwise unnecessary frame after each build.
diff --git a/desktop/test/profile_cache_test.dart b/desktop/test/profile_cache_test.dart
new file mode 100644
index 000000000..cb0999b4d
--- /dev/null
+++ b/desktop/test/profile_cache_test.dart
@@ -0,0 +1,352 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_login.dart';
+import 'package:harness/auth/sign_in_provider.dart';
+import 'package:harness/bootstrap/environment_provisioner.dart';
+import 'package:harness/core/config.dart';
+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/pane_layout_store.dart';
+import 'package:harness/state/profile_cache.dart';
+import 'package:harness/ws/local_cli_discovery.dart';
+
+// Task #2169: the last profile of the same signed-in account shows at once, and another account's never does. A machine
+// row has one owner, and a new sign-in writes a session with no machine id until its own is resolved, so the machine id
+// `harness auth status` names proves the account with no network.
+
+class _Memory implements LocalKeyValueStore {
+ final values = <String, String>{};
+ @override
+ Future<String?> read(String key) async => values[key];
+ @override
+ Future<void> write(String key, String value) async => values[key] = value;
+ @override
+ Future<void> delete(String key) async => values.remove(key);
+}
+
+class _SlowWrites extends _Memory {
+ final release = Completer<void>();
+ @override
+ Future<void> write(String key, String value) async {
+ await release.future;
+ await super.write(key, value);
+ }
+}
+
+class _Api extends ApiClient {
+ _Api() : super(config: AppConfig.dev, session: AuthSession());
+ final profiles = <Completer<Map<String, dynamic>?>>[];
+ @override
+ Future<Map<String, dynamic>?> desk() async => null;
+ @override
+ Future<Map<String, dynamic>?> me() {
+ final answer = Completer<Map<String, dynamic>?>();
+ profiles.add(answer);
+ return answer.future;
+ }
+
+ @override
+ Future<List<Machine>> machines() async => const [];
+}
+
+class _Cli extends CliLogin {
+ _Cli(this.status);
+ CliAuthStatus status;
+ bool fails = false;
+ @override
+ Future<CliAuthStatus> checkStatus() async {
+ if (fails) throw CliNotAvailableException('no CLI');
+ return status;
+ }
+
+ @override
+ Future<void> login({
+ void Function(String url)? onAuthorizeUrl,
+ SignInProvider? provider,
+ }) async {}
+ @override
+ Future<void> logout() async {}
+}
+
+class _Environment extends EnvironmentProvisioner {
+ @override
+ Future<EnvironmentReadiness> ensureReady({
+ required void Function(EnvironmentReadiness value) onProgress,
+ EnvironmentReadiness? resumeFrom,
+ bool install = true,
+ EnvironmentSetupMode? mode,
+ }) async {
+ final ready = EnvironmentReadiness(
+ steps: {
+ for (final step in EnvironmentStep.values)
+ step: EnvironmentStepStatus.ready,
+ },
+ phase: EnvironmentSetupPhase.ready,
+ );
+ onProgress(ready);
+ return ready;
+ }
+}
+
+class _Discovery extends LocalCliDiscovery {
+ _Discovery() : super(config: AppConfig.dev);
+ @override
+ Future<String?> computerId() async => null;
+ @override
+ Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>
+ null;
+}
+
+class _App extends AppNotifier {
+ _App(_Cli cli, LocalKeyValueStore storage)
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ cliLogin: cli,
+ environmentProvisioner: _Environment(),
+ localCliDiscovery: _Discovery(),
+ paneLayoutStore: PaneLayoutStore(storage: storage),
+ );
+ Completer<void>? daemon;
+ CurrentUserProfile? atDaemon;
+ @override
+ Future<void> ensureCliDaemonReady() async {
+ await Future<void>.delayed(Duration.zero);
+ atDaemon = currentUser;
+ await daemon?.future;
+ }
+}
+
+Map<String, dynamic> _me(String id) => {
+ 'user': {'id': id, 'email': '[email protected]', 'name': id},
+};
+
+Future<void> _ticks() async {
+ for (var i = 0; i < 20; i++) {
+ await Future<void>.delayed(Duration.zero);
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late _Memory storage;
+ final apps = <_App>[];
+ final apis = <_Api>[];
+
+ Future<({_App app, _Api api, _Cli cli})> open(
+ String? machine, {
+ bool loggedIn = true,
+ }) async {
+ final api = _Api();
+ final cli = _Cli(CliAuthStatus(loggedIn: loggedIn, machineId: machine));
+ final app = _App(cli, storage)..api = api;
+ apps.add(app);
+ apis.add(api);
+ await app.bootstrap();
+ await _ticks();
+ return (app: app, api: api, cli: cli);
+ }
+
+ setUp(() => storage = _Memory());
+ tearDown(() {
+ for (final app in apps) {
+ app.dispose();
+ }
+ apps.clear();
+ });
+
+ Future<void> signedInBefore(String machine, String id) async {
+ final first = await open(machine);
+ first.api.profiles.single.complete(_me(id));
+ await _ticks();
+ expect(first.app.currentUser?.id, id);
+ }
+
+ test('the same machine shows the last profile before the daemon, the server or anything else answers', () async {
+ await signedInBefore('machine-a', 'ada');
+ final again = await open('machine-a');
+ expect(again.app.atDaemon?.id, 'ada');
+ expect(again.app.currentUser?.email, '[email protected]');
+ });
+
+ test('refreshes it behind: the server\'s answer replaces what shows, and what is kept', () async {
+ await signedInBefore('machine-a', 'ada');
+ final again = await open('machine-a');
+ again.api.profiles.single.complete({
+ 'user': {
+ 'id': 'ada',
+ 'email': '[email protected]',
+ 'name': 'Ada Lovelace',
+ },
+ });
+ await _ticks();
+ expect(again.app.currentUser?.name, 'Ada Lovelace');
+ final third = await open('machine-a');
+ expect(third.app.atDaemon?.name, 'Ada Lovelace');
+ });
+
+ test('another machine id shows nobody, and removes what was kept', () async {
+ await signedInBefore('machine-a', 'ada');
+ final other = await open('machine-b');
+ expect(other.app.atDaemon, isNull);
+ expect(other.app.currentUser, isNull);
+ expect(await ProfileCache(storage).read('machine-a'), isNull);
+ });
+
+ test(
+ 'a session with no machine id yet, or an older CLI, shows nobody',
+ () async {
+ await signedInBefore('machine-a', 'ada');
+ final other = await open(null);
+ expect(other.app.atDaemon, isNull);
+ expect(other.app.currentUser, isNull);
+ },
+ );
+
+ test('never keeps a profile with no machine id to prove it', () async {
+ final first = await open(null);
+ first.api.profiles.single.complete(_me('ada'));
+ await _ticks();
+ expect(storage.values, isNot(contains(ProfileCache.key)));
+ });
+
+ // Security review of #2617: someone signs in as another account in a terminal while the answer is on its way.
+ test('if the server names another account, it wins, and nothing is kept under the old machine', () async {
+ await signedInBefore('machine-a', 'ada');
+ final again = await open('machine-a');
+ again.api.profiles.single.complete(_me('grace'));
+ await _ticks();
+ expect(again.app.currentUser?.id, 'grace');
+ expect(storage.values, isNot(contains(ProfileCache.key)));
+ final later = await open('machine-a');
+ expect(later.app.atDaemon, isNull);
+ });
+
+ test('a first record waits for the CLI to name the same machine still: a sign-in meanwhile keeps nothing', () async {
+ final first = await open('machine-a');
+ first.cli.status = const CliAuthStatus(
+ loggedIn: true,
+ machineId: 'machine-b',
+ );
+ first.api.profiles.single.complete(_me('grace'));
+ await _ticks();
+ expect(first.app.currentUser?.id, 'grace');
+ expect(storage.values, isNot(contains(ProfileCache.key)));
+ });
+
+ test('a first record is not kept when the CLI cannot say', () async {
+ final first = await open('machine-a');
+ first.cli.fails = true;
+ first.api.profiles.single.complete(_me('ada'));
+ await _ticks();
+ expect(storage.values, isNot(contains(ProfileCache.key)));
+ });
+
+ test('a kept profile is asked about again when the backend returns, until one answer has come', () async {
+ await signedInBefore('machine-a', 'ada');
+ final again = await open('machine-a');
+ expect(again.app.currentUser?.id, 'ada');
+ again.api.profiles.single.completeError(StateError('backend down'));
+ await _ticks();
+ expect(again.app.currentUser?.id, 'ada');
+ again.app.noteBackendOnlineForTest(false);
+ again.app.noteBackendOnlineForTest(true);
+ await _ticks();
+ expect(again.api.profiles, hasLength(2));
+ again.api.profiles.last.complete(_me('grace'));
+ await _ticks();
+ expect(again.app.currentUser?.id, 'grace');
+ again.app.noteBackendOnlineForTest(false);
+ again.app.noteBackendOnlineForTest(true);
+ await _ticks();
+ expect(again.api.profiles, hasLength(2));
+ });
+
+ test('a signed-out computer shows nobody and removes it', () async {
+ await signedInBefore('machine-a', 'ada');
+ final out = await open(null, loggedIn: false);
+ expect(out.app.currentUser, isNull);
+ expect(storage.values, isNot(contains(ProfileCache.key)));
+ });
+
+ test('signing out removes it, and a late answer from before does not bring it back', () async {
+ await signedInBefore('machine-a', 'ada');
+ final again = await open('machine-a');
+ await again.app.logout();
+ expect(storage.values, isNot(contains(ProfileCache.key)));
+ again.api.profiles.single.complete(_me('ada'));
+ await _ticks();
+ expect(storage.values, isNot(contains(ProfileCache.key)));
+ });
+
+ test(
+ 'a sign-out during a write leaves nothing: the store takes them in order',
+ () async {
+ final slow = _SlowWrites();
+ final cache = ProfileCache(slow);
+ final write = cache.write(
+ 'machine-a',
+ const CurrentUserProfile(id: 'ada', email: '[email protected]'),
+ );
+ final clear = cache.clear();
+ slow.release.complete();
+ await Future.wait([write, clear]);
+ expect(slow.values, isEmpty);
+ },
+ );
+
+ group('what is kept on disk', () {
+ final good = {
+ 'machineId': 'machine-a',
+ 'id': 'ada',
+ 'email': '[email protected]',
+ 'name': 'Ada',
+ 'avatarUrl': null,
+ };
+ for (final (name, stored) in [
+ ('not JSON', 'not json'),
+ ('not an object', '[]'),
+ ('with no id', jsonEncode({...good, 'id': null})),
+ ('with an empty id', jsonEncode({...good, 'id': ''})),
+ ('with no email', jsonEncode({...good, 'email': null})),
+ ('of a wrong type', jsonEncode({...good, 'name': 7})),
+ ]) {
+ test('reads as none when it is $name', () async {
+ storage.values[ProfileCache.key] = stored;
+ expect(await ProfileCache(storage).read('machine-a'), isNull);
+ });
+ }
+
+ test('holds no more than who the person is', () async {
+ await ProfileCache(storage).write(
+ 'machine-a',
+ const CurrentUserProfile(
+ id: 'ada',
+ email: '[email protected]',
+ name: 'Ada',
+ ),
+ );
+ expect(
+ (jsonDecode(storage.values[ProfileCache.key]!) as Map).keys.toSet(),
+ {'machineId', 'id', 'email', 'name', 'avatarUrl'},
+ );
+ });
+
+ test(
+ 'a store that fails reads as none, and a failed write changes nothing',
+ () async {
+ expect(await ProfileCache(null).read('machine-a'), isNull);
+ await ProfileCache(null).write(
+ 'machine-a',
+ const CurrentUserProfile(id: 'ada', email: '[email protected]'),
+ );
+ await ProfileCache(null).clear();
+ },
+ );
+ });
+}
diff --git a/desktop/test/startup_order_test.dart b/desktop/test/startup_order_test.dart
new file mode 100644
index 000000000..c8ac93874
--- /dev/null
+++ b/desktop/test/startup_order_test.dart
@@ -0,0 +1,274 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_login.dart';
+import 'package:harness/auth/sign_in_provider.dart';
+import 'package:harness/bootstrap/environment_provisioner.dart';
+import 'package:harness/core/config.dart';
+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/pane_layout_store.dart';
+import 'package:harness/ws/local_cli_discovery.dart';
+
+// Task #2169: what does not depend on each other starts together, so a slow step costs only itself.
+
+class _Api extends ApiClient {
+ _Api() : super(config: AppConfig.dev, session: AuthSession());
+ @override
+ Future<Map<String, dynamic>?> desk() async => null;
+ @override
+ Future<Map<String, dynamic>?> me() =>
+ Completer<Map<String, dynamic>?>().future;
+ @override
+ Future<List<Machine>> machines() async => const [];
+}
+
+class _Cli extends CliLogin {
+ _Cli(this.answers);
+ final List<Future<CliAuthStatus> Function()> answers;
+ int asked = 0;
+ @override
+ Future<CliAuthStatus> checkStatus() => answers[asked++]();
+ @override
+ Future<void> login({
+ void Function(String url)? onAuthorizeUrl,
+ SignInProvider? provider,
+ }) async {}
+ @override
+ Future<void> logout() async {}
+}
+
+EnvironmentReadiness _ready() => EnvironmentReadiness(
+ steps: {
+ for (final step in EnvironmentStep.values)
+ step: EnvironmentStepStatus.ready,
+ },
+ phase: EnvironmentSetupPhase.ready,
+);
+
+class _Environment extends EnvironmentProvisioner {
+ _Environment({this.held, this.first});
+ final Completer<void>? held;
+ final EnvironmentReadiness? first;
+ final installs = <bool>[];
+ @override
+ Future<EnvironmentReadiness> ensureReady({
+ required void Function(EnvironmentReadiness value) onProgress,
+ EnvironmentReadiness? resumeFrom,
+ bool install = true,
+ EnvironmentSetupMode? mode,
+ }) async {
+ installs.add(install);
+ await held?.future;
+ final result = installs.length == 1 && first != null ? first! : _ready();
+ onProgress(result);
+ return result;
+ }
+}
+
+class _Discovery extends LocalCliDiscovery {
+ _Discovery() : super(config: AppConfig.dev);
+ @override
+ Future<String?> computerId() async => null;
+ @override
+ Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>
+ null;
+}
+
+class _HeldStore implements LocalKeyValueStore {
+ final held = Completer<void>();
+ int reads = 0;
+ @override
+ Future<String?> read(String key) async {
+ reads++;
+ await held.future;
+ return null;
+ }
+
+ @override
+ Future<void> write(String key, String value) async {}
+ @override
+ Future<void> delete(String key) async {}
+}
+
+class _App extends AppNotifier {
+ _App(_Cli cli, _Environment environment, {super.paneLayoutStore})
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ cliLogin: cli,
+ environmentProvisioner: environment,
+ localCliDiscovery: _Discovery(),
+ ) {
+ api = _Api();
+ }
+ int daemonChecks = 0;
+ Completer<void>? daemon;
+ @override
+ Future<void> ensureCliDaemonReady() async {
+ daemonChecks++;
+ await daemon?.future;
+ }
+}
+
+Future<void> _ticks() async {
+ for (var i = 0; i < 20; i++) {
+ await Future<void>.delayed(Duration.zero);
+ }
+}
+
+const _in = CliAuthStatus(loggedIn: true);
+const _out = CliAuthStatus(loggedIn: false);
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ final apps = <_App>[];
+ _App make(_Cli cli, _Environment environment, {PaneLayoutStore? panes}) {
+ final app = _App(cli, environment, paneLayoutStore: panes);
+ apps.add(app);
+ return app;
+ }
+
+ tearDown(() {
+ for (final app in apps.splice()) {
+ app.dispose();
+ }
+ });
+
+ test('asks whether this computer is signed in while the tools are still being looked at, once', () async {
+ final held = Completer<void>(), cli = _Cli([() async => _in]);
+ final app = make(cli, _Environment(held: held));
+ final boot = app.bootstrap();
+ await _ticks();
+ expect(cli.asked, 1);
+ expect(app.status, isNot(AppStatus.authenticated));
+ held.complete();
+ await boot;
+ expect(cli.asked, 1);
+ expect(app.status, AppStatus.authenticated);
+ expect(app.signedIn, isTrue);
+ });
+
+ test('a check that failed early, as with no CLI yet, is asked again once the tools are ready', () async {
+ final cli = _Cli([
+ () async => throw CliNotAvailableException('no CLI yet'),
+ () async => _in,
+ ]);
+ final app = make(cli, _Environment());
+ await app.bootstrap();
+ expect(cli.asked, 2);
+ expect(app.signedIn, isTrue);
+ });
+
+ test(
+ 'a check from before an install is not trusted: it is asked again after',
+ () async {
+ final review = EnvironmentReadiness(
+ steps: {
+ for (final step in EnvironmentStep.values)
+ step: EnvironmentStepStatus.pending,
+ },
+ phase: EnvironmentSetupPhase.review,
+ plan: const [
+ EnvironmentPlanItem(
+ step: EnvironmentStep.tmux,
+ title: 'tmux',
+ detail: 'tmux',
+ command: 'tmux',
+ ),
+ ],
+ );
+ final cli = _Cli([() async => _out, () async => _in]);
+ final environment = _Environment(first: review);
+ final app = make(cli, environment);
+ await app.bootstrap();
+ expect(environment.installs, contains(true));
+ expect(cli.asked, 2);
+ expect(app.signedIn, isTrue);
+ },
+ );
+
+ test(
+ 'a check answered before a sign-out never signs the app back in',
+ () async {
+ final held = Completer<void>(),
+ cli = _Cli([() async => _in, () async => _out]);
+ final app = make(cli, _Environment(held: held));
+ final boot = app.bootstrap();
+ await _ticks();
+ expect(cli.asked, 1);
+ await app.logout();
+ held.complete();
+ await boot;
+ await _ticks();
+ expect(app.signedIn, isFalse);
+ expect(app.currentUser, isNull);
+ },
+ );
+
+ test('checks the daemon while the saved tabs are still being read, and finishes only with both', () async {
+ final store = _HeldStore(), daemon = Completer<void>();
+ final app = make(
+ _Cli([() async => _in]),
+ _Environment(),
+ panes: PaneLayoutStore(storage: store),
+ )..daemon = daemon;
+ final boot = app.bootstrap();
+ await _ticks();
+ expect(store.reads, greaterThan(0));
+ expect(app.daemonChecks, 1);
+ daemon.complete();
+ await _ticks();
+ expect(app.status, isNot(AppStatus.authenticated));
+ store.held.complete();
+ await boot;
+ expect(app.status, AppStatus.authenticated);
+ });
+
+ test('a daemon that fails still waits for the saved tabs, then opens with its error', () async {
+ final store = _HeldStore();
+ final app = _FailingDaemon(
+ _Cli([() async => _in]),
+ _Environment(),
+ panes: PaneLayoutStore(storage: store),
+ );
+ apps.add(app);
+ final boot = app.bootstrap();
+ await _ticks();
+ expect(app.status, isNot(AppStatus.authenticated));
+ store.held.complete();
+ await boot;
+ expect(app.status, AppStatus.authenticated);
+ expect(app.lastError, contains('no daemon'));
+ });
+
+ test('keeps a stopwatch of the startup steps', () async {
+ final app = make(_Cli([() async => _in]), _Environment());
+ await app.bootstrap();
+ expect(
+ app.startupTimings.keys,
+ containsAll(<String>['signed-in check', 'tools', 'saved tabs', 'daemon']),
+ );
+ expect(startupLogLine(app.startupTimings), contains('daemon after '));
+ expect(startupLogLine(app.startupTimings), isNot(contains(r'\$')));
+ expect(startupLogLine({'daemon': 12}), 'daemon after 12 ms');
+ });
+}
+
+class _FailingDaemon extends _App {
+ _FailingDaemon(super.cli, super.environment, {PaneLayoutStore? panes})
+ : super(paneLayoutStore: panes);
+ @override
+ Future<void> ensureCliDaemonReady() async => throw StateError('no daemon');
+}
+
+extension on List<_App> {
+ List<_App> splice() {
+ final out = [...this];
+ clear();
+ return out;
+ }
+}
diff --git a/desktop/test/super_tab_reading_client_test.dart b/desktop/test/super_tab_reading_client_test.dart
index c834ec697..486a992d6 100644
--- a/desktop/test/super_tab_reading_client_test.dart
+++ b/desktop/test/super_tab_reading_client_test.dart
@@ -1,7 +1,9 @@
import 'dart:async';
+import 'dart:typed_data';
import 'package:fake_async/fake_async.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/harness_attachments.dart';
import 'package:harness/super_tabs/client.dart';
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/notifications.dart';
@@ -109,6 +111,142 @@ SuperTabClient _client(
void main() {
_pushGroup();
+
+ // Files are bytes, so only this running app keeps them: a Swarm let go gives them to its next controller.
+ group('pasted files across a Swarm being let go', () {
+ HarnessAttachment file(String name) =>
+ HarnessAttachment(name, Uint8List.fromList([1]));
+ List<String> names(HarnessAttachments files) => [
+ for (final f in files.files) f.name,
+ ];
+ SuperTabController opened(
+ SuperTabClient client,
+ FakeAsync async,
+ String id,
+ ) {
+ late SuperTabController c;
+ client.open(id).then((value) => c = value);
+ async.elapse(const Duration(seconds: 1));
+ return c;
+ }
+
+ SuperTabClient started(_Backend backend) =>
+ _client(backend, reading: SuperTabReading.desktop)..bind('owner');
+
+ test('come back to the chat and the thread they were for', () {
+ fakeAsync((async) {
+ final client = started(_Backend());
+ final first = opened(client, async, 'tab');
+ first.attachments('lead').add([file('chat.png')]);
+ first.threadAttachments('lead', 'message-1').add([file('thread.png')]);
+ client.release('tab');
+ async.flushMicrotasks();
+ final second = opened(client, async, 'tab');
+ expect(identical(first, second), isFalse);
+ expect(names(second.attachments('lead')), ['chat.png']);
+ expect(names(second.threadAttachments('lead', 'message-1')), [
+ 'thread.png',
+ ]);
+ client.dispose();
+ });
+ });
+
+ test(
+ 'are given once: a second close and open finds them again, not twice',
+ () {
+ fakeAsync((async) {
+ final client = started(_Backend());
+ opened(client, async, 'tab').attachments('lead').add([file('a.png')]);
+ client.release('tab');
+ async.flushMicrotasks();
+ opened(client, async, 'tab');
+ client.release('tab');
+ async.flushMicrotasks();
+ expect(names(opened(client, async, 'tab').attachments('lead')), [
+ 'a.png',
+ ]);
+ client.dispose();
+ });
+ },
+ );
+
+ test('never reach another account', () {
+ fakeAsync((async) {
+ final client = started(_Backend());
+ opened(client, async, 'tab').attachments('lead').add([file('a.png')]);
+ client.release('tab');
+ async.flushMicrotasks();
+ client.bind('someone-else');
+ async.flushMicrotasks();
+ expect(
+ opened(client, async, 'tab').attachments('lead').isEmpty,
+ isTrue,
+ );
+ client.dispose();
+ });
+ });
+
+ test('are not kept once access has gone', () {
+ fakeAsync((async) {
+ final client = started(_Backend());
+ final first = opened(client, async, 'tab');
+ first.attachments('lead').add([file('a.png')]);
+ first.revokeAccess('Access went.', keepSaved: true);
+ client.release('tab');
+ async.flushMicrotasks();
+ expect(
+ opened(client, async, 'tab').attachments('lead').isEmpty,
+ isTrue,
+ );
+ client.dispose();
+ });
+ });
+
+ test('go with a conversation that left while the Swarm was closed', () {
+ fakeAsync((async) {
+ final backend = _Backend();
+ final client = started(backend);
+ final first = opened(client, async, 'tab');
+ first.attachments('offline').add([file('a.png')]);
+ first.threadAttachments('offline', 'message-1').add([file('b.png')]);
+ client.release('tab');
+ async.flushMicrotasks();
+ (backend.servers['tab']!.state['conversations'] as List).removeWhere(
+ (g) => (g as Map)['id'] == 'offline',
+ );
+ final second = opened(client, async, 'tab');
+ expect(second.attachments('offline').isEmpty, isTrue);
+ expect(
+ second.threadAttachments('offline', 'message-1').isEmpty,
+ isTrue,
+ );
+ client.dispose();
+ });
+ });
+
+ test('the newest eight Swarms keep theirs, so closed ones cannot hold memory for good', () {
+ fakeAsync((async) {
+ final client = started(_Backend());
+ for (var n = 0; n < 9; n++) {
+ opened(
+ client,
+ async,
+ 'tab$n',
+ ).attachments('lead').add([file('$n.png')]);
+ client.release('tab$n');
+ async.flushMicrotasks();
+ }
+ expect(
+ opened(client, async, 'tab0').attachments('lead').isEmpty,
+ isTrue,
+ );
+ expect(names(opened(client, async, 'tab1').attachments('lead')), [
+ '1.png',
+ ]);
+ client.dispose();
+ });
+ });
+ });
test('only the Swarm tab on screen polls; the others wait until shown', () {
fakeAsync((async) {
final backend = _Backend();
@@ -318,6 +456,46 @@ void main() {
});
});
+ // Task #2169: the saved view of the account signed in draws at once; another account's is never read.
+ test('Desktop: the same account opens to its saved view before any read, and another account never does', () {
+ fakeAsync((async) {
+ final backend = _Backend(), storage = MemoryStore();
+ backend.servers['tab']!.append('For the owner only');
+ final first = _client(backend, storage: storage, reading: SuperTabReading.desktop)
+ ..bind('owner')
+ ..show('tab');
+ first.open('tab');
+ async.elapse(const Duration(seconds: 1));
+ first.show(null);
+ async.flushMicrotasks();
+ first.dispose();
+ backend.servers['tab']!.holdReads = Completer<void>();
+
+ final same = _client(backend, storage: storage, reading: SuperTabReading.desktop)
+ ..bind('owner')
+ ..show('tab');
+ SuperTabController? shown;
+ same.open('tab').then((c) => shown = c);
+ async.elapse(const Duration(seconds: 1));
+ expect(shown!.showingSaved, isTrue);
+ expect(shown!.snapshot, isNotNull);
+ same.dispose();
+ async.flushMicrotasks();
+
+ final other = _client(backend, storage: storage, reading: SuperTabReading.desktop)..bind('someone-else');
+ async.flushMicrotasks();
+ SuperTabController? theirs;
+ other.open('tab').then((c) => theirs = c);
+ async.elapse(const Duration(seconds: 1));
+ expect(theirs!.showingSaved, isFalse);
+ expect(theirs!.snapshot, isNull);
+ other.dispose();
+ backend.servers['tab']!.holdReads!.complete();
+ backend.servers['tab']!.holdReads = null;
+ async.flushMicrotasks();
+ });
+ });
+
test('a Swarm released while it opens never reads; its open fails', () {
fakeAsync((async) {
final backend = _Backend();
diff --git a/desktop/test/super_tab_saved_view_test.dart b/desktop/test/super_tab_saved_view_test.dart
index 429647846..d4cb5e8f3 100644
--- a/desktop/test/super_tab_saved_view_test.dart
+++ b/desktop/test/super_tab_saved_view_test.dart
@@ -291,6 +291,56 @@ void _controllerTests() {
});
// Review of #1791, 2: the saved read is no longer bounded.
+ // Task #2169: Desktop draws at once, as the saved view is this account's own (SuperTabSavedViews is keyed by account).
+ group('on Desktop', () {
+ test('a saved view draws before the first read answers, and the read replaces it', () {
+ final server = ConversationServer()..append('Please start.');
+ final view = _saved(server);
+ fakeAsync((async) {
+ server
+ ..append('Done.')
+ ..holdReads = Completer<void>();
+ final c = _controller(_Reads(server), reading: SuperTabReading.desktop)..drawSaved(view);
+ expect(c.snapshot!.name, 'Pilot');
+ expect(c.messages('lead').single.text, 'Please start.');
+ expect(c.showingSaved, isTrue);
+ expect(c.loading, isFalse);
+ c.start();
+ async.flushMicrotasks();
+ expect(c.showingSaved, isTrue);
+ server.holdReads!.complete();
+ server.holdReads = null;
+ async.flushMicrotasks();
+ expect(c.showingSaved, isFalse);
+ expect(c.messages('lead').map((m) => m.text), ['Please start.', 'Done.']);
+ c.dispose();
+ });
+ });
+
+ test('a first read that is refused takes the saved view off the screen', () {
+ final server = ConversationServer()..append('Hello');
+ final view = _saved(server);
+ fakeAsync((async) {
+ final c = SuperTabController(
+ tabId: 'tab',
+ accountId: 'owner',
+ request: (method, path, {body}) => Future.error(const SuperTabFailure('FORBIDDEN', 'You no longer have access.', statusCode: 403)),
+ save: server.save,
+ initial: {'tabId': 'tab', 'accountId': 'owner', 'selectedId': 'lead'},
+ reading: SuperTabReading.desktop,
+ )..drawSaved(view);
+ expect(c.snapshot, isNotNull);
+ c.start();
+ async.flushMicrotasks();
+ expect(c.accessRevoked, isTrue);
+ expect(c.showingSaved, isFalse);
+ expect(c.snapshot, isNull);
+ expect(c.messages('lead'), isEmpty);
+ c.dispose();
+ });
+ });
+ });
+
test('a saved view read after the Swarm was refused draws nothing', () {
final server = ConversationServer()..append('Hello');
final view = _saved(server);
@@ -1396,8 +1446,8 @@ void _clearTests() {
}
void _desktopTests() {
- test('a saved view is drawn only once the first read says what the '
- 'reader may still see', () {
+ test('a saved view draws at once, and what the reader lost since goes when '
+ 'the first read answers', () {
final server = ConversationServer()..append('Hello');
final view = _saved(server);
fakeAsync((async) {
@@ -1409,11 +1459,11 @@ void _desktopTests() {
final reads = _Reads(server);
final c = _controller(reads, reading: SuperTabReading.desktop)
..drawSaved(view);
- expect(c.snapshot, isNull);
+ expect(c.snapshot!.conversation('offline'), isNotNull);
+ expect(c.showingSaved, isTrue);
c.start();
async.flushMicrotasks();
- expect(c.snapshot, isNull);
- expect(c.showingSaved, isFalse);
+ expect(c.showingSaved, isTrue);
// Only what changed since the save, beside the open conversation.
expect(reads.paths, [
'/api/super-tabs/tab/conversations/lead/messages',
@@ -1429,8 +1479,8 @@ void _desktopTests() {
});
});
- test('a Swarm opened again reads what changed since, with its chat beside '
- 'it, and draws once that answers', () {
+ test('a Swarm opened again draws at once and reads what changed since, with '
+ 'its chat beside it', () {
fakeAsync((async) {
final server = ConversationServer()..append('Hello');
final store = MemoryStore();
@@ -1460,7 +1510,8 @@ void _desktopTests() {
SuperTabController? c;
second.open('tab').then((opened) => c = opened);
async.flushMicrotasks();
- expect(c!.snapshot, isNull);
+ expect(c!.snapshot!.name, 'Pilot');
+ expect(c!.showingSaved, isTrue);
expect(paths.where((p) => p.contains('/api/super-tabs/tab/')), [
'/api/super-tabs/tab/conversations/lead/messages',
startsWith('/api/super-tabs/tab/changes?cursor='),
diff --git a/desktop/test/super_tab_thread_composer_test.dart b/desktop/test/super_tab_thread_composer_test.dart
index a51c8c959..dc377d081 100644
--- a/desktop/test/super_tab_thread_composer_test.dart
+++ b/desktop/test/super_tab_thread_composer_test.dart
@@ -93,6 +93,7 @@ void main() {
WidgetTester tester,
ConversationServer server, {
String account = 'owner',
+ Map<String, dynamic>? initial,
}) async {
// One logical pixel per device pixel, so the platform's drop position
// needs no scaling on any host.
@@ -100,7 +101,7 @@ void main() {
addTearDown(tester.view.resetDevicePixelRatio);
await tester.binding.setSurfaceSize(const Size(1400, 900));
addTearDown(() => tester.binding.setSurfaceSize(null));
- final c = shown = server.controller(account: account);
+ final c = shown = server.controller(account: account, initial: initial);
await c.refresh();
await tester.pumpWidget(
MaterialApp(
@@ -535,6 +536,387 @@ void main() {
});
});
+ // Diego: a reply being written was gone after switching Swarms or quitting, while the main chat's draft came back.
+ group('a reply being written survives the Swarm being let go', () {
+ // A save is on a timer: on a busy machine it comes later, never sooner.
+ Future<void> savedSoon(bool Function() done) async {
+ for (var n = 0; n < 200 && !done(); n++) {
+ await Future<void>.delayed(const Duration(milliseconds: 25));
+ }
+ }
+
+ Future<SuperTabController> again(ConversationServer server) async {
+ final next = server.controller(account: 'owner', initial: server.saved);
+ addTearDown(next.dispose);
+ return next;
+ }
+
+ test('its text and its tags come back', () async {
+ final server = threaded();
+ final c = server.controller();
+ await c.refresh();
+ c.openThread('message-1');
+ c.setThreadDraft('message-1', 'Half a thought @Kestrel');
+ c.threadMention('agent-1', '@Kestrel');
+ await c.flush();
+ c.dispose();
+
+ final next = await again(server);
+ expect(next.threadDraft('message-1'), 'Half a thought @Kestrel');
+ expect(next.threadMentions('lead', 'message-1'), {'agent-1': '@Kestrel'});
+ });
+
+ test('typing saves soon, with no flush', () async {
+ final server = threaded();
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ c.setThreadDraft('message-1', 'typing', conversationId: 'lead');
+ await savedSoon(() => jsonEncode(server.saved).contains('typing'));
+ expect(jsonEncode(server.saved), contains('typing'));
+ });
+
+ test('an emptied reply comes back as nothing', () async {
+ final server = threaded();
+ final c = server.controller();
+ await c.refresh();
+ c.setThreadDraft('message-1', 'gone soon', conversationId: 'lead');
+ c.setThreadDraft('message-1', '', conversationId: 'lead');
+ await c.flush();
+ c.dispose();
+ expect(jsonEncode(server.saved), isNot(contains('gone soon')));
+ expect((await again(server)).threadDraft('message-1'), isEmpty);
+ });
+
+ test('a sent reply does not come back', () async {
+ final server = threaded();
+ final c = server.controller();
+ await c.refresh();
+ c.openThread('message-1');
+ await c.loadThread();
+ c.setThreadDraft('message-1', 'sent now');
+ await c.sendThreadReply();
+ await c.flush();
+ c.dispose();
+ expect((await again(server)).threadDraft('message-1'), isEmpty);
+ });
+
+ test(
+ 'the newest 500 are kept, and writing in one again makes it newest',
+ () async {
+ final server = threaded();
+ final c = server.controller();
+ await c.refresh();
+ for (var n = 0; n < 502; n++) {
+ c.setThreadDraft('root-$n', 'draft $n', conversationId: 'lead');
+ }
+ c.setThreadDraft('root-0', 'again', conversationId: 'lead');
+ await c.flush();
+ c.dispose();
+ final next = await again(server);
+ expect(next.threadDraft('root-0'), 'again');
+ expect(next.threadDraft('root-1'), isEmpty);
+ expect(next.threadDraft('root-2'), isEmpty);
+ expect(next.threadDraft('root-3'), 'draft 3');
+ expect(next.threadDraft('root-501'), 'draft 501');
+ },
+ );
+
+ test('goes when its conversation goes for this reader', () async {
+ final server = threaded();
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ c.setThreadDraft('message-1', 'private words', conversationId: 'offline');
+ c.setThreadDraft('message-2', 'kept', conversationId: 'lead');
+ await c.flush();
+ (server.state['conversations'] as List).removeWhere(
+ (g) => (g as Map)['id'] == 'offline',
+ );
+ await c.refresh();
+ await c.flush();
+ expect(c.threadDraft('message-1'), isEmpty);
+ expect(c.threadDraft('message-2'), 'kept');
+ expect(jsonEncode(server.saved), isNot(contains('private words')));
+ });
+
+ test(
+ 'the thread open beside the chat opens again, with its replies',
+ () async {
+ final server = threaded();
+ final c = server.controller();
+ await c.refresh();
+ c.openThread('message-1');
+ await c.flush();
+ c.dispose();
+ final next = await again(server);
+ expect(next.openedThread, (conversationId: 'lead', root: 'message-1'));
+ await next.refresh();
+ await pumpEventQueue();
+ expect(next.threadMessages('message-1'), isNotEmpty);
+ },
+ );
+
+ // The read mark is the account's, on every device: a controller can open with nothing on screen.
+ group('a thread that opened again', () {
+ Future<(ConversationServer, SuperTabController)> restored() async {
+ final server = threaded();
+ final c = server.controller();
+ await c.refresh();
+ c.openThread('message-1');
+ await c.flush();
+ await pumpEventQueue();
+ c.dispose();
+ server.threadMarkPosts.clear();
+ // From someone else: a reader's own reply is never unread.
+ server.append('A reply while the Swarm was closed.');
+ server.messages.last
+ ..['thread'] = 'message-1'
+ ..['replyTo'] = 'message-1'
+ ..['author'] = {
+ 'kind': 'person',
+ 'id': 'member',
+ 'name': '[email protected]',
+ };
+ return (server, await again(server));
+ }
+
+ test('marks nothing read while its pane is not on screen', () async {
+ final (server, next) = await restored();
+ await next.refresh();
+ await pumpEventQueue();
+ await next.refresh();
+ await pumpEventQueue();
+ expect(next.threadMessages('message-1'), isNotEmpty);
+ expect(server.threadMarkPosts, isEmpty);
+ final thread = next.thread('lead', 'message-1')!;
+ expect(next.threadUnread(thread), isTrue);
+ });
+
+ test('marks it read once its pane is shown', () async {
+ final (server, next) = await restored();
+ await next.refresh();
+ await pumpEventQueue();
+ next.threadPaneShown();
+ await pumpEventQueue();
+ expect(server.threadMarkPosts, isNotEmpty);
+ final thread = next.thread('lead', 'message-1')!;
+ expect(next.threadUnread(thread), isFalse);
+ });
+
+ test('opened by hand marks it read as before', () async {
+ final (server, next) = await restored();
+ await next.refresh();
+ await pumpEventQueue();
+ next.openThread('message-1');
+ await next.loadThread();
+ await pumpEventQueue();
+ expect(server.threadMarkPosts, isNotEmpty);
+ });
+
+ // A Swarm's view can be built while hidden: the canvas stays Offstage on a utility tab, and the app can start in the background.
+ Map<String, dynamic> savedOpen() => {
+ 'tabId': 'tab',
+ 'accountId': 'owner',
+ 'selectedId': 'lead',
+ 'openThread': {'conversationId': 'lead', 'root': 'message-1'},
+ };
+ Future<void> mountHidden(
+ WidgetTester tester,
+ SuperTabController c, {
+ required bool hidden,
+ }) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: TickerMode(
+ enabled: !hidden,
+ child: Offstage(
+ offstage: hidden,
+ child: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ testThread('a hidden pane marks nothing, and marks once it is shown', (
+ tester,
+ ) async {
+ await tester.binding.setSurfaceSize(const Size(1400, 900));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final server = threaded();
+ final c = shown = server.controller(initial: savedOpen());
+ addTearDown(c.dispose);
+ await c.refresh();
+ await mountHidden(tester, c, hidden: true);
+ expect(
+ find.byKey(const ValueKey('super-thread-panel'), skipOffstage: false),
+ findsOneWidget,
+ );
+ expect(server.threadMarkPosts, isEmpty);
+ await mountHidden(tester, c, hidden: false);
+ expect(server.threadMarkPosts, isNotEmpty);
+ });
+
+ testThread(
+ 'an app in the background marks nothing, and marks once it is back',
+ (tester) async {
+ await tester.binding.setSurfaceSize(const Size(1400, 900));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ addTearDown(
+ () => tester.binding.handleAppLifecycleStateChanged(
+ AppLifecycleState.resumed,
+ ),
+ );
+ final server = threaded();
+ tester.binding.handleAppLifecycleStateChanged(
+ AppLifecycleState.inactive,
+ );
+ final c = shown = server.controller(initial: savedOpen());
+ addTearDown(c.dispose);
+ await c.refresh();
+ await mountHidden(tester, c, hidden: false);
+ await tester.pump(const Duration(milliseconds: 50));
+ expect(server.threadMarkPosts, isEmpty);
+ tester.binding.handleAppLifecycleStateChanged(
+ AppLifecycleState.resumed,
+ );
+ await tester.pumpAndSettle();
+ expect(server.threadMarkPosts, isNotEmpty);
+ },
+ );
+
+ testThread('the real pane says it is shown', (tester) async {
+ final server = threaded();
+ await show(
+ tester,
+ server,
+ initial: {
+ 'tabId': 'tab',
+ 'accountId': 'owner',
+ 'selectedId': 'lead',
+ 'openThread': {'conversationId': 'lead', 'root': 'message-1'},
+ },
+ );
+ expect(panel, findsOneWidget);
+ await tester.pumpAndSettle();
+ expect(server.threadMarkPosts, isNotEmpty);
+ });
+ });
+
+ test('a thread closed before the Swarm was let go stays closed', () async {
+ final server = threaded();
+ final c = server.controller();
+ await c.refresh();
+ c.openThread('message-1');
+ c.closeThread();
+ await c.flush();
+ c.dispose();
+ expect((await again(server)).openedThread, isNull);
+ });
+
+ test('opening or closing a thread saves soon, with no flush', () async {
+ final server = threaded();
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ c.openThread('message-1');
+ await savedSoon(() => server.saved?['openThread'] != null);
+ expect(server.saved!['openThread'], isNotNull);
+ c.closeThread();
+ await savedSoon(() => server.saved!['openThread'] == null);
+ expect(server.saved!['openThread'], isNull);
+ });
+
+ test(
+ 'a saved thread in a conversation no longer read does not open',
+ () async {
+ final server = threaded();
+ final c = server.controller(
+ initial: {
+ 'tabId': 'tab',
+ 'accountId': 'owner',
+ 'selectedId': 'lead',
+ 'openThread': {'conversationId': 'not-mine', 'root': 'message-1'},
+ },
+ );
+ addTearDown(c.dispose);
+ await c.refresh();
+ expect(c.openedThread, isNull);
+ },
+ );
+
+ test('a malformed saved thread opens nothing', () {
+ final server = threaded();
+ for (final open in <Object?>[
+ 'nope',
+ {'conversationId': 1, 'root': 'message-1'},
+ {'conversationId': 'lead'},
+ ]) {
+ final c = server.controller(
+ initial: {'tabId': 'tab', 'accountId': 'owner', 'openThread': open},
+ );
+ addTearDown(c.dispose);
+ expect(c.openedThread, isNull);
+ }
+ });
+
+ test('another account finds none of them', () async {
+ final server = threaded();
+ final c = server.controller();
+ await c.refresh();
+ c.setThreadDraft('message-1', 'mine', conversationId: 'lead');
+ await c.flush();
+ c.dispose();
+ final other = server.controller(account: 'member', initial: server.saved);
+ addTearDown(other.dispose);
+ expect(other.threadDraft('message-1'), isEmpty);
+ });
+
+ test(
+ 'state from an older client, or a malformed entry, loads with none',
+ () {
+ final server = threaded();
+ for (final drafts in <Object?>[
+ null,
+ 'nope',
+ {'a': 'not a map'},
+ {
+ 'b': {'conversationId': 1, 'text': 'x'},
+ },
+ {
+ 'c': {'conversationId': 'lead', 'text': 2},
+ },
+ {
+ 'd': {'conversationId': 'lead', 'text': 'kept', 'mentions': 'nope'},
+ },
+ ]) {
+ final c = server.controller(
+ initial: {
+ 'tabId': 'tab',
+ 'accountId': 'owner',
+ 'threadDrafts': drafts,
+ },
+ );
+ addTearDown(c.dispose);
+ for (final root in ['a', 'b', 'c']) {
+ expect(c.threadDraft(root), isEmpty);
+ }
+ }
+ },
+ );
+ });
+
group('privacy and lifecycle', () {
test('each conversation\'s thread keeps its own files, even for the same '
'root id', () {
diff --git a/docs/plans/2026-11-02-desktop-opens-at-once-plan.md b/docs/plans/2026-11-02-desktop-opens-at-once-plan.md
new file mode 100644
index 000000000..76a0f32c0
--- /dev/null
+++ b/docs/plans/2026-11-02-desktop-opens-at-once-plan.md
@@ -0,0 +1,95 @@
+# Desktop Opens To Your Last Screen At Once Implementation Plan
+
+> **How this is worked:** by the project's instructions, task by task, each failing test committed before its code.
+
+**Goal:** Desktop opens to the last screen at once: independent startup steps run together, and the same account's profile and saved view show without waiting for the network.
+
+**Architecture:** The sign-in check starts beside the tool probe, and the restores beside the daemon check. The app keeps the last profile with the machine id it was read under, and uses it only when `harness auth status` names that same machine. A machine row has exactly one owner, and a new sign-in writes a session with no machine id until its own is resolved, so a match proves the account without a network call. Saved views are already stored per account, so with the account proven the Swarm draws its saved view at once and the first read replaces it.
+
+**Tech Stack:** Dart, Flutter 3.47.2, `flutter_test`.
+
+**Spec:** Task #2169 (Dee).
+
+## Global Constraints
+
+- Never draw another account's profile or saved view.
+- No on/off switch: the change ships on.
+- Tests use a memory store and a fake sign-in, and never reach the real CLI.
+- Swarm code stays out of `cli/src/core`. No CLI or backend change.
+- The PR body starts with: `Requested by [email protected] through Harness.`
+- Two security reviews: Cleo and Reed.
+
+## Review Focus
+
+1. **Someone signs in as another account in a terminal while the app is closed.** `auth status` names another machine or none, so the old profile is not used and is removed, and the app waits for the server's answer as it does today.
+2. **The server answers with a different account than the kept profile.** The answer wins, the account changes as it does at any sign-in, and the kept profile is replaced.
+3. **The early sign-in check fails or the CLI is missing,** as on a first run. It is asked again after setup, and a failure there is reported as today. A check from before an install is never trusted.
+4. **The person signs out or signs in while an early check is running.** A check from an older sign-in is dropped.
+5. **A corrupt, partial or old kept profile:** ignored, with no crash, as if none were kept.
+
+## What this narrows, on purpose
+
+`confirmsSaved` also promised that "a conversation the reader lost since is never on screen". Drawing at once means a conversation the same account lost access to can show until the first read answers, and the read then removes it. The web has always worked this way. The task asks for this, and another account's view stays out as before.
+
+## Design
+
+- **Growth:** one small record per device, replaced at each profile read, deleted at sign-out and on any mismatch.
+- **Concurrency:** the check and the probe share nothing. Each result is applied under the sign-in revision, so a late result can't touch a new sign-in.
+- **Read cost:** one extra local key read at startup, and no extra network calls.
+- **Scale:** N/A because it is one record per device.
+- **Compatibility:** with no machine id from an older CLI, nothing is cached and the app waits for the server, as today.
+- **Migration and rollback:** none. Rolling back leaves one unused key.
+- **Audience:** the record is the signed-in person's own name, email and avatar address, in the same local store as their saved tabs. No token.
+- **Identity:** the machine id from the CLI's session proves the account, never the machine's OS user.
+- **Failure:** any failed read of the record means none is used. The server's answer always replaces it.
+- **Platforms:** Desktop on macOS, Linux and Windows. A viewer (web, phone) has no CLI and keeps its current path.
+
+---
+
+### Task 1: Startup runs independent steps together
+
+**Files:**
+- Modify: `desktop/lib/state/app_state.dart`
+- Test: `desktop/test/startup_order_test.dart`
+
+**Interfaces:**
+- Produces: `AppNotifier.startupTimings` (a stopwatch's marks, logged as `startup: …`).
+
+- [ ] **Step 1: Commit the failing tests:** the sign-in check is asked while the tool probe is still held; a sign-in check that failed early is asked again after setup, and one from before an install is not used; the restores and the daemon check are both started while neither has finished; a check from an older sign-in is dropped.
+- [ ] **Step 2: Watch them fail:** `flutter test test/startup_order_test.dart`.
+- [ ] **Step 3: Implement** the early check and the joined restores, keeping `_ensurePool` after the restores.
+- [ ] **Step 4: Run them, and commit.** Expected: PASS.
+
+### Task 2: The kept profile
+
+**Files:**
+- Create: `desktop/lib/state/profile_cache.dart`
+- Modify: `desktop/lib/state/app_state.dart`
+- Test: `desktop/test/profile_cache_test.dart`
+
+**Interfaces:**
+- Produces: `ProfileCache(LocalKeyValueStore?)` with `read(String machineId) -> Future<CurrentUserProfile?>`, `write(String machineId, CurrentUserProfile)`, `clear()`.
+
+- [ ] **Step 1: Commit the failing tests:** the same machine id shows the kept profile before the server answers; another machine id or none shows nobody and removes it; the server's answer replaces it, and a different account's answer changes the account; sign-out removes it; a corrupt record reads as none; a profile with no id is never kept.
+- [ ] **Step 2: Watch them fail:** `flutter test test/profile_cache_test.dart`.
+- [ ] **Step 3: Implement.** The kept profile is set after the sign-in check and before the daemon check.
+- [ ] **Step 4: Run them, and commit.** Expected: PASS.
+
+### Task 3: The saved view draws at once
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/reading.dart`, `desktop/lib/super_tabs/controller.dart`
+- Test: `desktop/test/super_tab_saved_view_test.dart`
+
+**Interfaces:**
+- Produces: `SuperTabReading.drawsSavedAtOnce`, true for Desktop.
+
+- [ ] **Step 1: Commit the failing tests:** on Desktop's policy a saved view draws before the first read answers and the first read replaces it, removing a conversation the reader lost; a refused first read clears it; another account's saved view is never read, kept profile or not.
+- [ ] **Step 2: Watch them fail:** `flutter test test/super_tab_saved_view_test.dart`.
+- [ ] **Step 3: Implement,** without changing what `confirmsSaved` forgets.
+- [ ] **Step 4: Run them, and commit.** Expected: PASS.
+
+### Task 4: Timings and proof
+
+- [ ] **Step 1: Measure** startup and first-open timings before and after, with the same held steps in a test, since this Mac can't build the macOS app. Post them in a PR comment.
+- [ ] **Step 2: Run** the Desktop suite's boot, profile and Swarm tests, mark the PR ready, and ask Cleo and Reed.
diff --git a/docs/plans/2026-11-02-thread-draft-survives-plan.md b/docs/plans/2026-11-02-thread-draft-survives-plan.md
new file mode 100644
index 000000000..69c91c970
--- /dev/null
+++ b/docs/plans/2026-11-02-thread-draft-survives-plan.md
@@ -0,0 +1,86 @@
+# A thread reply survives a Swarm switch and a quit Implementation Plan
+
+> Implemented task by task in this session, test first, each failing test committed before its code.
+
+**Goal:** A thread reply being written comes back after switching Swarms or quitting, as the main chat draft does.
+
+**Architecture:** `SuperTabController._localState` saves each thread draft with its conversation and tags, and the open thread; the constructor restores them, and `setThreadDraft` schedules a save. Pasted files are bytes and are not saved: the client hands them from the released controller to the next one, in memory, so they survive a switch but not a quit, as the main chat's do.
+
+**Tech Stack:** Flutter, Dart, `flutter_test`.
+
+**Spec:** task #2144; repro on main `680b3224a`.
+
+## Global Constraints
+
+- Desktop tests use a memory store and a fake sign-in, and never drive the real app on this Mac.
+- A draft goes when its conversation goes for this reader, as a chat draft does.
+- Saved state stays small: at most 500 thread drafts, as `threadSeen`.
+- Saved state from an older client, with no thread drafts, still loads.
+- Files never reach another account: the client's in-memory hand-over ends with the account.
+
+## Review Focus
+
+1. A conversation removed for this reader while its thread draft is saved: the text is gone from memory and from the next save. Pinned in Task 1.
+2. A saved entry that is malformed, or from another account: ignored without breaking the load. Pinned in Task 1.
+3. Sending or clearing a reply: no old text comes back on the next start. Pinned in Task 1.
+4. A restored open thread in a conversation no longer readable: the pane does not open. Pinned in Task 2.
+5. Another account signing in, or access lost, before a Swarm is opened again: its files are not handed on. Pinned in Task 3.
+
+## Design
+
+- **Growth:** the newest 500 thread drafts are kept; a sent or emptied draft leaves at once. Files in memory are kept for the newest 8 Swarms let go, and end with the account or when their conversation goes.
+- **Concurrency:** saves already run one after another (`_persist`); this adds fields only.
+- **Read cost:** read once at the controller's start; a save writes the state it already writes.
+- **Scale:** 10x threads is capped at 500 drafts. Saved state's size warns first.
+- **Compatibility:** old state has no such key and loads with none; an older client ignores the new keys.
+- **Migration and rollback:** none; an older client drops the keys on its next save.
+- **Audience:** the state is this account's on this computer, checked by `tabId` and `accountId` as today. A removed conversation's draft goes.
+- **Identity:** the account id of the signed-in reader, as today.
+- **Failure:** a save that fails says so as a chat draft's does.
+- **Platforms:** all Desktop platforms; the same code path.
+
+## Limits
+
+- Files do not survive a quit: they are bytes, kept in memory only, as the main chat's are.
+- After access is revoked, saved text stays on this computer as a chat draft's does.
+
+---
+
+### Task 1: Thread drafts are saved and restored
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/controller.dart`, `desktop/lib/super_tabs/thread_panel.dart`, `desktop/lib/super_tabs/threads_view.dart`
+- Test: `desktop/test/super_tab_thread_composer_test.dart`
+
+**Interfaces:**
+- Produces: `setThreadDraft(String root, String text, {String? conversationId})`; state key `threadDrafts`.
+
+- [ ] **Step 1: Write the failing test and commit it.** Set a draft and a tag, flush, dispose, build from what was saved: both are there.
+- [ ] **Step 2: Run it to verify it fails:** `flutter test test/super_tab_thread_composer_test.dart`.
+- [ ] **Step 3: Implement it and commit.**
+
+### Task 2: The open thread reopens
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/controller.dart`
+- Test: `desktop/test/super_tab_thread_composer_test.dart`
+
+**Interfaces:**
+- Produces: state key `openThread`.
+
+- [ ] **Step 1: Write the failing test and commit it.**
+- [ ] **Step 2: Run it to verify it fails.**
+- [ ] **Step 3: Implement it and commit.**
+
+### Task 3: Pasted files survive a release
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/controller.dart`, `desktop/lib/super_tabs/client.dart`
+- Test: `desktop/test/super_tab_reading_client_test.dart`
+
+**Interfaces:**
+- Produces: `SuperTabKeptFiles get keptFiles`; `void adoptFiles(SuperTabKeptFiles kept)`.
+
+- [ ] **Step 1: Write the failing test and commit it.**
+- [ ] **Step 2: Run it to verify it fails.**
+- [ ] **Step 3: Implement it and commit.**