# Apps in Lua: Kit and the runner

At the end of this chapter, a task list runs from one Lua file, with no
Rust of your own, drawn by Kit — and a test checks it without a window.

<a data-kui-example="440" href="live/tasks/index.html">Live Lua task list</a>

To write a view directly in the book, open the [Lua playground](playground.md).

## Build for the browser

The browser example was built by `kui pack --format web` from the Lua
project below. Its data file is stored in this browser.

```bash
kui pack tasks --format web --out dist
```

Serve `dist` over HTTP during development or deploy its contents to a
static HTTPS host. Apps on the same site store data separately by
their project ID.

The checkout also embeds this project on
[iOS and Android](mobile.md). Each mobile app keeps its own data.

## The host you do not write

The last chapter's host was yours. `kui` is one written for you
([ADR 0064](https://github.com/qxuken/kui/blob/main/docs/adr/0064-the-kui-runner.md)):
a binary that opens the window, loads your script as the app, loads
**Kit** beside it — a UI kit of ready components, drawn in a skin — and
gives the script a standard library: files, processes, HTTP, timers,
tasks. Install it with the script each release carries (Windows has
`install.ps1` beside it), or from npm:

```bash
curl -fsSL https://github.com/qxuken/kui/releases/download/v0.1.0-alpha.68/install.sh | sh
```

```bash
npm i -g @qxuken/kui-cli
```

`kui upgrade` later moves it to the newest release.

Then start an app, and run it:

```bash
kui new tasks
```

```bash
kui run --watch tasks
```

`--watch` reloads the script when you save it and keeps the model, so the
window you are looking at is the one you are editing.

## The docs, at your version

The runner carries kui's docs for its own version: the prop reference,
the how-do-I index, Kit's components, this book as text and the design
records. Ask it from a terminal:

```bash
kui docs hover_bg
```

```bash
kui docs kit.table
```

A prop in either spelling, a component or a question finds the rows and
entries that match, best first; `kui docs --adr 64` prints a design
record, and `kui docs` alone opens this book.

To keep them beside the app, for your editor or the coding agent you
work with, ask when you start it:

```bash
kui new tasks --docs
```

`--docs` writes them into `.kui/docs`, next to the types in `.kui/types`
(both gitignored). `--agents` writes them too, and a short block for
coding agents into `AGENTS.md` — or between markers at the end of an
`AGENTS.md` or `CLAUDE.md` the app already has — naming the version,
where the types and docs are, and the commands. `kui types --docs` (or
`--agents`) does the same for an app that already exists. Either is
remembered in `kui.config.lua` as `tooling = { docs = true }`, and when
`kui upgrade` brings a new runner, the next `kui run` or `kui check`
writes `.kui/` — and the block, between its markers — again for it.

## The folder

An app is a folder. `kui.config.lua` names it, gives it an `id` and a
version, and says its entry and its window:

```lua
return {
  name = "Tasks",
  id = "dev.kui.book.tasks",
  version = "1.0.0",
  entry = "main.lua",
  size = { w = 520, h = 440 },
}
```

The entry is a kui-lua script, the kind chapter 13's plugins were, with
three globals the runner looks for: `init`, `update` and `view`. It is
the loop of chapter 4, in Lua.

## The model

`init()` returns the model, which the runner keeps in the global
`model`. It reads the tasks from a file, if there is one — a call that
waits, at the top level, which is fine before the window opens:

```lua
function init()
  local tasks, err = {}, nil
  if kui.fs.exists(opts.file) then
    local ok, got = kui.fs.try_read(opts.file)
    if ok then ok, got = kui.json.try_decode(got) end
    if ok then tasks = got else err = got end
  end
  return { tasks = tasks, draft = "", error = err, saving = false }
end
```

`kui.fs.read` raises an error when the file cannot be read, and
`kui.json.decode` when it is not JSON. Each has a `try_` form, as every
runner call that can fail on its input or on the world does: `true` and
what the call returns, or `false` and the error's message. `init`
puts the message where Kit draws a mistake, so a broken file opens the
app and says why, where the plain calls would have stopped it.

Where the file is comes from the command line. `kui.parse_args` reads
the app's own arguments — what follows `--` — against a spec, and
writes `--help` from it:

```lua
local opts = kui.parse_args({
  about = "a task list on Kit",
  options = {
    file = { default = kui.data_dir .. "/tasks.json", value = "path",
      help = "where the tasks are kept" },
  },
})
```

```bash
kui run tasks -- --file /tmp/tasks.json
```

For an app with command-line actions as well as a window, add `commands`
to the spec. Each command is another spec with its own options and
positional arguments:

```lua
local opts = kui.parse_args {
  commands = {
    export = {
      about = "Export tasks",
      args = { { name = "file", required = true } },
    },
  },
}
if opts.command == "export" then
  -- Export to opts.command_args.file here.
  kui.exit(0)
  return
end
```

`kui run tasks -- export tasks.json` selects the command;
`kui run tasks -- export --help` prints its help before opening a window.
With no command, parsing returns normally so the app can open its window.
Set `command_required = true` to require a command. Commands can nest;
each selection adds `command` and `command_args` to that scope's result.
Parent options work before or after the command and stay in the parent's
result; the nearest definition wins when flag spellings overlap. Fixed
parent positionals precede the command; variadic positionals and `rest`
belong in a spec without commands.

## The view, from Kit

`require("kit.ui")` is Kit's components as functions. Each takes its
props and, where it holds any, its children; an `on_*` prop is the
message its event arrives as. The rest is the Lua builders chapter 13's plugins used —
`column`, `text` — with `$kitBg`, Kit's colour for a window's ground:

```lua
function done_count()
  local n = 0
  for _, t in ipairs(model.tasks) do
    if t.done then n = n + 1 end
  end
  return n
end

function view(env)
  local rows = {}
  for i, t in ipairs(model.tasks) do
    rows[#rows + 1] = kit.checkbox({ label = t.text, checked = t.done,
      on_toggle = { kind = "toggle", index = i } })
  end
  local done = done_count()
  return column { width = "grow", height = "grow", pad = 16, gap = 12, bg = "$kitBg",
    kit.toolbar({}, {
      kit.text_field({ label = "New task", hide_label = true, placeholder = "What needs doing?",
        value = model.draft, error = model.error,
        on_change = { kind = "draft" }, on_submit = { kind = "add" } }),
      kit.button({ label = "Add", variant = "primary", on_press = { kind = "add" } }),
      trailing = {
        kit.button({ label = "Clear done", icon = "trash", variant = "ghost", disabled = done == 0, on_press = { kind = "clear" } }),
      },
    }),
    kit.stat({ label = "Done", value = done .. " of " .. #model.tasks }),
    column { key = "tasks", gap = 4, width = "grow", height = "grow", scroll = true, pad = 4, table.unpack(rows) },
  }
end
```

A Kit component is a component in chapter 13's sense: the runner loaded
Kit as an extension, and `kit.button(…)` places `kit/button`. Its
events are your messages, with the event's fields under the event's
name — a checkbox's `toggle = { checked }`, a field's `change = { text }`.

## Update

`update(msg)` hears every message — your nodes', Kit's, and what the
app dispatches itself — and changes `model`. The next frame draws it:

```lua
function update(msg)
  if msg.kind == "draft" then
    model.draft, model.error = msg.change.text, nil
  elseif msg.kind == "add" then
    local text = model.draft:match("^%s*(.-)%s*$")
    if text == "" then
      model.error = "Name the task first"
      return
    end
    model.tasks[#model.tasks + 1] = { text = text, done = false }
    model.draft = ""
    save()
  elseif msg.kind == "toggle" then
    model.tasks[msg.index].done = msg.toggle.checked
    save()
  elseif msg.kind == "clear" then
    local left = {}
    for _, t in ipairs(model.tasks) do
      if not t.done then left[#left + 1] = t end
    end
    model.tasks = left
    save()
  elseif msg.kind == "saved" then
    model.saving = false
  end
end
```

An empty task is refused with `error`, which Kit draws under the field
in the danger colour and reads after its name.

## A task, so the window keeps drawing

Saving writes a file. On desktop, a file write in `update` blocks the frame.
In `kui.spawn`, the task yields while the runner writes the file. The mobile
and browser hosts run short task callbacks between frames. Keep a portable
callback small enough to finish in one turn. When the save finishes, it hands
a message back with `kui.dispatch`.

```lua
-- Writes the file in a task, so the window keeps drawing, and says so
-- with a message when it is done.
local function save()
  model.saving = true
  local text = kui.json.encode(kui.json.array(model.tasks))
  kui.spawn(function()
    kui.fs.write(opts.file, text)
    kui.dispatch({ kind = "saved" })
  end)
end
```

`kui.json.array` marks the list, so that an empty one is written `[]`
and not `{}`.

## The test

`kui test` discovers test files and runs their named cases. Start the app
with arguments pointing at a temporary file, drive its actual controls,
and inspect its model. Each case gets fresh app state:

```lua
local test = require('kui.test')
local path

test.before_each(function()
  path = kui.fs.temp_dir() .. '/tasks.json'
  test.start { args = { '--file', path } }
end)

test.it('an empty task explains what is missing', function()
  test.press('Add')
  test.expect(test.model().error):to_be('Name the task first')
end)

test.it('tasks can be added, completed, saved and reopened', function()
  test.type('New task', '  Water the ferns  ')
  test.press('Add')
  test.type('New task', 'Call the dentist')
  test.press('Add')
  test.expect(#test.model().tasks):to_be(2)
  test.expect(test.model().tasks[1].text):to_be('Water the ferns')

  test.press('Water the ferns')
  test.press('Clear done')
  test.wait_for(function() return not test.model().saving end)
  test.expect(#kui.json.decode(kui.fs.read(path))):to_be(1)

  test.start { args = { '--file', path } }
  test.expect(test.model().tasks[1].text):to_be('Call the dentist')
end)
```

```bash
cd tasks && kui test
```

`kui test --headed` shows the same execution. `--debug` opens the Kit
inspector and pauses before actions; `--ui` browses recorded frames,
state, messages and I/O. See [Testing without a window](testing.md) for
snapshots, mocks and CI output.

What `update` cannot show is what the keyboard and the pointer do on
their way to it: which control Tab lands on, which key a focused control
keeps, what is under a click. `kui.input` sends a headless run what a
window gets from the OS — `kui.input.key("tab")`,
`kui.input.key("down", { alt = true })`, `kui.input.move(x, y)`,
`kui.input.click(x, y)`, `kui.input.text("hi")` — each handled before
the next frame, so a timer step that presses Tab and a view that prints
`env.focus` a step later read the frame after it.

## Shipping it

Each desktop package bundles the native runner and your Lua project.
`kui pack` can assemble all the desktop targets from one machine.

```bash
kui pack tasks --target all --installer https://example.com/tasks/
```

`dist/` then holds a `.app` for macOS, an `.exe` for Windows, a binary for
each Linux, `SHA256SUMS`, and an `install.sh` and `install.ps1` that
fetch the right one from the URL you gave. Upload the folder there, and
`curl -fsSL https://example.com/tasks/install.sh | sh` installs it.
`--format npm` writes a package instead, for a team that already has
Node and a registry of its own.

The `id` is what names the app's own folder, `kui.data_dir` — which is
why the task list keeps its file there: a packed app's own files are
read-only.

For direct macOS distribution, sign and notarize the assembled bundle.
The [Linux packaging guide](pack-macos.md) shows the Docker workflow and
the checks to run on the receiving Mac.

## Where the runner goes from here

- **The standard library** — `kui.http` (a client and a server),
  `kui.process`, `kui.timer`, `kui.fs.walk`, workers on other cores,
  sqlite — is listed in the
  [runner's README](https://github.com/qxuken/kui/blob/main/crates/kui-cli/README.md).
- **Kit** — fields, tables of a hundred thousand rows, charts, a trace
  waterfall, dialogs, toasts, three skins — is in
  [`addons/kit`](https://github.com/qxuken/kui/tree/main/addons/kit);
  `kui play` opens its gallery, carried inside the runner. From a repository
  checkout, `kui run addons/kit/app` opens the same app.
- **The samples** in
  [`addons/kit/samples`](https://github.com/qxuken/kui/tree/main/addons/kit/samples)
  are four whole apps on the runner: an HTTP client with its own mock
  API, an ops dashboard in Teal, notes in sqlite, a settings window.
- **Teal**, typed Lua: name the entry `main.tl` and `kui check` types
  it against kui's, Kit's and the runner's declarations.
- **Devtools**: `kui run --devtools` opens the panel, and its Log tab
  has what the app printed.
