hex/crates/router
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Dax cdb96f585e
capture: keep all audio in long captures (#1795) (#1894)
* capture: stream audio to disk so long captures keep all of it

A capture's timeline now writes 16 kHz mono PCM16 to its bundle's
audio.wav as it records, with the leading offset and gaps as silence, so
memory stays flat and the 20-minute drop is gone. An 8-hour guard bounds
disk use only; past it the rest is one recorded gap.

A finished capture is transcribed from the WAV in 30 s pieces, the
reader hex transcribe already used (lifted to transcription/pieces.rs),
and each piece's words move onto the capture clock. The Parakeet, Apple
(path-based), and GGUF paths keep every word without holding the
session. The pipeline never rewrites a streamed audio.wav from empty
samples, an iPhone narration is read back where it must be re-based,
and a cancelled capture closes and removes its file.

* capture: say where a capture's audio stopped

A streamed capture keeps all of its audio, but the 8-hour disk guard (or
a failed audio write) still stops it early, and only the process log
said so. The timeline now carries the stop point onto RecordedAudio,
the bundle stores it as audioStoppedAtMs (serde default, so old bundles
load unchanged), and three places say it plainly: summary.md, `hex
capture show`, and `hex capture status`.

The guard records its point at a 1 s test limit, and the summary line is
tested at 12:34 and 8:00:00 so both clock shapes are covered.

* capture: fill the replay's stop point from its bundle

The 15 s replay builds Written too, on macOS only, so the new field
broke the macOS clippy job while Linux never compiled that function.

* capture: keep a recording out of recovery until it stops

Review fixes for the streamed timeline.

A capture now streams to `audio.wav.partial` and renames it to `audio.wav`
in `Timeline::finish`, so a bundle with a movie and an in-progress audio
file is never mistaken for a capture whose build never ran (recover's
orphan rule, Scrawl.app's `scrawl recover`) and retention cleans a crashed
one like any other bundle. Cancel and discard remove the partial; a failed
publish reads it back into memory rather than pointing at a missing file.

Also: a write failure's stop point is the last sample that reached the
file, not the end of the failed chunk; a trim failure counts every written
sample; the capture's words keep one running frame total instead of
adding truncated per-piece millis; an iPhone narration's `since` drains the
decoded samples instead of copying them and treats a missing file as no
audio; the phone and replay paths carry the audio stop point into their
bundles; and empty audio answers `source: "none"`, as `transcribe_with`
does.

Tests: a movie plus partial audio is never owed, retention trashes a
crashed bundle's media, a write failure records its stop point, a missing
streamed file shifts to no samples, and the replay shift moves the stop
point with the clock.

* capture: publish audio.wav only once its build journals the capture

Follow-ups from review.

A capture now streams to audio.wav.partial and keeps that name after it
stops: the partial is renamed to audio.wav right after the build writes
unfinished.json, so audio.wav never exists without a journal, and a
stopped capture waiting in the finish queue no longer looks like an
orphan to Scrawl.app's recover. A partial that cannot take the name is
read back and written by the build, and its partial name removed; the
replay removes the unshifted partial once the narration is read for
shifting.

Also: a periodic header flush error is now a write failure (the rest of
the capture is a gap) rather than a log line; the midpoint of a failed
write records where the file stopped; and the words test cuts pieces at
odd sample counts and computes offsets from the running frame total, so
per-piece millisecond drift would fail it.

Tests: a streamed audio takes its final name only when the build settles
it (and falls back when it cannot), a capture that has not been
journaled is never owed a rebuild, a mid-capture write failure stops
where the file stopped, and the word offsets are exact at odd piece
lengths.

* capture: consume a streamed recording's partial when it is read

Follow-ups from review.

`RecordedAudio::since` and `into_memory` now remove the partial once its
samples are read: an iPhone narration (capture.rs's `host_narration`
path) used to leave the whole streamed file in the finished bundle. The
replay relies on the same path instead of removing it by hand, and the
light zip leaves `audio.wav.partial` out defensively. A read that fails
is an error to `into_memory` (so a build keeps the only copy) while
`since` still treats a missing file as no audio for an iPhone.

A failed publish now reads the audio back only when it produced the
samples the recording had; a failed read keeps the partial and removes
any half-copied `audio.wav`. `publish_audio` takes `&mut self` and points
the recording at the published file.

A journaled bundle whose `audio.wav` is missing adopts `audio.wav.partial`
before rebuilding. Docs say the guarantee is a streamed capture's, and
that a crash while recording or queued is retention's job, not
recovery's.

Tests: reading a streamed recording consumes the partial; a finished
iPhone bundle keeps none; a streamed audio is published only when its
build settles it, including the read-back and unreadable-partial cases; a
journaled capture adopts its partial.

* capture: keep a failed audio publish recoverable

Follow-ups from review.

The publish fallback read the partial with `into_memory`, which deletes
it, and then ignored whether its own write landed: a failed write left
the audio nowhere. It now reads through `read_streamed` (no deletion),
writes `audio.wav` and checks the result, and removes the partial only
once that write succeeded. A failed read or write removes any half
`audio.wav` and fails the build, which is the pipeline's existing failed
path: `recover::finished` runs only for an `Ok` build, so `unfinished.json`
stays and the next launch's recovery adopts the partial instead of the
capture quietly finishing without its audio.

`publish_audio` also treats a landed copy as success even when deleting
the partial fails, logging it rather than reporting failure and letting
the fallback overwrite a good `audio.wav`.

Tests: a blocked target keeps the partial and fails the build; a
fallback write that lands consumes the partial and writes `audio.wav`;
an unreadable partial is kept.
2026-11-16 10:28:54 -05:00
..
src capture: keep all audio in long captures (#1795) (#1894) 2026-11-16 10:28:54 -05:00
Cargo.toml Roll in Abattoir's shared Rust lints (#557) 2026-10-30 21:49:20 -07:00
README.md feat(capture): Annotate suggests the OpenCode session open in a Ghostty pane, and never guesses between two (#1514) 2026-11-12 16:47:14 -08:00

scrawl-router

Where a capture or dictation goes among OpenCode sessions, sending it there, and taking it back. Scrawl's scrawl router … commands and Hex call the same code: Scrawl through its CLI and app, Hex in-process through Router.

The host owns the settings and the folders. The library never reads Scrawl's ~/.config/scrawl/config.json and never picks a folder of its own. It builds without gpui, ScreenCaptureKit, the Swift helper, cpal or objc2: its dependencies are anyhow, dirs, libc, serde and serde_json.

Using it

use std::time::Duration;
use scrawl_router::{Action, Router, RouterConfig, RouterDirs, parse_scrawl_config};

let config: RouterConfig = parse_scrawl_config(&std::fs::read_to_string(config_path)?);
let dirs = RouterDirs::under(&router_dir, Some(log_path), Some(captures_dir));
let router = Router::new(config, dirs).with_log(|line| eprintln!("{line}"));

let decision = router.decide(&serde_json::json!({"item": {"kind": "dictation", "text": "…"}}), Duration::from_millis(2500))?;
let sent = router.deliver(&decision.decision_id, "ses_…", Duration::from_secs(10))?;
let undone = router.undo(&sent.sent.unwrap().delivery_id, Duration::from_secs(10))?;
router.correct(&decision.decision_id, Action::Redirect, Some("ses_other"))?;

Every call blocks the calling thread until it's done or its deadline passes. Serializing a result with serde_json gives exactly what the matching scrawl router command prints (docs/routing.md).

The API

impl Router {
    pub fn new(config: RouterConfig, dirs: RouterDirs) -> Self;
    pub fn with_log(self, log: impl Fn(&str) + Send + Sync + 'static) -> Self;
    pub fn with_summary(self, summary: env::Summary) -> Self;   // fn(&ScrawlBundle, &Path) -> String
    pub fn with_opencode(self, opencode: Arc<dyn env::OpenCode>) -> Self;
    pub fn with_pages(self, pages: env::Pages) -> Self;         // fn(&str) -> Option<Registration>
    pub fn with_live(self, live: bool) -> Self;
    pub fn config(&self) -> &RouterConfig;
    pub fn dirs(&self) -> &RouterDirs;

    pub fn decide(&self, request: &serde_json::Value, deadline: Duration) -> Result<Decision>;
    pub fn deliver(&self, decision_id: &str, to: &str, deadline: Duration) -> Result<Delivered>;
    pub fn deliver_request(&self, request: DeliverRequest, deadline: Duration) -> Result<Delivered>;
    pub fn undo(&self, delivery_id: &str, deadline: Duration) -> Result<UndoReport>;
    pub fn correct(&self, decision_id: &str, action: Action, to: Option<&str>) -> Result<()>;
    pub fn log_correction(&self, line: &str) -> Result<()>;
    pub fn retry_outbox(&self) -> delivery::Report;
    pub fn eval(&self, options: EvalOptions) -> Result<()>;

    pub fn run<T>(&self, f: impl FnOnce() -> T) -> T;
    pub fn install_as_fallback(&self);
}
  • decide (router decide): request is {"item": {"kind", "text", "app", "title", "url", "selected_text", "mode"}, "pinned"?, "history"?}. The Decision has decision_id, decision (send, ask, fallback or keep), target, candidates, confidence, any_fits, model, ms, why, and suggested, would and offer_rule when they apply. It answers within deadline whatever happens: a timeout is a keep whose why says so. Sessions are read and Jev asked until 200 ms before the deadline. The decision is logged and saved for deliver and correct. Nothing is sent.
  • deliver (router deliver --decision <id> --to <session>): sends the decision's text (dictation) or bundle (capture). Delivered is {"ok", "state": "sent" | "queued", "session", "offer_rule"?}, plus delivery_id, message_id, delivery (steer or queue) and was_idle once sent. A send OpenCode didn't take is queued in the outbox; call retry_outbox every few seconds to retry it (Scrawl's ingest server does this for its own outbox). deliver_request takes the caller's item_id instead of a decision, or new text.
  • undo (router undo <id> --json): UndoReport is {"undone", "session", "message_id"}, where undone is withdrawn (removed before it was read), reverted (its turn interrupted and the session reverted to before it, committed, so the send and its turn are deleted; files go back only if the turn's edit tools changed them), disowned (the session was told to ignore it, also when anything arrived while the revert was staged or the commit failed, after clearing the staged revert), gone (the send or its session no longer exists), too-old (past undo_window_sec; nothing done, not an error) or unfinished (a staged revert could be neither committed nor cleared, so the session's next prompt would apply it; not saved, so the undo can be tried again). It errors only for a malformed ID, a server that can't be reached, or the deadline; a busy session is retried only until the deadline.
  • correct (router correct --decision <id> --action <cancel|redirect|paste|edit> [--to <session>]): logs that a decision was corrected, joined to it in the log. A redirect names where the item went instead. Picks are counted toward a rule offer by deliver, not here.
  • log_correction (router log): one correction line in Hex's spelling, joined to its decision.
  • eval (router eval): replays past captures and the items in dirs.eval through Jev and prints the accuracy.
  • run runs any module function (routing::…) with this router's settings. install_as_fallback makes them what the modules use outside a call, for a host that calls the modules directly.
  • with_opencode gives the router a host transport for OpenCode where this machine's registration isn't enough (Windows: a service in WSL). None from its request keeps the router's own local service path; its directory maps a capture folder to the path that server sees.

Rules are part of the config: config.with_rule(RuleKind::Site | RuleKind::App, key, target) and config.with_refused(key) return a new RouterConfig for the host to save. Scrawl, which keeps its rules as JSON, uses routing::policy::add_rule and refuse_rule on its routing object instead.

The settings (RouterConfig)

Serde camelCase, every field optional. parse_scrawl_config(&str) reads them from the text of Scrawl's config.json, where a key (or a sites/apps entry) that doesn't fit is dropped on its own; parse_scrawl_config_with_warnings also says what it dropped.

Field Scrawl's key Meaning
auto_send routing.autoSend What may send without asking: rules (default), confident or never.
undo_window_sec routing.undoWindowSec How long an undo still takes a send back (default 600).
sites routing.sites URL prefix → folder (~ allowed) or ses_ ID: where a site's items always go.
apps routing.apps Bundle ID (or a prefix) → folder or ses_ ID. General-purpose apps (browsers, terminals, editors) are ignored.
terminals routing.terminals Folder (~ allowed) → folder or ses_ ID: where captures of a terminal working in that folder or below go (the longest key wins). The home folder and / are ignored.
servers routing.servers URL prefix → the folder a file server serves.
aliases routing.aliases Spoken name → the session title or folder it means.
refused_rules routing.refusedRules Sites and bundle IDs never offered a rule again.
delivery delivery steer (join a busy session's turn, default) or queue (wait for it to end).
smart_routing experiments.smartRouting Weigh a capture's evidence rather than follow a dev site's port alone.
jev_routing experiments.jevRouting Ask Jev (needs smart_routing).
jev jevRouting (an object) Jev's thresholds and options.
jev_api_key jevApiKey The key Jev is called with; absent uses $OPENCODE_API_KEY, then OpenCode's own credential.
agent_host agentHost The SSH host whose OpenCode server holds the sessions, when it isn't this Mac.
agent_opencode agentOpencode The opencode command on that host.
send_captures autoSend Whether a capture of a dev site goes straight to its session (default on).

The folders (RouterDirs)

Each is Option<PathBuf>; None turns off what needs it. RouterDirs::under(router, log, captures) gives Scrawl's layout. To share decisions and undo records with the scrawl router CLI, use Scrawl's own: RouterDirs::under("~/Library/Application Support/scrawl/router", Some(".../scrawl/routing-decisions.jsonl"), Some(captures)).

Field Scrawl's layout Holds
decisions router/decisions/ Each decision's request and reply (<id>.json, 0600, kept 7 days), for deliver and correct.
outbox router/outbox/ Prompts waiting for a retry, a folder each.
deliveries router/deliveries/ Sends that can be undone (<delivery_id>.json, 0600, kept 7 days).
learned router/learned.json Each site's and app's delivered picks, counted toward a rule offer.
log routing-decisions.jsonl One JSON line per decision and correction (0600).
eval router/eval/ Kit's eval items (*.jsonl), read by eval.
captures Scrawl's captures folder .scrawl bundles: bundle IDs resolve here, and eval replays them.

What it reads and never touches

It reads OpenCode's own files to reach the server and its history: service.json under $XDG_STATE_HOME/opencode, ~/.local/state/opencode and $OPENCODE_CONFIG_DIR / $XDG_CONFIG_HOME/opencode; OpenCode's database read-only ($OPENCODE_DB, else found through the server); and $OPENCODE_PASSWORD / $OPENCODE_SERVER_PASSWORD, $OPENCODE_SESSION_ID, $OPENCODE_API_KEY and $SCRAWL_NO_OPENCODE.

It never reads ~/.config/scrawl/config.json or $SCRAWL_CONFIG, never writes under ~/Library/Application Support/scrawl unless the host's RouterDirs point there, and never reads $SCRAWL_ROUTER_DIR, $SCRAWL_ROUTING_LOG or $SCRAWL_AGENT_HOST (Scrawl reads those and passes the result in). Outside a Router call with no fallback installed it is inert: default settings, no folders, no log, and no OpenCode history read. Tests rely on that.