In Lumen Flow, Action Scripts let users write JavaScript to transform data and control a Flow’s execution. The first implementation ran these scripts on a dedicated queue, off the main thread. The interface stayed responsive, and a 30-second timeout limited how long the Flow waited for a result.

That seemed sufficient until I tested a script containing while (true) {}.

After 30 seconds, the caller received an error. The JavaScript, however, kept running. The call to JSContext.evaluateScript(_:) never returned, consuming CPU and preventing the queue from handling new scripts.

The timeout was working exactly as implemented: it limited the wait. I still needed to control the work that continued afterward.

A dedicated queue keeps the interface responsive

Moving evaluation to a dedicated queue helped keep the interface responsive. But that separation provided no way to interrupt a running script.

Swift Task cancellation is cooperative. Calling cancel() signals cancellation; the running code must check Task.isCancelled or call Task.checkCancellation() to respond. A loop inside evaluateScript(_:) does not do that automatically.

JavaScriptCore has internal mechanisms for limiting execution. The WebKit source includes a watchdog and the JSContextGroupSetExecutionTimeLimit function, declared in a private WebKit header. That distinction matters: a mechanism existing inside the engine does not make it a supported public API in Apple’s SDK.

For an application distributed through the Mac App Store, I didn’t want to depend on that private API. I needed a way to terminate evaluation through public mechanisms, even when the script didn’t cooperate.

That requirement moved execution into a separate process.

Why the worker runs behind an XPC service

One option was to launch a subprocess directly from the application and terminate it when the deadline expired. That would address termination, but I also needed to limit the resources available to that process.

Lumen Flow needs to make requests and work with user data. A helper that inherits the application’s sandbox may receive permissions it doesn’t need to evaluate an Action Script.

I therefore split execution across three components: the application, an XPC service with a restricted sandbox, and a disposable worker launched by the service. JavaScriptCore runs inside that worker.

Action Scripts architecture diagram. Lumen Flow sends an evaluation identified by evaluationID to an XPC service with a minimal sandbox. The service launches a disposable worker that runs JavaScriptCore. The result returns along the same path. To cancel an evaluation, the app sends cancelEvaluation to the XPC service, which maps the evaluationID to a PID and terminates the worker with SIGKILL.
Figure 1 — Action Script isolation. The app sends the evaluation to an XPC service with reduced privileges. The service supervises a disposable worker running JavaScriptCore. Each evaluationID is mapped to its corresponding PID; on timeout or cancellation, the supervisor terminates that worker.

Each worker handles a single evaluation. It receives the required data, prepares the JavaScript context, executes the script, and returns a serialized response. It then exits.

When the deadline expires, the supervisor sends SIGKILL and waits for the process to exit before returning the timeout error. The response therefore indicates that the evaluation has ended, rather than merely that the application has stopped waiting.

The XPC service and the worker serve different purposes. The service’s sandbox restricts the privileges available to the worker. The disposable process makes it possible to interrupt uncooperative execution without terminating the main application.

Running JavaScript inside the XPC service itself would not be enough. An infinite loop could tie up the service and interfere with subsequent evaluations. Keeping execution in a separate worker leaves the supervisor available to receive cancellation requests and terminate the process.

What capabilities a script receives

Scripts written by users themselves can still contain errors. They may come from an imported Flow, a copied example, or a seemingly harmless change. The runtime needs to remain predictable in those situations.

Alongside termination, I worked to limit what reached the worker.

The request contains a serialized DTO (data transfer object) with the data needed for evaluation: allowed JSON values, Flow information, the runtime bootstrap, and opaque identifiers for secrets. I don’t send the application’s entire state or persistence objects.

The native functions exposed to JavaScript are also part of this boundary. If the application gives a script a function that can read files or make requests, it is granting that capability, even if JavaScript has no direct access to the system APIs.

The runtime interface is therefore limited to the operations Action Scripts need. It exposes no Keychain or SwiftData operations, nor access to the application’s filesystem. File and network restrictions also depend on the process sandbox, rather than solely on those functions being absent from the JavaScript context.

For credentials, secret values remain in the application. The worker receives opaque references. If a script returns one of those references, the app checks that it was issued for that evaluation before resolving the secret. An object that merely imitates the reference’s structure is treated as ordinary data.

This reduces the movement of credentials between processes, but it does not make the entire request free of sensitive information. If a sensitive value is already present in the JSON data sent to the script, it remains accessible during that evaluation. Choosing which data crosses the boundary is also part of security.

To check the isolation, I ran verification checks on the actual worker. They confirmed that it remained confined to the service container rather than the main application container. The entitlements configuration was part of the evidence; the behavior of the running process was the other.

This design has limits, too. Terminating a worker at its deadline limits its duration, but does not, by itself, impose a memory limit or a response-size limit. Those are separate controls and need to be assessed independently.

How to verify that the timeout stopped the work

Receiving a timeout error was no longer enough. I already had an implementation that could return that error while the script kept running.

The tests began checking the process itself:

  • A script containing while (true) {} must be terminated when the deadline is reached.
  • The worker must have exited before the timeout response returns.
  • No orphaned process may remain consuming CPU.
  • A simple evaluation must work immediately afterward.
  • The behavior must be verified in the signed bundle used for distribution.

That last point is particularly important with XPC.

An anonymous listener allows testing of the protocol, serialization, and much of the service’s behavior. It does not verify that the service is correctly embedded in the application, that the system will launch it, or that code signing and the hardened runtime allow the complete execution path.

The tests also needed to cover the path used by the distributed application. Otherwise, I would have evidence about the protocol, but not yet about the integration.

The Stop button needed to reach the worker

After isolating evaluation, there was still a gap between the runtime’s behavior and what users expected from the Stop button.

The button canceled the Task driving the Flow. That prevented new nodes from starting. An Action Script evaluation already in progress, however, continued until it finished or reached its deadline.

If the script was inside a runtime-provided sleep(8000) call, the user could still wait eight seconds. With an infinite loop, the evaluation would continue until the 30-second limit.

The separate process made it possible to terminate the script. I still needed to connect that capability to Flow cancellation.

I added a cancellation message without a reply to the XPC protocol, along with a client-generated identifier for each evaluation:

@objc(LumenActionScriptXPCProtocol)
protocol ActionScriptXPCProtocol {
    func evaluate(
        _ request: Data,
        withReply reply: @escaping (Data) -> Void
    )

    func cancelEvaluation(_ evaluationID: String)
}

The supervisor associates the identifier with that evaluation’s worker. When the Task is canceled, the runtime sends cancelEvaluation, and the service terminates the corresponding process.

Cancellations arriving before the worker was ready also needed handling.

The message may arrive before the process is registered or while the input to be written to the pipe is being prepared. The service records early cancellations and checks that record at evaluation setup checkpoints. A request that has already been canceled can therefore be aborted before its script runs.

In the tests recorded during the investigation, canceling an evaluation running sleep(8000) took approximately 0.31 s after this change. For while (true) {}, termination completed in around 0.30 s. Immediate cancellation—before the evaluation payload was handed off to the service—completed in about 0.001 s.

These figures describe measurements from that implementation, not timing guarantees provided by the operating system.

The runtime contract also became clearer: a canceled evaluation returns no partial result. The worker is terminated, and changes that existed only in its memory are discarded.

This choice works because the worker operates on the data it receives and returns a result to the application. Terminating the process would not undo external side effects if the runtime allowed scripts to write files or send requests directly, for example.

The cost of a process per evaluation

The first isolated version worked, but it was slow for an interactive tool. In the measured scenario, an evaluation that took approximately 0.2 ms inside the main process took about 107 ms through the isolated execution path.

Before changing the architecture again, I measured where that time was going.

Part of the cost came from JavaScriptCore initialization. Another part came from Process.waitUntilExit(): its polling wait showed up in the latency of each evaluation.

I started keeping a prewarmed worker ready, with no user data. I also replaced waitUntilExit() with a DispatchSemaphore signaled by the process’s terminationHandler. The supervision thread still waits for the worker to exit; the polling wait is what was removed. In the current implementation, supervision runs on a dedicated thread, leaving the service available to receive cancellation requests.

Each process still handles a single evaluation. After handing over the prewarmed worker, the service prepares its replacement. The JavaScript context is not reused across evaluations.

With a prewarmed worker available, measured latency dropped to about 7 ms per evaluation. In a loop with no delay between calls, the average was approximately 57 ms: preparing replacement workers becomes significant again. The 7 ms figure measures evaluation with a ready process, not a complete Flow step or sustained throughput.

In the notarized application, the service and prewarmed worker had no measurable CPU usage while idle. During one run of the example Flow, the service and observed workers consumed a combined 14.9 ms out of the 543.6 ms of recorded CPU time: approximately 2.7% of the total. This is accumulated CPU time, not elapsed execution time.

These results come from a specific scenario, but they were sufficient to assess the cost for the interaction I needed to support.

After the timeout

The test became concrete: once the caller receives the error, has the worker exited? And does the next evaluation work?

In the previous runtime, the Flow received an error while the script could keep consuming CPU. Isolation made it possible to terminate the process; connecting cancelEvaluation to the Flow’s Task made the Stop button reach the evaluation already in progress as well.

There are more components to maintain: an XPC service, a worker, serialization, and process supervision. For Lumen Flow, that cost was justified when the tests showed that a script could be interrupted and the next one executed without closing the application.


I used an AI assistant to help revise the language and organization of this article. I take responsibility for its content.