# Droplet.ai interactive reference

Taps end to end: what the user sees, how events reach you (get_events, listen.mjs, webhooks, or nothing running), replying, checklists, and droplet_ask.

---

## What the user sees when they tap a button

```
User taps a button (no url)
   │  the button dims and shows "Sent" at once
   ▼
Droplet.ai stores the tap as an event for the agent that owns the widget
   │  the widget looks again every 3 s for up to a minute
   ▼
Your agent picks it up (get_events returns it, or your webhook answers 2xx)
   │  the button shows "Seen"
   ▼
Your agent updates the widget (set_widget)
      the button is itself again, and your new content shows
```

- "Sent" and "Seen" fade after 2 minutes. A tap you never answer just looks ignored.
- Any `set_widget` on that widget after the tap ends the Sent/Seen state, so always change something visible: "Seen" followed by the same widget looks broken.
- After each `set_widget` Droplet.ai pushes a redraw. iOS usually shows it within seconds, but it rate-limits widget redraws, so several updates in a burst can lag.
- A button with a `url` just opens it. No event.
- If the tap can't reach Droplet.ai (no network), the button goes back to normal and nothing is sent.

---

## The event

```text
{
  "id": "8b0d...",            unique; use it to handle each tap once
  "widget": "check-in",       the widget's slug
  "kind": "button",           "button", "check" or "answer"
  "target": "good",           button: its id. check: the item's title. answer: the request_id
  "value": { "label": "Good" },
  "source": "widget",         "widget", "app" (tapped in the Droplet.ai app) or "control" (Control Center, Lock Screen, Action button)
  "created_at": "2026-10-28T11:30:00.123Z"
}
```

For a checklist tick, `value` is `{"done": true, "block": 1, "item": 2}`, plus `"variant": 0` when the checklist is inside a version. Droplet.ai has already saved the tick; you only need the event to react (update a count, a bar, the next step). Use `block` and `item` when two items have the same title.

**Answers arrive here too.** When the user answers one of your `droplet_ask` questions (on your widget or in the app), you get:

```text
{ "id": "...", "widget": "question", "kind": "answer", "target": "<request_id>",
  "value": { "answer": "Yes, green", "question": "Make my widget green?", "request_id": "<request_id>" },
  "source": "widget", "created_at": "..." }
```

If you read the answer with `get_answer` first, the event is marked seen and won't come again. So one listener (get_events, listen.mjs, a webhook) covers taps, ticks and answers.

Events go only to the agent that owns the widget (the one that made it) or asked the question. They come in the order the user made them, each once (unless you `peek`).

---

## Never end your turn without a waker

If you end your turn while a tap or an answer is still to come, you never see it. Before you stop, start a waker:

- **Claude Code** (and any agent that can run a background command and is woken when it exits): run `node listen.mjs --once` as a background command (Bash with `run_in_background`). It waits for the next tap, tick or answer, prints it as one JSON line and exits 0, and Claude Code wakes you with that output, like a message from the user. Act on it, update the widget, and start a new `--once` if more replies are expected.
- **Hosted or always-on agents**: a webhook (Way 3). Droplet.ai POSTs every tap, tick and answer.
- **Anything else**: stay in the turn and keep calling `get_events` with `wait_seconds` 50 until the event comes and you've handled it.

```bash
curl -sO https://droplet.ai/kit/scripts/listen.mjs
DROPLET_TOKEN=dp_... node listen.mjs --once                     # next tap, tick or answer
DROPLET_TOKEN=dp_... node listen.mjs --widget question --once   # next answer to a droplet_ask question only
DROPLET_TOKEN=dp_... node listen.mjs --widget commute --once    # next tap on the "commute" widget only
```

If several events arrive in the same moment, each is printed on its own line before it exits.

---

## Way 1: get_events (long-poll)

```bash
curl -s -X POST "https://ujtuxanqlzmhnrzijfoo.supabase.co/functions/v1/agent-api" \
  -H "Authorization: Bearer $DROPLET_TOKEN" \
  -H "Content-Type: application/json" \
  -H "x-region: us-east-1" \
  -d '{"action":"get_events","wait_seconds":50}'
```

```text
{ "events": [ { "id": "...", "widget": "check-in", "kind": "button", "target": "good", ... } ] }
```

| Field | Notes |
|---|---|
| `wait_seconds` | 0 to 50, default 0. Droplet.ai checks every 0.3 s and returns the moment a tap lands, or after the wait with `events: []` and a `hint` |
| `slug` | Only this widget's taps |
| `peek` | `true` to look without marking them seen (the button stays Sent) |

Returned events are marked seen (the button turns Seen) and won't come back. Call again right away to keep listening. MCP: `droplet_get_events` with the same fields.

---

## Way 2: listen.mjs (a ready-made loop)

`listen.mjs` (Node 18+, no dependencies) keeps one `get_events` call open and runs your handler for each tap, tick or answer (`--once` waits for just the next one, then exits). Get it with `curl -sO https://droplet.ai/kit/scripts/listen.mjs`.

```bash
DROPLET_TOKEN=dp_... node listen.mjs                                  # print taps as JSON lines
DROPLET_TOKEN=dp_... node listen.mjs --on-tap "./handle-tap.sh"       # run a handler per tap
DROPLET_TOKEN=dp_... node listen.mjs --widget check-in --on-tap "node handler.mjs"
```

- The handler gets the event as JSON on stdin and in `$DROPLET_EVENT`.
- Every line it prints that is a JSON object is sent as `set_widget` the moment it's printed, in order. `slug` defaults to the tapped widget.
- **Each line is a `set_widget`.** Fields you send replace the old ones (`blocks` and `variants` as whole lists); fields you leave out keep their values, including `blocks` and `variants`. So a line with `blocks` must hold all of them, in the same order.
- Taps run one after another. On 401 or 403 it stops (exit code 2); other errors retry with backoff up to 30 s.

### Handler (shell)

```bash
#!/usr/bin/env bash
# handle-tap.sh: acknowledge at once, then answer.
target=$(python3 -c "import sys,json; print(json.load(sys.stdin)['target'])")
BTNS='{"type":"buttons","items":[{"id":"approve","label":"Approve","symbol":"checkmark"},{"id":"reject","label":"Reject","symbol":"xmark"}]}'
case "$target" in
  approve)
    echo "{\"blocks\":[{\"type\":\"text\",\"style\":\"title\",\"text\":\"Approving…\"},$BTNS]}"
    ./deploy.sh >/dev/null 2>&1
    echo "{\"blocks\":[{\"type\":\"text\",\"style\":\"title\",\"text\":\"Approved. Live.\"},$BTNS]}"
    ;;
  reject)
    echo "{\"blocks\":[{\"type\":\"text\",\"style\":\"title\",\"text\":\"Rejected.\"},$BTNS]}"
    ;;
esac
```

### Handler (Node.js)

```javascript
// handle-tap.mjs
import { readFileSync } from "node:fs";
const event = JSON.parse(readFileSync(0, "utf8"));
const buttons = { type: "buttons", items: [
  { id: "approve", label: "Approve", symbol: "checkmark" },
  { id: "reject", label: "Reject", symbol: "xmark" },
] };
const say = (text) => console.log(JSON.stringify({ blocks: [{ type: "text", style: "title", text }, buttons] }));

if (event.target === "approve") {
  say("Approving…");          // on the phone in about a second
  await deploy();             // your slow work
  say("Approved. Live.");
} else if (event.target === "reject") {
  say("Rejected.");
}
```

### Handler (Python)

```python
#!/usr/bin/env python3
import sys, json

event = json.load(sys.stdin)
buttons = {"type": "buttons", "items": [
    {"id": "approve", "label": "Approve", "symbol": "checkmark"},
    {"id": "reject", "label": "Reject", "symbol": "xmark"}]}

def say(text):
    print(json.dumps({"blocks": [{"type": "text", "style": "title", "text": text}, buttons]}), flush=True)

if event["target"] == "approve":
    say("Approving…")
    deploy()
    say("Approved. Live.")
elif event["target"] == "reject":
    say("Rejected.")
```

Use `flush=True` (Python) so the first line reaches listen.mjs straight away.

### Running listen.mjs as a service

macOS (launchd), `~/Library/LaunchAgents/com.droplet.listen.plist`:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>com.droplet.listen</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/local/bin/node</string>
    <string>/path/to/listen.mjs</string>
    <string>--on-tap</string><string>/path/to/handle-tap.sh</string>
  </array>
  <key>EnvironmentVariables</key>
  <dict><key>DROPLET_TOKEN</key><string>dp_YOUR_TOKEN</string></dict>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>StandardErrorPath</key><string>/tmp/droplet-listen.log</string>
</dict>
</plist>
```

```bash
launchctl load ~/Library/LaunchAgents/com.droplet.listen.plist
```

Linux (systemd user unit), `~/.config/systemd/user/droplet-listen.service`:

```ini
[Unit]
Description=Droplet.ai tap listener

[Service]
ExecStart=/usr/bin/node /path/to/listen.mjs --on-tap /path/to/handle-tap.sh
Environment=DROPLET_TOKEN=dp_YOUR_TOKEN
Restart=always
RestartSec=5

[Install]
WantedBy=default.target
```

```bash
systemctl --user enable --now droplet-listen
```

Or: `nohup env DROPLET_TOKEN=dp_... node listen.mjs --on-tap ./handle-tap.sh >> /tmp/droplet.log 2>&1 &`

---

## Way 3: webhook

For agents with a public https endpoint.

```bash
curl -s -X POST "https://ujtuxanqlzmhnrzijfoo.supabase.co/functions/v1/agent-api" \
  -H "Authorization: Bearer $DROPLET_TOKEN" -H "Content-Type: application/json" -H "x-region: us-east-1" \
  -d '{"action":"set_webhook","url":"https://yourapp.example.com/droplet/tap"}'
```

Returns `{"ok": true, "webhook": "...", "secret": "lvs_...", "how": "..."}`. The secret is shown once; store it. Calling `set_webhook` again makes a new secret. `{"url": null}` (or `""`) turns it off. MCP: `droplet_set_webhook`.

- The URL must be https and reachable from the internet (localhost and private addresses are rejected; use get_events locally).
- Droplet.ai POSTs `{"type": "widget_tap", "event": { ...the event above... }}` with headers `Content-Type: application/json`, `User-Agent: Droplet-Webhook/1` and `X-Droplet-Signature: sha256=<hex HMAC-SHA256 of the raw body, keyed with the secret>`.
- Answer 2xx within 6 s. Otherwise Droplet.ai tries again after 1.5 s and 4 s (three tries in all), with the same event `id`. A 2xx marks the tap Seen.
- A tap stays available to `get_events` until something marks it seen, so running a webhook and a get_events loop together can deliver the same tap twice. Pick one, or dedupe by `id`.

### Express

```javascript
import express from "express";
import { createHmac, timingSafeEqual } from "node:crypto";

const app = express();
app.use(express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } }));

app.post("/droplet/tap", (req, res) => {
  const expected = Buffer.from("sha256=" + createHmac("sha256", process.env.DROPLET_WEBHOOK_SECRET).update(req.rawBody).digest("hex"));
  const got = Buffer.from(req.get("x-droplet-signature") ?? "");
  if (got.length !== expected.length || !timingSafeEqual(got, expected)) return res.sendStatus(401);
  res.sendStatus(200);                          // answer first
  handleTap(req.body.event).catch(console.error); // then work
});
```

### Python

```python
import hmac, hashlib

def verify(raw_body: bytes, header: str, secret: str) -> bool:
    expected = "sha256=" + hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, header or "")

# event = json.loads(raw_body)["event"]
```

Sign over the raw bytes, never over re-serialized JSON.

---

## Way 4: nothing running (hosted and chat-only agents)

If you only run when the user talks to you, nobody picks taps up in between. Droplet.ai keeps them (unseen) until you call `droplet_get_events`, but the button's Sent fades after 2 minutes.

- Call `droplet_get_events` at the start of every conversation and handle what's waiting (taps and answers) before anything else.
- When you can, don't end a turn that waits on the user: use `droplet_ask` and keep waiting with `droplet_get_answer`, or start a waker (above).
- Design for it: `url` buttons (open a page, call, run a Shortcut), checklists (ticks save themselves), countdowns, versions and scheduled jobs all work with no agent.
- Use event buttons only when something will answer soon, and tell the user: "Taps reach me the next time we talk."

---

## Handle each tap once

```javascript
const handled = new Set(); // keep it on disk in production
async function handleTap(event) {
  if (handled.has(event.id)) return;
  handled.add(event.id);
  // ...
}
```

---

## Don't block the loop

Wrong: running a slow command (like starting a new AI CLI process) per tap, inside the loop. The user sees Sent for minutes, and later taps wait behind it.

Right: acknowledge first, work in the background, update again.

```python
import threading

def handle(event):
    set_widget(event["widget"], "On it…")       # within a second
    threading.Thread(target=lambda: set_widget(event["widget"], slow_answer(event))).start()

while True:
    for event in call("get_events", wait_seconds=50)["events"]:
        handle(event)
```

(`set_widget` here is your own helper that sends the full widget with the new text.)

---

## Button ids

- Lowercase words with dashes: `approve-deploy`, `snooze-1h`, `q2-yes`. Up to 30 characters, unique in the block. Without an `id`, the label slugified is used, so changing the label changes the id.
- Keep ids stable across updates. A button the user added to Control Center keeps sending its old id; handle unknown ids gracefully (update the widget to say what's current).

---

## Checklists

Every tick and untick is saved by Droplet.ai at once and sent to you as a `check` event. To react:

```javascript
if (event.kind === "check") {
  const { widgets } = await dropletCall("list_widgets");
  const w = widgets.find((x) => x.slug === event.widget);
  const list = w.blocks[event.value.block];          // or w.variants[event.value.variant].blocks[...]
  const done = list.items.filter((i) => i.done).length;
  // update the progress block, keep every item's done state as it is
}
```

Ticks are stored by position (block and item index). If you reorder or remove items while a tick is on its way, the tick can land on a different item, or fail with "That checklist item changed" if that position is gone. Add new items at the end, update checklists only when you need to, and always start from the current `done` states.

---

## Buttons or droplet_ask?

| | Widget buttons | droplet_ask |
|---|---|---|
| Shown as | Buttons on your widget | On your own widget ("<agent> asks" with the answer buttons, until answered), in the Droplet.ai app and the optional Questions widget; a notification only if `risk` is high, `notify` is true, or the user has no Droplet.ai widget |
| Best for | Decisions the widget shows in full: everyday choices, and consequential ones when the amount, recipient or target is on the widget ("Uber $14, here 8:05" [Book]) | Consequential steps whose details don't fit on a widget, free-text answers, anything that needs the user now, wherever they are |
| Answer | A `button` event | `get_answer` (`answered`, with the option or the user's own words), and an `answer` event on the same stream as taps |
| Waits | Until the user taps (no expiry) | Until answered or you cancel (no expiry) |
| Tracked | No | `list_requests` |

A tap on a button that names the action is the user's approval when the widget shows exactly what will happen (amount, recipient, target). If it doesn't, confirm with `droplet_ask` and put the details there. Either way, never act on money, sending, deleting or deploying silently, and after acting show the outcome and an Undo where you can (see "Think agentic, not dashboard" in SKILL.md).

### droplet_ask

| Field | Notes |
|---|---|
| `question` | Required, 140 characters |
| `details` | Up to 600 characters, shown when they open it |
| `kind` | `decision` (default: exactly 2 options, else Approve / Reject), `choice` (2 to 4), `input` (free text) |
| `options` | Up to 4, 40 characters each |
| `default_answer` | `input`: a one-tap suggested reply |
| `risk` | `low`, `medium` (default), `high`. High sends a notification |
| `notify` | `true` to send a notification anyway; `false` to keep a high-risk question silent. Without it, Droplet.ai notifies only for high risk or when the user has no Droplet.ai widget |
| `wait_seconds` | MCP only: how long `droplet_ask` waits (0 to 50, default 45). HTTP `ask` returns at once |

```javascript
// MCP
let r = await droplet_ask({ question: "Ship the release?", kind: "decision", options: ["Ship", "Wait"], risk: "high" });
while (r.status === "pending") r = await droplet_get_answer({ request_id: r.request_id, wait_seconds: 45 });
if (r.status === "answered" && r.answer === "Ship") ship();
// r.answer can also be the user's own words; anything else means don't ship.
```

A question is answered once. `cancelled` means you (or another call) withdrew it.

---

## Lock Screen

Lock Screen widgets have no buttons or ticks. A tap opens the widget's `url` (or Droplet.ai). For a one-tap action from the Lock Screen, the user can add your button through Droplet.ai's "Agent button" control (Lock Screen or Control Center); its taps arrive with `source: "control"`.
