-
+
{#if fieldError(postMessage.error, "body")}
{fieldError(postMessage.error, "body")}
{/if}
@@ -65,14 +114,17 @@
{postMessage.isPending ? "Posting…" : "Post"}
+ {#if typingBy}
+
{typingBy} is typing…
+ {/if}
{/if}
Recent
-{#if ctx.data.feed.length === 0}
+{#if feed.length === 0}
No messages yet. Set a display name and write the first one.
{:else}
- {#each ctx.data.feed as item (item.id)}
+ {#each feed as item (item.id)}
-
{item.displayName}
{item.body}
diff --git a/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/Board.kt b/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/Board.kt
index 7545dcc..2c43663 100644
--- a/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/Board.kt
+++ b/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/Board.kt
@@ -1,7 +1,10 @@
package dev.kolektiv.keel.samples.harbor
import dev.kolektiv.keel.KeelAction
+import dev.kolektiv.keel.KeelEvent
+import dev.kolektiv.keel.event.EventDirection
import dev.kolektiv.keel.ktor.PageValidationException
+import dev.kolektiv.keel.ktor.realtime.keelRealtime
import io.ktor.server.application.ApplicationCall
import java.time.Instant
import java.time.temporal.ChronoUnit
@@ -74,6 +77,7 @@ object Board {
)
created
}
+ notifyNameChanged(this, user)
return SetNameOut(user.toRef())
}
@@ -101,9 +105,36 @@ object Board {
at = timestamp(),
)
messages.add(0, message)
- return PostMessageOut(message.toFeedItem())
+ val item = message.toFeedItem()
+ keelRealtime.publish(HOME_CHANNEL, "harbor.message", item)
+ return PostMessageOut(item)
}
+ /**
+ * Client-sent typing notice: echo it to everyone watching the board. The
+ * handler is an `ApplicationCall` extension so cookies identify the
+ * author; the payload is the same `OUT`/`IN` type.
+ */
+ @KeelEvent("harbor.typing", EventDirection.BOTH)
+ fun ApplicationCall.typing(input: TypingNotice) {
+ val author = viewer(this) ?: return
+ if (input.displayName.isNotBlank() && input.displayName != author.displayName) {
+ throw PageValidationException(
+ mapOf("displayName" to listOf("Not your display name.")),
+ Unit,
+ )
+ }
+ keelRealtime.publish(HOME_CHANNEL, "harbor.typing", TypingNotice(author.displayName))
+ }
+
+ fun notifyNameChanged(call: ApplicationCall, user: User) {
+ // Flavor (b): tell home viewers to rehydrate the seed; renamed authors
+ // are then consistent everywhere.
+ call.keelRealtime.invalidate(HOME_CHANNEL, path = "/")
+ }
+
+ const val HOME_CHANNEL: String = "page:harbor.home"
+
private fun newId(): String = UUID.randomUUID().toString()
private fun timestamp(): String = Instant.now().truncatedTo(ChronoUnit.SECONDS).toString()
diff --git a/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/HarborApp.kt b/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/HarborApp.kt
index 3c8d0a2..fe25d6b 100644
--- a/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/HarborApp.kt
+++ b/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/HarborApp.kt
@@ -1,15 +1,21 @@
package dev.kolektiv.keel.samples.harbor
import dev.kolektiv.keel.bundle.FrontendBundle
+import dev.kolektiv.keel.event.EventDirection
import dev.kolektiv.keel.ktor.CspPolicy
import dev.kolektiv.keel.ktor.PageMissingException
import dev.kolektiv.keel.ktor.SharedProvider
import dev.kolektiv.keel.ktor.keel
import io.ktor.server.application.Application
+import io.ktor.server.application.install
+import io.ktor.server.sse.SSE
+import io.ktor.server.websocket.WebSockets
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
fun Application.harbor(bundle: FrontendBundle) {
+ install(WebSockets)
+ install(SSE)
keel {
this.bundle = bundle
watchPacks = true
@@ -45,5 +51,11 @@ fun Application.harbor(bundle: FrontendBundle) {
}
}
actions(Board)
+ realtime {
+ // Typed board events the host pushes, plus the `@KeelEvent`
+ // handlers on Board for client-sent notices.
+ event("harbor.message", EventDirection.OUT)
+ events(Board)
+ }
}
}
diff --git a/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/Pages.kt b/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/Pages.kt
index 5a6e81e..619c835 100644
--- a/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/Pages.kt
+++ b/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/Pages.kt
@@ -1,6 +1,8 @@
package dev.kolektiv.keel.samples.harbor
+import dev.kolektiv.keel.KeelEvent
import dev.kolektiv.keel.KeelType
+import dev.kolektiv.keel.event.EventDirection
import kotlinx.serialization.Serializable
@KeelType
@@ -10,6 +12,7 @@ data class UserRef(
val displayName: String,
)
+@KeelEvent("harbor.message", EventDirection.OUT)
@KeelType
@Serializable
data class FeedItem(
@@ -56,3 +59,8 @@ data class PostMessageIn(val body: String)
@KeelType
@Serializable
data class PostMessageOut(val message: FeedItem)
+
+/** Client-sent "someone is writing" notice, echoed to the same channel. */
+@KeelEvent("harbor.typing", EventDirection.BOTH)
+@Serializable
+data class TypingNotice(val displayName: String)
diff --git a/samples/harbor/src/test/kotlin/dev/kolektiv/keel/samples/harbor/HarborAppTest.kt b/samples/harbor/src/test/kotlin/dev/kolektiv/keel/samples/harbor/HarborAppTest.kt
index b491e5f..bd9f9a8 100644
--- a/samples/harbor/src/test/kotlin/dev/kolektiv/keel/samples/harbor/HarborAppTest.kt
+++ b/samples/harbor/src/test/kotlin/dev/kolektiv/keel/samples/harbor/HarborAppTest.kt
@@ -3,10 +3,14 @@ package dev.kolektiv.keel.samples.harbor
import dev.kolektiv.keel.Keel
import dev.kolektiv.keel.KeelJson
import dev.kolektiv.keel.bundle.FrontendBundle
+import dev.kolektiv.keel.realtime.KeelRealtimeEnvelope
import dev.kolektiv.keel.seed.KeelSeed
import dev.kolektiv.keel.typegen.ClasspathContract
import dev.kolektiv.keel.typegen.Typegen
import dev.kolektiv.keel.visit.KeelHeaders
+import io.ktor.client.plugins.websocket.DefaultClientWebSocketSession
+import io.ktor.client.plugins.websocket.WebSockets as ClientWebSockets
+import io.ktor.client.plugins.websocket.webSocket
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.post
@@ -16,9 +20,13 @@ import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import io.ktor.server.testing.testApplication
+import io.ktor.websocket.Frame
+import io.ktor.websocket.readText
+import kotlinx.coroutines.withTimeout
import kotlinx.serialization.json.add
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonArray
import kotlinx.serialization.json.putJsonObject
@@ -257,6 +265,70 @@ class HarborAppTest {
assertTrue(missingPath.bodyAsText().contains("\"path\":\"/nope\""))
}
+ @Test
+ fun `postMessage streams a harbor message event to the home channel`() = testApplication {
+ writePack()
+ application { harbor(FrontendBundle.fromDirectory(pack)) }
+ val client = createClient { install(ClientWebSockets) }
+ val named = client.post("${Keel.ACTION_PATH}/harbor.setName") {
+ contentType(ContentType.Application.Json)
+ setBody("""{"displayName":"Ada"}""")
+ }
+ val cookie = cookieHeader(named.headers["Set-Cookie"])
+
+ client.webSocket("/__keel/events?channels=page:harbor.home", request = { header("Cookie", cookie) }) {
+ val ready = nextRealtimeEnvelope()
+ assertEquals(KeelRealtimeEnvelope.READY, ready.type)
+ assertEquals(listOf("page:harbor.home"), ready.channels)
+
+ val posted = client.post("${Keel.ACTION_PATH}/harbor.postMessage") {
+ contentType(ContentType.Application.Json)
+ header("Cookie", cookie)
+ setBody("""{"body":"live from the pier"}""")
+ }
+ assertEquals(HttpStatusCode.OK, posted.status)
+
+ val event = nextRealtimeEnvelope()
+ assertEquals(KeelRealtimeEnvelope.EVENT, event.type)
+ assertEquals("harbor.message", event.event)
+ assertEquals("page:harbor.home", event.channel)
+ val data = event.data!!.jsonObject
+ assertEquals("live from the pier", data.getValue("body").jsonPrimitive.content)
+ assertEquals("Ada", data.getValue("displayName").jsonPrimitive.content)
+ }
+ }
+
+ @Test
+ fun `client typing notices round trip through the host`() = testApplication {
+ writePack()
+ application { harbor(FrontendBundle.fromDirectory(pack)) }
+ val client = createClient { install(ClientWebSockets) }
+ val named = client.post("${Keel.ACTION_PATH}/harbor.setName") {
+ contentType(ContentType.Application.Json)
+ setBody("""{"displayName":"Ada"}""")
+ }
+ val cookie = cookieHeader(named.headers["Set-Cookie"])
+
+ client.webSocket("/__keel/events?channels=page:harbor.home", request = { header("Cookie", cookie) }) {
+ assertEquals(KeelRealtimeEnvelope.READY, nextRealtimeEnvelope().type)
+ val envelope = KeelRealtimeEnvelope.send(
+ "harbor.typing",
+ buildJsonObject { put("displayName", "Ada") },
+ )
+ send(Frame.Text(KeelJson.codec.encodeToString(KeelRealtimeEnvelope.serializer(), envelope)))
+
+ val event = nextRealtimeEnvelope()
+ assertEquals("harbor.typing", event.event)
+ assertEquals("Ada", event.data!!.jsonObject.getValue("displayName").jsonPrimitive.content)
+ }
+ }
+
+ private suspend fun DefaultClientWebSocketSession.nextRealtimeEnvelope(): KeelRealtimeEnvelope =
+ KeelJson.codec.decodeFromString(
+ KeelRealtimeEnvelope.serializer(),
+ (withTimeout(5000) { incoming.receive() } as Frame.Text).readText(),
+ )
+
@Test
fun `generated page types stay in lockstep`() {
val expected = Path.of("pack/src/lib/page-types.ts").readText()
diff --git a/skills/keel-host/SKILL.md b/skills/keel-host/SKILL.md
index 32c837b..b7260bb 100644
--- a/skills/keel-host/SKILL.md
+++ b/skills/keel-host/SKILL.md
@@ -3,9 +3,11 @@ name: keel-host
description: >
Implement or extend a Keel host (server). Use when adding pages, actions,
CSRF, the live schema, pack loading and render-time pack choice, document
- head, CSP, or pack hot reload, or for a non-Ktor backend that speaks Keel.
+ head, CSP, pack hot reload, or realtime events over SSE/WebSocket, or for a
+ non-Ktor backend that speaks Keel.
Triggers: "keel host", "KeelEngine", "respondPage", "route.keel",
- "FrontendBundle", "/__keel/schema", "@KeelAction", "page registry".
+ "FrontendBundle", "/__keel/schema", "@KeelAction", "@KeelEvent",
+ "call.keelRealtime", "realtime", "page registry".
Slash: /keel-host.
---
@@ -109,6 +111,44 @@ stripped. Visits get no nonce and no header. Default policy:
`script-src 'nonce-…' 'strict-dynamic'; style-src 'self'; object-src 'none';
base-uri 'none'`.
+## Realtime
+
+Off by default. Enable by installing the Ktor transport plugins the host wants
+and adding a `realtime { }` block — endpoints exist only when both are true:
+
+```kotlin
+install(WebSockets) // and/or install(SSE)
+keel {
+ realtime {
+ event("harbor.message", EventDirection.OUT) // typed payload
+ on("harbor.typing") { call.keelRealtime.publish("page:harbor.home", "harbor.typing", it) }
+ events(Board) // @KeelEvent functions
+ authorize = { call, channel -> channel.startsWith("page:") || Board.viewer(call) != null }
+ heartbeatSeconds = 25
+ }
+}
+```
+
+- `@KeelEvent("id")` on a `@Serializable` class declares the payload (Typegen
+ emits `Events`); on a host function it registers a client-sent
+ handler the way `@KeelAction` registers writes. Directions: `IN`, `OUT`,
+ `BOTH`.
+- One endpoint, `/__keel/events`: SSE stream, WebSocket upgrade, and `POST`
+ sends from SSE clients (`sid` addresses the stream). Same JSON envelope both
+ directions, `v: 1`. Writes use the action CSRF policy.
+- Publish from a call: `call.keelRealtime.publish(channel, eventId, data)`
+ (typed) / `publishJson`; `invalidate(channel, path, only, except)` sends the
+ visit-shaped hint. `send(sid, …)` targets one stream.
+- Channel ids are host-owned strings; `page:…`/`user:…` are conventions, not
+ built-ins. `authorize` runs per channel at subscribe time with the caller's
+ cookies.
+- **No replay.** Subscriptions are ephemeral; `invalidate` tells the client
+ to rehydrate with a normal visit, and the client resubscribes with backoff.
+ Keep heartbeats on so dead connections are reaped.
+- A non-Ktor host implements the envelope from
+ `docs/src/content/docs/implementing/protocol.mdx`; the reference is
+ `ktor/realtime/`.
+
## Pack hot reload
- `KeelConfig.watchPacks = true` and `packWatchIntervalMs` (default 500,
diff --git a/skills/keel-pack/SKILL.md b/skills/keel-pack/SKILL.md
index b974929..15eeaba 100644
--- a/skills/keel-pack/SKILL.md
+++ b/skills/keel-pack/SKILL.md
@@ -4,9 +4,10 @@ description: >
Author or adapt a Keel frontend pack for Svelte, React, Vue, Solid,
Preact, Lit, or Angular. Use when writing pages and +head templates,
keelPack Vite config and .feb builds, typed contracts, navigation guards,
- action/effect patterns, or a RouterAdapter. Triggers: "keel pack",
- "+page.svelte", "+page.tsx", "+page.ts", "+head.html", "keelPack",
- "PageModule", ".feb", "supportedFrameworks", "beforeEach".
+ action/effect patterns, realtime events, or a RouterAdapter. Triggers:
+ "keel pack", "+page.svelte", "+page.tsx", "+page.ts", "+head.html",
+ "keelPack", "PageModule", ".feb", "supportedFrameworks", "beforeEach",
+ "useKeelEvent", "realtime", "invalidate".
Slash: /keel-pack.
---
@@ -186,6 +187,43 @@ on success by default so `page()` and the query cache rehydrate; reads still
come from the seed. `action(id, input)` is the same POST without the reactive
wrapper.
+## Realtime
+
+Only use it when the host opted in (`keel { realtime { } }`). `realtime` and
+`useKeelEvent` come from the adapter package; payload types come from
+generated `Events` (`@KeelEvent` classes on the host).
+
+```svelte
+import { realtime, useKeelEvent } from "@kolektiv/keel-svelte"
+import type { HarborEvents } from "../lib/page-types"
+
+let liveFeed = $state([])
+
+useKeelEvent("harbor.message", (item) => {
+ liveFeed = [item, ...liveFeed]
+})
+
+// client → host; the host may echo or broadcast it back
+void realtime.send("harbor.typing", { displayName })
+```
+
+- `useKeelEvent(event, handler)` (Angular: `injectKeelEvent`; Lit:
+ `useKeelEvent(host, …)` or `KeelEventController`) subscribes for the
+ component lifetime and always calls the latest handler. Call it once
+ during component init; do not call it conditionally.
+- The client auto-holds `page:` and follows seed changes. Add
+ channels with `realtime.subscribe(channel)`; `realtime.configure({ ... })`
+ customizes `channels`, transport, and backoff.
+- An `invalidate` envelope reloads the current page by default
+ (`router.reload({ preserveState: true })`). `realtime.onInvalidate` takes
+ over when the page wants a merge instead of a visit.
+- The seed is still the only read model: use events to patch *view* state
+ (toasts, presence, appends) or let `invalidate` rehydrate. Never treat an
+ event as the source of truth — no replay, and a reconnect resyncs by
+ reloading.
+- `realtime.status()` / `realtime.onStatus` expose `idle`, `connecting`,
+ `open`, `reconnecting`, `closed` if a page wants a live indicator.
+
## Navigation guards
`router.beforeEach(guard)` runs before the inflight visit is aborted, before
diff --git a/skills/keel-scaffold/SKILL.md b/skills/keel-scaffold/SKILL.md
index d74b5a4..c15a7c5 100644
--- a/skills/keel-scaffold/SKILL.md
+++ b/skills/keel-scaffold/SKILL.md
@@ -78,6 +78,12 @@ Angular). When a page id ends in `.notFound` (or is `not-found`/`notFound`)
it also sets `notFound:`. Type names come from `schema.pagesName`, else
PascalCase(id) + `Pages`.
+When the host's schema carries an `events` section (`@KeelEvent` payloads),
+`page-types.ts` also emits `Events` / `EventId` maps so a
+page can subscribe with `useKeelEvent(…)`
+instead of stringly-typed payloads; the direction (`in`/`out`/`both`) lives
+in `page-types.json`.
+
Framework-specific DX notes:
- **Lit** — `tsconfig.json` sets `experimentalDecorators: true` and