Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ JS workspace root is this repository (`packages/*` and `docs`).
<dir>` writes a blank pack from it for the chosen `--framework` (default
Svelte). Gradle `generateKeelTypes` is the
offline classpath scan. Actions are a Kotlin function `(In) -> Out`.
- Realtime is opt-in: `keel { realtime { } }` plus `install(SSE)` and/or
`install(WebSockets)` serves `/__keel/events` (SSE stream, WS upgrade, and
`POST` sends from SSE clients). Channels are host-owned strings; typed
`@KeelEvent` payloads are hints, the seed stays the only read model, and
`invalidate` rehydrates with a normal visit. No replay: reconnect means
resubscribe + reload.
- Packs ship as `.feb` (zip of `manifest.json` + modules). Hosts load a
`FrontendBundle` from a jar resource, a file, or an exploded directory.
- Visits hit the real page URL with `X-Keel-Visit: true`. `/__keel/navigate`
Expand Down
51 changes: 42 additions & 9 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,49 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [0.2.1] - 2026-10-26

Realtime release: a typed event registry, SSE and WebSocket host transports
at `/__keel/events`, and the client `realtime` / `useKeelEvent` helpers.
Ktor is bumped to 3.5.2.

### Added

- Docs: new Realtime guide (host opt-in, typed events, invalidate, reconnect,
client surface), the wire-protocol envelope section, Typegen and
framework-adapter updates, refreshed llms.txt and agent skills. (#74)
- Harbor testbench now runs live: posts stream to `page:harbor.home` as
`harbor.message`, renames send an `invalidate`, and clients send
`harbor.typing` notices that the host echoes back. (#75)
- Realtime client: `realtime` from `@kolektiv/keel` connects over WebSocket
(SSE fallback) to `/__keel/events`, auto-holds `page:<page id>`, dispatches
typed events to `realtime.on`, rehydrates the seed on `invalidate`,
`POST`s sends by `sid` when streaming SSE, and reconnects with backoff and
resubscribe. Every adapter gains a lifecycle-aware
`useKeelEvent` / `injectKeelEvent` helper. (#73)
- Realtime host: opt-in `keel { realtime { } }` serves SSE and WebSocket
transports at `/__keel/events` when `install(SSE)` and/or
`install(WebSockets)` are present. Host-owned channels, session-cookie
auth via an `authorize` hook, typed `publish` / `invalidate` helpers on
`call.keelRealtime`, heartbeats, CSRF-protected HTTP sends, and a
documented no-replay reconnect story (resubscribe and rehydrate the
seed). (#71)
- Typed realtime event registry: `@KeelEvent` (payload classes and host
handler functions), `dev.kolektiv.keel.event.EventRegistry` /
`EventDiscovery`, and the versioned JSON envelope
(`KeelRealtimeEnvelope`) both transports speak. Typegen and
`keel-scaffold` emit the events section (`HarborEvents` /
`HarborEventId`) next to pages and actions. (#72)
## [0.1.2] - 2026-10-26

### Changed

- Republish on `repo.kolektiv.computer`; docs use `@kolektiv/common-docs-chrome` ^0.0.1 and `@kolektiv/themes` ^0.0.1.
- Maven group is now `computer.kolektiv.keel`: `Keel.GROUP`, the docs
install cite, and the CI Maven check all moved. Kotlin packages are
unchanged (`dev.kolektiv.keel.*`). (#81)
- Republish on `repo.kolektiv.computer`; docs use `@kolektiv/common-docs-chrome` ^0.0.1 and `@kolektiv/themes` ^0.0.1.


## [0.1.1] - 2026-09-27

Expand All @@ -20,14 +58,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Publish Maven to `repo.kolektiv.computer` `maven-releases` / `maven-snapshots` only (dropped `keel-maven`).
- Publish and consume npm via `npm-public` on `repo.kolektiv.computer` (dropped `keel-npm`).
- Docs and consumer pins updated for the Kolektiv registry cut.


### Fixed

- npm publishing now targets the `keel-npm` registry for the `@kolektiv`
scope: the publish script swaps the committed repo-root `.npmrc`
(`npm-public`) for the publish config and restores it afterwards.

## [0.1.0] - 2026-09-14

### Added
Expand Down Expand Up @@ -104,7 +134,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- Docs and homepage tell the pack-at-render-time story: call-site pack
- Docs and homepage tell the pack-at-render-time story: c- Maven group is now `computer.kolektiv.keel`: `Keel.GROUP`, the docs
install cite, and the CI Maven check all moved. Kotlin packages are
unchanged (`dev.kolektiv.keel.*`). (#81)
- Republish on `repo.kolektiv.computer`; docs use `@kolektiv/common-docs-chrome` ^0.0.1 and `@kolektiv/themes` ^0.0.1.all-site pack
selection, "Choosing a pack" replaces the theme-chain page, no resolver
language (#11).
- Refreshed the agent skill suite (`keel-host`, `keel-pack`, `keel-scaffold`)
Expand Down
247 changes: 247 additions & 0 deletions docs/src/content/docs/advanced/realtime.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,247 @@
---
title: Realtime
description: Typed events and invalidations over SSE and WebSocket. The seed stays the read model.
category: advanced
order: 7
---

import CodePair from "../../../components/CodePair.astro"
import FrameworkPanel from "../../../components/FrameworkPanel.astro"
import { path } from "../../../lib/paths"

Realtime in Keel is **opt-in and advisory**. The seed is still the only read
model. A typed event says *something happened*; an `invalidate` says
*rehydrate with a normal visit*. Events missed while offline are not
replayed — the next visit always recovers the truth. That is what keeps
reconnect semantics small and the UI honest.

One endpoint, two transports. `GET /__keel/events` streams SSE when the host
installed the Ktor `SSE` plugin; the same path upgrades to a WebSocket when
`WebSockets` is installed. SSE clients `POST` envelopes to the same path for
client-to-host sends (`sid` addresses the stream). Both transports speak the
same JSON envelope — see
<a href={path("/docs/implementing/protocol")}>Wire protocol</a>.

## Enable it on the host

Install the plugins before `keel { }`, then opt in. Endpoints exist only when
the `realtime` block is present **and** at least one transport plugin is
installed.

```kotlin
install(WebSockets)
install(SSE)

keel {
realtime {
event<FeedItem>("harbor.message", EventDirection.OUT) // host → pack
on<TypingNotice>("harbor.typing") { input -> // pack → host
call.keelRealtime.publish("page:harbor.home", "harbor.typing", input)
}
events(Board) // @KeelEvent functions
authorize = { call, channel -> // session cookies
channel.startsWith("page:") || call.request.cookies["harbor_uid"] != null
}
heartbeatSeconds = 25
}
}
```

- `event<T>(id, direction)` declares a typed payload without a handler.
- `on<I>(id) { input -> … }` registers a handler for a client-sent event and
registers the binding as `IN` when it is not declared yet.
- `events(vararg hosts)` scans `@KeelEvent` functions the way `actions(hosts)`
scans `@KeelAction`; an `ApplicationCall.(Payload) -> Unit` extension gets
the handshake/POST call as `this`.
- `authorize` runs per channel at subscribe time. Channel ids are host-owned
strings; `page:…` and `user:…` are conventions, not built-ins.
- `heartbeatSeconds` sends `ping` envelopes (0 disables). Keepalives are how
dead SSE connections are noticed and reaped.

Publish from anywhere a call is reachable — actions, page loaders, jobs —
with `call.keelRealtime` (or `application.keelRealtime`):

```kotlin
@KeelAction("harbor.postMessage")
fun ApplicationCall.postMessage(input: PostMessageIn): PostMessageOut {
val item = Board.post(input.body)
keelRealtime.publish("page:harbor.home", "harbor.message", item) // flavor (a)
return PostMessageOut(item)
}

@KeelAction("harbor.setName")
fun ApplicationCall.setName(input: SetNameIn): SetNameOut {
val user = Board.rename(input.displayName)
keelRealtime.invalidate("page:harbor.home", path = "/") // flavor (b)
return SetNameOut(user)
}
```

`publish` encodes with the registered serializer; unknown or `IN`-only ids
throw. `invalidate(channel, path, only, except)` sends the visit-shaped hint.
`send(sid, …)` targets one connection.

## Subscribe in a pack

`@KeelEvent` on a `@Serializable` class is the contract: Typegen emits the
payload into `<Pack>Events` (`HarborEvents["harbor.message"]`). The client
side is the core `realtime` singleton plus one lifecycle helper per adapter.
`useKeelEvent` subscribes for the component's lifetime and keeps the latest
handler, so inline closures never resubscribe.

<CodePair
fw="svelte"
title="Typed events and sends"
ts={`import { realtime, useKeelEvent } from "@kolektiv/keel-svelte"
import type { HarborEvents } from "../lib/page-types"

let liveFeed = $state<FeedItem[]>([])

useKeelEvent<HarborEvents["harbor.message"]>("harbor.message", (item) => {
liveFeed = [item, ...liveFeed]
})

function announceTyping(displayName: string) {
void realtime.send("harbor.typing", { displayName })
}`}
js={`import { realtime, useKeelEvent } from "@kolektiv/keel-svelte"

let liveFeed = $state([])

useKeelEvent("harbor.message", (item) => {
liveFeed = [item, ...liveFeed]
})

function announceTyping(displayName) {
void realtime.send("harbor.typing", { displayName })
}`}
/>

<FrameworkPanel frameworks="react preact">
In React and Preact, `useKeelEvent` is a hook; the latest handler wins.

```tsx
import { useKeelEvent } from "@kolektiv/keel-react"
import type { HarborEvents } from "../lib/page-types"

useKeelEvent<HarborEvents["harbor.message"]>("harbor.message", (item) => {
setItems((current) => [item, ...current])
})
```
</FrameworkPanel>

<FrameworkPanel frameworks="vue">
In Vue, `useKeelEvent` subscribes in the component scope and releases on
scope dispose.

```vue
<script setup lang="ts">
import { realtime, useKeelEvent } from "@kolektiv/keel-vue"
import type { HarborEvents } from "../lib/page-types"

const items = ref<FeedItem[]>([])
useKeelEvent<HarborEvents["harbor.message"]>("harbor.message", (item) => {
items.value = [item, ...items.value]
})
function announceTyping(displayName: string) {
void realtime.send("harbor.typing", { displayName })
}
</script>
```
</FrameworkPanel>

<FrameworkPanel frameworks="solid">
Solid's `useKeelEvent` registers cleanup with the owner; read signals inside
the handler.

```tsx
import { useKeelEvent } from "@kolektiv/keel-solid"
import type { HarborEvents } from "../lib/page-types"

const [items, setItems] = createSignal<FeedItem[]>([])
useKeelEvent<HarborEvents["harbor.message"]>("harbor.message", (item) => {
setItems([item, ...items()])
})
```
</FrameworkPanel>

<FrameworkPanel frameworks="lit">
Lit gets a `ReactiveController`; `useKeelEvent` is the convenience wrapper.

```ts
import { useKeelEvent, type RealtimeMessage } from "@kolektiv/keel-lit"
import type { HarborEvents } from "../lib/page-types"

export class HarborFeed extends LitElement {
constructor() {
super()
useKeelEvent<HarborEvents["harbor.message"]>(this, "harbor.message", (item) => {
this.items = [item, ...this.items]
})
}
}
```
</FrameworkPanel>

<FrameworkPanel frameworks="angular">
Angular injects the subscription and releases it with the injector.

```ts
import { injectKeelEvent } from "@kolektiv/keel-angular"
import type { HarborEvents } from "../lib/page-types"

injectKeelEvent<HarborEvents["harbor.message"]>("harbor.message", (item) => {
this.items.update((current) => [item, ...current])
})
```
</FrameworkPanel>

## Channels

Channels are how the host targets traffic; the client only asks to listen.

- The client automatically holds `page:<page id>` and follows the seed as it
changes. Disable with `realtime.configure({ autoChannels: false })` or add
your own with `channels`.
- `realtime.subscribe(channel)` returns a release function; ref-counted, so
several components can hold the same channel.
- `realtime.configure({ channels: (seed) => [...] })` adds seed-derived
channels.
- Every channel is authorized at subscribe time with the same session cookies
as visits. A denied channel means no events, not an error page.

## Invalidate

When an `invalidate` envelope arrives and no handler is registered, the
client reloads the current page with
`router.reload({ preserveState: true })` — path, `only`, and `except` from
the envelope are honored. Registering `realtime.onInvalidate(handler)`
takes over, which is how a pack can merge partial state without a visit.

## Reconnect

`realtime.connect()` is idempotent. With `transport: "auto"` the client tries
WebSocket, falls back to SSE, and reconnects with exponential backoff plus
jitter (`minReconnectDelayMs` 500, `maxReconnectDelayMs` 15000). On every
re-open it resubscribes the channel set.

Because there is no replay, a reconnection that followed a live connection
also rehydrates: `router.reload({ preserveState: true })`. Set
`resyncOnReconnect: false` to opt out. A first connect never reloads — the
document seed is already fresh.

## Client surface

| Member | Effect |
| --- | --- |
| `realtime.configure(options)` | transport, `url`, channels, backoff, resync, `reloadOnInvalidate` |
| `realtime.connect()` / `disconnect()` | open or close the transport |
| `realtime.subscribe(channel)` | hold a channel; returns a release function |
| `realtime.on(event, handler)` | typed events; returns a release function |
| `realtime.onInvalidate(handler)` | take over invalidation handling |
| `realtime.send(event, data)` | client-to-host event (WebSocket frame or SSE `POST`) |
| `realtime.status()` / `onStatus(fn)` | `idle`, `connecting`, `open`, `reconnecting`, `closed` |
| `realtime.sid()` / `lastSeen()` | stream id, last envelope timestamp |

`realtime` is re-exported from every adapter package; `Harbor` opens two
browser windows to show posts and typing notices streaming in.
20 changes: 11 additions & 9 deletions docs/src/content/docs/implementing/framework-adapters.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ how each framework expresses reactivity, forms, and DOM access.
Svelte is the docs default. Sections for the other frameworks still apply when you pick them in the navbar. Scroll to that heading, or keep this page as the full matrix.
</FrameworkPanel>

| Framework | Package | Page state | Action / query | Components / directives | Guards | Mount |
| --- | --- | --- | --- | --- | --- | --- |
| Svelte 5 | `@kolektiv/keel-svelte` | `page()` store | `@tanstack/svelte-query` | `Link`, `Form`, `Head`, `use:keel` | `useNavigationGuard`, `useUnloadGuard` | `createPage` |
| React 18/19 | `@kolektiv/keel-react` | `usePage()` | `@tanstack/react-query`: `useAction`, `useKeelPageQuery` | `Link`, `Form`, `Head`, `useKeelAnchor` | `useNavigationGuard`, `useUnloadGuard` | `createPage` (`createRoot`, `flushSync`) |
| Vue 3 | `@kolektiv/keel-vue` | `usePage()` shallow ref | `@tanstack/vue-query` | SFC `Link`, `Form`, `Head`, `useKeelAnchor` | `useNavigationGuard`, `useUnloadGuard` | `createPage` (`createApp().mount`) |
| Solid 1.9 | `@kolektiv/keel-solid` | `usePage()` accessor | `@tanstack/solid-query` | JSX `Link`, `Form`, `Head`, `useKeelAnchor` | `useNavigationGuard`, `useUnloadGuard` | `createPage` (`render` + dispose) |
| Preact 10 | `@kolektiv/keel-preact` | `usePage()` | `@tanstack/preact-query` | JSX `Link`, `Form`, `Head`, `useKeelAnchor` | `useNavigationGuard`, `useUnloadGuard` | `createPage` (`render` / `render(null)`) |
| Lit 3 | `@kolektiv/keel-lit` | `KeelElement.page` / `usePage` controller | `@tanstack/query-core` controllers: `KeelActionController`, `KeelPageQueryController` | `<keel-link>`, `form()` helper, `<keel-head>`, `keelAnchor` | controllers | `createPage` (`render`) |
| Angular 19 | `@kolektiv/keel-angular` | `injectKeelPage()` signal | `@tanstack/angular-query-experimental` | `[keelLink]`, `[keelAnchor]`, `[keelForm]`, `KeelHead` | `injectNavigationGuard`, `injectUnloadGuard` | `createPage` (`createApplication` + `createComponent`/`attachView`) |
| Framework | Package | Page state | Action / query | Components / directives | Guards | Realtime | Mount |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Svelte 5 | `@kolektiv/keel-svelte` | `page()` store | `@tanstack/svelte-query` | `Link`, `Form`, `Head`, `use:keel` | `useNavigationGuard`, `useUnloadGuard` | `useKeelEvent`, `realtime` | `createPage` |
| React 18/19 | `@kolektiv/keel-react` | `usePage()` | `@tanstack/react-query`: `useAction`, `useKeelPageQuery` | `Link`, `Form`, `Head`, `useKeelAnchor` | `useNavigationGuard`, `useUnloadGuard` | `useKeelEvent`, `realtime` | `createPage` (`createRoot`, `flushSync`) |
| Vue 3 | `@kolektiv/keel-vue` | `usePage()` shallow ref | `@tanstack/vue-query` | SFC `Link`, `Form`, `Head`, `useKeelAnchor` | `useNavigationGuard`, `useUnloadGuard` | `useKeelEvent`, `realtime` | `createPage` (`createApp().mount`) |
| Solid 1.9 | `@kolektiv/keel-solid` | `usePage()` accessor | `@tanstack/solid-query` | JSX `Link`, `Form`, `Head`, `useKeelAnchor` | `useNavigationGuard`, `useUnloadGuard` | `useKeelEvent`, `realtime` | `createPage` (`render` + dispose) |
| Preact 10 | `@kolektiv/keel-preact` | `usePage()` | `@tanstack/preact-query` | JSX `Link`, `Form`, `Head`, `useKeelAnchor` | `useNavigationGuard`, `useUnloadGuard` | `useKeelEvent`, `realtime` | `createPage` (`render` / `render(null)`) |
| Lit 3 | `@kolektiv/keel-lit` | `KeelElement.page` / `usePage` controller | `@tanstack/query-core` controllers: `KeelActionController`, `KeelPageQueryController` | `<keel-link>`, `form()` helper, `<keel-head>`, `keelAnchor` | controllers | `KeelEventController`, `useKeelEvent`, `realtime` | `createPage` (`render`) |
| Angular 19 | `@kolektiv/keel-angular` | `injectKeelPage()` signal | `@tanstack/angular-query-experimental` | `[keelLink]`, `[keelAnchor]`, `[keelForm]`, `KeelHead` | `injectNavigationGuard`, `injectUnloadGuard` | `injectKeelEvent`, `realtime` | `createPage` (`createApplication` + `createComponent`/`attachView`) |

The first adapter was Svelte 5. The other six bindings copy its contract
rather than inventing a second one.
Expand All @@ -49,6 +49,8 @@ subscription, refs, signals, controllers).
`pageQueryKey(path)` (`["keel", "page", path]`). Actions invalidate the root
key with `refetchType: "none"` because the follow-up visit rehydrates it.

**Realtime.** `realtime` (the core client) is re-exported from every adapter; the lifecycle helper is `useKeelEvent` everywhere except Angular's `injectKeelEvent` (Lit also exposes the underlying `KeelEventController`). Each helper subscribes for the host/component lifetime, keeps the latest handler, and releases on unmount. See <a href={path("/docs/advanced/realtime")}>Realtime</a>.

**Visit interception.** `Link` and the anchor helpers intercept unmodified
left-clicks only. Modified clicks, non-left buttons, `defaultPrevented`, and
GET visits into `target="_blank"` fall through to the browser. Prefetch is
Expand Down
Loading
Loading