Skip to content

Resumable messages

A normal Arona message keeps its component models inside the running renderer fiber. When the process exits, the buttons still exist on Discord, but nothing can interpret them. A resumable message moves the source of truth into a MessageSessionStore and puts enough routing context into every custom_id to find it again.

interface MessageSession {
id: string; // primary key, embedded in custom ids
version: number; // the state version the message currently shows
status: "pending" | "active" | "closed";
component: string; // client registry key
build: string; // application fingerprint, "" disables the check
props: unknown; // caller-encoded props
state: Renderer.State; // Root.snapshot() from effect/ui
message?: { id: string; channelId?: string; guildId?: string };
ephemeral: boolean;
createdAt: number;
updatedAt: number;
expiresAt?: number;
lastInteractionId?: string;
}

state is the same encoded model tree Renderer.prerender produces. Instances whose model holds Schema.Redacted, and instances whose Layer was kept off the renderer, are deferred and start from init again.

The store is a Layer. FileStore.layer is portable and requires Effect’s FileSystem/Path services; FileStore.layerNode wires Node’s implementations:

import { MemoryStore } from "@arona/core";
import { FileStore } from "@arona/core/node";
import * as SqliteStore from "@arona/store-sqlite";
// Tests and a single gateway process.
const memory = MemoryStore.layer();
// Local development, one writer process.
const files = FileStore.layerNode("./.arona/sessions");
// One Node process, SQL compare-and-swap. Opens, migrates and closes the file.
const sqlite = SqliteStore.layer({ filename: "./.arona/sessions.sqlite" });

A client layer reads MessageSessionStore from the context when it is present, so providing the store layer to the client is all it takes to enable resume.

Every implementation provides create, get, update (version CAS), setState, attachMessage, findByMessage, close, sweep, and listActive. sweep and listActive are bounded pages: pass the returned cursor back until it is absent. A durable adapter such as Postgres, Redis, D1, or DynamoDB only needs those operations; update is the concurrency primitive.

const resumeAll = Effect.gen(function* () {
let cursor: string | undefined;
do {
const page = yield* store.listActive({
limit: 100,
...(cursor === undefined ? {} : { cursor }),
});
resume(page.sessions);
cursor = page.cursor;
} while (cursor !== undefined);
});
import { mountSessionMessage } from "@arona/platform-discord";
import { FileStore } from "@arona/core/node";
import { Effect } from "effect";
const sessions = FileStore.layerNode("./.arona/sessions");
const { root, session } =
yield *
mountSessionMessage(
interaction,
Counter,
{},
{
componentKey: "counter",
sessionProps: {}, // must be serialisable for a durable store
},
).pipe(Effect.provide(sessions));
// Later, after a restart, pass the loaded record and the existing message:
yield *
mountSessionMessage(
interaction,
Counter,
{},
{
componentKey: "counter",
session,
resume: interaction.message,
skipInitial: true,
},
).pipe(Effect.provide(sessions));

The first mount sends the message and stores its initial state at version 0. Each handled interaction snapshots the tree, stores the next state with a CAS update, and edits the message. A resumed mount does not call init for instances whose state ships.

A press can arrive while another process holds the writer lease. The interaction waits up to interactionWindowMs (1 second by default), retrying every interactionRetryMs (50 ms), and only drops with a warning when the window closes. That keeps a press made just after a slow commit instead of rejecting it as “session is busy”.

const config = Effect.runSync(
Config.all({
token: Config.Redacted("DISCORD_APP_TOKEN"),
clientId: Config.String("DISCORD_APP_ID"),
build: Config.option(Config.String("BUILD_ID")),
}),
);
const clientLayer = DiscordGatewayClient.layer({
token: config.token,
clientId: config.clientId,
intents: [Intent.Guilds],
devGuildId: Option.none(),
build: config.build,
}).pipe(Layer.provide(SqliteStore.layer({ filename: "./.arona/sessions.sqlite" })));
// Inside your effect:
const client = yield * DiscordGatewayClient;
client.registerComponent("counter", Counter);

DiscordGatewayClient.layer requires a MessageSessionStore. Use DiscordGatewayClient.layerEphemeral when the bot does not need resume. Two clients that need different stores should be built from separate layers.

With a store in the layer context:

  • slash commands built with SlashCommand.make use mountSessionMessage; their stored props are { params }, and the current interaction is restored through the component’s decodeProps hook;
  • a component interaction with an Arona custom_id is routed by session, not by scanning in-memory roots;
  • if no warm root exists, the client loads the record and mounts a resumed root against interaction.message;
  • a stale version heals the message from stored state and drops the click.

registerComponent(key, component, { decodeProps }) is how a cold process turns stored props back into live props. The default passes stored props through unchanged.

Commands provided through the client commands option also register their component and decodeProps hook at startup. That matters after a restart: the button click arrives before the command handler ever runs, and the client still has to know which component and command params to mount.

With a session bound, auto ids are document-order ordinals and explicit ids keep the author’s text as the key. Both are wrapped:

ar1.<sessionId>.<versionBase36>.<key>

key is a0, a1, … for auto ids and the author’s customId otherwise. The envelope stays under Discord’s 100-character limit; a longer explicit id fails at commit.

The ordinal is assigned at commit time, not node creation time. A restored tree that reaches the same final model therefore produces the same ids, even if the original process built it incrementally. If an interactive node moves or leaves, the next edit carries the recomputed ids.

On the gateway, the warm root map is only a cache. After a restart, the first interaction for a session loads the record and resumes lazily. Self-updating messages (queries, subscriptions, unmountAfter) do not run while the process is down; resume them eagerly by paging listActive until its cursor is absent if that matters.

createInteractionsHandler is a Fetch API handler for Discord’s Interactions Endpoint URL. It verifies the Ed25519 signature, answers PING, and feeds the shared core and session store through DiscordWorkerClient:

import { createInteractionsHandler, DiscordRest } from "@arona/platform-discord";
import { DiscordWorkerClient } from "@arona/platform-discord/worker";
const clientLayer = Layer.merge(
DiscordWorkerClient.layer({
build: config.build,
commands: [],
}).pipe(Layer.provide(sqlite)),
DiscordRest.layerFetch({ token: config.token }),
);
const handler = (request: Request) =>
Effect.gen(function* () {
const client = yield* DiscordWorkerClient;
client.registerComponent("counter", Counter);
return yield* createInteractionsHandler({
client,
publicKey: interactionConfig.publicKey,
// Inline: process before responding, so a modal can be the answer.
// A slow first frame auto-defers after `firstFrameTimeout` (2s default).
defer: false,
})(request);
}).pipe(Effect.provide(clientLayer));

Point the platform route at handler and pass the Request. The default verifier uses Node’s crypto; pass verify to plug in WebCrypto for a different runtime. Two modes:

  • defer: false (default) processes before responding. The first message update or modal becomes the interaction response, so dialogs work. If no response is ready within firstFrameTimeout (2 seconds by default), the handler acknowledges with type 5/type 6 and finishes through REST instead of missing Discord’s three-second callback window. A response produced just before the budget is still used. Pass firstFrameTimeout: false to disable the fallback.
  • defer: true returns type 5/type 6 immediately and continues through REST. Use the platform’s background hook (ctx.waitUntil, waitUntil, SQS, …). Modals cannot be opened after an acknowledgement, so keep modal-opening interactions on the inline path and below the first-frame budget.

Raw JSON messages, channel edits, and interaction-token edits are handled by the bundled DiscordRest client. Message file uploads over HTTP are not supported yet.

Keep these constraints in mind:

  • gateway and HTTP interactions are mutually exclusive per application;
  • HTTP gives you commands, buttons, selects, modals, and autocomplete, not MESSAGE_CREATE;
  • an interaction is not retried, so persist the session before acknowledging;
  • the token for @original lasts 15 minutes, while bot-token channel edits can continue after that for non-ephemeral messages;
  • a modal that was itself the initial response to a command has no platform message yet, so message-session resume cannot recover it on submit.
  • State is decoded with the component schemas. A different build must not resume it; set build and treat a mismatch as expired.
  • Props must be JSON-serialisable when the store is durable.
  • The file store checks CAS before writing but is not a multi-writer transaction. Use a database when several processes share state.
  • The HTTP adapter mounts a fresh root per request and releases session roots afterwards. It assumes one in-flight interaction per process; the store CAS prevents corruption, but add a per-session lease for concurrent handlers.
  • MemoryStore.layer loses sessions on a cold start. Behind HTTP, use a shared durable store.
  • HTTP message file uploads are not supported yet.
  • The snapshot/resume API is currently carried by the local djobbo/effect effect-ui branch (Root.snapshot and mount({ state })). Rebase that branch when upgrading.