# Watch for changes

> One socket that says which of your objects changed, so a page reads them again the moment they do.

`watch` tells you **which object changed**, never what it changed to: a deployment went ready, a message landed in a channel, an agent took a step. You read the object again. It's for keeping a page or a cache current without polling. It isn't the [event log or webhooks](https://www.noclick.com/docs/guide/webhooks.md): those record **what happened**, with its data, keep it 30 days and deliver each event at least once to your server. A change is a hint, delivered at most once, kept only long enough for a dropped connection to catch up.

## Follow changes

```python
import noclick

def refresh(obj, object_id):
    print("read again:", obj, object_id)

def refresh_everything():
    print("read everything you show again")

for message in noclick.watch(objects=["deployment", "domain"]):
    if message.type == "change":
        refresh(message.object, message.object_id)
    elif message.type == "reset" or (message.type == "ready" and not message.resumed):
        refresh_everything()
```

```ts
import { watch } from "noclick";

function refresh(object: string, objectId: string | null) {
  console.log("read again:", object, objectId);
}
function refreshEverything() {
  console.log("read everything you show again");
}

for await (const message of watch({ objects: ["deployment", "domain"] })) {
  if (message.type === "change") refresh(message.object, message.objectId);
  else if (message.type === "reset" || (message.type === "ready" && !message.resumed)) refreshEverything();
}
```

`objects` narrows what you follow; without it you follow every object your key may read. Python's `watch` needs the websockets package: `pip install "noclick[live]"`. It reconnects by itself, with a new token each time, and resumes after the last change it gave you; while connections keep dropping soon after they open, it waits longer before each try. It stops only for what trying again can't fix: the key revoked, a scope the key lacks, or `WatchRefused` when access ended while it was open.

## What you must do

A change can be lost: a deploy, a network blip or a busy second can drop one. So:

- On `reset`, read again everything you show. The room sends it when too much changed at once to say each, and `watch` hands you one in place of what piled up while you were busy (past 1,000 messages).
- On `ready` with `resumed` false, read everything again: it couldn't carry on from where you were. The first `ready` is one too, for anything you read before it.
- If what you show must never be stale, also read it again on a slow timer of your own.

A change's `status` is what the object's read said then; the read is the truth.

## In a browser

A page never holds your key. Give `watch` a client that goes through your server, and it asks your server for the token, then opens the socket to NoClick itself:

```ts
import { NoClick, watch } from "noclick";

// Your server forwards /api/v1/* to NoClick with its key, as the open app's does.
const client = new NoClick({ baseUrl: `${location.origin}/api`, apiKey: "held-by-your-server" });
for await (const message of watch({ client, objects: ["channel"] })) {
  if (message.type === "typing") console.log(message.userId, message.typing ? "is typing" : "stopped");
}
```

Or give it a function that asks your own server, which calls `watch_token` for the page's origin:

```python
import noclick

token = noclick.watch_token(user="user_42", origin="https://app.example.com")
print(token.url)    # hand url and token to the page; it opens the socket within a minute
```

```ts
import { watch, watchToken } from "noclick";

const token = await watchToken({ user: "user_42", origin: "https://app.example.com" });
console.log(token.url);   // hand url and token to the page; it opens the socket within a minute

// In the page:
for await (const message of watch({
  token: async () => (await fetch("/watch-token", { method: "POST" })).json(),
})) console.log(message.type);
```

A token opens one socket once, within a minute, and only from the origin it names. The socket's URL is `wss://api.noclick.com/v1/watch/socket/...`; allow it in your page's `connect-src`. `watch` sends a token only to a `wss://` URL (`ws://` on your own machine), so pass the url your server got on as it is.

If you open the socket yourself, offer the token as its subprotocol, beside `noclick.watch`, never in the URL, and resume with `after` in the URL:

```ts
const socket = new WebSocket(`${token.url}?after=${lastChangeId}`, ["noclick.watch", token.token]);
```

A socket without a valid token is refused before it opens. A refused one closes with 4401, a busy room with 4429, and the end of a connection's life with 4000.

## What a change says

| Field | |
| --- | --- |
| `object` | What changed, as its read names it: `deployment`, `domain`, `channel`, `agent`, ... |
| `object_id` | Its id. |
| `status` | Its status then, where it has one; null once it's gone. |
| `parent` | What it belongs to: a deployment's `project`, a call's `phone_number`, a trigger's `agent`. |
| `change` | What moved, for an agent (`turn`, `step`, `definition`, ...) and a channel (`message`, `reaction`, `thread`, ...). On an agent's `turn`, read its conversations again: a change never names one. |
| `version` | A workflow's graph version now. |
| `id` | The change's place in the stream; a reconnect resumes after it. |

Changes never carry names, text or anything the object's read would withhold. `typing` says who (a user's id, or `account`) started or stopped typing in a channel you read; you never hear your own. Ignore a message type or field you don't know: the stream grows.

The objects: `domain`, `deployment`, `repo`, `mcp_server`, `live_session`, `phone_call`, `workflow`, `durable_object_class`, `skill`, `memory`, `machine`, `sandbox`, `agent_move`, `connection`, `plan_usage`, `agent_trigger`, `approval`, `browser`, `agent`, `coding_agent`, `channel`, `workspace`, `workspace_resource`, `channel_sections`, `space_question`.

## Who hears what

- Your account's key, and you signed in, hear the account's changes, your users' included.
- A key acting for one of your users (`user`), or a user's [session](https://www.noclick.com/docs/guide/sessions.md), hears only that user's: their own objects, their own turns with your agents, and the channels and workspaces they read.
- Each key hears only the objects its [scopes](https://www.noclick.com/docs/guide/keys.md) read.
- Someone who joined one of your workspaces hears only what they can read there: its channels, its agents.
- A suspended or deleted user hears nothing.
- An app's own code, a publishable key and an MCP connection can't watch.

Revoking a key, or deleting or suspending a user, closes their sockets, and no token minted before it opens one.

## Limits

- A connection lasts up to 15 minutes, never past its key's or session's end; `watch` then reconnects and resumes.
- A key holds up to 20 connections to one room (its sessions together) and opens up to 120 a minute; a room holds up to 250.
- Your account follows up to 10,000 rooms at once (one per user watching, and the account's).
- A dropped connection resumes within 10 minutes, and the last 500 changes, while its room is awake; otherwise `ready` says it didn't resume, and you read again.
- More than 50 changes in a second become one `reset`, and one more once the second ends if more came.

Watching is free.
