blog · · engineering

The share extension had to implement ULID

Capturing a line without opening the app shipped on Android, the desktop and the TUI in one PR, against the same inbox iOS already had. The Android share target writes through outl_actions::capture over JNI and its Kotlin holds a folder path and three strings, because an Android share target is an activity in the app's own process with the Rust library already loaded. An iOS share extension is a separate process under a memory ceiling that library would not fit, so it carries a second ULID encoder, a second copy of the file format and a second copy of the one rule that turns a share into a line. Parity between those two is not a shared library. It is a ten-case JSON fixture that two test suites in two languages both read, which is the weakest form of code reuse and the only one the process boundary leaves available.

A
11 min read

The iOS share extension has its own ULID encoder.

Twenty-three lines of Crockford base32 in OutlKit/Capture/CaptureInbox.swift, in a repository where crates/outl-actions/src/capture.rs imports the ulid crate and calls Ulid::from_datetime inside the function that does the same job. Both produce 26 characters. Both have to produce the same 26 characters, because that string is the file name, the sort order of the inbox, and the id of the block the capture becomes.

The Android share target has no ULID encoder. It has a folder path, three strings and a timestamp.

Same feature, same PR, 57 files and 1,890 insertions. The difference between the two halves is not a language preference and it was not mine to make.

a memory ceiling, not a language preference

The feature is capturing a line without opening the app. RFC 0363 landed it on iOS in #362: a widget, an “Add to today” App Intent, a share extension. None of them touches the workspace. Each writes one <ULID>.json into an inbox in the App Group container, and the app drains it into the journal for the day the capture was made.

The reason extensions write a file instead of an op is in the RFC, and it is about the process, not the format:

Each of those runs in its own process, with its own sandbox and a memory ceiling far below what booting a workspace needs.

So on iOS the file format has a second implementation, in Swift, and that is the end of the argument. There is no version of the design where an extension calls outl_actions.

Android looks like the same feature and is a different situation entirely. There is no extension model. The share target is an ordinary activity declared in the manifest, running inside the app’s own process, which means liboutl_mobile_lib.so is already loaded by the time it starts. So it calls the library:

let Some(line) = outl_actions::capture::shared_line(Some(&text), Some(&url)) else {
    return Ok(jni::sys::JNI_FALSE);
};
let wrote = outl_actions::capture::write_capture(
    std::path::Path::new(&dir),
    &line,
    &source,
    captured_at_ms,
);

That is the whole of the Android write path, in crates/outl-mobile/src-tauri/src/capture_jni.rs. Eighty lines of file, most of it a doc comment and the JNI error posture (log, never throw, because a thrown exception lands inside the share activity and crashes the share sheet).

The split is not Rust versus Kotlin, it is what each side is allowed to know. OutlCapture.kt is 146 lines and none of them describe a capture. It creates filesDir/captures, exports it as OUTL_CAPTURE_INBOX before Tauri boots, builds an outl://capture intent for the widget and the tile, and nudges the webview on resume. The share activity pulls EXTRA_TEXT and EXTRA_SUBJECT off the intent and hands both across as they arrived, because deciding what to do with them is not its job.

the rule that exists twice, and the ten cases that hold it

The rule in question is small enough to quote whole. Here it is in Rust, the owner:

pub fn shared_line(text: Option<&str>, url: Option<&str>) -> Option<String> {
    let body = text
        .unwrap_or_default()
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .collect::<Vec<_>>()
        .join(" ");
    let link = url.unwrap_or_default().trim();
    match (body.is_empty(), link.is_empty()) {
        (true, true) => None,
        (true, false) => Some(link.to_string()),
        (false, true) => Some(body),
        (false, false) if body.contains(link) => Some(body),
        (false, false) => Some(format!("{body} {link}")),
    }
}

And in Swift, OutlKit/Capture/SharedLine.swift, which exists for exactly one reason:

public static func compose(text: String?, url: URL?) -> String? {
    let body = (text ?? "")
        .components(separatedBy: .newlines)
        .map { $0.trimmingCharacters(in: .whitespaces) }
        .filter { !$0.isEmpty }
        .joined(separator: " ")
    let link = url?.absoluteString ?? ""
    switch (body.isEmpty, link.isEmpty) {
    case (true, true): return nil
    case (true, false): return link
    case (false, true): return body
    case (false, false): return body.contains(link) ? body : "\(body) \(link)"
    }
}

The same four-way split in the same order, down to the check for a link the text already contains. They look like a translation because they are one.

Two implementations drift, and this pair drifts in one direction: a share that silently loses its link. Nobody files that bug accurately. You shared an article from Safari, the journal has the headline, the URL is gone, and you blame the browser.

So the cases moved out of both test suites into crates/outl-actions/tests/shared-line-cases.json, and both suites read it. The Rust side resolves it from CARGO_MANIFEST_DIR; the Swift side walks up from #filePath until it finds the same path, deliberately rather than vendoring a copy as a package resource, because a copy is the drift being closed. The file says what it is for in its own header:

"Both test suites read THIS file, so a case answered differently on one",
"side fails there instead of reaching a user as a share that lost its",
"link. Add a case here, never to one suite alone."

There are ten cases. Both suites assert there are at least ten:

assert!(
    fixture.cases.len() >= 10,
    "only {} cases in the fixture — a shrunken fixture is a pin that \
     stopped pinning",
    fixture.cases.len()
);

That assertion is there because of a lesson I paid for in a different feature. When I shipped LAN discovery, the test that was supposed to keep the Rust and the Swift agreeing on two wire constants compared a constant to its own literal one line below, stayed green forever, and was cited by three doc comments as the thing holding the contract. A fixture emptied to zero cases passes the same way: every assertion in the loop holds vacuously.

the comment that was the parity guarantee

The fixture is new. The claim it replaces was not.

a_share_becomes_one_line has been in crates/outl-actions/src/capture/tests.rs since the iOS work, and it opens like this:

// Every case `SharedLine.swift` answers, so the two cannot drift
// without one of them failing a test.

Below it is a hand-written list of assertions. Across the boundary in CaptureInboxTests.swift is testTextAndURLBecomeOneLine, a hand-written list of assertions covering four of the cases. Neither test can see the other. Nothing in the repository could have told you they disagreed. The sentence was true the day it was written and had no mechanism keeping it true.

This is the same shape as the tautology, one step up: not a test comparing a value to itself, but a comment asserting a cross-language invariant that no test could fail. Both are worse than silence, because a documented guarantee is a closed question and everybody downstream stops looking, me included.

Both hand-written tests are still there, which is fine. They are now ordinary unit tests of the Rust function and the Swift function. The comment is true now, and the fixture next to it is what makes it true.

the loop went from two copies to one, and that was the easy half

The drain is the other side of the inbox: the only path from a folder of files into the op log. Root invariant 7 says state that must converge goes through the op log, so a second process appending to ops-<actor>.jsonl is exactly what the whole design exists to avoid. One function owns the landing.

Except it did not, quite. The GUI clients take the workspace lock per capture and project the page; the TUI holds a plain &mut Workspace and needs neither. So there were two loops with two per-capture steps, and the loop is the part that must not differ: which captures are skipped, that a file is deleted only after its op is applied, and in what order.

drain_captures is now the loop, taking the per-capture step as a closure. crates/outl-tauri-shared/src/capture_inbox.rs passes one that locks and projects; crates/outl-tui/src/actions/lifecycle/capture.rs passes one that runs commit_page against the workspace it already holds. The crate’s own notes name what the second copy was costing: whether a blank capture gets deleted was free to start differing between the phone and the terminal, and the loop’s tests only ever covered one of them.

One detail in there I like more than it deserves. The report does not ask the closure what block id landed, because the block id is not something the landing gets an opinion about: it is the capture’s ULID, so the loop derives it rather than taking a second opinion on it.

That property is also what makes a drain idempotent across a crash between the op and the remove_file, and what makes two devices that both drained the same file-transport-synced capture converge on one block instead of two.

the desktop has no sandbox problem and got the inbox anyway

outl capture "call the venue" writes a file into <root>/.outl/captures/ and exits. A terminal can obviously open a workspace, so the sandbox argument does not apply here at all, and the reason is a different one.

outl daily append writes the block straight into the op log. It also boots the workspace, which is seconds on a large graph for one line, and if a GUI client is running then it holds the device’s write actor, so the CLI falls back to an ephemeral one and leaves a fresh ops-<ulid>.jsonl behind per call. That litter is the thing invariant 11 measures. Writing a file costs neither, and crates/outl-cli/src/cmd/capture.rs does not even open the workspace to validate the path: it checks for the .outl/ marker, because booting is the cost the command exists to avoid.

That gives the desktop every scriptable gesture it has. A macOS Service, a Shortcut, Raycast, a hotkey daemon: none of them can boot a workspace either, and now none of them has to.

the drain that loaded today over the page you asked for

The GUI half is installForegroundRefresh in crates/outl-frontend-shared/src/capture/index.ts, shared because the trigger is identical on both clients and only the writer differs. It drains on mount, on visibilitychange, and when the native side calls window.__outlCapturesArrived().

On the desktop I added one more trigger, window.addEventListener("focus", ...), because alt-tabbing to a terminal and back is not a visibility change and that round trip is the entire desktop capture gesture.

Then it broke cold start, in a way I did not predict. A drain that lands something calls back into the client to refresh, and the desktop’s refresh falls back to today’s journal when no page is open yet. On a cold start triggered by an outl:// deep link or an “Open With” file, no page is open yet. So the capture drain raced the thing you actually asked for and sometimes won:

// The drain below waits on this before refreshing, so a capture
// landing first cannot reach `refreshActivePage`'s no-page branch
// and load today over the requested target.
const initialNav: Promise<unknown> = pending
  ? handleDeepLink(pending)
  : pendingFile
    ? handleOpenFile(pendingFile)
    : loadToday();

The capture was never at risk; it was in the op log before the refresh ran. What was at risk was the navigation, and a user clicking a link into a specific page and landing on today reads as the link being broken.

what still has two owners

The fixture pins one function. Here is what it does not pin.

The capture file’s three key names (text, captured_at_ms, source) are declared once in Rust as a serde struct and once in Swift as a CodingKeys enum. The ULID alphabet and the 48-bit time split are implemented twice. The env var OUTL_CAPTURE_INBOX is spelled as a literal in Rust, in Kotlin and in Swift. Each of those has a test, and every one of those tests asserts against a value hardcoded in its own language. That is exactly the arrangement the mDNS constants test was in before I made it read the other copies off disk, and I did not do the same thing here.

The sharpest one is the env var, because of how it fails. Get it wrong in Kotlin and Os.setenv succeeds, inbox_from_env returns None, the drain reports zero landed and zero skipped, and every share piles up in filesDir/captures forever. No error, no log line, nothing on screen. It is the “looks present in the logs and does nothing” category again, which I keep finding is the one I am worst at catching.

And the two shared_line implementations are already not the same function. Rust’s str::lines splits on \n, tolerating a trailing \r. Swift’s components(separatedBy: .newlines) splits on the whole Unicode newline set, which includes a lone \r, U+0085 and U+2028. Hand them "a\rb" and Rust returns a\rb while Swift returns a b. No case in the fixture contains a lone carriage return, so the fixture is green and will stay green. I am not claiming anyone has hit it. I am saying the fixture pins the ten cases somebody thought of, which is what a fixture is, and that this is the ceiling of what reuse means across a process boundary.

The rest of the costs are recorded where the catalog records them, in crates/outl-shortcuts/src/capability_support.rs, which is the exhaustive match that turned client parity into something that fails to compile. CaptureOutsideTheApp reads Partial on the TUI, Partial on the desktop, Full on mobile. The TUI drains once at launch because nothing in it watches the folder, so a capture made while it is open waits for the next start. The desktop drains everything and has no gesture of its own: no menu bar item, no Service, no global hotkey that writes a capture, so the entry point is outl capture and whatever you wire it into. Android now has two inboxes, filesDir/captures and the workspace’s own, and outl capture --list reads only the second, so “where is my line” has two answers on exactly one platform.

The thing I would carry out of this: before planning to share a piece of logic between two clients, find out whether they are the same process. If they are, the whole question is where the function lives. If they are not, the function cannot be shared at any price, and the only question left is what artefact both sides can read, which will be a file full of examples and nothing stronger.

The capture inbox, both writers and the fixture are in the outl repository, and the design is RFC 0363.