The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Batch L: saved views in private files (#2065), firmware manifest cache for keepalives (#2067) (#2068)
0xken15492eb30d29d6
diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.tsindex 7f5242296..90bf2f95b 100644--- a/cli/src/cable/cableHost.spec.ts+++ b/cli/src/cable/cableHost.spec.ts@@ -1,5 +1,5 @@// How the wheel's rows are composed: the local row, and the fleet's rows around it.-import { describe, expect, it, vi } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import { DaemonCableHost, cableEventFor, cableStepFor, type CableHostWiring } from './cableHost.js'import type { FleetMachine, MachineFleet } from './machineFleet.js'@@ -1040,3 +1040,56 @@ describe('Swarm cards', () => {expect(await bare.swarmCardRecap('st1', 'l1')).toBeNull()})})++describe('firmware release lookup', () => {+ // A dial on 9.9.9 is never offered the manifest's 0.0.1, so each call ends after the manifest read and+ // the count below is exactly the GETs a plugged-in dial costs.+ const manifest = { circle: { version: '0.0.1', url: 'https://x/fw.bin', sha256: 'a'.repeat(64), size: 1 } }+ function stubManifest(ok = () => true) {+ const fetch = vi.fn(async () => (ok() ? new Response(JSON.stringify(manifest)) : new Response('', { status: 503 })))+ vi.stubGlobal('fetch', fetch)+ return fetch+ }+ afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers() })++ it('answers repeat keepalives from the release it read, for 30 minutes', async () => {+ vi.useFakeTimers()+ const fetch = stubManifest()+ const host = new DaemonCableHost(wiring())+ await host.firmwareFor('9.9.9', 'circle')+ for (let i = 0; i < 19; i++) {+ vi.advanceTimersByTime(15_000)+ await host.firmwareFor('9.9.9', 'circle', true)+ }+ expect(fetch).toHaveBeenCalledTimes(1)+ vi.advanceTimersByTime(30 * 60_000)+ await host.firmwareFor('9.9.9', 'circle', true)+ expect(fetch).toHaveBeenCalledTimes(2)+ })++ it('reads the manifest at once unless a keepalive asks, and per OTA key', async () => {+ const fetch = stubManifest()+ const host = new DaemonCableHost(wiring())+ await host.firmwareFor('9.9.9', 'circle')+ await host.firmwareFor('9.9.9', 'circle')+ expect(fetch).toHaveBeenCalledTimes(2)+ await host.firmwareFor('9.9.9', 'harness-pro', true)+ expect(fetch).toHaveBeenCalledTimes(3)+ })++ it('never keeps a failed read: the next keepalive asks again', async () => {+ let up = true+ const fetch = stubManifest(() => up)+ const host = new DaemonCableHost(wiring())+ await host.firmwareFor('9.9.9', 'circle')+ up = false+ // Nor does an earlier good read stand in for it.+ await host.firmwareFor('9.9.9', 'circle')+ await host.firmwareFor('9.9.9', 'circle', true)+ expect(fetch).toHaveBeenCalledTimes(3)+ up = true+ await host.firmwareFor('9.9.9', 'circle', true)+ await host.firmwareFor('9.9.9', 'circle', true)+ expect(fetch).toHaveBeenCalledTimes(4)+ })+})diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.tsindex fd7e16e57..4640df63a 100644--- a/cli/src/cable/cableHost.ts+++ b/cli/src/cable/cableHost.ts@@ -19,7 +19,7 @@ import { join } from 'node:path'import { notificationReadToken, type UnreadNotification } from '../lib/notificationRead.js'import type { RegisteredSession } from '../lib/registry.js'-import { fetchRelease, loadImage, shouldOffer } from './fwPush.js'+import { fetchRelease, loadImage, shouldOffer, type FirmwareRelease } from './fwPush.js'import { routeVoiceTask, type RouterAgent, type RouterContinuity } from '../lib/voiceRouter.js'import { env } from '../config/env.js'import { FleetRouter } from '../services/fleetRouter.js'@@ -145,6 +145,9 @@ function isPlaceholder(id: string): boolean {return id.startsWith('cable:')}+/** How long a keepalive may be answered from the last manifest read — see firmwareFor. */+const RELEASE_KEEP_MS = 30 * 60_000+export class DaemonCableHost implements CableHost {/*** This host's own router: over the bare fleet it is given (its tests), or over none, for this computer@@ -162,6 +165,9 @@ export class DaemonCableHost implements CableHost {*/private selected = ''+ /** The last good manifest read per OTA key, for keepalives — see firmwareFor. */+ private readonly releases = new Map<string, { release: FirmwareRelease; at: number }>()+/*** `fleet` is a bare lane to the other machines for this host's own router — its tests give it one. A* daemon gives none: its dial reaches the fleet service's router through the core (`wiring.fleet`).@@ -731,9 +737,19 @@ export class DaemonCableHost implements CableHost {* only thing that could plug in, and a brick the moment a Pro could: its ESP32-P4 cannot run an* ESP32-S3 image, and the cable that would let us put it right is the firmware that just stopped.*/- async firmwareFor(runningVersion: string, key: string): Promise<{ version: string; image: Buffer; sha256: string } | null> {+ async firmwareFor(runningVersion: string, key: string, keepalive = false): Promise<{ version: string; image: Buffer; sha256: string } | null> {if (env.CABLE_FW_DISABLE) return null- const release = await fetchRelease(env.CABLE_FW_MANIFEST_URL, key)+ // A plugged-in dial greets every fifteen seconds, and each greeting read the manifest from GCS: 240 GETs+ // an hour per device, with the pets' sync waiting behind each one (2026-10-29). A keepalive is answered+ // from the last good read for half an hour, so a new image reaches a dial already plugged in within that;+ // a new dial, image or connection reads at once. A failed read is not kept, so the next greeting retries.+ const kept = this.releases.get(key)+ let release = keepalive && kept && Date.now() - kept.at < RELEASE_KEEP_MS ? kept.release : null+ if (!release) {+ release = await fetchRelease(env.CABLE_FW_MANIFEST_URL, key)+ if (release) this.releases.set(key, { release, at: Date.now() })+ else this.releases.delete(key)+ }if (!release || !shouldOffer(runningVersion, release.version)) return nullconst image = await loadImage(release, join(env.ADAPTER_DATA_DIR, 'firmware'), key)if (!image) return nulldiff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.tsindex a576318e2..3c4e33074 100644--- a/cli/src/cable/cableSession.spec.ts+++ b/cli/src/cable/cableSession.spec.ts@@ -1069,6 +1069,33 @@ describe('cable session', () => {await session.stop()})+ it('asks for a fresh release on a new dial, image or connection, and lets keepalives reuse one', async () => {+ const firmwareFor = vi.fn(async (_v: string, _key: string, _keepalive?: boolean) => null)+ const ports: LoopbackPort[] = []+ const session = new CableSession(makeHost({ firmwareFor }), tmpLog(), async (onData, onClosed) => {+ const p = new LoopbackPort(onData, onClosed)+ ports.push(p)+ return p+ })+ session.start()+ await vi.waitFor(() => expect(ports).toHaveLength(1))+ const hi = { t: 'hello', product: 'harness', fw: '0.0.1', proto: 2, mac: 'aa:bb' }+ for (const hello of [hi, hi, hi, { ...hi, fw: '0.0.2' }, { ...hi, fw: '0.0.2' }, { ...hi, fw: '0.0.2', mac: 'cc:dd' }]) {+ ports[0].say(hello)+ await settle()+ }+ await ports[0].close('unplugged')+ await vi.waitFor(() => expect(ports).toHaveLength(2), NEXT_TICKS)+ ports[1].say({ ...hi, fw: '0.0.2', mac: 'cc:dd' })+ await settle()+ expect(firmwareFor.mock.calls).toEqual([+ ['0.0.1', 'commander'], ['0.0.1', 'commander', true], ['0.0.1', 'commander', true],+ ['0.0.2', 'commander'], ['0.0.2', 'commander', true], ['0.0.2', 'commander'],+ ['0.0.2', 'commander'],+ ])+ await session.stop()+ })+it('offers the image to a SECOND dial, even after a first one took it', async () => {// Found in the field: one dial updated, was unplugged, and a second still on the old image was plugged// into the same daemon and never offered anything. `offered` held bare version strings, so it was adiff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.tsindex 997a6a30d..c1a237ab5 100644--- a/cli/src/cable/cableSession.ts+++ b/cli/src/cable/cableSession.ts@@ -456,9 +456,10 @@ export interface CableHost {pets?(): PetStore | null/*** The image to offer a dial running `runningVersion`, or null for "nothing to do" — which covers a- * dial that is current, a dev build that must not be touched, and an unreachable manifest.+ * dial that is current, a dev build that must not be touched, and an unreachable manifest. `keepalive`+ * says the same dial on the same image greeted again, so a recent manifest read may answer it.*/- firmwareFor?(runningVersion: string, key: string): Promise<{ version: string; image: Buffer; sha256: string } | null>+ firmwareFor?(runningVersion: string, key: string, keepalive?: boolean): Promise<{ version: string; image: Buffer; sha256: string } | null>/*** A dial greeted us, or the port went away.*@@ -1318,8 +1319,9 @@ export class CableSession {const settingsChanged = JSON.stringify(settings) !== JSON.stringify(this.greetedSettings)this.greetedSettings = settingsthis.skinReported = hasUiSkin(msg.settings)- if (settingsChanged && mac === this.greetedMac && fw === this.greetedFw) this.report()- if (mac !== this.greetedMac || fw !== this.greetedFw) {+ const keepalive = mac === this.greetedMac && fw === this.greetedFw+ if (settingsChanged && keepalive) this.report()+ if (!keepalive) {this.playerOffset = this.playerRequest = 0this.playerLibraryKey = ''const returning = mac === this.greetedMac@@ -1342,7 +1344,7 @@ export class CableSession {// Offered on every greeting, but only ONCE per version per session: accepting makes the dial erase// a flash slot before it answers, so a cadence of retries would spend erase cycles on the user's// hardware every fifteen seconds, and nothing about the next greeting changes what went wrong.- await this.maybeOfferFirmware(str('fw') ?? '')+ await this.maybeOfferFirmware(str('fw') ?? '', keepalive)// AFTER the firmware offer, so a pending image is already `this.transfer` and the pets wait for it.this.readPetHello(msg)await this.syncPets()@@ -1890,7 +1892,7 @@ export class CableSession {this.fwStall.unref?.()}- private async maybeOfferFirmware(runningVersion: string): Promise<void> {+ private async maybeOfferFirmware(runningVersion: string, keepalive: boolean): Promise<void> {// A pack in flight also holds it back: the reader task that writes flash is busy with the pack, and the// next hello (every fifteen seconds) asks again.if (!this.host.firmwareFor || this.transfer || this.petTransfer || !runningVersion) return@@ -1905,7 +1907,8 @@ export class CableSession {}return}- const candidate = await this.host.firmwareFor(runningVersion, key).catch(() => null)+ const ask = keepalive ? this.host.firmwareFor(runningVersion, key, true) : this.host.firmwareFor(runningVersion, key)+ const candidate = await ask.catch(() => null)// A pet transfer may have started while that await was parked (petsChanged); never start an image beside it.if (this.petTransfer || this.transfer) return// Keyed by DIAL as well as version. Holding bare version strings made this a statement about thediff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.mdindex eb0136c51..5a4406af7 100644--- a/desktop/CLAUDE.md+++ b/desktop/CLAUDE.md@@ -611,6 +611,9 @@ add a kind there, not at the call site.- All local state is in `HarnessFileStore` (`~/.harness/desktop-app/state.json`, mode 0600, keyedstrings behind `LocalKeyValueStore`): connection config, skipped update version, theme, font, panelayout. `~/.harness/computer-id` is the machine identity shared with the CLI.+ A Swarm's saved view (up to 512 KB of chat) is never in it: each is a private file of its own in+ `swarm-views/` beside it (`super_tabs/view_store_native.dart`), and the first use moves out any+ that Desktop builds from 1.3.27 on left in `state.json`. Tests that pass a memory store keep views there.- The window is frameless on macOS via `window_manager` (`lib/core/desktop_window.dart`, same size and`TitleBarStyle.hidden` as Grid). On macOS the tabs are native, in the title bar beside the trafficlights (`SwarmTitlebar.swift`); the pane headers are a `DragToMoveArea`. A screen thatdiff --git a/desktop/lib/core/harness_file_store_native.dart b/desktop/lib/core/harness_file_store_native.dartindex f423289ce..2ae7f7ee7 100644--- a/desktop/lib/core/harness_file_store_native.dart+++ b/desktop/lib/core/harness_file_store_native.dart@@ -78,6 +78,10 @@ class HarnessFileStore implements BatchLocalKeyValueStore {});}+ /// The keys the document holds, without their values.+ Future<Set<String>> keys() =>+ _serialized(() async => (await _readDocument()).keys.toSet());+@overrideFuture<void> write(String key, String value) => _serialized(() async {final values = await _readDocument();diff --git a/desktop/lib/core/snapshot_store_native.dart b/desktop/lib/core/snapshot_store_native.dartindex 5ff7813e8..f13bdd9f7 100644--- a/desktop/lib/core/snapshot_store_native.dart+++ b/desktop/lib/core/snapshot_store_native.dart@@ -1,6 +1,7 @@import 'dart:io';import 'harness_file_store.dart';+import 'posix_file_mode.dart';import 'snapshot_store.dart';/// The real one: `~/.harness/desktop-app/<name>.json`.@@ -8,7 +9,7 @@ import 'snapshot_store.dart';/// Written to a temporary file and renamed, so a crash mid-write leaves the/// previous snapshot rather than half of a new one.class FileSnapshotStore implements SnapshotStore {- FileSnapshotStore(this.name, {Directory? directory})+ FileSnapshotStore(this.name, {Directory? directory, this.private = false}): directory =directory ?? Directory(HarnessFileStore.defaultDirectoryPath());@@ -16,6 +17,11 @@ class FileSnapshotStore implements SnapshotStore {final String name;final Directory directory;+ /// True keeps it to this user, as `state.json` is ([HarnessFileStore]): the+ /// directory 0700 and the file 0600 from its first byte, for a snapshot that+ /// holds an account's content.+ final bool private;+File get file => File('${directory.path}/$name.json');@override@@ -33,9 +39,28 @@ class FileSnapshotStore implements SnapshotStore {Future<void> write(String contents) async {try {await directory.create(recursive: true);- final temporary = File('${file.path}.tmp');- await temporary.writeAsString(contents, flush: true);- await temporary.rename(file.path);+ if (!private) {+ final temporary = File('${file.path}.tmp');+ await temporary.writeAsString(contents, flush: true);+ await temporary.rename(file.path);+ return;+ }+ await _restrict(directory.path, 0x1c0);+ // Its own temporary: two windows writing one at once must not write+ // into the same file.+ final temporary = File(+ '${file.path}.$pid.${DateTime.now().microsecondsSinceEpoch}.tmp',+ );+ try {+ if (PosixFileMode.supported) {+ PosixFileMode.createExclusive(temporary.path, 0x180);+ }+ await temporary.writeAsString(contents, flush: true);+ await _restrict(temporary.path, 0x180);+ await temporary.rename(file.path);+ } finally {+ if (await temporary.exists()) await temporary.delete();+ }} on Object {// A snapshot that could not be written costs the next launch a recompute// and nothing else, so it must not turn good work into a failure.@@ -51,4 +76,12 @@ class FileSnapshotStore implements SnapshotStore {// replaces the file.}}++ /// Windows has no POSIX modes, and a phone's sandbox is already private to+ /// the app, as [HarnessFileStore] has it.+ static Future<void> _restrict(String path, int mode) async {+ if (!PosixFileMode.supported) return;+ if ((await FileStat.stat(path)).mode & 0xfff == mode) return;+ PosixFileMode.chmod(path, mode);+ }}diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex e0e883b56..11eb87ae3 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1756,7 +1756,7 @@ class AppNotifier extends ChangeNotifier {late final superTabs = SuperTabClient(storage: localStore ?? HarnessFileStore.shared,- viewStorage: localStore ?? swarmViewStore(),+ viewStorage: swarmViewStore(beside: localStore),upload: uploadWith(() => api),avatarUpload: uploadAvatarWith(() => api),onMention: superTabMentionNotice(systemNotifications),diff --git a/desktop/lib/super_tabs/saved_view.dart b/desktop/lib/super_tabs/saved_view.dartindex d2026c982..29f5d8e05 100644--- a/desktop/lib/super_tabs/saved_view.dart+++ b/desktop/lib/super_tabs/saved_view.dart@@ -4,6 +4,12 @@ import 'dart:convert';import '../core/local_key_value_store.dart';import 'parts.dart';+/// A store that keeps each view apart, and so can drop every view of an+/// account it holds, its index's or not ([SuperTabSavedViews.forgetAccount]).+abstract interface class SavedViewSweep {+ Future<void> sweepAccount(String account);+}+/// The last view of a Swarm tab as read: the state the tab draws and the open/// conversation's last page, kept on this device so the next open draws it at/// once and reads after ([SuperTabReading.drawsSaved]; the web, where that@@ -18,12 +24,19 @@ class SuperTabSavedViews {/// How many Swarms an account keeps a view of, most recently used first.static const maxTabs = 3;- String _key(String account, String tabId) => 'super_tab.view.$account.$tabId';- String _index(String account) => 'super_tab.views.$account';+ /// What a view's key starts with; the account and the Swarm follow.+ static const viewPrefix = 'super_tab.view.';++ /// The Swarms an account keeps a view of, most recently used first.+ static String indexKey(String account) => 'super_tab.views.$account';++ String _key(String account, String tabId) => '$viewPrefix$account.$tabId';+ String _index(String account) => indexKey(account);/// The account whose views this device keeps: the one to forget when/// another signs in, in this page or after a reload.- static const _owner = 'super_tab.saved_by';+ static const ownerKey = 'super_tab.saved_by';+ static const _owner = ownerKey;Future<void> _tail = Future.value();@@ -160,6 +173,9 @@ class SuperTabSavedViews {await storage.delete(_key(account, tab));}await storage.delete(_index(account));+ if (storage case final SavedViewSweep sweep) {+ await sweep.sweepAccount(account);+ }}/// Clear now: every view this device keeps, for [account] and for anydiff --git a/desktop/lib/super_tabs/view_store_native.dart b/desktop/lib/super_tabs/view_store_native.dartindex aa2332904..65d3b0ce5 100644--- a/desktop/lib/super_tabs/view_store_native.dart+++ b/desktop/lib/super_tabs/view_store_native.dart@@ -1,12 +1,203 @@+import 'dart:convert';import 'dart:io';import '../core/harness_file_store.dart';import '../core/local_key_value_store.dart';+import '../core/snapshot_store.dart';+import '../logging/app_log.dart';+import 'saved_view.dart';-/// Where Desktop keeps each Swarm's saved view: a file of its own beside the-/// app's `state.json`, which stays small because every setting rewrites it.-LocalKeyValueStore swarmViewStore() => HarnessFileStore(- directory: Directory(- '${HarnessFileStore.defaultDirectoryPath()}${Platform.pathSeparator}swarm-views',- ),-);+/// Where Desktop keeps each Swarm's saved view, given the app's settings store+/// [beside]: never in it. A store of another kind is a test's, which keeps+/// views with everything else.+LocalKeyValueStore swarmViewStore({LocalKeyValueStore? beside}) =>+ switch (beside) {+ null => SwarmViewFiles(HarnessFileStore.shared),+ final HarnessFileStore settings => SwarmViewFiles(settings),+ final other => other,+ };++/// Desktop's saved Swarm views ([SuperTabSavedViews]): each in a private file+/// of its own in `swarm-views/` beside the settings `state.json`, so keeping+/// one rewrites that view alone, and no setting, pane or theme write carries+/// any. Which Swarms an account keeps, and whose device this is, are a few+/// bytes in that folder's own `state.json`.+///+/// Desktop builds from 1.3.27 on wrote all of it into the settings document;+/// the first operation moves it out, once ([_moveOut]).+class SwarmViewFiles implements LocalKeyValueStore, SavedViewSweep {+ SwarmViewFiles(this.settings)+ : directory = Directory(+ '${settings.directory.path}${Platform.pathSeparator}swarm-views',+ ) {+ _small = HarnessFileStore(directory: directory);+ }++ /// The app's settings document, which keeps no view.+ final HarnessFileStore settings;+ final Directory directory;+ late final HarnessFileStore _small;++ static bool _isView(String key) =>+ key.startsWith(SuperTabSavedViews.viewPrefix);++ static bool _isSaved(String key) =>+ _isView(key) ||+ key.startsWith(SuperTabSavedViews.indexKey('')) ||+ key == SuperTabSavedViews.ownerKey;++ /// One file per account and Swarm, named so no id can leave the folder,+ /// and every file of an account, its temporaries too, starts with+ /// [_accountPrefix].+ FileSnapshotStore _file(String key) {+ final id = key.substring(SuperTabSavedViews.viewPrefix.length);+ final dot = id.indexOf('.');+ final account = dot < 0 ? id : id.substring(0, dot);+ final tab = dot < 0 ? '' : id.substring(dot + 1);+ return FileSnapshotStore(+ '${_accountPrefix(account)}${_name(tab)}',+ directory: directory,+ private: true,+ );+ }++ static String _name(String id) =>+ base64Url.encode(utf8.encode(id)).replaceAll('=', '');++ static String _accountPrefix(String account) => 'view.${_name(account)}.';++ /// Every file of [account], an index lists it or not: one a stop left+ /// between a view's write and its index's, and a temporary a stop left+ /// mid-write.+ @override+ Future<void> sweepAccount(String account) async {+ await _ready();+ final prefix = _accountPrefix(account);+ for (final entry in await _entries()) {+ if (_basename(entry).startsWith(prefix)) await _remove(entry);+ }+ }++ Future<List<FileSystemEntity>> _entries() async {+ try {+ return await directory.list().toList();+ } on FileSystemException {+ return const [];+ }+ }++ static String _basename(FileSystemEntity entry) =>+ entry.uri.pathSegments.lastWhere((s) => s.isNotEmpty, orElse: () => '');++ /// Deletes [entry]; one that will not go is logged, by the folder alone:+ /// a file's name carries the account.+ Future<void> _remove(FileSystemEntity entry) async {+ try {+ await File(entry.path).delete();+ } on PathNotFoundException {+ // Already gone.+ } on FileSystemException catch (error) {+ appLog.warn(+ 'swarm',+ 'a saved view in swarm-views was not deleted: '+ '${error.osError?.message ?? error.runtimeType}',+ );+ }+ }++ Future<void>? _moved;+ Future<void> _ready() => _moved ??= _moveOut();++ @override+ Future<String?> read(String key) async {+ await _ready();+ return _isView(key) ? _file(key).read() : _small.read(key);+ }++ @override+ Future<void> write(String key, String value) async {+ await _ready();+ return _isView(key) ? _file(key).write(value) : _small.write(key, value);+ }++ @override+ Future<void> delete(String key) async {+ await _ready();+ return _isView(key) ? _remove(_file(key).file) : _small.delete(key);+ }++ /// Moves the views kept in a document into their files: first those in this+ /// folder's own, then those in the settings document. A failure leaves the+ /// rest where it was for the next launch.+ Future<void> _moveOut() async {+ // A temporary a stop left mid-write holds a view no index will name.+ for (final entry in await _entries()) {+ final name = _basename(entry);+ if (name.startsWith('view.') && name.endsWith('.tmp')) {+ await _remove(entry);+ }+ }+ try {+ await _moveFrom(_small);+ await _moveFrom(settings);+ } catch (error) {+ appLog.warn(+ 'swarm',+ 'saved views not moved out yet: ${error.runtimeType}',+ );+ }+ }++ /// Only the views of the account whose device this is, and only those its+ /// index lists, move; any other goes. An old key stays until its file is+ /// written, and a file already there (newer, or written before a stop) is+ /// kept. Then the old keys go.+ Future<void> _moveFrom(HarnessFileStore source) async {+ final own = identical(source, _small);+ final saved = (await source.keys()).where(own ? _isView : _isSaved).toList()+ // The views first: the document shrinks at the first rewrite.+ ..sort((a, b) => (_isView(a) ? 0 : 1) - (_isView(b) ? 0 : 1));+ if (saved.isEmpty) return;+ final values = await source.readMany(saved);+ final ownerKey = SuperTabSavedViews.ownerKey;+ final owner = await _small.read(ownerKey) ?? values[ownerKey];+ final indexKey = owner == null ? null : SuperTabSavedViews.indexKey(owner);+ final index = indexKey == null+ ? null+ : await _small.read(indexKey) ?? values[indexKey];+ final kept = {+ for (final tab in _tabs(index))+ '${SuperTabSavedViews.viewPrefix}$owner.$tab',+ };+ for (final key in saved.where(_isView)) {+ final value = values[key];+ if (value == null || !kept.contains(key)) continue;+ final file = _file(key);+ if (await file.read() != null) continue;+ await file.write(value);+ if (await file.read() != value) {+ throw FileSystemException('saved view not written', directory.path);+ }+ }+ if (!own && owner != null) {+ if (await _small.read(ownerKey) == null) {+ await _small.write(ownerKey, owner);+ }+ if (index != null && await _small.read(indexKey!) == null) {+ await _small.write(indexKey, index);+ }+ }+ for (final key in saved) {+ await source.delete(key);+ }+ }++ static List<String> _tabs(String? index) {+ if (index == null) return const [];+ try {+ return (jsonDecode(index) as List).whereType<String>().toList();+ } catch (_) {+ return const [];+ }+ }+}diff --git a/desktop/lib/super_tabs/view_store_web.dart b/desktop/lib/super_tabs/view_store_web.dartindex efe145fb8..6fdc80161 100644--- a/desktop/lib/super_tabs/view_store_web.dart+++ b/desktop/lib/super_tabs/view_store_web.dart@@ -2,4 +2,5 @@ import '../core/harness_file_store.dart';import '../core/local_key_value_store.dart';/// A browser keeps saved views in its own storage, as it always has.-LocalKeyValueStore swarmViewStore() => HarnessFileStore.shared;+LocalKeyValueStore swarmViewStore({LocalKeyValueStore? beside}) =>+ beside ?? HarnessFileStore.shared;diff --git a/desktop/test/super_tab_saved_view_test.dart b/desktop/test/super_tab_saved_view_test.dartindex ee5a7bd24..429647846 100644--- a/desktop/test/super_tab_saved_view_test.dart+++ b/desktop/test/super_tab_saved_view_test.dart@@ -39,7 +39,8 @@ Map<String, dynamic> _view({String tab = 'tab', int pad = 0}) {}/// A view as a controller hands it over, for other tests.-Map<String, dynamic> savedViewForTest() => _view();+Map<String, dynamic> savedViewForTest({String tab = 'tab', int pad = 0}) =>+ _view(tab: tab, pad: pad);void main() {group('a controller', _controllerTests);diff --git a/desktop/test/swarm_view_files_test.dart b/desktop/test/swarm_view_files_test.dartnew file mode 100644index 000000000..c5574eccb--- /dev/null+++ b/desktop/test/swarm_view_files_test.dart@@ -0,0 +1,380 @@+// Desktop keeps each Swarm's saved view in a private file of its own beside+// the settings `state.json`, never in it: every setting, pane or theme write+// rewrites that document under its lock, and it holds credentials. Views the+// 1.3.27+ builds wrote into it move out once, for the account they belong to.+import 'dart:convert';+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/harness_file_store.dart';+import 'package:harness/logging/app_log.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/pane_layout_store.dart';+import 'package:harness/super_tabs/saved_view.dart';++import 'super_tab_saved_view_test.dart' show savedViewForTest;++class _RecordingLog implements AppLog {+ final warnings = <String>[];++ @override+ void record(+ AppLogLevel level,+ String category,+ String message, {+ Object? error,+ StackTrace? stackTrace,+ }) {+ if (level == AppLogLevel.warn && category == 'swarm') {+ warnings.add('$message ${error ?? ''}');+ }+ }+}++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ late Directory scratch;+ late HarnessFileStore settings;++ setUp(() async {+ scratch = await Directory.systemTemp.createTemp('swarm-view-files-test-');+ settings = HarnessFileStore(+ directory: Directory('${scratch.path}/desktop-app-v2'),+ );+ });++ tearDown(() async {+ if (await scratch.exists()) await scratch.delete(recursive: true);+ });++ /// The app as `appStateProvider` builds it, with its settings in [settings].+ AppNotifier app() {+ final app = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ paneLayoutStore: PaneLayoutStore(storage: settings),+ );+ addTearDown(app.dispose);+ return app;+ }++ SuperTabSavedViews views(AppNotifier app) =>+ SuperTabSavedViews(app.superTabs.viewStorage);++ /// What a 1.3.27+ build left in the settings document: the view, the+ /// account's index and whose device this is, all beside the credentials.+ Future<void> savedByOldBuild(+ HarnessFileStore store, {+ String account = 'owner',+ String tab = 'tab',+ int pad = 0,+ }) async {+ final old = SuperTabSavedViews(store);+ await old.claim(account);+ expect(await old.write(account, tab, savedViewForTest(pad: pad)), isTrue);+ }++ Directory viewsDirectory() =>+ Directory('${settings.directory.path}/swarm-views');++ List<File> viewFiles() {+ final directory = viewsDirectory();+ if (!directory.existsSync()) return const [];+ return directory+ .listSync()+ .whereType<File>()+ .where((f) => f.uri.pathSegments.last.startsWith('view.'))+ .where((f) => f.path.endsWith('.json'))+ .toList();+ }++ Future<Set<String>> savedKeys(HarnessFileStore store) async {+ if (!await store.stateFile.exists()) return {};+ final values =+ (jsonDecode(await store.stateFile.readAsString())+ as Map<String, dynamic>)['values']+ as Map<String, dynamic>;+ return values.keys+ .where(+ (k) =>+ k.startsWith('super_tab.view.') ||+ k.startsWith('super_tab.views.') ||+ k == 'super_tab.saved_by',+ )+ .toSet();+ }++ group('the real app', () {+ test('never hands saved views the settings store', () {+ final real = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ paneLayoutStore: PaneLayoutStore(),+ );+ addTearDown(real.dispose);+ expect(real.localStore, same(HarnessFileStore.shared));+ expect(real.superTabs.storage, same(HarnessFileStore.shared));+ expect(real.superTabs.viewStorage, isNot(same(HarnessFileStore.shared)));+ expect(real.superTabs.viewStorage, isNot(isA<HarnessFileStore>()));+ });++ test(+ 'writing a saved view leaves the settings state.json unchanged',+ () async {+ await settings.write('theme', 'dark');+ final before = await settings.stateFile.readAsBytes();+ final kept = views(app());+ await kept.claim('owner');+ expect(await kept.write('owner', 'tab', savedViewForTest()), isTrue);+ expect(await settings.stateFile.readAsBytes(), before);+ expect(viewFiles(), hasLength(1));+ expect(await kept.readInTurn('owner', 'tab'), isNotNull);+ },+ );+ });++ group('one file per Swarm', () {+ test('a view is a private file, in a private directory', () async {+ final kept = views(app());+ await kept.claim('owner');+ await kept.write('owner', 'tab', savedViewForTest());+ expect(viewFiles(), hasLength(1));+ final file = viewFiles().single;+ expect((await file.stat()).mode & 0xfff, 0x180); // 0600+ expect((await viewsDirectory().stat()).mode & 0xfff, 0x1c0); // 0700+ }, skip: Platform.isWindows);++ test("writing one Swarm's view leaves another's file as it was", () async {+ final kept = views(app());+ await kept.claim('owner');+ await kept.write('owner', 'a', savedViewForTest(tab: 'a'));+ expect(viewFiles(), hasLength(1));+ final a = viewFiles().single;+ final before = await a.readAsString();+ final modified = (await a.stat()).modified;+ await kept.write('owner', 'b', savedViewForTest(tab: 'b', pad: 1000));+ expect(viewFiles(), hasLength(2));+ expect(await a.readAsString(), before);+ expect((await a.stat()).modified, modified);+ });++ test('signing out removes the files', () async {+ final kept = views(app());+ await kept.claim('owner');+ await kept.write('owner', 'a', savedViewForTest(tab: 'a'));+ await kept.write('owner', 'b', savedViewForTest(tab: 'b'));+ expect(viewFiles(), hasLength(2));+ await kept.claim(null);+ expect(viewFiles(), isEmpty);+ });++ test("another account signing in removes the last one's files", () async {+ final kept = views(app());+ await kept.claim('owner');+ await kept.write('owner', 'tab', savedViewForTest());+ expect(viewFiles(), hasLength(1));+ await kept.claim('other');+ expect(viewFiles(), isEmpty);+ expect(await kept.readInTurn('owner', 'tab'), isNull);+ });+ });++ group('nothing of an account stays behind', () {+ /// A view of [account] no index lists (a stop between the view's write+ /// and its index's), and a temporary left beside its file by a stop+ /// mid-write.+ Future<void> leftovers(AppNotifier app, String account) async {+ final store = app.superTabs.viewStorage;+ final before = viewFiles().map((f) => f.path).toSet();+ await store.write(+ '${SuperTabSavedViews.viewPrefix}$account.lost',+ jsonEncode(savedViewForTest()),+ );+ final lost = viewFiles().singleWhere((f) => !before.contains(f.path));+ await File('${lost.path}.999.1.tmp').writeAsString('Pilot');+ }++ List<String> left() => viewsDirectory().existsSync()+ ? viewsDirectory()+ .listSync()+ .map((e) => e.uri.pathSegments.where((s) => s.isNotEmpty).last)+ .where((n) => n.startsWith('view.'))+ .toList()+ : const [];++ test(+ 'signing out removes its files, listed or not, temporaries too',+ () async {+ final shown = app();+ final kept = views(shown);+ await kept.claim('owner');+ await kept.write('owner', 'tab', savedViewForTest());+ await leftovers(shown, 'owner');+ expect(left(), hasLength(3));+ await kept.claim(null);+ expect(left(), isEmpty);+ },+ );++ test("another account signing in removes all of the last one's", () async {+ final shown = app();+ final kept = views(shown);+ await kept.claim('owner');+ await kept.write('owner', 'tab', savedViewForTest());+ await leftovers(shown, 'owner');+ await kept.claim('other');+ expect(left(), isEmpty);+ expect(await kept.write('other', 'tab', savedViewForTest()), isTrue);+ expect(left(), hasLength(1));+ });++ test("Clear now removes the account's unlisted files too", () async {+ final shown = app();+ final kept = views(shown);+ await kept.claim('owner');+ await kept.write('owner', 'tab', savedViewForTest());+ await leftovers(shown, 'owner');+ await kept.clear('owner');+ expect(left(), isEmpty);+ });++ test('a new start removes temporaries a stop left behind', () async {+ final kept = views(app());+ await kept.claim('owner');+ await kept.write('owner', 'tab', savedViewForTest());+ await File('${viewFiles().single.path}.999.1.tmp').writeAsString('Pilot');+ expect(left(), hasLength(2));++ final again = views(app());+ expect(await again.readInTurn('owner', 'tab'), isNotNull);+ expect(left(), hasLength(1));+ });++ test(+ 'a file that will not go is logged, without its path or content',+ () async {+ final log = _RecordingLog();+ final previous = appLog;+ appLog = log;+ addTearDown(() => appLog = previous);+ final kept = views(app());+ await kept.claim('owner');+ await kept.write('owner', 'tab', savedViewForTest());+ // A folder where the view's file was: no file delete removes it.+ final file = viewFiles().single;+ await file.delete();+ await File('${file.path}/inside').create(recursive: true);++ await kept.claim(null);+ expect(log.warnings, isNotEmpty);+ for (final warning in log.warnings) {+ expect(warning, isNot(contains(scratch.path)));+ expect(warning, isNot(contains('view.')));+ expect(warning, isNot(contains('Pilot')));+ }+ },+ skip: Platform.isWindows,+ );+ });++ group('the views an older build kept in state.json', () {+ test(+ 'still open, then leave it, and a theme flip writes under 50 KB',+ () async {+ await settings.write('theme', 'light');+ await savedByOldBuild(settings, pad: 204 * 1024);+ expect(await settings.stateFile.length(), greaterThan(200 * 1024));++ final kept = views(app());+ expect((await kept.readInTurn('owner', 'tab'))?['lastChangedAt'], 7);+ expect(viewFiles(), hasLength(1));+ expect(await savedKeys(settings), isEmpty);+ expect(await settings.read('theme'), 'light');++ await settings.write('theme', 'dark');+ expect(await settings.stateFile.length(), lessThan(50 * 1024));+ },+ );++ test("are kept for the same account, and its Swarms' order", () async {+ await savedByOldBuild(settings, tab: 'a');+ final old = SuperTabSavedViews(settings);+ await old.write('owner', 'b', savedViewForTest(tab: 'b'));++ final kept = views(app());+ // Still this account's device: a write keeps, and the index moved too.+ expect(+ await kept.write('owner', 'c', savedViewForTest(tab: 'c')),+ isTrue,+ );+ expect(viewFiles(), hasLength(3));+ await kept.write('owner', 'd', savedViewForTest(tab: 'd'));+ // Three per account, most recent first: 'a', the oldest, went.+ expect(await kept.readInTurn('owner', 'a'), isNull);+ expect(await kept.readInTurn('owner', 'b'), isNotNull);+ });++ test("another account's leftover view is deleted, never moved", () async {+ await savedByOldBuild(settings);+ // A view of an account that no longer uses this device.+ await settings.write(+ 'super_tab.view.ghost.tab',+ jsonEncode(savedViewForTest()),+ );+ await settings.write('super_tab.views.ghost', jsonEncode(['tab']));++ final kept = views(app());+ expect(await kept.readInTurn('owner', 'tab'), isNotNull);+ expect(await kept.readInTurn('ghost', 'tab'), isNull);+ expect(viewFiles(), hasLength(1));+ expect(await savedKeys(settings), isEmpty);+ expect(await settings.stateFile.readAsString(), isNot(contains('Pilot')));+ });++ test('a move cut short after the file was written finishes', () async {+ await savedByOldBuild(settings);+ final legacy = await settings.read('super_tab.view.owner.tab');+ final index = await settings.read('super_tab.views.owner');+ expect(await views(app()).readInTurn('owner', 'tab'), isNotNull);+ // As if the app stopped after the file but before the keys went.+ await settings.write('super_tab.view.owner.tab', legacy!);+ await settings.write('super_tab.views.owner', index!);+ await settings.write('super_tab.saved_by', 'owner');++ final again = views(app());+ expect(await again.readInTurn('owner', 'tab'), isNotNull);+ expect(viewFiles(), hasLength(1));+ expect(await savedKeys(settings), isEmpty);+ });++ test('a newer view in its file wins over an old key left behind', () async {+ await savedByOldBuild(settings);+ final legacy = await settings.read('super_tab.view.owner.tab');+ final first = views(app());+ final newer = savedViewForTest()..['lastChangedAt'] = 99;+ expect(await first.write('owner', 'tab', newer), isTrue);+ await settings.write('super_tab.view.owner.tab', legacy!);++ final again = views(app());+ expect((await again.readInTurn('owner', 'tab'))!['lastChangedAt'], 99);+ expect(await savedKeys(settings), isEmpty);+ });++ test('a view in the unused swarm-views state.json moves too', () async {+ final unused = HarnessFileStore(directory: viewsDirectory());+ await savedByOldBuild(unused);++ final kept = views(app());+ expect(await kept.readInTurn('owner', 'tab'), isNotNull);+ expect(viewFiles(), hasLength(1));+ final left = await unused.stateFile.readAsString();+ expect(left, isNot(contains('super_tab.view.owner.tab')));+ expect(await unused.stateFile.length(), lessThan(50 * 1024));+ });+ });+}