@runic-artifex/views-effect
v0.23.0
Published
Optional Effect 4 adapter for generated Runic Views clients: headless, with React helpers
Maintainers
Readme
@runic-artifex/views-effect
An optional Effect 4 adapter for clients generated by Runic Views. It wraps any generated client, without a different code generator or runtime, so Effect applications get typed failures, timeouts, safe retries, interruptible operations and scoped connections. The plain TypeScript API stays the default; no other Runic package depends on this one.
The adapter is supported and follows the SDK's versioning: it ships with the
@runic-artifex/views version of your generated clients. A .NET command's
declared failure ([RunicFailure]) arrives as the tagged ViewDomainFailure.
It is headless: its root entry depends on no UI framework and works from any
TypeScript, and its only framework adapter is React
(@runic-artifex/views-effect/react). There are no Vue, Svelte or Angular
adapters, and none are planned for 1.0: in those frameworks, render state with
the framework package (useView, injectView) and run Effect workflows through
the headless API, as Framework helpers shows.
npm install @runic-artifex/views-effect@preview @runic-artifex/views@preview effect
pnpm add @runic-artifex/views-effect@preview @runic-artifex/views@preview effect
bun add @runic-artifex/views-effect@preview @runic-artifex/views@preview effectIt requires effect 4.0.1 or a later 4.x release, and the @runic-artifex/views
version of your generated clients. Effect's declarations use Disposable, so a
project that type-checks libraries (skipLibCheck: false) adds ESNext.Disposable
to compilerOptions.lib.
import { command, connect, operation, states } from "@runic-artifex/views-effect";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
import * as Stream from "effect/Stream";
import { connectEditor } from "./generated/editor.js";
const program = Effect.gen(function* () {
// Disposed when the scope closes.
const editor = yield* connect(connectEditor);
yield* Effect.forkScoped(Stream.runForEach(states(editor), state => Effect.log(state.title)));
yield* command(() => editor.setTitle("Draft"));
// Interrupting this Effect, or its timeout, cancels the save in .NET.
yield* operation(id => editor.startSave({ requestId: id }), {
requestId: crypto.randomUUID(),
retry: Schedule.exponential("200 millis").pipe(Schedule.take(3)),
timeout: "10 seconds",
});
}).pipe(
Effect.scoped,
Effect.catchTag("ViewReleased", () => Effect.log("The editor was closed or replaced.")),
);API
| Function | Returns | Behavior |
| --- | --- | --- |
| connect(source) | Effect<Client, ViewError, Scope> | Connects a generated connect<Name> function or a page reference and disposes the client when the scope closes. |
| clientLayer(service, source) | Layer<I, ViewError> | Provides a connected client as a Context service. It connects when the layer is built and disposes the client when the layer's scope closes. |
| states(client, { bufferSize? }) | Stream<State> | The current state, then each accepted state. A slow consumer skips to the latest state (bufferSize defaults to 1). |
| connectionStates({ lostAfter? }) | Stream<BridgeConnectionState> | The page's connection to .NET (connecting, connected, reconnecting, lost, closed), then each change. A slow consumer skips to the latest state. |
| command(() => client.method(...)) | Effect<A, ViewError> | Runs a command, setter, can… query or checked write. A command that declares a failure succeeds with its value and adds ViewDomainFailure<F>. |
| operation(start, options?) | Effect<Result, ViewOperationError> | Starts a start<Command> operation and waits for its terminal status; Result is void for a command without one. A declared failure adds ViewDomainFailure<F>. |
| catchCase(effect, handlers) | Effect<A \| …, E \| …, R \| …> | Handles every $case of a declared [RunicUnion] failure in the error channel; a missing case is a type error. |
| viewportChanges(controller) | Stream<CollectionViewport> | The rows a createCollectionViewportController requests, as a stream. |
| followViewport(controller, request) | Effect<void, E, R> | Sends each new row range to .NET and interrupts the request for a range the user scrolled past. |
| queryCollectionChanges(collection) | Stream<QueryCollectionSnapshot<T>> | The rows a query collection shows for its range: the current snapshot, then each change, latest only. |
| queryViewportChanges(controller) | Stream<QueryViewport<T>> | The layout of a createQueryViewportController with variable row heights, which loads the rows while the stream runs. |
| setQuery(collection, query) | Effect<void, ViewError> | Changes a query collection's sort and filter (ViewModel state every presentation shares). |
| indexOfKey(collection, key) | Effect<number \| undefined, ViewError> | The position of a key in the current query, to scroll a search result into view. |
| createEffectAction(program, { runFork? }) | EffectAction & AsyncDisposable | A latest-wins runner with status, pending, value, error and cause, for any UI framework. |
| fromBridgeError(error) | ViewError | Maps a BridgeError from plain code. |
A client service is an ordinary Effect 4 Context.Service whose shape is the
generated client type. clientLayer builds it from the same sources as
connect; a ManagedRuntime built from the layer connects once and disposes the
client with the runtime:
import { Context, Effect, ManagedRuntime } from "effect";
import { clientLayer, command } from "@runic-artifex/views-effect";
import { connectEditor, type EditorClient } from "./generated/editor.js";
class Editor extends Context.Service<Editor, EditorClient>()("app/Editor") {}
const runtime = ManagedRuntime.make(clientLayer(Editor, connectEditor));
await runtime.runPromise(Effect.gen(function* () {
const editor = yield* Editor;
yield* command(() => editor.save());
}));
await runtime.dispose(); // disposes the clientThe values command and operation wrap are those of the generated client, so
every generated module works unchanged. Only Bridge failures become typed
errors. Anything else, such as the RangeError a generated method throws for
an invalid argument, is a defect.
Errors
Each error is a Data.TaggedError, so Effect.catchTag and Effect.catchTags
select them. Each keeps the original BridgeError as cause and its route.
| Tag | BridgeError kind | Meaning |
| --- | --- | --- |
| ViewUnavailable | unavailable | No host installed window.__runicBridge, for example a page served by plain Vite. |
| ViewDisconnected | disconnected | The Bridge is not connected to .NET: the transport closed or the host ended. The client decides this; .NET never sends it. |
| ViewReleased | released | The Bridge is connected, but this View was released: the client was disposed, or .NET released the View, for example because navigation replaced it. |
| ViewTimeout | timeout | A Bridge exists but did not connect in time. |
| ViewRejected | rejected | .NET refused the call. cause.reason says why when .NET sent it: unavailable (CanExecute is false) or invalid-input. |
| ViewCancelled | cancelled | .NET cancelled the call. |
| ViewFailed | failed | The handler threw or the reply was invalid, or the .NET host speaks another Views protocol version (connect fails with a protocol diagnostic). detail has the .NET exception type, message and stack in development. |
ViewError is the union of these. Operations add four more, together
ViewOperationError:
| Tag | Meaning |
| --- | --- |
| ViewOperationFailed | The operation ended as failed, or succeeded without a deliverable result. Has status and detail. |
| ViewOperationCancelled | The operation ended as cancelled. |
| ViewOperationTimedOut | The timeout option passed; cancellation says how .NET answered the cancellation request. |
| ViewOperationUncertain | The client could not observe whether .NET admitted or finished the operation, or .NET no longer knows its outcome. Has status when a terminal status (expired, unknown) said so. |
Declared failures
A .NET command that declares its failure type ([RunicFailure(typeof(SaveFailure))])
makes the generated client resolve a BridgeOutcome. command and operation
move a declared failure into the error channel as ViewDomainFailure<F>, with the
decoded value as failure and, for an operation, its requestId; the success
value is the outcome's value. Commands without a declaration keep their types, and
a failure the window could not retain is ViewOperationFailed with the delivery
message.
const saved = catchCase(command(() => editor.save()), {
titleRequired: () => Effect.succeed("A note needs a title."),
titleTaken: taken => Effect.succeed(`"${taken.existingTitle}" already exists.`),
});
// Or one tag for every case: Effect.catchTag("ViewDomainFailure", error => ...)A declared failure is a terminal outcome, so operation's retry never retries it.
Operations, interruption and retries
- When
operation(...)ends without a terminal status, it sends the cancellation request for the operation it started and waits for the reply before it completes. That covers interruption (includingEffect.timeout,Effect.race, a closing scope, and an interruption between retries), thetimeoutoption, and a failure to observe the operation after the last attempt. Each operation is cancelled at most once. - The
timeoutoption bounds the wait for the result, which starts once .NET answered the start request. It fails withViewOperationTimedOut, which carries the request ID, unless .NET answers that the operation already finished; then it reports that outcome.Effect.timeoutaround the whole Effect fails withTimeoutErrorinstead, and if it passes while the start request is in flight, it waits for that reply so the admitted operation can be cancelled. Both use the EffectClock, soTestClockcontrols them. retryis accepted only together withrequestId. Every attempt starts the operation with that ID, and .NET answers a repeated start with the operation it already runs, so the command runs at most once. OnlyViewDisconnected,ViewTimeoutandViewOperationUncertainare retried (aViewReleasedView cannot answer a retry), andwhilecan narrow that further; a failed or cancelled operation is not retried. The operation keeps running between attempts, so the next attempt observes it.- Interrupting a
commandabandons its reply only; .NET keeps running a command it received. Use an operation when a call must be cancellable.
State streams
states and connectionStates end only when they are interrupted, so run them
in the scope that connected the client. connectionStates follows
onBridgeConnection: reconnecting after the transport dropped (clients keep
their last state meanwhile), lost after lostAfter milliseconds (5000 by
default) without a connection, and connected again when the host is back.
After the application closed the window it is closed, also once the
connection drops:
yield* Effect.forkScoped(connectionStates().pipe(
Stream.filter(state => state === "lost"),
Stream.runForEach(() => Effect.log("The application stopped responding.")),
));states ends only when it is interrupted. When .NET pushes a collection change the client cannot
apply, or the transport reconnects, the runtime re-reads the snapshot and the
stream receives it as an ordinary state; the stream does not fail. Read
failures of that re-read are reported through onBridgeDiagnostic from
@runic-artifex/views.
Translated text
texts(value, fallback?) is a stream of a text reference's text in the window's
language: the text now, then the text after each language switch.
textChanges() emits on each switch, and textLocales() is the locale that
text is shown in, now and after each switch, for rendering the page's own
m.*() messages again. In vite dev with the Translations Vite plugin 0.12.0
or later, textLocales() emits the same locale again when an edited message
updates in place (Edited messages in vite dev). Connect the page's Translations runtime
once with configureTranslatedText from @runic-artifex/views
(Translated text).
Appearance
appearances() is a stream of the page's appearance: the appearance now, then
each new one, from the engine's media queries or a host push
(Appearance).
View requests
client.requests.<name>.handle(handler) of a generated client registers the
handler of a ViewModel's ViewRequest<T> and returns the function that removes
it, so Effect.acquireRelease keeps it for the scope that connected the client:
const program = Effect.gen(function* () {
const editor = yield* connect(connectEditor);
yield* Effect.acquireRelease(
Effect.sync(() => editor.requests.focus.handle(({ member }) => focusField(member))),
remove => Effect.sync(remove),
);
yield* Effect.never;
}).pipe(Effect.scoped);The handler is a plain function: it runs once the page painted the state the
request was raised with, and its signal aborts when it is removed, the client
is disposed or the connection is lost. To run an Effect from it, fork it with
the runtime the application uses. A request is never replayed; see
View requests.
Framework helpers
Bindings keep rendering state with useView and its equivalents; Effect runs
workflows. createEffectAction is framework-neutral (current, subscribe,
run, interrupt, reset, dispose). run interrupts the previous run of
the same action and resolves to its Exit; it never rejects. dispose()
returns a Promise because interrupting a fiber is asynchronous, unlike the
dispose(): void of the other Runic controllers. The action also has
[Symbol.asyncDispose](), which calls dispose(), so await using releases it
where the engine defines Symbol.asyncDispose; elsewhere the package loads
unchanged and dispose() remains:
{
await using search = createEffectAction((query: string) => findNotes(query));
await search.run("runic");
} // await search.dispose()React has useEffectAction from @runic-artifex/views-effect/react. Unmounting
interrupts the current run, which cancels an operation in .NET:
import { operation } from "@runic-artifex/views-effect";
import { useEffectAction } from "@runic-artifex/views-effect/react";
import { useView } from "@runic-artifex/react";
export function EditorPage({ page }: { page: EditorPageReference }) {
const { state, client } = useView(page);
const save = useEffectAction(() => operation(() => client!.startSave(), { timeout: "10 seconds" }));
return <>
<button disabled={!client || !state?.canSave || save.pending} onClick={() => void save.run()}>Save</button>
{save.error?._tag === "ViewOperationTimedOut" && <p role="alert">Saving took too long and was cancelled.</p>}
</>;
}Outside React there is no adapter (the package is headless): wrap
createEffectAction in your framework's store and call dispose() when the
component is destroyed. In Vue:
import { createEffectAction, operation } from "@runic-artifex/views-effect";
import { onScopeDispose, shallowRef } from "vue";
const save = createEffectAction(() => operation(() => client.value!.startSave(), { timeout: "10 seconds" }));
const saveState = shallowRef(save.current);
const stop = save.subscribe(() => { saveState.value = save.current; });
onScopeDispose(() => { stop(); void save.dispose(); });Svelte does the same with $state and an $effect cleanup, and Angular with a
signal and DestroyRef.onDestroy.
This package has no field binding of its own. Bind inputs with createFieldController
from @runic-artifex/views and a generated {View}Fields descriptor, or with the
framework packages' useField (React useField from @runic-artifex/react), rather
than a command per keystroke in an Effect action: a
new run interrupts the previous one, which abandons its reply but not the write,
and the binding keeps the draft and orders and coalesces the writes. operation
completes with the outcome only; to show a running operation's progress, use the
framework packages' useOperation (injectOperation) or the handle's
subscribe(listener) of @runic-artifex/views.
A program that needs services runs through your runtime:
createEffectAction(program, { runFork: runtime.runFork }), with runtime a
ManagedRuntime. Helpers based on effect/reactivity atoms will follow when
that module is stable.
Fields and forms need no Effect wrapper: use createFieldController and createFormController from
@runic-artifex/views, and run a form's submit inside an action, such as
createEffectAction(() => Effect.promise(() => form.submit(() => editor.save()))).
The descriptors of row cells and nested members (InvoiceFields.lines.at(key).quantity, InvoiceFields.address.street,
field-paths/1) work with createFieldController the same way.
Testing
@runic-artifex/views/mock serves generated clients without .NET, and the
adapter's timeouts follow TestClock:
import { installMockBridge } from "@runic-artifex/views/mock";
import { TestClock } from "effect/testing";
const bridge = installMockBridge();
// Serve the View with its state; "manual" keeps its Save operations running until the test ends them.
bridge.view("editor", { state: editorState, operations: { save: "manual" } });
const client = await connectEditor();
const exit = await Effect.runPromise(Effect.gen(function* () {
const fiber = yield* Effect.forkChild(operation(() => client.startSave()).pipe(Effect.timeout("5 seconds")));
yield* TestClock.adjust("5 seconds");
return yield* Fiber.await(fiber);
}).pipe(Effect.provide(TestClock.layer())));
// The timeout cancelled the operation: bridge.calls now contains its `cancel` request.
bridge.calls.some(call => call.kind === "cancel" && call.member === "save"); // trueBundle cost
Measured on 2026-10-07 for 0.7.0-preview.1 with esbuild 0.28.2
(--bundle --minify --format=esm --target=es2023) and Node.js zlib gzip level 9, against the
generated Notes Editor client of
the Notes example,
whose Save declares a failure, and Effect 4.0.1. The
adapter and these bundles import Effect modules by subpath (effect/Effect,
effect/Stream); importing from the effect barrel, as in the last row, more
than doubles the cost, so prefer subpath imports in browser code:
| Bundle | gzip bytes |
| --- | --- |
| Plain client: connect, subscribe, command, operation with wait timeout and cancel | 7,795 |
| Adapter: command and operation, plain subscribe | 22,292 |
| Adapter: scoped connect, states Stream, command, operation with timeout | 27,387 |
| Notes frontend, plain | 11,371 |
| Notes frontend with the Effect editor | 30,024 |
| Same adapter bundle, importing { Effect, Stream } from "effect" | 62,566 |
The plain client row was 9,358 bytes before the 0.7 entry split, which brought
it to 6,833; declared failures (BridgeOutcome, the
operation status union and Save's failure decoder) add 962, and 1,116 to the plain
Notes frontend. bun run size in packages/web/views reproduces the plain
client row.
Applications that do not import this package do not pay for it.
