Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(glance): serve the card as a PNG and let a home screen widget read it with its own revocable token
nirholas4d894b087956
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6ade25492..f60d6af51 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,11 @@Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).+## 2026-08-29++- **Native widgets: your agent on the home screen** (`/docs/native-widgets`): Put your three.ws agent on an Android home screen (and the Windows 11 widgets board): what the widget shows, how to link and revoke it, every state it can be in, and the endpoints behind it.+- **Your agent on the Android home screen**: The three.ws Android app (1.1) now ships a home screen widget. It shows your agent's avatar, its name, and how many moves it made today, refreshes itself in the background about every half hour without opening the app, keeps the last card it saw when the phone is offline, and opens your agent with a tap. Link a phone from the Glance page in one tap; every linked widget is listed there with a revoke button, because each one carries its own token that can read your card and nothing else. The Glance card also comes as a PNG now, which is what any native widget host, chat client or image-only surface needs. (`/docs/native-widgets`) `[feature]`+## 2026-08-28- **Brownout** (`/brownout`): Every response from this API says where its data came from and how fresh it is, and every declared fallback has been proven by breaking the upstream it protects against, inside the real request path. Read the receipts: which provider refused, which one caught the request, and how old the answer was.diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 6308f6745..94829b922 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -50,7 +50,7 @@ bottom.| Cross-entity search | [pages/search.html](pages/search.html) `→ /search`, backend [api/search.js](api/search.js) + query layer [api/_lib/cross-search.js](api/_lib/cross-search.js) | Live | The one search across every creation type — avatars, on-chain/Solana agents, forged 3D models, worlds, and coins. Federates (not one SQL UNION — the stores are genuinely heterogeneous, two of five aren't even in the same database) five parallel queries, normalizes into one card shape, and ranks by recency plus real signals (follower count via `user_follows`, remix count, view count) — see the file header in `api/search.js` for the full unify-vs-federate writeup. Model results carry a working "Remix — $0.25" action against the existing paid rail ([api/x402/remix-asset.js](api/x402/remix-asset.js)), reused from [pages/creations.html](pages/creations.html) rather than re-derived. Coin search checks three.ws's own launch directory (`pump_agent_mints`) first, then falls back to market-wide pump.fun/Birdeye search for broader coverage (those external matches carry no verified timestamp or creator profile, and are ranked/labelled accordingly). Linked from the Discover nav menu. || Cross-surface rankings, streaks & badges | [pages/rankings.html](pages/rankings.html) `→ /rankings`, backend [api/leaderboard/unified.js](api/leaderboard/unified.js), streak/badge engine [api/_lib/streaks.js](api/_lib/streaks.js) (migration [api/_lib/migrations/20260712020000_leaderboard_streaks_badges.sql](api/_lib/migrations/20260712020000_leaderboard_streaks_badges.sql)), daily Top-10 badge sweep [api/cron/leaderboard-rollup.js](api/cron/leaderboard-rollup.js) | Live | Five real, queried leaderboard metrics — creations (forge models + worlds), remixes received, coin launches, followers, and walk distance (signed-in walkers, all-time) — ranked live with the viewer's own rank pinned even off-page. Every signed-in qualifying action (login, a finished forge model, a saved world, a `/walk` session) rolls a per-user daily streak in `user_streaks` via `recordDailyActivity()`, called from [api/_lib/auth.js](api/_lib/auth.js), [api/_lib/forge-store.js](api/_lib/forge-store.js), [api/_lib/diorama-store.js](api/_lib/diorama-store.js), and [api/walk/metrics.js](api/walk/metrics.js). Four real earned badges persist in `user_badges`: First Creation, Remixed (awarded in [api/x402/remix-asset.js](api/x402/remix-asset.js) when a remix lands on your creation), 7-Day Streak, and a daily-refreshed `top10_<metric>` per leaderboard. Streak + badges surface on the profile ([pages/profile.html](pages/profile.html)) and the Rankings page itself. Rejected metrics (documented in `api/leaderboard/unified.js`'s header): royalties earned in USD (the settlement record is a single overwritten JSONB column, not a cumulative ledger) and `/play` activity (no per-human-user session table exists). || create-agent (one command, one 3D character) | [packages/create-agent/](packages/create-agent) (client [src/forge.js](packages/create-agent/src/forge.js), scaffold [src/scaffold.js](packages/create-agent/src/scaffold.js), CLI [bin/create-agent.js](packages/create-agent/bin/create-agent.js)), server tools [api/_mcp-studio/tools.js](api/_mcp-studio/tools.js) | Live | `npm create @three-ws/agent "a friendly cartoon astronaut"` generates a textured figure, rigs it, downloads the GLB, and writes a folder with a working demo page and the embed snippet. No account and no API key: it rides the public, keyless JSON-RPC tools on [/api/mcp-studio](api/_mcp-studio) (`forge_avatar`, `forge_free`, `rig_mesh`) that the platform already exposes to MCP clients. A rigged character reliably outlives the endpoint's inline wait, so the client collects the returned poll handle and, when the job that finished was only the mesh, rigs it before reporting done: that is what the `stage` field on a pending result exists for. Progress is real elapsed time, never an invented bar. Docs [docs/create-agent.md](docs/create-agent.md). Tests: [tests/create-agent.test.js](tests/create-agent.test.js) |-| Glance (agent cards for home screens, READMEs and chat) | Page [public/glance/index.html](public/glance/index.html) `-> /glance` (+ [glance-page.js](public/glance/glance-page.js), [glance.css](public/glance/glance.css)), hosted element [public/glance/element.js](public/glance/element.js), endpoints [api/glance/card.js](api/glance/card.js) / [api/glance/mine.js](api/glance/mine.js) / [api/glance/template.js](api/glance/template.js), model [api/_lib/glance-card.js](api/_lib/glance-card.js), SVG [api/_lib/glance-svg.js](api/_lib/glance-svg.js), Adaptive Card [api/_lib/glance-adaptive.js](api/_lib/glance-adaptive.js), Windows widget worker [public/glance-sw.js](public/glance-sw.js) (imported by the VitePWA service worker, manifest `widgets` member in [vite.config.js](vite.config.js)), npm client [packages/agent-glance/](packages/agent-glance) | Live | One agent reduced to what fits in an OS widget slot: name, one live number (actions in the last 24h), and a link back. The same model renders four ways from one endpoint (JSON, SVG, Adaptive Card, and the `<agent-glance>` element), which is what keeps a new surface a rendering job rather than a data job. Windows 11 installs the widget straight from the PWA manifest (no store submission); Android, macOS and iOS are phase 5 of the roadmap and consume the same card. Deliberately not the 3D embed: no widget host on any of these platforms can run WebGL, so the body stays at [/widgets](public/widgets-gallery/index.html) and the status lives here. Private avatars never leak (the thumbnail is attached only for a public or unlisted avatar; everything else draws a generated monogram). Spec [specs/GLANCE_CARD.md](specs/GLANCE_CARD.md), docs [docs/glance.md](docs/glance.md). Tests: [tests/glance-card.test.js](tests/glance-card.test.js), [tests/glance-sw.test.js](tests/glance-sw.test.js), [tests/agent-glance-sdk.test.js](tests/agent-glance-sdk.test.js) |+| Glance (agent cards for home screens, READMEs and chat) | Page [public/glance/index.html](public/glance/index.html) `-> /glance` (+ [glance-page.js](public/glance/glance-page.js), [glance.css](public/glance/glance.css)), hosted element [public/glance/element.js](public/glance/element.js), endpoints [api/glance/card.js](api/glance/card.js) / [api/glance/mine.js](api/glance/mine.js) / [api/glance/token.js](api/glance/token.js) / [api/glance/template.js](api/glance/template.js), model [api/_lib/glance-card.js](api/_lib/glance-card.js), SVG [api/_lib/glance-svg.js](api/_lib/glance-svg.js), PNG [api/_lib/glance-png.js](api/_lib/glance-png.js), widget tokens [api/_lib/glance-tokens.js](api/_lib/glance-tokens.js) (`glance_widget_tokens`), Adaptive Card [api/_lib/glance-adaptive.js](api/_lib/glance-adaptive.js), Windows widget worker [public/glance-sw.js](public/glance-sw.js) (imported by the VitePWA service worker, manifest `widgets` member in [vite.config.js](vite.config.js)), Android home screen widget [solana-mobile/android-overlay/](solana-mobile/android-overlay/README.md) (applied by [solana-mobile/scripts/apply-overlay.mjs](solana-mobile/scripts/apply-overlay.mjs) inside `build-apk.sh`), npm client [packages/agent-glance/](packages/agent-glance) | Live | One agent reduced to what fits in an OS widget slot: name, one live number (actions in the last 24h), and a link back. The same model renders five ways from one endpoint (JSON, SVG, PNG, Adaptive Card, and the `<agent-glance>` element), which is what keeps a new surface a rendering job rather than a data job. Windows 11 installs the widget straight from the PWA manifest (no store submission). Android ships it in the app (1.1+): a WorkManager-refreshed `AppWidgetProvider` that fetches the PNG with a revocable per-account widget token minted on `/glance`, keeps the last card offline, and opens the agent on tap. macOS and iOS (WidgetKit) consume the same PNG and token next. Deliberately not the 3D embed: no widget host on any of these platforms can run WebGL, so the body stays at [/widgets](public/widgets-gallery/index.html) and the status lives here. Private avatars never leak (the thumbnail is attached only for a public or unlisted avatar; everything else draws a generated monogram). Spec [specs/GLANCE_CARD.md](specs/GLANCE_CARD.md), docs [docs/glance.md](docs/glance.md), [docs/native-widgets.md](docs/native-widgets.md). Tests: [tests/glance-card.test.js](tests/glance-card.test.js), [tests/glance-png.test.js](tests/glance-png.test.js), [tests/glance-tokens.test.js](tests/glance-tokens.test.js), [tests/glance-sw.test.js](tests/glance-sw.test.js), [tests/agent-glance-sdk.test.js](tests/agent-glance-sdk.test.js) || Daily Match (agent output arena) | [pages/daily-match.html](pages/daily-match.html) `→ /daily-match`, backend [api/leaderboard/daily-match.js](api/leaderboard/daily-match.js) | Live | Live daily standings ranking public agents by real output shipped since 00:00 UTC: agent_actions events, sniper + pump trades, confirmed skill sales, and coin launches, with realized sniper P&L shown for context (never scored). Computed live per request (no rollup cron), resets naturally at UTC midnight; includes yesterday's champion and a live-output feed. Reputation-first: no payouts hang off the score. Format adopted with credit from Bowyer's Arena (bowyer.app/arena), who build their agent pages on three.ws avatars. || KOL Tracker | [pages/tracker.html](pages/tracker.html) `→ /tracker`, backend [api/kol/[action].js](api/kol/%5Baction%5D.js) `→ GET /api/kol/tracker?window=&limit=`, aggregator [src/kol/tracker.js](src/kol/tracker.js), wallet list [src/kol/wallet-store.js](src/kol/wallet-store.js) (bundled [src/kol/wallets.json](src/kol/wallets.json) + admin R2 imports via `POST /api/kol/import-gmgn`), FIFO P&L engine [src/kol/wallet-pnl.js](src/kol/wallet-pnl.js), cached X follower/avatar lookup [src/kol/x-profile.js](src/kol/x-profile.js) | Live | Solana crypto KOLs ranked by realized P&L computed from each tracked wallet's own on-chain trade history (24h/7d/30d), with win rate, volume, and trade count — every number traceable to real trades, never a competitor's computed leaderboard. A wallet only shows an X handle/avatar/follower-count when an admin has explicitly attached a verified `xHandle` via `import-gmgn`'s `xHandles` map (never inferred or scraped); unattached wallets rank by wallet address alone. Rows with no configured trade source (`PUMPFUN_BOT_URL`) fall back to an imported `pnlUsd`/`winRate` labeled with its `pnlSource` rather than fabricating on-chain numbers. Prewarm cron: [api/cron/kol-tracker-refresh.js](api/cron/kol-tracker-refresh.js). || Agent Symphony (economy as generative music) | [pages/symphony.html](pages/symphony.html) `→ /symphony`, engine [src/symphony.js](src/symphony.js), grammar [src/symphony-score.js](src/symphony-score.js) | Live | The live activity bus (`GET /api/feed` + `/api/feed-stream` SSE) rendered as WebAudio generative music: one synthesized note per real platform event, voice by event type (payments pluck, coin buys land as bass, new agents chime, guard refusals play dissonance, jackpots glissando), pitch register by amount (whales sit lower), stable per-actor motif + stereo position via FNV-1a hash, all quantized to one pentatonic scale so arbitrary event streams harmonize. Canvas visualization, live ledger with real click-throughs, and a MediaRecorder tap that exports a shareable audio clip of the master bus. A burst gate collapses event floods (a sniper sweep emitting dozens of identical guard events) into one accented note per actor per 1.5s. Solo mode narrows the stream to one participant client-side (`?agent=<id>` exact, `?actor=<label>` case-insensitive), reachable from the per-row "solo" control and from the "Listen →" link on every agent profile's Wallet Story card. No audio assets, no synthetic events. Tests: [tests/symphony-score.test.js](tests/symphony-score.test.js) |diff --git a/api/_lib/glance-card.js b/api/_lib/glance-card.jsindex e66611e6f..edebab6a4 100644--- a/api/_lib/glance-card.js+++ b/api/_lib/glance-card.js@@ -203,6 +203,43 @@ export function relativeTime(then, now = new Date()) {return `${Math.floor(mo / 12)}y ago`;}+/**+ * A card that carries a message instead of an agent: the signed-out slot, the+ * unlinked widget, the account with no agent yet, the id nobody owns. It is+ * shaped exactly like an agent card so every renderer (SVG, PNG, Adaptive+ * Card, the element) draws it with no special case, and it always says what+ * to do next, because a widget that shows an error is a widget people remove.+ *+ * @param {{ name: string, headline: string, url: string, monogram?: string, description?: string|null }} notice+ */+export function noticeCard({ name, headline, url, monogram = '3', description = null }) {+ const now = new Date();+ return {+ version: GLANCE_CARD_VERSION,+ id: 'notice',+ name: String(name).slice(0, 64),+ description: description ? String(description).slice(0, 160) : null,+ url,+ createUrl: `${SITE}/create`,+ image: null,+ monogram: String(monogram).slice(0, 2),+ accent: { from: '#64748b', to: '#334155', hue: 215 },+ status: 'new',+ headline: String(headline).slice(0, 160),+ metric: { label: 'Moves today', value: 0 },+ stats: [+ { label: 'This week', value: 0 },+ { label: 'All time', value: 0 },+ { label: 'Days live', value: 0 },+ ],+ lastAction: null,+ bornAt: null,+ ageDays: null,+ updatedAt: now.toISOString(),+ ttl: GLANCE_CACHE_TTL_S,+ };+}+export async function glanceEtag(card) {const digest = await sha256([card.id, card.metric.value, card.stats.map((s) => s.value).join(','), card.status].join('|'),diff --git a/api/_lib/glance-png.js b/api/_lib/glance-png.jsnew file mode 100644index 000000000..2586e3a27--- /dev/null+++ b/api/_lib/glance-png.js@@ -0,0 +1,142 @@+/**+ * Glance card, as a PNG.+ * ----------------------+ * Android's RemoteViews, WidgetKit, and every other native widget host takes+ * a bitmap and nothing else: no SVG, no HTML, no WebGL. This module turns the+ * SVG encoding of a glance card into that bitmap with sharp (librsvg under the+ * hood), which is a few milliseconds of CPU rather than a chromium boot, and+ * which the API container already ships for thumbnails.+ *+ * Two things the SVG renderer leaves to the browser have to be settled here:+ *+ * 1. The avatar image. librsvg does not fetch over the network, so the+ * thumbnail is pulled once and inlined as a data URI. A thumbnail that+ * cannot be fetched in time degrades to the monogram, which is the same+ * fallback every other renderer uses; the card never fails on its image.+ * 2. The theme. There is no reader to honour `prefers-color-scheme`, so+ * `auto` resolves to dark, which is the palette a home screen widget+ * sits on in every launcher's default look.+ *+ * Rendered bitmaps for real agents are cached in R2 on a stable key with the+ * card's ETag in the object metadata: a stale object is overwritten in place+ * rather than piling up one key per metric change, and a cache that is not+ * configured or not reachable simply means rendering again, never an error.+ */++import sharp from 'sharp';+import { renderGlanceSvg, GLANCE_SIZES } from './glance-svg.js';+import { glanceEtag } from './glance-card.js';+import { getObjectWithMetadata, objectStorageConfigured, putObject } from './r2.js';++// Scale 2 is the density a modern phone draws at; 3 covers xxhdpi without the+// bitmap outgrowing what RemoteViews will ship across Binder.+export const GLANCE_PNG_SCALES = [1, 2, 3];+const DEFAULT_SCALE = 2;+const IMAGE_TIMEOUT_MS = 6000;+const IMAGE_MAX_BYTES = 4 * 1024 * 1024;+const CACHE_PREFIX = 'glance/png/v1';++/**+ * Resolve the query-string knobs a PNG caller can set.+ * @param {URLSearchParams} params+ */+export function pngOptions(params) {+ const size = GLANCE_SIZES[params.get('size')] ? params.get('size') : 'medium';+ const theme = params.get('theme') === 'light' ? 'light' : 'dark';+ const scale = GLANCE_PNG_SCALES.includes(Number(params.get('scale')))+ ? Number(params.get('scale'))+ : DEFAULT_SCALE;+ return { size, theme, scale };+}++/**+ * Fetch the card's thumbnail and return it as a data URI, or null when it+ * cannot be had within budget. The URL is the platform's own CDN (it came out+ * of thumbnailUrl()), so this is a first-party fetch, not user input.+ */+async function inlineImage(url) {+ if (!url) return null;+ try {+ const res = await fetch(url, {+ signal: AbortSignal.timeout(IMAGE_TIMEOUT_MS),+ headers: { accept: 'image/*' },+ });+ if (!res.ok) return null;+ const type = res.headers.get('content-type') || '';+ if (!type.startsWith('image/')) return null;+ const length = Number(res.headers.get('content-length') || 0);+ if (length > IMAGE_MAX_BYTES) return null;+ const bytes = Buffer.from(await res.arrayBuffer());+ if (bytes.length > IMAGE_MAX_BYTES) return null;+ // librsvg decodes PNG and JPEG data URIs; anything else (WebP, AVIF) is+ // transcoded so the portrait never comes out as an empty square.+ const mime = type.split(';')[0].trim();+ if (mime === 'image/png' || mime === 'image/jpeg') {+ return `data:${mime};base64,${bytes.toString('base64')}`;+ }+ const png = await sharp(bytes).png().toBuffer();+ return `data:image/png;base64,${png.toString('base64')}`;+ } catch {+ return null;+ }+}++/**+ * Rasterize a card. Pure apart from the thumbnail fetch: no cache, no+ * database, so the tests can run it against a built card.+ *+ * @param {object} card a model from buildGlanceCard() or noticeCard()+ * @param {{ size?: string, theme?: 'light'|'dark', scale?: number }} [opts]+ * @returns {Promise<{ png: Buffer, width: number, height: number }>}+ */+export async function rasterizeGlanceCard(card, { size = 'medium', theme = 'dark', scale = DEFAULT_SCALE } = {}) {+ const dim = GLANCE_SIZES[size] || GLANCE_SIZES.medium;+ const image = await inlineImage(card.image);+ const svg = renderGlanceSvg({ ...card, image }, { size, theme });+ const png = await sharp(Buffer.from(svg), { density: 72 * scale })+ .resize(dim.w * scale, dim.h * scale)+ .png({ compressionLevel: 9 })+ .toBuffer();+ return { png, width: dim.w * scale, height: dim.h * scale };+}++function cacheKey(card, { size, theme, scale }) {+ return `${CACHE_PREFIX}/${card.id}/${size}-${theme}-${scale}x.png`;+}++/**+ * The PNG for a real agent card, through the R2 cache. Notice cards (id+ * "notice") are rendered every time: they carry no image and take a+ * millisecond, and caching them would mean one key per message.+ *+ * @returns {Promise<{ png: Buffer, width: number, height: number, etag: string, cache: 'hit'|'miss'|'off' }>}+ */+export async function glancePng(card, opts) {+ const etag = await glanceEtag(card);+ // Object metadata travels as an HTTP header, so the stamp is the ETag's+ // digest alone, without the weak-validator prefix and quotes.+ const stamp = etag.replace(/[^a-z0-9-]/gi, '');+ const dim = GLANCE_SIZES[opts.size] || GLANCE_SIZES.medium;+ const cacheable = card.id !== 'notice' && card.id !== 'missing' && objectStorageConfigured();+ const key = cacheable ? cacheKey(card, opts) : null;++ if (key) {+ try {+ const hit = await getObjectWithMetadata(key);+ if (hit && hit.metadata.etag === stamp && hit.body.length > 0) {+ return { png: hit.body, width: dim.w * opts.scale, height: dim.h * opts.scale, etag, cache: 'hit' };+ }+ } catch {+ /* a cache read failure is a miss, never a failed card */+ }+ }++ const rendered = await rasterizeGlanceCard(card, opts);+ if (key) {+ // Written after the bytes are in hand and served from those same bytes:+ // nothing ever points at this key before the object exists, which is the+ // thumbnail rule (docs/avatar-thumbnails.md) applied to a cache.+ putObject({ key, body: rendered.png, contentType: 'image/png', metadata: { etag: stamp } }).catch(() => {});+ }+ return { ...rendered, etag, cache: key ? 'miss' : 'off' };+}diff --git a/api/_lib/glance-svg.js b/api/_lib/glance-svg.jsindex 95d3d0016..4f05c20e1 100644--- a/api/_lib/glance-svg.js+++ b/api/_lib/glance-svg.js@@ -100,11 +100,19 @@ ${small ? smallBody(card, ns) : wideBody(card, ns, dim, large)}}function themeCss(theme, ns) {+ // A fixed theme writes literal colors into the rules. Browsers would accept+ // `var()` too, but librsvg (which rasterizes the PNG encoding through sharp)+ // silently paints an unresolved custom property black and ignores+ // `prefers-color-scheme`, so a fixed theme is the only shape every renderer+ // agrees on. `auto` keeps the variables and the media query because that is+ // the one case where the reader's browser has to pick the palette.+ const rules = (t) =>+ `.${ns} .bg{fill:${t.bg}}.${ns} .panel{fill:${t.panel}}.${ns} .t{fill:${t.text}}.${ns} .m{fill:${t.muted}}.${ns} .line{stroke:${t.line}}`;+ if (theme === 'light') return rules(LIGHT);+ if (theme === 'dark') return rules(DARK);const vars = (t) =>`--bg:${t.bg};--panel:${t.panel};--text:${t.text};--muted:${t.muted};--line:${t.line}`;const base = `.${ns} .bg{fill:var(--bg)}.${ns} .panel{fill:var(--panel)}.${ns} .t{fill:var(--text)}.${ns} .m{fill:var(--muted)}.${ns} .line{stroke:var(--line)}`;- if (theme === 'light') return `.${ns}{${vars(LIGHT)}}${base}`;- if (theme === 'dark') return `.${ns}{${vars(DARK)}}${base}`;return `.${ns}{${vars(LIGHT)}}@media (prefers-color-scheme:dark){.${ns}{${vars(DARK)}}}${base}`;}diff --git a/api/_lib/glance-tokens.js b/api/_lib/glance-tokens.jsnew file mode 100644index 000000000..858e77519--- /dev/null+++ b/api/_lib/glance-tokens.js@@ -0,0 +1,155 @@+/**+ * Glance widget tokens.+ * ---------------------+ * The credential a native widget carries. A session cookie cannot do this+ * job: Android's WorkManager fetches the card from an OS process with no+ * cookie jar, and a widget stays on a phone long after every session that+ * minted it has expired. So the owner mints a token on /glance, the app+ * stores it, and the widget presents it on every read.+ *+ * Scope is the whole design: a token reads its owner's glance card and+ * nothing else. It is never accepted by any other endpoint, which is why it+ * lives in its own table with its own prefix rather than in the OAuth or API+ * key stores.+ *+ * plaintext = "glw_" + 32 url-safe characters (shown once, at creation)+ * prefix = the first 10 characters (what the revoke list shows)+ * hash = hex(sha256(plaintext)) (the only thing stored)+ */++import { sql } from './db.js';+import { randomToken, sha256 } from './crypto.js';++export const GLANCE_TOKEN_PREFIX = 'glw_';+export const GLANCE_TOKEN_PLATFORMS = new Set(['android', 'macos', 'ios', 'other']);+// Enough for every device a person owns, small enough that a script cannot+// fill the table through one account.+export const GLANCE_TOKEN_MAX_ACTIVE = 12;+const TOKEN_RE = /^glw_[A-Za-z0-9_-]{32}$/;+// `last_used_at` is for the owner's revoke list ("last seen 2h ago"), so a+// write per read would be waste: it moves at most once per five minutes.+const LAST_USED_STEP_MS = 5 * 60 * 1000;++/** @param {unknown} value */+export function looksLikeGlanceToken(value) {+ return typeof value === 'string' && TOKEN_RE.test(value);+}++/** Deterministic plaintext shape, so the tests can pin it without a database. */+export function mintPlaintext() {+ return GLANCE_TOKEN_PREFIX + randomToken(24);+}++export function prefixOf(plaintext) {+ return plaintext.slice(0, 10);+}++function rowView(row) {+ return {+ id: row.id,+ prefix: row.token_prefix,+ label: row.label,+ platform: row.platform,+ agentId: row.agent_id || null,+ createdAt: row.created_at,+ lastUsedAt: row.last_used_at || null,+ };+}++/**+ * Mint a token for a signed-in owner. Returns the plaintext exactly once.+ * @param {{ userId: string, label?: string, platform?: string, agentId?: string|null }} input+ */+export async function createGlanceToken({ userId, label, platform, agentId = null }) {+ const [{ active }] = await sql`+ SELECT count(*)::int AS active+ FROM glance_widget_tokens+ WHERE user_id = ${userId} AND revoked_at IS NULL+ `;+ if (active >= GLANCE_TOKEN_MAX_ACTIVE) {+ const err = new Error(`you already have ${GLANCE_TOKEN_MAX_ACTIVE} linked widgets; revoke one first`);+ err.code = 'too_many_tokens';+ err.status = 409;+ throw err;+ }++ const plaintext = mintPlaintext();+ const hash = await sha256(plaintext);+ const cleanLabel = String(label || '').trim().slice(0, 60) || 'Home screen widget';+ const cleanPlatform = GLANCE_TOKEN_PLATFORMS.has(platform) ? platform : 'other';++ const [row] = await sql`+ INSERT INTO glance_widget_tokens (user_id, token_hash, token_prefix, label, platform, agent_id)+ VALUES (${userId}, ${hash}, ${prefixOf(plaintext)}, ${cleanLabel}, ${cleanPlatform}, ${agentId})+ RETURNING id, token_prefix, label, platform, agent_id, created_at, last_used_at+ `;+ return { ...rowView(row), token: plaintext };+}++/**+ * Resolve a presented token to its owner. Returns null for anything that is+ * not a live token: wrong shape, unknown, or revoked. The caller renders the+ * "link again" card for null; it never learns which of those it was, and+ * neither does the network.+ *+ * @param {unknown} plaintext+ * @returns {Promise<null | { id: string, userId: string, agentId: string|null }>}+ */+export async function resolveGlanceToken(plaintext) {+ if (!looksLikeGlanceToken(plaintext)) return null;+ const hash = await sha256(plaintext);+ const [row] = await sql`+ SELECT id, user_id, agent_id, last_used_at+ FROM glance_widget_tokens+ WHERE token_hash = ${hash} AND revoked_at IS NULL+ LIMIT 1+ `;+ if (!row) return null;++ const lastUsed = row.last_used_at ? new Date(row.last_used_at).getTime() : 0;+ if (Date.now() - lastUsed > LAST_USED_STEP_MS) {+ // Best effort: the read must not wait on, or fail with, a bookkeeping write.+ sql`UPDATE glance_widget_tokens SET last_used_at = now() WHERE id = ${row.id}`.catch(() => {});+ }+ return { id: row.id, userId: row.user_id, agentId: row.agent_id || null };+}++/** The owner's live tokens, newest first, for the revoke list on /glance. */+export async function listGlanceTokens(userId) {+ const rows = await sql`+ SELECT id, token_prefix, label, platform, agent_id, created_at, last_used_at+ FROM glance_widget_tokens+ WHERE user_id = ${userId} AND revoked_at IS NULL+ ORDER BY created_at DESC+ `;+ return rows.map(rowView);+}++/**+ * Revoke one of the owner's tokens. Returns false when the id is not theirs+ * or is already revoked, which the endpoint reports as 404 in both cases:+ * revocation is idempotent and never confirms another account's ids.+ */+export async function revokeGlanceToken({ userId, tokenId }) {+ const rows = await sql`+ UPDATE glance_widget_tokens+ SET revoked_at = now()+ WHERE id = ${tokenId} AND user_id = ${userId} AND revoked_at IS NULL+ RETURNING id+ `;+ return rows.length > 0;+}++/**+ * Point an existing token at a different owned agent (or back to "first+ * owned" with null). The widget picks the change up on its next refresh.+ */+export async function pinGlanceToken({ userId, tokenId, agentId }) {+ const rows = await sql`+ UPDATE glance_widget_tokens+ SET agent_id = ${agentId}+ WHERE id = ${tokenId} AND user_id = ${userId} AND revoked_at IS NULL+ RETURNING id+ `;+ return rows.length > 0;+}diff --git a/api/_lib/migrations/20260829120000_glance_widget_tokens.sql b/api/_lib/migrations/20260829120000_glance_widget_tokens.sqlnew file mode 100644index 000000000..c5b409fb3--- /dev/null+++ b/api/_lib/migrations/20260829120000_glance_widget_tokens.sql@@ -0,0 +1,28 @@+begin;++-- Widget tokens for the Glance card.+--+-- A home screen widget outlives a browser session: Android's WorkManager+-- fetches the card from an OS process with no cookie jar, and a phone keeps+-- the widget for months. So a widget authenticates with its own credential,+-- minted by the signed-in owner, scoped to reading their own card and nothing+-- else, and revocable from /glance without touching the session that minted+-- it. Only the sha256 of the token is stored; the plaintext is shown once at+-- creation and handed straight to the app through the threews:// link.+create table if not exists glance_widget_tokens (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null references users(id) on delete cascade,+ token_hash text not null unique, -- sha256(plaintext)+ token_prefix text not null, -- "glw_" plus six characters, for the revoke list+ label text not null, -- what the owner sees ("Pixel 7"), never required to be unique+ platform text not null default 'android', -- android | macos | ios | other+ agent_id uuid references agent_identities(id) on delete set null, -- pinned agent, null = first owned+ created_at timestamptz not null default now(),+ last_used_at timestamptz,+ revoked_at timestamptz+);++create index if not exists glance_widget_tokens_user_idx+ on glance_widget_tokens(user_id, created_at desc);++commit;diff --git a/api/_lib/r2.js b/api/_lib/r2.jsindex 6e84952e2..ad76e08dc 100644--- a/api/_lib/r2.js+++ b/api/_lib/r2.js@@ -150,6 +150,24 @@ export async function getObjectBuffer(key) {return Buffer.concat(chunks);}+// Read an object together with the user metadata it was stored with. Used by+// caches that key on a stable path and decide freshness from a stamp in the+// metadata (the glance PNG cache stores the card's ETag there), so a stale+// object is overwritten in place instead of piling up a new key per version.+// Returns null when the object does not exist.+export async function getObjectWithMetadata(key) {+ let out;+ try {+ out = await r2.send(new GetObjectCommand({ Bucket: env.S3_BUCKET, Key: key }));+ } catch (err) {+ if (err?.$metadata?.httpStatusCode === 404 || err?.name === 'NoSuchKey') return null;+ throw err;+ }+ const chunks = [];+ for await (const chunk of out.Body) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));+ return { body: Buffer.concat(chunks), metadata: out.Metadata || {}, contentType: out.ContentType || null };+}+// Read just the leading `length` bytes of an object via an HTTP Range request.// Used by the rig classifier to read a GLB's glTF JSON chunk (which lives at// the file head) without downloading the whole — potentially large — mesh.diff --git a/api/glance/card.js b/api/glance/card.jsindex 29e1d8c2e..028a15853 100644--- a/api/glance/card.js+++ b/api/glance/card.js@@ -4,14 +4,18 @@* One agent, in whatever shape the surface asking for it can render.** ?agent=<uuid> required- * &format=json | svg | adaptive default json- * &size=small | medium | large svg only, default medium- * &theme=auto | light | dark svg only, default auto+ * &format=json | svg | png | adaptive default json+ * &size=small | medium | large svg and png, default medium+ * &theme=auto | light | dark svg and png, default auto (png: dark)+ * &scale=1 | 2 | 3 png only, pixel density, default 2** json the glance card model. What the Windows 11 widgets board binds* to its Adaptive Card template, and what <agent-glance> renders.* svg a self-contained card image for a README, a Slack unfurl, an* <img>, or any widget host that only takes a picture.+ * png the same card as a bitmap, for hosts that cannot draw SVG:+ * Android RemoteViews, WidgetKit, chat clients that unfurl only+ * raster images.* adaptive a fully bound Adaptive Card, for hosts that render one without* doing their own templating.*@@ -26,8 +30,9 @@* never a broken image in someone's home screen slot.*/-import { loadGlanceCard, glanceEtag } from '../_lib/glance-card.js';+import { loadGlanceCard, glanceEtag, noticeCard } from '../_lib/glance-card.js';import { renderGlanceSvg, GLANCE_SIZES } from '../_lib/glance-svg.js';+import { glancePng, pngOptions } from '../_lib/glance-png.js';import { adaptiveCardFor } from '../_lib/glance-adaptive.js';import { cors, json, error, wrap, method, varyOn } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -40,7 +45,7 @@ import { isUuid } from '../_lib/validate.js';const CACHE = 'public, max-age=60, s-maxage=120, stale-while-revalidate=600';const CACHE_MISS = 'public, max-age=30, s-maxage=60';-const FORMATS = new Set(['json', 'svg', 'adaptive']);+const FORMATS = new Set(['json', 'svg', 'png', 'adaptive']);const THEMES = new Set(['auto', 'light', 'dark']);export default wrap(async (req, res) => {@@ -80,6 +85,7 @@ export default wrap(async (req, res) => {res.setHeader('content-type', 'image/svg+xml; charset=utf-8');return res.end(renderGlanceSvg(card, { size, theme }));}+ if (format === 'png') return sendPng(res, 200, card, url.searchParams);if (format === 'adaptive') return json(res, 200, adaptiveCardFor(card));return json(res, 200, card);});@@ -90,27 +96,28 @@ export default wrap(async (req, res) => {* it can branch on.*/function notFound(res, format, size, theme, message) {- if (format !== 'svg') return error(res, 404, 'not_found', message);- const placeholder = {- id: 'missing',+ if (format !== 'svg' && format !== 'png') return error(res, 404, 'not_found', message);+ const placeholder = noticeCard({name: 'Agent not found',description: message,headline: message,url: 'https://three.ws/agents',- image: null,- monogram: '3',- accent: { from: '#64748b', to: '#334155', hue: 215 },- status: 'new',- metric: { label: 'Moves today', value: 0 },- stats: [- { label: 'This week', value: 0 },- { label: 'All time', value: 0 },- { label: 'Skills', value: 0 },- ],- lastAction: null,- };+ });+ if (format === 'png') return sendPng(res, 404, placeholder, new URLSearchParams({ size, theme }));res.statusCode = 404;res.setHeader('content-type', 'image/svg+xml; charset=utf-8');res.setHeader('cache-control', 'public, max-age=60');return res.end(renderGlanceSvg(placeholder, { size, theme }));}++async function sendPng(res, status, card, params) {+ const { png, width, height, cache } = await glancePng(card, pngOptions(params));+ res.statusCode = status;+ res.setHeader('content-type', 'image/png');+ res.setHeader('content-length', String(png.length));+ res.setHeader('x-glance-width', String(width));+ res.setHeader('x-glance-height', String(height));+ res.setHeader('x-glance-cache', cache);+ if (status !== 200) res.setHeader('cache-control', 'public, max-age=60');+ return res.end(png);+}diff --git a/api/glance/mine.js b/api/glance/mine.jsindex 6a2ba9d96..767d2c3ec 100644--- a/api/glance/mine.js+++ b/api/glance/mine.js@@ -2,27 +2,104 @@* GET /api/glance/mine* --------------------* The card for the signed-in owner's agent, plus the list of agents they could- * point a widget at instead. This is what the widget service worker calls: a- * home screen slot has no UI to pick an agent in, so the platform answers- * "your agent" and lets the owner change it from the page.+ * point a widget at instead. This is what the widget hosts call: a home+ * screen slot has no UI to pick an agent in, so the platform answers "your+ * agent" and lets the owner change it from the page.*- * ?agent=<uuid> pin a specific agent (must be one the caller owns)+ * Who is asking, in order:+ * 1. a widget token (`Authorization: Bearer glw_…` or `?token=glw_…`), the+ * credential a native widget carries because it has no session;+ * 2. the session cookie, which is what the Windows widget worker sends.*- * Signed out is a designed answer, not a 401: the widget shows a card that- * says sign in, because a widget that renders an error is a widget people- * remove. The response carries `signedIn` so the caller can branch.+ * ?agent=<uuid> pin a specific agent (must be one the caller owns)+ * ?format=json | png default json+ * &size=small|medium|large png only, default medium+ * &theme=dark|light png only, default dark+ * &scale=1|2|3 png only, default 2 (pixel density)+ *+ * Every state is a designed answer, never a 401: signed out, an unlinked or+ * revoked token, and an account with no agent yet all get a card that says+ * what to do next, because a widget that renders an error is a widget people+ * remove. JSON carries `state` so a caller can branch; PNG carries the same+ * in `x-glance-state` plus the tap target in `x-glance-url`, so a native+ * widget learns everything it needs from the one request that fetched the+ * bitmap.*/-import { loadGlanceCard } from '../_lib/glance-card.js';-import { getSessionUser } from '../_lib/auth.js';+import { loadGlanceCard, noticeCard } from '../_lib/glance-card.js';+import { glancePng, pngOptions } from '../_lib/glance-png.js';+import { resolveGlanceToken, looksLikeGlanceToken } from '../_lib/glance-tokens.js';+import { getSessionUser, extractBearer } from '../_lib/auth.js';import { sql } from '../_lib/db.js';import { cors, json, wrap, method, error } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { isUuid } from '../_lib/validate.js';+const SITE = 'https://three.ws';+const SIGN_IN_URL = `${SITE}/login?next=%2Fglance`;+const LINK_URL = `${SITE}/glance?link=android`;+const CREATE_URL = `${SITE}/create`;++export const GLANCE_STATES = {+ signedOut: 'signed-out',+ unlinked: 'unlinked',+ noAgent: 'no-agent',+ agent: 'agent',+};++/** The notice card for each non-agent state. Exported for the tests. */+export function stateCard(state) {+ if (state === GLANCE_STATES.unlinked) {+ return noticeCard({+ name: 'Widget unlinked',+ headline: 'Tap to link this widget to your account again.',+ description: 'This widget no longer has access to your agent.',+ url: LINK_URL,+ });+ }+ if (state === GLANCE_STATES.noAgent) {+ return noticeCard({+ name: 'No agent yet',+ headline: 'Tap to create your first agent.',+ description: 'Your agent will live here, with its moves for the day.',+ url: CREATE_URL,+ });+ }+ return noticeCard({+ name: 'three.ws',+ headline: 'Sign in to see your agent here.',+ description: 'Your agent, one live number, one tap back in.',+ url: SIGN_IN_URL,+ });+}++/**+ * Resolve the caller. A token that is presented but not live answers the+ * unlinked state even when a session cookie is also present: the widget that+ * sent it needs to learn that its credential is gone.+ */+async function resolveCaller(req, res, url) {+ // Only a bearer shaped like a widget token is one; any other bearer (an+ // OAuth access token, an API key) is ignored here and the session decides.+ // An explicit ?token= is always a widget's claim, so a malformed one is+ // answered as unlinked rather than as a stranger's signed-out card.+ const bearer = extractBearer(req);+ const query = url.searchParams.get('token') || '';+ const presented = looksLikeGlanceToken(bearer) ? bearer : query;+ if (presented) {+ const token = looksLikeGlanceToken(presented) ? await resolveGlanceToken(presented) : null;+ if (!token) return { state: GLANCE_STATES.unlinked };+ return { userId: token.userId, pinnedAgentId: token.agentId, via: 'token' };+ }+ const session = await getSessionUser(req, res);+ if (!session) return { state: GLANCE_STATES.signedOut };+ return { userId: session.id, pinnedAgentId: null, via: 'session' };+}+export default wrap(async (req, res) => {- // credentials: the widget SW sends the session cookie, so the response is- // per-user and must never be shared by a cache.+ // credentials: the Windows widget worker sends the session cookie, and a+ // native widget sends its token, so the response is per-caller and must+ // never be shared by a cache.if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET'])) return;res.setHeader('cache-control', 'private, no-store');@@ -30,38 +107,77 @@ export default wrap(async (req, res) => {const rl = await limits.widgetRead(clientIp(req));if (!rl.success) return error(res, 429, 'rate_limited', 'too many card reads');- const session = await getSessionUser(req, res);- if (!session) {- return json(res, 200, {- signedIn: false,- card: null,- agents: [],- signInUrl: 'https://three.ws/login',- createUrl: 'https://three.ws/create',- });- }+ const url = new URL(req.url, 'http://x');+ const format = url.searchParams.get('format') === 'png' ? 'png' : 'json';++ const caller = await resolveCaller(req, res, url);+ if (caller.state) return respond(res, format, url, { state: caller.state, card: stateCard(caller.state), agents: [] });const owned = await sql`SELECT id, nameFROM agent_identities- WHERE user_id = ${session.id} AND deleted_at IS NULL+ WHERE user_id = ${caller.userId} AND deleted_at IS NULLORDER BY created_at ASCLIMIT 25`;- const url = new URL(req.url, 'http://x');- const requested = url.searchParams.get('agent') || '';// A pinned agent the caller does not own falls back to their own first// agent rather than erroring: the widget keeps working after an agent is- // deleted or a different account signs in on the same device.+ // deleted or a different account signs in on the same device. The query+ // string wins over the token's pin so the page can preview any owned agent.+ const requested = url.searchParams.get('agent') || caller.pinnedAgentId || '';const pinned = isUuid(requested) && owned.some((a) => a.id === requested) ? requested : null;const target = pinned || owned[0]?.id || null;+ if (!target) {+ return respond(res, format, url, { state: GLANCE_STATES.noAgent, card: stateCard(GLANCE_STATES.noAgent), agents: [] });+ }++ const card = await loadGlanceCard(target);+ if (!card) {+ return respond(res, format, url, { state: GLANCE_STATES.noAgent, card: stateCard(GLANCE_STATES.noAgent), agents: owned });+ }+ return respond(res, format, url, { state: GLANCE_STATES.agent, card, agents: owned, via: caller.via });+});++async function respond(res, format, url, { state, card, agents, via = null }) {+ if (format === 'png') {+ const opts = pngOptions(url.searchParams);+ const { png, width, height, etag, cache } = await glancePng(card, opts);+ res.statusCode = 200;+ res.setHeader('content-type', 'image/png');+ res.setHeader('content-length', String(png.length));+ res.setHeader('etag', etag);+ res.setHeader('x-glance-state', state);+ res.setHeader('x-glance-url', card.url);+ res.setHeader('x-glance-name', headerSafe(card.name));+ res.setHeader('x-glance-metric', `${card.metric.value} ${headerSafe(card.metric.label)}`);+ res.setHeader('x-glance-agent', state === GLANCE_STATES.agent ? card.id : '');+ res.setHeader('x-glance-updated', card.updatedAt);+ res.setHeader('x-glance-width', String(width));+ res.setHeader('x-glance-height', String(height));+ res.setHeader('x-glance-cache', cache);+ return res.end(png);+ }++ const signedIn = state !== GLANCE_STATES.signedOut && state !== GLANCE_STATES.unlinked;return json(res, 200, {- signedIn: true,- card: target ? await loadGlanceCard(target) : null,- agents: owned.map((a) => ({ id: a.id, name: a.name })),- signInUrl: 'https://three.ws/login',- createUrl: 'https://three.ws/create',+ signedIn,+ state,+ via,+ card: state === GLANCE_STATES.agent ? card : null,+ notice: state === GLANCE_STATES.agent ? null : card,+ agents: agents.map((a) => ({ id: a.id, name: a.name })),+ signInUrl: SIGN_IN_URL,+ createUrl: CREATE_URL,+ linkUrl: LINK_URL,});-});+}++// Header values are ASCII: agent names are anything, so the header carries a+// readable approximation and the bitmap carries the real name.+function headerSafe(value) {+ return String(value ?? '')+ .replace(/[^\x20-\x7e]/g, '')+ .slice(0, 120);+}diff --git a/api/glance/token.js b/api/glance/token.jsnew file mode 100644index 000000000..77ae52324--- /dev/null+++ b/api/glance/token.js@@ -0,0 +1,120 @@+/**+ * /api/glance/token+ * -----------------+ * The owner's widget tokens: the credential a native home screen widget+ * carries instead of a session (see api/_lib/glance-tokens.js).+ *+ * GET list the caller's live tokens (prefix, label, platform, last seen)+ * POST mint one: { label?, platform?, agent? }. Answers the plaintext+ * exactly once, plus the Android deep link that hands it to the app.+ * PATCH { id, agent } repoint a token at another owned agent (null = first)+ * DELETE ?id=<uuid> revoke one. Idempotent; 404 for an id that is not+ * the caller's live token.+ *+ * Session only, same-site only: a token is a long-lived credential, so the+ * page that mints it has to be ours. Bearer callers (OAuth, API keys) are not+ * accepted here on purpose; a programmatic client that wants the card reads+ * /api/glance/card with the agent id, which is public.+ */++import { getSessionUser, isSameSiteOrigin } from '../_lib/auth.js';+import {+ createGlanceToken,+ listGlanceTokens,+ revokeGlanceToken,+ pinGlanceToken,+ GLANCE_TOKEN_PLATFORMS,+} from '../_lib/glance-tokens.js';+import { sql } from '../_lib/db.js';+import { cors, json, wrap, method, error, readJson } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { isUuid } from '../_lib/validate.js';++export const ANDROID_PACKAGE = 'ws.three.app';++/**+ * The intent: URL Chrome turns into a launch of the app's link activity. The+ * token rides in the query of a custom-scheme URI that only our package can+ * claim; the fallback sends a phone without the app to the install page.+ */+export function androidLinkUrl(token) {+ const fallback = encodeURIComponent('https://three.ws/seeker?utm_source=glance_link');+ return `intent://glance/link?token=${encodeURIComponent(token)}#Intent;scheme=threews;package=${ANDROID_PACKAGE};S.browser_fallback_url=${fallback};end`;+}++async function ownsAgent(userId, agentId) {+ const rows = await sql`+ SELECT 1 FROM agent_identities+ WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL+ LIMIT 1+ `;+ return rows.length > 0;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,PATCH,DELETE,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST', 'PATCH', 'DELETE'])) return;+ res.setHeader('cache-control', 'private, no-store');++ const session = await getSessionUser(req, res);+ if (!session) return error(res, 401, 'unauthorized', 'sign in to manage widget tokens');+ if (req.method !== 'GET' && !isSameSiteOrigin(req)) {+ return error(res, 403, 'forbidden', 'cross-site request blocked');+ }++ const rl = await limits.widgetWrite(session.id);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many widget token requests');++ if (req.method === 'GET') {+ return json(res, 200, { tokens: await listGlanceTokens(session.id) });+ }++ if (req.method === 'DELETE') {+ const url = new URL(req.url, 'http://x');+ const id = url.searchParams.get('id') || '';+ if (!isUuid(id)) return error(res, 400, 'bad_request', 'id must be a token id');+ const revoked = await revokeGlanceToken({ userId: session.id, tokenId: id });+ if (!revoked) return error(res, 404, 'not_found', 'no live token with that id');+ return json(res, 200, { revoked: true, id });+ }++ let body;+ try {+ body = await readJson(req, 4096);+ } catch (e) {+ return error(res, e.status || 400, 'bad_request', e.message);+ }++ let agentId = null;+ if (body.agent !== undefined && body.agent !== null && body.agent !== '') {+ if (!isUuid(body.agent)) return error(res, 400, 'bad_request', 'agent must be an agent id');+ if (!(await ownsAgent(session.id, body.agent))) {+ return error(res, 404, 'not_found', 'that agent is not yours');+ }+ agentId = body.agent;+ }++ if (req.method === 'PATCH') {+ if (!isUuid(body.id)) return error(res, 400, 'bad_request', 'id must be a token id');+ const pinned = await pinGlanceToken({ userId: session.id, tokenId: body.id, agentId });+ if (!pinned) return error(res, 404, 'not_found', 'no live token with that id');+ return json(res, 200, { id: body.id, agentId });+ }++ const platform = GLANCE_TOKEN_PLATFORMS.has(body.platform) ? body.platform : 'other';+ try {+ const minted = await createGlanceToken({+ userId: session.id,+ label: typeof body.label === 'string' ? body.label : '',+ platform,+ agentId,+ });+ return json(res, 201, {+ ...minted,+ links: { android: androidLinkUrl(minted.token) },+ });+ } catch (e) {+ if (e.code === 'too_many_tokens') return error(res, 409, e.code, e.message);+ throw e;+ }+});diff --git a/data/changelog.json b/data/changelog.jsonindex 569b60614..871a18199 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-08-29",+ "title": "Your agent on the Android home screen",+ "summary": "The three.ws Android app (1.1) now ships a home screen widget. It shows your agent's avatar, its name, and how many moves it made today, refreshes itself in the background about every half hour without opening the app, keeps the last card it saw when the phone is offline, and opens your agent with a tap. Link a phone from the Glance page in one tap; every linked widget is listed there with a revoke button, because each one carries its own token that can read your card and nothing else. The Glance card also comes as a PNG now, which is what any native widget host, chat client or image-only surface needs.",+ "tags": [+ "feature"+ ],+ "link": "/docs/native-widgets"+ },{"date": "2026-08-28","title": "three.ws is an Android app you can install today",diff --git a/data/pages.json b/data/pages.jsonindex 9615a2fe9..ac084e524 100644--- a/data/pages.json+++ b/data/pages.json@@ -778,6 +778,14 @@"changefreq": "monthly","added": "2026-08-28"},+ {+ "path": "/docs/native-widgets",+ "title": "Native widgets: your agent on the home screen",+ "description": "Put your three.ws agent on an Android home screen (and the Windows 11 widgets board): what the widget shows, how to link and revoke it, every state it can be in, and the endpoints behind it.",+ "priority": 0.6,+ "changefreq": "monthly",+ "added": "2026-08-29"+ },{"path": "/glance","title": "Glance",diff --git a/docs/api-reference.md b/docs/api-reference.mdindex df846bd04..1b845cb83 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -7189,6 +7189,46 @@ data: {"id":"6a29...","text":"Deploy is green","importance":80,"tone":"alert"}---+## Glance API++One agent reduced to what fits in an operating-system widget slot: name, avatar, one live number (moves in the last 24 hours), and a link back. Powers the Windows 11 widget, the Android home screen widget, README badges and the `<agent-glance>` element. Spec: [specs/GLANCE_CARD.md](../specs/GLANCE_CARD.md). Guide: [glance.md](glance.md), [native-widgets.md](native-widgets.md).++### Public card++```+GET /api/glance/card?agent=<uuid>&format=json|svg|png|adaptive&size=small|medium|large&theme=auto|light|dark&scale=1|2|3+```++No auth. `json` is the card model, `svg` a self-contained image, `png` a bitmap (`scale` is pixel density, `theme` resolves `auto` to dark), `adaptive` a bound Adaptive Card 1.6. Carries an `ETag` and answers `304` to `if-none-match`. An unknown agent answers `404`; for `svg` and `png` the body is still a real card that says so.++### My card++```+GET /api/glance/mine?format=json|png&agent=<uuid>&size=…&theme=dark|light&scale=…+Authorization: Bearer glw_… (widget token) or the session cookie+```++Always `200`. JSON: `{ signedIn, state, via, card, notice, agents, signInUrl, createUrl, linkUrl }`, `state` one of `agent`, `signed-out`, `unlinked`, `no-agent`. PNG: the card bitmap for whichever state applies, with `x-glance-state`, `x-glance-url` (tap target), `x-glance-name`, `x-glance-metric`, `x-glance-agent`, `x-glance-updated` headers. `cache-control: private, no-store`.++### Widget tokens++```+POST /api/glance/token { label?, platform?: android|macos|ios|other, agent?: uuid }+GET /api/glance/token+PATCH /api/glance/token { id, agent: uuid|null }+DELETE /api/glance/token?id=<uuid>+```++Session cookie required; writes must be same-site. `POST` answers `201` with `{ id, prefix, label, platform, agentId, createdAt, lastUsedAt, token, links: { android } }`. `token` is shown exactly once; `links.android` is the `intent://glance/link?token=…#Intent;scheme=threews;package=ws.three.app;…;end` URL that hands it to the Android app. At most 12 live tokens per account (`409 too_many_tokens`). `GET` answers `{ tokens: [...] }` without plaintexts. `DELETE` answers `{ revoked: true, id }`, or `404` for an id that is not the caller's live token.++| Error | Status | Meaning |+| --- | --- | --- |+| `unauthorized` | 401 | no session |+| `forbidden` | 403 | write from another origin |+| `not_found` | 404 | token or agent is not the caller's |+| `too_many_tokens` | 409 | 12 live tokens already |+| `rate_limited` | 429 | over the per-account write limit |+## PaginationPaginated list endpoints use `limit`/`offset` query parameters unless noted otherwise (each endpoint's own parameter table is authoritative; some small per-user lists, like `/api/agents` and `/api/widgets`, return everything with no pagination).diff --git a/docs/glance.md b/docs/glance.mdindex 01cb80e69..01d28c9ca 100644--- a/docs/glance.md+++ b/docs/glance.md@@ -65,9 +65,10 @@ Public, cacheable, side-effect free, no session required.| Parameter | Values | Default || --- | --- | --- || `agent` | agent uuid (required) | |-| `format` | `json`, `svg`, `adaptive` | `json` |-| `size` | `small` (240x240), `medium` (480x200), `large` (480x300). SVG only | `medium` |-| `theme` | `auto`, `light`, `dark`. SVG only | `auto` |+| `format` | `json`, `svg`, `png`, `adaptive` | `json` |+| `size` | `small` (240x240), `medium` (480x200), `large` (480x300). SVG and PNG | `medium` |+| `theme` | `auto`, `light`, `dark`. SVG and PNG (`auto` renders dark as PNG) | `auto` |+| `scale` | `1`, `2`, `3`: pixel density. PNG only | `2` |```bashcurl -s "https://three.ws/api/glance/card?agent=<agent-id>" | jq '.metric'@@ -80,9 +81,19 @@ The response carries an `ETag`; send it back as `if-none-match` and you get a `3A missing agent answers `404` with a real card that says so, not a broken image. That matters when the card is sitting in someone's home screen slot.+`format=png` is the same card as a bitmap, for hosts that cannot draw SVG (Android's RemoteViews, WidgetKit, chat clients that only unfurl raster images). It is rasterized with sharp from the SVG, cached in object storage per agent, size, theme and density, and re-rendered only when the card's ETag changes.+### `GET /api/glance/mine`-Session-scoped. Returns `{ signedIn, card, agents, signInUrl, createUrl }` for the caller's own agent, plus the list of agents they own so a widget can be pointed at a different one. Signed out is a `200` with `signedIn: false`, not a `401`: a widget that renders an error is a widget people remove.+The caller's own agent, plus the list of agents they own so a widget can be pointed at a different one. Two ways to say who is asking: the session cookie (what the Windows widget worker sends), or a widget token as `Authorization: Bearer glw_…` (what a native widget sends, because it has no session; see [native-widgets.md](native-widgets.md#how-the-widget-authenticates)).++Every state is a `200` with a designed card, never a `401`: a widget that renders an error is a widget people remove. `state` is one of `agent`, `signed-out`, `unlinked` (a revoked or unknown token), or `no-agent`; for the three non-agent states `card` is `null` and `notice` carries a card that says what to do next, with a tap target that does it.++`format=png` (with `size`, `theme`, `scale` as above) returns the bitmap for whichever state applies, with `x-glance-state`, `x-glance-url` (the tap target), `x-glance-name`, `x-glance-metric` and `x-glance-agent` in the headers, so a native widget learns everything from the one request that fetched the image.++### `POST | GET | PATCH | DELETE /api/glance/token`++The widget tokens. Session and same-site only. `POST { label?, platform?, agent? }` mints one and answers the plaintext exactly once, plus `links.android`, the `intent://` URL that hands it to the Android app. `GET` lists the caller's live tokens (prefix, label, platform, last seen), `PATCH { id, agent }` repoints one, `DELETE ?id=` revokes one. The revoke list on [/glance](https://three.ws/glance#devices) is this endpoint.### `GET /api/glance/template`@@ -150,8 +161,14 @@ Zero dependencies, bounded deadlines on every call, and a `GlanceError` that car---+## On an Android home screen++The three.ws Android app (1.1 and later) ships an **Agent glance** home screen widget: link the phone from [/glance](https://three.ws/glance#android), then add the widget from the launcher's picker. It fetches `/api/glance/mine?format=png` with its own token through WorkManager, keeps the last card when offline, and opens the agent on tap. Sizes, states, revocation and the native sources are all in [native-widgets.md](native-widgets.md#android).++---+## Where this is going-Glance is phase 5 of the [roadmap](https://github.com/nirholas/three.ws/blob/main/README.md#roadmap). Windows 11 and the web are live. Android is next (the signed `ws.three.app` shell already ships, the app widget provider is the remaining piece), then macOS and iOS through a shared WidgetKit extension. The scoped work order is [prompts/roadmap/native-widgets.md](https://github.com/nirholas/three.ws/blob/main/prompts/roadmap/native-widgets.md).+Glance is phase 5 of the [roadmap](https://github.com/nirholas/three.ws/blob/main/README.md#roadmap). Windows 11, Android and the web are live. macOS and iOS follow through a shared WidgetKit extension against the same PNG endpoint and the same widget token; the scoped work order is [prompts/roadmap/native-widgets.md](https://github.com/nirholas/three.ws/blob/main/prompts/roadmap/native-widgets.md).Every one of those surfaces consumes the endpoint documented above. The card is the contract; the hosts are just slots.diff --git a/docs/native-widgets.md b/docs/native-widgets.mdnew file mode 100644index 000000000..e19e47244--- /dev/null+++ b/docs/native-widgets.md@@ -0,0 +1,110 @@+# Native widgets: your agent on the home screen++A three.ws agent earns a slot on your phone's home screen. The widget shows the agent's+avatar, its name, and one live number (how many moves it made today), and a tap opens the app+on that agent. The system refreshes it in the background about every 30 minutes; you never+have to open the app to see the number move.++This page covers the native, operating-system widgets. The embeddable web widgets that put a+live 3D agent inside a web page are a different product: see [widgets.md](widgets.md).++## What the widget shows++Every platform renders the same card, the [Glance card](glance.md):++- the agent's avatar thumbnail (or a generated monogram when the avatar is private),+- the agent's name and description,+- **Moves today**: the number of real actions the agent logged in the last 24 hours,+- this week's and all-time totals, and the agent's skill count,+- when it last acted, and a status dot (green: active today, amber: idle, grey: never acted).++No widget host on any platform can run WebGL, so the card is a bitmap the server renders+(`GET /api/glance/mine?format=png`) and the 3D avatar stays one tap away on the agent page.++## Android++Requires the three.ws Android app, version 1.1 or later ([seeker-app.md](seeker-app.md)).++1. Open [three.ws/glance](https://three.ws/glance) on the phone, signed in, and tap+ **Link this phone**. The page mints a widget token and hands it to the app; Android asks+ whether to add the widget to the home screen right away.+2. If you skipped that prompt: long-press the home screen, choose **Widgets**, find+ **three.ws**, and drag **Agent glance** out. It comes in 2x2 (the square card), 4x2 (the+ wide card), and 4x3 (the wide card with **Create** and **My agents** buttons). Resize it+ and it re-fetches the matching size.+3. The widget refreshes itself through WorkManager, on the battery-aware schedule Android+ grants background apps (about every 30 minutes, only with a network connection). Tapping+ the "Updated …" line refreshes on demand.++What happens when things go wrong is designed, not accidental:++| Situation | What the widget shows |+| --- | --- |+| Not linked yet | "Add your agent. Tap to link this widget to your three.ws account." The tap opens the link flow in the app. |+| Linked, first download pending | "Fetching your agent." It is replaced by the card as soon as the download lands. |+| Phone offline, or the server unreachable | The last card it downloaded, with "From 14:02 (offline). Tap to retry." It never shows a spinner or a broken image. |+| Account has no agent | A card that says so, and a tap that opens `/create`. |+| Token revoked from /glance | A "Widget unlinked" card whose tap re-opens the link flow. The app drops the dead token. |+| App force-stopped, or phone rebooted | The widget survives both: the bitmap is on disk, the schedule is WorkManager's, and both come back with the launcher. |++### Which agent it shows++Your first agent, unless the widget was linked while a different one of yours was selected on+`/glance`; that agent is then pinned to the token. Repoint a widget with+`PATCH /api/glance/token` (`{ "id": "<token id>", "agent": "<agent id>" }`) or relink it.++### Revoking a widget++Open [three.ws/glance](https://three.ws/glance) signed in and scroll to **Linked widgets**.+Every phone widget is listed by the label it was linked with, its token prefix, and when it+was last seen. **Revoke** invalidates that token; on its next refresh the widget shows the+"Widget unlinked" card. Nothing else about your account changes: the token could only ever+read your glance card.++### How the widget authenticates++A home screen widget outlives every browser session, and Android fetches it from an OS process+with no cookie jar, so it cannot use the session. Instead `/glance` mints a **widget token**+(`POST /api/glance/token`), a random 32-character credential prefixed `glw_`. The server stores+only its SHA-256; the plaintext travels once, inside a `threews://glance/link?token=…` deep+link that only the `ws.three.app` package can claim, and then lives in the app's private+storage. The token is accepted by exactly one endpoint, `GET /api/glance/mine`, and reads+exactly one thing: the owner's card.++### For developers++The native sources live in [solana-mobile/android-overlay/](../solana-mobile/android-overlay/README.md)+and are laid over the Bubblewrap-generated project by `solana-mobile/scripts/apply-overlay.mjs`+during `build-apk.sh`. The emulator recipe for the five checks (add from the picker, refresh+without opening the app, survive force-stop, survive reboot, hold the cached card in airplane+mode) is in [solana-mobile/README.md](../solana-mobile/README.md#emulator-qa).++## Windows 11++Installs with the PWA, no store submission: open three.ws in Edge, install it, open the widgets+board (`Win + W`), **Add widgets**, pick **Agent glance**. It authenticates with your session and+refreshes every 15 minutes. Details in [glance.md](glance.md#on-the-windows-11-widgets-board).++## macOS and iOS++Planned: a shared WidgetKit extension (a `TimelineProvider` that fetches+`/api/glance/mine?format=png` with a widget token stored in the keychain) and a small SwiftUI+host app that signs in and mints the token. macOS ships first because it can be distributed+outside the App Store; the iOS build is the same extension target and waits on an Apple+Developer account. The card, the token, and the endpoint are the ones above; nothing on the+server changes for either.++## The endpoints++| Endpoint | Purpose |+| --- | --- |+| `GET /api/glance/mine?format=png&size=small\|medium\|large&theme=dark\|light&scale=1\|2\|3` | The card bitmap for the caller (widget token as `Authorization: Bearer`, or the session cookie). Always `200`; the state is in `x-glance-state` and the tap target in `x-glance-url`. |+| `GET /api/glance/mine` | The same as JSON: `{ signedIn, state, card, notice, agents, … }`. |+| `POST /api/glance/token` | Mint a widget token (session, same-site). Returns the plaintext once plus `links.android`. |+| `GET /api/glance/token` | List the caller's live tokens. |+| `PATCH /api/glance/token` | Repoint a token at another owned agent. |+| `DELETE /api/glance/token?id=…` | Revoke a token. |+| `GET /api/glance/card?agent=…&format=png` | Any public agent's card as a bitmap, no auth. |++The wire format is pinned in [specs/GLANCE_CARD.md](../specs/GLANCE_CARD.md); the full endpoint+reference is in [api-reference.md](api-reference.md#glance-api).diff --git a/public/changelog.json b/public/changelog.jsonindex 27ea3f8ed..ff0443aff 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,31 @@{- "generated_at": "2026-08-28T22:44:07.948Z",+ "generated_at": "2026-08-29T05:04:52.854Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-08-29",+ "type": "launch",+ "title": "Native widgets: your agent on the home screen",+ "summary": "Put your three.ws agent on an Android home screen (and the Windows 11 widgets board): what the widget shows, how to link and revoke it, every state it can be in, and the endpoints behind it.",+ "link": "/docs/native-widgets",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-08-29",+ "type": "update",+ "title": "Your agent on the Android home screen",+ "summary": "The three.ws Android app (1.1) now ships a home screen widget. It shows your agent's avatar, its name, and how many moves it made today, refreshes itself in the background about every half hour without opening the app, keeps the last card it saw when the phone is offline, and opens your agent with a tap. Link a phone from the Glance page in one tap; every linked widget is listed there with a revoke button, because each one carries its own token that can read your card and nothing else. The Glance card also comes as a PNG now, which is what any native widget host, chat client or image-only surface needs.",+ "link": "/docs/native-widgets",+ "tags": [+ "feature"+ ]+ },{"date": "2026-08-28","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 703a8e891..3fa48a6e9 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,22 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws: features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Native widgets: your agent on the home screen</title>+ <link>https://three.ws/docs/native-widgets</link>+ <guid isPermaLink="false">2026-08-29:Native widgets: your agent on the home screen</guid>+ <pubDate>Sat, 29 Aug 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Put your three.ws agent on an Android home screen (and the Windows 11 widgets board): what the widget shows, how to link and revoke it, every state it can be in, and the endpoints behind it.</description>+ </item>+ <item>+ <title>Your agent on the Android home screen</title>+ <link>https://three.ws/docs/native-widgets</link>+ <guid isPermaLink="false">2026-08-29:Your agent on the Android home screen</guid>+ <pubDate>Sat, 29 Aug 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The three.ws Android app (1.1) now ships a home screen widget. It shows your agent's avatar, its name, and how many moves it made today, refreshes itself in the background about every half hour without opening the app, keeps the last card it saw when the phone is offline, and opens your agent with a tap. Link a phone from the Glance page in one tap; every linked widget is listed there with a revoke button, because each one carries its own token that can read your card and nothing else. The Glance card also comes as a PNG now, which is what any native widget host, chat client or image-only surface needs.</description>+ </item><item><title>Brownout</title><link>https://three.ws/brownout</link>diff --git a/public/features.json b/public/features.jsonindex bb8689810..e38196589 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-28T22:44:07.938Z",+ "generated_at": "2026-08-29T05:04:52.843Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -942,6 +942,16 @@"tags": [],"showcase": false},+ {+ "path": "/docs/native-widgets",+ "title": "Native widgets: your agent on the home screen",+ "description": "Put your three.ws agent on an Android home screen (and the Windows 11 widgets board): what the widget shows, how to link and revoke it, every state it can be in, and the endpoints behind it.",+ "added": "2026-08-29",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/glance","title": "Glance",diff --git a/public/glance/glance-page.js b/public/glance/glance-page.jsindex 6f80f4fd7..8e4aaf885 100644--- a/public/glance/glance-page.js+++ b/public/glance/glance-page.js@@ -180,9 +180,150 @@ function wireControls() {});}+/**+ * Android hand-off. The page mints a widget token (POST /api/glance/token)+ * and opens the intent: URL the server returns; Chrome routes it to the app's+ * link activity, which stores the token and offers to pin the widget. A+ * visitor who arrives with ?link=android (the tap target of an unlinked+ * widget) is walked through it without pressing anything.+ */+const android = {+ button: document.getElementById('android-link-button'),+ status: document.getElementById('android-link-status'),+ devices: document.getElementById('devices'),+ list: document.getElementById('device-list'),+};++function deviceLabel() {+ const ua = navigator.userAgent;+ const model = ua.match(/;\s*([^;)]+?)\s+Build\//);+ if (model) return model[1].trim().slice(0, 40);+ return /Android/i.test(ua) ? 'Android phone' : 'Home screen widget';+}++async function linkAndroid({ auto = false } = {}) {+ android.button.disabled = true;+ android.status.textContent = 'Linking…';+ try {+ const res = await fetch('/api/glance/token', {+ method: 'POST',+ credentials: 'same-origin',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify({ platform: 'android', label: deviceLabel(), agent: state.agentId || null }),+ signal: AbortSignal.timeout(TIMEOUT_MS),+ });+ if (res.status === 401) {+ const next = encodeURIComponent('/glance?link=android');+ android.status.innerHTML = `<a href="/login?next=${next}">Sign in</a> first, then come back here.`;+ if (auto) location.assign(`/login?next=${next}`);+ return;+ }+ const body = await res.json().catch(() => ({}));+ if (!res.ok) {+ android.status.textContent = body.message || body.error || `Could not link (${res.status}).`;+ return;+ }+ android.status.textContent = 'Opening the three.ws app…';+ await loadDevices();+ location.assign(body.links.android);+ setTimeout(() => {+ android.status.textContent = 'Linked. Add "Agent glance" from your launcher\u2019s widget picker.';+ }, 1500);+ } catch (err) {+ android.status.textContent = `Could not link: ${err.message}`;+ } finally {+ android.button.disabled = false;+ }+}++function relative(iso) {+ if (!iso) return 'never used';+ const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);+ if (s < 60) return 'just now';+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;+ return `${Math.floor(s / 86400)}d ago`;+}++async function loadDevices() {+ let tokens;+ try {+ const res = await fetch('/api/glance/token', {+ credentials: 'same-origin',+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(TIMEOUT_MS),+ });+ if (res.status === 401) {+ android.devices.hidden = true;+ return;+ }+ if (!res.ok) throw new Error(`${res.status}`);+ tokens = (await res.json()).tokens || [];+ } catch {+ android.devices.hidden = true;+ return;+ }++ android.devices.hidden = false;+ android.list.innerHTML = '';+ if (!tokens.length) {+ const li = document.createElement('li');+ li.className = 'glance-device-empty';+ li.textContent = 'No widget is linked yet. Link a phone above and it appears here.';+ android.list.append(li);+ return;+ }+ for (const token of tokens) {+ const li = document.createElement('li');+ li.className = 'glance-device';+ const name = document.createElement('b');+ name.textContent = token.label;+ const prefix = document.createElement('code');+ prefix.textContent = `${token.prefix}…`;+ const meta = document.createElement('span');+ meta.className = 'meta';+ meta.textContent = `${token.platform}, linked ${relative(token.createdAt)}, last seen ${relative(token.lastUsedAt)}`;+ const revoke = document.createElement('button');+ revoke.type = 'button';+ revoke.className = 'glance-btn secondary';+ revoke.textContent = 'Revoke';+ revoke.setAttribute('aria-label', `Revoke the widget token ${token.label}`);+ revoke.addEventListener('click', async () => {+ revoke.disabled = true;+ li.classList.add('is-going');+ try {+ const res = await fetch(`/api/glance/token?id=${encodeURIComponent(token.id)}`, {+ method: 'DELETE',+ credentials: 'same-origin',+ signal: AbortSignal.timeout(TIMEOUT_MS),+ });+ if (!res.ok && res.status !== 404) throw new Error(`${res.status}`);+ await loadDevices();+ } catch (err) {+ li.classList.remove('is-going');+ revoke.disabled = false;+ meta.textContent = `Could not revoke: ${err.message}`;+ }+ });+ li.append(name, prefix, meta, revoke);+ android.list.append(li);+ }+}++function wireAndroid() {+ android.button.addEventListener('click', () => linkAndroid());+ loadDevices();+ const params = new URL(location.href).searchParams;+ if (params.get('link') === 'android') {+ document.getElementById('android')?.scrollIntoView({ block: 'center' });+ linkAndroid({ auto: true });+ }+}+async function main() {wireControls();wireCopyButtons();+ wireAndroid();const fromUrl = new URL(location.href).searchParams.get('agent');const { options, note } = await discoverAgents();diff --git a/public/glance/glance.css b/public/glance/glance.cssindex 19b709af0..82eb84399 100644--- a/public/glance/glance.css+++ b/public/glance/glance.css@@ -270,3 +270,91 @@ button.copy[data-state='done'] {gap: 56px;}}++/* Linked widgets: the Android link button and the revoke list. */+.glance-link {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.6rem 0.9rem;+ margin: 0.9rem 0 0.6rem;+}+.glance-btn {+ appearance: none;+ border: 1px solid var(--line, #262842);+ background: linear-gradient(135deg, #4f46e5, #7c3aed);+ color: #fff;+ font: inherit;+ font-weight: 600;+ padding: 0.55rem 1rem;+ border-radius: 999px;+ cursor: pointer;+ transition:+ transform 0.15s ease,+ box-shadow 0.15s ease,+ opacity 0.15s ease;+}+.glance-btn:hover {+ transform: translateY(-1px);+ box-shadow: 0 6px 18px rgba(99, 102, 241, 0.35);+}+.glance-btn:active {+ transform: translateY(0);+}+.glance-btn:focus-visible {+ outline: 2px solid #a5b4fc;+ outline-offset: 3px;+}+.glance-btn[disabled] {+ opacity: 0.6;+ cursor: progress;+}+.glance-btn.secondary {+ background: var(--panel, #15162a);+ color: inherit;+ font-weight: 500;+ padding: 0.35rem 0.75rem;+}+.glance-devices {+ margin-top: 2rem;+ padding-top: 1.5rem;+ border-top: 1px solid var(--line, #262842);+}+.glance-devices h3 {+ margin: 0 0 0.3rem;+}+.glance-device-list {+ list-style: none;+ margin: 1rem 0 0;+ padding: 0;+ display: grid;+ gap: 0.6rem;+}+.glance-device {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.4rem 1rem;+ padding: 0.7rem 0.9rem;+ border: 1px solid var(--line, #262842);+ border-radius: 14px;+ background: var(--panel, #15162a);+ transition: opacity 0.2s ease;+}+.glance-device.is-going {+ opacity: 0.4;+}+.glance-device b {+ font-weight: 600;+}+.glance-device code {+ font-size: 0.85em;+}+.glance-device .meta {+ color: var(--muted, #a2a7bd);+ font-size: 0.85rem;+ flex: 1 1 12rem;+}+.glance-device-empty {+ color: var(--muted, #a2a7bd);+}diff --git a/public/glance/index.html b/public/glance/index.htmlindex 456185a49..7fcbae6ec 100644--- a/public/glance/index.html+++ b/public/glance/index.html@@ -178,12 +178,22 @@module script, one tag. It polls only while it is on screen and the tab is visible.</p></article>- <article class="glance-surface">+ <article class="glance-surface is-live" id="android"><h3>Android</h3>- <p class="glance-status">Next</p>- <p>- The signed <code>ws.three.app</code> shell already ships. The app widget provider is- the remaining piece, and the card endpoint it needs is what this page is running on.+ <p class="glance-status">Live now</p>+ <ol>+ <li>Install the <a href="/seeker">three.ws app</a> (version 1.1 or later).</li>+ <li>Open this page on the phone, signed in, and tap <b>Link this phone</b>.</li>+ <li>Long-press the home screen, choose <b>Widgets</b>, and add <b>Agent glance</b>.</li>+ </ol>+ <p class="glance-link" id="android-link">+ <button type="button" class="glance-btn" id="android-link-button">Link this phone</button>+ <span class="glance-help" id="android-link-status"></span>+ </p>+ <p class="glance-note">+ The widget refreshes itself about every 30 minutes without opening the app, keeps the+ last card it saw when the phone is offline, and opens your agent on tap. It carries+ its own token, which you can revoke below at any time.</p></article><article class="glance-surface">@@ -196,6 +206,14 @@</p></article></div>+ <div class="glance-devices" id="devices" hidden>+ <h3>Linked widgets</h3>+ <p class="glance-help">+ Every phone widget holds its own token that can only read your glance card. Revoke one+ and that widget shows a "link again" card on its next refresh.+ </p>+ <ul id="device-list" class="glance-device-list" aria-live="polite"></ul>+ </div></section></main>diff --git a/public/llms-full.txt b/public/llms-full.txtindex e6d95b87b..44145159c 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -576,6 +576,12 @@ URL: https://three.ws/docs/glancePut a three.ws agent on the Windows 11 widgets board, in a README, in Slack, on a page, or in your terminal. Endpoint, element, widget worker and npm client.+### Native widgets: your agent on the home screen++URL: https://three.ws/docs/native-widgets++Put your three.ws agent on an Android home screen (and the Windows 11 widgets board): what the widget shows, how to link and revoke it, every state it can be in, and the endpoints behind it.+### GlanceURL: https://three.ws/glancediff --git a/public/llms.txt b/public/llms.txtindex 635dc5685..57662a271 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -122,6 +122,7 @@ Create and customize an agent.- [Brownout: proven fallbacks, not promised ones](https://three.ws/docs/brownout): Every response says where its data came from and how fresh it is, and every fallback the API claims has been executed for real against a genuinely refusing provider, inside the request path a user hits.- [Portal: walk any website in 3D](https://three.ws/docs/portal): Paste a web address and Portal builds a place out of it: sections become buildings sized by what they say, links become doors you step through, images become billboards. The API, the world spec, the npm package, the CLI and the MCP server behind /portal.- [Glance: agent cards for home screens](https://three.ws/docs/glance): Put a three.ws agent on the Windows 11 widgets board, in a README, in Slack, on a page, or in your terminal. Endpoint, element, widget worker and npm client.+- [Native widgets: your agent on the home screen](https://three.ws/docs/native-widgets): Put your three.ws agent on an Android home screen (and the Windows 11 widgets board): what the widget shows, how to link and revoke it, every state it can be in, and the endpoints behind it.- [Glance](https://three.ws/glance): Your three.ws agent on every home screen: a live card for the Windows 11 widgets board, a README, Slack, or any page.- [Widgets Gallery](https://three.ws/widgets): Pre-built chat, voice, and 3D-avatar widgets you can drop into any page.- [Hydrate](https://three.ws/hydrate): Take an existing on-chain agent (ERC-8004 / Solana) and attach a 3D body, voice, and skills.diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex af5f4b1f2..8959086e3 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -83,7 +83,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 872 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 873 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -95,7 +95,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 872 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 873 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -103,6 +103,14 @@<h2 id="sm-new-title">Newest<a class="sm-new-more" href="/changelog">full changelog →</a></h2><p class="sm-section-desc">The 9 most recently launched pages, straight to the live surface.</p><ul class="sm-list">+ <li>+ <a href="/docs/native-widgets">+ <span class="sm-new-date">Aug 29, 2026</span>+ <span class="sm-title">Native widgets: your agent on the home screen</span>+ <span class="sm-path">/docs/native-widgets</span>+ <span class="sm-desc">Put your three.ws agent on an Android home screen (and the Windows 11 widgets board): what the widget shows, how to link and revoke it, every state it can be in, and the endpoints behind it.</span>+ </a>+ </li><li><a href="/portal"><span class="sm-new-date">Aug 28, 2026</span>@@ -167,14 +175,6 @@<span class="sm-desc">Put a three.ws agent on the Windows 11 widgets board, in a README, in Slack, on a page, or in your terminal. Endpoint, element, widget worker and npm client.</span></a></li>- <li>- <a href="/glance">- <span class="sm-new-date">Aug 28, 2026</span>- <span class="sm-title">Glance</span>- <span class="sm-path">/glance</span>- <span class="sm-desc">Your three.ws agent on every home screen: a live card for the Windows 11 widgets board, a README, Slack, or any page.</span>- </a>- </li></ul></section><nav class="sm-toc" aria-label="Sections">@@ -593,7 +593,7 @@<section class="sm-section" id="build"><header>- <h2>Build<span class="sm-count" data-count>68</span></h2>+ <h2>Build<span class="sm-count" data-count>69</span></h2><p class="sm-section-desc">Create and customize an agent.</p></header><ul class="sm-list">@@ -849,6 +849,13 @@<span class="sm-desc">Put a three.ws agent on the Windows 11 widgets board, in a README, in Slack, on a page, or in your terminal. Endpoint, element, widget worker and npm client.</span></a></li>+ <li>+ <a href="/docs/native-widgets">+ <span class="sm-title">Native widgets: your agent on the home screen</span>+ <span class="sm-path">/docs/native-widgets</span>+ <span class="sm-desc">Put your three.ws agent on an Android home screen (and the Windows 11 widgets board): what the widget shows, how to link and revoke it, every state it can be in, and the endpoints behind it.</span>+ </a>+ </li><li><a href="/glance"><span class="sm-title">Glance</span>diff --git a/specs/GLANCE_CARD.md b/specs/GLANCE_CARD.mdindex 2db3de9e6..543387333 100644--- a/specs/GLANCE_CARD.md+++ b/specs/GLANCE_CARD.md@@ -3,7 +3,8 @@The wire format behind [`/api/glance/card`](../docs/glance.md). One three.ws agent, reduced to what fits in an operating system widget slot, a README badge, or a chat unfurl.- **Endpoint:** `GET https://three.ws/api/glance/card?agent=<uuid>`-- **Media types:** `application/json` (default), `image/svg+xml` (`format=svg`), Adaptive Card 1.6 JSON (`format=adaptive`)+- **Media types:** `application/json` (default), `image/svg+xml` (`format=svg`), `image/png` (`format=png`), Adaptive Card 1.6 JSON (`format=adaptive`)+- **Owner endpoint:** `GET https://three.ws/api/glance/mine` (session cookie or widget token), same encodings minus SVG and Adaptive- **Companion specs:** [3D_AGENT_CARD.md](3D_AGENT_CARD.md) (the on-chain identity document), [EMBED_SPEC.md](EMBED_SPEC.md) (the 3D embed)## Why it exists@@ -96,6 +97,32 @@ The SVG rendering serves three sizes, chosen to match the slots the widget board| `medium` | 480x200 | Android 4x2, Windows medium, README badge || `large` | 480x300 | Windows large, a dashboard tile |+## PNG encoding++`format=png` rasterizes the SVG at `scale` (1, 2 or 3) times the size above, so `medium` at `scale=2` is 960x400 pixels. `theme` is `dark` or `light`; a renderer that cannot ask the reader for a preference (every native widget host) MUST request one explicitly, and the server resolves `auto` to `dark`. The avatar image is inlined before rasterizing; an image that cannot be fetched degrades to the monogram exactly as in the SVG conformance rule.++## Notice cards++A response that has no agent to show (signed out, an unlinked widget token, an account with no agent, an unknown id) carries a document with the same fields, `id` set to `"notice"` (or `"missing"` for an unknown id), `image` `null`, `status` `"new"`, every numeric field `0`, and `headline` and `url` set to the next step (sign in, relink, create). A renderer treats it as any other card; that is the point.++## Owner endpoint and widget tokens++`GET /api/glance/mine` answers for the caller rather than for an id. It identifies the caller by the session cookie or by a **widget token** presented as `Authorization: Bearer glw_…` (or `?token=`). Tokens are minted by the owner at `POST /api/glance/token`, are 36 characters (`glw_` plus 32 URL-safe characters), are stored hashed, read this one endpoint and nothing else, and are revocable at `DELETE /api/glance/token?id=`.++The JSON answer is `{ signedIn, state, via, card, notice, agents, signInUrl, createUrl, linkUrl }` with `state` one of `agent`, `signed-out`, `unlinked`, `no-agent`. When `state` is `agent`, `card` is the document above and `notice` is `null`; otherwise `card` is `null` and `notice` is a notice card.++The PNG answer is always status `200` and carries the same facts in headers, so a host that only downloads a bitmap still learns where a tap goes:++| Header | Value |+| --- | --- |+| `x-glance-state` | the `state` above |+| `x-glance-url` | the card's `url`, the tap target |+| `x-glance-name` | `name`, ASCII-filtered |+| `x-glance-metric` | `"<value> <label>"` |+| `x-glance-agent` | the agent id, empty for a notice |+| `x-glance-updated` | `updatedAt` |+| `x-glance-width`, `x-glance-height` | bitmap pixels |+## VersioningNew optional fields are additive and do not bump `version`. Removing a field, changing a type, or changing the meaning of `metric` requires v2 served alongside v1; the `version` field is what lets a widget pinned a year ago keep rendering.@@ -105,5 +132,8 @@ New optional fields are additive and do not bump `version`. Removing a field, ch- Model: [api/_lib/glance-card.js](../api/_lib/glance-card.js)- SVG: [api/_lib/glance-svg.js](../api/_lib/glance-svg.js)- Adaptive Card: [api/_lib/glance-adaptive.js](../api/_lib/glance-adaptive.js)-- Endpoint: [api/glance/card.js](../api/glance/card.js)-- Conformance tests: [tests/glance-card.test.js](../tests/glance-card.test.js)+- PNG: [api/_lib/glance-png.js](../api/_lib/glance-png.js)+- Widget tokens: [api/_lib/glance-tokens.js](../api/_lib/glance-tokens.js), [api/glance/token.js](../api/glance/token.js)+- Endpoints: [api/glance/card.js](../api/glance/card.js), [api/glance/mine.js](../api/glance/mine.js)+- Android renderer: [solana-mobile/android-overlay/](../solana-mobile/android-overlay/README.md)+- Conformance tests: [tests/glance-card.test.js](../tests/glance-card.test.js), [tests/glance-png.test.js](../tests/glance-png.test.js), [tests/glance-tokens.test.js](../tests/glance-tokens.test.js)diff --git a/tests/glance-png.test.js b/tests/glance-png.test.jsnew file mode 100644index 000000000..7889ca636--- /dev/null+++ b/tests/glance-png.test.js@@ -0,0 +1,110 @@+// Glance PNG: the bitmap encoding native widget hosts consume.+//+// rasterizeGlanceCard runs the real SVG renderer through the real sharp+// pipeline; only the thumbnail fetch is network, and the cards here carry+// none, so the suite is hermetic.++import { describe, it, expect } from 'vitest';+import sharp from 'sharp';+import { buildGlanceCard, noticeCard } from '../api/_lib/glance-card.js';+import { renderGlanceSvg } from '../api/_lib/glance-svg.js';+import { rasterizeGlanceCard, pngOptions, GLANCE_PNG_SCALES } from '../api/_lib/glance-png.js';+import { stateCard, GLANCE_STATES } from '../api/glance/mine.js';++const NOW = new Date('2026-08-28T12:00:00.000Z');++function card(patch = {}) {+ return buildGlanceCard({+ agent: {+ id: '11111111-2222-3333-4444-555555555555',+ name: 'Atlas Scout',+ description: 'Watches the launch feed.',+ skills: ['watch'],+ created_at: new Date('2026-08-01T00:00:00.000Z'),+ avatar_thumbnail_key: null,+ avatar_visibility: null,+ ...patch,+ },+ activity: { total: 412, day: 17, week: 96 },+ last: { type: 'skill.invoke', created_at: new Date('2026-08-28T11:00:00.000Z') },+ now: NOW,+ });+}++async function pixel(png, x, y) {+ const { data, info } = await sharp(png).raw().toBuffer({ resolveWithObject: true });+ const i = (y * info.width + x) * info.channels;+ return [data[i], data[i + 1], data[i + 2]];+}++describe('pngOptions', () => {+ it('defaults to medium, dark, 2x and rejects what it does not know', () => {+ expect(pngOptions(new URLSearchParams(''))).toEqual({ size: 'medium', theme: 'dark', scale: 2 });+ expect(pngOptions(new URLSearchParams('size=huge&theme=auto&scale=7'))).toEqual({ size: 'medium', theme: 'dark', scale: 2 });+ expect(pngOptions(new URLSearchParams('size=small&theme=light&scale=3'))).toEqual({ size: 'small', theme: 'light', scale: 3 });+ expect(GLANCE_PNG_SCALES).toEqual([1, 2, 3]);+ });+});++describe('rasterizeGlanceCard', () => {+ it('renders every size at the requested density', async () => {+ const expected = { small: [240, 240], medium: [480, 200], large: [480, 300] };+ for (const [size, [w, h]] of Object.entries(expected)) {+ const out = await rasterizeGlanceCard(card(), { size, scale: 2 });+ const meta = await sharp(out.png).metadata();+ expect(meta.format).toBe('png');+ expect([meta.width, meta.height]).toEqual([w * 2, h * 2]);+ expect([out.width, out.height]).toEqual([w * 2, h * 2]);+ }+ });++ it('paints the fixed themes with literal colors, which is what librsvg can read', async () => {+ const dark = await rasterizeGlanceCard(card(), { theme: 'dark', scale: 1 });+ const light = await rasterizeGlanceCard(card(), { theme: 'light', scale: 1 });+ // Inside the rounded corner, away from the accent strip and any glyph.+ expect(await pixel(dark.png, 470, 190)).toEqual([11, 11, 22]);+ expect(await pixel(light.png, 470, 190)).toEqual([255, 255, 255]);+ });++ it('keeps the fixed-theme SVG free of custom properties', () => {+ expect(renderGlanceSvg(card(), { theme: 'dark' })).not.toContain('var(--');+ expect(renderGlanceSvg(card(), { theme: 'light' })).not.toContain('var(--');+ expect(renderGlanceSvg(card(), { theme: 'auto' })).toContain('prefers-color-scheme');+ });++ it('draws the monogram when the thumbnail cannot be fetched', async () => {+ const out = await rasterizeGlanceCard(card({ avatar_thumbnail_key: 'thumb/x.png', avatar_visibility: 'public' }), {+ size: 'small',+ scale: 1,+ });+ // The portrait square sits at 20..76; its fill is the accent gradient,+ // never the panel or a transparent hole.+ const [r, g, b] = await pixel(out.png, 30, 30);+ expect(r + g + b).toBeGreaterThan(0);+ expect([r, g, b]).not.toEqual([11, 11, 22]);+ });+});++describe('notice cards', () => {+ it('shape a message exactly like an agent card so every renderer draws them', () => {+ const notice = noticeCard({ name: 'Widget unlinked', headline: 'Tap to link again.', url: 'https://three.ws/glance' });+ const agent = card();+ expect(Object.keys(notice).sort()).toEqual(Object.keys(agent).sort());+ expect(notice.id).toBe('notice');+ expect(notice.image).toBeNull();+ expect(notice.stats).toHaveLength(3);+ });++ it('answer every non-agent widget state with a tap target that fixes it', async () => {+ const signedOut = stateCard(GLANCE_STATES.signedOut);+ const unlinked = stateCard(GLANCE_STATES.unlinked);+ const noAgent = stateCard(GLANCE_STATES.noAgent);+ expect(signedOut.url).toContain('/login');+ expect(unlinked.url).toContain('/glance?link=android');+ expect(noAgent.url).toBe('https://three.ws/create');+ for (const notice of [signedOut, unlinked, noAgent]) {+ const out = await rasterizeGlanceCard(notice, { size: 'small', scale: 1 });+ expect((await sharp(out.png).metadata()).width).toBe(240);+ }+ });+});diff --git a/tests/glance-tokens.test.js b/tests/glance-tokens.test.jsnew file mode 100644index 000000000..e86537236--- /dev/null+++ b/tests/glance-tokens.test.js@@ -0,0 +1,32 @@+// Glance widget tokens: the shape and the parts that need no database.++import { describe, it, expect } from 'vitest';+import { mintPlaintext, looksLikeGlanceToken, prefixOf, GLANCE_TOKEN_PREFIX } from '../api/_lib/glance-tokens.js';+import { androidLinkUrl, ANDROID_PACKAGE } from '../api/glance/token.js';++describe('glance widget tokens', () => {+ it('mint a prefixed, url-safe plaintext that the shape check accepts', () => {+ const token = mintPlaintext();+ expect(token.startsWith(GLANCE_TOKEN_PREFIX)).toBe(true);+ expect(token).toHaveLength(36);+ expect(looksLikeGlanceToken(token)).toBe(true);+ expect(prefixOf(token)).toBe(token.slice(0, 10));+ expect(mintPlaintext()).not.toBe(token);+ });++ it('reject everything that is not a widget token, without touching the database', () => {+ for (const bad of ['', null, undefined, 42, 'glw_', 'glw_short', 'sk_live_' + 'a'.repeat(32), `${'x'.repeat(36)}`]) {+ expect(looksLikeGlanceToken(bad)).toBe(false);+ }+ });++ it('hand the token to the Android app through an intent URL only our package can claim', () => {+ const token = mintPlaintext();+ const url = androidLinkUrl(token);+ expect(url.startsWith('intent://glance/link?token=')).toBe(true);+ expect(url).toContain(`package=${ANDROID_PACKAGE}`);+ expect(url).toContain('scheme=threews');+ expect(url).toContain('S.browser_fallback_url=');+ expect(url).toContain(encodeURIComponent(token));+ });+});