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.

feat(desktop): custom background from your own image

reinSPQR4a2bdf699ca2
diff --git a/CONTEXT.md b/CONTEXT.md
new file mode 100644
index 000000000..1ab4e12c1
--- /dev/null
+++ b/CONTEXT.md
@@ -0,0 +1,27 @@
+# Harness
+
+Harness runs and supervises coding agents across desktop, mobile, CLI and devices. This glossary fixes the words used across those apps.
+
+## Language
+
+### Appearance
+
+**Background**:
+The image or fill shown on an empty welcome or new-tab page; never shown behind agents or terminals.
+_Avoid_: Wallpaper, start background
+
+**Built-in background**:
+A background that ships with Harness, including the default Blank.
+_Avoid_: Default background, preset
+
+**Custom background**:
+The single background the user supplies from their own image; Harness keeps its own copy, so the original file can move or disappear.
+_Avoid_: Custom wallpaper, user image, uploaded background
+
+**Dim**:
+How much a custom background is darkened so the welcome text stays readable.
+_Avoid_: Overlay, opacity, brightness
+
+**Fit**:
+How a custom background is sized to the page: fill, fit, center or tile.
+_Avoid_: Scale mode, crop
diff --git a/desktop/design/wallpapers.md b/desktop/design/wallpapers.md
index a092e7cf9..0983b2c78 100644
--- a/desktop/design/wallpapers.md
+++ b/desktop/design/wallpapers.md
@@ -1,6 +1,6 @@
# New-tab wallpapers
-Blank remains the default and uses the selected tab's workspace color. Choose artwork under Customize Harness → Wallpaper. It appears only on empty welcome/new-tab pages. The welcome text and wallpaper stay mounted at their original position while the New Harness and Open Harness panels overlay the page.
+Blank remains the default and uses the selected tab's workspace color. Choose artwork under Customize Harness → Background. It appears only on empty welcome/new-tab pages. The welcome text and wallpaper stay mounted at their original position while the New Harness and Open Harness panels overlay the page.
The four images below were created with the built-in image generation tool. The PNG outputs were copied into the app without retouching. They are bundled locally; changing wallpaper does not make a network request. The center is deliberately quiet so the terminal-font welcome message remains readable.
@@ -39,6 +39,12 @@ Use case: stylized-concept. Asset type: minimal full-bleed 16:9 desktop wallpape
## Review
+## Custom background
+
+The last card in the picker takes the user's own image: click it to choose a file, or drop one on it. PNG, JPEG and WebP up to 20 MB are accepted. Harness keeps its own copy in `~/.harness/desktop-app-v2/backgrounds/`, scaled so the longest side is at most 3840px and flattened to one frame, so moving or deleting the original changes nothing. There is one slot: a new image replaces the copy, and Remove deletes it. Choosing a built-in background keeps the copy for a one-click return.
+
+While the custom background is selected, **Dim** (0–80%, default 40%) darkens it so the light welcome text stays readable, and **Fit** chooses fill (default), fit, center or tile. Center and tile show the image at real size, one image pixel per device pixel. A new image keeps both settings. If the copy goes missing, the page shows Blank and the card says "Image missing, choose again". The browser build has no folder to keep a copy in, so it hides the card. `test/custom_background_test.dart` covers import, persistence and the card.
+
Rendered app previews: [welcome with terminal wallpaper](review/welcome-terminal-wallpaper.png) and [keyboard shortcut popup](review/keyboard-shortcuts-browser.png).
`test/welcome_wallpaper_shortcuts_test.dart` loads the actual bundled images and renders the welcome content with the terminal font. It checks selection persistence, the blank default, font changes and compact layouts. `test/workspace_start_guide_test.dart` checks that opening and closing both command panels preserves the welcome text and wallpaper bounds, and that Customize Harness opens the wallpaper picker.
diff --git a/desktop/lib/settings/appearance/wallpaper_section.dart b/desktop/lib/settings/appearance/wallpaper_section.dart
index 0dccb4f33..b27ec5220 100644
--- a/desktop/lib/settings/appearance/wallpaper_section.dart
+++ b/desktop/lib/settings/appearance/wallpaper_section.dart
@@ -1,16 +1,24 @@
import 'dart:math' as math;
+import 'package:desktop_drop/desktop_drop.dart';
+import 'package:file_selector/file_selector.dart';
+import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
+import '../../core/desktop_window.dart';
import '../../shared/theme/app_theme.dart' as grid;
import '../../shared/theme/appearance_prefs_store.dart';
+import '../../shared/theme/custom_background.dart';
import '../../shared/theme/harness_background.dart';
import '../../widgets/swarm_wallpaper.dart';
class WallpaperSection extends StatelessWidget {
- const WallpaperSection({super.key, this.store});
+ const WallpaperSection({super.key, this.store, this.pickImage});
final AppearancePrefsStore? store;
+ /// Opens the file chooser; replaced in tests, which have no native dialog.
+ final Future<String?> Function()? pickImage;
+
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
@@ -21,7 +29,7 @@ class WallpaperSection extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
- 'Wallpaper',
+ 'Background',
style: grid.AppType.heading(color: grid.AppPalette.textPrimary),
),
const SizedBox(height: 8),
@@ -46,75 +54,336 @@ class WallpaperSection extends StatelessWidget {
for (final choice in HarnessBackground.gallery)
SizedBox(
width: width,
- child: Semantics(
- button: true,
+ child: _BackgroundCard(
+ key: ValueKey('wallpaper-${choice.name}'),
+ label: choice.label,
selected: value.background == choice,
- label: '${choice.label} wallpaper',
- child: Material(
- color: Colors.transparent,
- child: InkWell(
- key: ValueKey('wallpaper-${choice.name}'),
- onTap: () => prefs.setBackground(choice),
- borderRadius: BorderRadius.circular(8),
- child: Padding(
- padding: const EdgeInsets.all(3),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Container(
- clipBehavior: Clip.antiAlias,
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(8),
- border: Border.all(
- color: value.background == choice
- ? grid.AppPalette.swarmAccent
- : grid.AppPalette.divider,
- width: 2,
- ),
- ),
- child: AspectRatio(
- aspectRatio: 16 / 9,
- child: Stack(
- fit: StackFit.expand,
- children: [
- SwarmWallpaper(
- background: choice,
- thumbnail: true,
- ),
- if (value.background == choice)
- const Positioned(
- right: 8,
- bottom: 8,
- child: Icon(
- Icons.check_circle,
- color: Colors.white,
- size: 20,
- ),
- ),
- ],
- ),
- ),
- ),
- const SizedBox(height: 8),
- Text(
- choice.label,
- style: grid.AppType.label(
- color: grid.AppPalette.textPrimary,
- ),
- ),
- ],
- ),
- ),
- ),
+ onTap: () => prefs.setBackground(choice),
+ preview: SwarmWallpaper(
+ background: choice,
+ thumbnail: true,
+ store: prefs,
),
),
),
+ // The browser has no folder to keep a copy in.
+ if (!kIsWeb)
+ SizedBox(
+ width: width,
+ child: _CustomCard(
+ prefs: prefs,
+ value: value,
+ pickImage: pickImage ?? _pickImage,
+ ),
+ ),
],
);
},
),
+ if (!kIsWeb && value.background == HarnessBackground.custom) ...[
+ const SizedBox(height: 20),
+ _CustomControls(prefs: prefs, custom: value.custom),
+ ],
],
),
);
}
+
+ static Future<String?> _pickImage() async {
+ final file = await whileNativePicker(
+ () => openFile(
+ acceptedTypeGroups: const [
+ XTypeGroup(label: 'Images', extensions: customBackgroundExtensions),
+ ],
+ ),
+ );
+ return file?.path;
+ }
+}
+
+class _BackgroundCard extends StatelessWidget {
+ const _BackgroundCard({
+ super.key,
+ required this.label,
+ required this.selected,
+ required this.onTap,
+ required this.preview,
+ this.highlighted = false,
+ this.footer,
+ });
+ final String label;
+ final bool selected;
+ final VoidCallback onTap;
+ final Widget preview;
+
+ /// A file is being dragged over the card.
+ final bool highlighted;
+ final Widget? footer;
+
+ @override
+ Widget build(BuildContext context) {
+ return Semantics(
+ button: true,
+ selected: selected,
+ label: '$label background',
+ child: Material(
+ color: Colors.transparent,
+ child: InkWell(
+ onTap: onTap,
+ borderRadius: BorderRadius.circular(8),
+ child: Padding(
+ padding: const EdgeInsets.all(3),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Container(
+ clipBehavior: Clip.antiAlias,
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(8),
+ border: Border.all(
+ color: selected || highlighted
+ ? grid.AppPalette.swarmAccent
+ : grid.AppPalette.divider,
+ width: 2,
+ ),
+ ),
+ child: AspectRatio(
+ aspectRatio: 16 / 9,
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ preview,
+ if (selected)
+ const Positioned(
+ right: 8,
+ bottom: 8,
+ child: Icon(
+ Icons.check_circle,
+ color: Colors.white,
+ size: 20,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ label,
+ style: grid.AppType.label(color: grid.AppPalette.textPrimary),
+ ),
+ ?footer,
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// The user's own image: empty until one is chosen or dropped, then a card
+/// like the rest with Replace and Remove beneath it.
+class _CustomCard extends StatefulWidget {
+ const _CustomCard({
+ required this.prefs,
+ required this.value,
+ required this.pickImage,
+ });
+ final AppearancePrefsStore prefs;
+ final AppearancePrefs value;
+ final Future<String?> Function() pickImage;
+
+ @override
+ State<_CustomCard> createState() => _CustomCardState();
+}
+
+class _CustomCardState extends State<_CustomCard> {
+ bool _hovering = false;
+ bool _busy = false;
+ String? _error;
+
+ bool get _hasImage => widget.value.custom.image != null;
+
+ Future<void> _choose() async {
+ if (_busy) return;
+ final String? path;
+ try {
+ path = await widget.pickImage();
+ } catch (_) {
+ return;
+ }
+ if (path != null) await _use(path);
+ }
+
+ Future<void> _use(String path) async {
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ final error = await widget.prefs.chooseCustomBackground(path);
+ if (!mounted) return;
+ setState(() {
+ _busy = false;
+ _error = error;
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final muted = grid.AppType.label(color: grid.AppPalette.textSecondary);
+ return DropTarget(
+ key: const ValueKey('custom-background-drop'),
+ enable: !_busy,
+ onDragEntered: (_) => setState(() => _hovering = true),
+ onDragExited: (_) => setState(() => _hovering = false),
+ onDragDone: (details) async {
+ setState(() => _hovering = false);
+ if (details.files.isNotEmpty) await _use(details.files.first.path);
+ },
+ child: _BackgroundCard(
+ key: const ValueKey('wallpaper-custom'),
+ label: HarnessBackground.custom.label,
+ selected: widget.value.background == HarnessBackground.custom,
+ highlighted: _hovering,
+ onTap: _hasImage
+ ? () => widget.prefs.setBackground(HarnessBackground.custom)
+ : _choose,
+ preview: _busy
+ ? ColoredBox(
+ color: grid.AppPalette.swarmField,
+ child: const Center(
+ child: SizedBox.square(
+ dimension: 20,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ ),
+ )
+ : _hasImage
+ ? SwarmWallpaper(
+ background: HarnessBackground.custom,
+ thumbnail: true,
+ store: widget.prefs,
+ )
+ : ColoredBox(
+ key: const ValueKey('custom-background-empty'),
+ color: grid.AppPalette.panelBg,
+ child: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(
+ Icons.add_photo_alternate_outlined,
+ color: grid.AppPalette.textSecondary,
+ ),
+ const SizedBox(height: 6),
+ Text(
+ 'Choose image…',
+ style: grid.AppType.label(
+ color: grid.AppPalette.textPrimary,
+ ),
+ ),
+ Text('or drop one here', style: muted),
+ ],
+ ),
+ ),
+ ),
+ footer: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (_hasImage)
+ Wrap(
+ spacing: 8,
+ children: [
+ TextButton(
+ key: const ValueKey('custom-background-replace'),
+ onPressed: _busy ? null : _choose,
+ child: const Text('Replace…'),
+ ),
+ TextButton(
+ key: const ValueKey('custom-background-remove'),
+ onPressed: _busy
+ ? null
+ : () {
+ setState(() => _error = null);
+ widget.prefs.removeCustomBackground();
+ },
+ child: const Text('Remove'),
+ ),
+ ],
+ ),
+ if (_error case final error?)
+ Padding(
+ padding: const EdgeInsets.only(top: 4),
+ child: Text(
+ error,
+ key: const ValueKey('custom-background-error'),
+ style: grid.AppType.label(
+ color: Theme.of(context).colorScheme.error,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+/// Dim and fit, shown only while the custom background is selected: the
+/// built-in ones were drawn to be readable as they are.
+class _CustomControls extends StatelessWidget {
+ const _CustomControls({required this.prefs, required this.custom});
+ final AppearancePrefsStore prefs;
+ final CustomBackground custom;
+
+ @override
+ Widget build(BuildContext context) {
+ final label = grid.AppType.label(color: grid.AppPalette.textPrimary);
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text('Dim', style: label),
+ Row(
+ children: [
+ Expanded(
+ child: Slider(
+ key: const ValueKey('custom-background-dim'),
+ value: custom.dim,
+ max: CustomBackground.dimMax,
+ divisions: 16,
+ label: '${(custom.dim * 100).round()}%',
+ onChanged: (dim) => prefs.setCustomBackground(dim: dim),
+ ),
+ ),
+ SizedBox(
+ width: 44,
+ child: Text(
+ '${(custom.dim * 100).round()}%',
+ textAlign: TextAlign.end,
+ style: grid.AppType.label(color: grid.AppPalette.textSecondary),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 12),
+ Text('Fit', style: label),
+ const SizedBox(height: 8),
+ SegmentedButton<BackgroundFit>(
+ key: const ValueKey('custom-background-fit'),
+ showSelectedIcon: false,
+ segments: [
+ for (final fit in BackgroundFit.values)
+ ButtonSegment(
+ value: fit,
+ label: Text(fit.label, key: ValueKey('fit-${fit.name}')),
+ ),
+ ],
+ selected: {custom.fit},
+ onSelectionChanged: (selection) =>
+ prefs.setCustomBackground(fit: selection.first),
+ ),
+ ],
+ );
+ }
}
diff --git a/desktop/lib/shared/theme/appearance_prefs_store.dart b/desktop/lib/shared/theme/appearance_prefs_store.dart
index eaac0214a..b79e4b92f 100644
--- a/desktop/lib/shared/theme/appearance_prefs_store.dart
+++ b/desktop/lib/shared/theme/appearance_prefs_store.dart
@@ -1,10 +1,13 @@
import 'dart:convert';
+import 'dart:io';
import 'package:flutter/foundation.dart';
+import 'package:path/path.dart' as p;
import '../../core/harness_file_store.dart';
import '../../core/local_key_value_store.dart';
import 'color_palette.dart';
+import 'custom_background.dart';
import 'harness_background.dart';
import 'prompt_style.dart';
@@ -18,6 +21,7 @@ class AppearancePrefs {
this.uiSize = uiSizeDefault,
this.palette = HarnessPalette.graphite,
this.background = HarnessBackground.plain,
+ this.custom = const CustomBackground(),
this.prompt = const PromptPrefs(),
});
@@ -25,6 +29,10 @@ class AppearancePrefs {
final HarnessPalette palette;
final HarnessBackground background;
+ /// Kept while a built-in background is showing, so switching back is one
+ /// click.
+ final CustomBackground custom;
+
/// Legacy fields, retained for settings compatibility with older builds.
final String? uiFamily;
final double uiSize;
@@ -41,6 +49,7 @@ class AppearancePrefs {
double? uiSize,
HarnessPalette? palette,
HarnessBackground? background,
+ CustomBackground? custom,
PromptPrefs? prompt,
bool clearUiFamily = false,
}) => AppearancePrefs(
@@ -48,6 +57,7 @@ class AppearancePrefs {
uiSize: uiSize ?? this.uiSize,
palette: palette ?? this.palette,
background: background ?? this.background,
+ custom: custom ?? this.custom,
prompt: prompt ?? this.prompt,
);
@@ -58,11 +68,12 @@ class AppearancePrefs {
other.uiSize == uiSize &&
other.palette == palette &&
other.background == background &&
+ other.custom == custom &&
other.prompt == prompt;
@override
int get hashCode =>
- Object.hash(uiFamily, uiSize, palette, background, prompt);
+ Object.hash(uiFamily, uiSize, palette, background, custom, prompt);
}
/// The user's appearance choices, remembered across launches.
@@ -73,20 +84,37 @@ class AppearancePrefs {
/// above every provider scope in this app, and these values have to resolve
/// before there is a scope at all.
class AppearancePrefsStore extends ValueNotifier<AppearancePrefs> {
- AppearancePrefsStore({LocalKeyValueStore? storage})
- : _storage = storage ?? HarnessFileStore.shared,
- super(const AppearancePrefs());
+ AppearancePrefsStore({
+ LocalKeyValueStore? storage,
+ this._backgroundsDirectory,
+ }) : _storage = storage ?? HarnessFileStore.shared,
+ super(const AppearancePrefs());
static const _familyKey = 'app_ui_font_family';
static const _sizeKey = 'app_ui_font_size';
static const _paletteKey = 'app_color_palette';
static const _backgroundKey = 'harness_start_background';
+ static const _customKey = 'harness_custom_background';
static const _promptKey = 'workspace_prompt_v1';
Future<void>? _promptSave;
Future<void>? _paletteSave;
Future<void>? _backgroundSave;
+ Future<void>? _customSave;
final LocalKeyValueStore _storage;
+ final Directory? _backgroundsDirectory;
+
+ /// Harness's copies of custom backgrounds, beside `state.json`. Resolved on
+ /// first use: the browser build has no such folder and never asks for it.
+ Directory get backgroundsDirectory =>
+ _backgroundsDirectory ??
+ Directory(p.join(HarnessFileStore.defaultDirectoryPath(), 'backgrounds'));
+
+ /// The copy the custom background shows, or `null` when there is none.
+ File? get customBackgroundFile => switch (value.custom.image) {
+ final name? => File(p.join(backgroundsDirectory.path, name)),
+ null => null,
+ };
/// Read the saved choices, if there are any.
///
@@ -100,13 +128,21 @@ class AppearancePrefsStore extends ValueNotifier<AppearancePrefs> {
_sizeKey,
_paletteKey,
_backgroundKey,
+ _customKey,
_promptKey,
]);
+ final custom = _customFrom(saved[_customKey]);
+ final background = HarnessBackground.fromId(saved[_backgroundKey]);
value = AppearancePrefs(
uiFamily: _familyFrom(saved[_familyKey]),
uiSize: _sizeFrom(saved[_sizeKey]),
palette: HarnessPalette.fromId(saved[_paletteKey]),
- background: HarnessBackground.fromId(saved[_backgroundKey]),
+ // Custom with no image to show is Blank, not an empty selection.
+ background:
+ background == HarnessBackground.custom && custom.image == null
+ ? HarnessBackground.plain
+ : background,
+ custom: custom,
prompt: _promptFrom(saved[_promptKey]),
);
} catch (_) {
@@ -158,6 +194,70 @@ class AppearancePrefsStore extends ValueNotifier<AppearancePrefs> {
}
}
+ /// Dim and fit changes; the image itself changes only through
+ /// [chooseCustomBackground] and [removeCustomBackground].
+ Future<void> setCustomBackground({double? dim, BackgroundFit? fit}) =>
+ _setCustom(value.custom.copyWith(dim: dim, fit: fit));
+
+ /// Copies the image at [path] into Harness and shows it. Returns a line to
+ /// show the person when the file is refused; the current background stays.
+ Future<String?> chooseCustomBackground(String path) async {
+ final directory = backgroundsDirectory;
+ final String name;
+ try {
+ name = await importCustomBackground(path, directory);
+ } on CustomBackgroundError catch (error) {
+ return error.message;
+ }
+ await Future.wait([
+ _setCustom(value.custom.copyWith(image: name)),
+ setBackground(HarnessBackground.custom),
+ ]);
+ // Only once the new name is saved, so a crash in between never leaves the
+ // preferences pointing at a deleted file.
+ await pruneCustomBackgrounds(directory, keep: name);
+ return null;
+ }
+
+ /// Forgets the custom image and deletes Harness's copy. Blank takes over if
+ /// it was showing.
+ Future<void> removeCustomBackground() async {
+ await Future.wait([
+ if (value.background == HarnessBackground.custom)
+ setBackground(HarnessBackground.plain),
+ _setCustom(value.custom.copyWith(clearImage: true)),
+ ]);
+ await pruneCustomBackgrounds(backgroundsDirectory);
+ }
+
+ Future<void> _setCustom(CustomBackground custom) {
+ if (value.custom == custom) return _customSave ?? Future.value();
+ value = value.copyWith(custom: custom);
+ return _customSave ??= _saveCustom();
+ }
+
+ Future<void> _saveCustom() async {
+ try {
+ while (true) {
+ final custom = value.custom;
+ await _storage.write(_customKey, jsonEncode(custom.toJson()));
+ if (value.custom == custom) break;
+ }
+ } catch (_) {
+ // Keep the custom background for this run if storage is unavailable.
+ } finally {
+ _customSave = null;
+ }
+ }
+
+ static CustomBackground _customFrom(String? raw) {
+ try {
+ return CustomBackground.fromJson(raw == null ? null : jsonDecode(raw));
+ } catch (_) {
+ return const CustomBackground();
+ }
+ }
+
static PromptPrefs _promptFrom(String? raw) {
try {
return PromptPrefs.fromJson(raw == null ? null : jsonDecode(raw));
@@ -223,12 +323,14 @@ class AppearancePrefsStore extends ValueNotifier<AppearancePrefs> {
value = const AppearancePrefs();
await _paletteSave;
await _backgroundSave;
+ await _customSave;
await _promptSave;
try {
await _storage.delete(_familyKey);
await _storage.delete(_sizeKey);
await _storage.delete(_paletteKey);
await _storage.delete(_backgroundKey);
+ await _storage.delete(_customKey);
await _storage.delete(_promptKey);
} catch (_) {
// See above.
diff --git a/desktop/lib/shared/theme/custom_background.dart b/desktop/lib/shared/theme/custom_background.dart
new file mode 100644
index 000000000..38c194bfd
--- /dev/null
+++ b/desktop/lib/shared/theme/custom_background.dart
@@ -0,0 +1,199 @@
+import 'dart:io';
+import 'dart:math' as math;
+import 'dart:ui' as ui;
+
+import 'package:flutter/foundation.dart';
+import 'package:path/path.dart' as p;
+
+/// How a custom background is sized to the page.
+enum BackgroundFit {
+ fill('Fill'),
+ fit('Fit'),
+ center('Center'),
+ tile('Tile');
+
+ const BackgroundFit(this.label);
+ final String label;
+
+ static BackgroundFit fromId(Object? id) =>
+ values.where((value) => value.name == id).firstOrNull ?? fill;
+}
+
+/// The one image the user supplied, and how it is shown.
+///
+/// [image] names Harness's own copy inside the backgrounds folder, never the
+/// file the user picked: that one may move, be unplugged or be deleted. A new
+/// name per import also retires the old copy from Flutter's image cache.
+@immutable
+class CustomBackground {
+ const CustomBackground({
+ this.image,
+ this.dim = dimDefault,
+ this.fit = BackgroundFit.fill,
+ });
+
+ final String? image;
+ final double dim;
+ final BackgroundFit fit;
+
+ static const double dimDefault = 0.4;
+ static const double dimMax = 0.8;
+
+ CustomBackground copyWith({
+ String? image,
+ double? dim,
+ BackgroundFit? fit,
+ bool clearImage = false,
+ }) => CustomBackground(
+ image: clearImage ? null : (image ?? this.image),
+ dim: dim == null ? this.dim : _clampDim(dim),
+ fit: fit ?? this.fit,
+ );
+
+ Map<String, Object?> toJson() => {
+ if (image != null) 'image': image,
+ 'dim': dim,
+ 'fit': fit.name,
+ };
+
+ /// Tolerant like the rest of the appearance file: anything unreadable lands
+ /// on the default rather than throwing.
+ factory CustomBackground.fromJson(Object? json) {
+ if (json is! Map) return const CustomBackground();
+ final image = json['image'];
+ final dim = json['dim'];
+ return CustomBackground(
+ // A bare file name only: a hand-edited path must not point outside the
+ // backgrounds folder.
+ image: image is String && image.isNotEmpty && p.basename(image) == image
+ ? image
+ : null,
+ dim: dim is num ? _clampDim(dim.toDouble()) : dimDefault,
+ fit: BackgroundFit.fromId(json['fit']),
+ );
+ }
+
+ static double _clampDim(double dim) =>
+ dim.isFinite ? dim.clamp(0.0, dimMax) : dimDefault;
+
+ @override
+ bool operator ==(Object other) =>
+ other is CustomBackground &&
+ other.image == image &&
+ other.dim == dim &&
+ other.fit == fit;
+
+ @override
+ int get hashCode => Object.hash(image, dim, fit);
+}
+
+/// A file Harness will not use as a background, with a line for the person.
+class CustomBackgroundError implements Exception {
+ const CustomBackgroundError(this.message);
+ final String message;
+
+ @override
+ String toString() => message;
+}
+
+const customBackgroundExtensions = ['png', 'jpg', 'jpeg', 'webp'];
+const customBackgroundMaxBytes = 20 * 1024 * 1024;
+
+/// Longest side kept. Larger images are scaled down on import so memory and
+/// first paint stay predictable, whatever a camera produced.
+const customBackgroundMaxSide = 3840;
+
+/// Copies [sourcePath] into [directory] and returns the copy's file name.
+///
+/// The image is decoded here, not just checked by extension, so a broken file
+/// is refused now rather than painting Blank later. It is re-encoded as PNG
+/// only when it has to change: when it is too large, or animated (a background
+/// holds still).
+Future<String> importCustomBackground(
+ String sourcePath,
+ Directory directory,
+) async {
+ final extension = p.extension(sourcePath).toLowerCase().replaceFirst('.', '');
+ if (!customBackgroundExtensions.contains(extension)) {
+ throw const CustomBackgroundError('Use a PNG, JPEG or WebP image.');
+ }
+ final Uint8List bytes;
+ try {
+ final source = File(sourcePath);
+ if (await source.length() > customBackgroundMaxBytes) {
+ throw const CustomBackgroundError('Images must be 20 MB or smaller.');
+ }
+ bytes = await source.readAsBytes();
+ } on FileSystemException {
+ throw const CustomBackgroundError('Couldn’t read that file.');
+ }
+
+ final Uint8List out;
+ final String outExtension;
+ ui.ImageDescriptor? descriptor;
+ ui.Codec? codec;
+ ui.Image? frame;
+ try {
+ final buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
+ descriptor = await ui.ImageDescriptor.encoded(buffer);
+ buffer.dispose();
+ final width = descriptor.width, height = descriptor.height;
+ final longest = math.max(width, height);
+ final scale = longest > customBackgroundMaxSide
+ ? customBackgroundMaxSide / longest
+ : 1.0;
+ codec = await descriptor.instantiateCodec(
+ targetWidth: math.max(1, (width * scale).round()),
+ targetHeight: math.max(1, (height * scale).round()),
+ );
+ frame = (await codec.getNextFrame()).image;
+ if (scale == 1.0 && codec.frameCount == 1) {
+ out = bytes;
+ outExtension = extension == 'jpeg' ? 'jpg' : extension;
+ } else {
+ final png = await frame.toByteData(format: ui.ImageByteFormat.png);
+ if (png == null) throw const FormatException();
+ out = png.buffer.asUint8List(png.offsetInBytes, png.lengthInBytes);
+ outExtension = 'png';
+ }
+ } catch (_) {
+ throw const CustomBackgroundError('That image couldn’t be opened.');
+ } finally {
+ frame?.dispose();
+ codec?.dispose();
+ descriptor?.dispose();
+ }
+
+ try {
+ await directory.create(recursive: true);
+ final name =
+ 'custom-${DateTime.now().microsecondsSinceEpoch}.$outExtension';
+ // Written aside and renamed, so a crash mid-write never leaves a half image
+ // under the name the preferences point at.
+ final partial = File(p.join(directory.path, '$name.partial'));
+ await partial.writeAsBytes(out, flush: true);
+ await partial.rename(p.join(directory.path, name));
+ return name;
+ } on FileSystemException {
+ throw const CustomBackgroundError('Couldn’t save a copy of that image.');
+ }
+}
+
+/// Removes every copy in [directory] except [keep]. Best effort: a file that
+/// will not delete costs disk space, not the background.
+Future<void> pruneCustomBackgrounds(Directory directory, {String? keep}) async {
+ try {
+ if (!await directory.exists()) return;
+ await for (final entry in directory.list()) {
+ if (entry is File && p.basename(entry.path) != keep) {
+ try {
+ await entry.delete();
+ } on FileSystemException {
+ // See above.
+ }
+ }
+ }
+ } on FileSystemException {
+ // See above.
+ }
+}
diff --git a/desktop/lib/shared/theme/harness_background.dart b/desktop/lib/shared/theme/harness_background.dart
index 3a46f8e77..14e762d95 100644
--- a/desktop/lib/shared/theme/harness_background.dart
+++ b/desktop/lib/shared/theme/harness_background.dart
@@ -1,4 +1,4 @@
-/// Built-in backgrounds for empty Harness pages. Wallpaper never covers agents.
+/// Backgrounds for empty Harness pages. A background never covers agents.
enum HarnessBackground {
plain('Blank'),
renaissance('Renaissance notebook', 'renaissance-notebook.jpg'),
@@ -9,7 +9,11 @@ enum HarnessBackground {
lake('Lake', 'swarm-welcome-dusk.jpg'),
silk('Silk', 'swarm-welcome-abstract.jpg'),
threads('Threads', 'swarm-welcome-associative-memory.jpg'),
- constellation('Constellation', 'swarm-welcome-ai.jpg');
+ constellation('Constellation', 'swarm-welcome-ai.jpg'),
+
+ /// The user's own image (`CustomBackground`). Not in [gallery]: it has
+ /// its own card, which can be empty.
+ custom('Custom');
const HarnessBackground(this.label, [this.fileName]);
final String label;
diff --git a/desktop/lib/widgets/harness_customize_pane.dart b/desktop/lib/widgets/harness_customize_pane.dart
index 12cee3930..04785a356 100644
--- a/desktop/lib/widgets/harness_customize_pane.dart
+++ b/desktop/lib/widgets/harness_customize_pane.dart
@@ -89,7 +89,7 @@ class HarnessCustomizePane extends StatelessWidget {
),
Tab(
key: ValueKey('customize-wallpaper'),
- text: 'Wallpaper',
+ text: 'Background',
),
Tab(key: ValueKey('customize-terminal'), text: 'Terminal'),
],
diff --git a/desktop/lib/widgets/swarm_wallpaper.dart b/desktop/lib/widgets/swarm_wallpaper.dart
index 31b861a07..5ee168d89 100644
--- a/desktop/lib/widgets/swarm_wallpaper.dart
+++ b/desktop/lib/widgets/swarm_wallpaper.dart
@@ -1,33 +1,62 @@
+import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/theme/appearance_prefs_store.dart';
+import '../shared/theme/custom_background.dart';
import '../shared/theme/harness_background.dart';
import 'engine_identity.dart';
/// Empty pages default to the selected tab's fill. An explicit background is
/// used for picker thumbnails; the page follows the saved appearance choice.
class SwarmWallpaper extends StatelessWidget {
- const SwarmWallpaper({super.key, this.background, this.thumbnail = false});
+ const SwarmWallpaper({
+ super.key,
+ this.background,
+ this.thumbnail = false,
+ this.store,
+ });
final HarnessBackground? background;
final bool thumbnail;
+ /// Where the custom background's image, dim and fit come from.
+ final AppearancePrefsStore? store;
+
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
- if (background case final choice?) return _paint(choice);
+ final prefs = store ?? appearancePrefsStore;
+ // Listened to even for an explicit choice: the custom background's dim and
+ // fit move while its card is on screen.
return ValueListenableBuilder<AppearancePrefs>(
- valueListenable: appearancePrefsStore,
- builder: (context, prefs, _) => _paint(prefs.background),
+ valueListenable: prefs,
+ builder: (context, value, _) => _paint(
+ context,
+ background ?? value.background,
+ value.custom,
+ prefs.customBackgroundFile,
+ ),
);
}
- Widget _paint(HarnessBackground choice) {
+ Widget _paint(
+ BuildContext context,
+ HarnessBackground choice,
+ CustomBackground custom,
+ File? customFile,
+ ) {
if (choice == HarnessBackground.plain) {
return ColoredBox(color: grid.AppPalette.swarmField);
}
+ if (choice == HarnessBackground.custom) {
+ return _CustomImage(
+ file: customFile,
+ custom: custom,
+ thumbnail: thumbnail,
+ );
+ }
if (choice.asset case final asset?) {
return Stack(
fit: StackFit.expand,
@@ -92,6 +121,98 @@ class SwarmWallpaper extends StatelessWidget {
}
}
+/// The user's image, fitted and dimmed. A missing or broken copy paints Blank;
+/// its thumbnail says so, since that is where it can be fixed.
+class _CustomImage extends StatelessWidget {
+ const _CustomImage({
+ required this.file,
+ required this.custom,
+ required this.thumbnail,
+ });
+ final File? file;
+ final CustomBackground custom;
+ final bool thumbnail;
+
+ /// The page a thumbnail stands for. Center and tile show the image at its
+ /// real size, so a thumbnail draws a whole page and shrinks it, rather than
+ /// showing a real-size corner of the image.
+ static const _thumbnailPage = Size(1280, 720);
+
+ @override
+ Widget build(BuildContext context) {
+ final blank = ColoredBox(color: grid.AppPalette.swarmField);
+ final file = this.file;
+ if (file == null) return blank;
+ // Checked here rather than in an errorBuilder so the note is drawn at the
+ // card's size, not shrunk with the page and dimmed.
+ if (thumbnail && !file.existsSync()) {
+ return Container(
+ key: const ValueKey('custom-background-missing'),
+ color: grid.AppPalette.swarmField,
+ alignment: Alignment.center,
+ padding: const EdgeInsets.all(8),
+ child: Text(
+ 'Image missing, choose again',
+ textAlign: TextAlign.center,
+ style: grid.AppType.label(color: const Color(0xffdededb)),
+ ),
+ );
+ }
+ // Real size as the OS shows it: one image pixel per device pixel.
+ final scale = MediaQuery.devicePixelRatioOf(context);
+ Widget missing(BuildContext _, Object _, StackTrace? _) => blank;
+ final image = switch (custom.fit) {
+ BackgroundFit.fill => Image.file(
+ file,
+ fit: BoxFit.cover,
+ excludeFromSemantics: true,
+ errorBuilder: missing,
+ ),
+ BackgroundFit.fit => Image.file(
+ file,
+ fit: BoxFit.contain,
+ excludeFromSemantics: true,
+ errorBuilder: missing,
+ ),
+ BackgroundFit.center => Image.file(
+ file,
+ scale: scale,
+ fit: BoxFit.none,
+ excludeFromSemantics: true,
+ errorBuilder: missing,
+ ),
+ BackgroundFit.tile => Image.file(
+ file,
+ scale: scale,
+ fit: BoxFit.none,
+ alignment: Alignment.topLeft,
+ repeat: ImageRepeat.repeat,
+ excludeFromSemantics: true,
+ errorBuilder: missing,
+ ),
+ };
+ final page = Stack(
+ fit: StackFit.expand,
+ children: [
+ blank,
+ image,
+ IgnorePointer(
+ child: ColoredBox(
+ color: const Color(0xff000000).withValues(alpha: custom.dim),
+ ),
+ ),
+ ],
+ );
+ if (!thumbnail) return page;
+ return ClipRect(
+ child: FittedBox(
+ fit: BoxFit.cover,
+ child: SizedBox.fromSize(size: _thumbnailPage, child: page),
+ ),
+ );
+ }
+}
+
/// One wash: a radial fade from `opacity` at `at` to nothing, `rx`/`ry` wide
/// and tall as fractions of the canvas — the CSS
/// `radial-gradient(ellipse rx ry at …)` the mockup was drawn with.
diff --git a/desktop/test/custom_background_test.dart b/desktop/test/custom_background_test.dart
new file mode 100644
index 000000000..db2e3d9a0
--- /dev/null
+++ b/desktop/test/custom_background_test.dart
@@ -0,0 +1,289 @@
+import 'dart:io';
+import 'dart:typed_data';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/local_key_value_store.dart';
+import 'package:harness/settings/appearance/wallpaper_section.dart';
+import 'package:harness/shared/theme/appearance_prefs_store.dart';
+import 'package:harness/shared/theme/custom_background.dart';
+import 'package:harness/shared/theme/harness_background.dart';
+import 'package:path/path.dart' as p;
+
+class _Storage 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);
+}
+
+Future<Uint8List> _png(int width, int height) async {
+ final recorder = ui.PictureRecorder();
+ ui.Canvas(recorder).drawRect(
+ ui.Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()),
+ ui.Paint()..color = const ui.Color(0xff3366cc),
+ );
+ final image = await recorder.endRecording().toImage(width, height);
+ final data = await image.toByteData(format: ui.ImageByteFormat.png);
+ image.dispose();
+ return data!.buffer.asUint8List();
+}
+
+Future<(int, int)> _size(File file) async {
+ final buffer = await ui.ImmutableBuffer.fromUint8List(
+ await file.readAsBytes(),
+ );
+ final descriptor = await ui.ImageDescriptor.encoded(buffer);
+ final size = (descriptor.width, descriptor.height);
+ descriptor.dispose();
+ buffer.dispose();
+ return size;
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late Directory root;
+ late Directory backgrounds;
+
+ setUp(() {
+ root = Directory.systemTemp.createTempSync('custom-background-');
+ backgrounds = Directory(p.join(root.path, 'backgrounds'));
+ });
+ tearDown(() => root.deleteSync(recursive: true));
+
+ Future<String> source(String name, List<int> bytes) async {
+ final file = File(p.join(root.path, name));
+ await file.writeAsBytes(bytes);
+ return file.path;
+ }
+
+ group('import', () {
+ test('keeps a small image as it is', () async {
+ final bytes = await _png(64, 36);
+ final name = await importCustomBackground(
+ await source('photo.png', bytes),
+ backgrounds,
+ );
+ final copy = File(p.join(backgrounds.path, name));
+ expect(p.extension(name), '.png');
+ expect(await copy.readAsBytes(), bytes);
+ });
+
+ test('scales the longest side down to 3840', () async {
+ final name = await importCustomBackground(
+ await source('wide.png', await _png(4800, 200)),
+ backgrounds,
+ );
+ expect(await _size(File(p.join(backgrounds.path, name))), (3840, 160));
+ });
+
+ test('refuses other formats, broken images and large files', () async {
+ Future<String> refusal(String path) => importCustomBackground(
+ path,
+ backgrounds,
+ ).then((_) => 'accepted', onError: (Object e) => '$e');
+
+ expect(
+ await refusal(await source('anim.gif', [1, 2, 3])),
+ 'Use a PNG, JPEG or WebP image.',
+ );
+ expect(
+ await refusal(await source('broken.jpg', [1, 2, 3])),
+ 'That image couldn’t be opened.',
+ );
+ final large = File(p.join(root.path, 'large.png'));
+ final handle = await large.open(mode: FileMode.write);
+ await handle.truncate(customBackgroundMaxBytes + 1);
+ await handle.close();
+ expect(await refusal(large.path), 'Images must be 20 MB or smaller.');
+ expect(
+ await refusal(p.join(root.path, 'gone.png')),
+ 'Couldn’t read that file.',
+ );
+ expect(
+ backgrounds.existsSync() ? backgrounds.listSync() : const [],
+ isEmpty,
+ );
+ });
+ });
+
+ group('store', () {
+ test('choosing selects and persists; replacing prunes the old copy; '
+ 'removing returns to Blank', () async {
+ final storage = _Storage();
+ final prefs = AppearancePrefsStore(
+ storage: storage,
+ backgroundsDirectory: backgrounds,
+ );
+ addTearDown(prefs.dispose);
+
+ expect(
+ await prefs.chooseCustomBackground(
+ await source('a.png', await _png(8, 8)),
+ ),
+ isNull,
+ );
+ final first = prefs.value.custom.image!;
+ expect(prefs.value.background, HarnessBackground.custom);
+ expect(prefs.customBackgroundFile!.existsSync(), isTrue);
+
+ await prefs.setCustomBackground(dim: 0.6, fit: BackgroundFit.tile);
+ final restored = AppearancePrefsStore(
+ storage: storage,
+ backgroundsDirectory: backgrounds,
+ );
+ addTearDown(restored.dispose);
+ await restored.load();
+ expect(restored.value.background, HarnessBackground.custom);
+ expect(
+ restored.value.custom,
+ CustomBackground(image: first, dim: 0.6, fit: BackgroundFit.tile),
+ );
+
+ // A refused file leaves everything as it was.
+ expect(
+ await prefs.chooseCustomBackground(await source('b.gif', [0])),
+ isNotNull,
+ );
+ expect(prefs.value.custom.image, first);
+
+ await prefs.setBackground(HarnessBackground.renaissance);
+ expect(
+ await prefs.chooseCustomBackground(
+ await source('c.png', await _png(8, 8)),
+ ),
+ isNull,
+ );
+ final second = prefs.value.custom.image!;
+ expect(second, isNot(first));
+ expect(prefs.value.background, HarnessBackground.custom);
+ // Dim and fit survive a new image.
+ expect(prefs.value.custom.fit, BackgroundFit.tile);
+ expect(backgrounds.listSync().map((e) => p.basename(e.path)), [second]);
+
+ await prefs.removeCustomBackground();
+ expect(prefs.value.background, HarnessBackground.plain);
+ expect(prefs.value.custom.image, isNull);
+ expect(backgrounds.listSync(), isEmpty);
+ });
+
+ test('a saved custom choice with no image restores as Blank', () async {
+ final storage = _Storage()
+ ..values['harness_start_background'] = 'custom'
+ ..values['harness_custom_background'] = '{"image":"../state.json"}';
+ final prefs = AppearancePrefsStore(
+ storage: storage,
+ backgroundsDirectory: backgrounds,
+ );
+ addTearDown(prefs.dispose);
+ await prefs.load();
+ expect(prefs.value.background, HarnessBackground.plain);
+ expect(prefs.value.custom.image, isNull);
+ });
+ });
+
+ testWidgets('custom card: choose, adjust, report a refusal, remove', (
+ tester,
+ ) async {
+ tester.view.physicalSize = const Size(600, 1200);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ final prefs = AppearancePrefsStore(
+ storage: _Storage(),
+ backgroundsDirectory: backgrounds,
+ );
+ addTearDown(prefs.dispose);
+ final good = (await tester.runAsync(
+ () async => source('good.png', await _png(32, 18)),
+ ))!;
+ final bad = (await tester.runAsync(() => source('bad.png', [1, 2])))!;
+ var next = good;
+
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Material(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.all(20),
+ child: WallpaperSection(store: prefs, pickImage: () async => next),
+ ),
+ ),
+ ),
+ );
+
+ // File work happens on the real clock; let it finish, then paint.
+ Future<void> settle(bool Function() done) async {
+ for (var i = 0; i < 100 && !done(); i++) {
+ await tester.runAsync(
+ () => Future<void>.delayed(const Duration(milliseconds: 20)),
+ );
+ await tester.pump();
+ }
+ await tester.pump();
+ }
+
+ // Enabled again once the card has finished with the file.
+ bool replaceEnabled() {
+ final button = find.byKey(const ValueKey('custom-background-replace'));
+ return button.evaluate().isNotEmpty &&
+ tester.widget<TextButton>(button).onPressed != null;
+ }
+
+ expect(find.byKey(const ValueKey('custom-background-empty')), findsOne);
+ expect(find.byKey(const ValueKey('custom-background-dim')), findsNothing);
+
+ await tester.tap(find.byKey(const ValueKey('wallpaper-custom')));
+ await settle(() => prefs.value.custom.image != null && replaceEnabled());
+ expect(prefs.value.background, HarnessBackground.custom);
+ expect(find.byKey(const ValueKey('custom-background-dim')), findsOne);
+
+ await tester.ensureVisible(find.byKey(const ValueKey('fit-center')));
+ await tester.tap(find.byKey(const ValueKey('fit-center')));
+ await tester.pump();
+ expect(prefs.value.custom.fit, BackgroundFit.center);
+
+ next = bad;
+ await tester.ensureVisible(
+ find.byKey(const ValueKey('custom-background-replace')),
+ );
+ await tester.tap(find.byKey(const ValueKey('custom-background-replace')));
+ await settle(
+ () => find
+ .byKey(const ValueKey('custom-background-error'))
+ .evaluate()
+ .isNotEmpty,
+ );
+ expect(find.text('That image couldn’t be opened.'), findsOne);
+ expect(prefs.value.background, HarnessBackground.custom);
+
+ // Built-in selected: the controls go, the image stays for one-click return.
+ await tester.ensureVisible(find.byKey(const ValueKey('wallpaper-plain')));
+ await tester.tap(find.byKey(const ValueKey('wallpaper-plain')));
+ await tester.pump();
+ expect(find.byKey(const ValueKey('custom-background-dim')), findsNothing);
+ expect(prefs.value.custom.image, isNotNull);
+
+ // The copy vanishing is reported on the card.
+ await tester.runAsync(() => prefs.customBackgroundFile!.delete());
+ await tester.pumpWidget(const SizedBox());
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Material(
+ child: SingleChildScrollView(child: WallpaperSection(store: prefs)),
+ ),
+ ),
+ );
+ expect(find.byKey(const ValueKey('custom-background-missing')), findsOne);
+
+ await tester.ensureVisible(
+ find.byKey(const ValueKey('custom-background-remove')),
+ );
+ await tester.tap(find.byKey(const ValueKey('custom-background-remove')));
+ await settle(() => prefs.value.custom.image == null);
+ expect(find.byKey(const ValueKey('custom-background-empty')), findsOne);
+ expect(prefs.value.background, HarnessBackground.plain);
+ });
+}