Repository F# setup
open System
open System.IO
open System.Threading
open System.Threading.Tasks
open Axial
open Axial.Console
open Axial.FileSystem
open Axial.Hosting
open Axial.Hosting.Browser
open Axial.Hosting.Node
open Axial.State
open Axial.Telemetry
open Axial.Telemetry.JavaScript
open Axial.ElmishFlows

Elmish programs

The Axial.ElmishFlows package exposes the Axial.ElmishFlows namespace and connects an Elmish 5 program to Axial workflows. Create one runtime per program, passing an environment and a Post function that delivers callbacks on the host's dispatch thread. When already on that thread, Post should run inline; otherwise it should post to it. Do not call Elmish's dispatch directly from workers. Connect OnDefect to the host's crash reporting path; typed failures are messages, but defects are not.

Install

dotnet add package Axial.ElmishFlows

Axial.ElmishFlows brings Elmish 5 with it. Reference Elmish directly when your program uses Program.mkProgram and dispatch. Open Axial.ElmishFlows for the Axial API, and Axial when you override the runtime clock.

A minimal runtime supplies an environment, a Post function, a defect handler, a history capacity, and optional clock and log-sink overrides (Clock = None and LogSink = None keep the runtime's live defaults; Some installs that clock or sink for commands, subscriptions and layer provisioning):

Fragment
open Axial
open Axial.ElmishFlows
open Axial

// In an Elmish host, `Post` is usually the program's dispatch, so callbacks run on the host's dispatch thread.
// Here the code is already on that thread, so it runs the callback inline.
let runtime =
    ElmishRuntime.start
        { Post = (fun callback -> callback ())
          OnDefect = (fun defect -> failwith defect.Rendered)
          HistoryCapacity = 32
          Clock = None
          LogSink = None }
        ()

When Post is not already on the dispatch thread it must post to it (for example Application.Post in WPF or dispatching back to a UI loop); never call Elmish's dispatch directly from a worker.

First-use lifecycle

ElmishRuntime takes any environment, with no clock interface required: time comes from the runtime, and ElmishRuntimeOptions.Clock overrides it, and ElmishRuntimeOptions.LogSink replaces the default Information-and-above console sink. Keep the runtime's environment stable, and supply a command's current dependencies with Flow.localEnv. For example, a git client can open another repository without recreating its Elmish runtime:

Fragment
open Axial
open Axial.ElmishFlows
open Axial

type RepositoryEnvironment = { Repository: string }

let runtime =
    ElmishRuntime.start
        { Post = (fun callback -> callback ())
          OnDefect = (fun defect -> failwith defect.Rendered)
          HistoryCapacity = 32
          Clock = None
          LogSink = None }
        ()
let currentEnv = { Repository = "/repos/new" }
let repositoryName : Flow<RepositoryEnvironment, string, string> =
    Flow.envWith (fun env -> env.Repository)

let command =
    Cmd.OfFlow.either "repository" runtime
        (repositoryName |> Flow.localEnv (fun _ -> currentEnv))
        id
        (fun _ -> "unavailable")

Flow.localEnv selects the environment when the command runs; capture the selected environment for each command when constructing it so later repository switches do not change already-issued requests.

Provisioning with startLayer

When a runtime needs resources that must live for the whole program — a Cache.make* cache, queues, hubs, or a Layer.fromFlow resource — build them with a layer and start the runtime with ElmishRuntime.startLayer. The layer is provisioned inside the runtime's root scope, so Stop/StopAndWait releases what the layer acquired. A typed provisioning failure returns Error and leaves nothing running.

Fragment
open Axial
open Axial.ElmishFlows
open Axial

type CacheEnvironment = { Cache: Cache<int, Never, string> }

let layer : Layer<unit, string, CacheEnvironment> =
    Layer.fromFlow (flow {
        let! cache =
            Cache.make (fun key -> Flow.succeed $"value-{key}" : Flow<unit, Never, string>)
        return { Cache = cache }
    })

let runtime =
    match
        ElmishRuntime.startLayer
            { Post = (fun callback -> callback ())
              OnDefect = (fun defect -> failwith defect.Rendered)
              HistoryCapacity = 32
              Clock = None
              LogSink = None }
            layer
            ()
        |> Async.RunSynchronously
    with
    | Ok runtime -> runtime
    | Error error -> failwith error

Synchronous desktop startup

A desktop host often starts before an Elmish loop exists. Keep provisioning asynchronous, and put the one blocking wait at the host boundary:

Show page setup
open System
open Axial
open Axial
let shouldEqual expected actual =
    if actual <> expected then failwithf "Expected %A but got %A" expected actual
Verified
open Axial.ElmishFlows

let startDesktop
    (options: ElmishRuntimeOptions)
    (layer: Layer<'arg, string, 'env>)
    (input: 'arg)
    : Result<ElmishRuntime<'env>, string> =
    ElmishRuntime.startLayer options layer input
    |> Async.RunSynchronously
Requires & types
Requires: open Axial; open Axial.ElmishFlows (packages: Axial, Axial.ElmishFlows)
val startDesktop: ElmishRuntimeOptions -> Layer<'arg,string,'env> -> 'arg -> Result<ElmishRuntime<'env>,string>

Declare that function's exact file in [boundaries].files and add a rule-specific // axial-allow-AXG001: synchronous desktop host boundary with the reason. Startup must not require the blocked UI dispatcher: provision asynchronously first, or supply a prebuilt environment with ElmishRuntime.start when initialization is UI-affine. If provisioning posts work back to the dispatcher and waits for it, that is a dependency cycle the runner cannot repair. Keep the successful runtime alive until shutdown and call its documented Stop or StopAndWait exactly once; a synchronous stop is safe only when cleanup does not need the dispatcher.

Long-lived services and fire-and-forget

A service that lives as long as the program — a search pipeline, a poller, a cache warmer — belongs to the runtime, not to a never-completing command. Cmd.OfFlow.perform needs a success message, so running Flow.never through it forces an unreachable onSuccess. Start the service with ElmishRuntime.startService after the runtime starts and before the Elmish program does. It runs as a named fiber in the runtime's root scope with the runtime's environment; Stop/StopAndWait interrupts it and runs its finalizers. A defect goes to OnDefect under the service name, and so does a service that completes while the runtime is still running, since a service should last as long as the runtime. startService returns Error ServiceStartError.DuplicateName if a service with that name is still running, and Error ServiceStartError.RuntimeStopping once the runtime is stopping. Unlike Cmd.OfFlow.start, which update runs and which is expected to finish, a service is started by the host, one per name, and reports whether it started:

Fragment
open Axial
open Axial.ElmishFlows

type SearchEnvironment = { Requests: Queue<string>; Results: Hub<string> }

let searchPipeline : Flow<SearchEnvironment, Never, unit> =
    flow {
        let! env = Flow.env
        return!
            FlowStream.fromDequeue env.Requests
            |> FlowStream.mapFlow (fun query -> Hub.publish $"result:{query}" env.Results |> Flow.map ignore)
            |> FlowStream.runDrain
    }

let startServices (runtime: ElmishRuntime<SearchEnvironment>) : Result<unit, string> =
    runtime
    |> ElmishRuntime.startService "search-pipeline" searchPipeline
    |> Result.mapError (function
        | ServiceStartError.DuplicateName -> "the search pipeline is already running"
        | ServiceStartError.RuntimeStopping -> "the runtime is stopping")

The program then talks to the service through what the environment holds: it offers requests to the queue and subscribes to the hub with Sub.OfFlowStream.subscribe. A service whose lifetime follows the model instead — running only while a panel is open — is a subscription: Elmish disposes it (interrupting the stream and releasing its resources) when the model no longer asks for it:

Fragment
open Axial
open Axial.ElmishFlows
open Axial

// A search pipeline backed by an inbox: post queries, subscribe to results for the program's lifetime.
let searchPipeline (runtime: ElmishRuntime<unit>) =
    let inbox = Inbox.create 8 runtime
    let queries : FlowStream<unit, string, string> =
        Inbox.stream inbox |> FlowStream.map (fun query -> $"result:{query}")
    inbox, Sub.OfFlowStream.subscribe [ "search" ] runtime queries (fun error -> $"search-error:{error}")

When the service also needs resources provisioned once for the whole program, ElmishRuntime.startLayer above is the alternative: it builds the cache, queue, or hub inside the runtime's root scope and releases it on Stop/StopAndWait.

Cmd.OfFlow.start is the right tool for fire-and-forget work, but it accepts only Flow<'env, Never, unit>. A flow with a typed failure channel must handle that failure first — log it, then recover to unit:

Verified
let indexDocument (query: string) : Flow<unit, string, unit> =
    flow {
        if String.IsNullOrWhiteSpace query then
            return! Flow.fail "empty query"
    }

// Handle the typed failure before Cmd.OfFlow.start, which accepts only Flow<'env, Never, unit>.
let indexSafely (query: string) : Flow<unit, Never, unit> =
    indexDocument query
    |> Flow.recover (fun error ->
        flow {
            do! Log.error $"indexing skipped: {error}"
        })
Requires & types
Requires: open Axial; open System (packages: Axial)
val indexDocument: string -> Flow<unit,string,unit>
val indexSafely: string -> Flow<unit,Never,unit>
Verified
let log = Log.memory ()

indexSafely "" |> Flow.withLogSink log |> Flow.run () |> shouldEqual (Exit.Success ())

log.Entries |> Seq.map _.Message |> Seq.toList |> shouldEqual [ "indexing skipped: empty query" ]
Requires & types
Requires: open Axial (packages: Axial)
val log: TestLog
Fragment
open Axial
open Axial.ElmishFlows

// indexSafely already handled its typed failure, so its type is Flow<'env, Never, unit>.
let backgroundIndex runtime query =
    Cmd.OfFlow.start "index" runtime (indexSafely query)

Streaming results into update

Cmd.OfFlowStream.latest key runtime stream onElement onError runs a FlowStream as a command and dispatches each element as a message, in stream order, through Post. Starting another stream or Cmd.OfFlow.Latest command with the same key interrupts the running one, and elements it already posted that update has not yet seen are dropped, so a search-as-you-type command never mixes results from two queries. A typed failure dispatches onError after the elements before it; completion dispatches nothing, so append a final element when update needs to know the stream finished. Cmd.OfFlow.Latest.cancel key runtime stops it without a message.

Fragment
open Axial
open Axial.ElmishFlows

type SearchMsg =
    | Found of string list
    | SearchDone
    | SearchFailed of string

let search (runtime: ElmishRuntime<unit>) (files: FlowStream<unit, string, string>) (query: string) =
    let batches =
        files
        |> FlowStream.filter (fun path -> path.Contains query)
        |> FlowStream.groupedWithin 64 (System.TimeSpan.FromMilliseconds 100.0)
        |> FlowStream.map Found
        |> FlowStream.append (FlowStream.singleton SearchDone)
    Cmd.OfFlowStream.latest "search" runtime batches id SearchFailed

Each element costs one Post, so batch a fast stream with FlowStream.groupedWithin before dispatching it.

Command parameter order

Axial's commands keep Elmish's "work first" idea, but the runtime owns the command's root scope, so it precedes the flow. Pass the flow positionally, not piped:

Fragment
let command =
    Cmd.OfFlow.either "increment" runtime
        (Flow.succeed 2)
        id
        (fun (_: string) -> 0)

The order is name runtime workflow onSuccess onError for either; perform drops onError, attempt drops onSuccess, and Cmd.OfFlow.start name runtime workflow is fire-and-forget: it runs a Flow<'env, Never, unit> as a named fiber in the root scope, dispatches nothing, and reports defects to OnDefect.

Operation reference

The exhaustive operation inventory lives in the API reference:

  • Cmd: Cmd.OfFlow.either/perform/attempt/start, the latest-wins Cmd.OfFlow.Latest variants, and the streaming Cmd.OfFlowStream.latest.
  • Sub: Sub.OfFlowStream.subscribe for running a stream under a subscription id.
  • Inbox: Inbox.scopedSliding/scopedDropping/scopedBounded/ scopedUnbounded/scopedWith for an inbox built in the runtime's layer, and Inbox.create/offer/post/dropped/stream for synchronous UI input and search-as-you-type.
  • ElmishRuntime: start, startLayer, startService, test, and the Stop/StopAndWait shutdown methods.
  • TestRuntime: run, settle, drain, dispatched, and defects for tests with a manual clock.