brain: Run repository I/O asynchronously

ce4781dda1721c5dbde6b396aa9bda6a2d02e3c4
Serialize startup and session repository operations on background
workers so slow Git and Jujutsu commands do not block terminal
rendering. Keep optimistic review and comment state consistent when
preparation, enqueueing, or persistence fails.

Assisted-by: Codex:gpt-5.6-sol
Alexis Sellier committed ago 1 parent 1f6bc647
crates/brain/src/backend.rs +1 -1
693 693
694 694
/// A revision backend that lists the reviewed commits and their diffs.
695 695
///
696 696
/// The base and target revisions are resolved and stored when the backend is
697 697
/// constructed, so listing commits needs no further arguments.
698 -
pub trait Backend {
698 +
pub trait Backend: Send {
699 699
    /// Returns the user-facing revision range under review.
700 700
    fn range_label(&self) -> String;
701 701
    /// Returns the reviewed commits in `base..target`, oldest first.
702 702
    fn commits(&self) -> Result<Vec<Commit>, Error>;
703 703
f +0 -0
new.rs +0 -0
image.png +0 -0
new.txt +0 -0
crates/brain/src/comments.rs +8 -37
266 266
            .collect();
267 267
268 268
        Self { by_hunk, targets }
269 269
    }
270 270
271 -
    /// Applies one comment mutation only after `persist` accepts its encoded
272 -
    /// store, leaving both the store and this view unchanged on failure.
273 -
    pub fn transact<E>(
271 +
    /// Applies one comment mutation and returns the encoded updated store.
272 +
    ///
273 +
    /// The caller must persist the returned text through the session command
274 +
    /// worker and restore its snapshot if that command fails.
275 +
    pub fn transact(
274 276
        &mut self,
275 277
        store: &mut ReviewComments,
276 278
        update: impl FnOnce(&mut Self, &mut ReviewComments) -> bool,
277 -
        persist: impl FnOnce(&str) -> std::result::Result<(), E>,
278 -
    ) -> std::result::Result<bool, E> {
279 +
    ) -> Option<String> {
279 280
        let mut updated_store = store.clone();
280 281
        let mut updated_view = self.clone();
281 282
        if !update(&mut updated_view, &mut updated_store) {
282 -
            return Ok(false);
283 +
            return None;
283 284
        }
284 285
        let encoded = updated_store.encode();
285 -
        persist(&encoded)?;
286 286
        *store = updated_store;
287 287
        *self = updated_view;
288 -
        Ok(true)
288 +
        Some(encoded)
289 289
    }
290 290
291 291
    /// Authors a comment on `hunk` into `store`, returning whether one was
292 292
    /// added. The caller is responsible for persisting the updated store.
293 293
    pub fn author(&mut self, store: &mut ReviewComments, hunk: HunkId, body: String) -> bool {
520 520
521 521
        let reopened = Comments::new(&store, targets);
522 522
        assert!(reopened.for_hunk(HUNK).is_empty());
523 523
        assert_eq!(reopened.for_hunk(OTHER_HUNK)[0].body, "edited second");
524 524
    }
525 -
526 -
    #[test]
527 -
    fn failed_comment_persistence_keeps_store_and_view_unchanged() {
528 -
        let (mut store, mut comments) = empty_comments();
529 -
        assert!(comments.author(&mut store, HUNK, "old".to_owned()));
530 -
        let before = store.encode();
531 -
        let original = comments.for_hunk(HUNK).to_vec();
532 -
        let id = original[0].id.clone();
533 -
534 -
        let edited = comments.transact(
535 -
            &mut store,
536 -
            |comments, store| comments.edit(store, HUNK, &id, "new".to_owned()),
537 -
            |_| Err::<(), _>("write failed"),
538 -
        );
539 -
540 -
        assert!(edited.is_err());
541 -
        assert_eq!(store.encode(), before);
542 -
        assert_eq!(comments.for_hunk(HUNK), original);
543 -
544 -
        let deleted = comments.transact(
545 -
            &mut store,
546 -
            |comments, store| comments.delete(store, HUNK, &id),
547 -
            |_| Err::<(), _>("write failed"),
548 -
        );
549 -
550 -
        assert!(deleted.is_err());
551 -
        assert_eq!(store.encode(), before);
552 -
        assert_eq!(comments.for_hunk(HUNK), original);
553 -
    }
554 525
}
crates/brain/src/main.rs +208 -74
19 19
20 20
use std::env;
21 21
use std::ffi::{OsStr, OsString};
22 22
use std::io::{self, Write as _};
23 23
use std::process::ExitCode;
24 +
use std::sync::mpsc::{self, RecvTimeoutError};
25 +
use std::thread;
26 +
use std::time::Duration;
24 27
25 28
use lexopt::prelude::*;
26 29
use rustik_diff::{Builtins, DiffOptions, DiffPalette, FileTreeMode, HunkFocus, progress_bar};
27 30
use rustik_repo::{AheadBehind, MergeStatus, Rev};
28 31
use rustik_tui::{
29 -
    ActionList, Border, Color, Constraint, Dialog, Event, Key, Label, Line, Size, Style, Table,
30 -
    TableOptions, Terminal, colors,
32 +
    ActionList, Border, Color, Constraint, Dialog, Event, Key, Label, Line, Rect, Size, Style,
33 +
    Table, TableOptions, Terminal, colors,
31 34
};
32 35
use rustik_tui_termion as tui_termion;
33 36
34 37
use backend::{
35 38
    BrainStatus, BrainStatusBaseState, BrainStatusHead, BrainStatusState, CommentStatus,
38 41
use error::Error;
39 42
40 43
/// Terminal backend used by the interactive viewer.
41 44
type BrainTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::TerminalScreen>>;
42 45
46 +
/// Startup spinner repaint interval.
47 +
const STARTUP_SPINNER_INTERVAL: Duration = Duration::from_millis(80);
48 +
/// Startup spinner animation frames.
49 +
const STARTUP_SPINNER_FRAMES: &[char] = &['|', '/', '-', '\\'];
50 +
43 51
/// Command-line usage text.
44 52
const USAGE: &str = "usage: brain [status [--all]]\n       brain status <base> <target>\n       brain [--reset|--rebase] diff [<base>] <target>";
45 53
/// Default output width used when terminal width is unknown.
46 54
const DEFAULT_STATUS_WIDTH: usize = 140;
47 55
/// Marker shown for approved review state: ✔.
206 214
                    .action("x", "reset")
207 215
                    .action("esc", "quit"),
208 216
            )
209 217
            .max_size(Size::new(78, 10))
210 218
    }
219 +
}
220 +
221 +
/// Repository initialization command executed before the session starts.
222 +
enum StartupCommand {
223 +
    /// Opens the requested review and loads existing state.
224 +
    Open {
225 +
        /// Working directory used for repository discovery.
226 +
        cwd: std::path::PathBuf,
227 +
        /// Explicit review base, when supplied.
228 +
        base: Option<Rev>,
229 +
        /// Inclusive review target.
230 +
        target: Rev,
231 +
        /// Requested persisted-state policy.
232 +
        state: ReviewStateLoad,
233 +
    },
234 +
    /// Resolves stale persisted state using the selected action.
235 +
    Resolve {
236 +
        /// Already-open revision backend.
237 +
        backend: Box<dyn backend::Backend>,
238 +
        /// Stale-state resolution.
239 +
        action: StaleReviewStateAction,
240 +
    },
241 +
}
242 +
243 +
/// Fully loaded inputs for the interactive review session.
244 +
struct LoadedReview {
245 +
    /// Revision backend transferred to the session worker.
246 +
    backend: Box<dyn backend::Backend>,
247 +
    /// Loaded hidden review state.
248 +
    brain: backend::Brain,
249 +
    /// Parsed review-wide comments.
250 +
    comments: ReviewComments,
251 +
    /// Commits in the reviewed range, oldest first.
252 +
    commits: Vec<backend::Commit>,
253 +
}
254 +
255 +
/// Result of one startup repository command.
256 +
enum StartupOutput {
257 +
    /// Existing state is stale and requires a user decision.
258 +
    Stale(Box<dyn backend::Backend>),
259 +
    /// Fully loaded inputs for the interactive session.
260 +
    Loaded(Box<LoadedReview>),
261 +
}
262 +
263 +
/// Executes one blocking startup command on a worker thread.
264 +
fn execute_startup(command: StartupCommand) -> Result<StartupOutput, Error> {
265 +
    let (backend, brain) = match command {
266 +
        StartupCommand::Open {
267 +
            cwd,
268 +
            base,
269 +
            target,
270 +
            state,
271 +
        } => {
272 +
            let base = match base {
273 +
                Some(base) => base,
274 +
                None => backend::branch_base(&cwd, &target)?,
275 +
            };
276 +
            let backend = <dyn backend::Backend>::from_path(&cwd, base, target)?;
277 +
            let brain = match state {
278 +
                ReviewStateLoad::Existing => match backend.brain() {
279 +
                    Ok(brain) => brain,
280 +
                    Err(Error::StaleReviewState) => return Ok(StartupOutput::Stale(backend)),
281 +
                    Err(error) => return Err(error),
282 +
                },
283 +
                ReviewStateLoad::Fresh => backend.reset_brain()?,
284 +
                ReviewStateLoad::Rebase => backend.rebase_brain()?,
285 +
            };
286 +
            (backend, brain)
287 +
        }
288 +
        StartupCommand::Resolve { backend, action } => {
289 +
            let brain = match action {
290 +
                StaleReviewStateAction::Rebase => backend.rebase_brain()?,
291 +
                StaleReviewStateAction::Reset => backend.reset_brain()?,
292 +
                StaleReviewStateAction::Quit => return Ok(StartupOutput::Stale(backend)),
293 +
            };
294 +
            (backend, brain)
295 +
        }
296 +
    };
297 +
    let persisted = brain.read_comments()?;
298 +
    let comments = ReviewComments::parse(persisted.as_deref().unwrap_or_default())?;
299 +
    let commits = backend.commits()?;
300 +
    if commits.is_empty() {
301 +
        return Err(Error::Empty);
302 +
    }
303 +
    Ok(StartupOutput::Loaded(Box::new(LoadedReview {
304 +
        backend,
305 +
        brain,
306 +
        comments,
307 +
        commits,
308 +
    })))
309 +
}
310 +
311 +
/// Runs one startup command while animating the terminal status row.
312 +
fn wait_for_startup(
313 +
    terminal: &mut BrainTerminal,
314 +
    command: StartupCommand,
315 +
) -> Result<StartupOutput, Error> {
316 +
    let (sender, receiver) = mpsc::channel();
317 +
    let worker = thread::spawn(move || {
318 +
        let _ = sender.send(execute_startup(command));
319 +
    });
320 +
    let mut frame = 0usize;
321 +
    loop {
322 +
        match receiver.recv_timeout(STARTUP_SPINNER_INTERVAL) {
323 +
            Ok(result) => {
324 +
                let _ = worker.join();
325 +
                return result;
326 +
            }
327 +
            Err(RecvTimeoutError::Disconnected) => {
328 +
                let _ = worker.join();
329 +
                return Err(Error::Git(
330 +
                    "repository worker stopped unexpectedly".to_owned(),
331 +
                ));
332 +
            }
333 +
            Err(RecvTimeoutError::Timeout) => {
334 +
                let spinner = STARTUP_SPINNER_FRAMES[frame % STARTUP_SPINNER_FRAMES.len()];
335 +
                if let Err(error) = terminal.draw(|terminal_frame| {
336 +
                    let area = terminal_frame.area;
337 +
                    let status = Rect::new(0, area.rows.saturating_sub(1), area.cols, 1);
338 +
                    let line = Line::blank()
339 +
                        .item(Label::from_char(spinner))
340 +
                        .item(Label::space())
341 +
                        .item(Label::new("loading review"));
342 +
                    terminal_frame.render_widget(line, status);
343 +
                }) {
344 +
                    let _ = worker.join();
345 +
                    return Err(error.into());
346 +
                }
347 +
                frame = frame.wrapping_add(1);
348 +
            }
349 +
        }
350 +
    }
351 +
}
211 352
353 +
impl StaleReviewStatePrompt {
212 354
    /// Draws the prompt.
213 355
    fn draw(self, terminal: &mut BrainTerminal) -> Result<(), Error> {
214 356
        terminal.draw(|frame| {
215 357
            frame.render_widget(self.dialog(), frame.area);
216 358
        })?;
240 382
}
241 383
242 384
/// Loads the review range and runs the interactive diff session.
243 385
fn run_diff(state: ReviewStateLoad, base: Option<Rev>, target: Rev) -> Result<(), Error> {
244 386
    let cwd = env::current_dir()?;
245 -
    let base = match base {
246 -
        Some(base) => base,
247 -
        None => backend::branch_base(&cwd, &target)?,
248 -
    };
249 -
    let backend = <dyn backend::Backend>::from_path(&cwd, base, target)?;
250 -
    let mut terminal = None;
251 -
    let mut events = None;
252 -
    let brain = match state {
253 -
        ReviewStateLoad::Existing => match backend.brain() {
254 -
            Ok(brain) => brain,
255 -
            Err(Error::StaleReviewState) => {
256 -
                let terminal = terminal.get_or_insert(open_terminal()?);
257 -
                let events = events.get_or_insert_with(session::Events::spawn);
258 -
                let action = prompt_stale_review_state(terminal, events);
259 -
                let cursor = terminal.set_cursor_visible(true);
260 -
                let action = action?;
261 -
                cursor?;
262 -
263 -
                match action {
264 -
                    StaleReviewStateAction::Rebase => backend.rebase_brain()?,
265 -
                    StaleReviewStateAction::Reset => backend.reset_brain()?,
266 -
                    StaleReviewStateAction::Quit => return Ok(()),
267 -
                }
268 -
            }
269 -
            Err(error) => return Err(error),
270 -
        },
271 -
        ReviewStateLoad::Fresh => backend.reset_brain()?,
272 -
        ReviewStateLoad::Rebase => backend.rebase_brain()?,
273 -
    };
274 -
    let persisted = brain.read_comments()?;
275 -
    let comments = ReviewComments::parse(persisted.as_deref().unwrap_or_default())?;
276 -
277 -
    let assets = Builtins::load().map_err(|error| Error::Highlight(error.to_string()))?;
278 -
    let root = cwd
279 -
        .file_name()
280 -
        .and_then(OsStr::to_str)
281 -
        .filter(|name| !name.is_empty())
282 -
        .map(str::to_owned)
283 -
        .unwrap_or_else(|| cwd.display().to_string());
284 -
    let options = DiffOptions {
285 -
        diff_palette: assets.palette,
286 -
        file_tree: FileTreeMode::Auto,
287 -
        file_tree_root: root,
288 -
        hunk_focus: HunkFocus::DimUnfocused,
289 -
        ..DiffOptions::default()
290 -
    };
291 -
292 -
    // Multi-commit history decodes each patch once to select reviewable rows
293 -
    // and calculate exact progress. A single commit stays lazy until displayed.
294 -
    let commits = backend.commits()?;
295 -
    if commits.is_empty() {
296 -
        return Err(Error::Empty);
297 -
    }
298 -
299 -
    let mut terminal = match terminal {
300 -
        Some(terminal) => terminal,
301 -
        None => open_terminal()?,
302 -
    };
303 -
    let events = events.unwrap_or_else(session::Events::spawn);
304 -
387 +
    let mut terminal = open_terminal()?;
305 388
    terminal.clear()?;
306 389
    terminal.set_cursor_visible(false)?;
307 390
308 -
    let result = session::run(
309 -
        &mut terminal,
310 -
        events,
311 -
        commits,
312 -
        backend,
313 -
        brain,
314 -
        comments,
315 -
        options,
316 -
    );
317 -
    let cursor = terminal.set_cursor_visible(true);
391 +
    let result: Result<(), Error> = (|| {
392 +
        let command = StartupCommand::Open {
393 +
            cwd: cwd.clone(),
394 +
            base,
395 +
            target,
396 +
            state,
397 +
        };
398 +
        let events = session::Events::spawn();
399 +
        let mut output = wait_for_startup(&mut terminal, command)?;
400 +
        events.discard_pending();
401 +
        let (backend, brain, comments, commits) = loop {
402 +
            match output {
403 +
                StartupOutput::Loaded(loaded) => {
404 +
                    let LoadedReview {
405 +
                        backend,
406 +
                        brain,
407 +
                        comments,
408 +
                        commits,
409 +
                    } = *loaded;
410 +
                    break (backend, brain, comments, commits);
411 +
                }
412 +
                StartupOutput::Stale(backend) => {
413 +
                    let action = prompt_stale_review_state(&mut terminal, &events)?;
414 +
                    if action == StaleReviewStateAction::Quit {
415 +
                        return Ok(());
416 +
                    }
417 +
                    terminal.clear()?;
418 +
                    output = wait_for_startup(
419 +
                        &mut terminal,
420 +
                        StartupCommand::Resolve { backend, action },
421 +
                    )?;
422 +
                    events.discard_pending();
423 +
                }
424 +
            }
425 +
        };
318 426
427 +
        let assets = Builtins::load().map_err(|error| Error::Highlight(error.to_string()))?;
428 +
        let root = cwd
429 +
            .file_name()
430 +
            .and_then(OsStr::to_str)
431 +
            .filter(|name| !name.is_empty())
432 +
            .map(str::to_owned)
433 +
            .unwrap_or_else(|| cwd.display().to_string());
434 +
        let options = DiffOptions {
435 +
            diff_palette: assets.palette,
436 +
            file_tree: FileTreeMode::Auto,
437 +
            file_tree_root: root,
438 +
            hunk_focus: HunkFocus::DimUnfocused,
439 +
            ..DiffOptions::default()
440 +
        };
441 +
        events.discard_pending();
442 +
443 +
        terminal.clear()?;
444 +
        session::run(
445 +
            &mut terminal,
446 +
            events,
447 +
            commits,
448 +
            backend,
449 +
            brain,
450 +
            comments,
451 +
            options,
452 +
        )
453 +
    })();
454 +
    let cursor = terminal.set_cursor_visible(true);
319 455
    result?;
320 456
    cursor.map_err(Error::Io)
321 457
}
322 458
323 459
/// Prints the history view for the commits in `base..target`.
349 485
    let mut stdout = io::stdout().lock();
350 486
351 487
    for line in status_lines(&statuses, scope, status_width()) {
352 488
        writeln!(stdout, "{}", line.styled())?;
353 489
    }
354 -
355 490
    Ok(())
356 491
}
357 492
358 493
/// Returns styled status output lines.
359 494
fn status_lines(statuses: &[BrainStatus], scope: StatusScope, width: usize) -> Vec<Line> {
522 657
            }
523 658
            Event::Resize(_) => prompt.draw(terminal)?,
524 659
            _ => {}
525 660
        }
526 661
    }
527 -
528 662
    Ok(StaleReviewStateAction::Quit)
529 663
}
530 664
531 665
#[cfg(test)]
532 666
mod tests {
crates/brain/src/session.rs +359 -253
1 1
//! Terminal session loop for the `brain` review TUI.
2 2
3 3
use std::collections::BTreeSet;
4 4
use std::io;
5 5
use std::mem;
6 -
use std::sync::mpsc::{self, Receiver, Sender};
7 -
use std::thread::{self, JoinHandle};
6 +
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
7 +
use std::time::Duration;
8 8
9 9
use rustik_diff::{
10 10
    ContextChange, DiffAction, DiffDocument, DiffFocus, DiffOptions, DiffState, DiffViewer,
11 11
    FileDiff, FileTreeMode, HighlightOutput, HighlightRequest, Highlighter, ReviewProgress,
12 12
    ViewChange, spawn_highlighter,
13 13
};
14 -
use rustik_repo::DiffStat;
14 +
use rustik_repo::{DiffStat, git};
15 15
use rustik_tui::{
16 16
    Backend as TuiBackend, Column, Constraint, Control, Event, Key, Line, List, ListState, Mouse,
17 17
    MouseButton, Rect, ScrollView, Style, Table, TableOptions, Terminal,
18 18
};
19 19
use rustik_tui_termion as tui_termion;
20 20
21 21
use crate::backend::{
22 22
    Accepted, Backend, Brain, Commit, CommitHunks, CommitReviewState, FilePatches, HistoryStatus,
23 23
};
24 -
use crate::comments::ReviewComments;
24 +
use crate::comments::{Comments, ReviewComments};
25 25
use crate::error::Error;
26 26
use crate::review::{FileVisibility, HunkVisibility, Visibility};
27 27
28 28
mod commit;
29 29
mod event;
30 30
mod hunk;
31 31
mod status;
32 +
mod worker;
32 33
33 34
use commit::{CommitReview, CommitSlot};
34 35
use event::{ContextFetch, Resize, TerminalEvent, Update, context_change};
35 36
use hunk::{CommentEdit, HunkView};
36 37
pub(crate) use status::BRAIN_BADGE_BG;
37 38
use status::{
38 39
    ActionContext, Chrome, HISTORY_DIFFSTAT_MAX_WIDTH, SELECTED_COMMIT_BG, Status, StatusContext,
39 40
    commit_row, commit_row_suffix, current_timestamp, viewer_area,
40 41
};
42 +
use worker::{
43 +
    Command as WorkerCommand, LoadCommit, Output as WorkerOutput, ReviewMutation, Worker,
44 +
};
41 45
42 46
/// Terminal backend used by the interactive viewer.
43 47
type BrainTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::TerminalScreen>>;
44 48
45 49
/// Minimum width of a history diffstat graph.
46 50
const HISTORY_DIFFSTAT_MIN_WIDTH: usize = 8;
51 +
/// Spinner repaint interval while repository work is pending.
52 +
const SPINNER_INTERVAL: Duration = Duration::from_millis(80);
47 53
/// Fraction of the history panel available to the diffstat graph.
48 54
const HISTORY_DIFFSTAT_WIDTH_DIVISOR: usize = 6;
49 55
/// Active view in the session.
50 56
enum Mode {
51 57
    /// The commit list.
108 114
                Ok(_) => {}
109 115
                Err(_) => return None,
110 116
            }
111 117
        }
112 118
    }
119 +
120 +
    /// Discards input received while no interactive screen was visible.
121 +
    pub fn discard_pending(&self) {
122 +
        while self.rx.try_recv().is_ok() {}
123 +
    }
113 124
}
114 125
115 126
/// Runs the terminal event loop until the reviewer quits.
116 127
pub fn run(
117 128
    terminal: &mut BrainTerminal,
126 137
        tx: events_tx,
127 138
        rx: events_rx,
128 139
    } = events;
129 140
130 141
    let range = backend.range_label();
131 -
    let (mut slots, history_status) = if commits.len() > 1 {
132 -
        let (slots, status) = reviewed_slots(commits, &*backend, &brain)?;
133 -
        (slots, Some(status))
134 -
    } else {
135 -
        let slots = commits
136 -
            .into_iter()
137 -
            .map(|commit| CommitSlot {
138 -
                remaining_stats: commit.stats,
139 -
                commit,
140 -
                progress: ReviewProgress::default(),
141 -
                state: CommitReviewState::Pending,
142 -
                document: None,
143 -
                identities: None,
144 -
                loaded: None,
145 -
            })
146 -
            .collect::<Vec<_>>();
147 -
        (slots, None)
148 -
    };
142 +
    let history_commits = (commits.len() > 1).then(|| commits.clone());
143 +
    let mut repositories = commits
144 +
        .iter()
145 +
        .map(|commit| backend.repo(commit))
146 +
        .collect::<Vec<_>>();
147 +
    let mut slots = commits
148 +
        .into_iter()
149 +
        .map(|commit| CommitSlot {
150 +
            remaining_stats: commit.stats,
151 +
            commit,
152 +
            progress: ReviewProgress::default(),
153 +
            state: CommitReviewState::Pending,
154 +
            document: None,
155 +
            identities: None,
156 +
            loaded: None,
157 +
        })
158 +
        .collect::<Vec<_>>();
149 159
    slots.reverse();
160 +
    repositories.reverse();
150 161
    let mode = if slots.len() > 1 {
151 162
        Mode::Commits
152 163
    } else {
153 164
        Mode::Diff
154 165
    };
155 166
167 +
    let repository_worker = Worker::spawn(backend, brain.clone(), events_tx.clone());
156 168
    let mut session = Session {
157 169
        terminal,
158 170
        commits: slots,
159 171
        range,
160 -
        history_status,
172 +
        history_status: None,
161 173
        accepted: Vec::new(),
162 174
        pending: None,
163 175
        current: 0,
164 176
        hunk_visibility: HunkVisibility::default(),
165 177
        mode,
166 178
        parked: None,
167 179
        list: ListState::new(),
168 180
        options,
169 -
        backend,
181 +
        repositories,
170 182
        brain,
171 183
        comments,
172 184
        events_tx,
173 185
        generation: 0,
174 186
        highlighter: None,
187 +
        repository_worker,
175 188
        context_fetch: ContextFetch::default(),
176 189
        error: None,
190 +
        loading: None,
191 +
        spinner: 0,
177 192
    };
178 193
179 -
    if !matches!(session.mode, Mode::Commits) {
180 -
        session.current()?;
181 -
        session.reconcile_state();
182 -
        session.activate()?;
194 +
    if let Some(commits) = history_commits {
195 +
        session.loading = Some("loading history");
196 +
        session
197 +
            .repository_worker
198 +
            .send(WorkerCommand::LoadHistory { commits })
199 +
            .map_err(Error::Git)?;
200 +
    } else {
201 +
        session.request_commit(0)?;
183 202
    }
184 203
    session.redraw()?;
185 204
186 -
    while let Some(event) = TerminalEvent::receive(events_rx.recv())? {
205 +
    loop {
206 +
        let received = if session.loading.is_some() {
207 +
            match events_rx.recv_timeout(SPINNER_INTERVAL) {
208 +
                Ok(event) => Some(event),
209 +
                Err(RecvTimeoutError::Timeout) => {
210 +
                    session.spinner = session.spinner.wrapping_add(1);
211 +
                    session.redraw()?;
212 +
                    continue;
213 +
                }
214 +
                Err(RecvTimeoutError::Disconnected) => None,
215 +
            }
216 +
        } else {
217 +
            events_rx.recv().ok()
218 +
        };
219 +
        let Some(event) = received else {
220 +
            break;
221 +
        };
222 +
        let Some(event) = TerminalEvent::receive(Ok::<_, mpsc::RecvError>(event))? else {
223 +
            break;
224 +
        };
187 225
        let mut redraw = false;
188 226
        let mut next = Some(event);
189 -
        // Drain queued events before repainting so bursts coalesce into one
190 -
        // frame.
227 +
        // Drain queued events before repainting so bursts coalesce into one frame.
191 228
        while let Some(event) = next {
192 229
            match session.update(event) {
193 230
                Ok(Update::Continue) => {}
194 231
                Ok(Update::Redraw) => redraw = true,
195 232
                Ok(Update::Quit) => return Ok(()),
308 345
    before: DiffState,
309 346
    /// Viewer state after automatic navigation.
310 347
    after: DiffState,
311 348
}
312 349
313 -
/// One background acceptance update and its rollback state.
314 -
struct PendingAcceptance {
315 -
    /// Accepted identities restored if persistence fails.
316 -
    rollback: Accepted,
350 +
/// State around one optimistic acceptance.
351 +
struct AcceptancePending {
352 +
    /// Review state restored if persistence fails.
353 +
    rollback: Box<Brain>,
317 354
    /// Undo stack installed after successful persistence.
318 355
    undo: Vec<HunkLocation>,
319 356
    /// Navigation restored if the user has not moved again.
320 357
    navigation: Option<NavigationRollback>,
321 -
    /// Background repository update.
322 -
    worker: JoinHandle<Result<Brain, String>>,
358 +
}
359 +
360 +
/// Comment state restored if persistence fails.
361 +
struct CommentRollback {
362 +
    /// Commit whose comment view changed.
363 +
    commit: usize,
364 +
    /// Review-wide store before the optimistic mutation.
365 +
    store: ReviewComments,
366 +
    /// Commit-local view before the optimistic mutation.
367 +
    comments: Comments,
368 +
}
369 +
370 +
/// Optimistic state restored or finalized when persistence completes.
371 +
enum Pending {
372 +
    /// Hunk acceptance currently writing to the repository.
373 +
    Acceptance(AcceptancePending),
374 +
    /// Commit decision currently writing to the repository.
375 +
    Decision,
376 +
    /// Comment mutation currently writing to the repository.
377 +
    Comments(CommentRollback),
323 378
}
324 379
325 380
/// Interactive terminal session state.
326 381
struct Session<'a, T: TuiBackend<Error = io::Error>> {
327 382
    /// Terminal frame target.
332 387
    range: String,
333 388
    /// Lazily cached global progress and remaining statistics for history.
334 389
    history_status: Option<HistoryStatus>,
335 390
    /// Hunk acceptances available to undo, in acceptance order.
336 391
    accepted: Vec<HunkLocation>,
337 -
    /// Acceptance update currently writing to the repository.
338 -
    pending: Option<PendingAcceptance>,
392 +
    /// Optimistic state currently writing to the repository.
393 +
    pending: Option<Pending>,
339 394
    /// Index of the commit currently displayed.
340 395
    current: usize,
341 396
    /// Set of hunks visible across commit viewers.
342 397
    hunk_visibility: HunkVisibility,
343 398
    /// Active view: the commit list, the diff, or a hunk's comment box.
346 401
    parked: Option<Box<HunkView>>,
347 402
    /// Selection and scroll state for the commit-list tab.
348 403
    list: ListState,
349 404
    /// Viewer options used to build commit and per-hunk viewers.
350 405
    options: DiffOptions,
351 -
    /// Revision backend used for lazy commit loads and context refetches.
352 -
    backend: Box<dyn Backend>,
406 +
    /// Git contexts used only by background highlighters.
407 +
    repositories: Vec<git::Repository>,
408 +
    /// Serialized command interface for every UI-initiated repository operation.
409 +
    repository_worker: Worker,
353 410
    /// Hidden review state storing accepted identities, derived content, and comments.
354 411
    brain: Brain,
355 412
    /// Review-wide persistent comment store.
356 413
    comments: ReviewComments,
357 414
    /// Sender used to respawn the highlighter for the current commit.
360 417
    generation: u64,
361 418
    /// Highlighter for the current commit, respawned on each switch.
362 419
    highlighter: Option<Highlighter>,
363 420
    /// Whether a context refetch is in flight.
364 421
    context_fetch: ContextFetch,
422 +
    /// Repository operation currently represented by the status spinner.
423 +
    loading: Option<&'static str>,
424 +
    /// Current spinner animation frame.
425 +
    spinner: usize,
365 426
    /// Most recent recoverable session error shown in the status bar.
366 427
    error: Option<String>,
367 428
}
368 429
369 430
impl<T: TuiBackend<Error = io::Error>> Session<'_, T> {
370 -
    /// Returns the current commit's diff state, decoding it on first access.
431 +
    /// Returns the current commit's cached diff state.
371 432
    fn current(&mut self) -> Result<&mut CommitReview, Error> {
372 433
        self.load(self.current)
373 434
    }
374 435
375 -
    /// Returns commit `index`'s diff state, decoding it on first access.
436 +
    /// Returns commit `index`'s cached diff state.
376 437
    fn load(&mut self, index: usize) -> Result<&mut CommitReview, Error> {
438 +
        self.commits[index]
439 +
            .loaded
440 +
            .as_mut()
441 +
            .ok_or_else(|| Error::Git("commit is still loading".to_owned()))
442 +
    }
443 +
    /// Queues construction of one uncached commit viewer.
444 +
    fn request_commit(&mut self, index: usize) -> Result<(), Error> {
445 +
        if self.commits[index].loaded.is_some() {
446 +
            return Ok(());
447 +
        }
377 448
        let slot = &mut self.commits[index];
378 -
        let loaded = match slot.loaded.take() {
379 -
            Some(loaded) => loaded,
380 -
            None => {
381 -
                let document = match slot.document.take() {
382 -
                    Some(document) => document,
383 -
                    None => self.backend.diff_document(slot.commit.id)?.split_hunks(),
384 -
                };
385 -
                CommitReview::load(
386 -
                    &slot.commit,
387 -
                    document,
388 -
                    slot.identities.take(),
389 -
                    self.options.clone(),
390 -
                    &self.brain,
391 -
                    &self.comments,
392 -
                )?
393 -
            }
394 -
        };
395 -
        Ok(slot.loaded.insert(loaded))
449 +
        let command = WorkerCommand::LoadCommit(Box::new(LoadCommit {
450 +
            index,
451 +
            commit: slot.commit.clone(),
452 +
            document: slot.document.take(),
453 +
            identities: slot.identities.take(),
454 +
            options: self.options.clone(),
455 +
            comments: self.comments.clone(),
456 +
        }));
457 +
        self.repository_worker.send(command).map_err(Error::Git)?;
458 +
        self.loading = Some("loading commit");
459 +
        Ok(())
396 460
    }
397 461
398 462
    /// Applies one terminal or worker event and records redraw work.
399 463
    ///
400 464
    /// Input is routed by active mode first so the commit list and hunk editor
409 473
                if self.action_context() != ActionContext::HunkEdit
410 474
                    && matches!(event, Event::Key(Key::Ctrl('c')))
411 475
                {
412 476
                    return self.try_quit();
413 477
                }
478 +
                if self.loading.is_some() && !matches!(event, Event::Resize(_)) {
479 +
                    return Ok(Update::Continue);
480 +
                }
414 481
                let resize = if matches!(event, Event::Resize(_)) {
415 482
                    Resize::Changed
416 483
                } else {
417 484
                    Resize::Stable
418 485
                };
473 540
                    Update::Redraw
474 541
                } else {
475 542
                    Update::Continue
476 543
                })
477 544
            }
478 -
            TerminalEvent::Persistence(worker) => {
479 -
                let current = self
480 -
                    .pending
481 -
                    .as_ref()
482 -
                    .is_some_and(|pending| pending.worker.thread().id() == worker);
483 -
                if current {
484 -
                    Ok(match self.sync_acceptance()? {
485 -
                        ViewChange::Changed => Update::Redraw,
486 -
                        ViewChange::Unchanged => Update::Continue,
487 -
                    })
488 -
                } else {
489 -
                    Ok(Update::Continue)
490 -
                }
491 -
            }
545 +
            TerminalEvent::Worker(output) => self.handle_worker_output(*output),
492 546
        }
493 547
    }
494 548
495 -
    /// Waits for pending acceptance before leaving the session.
549 +
    /// Leaves the session unless repository work is still pending.
496 550
    fn try_quit(&mut self) -> Result<Update, Error> {
497 -
        let _ = self.sync_acceptance()?;
498 -
        Ok(if self.error.is_some() {
551 +
        Ok(if self.loading.is_some() || self.error.is_some() {
499 552
            Update::Redraw
500 553
        } else {
501 554
            Update::Quit
502 555
        })
503 556
    }
504 557
505 -
    /// Dispatches one input event, handling review keys before the viewer.
506 -
    fn handle_key(&mut self, event: Event<()>, area: Rect) -> Result<Control, Error> {
507 -
        if self.pending.is_some() && matches!(&event, Event::Key(Key::Char('a' | 'A' | 'u'))) {
508 -
            let _ = self.sync_acceptance()?;
509 -
            if self.error.is_some() {
510 -
                return Ok(Control::Redraw);
558 +
    /// Applies one completed repository command without performing I/O.
559 +
    fn handle_worker_output(&mut self, output: WorkerOutput) -> Result<Update, Error> {
560 +
        self.loading = None;
561 +
        match output {
562 +
            WorkerOutput::CommitLoaded { index, result } => match *result {
563 +
                Ok(loaded) => {
564 +
                    self.commits[index].loaded = Some(loaded);
565 +
                    self.reconcile_state();
566 +
                    if index == self.current && matches!(self.mode, Mode::Diff) {
567 +
                        self.activate()?;
568 +
                    } else if self.commits[self.current].loaded.is_none() {
569 +
                        self.request_commit(self.current)?;
570 +
                    }
571 +
                }
572 +
                Err(message) => self.error = Some(message.replace('\n', " · ")),
573 +
            },
574 +
            WorkerOutput::HistoryLoaded(result) => match *result {
575 +
                Ok((mut commits, status)) => {
576 +
                    commits.reverse();
577 +
                    self.commits = commits;
578 +
                    self.history_status = Some(status);
579 +
                }
580 +
                Err(message) => self.error = Some(message.replace('\n', " · ")),
581 +
            },
582 +
            WorkerOutput::SourcesLoaded { hunk, result } => match *result {
583 +
                Ok(viewer) => {
584 +
                    let mut view = HunkView::new(hunk, viewer, self.comments.author().to_owned());
585 +
                    view.enter();
586 +
                    self.mode = Mode::Hunk(Box::new(view));
587 +
                    self.restart_highlighter()?;
588 +
                }
589 +
                Err(message) => self.error = Some(message.replace('\n', " · ")),
590 +
            },
591 +
            WorkerOutput::Persisted(result) => {
592 +
                self.finish_persistence(*result)?;
511 593
            }
512 594
        }
595 +
        Ok(Update::Redraw)
596 +
    }
597 +
598 +
    /// Dispatches one input event, handling review keys before the viewer.
599 +
    fn handle_key(&mut self, event: Event<()>, area: Rect) -> Result<Control, Error> {
513 600
        match event {
514 601
            Event::Key(Key::Char('a')) => {
515 602
                if matches!(
516 603
                    self.current()?.viewer.state().focus,
517 604
                    Some(DiffFocus::Commit)
600 687
    fn select_commit(&mut self, index: usize) -> Result<(), Error> {
601 688
        if index != self.current {
602 689
            self.parked = None;
603 690
        }
604 691
        self.current = index;
605 -
606 -
        let newly_loaded = self.commits[index].loaded.is_none();
607 -
        self.current()?;
608 -
609 -
        if newly_loaded {
610 -
            // Project exact acceptance onto the freshly decoded hunks.
611 -
            self.reconcile_state();
612 -
        }
613 692
        self.mode = Mode::Diff;
614 -
        self.activate()?;
615 -
693 +
        if self.commits[index].loaded.is_some() {
694 +
            self.activate()?;
695 +
        } else {
696 +
            self.request_commit(index)?;
697 +
        }
616 698
        Ok(())
617 699
    }
618 700
619 701
    /// Routes one key while the commit-list tab is open.
620 702
    fn handle_commits_key(&mut self, event: Event<()>) -> Result<Control, Error> {
660 742
        }
661 743
    }
662 744
663 745
    /// Toggles acceptance of every hunk in one commit.
664 746
    fn toggle_commit_accepted(&mut self, index: usize) -> Result<(), Error> {
665 -
        let _ = self.sync_acceptance()?;
666 -
        if self.error.is_some() {
667 -
            return Ok(());
668 -
        }
669 -
        let loaded = self.load(index)?;
670 -
        let accepted = loaded.review.accepts_all(loaded.identities.keys().copied());
671 -
        let hunks = loaded
672 -
            .identities
747 +
        let identities = self.commits[index].identities()?;
748 +
        let accepted = !identities.is_empty()
749 +
            && identities
750 +
                .values()
751 +
                .all(|identity| self.brain.accepted.contains(identity));
752 +
        let hunks = identities
673 753
            .keys()
674 754
            .map(|hunk| (index, *hunk))
675 755
            .collect::<BTreeSet<_>>();
676 756
        if accepted {
677 757
            self.reject_hunks(hunks)?;
679 759
            self.accept_hunks(hunks)?;
680 760
        }
681 761
        Ok(())
682 762
    }
683 763
684 -
    /// Toggles the rejected state of one commit after pending persistence settles.
764 +
    /// Queues a toggle of one commit's rejected decision.
685 765
    fn toggle_commit_rejected(&mut self, index: usize) -> Result<(), Error> {
686 -
        let _ = self.sync_acceptance()?;
687 -
        if self.error.is_some() {
688 -
            return Ok(());
689 -
        }
690 766
        let commit = self.commits[index].commit.id;
691 -
        self.brain.toggle_commit_rejected(commit)?;
692 -
        self.reconcile_reviews()?;
693 -
        Ok(())
767 +
        self.persist_commit_decision(ReviewMutation::ToggleRejected { commit })
694 768
    }
695 769
696 -
    /// Toggles the dropped state of one commit after pending persistence settles.
770 +
    /// Queues a toggle of one commit's dropped decision.
697 771
    fn toggle_commit_dropped(&mut self, index: usize) -> Result<(), Error> {
698 -
        let _ = self.sync_acceptance()?;
699 -
        if self.error.is_some() {
700 -
            return Ok(());
701 -
        }
702 772
        let commit = self.commits[index].commit.id;
703 -
        self.brain.toggle_commit_dropped(commit)?;
704 -
        self.reconcile_reviews()?;
773 +
        self.persist_commit_decision(ReviewMutation::ToggleDropped { commit })
774 +
    }
775 +
776 +
    /// Starts persistence for a commit decision under the common pending state.
777 +
    fn persist_commit_decision(&mut self, mutation: ReviewMutation) -> Result<(), Error> {
778 +
        debug_assert!(self.pending.is_none());
779 +
        self.repository_worker
780 +
            .send(WorkerCommand::Mutate(mutation))
781 +
            .map_err(Error::Git)?;
782 +
        self.pending = Some(Pending::Decision);
783 +
        self.loading = Some("saving review");
705 784
        Ok(())
706 785
    }
707 786
708 787
    /// Toggles acceptance of the focused hunk.
709 788
    fn toggle_focused_hunk(&mut self, area: Rect) -> Result<(), Error> {
785 864
786 865
    /// Optimistically accepts the selected hunks and starts persistence.
787 866
    fn accept_hunks(&mut self, hunks: BTreeSet<HunkLocation>) -> Result<(), Error> {
788 867
        let identities = hunks
789 868
            .iter()
790 -
            .filter_map(|(index, hunk)| {
869 +
            .map(|(index, hunk)| {
791 870
                self.commits[*index]
792 -
                    .loaded
793 -
                    .as_ref()
794 -
                    .and_then(|loaded| loaded.identities.get(hunk))
871 +
                    .identities()?
872 +
                    .get(hunk)
795 873
                    .cloned()
874 +
                    .ok_or_else(|| Error::Git(format!("hunk {hunk:?} has no identity")))
796 875
            })
797 -
            .collect::<Vec<_>>();
876 +
            .collect::<Result<Vec<_>, Error>>()?;
798 877
799 878
        let mut accepted = self.brain.accepted.clone();
800 879
        accepted.extend(identities.iter().cloned());
801 880
802 881
        let mut undo = self.accepted.clone();
803 882
        undo.extend(hunks);
804 883
805 -
        self.persist_acceptance(accepted, undo, move |brain, patches| {
806 -
            brain.accept(identities, patches)
884 +
        self.persist_acceptance(accepted, undo, move |patches| ReviewMutation::Accept {
885 +
            identities,
886 +
            patches,
807 887
        })
808 888
    }
809 889
810 890
    /// Optimistically rejects the selected hunks and starts persistence.
811 891
    fn reject_hunks(&mut self, hunks: BTreeSet<HunkLocation>) -> Result<(), Error> {
812 892
        let identities = hunks
813 893
            .iter()
814 -
            .filter_map(|(index, hunk)| {
894 +
            .map(|(index, hunk)| {
815 895
                self.commits[*index]
816 -
                    .loaded
817 -
                    .as_ref()
818 -
                    .and_then(|loaded| loaded.identities.get(hunk))
896 +
                    .identities()?
897 +
                    .get(hunk)
819 898
                    .cloned()
899 +
                    .ok_or_else(|| Error::Git(format!("hunk {hunk:?} has no identity")))
820 900
            })
821 -
            .collect::<BTreeSet<_>>();
901 +
            .collect::<Result<BTreeSet<_>, Error>>()?;
822 902
823 903
        let mut accepted = self.brain.accepted.clone();
824 904
        accepted.retain(|identity| !identities.contains(identity));
825 905
826 906
        let mut undo = self.accepted.clone();
827 907
        undo.retain(|hunk| !hunks.contains(hunk));
828 908
829 -
        self.persist_acceptance(accepted, undo, move |brain, patches| {
830 -
            brain.reject(&identities, patches)
909 +
        self.persist_acceptance(accepted, undo, move |patches| ReviewMutation::Reject {
910 +
            identities,
911 +
            patches,
831 912
        })
832 913
    }
833 914
834 915
    /// Records automatic navigation for the pending rollback.
835 916
    fn record_navigation_rollback(
836 917
        &mut self,
837 918
        commit: usize,
838 919
        before: DiffState,
839 920
    ) -> Result<(), Error> {
840 921
        let after = self.load(commit)?.viewer.state().clone();
841 -
        if let Some(pending) = &mut self.pending {
922 +
        if let Some(Pending::Acceptance(pending)) = &mut self.pending {
842 923
            pending.navigation = Some(NavigationRollback {
843 924
                commit,
844 925
                before,
845 926
                after,
846 927
            });
851 932
    /// Shows optimistic state, prepares its projection, and starts persistence.
852 933
    fn persist_acceptance(
853 934
        &mut self,
854 935
        accepted: Accepted,
855 936
        undo: Vec<HunkLocation>,
856 -
        persist: impl FnOnce(&mut Brain, Vec<FilePatches>) -> Result<(), Error> + Send + 'static,
937 +
        mutation: impl FnOnce(Vec<FilePatches>) -> ReviewMutation,
857 938
    ) -> Result<(), Error> {
858 939
        debug_assert!(self.pending.is_none());
859 940
860 -
        let rollback = self.brain.accepted.clone();
861 -
        let mut brain = self.brain.clone();
941 +
        let rollback = self.brain.clone();
862 942
        self.brain.rollback(accepted);
863 -
864 943
        if let Err(error) = self.reconcile_reviews() {
865 -
            self.brain.rollback(rollback);
944 +
            self.brain = rollback;
866 945
            self.reconcile_state();
867 946
            return Err(error);
868 947
        }
869 948
870 -
        let mut patches = Vec::new();
871 -
        for slot in &self.commits {
872 -
            let Some(identities) = slot
873 -
                .identities
874 -
                .as_ref()
875 -
                .or_else(|| slot.loaded.as_ref().map(|loaded| &loaded.identities))
876 -
            else {
877 -
                self.brain.rollback(rollback);
878 -
                self.reconcile_reviews()?;
879 -
                return Err(Error::Git(
880 -
                    "commit slot has no cached identities".to_owned(),
881 -
                ));
882 -
            };
883 -
            let document = match slot.document() {
884 -
                Ok(document) => document,
885 -
                Err(error) => {
886 -
                    self.brain.rollback(rollback);
887 -
                    self.reconcile_reviews()?;
888 -
                    return Err(error);
889 -
                }
890 -
            };
891 -
            for file in &document.files {
892 -
                let hunks = file
893 -
                    .hunks
894 -
                    .iter()
895 -
                    .filter(|hunk| {
896 -
                        identities
897 -
                            .get(&hunk.id)
898 -
                            .is_some_and(|identity| self.brain.accepted.contains(identity))
899 -
                    })
900 -
                    .cloned()
901 -
                    .collect::<Vec<_>>();
902 -
                if !hunks.is_empty() {
903 -
                    let patch = match FilePatches::new(file, hunks) {
904 -
                        Ok(patch) => patch,
905 -
                        Err(error) => {
906 -
                            self.brain.rollback(rollback);
907 -
                            self.reconcile_reviews()?;
908 -
                            return Err(error);
909 -
                        }
910 -
                    };
911 -
                    patches.push(patch);
949 +
        let result = (|| -> Result<(), Error> {
950 +
            let mut patches = Vec::new();
951 +
            for slot in &self.commits {
952 +
                let identities = slot.identities()?;
953 +
                let document = slot.document()?;
954 +
                for file in &document.files {
955 +
                    let hunks = file
956 +
                        .hunks
957 +
                        .iter()
958 +
                        .filter(|hunk| {
959 +
                            identities
960 +
                                .get(&hunk.id)
961 +
                                .is_some_and(|identity| self.brain.accepted.contains(identity))
962 +
                        })
963 +
                        .cloned()
964 +
                        .collect::<Vec<_>>();
965 +
                    if !hunks.is_empty() {
966 +
                        let patch = FilePatches::new(file, hunks)?;
967 +
                        patches.push(patch);
968 +
                    }
912 969
                }
913 970
            }
914 -
        }
915 971
916 -
        let events = self.events_tx.clone();
917 -
        let worker = thread::spawn(move || {
918 -
            let result = persist(&mut brain, patches)
919 -
                .map(|()| brain)
920 -
                .map_err(|error| error.to_string());
921 -
            let _ = events.send(TerminalEvent::Persistence(thread::current().id()));
922 -
            result
923 -
        });
924 -
        self.pending = Some(PendingAcceptance {
925 -
            rollback,
972 +
            self.repository_worker
973 +
                .send(WorkerCommand::Mutate(mutation(patches)))
974 +
                .map_err(Error::Git)
975 +
        })();
976 +
        if let Err(error) = result {
977 +
            self.brain = rollback;
978 +
            self.reconcile_reviews()?;
979 +
            return Err(error);
980 +
        }
981 +
        self.loading = Some("saving review");
982 +
        self.pending = Some(Pending::Acceptance(AcceptancePending {
983 +
            rollback: Box::new(rollback),
926 984
            undo,
927 985
            navigation: None,
928 -
            worker,
929 -
        });
986 +
        }));
930 987
        Ok(())
931 988
    }
932 989
933 -
    /// Returns whether a failed update changed visible state through rollback.
934 -
    fn sync_acceptance(&mut self) -> Result<ViewChange, Error> {
990 +
    /// Finalizes one persisted state mutation or restores its optimistic state.
991 +
    fn finish_persistence(&mut self, result: Result<Option<Brain>, String>) -> Result<(), Error> {
935 992
        let Some(pending) = self.pending.take() else {
936 -
            return Ok(ViewChange::Unchanged);
993 +
            return Err(Error::Git(
994 +
                "persistence completed without pending state".to_owned(),
995 +
            ));
937 996
        };
938 -
        let PendingAcceptance {
939 -
            rollback,
940 -
            undo,
941 -
            navigation,
942 -
            worker,
943 -
        } = pending;
944 -
        let result = worker
945 -
            .join()
946 -
            .unwrap_or_else(|_| Err("acceptance update stopped unexpectedly".to_owned()));
947 -
948 -
        match result {
949 -
            Ok(brain) => {
950 -
                self.brain = brain;
951 -
                self.accepted = undo;
952 -
                Ok(ViewChange::Unchanged)
953 -
            }
997 +
        let committed = match result {
998 +
            Ok(committed) => committed,
954 999
            Err(message) => {
955 -
                let navigation = navigation.and_then(|navigation| {
956 -
                    let loaded = self.commits.get(navigation.commit)?.loaded.as_ref()?;
957 -
                    (loaded.viewer.state() == &navigation.after)
958 -
                        .then_some((navigation.commit, navigation.before))
959 -
                });
960 -
                self.brain.rollback(rollback);
961 -
                self.reconcile_reviews()?;
962 -
963 -
                if let Some((commit, state)) = navigation {
964 -
                    self.load(commit)?.viewer.set_state(state);
1000 +
                match pending {
1001 +
                    Pending::Acceptance(pending) => {
1002 +
                        let navigation = pending.navigation.and_then(|navigation| {
1003 +
                            let loaded = self.commits.get(navigation.commit)?.loaded.as_ref()?;
1004 +
                            (loaded.viewer.state() == &navigation.after)
1005 +
                                .then_some((navigation.commit, navigation.before))
1006 +
                        });
1007 +
                        self.brain = *pending.rollback;
1008 +
                        self.reconcile_reviews()?;
1009 +
                        if let Some((commit, state)) = navigation {
1010 +
                            self.load(commit)?.viewer.set_state(state);
1011 +
                        }
1012 +
                    }
1013 +
                    Pending::Decision => {}
1014 +
                    Pending::Comments(rollback) => {
1015 +
                        self.comments = rollback.store;
1016 +
                        if let Some(loaded) = &mut self.commits[rollback.commit].loaded {
1017 +
                            loaded.comments = rollback.comments;
1018 +
                            loaded.refresh_decorations();
1019 +
                        }
1020 +
                    }
965 1021
                }
966 1022
                self.error = Some(message.replace('\n', " · "));
967 -
                Ok(ViewChange::Changed)
1023 +
                return Ok(());
1024 +
            }
1025 +
        };
1026 +
        match pending {
1027 +
            Pending::Acceptance(pending) => {
1028 +
                let Some(brain) = committed else {
1029 +
                    return Err(Error::Git(
1030 +
                        "review persistence completed without review state".to_owned(),
1031 +
                    ));
1032 +
                };
1033 +
                self.brain = brain;
1034 +
                self.accepted = pending.undo;
1035 +
            }
1036 +
            Pending::Decision => {
1037 +
                let Some(brain) = committed else {
1038 +
                    return Err(Error::Git(
1039 +
                        "decision persistence completed without review state".to_owned(),
1040 +
                    ));
1041 +
                };
1042 +
                self.brain = brain;
1043 +
                self.reconcile_reviews()?;
1044 +
            }
1045 +
            Pending::Comments(_) => {
1046 +
                debug_assert!(committed.is_none());
968 1047
            }
969 1048
        }
1049 +
        Ok(())
970 1050
    }
971 1051
972 1052
    /// Opens the hunk view for the focused hunk to author a comment.
973 1053
    fn enter_hunk_view(&mut self, area: Rect) -> Result<(), Error> {
974 1054
        if !matches!(
999 1079
            Some((file, focused))
1000 1080
        }) else {
1001 1081
            return Ok(());
1002 1082
        };
1003 1083
        let document = DiffDocument::for_hunks(file, [focused.clone()]);
1004 -
        let mut viewer = DiffViewer::new(document, options);
1005 -
        viewer.load_file_sources(|oid| self.brain.read_blob(oid))?;
1006 -
1007 -
        let mut view = HunkView::new(hunk, viewer, self.comments.author().to_owned());
1008 -
        view.enter();
1009 -
        self.mode = Mode::Hunk(Box::new(view));
1010 -
        self.restart_highlighter()?;
1084 +
        let viewer = DiffViewer::new(document, options);
1085 +
        self.repository_worker
1086 +
            .send(WorkerCommand::LoadSources {
1087 +
                viewer: Box::new(viewer),
1088 +
                hunk,
1089 +
            })
1090 +
            .map_err(Error::Git)?;
1091 +
        self.loading = Some("loading file");
1011 1092
1012 1093
        Ok(())
1013 1094
    }
1014 1095
1015 1096
    /// Caches global progress and remaining statistics without loading commits.
1018 1099
            self.reconcile_state();
1019 1100
            let status_inputs = self
1020 1101
                .commits
1021 1102
                .iter()
1022 1103
                .map(|slot| {
1023 -
                    let identities = slot
1024 -
                        .identities
1025 -
                        .as_ref()
1026 -
                        .or_else(|| slot.loaded.as_ref().map(|loaded| &loaded.identities));
1027 -
                    let identities = identities.ok_or_else(|| {
1028 -
                        Error::Git("commit slot has no cached identities".to_owned())
1029 -
                    })?;
1104 +
                    let identities = slot.identities()?;
1030 1105
                    Ok((slot.commit.id, slot.document()?, identities))
1031 1106
                })
1032 1107
                .collect::<Result<Vec<_>, Error>>()?;
1033 1108
            let status = HistoryStatus::for_commits(&self.brain, &status_inputs);
1034 1109
            for slot in &mut self.commits {
1175 1250
        };
1176 1251
        let Some(loaded) = &mut self.commits[self.current].loaded else {
1177 1252
            return Ok(());
1178 1253
        };
1179 1254
        let added = matches!(target, CommentEdit::Add);
1180 -
        let brain = &self.brain;
1181 -
        let changed = loaded.comments.transact(
1182 -
            &mut self.comments,
1183 -
            |comments, store| match target {
1184 -
                CommentEdit::Add => comments.author(store, hunk, body),
1185 -
                CommentEdit::Edit(id) => comments.edit(store, hunk, &id, body),
1186 -
            },
1187 -
            |encoded| brain.write_comments(encoded),
1188 -
        )?;
1189 -
        if changed {
1255 +
        let rollback = CommentRollback {
1256 +
            commit: self.current,
1257 +
            store: self.comments.clone(),
1258 +
            comments: loaded.comments.clone(),
1259 +
        };
1260 +
        let encoded =
1261 +
            loaded
1262 +
                .comments
1263 +
                .transact(&mut self.comments, |comments, store| match target {
1264 +
                    CommentEdit::Add => comments.author(store, hunk, body),
1265 +
                    CommentEdit::Edit(id) => comments.edit(store, hunk, &id, body),
1266 +
                });
1267 +
        if let Some(encoded) = encoded {
1268 +
            if let Err(message) = self
1269 +
                .repository_worker
1270 +
                .send(WorkerCommand::WriteComments { encoded })
1271 +
            {
1272 +
                self.comments = rollback.store;
1273 +
                loaded.comments = rollback.comments;
1274 +
                loaded.refresh_decorations();
1275 +
                return Err(Error::Git(message));
1276 +
            }
1190 1277
            loaded.refresh_decorations();
1191 1278
            if added {
1192 1279
                let comments = loaded.comments.for_hunk(hunk).len();
1193 1280
                view.select_comment(comments.saturating_sub(1));
1194 1281
            }
1282 +
            self.pending = Some(Pending::Comments(rollback));
1283 +
            self.loading = Some("saving comment");
1195 1284
        }
1196 1285
        view.cancel_edit();
1197 1286
        Ok(())
1198 1287
    }
1199 1288
1272 1361
        let Some(comment) = comments.get(view.selected()) else {
1273 1362
            return Ok(());
1274 1363
        };
1275 1364
        let id = comment.id.clone();
1276 1365
        let hunk = view.hunk;
1277 -
        let brain = &self.brain;
1278 -
        if loaded.comments.transact(
1279 -
            &mut self.comments,
1280 -
            |comments, store| comments.delete(store, hunk, &id),
1281 -
            |encoded| brain.write_comments(encoded),
1282 -
        )? {
1366 +
        let rollback = CommentRollback {
1367 +
            commit: self.current,
1368 +
            store: self.comments.clone(),
1369 +
            comments: loaded.comments.clone(),
1370 +
        };
1371 +
        let encoded = loaded
1372 +
            .comments
1373 +
            .transact(&mut self.comments, |comments, store| {
1374 +
                comments.delete(store, hunk, &id)
1375 +
            });
1376 +
        if let Some(encoded) = encoded {
1377 +
            if let Err(message) = self
1378 +
                .repository_worker
1379 +
                .send(WorkerCommand::WriteComments { encoded })
1380 +
            {
1381 +
                self.comments = rollback.store;
1382 +
                loaded.comments = rollback.comments;
1383 +
                loaded.refresh_decorations();
1384 +
                return Err(Error::Git(message));
1385 +
            }
1283 1386
            loaded.refresh_decorations();
1284 1387
            let comments = loaded.comments.for_hunk(hunk).len();
1285 1388
            view.clamp_selection(comments);
1389 +
            self.pending = Some(Pending::Comments(rollback));
1390 +
            self.loading = Some("saving comment");
1286 1391
        }
1287 1392
        Ok(())
1288 1393
    }
1289 1394
1290 1395
    /// Applies current visibility and starts workers for the active commit.
1441 1546
        let highlighter = if let Mode::Hunk(view) = &self.mode {
1442 1547
            spawn_highlighter(view.viewer.document(), None, move |output| {
1443 1548
                let _ = tx.send(TerminalEvent::Highlight(generation, output));
1444 1549
            })
1445 1550
        } else {
1446 -
            let repo = Some(self.backend.repo(&self.commits[self.current].commit));
1551 +
            let repo = Some(self.repositories[self.current].clone());
1447 1552
            let loaded = self.current()?;
1448 1553
            spawn_highlighter(loaded.viewer.document(), repo, move |output| {
1449 1554
                let _ = tx.send(TerminalEvent::Highlight(generation, output));
1450 1555
            })
1451 1556
        };
1571 1676
                progress,
1572 1677
                stats,
1573 1678
                palette: self.options.diff_palette,
1574 1679
                visibility,
1575 1680
                error: self.error.clone(),
1681 +
                loading: self.loading.map(|operation| (operation, self.spinner)),
1576 1682
            },
1577 1683
            actions: self.action_context(),
1578 1684
        }
1579 1685
    }
1580 1686
a.rs +0 -0
crates/brain/src/session/commit.rs +8 -0
41 41
            .as_ref()
42 42
            .or_else(|| self.loaded.as_ref().map(|loaded| &loaded.document))
43 43
            .ok_or_else(|| Error::Git("commit slot has no diff document".to_owned()))
44 44
    }
45 45
46 +
    /// Returns exact hunk identities in either slot state.
47 +
    pub(super) fn identities(&self) -> Result<&BTreeMap<HunkId, AcceptedHunk>, Error> {
48 +
        self.identities
49 +
            .as_ref()
50 +
            .or_else(|| self.loaded.as_ref().map(|loaded| &loaded.identities))
51 +
            .ok_or_else(|| Error::Git("commit slot has no cached identities".to_owned()))
52 +
    }
53 +
46 54
    /// Returns the remaining diff statistics in either slot state.
47 55
    pub(super) fn remaining_stats(&self) -> DiffStat {
48 56
        self.loaded
49 57
            .as_ref()
50 58
            .map_or(self.remaining_stats, CommitReview::remaining_stats)
a.rs +0 -0
crates/brain/src/session/event.rs +4 -2
7 7
use rustik_diff::{ContextChange, HighlightOutput};
8 8
use rustik_tui::event::Modifiers;
9 9
use rustik_tui::{Control, Event, Key, Mouse, MouseButton};
10 10
use rustik_tui_termion as tui_termion;
11 11
12 +
use super::worker::Output;
13 +
12 14
/// Whether a context refetch is in flight.
13 15
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
14 16
pub(super) enum ContextFetch {
15 17
    /// No context request is currently running.
16 18
    #[default]
109 111
pub(super) enum TerminalEvent {
110 112
    /// Terminal input event.
111 113
    Input(io::Result<Event<()>>),
112 114
    /// Background highlighter output, tagged with its generation.
113 115
    Highlight(u64, HighlightOutput),
114 -
    /// Completion signal from one acceptance persistence thread.
115 -
    Persistence(thread::ThreadId),
116 +
    /// Completion from the serialized repository worker.
117 +
    Worker(Box<Output>),
116 118
}
117 119
118 120
impl TerminalEvent {
119 121
    /// Receives one channel event, propagating input failures.
120 122
    pub(super) fn receive<E>(event: Result<Self, E>) -> io::Result<Option<Self>> {
crates/brain/src/session/status.rs +17 -0
64 64
const FULL_FILE_MODE_ICON: &str = "↕";
65 65
/// Separator shown between footer status segments: ·.
66 66
const FOOTER_SEPARATOR: &str = " · ";
67 67
/// Marker used when footer text truncates: ….
68 68
const FOOTER_ELLIPSIS: &str = "…";
69 +
/// Frames used by the repository-operation status spinner.
70 +
const SPINNER_FRAMES: &[char] = &['|', '/', '-', '\\'];
69 71
/// Separator shown between plain action hints.
70 72
const ACTION_SEPARATOR: &str = " · ";
71 73
/// Key label shown for Tab: ⭾.
72 74
const TAB_KEY: &str = "⭾";
73 75
/// Key label shown for Return: ⮐.
155 157
    pub(super) palette: DiffPalette,
156 158
    /// Visibility modes for the active review view.
157 159
    pub(super) visibility: Visibility,
158 160
    /// Most recent recoverable session error.
159 161
    pub(super) error: Option<String>,
162 +
    /// Active repository operation and animation frame.
163 +
    pub(super) loading: Option<(&'static str, usize)>,
160 164
}
161 165
162 166
impl Widget for Status {
163 167
    fn size(&self, parent: Constraint) -> Size {
164 168
        Size::new(parent.max.cols, STATUS_ROWS).constrain(parent)
183 187
    fn bar(&self, cols: usize) -> HStack<'_> {
184 188
        if let Some(error) = &self.error {
185 189
            return HStack::default()
186 190
                .child(recoverable_error(error, FOOTER_VALUE_FG, FOOTER_BG).truncated(cols, ""));
187 191
        }
192 +
        if let Some((operation, frame)) = self.loading {
193 +
            let spinner = SPINNER_FRAMES[frame % SPINNER_FRAMES.len()];
194 +
            return HStack::default().child(
195 +
                Line::blank()
196 +
                    .item(Label::from_char(spinner).fg(FOOTER_VALUE_FG))
197 +
                    .item(Label::space())
198 +
                    .item(Label::new(operation).fg(FOOTER_VALUE_FG))
199 +
                    .style(Style::default().bg(FOOTER_BG))
200 +
                    .truncated(cols, FOOTER_ELLIPSIS),
201 +
            );
202 +
        }
188 203
        let right = self.right_status();
189 204
        let left_width = cols
190 205
            .saturating_sub(right.width())
191 206
            .saturating_sub(STATUS_RIGHT_PADDING)
192 207
            .saturating_sub(1);
626 641
                progress: ReviewProgress::default(),
627 642
                stats: DiffStat::default(),
628 643
                palette: DiffPalette::default(),
629 644
                visibility: Visibility::default(),
630 645
                error: Some("patch does not apply".to_owned()),
646 +
                loading: None,
631 647
            },
632 648
            actions: ActionContext::Commit,
633 649
        };
634 650
        let mut buffer = Buffer::empty(Rect::new(0, 0, 40, 2));
635 651
654 670
            },
655 671
            stats: DiffStat::default(),
656 672
            palette: DiffPalette::default(),
657 673
            visibility: Visibility::default(),
658 674
            error: None,
675 +
            loading: None,
659 676
        };
660 677
        let mut buffer = Buffer::empty(Rect::new(0, 0, 80, 1));
661 678
662 679
        status.render(buffer.area(), &mut buffer);
663 680
        let rendered = (0..buffer.area().cols)
crates/brain/src/session/worker.rs added +233 -0
1 +
//! Serialized repository I/O for the interactive session.
2 +
//!
3 +
//! All repository and filesystem I/O initiated by the UI must be represented by
4 +
//! a [`Command`] and executed here. Keeping the backend and writable review state
5 +
//! in this worker makes blocking the terminal event loop difficult by construction.
6 +
7 +
use std::collections::{BTreeMap, BTreeSet};
8 +
use std::sync::mpsc::{self, Sender};
9 +
use std::thread;
10 +
11 +
use rustik_diff::{DiffDocument, DiffOptions, DiffViewer, HunkId};
12 +
use rustik_repo::Oid;
13 +
14 +
use crate::backend::{AcceptedHunk, Backend, Brain, Commit, FilePatches};
15 +
use crate::comments::ReviewComments;
16 +
17 +
use super::commit::{CommitReview, CommitSlot};
18 +
use super::event::TerminalEvent;
19 +
use super::{HistoryStatus, reviewed_slots};
20 +
21 +
/// One review-state mutation executed by the repository worker.
22 +
pub(super) enum ReviewMutation {
23 +
    /// Accepts exact hunk identities and projects their patches.
24 +
    Accept {
25 +
        /// Identities being accepted.
26 +
        identities: Vec<AcceptedHunk>,
27 +
        /// File patches used to update the projected tree.
28 +
        patches: Vec<FilePatches>,
29 +
    },
30 +
    /// Rejects exact hunk identities and rebuilds their projected files.
31 +
    Reject {
32 +
        /// Identities being rejected.
33 +
        identities: BTreeSet<AcceptedHunk>,
34 +
        /// File patches used to update the projected tree.
35 +
        patches: Vec<FilePatches>,
36 +
    },
37 +
    /// Toggles one commit's rejected decision.
38 +
    ToggleRejected {
39 +
        /// Commit whose decision changes.
40 +
        commit: Oid,
41 +
    },
42 +
    /// Toggles one commit's dropped decision.
43 +
    ToggleDropped {
44 +
        /// Commit whose decision changes.
45 +
        commit: Oid,
46 +
    },
47 +
}
48 +
49 +
/// Inputs needed to construct one commit viewer.
50 +
pub(super) struct LoadCommit {
51 +
    /// Session commit index.
52 +
    pub(super) index: usize,
53 +
    /// Commit metadata.
54 +
    pub(super) commit: Commit,
55 +
    /// Previously cached split document.
56 +
    pub(super) document: Option<DiffDocument>,
57 +
    /// Previously cached exact hunk identities.
58 +
    pub(super) identities: Option<BTreeMap<HunkId, AcceptedHunk>>,
59 +
    /// Viewer construction options.
60 +
    pub(super) options: DiffOptions,
61 +
    /// Review comments used to decorate the viewer.
62 +
    pub(super) comments: ReviewComments,
63 +
}
64 +
65 +
/// Blocking operation sent from the UI to the repository worker.
66 +
pub(super) enum Command {
67 +
    /// Loads and constructs one commit viewer.
68 +
    LoadCommit(Box<LoadCommit>),
69 +
    /// Loads history documents and aggregate status.
70 +
    LoadHistory {
71 +
        /// Commits to load, oldest first.
72 +
        commits: Vec<Commit>,
73 +
    },
74 +
    /// Loads file sources into a focused hunk viewer.
75 +
    LoadSources {
76 +
        /// Viewer awaiting file contents.
77 +
        viewer: Box<DiffViewer>,
78 +
        /// Hunk that owns the viewer.
79 +
        hunk: HunkId,
80 +
    },
81 +
    /// Persists one review-state mutation.
82 +
    Mutate(ReviewMutation),
83 +
    /// Persists the complete encoded comment store.
84 +
    WriteComments {
85 +
        /// Encoded JSONL comment data.
86 +
        encoded: String,
87 +
    },
88 +
    /// Stops the worker after all preceding commands.
89 +
    Shutdown,
90 +
}
91 +
92 +
/// Typed result returned to the terminal event loop.
93 +
pub(super) enum Output {
94 +
    /// One commit viewer finished loading.
95 +
    CommitLoaded {
96 +
        /// Session commit index.
97 +
        index: usize,
98 +
        /// Loaded viewer or its user-facing failure.
99 +
        result: Box<Result<CommitReview, String>>,
100 +
    },
101 +
    /// History state finished loading.
102 +
    HistoryLoaded(Box<Result<(Vec<CommitSlot>, HistoryStatus), String>>),
103 +
    /// Focused hunk sources finished loading.
104 +
    SourcesLoaded {
105 +
        /// Hunk that owns the viewer.
106 +
        hunk: HunkId,
107 +
        /// Populated viewer or its user-facing failure.
108 +
        result: Box<Result<DiffViewer, String>>,
109 +
    },
110 +
    /// A state mutation finished persisting.
111 +
    Persisted(Box<Result<Option<Brain>, String>>),
112 +
}
113 +
114 +
/// Handle used by the UI to enqueue repository commands.
115 +
pub(super) struct Worker {
116 +
    /// Command sender owned by the terminal session.
117 +
    commands: Sender<Command>,
118 +
    /// Worker thread joined only after queued commands have completed.
119 +
    thread: Option<thread::JoinHandle<()>>,
120 +
}
121 +
122 +
impl Worker {
123 +
    /// Starts the serialized repository worker.
124 +
    pub(super) fn spawn(
125 +
        backend: Box<dyn Backend>,
126 +
        brain: Brain,
127 +
        events: Sender<TerminalEvent>,
128 +
    ) -> Self {
129 +
        let (commands, receiver) = mpsc::channel();
130 +
        let thread = thread::spawn(move || {
131 +
            let mut brain = brain;
132 +
            while let Ok(command) = receiver.recv() {
133 +
                let output = match command {
134 +
                    Command::LoadCommit(load) => {
135 +
                        let LoadCommit {
136 +
                            index,
137 +
                            commit,
138 +
                            document,
139 +
                            identities,
140 +
                            options,
141 +
                            comments,
142 +
                        } = *load;
143 +
                        let result = (|| {
144 +
                            let document = match document {
145 +
                                Some(document) => document,
146 +
                                None => backend.diff_document(commit.id)?.split_hunks(),
147 +
                            };
148 +
                            CommitReview::load(
149 +
                                &commit, document, identities, options, &brain, &comments,
150 +
                            )
151 +
                        })()
152 +
                        .map_err(|error| error.to_string());
153 +
                        Output::CommitLoaded {
154 +
                            index,
155 +
                            result: Box::new(result),
156 +
                        }
157 +
                    }
158 +
                    Command::LoadHistory { commits } => {
159 +
                        let result = reviewed_slots(commits, &*backend, &brain)
160 +
                            .map_err(|error| error.to_string());
161 +
                        Output::HistoryLoaded(Box::new(result))
162 +
                    }
163 +
                    Command::LoadSources { viewer, hunk } => {
164 +
                        let mut viewer = *viewer;
165 +
                        let result = viewer
166 +
                            .load_file_sources(|oid| brain.read_blob(oid))
167 +
                            .map(|()| viewer)
168 +
                            .map_err(|error| error.to_string());
169 +
                        Output::SourcesLoaded {
170 +
                            hunk,
171 +
                            result: Box::new(result),
172 +
                        }
173 +
                    }
174 +
                    Command::Mutate(mutation) => {
175 +
                        let result = match mutation {
176 +
                            ReviewMutation::Accept {
177 +
                                identities,
178 +
                                patches,
179 +
                            } => brain.accept(identities, patches),
180 +
                            ReviewMutation::Reject {
181 +
                                identities,
182 +
                                patches,
183 +
                            } => brain.reject(&identities, patches),
184 +
                            ReviewMutation::ToggleRejected { commit } => {
185 +
                                brain.toggle_commit_rejected(commit)
186 +
                            }
187 +
                            ReviewMutation::ToggleDropped { commit } => {
188 +
                                brain.toggle_commit_dropped(commit)
189 +
                            }
190 +
                        }
191 +
                        .map(|()| Some(brain.clone()))
192 +
                        .map_err(|error| error.to_string());
193 +
                        Output::Persisted(Box::new(result))
194 +
                    }
195 +
                    Command::WriteComments { encoded } => {
196 +
                        let result = brain
197 +
                            .write_comments(&encoded)
198 +
                            .map(|()| None)
199 +
                            .map_err(|error| error.to_string());
200 +
                        Output::Persisted(Box::new(result))
201 +
                    }
202 +
                    Command::Shutdown => break,
203 +
                };
204 +
                if events
205 +
                    .send(TerminalEvent::Worker(Box::new(output)))
206 +
                    .is_err()
207 +
                {
208 +
                    break;
209 +
                }
210 +
            }
211 +
        });
212 +
        Self {
213 +
            commands,
214 +
            thread: Some(thread),
215 +
        }
216 +
    }
217 +
218 +
    /// Enqueues one blocking operation without waiting for it.
219 +
    pub(super) fn send(&self, command: Command) -> Result<(), String> {
220 +
        self.commands
221 +
            .send(command)
222 +
            .map_err(|_| "repository worker stopped unexpectedly".to_owned())
223 +
    }
224 +
}
225 +
226 +
impl Drop for Worker {
227 +
    fn drop(&mut self) {
228 +
        let _ = self.commands.send(Command::Shutdown);
229 +
        if let Some(thread) = self.thread.take() {
230 +
            let _ = thread.join();
231 +
        }
232 +
    }
233 +
}