Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

docs(samples): a hackathon kit for the Fo team (#1380)

0xdiego2568f1dda1c968
diff --git a/docs/superpowers/specs/2026-10-16-hackathon-fo-samples-design.md b/docs/superpowers/specs/2026-10-16-hackathon-fo-samples-design.md
new file mode 100644
index 000000000..0be7797ec
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-16-hackathon-fo-samples-design.md
@@ -0,0 +1,83 @@
+# Hackathon samples for the Fo team
+
+October 16, 2026. Design approved in conversation with the owner. For a one-day hackathon on October 17: the Fo
+team has round Harness devices and needs to learn the repo and build on it.
+
+## What ships
+
+One folder, `samples/hackathon-fo/`, in US English (code, identifiers and code comments also in English):
+
+```
+samples/hackathon-fo/
+ README.md the guide: install, sign in, harnesses, Fo, the device
+ 01-fo-glance/ sample 1: a firmware screen for the round device, driven by Fo
+ 02-desk-assistant/ sample 2: new email → Fo → the device
+```
+
+No "ideas for later" section. No change to the product: the firmware solution ships as a patch in the sample,
+not merged into the firmware.
+
+## The guide (README.md)
+
+Step by step, each step with what you should see and what to do when it does not happen:
+
+1. Install Harness Desktop for macOS (https://harness.autonomous.ai/desktop; Linux AppImage noted; no Windows),
+ sign in (Google, Apple or email), and the CLI (`curl -fsSL https://harness.autonomous.ai/install.sh | bash`,
+ `harness login`, `harness start`).
+2. A harness: **New Harness** (⌘N), machine, folder, engine. Claude Code and Codex must be installed and signed in
+ (`claude`, `codex`) first.
+3. Fo: Settings ▸ Connectors ▸ **Add custom**, Remote MCP server URL `https://mcp.api.wajo.ai/fo`, sign in to Wajo
+ in the browser. Then **New Harness** ▸ Agent **Fo** (runs in Fo's cloud, opens a chat pane) and give it an errand.
+4. The round device: USB-C data cable to a Mac running Harness; Devices ("Plug in. Make it yours."), name it. On the
+ device: tap a tile to choose an agent, hold the face ~0.65 s to talk and release to send, the recap after a turn,
+ the bell for Notices. Gestures as the firmware implements them (touch), not "turn".
+5. Common problems: charge-only cable, daemon not running (`harness start`), engine not signed in, Fo not connected
+ (`NOT_CONNECTED`).
+6. A map of the repo for the samples: where the firmware, the daemon (`cli/`), the Desktop and the docs live.
+
+## Sample 1 — Fo glance face (`01-fo-glance/`)
+
+A firmware UI change on the round device, so the team builds, previews and flashes firmware.
+
+- **Warm-up: a theme.** A build flag `DEVICE_HABITAT_FO` on the pattern of `DEVICE_HABITAT_ORANGE` (`theme.h`,
+ `main/CMakeLists.txt`): Fo colours for the canvas, accent, working and voice.
+- **Main exercise: the glance screen.** When an agent's recap is a glance line, the device draws a glance screen
+ instead of the recap card:
+ - Line format (case-sensitive, one line, the whole recap or its first line):
+ `GLANCE applied=5 replies=2 interviews=1 goal=10` — up to 4 `key=value` pairs, keys `[a-z]{1,12}`,
+ values unsigned integers ≤ 9999; unknown keys shown as-is; `goal` is not shown as a number but drives the ring.
+ - The screen: the agent title arc as today, three numbers big with their labels, and a ring around the edge
+ (`ht_ring_arc`) filled `applied / goal`. Malformed lines fall back to the ordinary recap card.
+ - Data reaches the firmware the way recaps already do (the daemon's `summary` frame); no daemon change.
+- **Tooling:** `preview.sh` renders the Working, Recap and glance screens to PNG with the host renderer
+ (`test/test_touch_ui.py`, `HABITAT_PREVIEW_DIR`), no device needed. A host test for the glance parser.
+- **Build and flash:** ESP-IDF install note (start early), `idf.py -DPROJECT_VER=0.0.99 -DDEVICE_HABITAT_FO=1 build`
+ (0.0.99 so the daemon's OTA never overwrites it), the safe sequence (quit the app, `harness stop`, flash with
+ `idf.py -p <port> flash`, `harness start`), and back to the release with `harness flash`.
+- **Folder:** `README.md` (the exercise with pointers to the exact files and functions), `preview.sh`,
+ `solution.patch` (theme + glance, applies cleanly to main with `git apply`), and `fo-prompt.md` (what to tell Fo
+ so its replies end in a glance line).
+
+## Sample 2 — desk assistant (`02-desk-assistant/`)
+
+- `mail_to_fo.py`, Python 3 standard library only: IMAP over TLS (Gmail with an app password), polls every 30 s,
+ takes new unseen messages from one folder, and hands each to one long-lived Fo harness named "Fo inbox"
+ (created on the first email, written to afterwards). The text sent: sender, subject, a plain-text body cut to
+ 2,000 characters, and the instruction to summarise it in one sentence and say what to do; job-search mail also
+ updates the glance line of sample 1.
+- Fo's reply ends its turn, so the device beeps and files a notice with the recap; a Fo question appears on the
+ device's question screen.
+- Config in `.env` (`IMAP_HOST`, `IMAP_USER`, `IMAP_APP_PASSWORD`, `IMAP_FOLDER`, `POLL_SECONDS`). It stores no
+ mail on disk, only the UIDs it handled (`state.json`). It does not mark mail read unless `--mark-read`.
+- `--engine claude` sends the same text to a local Claude Code harness instead, for when Fo is unavailable.
+- How it reaches Fo: verified against the running daemon during implementation — `harness new fo -- <text>` /
+ the local WebSocket requests `agent_create {engine:'fo', prompt}` and `cloud_send` — and the README documents the
+ one that works. Unit tests for the mail-to-text step (HTML stripped, length cut, headers decoded).
+
+## Verification
+
+- Sample 1: `solution.patch` applies to main; the host tests pass; `preview.sh` renders the three screens; an
+ `idf.py` build with the flags succeeds. Flashing to a device is documented; it is done only if a round device
+ is connected.
+- Sample 2: the unit tests pass; a run against a real mailbox sends a test email into Fo and its reply shows on the
+ device (or, without a device, in the Fo pane).
diff --git a/samples/hackathon-fo/01-fo-glance/README.md b/samples/hackathon-fo/01-fo-glance/README.md
new file mode 100644
index 000000000..4dda5b08c
--- /dev/null
+++ b/samples/hackathon-fo/01-fo-glance/README.md
@@ -0,0 +1,237 @@
+# Sample 1: the Fo glance screen
+
+**Goal.** When an agent's recap is a *glance line*, the round device draws a screen of numbers instead of the recap
+card. Say Fo is helping you job hunt and answers `GLANCE applied=5 replies=2 interviews=1 goal=10`: the device shows
+three large numbers with labels, and a ring around the edge filled to 5/10.
+
+You'll build, preview and flash the round device's firmware (`devices/harness-device/firmware`, ESP32-S3).
+The daemon needs no changes: the data reaches the device along the same path the recap already takes.
+
+The counts in the job-hunt example mean:
+
+- `applied`: applications sent so far. A company confirming it received N applications counts all N.
+- `replies`: times a company or recruiter answered an application. A receipt confirmation is not a reply.
+- `interviews`: interviews scheduled or proposed.
+- `goal`: this week's application goal (default 10).
+
+What you'll build — the device with the solution applied (rendered by the firmware's own drawing code, 466 × 466):
+
+| Working (Fo theme) | Recap: the ordinary card | Glance: the same turn as numbers |
+|---|---|---|
+| <img src="../images/device-working.png" width="220" alt="Working screen with the Fo theme"> | <img src="../images/device-recap.png" width="220" alt="Ordinary recap card"> | <img src="../images/device-glance.png" width="220" alt="Glance screen: 6 applied, 0 replies, 1 interview, ring at 6/10"> |
+| the status line in Fo amber instead of green | an answer without a glance line | `GLANCE applied=6 replies=0 interviews=1 goal=10` |
+
+`preview.sh` writes the same three screens (`working.png`, `recap.png`, `glance.png`) on your Mac.
+
+In this folder:
+
+| File | What it's for |
+|---|---|
+| `README.md` | this exercise |
+| `preview.sh` | renders Working, Recap and Glance to PNG on the Mac, no device needed |
+| `ppm2png.py` | used by `preview.sh` to turn the renderer's PPM files into PNG (Python standard library only) |
+| `solution.patch` | the full solution (theme + glance + tests). Apply it to `main` with `git apply` |
+| `fo-prompt.md` | what to tell Fo so its answer starts with the glance line |
+
+> **Install ESP-IDF early** (it takes 15-30 minutes and downloads about 2 GB). The preview step doesn't need ESP-IDF;
+> the build step does:
+>
+> ```bash
+> mkdir -p ~/esp && git clone -b v5.5 --recursive https://github.com/espressif/esp-idf.git ~/esp/esp-idf
+> ~/esp/esp-idf/install.sh esp32s3
+> . ~/esp/esp-idf/export.sh # run this again in every new terminal
+> ```
+>
+> The firmware needs ESP-IDF 5.5 or later (`devices/harness-device/firmware/README.md`).
+
+---
+
+## 0. The glance line format
+
+```
+GLANCE applied=5 replies=2 interviews=1 goal=10
+```
+
+- Case-sensitive, and at the **start** of the recap: either the whole recap or its first line.
+- After `GLANCE` come at most **4** `key=value` pairs, separated by spaces.
+ - key: `[a-z]{1,12}`. Unknown keys still show as written (`pages=12` shows the label `pages`).
+ - value: an unsigned integer, **≤ 9999**.
+- `goal` doesn't show as a number. It's 100 % of the ring: the ring fills to `applied / goal`. If the line has no
+ `applied`, the ring counts the first number. With no `goal`, there's no ring.
+- The pairs end at the end of the line, the end of the text, or the first word without an `=`. Here's why: the recap
+ the device gets is the opening of the answer, with sentences joined and line breaks turned into spaces
+ (`cli/src/lib/deviceRecap.ts`, `recap_preview()` in `ui_habitat.c`). For example,
+ `GLANCE applied=5 goal=10 Sent 5 applications today.` is still a glance.
+- A malformed line (5 or more pairs, a key with uppercase letters or `_`, a value over 9999 or not a number, two
+ `goal`s, no number to show) is **not** a glance: the device draws the normal recap card.
+
+The glance screen has the agent's name on the upper curve (as today), up to 3 large numbers (Inter 44) with labels
+below them (Inter 20), a ring around the edge (`ht_ring_arc`) and the line `5 / 10 applied` on the lower curve.
+
+## 1. Run the preview before you change anything
+
+```bash
+cd samples/hackathon-fo/01-fo-glance
+./preview.sh # about 15 s; writes /tmp/fo-glance-preview/{working,recap,glance}.png and opens them
+```
+
+On `main` you'll see `working.png` and `recap.png`. Glance is reported missing because nothing draws it yet.
+`preview.sh` runs `devices/harness-device/firmware/test/test_touch_ui.py` with `HABITAT_PREVIEW_DIR`. That test
+compiles the firmware's **real UI code** for the Mac, steps through the states and writes a PPM for each screen. The
+script keeps `design-claude-{working,recap,glance}.ppm` and converts them to PNG. You need `cc` (Xcode Command Line
+Tools) and `python3`.
+
+Environment variables: `OUT_DIR=...` changes the output folder, `NO_OPEN=1` skips opening the images,
+`FIRMWARE_DIR=...` renders from a different checkout.
+
+## 2. Warm-up: a Fo theme (about 30 minutes)
+
+Add a `DEVICE_HABITAT_FO` build flag, following the existing `DEVICE_HABITAT_ORANGE`:
+
+1. `devices/harness-device/firmware/main/CMakeLists.txt`: find `if(DEVICE_HABITAT_ORANGE)` and add an identical
+ block for `DEVICE_HABITAT_FO` (`target_compile_definitions(${COMPONENT_LIB} PRIVATE DEVICE_HABITAT_FO=1)`).
+2. `devices/harness-device/firmware/main/ui/habitat/theme.h`: under `#ifdef DEVICE_HABITAT_FO`, set Fo colors for
+ - the `HT_THEME_FOCUS_CANVAS` background (the Focus face; a regular build has only the Focus face, flag
+ `HABITAT_FOCUS_ONLY`),
+ - `HT_THEME_ACCENT` (the accent color; in the main exercise it fills the glance ring),
+ - `HT_THEME_VOICE` (the mic bar while you speak),
+ - and add `HT_THEME_WORKING` for the "Coalescing… 0:34" line while the agent works. Its default stays `0x00ff2f`.
+3. `devices/harness-device/firmware/main/ui/habitat/focus.c` does **not** read the theme for the green: it has
+ `#define FOCUS_VOICE 0x00ff2fu`. Replace it with `HT_THEME_VOICE`, add `FOCUS_WORKING` = `HT_THEME_WORKING`, and
+ use it in the three places that draw the working line (search for `FOCUS_VOICE` in `ht_focus_face`: the line under
+ the scene, the middle line, the lower arc).
+4. To preview the theme: in `test/test_touch_ui.py`, next to the `HABITAT_TEST_ORANGE` line, add
+ `if os.environ.get('HABITAT_TEST_FO'): extra_includes.append('-DDEVICE_HABITAT_FO=1')`. `./preview.sh --fo`
+ sets this variable for you. If an `assert` comparing a color with `0x00ff2f` fails, compare with
+ `HT_THEME_WORKING` instead of the constant.
+
+The colors are only suggestions: the solution uses a `0x081018` background, amber accent `0xffb000`, working
+`0xffc040` and cyan voice `0x00e0ff`. The screen is RGB565, so colors are rounded to 5/6/5 bits.
+
+Check: run `./preview.sh --fo`; `working.png` should have a night-blue background and an amber working line.
+
+## 3. Main exercise: the glance screen
+
+### Where the data flows
+
+1. Fo answers. The daemon takes the opening of the answer as the recap: `deriveTurnSummary()` in
+ `cli/src/lib/deviceRecap.ts`, called from `cli/src/core/agents/cloud.ts` (`recapOf`).
+2. `cli/src/cable/cableSession.ts`, `summary()`, sends the cable frame `{ t: 'summary', agentId, recap, text }` over
+ USB.
+3. Firmware: `main/cable_client.c` (search for `strcmp(t, "summary")`) calls `ui_project_emit(..., "summary", text,
+ recap)`.
+4. `main/ui/habitat/ui_habitat.c`: `event()` stores the whitespace-collapsed recap (`recap_preview`) in `m->preview` /
+ `a->preview`. `change()` hands it to the agent face: `const char *recap = ... a->preview`, then
+ `ht_character_face(..., recap)`.
+5. `main/ui/habitat/focus.c`, `ht_focus_face()`, draws the recap card. **This is where you make your change.**
+
+### What to do
+
+1. **Parser**: create `main/ui/habitat/glance.h`, header-only (`static inline`), so tests only need to include it
+ instead of changing the file lists of dozens of compile commands:
+ ```c
+ typedef struct { char key[13]; uint16_t value; } ht_glance_pair_t;
+ typedef struct { ht_glance_pair_t shown[4]; uint8_t count; bool has_goal; uint16_t goal; } ht_glance_t;
+ bool ht_glance_parse(const char *text, ht_glance_t *g); // true = glance; false = normal recap
+ ```
+2. **Parser tests**: `test/test_glance.c`, added to `test/run.sh` (copy the compile block of `test_character`,
+ because this test also calls `ht_focus_face`). Cases to cover: a valid line, first line only, text right after the
+ pairs, more than 4 pairs, bad keys (`Applied`, `applied_today`, 13 letters), a value over 9999, a missing or wrong
+ `GLANCE` (`glance`, not at the start), and `goal` (not shown, two `goal`s, only `goal`).
+3. **Drawing**: in `ht_focus_face()`, right after `bool has_recap = ...`:
+ ```c
+ ht_glance_t glance;
+ if (has_recap && ht_glance_parse(recap, &glance)) { resting.showing = false; glance_face(s, f, &glance); return; }
+ ```
+ then write `static void glance_face(...)` above it. The drawing functions are in `main/ui/habitat/terminal.h`:
+ `ht_arc_title_face` (the name on the upper curve), `ht_ring_arc` (the ring; center, radius and width in 1/16 px,
+ angles counterclockwise from 3 o'clock, `width16 = 0` is an empty placeholder that holds the slot), `ht_lv_label` +
+ `label_runs` (text centered in a column), `ht_arc_status_face` (the lower curve), `ht_measure`. Fonts:
+ `ht_lv_inter_44`, `ht_lv_inter_30`, `ht_lv_inter_20` (`focus_faces.h`).
+4. **The most important rule** (the comment at the top of `focus.c`): `ht_damage()` compares run i of the old frame
+ with run i of the new frame. If the number or order of runs changes, it redraws the whole 466x466 screen. The home
+ face always emits **exactly 11 runs, in the same order**. The glance screen also keeps 11 runs in its slots: name ·
+ background ring (the pet's slot) · filled ring (the card's slot) · 3 numbers + 1 empty run (the 4 recap lines) ·
+ 3 labels (status + 2 resting lines) · lower curve. Where there's nothing to draw, emit an empty run (`no_text`,
+ `ht_ring_arc` with `width16 = 0`). **Don't drop runs.**
+5. The lower curve makes room for the notification bell and the footer button, like the relaxing face's line: leave it
+ out when `f->notices` or `f->footer_action` is set.
+6. The glance screen has no pet, so it doesn't need to redraw on a timer: in `ht_focus_pet_next_ms()`, return `0` when
+ the recap is a glance.
+7. **Preview**: in `test/test_touch_ui.py`, in the `THE DESIGN EXPORT` section, right after `DESIGN("recap")`, add:
+ ```c
+ DESIGN_HOME();
+ ui_project_emit("a", "sess", "summary", "GLANCE applied=5 replies=2 interviews=1 goal=10 Sent five applications today.",
+ "GLANCE applied=5 replies=2 interviews=1 goal=10 Sent five applications today.");
+ fake_ms = 1200; scene_take(); DESIGN("glance");
+ ```
+ After that, `./preview.sh` produces `glance.png`.
+
+Layout hints from the solution: ring radius 227, width 8, filled clockwise from 12 o'clock (`mid = 90 - half`,
+`half = 180 * applied / goal`); numbers at y 187, labels at y 248; 1, 2 or 3 columns 200, 150 or 120 px wide; a number
+wider than its column drops to Inter 30.
+
+## 4. The development loop
+
+```bash
+cd devices/harness-device/firmware
+
+# 1. Quick look on the Mac (about 15 s), after every UI change
+../../../samples/hackathon-fo/01-fo-glance/preview.sh --fo
+
+# 2. Host tests (about 3 minutes) before you flash
+bash test/run.sh
+
+# 3. Build for the device (a few minutes the first time, fast after that)
+. ~/esp/esp-idf/export.sh
+idf.py -B build-fo set-target esp32s3 # first time only
+idf.py -B build-fo -DPROJECT_VER=0.0.99 -DDEVICE_HABITAT_FO=1 build
+```
+
+**Why `0.0.99`:** the daemon pushes the official firmware over USB (OTA) to any device running a version older than
+the published one. A dev build with a low version gets overwritten after about 15 seconds and your changes
+"disappear". `0.0.99` is higher than the published version, so it stays.
+
+### Flash (in this order)
+
+Only one process can hold the serial port, and the daemon is holding it:
+
+```bash
+ls /dev/cu.usbmodem* # find the round device's port
+osascript -e 'quit app "Harness"' # 1. quit the Harness app
+harness stop # 2. stop the daemon (frees the USB port)
+idf.py -B build-fo -p /dev/cu.usbmodemXXXX flash # 3. flash
+harness start # 4. start the daemon again
+open -a Harness # 5. reopen the app
+```
+
+Don't flash after a failed build. Check: after a while, the device still runs `0.0.99` (Devices in the app, or the
+device log). Then send Fo a turn following `fo-prompt.md`: when the turn ends, the device beeps and shows the glance
+screen.
+
+### Go back to the official firmware
+
+```bash
+harness flash # flashes the published firmware again (USB plugged in, app and daemon running as usual)
+```
+
+## 5. Stuck?
+
+Apply the solution to a clean checkout of `main` (from the repo root):
+
+```bash
+git apply --check samples/hackathon-fo/01-fo-glance/solution.patch && git apply samples/hackathon-fo/01-fo-glance/solution.patch
+```
+
+The patch covers `theme.h`, `main/CMakeLists.txt`, `focus.c` (`glance_face`), the new `glance.h`, the new
+`test/test_glance.c`, `test/run.sh` and `test/test_touch_ui.py` (the glance preview, `HABITAT_TEST_FO`). To remove the
+solution: `git apply -R samples/hackathon-fo/01-fo-glance/solution.patch`.
+
+Common errors:
+
+- `preview.sh` reports `no .../design-claude-glance.ppm`: you haven't added `DESIGN("glance")` yet (step 3.7).
+- A test reports `Assertion failed ... count == 11`: the glance screen emits too few or too many runs (step 3.4).
+- The device still shows the recap card: the glance line isn't at the **start** of Fo's answer (see `fo-prompt.md`),
+ or the line is malformed. Try it with the parser in `test/test_glance.c`.
+- The device goes back to the old version after you flash: you forgot `-DPROJECT_VER=0.0.99`.
+- `idf.py flash` says the port is busy: the daemon or the app is still running (`harness stop`, quit the app).
diff --git a/samples/hackathon-fo/01-fo-glance/fo-prompt.md b/samples/hackathon-fo/01-fo-glance/fo-prompt.md
new file mode 100644
index 000000000..0af62e62c
--- /dev/null
+++ b/samples/hackathon-fo/01-fo-glance/fo-prompt.md
@@ -0,0 +1,63 @@
+# What to tell Fo so the glance screen shows up
+
+The round device only reads the turn's **recap**, which the daemon cuts from the **opening** of Fo's answer
+(`deriveTurnSummary` in `cli/src/lib/deviceRecap.ts`, called from `cli/src/core/agents/cloud.ts`). So the glance line
+must be the **first line** of the answer. If it's at the end, it gets cut off and the device shows the normal recap.
+
+Tested with `deriveTurnSummary` itself:
+
+| Fo's answer starts with | Recap the device gets | Device draws |
+|---|---|---|
+| `GLANCE applied=5 replies=2 interviews=1 goal=10`, a blank line, then the text | `GLANCE applied=5 replies=2 interviews=1 goal=10 Today I sent…` | the glance screen |
+| `**GLANCE applied=5 replies=2 goal=10**` (bold) | `GLANCE applied=5 replies=2 goal=10 Sent 5 applications.` (the `**` is dropped) | the glance screen |
+| text first, `GLANCE …` at the end | `Sent 5 applications today.` | the normal recap |
+
+The firmware reads `key=value` pairs up to the first word without an `=`, so text joined on after them is fine.
+
+## Instructions (paste at the start of your conversation with Fo)
+
+```text
+From now on, every answer you give MUST start with exactly one glance line, then a blank line, then the content.
+
+The glance line looks like this:
+GLANCE applied=<number> replies=<number> interviews=<number> goal=<number>
+
+Rules:
+- Write the word GLANCE in capitals exactly, with no punctuation, no bold, and not in a code block.
+- At most 4 key=value pairs, separated by one space. Keys use only lowercase letters a-z (at most 12), values are whole numbers 0..9999.
+- applied = applications sent so far (if a company confirms it received N applications, count all N);
+ replies = times a company or recruiter answered an application (a receipt confirmation is not a reply);
+ interviews = interviews scheduled or proposed; goal = this week's application goal (default 10).
+- Update the numbers every turn with what you know, even when nothing changed in that turn.
+
+Your job: help me find a Senior Backend Engineer (Go) role in Ho Chi Minh City or remote. Today, find 5 matching job postings,
+sum up each one in one line, and record that I applied to all 5.
+```
+
+Expected answer:
+
+```text
+GLANCE applied=5 replies=0 interviews=0 goal=10
+
+I found 5 matching postings and recorded that you applied:
+1. ...
+```
+
+On the device: the harness name on the upper curve, three numbers `5 / 0 / 0` labeled `applied / replies / interviews`,
+an amber ring filled to 5/10 around the edge, and the line `5 / 10 applied` on the lower curve.
+
+## Later turns
+
+- "Company A just answered my email and set up an interview for Friday." → Fo's answer starts with
+ `GLANCE applied=5 replies=1 interviews=1 goal=10`.
+- "I applied to 3 more." → `GLANCE applied=8 replies=1 interviews=1 goal=10`.
+
+Other keys work too, and the device shows them as written, for example `GLANCE pages=12 bugs=3 goal=40` for a
+different task. With no `applied`, the ring counts the first number. With no `goal`, there's no ring.
+
+## When the glance screen doesn't show up
+
+- Fo adds text before the glance line ("Hi there! GLANCE …"): remind it that "the FIRST line must be GLANCE".
+- A number is over 9999, a key has uppercase letters, underscores or accents (`Applied`, `applied_today`), or there are
+ more than 4 pairs: the device shows the normal recap. That's the intended behavior: a malformed line never turns into
+ wrong numbers.
diff --git a/samples/hackathon-fo/01-fo-glance/ppm2png.py b/samples/hackathon-fo/01-fo-glance/ppm2png.py
new file mode 100755
index 000000000..fccbfd129
--- /dev/null
+++ b/samples/hackathon-fo/01-fo-glance/ppm2png.py
@@ -0,0 +1,43 @@
+#!/usr/bin/env python3
+"""Convert binary PPM (P6) files to PNG with the Python standard library only.
+
+Usage: python3 ppm2png.py in.ppm out.png
+"""
+import struct
+import sys
+import zlib
+
+
+def read_ppm(path):
+ data = open(path, 'rb').read()
+ fields, pos = [], 0
+ while len(fields) < 4:
+ while data[pos:pos + 1].isspace():
+ pos += 1
+ if data[pos:pos + 1] == b'#':
+ pos = data.index(b'\n', pos) + 1
+ continue
+ end = pos
+ while not data[end:end + 1].isspace():
+ end += 1
+ fields.append(data[pos:end])
+ pos = end
+ if fields[0] != b'P6' or int(fields[3]) != 255:
+ raise SystemExit(f'{path}: not an 8-bit P6 PPM')
+ w, h = int(fields[1]), int(fields[2])
+ return w, h, data[pos + 1:pos + 1 + w * h * 3]
+
+
+def write_png(path, w, h, rgb):
+ def chunk(kind, body):
+ return struct.pack('>I', len(body)) + kind + body + struct.pack('>I', zlib.crc32(kind + body) & 0xffffffff)
+ rows = b''.join(b'\x00' + rgb[y * w * 3:(y + 1) * w * 3] for y in range(h))
+ png = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 2, 0, 0, 0))
+ png += chunk(b'IDAT', zlib.compress(rows, 9)) + chunk(b'IEND', b'')
+ open(path, 'wb').write(png)
+
+
+if __name__ == '__main__':
+ if len(sys.argv) != 3:
+ raise SystemExit(__doc__)
+ write_png(sys.argv[2], *read_ppm(sys.argv[1]))
diff --git a/samples/hackathon-fo/01-fo-glance/preview.sh b/samples/hackathon-fo/01-fo-glance/preview.sh
new file mode 100755
index 000000000..7456d304c
--- /dev/null
+++ b/samples/hackathon-fo/01-fo-glance/preview.sh
@@ -0,0 +1,50 @@
+#!/usr/bin/env bash
+# Render the round device's Working, Recap and Glance screens to PNG on this Mac — no device, no ESP-IDF.
+#
+# ./preview.sh the default colours
+# ./preview.sh --fo the Fo colours (-DDEVICE_HABITAT_FO=1, the warm-up)
+#
+# It runs the firmware's own host renderer (devices/harness-device/firmware/test/test_touch_ui.py) with
+# HABITAT_PREVIEW_DIR set: the test compiles the real UI code (focus.c, ui_habitat.c, ...) for the host,
+# drives it through its states and writes one PPM per screen. This script keeps three of them and turns
+# them into PNG with ppm2png.py (Python standard library only). Needs: cc (Xcode command line tools), python3.
+#
+# Output: $OUT_DIR (default /tmp/fo-glance-preview)/{working,recap,glance}.png
+set -euo pipefail
+
+here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+repo="$(git -C "$here" rev-parse --show-toplevel)"
+firmware="${FIRMWARE_DIR:-$repo/devices/harness-device/firmware}" # FIRMWARE_DIR: another checkout
+out="${OUT_DIR:-/tmp/fo-glance-preview}"
+raw="$out/raw"
+
+theme=()
+case "${1:-}" in
+ --fo) theme=(HABITAT_TEST_FO=1) ;;
+ "") ;;
+ *) echo "usage: $0 [--fo]" >&2; exit 2 ;;
+esac
+
+rm -rf "$raw"
+mkdir -p "$raw"
+echo "Rendering with the host renderer (about 15 s)..."
+(cd "$firmware" && env ${theme[@]+"${theme[@]}"} HABITAT_PREVIEW_DIR="$raw" python3 test/test_touch_ui.py >"$out/test.log" 2>&1) || {
+ echo "test_touch_ui.py failed — the last lines of $out/test.log:" >&2
+ tail -20 "$out/test.log" >&2
+ exit 1
+}
+
+# The design export draws every state for Claude (and Codex); Claude's are the ones kept here.
+status=0
+for screen in working recap glance; do
+ ppm="$raw/design-claude-$screen.ppm"
+ if [[ -f "$ppm" ]]; then
+ python3 "$here/ppm2png.py" "$ppm" "$out/$screen.png"
+ echo " $out/$screen.png"
+ else
+ echo " $screen: no $ppm — add the glance case to test_touch_ui.py (README, step 3), or apply solution.patch" >&2
+ status=1
+ fi
+done
+[[ "$(uname)" == Darwin && $status == 0 && -z "${NO_OPEN:-}" ]] && open "$out/working.png" "$out/recap.png" "$out/glance.png"
+exit $status
diff --git a/samples/hackathon-fo/01-fo-glance/solution.patch b/samples/hackathon-fo/01-fo-glance/solution.patch
new file mode 100644
index 000000000..07a77a876
--- /dev/null
+++ b/samples/hackathon-fo/01-fo-glance/solution.patch
@@ -0,0 +1,447 @@
+diff --git a/devices/harness-device/firmware/main/CMakeLists.txt b/devices/harness-device/firmware/main/CMakeLists.txt
+index 044187a11..1825dabf5 100644
+--- a/devices/harness-device/firmware/main/CMakeLists.txt
++++ b/devices/harness-device/firmware/main/CMakeLists.txt
+@@ -123,6 +123,11 @@ if(DEVICE_HABITAT_ORANGE)
+ target_compile_definitions(${COMPONENT_LIB} PRIVATE DEVICE_HABITAT_ORANGE=1)
+ endif()
+
++# The Fo colours (theme.h): -DDEVICE_HABITAT_FO=1.
++if(DEVICE_HABITAT_FO)
++ target_compile_definitions(${COMPONENT_LIB} PRIVATE DEVICE_HABITAT_FO=1)
++endif()
++
+ # Focus and nothing else until the companion skins are finished (owner, 2026-09-30); the host tests
+ # build without it and keep covering every skin. -DDEVICE_ALL_SKINS=1 lifts it for a build.
+ if(NOT DEVICE_ALL_SKINS)
+diff --git a/devices/harness-device/firmware/main/ui/habitat/focus.c b/devices/harness-device/firmware/main/ui/habitat/focus.c
+index 9cd5f93b8..9da15e8df 100644
+--- a/devices/harness-device/firmware/main/ui/habitat/focus.c
++++ b/devices/harness-device/firmware/main/ui/habitat/focus.c
+@@ -2,6 +2,7 @@
+ #include "pets.h"
+ #include "focus_faces.h"
+ #include "theme.h"
++#include "glance.h"
+ #include "../../pet_store.h"
+ #include "../../elapsed.h"
+ #include <math.h>
+@@ -60,7 +61,8 @@ enum { MARK_SIZE = 56, TITLE_BOTTOM = HT_ARC_Y + HT_ARC_CELL_HEIGHT, COL_X = 41,
+ #define FOCUS_CARD_RIM 0x3d3f47u
+ #define FOCUS_FG 0xeaeaf0u
+ #define FOCUS_EMPTY 0x585863u
+-#define FOCUS_VOICE 0x00ff2fu
++#define FOCUS_VOICE HT_THEME_VOICE // the listening meter and its word
++#define FOCUS_WORKING HT_THEME_WORKING // the working line
+ #define FOCUS_REST 0x9a9aa6u // the relaxing face's lower-arc line: the working line's arc and font, quiet grey
+
+ /*
+@@ -534,6 +536,9 @@ uint32_t ht_focus_pet_next_ms(const ht_character_face_t *f, const char *recap)
+ const ht_pet_scene_t *ss = sending_scene(f);
+ return ss ? scene_next_ms(ss, 0, f->clock_ms) : 0;
+ }
++ // The glance face has no pet: nothing on it moves, so it asks for no redraws.
++ ht_glance_t glance;
++ if (recap && ht_glance_parse(recap, &glance)) return 0;
+ uint32_t alert_step;
+ bool held;
+ const ht_pet_scene_t *alert = alert_scene(f, recap, &alert_step, &held);
+@@ -837,12 +842,76 @@ static void recap_cut(char *out, size_t cap, const char *recap, const ht_font_t
+ if (clipped) strcat(out, "\xe2\x80\xa6");
+ }
+
++/*
++ * THE GLANCE FACE — a recap that is a glance line (glance.h: "GLANCE applied=5 replies=2 interviews=1 goal=10")
++ * is drawn as numbers instead of the recap card: the name on the top arc as always, up to three numbers in
++ * Inter 44 with their keys under them in Inter 20, a ring around the edge filled progress / goal in the accent
++ * (ht_glance_progress: `applied`, else the first number), and "5 / 10 applied" on the lower arc.
++ *
++ * THE SAME ELEVEN RUNS as the home face, in their slots (see the rule at the top of this file): name, the ring's
++ * track (the mark's slot), its fill (the card's), the three numbers and an empty one (recap x4), the three keys
++ * (status, resting line x2), the lower arc. A missing number, key or fill is an empty run in its slot, so a new
++ * glance line with other numbers is a change of text, not a reshape.
++ */
++enum { GLANCE_RING_R = 227, GLANCE_RING_W = 8, GLANCE_NUM_Y = 187, GLANCE_KEY_Y = 248 };
++#define GLANCE_TRACK 0x26262cu // the ring's unfilled band: a step above the black
++static void glance_face(ht_scene_t *s, const ht_character_face_t *f, const ht_glance_t *g)
++{
++ const ht_font_t *big = &ht_lv_inter_44.base, *mid = &ht_lv_inter_30.base, *small = &ht_lv_inter_20.base;
++ ht_arc_title_face(s, ht_rgb(FOCUS_FG), f->recipient && *f->recipient ? f->recipient : "\xe2\x80\xa6",
++ &ht_arc_inter_prop);
++
++ // The ring: the whole circle in the track's grey, then the fill clockwise from twelve o'clock.
++ int c16 = HT_WIDTH / 2 * 16, r16 = GLANCE_RING_R * 16, w16 = GLANCE_RING_W * 16;
++ unsigned done = ht_glance_progress(g);
++ ht_ring_arc(s, c16, c16, r16, g->has_goal ? w16 : 0, 90, 180, ht_rgb(GLANCE_TRACK));
++ int half = g->has_goal && g->goal ? (int)((done >= g->goal ? 180u : 180u * done / g->goal)) : 0;
++ ht_ring_arc(s, c16, c16, r16, half ? w16 : 0, 90 - half, half, ht_rgb(HT_THEME_ACCENT));
++
++ // The numbers, side by side in equal columns; a number too wide for Inter 44 in its column steps down to 30.
++ unsigned n = g->count < HT_GLANCE_SHOWN ? g->count : HT_GLANCE_SHOWN;
++ int col_w = n == 1 ? 200 : n == 2 ? 150 : 120, left = (HT_WIDTH - (int)n * col_w) / 2;
++ for (unsigned i = 0; i < RECAP_LINES; i++) {
++ if (i >= n) { no_text(s, big); continue; }
++ char num[8];
++ snprintf(num, sizeof num, "%u", (unsigned)g->shown[i].value);
++ const ht_font_t *nf = ht_measure(big, num) <= col_w ? big : mid;
++ ht_lv_label_t l;
++ ht_lv_label(&l, nf, num, col_w, 1, true);
++ label_runs(s, &l, 1, left + (int)i * col_w, GLANCE_NUM_Y + (nf == big ? 0 : (big->height - mid->height) / 2), 0,
++ nf, ht_rgb(FOCUS_FG), s->background);
++ }
++ // Their keys, as written, in the resting grey; a long one ends in "...".
++ for (unsigned i = 0; i < 3; i++) {
++ if (i >= n) { no_text(s, small); continue; }
++ ht_lv_label_t l;
++ ht_lv_label(&l, small, g->shown[i].key, col_w - 8, 1, true);
++ label_runs(s, &l, 1, left + (int)i * col_w + 4, GLANCE_KEY_Y, 0, small, ht_rgb(FOCUS_REST), s->background);
++ }
++
++ // "5 / 10 applied" on the lower curve — left out (an empty slot) without a goal, or when the bell pill or a footer
++ // control has the lower edge, as the relaxing line is.
++ int before = s->count;
++ if (g->has_goal && !f->notices && !f->footer_action) {
++ const char *what = g->shown[0].key; // the key the ring counts (ht_glance_progress)
++ for (unsigned i = 0; i < g->count; i++)
++ if (!strcmp(g->shown[i].key, "applied")) what = "applied";
++ char line[48];
++ snprintf(line, sizeof line, "%u / %u %s", done, (unsigned)g->goal, what);
++ ht_arc_status_face(s, ht_rgb(FOCUS_REST), line, &ht_arc_inter_lower);
++ }
++ if (s->count == before) no_text(s, small);
++}
++
+ void ht_focus_face(ht_scene_t *s, const ht_character_face_t *f, uint8_t frame, uint16_t ink,
+ const char *recap)
+ {
+ (void)ink;
+ if (f->voice) { resting.showing = false; voice_face(s, f, frame); return; }
+ bool has_recap = recap && *recap;
++ // A glance line takes the recap card's place (glance_face above); anything else is drawn as before.
++ ht_glance_t glance;
++ if (has_recap && ht_glance_parse(recap, &glance)) { resting.showing = false; glance_face(s, f, &glance); return; }
+ bool working = !has_recap && f->activity && *f->activity;
+ bool retry = !has_recap && !working && f->status && *f->status;
+
+@@ -1013,10 +1082,10 @@ void ht_focus_face(ht_scene_t *s, const ht_character_face_t *f, uint8_t frame, u
+ status_fitted(line, sizeof line, f, lf, NULL, COL_W);
+ ht_lv_label_t l;
+ ht_lv_label(&l, lf, line, COL_W, 1, false);
+- label_runs(s, &l, 1, COL_X, SCENE_LINE_Y, 0, lf, ht_rgb(FOCUS_VOICE), s->background);
++ label_runs(s, &l, 1, COL_X, SCENE_LINE_Y, 0, lf, ht_rgb(FOCUS_WORKING), s->background);
+ } else if (status[0] && !scene)
+ label_runs(s, &body, 1, COL_X, body_y, 0, sf,
+- ht_rgb(retry ? FOCUS_FG : FOCUS_VOICE), s->background);
++ ht_rgb(retry ? FOCUS_FG : working ? FOCUS_WORKING : FOCUS_VOICE), s->background);
+ else no_text(s, sf);
+
+ // Nothing yet: said in the resting grey. With nothing standing above it (no pet, no mark: design 2026-10-06
+@@ -1035,7 +1104,7 @@ void ht_focus_face(ht_scene_t *s, const ht_character_face_t *f, uint8_t frame, u
+ if (scene && !taken) {
+ char arc[HT_TEXT_BYTES];
+ status_fitted(arc, sizeof arc, f, NULL, &ht_arc_inter_lower, HT_ARC_SPAN);
+- ht_arc_status_face(s, ht_rgb(FOCUS_VOICE), arc, &ht_arc_inter_lower);
++ ht_arc_status_face(s, ht_rgb(FOCUS_WORKING), arc, &ht_arc_inter_lower);
+ } else if (relax && !f->notices && !f->footer_action)
+ // The relaxing face's one line, in the working line's arc and font, quiet grey. Left out (an empty slot) when
+ // the bell pill (y 400, notices > 0; this face has no bubble to tell them) or a footer control (y 389..439)
+diff --git a/devices/harness-device/firmware/main/ui/habitat/glance.h b/devices/harness-device/firmware/main/ui/habitat/glance.h
+new file mode 100644
+index 000000000..a5187142c
+--- /dev/null
++++ b/devices/harness-device/firmware/main/ui/habitat/glance.h
+@@ -0,0 +1,93 @@
++#pragma once
++
++#include <stdbool.h>
++#include <stdint.h>
++#include <string.h>
++
++/*
++ * THE GLANCE LINE — an agent's recap that is a few numbers instead of a sentence.
++ *
++ * GLANCE applied=5 replies=2 interviews=1 goal=10
++ *
++ * Case-sensitive, at the very start of the recap. After "GLANCE" come up to four `key=value` pairs
++ * separated by spaces: a key is 1..12 letters a-z, a value an unsigned integer 0..9999. The pairs end at
++ * the end of the line ('\n'), the end of the text, or the first word with no '=' in it — the daemon's
++ * recap (cli/src/lib/deviceRecap.ts) runs the reply's opening sentences together, and recap_preview()
++ * in ui_habitat.c turns line breaks into spaces, so the prose after the line is still on it.
++ *
++ * `goal` is not shown as a number: it is the ring's 100 %. Every other key is shown as-is, the first
++ * three of them. Anything malformed (a fifth pair, a bad key, a value past 9999, no pair to show)
++ * is not a glance, and the face draws the ordinary recap card.
++ *
++ * Header-only and free of the renderer, so the host test (test/test_glance.c) can include it alone.
++ */
++enum { HT_GLANCE_PAIRS = 4, HT_GLANCE_SHOWN = 3, HT_GLANCE_KEY = 12, HT_GLANCE_MAX = 9999 };
++
++typedef struct {
++ char key[HT_GLANCE_KEY + 1];
++ uint16_t value;
++} ht_glance_pair_t;
++
++typedef struct {
++ ht_glance_pair_t shown[HT_GLANCE_PAIRS]; // in order, without `goal`
++ uint8_t count; // pairs in `shown` (1..4; the face draws the first three)
++ bool has_goal;
++ uint16_t goal;
++} ht_glance_t;
++
++// One `key=value` word at `p`, `len` bytes. False when it is not one.
++static inline bool ht_glance_pair(const char *p, size_t len, ht_glance_pair_t *out)
++{
++ const char *eq = (const char *)memchr(p, '=', len);
++ if (!eq) return false;
++ size_t klen = (size_t)(eq - p), vlen = len - klen - 1;
++ if (klen < 1 || klen > HT_GLANCE_KEY || vlen < 1 || vlen > 4) return false;
++ for (size_t i = 0; i < klen; i++)
++ if (p[i] < 'a' || p[i] > 'z') return false;
++ unsigned v = 0;
++ for (size_t i = 0; i < vlen; i++) {
++ if (eq[1 + i] < '0' || eq[1 + i] > '9') return false;
++ v = v * 10 + (unsigned)(eq[1 + i] - '0');
++ }
++ if (v > HT_GLANCE_MAX) return false;
++ memcpy(out->key, p, klen);
++ out->key[klen] = 0;
++ out->value = (uint16_t)v;
++ return true;
++}
++
++// True, with `g` filled, when `text` is a glance line; false (and `g` cleared) otherwise.
++static inline bool ht_glance_parse(const char *text, ht_glance_t *g)
++{
++ memset(g, 0, sizeof *g);
++ if (!text || strncmp(text, "GLANCE", 6) || (text[6] != ' ' && text[6] != '\t')) return false;
++ const char *p = text + 6;
++ unsigned pairs = 0;
++ for (;;) {
++ while (*p == ' ' || *p == '\t' || *p == '\r') p++;
++ if (!*p || *p == '\n') break;
++ size_t len = 0;
++ while (p[len] && p[len] != ' ' && p[len] != '\t' && p[len] != '\r' && p[len] != '\n') len++;
++ if (!memchr(p, '=', len)) break; // prose after the line: the pairs are over
++ ht_glance_pair_t pair;
++ if (++pairs > HT_GLANCE_PAIRS || !ht_glance_pair(p, len, &pair)) goto bad;
++ if (!strcmp(pair.key, "goal")) {
++ if (g->has_goal) goto bad;
++ g->has_goal = true;
++ g->goal = pair.value;
++ } else g->shown[g->count++] = pair;
++ p += len;
++ }
++ if (g->count) return true;
++bad:
++ memset(g, 0, sizeof *g);
++ return false;
++}
++
++// What the ring counts toward the goal: `applied` when the line has it, else its first number.
++static inline uint16_t ht_glance_progress(const ht_glance_t *g)
++{
++ for (unsigned i = 0; i < g->count; i++)
++ if (!strcmp(g->shown[i].key, "applied")) return g->shown[i].value;
++ return g->count ? g->shown[0].value : 0;
++}
+diff --git a/devices/harness-device/firmware/main/ui/habitat/theme.h b/devices/harness-device/firmware/main/ui/habitat/theme.h
+index 33df179cb..8e139f087 100644
+--- a/devices/harness-device/firmware/main/ui/habitat/theme.h
++++ b/devices/harness-device/firmware/main/ui/habitat/theme.h
+@@ -7,11 +7,17 @@
+ #define HT_THEME_CANVAS 0x181818u
+ // The Focus skin's canvas. Its design (mockup/newdesign.html, every screen) is on black, not on the
+ // terminal's charcoal — Focus is the pre-habitat layout and brings its ground with it.
++#ifdef DEVICE_HABITAT_FO
++#define HT_THEME_FOCUS_CANVAS 0x081018u // Fo: a deep night blue instead of black
++#else
+ #define HT_THEME_FOCUS_CANVAS 0x000000u
++#endif
+ #define HT_THEME_TEXT 0xefe7deu
+ #define HT_THEME_SECONDARY 0xada6adu
+ #ifdef DEVICE_HABITAT_ORANGE
+ #define HT_THEME_ACCENT 0xff6d00u
++#elif defined(DEVICE_HABITAT_FO)
++#define HT_THEME_ACCENT 0xffb000u // Fo amber (the glance ring's fill)
+ #else
+ #define HT_THEME_ACCENT 0xc6aaefu
+ #endif
+@@ -27,7 +33,18 @@
+ // It is a pure channel — brighter and harder than HT_THEME_DONE, which is the terminal's "finished"
+ // green and is what a status line uses. The old firmware kept the two apart for the same reason: the
+ // meter is the one thing on the glass that is supposed to shout, and a status line is not.
++#ifdef DEVICE_HABITAT_FO
++#define HT_THEME_VOICE 0x00e0ffu // Fo: a cyan meter and microphone
++#else
+ #define HT_THEME_VOICE 0x00ff2fu
++#endif
++// The Focus face's working line ("Coalescing… 0:34", on the lower arc or under the scene). The same green as the
++// voice by default; a theme can tell the two apart.
++#ifdef DEVICE_HABITAT_FO
++#define HT_THEME_WORKING 0xffc040u // Fo: warm amber while it works
++#else
++#define HT_THEME_WORKING 0x00ff2fu
++#endif
+ #define HT_THEME_DONE 0x0dbc79u
+ #define HT_THEME_QUESTION 0xe5e510u
+ #define HT_THEME_FAILED 0xcd3131u
+diff --git a/devices/harness-device/firmware/test/run.sh b/devices/harness-device/firmware/test/run.sh
+index 28003c37e..5da526063 100644
+--- a/devices/harness-device/firmware/test/run.sh
++++ b/devices/harness-device/firmware/test/run.sh
+@@ -39,6 +39,16 @@ cc -std=c11 -Wall -Wextra -Werror -O1 -g -fsanitize="${PET_SANITIZERS:-address,u
+ "$here/../main/ui/habitat/terminal.c" "$here/../main/ui/habitat/fonts.c" -lm
+ "$out/test_character_asan" "$here/vectors/pet_min.hpet" --custom-only
+ python3 "$here/test_character_preferences.py"
++# The glance line (glance.h) and the Focus face that draws it.
++cc -std=c11 -Wall -Wextra -Werror -O1 -g -fsanitize="${SANITIZERS:-undefined,bounds}" \
++ -I "$here/../main" -o "$out/test_glance" "$here/test_glance.c" "$here/../main/pet_store.c" "$here/../main/elapsed.c" \
++ "$here/../main/ui/habitat/character.c" "$here/../main/ui/habitat/illustrated.c" "$here/../main/ui/habitat/character_motion.c" \
++ "$here/../main/ui/habitat/character_layout.c" "$here/../main/ui/habitat/tux.c" \
++ "$here/../main/ui/habitat/focus.c" "$here/../main/ui/habitat/lvgl_fonts.c" "$here/../main/ui/habitat/lvgl_icons.c" "$here/../main/ui/habitat/focus_marks.c" "$here/../main/ui/habitat/focus_faces.c" "$here/../main/ui/habitat/pets.c" \
++ "$here/../main/ui/habitat/octopus.c" "$here/../main/ui/habitat/octopus_font.c" \
++ "$here/../main/ui/habitat/ascii_clip.c" \
++ "$here/../main/ui/habitat/terminal.c" "$here/../main/ui/habitat/fonts.c" -lm
++"$out/test_glance"
+
+ cc -std=c11 -Wall -Wextra -Werror -O1 -g -fsanitize="${SANITIZERS:-undefined,bounds}" \
+ -I "$here/../main" -o "$out/test_elapsed" "$here/test_elapsed.c" "$here/../main/elapsed.c"
+diff --git a/devices/harness-device/firmware/test/test_glance.c b/devices/harness-device/firmware/test/test_glance.c
+new file mode 100644
+index 000000000..83882d375
+--- /dev/null
++++ b/devices/harness-device/firmware/test/test_glance.c
+@@ -0,0 +1,100 @@
++// The glance line (main/ui/habitat/glance.h) and the Focus face that draws it (focus.c, glance_face).
++#include "ui/habitat/glance.h"
++#include "ui/habitat/focus.h"
++#include "ui/habitat/theme.h"
++#include <assert.h>
++#include <stdio.h>
++#include <string.h>
++
++static void parser(void)
++{
++ ht_glance_t g;
++ // The line from the spec: three numbers shown, the goal kept apart.
++ assert(ht_glance_parse("GLANCE applied=5 replies=2 interviews=1 goal=10", &g));
++ assert(g.count == 3 && g.has_goal && g.goal == 10);
++ assert(!strcmp(g.shown[0].key, "applied") && g.shown[0].value == 5);
++ assert(!strcmp(g.shown[1].key, "replies") && g.shown[1].value == 2);
++ assert(!strcmp(g.shown[2].key, "interviews") && g.shown[2].value == 1);
++ assert(ht_glance_progress(&g) == 5);
++ // Its first line only; and the daemon's recap, which runs the prose after it onto the same line.
++ assert(ht_glance_parse("GLANCE applied=5 goal=10\nToday I sent five applications.", &g) && g.count == 1);
++ assert(ht_glance_parse("GLANCE applied=5 replies=2 goal=10 Today I sent five. Two replied.", &g) && g.count == 2);
++ // Unknown keys are shown as-is; without `applied` the ring counts the first number.
++ assert(ht_glance_parse("GLANCE pages=40 bugs=3 goal=80", &g) && ht_glance_progress(&g) == 40);
++ assert(!strcmp(g.shown[1].key, "bugs") && g.shown[1].value == 3);
++ // No goal: no ring, the numbers still stand. The edges of a value and a key.
++ assert(ht_glance_parse("GLANCE applied=0", &g) && !g.has_goal && g.count == 1 && g.shown[0].value == 0);
++ assert(ht_glance_parse("GLANCE abcdefghijkl=9999", &g) && g.shown[0].value == 9999);
++ // A fourth number is kept (the face shows three).
++ assert(ht_glance_parse("GLANCE a=1 b=2 c=3 d=4", &g) && g.count == 4 && !g.has_goal);
++ // Malformed: the ordinary recap card.
++ assert(!ht_glance_parse("GLANCE a=1 b=2 c=3 d=4 goal=5", &g) && !g.count); // > 4 pairs
++ assert(!ht_glance_parse("GLANCE Applied=5", &g)); // capital in the key
++ assert(!ht_glance_parse("GLANCE applied_today=5", &g)); // not [a-z]
++ assert(!ht_glance_parse("GLANCE abcdefghijklm=1", &g)); // 13 letters
++ assert(!ht_glance_parse("GLANCE =5", &g)); // empty key
++ assert(!ht_glance_parse("GLANCE applied=10000", &g)); // > 9999
++ assert(!ht_glance_parse("GLANCE applied=99999999999", &g)); // far past it
++ assert(!ht_glance_parse("GLANCE applied=-1", &g)); // not unsigned
++ assert(!ht_glance_parse("GLANCE applied=5x", &g));
++ assert(!ht_glance_parse("GLANCE applied=", &g));
++ assert(!ht_glance_parse("GLANCE goal=10 goal=12 applied=1", &g)); // two goals
++ assert(!ht_glance_parse("GLANCE goal=10", &g)); // nothing to show
++ assert(!ht_glance_parse("GLANCE", &g) && !ht_glance_parse("GLANCE ", &g));
++ assert(!ht_glance_parse("glance applied=5", &g)); // case-sensitive
++ assert(!ht_glance_parse("GLANCEapplied=5", &g));
++ assert(!ht_glance_parse("Shipped it. GLANCE applied=5", &g)); // not at the start
++ assert(!ht_glance_parse("Applied to five jobs today.", &g));
++ assert(!ht_glance_parse("", &g) && !ht_glance_parse(NULL, &g));
++}
++
++static ht_character_face_t face(void)
++{
++ ht_character_face_t f;
++ memset(&f, 0, sizeof f);
++ f.recipient = "Fo job hunt";
++ f.engine = "fo";
++ f.clock_ms = 1200;
++ return f;
++}
++
++static void face_runs(void)
++{
++ static ht_scene_t s;
++ ht_character_face_t f = face();
++ // The glance face: the home face's eleven runs, the ring in the mark's and card's slots.
++ ht_scene_clear(&s, ht_rgb(HT_THEME_FOCUS_CANVAS));
++ ht_focus_face(&s, &f, 0, 0, "GLANCE applied=5 replies=2 interviews=1 goal=10");
++ assert(s.count == 11);
++ assert(s.runs[1].ring.set && s.runs[1].ring.w16 && s.runs[2].ring.set && s.runs[2].ring.w16);
++ assert(s.runs[2].ring.colour == ht_rgb(HT_THEME_ACCENT));
++ assert(!strcmp(s.runs[3].text, "5") && !strcmp(s.runs[4].text, "2") && !strcmp(s.runs[5].text, "1") && !s.runs[6].text[0]);
++ assert(!strcmp(s.runs[7].text, "applied") && !strcmp(s.runs[8].text, "replies") && !strcmp(s.runs[9].text, "interviews"));
++ assert(!strcmp(s.runs[10].text, "5 / 10 applied"));
++ assert(ht_focus_pet_next_ms(&f, "GLANCE applied=5 goal=10") == 0);
++ // Another glance line, fewer numbers and no goal: the same runs, the empty ones empty.
++ ht_scene_clear(&s, ht_rgb(HT_THEME_FOCUS_CANVAS));
++ ht_focus_face(&s, &f, 0, 0, "GLANCE applied=12");
++ assert(s.count == 11 && s.runs[1].ring.set && !s.runs[1].ring.w16 && !s.runs[2].ring.w16);
++ assert(!strcmp(s.runs[3].text, "12") && !s.runs[4].text[0] && !s.runs[8].text[0] && !s.runs[10].text[0]);
++ // Past the goal the ring is full; at zero it is empty.
++ ht_scene_clear(&s, ht_rgb(HT_THEME_FOCUS_CANVAS));
++ ht_focus_face(&s, &f, 0, 0, "GLANCE applied=12 goal=10");
++ assert(s.runs[2].ring.w16 && s.runs[2].ring.cosh == -16384);
++ ht_scene_clear(&s, ht_rgb(HT_THEME_FOCUS_CANVAS));
++ ht_focus_face(&s, &f, 0, 0, "GLANCE applied=0 goal=10");
++ assert(s.runs[1].ring.w16 && !s.runs[2].ring.w16);
++ // A malformed line is an ordinary recap: the card (a box) in its slot, the text on it.
++ ht_scene_clear(&s, ht_rgb(HT_THEME_FOCUS_CANVAS));
++ ht_focus_face(&s, &f, 0, 0, "GLANCE applied=10000 goal=10");
++ assert(s.count == 11 && !s.runs[1].ring.set && s.runs[2].box.h && !s.runs[2].ring.set);
++ assert(strstr(s.runs[3].text, "GLANCE"));
++}
++
++int main(void)
++{
++ parser();
++ face_runs();
++ puts("glance: PASS (parser, fallback, face runs)");
++ return 0;
++}
+diff --git a/devices/harness-device/firmware/test/test_touch_ui.py b/devices/harness-device/firmware/test/test_touch_ui.py
+index 71ab1a04f..a921d73d7 100644
+--- a/devices/harness-device/firmware/test/test_touch_ui.py
++++ b/devices/harness-device/firmware/test/test_touch_ui.py
+@@ -2158,7 +2158,7 @@ int main(int argc, char **argv) {
+ assert(from && ALERT_AT(0) && BLUE_BOX() < 0 && COUNT("1") < 0 && scene.count == runs);
+ for (int i = 0; i < scene.count; i++) {
+ assert(scene.runs[i].font != &ht_lv_montserrat_14.base || !scene.runs[i].text[0]); // no bell pill
+- if (scene.runs[i].arc == 2 && scene.runs[i].text[0]) assert(scene.runs[i].fg == ht_rgb(0x00ff2f));
++ if (scene.runs[i].arc == 2 && scene.runs[i].text[0]) assert(scene.runs[i].fg == ht_rgb(HT_THEME_WORKING));
+ }
+ // its next step, or the working scene's next frame if that comes first
+ assert(s.pet_next_ms > from && s.pet_next_ms <= from + S);
+@@ -2759,6 +2759,11 @@ int main(int argc, char **argv) {
+ ui_project_emit("a", "sess", "summary", "Shipped the retry queue and moved the parser tests to the new fixtures. All 44 checks pass.",
+ "Shipped the retry queue and moved the parser tests to the new fixtures. All 44 checks pass.");
+ fake_ms = 1200; scene_take(); DESIGN("recap");
++ // The glance face (focus.c glance_face): a recap that is a glance line, as the daemon sends one.
++ DESIGN_HOME();
++ ui_project_emit("a", "sess", "summary", "GLANCE applied=5 replies=2 interviews=1 goal=10 Sent five applications today.",
++ "GLANCE applied=5 replies=2 interviews=1 goal=10 Sent five applications today.");
++ fake_ms = 1200; scene_take(); DESIGN("glance");
+ DESIGN_HOME(); s.agents[0].busy = true; strcpy(s.agents[0].tool, "Coalescing");
+ fake_ms = 1200; scene_take(); s.agents[0].busy_ms = 1; fake_ms = 34000 + 1200; scene_take(); DESIGN("working");
+ {
+@@ -2798,6 +2803,7 @@ int main(int argc, char **argv) {
+ '''
+ extra_sources = []
+ extra_includes = ['-DDEVICE_HABITAT_ORANGE=1'] if os.environ.get('HABITAT_TEST_ORANGE') else []
++if os.environ.get('HABITAT_TEST_FO'): extra_includes.append('-DDEVICE_HABITAT_FO=1') # the Fo colours (theme.h)
+ if os.environ.get('HABITAT_BRIDGE_TRACE'):
+ from bridge_flow_replay import instrument
+ code = instrument(code, os.environ['HABITAT_BRIDGE_TRACE'], native.parent.parent)
diff --git a/samples/hackathon-fo/02-desk-assistant/.env.example b/samples/hackathon-fo/02-desk-assistant/.env.example
new file mode 100644
index 000000000..9e769c583
--- /dev/null
+++ b/samples/hackathon-fo/02-desk-assistant/.env.example
@@ -0,0 +1,10 @@
+# Copy to .env (never commit .env) and fill in.
+# Gmail: IMAP over TLS with an app password (Google Account > Security > 2-Step Verification > App passwords).
+IMAP_HOST=imap.gmail.com
+# The 16 letters Google shows, spaces or not.
+IMAP_APP_PASSWORD=abcd efgh ijkl mnop
+# The folder (Gmail label) to watch. INBOX, or a label such as "Jobs".
+IMAP_FOLDER=INBOX
+# How often to look for new unseen mail, in seconds (at least 10).
+POLL_SECONDS=30
diff --git a/samples/hackathon-fo/02-desk-assistant/.gitignore b/samples/hackathon-fo/02-desk-assistant/.gitignore
new file mode 100644
index 000000000..a744a2512
--- /dev/null
+++ b/samples/hackathon-fo/02-desk-assistant/.gitignore
@@ -0,0 +1,4 @@
+.env
+state.json
+state.json.tmp
+__pycache__/
diff --git a/samples/hackathon-fo/02-desk-assistant/README.md b/samples/hackathon-fo/02-desk-assistant/README.md
new file mode 100644
index 000000000..6d5e56ef8
--- /dev/null
+++ b/samples/hackathon-fo/02-desk-assistant/README.md
@@ -0,0 +1,184 @@
+# Sample 2 — Desk assistant: new email → Fo → round device
+
+A small Python script (`mail_to_fo.py`, standard library only) reads your mailbox over IMAP, checks for new unread
+email every 30 seconds, and hands each email to **one** long-lived Fo harness named **Fo inbox**. Fo sums up the email
+in one sentence and tells you what to do about it. When Fo finishes answering, its turn ends: the round device beeps
+and creates a Notice with the recap. Job-hunt emails also update the `GLANCE …` line, so the
+[Sample 1](../01-fo-glance/README.md) screen can draw the numbers.
+
+```
+Gmail ──IMAP/TLS──▶ mail_to_fo.py ──ws://127.0.0.1:18473/api/local-ws──▶ Harness daemon ──▶ Fo (cloud)
+ │
+ round device ◀── recap ──────┘
+```
+
+What you'll see on the device (rendered by the firmware's own drawing code):
+
+| 1. Email arrives | 2. Tap the bell | 3. Open Fo inbox |
+|---|---|---|
+| <img src="../images/device-notice.png" width="220" alt="Bell with 1 beside the working pet"> | <img src="../images/device-inbox.png" width="220" alt="Notices page with Fo inbox's message"> | <img src="../images/device-glance.png" width="220" alt="Glance screen with the job-hunt numbers"> |
+| Fo answered: the bell and its count pop in beside whatever agent you're on | Notices: the machine, **Fo inbox**, and Fo's one-line summary | with Sample 1 flashed, a job-hunt email shows as numbers; without it, the recap card |
+
+What the script sends to Fo: the sender, subject, date, the body as plain text (HTML stripped, cut to 2,000
+characters) and the summarizing instructions. The script **doesn't save email** to disk: `state.json` only keeps the
+harness id and the UIDs it has handled. It **doesn't mark email as read** unless you run it with `--mark-read`.
+
+## The files
+
+| File | What it is |
+|---|---|
+| `mail_to_fo.py` | the main script: IMAP → text → harness (with a minimal RFC 6455 WebSocket client) |
+| `test_mail_to_fo.py` | unit tests (MIME multipart, HTML stripping, RFC 2047 header decoding, the 2,000-character cut, `state.json`, a fake IMAP loop) |
+| `sample.eml` | a fake email (an interview invitation, HTML, non-ASCII headers) to try without a mailbox |
+| `.env.example` | a config template; copy it to `.env` |
+
+## 1. Get ready
+
+1. Finish steps 1 and 3 of the [main guide](../README.md): Harness is running (`harness start`), you're signed in,
+ and **Fo is connected** (Settings ▸ Connectors ▸ **Add custom**, `https://mcp.api.wajo.ai/fo`).
+2. Python 3.9 or later (`python3 --version`). Nothing to `pip install`.
+3. Check that the script can talk to the daemon and Fo:
+
+ ```bash
+ cd samples/hackathon-fo/02-desk-assistant
+ python3 mail_to_fo.py --check
+ ```
+
+ **You should see:** `Fo is connected.` If you see `NOT_CONNECTED` or `DAEMON_UNREACHABLE`, see
+ [Stuck?](#7-stuck) below.
+
+## 2. Gmail app password
+
+Gmail doesn't allow IMAP sign-in with your regular password. You need an **app password** (16 letters):
+
+1. Turn on **2-Step Verification** for your Google account: https://myaccount.google.com/security.
+2. Open https://myaccount.google.com/apppasswords, enter a name (for example `harness-desk`), and click **Create**.
+3. Google shows 16 letters like `abcd efgh ijkl mnop`. Copy them right away (they're shown only once).
+4. Your company's Google Workspace admin may have turned off app passwords. If so, use a personal Gmail account.
+
+Use a test mailbox or a separate label (for example, a filter that moves job email to a `Jobs` label) so you don't send
+your whole personal inbox to Fo.
+
+## 3. Set up `.env`
+
+```bash
+cp .env.example .env
+```
+
+| Variable | Example | Meaning |
+|---|---|---|
+| `IMAP_HOST` | `imap.gmail.com` | the IMAP server (port 993, TLS) |
+| `IMAP_USER` | `[email protected]` | your email address |
+| `IMAP_APP_PASSWORD` | `abcd efgh ijkl mnop` | the app password from step 2 |
+| `IMAP_FOLDER` | `INBOX` or `Jobs` | the folder / label to watch |
+| `POLL_SECONDS` | `30` | how often to check (at least 10) |
+
+`.env` and `state.json` are already in `.gitignore`: don't commit them.
+
+## 4. Run it
+
+First try it with the fake email, no mailbox needed:
+
+```bash
+python3 mail_to_fo.py --dry-run-message sample.eml --print-only # only prints what would be sent
+python3 mail_to_fo.py --dry-run-message sample.eml # really sends it to Fo
+```
+
+**You should see** (in about 15–40 seconds):
+
+```
+Started Fo inbox (cloud_…).
+Fo: GLANCE applied=0 replies=0 interviews=1 goal=10
+
+A company invited you to interview for the Frontend Engineer role on Monday Oct 20 at 10:00 …
+```
+
+Next time, the script doesn't create a new harness; it keeps writing to **Fo inbox** (`Sent to Fo inbox (cloud_…)`).
+Its id is in `state.json`. If you close that harness, the script creates a new one next time.
+
+Then run it for real with your mailbox:
+
+```bash
+python3 mail_to_fo.py # runs until you press Ctrl-C
+python3 mail_to_fo.py --once # checks once, then exits
+python3 mail_to_fo.py --mark-read # marks the emails sent to Fo as read
+```
+
+**You should see:** `Watching INBOX of [email protected] every 30 s -> Fo inbox.` Send yourself an email. Within 30
+seconds you get `New mail 1234: <subject>`, then Fo's answer. On the first run, **every** unread email in the folder is
+sent, so start with a folder that has few unread emails.
+
+Other options: `--env PATH`, `--state PATH`, `--port N` (default 18473, or the `HARNESS_PORT` variable), `--help`.
+
+### When Fo isn't available: `--engine claude`
+
+```bash
+python3 mail_to_fo.py --engine claude --dry-run-message sample.eml
+python3 mail_to_fo.py --engine claude
+```
+
+The same content goes to a **Claude Code** harness on this machine, named **Mail inbox**, in the
+`~/harnesses/mail-inbox` folder that Harness creates. Claude Code must be installed and signed in (`claude`). Later
+emails are typed into its pane. The script waits for Claude to finish its turn before it sends the next email, and
+prints `Claude finished its turn.`. Read the answer in the **Mail inbox** pane of Harness Desktop or on the round
+device.
+
+## 5. On the round device
+
+- While Fo works, the **Fo inbox** tile switches to the working state.
+- When Fo finishes answering: the device **beeps** and the **Notices** bell gets a new entry. Open it to see the
+ **recap**, the first paragraph of Fo's answer (a one-sentence summary + what to do).
+- Job-hunt emails: the answer starts with `GLANCE applied=… replies=… interviews=… goal=10`. With the Sample 1
+ firmware, the device draws the glance screen (three numbers and a progress ring) instead of the recap card. The stock
+ firmware just shows that line as text.
+- If Fo asks a question and offers choices (a list of 1., 2., …), the question appears on the device's **question
+ screen**: tap to choose. Answer questions without choices in Fo's chat pane in Harness Desktop.
+- No round device: open Harness Desktop. The **Fo inbox** chat pane shows the whole conversation.
+
+## 6. How the script talks to Harness
+
+No CLI command sends text to an existing harness from a regular terminal (`harness send` is only for agents in the
+same tab), so the script talks to the daemon directly over the loopback WebSocket, like `harness new` does:
+
+1. Open `ws://127.0.0.1:18473/api/local-ws` (no `Origin` header, no token needed; it accepts connections from this
+ machine only).
+2. Send `{"type":"machine_select","payload":{"machineId":"<id>","localProtocolVersion":1,"tool":true}}`. Get the
+ `machineId` from `harness machines list --json` (the `"current":true` row). Wait for the `connected` frame.
+3. Each request is `{"type":"<name>","payload":{…,"requestId":"<uuid>"}}`. The answer is `<name>_result` with the same
+ `requestId`, with `error`/`detail` if it was rejected.
+
+| Request | What it's for |
+|---|---|
+| `cloud_agents {}` | whether Fo is connected (`agents[].connected`) |
+| `agent_create {engine:"fo", name:"Fo inbox", prompt, creationId}` | creates the Fo harness with the first email (an empty prompt is rejected: "Tell Fo what to do.") |
+| `cloud_send {agentId, text}` | sends the next email to Fo inbox |
+| `cloud_transcript {agentId}` | reads Fo's answer to print it in the terminal |
+| `agents_list {}` | whether the harness is still alive (`id`, `status`, `activity.state`) |
+| `agent_create {engine:"claude", name:"Mail inbox", projectSource:"new", projectName:"mail-inbox", prompt, creationId}` | the Claude Code harness (`--engine claude`) |
+| `message {agentId, content}` | types text into the Claude pane (the daemon doesn't answer this frame) |
+
+The script doesn't send the recap to the round device: the daemon creates it when Fo's turn ends
+(`cli/src/core/agents/cloud.ts`, `commander_event` of type `summary`). To dig deeper: `cli/src/localWsServer.ts` (the
+handshake), `cli/src/cloud/service.ts` (`cloud_*`), `cli/src/cloud/fo.ts` (Fo over MCP), `cli/src/lib/newCommand.ts`
+(`harness new`).
+
+## 7. Stuck?
+
+| You see | What to do |
+|---|---|
+| `NOT_CONNECTED: Fo is not connected` | Connect Fo: Harness Desktop ▸ Settings ▸ Connectors ▸ **Add custom**, URL `https://mcp.api.wajo.ai/fo`, sign in to Wajo in the browser. Run `--check` again. In the meantime you can use `--engine claude`. |
+| `DAEMON_UNREACHABLE: Harness is not running on port 18473` | The daemon isn't running: `harness start` (or open Harness Desktop). `harness status` should say `● running`. |
+| `NOT_SIGNED_IN` | `harness login`, then `harness start`. |
+| `DISCONNECTED: closed 4404 NO_PEER_LINK` (or `4403 machine mismatch`) | Wrong `machineId`: check that `harness machines list --json` has a `"current":true` row. |
+| `Poll failed: b'[AUTHENTICATIONFAILED] Invalid credentials …'` | Wrong app password, or you used your regular password. Create a new app password (step 2). |
+| `Cannot open folder Jobs` | Wrong label name. Write nested labels as `Parent/Child`. |
+| `Fo has not answered yet; its reply still reaches the device.` | Fo took longer than 3 minutes to answer. That's fine: when it's done, the round device still gets the Notice. |
+| Fo inbox doesn't show up | Open Harness Desktop: the **Fo inbox** pane sits with your other harnesses. Delete `state.json` to start a new harness. |
+| `--engine claude` sits idle | Claude Code is asking something in the **Mail inbox** pane (sign-in, folder permission): answer it in the pane. |
+| The round device doesn't beep | See steps 4–5 of the [main guide](../README.md): a data cable, and the device shows up in Devices. |
+
+Run the tests:
+
+```bash
+python3 -m unittest -v
+```
diff --git a/samples/hackathon-fo/02-desk-assistant/mail_to_fo.py b/samples/hackathon-fo/02-desk-assistant/mail_to_fo.py
new file mode 100644
index 000000000..670da3d07
--- /dev/null
+++ b/samples/hackathon-fo/02-desk-assistant/mail_to_fo.py
@@ -0,0 +1,647 @@
+#!/usr/bin/env python3
+"""New email -> Fo -> the round device.
+
+Polls one IMAP folder (Gmail with an app password), turns each new unseen message into a short text
+(sender, subject, plain-text body cut to 2,000 characters, and what to do with it) and hands it to one
+long-lived harness: the cloud agent Fo ("Fo inbox"), or with --engine claude a local Claude Code harness
+("Mail inbox"). The harness's reply ends its turn, so the device beeps and files a notice with the recap.
+
+It talks to the Harness daemon on this computer over its loopback WebSocket
+(ws://127.0.0.1:18473/api/local-ws), the same socket `harness new` uses. Python's standard library has
+no WebSocket client, so a minimal RFC 6455 client is below.
+
+Standard library only. It stores no mail on disk: state.json keeps the harness id and the UIDs handled.
+"""
+from __future__ import annotations
+
+import argparse
+import base64
+import email
+import email.header
+import email.utils
+import html
+import html.parser
+import imaplib
+import json
+import os
+import re
+import socket
+import ssl
+import struct
+import subprocess
+import sys
+import time
+import uuid
+from typing import Any, Callable, Optional
+
+BODY_LIMIT = 2000
+DEFAULT_PORT = 18473
+LOCAL_WS_PATH = "/api/local-ws"
+HARNESS_NAMES = {"fo": "Fo inbox", "claude": "Mail inbox"}
+# How many handled UIDs state.json keeps per folder: enough to never see one twice, small enough to read.
+UID_MEMORY = 5000
+
+INSTRUCTION = (
+ "A new email arrived. Answer in one short paragraph first: summarise it in one sentence and say what I "
+ "should do about it (reply, archive, add to calendar, ...). That first paragraph is what my small round "
+ "screen shows, so keep it short.\n"
+ "If it is job-search mail (an application sent, a reply from a company, an interview invitation), update "
+ "today's counts and START your answer with exactly one line in this form, then a blank line, then the "
+ "paragraph:\n"
+ "GLANCE applied=<n> replies=<n> interviews=<n> goal=10\n"
+ "(plain text, no bold, no code block; whole numbers 0-9999). The counts are running totals:\n"
+ "- applied: applications I have sent; a company confirming it received N applications counts all N;\n"
+ "- replies: messages from a company or recruiter that answer an application (a confirmation of receipt "
+ "is not a reply);\n"
+ "- interviews: interviews scheduled or proposed."
+)
+
+
+# ---------------------------------------------------------------------------------------------------------------
+# Mail -> text
+# ---------------------------------------------------------------------------------------------------------------
+
+class _TextExtractor(html.parser.HTMLParser):
+ """The visible text of an HTML body: no scripts, styles or head; block tags become line breaks."""
+
+ SKIP = {"script", "style", "head", "title", "noscript"}
+ BLOCK = {"p", "div", "br", "li", "tr", "h1", "h2", "h3", "h4", "h5", "h6", "table", "ul", "ol", "blockquote", "hr"}
+
+ def __init__(self) -> None:
+ super().__init__(convert_charrefs=True)
+ self.parts: list[str] = []
+ self.skipping = 0
+
+ def handle_starttag(self, tag: str, attrs: Any) -> None:
+ if tag in self.SKIP:
+ self.skipping += 1
+ elif tag in self.BLOCK:
+ self.parts.append("\n")
+
+ def handle_startendtag(self, tag: str, attrs: Any) -> None:
+ if tag in self.BLOCK:
+ self.parts.append("\n")
+
+ def handle_endtag(self, tag: str) -> None:
+ if tag in self.SKIP:
+ self.skipping = max(0, self.skipping - 1)
+ elif tag in self.BLOCK:
+ self.parts.append("\n")
+
+ def handle_data(self, data: str) -> None:
+ if not self.skipping:
+ # HTML whitespace, newlines included, is one space; only block tags break lines.
+ self.parts.append(re.sub(r"\s+", " ", data))
+
+
+def html_to_text(markup: str) -> str:
+ parser = _TextExtractor()
+ try:
+ parser.feed(markup)
+ parser.close()
+ except Exception: # A broken document still yields what was read.
+ pass
+ return tidy("".join(parser.parts))
+
+
+def tidy(text: str) -> str:
+ """Collapse runs of spaces and blank lines; strip each line."""
+ text = html.unescape(text).replace("\r\n", "\n").replace("\r", "\n").replace(" ", " ")
+ lines = [re.sub(r"[ \t\f\v]+", " ", line).strip() for line in text.split("\n")]
+ out: list[str] = []
+ for line in lines:
+ if line or (out and out[-1]):
+ out.append(line)
+ return "\n".join(out).strip()
+
+
+def decode_header(value: Optional[str]) -> str:
+ """An RFC 2047 header (=?UTF-8?B?...?=) as plain text."""
+ if not value:
+ return ""
+ try:
+ return str(email.header.make_header(email.header.decode_header(value))).strip()
+ except Exception:
+ return value.strip()
+
+
+def _part_text(part: email.message.Message) -> str:
+ payload = part.get_payload(decode=True)
+ if payload is None:
+ return ""
+ charset = part.get_content_charset() or "utf-8"
+ try:
+ return payload.decode(charset, errors="replace")
+ except LookupError:
+ return payload.decode("utf-8", errors="replace")
+
+
+def body_text(msg: email.message.Message) -> str:
+ """The message's plain-text body: text/plain when there is one, else its HTML stripped. Attachments skipped."""
+ plain: list[str] = []
+ rich: list[str] = []
+ for part in msg.walk() if msg.is_multipart() else [msg]:
+ if part.is_multipart():
+ continue
+ if (part.get_content_disposition() or "") == "attachment":
+ continue
+ kind = part.get_content_type()
+ if kind == "text/plain":
+ plain.append(_part_text(part))
+ elif kind == "text/html":
+ rich.append(_part_text(part))
+ if any(p.strip() for p in plain):
+ return tidy("\n\n".join(plain))
+ return html_to_text("\n".join(rich))
+
+
+def cut(text: str, limit: int = BODY_LIMIT) -> str:
+ if len(text) <= limit:
+ return text
+ return text[: limit - 1].rstrip() + "…"
+
+
+def mail_summary(raw: bytes) -> dict[str, str]:
+ """Sender, subject and body (cut to BODY_LIMIT) of one RFC 822 message."""
+ msg = email.message_from_bytes(raw)
+ sender = decode_header(msg.get("From"))
+ name, address = email.utils.parseaddr(sender)
+ return {
+ "from": f"{name} <{address}>" if name and address else (address or sender),
+ "subject": decode_header(msg.get("Subject")) or "(no subject)",
+ "date": decode_header(msg.get("Date")),
+ "body": cut(body_text(msg)),
+ }
+
+
+def mail_to_text(raw: bytes) -> str:
+ """The words sent to the harness for one message."""
+ m = mail_summary(raw)
+ lines = [INSTRUCTION, "", f"From: {m['from']}", f"Subject: {m['subject']}"]
+ if m["date"]:
+ lines.append(f"Date: {m['date']}")
+ lines += ["", m["body"] or "(empty body)"]
+ return "\n".join(lines)
+
+
+# ---------------------------------------------------------------------------------------------------------------
+# State
+# ---------------------------------------------------------------------------------------------------------------
+
+def load_state(path: str) -> dict[str, Any]:
+ try:
+ with open(path, encoding="utf-8") as f:
+ state = json.load(f)
+ except (FileNotFoundError, json.JSONDecodeError):
+ state = {}
+ if not isinstance(state, dict):
+ state = {}
+ state.setdefault("agents", {}) # engine -> agent id
+ state.setdefault("folders", {}) # folder -> {"uidvalidity": str, "handled": [uid, ...]}
+ return state
+
+
+def save_state(path: str, state: dict[str, Any]) -> None:
+ tmp = f"{path}.tmp"
+ with open(tmp, "w", encoding="utf-8") as f:
+ json.dump(state, f, indent=2)
+ os.replace(tmp, path)
+
+
+def folder_state(state: dict[str, Any], folder: str, uidvalidity: str) -> dict[str, Any]:
+ """The folder's record; a changed UIDVALIDITY means the server renumbered it, so old UIDs mean nothing."""
+ entry = state["folders"].get(folder)
+ if not entry or entry.get("uidvalidity") != uidvalidity:
+ entry = {"uidvalidity": uidvalidity, "handled": []}
+ state["folders"][folder] = entry
+ return entry
+
+
+def is_handled(entry: dict[str, Any], uid: str) -> bool:
+ return uid in entry["handled"]
+
+
+def mark_handled(entry: dict[str, Any], uid: str) -> None:
+ if uid not in entry["handled"]:
+ entry["handled"].append(uid)
+ del entry["handled"][:-UID_MEMORY]
+
+
+def load_env(path: str) -> dict[str, str]:
+ """KEY=VALUE lines; # comments; optional quotes. The real environment wins."""
+ values: dict[str, str] = {}
+ try:
+ with open(path, encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ key, value = line.split("=", 1)
+ value = value.strip()
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
+ value = value[1:-1]
+ values[key.strip()] = value
+ except FileNotFoundError:
+ pass
+ for key in {*values, "IMAP_HOST", "IMAP_USER", "IMAP_APP_PASSWORD", "IMAP_FOLDER", "POLL_SECONDS"}:
+ if key in os.environ:
+ values[key] = os.environ[key]
+ return values
+
+
+# ---------------------------------------------------------------------------------------------------------------
+# The daemon's loopback WebSocket (a minimal RFC 6455 client: text frames, masked, no extensions)
+# ---------------------------------------------------------------------------------------------------------------
+
+class DaemonError(Exception):
+ def __init__(self, code: str, detail: str = "") -> None:
+ super().__init__(f"{code}: {detail}" if detail else code)
+ self.code = code
+ self.detail = detail
+
+
+class WebSocket:
+ def __init__(self, host: str, port: int, path: str, timeout: float = 10.0) -> None:
+ try:
+ self.sock = socket.create_connection((host, port), timeout=timeout)
+ except OSError as error:
+ raise DaemonError("DAEMON_UNREACHABLE", f"Harness is not running on port {port} ({error}). Run `harness start`.")
+ key = base64.b64encode(os.urandom(16)).decode()
+ # No Origin header: the daemon refuses any (a browser always sends one).
+ request = (f"GET {path} HTTP/1.1\r\nHost: {host}:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
+ f"Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n")
+ self.sock.sendall(request.encode())
+ head = b""
+ while b"\r\n\r\n" not in head:
+ chunk = self.sock.recv(4096)
+ if not chunk:
+ raise DaemonError("DAEMON_UNREACHABLE", "The daemon closed the connection during the handshake.")
+ head += chunk
+ head, self.buffer = head.split(b"\r\n\r\n", 1)
+ status = head.split(b"\r\n", 1)[0].decode(errors="replace")
+ if " 101 " not in status + " ":
+ raise DaemonError("DAEMON_REFUSED", status)
+
+ def send(self, text: str) -> None:
+ data = text.encode()
+ header = bytearray([0x81])
+ n = len(data)
+ if n < 126:
+ header.append(0x80 | n)
+ elif n < 1 << 16:
+ header.append(0x80 | 126)
+ header += struct.pack("!H", n)
+ else:
+ header.append(0x80 | 127)
+ header += struct.pack("!Q", n)
+ mask = os.urandom(4)
+ header += mask
+ self.sock.sendall(bytes(header) + bytes(b ^ mask[i % 4] for i, b in enumerate(data)))
+
+ def _read(self, n: int) -> bytes:
+ while len(self.buffer) < n:
+ chunk = self.sock.recv(65536)
+ if not chunk:
+ raise DaemonError("DISCONNECTED", "The daemon connection closed.")
+ self.buffer += chunk
+ out, self.buffer = self.buffer[:n], self.buffer[n:]
+ return out
+
+ def _control(self, opcode: int, payload: bytes) -> None:
+ mask = os.urandom(4)
+ self.sock.sendall(bytes([0x80 | opcode, 0x80 | len(payload)]) + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(payload)))
+
+ def recv(self) -> str:
+ """The next whole text message; answers pings, skips binary (terminal) frames."""
+ message = b""
+ kind = None
+ while True:
+ b1, b2 = self._read(2)
+ fin, opcode = b1 & 0x80, b1 & 0x0F
+ n = b2 & 0x7F
+ if n == 126:
+ n = struct.unpack("!H", self._read(2))[0]
+ elif n == 127:
+ n = struct.unpack("!Q", self._read(8))[0]
+ mask = self._read(4) if b2 & 0x80 else None
+ payload = self._read(n)
+ if mask:
+ payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
+ if opcode == 0x8:
+ code = struct.unpack("!H", payload[:2])[0] if len(payload) >= 2 else 1005
+ raise DaemonError("DISCONNECTED", f"closed {code} {payload[2:].decode(errors='replace')}".strip())
+ if opcode == 0x9:
+ self._control(0xA, payload[:125])
+ continue
+ if opcode == 0xA:
+ continue
+ if opcode in (0x1, 0x2):
+ kind, message = opcode, payload
+ elif opcode == 0x0:
+ message += payload
+ if fin:
+ if kind == 0x1:
+ return message.decode(errors="replace")
+ message, kind = b"", None
+
+ def close(self) -> None:
+ try:
+ self._control(0x8, struct.pack("!H", 1000))
+ self.sock.close()
+ except OSError:
+ pass
+
+
+def this_machine_id() -> str:
+ """The id this daemon serves under: `harness machines list --json` (the current one), else the auth session."""
+ try:
+ out = subprocess.run(["harness", "machines", "list", "--json"], capture_output=True, text=True, timeout=20).stdout
+ for line in out.splitlines():
+ try:
+ row = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ rows = row if isinstance(row, list) else row.get("machines", [row]) if isinstance(row, dict) else []
+ for each in rows:
+ if isinstance(each, dict) and each.get("current") and each.get("machineId"):
+ return str(each["machineId"])
+ except (OSError, subprocess.SubprocessError):
+ pass
+ try:
+ with open(os.path.expanduser("~/.harness/auth/session.json"), encoding="utf-8") as f:
+ machine = json.load(f).get("machineId")
+ if machine:
+ return str(machine)
+ except (OSError, json.JSONDecodeError):
+ pass
+ raise DaemonError("NOT_SIGNED_IN", "Could not find this machine's id. Run `harness login`, then `harness start`.")
+
+
+class Daemon:
+ """One session with the daemon: select this machine as a tool, then ask one request at a time."""
+
+ def __init__(self, port: int = DEFAULT_PORT, machine_id: Optional[str] = None, timeout: float = 200.0) -> None:
+ self.ws = WebSocket("127.0.0.1", port, LOCAL_WS_PATH)
+ self.ws.sock.settimeout(timeout)
+ self.ws.send(json.dumps({"type": "machine_select", "payload": {
+ "machineId": machine_id or this_machine_id(), "localProtocolVersion": 1, "tool": True}}))
+ while True:
+ frame = json.loads(self.ws.recv())
+ if frame.get("type") == "connected":
+ return
+ if frame.get("type") == "machine_select_error":
+ raise DaemonError(str(frame.get("payload", {}).get("error", "MACHINE_UNAVAILABLE")))
+
+ def request(self, kind: str, payload: dict[str, Any]) -> dict[str, Any]:
+ request_id = str(uuid.uuid4())
+ self.ws.send(json.dumps({"type": kind, "payload": {**payload, "requestId": request_id}}))
+ while True:
+ try:
+ frame = json.loads(self.ws.recv())
+ except socket.timeout:
+ raise DaemonError("TIMEOUT", f"Harness did not answer {kind} in time.")
+ body = frame.get("payload") or {}
+ if isinstance(body, dict) and body.get("requestId") == request_id:
+ if body.get("error") is not None:
+ raise DaemonError(str(body["error"]), str(body.get("detail") or ""))
+ return body
+
+ def tell(self, kind: str, payload: dict[str, Any]) -> None:
+ """A frame the daemon does not answer (`message`)."""
+ self.ws.send(json.dumps({"type": kind, "payload": payload}))
+
+ def close(self) -> None:
+ self.ws.close()
+
+
+# ---------------------------------------------------------------------------------------------------------------
+# The harness
+# ---------------------------------------------------------------------------------------------------------------
+
+def fo_connected(daemon: Daemon) -> bool:
+ agents = daemon.request("cloud_agents", {}).get("agents", [])
+ return any(a.get("id") == "fo" and a.get("connected") for a in agents)
+
+
+def live_agents(daemon: Daemon) -> dict[str, dict[str, Any]]:
+ """Every harness this daemon lists, by id."""
+ reply = daemon.request("agents_list", {})
+ rows = reply.get("agents") or []
+ return {str(a["id"]): a for a in rows if isinstance(a, dict) and a.get("id") and a.get("status") != "stopped"}
+
+
+def create_harness(daemon: Daemon, engine: str, text: str) -> str:
+ """A new harness with [text] as its first task; its agent id."""
+ creation = str(uuid.uuid4())
+ payload: dict[str, Any] = {"engine": engine, "name": HARNESS_NAMES[engine], "prompt": text, "creationId": creation}
+ if engine == "claude":
+ # A project folder Harness makes (~/harnesses/mail-inbox): Harness answers Claude Code's
+ # "trust this folder?" for it, where a folder we name would wait for the person.
+ payload.update({"projectSource": "new", "projectName": "mail-inbox"})
+ reply = daemon.request("agent_create", payload)
+ # A local launch may be held a moment (pending): asked after, as `harness new` does.
+ for _ in range(60):
+ if reply.get("state") not in ("pending", "unconfirmed"):
+ break
+ time.sleep(2)
+ reply = daemon.request("agent_create_status", {"creationId": creation})
+ if reply.get("state") not in (None, "created"):
+ failure = reply.get("failure") or {}
+ raise DaemonError(str(failure.get("code") or reply.get("state")), str(failure.get("detail") or ""))
+ agent = reply.get("agent") or {}
+ agent_id = agent.get("id") or agent.get("agentId") or reply.get("agentId")
+ if not agent_id:
+ raise DaemonError("UNCONFIRMED", f"agent_create answered without an agent: {json.dumps(reply)[:300]}")
+ return str(agent_id)
+
+
+def send_words(daemon: Daemon, engine: str, agent_id: str, text: str) -> None:
+ if engine == "fo":
+ daemon.request("cloud_send", {"agentId": agent_id, "text": text})
+ else:
+ # Typed into the pane, as the app's prompt box does; the daemon does not answer this frame.
+ daemon.tell("message", {"agentId": agent_id, "content": text})
+
+
+def fo_reply(daemon: Daemon, agent_id: str, after: int, timeout: float = 180.0) -> Optional[str]:
+ """Fo's next words after message [after] of its conversation, or None when it says nothing in time."""
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ reply = daemon.request("cloud_transcript", {"agentId": agent_id})
+ messages = reply.get("messages") or []
+ total = int(reply.get("total") or len(messages))
+ new = messages[len(messages) - (total - after):] if total > after else []
+ said = [m.get("text", "") for m in new if m.get("from") == "agent"]
+ if said:
+ return said[-1]
+ time.sleep(3)
+ return None
+
+
+def transcript_length(daemon: Daemon, agent_id: str) -> int:
+ reply = daemon.request("cloud_transcript", {"agentId": agent_id})
+ return int(reply.get("total") or len(reply.get("messages") or []))
+
+
+def deliver(daemon: Daemon, state: dict[str, Any], state_path: str, engine: str, text: str,
+ log: Callable[[str], None] = print) -> None:
+ """Hand [text] to the long-lived harness: created on the first email, written to afterwards."""
+ agent_id = state["agents"].get(engine)
+ if agent_id and agent_id not in live_agents(daemon):
+ log(f"{HARNESS_NAMES[engine]} ({agent_id}) is gone; starting a new one.")
+ agent_id = None
+ before = 0
+ if agent_id:
+ if engine == "fo":
+ before = transcript_length(daemon, agent_id)
+ send_words(daemon, engine, agent_id, text)
+ log(f"Sent to {HARNESS_NAMES[engine]} ({agent_id}).")
+ else:
+ agent_id = create_harness(daemon, engine, text)
+ state["agents"][engine] = agent_id
+ save_state(state_path, state)
+ log(f"Started {HARNESS_NAMES[engine]} ({agent_id}).")
+ if engine == "fo":
+ # Waiting keeps one email per turn: words sent while Fo works cut short the look for its reply.
+ answer = fo_reply(daemon, agent_id, before)
+ log(f"Fo: {answer}" if answer else "Fo has not answered yet; its reply still reaches the device.")
+ else:
+ # One email per turn here too: the next words wait until Claude's turn has ended.
+ log("Claude finished its turn." if wait_idle(daemon, agent_id) else "Claude is still working; moving on.")
+
+
+def wait_idle(daemon: Daemon, agent_id: str, timeout: float = 300.0) -> bool:
+ """True once the harness has worked and is idle again (or never started working within 20 s)."""
+ deadline, seen_working, began = time.time() + timeout, False, time.time()
+ while time.time() < deadline:
+ row = live_agents(daemon).get(agent_id) or {}
+ activity = row.get("activity") or {}
+ # "working" is a lease: it holds for validForMs unless renewed, so an expired one is idle.
+ working = (activity.get("state") == "working" and float(activity.get("validForMs") or 0) > 0) \
+ or (row.get("launch") or {}).get("state") == "starting"
+ seen_working = seen_working or working
+ if not working and (seen_working or time.time() - began > 20):
+ return True
+ time.sleep(3)
+ return False
+
+
+# ---------------------------------------------------------------------------------------------------------------
+# IMAP
+# ---------------------------------------------------------------------------------------------------------------
+
+def poll_once(config: dict[str, str], state: dict[str, Any], state_path: str, engine: str, port: int,
+ mark_read: bool) -> int:
+ folder = config.get("IMAP_FOLDER") or "INBOX"
+ imap = imaplib.IMAP4_SSL(config["IMAP_HOST"], ssl_context=ssl.create_default_context())
+ handled = 0
+ try:
+ imap.login(config["IMAP_USER"], config["IMAP_APP_PASSWORD"])
+ status, data = imap.select(f'"{folder}"', readonly=not mark_read)
+ if status != "OK":
+ raise RuntimeError(f"Cannot open folder {folder}: {data}")
+ uidvalidity = (imap.response("UIDVALIDITY")[1] or [b"0"])[0]
+ entry = folder_state(state, folder, uidvalidity.decode() if isinstance(uidvalidity, bytes) else str(uidvalidity))
+ status, data = imap.uid("search", None, "UNSEEN")
+ uids = [u.decode() for u in (data[0] or b"").split()] if status == "OK" else []
+ fresh = [u for u in uids if not is_handled(entry, u)]
+ if not fresh:
+ return 0
+ daemon = Daemon(port)
+ try:
+ for uid in fresh:
+ # BODY.PEEK leaves the message unread.
+ status, parts = imap.uid("fetch", uid, "(BODY.PEEK[])")
+ raw = next((p[1] for p in parts or [] if isinstance(p, tuple)), None)
+ if status != "OK" or raw is None:
+ continue
+ print(f"New mail {uid}: {mail_summary(raw)['subject']}")
+ deliver(daemon, state, state_path, engine, mail_to_text(raw))
+ mark_handled(entry, uid)
+ save_state(state_path, state)
+ if mark_read:
+ imap.uid("store", uid, "+FLAGS", "(\\Seen)")
+ handled += 1
+ finally:
+ daemon.close()
+ finally:
+ try:
+ imap.logout()
+ except Exception:
+ pass
+ return handled
+
+
+def main(argv: Optional[list[str]] = None) -> int:
+ here = os.path.dirname(os.path.abspath(__file__))
+ parser = argparse.ArgumentParser(description="New email -> Fo -> the round device.")
+ parser.add_argument("--engine", choices=["fo", "claude"], default="fo", help="Fo in the cloud (default) or a local Claude Code harness")
+ parser.add_argument("--env", default=os.path.join(here, ".env"), help="config file (default: .env beside this script)")
+ parser.add_argument("--state", default=os.path.join(here, "state.json"), help="harness id and handled UIDs")
+ parser.add_argument("--port", type=int, default=int(os.environ.get("HARNESS_PORT", DEFAULT_PORT)), help="the daemon's port")
+ parser.add_argument("--mark-read", action="store_true", help="mark each handled message read")
+ parser.add_argument("--once", action="store_true", help="poll once and exit")
+ parser.add_argument("--dry-run-message", metavar="FILE",
+ help="no IMAP: send one RFC 822 message from FILE ('-' for stdin) through the same path")
+ parser.add_argument("--print-only", action="store_true", help="with --dry-run-message: print the text, send nothing")
+ parser.add_argument("--check", action="store_true", help="say whether the daemon answers and Fo is connected, then exit")
+ args = parser.parse_args(argv)
+
+ try:
+ if args.check:
+ daemon = Daemon(args.port)
+ try:
+ ok = fo_connected(daemon)
+ print("Fo is connected." if ok else "NOT_CONNECTED: Fo is not connected. Settings ▸ Connectors ▸ Add custom, https://mcp.api.wajo.ai/fo")
+ return 0 if ok else 3
+ finally:
+ daemon.close()
+
+ if args.dry_run_message:
+ raw = sys.stdin.buffer.read() if args.dry_run_message == "-" else open(args.dry_run_message, "rb").read()
+ text = mail_to_text(raw)
+ if args.print_only:
+ print(text)
+ return 0
+ state = load_state(args.state)
+ daemon = Daemon(args.port)
+ try:
+ if args.engine == "fo" and not fo_connected(daemon):
+ raise DaemonError("NOT_CONNECTED", "Fo is not connected. Connect it, or run with --engine claude.")
+ deliver(daemon, state, args.state, args.engine, text)
+ finally:
+ daemon.close()
+ return 0
+
+ config = load_env(args.env)
+ missing = [k for k in ("IMAP_HOST", "IMAP_USER", "IMAP_APP_PASSWORD") if not config.get(k)]
+ if missing:
+ print(f"Missing in {args.env}: {', '.join(missing)} (copy .env.example to .env)", file=sys.stderr)
+ return 2
+ every = max(10, int(config.get("POLL_SECONDS") or 30))
+ if args.engine == "fo":
+ daemon = Daemon(args.port)
+ try:
+ if not fo_connected(daemon):
+ raise DaemonError("NOT_CONNECTED", "Fo is not connected. Connect it, or run with --engine claude.")
+ finally:
+ daemon.close()
+ print(f"Watching {config.get('IMAP_FOLDER') or 'INBOX'} of {config['IMAP_USER']} every {every} s -> {HARNESS_NAMES[args.engine]}. Ctrl-C stops.")
+ while True:
+ state = load_state(args.state)
+ try:
+ poll_once(config, state, args.state, args.engine, args.port, args.mark_read)
+ except (imaplib.IMAP4.error, OSError, RuntimeError) as error:
+ print(f"Poll failed: {error}", file=sys.stderr)
+ if args.once:
+ return 0
+ time.sleep(every)
+ except DaemonError as error:
+ print(str(error), file=sys.stderr)
+ return 1
+ except KeyboardInterrupt:
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/samples/hackathon-fo/02-desk-assistant/sample.eml b/samples/hackathon-fo/02-desk-assistant/sample.eml
new file mode 100644
index 000000000..60f1f0612
--- /dev/null
+++ b/samples/hackathon-fo/02-desk-assistant/sample.eml
@@ -0,0 +1,17 @@
+From: =?UTF-8?B?Wm/DqyBNw7xsbGVy?= <[email protected]>
+Subject: =?UTF-8?Q?Interview_invitation_=E2=80=93?= Frontend Engineer
+Date: Thu, 16 Oct 2026 09:00:00 -0700
+MIME-Version: 1.0
+Content-Type: multipart/alternative; boundary="b1"
+
+--b1
+Content-Type: text/html; charset=utf-8
+
+<html><head><style>p{color:red}</style></head><body>
+<p>Hi,</p>
+<p>Thank you for applying for the <b>Frontend Engineer</b> role. We'd like to invite you to interview on
+<b>Monday, Oct 20 at 10:00 AM</b>. Could you confirm that works for you?</p>
+<p>Best regards,<br>Zoë</p>
+</body></html>
+--b1--
diff --git a/samples/hackathon-fo/02-desk-assistant/test_mail_to_fo.py b/samples/hackathon-fo/02-desk-assistant/test_mail_to_fo.py
new file mode 100644
index 000000000..0b11239bb
--- /dev/null
+++ b/samples/hackathon-fo/02-desk-assistant/test_mail_to_fo.py
@@ -0,0 +1,232 @@
+"""Unit tests for mail_to_fo.py: the mail-to-text step and the state file. Run: python3 -m unittest -v"""
+import json
+import os
+import tempfile
+import unittest
+from email.mime.application import MIMEApplication
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+
+import mail_to_fo as m
+
+
+def multipart(plain=None, html=None, attachment=None, subject="Hello", sender="[email protected]"):
+ msg = MIMEMultipart("mixed")
+ alt = MIMEMultipart("alternative")
+ if plain is not None:
+ alt.attach(MIMEText(plain, "plain", "utf-8"))
+ if html is not None:
+ alt.attach(MIMEText(html, "html", "utf-8"))
+ msg.attach(alt)
+ if attachment is not None:
+ part = MIMEApplication(attachment, Name="cv.pdf")
+ part["Content-Disposition"] = 'attachment; filename="cv.pdf"'
+ msg.attach(part)
+ msg["Subject"] = subject
+ msg["From"] = sender
+ return msg.as_bytes()
+
+
+class MailToText(unittest.TestCase):
+ def test_prefers_plain_part(self):
+ raw = multipart(plain="Plain words.", html="<p>HTML words.</p>")
+ self.assertEqual(m.mail_summary(raw)["body"], "Plain words.")
+
+ def test_html_only_is_stripped(self):
+ raw = multipart(html="<html><head><title>T</title><style>p{color:red}</style></head>"
+ "<body><script>alert(1)</script><p>Hi &amp; welcome,</p>"
+ "<p>see <b>you</b>\n soon</p></body></html>")
+ body = m.mail_summary(raw)["body"]
+ self.assertEqual(body, "Hi & welcome,\n\nsee you soon")
+ for leftover in ("<", ">", "color:red", "alert", "T\n"):
+ self.assertNotIn(leftover, body)
+
+ def test_html_line_breaks(self):
+ self.assertEqual(m.html_to_text("Line one<br>Line two<br/>Line three"), "Line one\nLine two\nLine three")
+
+ def test_attachment_skipped(self):
+ raw = multipart(plain="See attached.", attachment=b"%PDF-1.4 binary")
+ self.assertEqual(m.mail_summary(raw)["body"], "See attached.")
+
+ def test_rfc2047_headers_decoded(self):
+ raw = (b"From: =?UTF-8?B?Wm/DqyBNw7xsbGVy?= <[email protected]>\r\n"
+ b"Subject: =?UTF-8?Q?Interview_invitation_=E2=80=93_next_steps?=\r\n"
+ b"Content-Type: text/plain; charset=utf-8\r\n\r\nBody\r\n")
+ summary = m.mail_summary(raw)
+ self.assertEqual(summary["from"], "Zoë Müller <[email protected]>")
+ self.assertEqual(summary["subject"], "Interview invitation – next steps")
+
+ def test_non_utf8_charset(self):
+ raw = "Subject: x\r\nContent-Type: text/plain; charset=iso-8859-1\r\n\r\ncaf\xe9\r\n".encode("latin-1")
+ self.assertEqual(m.mail_summary(raw)["body"], "café")
+
+ def test_body_cut_to_limit(self):
+ raw = multipart(plain="word " * 1000)
+ body = m.mail_summary(raw)["body"]
+ self.assertLessEqual(len(body), m.BODY_LIMIT)
+ self.assertTrue(body.endswith("…"))
+ short = m.mail_summary(multipart(plain="short"))["body"]
+ self.assertEqual(short, "short")
+
+ def test_text_has_instruction_and_fields(self):
+ text = m.mail_to_text(multipart(plain="Interview on Monday.", subject="Interview", sender="HR <[email protected]>"))
+ self.assertTrue(text.startswith(m.INSTRUCTION))
+ self.assertIn("From: HR <[email protected]>", text)
+ self.assertIn("Subject: Interview", text)
+ self.assertIn("GLANCE applied=", text)
+ self.assertTrue(text.rstrip().endswith("Interview on Monday."))
+
+ def test_missing_subject_and_empty_body(self):
+ raw = b"From: [email protected]\r\nContent-Type: text/plain\r\n\r\n"
+ text = m.mail_to_text(raw)
+ self.assertIn("Subject: (no subject)", text)
+ self.assertIn("(empty body)", text)
+
+ def test_sample_email(self):
+ with open(os.path.join(os.path.dirname(__file__), "sample.eml"), "rb") as f:
+ summary = m.mail_summary(f.read())
+ self.assertEqual(summary["subject"], "Interview invitation – Frontend Engineer")
+ self.assertIn("Monday, Oct 20 at 10:00 AM", summary["body"])
+ self.assertNotIn("color:red", summary["body"])
+
+
+class State(unittest.TestCase):
+ def setUp(self):
+ self.dir = tempfile.TemporaryDirectory()
+ self.path = os.path.join(self.dir.name, "state.json")
+
+ def tearDown(self):
+ self.dir.cleanup()
+
+ def test_missing_or_broken_file_is_empty(self):
+ self.assertEqual(m.load_state(self.path), {"agents": {}, "folders": {}})
+ with open(self.path, "w") as f:
+ f.write("{not json")
+ self.assertEqual(m.load_state(self.path), {"agents": {}, "folders": {}})
+
+ def test_round_trip_keeps_agent_and_uids(self):
+ state = m.load_state(self.path)
+ state["agents"]["fo"] = "cloud_abc"
+ entry = m.folder_state(state, "INBOX", "42")
+ m.mark_handled(entry, "7")
+ m.mark_handled(entry, "7")
+ m.save_state(self.path, state)
+ again = m.load_state(self.path)
+ self.assertEqual(again["agents"], {"fo": "cloud_abc"})
+ self.assertTrue(m.is_handled(m.folder_state(again, "INBOX", "42"), "7"))
+ self.assertEqual(again["folders"]["INBOX"]["handled"], ["7"])
+ self.assertFalse(os.path.exists(self.path + ".tmp"))
+
+ def test_state_holds_no_mail(self):
+ state = m.load_state(self.path)
+ m.mark_handled(m.folder_state(state, "INBOX", "1"), "9")
+ m.save_state(self.path, state)
+ with open(self.path) as f:
+ self.assertEqual(set(json.load(f)), {"agents", "folders"})
+
+ def test_uidvalidity_change_forgets_uids(self):
+ state = m.load_state(self.path)
+ m.mark_handled(m.folder_state(state, "INBOX", "1"), "5")
+ self.assertFalse(m.is_handled(m.folder_state(state, "INBOX", "2"), "5"))
+
+ def test_handled_list_is_bounded(self):
+ state = m.load_state(self.path)
+ entry = m.folder_state(state, "INBOX", "1")
+ for uid in range(m.UID_MEMORY + 10):
+ m.mark_handled(entry, str(uid))
+ self.assertEqual(len(entry["handled"]), m.UID_MEMORY)
+ self.assertTrue(m.is_handled(entry, str(m.UID_MEMORY + 9)))
+ self.assertFalse(m.is_handled(entry, "0"))
+
+
+class FakeImap:
+ """Enough of imaplib.IMAP4_SSL for poll_once: one folder, messages by UID, flags recorded."""
+
+ def __init__(self, messages, unseen):
+ self.messages, self.unseen, self.stored, self.readonly = messages, unseen, [], None
+
+ def __call__(self, host, ssl_context=None):
+ return self
+
+ def login(self, user, password):
+ return "OK", [b"ok"]
+
+ def select(self, folder, readonly=False):
+ self.readonly = readonly
+ return "OK", [str(len(self.messages)).encode()]
+
+ def response(self, code):
+ return code, [b"777"]
+
+ def uid(self, command, *args):
+ if command == "search":
+ return "OK", [" ".join(self.unseen).encode()]
+ if command == "fetch":
+ return "OK", [(b"1 (BODY[] {n}", self.messages[args[0]]), b")"]
+ if command == "store":
+ self.stored.append(args[0])
+ return "OK", []
+
+ def logout(self):
+ pass
+
+
+class FakeDaemon:
+ def __init__(self, port):
+ pass
+
+ def close(self):
+ pass
+
+
+class Poll(unittest.TestCase):
+ def setUp(self):
+ self.dir = tempfile.TemporaryDirectory()
+ self.path = os.path.join(self.dir.name, "state.json")
+ self.sent = []
+ self.saved = (m.imaplib.IMAP4_SSL, m.Daemon, m.deliver)
+ m.Daemon = FakeDaemon
+ m.deliver = lambda daemon, state, path, engine, text: self.sent.append(text)
+
+ def tearDown(self):
+ m.imaplib.IMAP4_SSL, m.Daemon, m.deliver = self.saved
+ self.dir.cleanup()
+
+ def run_poll(self, imap, mark_read=False):
+ m.imaplib.IMAP4_SSL = imap
+ config = {"IMAP_HOST": "imap.example", "IMAP_USER": "u", "IMAP_APP_PASSWORD": "p", "IMAP_FOLDER": "INBOX"}
+ state = m.load_state(self.path)
+ return m.poll_once(config, state, self.path, "fo", 1, mark_read)
+
+ def test_new_mail_sent_once_and_left_unread(self):
+ imap = FakeImap({"5": multipart(plain="one", subject="A"), "6": multipart(plain="two", subject="B")}, ["5", "6"])
+ self.assertEqual(self.run_poll(imap), 2)
+ self.assertEqual(len(self.sent), 2)
+ self.assertTrue(imap.readonly)
+ self.assertEqual(imap.stored, [])
+ self.assertEqual(self.run_poll(imap), 0)
+ self.assertEqual(len(self.sent), 2)
+ self.assertEqual(m.load_state(self.path)["folders"]["INBOX"], {"uidvalidity": "777", "handled": ["5", "6"]})
+
+ def test_mark_read(self):
+ imap = FakeImap({"5": multipart(plain="one")}, ["5"])
+ self.run_poll(imap, mark_read=True)
+ self.assertFalse(imap.readonly)
+ self.assertEqual(imap.stored, ["5"])
+
+
+class Env(unittest.TestCase):
+ def test_parses_quotes_and_comments(self):
+ with tempfile.NamedTemporaryFile("w", suffix=".env", delete=False) as f:
+ f.write("# comment\nIMAP_HOST=imap.gmail.com\nIMAP_APP_PASSWORD=\"abcd efgh ijkl mnop\"\n\nPOLL_SECONDS=30\n")
+ try:
+ values = m.load_env(f.name)
+ finally:
+ os.unlink(f.name)
+ self.assertEqual(values["IMAP_HOST"], "imap.gmail.com")
+ self.assertEqual(values["IMAP_APP_PASSWORD"], "abcd efgh ijkl mnop")
+ self.assertEqual(values["POLL_SECONDS"], "30")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/samples/hackathon-fo/README.md b/samples/hackathon-fo/README.md
new file mode 100644
index 000000000..f9e40ab87
--- /dev/null
+++ b/samples/hackathon-fo/README.md
@@ -0,0 +1,149 @@
+# Hackathon Fo × Harness
+
+This guide takes your team from opening the box to running agents on the round device (Harness device), then on to two
+code samples that dig into the repo. Work through the steps in order. Each step has **You should see** so you know it
+worked, and **Stuck?** for when it didn't.
+
+> You need a Mac (macOS 12 or later), a Google, Apple or email account, and the round device with a USB-C cable that
+> **carries data**. Harness Desktop runs on macOS and Linux. There is no Windows version yet.
+
+- [1. Install Harness and sign in](#1-install-harness-and-sign-in)
+- [2. Run your first agent (Claude Code, Codex, …)](#2-run-your-first-agent)
+- [3. Add Fo and run an agent with Fo](#3-add-fo-and-run-an-agent-with-fo)
+- [4. Plug in the round device and work with agents on it](#4-plug-in-the-round-device)
+- [5. Troubleshooting](#5-troubleshooting)
+- [6. Repo map](#6-repo-map)
+- [Sample 1 — Fo glance: your own firmware screen for the round device](01-fo-glance/README.md)
+- [Sample 2 — Desk assistant: new email → Fo → round device](02-desk-assistant/README.md)
+
+---
+
+## 1. Install Harness and sign in
+
+1. Download **Harness Desktop** from https://harness.autonomous.ai/desktop → **Download the app for macOS**, drag
+ Harness into Applications and open it. (Linux: download the AppImage, `chmod +x` it, then open it.)
+2. Sign in with **Continue with Google**, **Continue with Apple** or **Continue with email**. Your browser opens a
+ sign-in page. When you're done, go back to the app.
+3. On first run the app installs everything else for you: the `harness` command-line tool
+ (`~/.local/bin/harness`), tmux, and the background daemon, which it starts. Nothing to install by hand. Check in a
+ new terminal:
+
+ ```bash
+ harness --version # the CLI the app installed
+ harness status # the daemon is running and signed in to your account
+ ```
+
+**You should see:** the app opens your workspace; `harness status` shows `status ● running` and `local api
+http://127.0.0.1:18473`.
+
+**Stuck?** `harness: command not found`: open a new terminal (the app adds `~/.local/bin` to your PATH), or run
+`~/.local/bin/harness`. `harness status` says signed out: run `harness login` with the same account as the app.
+Every machine on the team must sign in to **the same account** to see each other. To replay the in-app
+guide: Help ▸ Welcome Tour.
+
+## 2. Run your first agent
+
+Harness doesn't replace your agent. It runs each vendor's own CLI and keeps track of it. So **first install and sign in
+to the CLI of the engine** you want to use:
+
+| Engine | Command | Sign in |
+|---|---|---|
+| Claude Code | `claude` | run `claude` once and follow the prompts |
+| Codex | `codex` | run `codex` once and sign in |
+| Muse, Cursor, OpenCode, … | `muse`, `cursor-agent`, `opencode` | same as above |
+
+Then, in the app:
+
+1. **New Harness** (⌘N).
+2. Pick the **machine**, the working **folder** (or **Clone repository** to clone a GitHub repo), and the **engine**
+ (Claude Code, Codex, …). Advanced has the permission mode (the default is the engine's auto-approve).
+3. Type your task into the pane that opens.
+
+Or from the terminal:
+
+```bash
+harness new # Claude Code in the current folder
+harness new codex ~/code/my-app # Codex in the given folder
+harness new codex my-game # creates a new project in ~/harnesses/my-game
+```
+
+**You should see:** the agent's terminal pane. The top tab shows a spinner while the agent works and ✓ when it's done.
+
+## 3. Add Fo and run an agent with Fo
+
+Fo is Wajo's agent. It runs **on Fo's cloud**, not on your machine. Harness talks to Fo over MCP, so "signing in to
+Fo" means adding Fo as a Connection:
+
+1. **Settings ▸ Connectors ▸ Add custom**.
+2. **Name**: `Fo`. **Remote MCP server URL**: `https://mcp.api.wajo.ai/fo`. Click **Continue**.
+3. Your browser opens the Wajo sign-in page. Sign in, then go back to the app.
+4. **New Harness** (⌘N) ▸ under **Agent**, pick **Fo**. The Computer field switches to **Fo's cloud** on its own (Fo
+ needs no folder, model or permissions). Type a task, for example: *"Find me 3 quiet coffee shops in District 1
+ that stay open until 10 pm"*.
+
+**You should see:** a chat pane (not a terminal). Fo may answer right away, or say it's working and answer later. When
+Fo asks you something and offers choices, the question shows up for you to pick an answer.
+
+**Stuck?**
+- You see `NOT_CONNECTED` / "Connect Fo in Connections…" → steps 1–3 aren't done. Do Add custom again.
+- You can't stop Fo from Harness. Closing the pane only stops following it ("Fo keeps working on its own").
+- Claude Code and Codex can use Fo's tools through the same Fo connection.
+
+## 4. Plug in the round device
+
+1. Make sure Harness is running on the Mac (`harness start`, app open).
+2. Plug the round device into the Mac with a **USB-C data cable**. There's no Wi-Fi and no pairing code: plugging it in
+ connects it.
+3. In the app, click **Manage Harness devices** in the toolbar → **"Plug in. Make it yours."** → wait for
+ "Waiting for a USB connection…" to change to your device → set a **Device name** → **Finish setup**.
+
+**You should see on the device:** the word **Harness**, then the pet of the selected agent. The device follows the app
+window: the tabs and panes open in the app are what the device shows.
+
+**Working with agents on the device (touch):**
+
+| To | Do this |
+|---|---|
+| Pick an agent | tap the agent's tile; drag to scroll the list |
+| Switch tabs | hold on the main screen to open the tab list, release to open one |
+| Talk to the agent | **hold the face for about 0.65 seconds** → *Listening* appears → speak → release to send |
+| See what the agent is doing | the **Working** screen: the pet at work, the current task and a timer |
+| See the result | when the agent finishes its turn, the **Recap** screen sums up what it did |
+| Notifications | a bell with a count on the screen → tap it to open **Notices** (one per page, ✕ to close) |
+| Interrupt the running turn | press the **BOOT** button once |
+
+Try it now: on the device, pick the Claude agent from step 2, hold the face and say *"list the files in this folder"*,
+release, and watch the device go from Working → Recap. Then do the same with Fo.
+
+**Note:** when an agent asks for permission (approval), the device only **tells** you. Approve it in the app or the
+terminal.
+
+## 5. Troubleshooting
+
+| Symptom | Common cause | What to do |
+|---|---|---|
+| The app doesn't see the round device | the cable is charge-only | use a data cable, plugged straight into the Mac |
+| The device shows Harness, then stays on "Loading..." | the daemon isn't running | `harness start` |
+| The agent pane shows an error as soon as it opens | the engine isn't signed in | run `claude` / `codex` in a terminal and sign in |
+| Fo reports `NOT_CONNECTED` | the Fo connection wasn't added | redo section 3 |
+| The device doesn't show the agent you just created | the agent isn't bound yet | wait a few seconds; if it still isn't there, run `harness logs export` and send it to the Harness team |
+
+## 6. Repo map
+
+| Folder | What it is | Used in |
+|---|---|---|
+| `devices/harness-device/firmware/` | the round device's firmware (ESP32-S3, ESP-IDF, C) | Sample 1 |
+| `devices/harness-device/firmware/main/ui/habitat/` | all the screen drawing: `focus.c` (the Focus face), `theme.h` (colors), `terminal.h` (drawing primitives) | Sample 1 |
+| `devices/harness-device/firmware/test/` | tests that run on the Mac, including a renderer that writes screens to images | Sample 1 |
+| `cli/` | the `harness` daemon (TypeScript): agents, engines, devices, Fo (`cli/src/cloud/fo.ts`) | Sample 2 |
+| `cli/src/cable/` | the daemon ↔ round device protocol over USB | further reading |
+| `desktop/` | the Harness Desktop app (Flutter) | further reading |
+| `docs/` | `app.md`, `cli.md`, `engines.md`, `architecture.md` | further reading |
+
+| Sample 1: your own firmware screen | Sample 2: email reaches you on the device |
+|---|---|
+| <img src="images/device-glance.png" width="240" alt="Glance screen"> | <img src="images/device-inbox.png" width="240" alt="Notices page with Fo inbox's message"> |
+
+When you're ready, go on to [Sample 1](01-fo-glance/README.md) and [Sample 2](02-desk-assistant/README.md). The two
+samples connect: Sample 2 feeds email to Fo, Fo answers with a line of numbers, and the Sample 1 screen draws those
+numbers on the round device.
diff --git a/samples/hackathon-fo/images/device-glance.png b/samples/hackathon-fo/images/device-glance.png
new file mode 100644
index 000000000..5ff2be30e
Binary files /dev/null and b/samples/hackathon-fo/images/device-glance.png differ
diff --git a/samples/hackathon-fo/images/device-inbox.png b/samples/hackathon-fo/images/device-inbox.png
new file mode 100644
index 000000000..db1a7907d
Binary files /dev/null and b/samples/hackathon-fo/images/device-inbox.png differ
diff --git a/samples/hackathon-fo/images/device-notice.png b/samples/hackathon-fo/images/device-notice.png
new file mode 100644
index 000000000..e3f46d321
Binary files /dev/null and b/samples/hackathon-fo/images/device-notice.png differ
diff --git a/samples/hackathon-fo/images/device-recap.png b/samples/hackathon-fo/images/device-recap.png
new file mode 100644
index 000000000..51db6b940
Binary files /dev/null and b/samples/hackathon-fo/images/device-recap.png differ
diff --git a/samples/hackathon-fo/images/device-working.png b/samples/hackathon-fo/images/device-working.png
new file mode 100644
index 000000000..7b5e644aa
Binary files /dev/null and b/samples/hackathon-fo/images/device-working.png differ