@lunora/angular is the Angular adapter for Lunora. It's a thin layer over the
framework-neutral @lunora/client, which owns the
WebSocket transport, subscription registry, offline queue, and delta-merge.
Angular signals map directly onto Lunora's per-subscription deltas, so a live
query is a signal the WebSocket writes to.
The API is signal-first and at parity with the other adapters: a dependency injection (DI) token
carrying one shared client, liveQuery, subscription, mutate/mutator,
runAction, stream, paginatedQuery/infiniteQuery, presence,
rateLimit, flag/flags, auth/authGate, liveTopic, the agent and voice primitives,
connectionStatus, and hydratePreloaded alongside the @lunora/angular/server
subpath for the server-side rendering (SSR) handoff.
Install
pnpm add @lunora/angular@angular/core (^19.2.0 || ^20.0.0 || ^21.0.0 || ^22.0.0) is a peer
dependency; the host app supplies the Angular runtime.
Exports
| Symbol | Kind | Role |
|---|---|---|
provideLunora | provider factory | Wires a LunoraClient into the application injector. Add to your app config. |
injectLunoraClient | function | Read the LunoraClient from the current injector. Throws outside an injection context; inside DI, LUNORA_CLIENT's root-scoped default applies when no provider was registered. |
LUNORA_CLIENT | injection token | The DI token every reactive primitive resolves the client from. Root-scoped default: a same-origin browser client. |
liveQuery | function | Live query as an Angular Signal. Pass a function/Signal for reactive args, or "skip" to short-circuit. |
mutate | function | Run a mutation and resolve with the server result. Optimistic updates + offline queue pass through to the client. |
runAction | function | Run an action and resolve with the server result. No optimistic options — an action is not a write. |
connectionStatus | function | Signal of the aggregate live-socket status across all shard connections. |
Beyond the table: subscription, mutator, stream, paginatedQuery /
infiniteQuery, presence, rateLimit, flag / flags, auth / authGate,
agent, agentChat, agentState, agentToolEvents, voiceAgent, and
hydratePreloaded (with the @lunora/angular/server subpath) are all exported
too — see the sections below and the package's src/index.ts for the full list.
Re-exported types: ArgsOf, ConnectionStatus, FunctionReference,
LunoraClient, LunoraClientOptions, MutationCallOptions, Preloaded, ReturnOf,
SubscriptionError, Unsubscribe, plus ProvideLunoraOptions,
LiveQueryOptions, ConnectionStatusOptions, MutateOptions, and
RunActionOptions. The SKIP sentinel ("skip") is re-exported from
@lunora/client/query.
Wire the client — provideLunora / injectLunoraClient / LUNORA_CLIENT
Add provideLunora to your application config. It defaults to the page origin
(the single-worker deploy where /_lunora/ws loops back into the app's own
worker); pass options to point at a remote URL, or hand it an
already-constructed LunoraClient to share one instance.
import { provideLunora } from "@lunora/angular";
import type { ApplicationConfig } from "@angular/core";
export const appConfig: ApplicationConfig = {
providers: [provideLunora(/* { url: "https://api.example.com" } */)],
};LUNORA_CLIENT (the underlying InjectionToken) has a root-scoped default
factory, so every reactive primitive resolves a client even without
provideLunora: it builds one same-origin browser client lazily. Call
injectLunoraClient() inside an injection context (a component/service field
initializer or constructor) to hold the client for imperative calls, since
mutations usually fire from event handlers, which run outside an injection
context:
import { Component } from "@angular/core";
import { injectLunoraClient, mutate } from "@lunora/angular";
import { api } from "../lunora/_generated/api";
@Component({/* … */})
export class Composer {
private readonly client = injectLunoraClient();
send(text: string) {
return mutate(api.messages.send, { text }, { client: this.client });
}
}liveQuery(fn, args, options?)
Subscribes to a server query and mirrors its value into an Angular signal.
Reads undefined until the first server frame lands, then updates on every
delta the WebSocket pushes. The subscription tears down automatically when the
owning DestroyRef fires (DestroyRef.onDestroy), by default the calling
component/service's own DestroyRef, resolved via inject(DestroyRef).
Call it from an injection context so the default DestroyRef resolves the
caller's lifetime:
import { Component } from "@angular/core";
import { liveQuery } from "@lunora/angular";
import { api } from "../lunora/_generated/api";
@Component({
selector: "app-messages",
standalone: true,
template: `@for (m of messages()?.messages ?? []; track m.id) {
<p>{{ m.text }}</p>
}`,
})
export class MessagesComponent {
readonly messages = liveQuery(api.messages.list, { channelId: "general" });
}Pass "skip" (the SKIP sentinel from @lunora/client/query) as args to
short-circuit: no network call, no socket; the signal stays undefined.
readonly profile = liveQuery(api.users.me, signedIn ? {} : "skip");args may be a plain value or a function/Signal. A plain value resolves
once and never re-runs. A function is reactive, like the Vue/Solid adapters:
each change tears the previous subscription down, resets the signal to
undefined, and opens a fresh one — so calling it from outside an injection
context needs an explicit injector alongside client/destroyRef.
subscription and paginatedQuery/infiniteQuery take the same form. Pass
{ shardKey } to route to a specific shard when the target
function is .shardBy(...)-partitioned, and { onError } to observe a
post-attach subscription failure (without it, a failure after the initial
attach is dropped silently and the signal stops updating). To call
outside an injection context (e.g. lazily in ngOnInit), supply client and
destroyRef explicitly via the options object.
liveTopic(source, options?)
Follows one topic a defineLiveStream declares, and mirrors the last payload and
any refusal into lastEvent and error signals. It subscribes when the owning
DestroyRef is created and unsubscribes when it is destroyed.
source is the reference _generated/live.ts hands out, or a function returning
one. The stream's route is resolved against the injected LunoraClient, and
lastEvent and onEvent are typed by the payload the topic declares. A function
makes the topic reactive: a new topic resubscribes, while a new onEvent or
onError is read at call time and does not. options takes client,
destroyRef and injector, which the reactive form needs when called outside an
injection context, plus shardKey and sessionKey (each a string or a function returning one, which resubscribes on change) and the transport tuning headers,
withCredentials, retryDelay and maxDelayMs.
readonly comments = liveTopic(() => live.posts.comments({ postId: this.postId() }));mutate(fn, args, options?)
Runs a Lunora mutation and resolves with the server result (rejects on
failure). Optimistic updates stay client-owned: the optimistic /
optimisticUpdate call options pass straight through to client.mutation,
which applies and rolls them back against the live subscription cache, the
same cache liveQuery reads, so an optimistic write reflects immediately and
reverts on failure. The client's offline queue also engages when the socket is
down, so the write stays durable across reconnects.
import { injectLunoraClient, mutate } from "@lunora/angular";
import { api } from "../lunora/_generated/api";
@Component({/* … */})
export class Composer {
private readonly client = injectLunoraClient();
send(channelId: string, text: string) {
return mutate(
api.messages.send,
{ channelId, text },
{
client: this.client,
optimisticUpdate: (store, args) => {
const current = store.getQuery(api.messages.list, { channelId: args.channelId }) ?? [];
store.setQuery(api.messages.list, { channelId: args.channelId }, [...current, { text: args.text }]);
},
},
);
}
}When called from within an injection context you may omit client and let it
resolve from the injector, the same way liveQuery and connectionStatus do.
runAction(fn, args, options?)
Runs a Lunora action and resolves with the server result (rejects on failure).
Like mutate, it's a plain function rather than a reactive handle: Angular's
adapter models writes as calls, because they fire from event handlers where a
signal-returning primitive has nothing to bind to. The other adapters return a
reactive { call, pending, … } handle because their idioms make that natural;
this one does not, so track pending state with your own signal if you need it.
import { injectLunoraClient, runAction } from "@lunora/angular";
import { api } from "../lunora/_generated/api";
@Component({/* … */})
export class Toolbar {
private readonly client = injectLunoraClient();
verify() {
return runAction(api.commands.run, { command: "lunora", args: ["verify"] }, { client: this.client });
}
}Options are { client, shardKey }. Unlike mutate there are no optimistic /
optimisticUpdate options: an optimistic update patches the subscription cache
on the assumption a write will land, and an action is not a write — it runs in
the Worker, may call a third party, and has no declared effect on any query.
When called from within an injection context you may omit client.
connectionStatus(options?)
A signal of the client's aggregate live-socket status across all shard
connections. Reads the current status synchronously and updates on every
transition (idle, connecting, connected, offline or polling). The listener is
removed when the owning DestroyRef fires.
import { connectionStatus } from "@lunora/angular";
@Component({/* … */})
export class ConnectionBadge {
readonly status = connectionStatus(); // Signal<"idle" | "connecting" | "connected" | "offline" | "polling">
}Agent tool events — agentToolEvents(options)
Observes one agent thread's tool activity, separate from its chat
transcript: which tools the model called, what they returned, which are parked
on a human approval, and any in-flight ctx.reportProgress(...) updates.
options: { api, threadKey, stream?, limit?, client?, destroyRef? } — api
is the generated api (it reads api.agents.agentMessages), and stream is
the same app stream reference agentChat takes. Returns { events }, a
Signal. Call it from an injection context (a field initializer or constructor)
so the default inject(DestroyRef) owns the teardown; pass client +
destroyRef to call it anywhere else.
Each event discriminates on type:
type | Fields | Source |
|---|---|---|
call | toolCallId, toolName, input, seq | durable |
result | toolCallId?, toolName?, output, status?, seq | durable |
awaiting-approval | toolCallId?, toolName?, seq | durable |
awaiting-secret | toolCallId?, toolName?, seq | durable |
progress | toolCallId, data | live stream |
Durable events come first, oldest first by seq, followed by the ephemeral
progress events for the in-flight turn. With no stream reference only the
durable lifecycle is surfaced. The array is rebuilt on every update — treat it
as derived, not identity-stable, and key rendered rows on toolCallId/seq.
import { Component } from "@angular/core";
import { agentToolEvents } from "@lunora/angular";
import { api } from "./lunora/_generated/api";
@Component({
selector: "tool-timeline",
template: `<ol>
@for (event of events(); track $index) {
<li>{{ event.type }}</li>
}
</ol>`,
})
export class ToolTimelineComponent {
readonly events = agentToolEvents({ api, stream: api.chat.liveEvents, threadKey: "thread-1" }).events;
}Voice agents — voiceAgent(options)
Opens a full-duplex voice call against a voice-enabled agent — the
api.agents.<name>Voice reference codegen emits. Microphone capture goes up the
agent's WebSocket, synthesized speech comes back down, and transcripts plus
barge-in are surfaced along the way.
options: { voice, threadKey, silenceThreshold?, silenceDurationMs?, interruptThreshold?, interruptChunks?, createMicrophone?, createSocket?, createSpeaker?, client?, destroyRef? }. threadKey is shared with the agent's
text turns, so a voice call continues the very same conversation agentChat
renders.
Returns { status, connected, transcript, interimTranscript, audioLevel, isMuted, error, startCall, endCall, sendText, toggleMute }, where every value
is a Signal. status is
"idle" | "listening" | "thinking" | "speaking".
import { Component } from "@angular/core";
import { voiceAgent } from "@lunora/angular";
import { api } from "./lunora/_generated/api";
@Component({
selector: "call-button",
template: `
<button (click)="call.status() === 'idle' ? call.startCall() : call.endCall()">
{{ call.status() === "idle" ? "Call" : "Hang up" }}
</button>
<meter max="1" [value]="call.audioLevel()"></meter>
<p>{{ call.transcript() }}</p>
`,
})
export class CallButtonComponent {
readonly call = voiceAgent({ threadKey: "thread-1", voice: api.agents.supportVoice });
}Microphone and audio lifecycle
The part the type signature does not tell you:
- Nothing opens until
startCall(). Creating the handle touches neither the microphone nor the socket.startCallis what callsgetUserMedia, so it has to run from a user gesture — browsers block both the permission prompt andAudioContextresumption outside one. It is idempotent while a call is active, and a denied permission lands inerrorrather than throwing at the call site. - A failed turn drops its partial answer. When the model fails mid-answer (or its
stream is cut short), the text already streamed for that turn is cleared from
interimTranscriptanderroris set; the call returns tolistening. A retried turn starts its text from empty, never from the failed attempt's prefix. endCall()releases everything — the socket, the microphone tracks, and the Web Audio graph — and is idempotent. The owningDestroyRefcalls it on destroy, so a destroyed component ends its call.audioLevelis the live input root mean square (RMS) level (0–1). It drives a mic meter, and it is also what the heuristics read:silenceThreshold+silenceDurationMsdecide when an utterance auto-commits (defaults0.01/1200ms), andinterruptThreshold+interruptChunksdecide when the user barges in on the agent mid-sentence (defaults0.15/3consecutive chunks). These are room-dependent; tune them against real hardware rather than trusting the defaults.createMicrophone/createSpeaker/createSocketare injection seams for tests and non-DOM hosts. The defaults aregetUserMedia+ Web Audio +new WebSocket(url), so the primitive is inert (and mockable) anywhere those are missing.
API reference
Each entry lists the signature, then the options and the result. The
signatures are taken from packages/angular/src.
subscription(reference, args, options?)
Type: (reference, args: ArgsOf<F> | "skip" | (() => ArgsOf<F> | "skip"), options?: SubscriptionOptions) => SubscriptionResult<ReturnOf<F>>
Subscribes to a query and returns its data and error signals. Use it when
you need the error signal, because liveQuery only reports failures through
onError. Options are client, destroyRef, injector, onError and
shardKey.
paginatedQuery(reference, args, options)
Type: (reference, args: PaginatedArgs<F> | "skip" | (() => PaginatedArgs<F> | "skip"), options: PaginatedQueryOptions) => PaginatedQueryResult<PageItemOf<F>>
Subscribes to a paginated query. initialNumItems is required. Returns the
results, status, isLoading and error signals and loadMore(numberItems).
Options also take client, destroyRef, injector, onError and shardKey.
infiniteQuery(reference, args, options)
Type: (reference, args: PaginatedArgs<F> | "skip" | (() => PaginatedArgs<F> | "skip"), options: PaginatedQueryOptions) => InfiniteQueryResult<PageItemOf<F>>
The same subscription as paginatedQuery, shaped for infinite scroll. Returns
the pages, status, hasNextPage, isFetchingNextPage, isLoading and
error signals and fetchNextPage(numberItems?).
stream(reference, args, options?)
Type: (reference, args: ArgsOf<F> | "skip", options?: StreamOptions) => StreamResult<ReturnOf<F>>
Subscribes to a stream function. Returns the chunks and error signals, a
status signal ("idle" | "streaming" | "complete" | "error") and cancel().
Options are client, destroyRef, durable, maxBuffer and shardKey.
mutator(handle)
Type: <TArgs>(handle: MutatorHandle<TArgs>) => MutatorResult<TArgs>
Wraps a mutation handle for template-driven calls. Returns mutate(args), which
resolves once the write completes, and the pending, error and isError
signals. reset() clears the error.
presence(roomId, options)
Type: <H, L>(roomId: string, options: PresenceOptions<H, L>) => PresenceResult<L>
Joins a presence room. heartbeat and listPresent are required. Options
also take client, data, destroyRef, intervalMs, onError, sessionId
and shardKey. Returns the present and error signals, the sessionId, and
setData(data).
rateLimit(config, options?)
Type: (config: RateLimitConfig, options?: RateLimitOptions) => RateLimitResult
Tracks a client-side rate limit. Options are destroyRef, now (a clock
returning milliseconds) and tickMs, which defaults to 1000. Returns the
ok, disabled and retryAfter signals, check(count?), consume(count?)
and reset().
flag(key, defaultValue, options?)
Type: <T extends FlagValue>(key: string, defaultValue: T, options?: FlagOptions) => Signal<T>
Returns a signal of one feature flag's value. Options are client and
destroyRef.
flags(defaults, options?)
Type: <T extends Record<string, FlagValue>>(flagDefaults: T, options?: FlagsOptions) => Signal<T>
Returns a signal of several feature flags, keyed as in defaults. Options are
client and destroyRef.
auth(options?)
Type: (options?: AuthOptions) => AuthResult
Returns the signed-in user, the token and the status signals, and
setToken(token), which takes null to clear the session. Options are client
and destroyRef.
authGate(options?)
Type: (options?: AuthOptions) => AuthGateResult
Returns the isAuthenticated and isLoading signals for guarding a route or a
template. Takes the same options as auth.
hydratePreloaded(preloaded, options?)
Type: <T>(preloaded: Preloaded<T>, options?: HydratePreloadedOptions) => HydratePreloadedResult<T>
Hydrates a query that the server preloaded into a live subscription. Returns
the data and error signals. Options are client
and destroyRef. The Preloaded value comes from the @lunora/angular/server
helpers.
agentState(options)
Type: <T>(options: AgentStateOptions) => AgentStateResult<T>
Subscribes to one agent thread's state through the generated
api.agents.agentState query. Options are api, threadKey, client and
destroyRef. Returns the state and error signals.
agentChat(options)
Type: (options: AgentChatOptions) => AgentChatResult
Renders one agent thread's messages and sends turns to it. Options are api,
threadKey, stream, send, sendArgs, cancel, limit, onError and
client.
agent(options)
Type: (options: AgentOptions) => AgentResult
Thread-level agent primitive. The options and result are typed by
AgentOptions and AgentResult in packages/angular/src/agent.ts.
@lunora/angular/upload
Type: (options: UploadOptions) => UploadApi
Uploads files through the framework-neutral storage client. The subpath also
exports createUpload, createTusAdapter, createMultipartAdapter,
createChunkedRestAdapter and UploadControl.
@lunora/angular/server
Re-exports createServerClient, preloadQuery, preloadedQueryResult,
getServerSession, serializePreloaded and deserializePreloaded from
@lunora/client/ssr.