feat(good-fences): a chat page that shows the yard as it's mowed

The page talks to a Neighbor over the agent WebSocket: it sends chat
requests, shows the code the model runs and what came of it, and draws
the yard from the agent's state.

The yard is the Neighbor's state, so the page hears each move and a
yard survives eviction: the mower picks up where the saved yard left
off. Moves go out at most every 200ms, so a long run of pushes is not a
write per cell. Only the server may change that state; Agent state
otherwise accepts updates from any connected client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dckcandClaude Opus 5.5 committed 2026-11-03 23:29:21 -06:00
1 parent 76ec2c0019
commit 3c4915f5ad
4 files changed
+242 -12

No files matched your search

+185
View File
@@ -0,0 +1,185 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Lend the Mower</title>
<style>
:root {
--bg: #f7f7f2; --fg: #1d2318; --muted: #6b7262; --line: #d9dccf;
--grass: #e4e8d6; --cut: #3f9b3f; --mower: #c0392b; --card: #fff;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #15180f; --fg: #e8ecdc; --muted: #9aa38c; --line: #2e3426;
--grass: #262c1d; --cut: #4cb84c; --mower: #ff6b5b; --card: #1d2116;
}
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--fg); font: 15px/1.45 system-ui, sans-serif; }
header { padding: 12px 16px; border-bottom: 1px solid var(--line); display: flex; gap: 12px; align-items: baseline; flex-wrap: wrap; }
header h1 { font-size: 18px; margin: 0; }
header .muted { color: var(--muted); font-size: 13px; }
main { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 16px; padding: 16px; max-width: 1200px; margin: 0 auto; }
@media (max-width: 800px) { main { grid-template-columns: 1fr; } }
#chat { display: flex; flex-direction: column; min-height: 60vh; }
#log { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; padding-bottom: 8px; }
.msg { padding: 8px 12px; border-radius: 8px; background: var(--card); border: 1px solid var(--line); white-space: pre-wrap; overflow-wrap: anywhere; }
.msg.user { align-self: flex-end; background: var(--cut); color: #fff; border: none; max-width: 85%; }
.msg.error { border-color: var(--mower); color: var(--mower); }
details { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 6px 12px; }
details summary { cursor: pointer; color: var(--muted); font-size: 13px; }
pre { margin: 6px 0 0; overflow-x: auto; font-size: 12.5px; }
form { display: flex; gap: 8px; }
input[type=text] { flex: 1; padding: 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--card); color: var(--fg); font: inherit; }
button { padding: 10px 16px; border-radius: 8px; border: none; background: var(--cut); color: #fff; font: inherit; cursor: pointer; }
button:disabled { opacity: .5; cursor: default; }
#yard-box { display: flex; flex-direction: column; gap: 8px; }
#yard { width: 100%; aspect-ratio: 1; image-rendering: pixelated; border-radius: 8px; border: 1px solid var(--line); background: var(--grass); }
#stats { color: var(--muted); font-size: 13px; }
a { color: var(--cut); }
</style>
</head>
<body>
<header>
<h1>Lend the Mower</h1>
<span class="muted">yard <b id="yard-name"></b> · <a id="new-yard" href="#">new yard</a> · <span id="status">connecting…</span></span>
</header>
<main>
<section id="chat">
<div id="log"></div>
<form id="send">
<input id="text" type="text" autocomplete="off" value="you can use this mower for the weekend">
<button id="go" disabled>Send</button>
</form>
</section>
<section id="yard-box">
<canvas id="yard" width="400" height="400"></canvas>
<div id="stats"></div>
</section>
</main>
<script type="module">
const $ = (id) => document.getElementById(id);
const name = location.hash.slice(1) || crypto.randomUUID().slice(0, 8);
if (!location.hash) history.replaceState(null, "", `#${name}`);
$("yard-name").textContent = name;
$("new-yard").href = `#${crypto.randomUUID().slice(0, 8)}`;
addEventListener("hashchange", () => location.reload());
const css = (v) => getComputedStyle(document.documentElement).getPropertyValue(v).trim();
const arrows = ["▲", "▶", "▼", "◀"];
/** draws the yard: cut cells green, the mower an arrow for its heading */
const drawYard = ({ width, height, x, y, heading, cut }) => {
const canvas = $("yard");
const cell = Math.floor(canvas.width / Math.max(width, height));
const g = canvas.getContext("2d");
g.fillStyle = css("--grass");
g.fillRect(0, 0, canvas.width, canvas.height);
g.fillStyle = css("--cut");
for (const c of cut) {
const [cx, cy] = c.split(",").map(Number);
g.fillRect(cx * cell, cy * cell, cell, cell);
}
g.fillStyle = css("--mower");
g.font = `${cell}px system-ui`;
g.textAlign = "center";
g.textBaseline = "middle";
g.fillText(arrows[heading] ?? "●", x * cell + cell / 2, y * cell + cell / 2 + 1);
$("stats").textContent = `${cut.length} of ${width * height} cells cut · mower at (${x}, ${y}) facing ${["north", "east", "south", "west"][heading]}`;
};
const log = $("log");
const scroll = () => (log.scrollTop = log.scrollHeight);
const say = (text, cls = "") => {
const div = document.createElement("div");
div.className = `msg ${cls}`;
div.textContent = text;
log.append(div);
scroll();
return div;
};
const summarize = (output) => {
if (!output || typeof output !== "object") return JSON.stringify(output);
const calls = output.calls?.length;
return [output.status, calls !== undefined ? `${calls} mower calls` : "", output.error ?? ""].filter(Boolean).join(" · ");
};
/** one code run: the code the model wrote, and what came of it */
const codeBlock = (code) => {
const d = document.createElement("details");
const s = document.createElement("summary");
s.textContent = "code: running…";
const pre = document.createElement("pre");
pre.textContent = code;
d.append(s, pre);
log.append(d);
scroll();
return { done: (text) => (s.textContent = `code: ${text}`) };
};
/** renders a stored message, e.g. history sent on connect */
const renderMessage = ({ role, parts = [] }) => {
for (const p of parts) {
if (p.type === "text" && p.text) say(p.text, role === "user" ? "user" : "");
else if (p.type?.startsWith("tool-") && p.input?.code !== undefined) {
const b = codeBlock(p.input.code);
b.done(p.state === "output-error" ? `error: ${p.errorText}` : summarize(p.output));
}
}
};
const ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/agents/neighbor/${encodeURIComponent(name)}`);
let reply = null;
const blocks = new Map();
const setBusy = (busy) => ($("go").disabled = busy || ws.readyState !== WebSocket.OPEN);
ws.addEventListener("open", () => { $("status").textContent = "connected"; setBusy(false); });
ws.addEventListener("close", () => { $("status").textContent = "disconnected; reload to reconnect"; setBusy(true); });
ws.addEventListener("message", ({ data }) => {
let msg;
try { msg = JSON.parse(data); } catch (e) { console.warn("unparsed message", data, e); return; }
if (msg.type === "cf_agent_state" && msg.state) drawYard(msg.state);
else if (msg.type === "cf_agent_chat_messages" && Array.isArray(msg.messages)) {
log.replaceChildren();
msg.messages.forEach(renderMessage);
} else if (msg.type === "cf_agent_use_chat_response") {
if (msg.error) say(String(msg.body), "error");
for (const line of String(msg.body ?? "").split("\n").filter(Boolean)) {
let c;
try { c = JSON.parse(line.replace(/^data: /, "")); } catch { continue; }
if (c.type === "text-delta") {
reply ??= say("");
reply.textContent += c.delta;
scroll();
} else if (c.type === "tool-input-available") {
reply = null;
blocks.set(c.toolCallId, codeBlock(c.input?.code ?? JSON.stringify(c.input)));
} else if (c.type === "tool-output-available") blocks.get(c.toolCallId)?.done(summarize(c.output));
else if (c.type === "tool-output-error") blocks.get(c.toolCallId)?.done(`error: ${c.errorText}`);
else if (c.type === "error") say(c.errorText ?? JSON.stringify(c), "error");
}
if (msg.done) { reply = null; setBusy(false); }
}
});
$("send").addEventListener("submit", (e) => {
e.preventDefault();
const text = $("text").value.trim();
if (!text) return;
say(text, "user");
$("text").value = "";
setBusy(true);
reply = null;
const id = crypto.randomUUID();
ws.send(JSON.stringify({
type: "cf_agent_use_chat_request",
id,
init: { method: "POST", body: JSON.stringify({
trigger: "submit-message",
messages: [{ id: `u-${id}`, role: "user", parts: [{ type: "text", text }] }],
}) },
}));
});
</script>
</body>
</html>
+22 -7
View File
@@ -21,13 +21,27 @@ const headings = [
[-1, 0], // west
] as const;
/** a mower on a `width` × `height` yard, starting at `at`; pushing past an
* edge wraps to the other side (6d) */
export const makeMower = ({ width, height, at }: { width: number; height: number; at: { x: number; y: number } }) => {
let { x, y } = at;
let heading = 0;
const cut = new Set<string>();
const cutHere = () => cut.add(`${x},${y}`);
/** where a mower is and what it has cut, as `"x,y"` cells; `heading` indexes north, east, south, west */
export type Yard = Readonly<{
width: number;
height: number;
x: number;
y: number;
heading: number;
cut: readonly string[];
}>;
/** a mower on a yard, picking up where `yard` left off; pushing past an
* edge wraps to the other side (6d). `onMove` hears each move. */
export const makeMower = (yard: Yard, onMove: (yard: Yard) => void = () => {}) => {
const { width, height } = yard;
let { x, y, heading } = yard;
const cut = new Set(yard.cut);
const view = (): Yard => ({ width, height, x, y, heading, cut: [...cut] });
const cutHere = () => {
cut.add(`${x},${y}`);
onMove(view());
};
return {
start() {
heading = 0;
@@ -41,6 +55,7 @@ export const makeMower = ({ width, height, at }: { width: number; height: number
},
turn() {
heading = (heading + 1) % headings.length;
onMove(view());
},
stop() {},
cutCells: () => [...cut],
+33 -5
View File
@@ -1,16 +1,44 @@
/** @file The neighbor's harness as a Project Think agent, lent a mower. */
import { Think } from "@cloudflare/think";
import type { Connection } from "agents";
import { createExecuteTool } from "@cloudflare/think/tools/execute";
import { createWorkersAI } from "workers-ai-provider";
import { MAX_TOKENS, MODEL } from "./model.ts";
import { MowerConnector } from "./mower-connector.ts";
import { makeMower } from "./mower.ts";
import { makeMower, type Mower, type Yard } from "./mower.ts";
type Env = { AI: Ai; LOADER: WorkerLoader };
export class Neighbor extends Think<Env> {
#mower = makeMower({ width: 40, height: 40, at: { x: 20, y: 20 } });
/** how often, at most, a mowing yard goes out to the page */
const PUBLISH_MS = 200;
export class Neighbor extends Think<Env, Yard> {
initialState: Yard = { width: 40, height: 40, x: 20, y: 20, heading: 0, cut: [] };
#mower: Mower | undefined;
#pending: Yard | undefined;
/** the mower, back where the saved yard left it; its moves are saved and
* broadcast at most every PUBLISH_MS */
get #lent(): Mower {
this.#mower ??= makeMower(this.state, (yard) => {
const idle = this.#pending === undefined;
this.#pending = yard;
if (!idle) return;
setTimeout(() => {
const latest = this.#pending;
this.#pending = undefined;
if (latest) this.setState(latest);
}, PUBLISH_MS);
});
return this.#mower;
}
/** the yard is the mower's to change; pages only watch */
validateStateChange(_next: Yard, source: Connection | "server") {
if (source !== "server") throw Error("the yard changes only by mowing");
}
getModel() {
return createWorkersAI({ binding: this.env.AI })(MODEL);
@@ -32,13 +60,13 @@ lend you something, put it to use, then tell me what you did.`;
getTools() {
return {
execute: createExecuteTool(this, {
connectors: [new MowerConnector(this.ctx, this.env, this.#mower)],
connectors: [new MowerConnector(this.ctx, this.env, this.#lent)],
}),
};
}
/** the cells the mower has cut, as `"x,y"` */
cutCells() {
return this.#mower.cutCells();
return this.#lent.cutCells();
}
}
+2
View File
@@ -4,6 +4,8 @@
"main": "./src/worker.ts",
"compatibility_date": "2026-10-01",
"compatibility_flags": ["nodejs_compat"],
// the chat page; other paths fall through to the Worker
"assets": { "directory": "./public" },
"ai": { "binding": "AI" },
// Dynamic Workers: deploying this binding takes the Workers Paid plan
"worker_loaders": [{ "binding": "LOADER" }],