# Writing a devtools tab

A module adds to [`@hamur/devtools`](/devtools) with four calls of `hamur/kit`, each one a few lines in `setup`. A tab adds a page to the panel, an app adds a button to the toolbar that draws on your page, an RPC function gives them data from the dev server, and a dev process runs a program next to `hamur dev`. The tab and the app run in the browser and are written with plain DOM and `defineDevtoolsApp` of `hamur/app`; the RPC function and the process run in the dev server.

Without `@hamur/devtools` the calls record and nothing reads the record, and in a build they check their arguments and record nothing, so a module needs no branch for either case.

## A tab

`addDevtoolsTab` takes a `name` (lower case, digits and `-`, starting with a letter, unique among tabs), a `title`, an `icon` (SVG markup or one or two characters) and a `view`. The tab appears in the Modules group of the sidebar, after the built-in tabs, in the order of the calls.

A module view is a file whose default export is `defineDevtoolsApp({ init })`. `entry` is an absolute path, a path from the app's root or a package specifier; `createResolver(import.meta.url).resolve()` gives an absolute path next to the module. The panel bundles the file with `Bun.build`, so it may import other files and packages. A change to the file builds the panel again and reloads the open panel; a build that fails shows its error in the panel.

````ts [devtools/notes-module.ts]
import { addDevtoolsTab, createResolver, defineModule, extendDevtoolsRpc, useDevChannel } from "hamur/kit"

export default defineModule({
  meta: { name: "notes" },
  setup() {
    const resolver = createResolver(import.meta.url)
    const notes: string[] = []

    addDevtoolsTab({
      name: "notes",
      title: "Notes",
      icon: "N",
      view: { type: "module", entry: resolver.resolve("./notes-view.ts") },
    })

    extendDevtoolsRpc("notes:list", () => notes)
    extendDevtoolsRpc<{ text: string }, number>("notes:add", ({ text }) => {
      notes.push(text)
      useDevChannel().send("notes:changed", { count: notes.length }, "devtools")
      return notes.length
    })
  },
})
````

`init(canvas, ctx)` draws into `canvas`, the content area of the tab, and the function it returns runs when the tab is closed. `ctx.setBadge(text)` writes the number on the tab's sidebar item, `ctx.rpc(name, args)` calls a function of the dev server, and `ctx.on(event, fn)` receives what a module pushes. A view whose `init` throws shows `Tab "notes" failed: <message>` in the panel.

````ts [devtools/notes-view.ts]
import { defineDevtoolsApp } from "hamur/app"

export default defineDevtoolsApp({
  async init(canvas, ctx) {
    canvas.style.color = "var(--fg)"
    const input = document.createElement("input")
    const add = Object.assign(document.createElement("button"), { textContent: "Add" })
    const list = document.createElement("ul")
    canvas.append(input, add, list)

    const draw = async () => {
      const notes = await ctx.rpc<string[]>("notes:list")
      list.replaceChildren(...notes.map((text) => Object.assign(document.createElement("li"), { textContent: text })))
      ctx.setBadge(String(notes.length))
    }

    add.onclick = async () => {
      await ctx.rpc("notes:add", { text: input.value })
      input.value = ""
    }

    const stop = ctx.on("notes:changed", draw)
    await draw()
    return stop
  },
})
````

The panel's look is a set of CSS custom properties on `:root`, and a tab that styles itself on them follows the light and dark theme and the scale: `--app`, `--panel`, `--raised`, `--hover`, `--active`, `--field`, `--line`, `--line-strong`, `--hairline`, `--fg`, `--fg-2`, `--fg-3`, `--fg-4`, `--side`, `--side-icon`, `--accent`, `--accent-soft`, `--amber`, `--red`, `--green`, `--blue` and `--violet`. Use `rem` for sizes. Do not rely on the panel's other classes.

`ctx.page` is the page hook of the app page, `window.__hamur_devtools`, and is `undefined` when the panel was opened on its own. It gives the current route and the loader data of each match, the payload and the `useState` values (with `setState`), the head, the `hamur:*` performance measures, the hydration mismatch reports and the toolbar. See [`defineDevtoolsApp`](/api-reference/app#devtools).

A tab can also be a page of your own. `{ type: "iframe", src }` shows `src`, a path below `app.baseURL` or an `http` or `https` address, in a frame, and the dev handler of the module can answer it.

````ts [devtools/iframe-tab-module.ts]
import { addDevServerHandler, addDevtoolsTab, defineModule } from "hamur/kit"

export default defineModule({
  meta: { name: "mailbox" },
  setup() {
    addDevServerHandler({
      route: "/_mailbox/",
      handler: () => new Response("<h1>Mailbox</h1>", { headers: { "content-type": "text/html; charset=utf-8" } }),
    })
    addDevtoolsTab({ name: "mailbox", title: "Mailbox", icon: "M", view: { type: "iframe", src: "/_mailbox/" } })
  },
})
````

## RPC functions

`extendDevtoolsRpc(name, fn)` registers a function that a tab or app calls with `ctx.rpc(name, args)`. The name is `<module>:<function>`; `hamur:`, `bun:` and `vite:` are reserved, and two modules cannot take the same name. The function runs in the dev server with the module's context, so `useHamur()` works inside it. It gets the JSON that the caller sent and nothing of the request, no header and no cookie, and its result must survive `JSON.stringify`. A function that throws rejects the call in the browser with its message.

To tell open tabs that something changed, send from the dev server with `useDevChannel().send(event, data, "devtools")`, as `notes:add` does above. The event name is `<module>:<event>` and `ctx.on` receives it. Only devtools panels get a message sent to `"devtools"`, a page never does. See [Dev channel](/dev-channel).

## An app

`addDevtoolsApp` takes the same keys as a tab, with `entry` in place of `view`. It adds a button after the Hamur button of the toolbar. A click imports the entry and calls its `init` with a canvas that covers the whole page, drawn in the toolbar's shadow root; the next click calls the function that `init` returned and empties the canvas. The canvas ignores the pointer, so the page below it keeps working; set `canvas.style.pointerEvents = "auto"` to take it. `ctx.setBadge(text)` writes on the button, and `undefined` clears it.

````ts [devtools/grid-module.ts]
import { addDevtoolsApp, createResolver, defineModule } from "hamur/kit"

export default defineModule({
  meta: { name: "grid" },
  setup() {
    const resolver = createResolver(import.meta.url)
    addDevtoolsApp({ name: "grid", title: "Show the 8 px grid", icon: "#", entry: resolver.resolve("./grid-app.ts") })
  },
})
````

````ts [devtools/grid-app.ts]
import { defineDevtoolsApp } from "hamur/app"

export default defineDevtoolsApp({
  init(canvas, ctx) {
    const grid = document.createElement("div")
    grid.style.cssText =
      "position:absolute;inset:0;background:repeating-linear-gradient(90deg,rgba(255,0,0,.25) 0 1px,transparent 1px 8px)"
    canvas.append(grid)
    ctx.setBadge("on")
    return () => ctx.setBadge(undefined)
  },
})
````

A view that throws marks its button and logs `[hamur] devtools app "grid" failed: <message>` in the browser console.

## A process

`startDevProcess` runs a program next to `hamur dev`, such as a code generator in watch mode. It starts right after the dev server is ready, in `cwd` (absolute, or from the app's root, which is the default) with `env` added to the dev server's environment. It works without `@hamur/devtools`.

````ts [devtools/codegen-module.ts]
import { defineModule, startDevProcess } from "hamur/kit"

export default defineModule({
  meta: { name: "codegen" },
  setup() {
    startDevProcess({
      name: "codegen",
      command: "bun",
      args: ["run", "codegen", "--watch"],
      cwd: "tools",
      env: { FORCE_COLOR: "1" },
    })
  },
})
````

Each line of its output prints as `[codegen] <line>`. The Terminals and logs tab keeps the last 1000 lines of both streams and has Restart and Kill. When the process exits, `hamur dev` logs `[hamur] dev process codegen exited with code <n>` and does not start it again; a command that cannot start logs `[hamur] dev process codegen could not start: <message>` and shows as failed. Restart and kill send `SIGTERM` and then `SIGKILL` after 3 seconds, and so does `hamur dev` when it stops or restarts.

## Names and errors

Each of the four calls checks its arguments when it runs and throws at the start of `hamur dev` with a message such as `hamur/kit: addDevtoolsTab name "Pages" must match /^[a-z][a-z0-9-]*$/` or `hamur/kit: addDevtoolsTab name "notes" is already registered by <module>`. [`hamur/kit`](/api-reference/kit) lists every message, with [`useDevtoolsRegistry`](/api-reference/kit) that `@hamur/devtools` reads.
