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): Finder tile — browse, edit and review Git changes of a folder (#1450)

Jacob Pham940bb3714259
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index 34c9acbda..8a023e39a 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -494,6 +494,38 @@ add a kind there, not at the call site.
`inventory()` restyles existing panes on each scan). ⚠️ `theme_set`/`theme_set_result` are in the
E2EE type sets in `cli/src/lib/e2ee/core.ts`, which re-pinned the interop keystone; a daemon
that predates the type goes silent, which the app treats as "not supported" — never an error.
+- **A Finder tile is a folder, not a terminal** (`lib/finder/`, `PaneKind.finder`), modelled on Orca's
+ Explorer, Source Control and editor tabs. New Harness lists Finder beside Terminal
+ (`kFinderEngine`), and a Finder never opens alone (owner, 2026-10-20): it is chosen as a Store
+ harness is — Harness row "Finder", then "Run Finder with" an agent, its model and approvals
+ (`NewHarnessController.isFinder`; `harnessId` reads `finder` while `_harnessId` stays the DSH
+ one) — and starts that chat in the folder (no worktree; the first message goes to it).
+ `AppNotifier.openFinderBeside` puts the tile LEFT of that terminal at 70/30, as a harness's web
+ viewer sits. It is the chat's viewer (`ownerAgentId`, `TerminalPane.viewsAgent`): it moves and
+ closes with the terminal, and the two are one group — the Finder has no Close of its own, and
+ closing it (⌘W) closes its chat (`requestClosePane`). Viewers are never in the saved layout or the desk, so the folder is
+ kept per chat in `FinderRoots` (`finder.roots` in the local store); `_syncViewerPane` brings the
+ Finder back whenever that chat's terminal is shown — after a restart too — until it is closed by
+ hand or the agent stops. With no file open the tile is only as wide as its file list, and its
+ header's Collapse (Orca's `PanelLeftClose`) folds it to a 44px rail (`FinderRail`): the panel
+ reports that width (`TerminalPane.fixedWidth`, `AppNotifier.setPaneFixedWidth`) and `PaneGrid`
+ gives it to a full-height edge tile, sliding the others into the rest (`pinFixedColumn`,
+ `widgets/pane_fixed_width.dart`; no divider drag while pinned). Opening a file takes its share
+ back. Left: Files (a lazy
+ tree with Git colours, ignored entries faint via `git check-ignore`, a right-click menu, names
+ typed in place, Trash rather than delete) or Changes (Conflicts / Changes / Staged / Untracked
+ with +/- counts, Stage, Unstage, Discard). Right: tabs — a single click opens a preview tab that
+ the next one replaces, a second click or an edit keeps it. Files open in `re_editor` with
+ re_highlight colours, find/replace, ⌘S, the file's own line break and indent; Markdown opens
+ rendered with its source a click away; diffs are whole-file (`--unified=1000000`), folded,
+ inline or side by side. A watcher (FSEvents on macOS) refreshes the tree, clean tabs and Git,
+ with a 60 s safety read; a tab edited when its file changes on disk gets Reload / Keep My Edits.
+ Closing a tile or tab with unsaved edits asks first (`TerminalPane.beforeClose`). ⌘S and ⌘F are
+ workspace bindings elsewhere, so the editor's `KeymapRegion(keeps:)` takes them back while it
+ has focus. The editor highlights on an isolate that headless tests never let answer — check
+ colours with `integration_test/finder_native_test.dart`. Only `LocalFinderFiles`/`LocalFinderGit`
+ exist, so other machines and the browser offer the row disabled (`canOpenFinderOn`) until the
+ daemon serves listings, reads, writes and Git.
- `third_party/xterm` is a **vendored, patched** xterm 4.0.0 (atomic `replaceRange` fix for scroll
regions — see its `README.autonomous.md`). Do not replace it with the pub package; the regression
lives in `test/terminal_session_test.dart`.
diff --git a/desktop/integration_test/finder_native_test.dart b/desktop/integration_test/finder_native_test.dart
new file mode 100644
index 000000000..018dd4100
--- /dev/null
+++ b/desktop/integration_test/finder_native_test.dart
@@ -0,0 +1,106 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/test_run.dart';
+import 'package:harness/finder/widgets/finder_pane_panel.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:integration_test/integration_test.dart';
+import 'package:path/path.dart' as p;
+import 'package:window_manager/window_manager.dart';
+
+// A Finder tile on a real folder, disk, `git` and renderer. The editor's
+// highlighting runs on an isolate that headless widget tests never let
+// answer, so only a native run shows the colours:
+// FLUTTER_TEST=1 flutter test -d macos --no-pub \
+// integration_test/finder_native_test.dart
+// FINDER_CAPTURE_DIR optionally saves what the tile drew.
+void main() {
+ if (!kUnderTest) throw StateError('Finder fixtures require FLUTTER_TEST=1');
+ IntegrationTestWidgetsFlutterBinding.ensureInitialized();
+ setUpAll(() async {
+ await windowManager.ensureInitialized();
+ await windowManager.setSize(const Size(1300, 800));
+ await windowManager.show();
+ });
+
+ late String root;
+ setUp(() async {
+ root = await (await Directory.systemTemp.createTemp('finder-native-'))
+ .resolveSymbolicLinks();
+ Future<void> git(List<String> args) =>
+ Process.run('git', ['-C', root, ...args]);
+ await git(['init', '-q', '-b', 'main']);
+ await git(['config', 'user.email', 'finder@test']);
+ await git(['config', 'user.name', 'Finder Test']);
+ File(p.join(root, 'main.dart')).writeAsStringSync(
+ '// A greeting.\nvoid main() {\n final name = "world";\n print(name);\n}\n',
+ );
+ await git(['add', '.']);
+ await git(['commit', '-qm', 'first']);
+ File(p.join(root, 'main.dart')).writeAsStringSync(
+ '// A greeting.\nvoid main() {\n final name = "Harness";\n print(name);\n}\n',
+ );
+ });
+ tearDown(() => Directory(root).delete(recursive: true));
+
+ testWidgets('the editor colours code and the diff shows the edit', (
+ tester,
+ ) async {
+ final frame = GlobalKey();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Builder(
+ builder: (context) {
+ grid.AppTheme.brightness.value = Theme.of(context).brightness;
+ return grid.BrightnessScope(
+ child: Scaffold(
+ body: RepaintBoundary(
+ key: frame,
+ child: FinderPanePanel(root: root),
+ ),
+ ),
+ );
+ },
+ ),
+ ),
+ );
+ await _settle(tester);
+ await tester.tap(find.text('main.dart'));
+ await _settle(tester);
+
+ expect(find.byKey(const ValueKey('finder-code-editor')), findsOneWidget);
+ // re_editor paints its own paragraphs, so the colours are checked by eye
+ // in the capture.
+ await _capture(frame, 'editor');
+
+ await tester.tap(find.byKey(const ValueKey('finder-mode-changes')));
+ await _settle(tester);
+ await tester.tap(
+ find.byKey(const ValueKey('finder-change-unstaged-main.dart')),
+ );
+ await _settle(tester);
+ expect(find.byKey(const ValueKey('finder-diff')), findsOneWidget);
+ await _capture(frame, 'diff');
+ });
+}
+
+Future<void> _settle(WidgetTester tester) async {
+ for (var i = 0; i < 20; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+}
+
+Future<void> _capture(GlobalKey frame, String name) async {
+ final dir = Platform.environment['FINDER_CAPTURE_DIR'];
+ if (dir == null) return;
+ final boundary =
+ frame.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ final image = await boundary.toImage();
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ File(p.join(dir, 'finder-$name.png'))
+ .writeAsBytesSync(png!.buffer.asUint8List());
+}
diff --git a/desktop/lib/core/git_worktree.dart b/desktop/lib/core/git_worktree.dart
index 93b60af84..25878800e 100644
--- a/desktop/lib/core/git_worktree.dart
+++ b/desktop/lib/core/git_worktree.dart
@@ -298,7 +298,7 @@ Future<Map<String, List<String>?>> _refreshRemoteBranches(
/// Whether [path] or a folder above it holds `.git`: a directory, or the file
/// a linked worktree has.
-Future<bool> _insideGitCheckout(String path) async {
+Future<bool> insideGitCheckout(String path) async {
// git resolves the folder physically: ~/proj linked into a repository's
// packages/app is in that repository though nothing above ~/proj says so.
final String real;
@@ -324,7 +324,7 @@ Future<Map<String, dynamic>> readLocalGitProject(
String source, {
bool refresh = false,
GitProcessStarter? startProcess,
- Future<bool> Function(String path) insideCheckout = _insideGitCheckout,
+ Future<bool> Function(String path) insideCheckout = insideGitCheckout,
}) async {
Future<({int code, String output, String errorOutput})> git(
List<String> arguments,
@@ -868,6 +868,15 @@ bool _diskFullMessage(String message) => RegExp(
caseSensitive: false,
).hasMatch(message);
+/// Runs git in [source] the way every reader here does: a scrubbed
+/// environment, no prompts, at most 1 MiB of output, and a deadline. Throws
+/// [RepositoryCloneException] when git cannot start, overflows or times out.
+Future<({int code, String output, String errorOutput})> runLocalGit(
+ String source,
+ List<String> arguments, {
+ Duration timeout = const Duration(seconds: 4),
+}) => _git(source, arguments, timeout: timeout);
+
Future<({int code, String output, String errorOutput})> _git(
String source,
List<String> arguments, {
diff --git a/desktop/lib/core/reveal_folder.dart b/desktop/lib/core/reveal_folder.dart
index fd804a8f0..d5b3af3f0 100644
--- a/desktop/lib/core/reveal_folder.dart
+++ b/desktop/lib/core/reveal_folder.dart
@@ -12,6 +12,18 @@ import 'dart:io';
/// caller can act on.
Future<bool> revealFolder(String path) async {
if (!Directory(path).existsSync()) return false;
+ return _openWithSystem(path);
+}
+
+/// Opens the file at [path] in the app the system gives its kind — Preview
+/// for a PDF, the person's player for a video. For what a Finder tile cannot
+/// draw itself.
+Future<bool> openFile(String path) async {
+ if (!File(path).existsSync()) return false;
+ return _openWithSystem(path);
+}
+
+Future<bool> _openWithSystem(String path) async {
final executable = Platform.isMacOS
? '/usr/bin/open'
: Platform.isWindows
diff --git a/desktop/lib/finder/finder_availability.dart b/desktop/lib/finder/finder_availability.dart
new file mode 100644
index 000000000..2780cb6fd
--- /dev/null
+++ b/desktop/lib/finder/finder_availability.dart
@@ -0,0 +1,12 @@
+import '../core/viewer_mode.dart';
+import '../state/app_state.dart' show MachineState;
+
+/// Why the Finder's row cannot be chosen on another machine.
+const kFinderElsewhere =
+ 'Finder opens folders on This computer for now. Choose This computer.';
+
+/// Whether a Finder tile can open on [machine]: this computer, in the
+/// desktop app. A browser has no disk to read, and a remote machine's files
+/// need the daemon to serve them first (see `FinderSource`).
+bool canOpenFinderOn(MachineState? machine) =>
+ !kViewerMode && machine != null && machine.isLocalMachine;
diff --git a/desktop/lib/finder/finder_controller.dart b/desktop/lib/finder/finder_controller.dart
new file mode 100644
index 000000000..220d3fcce
--- /dev/null
+++ b/desktop/lib/finder/finder_controller.dart
@@ -0,0 +1,180 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:path/path.dart' as p;
+
+import 'finder_diff_document.dart';
+import 'finder_document.dart';
+import 'finder_files.dart';
+import 'finder_git.dart';
+import 'finder_git_state.dart';
+import 'finder_load.dart';
+import 'finder_models.dart';
+import 'finder_tabs.dart';
+import 'finder_tree.dart';
+import 'finder_watch.dart' show isGitInternal;
+
+/// The two halves of a Finder tile's sidebar.
+enum FinderMode { files, changes }
+
+/// How often the tile reads Git without being told to, as Orca's safety poll
+/// does: the watcher can miss what another program did to the index.
+const kFinderSafetyRefresh = Duration(seconds: 60);
+
+/// Everything one Finder tile shows: its folder tree, its Git changes and
+/// its open tabs — kept in step with the disk by a watcher.
+class FinderController extends ChangeNotifier {
+ FinderController({
+ required this.root,
+ required this.files,
+ required FinderGit git,
+ }) : git = FinderGitState(root, git) {
+ tree = FinderTree(root, files, _notify)..onListed = this.git.markIgnored;
+ this.git.addListener(_gitChanged);
+ }
+
+ final String root;
+ final FinderFiles files;
+ final FinderGitState git;
+ final FinderTabs tabs = FinderTabs();
+ late final FinderTree tree;
+
+ FinderMode mode = FinderMode.files;
+
+ /// Diffs show both sides in columns rather than one interleaved column.
+ bool sideBySide = false;
+
+ /// What the last action could not do, said at the foot of the sidebar
+ /// until the next one or a few seconds pass.
+ String? notice;
+ Timer? _noticeTimer;
+
+ StreamSubscription<Set<String>>? _watch;
+ int _gitRevision = 0;
+ Timer? _safety;
+ bool _disposed = false;
+
+ /// Reads the folder and its repository, then follows the disk.
+ Future<void> start() async {
+ _watch ??= files.watch(root).listen(onDiskChanged);
+ _safety ??= Timer.periodic(kFinderSafetyRefresh, (_) => git.refresh());
+ await refresh();
+ }
+
+ /// Reads everything again: the tree, the changes, the open diffs.
+ Future<void> refresh() async {
+ await Future.wait([tree.reload(), git.refresh()]);
+ // Folders listed before Git answered have no ignored marks yet.
+ final listed = [
+ for (final row in tree.rows) row.entry,
+ ...switch (tree.listingOf(root)) {
+ FinderLoaded(:final value) => value,
+ _ => const <FinderEntry>[],
+ },
+ ];
+ await git.markIgnored(listed);
+ }
+
+ /// A batch of paths the watcher heard change.
+ void onDiskChanged(Set<String> paths) {
+ final project = paths.where((path) => !isGitInternal(path)).toSet();
+ // A path's folder lists it; the path itself may be a folder whose own
+ // entries moved (FSEvents reports the root that way). Only folders
+ // already listed are read again.
+ unawaited(
+ tree.refresh({
+ for (final path in project) ...[path, p.dirname(path)],
+ }),
+ );
+ for (final tab in tabs.tabs) {
+ if (project.contains(tab.path)) unawaited(tab.document?.diskChanged());
+ }
+ unawaited(git.refresh());
+ }
+
+ void setMode(FinderMode next) {
+ if (mode == next) return;
+ mode = next;
+ _notify();
+ if (next == FinderMode.changes) unawaited(git.refresh());
+ }
+
+ void toggleSideBySide() {
+ sideBySide = !sideBySide;
+ _notify();
+ }
+
+ /// Opens [path] in a tab — a preview unless [preview] is false.
+ FinderTab openFile(String path, {bool preview = true}) =>
+ tabs.open(finderFileTabId(path), () {
+ final document = FinderDocument(path, files);
+ document.addListener(() => _pinWhenEdited(document));
+ unawaited(document.load());
+ return FinderTab.file(document);
+ }, preview: preview);
+
+ /// Opens [change]'s diff in a tab.
+ FinderTab openChange(GitChange change, {bool preview = true}) {
+ final repository = git.repository;
+ return tabs.open(finderDiffTabId(change), () {
+ final diff = FinderDiffDocument(
+ change,
+ p.join(repository?.root ?? root, change.path),
+ git.diff,
+ );
+ unawaited(diff.load());
+ return FinderTab.diff(diff);
+ }, preview: preview);
+ }
+
+ void say(String message) {
+ notice = message;
+ _noticeTimer?.cancel();
+ _noticeTimer = Timer(const Duration(seconds: 6), () {
+ notice = null;
+ _notify();
+ });
+ _notify();
+ }
+
+ /// The path the tree highlights: the file in the front tab.
+ String? get activePath => tabs.active?.path;
+
+ /// Saves the front tab's file. Diffs of it follow through the watcher.
+ Future<bool> saveActive() async =>
+ await tabs.active?.document?.save() ?? false;
+
+ void _pinWhenEdited(FinderDocument document) {
+ final tab = tabs.byId(finderFileTabId(document.path));
+ if (tab != null && tab.preview && document.dirty) tabs.pin(tab.id);
+ }
+
+ /// Open diffs read again whenever Git's status does, so a stage or a
+ /// save shows in them.
+ void _gitChanged() {
+ if (git.revision != _gitRevision) {
+ _gitRevision = git.revision;
+ for (final tab in tabs.tabs) {
+ unawaited(tab.diff?.load());
+ }
+ }
+ _notify();
+ }
+
+ void _notify() {
+ if (!_disposed) notifyListeners();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _safety?.cancel();
+ _noticeTimer?.cancel();
+ unawaited(_watch?.cancel());
+ git
+ ..removeListener(_gitChanged)
+ ..dispose();
+ tabs.dispose();
+ super.dispose();
+ }
+}
diff --git a/desktop/lib/finder/finder_diff_document.dart b/desktop/lib/finder/finder_diff_document.dart
new file mode 100644
index 000000000..3683dee41
--- /dev/null
+++ b/desktop/lib/finder/finder_diff_document.dart
@@ -0,0 +1,36 @@
+import 'package:flutter/foundation.dart';
+
+import 'finder_files.dart' show FinderException;
+import 'finder_load.dart';
+import 'finder_models.dart';
+
+/// One change open in a diff tab: the change, and its diff as Git tells it.
+class FinderDiffDocument extends ChangeNotifier {
+ FinderDiffDocument(this.change, this.path, this._read);
+
+ final GitChange change;
+
+ /// The changed file, absolute.
+ final String path;
+ final Future<List<DiffLine>> Function(GitChange change) _read;
+
+ FinderLoad<List<DiffLine>> diff = const FinderLoading();
+ bool _disposed = false;
+
+ /// Reads the diff again — after a save, a stage or the disk moving. The
+ /// lines on screen stay until the new ones arrive.
+ Future<void> load() async {
+ try {
+ diff = FinderLoaded(await _read(change));
+ } on FinderException catch (error) {
+ diff = FinderFailed(error.message);
+ }
+ if (!_disposed) notifyListeners();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ super.dispose();
+ }
+}
diff --git a/desktop/lib/finder/finder_diff_rows.dart b/desktop/lib/finder/finder_diff_rows.dart
new file mode 100644
index 000000000..f292ee5bd
--- /dev/null
+++ b/desktop/lib/finder/finder_diff_rows.dart
@@ -0,0 +1,150 @@
+import 'finder_models.dart';
+
+/// Unchanged lines kept around each change; longer unchanged runs fold —
+/// Monaco's "hide unchanged regions", as Orca's diff shows them.
+const kDiffContext = 3;
+
+/// One row of a diff as the view draws it.
+sealed class DiffRow {
+ const DiffRow();
+}
+
+/// Inline: one line, on whichever side it exists.
+class DiffSingleRow extends DiffRow {
+ const DiffSingleRow(this.line);
+ final DiffLine line;
+}
+
+/// Side by side: the old line on the left, the new on the right; a missing
+/// side is an insertion or a deletion.
+class DiffPairRow extends DiffRow {
+ const DiffPairRow(this.left, this.right);
+ final DiffLine? left, right;
+}
+
+/// A folded run of unchanged lines; [key] unfolds it.
+class DiffFoldRow extends DiffRow {
+ const DiffFoldRow(this.key, this.count);
+ final int key;
+ final int count;
+}
+
+/// Git's file headers say what the tab already says; only the notes that
+/// mean something (`Binary files differ`, `\ No newline…`) are kept.
+bool _shown(DiffLine line) =>
+ line.kind != DiffLineKind.hunk &&
+ !(line.kind == DiffLineKind.meta &&
+ RegExp(
+ r'^(diff --git|index |--- |\+\+\+ |new file|deleted file|old mode|new mode|similarity|rename |copy )',
+ ).hasMatch(line.text));
+
+/// The rows of [lines] read top to bottom, unchanged runs folded unless
+/// their key is in [unfolded].
+List<DiffRow> inlineDiffRows(List<DiffLine> lines, Set<int> unfolded) =>
+ _fold(lines.where(_shown).toList(), unfolded, DiffSingleRow.new);
+
+/// The rows of [lines] in two columns: each run of removals beside the run
+/// of additions that replaced it.
+List<DiffRow> sideBySideDiffRows(List<DiffLine> lines, Set<int> unfolded) {
+ final shown = lines.where(_shown).toList();
+ final rows = <DiffRow>[];
+ for (var i = 0; i < shown.length;) {
+ final line = shown[i];
+ if (line.kind != DiffLineKind.removed && line.kind != DiffLineKind.added) {
+ rows.add(DiffPairRow(line, line));
+ i++;
+ continue;
+ }
+ final removed = <DiffLine>[], added = <DiffLine>[];
+ while (i < shown.length && shown[i].kind == DiffLineKind.removed) {
+ removed.add(shown[i++]);
+ }
+ while (i < shown.length && shown[i].kind == DiffLineKind.added) {
+ added.add(shown[i++]);
+ }
+ final height = removed.length > added.length
+ ? removed.length
+ : added.length;
+ for (var j = 0; j < height; j++) {
+ rows.add(
+ DiffPairRow(
+ j < removed.length ? removed[j] : null,
+ j < added.length ? added[j] : null,
+ ),
+ );
+ }
+ }
+ return _foldPairs(rows, unfolded);
+}
+
+/// Where each change starts, as row indexes — what Previous and Next change
+/// move between.
+List<int> diffChangeStarts(List<DiffRow> rows) {
+ final starts = <int>[];
+ var inChange = false;
+ for (var i = 0; i < rows.length; i++) {
+ final changed = _isChange(rows[i]);
+ if (changed && !inChange) starts.add(i);
+ inChange = changed;
+ }
+ return starts;
+}
+
+bool _isChange(DiffRow row) => switch (row) {
+ DiffSingleRow(:final line) => _changed(line),
+ DiffPairRow(:final left, :final right) => _changed(left) || _changed(right),
+ DiffFoldRow() => false,
+};
+
+bool _changed(DiffLine? line) =>
+ line?.kind == DiffLineKind.added || line?.kind == DiffLineKind.removed;
+
+List<DiffRow> _fold(
+ List<DiffLine> lines,
+ Set<int> unfolded,
+ DiffRow Function(DiffLine) row,
+) => _foldRuns(
+ [for (final line in lines) row(line)],
+ (row) => (row as DiffSingleRow).line.kind == DiffLineKind.context,
+ unfolded,
+);
+
+List<DiffRow> _foldPairs(List<DiffRow> rows, Set<int> unfolded) =>
+ _foldRuns(rows, (row) {
+ final pair = row as DiffPairRow;
+ return identical(pair.left, pair.right) &&
+ pair.left?.kind == DiffLineKind.context;
+ }, unfolded);
+
+/// Replaces the middle of every unchanged run longer than twice
+/// [kDiffContext] with a fold, keyed by where the run starts.
+List<DiffRow> _foldRuns(
+ List<DiffRow> rows,
+ bool Function(DiffRow) unchanged,
+ Set<int> unfolded,
+) {
+ final out = <DiffRow>[];
+ for (var i = 0; i < rows.length;) {
+ if (!unchanged(rows[i])) {
+ out.add(rows[i++]);
+ continue;
+ }
+ var end = i;
+ while (end < rows.length && unchanged(rows[end])) {
+ end++;
+ }
+ final keepStart = i == 0 ? 0 : kDiffContext;
+ final keepEnd = end == rows.length ? 0 : kDiffContext;
+ final hidden = end - i - keepStart - keepEnd;
+ if (hidden <= 1 || unfolded.contains(i)) {
+ out.addAll(rows.sublist(i, end));
+ } else {
+ out
+ ..addAll(rows.sublist(i, i + keepStart))
+ ..add(DiffFoldRow(i, hidden))
+ ..addAll(rows.sublist(end - keepEnd, end));
+ }
+ i = end;
+ }
+ return out;
+}
diff --git a/desktop/lib/finder/finder_document.dart b/desktop/lib/finder/finder_document.dart
new file mode 100644
index 000000000..75c601d9f
--- /dev/null
+++ b/desktop/lib/finder/finder_document.dart
@@ -0,0 +1,155 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:re_editor/re_editor.dart';
+
+import 'finder_files.dart';
+import 'finder_load.dart';
+import 'finder_models.dart';
+import 'finder_text_format.dart';
+
+/// What happened to the file on disk while a tab held it.
+enum FinderDiskChange { none, changed, deleted }
+
+/// One file open in a Finder tab: its content, its edits, and whether they
+/// are saved — Orca's editor buffer, for one file.
+///
+/// Edits are compared against what was last read or saved, so typing a
+/// change and undoing it leaves the file clean again.
+class FinderDocument extends ChangeNotifier {
+ FinderDocument(this.path, this._files);
+
+ final String path;
+ final FinderFiles _files;
+
+ FinderLoad<FinderContent> content = const FinderLoading();
+ CodeLineEditingController? editor;
+ bool dirty = false;
+ bool saving = false;
+ String? saveError;
+ FinderDiskChange disk = FinderDiskChange.none;
+
+ String _saved = '';
+ DiskStamp? _stamp;
+ CodeLines? _lines;
+ Timer? _compare;
+ bool _disposed = false;
+
+ Future<void> load() async {
+ try {
+ final read = await _files.read(path);
+ if (read is FinderText) _adopt(read);
+ content = FinderLoaded(read);
+ } on FinderException catch (error) {
+ content = FinderFailed(error.message);
+ }
+ _notify();
+ }
+
+ /// Writes the editor's text. False when there was nothing to write or the
+ /// write failed ([saveError] says why).
+ Future<bool> save() async {
+ final editor = this.editor;
+ if (editor == null || saving) return false;
+ saving = true;
+ saveError = null;
+ _notify();
+ final text = editor.text;
+ try {
+ _stamp = await _files.write(path, text);
+ _saved = text;
+ disk = FinderDiskChange.none;
+ _setDirty(editor.text != text);
+ return true;
+ } on FinderException catch (error) {
+ saveError = error.message;
+ return false;
+ } finally {
+ saving = false;
+ _notify();
+ }
+ }
+
+ /// The watcher saw this path change. A clean tab follows the disk; a tab
+ /// with edits keeps them and says the file changed under it.
+ Future<void> diskChanged() async {
+ final stamp = await _files.stamp(path);
+ if (stamp != null && stamp == _stamp) return; // This tab's own save.
+ if (stamp == null) {
+ disk = FinderDiskChange.deleted;
+ return _notify();
+ }
+ if (!dirty) return reloadFromDisk();
+ disk = FinderDiskChange.changed;
+ _notify();
+ }
+
+ /// Drops the edits and reads the file again.
+ Future<void> reloadFromDisk() async {
+ try {
+ final read = await _files.read(path);
+ if (read is FinderText && editor != null) {
+ _saved = read.text;
+ _stamp = read.stamp;
+ editor!.text = read.text;
+ _setDirty(false);
+ } else {
+ await load();
+ }
+ disk = FinderDiskChange.none;
+ } on FinderException catch (error) {
+ saveError = error.message;
+ }
+ _notify();
+ }
+
+ /// Keeps the edits over the disk's version; the next save overwrites it.
+ Future<void> keepMine() async {
+ _stamp = await _files.stamp(path);
+ disk = FinderDiskChange.none;
+ _notify();
+ }
+
+ void _adopt(FinderText read) {
+ _saved = read.text;
+ _stamp = read.stamp;
+ editor?.dispose();
+ editor = CodeLineEditingController.fromText(
+ read.text,
+ detectTextFormat(read.text),
+ )..addListener(_edited);
+ _lines = editor!.codeLines;
+ }
+
+ /// Selection moves notify too; only a new set of lines is an edit. Marked
+ /// dirty at once, and checked against the saved text a moment later — a
+ /// full comparison per keystroke would cost a large file its typing.
+ void _edited() {
+ final lines = editor!.codeLines;
+ if (identical(lines, _lines)) return;
+ _lines = lines;
+ _setDirty(true);
+ _compare?.cancel();
+ _compare = Timer(const Duration(milliseconds: 250), () {
+ if (!_disposed) _setDirty(editor!.text != _saved);
+ });
+ }
+
+ void _setDirty(bool value) {
+ if (dirty == value) return;
+ dirty = value;
+ _notify();
+ }
+
+ void _notify() {
+ if (!_disposed) notifyListeners();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _compare?.cancel();
+ editor?.dispose();
+ super.dispose();
+ }
+}
diff --git a/desktop/lib/finder/finder_file_actions.dart b/desktop/lib/finder/finder_file_actions.dart
new file mode 100644
index 000000000..9cb89aece
--- /dev/null
+++ b/desktop/lib/finder/finder_file_actions.dart
@@ -0,0 +1,91 @@
+import 'package:path/path.dart' as p;
+
+import 'finder_controller.dart';
+import 'finder_files.dart';
+import 'finder_models.dart';
+
+/// What the tree's menu and the Changes rows do to files. Each answers why
+/// it failed, or null, and leaves the refresh to the watcher and Git.
+extension FinderFileActions on FinderController {
+ /// Makes [name] in [folder] — a file opened in a pinned tab, or a folder
+ /// opened in the tree.
+ Future<String?> create(
+ String folder,
+ String name, {
+ required bool asFolder,
+ }) => _attempt(() async {
+ final path = p.join(folder, _validName(name));
+ if (asFolder) {
+ await files.createFolder(path);
+ } else {
+ await files.createFile(path);
+ }
+ await tree.refresh({folder});
+ if (folder != root) await tree.expand(folder);
+ if (!asFolder) openFile(path, preview: false);
+ });
+
+ /// Renames [path] in place. Its open tabs close: they name the old path.
+ Future<String?> rename(String path, String name) => _attempt(() async {
+ final target = p.join(p.dirname(path), _validName(name));
+ if (target == path) return;
+ if (tabs.under(path).any((tab) => tab.dirty)) {
+ throw const FinderException('Save or close its changed tabs first.');
+ }
+ await files.rename(path, target);
+ for (final tab in tabs.under(path)) {
+ tabs.close(tab.id);
+ }
+ await tree.refresh({p.dirname(path)});
+ });
+
+ /// Moves [path] to the Trash, closing its tabs.
+ Future<String?> trash(String path) => _attempt(() async {
+ await files.trash(path);
+ for (final tab in tabs.under(path)) {
+ tabs.close(tab.id);
+ }
+ await tree.refresh({p.dirname(path)});
+ await git.refresh();
+ });
+
+ /// Throws away [changes]: tracked files go back to what the index has,
+ /// untracked ones go to the Trash — never deleted outright.
+ Future<String?> discard(List<GitChange> changes) => _attempt(() async {
+ final repository = git.repository;
+ if (repository == null) return;
+ for (final change in changes.where((c) => c.area == GitArea.untracked)) {
+ await files.trash(p.join(repository.root, change.path));
+ }
+ await git.discard([
+ for (final change in changes)
+ if (change.area == GitArea.unstaged) change,
+ ]);
+ });
+
+ Future<String?> stage(List<GitChange> changes) =>
+ _attempt(() => git.stage(changes));
+
+ Future<String?> unstage(List<GitChange> changes) =>
+ _attempt(() => git.unstage(changes));
+
+ Future<String?> _attempt(Future<void> Function() action) async {
+ try {
+ await action();
+ return null;
+ } on FinderException catch (error) {
+ return error.message;
+ }
+ }
+}
+
+String _validName(String name) {
+ final trimmed = name.trim();
+ if (trimmed.isEmpty || trimmed == '.' || trimmed == '..') {
+ throw const FinderException('Enter a name.');
+ }
+ if (trimmed.contains('/') || trimmed.contains('\u0000')) {
+ throw const FinderException('A name can’t contain “/”.');
+ }
+ return trimmed;
+}
diff --git a/desktop/lib/finder/finder_file_kind.dart b/desktop/lib/finder/finder_file_kind.dart
new file mode 100644
index 000000000..c8ca97af2
--- /dev/null
+++ b/desktop/lib/finder/finder_file_kind.dart
@@ -0,0 +1,71 @@
+import 'dart:typed_data';
+
+import 'package:path/path.dart' as p;
+
+/// What a file is, as far as which view opens it is concerned.
+enum FinderFileKind { text, markdown, image, svg, other }
+
+/// What the preview can draw, told by the name. [FinderFileKind.other] is not
+/// "unsupported" yet: a file with no known extension is read and SNIFFED
+/// ([looksLikeText]), because `LICENSE`, `Makefile` and `.env` are text.
+FinderFileKind finderFileKind(String path) {
+ final name = p.basename(path).toLowerCase();
+ final dot = name.lastIndexOf('.');
+ final extension = dot < 0 ? '' : name.substring(dot + 1);
+ if (_markdown.contains(extension)) return FinderFileKind.markdown;
+ if (extension == 'svg') return FinderFileKind.svg;
+ if (_images.contains(extension)) return FinderFileKind.image;
+ if (_binary.contains(extension)) return FinderFileKind.other;
+ if (_text.contains(extension) || _textNames.contains(name)) {
+ return FinderFileKind.text;
+ }
+ return FinderFileKind.other;
+}
+
+/// Whether [head] — a file's first bytes — reads as text: no NUL byte, and
+/// few enough control characters that it is not a binary format.
+bool looksLikeText(Uint8List head) {
+ if (head.isEmpty) return true;
+ var control = 0;
+ for (final byte in head) {
+ if (byte == 0) return false;
+ if (byte < 0x09 || (byte > 0x0d && byte < 0x20)) control++;
+ }
+ return control * 100 < head.length * 2;
+}
+
+const _markdown = {'md', 'markdown', 'mdx'};
+
+/// The formats Flutter's own image codecs decode on every desktop target.
+const _images = {'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'wbmp'};
+
+/// Extensions never worth sniffing: they are binary even when their first
+/// bytes happen to look like text.
+const _binary = {
+ 'pdf', 'zip', 'gz', 'tgz', 'tar', 'bz2', 'xz', 'zst', '7z', 'rar', //
+ 'dmg', 'iso', 'jar', 'apk', 'ipa', 'exe', 'dll', 'so', 'dylib', 'o', 'a',
+ 'class', 'wasm', 'mp3', 'mp4', 'mov', 'm4a', 'wav', 'flac', 'ogg', 'webm',
+ 'mkv', 'avi', 'heic', 'heif', 'avif', 'tif', 'tiff', 'psd', 'sketch',
+ 'fig', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'key', 'numbers',
+ 'pages', 'sqlite', 'sqlite3', 'db', 'ttf', 'otf', 'woff', 'woff2',
+};
+
+const _text = {
+ 'txt', 'log', 'rst', 'csv', 'tsv', 'diff', 'patch', //
+ 'json', 'jsonl', 'json5', 'yaml', 'yml', 'toml', 'xml', 'plist', 'ini',
+ 'env', 'lock', 'conf', 'cfg', 'properties', 'gradle', 'cmake',
+ 'dart', 'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'py', 'go', 'rs', 'java',
+ 'kt', 'kts', 'swift', 'c', 'cc', 'cpp', 'h', 'hpp', 'm', 'mm', 'cs', 'rb',
+ 'php', 'lua', 'r', 'html', 'htm', 'css', 'scss', 'sass', 'less', 'vue',
+ 'svelte', 'sql', 'graphql', 'gql', 'proto', 'ipynb', 'sh', 'bash', 'zsh',
+ 'fish', 'ps1', 'bat', 'command', 'tf', 'hcl', 'nix', 'ex', 'exs', 'erl',
+ 'hs', 'ml', 'clj', 'scala', 'zig', 'v', 'sv', 'vhd', 'ino', 'gitignore',
+ 'gitattributes', 'editorconfig', 'npmrc', 'nvmrc', 'prettierrc',
+ 'eslintrc', 'babelrc', 'dockerignore', 'srt', 'vtt', 'tex', 'bib',
+};
+
+const _textNames = {
+ 'makefile', 'dockerfile', 'license', 'licence', 'readme', 'changelog', //
+ 'procfile', 'gemfile', 'rakefile', 'podfile', 'brewfile', 'justfile',
+ 'codeowners', 'authors', 'notice',
+};
diff --git a/desktop/lib/finder/finder_files.dart b/desktop/lib/finder/finder_files.dart
new file mode 100644
index 000000000..3feca586d
--- /dev/null
+++ b/desktop/lib/finder/finder_files.dart
@@ -0,0 +1,61 @@
+import 'finder_models.dart';
+
+/// A text file larger than this opens as "too large" rather than in the
+/// editor; the system's app is offered instead.
+const kFinderEditLimit = 10 * 1024 * 1024;
+
+/// An image larger than this is opened in the system's viewer instead.
+const kFinderImageLimit = 50 * 1024 * 1024;
+
+/// A listing stops here; a folder this size is not read by scrolling a tree.
+const kFinderListLimit = 5000;
+
+/// Entries a tree never shows, as Orca hides them: Git's store, the package
+/// cache nobody browses, and macOS's litter.
+const kFinderHiddenNames = {'.git', 'node_modules', '.DS_Store'};
+
+/// A read or write that failed, worded for the person reading the tile.
+class FinderException implements Exception {
+ const FinderException(this.message);
+ final String message;
+
+ @override
+ String toString() => message;
+}
+
+/// Where a Finder tile reads and writes its machine's files.
+///
+/// One seam so the tile does not care where the folder is: this computer's
+/// disk today ([LocalFinderFiles]).
+// TODO(BE): a remote machine needs daemon requests for these — `fs_list_dir`
+// lists folders only and `agent_read_file` serves media from an agent's own
+// project — before the Finder can open there.
+abstract interface class FinderFiles {
+ /// One level of [directory], folders first, each group by name.
+ Future<List<FinderEntry>> list(String directory);
+
+ /// The file at [path] as an editor tab shows it.
+ Future<FinderContent> read(String path);
+
+ /// When the file at [path] last changed, or null when it is gone.
+ Future<DiskStamp?> stamp(String path);
+
+ /// Replaces the file at [path] with [text]; answers its new stamp.
+ Future<DiskStamp> write(String path, String text);
+
+ Future<void> createFile(String path);
+ Future<void> createFolder(String path);
+ Future<void> rename(String from, String to);
+
+ /// Moves [path] to the Trash, so a delete can be taken back.
+ Future<void> trash(String path);
+
+ /// Hands [path] to the system's own app for its kind.
+ Future<bool> open(String path);
+
+ /// Shows [path] in the system's file manager.
+ Future<bool> reveal(String path);
+
+ /// The paths under [root] that changed, a batch at a time.
+ Stream<Set<String>> watch(String root);
+}
diff --git a/desktop/lib/finder/finder_git.dart b/desktop/lib/finder/finder_git.dart
new file mode 100644
index 000000000..76031657c
--- /dev/null
+++ b/desktop/lib/finder/finder_git.dart
@@ -0,0 +1,24 @@
+import 'finder_models.dart';
+
+/// Where a Finder tile reads and changes its folder's Git state.
+///
+/// Every call runs `git` itself, like Orca's main process does — porcelain
+/// output, no prompts, bounded — never a library's idea of the repository.
+abstract interface class FinderGit {
+ /// The repository [folder] is in, with what changed under it, or null when
+ /// it is in none.
+ Future<GitChanges?> changes(String folder);
+
+ /// The paths of the [entries] Git ignores.
+ Future<Set<String>> ignored(GitChanges repository, List<FinderEntry> entries);
+
+ /// How [change] differs, with the whole file as context.
+ Future<List<DiffLine>> diff(GitChanges repository, GitChange change);
+
+ Future<void> stage(GitChanges repository, List<GitChange> changes);
+ Future<void> unstage(GitChanges repository, List<GitChange> changes);
+
+ /// Puts tracked files back as the index has them. Untracked files are not
+ /// Git's to discard; the tile moves those to the Trash.
+ Future<void> discard(GitChanges repository, List<GitChange> changes);
+}
diff --git a/desktop/lib/finder/finder_git_state.dart b/desktop/lib/finder/finder_git_state.dart
new file mode 100644
index 000000000..90ea350e6
--- /dev/null
+++ b/desktop/lib/finder/finder_git_state.dart
@@ -0,0 +1,156 @@
+import 'package:flutter/foundation.dart';
+import 'package:path/path.dart' as p;
+
+import 'finder_files.dart' show FinderException;
+import 'finder_git.dart';
+import 'finder_load.dart';
+import 'finder_models.dart';
+
+/// Which status a file or folder shows when several apply — Orca's order:
+/// a conflict over everything, a deletion over an edit, an edit over an add.
+const _priority = [
+ GitChangeKind.conflicted,
+ GitChangeKind.deleted,
+ GitChangeKind.modified,
+ GitChangeKind.typeChanged,
+ GitChangeKind.added,
+ GitChangeKind.untracked,
+ GitChangeKind.renamed,
+ GitChangeKind.copied,
+];
+
+/// A Finder tile's view of its repository: the changes, the marks the tree
+/// draws from them, and which listed entries Git ignores.
+class FinderGitState extends ChangeNotifier {
+ FinderGitState(this.root, this._git);
+
+ final String root;
+ final FinderGit _git;
+
+ FinderLoad<GitChanges?> status = const FinderLoading();
+
+ /// Counts status reads, so a listener can tell a new status from a new
+ /// ignored mark.
+ int revision = 0;
+ Map<String, GitChangeKind> _files = const {};
+ Map<String, GitChangeKind> _folders = const {};
+ final Set<String> _ignored = {};
+ Future<void>? _reading;
+ bool _again = false;
+ bool _disposed = false;
+
+ GitChanges? get repository => switch (status) {
+ FinderLoaded(:final value) => value,
+ _ => null,
+ };
+
+ GitChangeKind? fileStatus(String path) => _files[path];
+
+ /// A folder wears its most pressing child's status — never a deletion,
+ /// since the deleted file is not in the folder to see.
+ GitChangeKind? folderStatus(String path) => _folders[path];
+
+ bool isIgnored(String path) => _ignored.contains(path);
+
+ /// Reads the status again. Calls made while one read is running share the
+ /// next read instead of starting their own — a save and a watcher batch in
+ /// the same moment are one `git status`.
+ Future<void> refresh() {
+ if (_reading != null) {
+ _again = true;
+ return _reading!;
+ }
+ return _reading = _read().whenComplete(() {
+ _reading = null;
+ if (_again) {
+ _again = false;
+ refresh();
+ }
+ });
+ }
+
+ /// Marks which of [entries] Git ignores; the tree shows them faint.
+ Future<void> markIgnored(List<FinderEntry> entries) async {
+ final repository = this.repository;
+ if (repository == null || entries.isEmpty) return;
+ try {
+ final ignored = await _git.ignored(repository, entries);
+ for (final entry in entries) {
+ ignored.contains(entry.path)
+ ? _ignored.add(entry.path)
+ : _ignored.remove(entry.path);
+ }
+ _notify();
+ } on FinderException {
+ // A mark, not content: without it the tree still reads.
+ }
+ }
+
+ Future<void> stage(List<GitChange> changes) => _then(_git.stage, changes);
+ Future<void> unstage(List<GitChange> changes) => _then(_git.unstage, changes);
+ Future<void> discard(List<GitChange> changes) => _then(_git.discard, changes);
+
+ Future<List<DiffLine>> diff(GitChange change) {
+ final repository = this.repository;
+ if (repository == null) {
+ throw const FinderException('This folder is no longer in Git.');
+ }
+ return _git.diff(repository, change);
+ }
+
+ Future<void> _then(
+ Future<void> Function(GitChanges, List<GitChange>) action,
+ List<GitChange> changes,
+ ) async {
+ final repository = this.repository;
+ if (repository == null) return;
+ try {
+ await action(repository, changes);
+ } finally {
+ await refresh();
+ }
+ }
+
+ Future<void> _read() async {
+ try {
+ status = FinderLoaded(await _git.changes(root));
+ } on FinderException catch (error) {
+ status = FinderFailed(error.message);
+ }
+ _index(repository);
+ revision++;
+ _notify();
+ }
+
+ void _index(GitChanges? repository) {
+ final files = <String, GitChangeKind>{};
+ final folders = <String, GitChangeKind>{};
+ for (final change in repository?.changes ?? const <GitChange>[]) {
+ final path = p.join(repository!.root, change.path);
+ files[path] = _stronger(files[path], change.kind);
+ if (change.kind == GitChangeKind.deleted) continue;
+ for (var dir = p.dirname(path); p.isWithin(root, dir) || dir == root;) {
+ folders[dir] = _stronger(folders[dir], change.kind);
+ if (dir == root) break;
+ dir = p.dirname(dir);
+ }
+ }
+ _files = files;
+ _folders = folders;
+ }
+
+ void _notify() {
+ if (!_disposed) notifyListeners();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ super.dispose();
+ }
+}
+
+GitChangeKind _stronger(GitChangeKind? current, GitChangeKind next) =>
+ current == null || _priority.indexOf(next) < _priority.indexOf(current)
+ ? next
+ : current;
diff --git a/desktop/lib/finder/finder_language.dart b/desktop/lib/finder/finder_language.dart
new file mode 100644
index 000000000..709465f1d
--- /dev/null
+++ b/desktop/lib/finder/finder_language.dart
@@ -0,0 +1,78 @@
+import 'package:path/path.dart' as p;
+
+/// The highlighter's language for a file, told the way Orca's
+/// `detectLanguage` tells it: an exact file name first (`Dockerfile`,
+/// `.gitignore`), then its extension. Null is plain text.
+///
+/// Ids are re_highlight's (`builtinAllLanguages`), so a value here always
+/// names a grammar the editor has.
+String? finderLanguageOf(String path) {
+ final name = p.basename(path);
+ final lower = name.toLowerCase();
+ final byName = _byName[name] ?? _byName[lower];
+ if (byName != null) return byName;
+ if (lower.startsWith('.env')) return 'ini';
+ if (lower.startsWith('dockerfile')) return 'dockerfile';
+ final dot = lower.lastIndexOf('.');
+ if (dot < 0) return null;
+ return _byExtension[lower.substring(dot + 1)];
+}
+
+const _byName = {
+ 'Dockerfile': 'dockerfile',
+ 'Makefile': 'makefile',
+ 'makefile': 'makefile',
+ 'GNUmakefile': 'makefile',
+ 'CMakeLists.txt': 'cmake',
+ 'Gemfile': 'ruby',
+ 'Rakefile': 'ruby',
+ 'Podfile': 'ruby',
+ 'Brewfile': 'ruby',
+ 'Vagrantfile': 'ruby',
+ 'Justfile': 'makefile',
+ 'justfile': 'makefile',
+ '.gitignore': 'bash',
+ '.dockerignore': 'bash',
+ '.gitattributes': 'bash',
+ '.editorconfig': 'ini',
+ '.npmrc': 'ini',
+ '.bashrc': 'bash',
+ '.zshrc': 'bash',
+ '.profile': 'bash',
+ 'nginx.conf': 'nginx',
+};
+
+const _byExtension = {
+ 'dart': 'dart',
+ 'ts': 'typescript', 'tsx': 'typescript', 'mts': 'typescript', //
+ 'cts': 'typescript',
+ 'js': 'javascript', 'jsx': 'javascript', 'mjs': 'javascript',
+ 'cjs': 'javascript',
+ 'json': 'json', 'jsonc': 'json', 'json5': 'json', 'jsonl': 'json',
+ 'ipynb': 'json', 'lock': 'json',
+ 'py': 'python', 'pyi': 'python', 'pyw': 'python',
+ 'go': 'go', 'rs': 'rust', 'swift': 'swift', 'kt': 'kotlin', 'kts': 'kotlin',
+ 'java': 'java', 'scala': 'scala', 'groovy': 'groovy', 'gradle': 'gradle',
+ 'c': 'c', 'h': 'c', 'cc': 'cpp', 'cpp': 'cpp', 'cxx': 'cpp', 'hpp': 'cpp',
+ 'hh': 'cpp', 'ino': 'arduino', 'm': 'objectivec', 'mm': 'objectivec',
+ 'cs': 'csharp', 'fs': 'fsharp', 'vb': 'vbnet',
+ 'rb': 'ruby', 'erb': 'erb', 'php': 'php', 'pl': 'perl', 'lua': 'lua',
+ 'r': 'r', 'jl': 'julia', 'ex': 'elixir', 'exs': 'elixir', 'erl': 'erlang',
+ 'hs': 'haskell', 'ml': 'ocaml', 'clj': 'clojure', 'elm': 'elm',
+ 'zig': 'c', 'nim': 'nim', 'nix': 'nix', 'v': 'verilog', 'sv': 'verilog',
+ 'vhd': 'vhdl', 'vhdl': 'vhdl', 'glsl': 'glsl', 'wgsl': 'glsl',
+ 'html': 'xml', 'htm': 'xml', 'xhtml': 'xml', 'xml': 'xml', 'svg': 'xml',
+ 'plist': 'xml', 'xsd': 'xml', 'vue': 'vue', 'svelte': 'xml',
+ 'css': 'css', 'scss': 'scss', 'sass': 'scss', 'less': 'less',
+ 'styl': 'stylus',
+ 'md': 'markdown', 'markdown': 'markdown', 'mdx': 'markdown',
+ 'yaml': 'yaml', 'yml': 'yaml', 'toml': 'ini', 'ini': 'ini', 'cfg': 'ini',
+ 'conf': 'ini', 'properties': 'properties', 'env': 'ini',
+ 'sh': 'bash', 'bash': 'bash', 'zsh': 'bash', 'fish': 'bash',
+ 'command': 'bash', 'ps1': 'powershell', 'bat': 'dos', 'cmd': 'dos',
+ 'sql': 'sql', 'graphql': 'graphql', 'gql': 'graphql', 'prisma': 'graphql',
+ 'proto': 'protobuf', 'thrift': 'thrift', 'tf': 'ini', 'hcl': 'ini',
+ 'diff': 'diff', 'patch': 'diff', 'tex': 'latex', 'cmake': 'cmake',
+ 'mk': 'makefile', 'scad': 'openscad', 'wat': 'wasm', 'asm': 'x86asm',
+ 's': 'armasm',
+};
diff --git a/desktop/lib/finder/finder_load.dart b/desktop/lib/finder/finder_load.dart
new file mode 100644
index 000000000..249df489e
--- /dev/null
+++ b/desktop/lib/finder/finder_load.dart
@@ -0,0 +1,19 @@
+/// A read in one of its three states. Kept apart so "loading" and "answered
+/// with nothing" never render the same.
+sealed class FinderLoad<T> {
+ const FinderLoad();
+}
+
+class FinderLoading<T> extends FinderLoad<T> {
+ const FinderLoading();
+}
+
+class FinderLoaded<T> extends FinderLoad<T> {
+ const FinderLoaded(this.value);
+ final T value;
+}
+
+class FinderFailed<T> extends FinderLoad<T> {
+ const FinderFailed(this.message);
+ final String message;
+}
diff --git a/desktop/lib/finder/finder_models.dart b/desktop/lib/finder/finder_models.dart
new file mode 100644
index 000000000..70bfbece2
--- /dev/null
+++ b/desktop/lib/finder/finder_models.dart
@@ -0,0 +1,148 @@
+import 'dart:typed_data';
+
+/// One row of a folder listing in a Finder tile.
+class FinderEntry {
+ const FinderEntry({
+ required this.name,
+ required this.path,
+ required this.isDirectory,
+ });
+
+ final String name;
+
+ /// Absolute, on the tile's machine.
+ final String path;
+ final bool isDirectory;
+}
+
+/// A file's size and modification time: enough to tell a later read apart
+/// from the one an editor holds, and to recognise the tile's own save.
+class DiskStamp {
+ const DiskStamp(this.modified, this.size);
+ final DateTime modified;
+ final int size;
+
+ @override
+ bool operator ==(Object other) =>
+ other is DiskStamp && other.modified == modified && other.size == size;
+
+ @override
+ int get hashCode => Object.hash(modified, size);
+}
+
+/// A file as an editor tab reads it. Sealed, so the tab answers every shape.
+sealed class FinderContent {
+ const FinderContent();
+}
+
+class FinderText extends FinderContent {
+ const FinderText(this.text, this.stamp);
+ final String text;
+ final DiskStamp stamp;
+}
+
+class FinderImage extends FinderContent {
+ const FinderImage(this.bytes, {this.svg = false});
+ final Uint8List bytes;
+ final bool svg;
+}
+
+/// A file the tile cannot draw — a binary, or one too large to edit here —
+/// said with why, so the tab can offer the system's own app instead.
+class FinderBinary extends FinderContent {
+ const FinderBinary(this.reason);
+ final String reason;
+}
+
+/// How one path differs from what Git last recorded.
+enum GitChangeKind {
+ modified,
+ added,
+ deleted,
+ renamed,
+ copied,
+ typeChanged,
+ untracked,
+ conflicted,
+}
+
+/// Which list a change belongs to — the sections of the Changes view, in the
+/// order they are shown: conflicts first, because nothing commits past them.
+enum GitArea { conflict, unstaged, staged, untracked }
+
+/// One row of `git status`: a path, and which side of the index it is on.
+///
+/// A file edited after it was staged is TWO rows (`MM`), one staged and one
+/// not, because those are two different diffs.
+class GitChange {
+ const GitChange({
+ required this.path,
+ required this.kind,
+ required this.area,
+ this.originalPath,
+ this.added,
+ this.removed,
+ });
+
+ /// Relative to the repository root, as Git spells it (forward slashes).
+ final String path;
+ final GitChangeKind kind;
+ final GitArea area;
+
+ /// A rename's or copy's source, relative to the repository root.
+ final String? originalPath;
+
+ /// Lines added and removed, from `git diff --numstat`; null for a binary
+ /// or before the count is read.
+ final int? added, removed;
+
+ bool get staged => area == GitArea.staged;
+
+ GitChange withCounts(int? added, int? removed) => GitChange(
+ path: path,
+ kind: kind,
+ area: area,
+ originalPath: originalPath,
+ added: added,
+ removed: removed,
+ );
+
+ /// The same change whatever its line counts: a selection survives them.
+ @override
+ bool operator ==(Object other) =>
+ other is GitChange &&
+ other.path == path &&
+ other.kind == kind &&
+ other.area == area &&
+ other.originalPath == originalPath;
+
+ @override
+ int get hashCode => Object.hash(path, kind, area, originalPath);
+}
+
+/// A folder's repository as the Changes view reads it.
+class GitChanges {
+ const GitChanges({
+ required this.root,
+ required this.changes,
+ this.branch,
+ this.ahead = 0,
+ this.behind = 0,
+ });
+
+ /// The repository's top folder: every [GitChange.path] is relative to it.
+ final String root;
+ final String? branch;
+ final int ahead, behind;
+ final List<GitChange> changes;
+}
+
+enum DiffLineKind { meta, hunk, context, added, removed }
+
+/// One line of a unified diff, numbered on the side(s) it exists on.
+class DiffLine {
+ const DiffLine(this.kind, this.text, {this.oldLine, this.newLine});
+ final DiffLineKind kind;
+ final String text;
+ final int? oldLine, newLine;
+}
diff --git a/desktop/lib/finder/finder_roots.dart b/desktop/lib/finder/finder_roots.dart
new file mode 100644
index 000000000..d2cb782c5
--- /dev/null
+++ b/desktop/lib/finder/finder_roots.dart
@@ -0,0 +1,81 @@
+import 'dart:convert';
+
+import '../core/local_key_value_store.dart';
+
+/// Which folder each chat's Finder shows, by machine and agent — what lets a
+/// Finder come back beside its chat after the app restarts. Viewer tiles are
+/// never in the saved layout (`PaneKind`), so this is the Finder's own note,
+/// kept in this computer's small preferences store.
+class FinderRoots {
+ FinderRoots(this._storage);
+
+ static const storageKey = 'finder.roots';
+
+ /// Old entries go first once this many are kept: an agent stopped while
+ /// the app was closed never says so here.
+ static const capacity = 200;
+
+ final LocalKeyValueStore? Function() _storage;
+ final _roots = <(String, String), String>{};
+ Future<void>? _loading;
+
+ String? rootOf(String machineId, String agentId) =>
+ _roots[(machineId, agentId)];
+
+ /// Reads the saved folders once. A folder set before it lands wins.
+ Future<void> load() => _loading ??= _load();
+
+ Future<void> _load() async {
+ final String? raw;
+ try {
+ raw = await _storage()?.read(storageKey);
+ } catch (_) {
+ return; // unreadable: no Finder comes back, nothing breaks
+ }
+ if (raw == null) return;
+ final Object? entries;
+ try {
+ entries = jsonDecode(raw);
+ } on FormatException {
+ return;
+ }
+ if (entries is! List) return;
+ for (final entry in entries) {
+ if (entry is! Map) continue;
+ final machine = entry['machineId'], agent = entry['agentId'];
+ final root = entry['root'];
+ if (machine is! String || agent is! String || root is! String) continue;
+ _roots.putIfAbsent((machine, agent), () => root);
+ }
+ }
+
+ void set(String machineId, String agentId, String root) {
+ _roots.remove((machineId, agentId));
+ _roots[(machineId, agentId)] = root;
+ while (_roots.length > capacity) {
+ _roots.remove(_roots.keys.first);
+ }
+ _save();
+ }
+
+ void forget(String machineId, String agentId) {
+ if (_roots.remove((machineId, agentId)) != null) _save();
+ }
+
+ /// A chat that became another agent (a switch) keeps its Finder.
+ void move(String machineId, String from, String to) {
+ final root = _roots.remove((machineId, from));
+ if (root != null) set(machineId, to, root);
+ }
+
+ void _save() {
+ final store = _storage();
+ if (store == null) return;
+ final value = jsonEncode([
+ for (final MapEntry(key: (machine, agent), value: root)
+ in _roots.entries)
+ {'machineId': machine, 'agentId': agent, 'root': root},
+ ]);
+ store.write(storageKey, value).catchError((Object _) {});
+ }
+}
diff --git a/desktop/lib/finder/finder_tabs.dart b/desktop/lib/finder/finder_tabs.dart
new file mode 100644
index 000000000..6a6f78c7f
--- /dev/null
+++ b/desktop/lib/finder/finder_tabs.dart
@@ -0,0 +1,124 @@
+import 'package:flutter/foundation.dart';
+import 'package:path/path.dart' as p;
+
+import 'finder_diff_document.dart';
+import 'finder_document.dart';
+import 'finder_models.dart';
+
+/// One tab of a Finder tile's editor area: a file to edit, or a change's
+/// diff. Exactly one of [document] and [diff] is set.
+class FinderTab {
+ FinderTab.file(FinderDocument file)
+ : id = finderFileTabId(file.path),
+ path = file.path,
+ document = file,
+ diff = null;
+
+ FinderTab.diff(FinderDiffDocument change)
+ : id = finderDiffTabId(change.change),
+ path = change.path,
+ document = null,
+ diff = change;
+
+ final String id;
+
+ /// The file the tab is about, absolute.
+ final String path;
+ final FinderDocument? document;
+ final FinderDiffDocument? diff;
+
+ /// A preview tab is the one a single click replaces; editing, a double
+ /// click or opening it again pins it — Orca's preview tabs.
+ bool preview = false;
+
+ String get title => p.basename(path);
+ bool get dirty => document?.dirty ?? false;
+
+ void dispose() {
+ document?.dispose();
+ diff?.dispose();
+ }
+}
+
+/// The open tabs of one Finder tile and which is in front.
+class FinderTabs extends ChangeNotifier {
+ final List<FinderTab> tabs = [];
+ String? activeId;
+
+ FinderTab? get active => tabs.where((tab) => tab.id == activeId).firstOrNull;
+
+ FinderTab? byId(String id) => tabs.where((tab) => tab.id == id).firstOrNull;
+
+ /// Brings the tab [id] to the front, making it with [create] when it is not
+ /// open. A preview takes the place of the current preview tab, unless that
+ /// one has edits.
+ FinderTab open(
+ String id,
+ FinderTab Function() create, {
+ required bool preview,
+ }) {
+ if (byId(id) case final open?) {
+ if (!preview) open.preview = false;
+ activate(id);
+ return open;
+ }
+ final tab = create()..preview = preview;
+ final replaced = preview
+ ? tabs.indexWhere((t) => t.preview && !t.dirty)
+ : -1;
+ if (replaced >= 0) {
+ tabs[replaced].dispose();
+ tabs[replaced] = tab;
+ } else {
+ final at = tabs.indexWhere((t) => t.id == activeId);
+ tabs.insert(at < 0 ? tabs.length : at + 1, tab);
+ }
+ activate(tab.id);
+ return tab;
+ }
+
+ void activate(String id) {
+ activeId = id;
+ notifyListeners();
+ }
+
+ void pin(String id) {
+ final tab = byId(id);
+ if (tab == null || !tab.preview) return;
+ tab.preview = false;
+ notifyListeners();
+ }
+
+ /// Closes [id]; the tab to its right — or else its left — comes forward.
+ void close(String id) {
+ final index = tabs.indexWhere((tab) => tab.id == id);
+ if (index < 0) return;
+ tabs.removeAt(index).dispose();
+ if (activeId == id) {
+ activeId = tabs.isEmpty ? null : tabs[index.clamp(0, tabs.length - 1)].id;
+ }
+ notifyListeners();
+ }
+
+ /// Every tab about [path] or anything under it — what a rename or a trash
+ /// of that path closes.
+ List<FinderTab> under(String path) => [
+ for (final tab in tabs)
+ if (tab.path == path || p.isWithin(path, tab.path)) tab,
+ ];
+
+ @override
+ void dispose() {
+ for (final tab in tabs) {
+ tab.dispose();
+ }
+ super.dispose();
+ }
+}
+
+/// The id a change's diff tab has, so a click finds it already open.
+String finderDiffTabId(GitChange change) =>
+ 'diff:${change.area.name}:${change.path}';
+
+/// The id a file's tab has.
+String finderFileTabId(String path) => 'file:$path';
diff --git a/desktop/lib/finder/finder_text_format.dart b/desktop/lib/finder/finder_text_format.dart
new file mode 100644
index 000000000..af52d9d18
--- /dev/null
+++ b/desktop/lib/finder/finder_text_format.dart
@@ -0,0 +1,30 @@
+import 'package:re_editor/re_editor.dart';
+
+/// How a file writes its lines, read from the file itself so a save puts
+/// back what was there: its line break and its indent width. The way Monaco
+/// detects them for Orca — by majority, never by a project setting.
+CodeLineOptions detectTextFormat(String text) =>
+ CodeLineOptions(lineBreak: _lineBreakOf(text), indentSize: _indentOf(text));
+
+TextLineBreak _lineBreakOf(String text) {
+ final crlf = '\r\n'.allMatches(text).length;
+ final lf = '\n'.allMatches(text).length - crlf;
+ return crlf > lf ? TextLineBreak.crlf : TextLineBreak.lf;
+}
+
+/// The most common step between the space indents of neighbouring lines,
+/// 2 when nothing says otherwise. Tabs read as a step of one tab.
+int _indentOf(String text) {
+ final steps = <int, int>{};
+ var previous = 0;
+ for (final line in text.split('\n').take(2000)) {
+ if (line.trim().isEmpty) continue;
+ final indent = line.length - line.trimLeft().length;
+ if (line.startsWith('\t')) return 4;
+ final step = (indent - previous).abs();
+ if (step >= 2 && step <= 8) steps[step] = (steps[step] ?? 0) + 1;
+ previous = indent;
+ }
+ if (steps.isEmpty) return 2;
+ return steps.entries.reduce((a, b) => b.value > a.value ? b : a).key;
+}
diff --git a/desktop/lib/finder/finder_tree.dart b/desktop/lib/finder/finder_tree.dart
new file mode 100644
index 000000000..f7519143a
--- /dev/null
+++ b/desktop/lib/finder/finder_tree.dart
@@ -0,0 +1,106 @@
+import 'finder_files.dart';
+import 'finder_load.dart';
+import 'finder_models.dart';
+
+/// One visible row of the tree: an entry and how deep it sits.
+class FinderTreeRow {
+ const FinderTreeRow(
+ this.entry,
+ this.depth, {
+ required this.expanded,
+ this.listing,
+ });
+ final FinderEntry entry;
+ final int depth;
+ final bool expanded;
+
+ /// An open folder's own read, so the row can say it is still listing or
+ /// could not be listed — its children are not there to say it.
+ final FinderLoad<List<FinderEntry>>? listing;
+}
+
+/// A folder tree read lazily: a folder is listed the first time it opens, and
+/// the listing is kept while it is closed so reopening it is instant.
+class FinderTree {
+ FinderTree(this.root, this._files, this._changed);
+
+ final String root;
+ final FinderFiles _files;
+ final void Function() _changed;
+ final Map<String, FinderLoad<List<FinderEntry>>> _listings = {};
+ final Set<String> _expanded = {};
+
+ /// Called with each folder's entries once they are listed — where the
+ /// ignored-file marks are asked for.
+ void Function(List<FinderEntry> entries)? onListed;
+
+ FinderLoad<List<FinderEntry>> listingOf(String folder) =>
+ _listings[folder] ?? const FinderLoading();
+
+ bool isExpanded(String folder) => _expanded.contains(folder);
+
+ /// Reads the root, and every open folder again.
+ Future<void> reload() => refresh({root, ..._expanded});
+
+ /// Reads [folders] again — those already listed; a folder never opened is
+ /// read when it is.
+ Future<void> refresh(Set<String> folders) => Future.wait([
+ for (final folder in folders)
+ if (folder == root || _listings.containsKey(folder)) _list(folder),
+ ]);
+
+ Future<void> toggle(String folder) async {
+ if (_expanded.remove(folder)) return _changed();
+ await expand(folder);
+ }
+
+ Future<void> expand(String folder) async {
+ _expanded.add(folder);
+ _changed();
+ if (_listings[folder] is! FinderLoaded) await _list(folder);
+ }
+
+ void collapseAll() {
+ _expanded.clear();
+ _changed();
+ }
+
+ /// The tree as it reads top to bottom: every entry under an open folder.
+ List<FinderTreeRow> get rows {
+ final rows = <FinderTreeRow>[];
+ void walk(String folder, int depth) {
+ final listing = _listings[folder];
+ if (listing is! FinderLoaded<List<FinderEntry>>) return;
+ for (final entry in listing.value) {
+ final open = entry.isDirectory && _expanded.contains(entry.path);
+ rows.add(
+ FinderTreeRow(
+ entry,
+ depth,
+ expanded: open,
+ listing: open ? listingOf(entry.path) : null,
+ ),
+ );
+ if (open) walk(entry.path, depth + 1);
+ }
+ }
+
+ walk(root, 0);
+ return rows;
+ }
+
+ Future<void> _list(String folder) async {
+ // A refresh keeps the rows on screen until the new ones arrive.
+ if (_listings[folder] is! FinderLoaded) {
+ _listings[folder] = const FinderLoading();
+ }
+ try {
+ final entries = await _files.list(folder);
+ _listings[folder] = FinderLoaded(entries);
+ onListed?.call(entries);
+ } on FinderException catch (error) {
+ _listings[folder] = FinderFailed(error.message);
+ }
+ _changed();
+ }
+}
diff --git a/desktop/lib/finder/finder_watch.dart b/desktop/lib/finder/finder_watch.dart
new file mode 100644
index 000000000..2af6442ec
--- /dev/null
+++ b/desktop/lib/finder/finder_watch.dart
@@ -0,0 +1,66 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:path/path.dart' as p;
+
+/// Git's own files worth hearing about: what was staged, which branch is out
+/// and where branches point. Everything else under `.git` is churn.
+final _gitSignals = RegExp(r'[/\\]\.git[/\\](index|HEAD|refs[/\\].*)$');
+
+/// The paths under [root] that changed, in batches [settle] apart — one
+/// `git checkout` is thousands of events and should be one refresh.
+///
+/// macOS reports the whole tree (FSEvents). Where the platform cannot watch
+/// recursively (Linux), only the root's own entries are heard; the tile's
+/// safety refresh covers the rest.
+Stream<Set<String>> watchFolder(
+ String root, {
+ Duration settle = const Duration(milliseconds: 150),
+}) {
+ final pending = <String>{};
+ StreamSubscription<FileSystemEvent>? events;
+ Timer? timer;
+ late final StreamController<Set<String>> batches;
+
+ void hear(FileSystemEvent event) {
+ for (final path in [
+ event.path,
+ if (event is FileSystemMoveEvent) ?event.destination,
+ ]) {
+ if (_worthHearing(path)) pending.add(p.normalize(path));
+ }
+ if (pending.isEmpty) return;
+ timer ??= Timer(settle, () {
+ timer = null;
+ batches.add({...pending});
+ pending.clear();
+ });
+ }
+
+ batches = StreamController<Set<String>>(
+ onListen: () {
+ Stream<FileSystemEvent> source;
+ try {
+ source = Directory(root).watch(recursive: !Platform.isLinux);
+ } on FileSystemException {
+ return;
+ }
+ events = source.listen(hear, onError: (Object _) {});
+ },
+ onCancel: () async {
+ timer?.cancel();
+ await events?.cancel();
+ },
+ );
+ return batches.stream;
+}
+
+bool _worthHearing(String path) {
+ final parts = p.split(path);
+ if (parts.contains('node_modules')) return false;
+ if (!parts.contains('.git')) return true;
+ return _gitSignals.hasMatch(path);
+}
+
+/// Whether [path] is one of Git's own files rather than the project's.
+bool isGitInternal(String path) => p.split(path).contains('.git');
diff --git a/desktop/lib/finder/git_numstat_parser.dart b/desktop/lib/finder/git_numstat_parser.dart
new file mode 100644
index 000000000..c1c75441f
--- /dev/null
+++ b/desktop/lib/finder/git_numstat_parser.dart
@@ -0,0 +1,24 @@
+/// Lines added and removed per path, from `git diff --numstat -z`.
+///
+/// A binary file is counted `-\t-`, which reads as no count at all (null)
+/// rather than as zero. A rename's record is followed by its two paths, and
+/// is filed under the new one — the path `git status` names it by.
+Map<String, (int?, int?)> parseGitNumstat(String output) {
+ final counts = <String, (int?, int?)>{};
+ final records = output.split('\u0000');
+ for (var i = 0; i < records.length; i++) {
+ final fields = records[i].split('\t');
+ if (fields.length != 3) continue;
+ final added = int.tryParse(fields[0]);
+ final removed = int.tryParse(fields[1]);
+ var path = fields[2];
+ if (path.isEmpty) {
+ // Renamed: the old path, then the new one, in the next two records.
+ if (i + 2 >= records.length) break;
+ path = records[i + 2];
+ i += 2;
+ }
+ counts[path] = (added, removed);
+ }
+ return counts;
+}
diff --git a/desktop/lib/finder/git_status_parser.dart b/desktop/lib/finder/git_status_parser.dart
new file mode 100644
index 000000000..5adbf9a7b
--- /dev/null
+++ b/desktop/lib/finder/git_status_parser.dart
@@ -0,0 +1,103 @@
+import 'finder_models.dart';
+
+/// The branch line `git status --branch` leads with, and the changes after it.
+typedef ParsedGitStatus = ({
+ String? branch,
+ int ahead,
+ int behind,
+ List<GitChange> changes,
+});
+
+const _conflicts = {'DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'};
+
+/// Reads `git status --porcelain=v1 -z --branch` output.
+///
+/// `-z` keeps every path verbatim — no quoting of spaces or non-ASCII — and
+/// puts a rename's source in the NEXT record rather than after an arrow, so
+/// this never has to unescape anything.
+ParsedGitStatus parseGitStatus(String output) {
+ final records = output.split('\u0000');
+ String? branch;
+ var ahead = 0, behind = 0;
+ final changes = <GitChange>[];
+ for (var i = 0; i < records.length; i++) {
+ final record = records[i];
+ if (record.startsWith('## ')) {
+ (branch, ahead, behind) = _parseBranch(record.substring(3));
+ continue;
+ }
+ if (record.length < 4) continue;
+ final x = record[0], y = record[1];
+ final path = record.substring(3);
+ final code = '$x$y';
+ if (code == '??') {
+ changes.add(
+ GitChange(
+ path: path,
+ kind: GitChangeKind.untracked,
+ area: GitArea.untracked,
+ ),
+ );
+ continue;
+ }
+ if (code == '!!') continue;
+ if (_conflicts.contains(code)) {
+ changes.add(
+ GitChange(
+ path: path,
+ kind: GitChangeKind.conflicted,
+ area: GitArea.conflict,
+ ),
+ );
+ continue;
+ }
+ final moved = x == 'R' || x == 'C';
+ final original = moved && i + 1 < records.length ? records[++i] : null;
+ if (x != ' ') {
+ changes.add(
+ GitChange(
+ path: path,
+ kind: _kindOf(x),
+ area: GitArea.staged,
+ originalPath: original,
+ ),
+ );
+ }
+ if (y != ' ') {
+ changes.add(
+ GitChange(path: path, kind: _kindOf(y), area: GitArea.unstaged),
+ );
+ }
+ }
+ return (branch: branch, ahead: ahead, behind: behind, changes: changes);
+}
+
+GitChangeKind _kindOf(String code) => switch (code) {
+ 'A' => GitChangeKind.added,
+ 'D' => GitChangeKind.deleted,
+ 'R' => GitChangeKind.renamed,
+ 'C' => GitChangeKind.copied,
+ 'T' => GitChangeKind.typeChanged,
+ _ => GitChangeKind.modified,
+};
+
+/// `main...origin/main [ahead 1, behind 2]`, `No commits yet on main`, or
+/// `HEAD (no branch)` for a detached checkout.
+(String?, int, int) _parseBranch(String line) {
+ final bracket = RegExp(r' \[(.*)\]$').firstMatch(line);
+ final head = bracket == null ? line : line.substring(0, bracket.start);
+ int count(String word) =>
+ int.tryParse(
+ RegExp('$word (\\d+)').firstMatch(bracket?.group(1) ?? '')?.group(1) ??
+ '',
+ ) ??
+ 0;
+ final local = head.split('...').first;
+ final branch = switch (local) {
+ _ when local.startsWith('No commits yet on ') => local.substring(18),
+ _ when local.startsWith('Initial commit on ') => local.substring(18),
+ 'HEAD (no branch)' => null,
+ _ => local,
+ };
+ return (branch, count('ahead'), count('behind'));
+}
diff --git a/desktop/lib/finder/local_finder_files.dart b/desktop/lib/finder/local_finder_files.dart
new file mode 100644
index 000000000..2d6dd429b
--- /dev/null
+++ b/desktop/lib/finder/local_finder_files.dart
@@ -0,0 +1,151 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:path/path.dart' as p;
+
+import '../core/reveal_folder.dart' as system;
+import 'finder_file_kind.dart';
+import 'finder_files.dart';
+import 'finder_models.dart';
+import 'finder_watch.dart';
+
+/// [FinderFiles] over this computer's own disk.
+class LocalFinderFiles implements FinderFiles {
+ const LocalFinderFiles();
+
+ @override
+ Future<List<FinderEntry>> list(String directory) async {
+ final entries = <FinderEntry>[];
+ try {
+ await for (final entity in Directory(directory).list(followLinks: true)) {
+ final name = p.basename(entity.path);
+ if (kFinderHiddenNames.contains(name)) continue;
+ entries.add(
+ FinderEntry(
+ name: name,
+ path: entity.path,
+ isDirectory: entity is Directory,
+ ),
+ );
+ if (entries.length >= kFinderListLimit) break;
+ }
+ } on FileSystemException catch (error) {
+ throw FinderException(_failure(error, 'read this folder'));
+ }
+ return entries..sort(_foldersFirst);
+ }
+
+ @override
+ Future<FinderContent> read(String path) async {
+ final file = File(path);
+ final stat = await _guard(file.stat, 'read this file');
+ if (stat.type == FileSystemEntityType.notFound) {
+ throw const FinderException('This file no longer exists.');
+ }
+ final kind = finderFileKind(path);
+ if (kind == FinderFileKind.image || kind == FinderFileKind.svg) {
+ if (stat.size > kFinderImageLimit) {
+ return const FinderBinary('This image is too large to show here.');
+ }
+ final bytes = await _guard(file.readAsBytes, 'read this file');
+ return FinderImage(bytes, svg: kind == FinderFileKind.svg);
+ }
+ if (stat.size > kFinderEditLimit) {
+ return const FinderBinary('This file is too large to open here.');
+ }
+ final bytes = await _guard(file.readAsBytes, 'read this file');
+ final head = Uint8List.sublistView(bytes, 0, bytes.length.clamp(0, 8192));
+ if (kind == FinderFileKind.other && !looksLikeText(head)) {
+ return const FinderBinary('Binary file — it can’t be shown here.');
+ }
+ return FinderText(
+ utf8.decode(bytes, allowMalformed: true),
+ DiskStamp(stat.modified, stat.size),
+ );
+ }
+
+ @override
+ Future<DiskStamp?> stamp(String path) async {
+ final stat = await File(path).stat();
+ if (stat.type == FileSystemEntityType.notFound) return null;
+ return DiskStamp(stat.modified, stat.size);
+ }
+
+ @override
+ Future<DiskStamp> write(String path, String text) async {
+ final file = File(path);
+ await _guard(() => file.writeAsString(text, flush: true), 'save this file');
+ final stat = await file.stat();
+ return DiskStamp(stat.modified, stat.size);
+ }
+
+ @override
+ Future<void> createFile(String path) =>
+ _guard(() => File(path).create(exclusive: true), 'create this file');
+
+ @override
+ Future<void> createFolder(String path) =>
+ _guard(() => Directory(path).create(), 'create this folder');
+
+ @override
+ Future<void> rename(String from, String to) async {
+ if (await FileSystemEntity.type(to) != FileSystemEntityType.notFound) {
+ throw FinderException('“${p.basename(to)}” already exists here.');
+ }
+ await _guard(
+ () => FileSystemEntity.isDirectory(from).then(
+ (folder) => folder ? Directory(from).rename(to) : File(from).rename(to),
+ ),
+ 'rename this item',
+ );
+ }
+
+ @override
+ Future<void> trash(String path) async {
+ // macOS's own `trash` (macOS 14+) and freedesktop's `gio trash`: both put
+ // the item where the person's Trash can give it back.
+ final command = Platform.isMacOS
+ ? ('/usr/bin/trash', [path])
+ : ('gio', ['trash', path]);
+ try {
+ final result = await Process.run(command.$1, command.$2);
+ if (result.exitCode == 0) return;
+ } on ProcessException {
+ // Reported below, as for a failed run.
+ }
+ throw const FinderException('Couldn’t move this item to the Trash.');
+ }
+
+ @override
+ Future<bool> open(String path) => system.openFile(path);
+
+ @override
+ Future<bool> reveal(String path) => system.revealFile(path);
+
+ @override
+ Stream<Set<String>> watch(String root) => watchFolder(root);
+}
+
+int _foldersFirst(FinderEntry a, FinderEntry b) {
+ if (a.isDirectory != b.isDirectory) return a.isDirectory ? -1 : 1;
+ return a.name.toLowerCase().compareTo(b.name.toLowerCase());
+}
+
+Future<T> _guard<T>(Future<T> Function() action, String what) async {
+ try {
+ return await action();
+ } on FileSystemException catch (error) {
+ throw FinderException(_failure(error, what));
+ }
+}
+
+String _failure(FileSystemException error, String what) =>
+ switch (error.osError?.errorCode) {
+ 1 || 13 => 'Harness isn’t allowed to $what.',
+ 2 => 'This item no longer exists. It may have moved or been deleted.',
+ 17 => 'An item with this name already exists.',
+ 28 => 'There isn’t enough disk space to $what.',
+ _ => 'Couldn’t $what.',
+ };
diff --git a/desktop/lib/finder/local_finder_git.dart b/desktop/lib/finder/local_finder_git.dart
new file mode 100644
index 000000000..26393862b
--- /dev/null
+++ b/desktop/lib/finder/local_finder_git.dart
@@ -0,0 +1,159 @@
+import 'package:path/path.dart' as p;
+
+import '../core/git_worktree.dart' show insideGitCheckout, runLocalGit;
+import 'finder_files.dart' show FinderException;
+import 'finder_git.dart';
+import 'finder_models.dart';
+import 'git_numstat_parser.dart';
+import 'git_status_parser.dart';
+import 'unified_diff_parser.dart';
+
+/// Context wide enough that a diff carries the whole file: the view folds
+/// the unchanged runs itself, and can unfold them without asking git again.
+const _wholeFile = '--unified=1000000';
+
+/// [FinderGit] over this computer's `git`.
+class LocalFinderGit implements FinderGit {
+ const LocalFinderGit();
+
+ @override
+ Future<GitChanges?> changes(String folder) async {
+ if (!await insideGitCheckout(folder)) return null;
+ final top = await _git(folder, ['rev-parse', '--show-toplevel']);
+ if (top.code != 0) return null;
+ final root = top.output.trim();
+ final (status, unstagedCounts, stagedCounts) = await (
+ _git(folder, [
+ '-c', 'core.quotePath=false', //
+ 'status', '--porcelain=v1', '-z', '--branch', '--untracked-files=all',
+ '--', '.',
+ ]),
+ _git(root, ['diff', '--numstat', '-z', '-M']),
+ _git(root, ['diff', '--cached', '--numstat', '-z', '-M']),
+ ).wait;
+ if (status.code != 0) {
+ throw const FinderException('Git couldn’t read this folder’s changes.');
+ }
+ final parsed = parseGitStatus(status.output);
+ final unstaged = parseGitNumstat(unstagedCounts.output);
+ final staged = parseGitNumstat(stagedCounts.output);
+ return GitChanges(
+ root: root,
+ branch: parsed.branch,
+ ahead: parsed.ahead,
+ behind: parsed.behind,
+ changes: [
+ for (final change in parsed.changes)
+ switch ((change.staged ? staged : unstaged)[change.path]) {
+ (final added, final removed) => change.withCounts(added, removed),
+ null => change,
+ },
+ ],
+ );
+ }
+
+ @override
+ Future<Set<String>> ignored(
+ GitChanges repository,
+ List<FinderEntry> entries,
+ ) async {
+ if (entries.isEmpty) return const {};
+ // A folder is asked with its trailing slash: `build/` in .gitignore
+ // matches only folders, and git does not look at the disk to tell.
+ String asked(FinderEntry entry) =>
+ entry.isDirectory ? '${entry.path}/' : entry.path;
+ // One path a line: `-z` is for `--stdin` only, and quotePath off keeps
+ // non-ASCII names as they are.
+ final result = await _git(repository.root, [
+ '-c',
+ 'core.quotePath=false',
+ 'check-ignore',
+ '--',
+ ...entries.map(asked),
+ ]);
+ // 1 is "none of them": an answer, not a failure.
+ if (result.code != 0) return const {};
+ final ignored = result.output.split('\n').toSet();
+ return {
+ for (final entry in entries)
+ if (ignored.contains(asked(entry))) entry.path,
+ };
+ }
+
+ @override
+ Future<List<DiffLine>> diff(GitChanges repository, GitChange change) async {
+ final untracked = change.area == GitArea.untracked;
+ final result = await _git(repository.root, [
+ 'diff',
+ '--no-color',
+ '--no-ext-diff',
+ _wholeFile,
+ if (change.staged) ...['--cached', '-M'],
+ if (untracked) '--no-index',
+ '--',
+ if (untracked) '/dev/null',
+ change.path,
+ ?change.originalPath,
+ ], timeout: const Duration(seconds: 10));
+ // `--no-index` answers 1 when the files differ, which is always here.
+ if (result.code != 0 && !(untracked && result.code == 1)) {
+ throw const FinderException('Git couldn’t show this change.');
+ }
+ return parseUnifiedDiff(result.output);
+ }
+
+ @override
+ Future<void> stage(GitChanges repository, List<GitChange> changes) =>
+ _mutate(repository, ['add', '-A', '--'], _paths(changes), 'stage');
+
+ @override
+ Future<void> unstage(GitChanges repository, List<GitChange> changes) =>
+ _mutate(repository, ['reset', '-q', '--'], _paths(changes), 'unstage');
+
+ @override
+ Future<void> discard(GitChanges repository, List<GitChange> changes) =>
+ _mutate(
+ repository,
+ ['restore', '--worktree', '--'],
+ [for (final change in changes) change.path],
+ 'discard',
+ );
+
+ Future<void> _mutate(
+ GitChanges repository,
+ List<String> command,
+ List<String> paths,
+ String verb,
+ ) async {
+ if (paths.isEmpty) return;
+ final result = await _git(repository.root, [...command, ...paths]);
+ if (result.code != 0) {
+ throw FinderException('Git couldn’t $verb ${_count(paths)}.');
+ }
+ }
+}
+
+/// A rename is two paths to Git: both have to move together.
+List<String> _paths(List<GitChange> changes) => [
+ for (final change in changes) ...[change.path, ?change.originalPath],
+];
+
+String _count(List<String> paths) => paths.length == 1
+ ? p.posix.basename(paths.single)
+ : '${paths.length} files';
+
+Future<({int code, String output, String errorOutput})> _git(
+ String folder,
+ List<String> arguments, {
+ Duration timeout = const Duration(seconds: 6),
+}) async {
+ try {
+ return await runLocalGit(folder, arguments, timeout: timeout);
+ } on Exception {
+ // Overflow, a deadline or no git at all: never git's own words, which can
+ // carry repository contents.
+ throw const FinderException(
+ 'Git didn’t answer in time, or the change is too large to show.',
+ );
+ }
+}
diff --git a/desktop/lib/finder/unified_diff_parser.dart b/desktop/lib/finder/unified_diff_parser.dart
new file mode 100644
index 000000000..cd79e4a11
--- /dev/null
+++ b/desktop/lib/finder/unified_diff_parser.dart
@@ -0,0 +1,52 @@
+import 'finder_models.dart';
+
+final _hunkHeader = RegExp(r'^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@');
+
+/// Splits `git diff` output into lines numbered on the side(s) each exists on.
+///
+/// Everything before the first hunk — `diff --git`, `index`, `---`/`+++` — is
+/// [DiffLineKind.meta], so a `+++ b/file` header is never read as an addition.
+List<DiffLine> parseUnifiedDiff(String diff) {
+ final lines = <DiffLine>[];
+ int? oldLine, newLine;
+ for (final raw in diff.split('\n')) {
+ final hunk = _hunkHeader.firstMatch(raw);
+ if (hunk != null) {
+ oldLine = int.parse(hunk.group(1)!);
+ newLine = int.parse(hunk.group(2)!);
+ lines.add(DiffLine(DiffLineKind.hunk, raw));
+ continue;
+ }
+ if (raw.startsWith('diff --git ')) {
+ oldLine = newLine = null;
+ }
+ if (oldLine == null || newLine == null) {
+ if (raw.isNotEmpty) lines.add(DiffLine(DiffLineKind.meta, raw));
+ continue;
+ }
+ if (raw.startsWith('+')) {
+ lines.add(
+ DiffLine(DiffLineKind.added, raw.substring(1), newLine: newLine++),
+ );
+ } else if (raw.startsWith('-')) {
+ lines.add(
+ DiffLine(DiffLineKind.removed, raw.substring(1), oldLine: oldLine++),
+ );
+ } else if (raw.startsWith(r'\')) {
+ // "\ No newline at end of file" belongs to the line before it.
+ lines.add(DiffLine(DiffLineKind.meta, raw));
+ } else if (raw.isNotEmpty) {
+ // Git prefixes even an empty context line with a space, so a bare
+ // empty line is only the output's own final newline.
+ lines.add(
+ DiffLine(
+ DiffLineKind.context,
+ raw.substring(1),
+ oldLine: oldLine++,
+ newLine: newLine++,
+ ),
+ );
+ }
+ }
+ return lines;
+}
diff --git a/desktop/lib/finder/widgets/finder_change_row.dart b/desktop/lib/finder/widgets/finder_change_row.dart
new file mode 100644
index 000000000..e8a0144e0
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_change_row.dart
@@ -0,0 +1,134 @@
+import 'package:flutter/material.dart';
+import 'package:path/path.dart' as p;
+
+import '../../shared/theme/app_icons.dart';
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../shared/theme/file_type_icon.dart';
+import '../../shared/widgets/app_icon_button.dart';
+import '../../theme/app_theme.dart';
+import '../finder_models.dart';
+import 'finder_row.dart';
+import 'git_change_mark.dart';
+
+/// What a Changes row can do from under the pointer, null for what this
+/// change cannot have done to it.
+class FinderChangeRowActions {
+ const FinderChangeRowActions({
+ required this.onOpen,
+ this.onOpenFile,
+ this.onStage,
+ this.onUnstage,
+ this.onDiscard,
+ });
+
+ final VoidCallback onOpen;
+ final VoidCallback? onOpenFile, onStage, onUnstage, onDiscard;
+}
+
+/// One change, as Orca's Source Control row draws it: the name in its
+/// status colour, its folder, its +/- line counts and status letter — and,
+/// under the pointer, Open File, Discard and Stage or Unstage.
+class FinderChangeRow extends StatefulWidget {
+ const FinderChangeRow({
+ super.key,
+ required this.change,
+ required this.selected,
+ required this.actions,
+ });
+
+ final GitChange change;
+ final bool selected;
+ final FinderChangeRowActions actions;
+
+ @override
+ State<FinderChangeRow> createState() => _FinderChangeRowState();
+}
+
+class _FinderChangeRowState extends State<FinderChangeRow> {
+ bool _hovered = false;
+
+ @override
+ Widget build(BuildContext context) {
+ final change = widget.change;
+ final actions = widget.actions;
+ final folder = p.posix.dirname(change.path);
+ return MouseRegion(
+ onEnter: (_) => setState(() => _hovered = true),
+ onExit: (_) => setState(() => _hovered = false),
+ child: FinderRow(
+ icon: fileTypeIcon(change.path),
+ label: p.posix.basename(change.path),
+ detail: folder == '.' ? null : folder,
+ labelColor: gitChangeStyle(change.kind).color,
+ strike: change.kind == GitChangeKind.deleted,
+ selected: widget.selected,
+ onTap: actions.onOpen,
+ trailing: _hovered ? _HoverActions(actions) : _Summary(change),
+ ),
+ );
+ }
+}
+
+class _Summary extends StatelessWidget {
+ const _Summary(this.change);
+
+ final GitChange change;
+
+ @override
+ Widget build(BuildContext context) {
+ final style = grid.AppType.monoMeta();
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if ((change.added ?? 0) > 0)
+ Text(
+ '+${change.added} ',
+ style: style.copyWith(color: AppColors.success),
+ ),
+ if ((change.removed ?? 0) > 0)
+ Text(
+ '−${change.removed} ',
+ style: style.copyWith(color: AppColors.danger),
+ ),
+ GitChangeMark(change.kind),
+ ],
+ );
+ }
+}
+
+class _HoverActions extends StatelessWidget {
+ const _HoverActions(this.actions);
+
+ final FinderChangeRowActions actions;
+
+ @override
+ Widget build(BuildContext context) => Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (actions.onOpenFile case final open?)
+ _button(AppIcons.file, 'Open File', open, 'open-file'),
+ if (actions.onDiscard case final discard?)
+ _button(AppIcons.undo2, 'Discard Changes', discard, 'discard'),
+ if (actions.onStage case final stage?)
+ _button(AppIcons.plus, 'Stage Changes', stage, 'stage'),
+ if (actions.onUnstage case final unstage?)
+ _button(AppIcons.minus, 'Unstage Changes', unstage, 'unstage'),
+ ],
+ );
+
+ Widget _button(
+ IconData icon,
+ String tooltip,
+ VoidCallback onTap,
+ String id,
+ ) => SizedBox(
+ height: FinderRow.height - 4,
+ child: AppIconButton(
+ key: ValueKey('finder-change-$id'),
+ icon: icon,
+ tooltip: tooltip,
+ size: 13,
+ onPressed: onTap,
+ ),
+ );
+}
diff --git a/desktop/lib/finder/widgets/finder_changes_view.dart b/desktop/lib/finder/widgets/finder_changes_view.dart
new file mode 100644
index 000000000..3d6853f7a
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_changes_view.dart
@@ -0,0 +1,175 @@
+import 'package:flutter/material.dart';
+import 'package:path/path.dart' as p;
+
+import '../../shared/theme/app_icons.dart';
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../shared/widgets/app_icon_button.dart';
+import '../../shared/widgets/empty_state.dart';
+import '../../shared/widgets/skeleton.dart';
+import '../../theme/app_theme.dart';
+import '../finder_controller.dart';
+import '../finder_file_actions.dart';
+import '../finder_load.dart';
+import '../finder_models.dart';
+import 'finder_change_row.dart';
+import 'finder_click.dart';
+import 'finder_dialogs.dart';
+
+/// The Changes half of the sidebar, Orca's Source Control list: Conflicts
+/// first, then Changes, Staged Changes and Untracked Files, each with its
+/// Stage, Unstage and Discard — for one file or the whole section.
+class FinderChangesView extends StatefulWidget {
+ const FinderChangesView({super.key, required this.controller});
+
+ final FinderController controller;
+
+ @override
+ State<FinderChangesView> createState() => _FinderChangesViewState();
+}
+
+class _FinderChangesViewState extends State<FinderChangesView> {
+ final _clicks = FinderClickTracker();
+
+ FinderController get _controller => widget.controller;
+
+ @override
+ Widget build(BuildContext context) => switch (_controller.git.status) {
+ FinderLoading() => const SkeletonList(rows: 6, padding: EdgeInsets.all(10)),
+ FinderFailed(:final message) => EmptyState(
+ icon: AppIcons.circleAlert,
+ title: 'Can’t read changes',
+ message: message,
+ compact: true,
+ ),
+ FinderLoaded(value: null) => const EmptyState(
+ icon: AppIcons.gitBranch,
+ title: 'Not a Git repository',
+ message: 'This folder isn’t in a Git repository.',
+ compact: true,
+ ),
+ FinderLoaded(:final value?) when value.changes.isEmpty => const EmptyState(
+ icon: AppIcons.gitBranch,
+ title: 'No changes',
+ message: 'Everything here matches the last commit.',
+ compact: true,
+ ),
+ FinderLoaded(:final value?) => ListView(
+ key: const ValueKey('finder-changes'),
+ padding: const EdgeInsets.symmetric(vertical: 4),
+ children: [
+ for (final area in GitArea.values)
+ if (value.changes.where((c) => c.area == area).toList()
+ case final changes when changes.isNotEmpty) ...[
+ _heading(area, changes),
+ for (final change in changes) _row(value, change),
+ ],
+ ],
+ ),
+ };
+
+ Widget _heading(GitArea area, List<GitChange> changes) => _Heading(
+ title: switch (area) {
+ GitArea.conflict => 'Conflicts',
+ GitArea.unstaged => 'Changes',
+ GitArea.staged => 'Staged Changes',
+ GitArea.untracked => 'Untracked Files',
+ },
+ count: changes.length,
+ actions: [
+ if (area == GitArea.unstaged || area == GitArea.untracked) ...[
+ AppIconButton(
+ icon: AppIcons.undo2,
+ tooltip: area == GitArea.untracked
+ ? 'Move All to Trash'
+ : 'Discard All',
+ onPressed: () => _discard(changes),
+ ),
+ AppIconButton(
+ icon: AppIcons.plus,
+ tooltip: 'Stage All',
+ onPressed: () => _report(_controller.stage(changes)),
+ ),
+ ],
+ if (area == GitArea.staged)
+ AppIconButton(
+ icon: AppIcons.minus,
+ tooltip: 'Unstage All',
+ onPressed: () => _report(_controller.unstage(changes)),
+ ),
+ ],
+ );
+
+ Widget _row(GitChanges repository, GitChange change) {
+ final area = change.area;
+ final path = p.join(repository.root, change.path);
+ return FinderChangeRow(
+ key: ValueKey('finder-change-${area.name}-${change.path}'),
+ change: change,
+ selected: _controller.tabs.active?.diff?.change == change,
+ actions: FinderChangeRowActions(
+ onOpen: () {
+ final keep = _clicks.isDouble('${area.name}:${change.path}');
+ _controller.openChange(change, preview: !keep);
+ },
+ onOpenFile: change.kind == GitChangeKind.deleted
+ ? null
+ : () => _controller.openFile(path, preview: false),
+ onDiscard: area == GitArea.unstaged || area == GitArea.untracked
+ ? () => _discard([change])
+ : null,
+ onStage: area == GitArea.staged
+ ? null
+ : () => _report(_controller.stage([change])),
+ onUnstage: area == GitArea.staged
+ ? () => _report(_controller.unstage([change]))
+ : null,
+ ),
+ );
+ }
+
+ Future<void> _discard(List<GitChange> changes) async {
+ final untracked = changes.every((c) => c.area == GitArea.untracked);
+ final what = changes.length == 1
+ ? '“${p.posix.basename(changes.single.path)}”'
+ : '${changes.length} files';
+ if (!await confirmDiscard(context, what: what, untracked: untracked)) {
+ return;
+ }
+ await _report(_controller.discard(changes));
+ }
+
+ Future<void> _report(Future<String?> action) async {
+ if (await action case final error?) _controller.say(error);
+ }
+}
+
+class _Heading extends StatelessWidget {
+ const _Heading({
+ required this.title,
+ required this.count,
+ required this.actions,
+ });
+
+ final String title;
+ final int count;
+ final List<Widget> actions;
+
+ @override
+ Widget build(BuildContext context) => Padding(
+ padding: const EdgeInsets.fromLTRB(12, 6, 6, 2),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ '$title $count',
+ style: grid.AppType.caption(
+ color: AppColors.muted,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ ),
+ ...actions,
+ ],
+ ),
+ );
+}
diff --git a/desktop/lib/finder/widgets/finder_click.dart b/desktop/lib/finder/widgets/finder_click.dart
new file mode 100644
index 000000000..8692e535d
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_click.dart
@@ -0,0 +1,23 @@
+import 'package:clock/clock.dart';
+
+/// Tells a second click on the same row from a first, without delaying the
+/// first: a single click opens a preview at once, and a second within
+/// [window] keeps it — Orca's preview tabs, at click speed. Timed by
+/// [clock], so a widget test's fake time decides it, not the runner's speed.
+class FinderClickTracker {
+ FinderClickTracker({this.window = const Duration(milliseconds: 400)});
+
+ final Duration window;
+ String? _last;
+ DateTime? _at;
+
+ /// Whether this click on [id] is the second of a double click.
+ bool isDouble(String id, {DateTime? now}) {
+ final time = now ?? clock.now();
+ final second =
+ _last == id && _at != null && time.difference(_at!) <= window;
+ _last = second ? null : id;
+ _at = second ? null : time;
+ return second;
+ }
+}
diff --git a/desktop/lib/finder/widgets/finder_code_editor.dart b/desktop/lib/finder/widgets/finder_code_editor.dart
new file mode 100644
index 000000000..eade0802a
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_code_editor.dart
@@ -0,0 +1,126 @@
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:re_editor/re_editor.dart';
+
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../shortcuts/app_keymap.dart' show KeymapRegion;
+import '../../shortcuts/keymap.dart';
+import '../../theme/app_theme.dart';
+import 'finder_code_theme.dart';
+import 'finder_find_panel.dart';
+
+/// The strokes an editor takes ahead of the workspace's bindings while it
+/// has focus — ⌘S is Harness Store and ⌘F the terminal's find elsewhere,
+/// but in a file they save and search it, as in Orca. Built on ⌘ for every
+/// platform: the keymap moves the workspace to Alt where ⌘ is missing.
+final kFinderEditorKeys = {
+ for (final keys in [
+ 'cmd+s', 'cmd+f', 'cmd+alt+f', 'cmd+z', 'cmd+shift+z', 'cmd+a', //
+ 'cmd+c', 'cmd+x', 'cmd+v', 'cmd+slash', 'alt+up', 'alt+down',
+ ])
+ KeyStroke.parse(keys),
+};
+
+/// ⌘S on a Mac, Ctrl+S elsewhere — the editor's save, as in Orca.
+SingleActivator get finderSaveKey => SingleActivator(
+ LogicalKeyboardKey.keyS,
+ meta: defaultTargetPlatform == TargetPlatform.macOS,
+ control: defaultTargetPlatform != TargetPlatform.macOS,
+);
+
+/// A file's text in an editor: highlighted for its language, numbered,
+/// foldable, searchable (⌘F) and saved with ⌘S — the Monaco tab of Orca,
+/// drawn by re_editor.
+class FinderCodeEditor extends StatefulWidget {
+ const FinderCodeEditor({
+ super.key,
+ required this.controller,
+ required this.language,
+ required this.onSave,
+ this.wordWrap = true,
+ this.readOnly = false,
+ });
+
+ final CodeLineEditingController controller;
+
+ /// A [finderLanguageOf] id; null is plain text.
+ final String? language;
+ final VoidCallback onSave;
+ final bool wordWrap;
+ final bool readOnly;
+
+ @override
+ State<FinderCodeEditor> createState() => _FinderCodeEditorState();
+}
+
+class _FinderCodeEditorState extends State<FinderCodeEditor> {
+ late CodeFindController _find = CodeFindController(widget.controller);
+
+ @override
+ void didUpdateWidget(FinderCodeEditor old) {
+ super.didUpdateWidget(old);
+ if (old.controller != widget.controller) {
+ _find.dispose();
+ _find = CodeFindController(widget.controller);
+ }
+ }
+
+ @override
+ void dispose() {
+ _find.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final brightness = grid.AppTheme.watch(context);
+ final code = grid.AppType.mono(color: AppColors.text);
+ final number = grid.AppType.mono(color: AppColors.muted);
+ return KeymapRegion(
+ contextKind: KeymapContext.workspace,
+ keeps: kFinderEditorKeys,
+ child: CallbackShortcuts(
+ bindings: {finderSaveKey: widget.onSave},
+ child: CodeEditor(
+ key: const ValueKey('finder-code-editor'),
+ controller: widget.controller,
+ findController: _find,
+ readOnly: widget.readOnly,
+ wordWrap: widget.wordWrap,
+ padding: const EdgeInsets.fromLTRB(4, 6, 12, 24),
+ style: CodeEditorStyle(
+ fontSize: code.fontSize,
+ fontFamily: code.fontFamily,
+ fontFamilyFallback: code.fontFamilyFallback,
+ fontHeight: 1.45,
+ textColor: AppColors.text,
+ backgroundColor: Colors.transparent,
+ selectionColor: AppColors.accent.withValues(alpha: .28),
+ cursorColor: AppColors.accent,
+ cursorLineColor: AppColors.rowHover,
+ chunkIndicatorColor: AppColors.muted,
+ codeTheme: finderEditorHighlight(widget.language, brightness),
+ ),
+ indicatorBuilder: (context, editing, chunks, notifier) => Row(
+ children: [
+ DefaultCodeLineNumber(
+ controller: editing,
+ notifier: notifier,
+ textStyle: number,
+ focusedTextStyle: number.copyWith(color: AppColors.text),
+ ),
+ DefaultCodeChunkIndicator(
+ width: 16,
+ controller: chunks,
+ notifier: notifier,
+ ),
+ ],
+ ),
+ findBuilder: (context, controller, readOnly) =>
+ FinderFindPanel(controller: controller, readOnly: readOnly),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/finder/widgets/finder_code_theme.dart b/desktop/lib/finder/widgets/finder_code_theme.dart
new file mode 100644
index 000000000..67e798979
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_code_theme.dart
@@ -0,0 +1,53 @@
+import 'package:flutter/painting.dart';
+import 'package:flutter/services.dart' show Brightness;
+import 'package:re_editor/re_editor.dart';
+import 'package:re_highlight/languages/all.dart';
+import 'package:re_highlight/re_highlight.dart';
+import 'package:re_highlight/styles/github-dark.dart';
+import 'package:re_highlight/styles/github.dart';
+
+/// The token colours a Finder tab paints code in: GitHub's, light or dark,
+/// with the page's own ground — the pane already has one.
+Map<String, TextStyle> finderCodeColors(Brightness brightness) {
+ final theme = brightness == Brightness.dark ? githubDarkTheme : githubTheme;
+ return {...theme, 'root': TextStyle(color: theme['root']?.color)};
+}
+
+/// The editor's highlighting for [language] (a [finderLanguageOf] id), or
+/// null for plain text. One instance per language and brightness: the
+/// editor re-highlights the whole file whenever it is handed a new one.
+CodeHighlightTheme? finderEditorHighlight(
+ String? language,
+ Brightness brightness,
+) {
+ final mode = language == null ? null : builtinAllLanguages[language];
+ if (mode == null) return null;
+ return _editorThemes.putIfAbsent(
+ (language!, brightness),
+ () => CodeHighlightTheme(
+ languages: {language: CodeHighlightThemeMode(mode: mode)},
+ theme: finderCodeColors(brightness),
+ ),
+ );
+}
+
+final _editorThemes = <(String, Brightness), CodeHighlightTheme>{};
+
+final _highlighter = Highlight()..registerLanguages(builtinAllLanguages);
+
+/// One line of code coloured on its own — a diff's line, which has no file
+/// around it to carry a comment or a string across lines. Plain when
+/// [language] is null or unknown.
+TextSpan highlightLine(
+ String line,
+ String? language,
+ TextStyle base,
+ Brightness brightness,
+) {
+ if (language == null || builtinAllLanguages[language] == null) {
+ return TextSpan(text: line, style: base);
+ }
+ final renderer = TextSpanRenderer(base, finderCodeColors(brightness));
+ _highlighter.highlight(code: line, language: language).render(renderer);
+ return renderer.span ?? TextSpan(text: line, style: base);
+}
diff --git a/desktop/lib/finder/widgets/finder_context_menu.dart b/desktop/lib/finder/widgets/finder_context_menu.dart
new file mode 100644
index 000000000..0c47568bd
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_context_menu.dart
@@ -0,0 +1,36 @@
+import 'package:flutter/material.dart';
+
+/// A right-click menu for a row of the tree or the Changes list, drawn by
+/// the app's own menu theme (`AppMenuItem` rows).
+class FinderContextMenu extends StatefulWidget {
+ const FinderContextMenu({
+ super.key,
+ required this.items,
+ required this.child,
+ });
+
+ /// Built when the menu opens, so it reflects the row as it is then.
+ final List<Widget> Function() items;
+ final Widget child;
+
+ @override
+ State<FinderContextMenu> createState() => _FinderContextMenuState();
+}
+
+class _FinderContextMenuState extends State<FinderContextMenu> {
+ final _menu = MenuController();
+ List<Widget> _items = const [];
+
+ @override
+ Widget build(BuildContext context) => MenuAnchor(
+ controller: _menu,
+ menuChildren: _items,
+ child: GestureDetector(
+ onSecondaryTapDown: (details) {
+ setState(() => _items = widget.items());
+ _menu.open(position: details.localPosition);
+ },
+ child: widget.child,
+ ),
+ );
+}
diff --git a/desktop/lib/finder/widgets/finder_dialogs.dart b/desktop/lib/finder/widgets/finder_dialogs.dart
new file mode 100644
index 000000000..14c807f14
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_dialogs.dart
@@ -0,0 +1,103 @@
+import 'package:flutter/material.dart';
+
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../widgets/desktop_chrome.dart';
+import '../../widgets/desktop_prompt_surface.dart';
+import '../../widgets/terminal_prompt.dart';
+
+/// What to do with a tab's unsaved edits as it closes — Orca's choices.
+enum FinderUnsavedChoice { save, discard }
+
+/// How a choice's button reads: quiet, the way forward, or destructive.
+enum _Tone { plain, primary, danger }
+
+/// "Do you want to save the changes you made to [name]?" Null is Cancel.
+Future<FinderUnsavedChoice?> askToSaveChanges(
+ BuildContext context,
+ String name,
+) => _ask(
+ context,
+ title: 'Unsaved changes',
+ message:
+ 'Do you want to save the changes you made to $name? '
+ 'Your changes will be lost if you don’t save them.',
+ choices: const [
+ ('Don’t Save', FinderUnsavedChoice.discard, _Tone.plain),
+ ('Save', FinderUnsavedChoice.save, _Tone.primary),
+ ],
+);
+
+/// Whether to throw away [what]: "Discard changes?" for tracked files, and
+/// for untracked ones a move to the Trash.
+Future<bool> confirmDiscard(
+ BuildContext context, {
+ required String what,
+ required bool untracked,
+}) async =>
+ await _ask(
+ context,
+ title: untracked ? 'Move to Trash?' : 'Discard changes?',
+ message: untracked
+ ? '$what isn’t in Git yet. It goes to the Trash, where you can '
+ 'restore it.'
+ : 'The changes to $what will be lost. This cannot be undone.',
+ choices: [(untracked ? 'Move to Trash' : 'Discard', true, _Tone.danger)],
+ ) ==
+ true;
+
+/// Whether to move [name] to the Trash from the tree.
+Future<bool> confirmTrash(BuildContext context, String name) async =>
+ await _ask(
+ context,
+ title: 'Move to Trash?',
+ message: '“$name” goes to the Trash, where you can restore it.',
+ choices: const [('Move to Trash', true, _Tone.danger)],
+ ) ==
+ true;
+
+/// A prompt with Cancel and [choices]; each is (label, value, tone).
+/// The last choice is the default (↵).
+Future<T?> _ask<T>(
+ BuildContext context, {
+ required String title,
+ required String message,
+ required List<(String, T, _Tone)> choices,
+}) => showTerminalPrompt<T>(
+ context,
+ builder: (context) {
+ void cancel() => Navigator.pop(context);
+ return TerminalPromptKeys(
+ cancel: cancel,
+ accept: () => Navigator.pop(context, choices.last.$2),
+ child: DesktopPromptSurface(
+ body: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(title, style: DesktopChrome.heading()),
+ const SizedBox(height: DesktopChrome.groupGap),
+ Text(message, style: DesktopChrome.text(size: 13)),
+ ],
+ ),
+ actions: [
+ TextButton(onPressed: cancel, child: const Text('Cancel')),
+ for (final (label, value, tone) in choices)
+ tone == _Tone.plain
+ ? TextButton(
+ key: ValueKey('finder-dialog-$label'),
+ onPressed: () => Navigator.pop(context, value),
+ child: Text(label),
+ )
+ : FilledButton(
+ key: ValueKey('finder-dialog-$label'),
+ autofocus: tone == _Tone.primary,
+ onPressed: () => Navigator.pop(context, value),
+ style: tone == _Tone.danger
+ ? grid.dangerButtonStyle()
+ : null,
+ child: Text(label),
+ ),
+ ],
+ ),
+ );
+ },
+);
diff --git a/desktop/lib/finder/widgets/finder_diff_keys.dart b/desktop/lib/finder/widgets/finder_diff_keys.dart
new file mode 100644
index 000000000..a262de361
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_diff_keys.dart
@@ -0,0 +1,24 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+/// F7 and ⇧F7, Orca's next and previous change, while the diff has focus.
+class FinderDiffKeys extends StatelessWidget {
+ const FinderDiffKeys({
+ super.key,
+ required this.onPrevious,
+ required this.onNext,
+ required this.child,
+ });
+
+ final VoidCallback onPrevious, onNext;
+ final Widget child;
+
+ @override
+ Widget build(BuildContext context) => CallbackShortcuts(
+ bindings: {
+ const SingleActivator(LogicalKeyboardKey.f7): onNext,
+ const SingleActivator(LogicalKeyboardKey.f7, shift: true): onPrevious,
+ },
+ child: Focus(child: child),
+ );
+}
diff --git a/desktop/lib/finder/widgets/finder_diff_line.dart b/desktop/lib/finder/widgets/finder_diff_line.dart
new file mode 100644
index 000000000..4b5287573
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_diff_line.dart
@@ -0,0 +1,145 @@
+import 'package:flutter/material.dart';
+
+import '../../shared/theme/app_icons.dart';
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../theme/app_theme.dart';
+import '../finder_diff_rows.dart';
+import '../finder_models.dart';
+import 'finder_code_theme.dart';
+
+/// Every diff row is this tall, so Previous/Next can scroll to a row by
+/// arithmetic.
+const kDiffRowHeight = 20.0;
+
+/// One row of a diff: a line (inline), a pair of lines (side by side), or a
+/// fold of unchanged lines to open.
+class FinderDiffLine extends StatelessWidget {
+ const FinderDiffLine({
+ super.key,
+ required this.row,
+ required this.language,
+ required this.gutterDigits,
+ required this.onUnfold,
+ });
+
+ final DiffRow row;
+ final String? language;
+ final int gutterDigits;
+ final ValueChanged<int> onUnfold;
+
+ @override
+ Widget build(BuildContext context) => switch (row) {
+ DiffSingleRow(:final line) => _Side(
+ line: line,
+ numbers: [line.oldLine, line.newLine],
+ language: language,
+ digits: gutterDigits,
+ ),
+ DiffPairRow(:final left, :final right) => Row(
+ children: [
+ Expanded(
+ child: _Side(
+ line: left,
+ numbers: [left?.oldLine],
+ language: language,
+ digits: gutterDigits,
+ ),
+ ),
+ VerticalDivider(width: 1, color: AppColors.border),
+ Expanded(
+ child: _Side(
+ line: right,
+ numbers: [right?.newLine],
+ language: language,
+ digits: gutterDigits,
+ ),
+ ),
+ ],
+ ),
+ DiffFoldRow(:final key, :final count) => InkWell(
+ onTap: () => onUnfold(key),
+ child: ColoredBox(
+ color: AppColors.accent.withValues(alpha: .07),
+ child: Row(
+ children: [
+ const SizedBox(width: 12),
+ Icon(AppIcons.chevronsDownUp, size: 12, color: AppColors.muted),
+ const SizedBox(width: 8),
+ Text(
+ count == 1 ? '1 unchanged line' : '$count unchanged lines',
+ style: grid.AppType.caption(color: AppColors.muted),
+ ),
+ ],
+ ),
+ ),
+ ),
+ };
+}
+
+/// One side of a row: its number(s), and the line coloured for its language
+/// on the wash of its change. A missing side is a blank, hatched quietly.
+class _Side extends StatelessWidget {
+ const _Side({
+ required this.line,
+ required this.numbers,
+ required this.language,
+ required this.digits,
+ });
+
+ final DiffLine? line;
+ final List<int?> numbers;
+ final String? language;
+ final int digits;
+
+ @override
+ Widget build(BuildContext context) {
+ final brightness = grid.AppTheme.watch(context);
+ final line = this.line;
+ final base = grid.AppType.mono(color: AppColors.text, height: 1.2);
+ final gutter = grid.AppType.mono(color: AppColors.muted, height: 1.2);
+ return ColoredBox(
+ color: switch (line?.kind) {
+ null => AppColors.border.withValues(alpha: .25),
+ DiffLineKind.added => AppColors.success.withValues(alpha: .16),
+ DiffLineKind.removed => AppColors.danger.withValues(alpha: .16),
+ _ => Colors.transparent,
+ },
+ child: Row(
+ children: [
+ for (final number in numbers)
+ SizedBox(
+ width: digits * 8.0 + 14,
+ child: Text(
+ number?.toString() ?? '',
+ textAlign: TextAlign.right,
+ style: gutter,
+ ),
+ ),
+ SizedBox(
+ width: 18,
+ child: Text(
+ switch (line?.kind) {
+ DiffLineKind.added => '+',
+ DiffLineKind.removed => '−',
+ _ => '',
+ },
+ textAlign: TextAlign.center,
+ style: gutter,
+ ),
+ ),
+ if (line != null)
+ Expanded(
+ child: Text.rich(
+ line.kind == DiffLineKind.meta
+ ? TextSpan(text: line.text, style: gutter)
+ : highlightLine(line.text, language, base, brightness),
+ maxLines: 1,
+ softWrap: false,
+ overflow: TextOverflow.clip,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/finder/widgets/finder_diff_view.dart b/desktop/lib/finder/widgets/finder_diff_view.dart
new file mode 100644
index 000000000..906705269
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_diff_view.dart
@@ -0,0 +1,179 @@
+import 'dart:math';
+
+import 'package:flutter/material.dart';
+
+import '../../shared/theme/app_icons.dart';
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../shared/widgets/app_icon_button.dart';
+import '../../shared/widgets/empty_state.dart';
+import '../../shared/widgets/skeleton.dart';
+import '../../theme/app_theme.dart';
+import '../finder_diff_rows.dart';
+import '../finder_load.dart';
+import '../finder_models.dart';
+import 'finder_diff_keys.dart';
+import 'finder_diff_line.dart';
+import 'finder_surface_bar.dart';
+
+/// A change's diff, as Orca's diff tab shows it: inline or side by side,
+/// unchanged runs folded, and Previous/Next change (⇧F7/F7) between edits.
+class FinderDiffView extends StatefulWidget {
+ const FinderDiffView({
+ super.key,
+ required this.label,
+ required this.diff,
+ required this.language,
+ required this.sideBySide,
+ required this.onToggleSideBySide,
+ this.onOpenFile,
+ });
+
+ final String label;
+ final FinderLoad<List<DiffLine>> diff;
+ final String? language;
+ final bool sideBySide;
+ final VoidCallback onToggleSideBySide;
+
+ /// Opens the file to edit; null for a deleted one.
+ final VoidCallback? onOpenFile;
+
+ @override
+ State<FinderDiffView> createState() => _FinderDiffViewState();
+}
+
+class _FinderDiffViewState extends State<FinderDiffView> {
+ final _scroll = ScrollController();
+ final _unfolded = <int>{};
+ int _change = -1;
+
+ /// Whether the diff has been taken to its first change, as Orca's does
+ /// once when it opens.
+ bool _revealed = false;
+
+ @override
+ void dispose() {
+ _scroll.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final lines = switch (widget.diff) {
+ FinderLoaded(:final value) => value,
+ _ => null,
+ };
+ final rows = lines == null
+ ? const <DiffRow>[]
+ : widget.sideBySide
+ ? sideBySideDiffRows(lines, _unfolded)
+ : inlineDiffRows(lines, _unfolded);
+ final starts = diffChangeStarts(rows);
+ if (!_revealed && starts.isNotEmpty) {
+ _revealed = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _go(starts, 1);
+ });
+ }
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ FinderSurfaceBar(
+ label: widget.label,
+ actions: [
+ Text(
+ starts.isEmpty ? '' : '${_change + 1} of ${starts.length}',
+ style: grid.AppType.caption(color: AppColors.muted),
+ ),
+ AppIconButton(
+ key: const ValueKey('finder-diff-previous'),
+ icon: AppIcons.arrowUp,
+ tooltip: 'Previous change · ⇧F7',
+ onPressed: starts.isEmpty ? null : () => _go(starts, -1),
+ ),
+ AppIconButton(
+ key: const ValueKey('finder-diff-next'),
+ icon: AppIcons.arrowDown,
+ tooltip: 'Next change · F7',
+ onPressed: starts.isEmpty ? null : () => _go(starts, 1),
+ ),
+ AppIconButton(
+ key: const ValueKey('finder-diff-layout'),
+ icon: widget.sideBySide ? AppIcons.rows2 : AppIcons.columns2,
+ tooltip: widget.sideBySide
+ ? 'Switch to inline diff'
+ : 'Switch to side-by-side diff',
+ onPressed: widget.onToggleSideBySide,
+ ),
+ if (widget.onOpenFile case final open?)
+ AppIconButton(
+ key: const ValueKey('finder-diff-open-file'),
+ icon: AppIcons.pencil,
+ tooltip: 'Open file to edit',
+ onPressed: open,
+ ),
+ ],
+ ),
+ Divider(height: 1, color: AppColors.border),
+ Expanded(child: _body(rows)),
+ ],
+ );
+ }
+
+ Widget _body(List<DiffRow> rows) => switch (widget.diff) {
+ FinderLoading() => const SkeletonList(
+ rows: 10,
+ padding: EdgeInsets.all(16),
+ ),
+ FinderFailed(:final message) => EmptyState(
+ icon: AppIcons.circleAlert,
+ title: 'Can’t show this change',
+ message: message,
+ compact: true,
+ ),
+ FinderLoaded() when rows.isEmpty => const EmptyState(
+ icon: AppIcons.fileDiff,
+ title: 'No differences to show',
+ message: 'Only the file’s mode or name changed.',
+ compact: true,
+ ),
+ FinderLoaded() => FinderDiffKeys(
+ onPrevious: () => _go(diffChangeStarts(rows), -1),
+ onNext: () => _go(diffChangeStarts(rows), 1),
+ child: ListView.builder(
+ key: const ValueKey('finder-diff'),
+ controller: _scroll,
+ itemExtent: kDiffRowHeight,
+ padding: const EdgeInsets.symmetric(vertical: 6),
+ itemCount: rows.length,
+ itemBuilder: (context, index) => FinderDiffLine(
+ row: rows[index],
+ language: widget.language,
+ gutterDigits: _digits(rows),
+ onUnfold: (key) => setState(() => _unfolded.add(key)),
+ ),
+ ),
+ ),
+ };
+
+ void _go(List<int> starts, int step) {
+ if (starts.isEmpty) return;
+ setState(() => _change = (_change + step) % starts.length);
+ if (_scroll.hasClients) {
+ _scroll.animateTo(
+ max(0, starts[_change] - 3) * kDiffRowHeight,
+ duration: const Duration(milliseconds: 160),
+ curve: Curves.easeOut,
+ );
+ }
+ }
+
+ int _digits(List<DiffRow> rows) => switch (widget.diff) {
+ FinderLoaded(:final value) =>
+ value
+ .fold(0, (n, l) => max(n, max(l.oldLine ?? 0, l.newLine ?? 0)))
+ .toString()
+ .length,
+ _ => 1,
+ };
+}
diff --git a/desktop/lib/finder/widgets/finder_disk_banner.dart b/desktop/lib/finder/widgets/finder_disk_banner.dart
new file mode 100644
index 000000000..01cec6209
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_disk_banner.dart
@@ -0,0 +1,55 @@
+import 'package:flutter/material.dart';
+
+import '../../shared/theme/app_icons.dart';
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../theme/app_theme.dart';
+import '../finder_document.dart';
+
+/// Said over a tab whose file moved under its edits — Orca's "changed on
+/// disk" banner, with its two ways out — or whose save failed.
+class FinderDiskBanner extends StatelessWidget {
+ const FinderDiskBanner({super.key, required this.document});
+
+ final FinderDocument document;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final (message, actions) = switch (document.disk) {
+ FinderDiskChange.changed => (
+ 'This file changed on disk while you have unsaved edits.',
+ [
+ _action('Reload from Disk', document.reloadFromDisk),
+ _action('Keep My Edits', document.keepMine),
+ ],
+ ),
+ FinderDiskChange.deleted => (
+ 'This file was deleted or moved. Saving puts it back.',
+ const <Widget>[],
+ ),
+ FinderDiskChange.none => (document.saveError, const <Widget>[]),
+ };
+ if (message == null) return const SizedBox.shrink();
+ return Container(
+ key: const ValueKey('finder-disk-banner'),
+ color: AppColors.warning.withValues(alpha: .14),
+ padding: const EdgeInsets.fromLTRB(14, 4, 8, 4),
+ child: Row(
+ children: [
+ Icon(AppIcons.triangleAlert, size: 14, color: AppColors.warning),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ message,
+ style: grid.AppType.label(color: AppColors.text),
+ ),
+ ),
+ ...actions,
+ ],
+ ),
+ );
+ }
+
+ Widget _action(String label, Future<void> Function() onPressed) =>
+ TextButton(onPressed: onPressed, child: Text(label));
+}
diff --git a/desktop/lib/finder/widgets/finder_editor_area.dart b/desktop/lib/finder/widgets/finder_editor_area.dart
new file mode 100644
index 000000000..3afdd551a
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_editor_area.dart
@@ -0,0 +1,70 @@
+import 'package:flutter/material.dart';
+import 'package:path/path.dart' as p;
+
+import '../../theme/app_theme.dart';
+import '../finder_controller.dart';
+import '../finder_language.dart';
+import '../finder_models.dart';
+import '../finder_tabs.dart';
+import 'finder_diff_view.dart';
+import 'finder_file_surface.dart';
+import 'finder_tab_bar.dart';
+import 'finder_tab_close.dart';
+
+/// The tile's right side: its tabs, and the front one's file or diff.
+class FinderEditorArea extends StatelessWidget {
+ const FinderEditorArea({super.key, required this.controller});
+
+ final FinderController controller;
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ // The controller too: Inline/Side by side is the tile's, not a tab's.
+ listenable: Listenable.merge([controller.tabs, controller]),
+ builder: (context, _) {
+ final active = controller.tabs.active;
+ // Shown only while a tab is open (FinderPanePanel); no tab, nothing.
+ if (active == null) return const SizedBox.shrink();
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ FinderTabBar(
+ tabs: controller.tabs,
+ onClose: (tab) => closeFinderTab(context, controller, tab),
+ ),
+ Divider(height: 1, color: AppColors.border),
+ Expanded(child: _surface(active)),
+ ],
+ );
+ },
+ );
+
+ Widget _surface(FinderTab tab) {
+ if (tab.document case final document?) {
+ return FinderFileSurface(
+ key: ValueKey(tab.id),
+ document: document,
+ label: p.relative(document.path, from: controller.root),
+ onOpenExternally: () => controller.files.open(document.path),
+ );
+ }
+ final diff = tab.diff!;
+ final change = diff.change;
+ return ListenableBuilder(
+ key: ValueKey(tab.id),
+ listenable: diff,
+ builder: (context, _) => FinderDiffView(
+ label: change.originalPath == null
+ ? change.path
+ : '${change.originalPath} → ${change.path}',
+ diff: diff.diff,
+ language: finderLanguageOf(change.path),
+ sideBySide: controller.sideBySide,
+ onToggleSideBySide: controller.toggleSideBySide,
+ onOpenFile: change.kind == GitChangeKind.deleted
+ ? null
+ : () => controller.openFile(diff.path, preview: false),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/finder/widgets/finder_file_surface.dart b/desktop/lib/finder/widgets/finder_file_surface.dart
new file mode 100644
index 000000000..37deed176
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_file_surface.dart
@@ -0,0 +1,139 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_svg/flutter_svg.dart';
+
+import '../../shared/theme/app_icons.dart';
+import '../../shared/widgets/app_icon_button.dart';
+import '../../shared/widgets/empty_state.dart';
+import '../../shared/widgets/skeleton.dart';
+import '../../theme/app_theme.dart';
+import '../finder_document.dart';
+import '../finder_file_kind.dart';
+import '../finder_language.dart';
+import '../finder_load.dart';
+import '../finder_models.dart';
+import 'finder_code_editor.dart';
+import 'finder_disk_banner.dart';
+import 'finder_markdown_view.dart';
+import 'finder_surface_bar.dart';
+
+/// A file tab's content: the editor for text, Preview or Source for
+/// Markdown, the picture for an image, and the system's app for the rest —
+/// Orca's choice of viewer by kind.
+class FinderFileSurface extends StatefulWidget {
+ const FinderFileSurface({
+ super.key,
+ required this.document,
+ required this.label,
+ required this.onOpenExternally,
+ });
+
+ final FinderDocument document;
+ final String label;
+ final VoidCallback onOpenExternally;
+
+ @override
+ State<FinderFileSurface> createState() => _FinderFileSurfaceState();
+}
+
+class _FinderFileSurfaceState extends State<FinderFileSurface> {
+ /// Markdown opens rendered; the eye switches to its source to edit it.
+ bool _source = false;
+ bool _wrap = true;
+
+ FinderDocument get _document => widget.document;
+
+ bool get _markdown =>
+ finderFileKind(_document.path) == FinderFileKind.markdown;
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: _document,
+ builder: (context, _) => Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ FinderSurfaceBar(label: widget.label, actions: _actions()),
+ Divider(height: 1, color: AppColors.border),
+ FinderDiskBanner(document: _document),
+ Expanded(child: _body()),
+ ],
+ ),
+ );
+
+ List<Widget> _actions() {
+ final text = switch (_document.content) {
+ FinderLoaded(value: FinderText()) => true,
+ _ => false,
+ };
+ return [
+ if (text && _markdown)
+ AppIconButton(
+ key: const ValueKey('finder-markdown-source'),
+ icon: _source ? AppIcons.eye : AppIcons.code,
+ tooltip: _source ? 'Show preview' : 'Edit source',
+ onPressed: () => setState(() => _source = !_source),
+ ),
+ if (text && (!_markdown || _source))
+ AppIconButton(
+ key: const ValueKey('finder-word-wrap'),
+ icon: AppIcons.wrapText,
+ tooltip: _wrap ? 'Turn word wrap off' : 'Turn word wrap on',
+ selected: _wrap,
+ onPressed: () => setState(() => _wrap = !_wrap),
+ ),
+ AppIconButton(
+ key: const ValueKey('finder-open-file'),
+ icon: AppIcons.externalLink,
+ tooltip: 'Open with default app',
+ onPressed: widget.onOpenExternally,
+ ),
+ ];
+ }
+
+ Widget _body() => switch (_document.content) {
+ FinderLoading() => const SkeletonList(
+ rows: 12,
+ padding: EdgeInsets.all(16),
+ ),
+ FinderFailed(:final message) => EmptyState(
+ icon: AppIcons.circleAlert,
+ title: 'Can’t open this file',
+ message: message,
+ compact: true,
+ ),
+ FinderLoaded(:final value) => _content(value),
+ };
+
+ Widget _content(FinderContent content) => switch (content) {
+ FinderText() when _markdown && !_source => ListenableBuilder(
+ listenable: _document.editor!,
+ builder: (context, _) => FinderMarkdownView(_document.editor!.text),
+ ),
+ FinderText() => FinderCodeEditor(
+ controller: _document.editor!,
+ language: finderLanguageOf(_document.path),
+ wordWrap: _wrap,
+ onSave: _document.save,
+ ),
+ FinderImage(:final bytes, :final svg) => InteractiveViewer(
+ key: const ValueKey('finder-image'),
+ maxScale: 8,
+ child: Center(
+ child: Padding(
+ padding: const EdgeInsets.all(16),
+ child: svg ? SvgPicture.memory(bytes) : Image.memory(bytes),
+ ),
+ ),
+ ),
+ FinderBinary(:final reason) => EmptyState(
+ icon: AppIcons.file,
+ title: 'No preview',
+ message: reason,
+ compact: true,
+ action: TextButton(
+ key: const ValueKey('finder-open-externally'),
+ onPressed: widget.onOpenExternally,
+ child: const Text('Open with default app'),
+ ),
+ ),
+ };
+}
diff --git a/desktop/lib/finder/widgets/finder_find_panel.dart b/desktop/lib/finder/widgets/finder_find_panel.dart
new file mode 100644
index 000000000..03f193ed9
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_find_panel.dart
@@ -0,0 +1,155 @@
+import 'package:flutter/material.dart';
+import 'package:re_editor/re_editor.dart';
+
+import '../../shared/theme/app_icons.dart';
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../shared/widgets/app_icon_button.dart';
+import '../../theme/app_theme.dart';
+
+const _rowHeight = 34.0;
+
+/// The editor's find and replace bar (⌘F, ⌥⌘F), over the code's top right
+/// the way Monaco's sits in Orca. re_editor runs the search; this draws it.
+class FinderFindPanel extends StatelessWidget implements PreferredSizeWidget {
+ const FinderFindPanel({
+ super.key,
+ required this.controller,
+ required this.readOnly,
+ });
+
+ final CodeFindController controller;
+ final bool readOnly;
+
+ @override
+ Size get preferredSize => Size(double.infinity, switch (controller.value) {
+ null => 0,
+ final value => value.replaceMode ? _rowHeight * 2 + 8 : _rowHeight + 8,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final value = controller.value;
+ if (value == null) return const SizedBox.shrink();
+ grid.AppTheme.watch(context);
+ return Align(
+ alignment: Alignment.topRight,
+ child: Container(
+ width: 380,
+ margin: const EdgeInsets.fromLTRB(8, 4, 12, 4),
+ padding: const EdgeInsets.symmetric(horizontal: 6),
+ decoration: BoxDecoration(
+ color: grid.AppPalette.panelBg,
+ border: Border.all(color: AppColors.border),
+ borderRadius: BorderRadius.circular(6),
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ _row([
+ _field(
+ controller.findInputController,
+ controller.findInputFocusNode,
+ 'Find',
+ ),
+ _toggle(
+ AppIcons.caseSensitive,
+ 'Match case',
+ value.option.caseSensitive,
+ controller.toggleCaseSensitive,
+ ),
+ _toggle(
+ AppIcons.regex,
+ 'Use regular expression',
+ value.option.regex,
+ controller.toggleRegex,
+ ),
+ SizedBox(
+ width: 54,
+ child: Text(
+ _count(value),
+ textAlign: TextAlign.center,
+ style: grid.AppType.caption(color: AppColors.muted),
+ ),
+ ),
+ _button(
+ AppIcons.arrowUp,
+ 'Previous match',
+ value.result == null ? null : controller.previousMatch,
+ ),
+ _button(
+ AppIcons.arrowDown,
+ 'Next match',
+ value.result == null ? null : controller.nextMatch,
+ ),
+ if (!readOnly)
+ _toggle(
+ AppIcons.replace,
+ 'Replace',
+ value.replaceMode,
+ controller.toggleMode,
+ ),
+ _button(AppIcons.close, 'Close', controller.close),
+ ]),
+ if (value.replaceMode && !readOnly)
+ _row([
+ _field(
+ controller.replaceInputController,
+ controller.replaceInputFocusNode,
+ 'Replace',
+ ),
+ TextButton(
+ onPressed: value.result == null
+ ? null
+ : controller.replaceMatch,
+ child: const Text('Replace'),
+ ),
+ TextButton(
+ onPressed: value.result == null
+ ? null
+ : controller.replaceAllMatches,
+ child: const Text('All'),
+ ),
+ ]),
+ ],
+ ),
+ ),
+ );
+ }
+
+ String _count(CodeFindValue value) => switch (value.result) {
+ null => 'No results',
+ final result when result.matches.isEmpty => 'No results',
+ final result => '${result.index + 1} of ${result.matches.length}',
+ };
+
+ Widget _row(List<Widget> children) => SizedBox(
+ height: _rowHeight,
+ child: Row(children: children),
+ );
+
+ Widget _field(TextEditingController text, FocusNode focus, String hint) =>
+ Expanded(
+ child: TextField(
+ controller: text,
+ focusNode: focus,
+ style: grid.AppType.label(color: AppColors.text),
+ decoration: InputDecoration(
+ isDense: true,
+ hintText: hint,
+ border: InputBorder.none,
+ contentPadding: const EdgeInsets.symmetric(horizontal: 6),
+ ),
+ ),
+ );
+
+ Widget _toggle(IconData icon, String tooltip, bool on, VoidCallback onTap) =>
+ AppIconButton(
+ icon: icon,
+ tooltip: tooltip,
+ selected: on,
+ onPressed: onTap,
+ );
+
+ Widget _button(IconData icon, String tooltip, VoidCallback? onTap) =>
+ AppIconButton(icon: icon, tooltip: tooltip, onPressed: onTap);
+}
diff --git a/desktop/lib/finder/widgets/finder_header.dart b/desktop/lib/finder/widgets/finder_header.dart
new file mode 100644
index 000000000..9f59d924e
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_header.dart
@@ -0,0 +1,89 @@
+import 'package:flutter/material.dart';
+import 'package:path/path.dart' as p;
+
+import '../../shared/theme/app_pane_icon.dart';
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../shared/theme/workspace_bar_style.dart';
+import '../../theme/app_theme.dart';
+import '../../widgets/agent_drag.dart' show PaneHeaderButton;
+import '../../widgets/engine_identity.dart';
+import '../finder_controller.dart';
+
+/// The Finder tile's header: its folder, the branch it is on with how far
+/// it is from upstream, Collapse (to a rail, as Orca folds a sidebar) and
+/// Refresh. No Close: the Finder and its chat are one group, closed from the
+/// chat (`AppNotifier.requestClosePane`).
+class FinderHeader extends StatelessWidget {
+ const FinderHeader({
+ super.key,
+ required this.controller,
+ required this.compact,
+ required this.onCollapse,
+ });
+
+ final FinderController controller;
+ final bool compact;
+ final VoidCallback onCollapse;
+
+ @override
+ Widget build(BuildContext context) {
+ final repository = controller.git.repository;
+ final branch = [
+ ?repository?.branch,
+ if ((repository?.ahead ?? 0) > 0) '↑${repository!.ahead}',
+ if ((repository?.behind ?? 0) > 0) '↓${repository!.behind}',
+ ].join(' ');
+ return MediaQuery.withNoTextScaling(
+ child: SizedBox(
+ height: compact ? 38 : 46,
+ child: Padding(
+ padding: const EdgeInsets.only(
+ left: 14,
+ right: grid.AppDesktop.paneCloseInset,
+ ),
+ child: Row(
+ children: [
+ const EngineMark(engine: kFinderEngine, size: 17),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Tooltip(
+ message: controller.root,
+ waitDuration: const Duration(milliseconds: 500),
+ child: Text.rich(
+ key: const ValueKey('finder-pane-title'),
+ TextSpan(
+ text: p.basename(controller.root),
+ style: workspaceBarTextStyle(color: AppColors.text),
+ children: [
+ if (branch.isNotEmpty)
+ TextSpan(
+ text: ' $branch',
+ style: grid.AppType.monoLabel(
+ color: AppColors.mutedStrong,
+ ),
+ ),
+ ],
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ ),
+ PaneHeaderButton(
+ key: const ValueKey('finder-collapse'),
+ label: 'Collapse Finder',
+ icon: AppPaneSymbol.collapseLeft,
+ onPressed: onCollapse,
+ ),
+ PaneHeaderButton(
+ label: 'Refresh',
+ icon: AppPaneSymbol.reload,
+ onPressed: controller.refresh,
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/finder/widgets/finder_markdown_view.dart b/desktop/lib/finder/widgets/finder_markdown_view.dart
new file mode 100644
index 000000000..49bf1aa64
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_markdown_view.dart
@@ -0,0 +1,31 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';
+
+import '../../core/open_in_browser.dart';
+import '../../widgets/markdown_style.dart';
+
+/// A Markdown file rendered — Orca's preview. Images stay labels: a preview
+/// never fetches from the network or reads files the Markdown points at.
+class FinderMarkdownView extends StatelessWidget {
+ const FinderMarkdownView(this.text, {super.key});
+
+ final String text;
+
+ @override
+ Widget build(BuildContext context) => SelectionArea(
+ child: SingleChildScrollView(
+ key: const ValueKey('finder-markdown'),
+ padding: const EdgeInsets.fromLTRB(24, 18, 24, 32),
+ child: MarkdownBody(
+ data: text,
+ styleSheet: desktopMarkdownStyleSheet(context),
+ onTapLink: (_, href, _) {
+ final uri = href == null ? null : Uri.tryParse(href);
+ if (uri != null) openInBrowser(uri);
+ },
+ imageBuilder: (_, _, alt) =>
+ Text(alt?.isNotEmpty == true ? 'Image: $alt' : 'Image'),
+ ),
+ ),
+ );
+}
diff --git a/desktop/lib/finder/widgets/finder_name_field.dart b/desktop/lib/finder/widgets/finder_name_field.dart
new file mode 100644
index 000000000..1923546b3
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_name_field.dart
@@ -0,0 +1,132 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:path/path.dart' as p;
+
+import '../../shared/theme/app_icons.dart';
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../theme/app_theme.dart';
+import 'finder_row.dart';
+
+/// The name typed in place in the tree — a new file, a new folder, or a
+/// rename — the way Orca's explorer takes it: ↵ commits, Esc or leaving
+/// cancels, and a refusal stays beside the field until the name changes.
+class FinderNameField extends StatefulWidget {
+ const FinderNameField({
+ super.key,
+ required this.depth,
+ required this.icon,
+ required this.onSubmit,
+ required this.onCancel,
+ this.initial = '',
+ });
+
+ final int depth;
+ final IconData icon;
+ final String initial;
+
+ /// Answers why the name was refused, or null when it was taken.
+ final Future<String?> Function(String name) onSubmit;
+ final VoidCallback onCancel;
+
+ @override
+ State<FinderNameField> createState() => _FinderNameFieldState();
+}
+
+class _FinderNameFieldState extends State<FinderNameField> {
+ late final _text = TextEditingController(text: widget.initial)
+ // A rename selects the name, not its extension, as Finder does.
+ ..selection = TextSelection(
+ baseOffset: 0,
+ extentOffset: p.basenameWithoutExtension(widget.initial).length,
+ );
+ final _focus = FocusNode();
+ String? _error;
+ bool _busy = false;
+
+ @override
+ void initState() {
+ super.initState();
+ _focus.addListener(() {
+ if (!_focus.hasFocus && !_busy) widget.onCancel();
+ });
+ WidgetsBinding.instance.addPostFrameCallback((_) => _focus.requestFocus());
+ }
+
+ @override
+ void dispose() {
+ _text.dispose();
+ _focus.dispose();
+ super.dispose();
+ }
+
+ Future<void> _submit() async {
+ _busy = true;
+ final error = await widget.onSubmit(_text.text);
+ if (!mounted) return;
+ _busy = false;
+ setState(() => _error = error);
+ if (error != null) _focus.requestFocus();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return Padding(
+ padding: EdgeInsets.only(
+ left: 8 + (widget.depth + 1) * FinderRow.indentStep,
+ right: 8,
+ ),
+ child: Row(
+ children: [
+ Icon(widget.icon, size: 14, color: AppColors.mutedStrong),
+ const SizedBox(width: 6),
+ Expanded(
+ child: CallbackShortcuts(
+ bindings: {
+ const SingleActivator(LogicalKeyboardKey.escape):
+ widget.onCancel,
+ },
+ child: TextField(
+ key: const ValueKey('finder-name-field'),
+ controller: _text,
+ focusNode: _focus,
+ onSubmitted: (_) => _submit(),
+ onChanged: (_) => setState(() => _error = null),
+ style: grid.AppType.label(color: AppColors.text),
+ decoration: InputDecoration(
+ isDense: true,
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 6,
+ vertical: 4,
+ ),
+ border: OutlineInputBorder(
+ borderSide: BorderSide(
+ color: _error == null
+ ? AppColors.accent
+ : AppColors.danger,
+ ),
+ ),
+ suffixIconConstraints: const BoxConstraints(),
+ suffixIcon: _error == null
+ ? null
+ : Tooltip(
+ message: _error,
+ child: Padding(
+ padding: const EdgeInsets.only(right: 6),
+ child: Icon(
+ AppIcons.circleAlert,
+ key: const ValueKey('finder-name-error'),
+ size: 13,
+ color: AppColors.danger,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/finder/widgets/finder_pane_panel.dart b/desktop/lib/finder/widgets/finder_pane_panel.dart
new file mode 100644
index 000000000..8cbfc4196
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_pane_panel.dart
@@ -0,0 +1,202 @@
+import 'package:flutter/material.dart';
+
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../theme/app_theme.dart';
+import '../finder_controller.dart';
+import '../finder_files.dart';
+import '../finder_git.dart';
+import '../local_finder_files.dart';
+import '../local_finder_git.dart';
+import 'finder_editor_area.dart';
+import 'finder_header.dart';
+import 'finder_rail.dart';
+import 'finder_sidebar.dart';
+import 'finder_tab_close.dart';
+
+/// A Finder tile: a folder's files and Git changes on the left, its open
+/// files and diffs in tabs on the right — Orca's explorer, source control
+/// and editor, in one pane.
+///
+/// With no file open it is only as wide as its file list, and folded it is a
+/// rail ([FinderRail]): it asks the grid for that width ([onFixedWidth]), so
+/// the chat beside it gets the room the empty editor would have taken.
+///
+/// It owns its [FinderController] for the tile's life; the grid keys cells by
+/// a GlobalKey, so moving the tile keeps its tabs and edits.
+class FinderPanePanel extends StatefulWidget {
+ const FinderPanePanel({
+ super.key,
+ required this.root,
+ this.files = const LocalFinderFiles(),
+ this.git = const LocalFinderGit(),
+ this.onGuardClose,
+ this.compactHeader = false,
+ this.onFixedWidth,
+ });
+
+ final String root;
+ final FinderFiles files;
+ final FinderGit git;
+
+ /// Handed the check the pane's close must pass while this panel is
+ /// mounted — unsaved tabs are asked about first — and null when it goes.
+ final void Function(Future<bool> Function()? guard)? onGuardClose;
+ final bool compactHeader;
+
+ /// Told the width in pixels the tile wants while it shows no editor, and
+ /// null when it takes its share of the tab again.
+ final ValueChanged<double?>? onFixedWidth;
+
+ @override
+ State<FinderPanePanel> createState() => _FinderPanePanelState();
+}
+
+class _FinderPanePanelState extends State<FinderPanePanel> {
+ late final FinderController _controller = FinderController(
+ root: widget.root,
+ files: widget.files,
+ git: widget.git,
+ );
+ double _sidebar = 260;
+ bool _collapsed = false;
+ bool _editing = false;
+ double? _reported;
+
+ double get _headerHeight => widget.compactHeader ? 38 : 46;
+
+ /// Folded, the rail; with no file open, the file list and its splitter;
+ /// otherwise its share of the tab.
+ double? get _fixedWidth => _collapsed
+ ? kFinderRailWidth
+ : _editing
+ ? null
+ : _sidebar + _Splitter.width;
+
+ @override
+ void initState() {
+ super.initState();
+ _controller.start();
+ _controller.tabs.addListener(_onTabs);
+ widget.onGuardClose?.call(() => closeAllFinderTabs(context, _controller));
+ WidgetsBinding.instance.addPostFrameCallback((_) => _report());
+ }
+
+ @override
+ void dispose() {
+ _controller.tabs.removeListener(_onTabs);
+ widget.onGuardClose?.call(null);
+ _controller.dispose();
+ super.dispose();
+ }
+
+ void _onTabs() {
+ final editing = _controller.tabs.tabs.isNotEmpty;
+ if (editing == _editing) return;
+ // Opening a file unfolds a folded Finder: it is where the file shows.
+ setState(() {
+ _editing = editing;
+ if (editing) _collapsed = false;
+ });
+ _report();
+ }
+
+ void _setCollapsed(bool collapsed) {
+ setState(() => _collapsed = collapsed);
+ _report();
+ }
+
+ void _report() {
+ final width = _fixedWidth;
+ if (!mounted || width == _reported) return;
+ _reported = width;
+ widget.onFixedWidth?.call(width);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ if (_collapsed) {
+ return FinderRail(
+ controller: _controller,
+ headerHeight: _headerHeight,
+ onExpand: () => _setCollapsed(false),
+ );
+ }
+ return ColoredBox(
+ color: grid.AppPalette.windowBg,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ ListenableBuilder(
+ listenable: _controller.git,
+ builder: (context, _) => FinderHeader(
+ controller: _controller,
+ compact: widget.compactHeader,
+ onCollapse: () => _setCollapsed(true),
+ ),
+ ),
+ Divider(height: 1, color: AppColors.border),
+ Expanded(child: _editing ? _body() : _filesOnly()),
+ ],
+ ),
+ );
+ }
+
+ Widget _sidebarList() => ListenableBuilder(
+ listenable: Listenable.merge([_controller, _controller.git]),
+ builder: (context, _) => FinderSidebar(controller: _controller),
+ );
+
+ /// No file open: the file list is the whole tile, and its edge sets how
+ /// wide the tile asks to be.
+ Widget _filesOnly() => Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(child: _sidebarList()),
+ _Splitter(
+ onDrag: (dx) {
+ setState(() => _sidebar = (_sidebar + dx).clamp(160.0, 640.0));
+ _report();
+ },
+ ),
+ ],
+ );
+
+ Widget _body() => LayoutBuilder(
+ builder: (context, constraints) {
+ final width = _sidebar.clamp(160.0, constraints.maxWidth * .6);
+ return Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ SizedBox(width: width, child: _sidebarList()),
+ _Splitter(onDrag: (dx) => setState(() => _sidebar = width + dx)),
+ Expanded(child: FinderEditorArea(controller: _controller)),
+ ],
+ );
+ },
+ );
+}
+
+/// The line between the sidebar and the tabs, dragged to resize them.
+class _Splitter extends StatelessWidget {
+ const _Splitter({required this.onDrag});
+
+ static const width = 5.0;
+
+ final ValueChanged<double> onDrag;
+
+ @override
+ Widget build(BuildContext context) => MouseRegion(
+ cursor: SystemMouseCursors.resizeColumn,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onHorizontalDragUpdate: (details) => onDrag(details.delta.dx),
+ child: SizedBox(
+ width: width,
+ child: Center(
+ child: VerticalDivider(width: 1, color: AppColors.border),
+ ),
+ ),
+ ),
+ );
+}
diff --git a/desktop/lib/finder/widgets/finder_rail.dart b/desktop/lib/finder/widgets/finder_rail.dart
new file mode 100644
index 000000000..f695a1254
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_rail.dart
@@ -0,0 +1,73 @@
+import 'package:flutter/material.dart';
+
+import '../../shared/theme/app_icons.dart';
+import '../../shared/theme/app_pane_icon.dart';
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../shared/widgets/app_icon_button.dart';
+import '../../theme/app_theme.dart';
+import '../../widgets/agent_drag.dart' show PaneHeaderButton;
+import '../finder_controller.dart';
+
+/// How wide a folded Finder is: one column of buttons.
+const kFinderRailWidth = 44.0;
+
+/// A Finder folded to its edge, as Orca folds a sidebar: Expand, and the
+/// Files and Changes lists one click away, each opening the Finder on it.
+class FinderRail extends StatelessWidget {
+ const FinderRail({
+ super.key,
+ required this.controller,
+ required this.headerHeight,
+ required this.onExpand,
+ });
+
+ final FinderController controller;
+ final double headerHeight;
+ final VoidCallback onExpand;
+
+ void _open(FinderMode mode) {
+ controller.setMode(mode);
+ onExpand();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final mode = controller.mode;
+ return ColoredBox(
+ key: const ValueKey('finder-rail'),
+ color: grid.AppPalette.windowBg,
+ child: Column(
+ children: [
+ SizedBox(
+ height: headerHeight,
+ child: Center(
+ child: PaneHeaderButton(
+ key: const ValueKey('finder-expand'),
+ label: 'Expand Finder',
+ icon: AppPaneSymbol.expandLeft,
+ onPressed: onExpand,
+ ),
+ ),
+ ),
+ Divider(height: 1, color: AppColors.border),
+ const SizedBox(height: 6),
+ AppIconButton(
+ key: const ValueKey('finder-rail-files'),
+ icon: AppIcons.folder,
+ tooltip: 'Files',
+ selected: mode == FinderMode.files,
+ onPressed: () => _open(FinderMode.files),
+ ),
+ AppIconButton(
+ key: const ValueKey('finder-rail-changes'),
+ icon: AppIcons.gitBranch,
+ tooltip: 'Changes',
+ selected: mode == FinderMode.changes,
+ onPressed: () => _open(FinderMode.changes),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/finder/widgets/finder_row.dart b/desktop/lib/finder/widgets/finder_row.dart
new file mode 100644
index 000000000..255ed2595
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_row.dart
@@ -0,0 +1,126 @@
+import 'package:flutter/material.dart';
+
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../theme/app_theme.dart';
+
+/// One row of a Finder sidebar — a tree entry or a change — so both lists
+/// share one height, indent, hover and selection.
+class FinderRow extends StatelessWidget {
+ const FinderRow({
+ super.key,
+ required this.icon,
+ required this.label,
+ required this.onTap,
+ this.indent = 0,
+ this.selected = false,
+ this.detail,
+ this.leading,
+ this.trailing,
+ this.labelColor,
+ this.strike = false,
+ this.faint = false,
+ });
+
+ static const height = 26.0;
+ static const indentStep = 14.0;
+
+ final IconData icon;
+ final String label;
+ final VoidCallback onTap;
+ final int indent;
+ final bool selected;
+
+ /// Quieter text after the label: a changed file's folder.
+ final String? detail;
+
+ /// Before the icon: a folder's disclosure chevron.
+ final Widget? leading;
+ final Widget? trailing;
+ final Color? labelColor;
+
+ /// A deleted file, crossed through.
+ final bool strike;
+
+ /// An entry Git ignores: italic and quiet, as Orca draws it.
+ final bool faint;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return Material(
+ color: selected ? AppColors.selected : Colors.transparent,
+ child: InkWell(
+ // No onDoubleTap here: it would hold every single tap back until
+ // the double-tap window passed. Callers that pin on a second click
+ // tell it from the first by time ([FinderClickTracker]).
+ onTap: onTap,
+ hoverColor: AppColors.rowHover,
+ child: SizedBox(
+ height: height,
+ child: Padding(
+ padding: EdgeInsets.only(left: 8 + indent * indentStep, right: 10),
+ child: Row(
+ children: [
+ SizedBox(width: 16, child: leading),
+ Icon(
+ icon,
+ size: 14,
+ color: faint
+ ? AppColors.muted
+ : labelColor ?? AppColors.mutedStrong,
+ ),
+ const SizedBox(width: 6),
+ // The name keeps what it needs and the folder takes what is
+ // left, so every row's mark lines up at the right edge. The
+ // name gets the larger share when both are long: it is what
+ // the row is.
+ Expanded(
+ child: Row(
+ children: [
+ Flexible(
+ flex: 3,
+ child: Text(
+ label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style:
+ grid.AppType.label(
+ color: faint
+ ? AppColors.muted
+ : labelColor ?? AppColors.text,
+ fontWeight: FontWeight.w400,
+ fontStyle: faint ? FontStyle.italic : null,
+ ).copyWith(
+ decoration: strike
+ ? TextDecoration.lineThrough
+ : null,
+ ),
+ ),
+ ),
+ if (detail case final detail?) ...[
+ const SizedBox(width: 6),
+ Expanded(
+ flex: 2,
+ child: Text(
+ detail,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: grid.AppType.caption(color: AppColors.muted),
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ if (trailing case final trailing?) ...[
+ const SizedBox(width: 6),
+ trailing,
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/finder/widgets/finder_sidebar.dart b/desktop/lib/finder/widgets/finder_sidebar.dart
new file mode 100644
index 000000000..805423ab4
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_sidebar.dart
@@ -0,0 +1,170 @@
+import 'package:flutter/material.dart';
+import 'package:path/path.dart' as p;
+
+import '../../shared/theme/app_icons.dart';
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../shared/widgets/app_icon_button.dart';
+import '../../theme/app_theme.dart';
+import '../finder_controller.dart';
+import 'finder_changes_view.dart';
+import 'finder_tree_view.dart';
+
+/// The tile's left column: Files or Changes — Orca's Explorer and Source
+/// Control, side by side in one switch — with the list for the one chosen.
+class FinderSidebar extends StatefulWidget {
+ const FinderSidebar({super.key, required this.controller});
+
+ final FinderController controller;
+
+ @override
+ State<FinderSidebar> createState() => _FinderSidebarState();
+}
+
+class _FinderSidebarState extends State<FinderSidebar> {
+ final _tree = GlobalKey<FinderTreeViewState>();
+
+ FinderController get _controller => widget.controller;
+
+ /// Where New File and New Folder make things: the folder on the keyboard's
+ /// row, the folder of the file there, or the top.
+ String get _targetFolder {
+ final at = _tree.currentState?.cursor ?? _controller.activePath;
+ if (at == null) return _controller.root;
+ final folder = _controller.tree.rows.any(
+ (row) => row.entry.path == at && row.entry.isDirectory,
+ );
+ return folder ? at : p.dirname(at);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final files = _controller.mode == FinderMode.files;
+ final count = _controller.git.repository?.changes.length ?? 0;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.all(6),
+ child: Row(
+ children: [
+ Expanded(
+ child: _ModeTab(
+ key: const ValueKey('finder-mode-files'),
+ label: 'Files',
+ selected: files,
+ onTap: () => _controller.setMode(FinderMode.files),
+ ),
+ ),
+ Expanded(
+ child: _ModeTab(
+ key: const ValueKey('finder-mode-changes'),
+ label: count == 0 ? 'Changes' : 'Changes $count',
+ selected: !files,
+ onTap: () => _controller.setMode(FinderMode.changes),
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (files) _toolbar(),
+ Divider(height: 1, color: AppColors.border),
+ Expanded(
+ child: files
+ ? FinderTreeView(key: _tree, controller: _controller)
+ : FinderChangesView(controller: _controller),
+ ),
+ if (_controller.notice case final notice?)
+ Container(
+ key: const ValueKey('finder-notice'),
+ color: AppColors.danger.withValues(alpha: .12),
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
+ child: Text(
+ notice,
+ style: grid.AppType.caption(color: AppColors.text),
+ ),
+ ),
+ ],
+ );
+ }
+
+ /// The Files toolbar, on its own row as Orca's Explorer has it: the
+ /// folder's name, and New File, New Folder and Collapse All.
+ Widget _toolbar() => Padding(
+ padding: const EdgeInsets.only(left: 12, right: 4),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ p.basename(_controller.root).toUpperCase(),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: grid.AppType.caption(
+ color: AppColors.muted,
+ fontWeight: FontWeight.w600,
+ letterSpacing: .6,
+ ),
+ ),
+ ),
+ AppIconButton(
+ key: const ValueKey('finder-new-file'),
+ icon: AppIcons.filePlus,
+ tooltip: 'New File',
+ onPressed: () =>
+ _tree.currentState?.startCreate(_targetFolder, asFolder: false),
+ ),
+ AppIconButton(
+ icon: AppIcons.folderPlus,
+ tooltip: 'New Folder',
+ onPressed: () =>
+ _tree.currentState?.startCreate(_targetFolder, asFolder: true),
+ ),
+ AppIconButton(
+ icon: AppIcons.chevronsDownUp,
+ tooltip: 'Collapse All',
+ onPressed: _controller.tree.collapseAll,
+ ),
+ ],
+ ),
+ );
+}
+
+class _ModeTab extends StatelessWidget {
+ const _ModeTab({
+ super.key,
+ required this.label,
+ required this.selected,
+ required this.onTap,
+ });
+
+ final String label;
+ final bool selected;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) => Semantics(
+ selected: selected,
+ button: true,
+ child: InkWell(
+ onTap: onTap,
+ borderRadius: BorderRadius.circular(6),
+ hoverColor: AppColors.rowHover,
+ child: Container(
+ height: 26,
+ padding: const EdgeInsets.symmetric(horizontal: 10),
+ alignment: Alignment.center,
+ decoration: BoxDecoration(
+ color: selected ? AppColors.selected : null,
+ borderRadius: BorderRadius.circular(6),
+ ),
+ child: Text(
+ label,
+ style: grid.AppType.label(
+ color: selected ? AppColors.text : AppColors.mutedStrong,
+ fontWeight: selected ? FontWeight.w600 : FontWeight.w500,
+ ),
+ ),
+ ),
+ ),
+ );
+}
diff --git a/desktop/lib/finder/widgets/finder_surface_bar.dart b/desktop/lib/finder/widgets/finder_surface_bar.dart
new file mode 100644
index 000000000..8901bd4d1
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_surface_bar.dart
@@ -0,0 +1,42 @@
+import 'package:flutter/material.dart';
+
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../theme/app_theme.dart';
+
+/// The strip over a tab's content: what it shows, and what can be done to
+/// it — a file's path and Preview/Source, a diff's sides and its changes.
+class FinderSurfaceBar extends StatelessWidget {
+ const FinderSurfaceBar({
+ super.key,
+ required this.label,
+ this.actions = const [],
+ });
+
+ final String label;
+ final List<Widget> actions;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return SizedBox(
+ height: 32,
+ child: Padding(
+ padding: const EdgeInsets.only(left: 14, right: 6),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ label,
+ key: const ValueKey('finder-surface-label'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: grid.AppType.monoLabel(color: AppColors.mutedStrong),
+ ),
+ ),
+ ...actions,
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/finder/widgets/finder_tab_bar.dart b/desktop/lib/finder/widgets/finder_tab_bar.dart
new file mode 100644
index 000000000..84193ab47
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_tab_bar.dart
@@ -0,0 +1,190 @@
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+
+import '../../shared/theme/app_icons.dart';
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../shared/theme/file_type_icon.dart';
+import '../../theme/app_theme.dart';
+import '../finder_models.dart';
+import '../finder_tabs.dart';
+import 'finder_click.dart';
+
+/// The open tabs, as Orca's tab bar draws them: a preview tab in italics
+/// (the next single click replaces it), a dot for unsaved edits that turns
+/// into × under the pointer, a double click to keep it, a middle click to
+/// close it.
+class FinderTabBar extends StatelessWidget {
+ const FinderTabBar({super.key, required this.tabs, required this.onClose});
+
+ final FinderTabs tabs;
+ final ValueChanged<FinderTab> onClose;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return SizedBox(
+ height: 32,
+ child: ListView(
+ scrollDirection: Axis.horizontal,
+ children: [
+ for (final tab in tabs.tabs)
+ // Each tab hears its own file: saving clears its dot without
+ // the tab list changing.
+ ListenableBuilder(
+ key: ValueKey('finder-tab-${tab.id}'),
+ listenable: tab.document ?? tab.diff!,
+ builder: (context, _) => _Tab(
+ tab: tab,
+ active: tab.id == tabs.activeId,
+ onTap: () => tabs.activate(tab.id),
+ onPin: () => tabs.pin(tab.id),
+ onClose: () => onClose(tab),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class _Tab extends StatefulWidget {
+ const _Tab({
+ required this.tab,
+ required this.active,
+ required this.onTap,
+ required this.onPin,
+ required this.onClose,
+ });
+
+ final FinderTab tab;
+ final bool active;
+ final VoidCallback onTap, onPin, onClose;
+
+ @override
+ State<_Tab> createState() => _TabState();
+}
+
+class _TabState extends State<_Tab> {
+ final _clicks = FinderClickTracker();
+ bool _hovered = false;
+
+ @override
+ Widget build(BuildContext context) {
+ final tab = widget.tab;
+ final diff = tab.diff;
+ return Listener(
+ onPointerDown: (event) {
+ if (event.buttons == kMiddleMouseButton) widget.onClose();
+ },
+ child: MouseRegion(
+ onEnter: (_) => setState(() => _hovered = true),
+ onExit: (_) => setState(() => _hovered = false),
+ child: GestureDetector(
+ // A second click pins, told apart by time: an onDoubleTap here
+ // would hold every click — the × included — for the double-tap
+ // window.
+ onTap: () {
+ widget.onTap();
+ if (_clicks.isDouble(widget.tab.id)) widget.onPin();
+ },
+ child: Container(
+ padding: const EdgeInsets.only(left: 10, right: 4),
+ decoration: BoxDecoration(
+ color: widget.active
+ ? grid.AppPalette.windowBg
+ : _hovered
+ ? AppColors.rowHover
+ : Colors.transparent,
+ border: Border(
+ right: BorderSide(color: AppColors.border),
+ top: BorderSide(
+ color: widget.active ? AppColors.accent : Colors.transparent,
+ width: 2,
+ ),
+ ),
+ ),
+ child: Row(
+ children: [
+ Icon(
+ diff == null ? fileTypeIcon(tab.title) : AppIcons.fileDiff,
+ size: 13,
+ color: AppColors.mutedStrong,
+ ),
+ const SizedBox(width: 6),
+ Text(
+ diff == null
+ ? tab.title
+ : '${tab.title} ${_side(diff.change)}',
+ style: grid.AppType.label(
+ color: widget.active
+ ? AppColors.text
+ : AppColors.mutedStrong,
+ fontWeight: FontWeight.w400,
+ fontStyle: tab.preview ? FontStyle.italic : null,
+ ),
+ ),
+ const SizedBox(width: 4),
+ _CloseMark(
+ dirty: tab.dirty,
+ visible: _hovered || widget.active,
+ hovered: _hovered,
+ onPressed: widget.onClose,
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ String _side(GitChange change) => switch (change.area) {
+ GitArea.staged => '(Index)',
+ GitArea.untracked => '(Untracked)',
+ _ => '(Working Tree)',
+ };
+}
+
+/// ● while the tab has unsaved edits, × to close under the pointer.
+class _CloseMark extends StatelessWidget {
+ const _CloseMark({
+ required this.dirty,
+ required this.visible,
+ required this.hovered,
+ required this.onPressed,
+ });
+
+ /// The × shows on the front tab and under the pointer, as in Orca.
+ final bool dirty, visible, hovered;
+ final VoidCallback onPressed;
+
+ @override
+ Widget build(BuildContext context) {
+ final showDot = dirty && !hovered;
+ return SizedBox.square(
+ dimension: 20,
+ // One button either way: the dot of unsaved edits closes the tab too.
+ child: IconButton(
+ key: const ValueKey('finder-tab-close'),
+ padding: EdgeInsets.zero,
+ iconSize: 12,
+ tooltip: dirty ? 'Close (unsaved)' : 'Close',
+ onPressed: onPressed,
+ icon: showDot
+ ? Container(
+ key: const ValueKey('finder-tab-dirty'),
+ width: 7,
+ height: 7,
+ decoration: BoxDecoration(
+ color: AppColors.text,
+ shape: BoxShape.circle,
+ ),
+ )
+ : Icon(
+ AppIcons.close,
+ color: visible ? AppColors.mutedStrong : Colors.transparent,
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/finder/widgets/finder_tab_close.dart b/desktop/lib/finder/widgets/finder_tab_close.dart
new file mode 100644
index 000000000..15b5109c4
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_tab_close.dart
@@ -0,0 +1,37 @@
+import 'package:flutter/widgets.dart';
+
+import '../finder_controller.dart';
+import '../finder_tabs.dart';
+import 'finder_dialogs.dart';
+
+/// Closes [tab], asking first when it has unsaved edits — Save, Don't Save
+/// or Cancel. False when the person kept it open or the save failed.
+Future<bool> closeFinderTab(
+ BuildContext context,
+ FinderController controller,
+ FinderTab tab,
+) async {
+ if (tab.dirty) {
+ final choice = await askToSaveChanges(context, tab.title);
+ if (choice == null) return false;
+ if (choice == FinderUnsavedChoice.save && !await tab.document!.save()) {
+ return false;
+ }
+ }
+ controller.tabs.close(tab.id);
+ return true;
+}
+
+/// Asks about every tab with unsaved edits, one at a time, before the whole
+/// tile closes. False as soon as one is kept open.
+Future<bool> closeAllFinderTabs(
+ BuildContext context,
+ FinderController controller,
+) async {
+ for (final tab in controller.tabs.tabs.where((t) => t.dirty).toList()) {
+ if (!context.mounted) return false;
+ controller.tabs.activate(tab.id);
+ if (!await closeFinderTab(context, controller, tab)) return false;
+ }
+ return true;
+}
diff --git a/desktop/lib/finder/widgets/finder_tree_keys.dart b/desktop/lib/finder/widgets/finder_tree_keys.dart
new file mode 100644
index 000000000..31f11a372
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_tree_keys.dart
@@ -0,0 +1,86 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:path/path.dart' as p;
+
+import '../finder_tree.dart';
+import 'finder_row.dart';
+import 'finder_tree_menu.dart';
+import 'finder_tree_view.dart';
+
+/// The tree's keyboard, Orca's explorer keys: ↑/↓ move, → opens a folder or
+/// steps into it, ← closes it or steps out, Space opens, ↵ or F2 renames,
+/// ⌘⌫ / Delete moves to the Trash, Esc lets go of the row.
+class FinderTreeKeys extends StatelessWidget {
+ const FinderTreeKeys({
+ super.key,
+ required this.tree,
+ required this.rows,
+ required this.child,
+ });
+
+ final FinderTreeViewState tree;
+ final List<FinderTreeRow> rows;
+ final Widget child;
+
+ @override
+ Widget build(BuildContext context) => Focus(
+ focusNode: tree.focus,
+ onKeyEvent: (_, event) =>
+ event is KeyUpEvent ? KeyEventResult.ignored : _key(context, event),
+ child: child,
+ );
+
+ KeyEventResult _key(BuildContext context, KeyEvent event) {
+ final at = rows.indexWhere(
+ (row) => row.entry.path == (tree.cursor ?? tree.controller.activePath),
+ );
+ final row = at < 0 ? null : rows[at];
+ final key = event.logicalKey;
+ final meta = HardwareKeyboard.instance.isMetaPressed;
+ switch (key) {
+ case LogicalKeyboardKey.arrowDown || LogicalKeyboardKey.arrowUp:
+ final step = key == LogicalKeyboardKey.arrowDown ? 1 : -1;
+ _move((at + step).clamp(0, rows.length - 1));
+ case LogicalKeyboardKey.arrowRight
+ when row != null && row.entry.isDirectory:
+ row.expanded
+ ? _move(at + 1)
+ : tree.controller.tree.expand(row.entry.path);
+ case LogicalKeyboardKey.arrowLeft when row != null:
+ if (row.expanded) {
+ tree.controller.tree.toggle(row.entry.path);
+ } else {
+ final parent = p.dirname(row.entry.path);
+ _move(rows.indexWhere((r) => r.entry.path == parent));
+ }
+ case LogicalKeyboardKey.space when row != null:
+ tree.open(row.entry);
+ case LogicalKeyboardKey.enter || LogicalKeyboardKey.f2 when row != null:
+ tree.startRename(row.entry);
+ case LogicalKeyboardKey.delete when row != null:
+ trashEntry(context, tree.controller, row.entry);
+ case LogicalKeyboardKey.backspace when row != null && meta:
+ trashEntry(context, tree.controller, row.entry);
+ case LogicalKeyboardKey.escape:
+ tree.moveCursor(null);
+ default:
+ return KeyEventResult.ignored;
+ }
+ return KeyEventResult.handled;
+ }
+
+ /// Puts the cursor on row [index] and scrolls it into view.
+ void _move(int index) {
+ if (index < 0 || index >= rows.length) return;
+ tree.moveCursor(rows[index].entry.path);
+ final scroll = tree.scroll;
+ if (!scroll.hasClients) return;
+ final top = index * FinderRow.height;
+ final view = scroll.position.viewportDimension;
+ if (top < scroll.offset) {
+ scroll.jumpTo(top);
+ } else if (top + FinderRow.height > scroll.offset + view) {
+ scroll.jumpTo(top + FinderRow.height - view);
+ }
+ }
+}
diff --git a/desktop/lib/finder/widgets/finder_tree_menu.dart b/desktop/lib/finder/widgets/finder_tree_menu.dart
new file mode 100644
index 000000000..10e5f8239
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_tree_menu.dart
@@ -0,0 +1,88 @@
+import 'dart:io' show Platform;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:path/path.dart' as p;
+
+import '../../shared/theme/app_icons.dart';
+import '../../shared/widgets/app_menu.dart';
+import '../finder_controller.dart';
+import '../finder_file_actions.dart';
+import '../finder_models.dart';
+import 'finder_dialogs.dart';
+
+/// What a right click on the tree offers — Orca's explorer menu, less what a
+/// tile has no use for: new items, rename, the two paths, reveal, open with
+/// the system's app, and the Trash.
+List<Widget> finderTreeMenu({
+ required BuildContext context,
+ required FinderController controller,
+ required FinderEntry? entry,
+ required void Function(String folder, {required bool asFolder}) onCreate,
+ required void Function(FinderEntry entry) onRename,
+}) {
+ final target = entry?.path ?? controller.root;
+ final folder = entry == null || entry.isDirectory
+ ? target
+ : p.dirname(target);
+ void copy(String text) => Clipboard.setData(ClipboardData(text: text));
+ return [
+ AppMenuItem(
+ icon: AppIcons.filePlus,
+ label: 'New File…',
+ onPressed: () => onCreate(folder, asFolder: false),
+ ),
+ AppMenuItem(
+ icon: AppIcons.folderPlus,
+ label: 'New Folder…',
+ onPressed: () => onCreate(folder, asFolder: true),
+ ),
+ const AppMenuDivider(),
+ AppMenuItem(
+ icon: AppIcons.copy,
+ label: 'Copy Path',
+ onPressed: () => copy(target),
+ ),
+ AppMenuItem(
+ icon: AppIcons.copy,
+ label: 'Copy Relative Path',
+ onPressed: () => copy(p.relative(target, from: controller.root)),
+ ),
+ AppMenuItem(
+ icon: AppIcons.folderOpen,
+ label: Platform.isMacOS ? 'Reveal in Finder' : 'Show in File Manager',
+ onPressed: () => controller.files.reveal(target),
+ ),
+ if (entry != null && !entry.isDirectory)
+ AppMenuItem(
+ icon: AppIcons.externalLink,
+ label: 'Open with Default App',
+ onPressed: () => controller.files.open(target),
+ ),
+ if (entry != null) ...[
+ const AppMenuDivider(),
+ AppMenuItem(
+ icon: AppIcons.pencil,
+ label: 'Rename',
+ onPressed: () => onRename(entry),
+ ),
+ AppMenuItem(
+ icon: AppIcons.trash2,
+ label: 'Move to Trash',
+ danger: true,
+ onPressed: () => trashEntry(context, controller, entry),
+ ),
+ ],
+ ];
+}
+
+/// Asks, then moves [entry] to the Trash.
+Future<void> trashEntry(
+ BuildContext context,
+ FinderController controller,
+ FinderEntry entry,
+) async {
+ if (!await confirmTrash(context, entry.name)) return;
+ final error = await controller.trash(entry.path);
+ if (error != null) controller.say(error);
+}
diff --git a/desktop/lib/finder/widgets/finder_tree_row_view.dart b/desktop/lib/finder/widgets/finder_tree_row_view.dart
new file mode 100644
index 000000000..2814802fd
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_tree_row_view.dart
@@ -0,0 +1,74 @@
+import 'package:flutter/material.dart';
+
+import '../../shared/theme/app_icons.dart';
+import '../../shared/theme/file_type_icon.dart';
+import '../../theme/app_theme.dart';
+import '../finder_git_state.dart';
+import '../finder_load.dart';
+import '../finder_tree.dart';
+import 'finder_context_menu.dart';
+import 'finder_row.dart';
+import 'git_change_mark.dart';
+
+/// One entry of the tree: its name in Git's colour (a folder in its most
+/// pressing child's), faint when Git ignores it, its status letter, and the
+/// right-click menu.
+class FinderTreeRowView extends StatelessWidget {
+ const FinderTreeRowView({
+ super.key,
+ required this.row,
+ required this.git,
+ required this.selected,
+ required this.menu,
+ required this.onTap,
+ });
+
+ final FinderTreeRow row;
+ final FinderGitState git;
+ final bool selected;
+ final List<Widget> Function() menu;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final entry = row.entry;
+ final status = entry.isDirectory
+ ? git.folderStatus(entry.path)
+ : git.fileStatus(entry.path);
+ return FinderContextMenu(
+ items: menu,
+ child: FinderRow(
+ indent: row.depth,
+ icon: entry.isDirectory
+ ? row.expanded
+ ? AppIcons.folderOpen
+ : AppIcons.folder
+ : fileTypeIcon(entry.name),
+ label: entry.name,
+ labelColor: status == null ? null : gitChangeStyle(status).color,
+ faint: git.isIgnored(entry.path),
+ selected: selected,
+ leading: entry.isDirectory
+ ? Icon(
+ row.expanded ? AppIcons.chevronDown : AppIcons.chevronRight,
+ size: 12,
+ color: AppColors.muted,
+ )
+ : null,
+ trailing: switch (row.listing) {
+ FinderFailed(:final message) => Tooltip(
+ message: message,
+ child: Icon(
+ AppIcons.circleAlert,
+ size: 12,
+ color: AppColors.danger,
+ ),
+ ),
+ _ when !entry.isDirectory && status != null => GitChangeMark(status),
+ _ => null,
+ },
+ onTap: onTap,
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/finder/widgets/finder_tree_view.dart b/desktop/lib/finder/widgets/finder_tree_view.dart
new file mode 100644
index 000000000..bd971d408
--- /dev/null
+++ b/desktop/lib/finder/widgets/finder_tree_view.dart
@@ -0,0 +1,177 @@
+import 'package:flutter/material.dart';
+
+import '../../shared/theme/app_icons.dart';
+import '../../shared/widgets/empty_state.dart';
+import '../../shared/widgets/skeleton.dart';
+import '../finder_controller.dart';
+import '../finder_file_actions.dart';
+import '../finder_load.dart';
+import '../finder_models.dart';
+import '../finder_tree.dart';
+import 'finder_click.dart';
+import 'finder_context_menu.dart';
+import 'finder_name_field.dart';
+import 'finder_row.dart';
+import 'finder_tree_keys.dart';
+import 'finder_tree_menu.dart';
+import 'finder_tree_row_view.dart';
+
+/// A name being typed in place: a new file or folder in [folder], or a
+/// rename of [entry].
+class FinderTreeEdit {
+ const FinderTreeEdit.create(String this.folder, {required this.asFolder})
+ : entry = null;
+ const FinderTreeEdit.rename(FinderEntry this.entry)
+ : folder = null,
+ asFolder = false;
+
+ final String? folder;
+ final FinderEntry? entry;
+ final bool asFolder;
+}
+
+/// The Files half of the sidebar: the tile's folder as Orca's explorer
+/// shows it — Git's colours on names, ignored entries faint, a right-click
+/// menu, names typed in place, and the keyboard (`FinderTreeKeys`).
+class FinderTreeView extends StatefulWidget {
+ const FinderTreeView({super.key, required this.controller});
+
+ final FinderController controller;
+
+ @override
+ State<FinderTreeView> createState() => FinderTreeViewState();
+}
+
+class FinderTreeViewState extends State<FinderTreeView> {
+ final _clicks = FinderClickTracker();
+ final focus = FocusNode(debugLabel: 'Finder tree');
+ final scroll = ScrollController();
+
+ /// The row the keyboard is on; the front tab's file when nobody moved it.
+ String? get cursor => _cursor;
+ String? _cursor;
+ FinderTreeEdit? _edit;
+
+ FinderController get controller => widget.controller;
+
+ @override
+ void dispose() {
+ focus.dispose();
+ scroll.dispose();
+ super.dispose();
+ }
+
+ Future<void> startCreate(String folder, {required bool asFolder}) async {
+ if (folder != controller.root) await controller.tree.expand(folder);
+ setState(() => _edit = FinderTreeEdit.create(folder, asFolder: asFolder));
+ }
+
+ void moveCursor(String? path) => setState(() => _cursor = path);
+
+ void startRename(FinderEntry entry) =>
+ setState(() => _edit = FinderTreeEdit.rename(entry));
+
+ /// A click or Space: a folder opens or closes; a file opens in a preview
+ /// tab, kept by a second click.
+ void open(FinderEntry entry) {
+ focus.requestFocus();
+ moveCursor(entry.path);
+ if (entry.isDirectory) {
+ controller.tree.toggle(entry.path);
+ return;
+ }
+ final keep = _clicks.isDouble(entry.path);
+ controller.openFile(entry.path, preview: !keep);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final tree = controller.tree;
+ return switch (tree.listingOf(tree.root)) {
+ FinderLoading() => const SkeletonList(
+ rows: 8,
+ padding: EdgeInsets.all(10),
+ ),
+ FinderFailed(:final message) => EmptyState(
+ icon: AppIcons.circleAlert,
+ title: 'Can’t read this folder',
+ message: message,
+ compact: true,
+ ),
+ FinderLoaded() => _list(tree.rows),
+ };
+ }
+
+ Widget _list(List<FinderTreeRow> rows) {
+ final items = _withEdit(rows);
+ return FinderTreeKeys(
+ tree: this,
+ rows: rows,
+ child: FinderContextMenu(
+ items: () => _menu(null),
+ child: ListView.builder(
+ key: const ValueKey('finder-tree'),
+ controller: scroll,
+ padding: const EdgeInsets.symmetric(vertical: 4),
+ itemExtent: FinderRow.height,
+ itemCount: items.length,
+ itemBuilder: (context, index) => switch (items[index]) {
+ final FinderTreeRow row => _row(row),
+ (final int depth, final FinderTreeEdit edit) => _field(depth, edit),
+ _ => const SizedBox.shrink(),
+ },
+ ),
+ ),
+ );
+ }
+
+ /// The rows, with the name field where the edit puts it: in place of the
+ /// renamed row, or first inside the folder something is made in.
+ List<Object> _withEdit(List<FinderTreeRow> rows) {
+ final edit = _edit;
+ if (edit == null) return rows;
+ if (edit.entry case final entry?) {
+ return [
+ for (final row in rows)
+ row.entry.path == entry.path ? (row.depth - 1, edit) : row,
+ ];
+ }
+ if (edit.folder == controller.root) return [(-1, edit), ...rows];
+ final at = rows.indexWhere((row) => row.entry.path == edit.folder);
+ if (at < 0) return rows;
+ return [...rows.take(at + 1), (rows[at].depth, edit), ...rows.skip(at + 1)];
+ }
+
+ Widget _field(int depth, FinderTreeEdit edit) => FinderNameField(
+ depth: depth,
+ icon: edit.asFolder || (edit.entry?.isDirectory ?? false)
+ ? AppIcons.folder
+ : AppIcons.file,
+ initial: edit.entry?.name ?? '',
+ onCancel: () => setState(() => _edit = null),
+ onSubmit: (name) async {
+ final error = edit.entry == null
+ ? await controller.create(edit.folder!, name, asFolder: edit.asFolder)
+ : await controller.rename(edit.entry!.path, name);
+ if (error == null && mounted) setState(() => _edit = null);
+ return error;
+ },
+ );
+
+ Widget _row(FinderTreeRow row) => FinderTreeRowView(
+ key: ValueKey('finder-tree-${row.entry.path}'),
+ row: row,
+ git: controller.git,
+ selected: row.entry.path == (cursor ?? controller.activePath),
+ menu: () => _menu(row.entry),
+ onTap: () => open(row.entry),
+ );
+
+ List<Widget> _menu(FinderEntry? entry) => finderTreeMenu(
+ context: context,
+ controller: controller,
+ entry: entry,
+ onCreate: startCreate,
+ onRename: startRename,
+ );
+}
diff --git a/desktop/lib/finder/widgets/git_change_mark.dart b/desktop/lib/finder/widgets/git_change_mark.dart
new file mode 100644
index 000000000..21f26b163
--- /dev/null
+++ b/desktop/lib/finder/widgets/git_change_mark.dart
@@ -0,0 +1,87 @@
+import 'package:flutter/material.dart';
+
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../theme/app_theme.dart';
+import '../finder_models.dart';
+
+/// The letter Git's own short status uses for [kind], and the ink for it —
+/// one table, so the tree and the Changes list never disagree.
+({String letter, String label, Color color}) gitChangeStyle(
+ GitChangeKind kind,
+) => switch (kind) {
+ GitChangeKind.modified => (
+ letter: 'M',
+ label: 'Modified',
+ color: AppColors.warning,
+ ),
+ GitChangeKind.added => (
+ letter: 'A',
+ label: 'Added',
+ color: AppColors.success,
+ ),
+ GitChangeKind.deleted => (
+ letter: 'D',
+ label: 'Deleted',
+ color: AppColors.danger,
+ ),
+ GitChangeKind.renamed => (
+ letter: 'R',
+ label: 'Renamed',
+ color: AppColors.accent,
+ ),
+ GitChangeKind.copied => (
+ letter: 'C',
+ label: 'Copied',
+ color: AppColors.accent,
+ ),
+ GitChangeKind.typeChanged => (
+ letter: 'T',
+ label: 'Type changed',
+ color: AppColors.warning,
+ ),
+ GitChangeKind.untracked => (
+ letter: 'U',
+ label: 'Untracked',
+ color: AppColors.success,
+ ),
+ GitChangeKind.conflicted => (
+ letter: '!',
+ label: 'Conflicted',
+ color: AppColors.danger,
+ ),
+};
+
+/// A change's letter, at the end of a row.
+class GitChangeMark extends StatelessWidget {
+ const GitChangeMark(this.kind, {super.key});
+
+ final GitChangeKind kind;
+
+ @override
+ Widget build(BuildContext context) {
+ final style = gitChangeStyle(kind);
+ return Tooltip(
+ message: style.label,
+ waitDuration: const Duration(milliseconds: 500),
+ child: Text(
+ style.letter,
+ style: grid.AppType.monoLabel(
+ color: style.color,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ );
+ }
+}
+
+/// The dot a closed folder wears when something inside it changed.
+class GitChangeDot extends StatelessWidget {
+ const GitChangeDot({super.key});
+
+ @override
+ Widget build(BuildContext context) => Container(
+ width: 6,
+ height: 6,
+ decoration: BoxDecoration(color: AppColors.warning, shape: BoxShape.circle),
+ );
+}
diff --git a/desktop/lib/shared/theme/app_icons.dart b/desktop/lib/shared/theme/app_icons.dart
index a43b666bd..eaf0d4465 100644
--- a/desktop/lib/shared/theme/app_icons.dart
+++ b/desktop/lib/shared/theme/app_icons.dart
@@ -31,6 +31,7 @@ abstract final class AppIcons {
static const arrowRightLeft = LucideIcons.arrowRightLeft400;
static const arrowRightToLine = LucideIcons.arrowRightToLine400;
static const arrowUp = LucideIcons.arrowUp400;
+ static const arrowDown = LucideIcons.arrowDown400;
static const arrowUpRight = LucideIcons.arrowUpRight400;
static const bell = LucideIcons.bell400;
static const bellRing = LucideIcons.bellRing400;
@@ -66,6 +67,8 @@ abstract final class AppIcons {
static const code = LucideIcons.code400;
static const coins = LucideIcons.coins400;
static const columns2 = LucideIcons.columns2400;
+ static const caseSensitive = LucideIcons.caseSensitive400;
+ static const chevronsDownUp = LucideIcons.chevronsDownUp400;
static const command = LucideIcons.command400;
static const copy = LucideIcons.copy400;
static const copyPlus = LucideIcons.copyPlus400;
@@ -84,6 +87,7 @@ abstract final class AppIcons {
static const fileArchive = LucideIcons.fileArchive400;
static const fileBraces = LucideIcons.fileBraces400;
static const fileCode = LucideIcons.fileCode400;
+ static const filePlus = LucideIcons.filePlus400;
static const fileDiff = LucideIcons.fileDiff400;
static const fileDown = LucideIcons.fileDown400;
static const fileImage = LucideIcons.fileImage400;
@@ -137,6 +141,8 @@ abstract final class AppIcons {
static const palette = LucideIcons.palette400;
static const paperclip = LucideIcons.paperclip400;
static const panelLeft = LucideIcons.panelLeft400;
+ static const panelLeftClose = LucideIcons.panelLeftClose400;
+ static const panelLeftOpen = LucideIcons.panelLeftOpen400;
static const panelsTopLeft = LucideIcons.panelsTopLeft400;
static const pause = LucideIcons.pause400;
static const pencil = LucideIcons.pencil400;
@@ -148,6 +154,8 @@ abstract final class AppIcons {
static const radioTower = LucideIcons.radioTower400;
static const refreshCw = LucideIcons.refreshCw400;
static const rocket = LucideIcons.rocket400;
+ static const regex = LucideIcons.regex400;
+ static const replace = LucideIcons.replace400;
static const rotateCcw = LucideIcons.rotateCcw400;
static const rotateCw = LucideIcons.rotateCw400;
static const rows2 = LucideIcons.rows2400;
@@ -178,11 +186,13 @@ abstract final class AppIcons {
static const trash2 = LucideIcons.trash2400;
static const triangleAlert = LucideIcons.triangleAlert400;
static const type = LucideIcons.type400;
+ static const undo2 = LucideIcons.undo2400;
static const unlink = LucideIcons.unlink400;
static const unplug = LucideIcons.unplug400;
static const usb = LucideIcons.usb400;
static const user = LucideIcons.user400;
static const users = LucideIcons.users400;
static const waypoints = LucideIcons.waypoints400;
+ static const wrapText = LucideIcons.wrapText400;
static const zap = LucideIcons.zap400;
}
diff --git a/desktop/lib/shared/theme/app_pane_icon.dart b/desktop/lib/shared/theme/app_pane_icon.dart
index 2329c5979..3af88c298 100644
--- a/desktop/lib/shared/theme/app_pane_icon.dart
+++ b/desktop/lib/shared/theme/app_pane_icon.dart
@@ -4,7 +4,16 @@ import 'package:flutter/material.dart';
import 'app_icons.dart';
-enum AppPaneSymbol { splitDown, splitRight, zoom, restore, reload, close }
+enum AppPaneSymbol {
+ splitDown,
+ splitRight,
+ zoom,
+ restore,
+ reload,
+ close,
+ collapseLeft,
+ expandLeft,
+}
/// Optical variants for the small, repeated pane controls. The split and zoom
/// outlines keep Lucide's 24-unit grid, two-unit stroke and round caps, with
@@ -21,6 +30,8 @@ class AppPaneIcon extends StatelessWidget {
final glyph = switch (symbol) {
AppPaneSymbol.close => AppIcons.close,
AppPaneSymbol.reload => AppIcons.refreshCw,
+ AppPaneSymbol.collapseLeft => AppIcons.panelLeftClose,
+ AppPaneSymbol.expandLeft => AppIcons.panelLeftOpen,
_ => null,
};
if (glyph != null) return Icon(glyph, color: color, size: size);
@@ -88,6 +99,8 @@ class _PaneIconPainter extends CustomPainter {
}
case AppPaneSymbol.close:
case AppPaneSymbol.reload:
+ case AppPaneSymbol.collapseLeft:
+ case AppPaneSymbol.expandLeft:
break; // These delegate to the catalogue's font glyphs above.
}
canvas.restore();
diff --git a/desktop/lib/shortcuts/app_keymap.dart b/desktop/lib/shortcuts/app_keymap.dart
index 98afe6353..893dafcbe 100644
--- a/desktop/lib/shortcuts/app_keymap.dart
+++ b/desktop/lib/shortcuts/app_keymap.dart
@@ -153,6 +153,7 @@ class KeymapRegion extends InheritedWidget {
required this.contextKind,
this.actions,
this.composing,
+ this.keeps,
this.terminalFocusNode,
required super.child,
});
@@ -160,6 +161,11 @@ class KeymapRegion extends InheritedWidget {
final Map<String, VoidCallback>? actions;
final bool Function()? composing;
+ /// Strokes the focused field takes for itself, ahead of any workspace
+ /// binding — a code editor's ⌘S, ⌘F and ⌘Z. Null keeps none, which is
+ /// every region but an editor.
+ final Set<KeyStroke>? keeps;
+
/// Only this renderer owns terminal input; pane chrome remains outside.
final FocusNode? terminalFocusNode;
static KeymapRegion? of(BuildContext context) =>
diff --git a/desktop/lib/shortcuts/keymap_host.dart b/desktop/lib/shortcuts/keymap_host.dart
index c36e34af2..08737c475 100644
--- a/desktop/lib/shortcuts/keymap_host.dart
+++ b/desktop/lib/shortcuts/keymap_host.dart
@@ -121,6 +121,12 @@ class _KeymapHostState extends State<KeymapHost> with WidgetsBindingObserver {
return KeyEventResult.ignored;
}
final region = KeymapRegion.of(context);
+ if (region?.keeps case final keeps?
+ when keeps.contains(keyStrokeForEvent(event))) {
+ _dispatch.cancel();
+ _notifyPending();
+ return KeyEventResult.ignored;
+ }
final localActions = region?.actions;
if (localActions == null && !widget.enabled()) {
_dispatch.cancel();
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 2bd1d0c7e..6e71fd4a8 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -36,6 +36,7 @@ import 'essential_harness_controller.dart';
import 'agent_handoff_file.dart';
import 'agent_switch_handoff.dart';
import '../agent_messages/agent_messages.dart';
+import '../finder/finder_roots.dart';
import '../agent_messages/shared_tab_errors.dart';
import '../agent_messages/shared_tab_placement.dart';
import '../agent_messages/shared_tabs.dart';
@@ -3283,41 +3284,73 @@ class AppNotifier extends ChangeNotifier {
final tab = swarms.where((s) => s.id == id).firstOrNull;
if (tab == null) return Future.value();
final captured = tab.panes.toList();
- return _requestViewClose(
- 'tab:$id',
- tab,
+ return _afterCloseGuards(
captured,
- () async {
- if (tab.panes.length != captured.length ||
- !captured.every(tab.panes.contains)) {
- return;
- }
- await closeSwarm(id);
- },
- tabName: tab.name,
- wholeTab: true,
+ () => _requestViewClose(
+ 'tab:$id',
+ tab,
+ captured,
+ () async {
+ if (tab.panes.length != captured.length ||
+ !captured.every(tab.panes.contains)) {
+ return;
+ }
+ await closeSwarm(id);
+ },
+ tabName: tab.name,
+ wholeTab: true,
+ ),
);
}
+ /// Runs [close] once every pane in [panes] with a close check has passed
+ /// it — a Finder tile asks about its unsaved tabs (`TerminalPane.beforeClose`),
+ /// one tile at a time. A tile kept open keeps the whole close from happening.
+ Future<void> _afterCloseGuards(
+ List<TerminalPane> panes,
+ Future<void> Function() close,
+ ) async {
+ for (final pane in panes) {
+ if (pane.beforeClose case final guard? when !await guard()) return;
+ }
+ await close();
+ }
+
Future<void> requestClosePane(int paneId) {
final tab = activeSwarm;
if (tab.isSuperTab && tab.superTabId != null) return Future.value();
final pane = tab.panes.where((p) => p.id == paneId).firstOrNull;
if (pane == null) return Future.value();
if (tab.isCompanions || tab.isDevices) return requestCloseSwarm(tab.id);
+ // A Finder and its chat are one group: closing the Finder closes the chat,
+ // which takes the Finder with it, exactly as the chat's own Close does.
+ if (pane.isFinder && pane.ownerAgentId != null) {
+ final chat = tab.panes
+ .where(
+ (p) =>
+ !p.isViewer &&
+ p.machineId == pane.machineId &&
+ p.agentId == pane.ownerAgentId,
+ )
+ .firstOrNull;
+ if (chat != null) return requestClosePane(chat.id);
+ }
final captured = tab.panes
.where(
(p) =>
identical(p, pane) ||
- (!pane.isWeb &&
- p.isWeb &&
- p.machineId == pane.machineId &&
- p.ownerAgentId == pane.agentId),
+ p.viewsAgent(pane.machineId, pane.agentId),
)
.toList();
- return _requestViewClose('pane:${tab.id}:$paneId', tab, captured, () async {
- if (tab.panes.contains(pane)) await closePane(paneId, swarmId: tab.id);
- });
+ return _afterCloseGuards(
+ captured,
+ () =>
+ _requestViewClose('pane:${tab.id}:$paneId', tab, captured, () async {
+ if (tab.panes.contains(pane)) {
+ await closePane(paneId, swarmId: tab.id);
+ }
+ }),
+ );
}
Future<void> _requestViewClose(
@@ -11995,8 +12028,7 @@ class AppNotifier extends ChangeNotifier {
for (final pane in allPanes.toList()) {
final owned =
pane.machineId == machineId &&
- (pane.agentId == agentId ||
- (pane.isWeb && pane.ownerAgentId == agentId));
+ (pane.agentId == agentId || pane.viewsAgent(machineId, agentId));
if (!owned) continue;
// The explicit Close owns these panes until its disk-safe acknowledgement,
// so it can preserve recently-closed layout and composer history normally.
@@ -12014,6 +12046,7 @@ class AppNotifier extends ChangeNotifier {
}
_closeTabsEmptiedByStop(affected);
_dismissedViewers.remove(_viewerKey(machineId, agentId));
+ finderRoots.forget(machineId, agentId);
_persistLayout();
_announceAppFocus();
try {
@@ -12056,7 +12089,7 @@ class AppNotifier extends ChangeNotifier {
final dismissed =
viewerState != null &&
_dismissedViewers[_viewerKey(machineId, agent.id)] == viewerState;
- var changed = false;
+ var changed = _syncFinderPane(machineId, agent.id);
// Tab by tab: wherever this agent's terminal is, its viewer is beside it,
// and nowhere else. A terminal opened in a second tab gets a second
// viewer; a tab whose terminal went loses its viewer.
@@ -12106,30 +12139,35 @@ class AppNotifier extends ChangeNotifier {
viewerError: agent.viewerError,
ownerAgentId: agent.id,
);
- swarm.panes.insert(insertion, pane);
+ _insertViewer(swarm, insertion, pane);
// Counts opening a pane with a URL or a known launch error, not rendering its private page.
productMeasurement.begin(ProductFlow.viewerOpen)(
agent.viewerError == null ? ProductOutcome.ok : ProductOutcome.failed,
);
- // The same bookkeeping a split does when it grows the grid by one:
- // pins past the insertion slide right, and the shape is re-derived.
- swarm.pinnedSlots.updateAll(
- (_, slot) => slot >= insertion ? slot + 1 : slot,
- );
- swarm.arranged = null;
- swarm.arrangedKey = null;
- // Alone with its terminal, the viewer takes 70% of the tab and the
- // assistant keeps 30%. Only when nobody has sized this pair
- // by hand: a manual layout is the user's.
- if (swarm.panes.length == 2 && swarm.paneSizes['2:manual'] == null) {
- swarm.savePaneSizes('2:manual', PaneArrangement.viewerBesideTerminal);
- }
changed = true;
}
if (changed) _persistLayout();
return changed;
}
+ /// Puts a viewer into [swarm] at [insertion], beside its terminal.
+ void _insertViewer(Swarm swarm, int insertion, TerminalPane viewer) {
+ swarm.panes.insert(insertion, viewer);
+ // The same bookkeeping a split does when it grows the grid by one:
+ // pins past the insertion slide right, and the shape is re-derived.
+ swarm.pinnedSlots.updateAll(
+ (_, slot) => slot >= insertion ? slot + 1 : slot,
+ );
+ swarm.arranged = null;
+ swarm.arrangedKey = null;
+ // Alone with its terminal, the viewer takes 70% of the tab and the
+ // assistant keeps 30%. Only when nobody has sized this pair
+ // by hand: a manual layout is the user's.
+ if (swarm.panes.length == 2 && swarm.paneSizes['2:manual'] == null) {
+ swarm.savePaneSizes('2:manual', PaneArrangement.viewerBesideTerminal);
+ }
+ }
+
/// Opening an essential (Harness Monitor, Memories) reveals its ordinary DSH pair: its viewer is
/// focused in the active tab, unzoomed. Zoom is an explicit pane action.
void showHarnessViewer(String machineId, String agentId) {
@@ -15568,6 +15606,7 @@ class AppNotifier extends ChangeNotifier {
for (final pane in viewers) {
if (allPanes.contains(pane)) pane.ownerAgentId = nextId;
}
+ finderRoots.move(machineId, source.id, nextId);
for (final swarm in swarms) {
if (swarm.titleMachineId == machineId &&
swarm.titleAgentId == source.id) {
@@ -16863,6 +16902,78 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
}
+ /// Which folder each chat's Finder shows, kept so a Finder comes back
+ /// beside its chat after a restart.
+ late final finderRoots = FinderRoots(() => localStore);
+
+ /// Opens a Finder tile on [root] LEFT of [agentId]'s terminal, where a
+ /// harness's viewer sits: New Harness's Finder is a folder with a chat
+ /// beside it, never a folder alone. It is that chat's viewer from then on
+ /// ([TerminalPane.viewsAgent]) — it moves and closes with the terminal, and
+ /// comes back with it ([finderRoots]). Returns why it could not open, or null.
+ String? openFinderBeside(String machineId, String agentId, String root) {
+ finderRoots.set(machineId, agentId, root);
+ final shown = swarms.any(
+ (swarm) => swarm.panes.any(
+ (pane) =>
+ !pane.isViewer &&
+ pane.machineId == machineId &&
+ pane.agentId == agentId,
+ ),
+ );
+ if (!shown) return 'The chat closed before its Finder could open.';
+ if (!_syncFinderPane(machineId, agentId)) {
+ return 'This tab is full, so the Finder could not open beside the chat.';
+ }
+ notifyListeners();
+ return null;
+ }
+
+ /// A tile's own pixel width ([TerminalPane.fixedWidth]), or null to give
+ /// it back its share of the tab.
+ void setPaneFixedWidth(int paneId, double? width) {
+ final pane = allPanes.where((p) => p.id == paneId).firstOrNull;
+ if (pane == null || pane.fixedWidth == width) return;
+ pane.fixedWidth = width;
+ notifyListeners();
+ }
+
+ /// Puts [agentId]'s Finder, if it has one, beside its terminal in every
+ /// tab that shows that terminal without it. Whether one went in.
+ bool _syncFinderPane(String machineId, String agentId) {
+ final root = finderRoots.rootOf(machineId, agentId);
+ if (root == null) return false;
+ var changed = false;
+ for (final swarm in swarms) {
+ final at = swarm.panes.indexWhere(
+ (pane) =>
+ !pane.isViewer &&
+ pane.machineId == machineId &&
+ pane.agentId == agentId,
+ );
+ if (at < 0 ||
+ swarm.panes.length >= maxPanes ||
+ swarm.panes.any(
+ (pane) => pane.isFinder && pane.viewsAgent(machineId, agentId),
+ )) {
+ continue;
+ }
+ _insertViewer(
+ swarm,
+ at,
+ TerminalPane(
+ id: _nextPaneId++,
+ machineId: machineId,
+ kind: PaneKind.finder,
+ finderRoot: root,
+ ownerAgentId: agentId,
+ ),
+ );
+ changed = true;
+ }
+ return changed;
+ }
+
Future<void> assignAgentToPane(
int? paneId,
String machineId,
@@ -17748,9 +17859,7 @@ class AppNotifier extends ChangeNotifier {
final viewers = <TerminalPane>[];
if (!pane.isWeb && pane.agentId != null) {
for (final viewer in source.panes.toList()) {
- if (viewer.isWeb &&
- viewer.machineId == pane.machineId &&
- viewer.ownerAgentId == pane.agentId) {
+ if (viewer.viewsAgent(pane.machineId, pane.agentId)) {
source.remove(viewer);
viewers.add(viewer);
}
@@ -17819,6 +17928,10 @@ class AppNotifier extends ChangeNotifier {
await closeSwarm(tab.id, persist: persist);
return;
}
+ // A Finder closed by hand stays closed: its chat no longer brings it back.
+ if (pane.isFinder && pane.ownerAgentId != null) {
+ finderRoots.forget(pane.machineId, pane.ownerAgentId!);
+ }
if (pane.isWeb) {
// A viewer closed by hand stays closed for THIS page: the agent's next
// frame carries the same URL and must not reopen it. A different URL —
@@ -17831,11 +17944,7 @@ class AppNotifier extends ChangeNotifier {
}
bool closesWithPane(TerminalPane candidate) =>
candidate == pane ||
- (!pane.isWeb &&
- pane.agentId != null &&
- candidate.isWeb &&
- candidate.machineId == pane.machineId &&
- candidate.ownerAgentId == pane.agentId);
+ candidate.viewsAgent(pane.machineId, pane.agentId);
if (tab.kind == 'harness' &&
tab.panes.every(closesWithPane) &&
!_activeAgentCreations.any((attempt) => attempt._targetId == tab.id)) {
@@ -17872,9 +17981,7 @@ class AppNotifier extends ChangeNotifier {
// viewer's own close above is different — it is a choice about the page.
if (!pane.isWeb && pane.agentId != null) {
for (final viewer in tab.panes.toList()) {
- if (viewer.isWeb &&
- viewer.machineId == pane.machineId &&
- viewer.ownerAgentId == pane.agentId) {
+ if (viewer.viewsAgent(pane.machineId, pane.agentId)) {
tab.remove(viewer);
}
}
@@ -18343,9 +18450,7 @@ class AppNotifier extends ChangeNotifier {
swarm.remove(pane);
released.add(pane);
for (final viewer in swarm.panes.toList()) {
- if (viewer.isWeb &&
- viewer.machineId == pane.machineId &&
- viewer.ownerAgentId == pane.agentId) {
+ if (viewer.viewsAgent(pane.machineId, pane.agentId)) {
swarm.remove(viewer);
}
}
@@ -18609,6 +18714,8 @@ class AppNotifier extends ChangeNotifier {
if (workspaceEnabled?.call() == false) return;
final store = _paneLayout;
if (store == null) return;
+ // Before any chat is restored: its Finder comes back with its agent.
+ await finderRoots.load();
final initialSwarm = activeSwarm;
final revision = _layoutRevision;
final authRevision = _authRevision;
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index c8a7bff1a..97a9d55ea 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -25,6 +25,7 @@ import '../core/permission_modes.dart';
import '../core/project_folder.dart';
import '../core/repository_clone.dart';
import '../core/test_run.dart';
+import '../finder/finder_availability.dart';
import '../widgets/engine_identity.dart';
import '../widgets/resting_model_words.dart';
import 'app_state.dart';
@@ -453,21 +454,27 @@ class NewHarnessController extends ChangeNotifier {
draft != null || engine != null || harnessId != null;
_rememberedAgent = !explicitSelection;
engine = draft?.engine ?? engine;
- _harnessId =
- draft?.harnessId ??
- harnessId ??
- (isHarnessId(engine)
- ? engine
- : explicitSelection
- ? null
- : app.agentPreference.harness);
- _engine = draft != null && !isHarnessId(draft.engine)
- ? draft.engine
+ // A Finder is chosen as a harness is: by itself, or with its chat's agent.
+ _finder =
+ isFinderEngine(draft?.harnessId ?? harnessId) || isFinderEngine(engine);
+ if (isFinderEngine(engine)) engine = null;
+ _harnessId = _finder
+ ? null
+ : draft?.harnessId ??
+ harnessId ??
+ (isHarnessId(engine)
+ ? engine
+ : explicitSelection
+ ? null
+ : app.agentPreference.harness);
+ _engine = draft != null && engine != null && !isHarnessId(engine)
+ ? engine
: harnessId != null && engine != null && !isHarnessId(engine)
? engine
: _initialEngine(isHarnessId(engine) ? null : engine);
+ if (_finder) _engine = _finderChat(_engine);
_restorePermissionMode();
- _model = isTerminal ? null : draft?.model;
+ _model = _noAgentSetup ? null : draft?.model;
_modelUsage = modelUsage;
_ownsModelUsage = modelUsage == null;
_modelUsage?.addListener(_refresh);
@@ -595,7 +602,10 @@ class NewHarnessController extends ChangeNotifier {
late String _engine;
String? _harnessId;
- String? get harnessId => _harnessId;
+
+ /// What the Harness row answers: a Store harness, the Finder, or null for
+ /// an agent on its own. Both of the first two run on [engine].
+ String? get harnessId => _finder ? kFinderEngine : _harnessId;
/// The harness this form is installing, or failed to install, on its way to
/// starting — so the form can show the machine's own narration of it.
@@ -617,7 +627,7 @@ class NewHarnessController extends ChangeNotifier {
return entry != null && !entry.isViewerPackage;
}
- String get harnessLabel => _harnessId == null ? 'Code' : labelOf(_harnessId!);
+ String get harnessLabel => harnessId == null ? 'Code' : labelOf(harnessId!);
bool advancedOpen = false;
bool _selectionTouched = false;
bool _rememberedAgent = false;
@@ -657,8 +667,9 @@ class NewHarnessController extends ChangeNotifier {
void _startAsGuest() {
_project = const NewHarnessProject.fresh();
// An agent a guest cannot start there (OpenCode, a Store harness) gives way to Claude Code.
- if (_harnessId != null || !compatibleEngines.contains(_engine)) {
+ if (_harnessId != null || _finder || !compatibleEngines.contains(_engine)) {
_harnessId = null;
+ _finder = false;
_engine = compatibleEngines.first;
_restorePermissionMode();
}
@@ -693,6 +704,10 @@ class NewHarnessController extends ChangeNotifier {
List<String> get compatibleEngines => asGuest
? const ['claude', 'codex']
+ // A Finder's chat runs beside it on this computer: an agent, never
+ // the cloud or a bare shell.
+ : _finder
+ ? [for (final engine in allEngines) engine.id]
: _harnessId == null
? [
for (final engine in allEngines) engine.id,
@@ -809,7 +824,7 @@ class NewHarnessController extends ChangeNotifier {
bool refreshingBranches = false;
String? branchRefreshError;
DateTime? _branchesCheckedAt;
- bool get isGitProject => _gitProject.isGit && !isTerminal && !isCloud;
+ bool get isGitProject => _gitProject.isGit && !_noGitSetup && !isCloud;
/// A worktree the person picked: the harness works in it, on its branch.
bool get inWorktree => _project.exact && _gitProject.mainFolder != null;
@@ -937,7 +952,9 @@ class NewHarnessController extends ChangeNotifier {
}
void retryGitProject() {
- if (locked || checkingGit || _project.folder == null || isTerminal) return;
+ if (locked || checkingGit || _project.folder == null || _noGitSetup) {
+ return;
+ }
error = null;
_gitFuture = _readGitProject(_gitKey!);
notifyListeners();
@@ -992,7 +1009,7 @@ class NewHarnessController extends ChangeNotifier {
}
void _syncGitProject() {
- final key = (_machineId, _project.folder, isTerminal);
+ final key = (_machineId, _project.folder, _noGitSetup);
if (_gitKey == key) return;
if (_gitKey != null) {
_worktree = null;
@@ -1102,7 +1119,7 @@ class NewHarnessController extends ChangeNotifier {
static String _modelId(GridModel model) =>
'model:${jsonEncode([model.grid, model.id])}';
bool _modelAvailable(GridModel model) =>
- !isTerminal &&
+ !_noAgentSetup &&
_modelCatalog?.supportsModelLaunch == true &&
_modelCatalog!.reachable &&
_modelCatalog!.canRunLocally(_engine) &&
@@ -1241,7 +1258,7 @@ class NewHarnessController extends ChangeNotifier {
NewHarnessDraft get draft => NewHarnessDraft(
machineId: _machineId,
engine: _engine,
- harnessId: _harnessId,
+ harnessId: harnessId,
model: _model,
advancedOpen: advancedOpen,
project: _project,
@@ -1276,7 +1293,7 @@ class NewHarnessController extends ChangeNotifier {
branchName: _branchName,
placeholder: placeholder,
)
- : _project.folder != null || isTerminal
+ : _project.folder != null || _noAgentSetup
? null
: _project.repository != null
? ProjectFolderRequest.remote(_project.repository!)
@@ -1372,7 +1389,7 @@ class NewHarnessController extends ChangeNotifier {
bool get takesTask => isCloud || takesFirstTask(_base);
bool get taskTooLong => task.trim().length > kFirstTaskMaxLength;
List<PermissionMode> get _modes =>
- isTerminal || isCloud ? const [] : permissionModesOf(_base);
+ _noAgentSetup || isCloud ? const [] : permissionModesOf(_base);
bool get hasModes => _modes.isNotEmpty;
String get mode =>
_modes.any((mode) => mode.id == _mode) ? _mode : kDefaultPermissionMode;
@@ -1438,7 +1455,7 @@ class NewHarnessController extends ChangeNotifier {
List<NewHarnessField> get fields => [
NewHarnessField.harness,
NewHarnessField.agent,
- if (!isTerminal && !asGuest) NewHarnessField.model,
+ if (!_noAgentSetup && !asGuest) NewHarnessField.model,
NewHarnessField.machine,
// A guest picks only among the folders the owner shares, when there are any.
if (!asGuest || (_guestFolders?.folders.isNotEmpty ?? false))
@@ -1487,6 +1504,17 @@ class NewHarnessController extends ChangeNotifier {
MachineState? get _machine => app.stateOf(_machineId);
bool get isTerminal => isTerminalEngine(_engine);
+ /// A Finder: the folder to browse, with a chat on [engine] beside it.
+ bool _finder = false;
+ bool get isFinder => _finder;
+
+ /// The plain shell: no model or permission mode to set up.
+ bool get _noAgentSetup => isTerminal;
+
+ /// No branch or worktree: the plain shell, and a Finder, whose chat works
+ /// in exactly the folder the Finder shows.
+ bool get _noGitSetup => isTerminal || isFinder;
+
/// A cloud agent (Fo, Devin Cloud, Cursor Cloud): it runs on its maker's
/// servers, so it takes no folder, model, approvals or branch here — a coding
/// one takes a GitHub repository, and Devin Cloud an ACU limit.
@@ -1575,7 +1603,7 @@ class NewHarnessController extends ChangeNotifier {
// binary) is as unavailable as a remembered one.
(_engineRemembered || !engineState!.installable))) {
return (
- field: _harnessId == null
+ field: harnessId == null
? NewHarnessField.harness
: NewHarnessField.agent,
message: '$agentLabel is unavailable. Choose an agent.',
@@ -1620,7 +1648,7 @@ class NewHarnessController extends ChangeNotifier {
String get agentLabel => labelOf(_engine);
String get launchAgentLabel =>
- _harnessId == null ? agentLabel : '$harnessLabel · $agentLabel';
+ harnessId == null ? agentLabel : '$harnessLabel · $agentLabel';
String get launchProjectLabel =>
'$machineLabel:${needsProject ? "Choose project" : projectLabel}';
String labelOf(String id) => currentHarnessName(
@@ -1944,7 +1972,7 @@ class NewHarnessController extends ChangeNotifier {
/// wears the ✓, as the current folder and branch do in an editor's pickers.
bool isCurrent(NewHarnessOption option) => switch (field) {
NewHarnessField.launch || NewHarnessField.task => false,
- NewHarnessField.harness => option.id == (_harnessId ?? _engine),
+ NewHarnessField.harness => option.id == (harnessId ?? _engine),
NewHarnessField.agent => option.id == _engine,
NewHarnessField.model =>
option.id == (_model == null ? defaultModelId : _modelId(_model!)),
@@ -2024,7 +2052,7 @@ class NewHarnessController extends ChangeNotifier {
if (_project.generated != null) _project = _generatedProject();
}
_restorePermissionMode();
- if (saved == null || saved.engine != _engine || isTerminal) return;
+ if (saved == null || saved.engine != _engine || _noAgentSetup) return;
if (!_modelTouched) {
_model = saved.model;
if (_model != null) unawaited(refreshModels());
@@ -2211,7 +2239,9 @@ class NewHarnessController extends ChangeNotifier {
void _apply(NewHarnessOption option) {
switch (field) {
case NewHarnessField.harness:
- if (isHarnessId(option.id) && option.id != codingId) {
+ if (isFinderEngine(option.id)) {
+ _selectFinder();
+ } else if (isHarnessId(option.id) && option.id != codingId) {
_selectHarness(option.id);
} else {
_selectHarness(null);
@@ -2271,7 +2301,7 @@ class NewHarnessController extends ChangeNotifier {
_engine = engine;
if (changed && _desktopChoices && !_modelTouched) _model = null;
if (changed) _restorePermissionMode();
- if (isTerminal) _model = null;
+ if (_noAgentSetup) _model = null;
if (changed &&
_harnessId == null &&
_project.generated != null &&
@@ -2290,6 +2320,7 @@ class NewHarnessController extends ChangeNotifier {
void _selectHarness(String? id) {
_selectionTouched = true;
_harnessId = id;
+ _finder = false;
_installing = null;
_selectEngine(
_desktopChoices
@@ -2302,6 +2333,24 @@ class NewHarnessController extends ChangeNotifier {
}
}
+ /// The Finder keeps the agent already chosen as its chat when it can run
+ /// one; otherwise the box's own first choice.
+ void _selectFinder() {
+ _selectionTouched = true;
+ _harnessId = null;
+ _installing = null;
+ _finder = true;
+ if (!compatibleEngines.contains(_engine)) {
+ _selectEngine(_finderChat(_initialEngine(null)));
+ }
+ }
+
+ /// [candidate] when a Finder's chat can run it — an agent, not the cloud or
+ /// a bare shell — else the agent signed in here, else the product default.
+ String _finderChat(String candidate) => compatibleEngines.contains(candidate)
+ ? candidate
+ : _accountAgent() ?? defaultHarnessEngine;
+
void _selectMachine(String id) {
_installing = null;
if (_machineId == id) return;
@@ -2337,7 +2386,7 @@ class NewHarnessController extends ChangeNotifier {
NewHarnessProject _generatedProject() => NewHarnessProject.generated(
ProjectFolderRequest.generated(
- label: _harnessId == null ? engineIdentity(_engine).label : harnessLabel,
+ label: harnessId == null ? engineIdentity(_engine).label : harnessLabel,
at: _now(),
// Only a task the agent will actually be sent names the project.
task: takesTask ? task : null,
@@ -3114,18 +3163,18 @@ class NewHarnessController extends ChangeNotifier {
'autonomous/strudel',
'autonomous/typst',
...harnesses,
+ kFinderEngine,
kTerminalEngine,
])
if (isHarnessId(id)
? _offered(id)
: engines.contains(id) ||
isCloudAgentId(id) ||
+ id == kFinderEngine ||
id == kTerminalEngine)
isHarnessId(id) ? operationId(id) : id,
})
- isHarnessId(id)
- ? row(id)
- : NewHarnessOption(id: id, title: labelOf(id), engine: id),
+ isHarnessId(id) ? row(id) : _engineOption(id),
]);
}
return _ranked([
@@ -3134,9 +3183,10 @@ class NewHarnessController extends ChangeNotifier {
_engine,
...app.agentPreference.recent.where((id) => !isHarnessId(id)),
for (final engine in allEngines) engine.id,
+ kFinderEngine,
kTerminalEngine,
})
- NewHarnessOption(id: id, title: labelOf(id), engine: id),
+ _engineOption(id),
for (final id in rest.where(installed)) row(id),
for (final id in rest.where((id) => !installed(id))) row(id),
]);
@@ -3147,12 +3197,25 @@ class NewHarnessController extends ChangeNotifier {
_engine,
...app.agentPreference.recent,
for (final identity in allEngines) identity.id,
+ kFinderEngine,
kTerminalEngine,
})
- if (!isHarnessId(id) && compatibleEngines.contains(id))
- NewHarnessOption(id: id, title: labelOf(id), engine: id, detail: ''),
+ if (!isHarnessId(id) && compatibleEngines.contains(id)) _engineOption(id),
]);
+ /// An agent's row. The Finder reads this computer's disk, so on any other
+ /// machine its row says so instead of opening.
+ NewHarnessOption _engineOption(String id) {
+ final finderElsewhere = isFinderEngine(id) && !canOpenFinderOn(_machine);
+ return NewHarnessOption(
+ id: id,
+ title: labelOf(id),
+ engine: id,
+ enabled: !finderElsewhere,
+ why: finderElsewhere ? kFinderElsewhere : null,
+ );
+ }
+
/// Whether [machine] can be given work now — the same test that enables
/// its row below.
bool _machineUsable(MachineState machine) =>
@@ -3838,6 +3901,7 @@ class NewHarnessController extends ChangeNotifier {
'will not be sent. Press again to make it anyway.',
);
}
+ if (isFinder && !canOpenFinderOn(_machine)) return _fail(kFinderElsewhere);
final machine = _machine;
if (machine == null) {
error = 'Choose a machine.';
@@ -3849,7 +3913,7 @@ class NewHarnessController extends ChangeNotifier {
var harness = asGuest ? null : _harnessId;
final model = asGuest ? null : _model;
final terminal = isTerminalEngine(choice);
- final base = choice;
+ final base = _base;
// The daemon's launch installs a missing engine inside its new terminal.
// A cached availability probe must not block that first launch.
final recheck = checking;
@@ -4018,8 +4082,16 @@ class NewHarnessController extends ChangeNotifier {
destination?.stageAttachments == null) {
_deliverFiles(attempt.agentId, files, launchMessage);
}
+ if (failure == null && isFinder && attempt.agentId != null) {
+ final root = attempt.preparedFolder ?? folder;
+ final problem = root == null
+ ? 'The chat has no folder for the Finder to show.'
+ : app.openFinderBeside(_machineId, attempt.agentId!, root);
+ if (problem != null) return _fail('Chat started. $problem');
+ }
// Creation can replace an embedded form before this future returns. Save
- // the confirmed choices even if that form has already been disposed.
+ // the confirmed choices even if that form has already been disposed. A
+ // Finder's chat is remembered as its agent; the Finder itself is not.
if (failure == null && attempt.agentId != null) {
unawaited(
app.agentPreference.remember(
@@ -4042,7 +4114,7 @@ class NewHarnessController extends ChangeNotifier {
// A picked worktree prepared in place is still the one picked.
exact: _project.exact && attempt.preparedFolder == _project.folder,
);
- _gitKey = (_machineId, _project.folder, isTerminal);
+ _gitKey = (_machineId, _project.folder, _noGitSetup);
_worktree = false;
_branchRef = null;
_gitProject = const GitProjectInfo();
diff --git a/desktop/lib/state/terminal_pane.dart b/desktop/lib/state/terminal_pane.dart
index b1082b713..367fd59fc 100644
--- a/desktop/lib/state/terminal_pane.dart
+++ b/desktop/lib/state/terminal_pane.dart
@@ -11,8 +11,11 @@ import '../core/models.dart' show SharedHarness;
/// is, and the tile follows) and never persisted: a restored layout re-opens
/// it from the agent's next frame, so a stale URL from a previous run can
/// never be loaded. [companion] and [devices] are built-in native DSH viewers,
-/// derived only after their account's experiment is enabled.
-enum PaneKind { terminal, web, companion, devices }
+/// derived only after their account's experiment is enabled. A [finder] tile
+/// is a folder on its machine, browsed in place (`lib/finder/`), opened beside
+/// the chat New Harness starts with it; like the other viewers it is never in
+/// the saved layout or the desk.
+enum PaneKind { terminal, web, companion, devices, finder }
/// One tile in the terminal grid.
///
@@ -32,24 +35,44 @@ class TerminalPane {
this.url,
this.viewerError,
this.ownerAgentId,
+ this.finderRoot,
}) : assert(
kind != PaneKind.web || (agentId == null && ownerAgentId != null),
'a web tile belongs to an agent through ownerAgentId, never agentId',
+ ),
+ assert(
+ (kind == PaneKind.finder) == (finderRoot != null) &&
+ (kind != PaneKind.finder || agentId == null),
+ 'a Finder tile has a folder and no agent; no other tile has a folder',
);
final PaneKind kind;
bool get isWeb => kind == PaneKind.web;
bool get isCompanion => kind == PaneKind.companion;
bool get isDevices => kind == PaneKind.devices;
- bool get isViewer => isWeb || isCompanion || isDevices;
+ bool get isFinder => kind == PaneKind.finder;
+ bool get isViewer => isWeb || isCompanion || isDevices || isFinder;
+
+ /// Whether this is [agentId]'s own viewer on [machineId] — its harness's
+ /// page, or the Finder opened with its chat — which lives beside that
+ /// agent's terminal, so it moves and closes with it.
+ bool viewsAgent(String machineId, String? agentId) =>
+ (isWeb || isFinder) &&
+ agentId != null &&
+ this.machineId == machineId &&
+ ownerAgentId == agentId;
+
+ /// [PaneKind.finder] only: the folder the tile browses, on [machineId].
+ final String? finderRoot;
/// [PaneKind.web] only: what the tile loads. Changes when the agent's frame
/// names a new viewer URL; the panel navigates rather than remounts.
String? url;
String? viewerError;
- /// The agent whose viewer this is. The native companion viewer can exist
- /// before its agent starts, then follows the selected individual.
+ /// The agent whose viewer this is: a web viewer's harness, a Finder's
+ /// chat. The native companion viewer can exist before its agent starts,
+ /// then follows the selected individual.
/// Kept OFF [agentId]
/// on purpose — everything that attaches a terminal, persists a layout or
/// remembers a closed agent keys on [agentId] being set, and none of that
@@ -87,6 +110,16 @@ class TerminalPane {
/// Browser viewer input, installed only while its renderer is mounted.
bool Function()? focusViewerInput;
+
+ /// A width in pixels this tile asks for instead of its share of the tab:
+ /// a Finder showing only its files, or folded to a rail. The grid gives it
+ /// to a full-height tile at the tab's left or right edge
+ /// (`pinFixedColumn`); never saved.
+ double? fixedWidth;
+
+ /// What closing this tile must ask first, installed only while its panel
+ /// is mounted: a Finder tile's unsaved tabs. False keeps the tile open.
+ Future<bool> Function()? beforeClose;
SharedHarness? sharedHarness;
String? sharedOwnerName;
diff --git a/desktop/lib/super_tabs/message_text.dart b/desktop/lib/super_tabs/message_text.dart
index ccaf2216c..2794655c7 100644
--- a/desktop/lib/super_tabs/message_text.dart
+++ b/desktop/lib/super_tabs/message_text.dart
@@ -5,6 +5,7 @@ import 'package:markdown/markdown.dart' as md;
import '../core/open_in_browser.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../widgets/desktop_chrome.dart';
+import '../widgets/markdown_style.dart';
/// Shared content is selectable, never executable. Markdown images are labels,
/// not automatic network requests or reads from a collaborator's local disk.
@@ -31,8 +32,6 @@ class SuperTabMessageText extends StatelessWidget {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
- final body = DesktopChrome.text();
- final heading = body.copyWith(fontWeight: FontWeight.w600);
return MarkdownBody(
data: text,
selectable: false,
@@ -40,51 +39,7 @@ class SuperTabMessageText extends StatelessWidget {
inlineSyntaxes: [_WebAutolink(), _WorkgroupReference(references)],
builders: {'pre': _WrappedCode()},
paddingBuilders: {'a': _CompactLinkLabel()},
- styleSheet: MarkdownStyleSheet.fromTheme(Theme.of(context)).copyWith(
- p: body,
- a: TextStyle(
- color: DesktopChrome.accent,
- decoration: TextDecoration.underline,
- ),
- h1: heading.copyWith(fontSize: 17),
- h2: heading.copyWith(fontSize: 16),
- h3: heading,
- h4: heading,
- h5: heading,
- h6: heading,
- strong: const TextStyle(fontWeight: FontWeight.w600),
- code: grid.AppType.mono(
- color: DesktopChrome.foreground,
- height: 1.5,
- ).copyWith(backgroundColor: DesktopChrome.field),
- blockSpacing: 8,
- listIndent: 20,
- listBullet: body,
- blockquote: body.copyWith(color: DesktopChrome.muted),
- blockquotePadding: const EdgeInsets.symmetric(
- horizontal: 12,
- vertical: 4,
- ),
- blockquoteDecoration: BoxDecoration(
- border: Border(left: BorderSide(color: DesktopChrome.rim, width: 2)),
- ),
- codeblockPadding: const EdgeInsets.all(12),
- codeblockDecoration: BoxDecoration(
- color: DesktopChrome.field,
- borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
- ),
- tableHead: heading,
- tableColumnWidth: const FlexColumnWidth(),
- tableBody: body,
- tableBorder: TableBorder.all(color: DesktopChrome.rim),
- tableCellsPadding: const EdgeInsets.symmetric(
- horizontal: 12,
- vertical: 8,
- ),
- horizontalRuleDecoration: BoxDecoration(
- border: Border(top: BorderSide(color: DesktopChrome.rim)),
- ),
- ),
+ styleSheet: desktopMarkdownStyleSheet(context),
onTapLink: (_, href, _) {
final number = href?.startsWith('workgroup:') == true
? int.tryParse(href!.substring(10))
diff --git a/desktop/lib/widgets/engine_identity.dart b/desktop/lib/widgets/engine_identity.dart
index 867fa4508..d3b056dcc 100644
--- a/desktop/lib/widgets/engine_identity.dart
+++ b/desktop/lib/widgets/engine_identity.dart
@@ -861,6 +861,23 @@ const EngineIdentity _terminal = EngineIdentity(
color: Color(0xffa8b0b8),
);
+/// A Finder tile's id in New Harness's agent list (`lib/finder/`): a folder
+/// browsed in place — its files, previews and Git changes — with no process
+/// behind it. Like [kTerminalEngine] it is not in [_engines]: nothing to
+/// probe, install or launch, and the daemon never hears this id.
+const String kFinderEngine = 'finder';
+
+const EngineIdentity _finder = EngineIdentity(
+ id: kFinderEngine,
+ label: 'Finder',
+ category: 'Files',
+ tagline: 'Browse files, previews and Git changes',
+ blurb:
+ 'A folder as a tree, with each file previewed beside it and the '
+ 'folder’s Git changes shown as diffs. Nothing runs, nothing to install.',
+ color: Color(0xff7fb4e8),
+);
+
/// The cloud agents (CLI lib/cloudAgents.ts): agents that run on their maker's
/// servers, reached through its API, with no terminal here. A SEPARATE map from
/// [_engines] for the reason [_harnesses] is one: never probed as an engine
@@ -926,6 +943,12 @@ EngineIdentity get terminalIdentity => _terminal;
/// Whether [engine] is the shell rather than an agent.
bool isTerminalEngine(String? engine) => engine == kTerminalEngine;
+/// The Finder's face, for New Harness's agent list.
+EngineIdentity get finderIdentity => _finder;
+
+/// Whether [engine] is the Finder: a folder to browse, not a process to start.
+bool isFinderEngine(String? engine) => engine == kFinderEngine;
+
/// All known engines, in declaration order — for the New Agent engine picker.
List<EngineIdentity> get allEngines => _engines.values.toList(growable: false);
@@ -944,7 +967,11 @@ EngineIdentity engineIdentity(String? engine, {String? displayName}) {
_cloudAgents[id] ??
_harnesses[canonicalHarnessId(id)] ??
_linkedHarnesses[id] ??
- (id == kTerminalEngine ? _terminal : null);
+ switch (id) {
+ kTerminalEngine => _terminal,
+ kFinderEngine => _finder,
+ _ => null,
+ };
if (known != null) return known;
final raw = displayName?.trim().isNotEmpty == true
? displayName!.trim()
@@ -1032,6 +1059,13 @@ class EngineMark extends StatelessWidget {
// takes the secondary ink (5.0:1).
color: dark ? identity.color : AppColors.mutedStrong,
)
+ : identity.id == kFinderEngine
+ ? Icon(
+ AppIcons.folderOpen,
+ key: const ValueKey('engine-icon-finder'),
+ size: size,
+ color: dark ? identity.color : AppColors.accent,
+ )
: _InitialMark(
key: ValueKey('engine-fallback-${identity.id}'),
identity: identity,
diff --git a/desktop/lib/widgets/markdown_style.dart b/desktop/lib/widgets/markdown_style.dart
new file mode 100644
index 000000000..629f07b56
--- /dev/null
+++ b/desktop/lib/widgets/markdown_style.dart
@@ -0,0 +1,51 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import 'desktop_chrome.dart';
+
+/// The app's Markdown, in its own type and colours — a shared message and a
+/// previewed README read alike.
+MarkdownStyleSheet desktopMarkdownStyleSheet(BuildContext context) {
+ final body = DesktopChrome.text();
+ final heading = body.copyWith(fontWeight: FontWeight.w600);
+ return MarkdownStyleSheet.fromTheme(Theme.of(context)).copyWith(
+ p: body,
+ a: TextStyle(
+ color: DesktopChrome.accent,
+ decoration: TextDecoration.underline,
+ ),
+ h1: heading.copyWith(fontSize: 17),
+ h2: heading.copyWith(fontSize: 16),
+ h3: heading,
+ h4: heading,
+ h5: heading,
+ h6: heading,
+ strong: const TextStyle(fontWeight: FontWeight.w600),
+ code: grid.AppType.mono(
+ color: DesktopChrome.foreground,
+ height: 1.5,
+ ).copyWith(backgroundColor: DesktopChrome.field),
+ blockSpacing: 8,
+ listIndent: 20,
+ listBullet: body,
+ blockquote: body.copyWith(color: DesktopChrome.muted),
+ blockquotePadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
+ blockquoteDecoration: BoxDecoration(
+ border: Border(left: BorderSide(color: DesktopChrome.rim, width: 2)),
+ ),
+ codeblockPadding: const EdgeInsets.all(12),
+ codeblockDecoration: BoxDecoration(
+ color: DesktopChrome.field,
+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
+ ),
+ tableHead: heading,
+ tableColumnWidth: const FlexColumnWidth(),
+ tableBody: body,
+ tableBorder: TableBorder.all(color: DesktopChrome.rim),
+ tableCellsPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
+ horizontalRuleDecoration: BoxDecoration(
+ border: Border(top: BorderSide(color: DesktopChrome.rim)),
+ ),
+ );
+}
diff --git a/desktop/lib/widgets/pane_fixed_width.dart b/desktop/lib/widgets/pane_fixed_width.dart
new file mode 100644
index 000000000..a5d3651fe
--- /dev/null
+++ b/desktop/lib/widgets/pane_fixed_width.dart
@@ -0,0 +1,53 @@
+import 'dart:ui';
+
+/// Gives a full-height tile at the canvas's left or right edge the width its
+/// pane asks for ([widths], `TerminalPane.fixedWidth`) and slides every other
+/// tile's vertical cuts, in proportion, into the room left. Only one such
+/// tile is honoured; the others keep at least [minOther] between them.
+/// Null when no tile asks, or none that asks can be given it.
+List<Rect>? pinFixedColumn(
+ List<Rect> tiles,
+ List<double?> widths,
+ Size canvas, {
+ required double gap,
+ required double minOther,
+}) {
+ const slack = .5;
+ for (var i = 0; i < tiles.length && tiles.length > 1; i++) {
+ final want = widths[i];
+ final tile = tiles[i];
+ if (want == null ||
+ tile.top > slack ||
+ (tile.bottom - canvas.height).abs() > slack) {
+ continue;
+ }
+ final atLeft = tile.left < slack;
+ if (!atLeft && (tile.right - canvas.width).abs() > slack) continue;
+ final room = canvas.width - gap - minOther;
+ if (room <= 0) return null;
+ final width = want.clamp(0.0, room);
+ // The others' span, before and after: everything beside the pinned tile.
+ final (from, to) = atLeft
+ ? ((tile.right + gap, canvas.width), (width + gap, canvas.width))
+ : ((0.0, tile.left - gap), (0.0, canvas.width - width - gap));
+ double move(double x) =>
+ to.$1 + (x - from.$1) * (to.$2 - to.$1) / (from.$2 - from.$1);
+ return [
+ for (var j = 0; j < tiles.length; j++)
+ j == i
+ ? Rect.fromLTWH(
+ atLeft ? 0 : canvas.width - width,
+ tile.top,
+ width,
+ tile.height,
+ )
+ : Rect.fromLTRB(
+ move(tiles[j].left),
+ tiles[j].top,
+ move(tiles[j].right),
+ tiles[j].bottom,
+ ),
+ ];
+ }
+ return null;
+}
diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dart
index 097d52792..d973bb10e 100644
--- a/desktop/lib/widgets/pane_grid.dart
+++ b/desktop/lib/widgets/pane_grid.dart
@@ -1,3 +1,4 @@
+import '../finder/widgets/finder_pane_panel.dart';
import '../super_tabs/pane.dart';
import '../super_tabs/saved_session.dart';
import '../sharing/shared_harness_panel.dart';
@@ -26,6 +27,7 @@ import '../state/app_state.dart';
import '../state/harness_sessions.dart' show heldLaunchDetail;
import '../state/pane_preset.dart';
import '../state/pane_arrangement.dart';
+import 'pane_fixed_width.dart';
import '../state/terminal_pane.dart';
import '../terminal/terminal_binary.dart';
import '../terminal/terminal_text.dart';
@@ -574,9 +576,18 @@ class _SwarmCanvasState extends State<_SwarmCanvas> {
);
}
if (layout.columns != null) app.gridColumns = layout.columns;
+ // A tile that asks for its own width (a Finder showing only its
+ // files) takes it; its divider is not dragged while it does.
+ final pinned = pinFixedColumn(
+ layout.rectangles,
+ [for (final pane in visible) pane.fixedWidth],
+ Size(layout.width, layout.height),
+ gap: kPaneGap,
+ minOther: _MinTile.of().width,
+ );
+ final tiles = pinned ?? layout.rectangles;
final rectangles = {
- for (var i = 0; i < visible.length; i++)
- visible[i].id: layout.rectangles[i],
+ for (var i = 0; i < visible.length; i++) visible[i].id: tiles[i],
};
final retainedIds = app.allPanes.map((pane) => pane.id).toSet();
_inputLayers.removeWhere((id, _) => !retainedIds.contains(id));
@@ -653,6 +664,7 @@ class _SwarmCanvasState extends State<_SwarmCanvas> {
),
),
if (_shownZoom == null &&
+ pinned == null &&
layout.arrangement?.dividers.isNotEmpty == true)
Positioned.fill(child: _resizeLayer(layout)),
],
@@ -1593,6 +1605,17 @@ class _PaneContent extends StatelessWidget {
);
}
+ // A folder browsed in place: no agent and no terminal behind it.
+ if (pane.finderRoot case final root? when pane.isFinder) {
+ return FinderPanePanel(
+ key: ValueKey('finder-pane-${pane.id}'),
+ root: root,
+ onGuardClose: (guard) => pane.beforeClose = guard,
+ onFixedWidth: (width) => notifier.setPaneFixedWidth(pane.id, width),
+ compactHeader: swarmMode,
+ );
+ }
+
// A harness's viewer: the one tile that is not a terminal and not about a
// machine. Decided first, before anything below reads `agentId` — which a
// viewer keeps null on purpose (see TerminalPane.ownerAgentId).
diff --git a/desktop/pubspec.lock b/desktop/pubspec.lock
index 9ddc06b0c..fa2e1bf7b 100644
--- a/desktop/pubspec.lock
+++ b/desktop/pubspec.lock
@@ -42,7 +42,7 @@ packages:
source: hosted
version: "1.4.1"
clock:
- dependency: transitive
+ dependency: "direct main"
description:
name: clock
sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e
@@ -319,6 +319,22 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
+ isolate_contactor:
+ dependency: transitive
+ description:
+ name: isolate_contactor
+ sha256: "6ba8434ceb58238a1389d6365111a3efe7baa1c68a66f4db6d63d351cf6c3a0f"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.1.0"
+ isolate_manager:
+ dependency: transitive
+ description:
+ name: isolate_manager
+ sha256: "22ed0c25f80ec3b5f21e3a55d060f4650afff33f27c2dff34c0f9409d5759ae5"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.1.5+1"
json_annotation:
dependency: transitive
description:
@@ -503,6 +519,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.2.2"
+ re_editor:
+ dependency: "direct main"
+ description:
+ name: re_editor
+ sha256: "66671c4774a6b4c5254c9a53ab35a083e7e7da9ae371c519bcf491c70a2a4e56"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.10.0"
+ re_highlight:
+ dependency: "direct main"
+ description:
+ name: re_highlight
+ sha256: "6c4ac3f76f939fb7ca9df013df98526634e17d8f7460e028bd23a035870024f2"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.0.3"
riverpod:
dependency: transitive
description:
diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yaml
index 9262fb199..864d34325 100644
--- a/desktop/pubspec.yaml
+++ b/desktop/pubspec.yaml
@@ -36,6 +36,8 @@ dependencies:
sdk: flutter
# Natural ordering for numbered agents, projects, and completion candidates.
collection: ^1.19.1
+ # A wall clock tests can move: the Finder tells a double click by time.
+ clock: ^1.1.2
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
@@ -95,6 +97,10 @@ dependencies:
# Named directly for the WebKit creation params (muted autoplay in viewer panes).
webview_flutter_platform_interface: ^2.15.1
webview_flutter_wkwebview: ^3.26.1
+ # The Finder tile's code editor and its highlighter (lib/finder/): pure
+ # Dart, no native plugin, so the macOS SPM package list is unchanged.
+ re_editor: ^0.10.0
+ re_highlight: ^0.0.3
dev_dependencies:
flutter_test:
diff --git a/desktop/test/finder/fakes.dart b/desktop/test/finder/fakes.dart
new file mode 100644
index 000000000..d057e1c47
--- /dev/null
+++ b/desktop/test/finder/fakes.dart
@@ -0,0 +1,151 @@
+import 'dart:async';
+
+import 'package:harness/finder/finder_files.dart';
+import 'package:harness/finder/finder_git.dart';
+import 'package:harness/finder/finder_models.dart';
+import 'package:path/path.dart' as p;
+
+/// An in-memory folder: `/r` holds `lib/main.dart` and `README.md`.
+class FakeFinderFiles implements FinderFiles {
+ final texts = <String, String>{
+ '/r/README.md': '# Readme\n\nHello',
+ '/r/lib/main.dart': 'void main() {}\n',
+ };
+ final folders = <String>{'/r', '/r/lib'};
+ final stamps = <String, DiskStamp>{};
+ final listed = <String>[];
+ final writes = <String, String>{};
+ final trashed = <String>[];
+ final opened = <String>[];
+ final disk = StreamController<Set<String>>.broadcast();
+ int _clock = 0;
+
+ DiskStamp _touch(String path) =>
+ stamps[path] = DiskStamp(DateTime(2026, 10, 20, 0, 0, ++_clock), 1);
+
+ /// Something other than the tile changed [path].
+ void changeOnDisk(String path, String text) {
+ texts[path] = text;
+ _touch(path);
+ }
+
+ @override
+ Future<List<FinderEntry>> list(String directory) async {
+ listed.add(directory);
+ return [
+ for (final folder in folders.where(
+ (f) => p.dirname(f) == directory && f != directory,
+ ))
+ FinderEntry(name: p.basename(folder), path: folder, isDirectory: true),
+ for (final file in texts.keys.where((f) => p.dirname(f) == directory))
+ FinderEntry(name: p.basename(file), path: file, isDirectory: false),
+ ];
+ }
+
+ @override
+ Future<FinderContent> read(String path) async {
+ final text = texts[path];
+ if (text == null) {
+ throw const FinderException('This file no longer exists.');
+ }
+ return FinderText(text, stamps[path] ?? _touch(path));
+ }
+
+ @override
+ Future<DiskStamp?> stamp(String path) async =>
+ texts.containsKey(path) ? stamps[path] ?? _touch(path) : null;
+
+ @override
+ Future<DiskStamp> write(String path, String text) async {
+ texts[path] = text;
+ writes[path] = text;
+ return _touch(path);
+ }
+
+ @override
+ Future<void> createFile(String path) async {
+ if (texts.containsKey(path)) {
+ throw const FinderException('An item with this name already exists.');
+ }
+ texts[path] = '';
+ }
+
+ @override
+ Future<void> createFolder(String path) async => folders.add(path);
+
+ @override
+ Future<void> rename(String from, String to) async {
+ texts[to] = texts.remove(from)!;
+ }
+
+ @override
+ Future<void> trash(String path) async {
+ trashed.add(path);
+ texts.remove(path);
+ }
+
+ @override
+ Future<bool> open(String path) async {
+ opened.add(path);
+ return true;
+ }
+
+ @override
+ Future<bool> reveal(String path) async => true;
+
+ @override
+ Stream<Set<String>> watch(String root) => disk.stream;
+}
+
+/// `/r` as a repository on `main`, one commit ahead, with `lib/main.dart`
+/// edited.
+class FakeFinderGit implements FinderGit {
+ static const edited = GitChange(
+ path: 'lib/main.dart',
+ kind: GitChangeKind.modified,
+ area: GitArea.unstaged,
+ added: 1,
+ removed: 1,
+ );
+
+ List<GitChange> current = [edited];
+ final staged = <String>[];
+ final unstaged = <String>[];
+ final discarded = <String>[];
+ Set<String> ignoredPaths = {};
+ bool fail = false;
+ int reads = 0;
+
+ @override
+ Future<GitChanges?> changes(String folder) async {
+ reads++;
+ if (fail) throw const FinderException('Git is gone.');
+ return GitChanges(root: '/r', branch: 'main', ahead: 1, changes: current);
+ }
+
+ @override
+ Future<Set<String>> ignored(
+ GitChanges repository,
+ List<FinderEntry> entries,
+ ) async => entries.map((e) => e.path).where(ignoredPaths.contains).toSet();
+
+ @override
+ Future<List<DiffLine>> diff(GitChanges repository, GitChange change) async =>
+ const [
+ DiffLine(DiffLineKind.hunk, '@@ -1 +1 @@'),
+ DiffLine(DiffLineKind.removed, 'old line', oldLine: 1),
+ DiffLine(DiffLineKind.added, 'new line', newLine: 1),
+ ];
+
+ @override
+ Future<void> stage(GitChanges repository, List<GitChange> changes) async =>
+ staged.addAll(changes.map((c) => c.path));
+
+ @override
+ Future<void> unstage(GitChanges repository, List<GitChange> changes) async =>
+ unstaged.addAll(changes.map((c) => c.path));
+
+ @override
+ Future<void> discard(GitChanges repository, List<GitChange> changes) async =>
+ discarded.addAll(changes.map((c) => c.path));
+}
diff --git a/desktop/test/finder/finder_controller_test.dart b/desktop/test/finder/finder_controller_test.dart
new file mode 100644
index 000000000..091d2ba06
--- /dev/null
+++ b/desktop/test/finder/finder_controller_test.dart
@@ -0,0 +1,177 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/finder/finder_controller.dart';
+import 'package:harness/finder/finder_document.dart';
+import 'package:harness/finder/finder_file_actions.dart';
+import 'package:harness/finder/finder_load.dart';
+import 'package:harness/finder/finder_models.dart';
+
+import 'fakes.dart';
+
+void main() {
+ late FakeFinderFiles files;
+ late FakeFinderGit git;
+ late FinderController controller;
+
+ setUp(() async {
+ files = FakeFinderFiles();
+ git = FakeFinderGit();
+ controller = FinderController(root: '/r', files: files, git: git);
+ addTearDown(controller.dispose);
+ await controller.start();
+ });
+
+ FinderDocument documentOf(String path) =>
+ controller.tabs.byId('file:$path')!.document!;
+
+ test('reads the tree and the repository, and marks what changed', () {
+ expect(controller.tree.rows.map((r) => r.entry.name), ['lib', 'README.md']);
+ expect(
+ controller.git.fileStatus('/r/lib/main.dart'),
+ GitChangeKind.modified,
+ );
+ expect(controller.git.folderStatus('/r/lib'), GitChangeKind.modified);
+ expect(controller.git.repository?.branch, 'main');
+ });
+
+ test(
+ 'a preview tab gives way to the next preview; a kept one stays',
+ () async {
+ controller.openFile('/r/README.md');
+ controller.openFile('/r/lib/main.dart');
+ expect(controller.tabs.tabs.map((t) => t.path), ['/r/lib/main.dart']);
+
+ controller.openFile('/r/lib/main.dart', preview: false);
+ controller.openFile('/r/README.md');
+ expect(controller.tabs.tabs.map((t) => (t.path, t.preview)), [
+ ('/r/lib/main.dart', false),
+ ('/r/README.md', true),
+ ]);
+ expect(controller.tabs.activeId, 'file:/r/README.md');
+ },
+ );
+
+ test(
+ 'editing keeps a preview tab, marks it dirty, and saving writes it',
+ () async {
+ controller.openFile('/r/lib/main.dart');
+ await pumpEventQueue();
+ final document = documentOf('/r/lib/main.dart');
+ document.editor!.text = 'void main() => print(1);\n';
+ expect(document.dirty, isTrue);
+ expect(controller.tabs.active!.preview, isFalse);
+
+ expect(await controller.saveActive(), isTrue);
+ expect(files.writes['/r/lib/main.dart'], 'void main() => print(1);\n');
+ expect(document.dirty, isFalse);
+ },
+ );
+
+ test('undoing back to the saved text leaves the tab clean', () async {
+ controller.openFile('/r/lib/main.dart');
+ await pumpEventQueue();
+ final document = documentOf('/r/lib/main.dart');
+ document.editor!.text = 'changed';
+ document.editor!.text = 'void main() {}\n';
+ await Future<void>.delayed(const Duration(milliseconds: 300));
+ expect(document.dirty, isFalse);
+ });
+
+ test('a clean tab follows the disk; a dirty one asks', () async {
+ controller.openFile('/r/README.md', preview: false);
+ controller.openFile('/r/lib/main.dart', preview: false);
+ await pumpEventQueue();
+
+ files.changeOnDisk('/r/README.md', '# New');
+ controller.onDiskChanged({'/r/README.md'});
+ await pumpEventQueue();
+ expect(documentOf('/r/README.md').editor!.text, '# New');
+
+ final edited = documentOf('/r/lib/main.dart');
+ edited.editor!.text = 'mine';
+ files.changeOnDisk('/r/lib/main.dart', 'theirs');
+ controller.onDiskChanged({'/r/lib/main.dart'});
+ await pumpEventQueue();
+ expect(edited.disk, FinderDiskChange.changed);
+ expect(edited.editor!.text, 'mine');
+
+ await edited.reloadFromDisk();
+ expect(edited.editor!.text, 'theirs');
+ expect(edited.dirty, isFalse);
+ expect(edited.disk, FinderDiskChange.none);
+ });
+
+ test('its own save is not mistaken for a change on disk', () async {
+ controller.openFile('/r/lib/main.dart');
+ await pumpEventQueue();
+ final document = documentOf('/r/lib/main.dart');
+ document.editor!.text = 'saved';
+ await document.save();
+ document.editor!.text = 'typing on';
+ controller.onDiskChanged({'/r/lib/main.dart'});
+ await pumpEventQueue();
+ expect(document.disk, FinderDiskChange.none);
+ });
+
+ test('a change opens its diff, and Stage reads Git again', () async {
+ controller.openChange(FakeFinderGit.edited);
+ await pumpEventQueue();
+ final diff = controller.tabs.active!.diff!;
+ expect(diff.diff, isA<FinderLoaded<List<DiffLine>>>());
+
+ final reads = git.reads;
+ expect(await controller.stage([FakeFinderGit.edited]), isNull);
+ expect(git.staged, ['lib/main.dart']);
+ expect(git.reads, greaterThan(reads));
+ });
+
+ test('discard restores tracked files and trashes untracked ones', () async {
+ const fresh = GitChange(
+ path: 'notes.txt',
+ kind: GitChangeKind.untracked,
+ area: GitArea.untracked,
+ );
+ expect(await controller.discard([FakeFinderGit.edited, fresh]), isNull);
+ expect(git.discarded, ['lib/main.dart']);
+ expect(files.trashed, ['/r/notes.txt']);
+ });
+
+ test(
+ 'new files open kept; names are checked; renames close old tabs',
+ () async {
+ expect(
+ await controller.create('/r/lib', 'a.dart', asFolder: false),
+ isNull,
+ );
+ expect(controller.tabs.active!.path, '/r/lib/a.dart');
+ expect(controller.tabs.active!.preview, isFalse);
+ expect(await controller.create('/r', 'x/y', asFolder: false), isNotNull);
+ expect(await controller.create('/r', ' ', asFolder: false), isNotNull);
+
+ expect(await controller.rename('/r/lib/a.dart', 'b.dart'), isNull);
+ expect(controller.tabs.byId('file:/r/lib/a.dart'), isNull);
+ expect(files.texts.containsKey('/r/lib/b.dart'), isTrue);
+ },
+ );
+
+ test('a rename waits while the file has unsaved edits', () async {
+ controller.openFile('/r/README.md');
+ await pumpEventQueue();
+ documentOf('/r/README.md').editor!.text = 'draft';
+ expect(await controller.rename('/r/README.md', 'R.md'), isNotNull);
+ expect(files.texts.containsKey('/r/README.md'), isTrue);
+ });
+
+ test('a failed Git read is said, and clears the marks', () async {
+ git.fail = true;
+ await controller.git.refresh();
+ expect(controller.git.status, isA<FinderFailed<GitChanges?>>());
+ expect(controller.git.fileStatus('/r/lib/main.dart'), isNull);
+ });
+
+ test('ignored entries are marked once Git answers', () async {
+ git.ignoredPaths = {'/r/README.md'};
+ await controller.refresh();
+ expect(controller.git.isIgnored('/r/README.md'), isTrue);
+ expect(controller.git.isIgnored('/r/lib'), isFalse);
+ });
+}
diff --git a/desktop/test/finder/finder_diff_rows_test.dart b/desktop/test/finder/finder_diff_rows_test.dart
new file mode 100644
index 000000000..db10b30af
--- /dev/null
+++ b/desktop/test/finder/finder_diff_rows_test.dart
@@ -0,0 +1,48 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/finder/finder_diff_rows.dart';
+import 'package:harness/finder/finder_models.dart';
+
+/// A 20-line file whose 10th line changed, as a whole-file diff reads.
+List<DiffLine> _diff() => [
+ const DiffLine(DiffLineKind.meta, 'diff --git a/f b/f'),
+ const DiffLine(DiffLineKind.hunk, '@@ -1,20 +1,20 @@'),
+ for (var i = 1; i < 10; i++)
+ DiffLine(DiffLineKind.context, 'line $i', oldLine: i, newLine: i),
+ const DiffLine(DiffLineKind.removed, 'old 10', oldLine: 10),
+ const DiffLine(DiffLineKind.added, 'new 10', newLine: 10),
+ const DiffLine(DiffLineKind.added, 'new 11', newLine: 11),
+ for (var i = 11; i <= 20; i++)
+ DiffLine(DiffLineKind.context, 'line $i', oldLine: i, newLine: i + 1),
+];
+
+void main() {
+ test('inline rows drop headers and fold unchanged runs to 3 lines', () {
+ final rows = inlineDiffRows(_diff(), const {});
+ expect(rows.first, isA<DiffFoldRow>());
+ expect((rows.first as DiffFoldRow).count, 6);
+ expect(rows.whereType<DiffFoldRow>().map((f) => f.count), [6, 7]);
+ // 3 context, the change (3 lines), 3 context, around the two folds.
+ expect(rows, hasLength(2 + 3 + 3 + 3));
+ expect(diffChangeStarts(rows), [4]);
+ });
+
+ test('a fold opens by its key', () {
+ final folded = inlineDiffRows(_diff(), const {});
+ final key = (folded.first as DiffFoldRow).key;
+ final opened = inlineDiffRows(_diff(), {key});
+ expect(opened.first, isA<DiffSingleRow>());
+ expect(opened.whereType<DiffFoldRow>(), hasLength(1));
+ });
+
+ test('side by side pairs a removal with the addition that replaced it', () {
+ final rows = sideBySideDiffRows(_diff(), const {});
+ final pairs = rows.whereType<DiffPairRow>().where(
+ (r) => r.left?.kind != DiffLineKind.context,
+ );
+ expect(pairs.map((r) => (r.left?.text, r.right?.text)), [
+ ('old 10', 'new 10'),
+ (null, 'new 11'),
+ ]);
+ expect(diffChangeStarts(rows), hasLength(1));
+ });
+}
diff --git a/desktop/test/finder/finder_file_kind_test.dart b/desktop/test/finder/finder_file_kind_test.dart
new file mode 100644
index 000000000..979bf64a0
--- /dev/null
+++ b/desktop/test/finder/finder_file_kind_test.dart
@@ -0,0 +1,28 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/finder/finder_file_kind.dart';
+
+void main() {
+ test('tells a kind by its extension or a known name', () {
+ expect(finderFileKind('/r/README.md'), FinderFileKind.markdown);
+ expect(finderFileKind('/r/logo.svg'), FinderFileKind.svg);
+ expect(finderFileKind('/r/shot.PNG'), FinderFileKind.image);
+ expect(finderFileKind('/r/lib/main.dart'), FinderFileKind.text);
+ expect(finderFileKind('/r/.gitignore'), FinderFileKind.text);
+ expect(finderFileKind('/r/Makefile'), FinderFileKind.text);
+ expect(finderFileKind('/r/report.pdf'), FinderFileKind.other);
+ expect(finderFileKind('/r/unknown.xyz'), FinderFileKind.other);
+ });
+
+ test('sniffs text apart from binary', () {
+ expect(looksLikeText(Uint8List(0)), isTrue);
+ expect(looksLikeText(utf8.encode('plain\ttext\r\nwith lines')), isTrue);
+ expect(
+ looksLikeText(Uint8List.fromList([0x89, 0x50, 0x4e, 0x47, 0, 1])),
+ isFalse,
+ );
+ expect(looksLikeText(Uint8List.fromList(List.filled(100, 0x01))), isFalse);
+ });
+}
diff --git a/desktop/test/finder/finder_language_test.dart b/desktop/test/finder/finder_language_test.dart
new file mode 100644
index 000000000..5995c7631
--- /dev/null
+++ b/desktop/test/finder/finder_language_test.dart
@@ -0,0 +1,27 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/finder/finder_language.dart';
+import 'package:harness/finder/finder_text_format.dart';
+import 'package:re_editor/re_editor.dart';
+
+void main() {
+ test('a file name wins over its extension, then the extension', () {
+ expect(finderLanguageOf('/r/Dockerfile'), 'dockerfile');
+ expect(finderLanguageOf('/r/Dockerfile.dev'), 'dockerfile');
+ expect(finderLanguageOf('/r/.env.local'), 'ini');
+ expect(finderLanguageOf('/r/Makefile'), 'makefile');
+ expect(finderLanguageOf('/r/app.TSX'), 'typescript');
+ expect(finderLanguageOf('/r/lib/main.dart'), 'dart');
+ expect(finderLanguageOf('/r/README.md'), 'markdown');
+ expect(finderLanguageOf('/r/notes'), isNull);
+ });
+
+ test('a file keeps its own line break and indent width', () {
+ final crlf = detectTextFormat('a\r\n b\r\n c\r\n');
+ expect(crlf.lineBreak, TextLineBreak.crlf);
+ expect(crlf.indentSize, 2);
+ final four = detectTextFormat('def f():\n if x:\n y\n z\n');
+ expect(four.lineBreak, TextLineBreak.lf);
+ expect(four.indentSize, 4);
+ expect(detectTextFormat('').indentSize, 2);
+ });
+}
diff --git a/desktop/test/finder/finder_new_harness_test.dart b/desktop/test/finder/finder_new_harness_test.dart
new file mode 100644
index 000000000..fee6e7cd0
--- /dev/null
+++ b/desktop/test/finder/finder_new_harness_test.dart
@@ -0,0 +1,199 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/finder/finder_availability.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/pane_arrangement.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import '../swarm_state_test.dart' show createApp;
+
+class _Connection extends WsConn {
+ _Connection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final creates = <Map<String, dynamic>>[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async => switch (type) {
+ 'git_project_info' => {'isGit': true},
+ 'dsh_list' => {'dsh': const []},
+ 'agent_create' => _create(payload),
+ _ => {},
+ };
+
+ Map<String, dynamic> _create(Map<String, dynamic> payload) {
+ creates.add(Map.of(payload));
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': {
+ 'id': 'chat',
+ 'name': 'Chat',
+ 'engine': payload['engine'],
+ 'terminalAvailable': true,
+ 'project': {'name': 'repo', 'cwd': payload['cwd']},
+ },
+ };
+ }
+}
+
+void main() {
+ late _Connection connection;
+ late AppNotifier app;
+
+ setUp(() {
+ connection = _Connection();
+ app = createApp(connectionForTest: (_) => connection, connected: true);
+ app.machineStates['m']!
+ ..agents = []
+ ..localOnly = true;
+ addTearDown(app.dispose);
+ });
+
+ NewHarnessController box({String? folder = '/work/repo', String? engine}) {
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ harnessId: 'finder',
+ engine: engine,
+ folder: folder,
+ );
+ addTearDown(box.dispose);
+ return box;
+ }
+
+ test('Finder starts a chat in the folder and opens left of it', () async {
+ final finder = box();
+ await pumpEventQueue();
+ expect(finder.isFinder, isTrue);
+ expect(finder.harnessId, 'finder');
+ expect(finder.isGitProject, isFalse, reason: 'no worktree: same folder');
+ finder.task = 'Explain this repo';
+
+ expect(await finder.create(), NewHarnessOutcome.created);
+ final create = connection.creates.single;
+ expect(create['engine'], finder.engine);
+ expect(create['cwd'], '/work/repo');
+ expect(create['prompt'], 'Explain this repo');
+
+ final tab = app.activeSwarm;
+ expect(tab.panes, hasLength(2));
+ final [viewer, chat] = tab.panes;
+ expect(viewer.isFinder, isTrue);
+ expect(viewer.finderRoot, '/work/repo');
+ expect(viewer.viewsAgent('m', 'chat'), isTrue);
+ expect(chat.agentId, 'chat');
+ expect(tab.focusedPaneId, chat.id, reason: 'the person types in the chat');
+ expect(
+ tab.paneSizes['2:manual'],
+ same(PaneArrangement.viewerBesideTerminal),
+ );
+ expect(tab.toJson()['panes'], hasLength(1), reason: 'viewers are unsaved');
+ });
+
+ test('closing the Finder closes the group: its chat too', () async {
+ expect(await box().create(), NewHarnessOutcome.created);
+ final viewer = app.activeSwarm.panes.firstWhere((p) => p.isFinder);
+ await app.requestClosePane(viewer.id);
+ await pumpEventQueue();
+ expect(app.allPanes, isEmpty);
+ });
+
+ test('closing the chat closes its Finder', () async {
+ expect(await box().create(), NewHarnessOutcome.created);
+ final chat = app.activeSwarm.panes.firstWhere((p) => p.agentId == 'chat');
+ await app.closePane(chat.id);
+ expect(app.allPanes.where((p) => p.isFinder), isEmpty);
+ });
+
+ test('the chat is chosen like a harness\'s agent, with model and mode', () {
+ final finder = box(engine: 'codex');
+ expect(finder.engine, 'codex');
+ expect(finder.launchAgentLabel, 'Finder · Codex');
+ expect(finder.fields, contains(NewHarnessField.model));
+ expect(finder.hasModes, isTrue);
+
+ finder.focusField(NewHarnessField.agent);
+ final ids = [for (final option in finder.options) option.id];
+ expect(ids, containsAll(['claude', 'codex']));
+ expect(ids, isNot(anyOf(contains('finder'), contains('terminal'))));
+ finder.applyOption(finder.options.firstWhere((o) => o.id == 'claude'));
+ expect(finder.engine, 'claude');
+ expect(finder.isFinder, isTrue);
+ });
+
+ test('picking Finder in the Harness list keeps the agent as its chat', () {
+ final picker = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/repo',
+ );
+ addTearDown(picker.dispose);
+ picker.focusField(NewHarnessField.harness);
+ picker.applyOption(picker.options.firstWhere((o) => o.id == 'finder'));
+ expect(picker.isFinder, isTrue);
+ expect(picker.engine, 'codex');
+ expect(picker.draft.harnessId, 'finder');
+
+ picker.focusField(NewHarnessField.harness);
+ picker.applyOption(picker.options.firstWhere((o) => o.id == 'claude'));
+ expect(picker.isFinder, isFalse);
+ });
+
+ test('a shell cannot be a Finder\'s chat', () {
+ expect(box(engine: 'terminal').engine, isNot('terminal'));
+ });
+
+ test('a chat shown again brings its Finder back, until closed', () async {
+ expect(await box().create(), NewHarnessOutcome.created);
+ final tab = app.activeSwarm;
+ Future<void> synced() => app.handleEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {
+ 'agent': {
+ 'id': 'chat',
+ 'name': 'Chat',
+ 'engine': 'claude',
+ 'terminalAvailable': true,
+ },
+ },
+ });
+ // A restart restores the chat alone: viewers are never saved.
+ tab.remove(tab.panes.firstWhere((p) => p.isFinder));
+ await synced();
+ expect(tab.panes.first.finderRoot, '/work/repo');
+ expect(tab.panes, hasLength(2));
+
+ await app.closePane(tab.panes.first.id);
+ await synced();
+ expect(tab.panes.where((p) => p.isFinder), isEmpty);
+ });
+
+ test('Finder needs a folder', () async {
+ final finder = box(folder: null);
+ await pumpEventQueue();
+ expect(finder.requiredChoice?.field, NewHarnessField.projectMenu);
+ });
+
+ test('another machine offers Finder disabled and says why', () async {
+ app.machineStates['m']!.localOnly = false;
+ final finder = box();
+ await pumpEventQueue();
+ expect(await finder.create(), NewHarnessOutcome.failed);
+ expect(finder.error, kFinderElsewhere);
+ expect(connection.creates, isEmpty);
+ });
+}
diff --git a/desktop/test/finder/finder_pane_panel_test.dart b/desktop/test/finder/finder_pane_panel_test.dart
new file mode 100644
index 000000000..399a66812
--- /dev/null
+++ b/desktop/test/finder/finder_pane_panel_test.dart
@@ -0,0 +1,245 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/gestures.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/finder/widgets/finder_pane_panel.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+
+import 'fakes.dart';
+
+void main() {
+ late FakeFinderFiles files;
+ late FakeFinderGit git;
+ late List<double?> widths;
+
+ Future<void> pumpPanel(WidgetTester tester) async {
+ files = FakeFinderFiles();
+ git = FakeFinderGit();
+ widths = [];
+ tester.view.physicalSize = const Size(1200, 800);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Builder(
+ builder: (context) {
+ grid.AppTheme.brightness.value = Theme.of(context).brightness;
+ return grid.BrightnessScope(
+ child: Scaffold(
+ body: FinderPanePanel(
+ root: '/r',
+ files: files,
+ git: git,
+ onFixedWidth: widths.add,
+ ),
+ ),
+ );
+ },
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ /// Types [text] the way the system sends it to re_editor: as a delta on
+ /// the text input channel, to the client the editor registered.
+ Future<void> type(WidgetTester tester, String text) async {
+ final setClient = tester.testTextInput.log.lastWhere(
+ (call) => call.method == 'TextInput.setClient',
+ );
+ final id = (setClient.arguments as List)[0] as int;
+ await tester.binding.defaultBinaryMessenger.handlePlatformMessage(
+ SystemChannels.textInput.name,
+ SystemChannels.textInput.codec.encodeMethodCall(
+ MethodCall('TextInputClient.updateEditingStateWithDeltas', [
+ id,
+ {
+ 'deltas': [
+ {
+ 'oldText': '',
+ 'deltaText': text,
+ 'deltaStart': 0,
+ 'deltaEnd': 0,
+ 'selectionBase': text.length,
+ 'selectionExtent': text.length,
+ 'selectionAffinity': 'TextAffinity.downstream',
+ 'selectionIsDirectional': false,
+ 'composingBase': -1,
+ 'composingExtent': -1,
+ },
+ ],
+ },
+ ]),
+ ),
+ (_) {},
+ );
+ await tester.pump();
+ }
+
+ Finder tab(String path) => find.byKey(ValueKey('finder-tab-file:$path'));
+
+ testWidgets('a click previews a file; a second click keeps it', (
+ tester,
+ ) async {
+ await pumpPanel(tester);
+ expect(find.byKey(const ValueKey('finder-code-editor')), findsNothing);
+
+ await tester.tap(find.text('lib'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('main.dart'));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('finder-code-editor')), findsOneWidget);
+ final title = find.descendant(
+ of: tab('/r/lib/main.dart'),
+ matching: find.text('main.dart'),
+ );
+ expect(tester.widget<Text>(title).style?.fontStyle, FontStyle.italic);
+
+ // A double click: the second click within the window, on the clock the
+ // test moves, so a slow runner cannot split it into two single clicks.
+ await tester.tap(find.text('main.dart').first);
+ await tester.pump(const Duration(milliseconds: 50));
+ await tester.tap(find.text('main.dart').first);
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<Text>(title).style?.fontStyle,
+ isNot(FontStyle.italic),
+ );
+ });
+
+ testWidgets('typing marks the tab unsaved and ⌘S saves it', (tester) async {
+ await pumpPanel(tester);
+ await tester.tap(find.text('lib'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('main.dart'));
+ await tester.pumpAndSettle();
+
+ await tester.tap(find.byKey(const ValueKey('finder-code-editor')));
+ await tester.pump();
+ await type(tester, 'x');
+ expect(find.byKey(const ValueKey('finder-tab-dirty')), findsOneWidget);
+
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyS);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
+ await tester.pumpAndSettle();
+ expect(files.writes['/r/lib/main.dart'], contains('x'));
+ expect(find.byKey(const ValueKey('finder-tab-dirty')), findsNothing);
+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
+
+ testWidgets('closing an unsaved tab asks; Don’t Save drops the edits', (
+ tester,
+ ) async {
+ await pumpPanel(tester);
+ await tester.tap(find.text('README.md'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('finder-markdown-source')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('finder-code-editor')));
+ await tester.pump();
+ await type(tester, 'y');
+ expect(find.byKey(const ValueKey('finder-tab-dirty')), findsOneWidget);
+
+ await tester.tap(find.byKey(const ValueKey('finder-tab-close')));
+ await tester.pumpAndSettle();
+ expect(find.text('Unsaved changes'), findsOneWidget);
+ await tester.tap(find.byKey(const ValueKey('finder-dialog-Don’t Save')));
+ await tester.pumpAndSettle();
+ expect(tab('/r/README.md'), findsNothing);
+ expect(files.writes, isEmpty);
+ });
+
+ testWidgets('Markdown opens rendered and switches to its source', (
+ tester,
+ ) async {
+ await pumpPanel(tester);
+ await tester.tap(find.text('README.md'));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('finder-markdown')), findsOneWidget);
+ expect(find.text('Hello'), findsOneWidget);
+ await tester.tap(find.byKey(const ValueKey('finder-markdown-source')));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('finder-code-editor')), findsOneWidget);
+ });
+
+ testWidgets('a change opens its diff, inline or side by side', (
+ tester,
+ ) async {
+ await pumpPanel(tester);
+ await tester.tap(find.byKey(const ValueKey('finder-mode-changes')));
+ await tester.pumpAndSettle();
+ expect(find.text('Changes 1'), findsWidgets);
+ expect(find.text('+1 '), findsOneWidget);
+
+ await tester.tap(find.text('main.dart'));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('finder-diff')), findsOneWidget);
+ expect(find.textContaining('old line', findRichText: true), findsOneWidget);
+ expect(find.textContaining('new line', findRichText: true), findsOneWidget);
+
+ await tester.tap(find.byKey(const ValueKey('finder-diff-layout')));
+ await tester.pumpAndSettle();
+ expect(find.byType(VerticalDivider), findsWidgets);
+ });
+
+ testWidgets('a change stages from under the pointer', (tester) async {
+ await pumpPanel(tester);
+ await tester.tap(find.byKey(const ValueKey('finder-mode-changes')));
+ await tester.pumpAndSettle();
+ final gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await gesture.addPointer(
+ location: tester.getCenter(find.text('main.dart')),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('finder-change-stage')));
+ await tester.pumpAndSettle();
+ expect(git.staged, ['lib/main.dart']);
+ await gesture.removePointer();
+ });
+
+ testWidgets('New File names a file in place and opens it', (tester) async {
+ await pumpPanel(tester);
+ await tester.tap(find.byKey(const ValueKey('finder-new-file')));
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const ValueKey('finder-name-field')),
+ 'notes.md',
+ );
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(files.texts.containsKey('/r/notes.md'), isTrue);
+ expect(tab('/r/notes.md'), findsOneWidget);
+ });
+
+ testWidgets('with no file open it asks only for its file list\'s width', (
+ tester,
+ ) async {
+ await pumpPanel(tester);
+ expect(widths, [265]);
+
+ await tester.tap(find.text('README.md'));
+ await tester.pumpAndSettle();
+ expect(widths.last, isNull, reason: 'a file open takes its share');
+
+ await tester.tap(find.byKey(const ValueKey('finder-tab-close')));
+ await tester.pumpAndSettle();
+ expect(widths.last, 265);
+ });
+
+ testWidgets('Collapse folds it to a rail; the rail opens it again', (
+ tester,
+ ) async {
+ await pumpPanel(tester);
+ await tester.tap(find.byKey(const ValueKey('finder-collapse')));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('finder-rail')), findsOneWidget);
+ expect(widths.last, 44);
+
+ await tester.tap(find.byKey(const ValueKey('finder-rail-changes')));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('finder-rail')), findsNothing);
+ expect(find.byKey(const ValueKey('finder-changes')), findsOneWidget);
+ expect(widths.last, 265);
+ });
+}
diff --git a/desktop/test/finder/finder_roots_test.dart b/desktop/test/finder/finder_roots_test.dart
new file mode 100644
index 000000000..4cbe5535e
--- /dev/null
+++ b/desktop/test/finder/finder_roots_test.dart
@@ -0,0 +1,59 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/local_key_value_store.dart';
+import 'package:harness/finder/finder_roots.dart';
+
+class _MemoryStore 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);
+}
+
+void main() {
+ late _MemoryStore store;
+ FinderRoots roots() => FinderRoots(() => store);
+
+ setUp(() => store = _MemoryStore());
+
+ test('a folder set is read back by the next run', () async {
+ roots()
+ ..set('m', 'a', '/work/a')
+ ..set('m', 'b', '/work/b')
+ ..forget('m', 'b');
+ await pumpEventQueue();
+ final next = roots();
+ await next.load();
+ expect(next.rootOf('m', 'a'), '/work/a');
+ expect(next.rootOf('m', 'b'), isNull);
+ });
+
+ test('a switched chat keeps its Finder', () {
+ final kept = roots()
+ ..set('m', 'old', '/work')
+ ..move('m', 'old', 'new');
+ expect(kept.rootOf('m', 'old'), isNull);
+ expect(kept.rootOf('m', 'new'), '/work');
+ });
+
+ test('the oldest folders go past capacity', () {
+ final kept = roots();
+ for (var i = 0; i <= FinderRoots.capacity; i++) {
+ kept.set('m', '$i', '/work/$i');
+ }
+ expect(kept.rootOf('m', '0'), isNull);
+ expect(kept.rootOf('m', '${FinderRoots.capacity}'), isNotNull);
+ });
+
+ test('a damaged note restores nothing and breaks nothing', () async {
+ store.values[FinderRoots.storageKey] = '{not json';
+ final next = roots();
+ await next.load();
+ expect(next.rootOf('m', 'a'), isNull);
+ });
+}
diff --git a/desktop/test/finder/git_parsing_test.dart b/desktop/test/finder/git_parsing_test.dart
new file mode 100644
index 000000000..c12655227
--- /dev/null
+++ b/desktop/test/finder/git_parsing_test.dart
@@ -0,0 +1,135 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/finder/finder_models.dart';
+import 'package:harness/finder/git_numstat_parser.dart';
+import 'package:harness/finder/git_status_parser.dart';
+import 'package:harness/finder/unified_diff_parser.dart';
+
+void main() {
+ group('parseGitStatus', () {
+ test('reads the branch line with its distance from upstream', () {
+ final parsed = parseGitStatus(
+ '## main...origin/main [ahead 2, behind 1]\u0000',
+ );
+ expect(parsed.branch, 'main');
+ expect(parsed.ahead, 2);
+ expect(parsed.behind, 1);
+ expect(parsed.changes, isEmpty);
+ });
+
+ test('names the branch of a repository with no commits, and none when detached', () {
+ expect(
+ parseGitStatus('## No commits yet on trunk\u0000').branch,
+ 'trunk',
+ );
+ expect(parseGitStatus('## HEAD (no branch)\u0000').branch, isNull);
+ });
+
+ test('splits a file staged and edited again into two changes', () {
+ final parsed = parseGitStatus('## main\u0000MM lib/a.dart\u0000');
+ expect(parsed.changes, const [
+ GitChange(
+ path: 'lib/a.dart',
+ kind: GitChangeKind.modified,
+ area: GitArea.staged,
+ ),
+ GitChange(
+ path: 'lib/a.dart',
+ kind: GitChangeKind.modified,
+ area: GitArea.unstaged,
+ ),
+ ]);
+ });
+
+ test(
+ 'takes a rename source from the next record and keeps paths verbatim',
+ () {
+ final parsed = parseGitStatus(
+ 'R new name.md\u0000old name.md\u0000?? notes/ý tưởng.txt\u0000 D gone.txt\u0000',
+ );
+ expect(parsed.changes, const [
+ GitChange(
+ path: 'new name.md',
+ kind: GitChangeKind.renamed,
+ area: GitArea.staged,
+ originalPath: 'old name.md',
+ ),
+ GitChange(
+ path: 'notes/ý tưởng.txt',
+ kind: GitChangeKind.untracked,
+ area: GitArea.untracked,
+ ),
+ GitChange(
+ path: 'gone.txt',
+ kind: GitChangeKind.deleted,
+ area: GitArea.unstaged,
+ ),
+ ]);
+ },
+ );
+
+ test('reads a merge conflict as one conflicted change', () {
+ expect(parseGitStatus('UU lib/a.dart\u0000').changes, const [
+ GitChange(
+ path: 'lib/a.dart',
+ kind: GitChangeKind.conflicted,
+ area: GitArea.conflict,
+ ),
+ ]);
+ });
+ });
+
+ group('parseUnifiedDiff', () {
+ test('numbers each line on the side it exists on', () {
+ final lines = parseUnifiedDiff('''diff --git a/a.txt b/a.txt
+index 1..2 100644
+--- a/a.txt
++++ b/a.txt
+@@ -3,3 +3,3 @@ intro
+ keep
+-old
++new
+
+''');
+ expect(lines.map((l) => l.kind), [
+ DiffLineKind.meta,
+ DiffLineKind.meta,
+ DiffLineKind.meta,
+ DiffLineKind.meta,
+ DiffLineKind.hunk,
+ DiffLineKind.context,
+ DiffLineKind.removed,
+ DiffLineKind.added,
+ DiffLineKind.context,
+ ]);
+ expect((lines[5].oldLine, lines[5].newLine), (3, 3));
+ expect(
+ (lines[6].text, lines[6].oldLine, lines[6].newLine),
+ ('old', 4, null),
+ );
+ expect(
+ (lines[7].text, lines[7].oldLine, lines[7].newLine),
+ ('new', null, 4),
+ );
+ expect((lines[8].text, lines[8].oldLine, lines[8].newLine), ('', 5, 5));
+ });
+
+ test('never reads the +++ header as an added line', () {
+ final lines = parseUnifiedDiff(
+ '--- /dev/null\n+++ b/new.txt\n@@ -0,0 +1 @@\n+hello\n',
+ );
+ expect(
+ lines.where((l) => l.kind == DiffLineKind.added).single.text,
+ 'hello',
+ );
+ });
+ });
+
+ test('parseGitNumstat counts lines, files a rename under its new path', () {
+ expect(
+ parseGitNumstat(
+ '3\t1\tlib/a.dart\u0000-\t-\tlogo.png\u00002\t0\t\u0000old.md\u0000new.md\u0000',
+ ),
+ {'lib/a.dart': (3, 1), 'logo.png': (null, null), 'new.md': (2, 0)},
+ );
+ });
+}
diff --git a/desktop/test/finder/local_finder_test.dart b/desktop/test/finder/local_finder_test.dart
new file mode 100644
index 000000000..2aa91fbeb
--- /dev/null
+++ b/desktop/test/finder/local_finder_test.dart
@@ -0,0 +1,161 @@
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/finder/finder_models.dart';
+import 'package:harness/finder/local_finder_files.dart';
+import 'package:harness/finder/local_finder_git.dart';
+import 'package:path/path.dart' as p;
+
+/// Against a real folder and a real `git`, because what is under test is how
+/// this side reads and changes them.
+void main() {
+ late String root;
+ const files = LocalFinderFiles();
+ const git = LocalFinderGit();
+
+ Future<void> run(List<String> args) async {
+ final result = await Process.run('git', ['-C', root, ...args]);
+ expect(result.exitCode, 0, reason: '${result.stderr}');
+ }
+
+ File file(String name) => File(p.join(root, name));
+
+ setUp(() async {
+ final temp = await Directory.systemTemp.createTemp('finder-');
+ root = await temp.resolveSymbolicLinks();
+ });
+ tearDown(() => Directory(root).delete(recursive: true));
+
+ Future<GitChanges> repository() async {
+ await run(['init', '-q', '-b', 'main']);
+ await run(['config', 'user.email', 'finder@test']);
+ await run(['config', 'user.name', 'Finder Test']);
+ file('a.txt').writeAsStringSync('one\ntwo\n');
+ file('.gitignore').writeAsStringSync('build/\n');
+ await run(['add', '.']);
+ await run(['commit', '-qm', 'first']);
+ return (await git.changes(root))!;
+ }
+
+ test(
+ 'lists folders first and hides .git, node_modules and .DS_Store',
+ () async {
+ for (final dir in ['src', '.git', 'node_modules']) {
+ Directory(p.join(root, dir)).createSync();
+ }
+ for (final name in ['b.txt', 'A.md', '.DS_Store', '.env']) {
+ file(name).writeAsStringSync('x');
+ }
+ final names = [for (final e in await files.list(root)) e.name];
+ expect(names, ['src', '.env', 'A.md', 'b.txt']);
+ },
+ );
+
+ test(
+ 'reads text with its stamp, images as bytes, and refuses binaries',
+ () async {
+ file('LICENSE').writeAsStringSync('MIT');
+ file('a.png').writeAsBytesSync([1, 2, 3]);
+ file('blob').writeAsBytesSync([0, 1, 2]);
+ final text = await files.read(p.join(root, 'LICENSE'));
+ expect(text, isA<FinderText>().having((t) => t.text, 'text', 'MIT'));
+ expect(
+ (text as FinderText).stamp,
+ await files.stamp(p.join(root, 'LICENSE')),
+ );
+ expect(await files.read(p.join(root, 'a.png')), isA<FinderImage>());
+ expect(await files.read(p.join(root, 'blob')), isA<FinderBinary>());
+ },
+ );
+
+ test('writes, creates and renames, refusing to overwrite', () async {
+ final path = p.join(root, 'n.txt');
+ await files.createFile(path);
+ final stamp = await files.write(path, 'hello');
+ expect(file('n.txt').readAsStringSync(), 'hello');
+ expect(stamp, await files.stamp(path));
+ file('taken.txt').writeAsStringSync('x');
+ await expectLater(
+ files.rename(path, p.join(root, 'taken.txt')),
+ throwsA(anything),
+ );
+ await files.rename(path, p.join(root, 'm.txt'));
+ expect(file('m.txt').existsSync(), isTrue);
+ });
+
+ test('hears a change on disk', () async {
+ final written = p.join(root, 'w.txt');
+ final heard = files.watch(root).firstWhere((b) => b.contains(written));
+ await Future<void>.delayed(const Duration(milliseconds: 300));
+ file('w.txt').writeAsStringSync('x');
+ expect(await heard.timeout(const Duration(seconds: 5)), contains(written));
+ });
+
+ test('says a folder outside any repository has no changes', () async {
+ expect(await git.changes(root), isNull);
+ });
+
+ test(
+ 'reads changes with line counts, and diffs with the whole file',
+ () async {
+ await repository();
+ file('a.txt').writeAsStringSync('one\nTWO\n');
+ file('new.txt').writeAsStringSync('fresh\n');
+ final repo = (await git.changes(root))!;
+ expect(repo.branch, 'main');
+ expect(repo.changes.map((c) => (c.path, c.area, c.added, c.removed)), [
+ ('a.txt', GitArea.unstaged, 1, 1),
+ ('new.txt', GitArea.untracked, null, null),
+ ]);
+ final diff = await git.diff(repo, repo.changes.first);
+ expect(
+ [
+ for (final l in diff)
+ if (l.kind != DiffLineKind.meta && l.kind != DiffLineKind.hunk)
+ '${l.kind.name}:${l.text}',
+ ],
+ ['context:one', 'removed:two', 'added:TWO'],
+ );
+ final added = await git.diff(repo, repo.changes.last);
+ expect(
+ added.where((l) => l.kind == DiffLineKind.added).single.text,
+ 'fresh',
+ );
+ },
+ );
+
+ test('stages, unstages and discards', () async {
+ var repo = await repository();
+ file('a.txt').writeAsStringSync('changed\n');
+ repo = (await git.changes(root))!;
+ await git.stage(repo, repo.changes);
+ repo = (await git.changes(root))!;
+ expect(repo.changes.single.area, GitArea.staged);
+ await git.unstage(repo, repo.changes);
+ repo = (await git.changes(root))!;
+ expect(repo.changes.single.area, GitArea.unstaged);
+ await git.discard(repo, repo.changes);
+ expect(file('a.txt').readAsStringSync(), 'one\ntwo\n');
+ expect((await git.changes(root))!.changes, isEmpty);
+ });
+
+ test('tells which entries Git ignores', () async {
+ final repo = await repository();
+ Directory(p.join(root, 'build')).createSync();
+ expect(
+ await git.ignored(repo, [
+ FinderEntry(
+ name: 'build',
+ path: p.join(root, 'build'),
+ isDirectory: true,
+ ),
+ FinderEntry(
+ name: 'a.txt',
+ path: p.join(root, 'a.txt'),
+ isDirectory: false,
+ ),
+ ]),
+ {p.join(root, 'build')},
+ );
+ });
+}
diff --git a/desktop/test/keymap_host_test.dart b/desktop/test/keymap_host_test.dart
index d237701c5..186d0e88d 100644
--- a/desktop/test/keymap_host_test.dart
+++ b/desktop/test/keymap_host_test.dart
@@ -509,6 +509,51 @@ void main() {
},
);
+ testWidgets('a region keeps its own strokes from the workspace bindings', (
+ tester,
+ ) async {
+ final map = MemoryKeymap();
+ final focus = FocusNode();
+ final delivered = <String>[];
+ var searches = 0;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: KeymapProvider(
+ keymap: map,
+ child: KeymapHost(
+ keymap: map,
+ enabled: () => true,
+ actions: {'swarm.new': () => searches++},
+ child: KeymapRegion(
+ contextKind: KeymapContext.workspace,
+ // An editor's ⌘T would be its own; the workspace keeps the rest.
+ keeps: {KeyStroke.parse('cmd+t')},
+ child: Focus(
+ focusNode: focus,
+ autofocus: true,
+ onKeyEvent: (_, event) {
+ final stroke = keyStrokeForEvent(event);
+ if (event is KeyDownEvent && stroke != null) {
+ delivered.add(stroke.toString());
+ }
+ return KeyEventResult.handled;
+ },
+ child: const SizedBox(width: 100, height: 100),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ expect(searches, 0);
+ expect(delivered, ['cmd+t']);
+ await tester.pumpWidget(const SizedBox());
+ focus.dispose();
+ map.dispose();
+ });
+
testWidgets(
'modal picker actions stay local and respect active text composition',
(tester) async {
diff --git a/desktop/test/pane_fixed_width_test.dart b/desktop/test/pane_fixed_width_test.dart
new file mode 100644
index 000000000..138ce3f16
--- /dev/null
+++ b/desktop/test/pane_fixed_width_test.dart
@@ -0,0 +1,54 @@
+import 'dart:ui';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/widgets/pane_fixed_width.dart';
+
+void main() {
+ const canvas = Size(1000, 600);
+ const gap = 8.0;
+ // 70/30: [0, 696] and [704, 1000].
+ final pair = [
+ const Rect.fromLTRB(0, 0, 696, 600),
+ const Rect.fromLTRB(704, 0, 1000, 600),
+ ];
+
+ List<Rect>? pin(List<Rect> tiles, List<double?> widths, {double min = 200}) =>
+ pinFixedColumn(tiles, widths, canvas, gap: gap, minOther: min);
+
+ test('a left tile takes its width and the rest takes the room', () {
+ final tiles = pin(pair, [265, null])!;
+ expect(tiles[0], const Rect.fromLTRB(0, 0, 265, 600));
+ expect(tiles[1], const Rect.fromLTRB(273, 0, 1000, 600));
+ });
+
+ test('a right tile pins to the right edge', () {
+ final tiles = pin(pair, [null, 120])!;
+ expect(tiles[1], const Rect.fromLTRB(880, 0, 1000, 600));
+ expect(tiles[0], const Rect.fromLTRB(0, 0, 872, 600));
+ });
+
+ test('the others keep their proportions and stacking', () {
+ final three = [
+ const Rect.fromLTRB(0, 0, 496, 600),
+ const Rect.fromLTRB(504, 0, 1000, 296),
+ const Rect.fromLTRB(504, 304, 1000, 600),
+ ];
+ final tiles = pin(three, [100, null, null])!;
+ expect(tiles[1], const Rect.fromLTRB(108, 0, 1000, 296));
+ expect(tiles[2], const Rect.fromLTRB(108, 304, 1000, 600));
+ });
+
+ test('never squeezes the others below their minimum', () {
+ final tiles = pin(pair, [990, null], min: 300)!;
+ expect(tiles[0].width, 1000 - gap - 300);
+ });
+
+ test('a tile not spanning an edge, or no width asked, pins nothing', () {
+ expect(pin(pair, [null, null]), isNull);
+ final stacked = [
+ const Rect.fromLTRB(0, 0, 1000, 296),
+ const Rect.fromLTRB(0, 304, 1000, 600),
+ ];
+ expect(pin(stacked, [265, null]), isNull);
+ });
+}