Dev.to WebDev 🛠 Dev 👁 0 📖 5 min read

Safari's native messaging can't stream, so I long-poll the on-device model

TL;DR. sendNativeMessage in Safari returns exactly one reply. To stream a model's output through it, the background script asks "anything after character N?" in a loop, and the Swift side holds each request for up to a s

Safari's native messaging can't stream, so I long-poll the on-device model

TL;DR. sendNativeMessage in Safari returns exactly one reply. To stream a model's output through it,
the background script asks "anything after character N?" in a loop, and the Swift side holds each
request for up to a second until the text grows. Every reply carries the whole text so far, counted in
UTF-16. Then keep the background script alive yourself, and don't write to storage.session per poll.

I'm working on Epitome, a Safari extension for Mac, iPhone and iPad. It summarizes the current page with
the model Apple ships on the device (the Foundation Models framework).

On my MacBook Pro with an M5 Pro the first words come back after about two seconds, and a summary of a
long article takes 8 to 15. These are my numbers, not a benchmark: on other Macs and on iPhones they'll
be different.
When I tried showing nothing for 15 seconds and then the whole text at once, it felt like the extension
had hung. So the text had to appear while the model writes it.

The problem: a Safari Web Extension reaches its native code through runtime.sendNativeMessage, and each
message gets exactly one reply. As far as I could find, that's all there is, on the Mac and on iOS.

Start a job, then keep asking

The model runs in the native half, an app extension written in Swift. The background script sends
start and gets a job id back right away.

From then on it keeps asking: "anything after character N?" The Swift side doesn't answer at once. It
holds the request for up to a second, until there's more text than N or the job has finished.

Swift answers a poll only when there's new text or a second has passed. The JavaScript loop just sends the next poll as soon as a reply arrives.
Swift answers a poll only when there's new text or a second has passed. The JavaScript loop just sends the next poll as soon as a reply arrives.
Two early decisions paid off later.

The first: a reply always holds the full text, not a delta. Foundation Models' streamResponse already
hands you snapshots of the whole response, so Swift doesn't diff anything. On the JavaScript side, a
dropped or duplicated reply doesn't matter, because the next one overwrites the text.

The second: since is measured in UTF-16 code units, because that's what string.length returns in JavaScript.
Swift's String.count counts grapheme clusters, a different number as soon as the text has an emoji or a
Devanagari conjunct. So Swift compares with text.utf16.count, and the background just passes
response.text.length back.

On the native side the jobs belong to an actor. Here's poll with the error handling cut out:

actor SummaryJobStore {
    func poll(_ id: String, since: Int) async -> JobState? {
        guard let job = jobs[id] else { return nil }   // → "jobLost"
        if !job.state.done && job.state.text.utf16.count <= since {
            await waitForChange(of: id)                // new text, or 1 s
        }
        return jobs[id]?.state                         // the whole text so far
    }
}

waitForChange stores a continuation. Two things can resume it: the generating task writing new text,
or a one-second timer, whichever fires first. When new text wins, the timer gets cancelled. My first
version forgot that step. With a fast model, sleeping timer tasks piled up one after another.

The JavaScript loop has no timer at all, since every call already blocks on the Swift side:

export async function runPoll(jobId: string, sink: PollSink, poll: PollFn) {
  let since = 0;
  for (;;) {
    if (sink.stopRequested()) return sink.onStopped();
    const response = await poll(jobId, since);
    if (!response.ok) return sink.onError(response.error);
    since = response.text.length;          // UTF-16, matches the Swift side
    await sink.onText(response.text, response.done);
    if (response.done) return;
  }
}

The job belongs to the background script, and the popup only displays what the background has. You can
close the popup in the middle of a summary, open it a minute later, and the summary will have kept going.

Bug 1: Safari unloads the background while it waits

The background is a non-persistent script. Safari unloads it 30 seconds after the last runtime message,
and a sendNativeMessage call still waiting for its reply doesn't count as one.

I ran into this in October on an iPhone. A long job kept running after the popup was closed (it builds a
condensed version of a long video), and it stopped 30 seconds later. Every time, with nothing in the logs.

The same long job with the popup closed, before and after the fix.
The same long job with the popup closed, before and after the fix.
The fix isn't pretty, but I haven't found a better one. While any native call is pending, the background
sends a message nobody listens to, every 8 seconds:

let inFlight = 0;
let keepAlive: ReturnType<typeof setInterval> | undefined;

function holdOpen() {
  if (keepAlive) return;
  keepAlive = setInterval(() => {
    if (inFlight > 0) {
      browser.runtime.sendMessage({ type: "keepAlive" }).catch(() => undefined);
      return;
    }
    clearInterval(keepAlive);
    keepAlive = undefined;
  }, 8000);
}

sendNative bumps inFlight, calls holdOpen(), and decrements the counter in finally.

Bug 2: storage.session runs out after a few dozen writes

Originally I wrote the job to storage.session after every poll, so a popup opened later could pick it
up. The first summary worked fine. Every one after it failed silently. Safari had hit its
storage.session quota ("Exceeded storage quota") after a few dozen writes.

Now the running job lives only in the background's memory, and the popup gets updates as runtime
messages. A finished job (done, stopped or failed) is written to storage once.

Bug 3: the native process can go away

The system kills the app extension whenever it likes: low memory, an update, a crash. The next poll then
reaches a fresh process that knows nothing about the job.

So poll returns nil for an unknown id, and JavaScript gets it as a jobLost error. The popup keeps
the text it has already received and says the summary was interrupted. Without this it would show a
spinner that never stops.

Bug 4: token counting can take 30 seconds

The page text has to fit in the model's context window, so I trim it before the job starts. For the
length check I ask the model for its own token count. Estimating tokens from the number of characters is
off too often to be useful.

On my iPhone I saw that call take 10 to 33 seconds while another job was generating: the model does the
counting too, so one request waits for the other. Now, when the answer is known without the model
("nothing to summarize", "too short", "busy"), the request replies first and counts nothing. Otherwise you
get an empty popup and no idea what it's doing.

Where it ended up

On my M5 Pro the first words show up after about two seconds, and then the text keeps coming at roughly
reading speed. The polls arrive in uneven bursts, so the popup smooths that out and reveals the words at a
steady pace. That part is plain CSS and JavaScript, though, and has nothing to do with native messaging.

Epitome is on the App Store for Mac, iPhone and iPad: opanchenko.com/epitome.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.