Section 20 of 25

Case study: Quayside

Contents

Quayside is a fictional desktop application, invented for this document. It is loosely modelled on the kind of software we build, but every name, number and file below is made up. Quayside records calls, transcribes them on the device, writes a summary with a local or a cloud model, runs follow-up tasks with coding agents, syncs action items to a shared team board, and has a phone companion that can watch a recording and send a note into it.

It has been built for two years by a small team in a hurry, and it works. It is also a textbook of everything section 1 described.

20.1. Before

src-tauri/src/
  main.rs                 40 lines
  lib.rs                  2,300 lines   setup, 148 commands, emit helpers, menu
  state.rs                AppState with 41 fields
  handlers.rs             31,000 lines  "all the commands"
  handlers/
    recording.rs          6,800 lines
    sync.rs               4,100 lines
    agents.rs             9,700 lines
  engine/
    recorder.rs           imports tauri::AppHandle to emit levels
    transcriber.rs        imports tauri::AppHandle to emit words
  db.rs                   opens SQLite connections in 9 places
  utils.rs                6,400 lines
  companion/              phone hub: crypto, pairing, and AppState everywhere
windowlib.rs · 2.3khandlers.rs · 31kAppState · 41engine/db.rs · 9 × openstatic × 12utils.rs · 6.4k

The measurement from step 1 of the migration:

What Value
Rust lines (without tests) ~78,000
Files that use tauri:: 37 of 112
#[tauri::command] functions 148, in 4 files
Fields of AppState 41, of which 14 are Mutex<…> or atomics
static with state 12
Places that open a writing SQLite connection 9
Files with #[cfg(target_os = …)] 23
Variants of start_recording_* 7
Time to run the domain tests they need a window, so nobody runs them

20.2. Symptoms in the code

The application state, 11 of its 41 fields:

pub struct AppState {
    pub db_path: PathBuf,
    pub recording: Mutex<Option<RecordingSession>>,
    pub recording_cancel: AtomicBool,
    pub level_task: Mutex<Option<JoinHandle<()>>>,
    pub transcribing: Mutex<HashMap<String, CancellationToken>>,
    pub summarizing: Mutex<HashMap<String, CancellationToken>>,
    pub agent_runs: Mutex<HashMap<String, AgentRun>>,
    pub agent_slots: Mutex<usize>,
    pub sync_in_flight: AtomicBool,
    pub companion: Mutex<Option<CompanionHub>>,
    pub model_prices: Mutex<Option<(Instant, PriceList)>>,
}

A stop that leaks between recordings. The user presses Stop, then quickly starts a new recording. The old recording's loop has not yet read the flag; the new recording resets nothing; the next check of recording_cancel stops the new recording:

static RECORDING_CANCEL: AtomicBool = AtomicBool::new(false);

#[tauri::command]
fn stop_recording() {
    RECORDING_CANCEL.store(true, Ordering::SeqCst);
}

The domain talks to the window directly, so it cannot be tested without one:

pub async fn transcribe(app: AppHandle, file: PathBuf) -> Result<(), String> {
    let mut words = whisper::stream(&file)?;
    while let Some(word) = words.next().await {
        app.emit("transcript-word", &word).map_err(|e| e.to_string())?;
    }
    Ok(())
}

Variants multiply:

pub async fn start_recording(…)
pub async fn start_recording_with_limit(…)
pub async fn start_recording_with_limit_and_device(…)
pub async fn start_recording_for_meeting(…)
pub async fn start_recording_for_meeting_with_limit(…)
pub async fn start_recording_from_companion(…)
pub async fn start_recording_with_test_hook(…)

And the operating system is everywhere:

#[cfg(target_os = "macos")]
fn reveal(path: &Path) {
    let _ = Command::new("sh").arg("-c").arg(format!("open -R '{}'", path.display())).spawn();
}

That last one is also a shell injection waiting for a file name with a quote in it.

20.3. The migration, step by step

Step 2: invert dependencies. The transcriber stops taking an AppHandle. It writes words into a bounded channel that core owns; app pumps the channel into the window. The upload code stops reading AppState and receives the two values it needs as arguments.

pub async fn transcribe(file: &Path, words: WordSink) -> Result<Outcome<Transcript>, TranscribeError> {
    let mut stream = drivers::whisper::stream(file).await?;
    let mut transcript = Transcript::default();
    while let Some(word) = stream.next().await {
        transcript.push(word.clone());
        if words.send(word) == Sent::Closed {
            return Ok(Outcome::Cancelled);
        }
    }
    Ok(Outcome::Done(transcript))
}

Step 3: split app and core. A workspace with quayside-core (no tauri) and the existing src-tauri as app. lib.rs in the app keeps pub use quayside_core::{…}; so every old path still compiles. Proof: planting use tauri::Manager; in core fails to compile.

Step 4: kit, store, drivers. The nine SQLite openings collapse into one writer in quayside-store. Recorder, transcriber, model clients and git go to quayside-drivers. The 23 files with #[cfg] become one platform/ folder with unix.rs, macos.rs and unsupported.rs, and reveal becomes a contract:

pub fn reveal_path(path: &Path) -> Result<(), PlatformError> {
    let status = Command::new("/usr/bin/open").arg("-R").arg(path).status()?;
    status.success().then_some(()).ok_or(PlatformError::Refused("open -R"))
}

No shell, no quoting, no injection.

Step 5: slices. handlers.rs and utils.rs are taken apart into slices, smallest first:

settings → device → llm → summary → transcript → board → companion → agent → recording

Step 6: kit::Jobs. transcribing and summarizing (two maps with cancellation tokens) become one Jobs<TranscriptId> inside the transcript service and one Jobs<SummaryId> inside the summary service.

Step 7: actors. Three pieces of state pass the test from 9.1: the recording, the agent runs and the board sync. The recording goes first, with update tests written against today's behaviour. The AtomicBool disappears; Stop now carries the generation of the recording it means, and the leak from 20.2 becomes a one-line test that stays green forever. The seven start_recording_* functions become one:

pub struct StartRecording {
    pub title: String,
    pub device: Option<DeviceId>,
    pub meeting: Option<MeetingId>,
    pub limit: Option<Duration>,
    pub origin: Origin,
}

Step 8: checks. Each check from section 16 switches on with its baseline. Most baselines are already empty, because the steps above removed the violations.

20.4. After

Cargo.toml                       [workspace]
crates/
  quayside-kit/                  paths, ids, durable_file, jobs, logging
  quayside-store/                writer, schema, migrations
  quayside-drivers/
    src/
      whisper.rs  recorder.rs  models.rs  git.rs
      platform/   mod.rs  unix.rs  macos.rs  unsupported.rs
  quayside-core/
    src/
      recording/  mod.rs model.rs logic.rs service.rs actor/
      transcript/ mod.rs model.rs logic.rs store.rs service.rs
      summary/    mod.rs model.rs service.rs
      agent/      mod.rs model.rs logic.rs store.rs service.rs actor/
      board/      mod.rs model.rs logic.rs store.rs service.rs actor/
      companion/  mod.rs model.rs logic.rs store.rs service.rs
      device/  llm/  settings/  guard/
src-tauri/
  src/
    main.rs lib.rs state.rs error.rs platform.rs
    recording/  mod.rs commands.rs dto.rs events.rs
    transcript/ mod.rs commands.rs dto.rs events.rs
    …
    doors/companion/

A command after the migration:

#[tauri::command]
pub async fn recording_stop(
    state: State<'_, AppState>,
    generation: u64,
) -> Result<(), IpcError> {
    state.recordings.send(recording::Msg::Stop { generation }).await?;
    Ok(())
}

The same measurement, repeated:

What Before After
Files that use tauri:: 37 12, all in src-tauri
Longest command 140 lines 9 lines
Fields of AppState 41 9
static with state 12 0
Writing SQLite connections 9 places 1
Files with an operating-system #[cfg] 23 3, all in platform/
Variants of start_recording_* 7 1
Domain tests needed a window run in a few seconds, no window
Compiles for Linux and Windows (except app) no yes, checked in CI

These numbers are illustrative. The shape of the change is what matters: every row moved in the direction of one owner, one place and one rule.