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(desktop): add live widgets, a widgets board and a platform assistant, and put the desktop back at /
nirholas9c47f3cebd4a
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 74cf9da59..1cbd43bda 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -25,8 +25,9 @@ bottom.| Event Market scoring, leaderboard and rewards | [api/_lib/event-markets/scoring.js](api/_lib/event-markets/scoring.js), [rollup.js](api/_lib/event-markets/rollup.js), [fairness.js](api/_lib/event-markets/fairness.js), [leaderboard.js](api/_lib/event-markets/leaderboard.js), [api/cron/event-markets-rollup.js](api/cron/event-markets-rollup.js), [data/event-market-scoring.json](data/event-market-scoring.json), [pages/event-markets-leaderboard.html](pages/event-markets-leaderboard.html) `→ /event-markets/leaderboard`, [scripts/event-markets-season-payouts.mjs](scripts/event-markets-season-payouts.mjs) | Live once migration 20261012400000 is applied; payouts owner-gated | Scores, streaks, season ranks and badges from the rollup cron; wallet-derived names; fair-play ranking checks; season reward table printed for owner approval, never sent automatically. Docs: [docs/event-markets.md](docs/event-markets.md#scoring-and-seasons). Tests: [tests/event-markets-scoring.test.js](tests/event-markets-scoring.test.js) || Event Market live feed | [api/event-markets/stream.js](api/event-markets/stream.js), [api/_lib/event-markets/hub.js](api/_lib/event-markets/hub.js), [feed.js](api/_lib/event-markets/feed.js), [moves.js](api/_lib/event-markets/moves.js), [live-stats.js](api/_lib/event-markets/live-stats.js), [api/cron/event-markets-feed.js](api/cron/event-markets-feed.js), [src/event-markets/live-feed.js](src/event-markets/live-feed.js), [ticker.js](src/event-markets/ticker.js), [data/event-markets-feed.json](data/event-markets-feed.json) | Live (migration 20261012200000 applied) | SSE odds, picks, moves and lifecycle with Last-Event-ID resume, odds-move detector, home ticker, in-place odds on the market page with polling fallback, pulse and trending additions. Docs: [docs/event-markets.md](docs/event-markets.md#live-feed). Tests: [tests/event-markets-live-feed.test.js](tests/event-markets-live-feed.test.js), [tests/event-markets-live-stats.test.js](tests/event-markets-live-stats.test.js). Bench: [scripts/event-markets-fanout-bench.mjs](scripts/event-markets-fanout-bench.mjs) || App pages (hub plus Android, Seeker, iOS, Desktop, Web) | Pages [pages/apps.html](pages/apps.html) `→ /apps` and `pages/apps-{web,android,seeker,ios,desktop}.html` `→ /apps/*`, code [src/apps.js](src/apps.js), [src/apps.css](src/apps.css) | Built and verified locally | One page per platform with its real install path and status; the desktop page reads the live release feed. Docs: [docs/apps.md](docs/apps.md) |-| Homepage: the Field (a live, zoomable map of every agent and surface) | Page [pages/desktop.html](pages/desktop.html) `→ /`, code [src/field/](src/field) ([README](src/field/README.md)): pure layout and camera [logic.js](src/field/logic.js), feeds [data.js](src/field/data.js), map [field.js](src/field/field.js), entry and legacy switch [entry.js](src/field/entry.js) | Built and verified locally | Public agents drawn as stars in a golden-angle core around ten live districts; semantic zoom from one readout per district to full cards (avatars, launches, $THREE quote and CA, Pulse wallet moves, top skills, most-talked-to agents); Pulse events fly in as comets; search over places, agents and every nav page; any page opens in place at a shareable `/?go=` URL. The windowed desktop and campus stay at `/?view=desktop` and `/?world=1`. Docs: [docs/field.md](docs/field.md) |+| The Field (a live, zoomable map of every agent and surface) | Page [pages/desktop.html](pages/desktop.html) `→ /?view=field`, code [src/field/](src/field) ([README](src/field/README.md)): pure layout and camera [logic.js](src/field/logic.js), feeds [data.js](src/field/data.js), map [field.js](src/field/field.js), entry and view switch [entry.js](src/field/entry.js) | Built and verified locally | Public agents drawn as stars in a golden-angle core around ten live districts; semantic zoom from one readout per district to full cards (avatars, launches, $THREE quote and CA, Pulse wallet moves, top skills, most-talked-to agents); Pulse events fly in as comets; search over places, agents and every nav page; any page opens in place at a shareable `/?go=` URL. The homepage `/` is the web desktop; the campus is at `/?world=1`. Docs: [docs/field.md](docs/field.md) || Web desktop (homepage as an OS, with a 3D campus in front of it) | Page [pages/desktop.html](pages/desktop.html) `→ /`, code [src/desktop/](src/desktop) ([README](src/desktop/README.md)): boot and lock screen [boot.js](src/desktop/boot.js) + [boot-logic.js](src/desktop/boot-logic.js), campus [src/desktop/world/](src/desktop/world), gem ledger [api/world/gems.js](api/world/gems.js) over [api/_lib/world-gems.js](api/_lib/world-gems.js) (migration `20261015000000_world_gems.sql`); previous homepage [pages/home.html](pages/home.html) `→ /classic` | Built and verified locally | Boots with a live log of real checks (GPU, site catalog, account, fonts, avatar, $THREE feed, gem ledger), locks with a greeting and live chips, then the visitor walks in as their avatar: a campus with the home office (sit at the desk to open the desktop on the monitor, pick up the phone for Pocket, put on the headset for WebXR), the three.ws Exchange with a live ticker (Trenches), the Launchpad, the Forge, the Gallery, Agent Plaza, the Marketplace and a gem mine with server-rolled, rate-limited digs. Real registered agents stand on the campus in their own bodies ([world/cast.js](src/desktop/world/cast.js), [agents.js](src/desktop/world/agents.js), [talk.js](src/desktop/world/talk.js)): a greeter meets you at the gate, and walking up to any of them opens a conversation through its own `/api/chat` brain, with the one-tag `<agent-3d>` embed to put it on your own site. Taskbar, Start, widgets and snappable windows framing real three.ws pages in the CTRL Mica theme; icons on a snap grid, All Apps, Settings (profile, Arrival, accent, wallpaper, icon size), session in localStorage plus IndexedDB. Framed pages hide the site nav via `public/nav.js` (`tws-os:` frame name). Docs: [docs/desktop.md](docs/desktop.md). Tests: [tests/desktop-boot.test.js](tests/desktop-boot.test.js), [tests/world-places.test.js](tests/world-places.test.js), [tests/world-ticker.test.js](tests/world-ticker.test.js), [tests/desktop-layout.test.js](tests/desktop-layout.test.js), [tests/desktop-page.test.js](tests/desktop-page.test.js); browser drives [scripts/desktop-world-smoke.mjs](scripts/desktop-world-smoke.mjs), [scripts/desktop-interact.mjs](scripts/desktop-interact.mjs) |+| Desktop widgets and assistant | Code [src/desktop/widgets/](src/desktop/widgets) ([README](src/desktop/widgets/README.md)): pure grid, catalog and formatting [logic.js](src/desktop/widgets/logic.js), shared feeds [data.js](src/desktop/widgets/data.js), renderers [render.js](src/desktop/widgets/render.js), desktop layer, gallery and board [index.js](src/desktop/widgets/index.js); assistant [src/desktop/assistant/](src/desktop/assistant) ([README](src/desktop/assistant/README.md)) | Built and verified locally | Eleven live widgets ($THREE, Weather, Clock, Calendar, New agents, Pulse, Launches, Platform, Headlines, System, Sticky note) in three sizes, pinned to a snap grid on the desktop (drag, edit mode, Add widget gallery with live previews) or on the widgets board with a greeting and a news column; feeds shared and paused while hidden, offline states with retry. The assistant streams `/api/chat`, opens desktop apps from `[[open:id]]` tags, and switches to any public agent's persona. Docs: [docs/desktop-widgets.md](docs/desktop-widgets.md). Tests: [tests/desktop-widgets.test.js](tests/desktop-widgets.test.js), [tests/desktop-assistant.test.js](tests/desktop-assistant.test.js) || Trenches Pulse (Solana + Robinhood Chain intelligence) | Service [services/pulse/](services/pulse) (vendored nirholas/pulse: firehose, scorer, API, Telegram newsletter), proxy [api/trenches.js](api/trenches.js) `→ /api/trenches`, page [pages/trenches.html](pages/trenches.html) + [src/trenches.js](src/trenches.js) `→ /trenches` | Built and verified locally; service deploy pending owner approval | Real pump.fun firehose over Solana WebSocket: launches, graduations, hottest tokens, runners, scored wallets. Offline upstream is a designed 503 state, never fabricated data. Docs: [docs/trenches.md](docs/trenches.md). Tests: [tests/trenches-api.test.js](tests/trenches-api.test.js) || Browse by goal (every feature grouped into twelve goals, search, pins, what-next strip) | [pages/everything.html](pages/everything.html), [src/everything.js](src/everything.js), [src/everything.css](src/everything.css), taxonomy [scripts/lib/feature-jobs.mjs](scripts/lib/feature-jobs.mjs), [public/next-steps.js](public/next-steps.js) | Live | `/everything` reads `public/features.json`, which `scripts/build-page-index.mjs` builds from `data/pages.json` plus the goal taxonomy, so a new page appears with no extra step. Also drives the goal labels in the ⌘K palette and the nav entry. Docs: [docs/everything.md](docs/everything.md). Tests: [tests/feature-jobs.test.js](tests/feature-jobs.test.js), [tests/next-steps.test.js](tests/next-steps.test.js) || Event Market agent forecasters | [api/_lib/event-markets/forecasters.js](api/_lib/event-markets/forecasters.js), [analyze.js](api/_lib/event-markets/analyze.js), [forecast-runner.js](api/_lib/event-markets/forecast-runner.js), [forecaster-routes.js](api/_lib/event-markets/forecaster-routes.js), [api/cron/event-markets-forecasters.js](api/cron/event-markets-forecasters.js), [api/_mcpagent/event-market-forecast-tools.js](api/_mcpagent/event-market-forecast-tools.js), [src/event-markets/forecasting.js](src/event-markets/forecasting.js), [forecasters.js](src/event-markets/forecasters.js), [pages/event-markets-forecasters.html](pages/event-markets-forecasters.html) `→ /event-markets/forecasters`, [data/event-markets-agents.json](data/event-markets-agents.json) | Live (migration 20261012120000 applied) | Agent picks as the agent's own identity with confidence, rationale and evidence; market-page agents panel; track record and calibration on the agent profile; ranked board; follow with notifications; owner-controlled autonomous mode (off by default); MCP analyze, forecasters and agent pick. Docs: [docs/event-markets.md](docs/event-markets.md#agents). Tests: [tests/event-markets-agents.test.js](tests/event-markets-agents.test.js), [tests/event-markets-agents-mcp.test.js](tests/event-markets-agents-mcp.test.js), [tests/event-markets-forecasting-ui.test.js](tests/event-markets-forecasting-ui.test.js) |diff --git a/data/changelog.json b/data/changelog.jsonindex 4ea75a07e..78da1bd2e 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$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, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-11",+ "title": "Live widgets and an assistant on the desktop, and the desktop is back at /",+ "link": "/docs/desktop-widgets",+ "summary": "The homepage is the web desktop again, and the Field moves to /?view=field. The desktop gains eleven live widgets: the $THREE price with a 24 hour chart, weather where you are, clock, calendar, the newest agents, Pulse wallet moves, coins launched through three.ws, platform stats, headlines from the news desk, your device's battery, network and storage, and sticky notes. Pin them to the desktop in small, medium or large, drag them on a snap grid, or keep them on the widgets board beside a news column. The new assistant pane answers questions about three.ws, opens the right app from its reply, and lets you switch to any public agent and talk to it instead. Nothing is sample data: a source that is down says so and offers a retry.",+ "tags": [+ "feature",+ "desktop"+ ]+ },{"date": "2026-10-11","title": "Real agents live on the campus: a greeter meets you at the gate and every agent you walk up to talks back",diff --git a/data/pages.json b/data/pages.jsonindex 7c3caca78..112618c89 100644--- a/data/pages.json+++ b/data/pages.json@@ -4244,6 +4244,14 @@"changefreq": "monthly","added": "2026-10-11"},+ {+ "path": "/docs/desktop-widgets",+ "title": "Desktop Widgets and Assistant",+ "description": "The live widgets on the three.ws desktop and widgets board ($THREE, weather, Pulse, launches, new agents, headlines, system) and the assistant that answers about the platform, opens apps and lets you talk to any public agent.",+ "priority": 0.5,+ "changefreq": "monthly",+ "added": "2026-10-11"+ },{"path": "/docs/event-markets","title": "Docs · Event Markets",diff --git a/docs/desktop-widgets.md b/docs/desktop-widgets.mdnew file mode 100644index 000000000..4f70ae1d1--- /dev/null+++ b/docs/desktop-widgets.md@@ -0,0 +1,85 @@+# Desktop widgets and assistant++The web desktop at `/` has two live surfaces beside its windows: **widgets**,+small cards of real data that sit on the desktop or on the widgets board, and+the **assistant**, a chat pane that knows the platform and can open apps for+you. Neither shows sample data. When a source is down the card says what failed+and offers a retry, and stale numbers are labelled as stale.++## Widgets++| Widget | What it shows | Source |+| --- | --- | --- |+| $THREE | Price, 24 h change, market cap, a 24 hour chart | `/api/three-token/stats`, `/api/pump/price-history` |+| Weather | Conditions, feels-like, the next hours; at large size humidity and wind | Open-Meteo, for your saved city or your location |+| Clock | Analog face, local time and date | This device |+| Calendar | The month, starting on your locale's first weekday | This device |+| New agents | The newest public agents, each opening its profile | `/api/agents/public?sort=newest` |+| Pulse | Live wallet moves by agents | `/api/pulse` |+| Launches | Coins agents launched through three.ws | `/api/pump/launches` |+| Platform | Agents, launches and strategies right now | `/api/stats` |+| Headlines | Top stories from the three.ws news desk | `/api/news/feed` |+| System | Battery, network, memory and storage | Browser APIs; anything the browser does not expose is left out |+| Sticky note | Your own text, saved as you type | This browser |++Most widgets come in small (1 x 1), medium (2 x 1) and large (2 x 2), and each+renders a layout made for its size rather than a scaled copy. Feeds are shared:+a $THREE card on the desktop and another on the board make one request, polls+pause while the tab is hidden and refresh the moment it returns.++### On the desktop++Widgets sit on a grid along the right edge of the desktop.++- **Move:** drag a widget by its header. A ghost shows the cell it will land in;+ drops onto an occupied cell are refused.+- **Resize, refresh, open, remove:** right-click a widget or use its `...` button.+- **Edit mode:** right-click the desktop, **Edit widgets**. Every widget shows a+ remove button and a bar offers **Add widget** and **Done** (Escape also exits).+- **Add:** right-click the desktop, **Add a widget**. The gallery shows a live+ preview of each widget at each size before you add it.++The layout follows the screen: on a smaller window widgets re-flow into the+first free cells, and under 640 px wide the desktop layer hides and widgets+live on the board only.++### The board++The taskbar's Widgets button (or Ctrl+Alt+W) opens the board: a greeting with+the date, your board widgets, and a news column with the lead story expanded.+Each board widget can be pinned to the desktop, moved up or removed, and+**Add widget** opens the same gallery. Escape, a click outside or focusing a+window closes it.++## Assistant++The taskbar's Assistant button (or Ctrl+Alt+C) opens a pane on the right edge.++- **Ask anything about three.ws.** Replies stream from `/api/chat` and work+ signed out. The assistant is grounded on the date, $THREE and the desktop's+ app list, and never asks for keys or seed phrases.+- **It opens apps.** When an app would help, the reply ends with buttons such as+ **Open Create**; only real desktop apps can appear.+- **Talk to an agent.** Click the name in the header to search public agents+ and switch to one; the conversation then uses that agent's persona and brain.+- **Stop, retry, start over.** The send button becomes Stop while a reply+ streams, a failed reply shows why (rate limit, sign-in needed, network) and+ is left out of the conversation history, and the new-chat button clears it.+- Enter sends, Shift+Enter adds a line. The conversation is saved in this+ browser and stays in sync across tabs.++## Storage++Everything is local to the browser: `tws-widgets:desktop`, `tws-widgets:board`+and `tws-widgets:place` for widgets, `tws-assistant:v1` for the conversation.+Clearing site data resets both to their defaults.++## Code++[src/desktop/widgets/](../src/desktop/widgets/README.md) and+[src/desktop/assistant/](../src/desktop/assistant/README.md). Pure rules are+unit tested in `tests/desktop-widgets.test.js` and+`tests/desktop-assistant.test.js`. The shell wires the taskbar buttons,+shortcuts and desktop menu in `src/desktop/shell.js`. See also+[desktop.md](desktop.md) for the rest of the desktop and [field.md](field.md)+for the Field at `/?view=field`.diff --git a/docs/field.md b/docs/field.mdindex dfcd11233..2f2493a93 100644--- a/docs/field.md+++ b/docs/field.md@@ -1,6 +1,6 @@# The Field-`/` is the Field: one zoomable map of the whole platform, drawn from live data.+`/?view=field` is the Field: one zoomable map of the whole platform, drawn from live data.At the centre is the core, every public agent placed as a star on a golden-anglespiral (newest in the middle). Around it sit the districts, one per productsurface. Wallet moves from Pulse fly across the map as comets and land in the@@ -8,9 +8,9 @@ district they belong to. Nothing on the map is decorative: every number, faceand trail comes from a real endpoint, and when a feed is down its district saysso and offers a retry.-The windowed desktop and the 3D campus are still one click away:-`/?view=desktop` and `/?world=1` (see [desktop.md](desktop.md)). The previous-homepage stays at `/classic`.+The homepage `/` is the web desktop (see [desktop.md](desktop.md) and+[desktop-widgets.md](desktop-widgets.md)); its 3D campus is at `/?world=1` and+the previous homepage stays at `/classic`.## Moving around@@ -86,5 +86,5 @@ and desktop sizes that no two tags overlap at the home view.[src/field/](../src/field/README.md): `logic.js` (pure layout, camera, searchand formatting, unit tested), `data.js` (the feeds), `field.js` (DOM, canvas,-input, surfaces), `field.css`, and `entry.js` (picks the Field or the legacy-desktop for `pages/desktop.html`).+input, surfaces), `field.css`, and `entry.js` (loads the desktop for `pages/desktop.html`, or the Field+when the URL carries `?view=field`).diff --git a/src/desktop/assistant/README.md b/src/desktop/assistant/README.mdnew file mode 100644index 000000000..3326797e4--- /dev/null+++ b/src/desktop/assistant/README.md@@ -0,0 +1,13 @@+# src/desktop/assistant++The desktop assistant: a chat pane docked to the right edge, opened from the+taskbar. It answers through `/api/chat` (streamed over SSE, works signed out),+knows every desktop app and can open one from its reply, and can switch to any+public agent so you talk to that agent's own persona. Guide:+[docs/desktop-widgets.md](../../../docs/desktop-widgets.md#assistant).++| File | Role |+| --- | --- |+| `logic.js` | Pure helpers: the grounding system prompt (kept under the API's 2000 characters, lists app ids), `parseActions` for `[[open:appId]]` tags (unknown ids dropped), `hidePartialTag` while streaming, `trimHistory` (last 20 turns), a safe Markdown renderer (escaped first, http(s) and same-site links only), starter suggestions. Unit tested in `tests/desktop-assistant.test.js` |+| `index.js` | The pane: `toggleAssistant(ctx)` / `closeAssistant()`, the agent picker over `/api/agents/public`, streaming with stop, rate-limit and sign-in errors, Open-app buttons, conversation saved under `tws-assistant:v1` and synced across tabs. Failed turns never enter the model history |+| `assistant.css` | Pane, picker, messages, composer; full width under 640 px; reduced motion |diff --git a/src/desktop/assistant/assistant.css b/src/desktop/assistant/assistant.cssnew file mode 100644index 000000000..c4f53ec14--- /dev/null+++ b/src/desktop/assistant/assistant.css@@ -0,0 +1,492 @@+/* The desktop assistant: a frosted pane docked to the right edge above the taskbar. */++.asx {+ position: absolute;+ top: 10px;+ right: 10px;+ bottom: calc(var(--task-h, 48px) + 10px);+ z-index: 10001;+ width: min(400px, calc(100vw - 20px));+ display: flex;+ flex-direction: column;+ color: var(--text);+ background: color-mix(in srgb, var(--bg) 58%, transparent);+ backdrop-filter: blur(48px) saturate(1.8);+ -webkit-backdrop-filter: blur(48px) saturate(1.8);+ border: 1px solid color-mix(in srgb, var(--text) 10%, transparent);+ border-radius: 20px;+ box-shadow: 0 30px 80px -20px rgb(0 0 0 / 0.6);+ font-size: 13.5px;+ overflow: hidden;+ transform: translateX(calc(100% + 24px));+ opacity: 0;+ transition:+ transform 0.26s cubic-bezier(0.2, 0.8, 0.2, 1),+ opacity 0.2s;+}+.asx.in {+ transform: none;+ opacity: 1;+}+.asx :focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}++.asx-head {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 10px 10px 8px 12px;+ border-bottom: 1px solid color-mix(in srgb, var(--text) 8%, transparent);+}+.asx-who {+ display: flex;+ align-items: center;+ gap: 10px;+ min-width: 0;+ padding: 4px 8px 4px 4px;+ border: 0;+ border-radius: 12px;+ background: none;+ color: var(--text);+ font: inherit;+ text-align: left;+ cursor: pointer;+}+.asx-who:hover,+.asx-who[aria-expanded='true'] {+ background: color-mix(in srgb, var(--text) 7%, transparent);+}+.asx-who > span {+ display: grid;+ min-width: 0;+}+.asx-who b {+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.asx-who small {+ color: var(--text2);+ font-size: 11px;+}+.asx-who > .ico {+ transform: rotate(90deg);+ color: var(--text2);+ flex: none;+}+.asx img,+.asx i:not(.asx-dots i) {+ flex: none;+ width: 32px;+ height: 32px;+ border-radius: 10px;+ object-fit: cover;+ display: grid;+ place-items: center;+ font-style: normal;+ font-weight: 700;+ color: #fff;+ background: linear-gradient(135deg, var(--theme-1, #ad6eca), var(--theme-2, #3b91d8));+}+.asx-logo.big {+ width: 56px;+ height: 56px;+ border-radius: 18px;+}+.asx-tools {+ margin-left: auto;+ display: flex;+ gap: 2px;+}+.asx-ib {+ display: grid;+ place-items: center;+ width: 34px;+ height: 34px;+ border: 0;+ border-radius: 10px;+ background: none;+ color: var(--text2);+ cursor: pointer;+}+.asx-ib:hover {+ background: color-mix(in srgb, var(--text) 8%, transparent);+ color: var(--text);+}+.asx-ib:active {+ transform: scale(0.94);+}++/* agent picker */+.asx-pick {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 10px;+ max-height: 55%;+ border-bottom: 1px solid color-mix(in srgb, var(--text) 8%, transparent);+ background: color-mix(in srgb, var(--card) 50%, transparent);+}+.asx-pick[hidden] {+ display: none;+}+.asx-search {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 0 10px;+ height: 36px;+ border-radius: 10px;+ border: 1px solid color-mix(in srgb, var(--text) 10%, transparent);+ background: color-mix(in srgb, var(--card) 80%, transparent);+ color: var(--text2);+}+.asx-search:focus-within {+ border-color: var(--accent);+}+.asx-search input {+ flex: 1;+ min-width: 0;+ border: 0;+ background: none;+ color: var(--text);+ font: inherit;+ outline: none;+}+.asx-pick ul {+ list-style: none;+ margin: 0;+ padding: 0;+ overflow: auto;+ display: grid;+ gap: 2px;+}+.asx-pick li button {+ width: 100%;+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 6px 8px;+ border: 0;+ border-radius: 10px;+ background: none;+ color: var(--text);+ font: inherit;+ text-align: left;+ cursor: pointer;+}+.asx-pick li button > span {+ display: grid;+ min-width: 0;+}+.asx-pick li small {+ color: var(--text2);+ font-size: 11.5px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.asx-pick li button:hover {+ background: color-mix(in srgb, var(--text) 7%, transparent);+}+.asx-pick li button[aria-selected='true'] {+ background: color-mix(in srgb, var(--accent) 16%, transparent);+}+.asx-pick > small {+ color: var(--text2);+ font-size: 12px;+ padding: 0 4px;+}+.asx-pick > small:empty {+ display: none;+}++/* conversation */+.asx-log {+ flex: 1;+ min-height: 0;+ overflow: auto;+ overscroll-behavior: contain;+ padding: 14px 14px 6px;+ display: flex;+ flex-direction: column;+ gap: 10px;+ scrollbar-width: thin;+}+.asx-hello {+ margin: auto 0;+ display: grid;+ justify-items: center;+ gap: 8px;+ text-align: center;+ padding: 12px 6px;+}+.asx-hello img,+.asx-hello > i {+ width: 56px;+ height: 56px;+ border-radius: 18px;+ font-size: 22px;+}+.asx-hello b {+ font-size: 18px;+ font-weight: 650;+}+.asx-hello span {+ color: var(--text2);+ max-width: 30ch;+}+.asx-sugs {+ display: grid;+ gap: 6px;+ width: 100%;+ margin-top: 10px;+}+.asx-sugs button {+ padding: 10px 12px;+ border-radius: 12px;+ border: 1px solid color-mix(in srgb, var(--text) 10%, transparent);+ background: color-mix(in srgb, var(--card) 60%, transparent);+ color: var(--text);+ font: inherit;+ text-align: left;+ cursor: pointer;+ transition:+ background 0.15s,+ border-color 0.15s;+}+.asx-sugs button:hover {+ background: color-mix(in srgb, var(--card) 90%, transparent);+ border-color: color-mix(in srgb, var(--accent) 50%, transparent);+}+.asx-sugs button:active {+ transform: scale(0.99);+}+.asx-msg {+ max-width: 88%;+ line-height: 1.5;+ overflow-wrap: anywhere;+}+.asx-msg.me {+ align-self: flex-end;+ padding: 8px 12px;+ border-radius: 16px 16px 4px 16px;+ background: var(--accent);+ color: #fff;+ white-space: pre-wrap;+}+.asx-msg.ai {+ align-self: flex-start;+ max-width: 100%;+}+.asx-msg.ai p,+.asx-msg.ai ul,+.asx-msg.ai ol,+.asx-msg.ai pre,+.asx-msg.ai h4 {+ margin: 0 0 8px;+}+.asx-msg.ai > :last-child {+ margin-bottom: 0;+}+.asx-msg.ai ul,+.asx-msg.ai ol {+ padding-left: 20px;+}+.asx-msg.ai h4 {+ font-size: 14px;+}+.asx-msg.ai a {+ color: var(--accent);+ text-underline-offset: 2px;+}+.asx-msg code {+ padding: 1px 5px;+ border-radius: 5px;+ font-size: 12.5px;+ background: color-mix(in srgb, var(--text) 9%, transparent);+ overflow-wrap: anywhere;+}+.asx-msg pre {+ padding: 10px;+ border-radius: 10px;+ overflow: auto;+ background: color-mix(in srgb, var(--text) 8%, transparent);+}+.asx-msg pre code {+ padding: 0;+ background: none;+}+.asx-msg.typing > :last-child::after {+ content: '';+ display: inline-block;+ width: 7px;+ height: 14px;+ margin-left: 2px;+ vertical-align: -2px;+ border-radius: 2px;+ background: var(--accent);+ animation: asx-blink 1s steps(2) infinite;+}+@keyframes asx-blink {+ 50% {+ opacity: 0;+ }+}+.asx-dots {+ display: inline-flex;+ gap: 4px;+ padding: 6px 0;+}+.asx-dots i {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: var(--text2);+ animation: asx-bounce 1s infinite ease-in-out;+}+.asx-dots i:nth-child(2) {+ animation-delay: 0.15s;+}+.asx-dots i:nth-child(3) {+ animation-delay: 0.3s;+}+.asx-msg.typing .asx-dots::after {+ content: none;+}+@keyframes asx-bounce {+ 0%,+ 80%,+ 100% {+ transform: translateY(0);+ opacity: 0.5;+ }+ 40% {+ transform: translateY(-4px);+ opacity: 1;+ }+}+.asx-err {+ color: #f0524f;+ font-size: 12.5px;+}+[data-theme='light'] .asx-err {+ color: #c62f2c;+}+.asx-acts {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ margin-top: 8px;+}+.asx-acts button {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 32px;+ padding: 0 12px;+ border-radius: 99px;+ border: 1px solid color-mix(in srgb, var(--accent) 45%, transparent);+ background: color-mix(in srgb, var(--accent) 12%, transparent);+ color: var(--text);+ font: inherit;+ font-size: 12.5px;+ font-weight: 600;+ cursor: pointer;+}+.asx-acts button:hover {+ background: color-mix(in srgb, var(--accent) 22%, transparent);+}+.asx-acts button:active {+ transform: scale(0.97);+}++/* composer */+.asx-form {+ display: flex;+ align-items: flex-end;+ gap: 8px;+ margin: 6px 12px 4px;+ padding: 6px 6px 6px 12px;+ border-radius: 16px;+ border: 1px solid color-mix(in srgb, var(--text) 12%, transparent);+ background: color-mix(in srgb, var(--card) 80%, transparent);+}+.asx-form:focus-within {+ border-color: var(--accent);+}+.asx-form textarea {+ flex: 1;+ min-width: 0;+ resize: none;+ max-height: 160px;+ padding: 7px 0;+ border: 0;+ background: none;+ color: var(--text);+ font: inherit;+ line-height: 1.4;+ outline: none;+}+.asx-form textarea:focus-visible {+ outline: none;+}+.asx-form textarea::placeholder {+ color: var(--text2);+}+.asx-send {+ flex: none;+ display: grid;+ place-items: center;+ width: 34px;+ height: 34px;+ border: 0;+ border-radius: 11px;+ background: var(--accent);+ color: #fff;+ cursor: pointer;+ transition:+ opacity 0.15s,+ transform 0.1s;+}+.asx-send:hover:not(:disabled) {+ background: color-mix(in srgb, var(--accent) 86%, #fff);+}+.asx-send:active:not(:disabled) {+ transform: scale(0.94);+}+.asx-send:disabled {+ opacity: 0.4;+ cursor: default;+}+.asx-send.stop {+ background: color-mix(in srgb, var(--text) 80%, transparent);+ color: var(--bg);+}+.asx-foot {+ margin: 0;+ padding: 2px 14px 10px;+ color: var(--text2);+ font-size: 10.5px;+ text-align: center;+}++@media (max-width: 640px) {+ .asx {+ top: 8px;+ right: 8px;+ left: 8px;+ width: auto;+ }+}+@media (prefers-reduced-motion: reduce) {+ .asx {+ transition: none;+ }+ .asx-dots i,+ .asx-msg.typing > :last-child::after {+ animation: none;+ }+}diff --git a/src/desktop/assistant/index.js b/src/desktop/assistant/index.jsnew file mode 100644index 000000000..54f04774f--- /dev/null+++ b/src/desktop/assistant/index.js@@ -0,0 +1,366 @@+// The desktop assistant: a panel that slides in from the right edge, like the+// assistant pane of a modern OS. It streams real replies from /api/chat, can+// open any desktop app it suggests ([[open:app]] tags), and can hand the+// conversation to any public three.ws agent so the visitor talks to that+// agent's own brain. The shell calls toggleAssistant({ root, anchor, launchId, toast }).+// See README.md.++import './assistant.css';+import { icon } from '../icons.js';+import { ALL_APPS } from '../apps.js';+import { parseSse } from '../world/cast.js';+import { SUGGESTIONS, hidePartialTag, parseActions, renderMarkdown, systemPrompt, trimHistory } from './logic.js';++const STORE = 'tws-assistant:v1';+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+const APPS = ALL_APPS.filter((a) => a.id && a.title && !a.hidden);+const KNOWN = new Set(APPS.map((a) => a.id));+const appTitle = (id) => APPS.find((a) => a.id === id)?.title || id;++function loadState() {+ try {+ const s = JSON.parse(localStorage.getItem(STORE) || 'null');+ if (s && Array.isArray(s.messages)) return { messages: trimHistory(s.messages), agent: s.agent?.id ? s.agent : null };+ } catch {+ /* storage blocked or corrupt */+ }+ return { messages: [], agent: null };+}+function saveState(s) {+ try {+ localStorage.setItem(STORE, JSON.stringify({ messages: trimHistory(s.messages.filter((m) => !m.failed)), agent: s.agent }));+ } catch {+ /* storage blocked: the chat lasts for this visit */+ }+}++/** Stream one reply. `onText(textSoFar)` fires as chunks land. */+async function streamChat({ message, history, agent, signal, onText }) {+ const r = await fetch('/api/chat', {+ method: 'POST',+ credentials: 'same-origin',+ headers: { 'content-type': 'application/json', accept: 'text/event-stream' },+ signal,+ body: JSON.stringify({+ message,+ history: trimHistory(history),+ ...(agent ? { agentId: agent.id } : {}),+ system_prompt: systemPrompt(APPS, { agent }),+ context: { modelName: agent?.name || 'three.ws assistant', currentEnvironment: 'three.ws desktop' },+ }),+ });+ if (r.status === 429) throw new Error('Too many messages in a short time. Wait a minute, then try again.');+ if (!r.ok) {+ let detail = '';+ try {+ const j = await r.json();+ detail = j.error_description || j.message || '';+ } catch {+ /* no JSON body */+ }+ if (r.status === 401) detail = agent ? `Sign in to talk to ${agent.name}.` : 'Sign in to keep chatting.';+ throw new Error(detail || `The assistant could not answer (${r.status}).`);+ }+ if (!(r.headers.get('content-type') || '').includes('text/event-stream')) {+ const j = await r.json();+ const t = String(j.reply || j.text || '').trim();+ onText(t);+ return t;+ }+ const reader = r.body.getReader();+ const dec = new TextDecoder();+ let buf = '';+ let text = '';+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ buf += dec.decode(value, { stream: true });+ const parsed = parseSse(buf);+ buf = parsed.rest;+ for (const ev of parsed.events) {+ if (ev.type === 'chunk' && ev.text) {+ text += ev.text;+ onText(text);+ } else if (ev.type === 'done' && ev.reply && !text) {+ text = String(ev.reply);+ onText(text);+ } else if (ev.type === 'error') throw new Error(ev.message || 'The assistant could not answer.');+ }+ }+ return text.trim();+}++let panel = null;++export function toggleAssistant(ctx) {+ if (panel) {+ panel.close();+ return false;+ }+ panel = open(ctx);+ return true;+}++/** Close the assistant if it is open. */+export function closeAssistant() {+ panel?.close();+}++function open(ctx) {+ const state = loadState();+ let busy = null;+ const el = document.createElement('aside');+ el.className = 'asx';+ el.setAttribute('role', 'dialog');+ el.setAttribute('aria-label', 'Assistant');+ el.innerHTML =+ `<header class="asx-head"><button type="button" class="asx-who" aria-haspopup="dialog" title="Choose who you are talking to"></button>` ++ `<span class="asx-tools"><button type="button" class="asx-ib" data-new title="New chat" aria-label="New chat">${icon('edit', 17)}</button>` ++ `<button type="button" class="asx-ib" data-close title="Close" aria-label="Close assistant">${icon('close', 17)}</button></span></header>` ++ `<div class="asx-pick" hidden><div class="asx-search">${icon('search', 15)}<input type="search" placeholder="Search public agents" aria-label="Search public agents" autocomplete="off"></div><ul role="listbox" aria-label="Agents"></ul><small aria-live="polite"></small></div>` ++ `<div class="asx-log" role="log" aria-live="polite"></div>` ++ `<form class="asx-form"><textarea rows="1" maxlength="4000" placeholder="Ask anything" aria-label="Message"></textarea>` ++ `<button type="submit" class="asx-send" aria-label="Send">${icon('next', 17)}</button></form>` ++ `<p class="asx-foot">Replies are generated by AI and can be wrong. Never share a seed phrase or private key.</p>`;+ (ctx.root || document.body).append(el);++ const log = el.querySelector('.asx-log');+ const form = el.querySelector('form');+ const input = form.querySelector('textarea');+ const send = form.querySelector('.asx-send');+ const who = el.querySelector('.asx-who');+ const pick = el.querySelector('.asx-pick');++ // ---------- who you're talking to ----------+ const avatar = (a) =>+ a?.avatar_thumbnail ? `<img src="${esc(a.avatar_thumbnail)}" alt="" referrerpolicy="no-referrer">` : a ? `<i>${esc(a.name.slice(0, 1).toUpperCase())}</i>` : `<i class="asx-logo">${icon('sparkle', 15)}</i>`;+ const paintWho = () => {+ who.innerHTML = `${avatar(state.agent)}<span><b>${esc(state.agent?.name || 'Assistant')}</b><small>${state.agent ? 'three.ws agent' : 'three.ws'}</small></span>${icon('chevron', 12)}`;+ input.placeholder = state.agent ? `Message ${state.agent.name}` : 'Ask anything about three.ws';+ };+ el.addEventListener(+ 'error',+ (e) => {+ if (e.target instanceof HTMLImageElement) {+ const i = document.createElement('i');+ i.textContent = '?';+ e.target.replaceWith(i);+ }+ },+ true,+ );++ let searchSeq = 0;+ let searchTimer = 0;+ const pickInput = pick.querySelector('input');+ const pickList = pick.querySelector('ul');+ const pickNote = pick.querySelector('small');+ const choose = (agent) => {+ if ((agent?.id || null) !== (state.agent?.id || null)) {+ state.agent = agent;+ state.messages = [];+ saveState(state);+ paintLog();+ }+ paintWho();+ togglePick(false);+ input.focus();+ };+ const search = async () => {+ const my = ++searchSeq;+ const q = pickInput.value.trim();+ pickNote.textContent = 'Loading agents...';+ try {+ const r = await fetch(`/api/agents/public?${new URLSearchParams({ sort: 'popular', limit: '20', ...(q ? { q } : {}) })}`, { credentials: 'same-origin' });+ if (!r.ok) throw new Error(r.status === 429 ? 'Too many searches. Try again in a moment.' : `Agents are unavailable (${r.status}).`);+ const j = await r.json();+ if (my !== searchSeq) return;+ const agents = (j.agents || []).filter((a) => a.id && a.name);+ pickNote.textContent = agents.length ? '' : q ? `No public agent matches "${q}".` : 'No public agents yet.';+ pickList.innerHTML =+ `<li><button type="button" role="option" data-id="" aria-selected="${!state.agent}">${avatar(null)}<span><b>three.ws assistant</b><small>Knows the platform and opens apps for you</small></span></button></li>` ++ agents.map((a, i) => `<li><button type="button" role="option" data-i="${i}" aria-selected="${state.agent?.id === a.id}">${avatar(a)}<span><b>${esc(a.name)}</b><small>${esc(a.description || 'A three.ws agent')}</small></span></button></li>`).join('');+ pickList.querySelector('[data-id=""]').addEventListener('click', () => choose(null));+ pickList.querySelectorAll('[data-i]').forEach((b) => {+ const a = agents[b.dataset.i];+ b.addEventListener('click', () => choose({ id: a.id, name: a.name, avatar_thumbnail: a.avatar_thumbnail || null }));+ });+ } catch (e) {+ if (my === searchSeq) pickNote.textContent = e.message;+ }+ };+ const togglePick = (on = pick.hidden) => {+ pick.hidden = !on;+ who.setAttribute('aria-expanded', String(on));+ if (on) {+ search();+ pickInput.focus();+ }+ };+ who.addEventListener('click', () => togglePick());+ pickInput.addEventListener('input', () => {+ clearTimeout(searchTimer);+ searchTimer = setTimeout(search, 250);+ });++ // ---------- the conversation ----------+ const bubble = (m) => {+ const div = document.createElement('div');+ div.className = `asx-msg ${m.role === 'user' ? 'me' : 'ai'}`;+ fill(div, m);+ return div;+ };+ const fill = (div, m, streaming = false) => {+ if (m.role === 'user') {+ div.textContent = m.content;+ return;+ }+ const { text, actions } = parseActions(streaming ? hidePartialTag(m.content) : m.content, KNOWN);+ div.innerHTML = renderMarkdown(text) || (streaming ? '<span class="asx-dots" aria-label="Thinking"><i></i><i></i><i></i></span>' : '');+ if (m.error) div.insertAdjacentHTML('beforeend', `<p class="asx-err">${esc(m.error)}</p>`);+ if (!streaming && actions.length) {+ const row = document.createElement('div');+ row.className = 'asx-acts';+ for (const id of actions) {+ const b = document.createElement('button');+ b.type = 'button';+ b.innerHTML = `${icon(APPS.find((a) => a.id === id)?.icon || 'external', 14)}Open ${esc(appTitle(id))}`;+ b.addEventListener('click', () => ctx.launchId(id));+ row.append(b);+ }+ div.append(row);+ }+ div.classList.toggle('typing', streaming);+ };+ const paintLog = () => {+ log.replaceChildren();+ if (!state.messages.length) {+ const hi = document.createElement('div');+ hi.className = 'asx-hello';+ hi.innerHTML = state.agent+ ? `${avatar(state.agent)}<b>Talk with ${esc(state.agent.name)}</b><span>Replies come from this agent's own brain on three.ws.</span>`+ : `<i class="asx-logo big">${icon('sparkle', 26)}</i><b>How can I help?</b><span>Ask about three.ws, or have me open the right app for you.</span>` ++ `<div class="asx-sugs">${SUGGESTIONS.map((s, i) => `<button type="button" data-s="${i}">${esc(s.label)}</button>`).join('')}</div>`;+ hi.querySelectorAll('[data-s]').forEach((b) => b.addEventListener('click', () => ask(SUGGESTIONS[b.dataset.s].prompt)));+ log.append(hi);+ return;+ }+ for (const m of state.messages) log.append(bubble(m));+ log.scrollTop = log.scrollHeight;+ };++ const setBusy = (ctrl) => {+ busy = ctrl;+ send.innerHTML = ctrl ? icon('pause', 17) : icon('next', 17);+ send.setAttribute('aria-label', ctrl ? 'Stop' : 'Send');+ send.classList.toggle('stop', !!ctrl);+ };+ async function ask(text) {+ const message = String(text || '').trim();+ if (!message || busy) return;+ const history = state.messages.filter((m) => !m.failed);+ state.messages.push({ role: 'user', content: message });+ const reply = { role: 'assistant', content: '' };+ state.messages.push(reply);+ paintLog();+ const div = log.lastElementChild;+ fill(div, reply, true);+ log.scrollTop = log.scrollHeight;+ const ctrl = new AbortController();+ setBusy(ctrl);+ try {+ reply.content = await streamChat({+ message,+ history,+ agent: state.agent,+ signal: ctrl.signal,+ onText: (t) => {+ reply.content = t;+ fill(div, reply, true);+ const near = log.scrollHeight - log.scrollTop - log.clientHeight < 80;+ if (near) log.scrollTop = log.scrollHeight;+ },+ });+ if (!reply.content) reply.error = 'No reply came back. Try asking again.';+ } catch (e) {+ if (e.name === 'AbortError') {+ if (!reply.content) reply.error = 'Stopped.';+ } else reply.error = e.message || 'The assistant could not answer.';+ } finally {+ setBusy(null);+ fill(div, reply);+ // Failed turns stay on screen but never go back to the model.+ if (!reply.content) {+ reply.failed = true;+ state.messages[state.messages.length - 2].failed = true;+ }+ saveState(state);+ log.scrollTop = log.scrollHeight;+ }+ }++ form.addEventListener('submit', (e) => {+ e.preventDefault();+ if (busy) return busy.abort();+ const t = input.value;+ input.value = '';+ grow();+ ask(t);+ });+ const grow = () => {+ input.style.height = 'auto';+ input.style.height = `${Math.min(input.scrollHeight, 160)}px`;+ send.disabled = !busy && !input.value.trim();+ };+ input.addEventListener('input', grow);+ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {+ e.preventDefault();+ form.requestSubmit();+ }+ });+ el.querySelector('[data-new]').addEventListener('click', () => {+ busy?.abort();+ state.messages = [];+ saveState(state);+ paintLog();+ input.focus();+ });+ el.querySelector('[data-close]').addEventListener('click', () => close());+ const onKey = (e) => {+ if (e.key !== 'Escape') return;+ if (!pick.hidden) return togglePick(false);+ close();+ ctx.anchor?.focus?.();+ };+ el.addEventListener('keydown', onKey);+ // Keep the stored conversation in step with another tab.+ const onStorage = (e) => {+ if (e.key !== STORE || busy) return;+ const s = loadState();+ state.messages = s.messages;+ state.agent = s.agent;+ paintWho();+ paintLog();+ };+ addEventListener('storage', onStorage);++ paintWho();+ paintLog();+ grow();+ ctx.anchor?.setAttribute?.('aria-expanded', 'true');+ requestAnimationFrame(() => el.classList.add('in'));+ setTimeout(() => input.focus({ preventScroll: true }), 60);++ function close() {+ if (panel?.el !== el) return;+ panel = null;+ busy?.abort();+ clearTimeout(searchTimer);+ removeEventListener('storage', onStorage);+ ctx.anchor?.setAttribute?.('aria-expanded', 'false');+ el.classList.remove('in');+ setTimeout(() => el.remove(), matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 220);+ }+ return { el, close };+}diff --git a/src/desktop/assistant/logic.js b/src/desktop/assistant/logic.jsnew file mode 100644index 000000000..9a8ac2486--- /dev/null+++ b/src/desktop/assistant/logic.js@@ -0,0 +1,151 @@+// Pure helpers for the desktop assistant: the grounding prompt, the+// [[open:app]] actions a reply may carry, history trimming for /api/chat, and+// a small safe Markdown renderer. No DOM, no network: unit tested.++export const THREE_CA = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+export const HISTORY_MAX = 20;+const PROMPT_MAX = 2000;+const TURN_MAX = 4000;++/**+ * The system prompt for the platform assistant. `apps` is [{ id, title, desc }];+ * the list is trimmed to keep the whole prompt under the API's 2000 characters.+ */+export function systemPrompt(apps = [], { now = new Date(), agent = null } = {}) {+ const date = now.toISOString().slice(0, 10);+ if (agent) {+ return (+ `You are ${agent.name}, a three.ws agent, talking with a visitor inside the three.ws desktop. Stay in character, be concise and friendly. ` ++ `Today is ${date}. Never invent prices, balances or facts you do not have. Never ask for seed phrases or private keys.`+ ).slice(0, PROMPT_MAX);+ }+ const head =+ `You are the three.ws assistant, built into the three.ws desktop in the visitor's browser. three.ws is a platform for 3D AI agents with avatars, wallets and their own coins on Solana. ` ++ `Answer concisely in plain language with short paragraphs or lists. Today is ${date}. ` ++ `$THREE is the platform's coin (contract ${THREE_CA}); it is the only coin you recommend. Never give financial advice, invent prices or balances, or ask for seed phrases or private keys. ` ++ `When an app would help, end your reply with one or two tags like [[open:appId]] using only these ids:\n`;+ const tail = '\nDo not use any other app id.';+ let list = '';+ for (const a of apps) {+ const line = `${a.id}: ${a.title}${a.desc ? ` (${a.desc})` : ''}\n`;+ if (head.length + list.length + line.length + tail.length > PROMPT_MAX) break;+ list += line;+ }+ return `${head}${list.trimEnd()}${tail}`;+}++/**+ * Pull [[open:appId]] tags out of a reply. Only ids in `known` survive, each+ * once; the tags are removed from the text either way.+ */+export function parseActions(text, known) {+ const ok = known instanceof Set ? known : new Set(known || []);+ const actions = [];+ const clean = String(text || '')+ .replace(/\[\[\s*open\s*:\s*([\w:/.-]+)\s*\]\]/gi, (_, id) => {+ if (ok.has(id) && !actions.includes(id)) actions.push(id);+ return '';+ })+ .replace(/[ \t]+\n/g, '\n')+ .replace(/\n{3,}/g, '\n\n')+ .trim();+ return { text: clean, actions };+}++/** A tag still being typed at the end of a streamed reply: hide it until it closes. */+export function hidePartialTag(text) {+ return String(text || '').replace(/\[\[[^\]]*\]?$/, '');+}++/** The history /api/chat accepts: the last 20 user/assistant turns, text only, capped. */+export function trimHistory(messages) {+ return (Array.isArray(messages) ? messages : [])+ .filter((m) => m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string' && m.content.trim())+ .map((m) => ({ role: m.role, content: m.content.slice(0, TURN_MAX) }))+ .slice(-HISTORY_MAX);+}++const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);++function inline(s) {+ // Code spans first so their contents are not formatted.+ const codes = [];+ let out = esc(s).replace(/`([^`\n]+)`/g, (_, c) => {+ codes.push(c);+ return `\u0000${codes.length - 1}\u0000`;+ });+ out = out+ .replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+|\/(?!\/)[^\s)]*)\)/g, (_, label, href) => `<a href="${href}" target="_blank" rel="noopener noreferrer">${label}</a>`)+ .replace(/(^|[\s(])(https?:\/\/[^\s<)]+[^\s<).,;:!?'"])/g, (_, pre, url) => `${pre}<a href="${url}" target="_blank" rel="noopener noreferrer">${url}</a>`)+ .replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>')+ .replace(/(^|[^*\w])\*([^*\n]+)\*(?!\w)/g, '$1<em>$2</em>');+ return out.replace(/\u0000(\d+)\u0000/g, (_, i) => `<code>${codes[i]}</code>`);+}++/**+ * Render a reply as safe HTML: paragraphs, bullet and numbered lists,+ * headings, fenced code, bold, italics, inline code and links. Everything+ * else is escaped text.+ */+export function renderMarkdown(text) {+ const lines = String(text || '').replace(/\r\n?/g, '\n').split('\n');+ const out = [];+ let list = null;+ let para = [];+ let fence = null;+ const flushPara = () => {+ if (para.length) out.push(`<p>${para.map(inline).join('<br>')}</p>`);+ para = [];+ };+ const flushList = () => {+ if (list) out.push(`<${list.tag}>${list.items.map((i) => `<li>${inline(i)}</li>`).join('')}</${list.tag}>`);+ list = null;+ };+ for (const line of lines) {+ if (fence) {+ if (/^```/.test(line)) {+ out.push(`<pre><code>${esc(fence.join('\n'))}</code></pre>`);+ fence = null;+ } else fence.push(line);+ continue;+ }+ if (/^```/.test(line)) {+ flushPara();+ flushList();+ fence = [];+ continue;+ }+ const bullet = line.match(/^\s*[-*•]\s+(.*)$/);+ const num = line.match(/^\s*\d+[.)]\s+(.*)$/);+ const head = line.match(/^\s{0,3}#{1,4}\s+(.*)$/);+ if (bullet || num) {+ flushPara();+ const tag = bullet ? 'ul' : 'ol';+ if (list && list.tag !== tag) flushList();+ list ||= { tag, items: [] };+ list.items.push((bullet || num)[1]);+ } else if (head) {+ flushPara();+ flushList();+ out.push(`<h4>${inline(head[1])}</h4>`);+ } else if (!line.trim()) {+ flushPara();+ flushList();+ } else {+ flushList();+ para.push(line.trim());+ }+ }+ if (fence) out.push(`<pre><code>${esc(fence.join('\n'))}</code></pre>`);+ flushPara();+ flushList();+ return out.join('');+}++/** Starter prompts shown on an empty conversation. */+export const SUGGESTIONS = [+ { label: 'What can I build on three.ws?', prompt: 'What can I build on three.ws? Give me the three best places to start.' },+ { label: 'Make my first agent', prompt: 'Walk me through creating my first 3D agent, step by step.' },+ { label: 'What is $THREE?', prompt: 'What is $THREE and how does it fit into three.ws?' },+ { label: 'Turn a prompt into a 3D model', prompt: 'How do I turn a text prompt into a textured 3D model here?' },+];diff --git a/src/desktop/widgets/README.md b/src/desktop/widgets/README.mdnew file mode 100644index 000000000..d833a4ad8--- /dev/null+++ b/src/desktop/widgets/README.md@@ -0,0 +1,36 @@+# src/desktop/widgets++Live widgets for the web desktop: cards pinned to the desktop itself, and the+widgets board that slides in from the taskbar's Widgets button. Every value+comes from a real three.ws endpoint, Open-Meteo or the device; a feed that+fails says so and offers a retry. Guide: [docs/desktop-widgets.md](../../../docs/desktop-widgets.md).++| File | Role |+| --- | --- |+| `logic.js` | Pure rules: the catalog (`CATALOG`), sizes, the desktop grid with first-fit placement and stored-layout validation (`gridFor`, `fits`, `firstFit`, `settle`, `cellAt`), number, price and time formatting, sparkline geometry, weather codes, the month grid. Unit tested in `tests/desktop-widgets.test.js` |+| `data.js` | Shared feeds (`subscribe`, `refresh`): one fetch per feed for every widget that reads it, polled on its own cadence, paused while the tab is hidden, last good data kept on failure. Also the weather place (saved city, geolocation, Open-Meteo geocoding search) |+| `render.js` | One renderer per widget type (`renderWidget`), with skeleton, offline and empty states |+| `index.js` | The shell surface: `mountDesktopWidgets` (grid layer, drag to move, edit mode, Add widget gallery), `toggleWidgets` / `closeWidgets` (the board with a greeting, your widgets and a news column), `editDesktopWidgets`, `addDesktopWidget` |+| `widgets.css` | Card, per-widget, desktop layer, edit mode, menus, gallery and board styles; light and dark through the shell tokens; phone and reduced-motion rules |++## Feeds++| Feed | Source | Refresh |+| --- | --- | --- |+| `token` | `/api/three-token/stats` | 60 s |+| `history` | `/api/pump/price-history` (15 minute candles, last 24 h) | 5 min |+| `stats` | `/api/stats` | 60 s |+| `agents` | `/api/agents/public?sort=newest` | 2 min |+| `pulse` | `/api/pulse` | 15 s |+| `launches` | `/api/pump/launches` | 2 min |+| `news` | `/api/news/feed?featured=1` | 5 min |+| `weather` | Open-Meteo forecast for the saved or located place | 15 min |++Clock, Calendar, System (Battery, Network Information, memory and storage+estimates where the browser exposes them) and Sticky note read the device only.++## Storage++`tws-widgets:desktop` (desktop layout), `tws-widgets:board` (board widgets),+`tws-widgets:place` (weather place). A sticky note's text is saved inside its+layout entry. All in `localStorage`; a missing or corrupt value falls back to the default layout.diff --git a/src/desktop/widgets/data.js b/src/desktop/widgets/data.jsnew file mode 100644index 000000000..77a16d7f5--- /dev/null+++ b/src/desktop/widgets/data.js@@ -0,0 +1,196 @@+// Live sources for the widgets. Each feed is fetched once and shared by every+// widget that reads it (desktop and board alike), polled on its own cadence+// while anyone subscribes, paused while the tab is hidden, and refreshed the+// moment it comes back. A failed fetch keeps the last good data and reports+// the error, so a widget can show stale numbers with a note or an offline+// state with a retry. Nothing here invents a value.++import { tzCity, usesFahrenheit } from './logic.js';++export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const PLACE_KEY = 'tws-widgets:place';++async function getJson(url, init) {+ const r = await fetch(url, { credentials: 'same-origin', headers: { accept: 'application/json' }, ...init });+ if (!r.ok) throw new Error(`${r.status === 429 ? 'Rate limited' : 'Unavailable'} (${r.status})`);+ return r.json();+}++// ---------- place (for weather) ----------++function readPlace() {+ try {+ const p = JSON.parse(localStorage.getItem(PLACE_KEY) || 'null');+ if (p && Number.isFinite(p.lat) && Number.isFinite(p.lon) && typeof p.name === 'string') return p;+ } catch {+ /* storage blocked or corrupt */+ }+ return null;+}++export function setPlace(place) {+ try {+ localStorage.setItem(PLACE_KEY, JSON.stringify(place));+ } catch {+ /* storage blocked: the place still applies for this visit */+ }+ memoPlace = place;+ refresh('weather');+}+let memoPlace = null;++/** Open-Meteo geocoding: city search for the weather widget. */+export async function searchPlaces(q) {+ const name = String(q || '').trim();+ if (name.length < 2) return [];+ const j = await getJson(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(name)}&count=6&language=${encodeURIComponent((navigator.language || 'en').slice(0, 2))}&format=json`, { credentials: 'omit' });+ return (j.results || []).map((r) => ({ name: r.name, region: [r.admin1, r.country].filter(Boolean).join(', '), lat: r.latitude, lon: r.longitude }));+}++/** Ask the browser for the device position (prompts the visitor). */+export function locate() {+ return new Promise((resolve, reject) => {+ if (!navigator.geolocation) return reject(new Error('This browser cannot share a location.'));+ navigator.geolocation.getCurrentPosition(+ (p) => resolve({ name: 'Your location', region: '', lat: +p.coords.latitude.toFixed(3), lon: +p.coords.longitude.toFixed(3), device: true }),+ (e) => reject(new Error(e.code === 1 ? 'Location permission was denied.' : 'Your location is unavailable right now.')),+ { timeout: 10000, maximumAge: 30 * 60 * 1000 },+ );+ });+}++/**+ * The weather place: the one the visitor chose, else the city named by their+ * time zone (geocoded, never guessed coordinates). Null when neither exists,+ * which the widget shows as "Choose a city".+ */+async function resolvePlace() {+ memoPlace ||= readPlace();+ if (memoPlace) return memoPlace;+ const city = tzCity(Intl.DateTimeFormat().resolvedOptions().timeZone);+ if (!city) return null;+ const [hit] = await searchPlaces(city);+ if (hit) memoPlace = { ...hit, fromZone: true };+ return memoPlace;+}++async function loadWeather() {+ const place = await resolvePlace();+ if (!place) return { place: null };+ const q = new URLSearchParams({+ latitude: String(place.lat),+ longitude: String(place.lon),+ current: 'temperature_2m,apparent_temperature,relative_humidity_2m,weather_code,is_day,wind_speed_10m',+ hourly: 'temperature_2m,weather_code,is_day',+ daily: 'temperature_2m_max,temperature_2m_min,weather_code',+ forecast_days: '5',+ timezone: 'auto',+ });+ if (usesFahrenheit(navigator.language)) {+ q.set('temperature_unit', 'fahrenheit');+ q.set('wind_speed_unit', 'mph');+ }+ const j = await getJson(`https://api.open-meteo.com/v1/forecast?${q}`, { credentials: 'omit' });+ const now = Date.now();+ const hours = (j.hourly?.time || [])+ .map((t, i) => ({ t: Date.parse(`${t}${offsetSuffix(j.utc_offset_seconds)}`), temp: j.hourly.temperature_2m[i], code: j.hourly.weather_code[i], day: !!j.hourly.is_day[i] }))+ .filter((x) => x.t >= now - 3600_000)+ .slice(0, 6);+ const days = (j.daily?.time || []).map((t, i) => ({ date: t, hi: j.daily.temperature_2m_max[i], lo: j.daily.temperature_2m_min[i], code: j.daily.weather_code[i] }));+ return { place, current: j.current, hours, days, unit: j.current_units?.temperature_2m || '°C', wind: j.current_units?.wind_speed_10m || 'km/h' };+}+const offsetSuffix = (s) => {+ const n = Number(s) || 0;+ const sign = n < 0 ? '-' : '+';+ const a = Math.abs(n);+ return `${sign}${String(Math.floor(a / 3600)).padStart(2, '0')}:${String(Math.floor((a % 3600) / 60)).padStart(2, '0')}`;+};++// ---------- the feeds ----------++const SOURCES = {+ token: { ttl: 60_000, load: () => getJson('/api/three-token/stats').then((j) => j.token) },+ history: {+ ttl: 300_000,+ load: () => {+ const to = Math.floor(Date.now() / 1000);+ return getJson(`/api/pump/price-history?mint=${THREE_MINT}&interval=15m&from=${to - 86400}&to=${to}`).then((j) => ({ candles: j.data || [], stale: !!j.stale }));+ },+ },+ stats: { ttl: 60_000, load: () => getJson('/api/stats').then((j) => j.stats) },+ agents: { ttl: 120_000, load: () => getJson('/api/agents/public?sort=newest&limit=12').then((j) => j.agents || []) },+ pulse: { ttl: 15_000, load: () => getJson('/api/pulse?limit=12').then((j) => j.data?.events || []) },+ launches: { ttl: 120_000, load: () => getJson('/api/pump/launches?limit=8').then((j) => j.data?.launches || []) },+ news: { ttl: 300_000, load: () => getJson('/api/news/feed?limit=12&featured=1').then((j) => j.articles || []) },+ weather: { ttl: 15 * 60_000, load: loadWeather },+};++const state = new Map();+const entry = (key) => {+ let e = state.get(key);+ if (!e) {+ e = { data: undefined, error: null, at: 0, loading: false, subs: new Set(), timer: 0 };+ state.set(key, e);+ }+ return e;+};+const emit = (e) => e.subs.forEach((fn) => fn({ data: e.data, error: e.error, at: e.at, loading: e.loading }));++async function load(key) {+ const src = SOURCES[key];+ const e = entry(key);+ if (!src || e.loading) return;+ e.loading = true;+ emit(e);+ try {+ e.data = await src.load();+ e.error = null;+ e.at = Date.now();+ } catch (err) {+ e.error = err?.message || 'Unavailable';+ } finally {+ e.loading = false;+ emit(e);+ schedule(key);+ }+}++function schedule(key) {+ const e = entry(key);+ clearTimeout(e.timer);+ if (!e.subs.size || document.hidden) return;+ // A failing source backs off to twice its cadence so an outage is not hammered.+ const wait = SOURCES[key].ttl * (e.error ? 2 : 1);+ e.timer = setTimeout(() => load(key), wait);+}++/** Refetch now (the Retry button, a changed place). */+export function refresh(key) {+ return load(key);+}++/**+ * Subscribe to a feed. `fn` gets { data, error, at, loading } now and on every+ * change. Returns the unsubscribe function.+ */+export function subscribe(key, fn) {+ if (!SOURCES[key]) throw new Error(`Unknown widget feed: ${key}`);+ const e = entry(key);+ e.subs.add(fn);+ fn({ data: e.data, error: e.error, at: e.at, loading: e.loading });+ if (!e.at || Date.now() - e.at > SOURCES[key].ttl) load(key);+ else schedule(key);+ return () => {+ e.subs.delete(fn);+ if (!e.subs.size) clearTimeout(e.timer);+ };+}++document.addEventListener('visibilitychange', () => {+ if (document.hidden) return state.forEach((e) => clearTimeout(e.timer));+ for (const [key, e] of state) {+ if (!e.subs.size) continue;+ if (Date.now() - e.at > SOURCES[key].ttl) load(key);+ else schedule(key);+ }+});diff --git a/src/desktop/widgets/index.js b/src/desktop/widgets/index.jsnew file mode 100644index 000000000..75e053ed4--- /dev/null+++ b/src/desktop/widgets/index.js@@ -0,0 +1,611 @@+// The desktop widgets: a board that slides up from the taskbar (widgets on the+// left, the live news desk on the right) and widgets pinned on the desktop+// itself, dragged on a snapping grid, resized, added from a gallery and+// removed in edit mode. Layouts persist per browser. The shell drives it+// through toggleWidgets, mountDesktopWidgets, editDesktopWidgets and+// addDesktopWidget; README.md lists what each takes.++import './widgets.css';+import { icon } from '../icons.js';+import { CATALOG, DEFAULT_LAYOUT, SIZES, STEP, catalogItem, cellAt, firstFit, fits, gridFor, pixelBox, relTime, settle } from './logic.js';+import { renderWidget, handleBrokenImages, WIDGET_ICONS } from './render.js';+import { refresh, subscribe } from './data.js';++const DESK_KEY = 'tws-widgets:desktop';+const BOARD_KEY = 'tws-widgets:board';+const BOARD_DEFAULT = [+ { type: 'three', size: 'm' },+ { type: 'weather', size: 'm' },+ { type: 'clock', size: 's' },+ { type: 'platform', size: 's' },+ { type: 'agents', size: 'm' },+ { type: 'launches', size: 'l' },+ { type: 'calendar', size: 'l' },+];+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+const LOCALE = navigator.language || 'en-US';++function load(key, fallback) {+ try {+ const v = JSON.parse(localStorage.getItem(key) || 'null');+ if (Array.isArray(v)) return v;+ } catch {+ /* storage blocked or corrupt: start from the default */+ }+ return fallback.map((w) => ({ ...w }));+}+function save(key, list) {+ try {+ localStorage.setItem(key, JSON.stringify(list.map(({ id, type, size, col, row, data }) => ({ id, type, size, col, row, ...(data ? { data } : {}) }))));+ } catch {+ /* storage blocked: the layout lasts for this visit */+ }+}+const newId = () => `w${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;++// ---------- small menu ----------++// Menus and the gallery mount inside the shell root so they inherit the .os theme tokens.+let osRoot = null;+const layerHost = () => (osRoot?.isConnected ? osRoot : document.body);+let openMenu = null;+function closeMenu() {+ openMenu?.remove();+ openMenu = null;+}+function menu(x, y, items, host = layerHost()) {+ closeMenu();+ const m = document.createElement('div');+ m.className = 'wgx-menu';+ m.setAttribute('role', 'menu');+ for (const it of items) {+ if (it === '-') {+ m.append(Object.assign(document.createElement('hr'), {}));+ continue;+ }+ const [label, ic, fn, on] = it;+ const b = document.createElement('button');+ b.type = 'button';+ b.setAttribute('role', 'menuitem');+ if (on) b.classList.add('on');+ b.innerHTML = `${icon(ic, 15)}<span>${esc(label)}</span>${on ? icon('check', 14) : ''}`;+ b.addEventListener('click', (e) => {+ e.stopPropagation();+ closeMenu();+ fn();+ });+ m.append(b);+ }+ host.append(m);+ const r = m.getBoundingClientRect();+ m.style.left = `${Math.max(8, Math.min(x, innerWidth - r.width - 8))}px`;+ m.style.top = `${Math.max(8, Math.min(y, innerHeight - r.height - 8))}px`;+ openMenu = m;+ m.querySelector('button')?.focus({ preventScroll: true });+ m.addEventListener('keydown', (e) => {+ const bs = [...m.querySelectorAll('button')];+ const i = bs.indexOf(document.activeElement);+ if (e.key === 'ArrowDown') bs[(i + 1) % bs.length].focus();+ else if (e.key === 'ArrowUp') bs[(i - 1 + bs.length) % bs.length].focus();+ else if (e.key === 'Escape') closeMenu();+ else return;+ e.preventDefault();+ });+}+addEventListener('pointerdown', (e) => openMenu && !openMenu.contains(e.target) && closeMenu(), true);+addEventListener('blur', closeMenu);++// ---------- one widget card ----------++/**+ * Build a widget card. `opts.menu(w)` returns the extra menu items for where+ * the card lives (desktop or board); `opts.onSave(w)` persists `w.data`.+ */+function card(w, ctx, opts) {+ const item = catalogItem(w.type);+ const el = document.createElement('section');+ el.className = `wgx t-${w.type} sz-${w.size}`;+ el.dataset.id = w.id;+ el.setAttribute('aria-label', `${item.title} widget`);+ const head = document.createElement('header');+ head.innerHTML =+ `<button type="button" class="wgx-title" ${item.app ? '' : 'disabled'} title="${item.app ? `Open ${esc(item.title)}` : esc(item.title)}">${icon(WIDGET_ICONS[w.type] || 'widgets', 14)}<b>${esc(item.title)}</b></button>` ++ `<button type="button" class="wgx-more" aria-label="${esc(item.title)} widget options" aria-haspopup="menu">${icon('more', 16)}</button>`;+ const body = document.createElement('div');+ body.className = 'wgx-body';+ el.append(head, body);+ handleBrokenImages(el);+ if (item.app) head.querySelector('.wgx-title').addEventListener('click', () => ctx.launchId(item.app));+ const items = () => [+ ...item.sizes.map((s) => [SIZES[s].label, 'maximize', () => opts.resize(w, s), w.size === s]),+ '-',+ ...(item.feeds.length ? [['Refresh', 'reload', () => item.feeds.forEach(refresh)]] : []),+ ...(item.app ? [[`Open ${item.title}`, 'external', () => ctx.launchId(item.app)]] : []),+ ...opts.menu(w),+ ];+ const more = head.querySelector('.wgx-more');+ more.addEventListener('click', (e) => {+ e.stopPropagation();+ const r = more.getBoundingClientRect();+ menu(r.left, r.bottom + 4, items());+ });+ el.addEventListener('contextmenu', (e) => {+ if (e.target.closest('textarea, input')) return;+ e.preventDefault();+ e.stopPropagation();+ menu(e.clientX, e.clientY, items());+ });+ let cleanup = renderWidget(body, w, {+ launchId: ctx.launchId,+ toast: ctx.toast,+ save: (data) => {+ w.data = data;+ opts.onSave(w);+ },+ });+ el.dispose = () => {+ cleanup();+ cleanup = () => {};+ };+ return el;+}++// ---------- the Add widget gallery ----------++function gallery(ctx, onAdd, title = 'Add a widget') {+ const back = document.createElement('div');+ back.className = 'wgx-gallery-back';+ const dlg = document.createElement('div');+ dlg.className = 'wgx-gallery';+ dlg.setAttribute('role', 'dialog');+ dlg.setAttribute('aria-modal', 'true');+ dlg.setAttribute('aria-label', title);+ let pick = CATALOG[0];+ let size = pick.sizes[0];+ let preview = null;+ dlg.innerHTML =+ `<header><b>${esc(title)}</b><button type="button" class="wgx-btn icon" data-close aria-label="Close">${icon('close', 16)}</button></header>` ++ `<div class="wgx-gal-main"><ul class="wgx-gal-list" role="listbox" aria-label="Widgets">${CATALOG.map((c, i) => `<li><button type="button" role="option" data-i="${i}">${icon(WIDGET_ICONS[c.type], 18)}<span><b>${esc(c.title)}</b><small>${esc(c.desc)}</small></span></button></li>`).join('')}</ul>` ++ `<div class="wgx-gal-preview"><div class="wgx-gal-stage"></div><div class="wgx-gal-sizes" role="radiogroup" aria-label="Size"></div><button type="button" class="wgx-btn primary wgx-gal-add">${icon('pin', 15)}Add widget</button></div></div>`;+ back.append(dlg);+ layerHost().append(back);+ const stage = dlg.querySelector('.wgx-gal-stage');+ const sizes = dlg.querySelector('.wgx-gal-sizes');+ const paint = () => {+ dlg.querySelectorAll('[data-i]').forEach((b) => b.setAttribute('aria-selected', String(CATALOG[b.dataset.i] === pick)));+ sizes.innerHTML = pick.sizes.map((s) => `<button type="button" role="radio" aria-checked="${s === size}" data-s="${s}">${SIZES[s].label}</button>`).join('');+ sizes.querySelectorAll('[data-s]').forEach((b) =>+ b.addEventListener('click', () => {+ size = b.dataset.s;+ paint();+ }),+ );+ preview?.dispose();+ preview = card({ id: 'preview', type: pick.type, size }, ctx, { menu: () => [], resize: (_, s) => ((size = s), paint()), onSave: () => {} });+ preview.classList.add('preview');+ stage.replaceChildren(preview);+ };+ dlg.querySelectorAll('[data-i]').forEach((b) =>+ b.addEventListener('click', () => {+ pick = CATALOG[b.dataset.i];+ size = pick.sizes[0];+ paint();+ }),+ );+ const close = () => {+ preview?.dispose();+ back.remove();+ removeEventListener('keydown', onKey, true);+ };+ const onKey = (e) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ close();+ }+ };+ addEventListener('keydown', onKey, true);+ back.addEventListener('pointerdown', (e) => e.target === back && close());+ dlg.querySelector('[data-close]').addEventListener('click', close);+ dlg.querySelector('.wgx-gal-add').addEventListener('click', () => {+ if (onAdd({ type: pick.type, size }) !== false) close();+ });+ paint();+ dlg.querySelector('[data-i]').focus({ preventScroll: true });+}++// ---------- desktop widgets ----------++let desk = null;++export function mountDesktopWidgets(ctx) {+ desk?.destroy();+ osRoot = ctx.root || osRoot;+ const host = ctx.desktop || ctx.root;+ const insets = typeof ctx.insets === 'function' ? ctx.insets : () => ({ top: 12, right: 12, bottom: 84, left: 120 });+ const layer = document.createElement('div');+ layer.className = 'wgx-desk';+ layer.setAttribute('role', 'region');+ layer.setAttribute('aria-label', 'Desktop widgets');+ const bar = document.createElement('div');+ bar.className = 'wgx-editbar';+ bar.innerHTML = `<button type="button" class="wgx-btn primary" data-add>${icon('plus', 15)}Add widget</button><button type="button" class="wgx-btn" data-done>${icon('check', 15)}Done</button>`;+ const ghost = document.createElement('div');+ ghost.className = 'wgx-ghost';+ layer.append(ghost, bar);+ host.append(layer);++ let stored = load(DESK_KEY, DEFAULT_LAYOUT);+ let laid = [];+ let grid = { cols: 0, rows: 0 };+ const cards = new Map();++ const persist = () => save(DESK_KEY, stored);+ function place(el, w) {+ const b = pixelBox(w);+ el.style.right = `${b.right}px`;+ el.style.top = `${b.top}px`;+ el.style.width = `${b.width}px`;+ el.style.height = `${b.height}px`;+ }+ function frame() {+ const i = insets();+ layer.style.inset = `${i.top}px ${i.right}px ${i.bottom}px ${i.left}px`;+ const r = layer.getBoundingClientRect();+ grid = gridFor(r.width, r.height);+ }+ function render() {+ frame();+ laid = settle(stored, grid);+ // Settling gives every stored widget a stable id; keep those.+ stored = laid.map((w) => ({ ...w, hidden: undefined }));+ const live = new Set();+ for (const w of laid) {+ if (w.hidden) continue;+ live.add(w.id);+ let el = cards.get(w.id);+ if (el && (el.dataset.size !== w.size)) {+ el.dispose();+ el.remove();+ el = null;+ }+ if (!el) {+ el = card(w, ctx, {+ menu: (x) => [+ '-',+ ['Edit widgets', 'edit', () => setEdit(true)],+ ['Remove from desktop', 'close', () => remove(x.id)],+ ],+ resize,+ onSave: (x) => {+ const s = stored.find((o) => o.id === x.id);+ if (s) s.data = x.data;+ persist();+ },+ });+ el.dataset.size = w.size;+ const x = document.createElement('button');+ x.type = 'button';+ x.className = 'wgx-x';+ x.setAttribute('aria-label', `Remove ${catalogItem(w.type).title}`);+ x.innerHTML = icon('close', 12);+ x.addEventListener('click', (e) => {+ e.stopPropagation();+ remove(w.id);+ });+ el.append(x);+ drag(el, w.id);+ cards.set(w.id, el);+ layer.insertBefore(el, ghost);+ }+ place(el, w);+ }+ for (const [id, el] of cards) {+ if (live.has(id)) continue;+ el.dispose();+ el.remove();+ cards.delete(id);+ }+ layer.classList.toggle('empty', !live.size);+ }+ function remove(id) {+ stored = stored.filter((w) => w.id !== id);+ persist();+ render();+ }+ function resize(w, size) {+ const s = stored.find((o) => o.id === w.id);+ if (!s || s.size === size) return;+ const others = laid.filter((o) => !o.hidden && o.id !== w.id);+ const next = { ...s, size };+ if (fits(next, s.col, s.row, others, grid)) s.size = size;+ else {+ const at = firstFit(next, others, grid);+ if (!at) return ctx.toast?.('No room for a bigger widget. Remove one or make one smaller.');+ Object.assign(s, { size }, at);+ }+ persist();+ render();+ }+ function add(spec) {+ const w = { id: newId(), ...spec };+ const at = firstFit(w, laid.filter((o) => !o.hidden), grid);+ if (!at) {+ ctx.toast?.('No room on the desktop. Remove a widget or make one smaller.');+ return false;+ }+ stored.push({ ...w, ...at });+ persist();+ render();+ cards.get(w.id)?.scrollIntoView?.({ block: 'nearest' });+ return true;+ }++ // Drag by the header, snapping to the grid; a drop on a taken cell springs back.+ function drag(el, id) {+ const head = el.querySelector('header');+ head.addEventListener('pointerdown', (e) => {+ if (e.button !== 0 || e.target.closest('.wgx-more')) return;+ const w = laid.find((o) => o.id === id);+ if (!w) return;+ const lr = layer.getBoundingClientRect();+ const er = el.getBoundingClientRect();+ const offX = e.clientX - er.left;+ const offY = e.clientY - er.top;+ let moved = false;+ let target = null;+ const onMove = (ev) => {+ if (!moved && Math.hypot(ev.clientX - e.clientX, ev.clientY - e.clientY) < 5) return;+ if (!moved) {+ moved = true;+ el.classList.add('dragging');+ head.setPointerCapture?.(e.pointerId);+ }+ const left = ev.clientX - offX - lr.left;+ const top = ev.clientY - offY - lr.top;+ el.style.right = `${lr.width - left - er.width}px`;+ el.style.top = `${top}px`;+ const cell = cellAt(lr.width - left - er.width, top);+ const ok = fits(w, cell.col, cell.row, laid.filter((o) => !o.hidden), grid);+ target = ok ? cell : null;+ ghost.classList.toggle('on', ok);+ if (ok) {+ const b = pixelBox({ ...w, ...cell });+ Object.assign(ghost.style, { right: `${b.right}px`, top: `${b.top}px`, width: `${b.width}px`, height: `${b.height}px` });+ }+ };+ const onUp = () => {+ removeEventListener('pointermove', onMove);+ removeEventListener('pointerup', onUp);+ removeEventListener('pointercancel', onUp);+ ghost.classList.remove('on');+ el.classList.remove('dragging');+ if (!moved) return;+ el.classList.add('was-dragged');+ setTimeout(() => el.classList.remove('was-dragged'), 0);+ const s = stored.find((o) => o.id === id);+ if (target && s) {+ Object.assign(s, target);+ persist();+ }+ render();+ };+ addEventListener('pointermove', onMove);+ addEventListener('pointerup', onUp);+ addEventListener('pointercancel', onUp);+ });+ // Suppress the title's "open app" click when the press was a drag.+ head.addEventListener('click', (e) => el.classList.contains('was-dragged') && e.stopPropagation(), true);+ }++ function setEdit(on) {+ layer.classList.toggle('editing', on);+ if (on) bar.querySelector('[data-add]').focus({ preventScroll: true });+ }+ bar.querySelector('[data-add]').addEventListener('click', () => gallery(ctx, add));+ bar.querySelector('[data-done]').addEventListener('click', () => setEdit(false));+ const onKey = (e) => e.key === 'Escape' && layer.classList.contains('editing') && !document.querySelector('.wgx-gallery') && setEdit(false);+ addEventListener('keydown', onKey);+ let raf = 0;+ const ro = new ResizeObserver(() => {+ cancelAnimationFrame(raf);+ raf = requestAnimationFrame(render);+ });+ ro.observe(host);+ render();++ desk = {+ edit: (on = !layer.classList.contains('editing')) => setEdit(on),+ add: (spec) => add(spec),+ openGallery: () => gallery(ctx, add),+ relayout: render,+ destroy() {+ ro.disconnect();+ removeEventListener('keydown', onKey);+ cards.forEach((el) => el.dispose());+ layer.remove();+ desk = null;+ },+ };+ return desk;+}++/** Toggle edit mode on the desktop widgets (desktop context menu "Edit widgets"). */+export function editDesktopWidgets(on) {+ desk?.edit(on);+}++/** Open the Add widget gallery for the desktop. */+export function addDesktopWidget() {+ if (!desk) return;+ desk.edit(true);+ desk.openGallery();+}++// ---------- the widgets board ----------++let board = null;++export function toggleWidgets(ctx) {+ if (board) {+ board.close();+ return false;+ }+ osRoot = ctx.root || osRoot;+ const anchor = ctx.anchor;+ const panel = document.createElement('div');+ panel.className = 'wgx-board';+ panel.setAttribute('role', 'dialog');+ panel.setAttribute('aria-label', 'Widgets');+ panel.innerHTML =+ `<div class="wgx-col wgx-col-w"><div class="wgx-bar"><span class="wgx-hello"><b></b><small></small></span><button type="button" class="wgx-btn icon" data-add title="Add a widget" aria-label="Add a widget">${icon('plus', 16)}</button></div><div class="wgx-grid"></div></div>` ++ `<div class="wgx-col wgx-col-n"><div class="wgx-bar"><span class="wgx-hello"><b>News</b><small>Headlines from the three.ws news desk, linked to each publisher</small></span><button type="button" class="wgx-btn icon" data-refresh title="Refresh news" aria-label="Refresh news">${icon('reload', 16)}</button></div><div class="wgx-feed" aria-live="polite"></div></div>`;+ (ctx.root || document.body).append(panel);+ handleBrokenImages(panel);++ const hello = panel.querySelector('.wgx-hello b');+ const sub = panel.querySelector('.wgx-hello small');+ const greet = () => {+ const d = new Date();+ const h = d.getHours();+ hello.textContent = h < 5 ? 'Good night' : h < 12 ? 'Good morning' : h < 18 ? 'Good afternoon' : 'Good evening';+ sub.textContent = `${d.toLocaleDateString(LOCALE, { weekday: 'long', month: 'long', day: 'numeric' })} · ${d.toLocaleTimeString(LOCALE, { hour: 'numeric', minute: '2-digit' })}`;+ };+ greet();+ const greetTimer = setInterval(greet, 15_000);++ // Position above the taskbar button, centred on screen like the shell's flyouts.+ const place = () => {+ const r = anchor?.getBoundingClientRect?.();+ const bottomGap = r ? Math.max(8, innerHeight - r.top + 10) : 84;+ panel.style.bottom = `${bottomGap}px`;+ panel.style.maxHeight = `${Math.max(320, innerHeight - bottomGap - 16)}px`;+ };+ place();+ addEventListener('resize', place);++ // Widgets column.+ const gridEl = panel.querySelector('.wgx-grid');+ let list = settle(load(BOARD_KEY, BOARD_DEFAULT), { cols: 99, rows: 99 }).map(({ hidden, col, row, ...w }) => w);+ const cards = [];+ const persist = () => save(BOARD_KEY, list);+ const paintGrid = () => {+ cards.splice(0).forEach((c) => c.dispose());+ gridEl.replaceChildren();+ if (!list.length) {+ gridEl.innerHTML = `<div class="wgx-empty big"><span>Your board is empty.</span><button type="button" class="wgx-btn primary">${icon('plus', 15)}Add a widget</button></div>`;+ gridEl.querySelector('button').addEventListener('click', openAdd);+ return;+ }+ for (const w of list) {+ const el = card(w, ctx, {+ menu: (x) => [+ '-',+ ...(desk ? [['Pin to desktop', 'pin', () => desk.add({ type: x.type, size: x.size, ...(x.data ? { data: x.data } : {}) }) && ctx.toast?.(`${catalogItem(x.type).title} pinned to the desktop`)]] : []),+ ['Move up', 'chevron', () => move(x.id, -1)],+ ['Remove', 'close', () => {+ list = list.filter((o) => o.id !== x.id);+ persist();+ paintGrid();+ }],+ ],+ resize: (x, s) => {+ x.size = s;+ persist();+ paintGrid();+ },+ onSave: persist,+ });+ cards.push(el);+ gridEl.append(el);+ }+ };+ const move = (id, d) => {+ const i = list.findIndex((o) => o.id === id);+ const j = i + d;+ if (i < 0 || j < 0 || j >= list.length) return;+ [list[i], list[j]] = [list[j], list[i]];+ persist();+ paintGrid();+ };+ const openAdd = () =>+ gallery(ctx, (spec) => {+ list.push({ id: newId(), ...spec });+ persist();+ paintGrid();+ gridEl.lastElementChild?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });+ });+ panel.querySelector('[data-add]').addEventListener('click', openAdd);+ paintGrid();++ // News column.+ const feed = panel.querySelector('.wgx-feed');+ feed.innerHTML = `<div class="wgx-skel news" aria-hidden="true">${'<i></i>'.repeat(6)}</div>`;+ const unNews = subscribe('news', (s) => {+ if (s.data === undefined) {+ if (s.error) {+ feed.innerHTML = `<div class="wgx-off"><b>${icon('cloud', 18)} News is offline</b><span>${esc(s.error)}</span><button type="button" class="wgx-btn">Retry</button></div>`;+ feed.querySelector('button').addEventListener('click', () => refresh('news'));+ }+ return;+ }+ if (!s.data.length) {+ feed.innerHTML = '<div class="wgx-empty"><span>No headlines right now. Try again in a few minutes.</span></div>';+ return;+ }+ feed.innerHTML = s.data+ .map(+ (a, i) =>+ `<a class="wgx-story${i === 0 && a.image ? ' lead' : ''}" href="${esc(a.link)}" target="_blank" rel="noopener noreferrer">${a.image ? `<img src="${esc(a.image)}" alt="" loading="lazy" referrerpolicy="no-referrer">` : ''}<span><small>${esc(a.source)} · ${relTime(a.pub_date)}</small><b>${esc(a.title)}</b>${i < 3 && a.description ? `<em>${esc(a.description.slice(0, 160))}</em>` : ''}</span></a>`,+ )+ .join('');+ });+ panel.querySelector('[data-refresh]').addEventListener('click', () => refresh('news'));++ // Dismiss: outside press, Escape, or the taskbar button again.+ const onDown = (e) => {+ if (panel.contains(e.target) || anchor?.contains?.(e.target) || e.target.closest?.('.wgx-gallery-back, .wgx-menu')) return;+ close();+ };+ const onKey = (e) => {+ if (e.key !== 'Escape' || document.querySelector('.wgx-gallery') || openMenu) return;+ close();+ anchor?.focus?.();+ };+ setTimeout(() => {+ addEventListener('pointerdown', onDown, true);+ addEventListener('blur', onBlur);+ });+ // A press inside a framed page never reaches this document: the window blur is the signal.+ const onBlur = () => setTimeout(() => document.activeElement?.tagName === 'IFRAME' && close(), 0);+ addEventListener('keydown', onKey);+ anchor?.setAttribute?.('aria-expanded', 'true');+ requestAnimationFrame(() => panel.classList.add('in'));+ panel.querySelector('[data-add]').focus({ preventScroll: true });++ function close() {+ if (!board) return;+ board = null;+ clearInterval(greetTimer);+ unNews();+ cards.forEach((c) => c.dispose());+ removeEventListener('pointerdown', onDown, true);+ removeEventListener('blur', onBlur);+ removeEventListener('keydown', onKey);+ removeEventListener('resize', place);+ anchor?.setAttribute?.('aria-expanded', 'false');+ closeMenu();+ panel.classList.remove('in');+ panel.classList.add('out');+ setTimeout(() => panel.remove(), matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 180);+ }+ board = { close };+ return true;+}++/** Close the board if it is open (the shell calls this when another flyout opens). */+export function closeWidgets() {+ board?.close();+}++// Re-exported so the shell's search can list widgets by name.+export { CATALOG as WIDGET_CATALOG, STEP as WIDGET_STEP };diff --git a/src/desktop/widgets/logic.js b/src/desktop/widgets/logic.jsnew file mode 100644index 000000000..92de42619--- /dev/null+++ b/src/desktop/widgets/logic.js@@ -0,0 +1,262 @@+// Pure rules for the desktop widgets: the catalog, the desktop grid and its+// first-fit placement, stored-layout validation, number and time formatting,+// sparkline geometry, weather codes and the month grid. No DOM, unit tested in+// tests/desktop-widgets.test.js.++/** Pixel size of one grid unit and the gap between widgets. */+export const UNIT = 168;+export const GAP = 14;+export const STEP = UNIT + GAP;++/** Widget sizes in grid units. */+export const SIZES = {+ s: { w: 1, h: 1, label: 'Small' },+ m: { w: 2, h: 1, label: 'Medium' },+ l: { w: 2, h: 2, label: 'Large' },+};++/**+ * Every widget a visitor can add. `sizes` lists the sizes the widget renders+ * well at, the first being its default. `feeds` names the live sources it reads+ * (see data.js), so the board can say where the numbers come from.+ */+export const CATALOG = [+ { type: 'three', title: '$THREE', desc: 'Live price, 24h change and a 24 hour chart', sizes: ['m', 's', 'l'], feeds: ['token', 'history'], app: 'trenches' },+ { type: 'weather', title: 'Weather', desc: 'Current conditions and the next hours where you are', sizes: ['m', 's', 'l'], feeds: ['weather'], app: 'weather' },+ { type: 'clock', title: 'Clock', desc: 'Analog clock with your local time and date', sizes: ['s', 'm'], feeds: [], app: 'clock' },+ { type: 'calendar', title: 'Calendar', desc: 'This month at a glance', sizes: ['l', 'm'], feeds: [] },+ { type: 'agents', title: 'New agents', desc: 'The newest agents on three.ws', sizes: ['m', 'l'], feeds: ['agents'], app: 'discover' },+ { type: 'pulse', title: 'Pulse', desc: 'Live wallet moves by agents', sizes: ['l', 'm'], feeds: ['pulse'], app: 'pulse' },+ { type: 'launches', title: 'Launches', desc: 'Coins agents launched through three.ws', sizes: ['l', 'm'], feeds: ['launches'], app: 'launcher' },+ { type: 'platform', title: 'Platform', desc: 'Agents, launches and strategies right now', sizes: ['m', 's'], feeds: ['stats'] },+ { type: 'news', title: 'Headlines', desc: 'Top crypto headlines from the three.ws news desk', sizes: ['l', 'm'], feeds: ['news'], app: 'page:/markets/news' },+ { type: 'system', title: 'System', desc: 'Battery, network, memory and storage of this device', sizes: ['m', 's'], feeds: [] },+ { type: 'note', title: 'Sticky note', desc: 'A note that stays on your desktop', sizes: ['s', 'm', 'l'], feeds: [] },+];++export const catalogItem = (type) => CATALOG.find((c) => c.type === type) || null;++/** The widgets a fresh desktop starts with. */+export const DEFAULT_LAYOUT = [+ { type: 'three', size: 'm' },+ { type: 'weather', size: 'm' },+ { type: 'clock', size: 's' },+ { type: 'platform', size: 's' },+ { type: 'pulse', size: 'l' },+];++/** How many grid columns and rows fit a work area of the given pixel size. */+export function gridFor(width, height) {+ return {+ cols: Math.max(0, Math.floor((width + GAP) / STEP)),+ rows: Math.max(0, Math.floor((height + GAP) / STEP)),+ };+}++const sizeOf = (w) => SIZES[w.size] || SIZES.s;+const hits = (a, b) => a.col < b.col + b.w && b.col < a.col + a.w && a.row < b.row + b.h && b.row < a.row + a.h;+const box = (w) => ({ col: w.col, row: w.row, ...sizeOf(w) });++/** True when a widget at (col,row) fits the grid and overlaps none of `others`. */+export function fits(widget, col, row, others, grid) {+ const s = sizeOf(widget);+ if (col < 0 || row < 0 || col + s.w > grid.cols || row + s.h > grid.rows) return false;+ const me = { col, row, w: s.w, h: s.h };+ return !others.some((o) => o.id !== widget.id && hits(me, box(o)));+}++/**+ * First free cell for `widget`. Columns count from the right edge of the work+ * area (column 0 is rightmost) so widgets fill in from the right and leave the+ * desktop icons on the left alone. Scans column by column, top to bottom.+ * Returns null when the grid is full.+ */+export function firstFit(widget, others, grid) {+ for (let col = 0; col < grid.cols; col++) {+ for (let row = 0; row < grid.rows; row++) if (fits(widget, col, row, others, grid)) return { col, row };+ }+ return null;+}++/**+ * Validate a stored layout: drop unknown types and bad sizes, give every widget+ * an id, and re-place anything that no longer fits (a smaller window, a moved+ * neighbour). Widgets that cannot fit at all are kept with `hidden: true` so+ * they come back when there is room again.+ */+export function settle(raw, grid) {+ const list = Array.isArray(raw) ? raw : [];+ const out = [];+ let n = 0;+ for (const r of list) {+ if (!r || typeof r !== 'object') continue;+ const item = catalogItem(r.type);+ if (!item) continue;+ const size = item.sizes.includes(r.size) ? r.size : item.sizes[0];+ const id = typeof r.id === 'string' && /^[\w-]{1,40}$/.test(r.id) && !out.some((o) => o.id === r.id) ? r.id : `w${Date.now().toString(36)}${n++}`;+ const w = { id, type: r.type, size, col: Number.isInteger(r.col) ? r.col : -1, row: Number.isInteger(r.row) ? r.row : -1 };+ if (r.data && typeof r.data === 'object') w.data = r.data;+ const placed = out.filter((o) => !o.hidden);+ if (!fits(w, w.col, w.row, placed, grid)) {+ const at = firstFit(w, placed, grid);+ if (at) Object.assign(w, at);+ else w.hidden = true;+ }+ out.push(w);+ }+ return out;+}++/** Nearest grid cell to a pixel offset measured from the top-right of the work area. */+export function cellAt(dxFromRight, dyFromTop) {+ return { col: Math.max(0, Math.round(dxFromRight / STEP)), row: Math.max(0, Math.round(dyFromTop / STEP)) };+}++/** Pixel box of a widget, `right`/`top` offsets from the work area's top-right. */+export function pixelBox(w) {+ const s = sizeOf(w);+ return { right: w.col * STEP, top: w.row * STEP, width: s.w * UNIT + (s.w - 1) * GAP, height: s.h * UNIT + (s.h - 1) * GAP };+}++// ---------- formatting ----------++/** USD price with enough significant digits for sub-cent tokens. */+export function fmtPrice(v) {+ const n = Number(v);+ if (!Number.isFinite(n) || n < 0) return '';+ if (n === 0) return '$0.00';+ if (n >= 1) return `$${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;+ const digits = Math.min(10, Math.max(2, 2 - Math.floor(Math.log10(n))));+ return `$${n.toFixed(digits)}`;+}++/** 1234 -> 1.2K, 502446 -> 502K, 1.5e6 -> 1.5M. */+export function fmtCompact(v, prefix = '') {+ const n = Number(v);+ if (!Number.isFinite(n)) return '';+ const abs = Math.abs(n);+ const unit = abs >= 1e9 ? [1e9, 'B'] : abs >= 1e6 ? [1e6, 'M'] : abs >= 1e3 ? [1e3, 'K'] : [1, ''];+ const x = n / unit[0];+ const s = unit[0] === 1 ? String(Math.round(x)) : x.toFixed(Math.abs(x) >= 100 ? 0 : 1).replace(/\.0$/, '');+ return `${prefix}${s}${unit[1]}`;+}++/** Signed percent: +3.2%, -0.4%, 0.0%. */+export function fmtPct(v) {+ if (v == null || v === '') return '';+ const n = Number(v);+ if (!Number.isFinite(n)) return '';+ return `${n > 0 ? '+' : ''}${n.toFixed(Math.abs(n) >= 100 ? 0 : 1)}%`;+}++/** Compact age: now, 4m, 3h, 2d. */+export function relTime(ts, now = Date.now()) {+ const t = typeof ts === 'number' ? ts : Date.parse(ts);+ if (!Number.isFinite(t)) return '';+ const s = Math.max(0, (now - t) / 1000);+ if (s < 45) return 'now';+ if (s < 3600) return `${Math.round(s / 60)}m`;+ if (s < 86400) return `${Math.round(s / 3600)}h`;+ return `${Math.round(s / 86400)}d`;+}++/**+ * SVG path data for a sparkline through `values`, fitted to w x h with a small+ * vertical pad. Returns { line, area } ('' when there are fewer than 2 points).+ */+export function sparkPath(values, w, h, pad = 2) {+ const v = (values || []).map(Number).filter(Number.isFinite);+ if (v.length < 2) return { line: '', area: '' };+ const lo = Math.min(...v);+ const hi = Math.max(...v);+ const span = hi - lo || 1;+ const pts = v.map((x, i) => [(i / (v.length - 1)) * w, pad + (1 - (x - lo) / span) * (h - pad * 2)]);+ const line = pts.map(([x, y], i) => `${i ? 'L' : 'M'}${x.toFixed(1)} ${y.toFixed(1)}`).join('');+ return { line, area: `${line}L${w} ${h}L0 ${h}Z` };+}++// ---------- weather ----------++const WMO = [+ [[0], 'Clear', 'sun'],+ [[1], 'Mostly clear', 'sun'],+ [[2], 'Partly cloudy', 'partly'],+ [[3], 'Overcast', 'cloud'],+ [[45, 48], 'Fog', 'fog'],+ [[51, 53, 55, 56, 57], 'Drizzle', 'rain'],+ [[61, 63, 66, 80, 81], 'Rain', 'rain'],+ [[65, 67, 82], 'Heavy rain', 'rain'],+ [[71, 73, 75, 77, 85, 86], 'Snow', 'snow'],+ [[95, 96, 99], 'Thunderstorm', 'storm'],+];++/** Open-Meteo WMO weather code to a label and an icon key. Night swaps sun for moon. */+export function weatherInfo(code, isDay = true) {+ const hit = WMO.find(([codes]) => codes.includes(Number(code)));+ const [, label, icon] = hit || [null, 'Unknown', 'cloud'];+ return { label, icon: !isDay && icon === 'sun' ? 'moon' : !isDay && icon === 'partly' ? 'partly-night' : icon };+}++/** A readable city from an IANA time zone: "America/New_York" -> "New York". */+export function tzCity(tz) {+ const last = String(tz || '').split('/').pop() || '';+ if (!last || /^(UTC|GMT|Etc)/i.test(last) || /[+-]\d/.test(last)) return '';+ return last.replace(/_/g, ' ');+}++/** Fahrenheit for the few regions that use it, Celsius everywhere else. */+export function usesFahrenheit(locale) {+ return /-(US|LR|MM|BS|BZ|KY|PW)\b/i.test(String(locale || ''));+}++// ---------- calendar ----------++/**+ * The 6x7 day grid for the month containing `date`, weeks starting on+ * `weekStart` (0 Sunday, 1 Monday). Each cell: { y, m, d, inMonth, today }.+ */+export function monthGrid(date, weekStart = 0, today = new Date()) {+ const first = new Date(date.getFullYear(), date.getMonth(), 1);+ const lead = (first.getDay() - weekStart + 7) % 7;+ const start = new Date(first.getFullYear(), first.getMonth(), 1 - lead);+ const cells = [];+ for (let i = 0; i < 42; i++) {+ const d = new Date(start.getFullYear(), start.getMonth(), start.getDate() + i);+ cells.push({+ y: d.getFullYear(),+ m: d.getMonth(),+ d: d.getDate(),+ inMonth: d.getMonth() === first.getMonth(),+ today: d.getFullYear() === today.getFullYear() && d.getMonth() === today.getMonth() && d.getDate() === today.getDate(),+ });+ }+ return cells;+}++/** First day of the week for a locale (1 Monday for most of the world, 0 Sunday for a few). */+export function weekStartFor(locale) {+ try {+ const info = new Intl.Locale(locale);+ const wi = info.getWeekInfo?.() || info.weekInfo;+ if (wi && Number.isInteger(wi.firstDay)) return wi.firstDay % 7;+ } catch {+ /* older engines */+ }+ return /-(US|CA|JP|BR|IL|PH|MX|KR|TW|IN|ZA|SA|AU)\b/i.test(String(locale || '')) ? 0 : 1;+}++// ---------- system ----------++/** "1.2 GB" style byte formatting. */+export function fmtBytes(b) {+ const n = Number(b);+ if (!Number.isFinite(n) || n < 0) return '';+ const u = ['B', 'KB', 'MB', 'GB', 'TB'];+ let i = 0;+ let x = n;+ while (x >= 1024 && i < u.length - 1) {+ x /= 1024;+ i++;+ }+ return `${x.toFixed(x >= 10 || i === 0 ? 0 : 1)} ${u[i]}`;+}diff --git a/src/desktop/widgets/render.js b/src/desktop/widgets/render.jsnew file mode 100644index 000000000..976ad674c--- /dev/null+++ b/src/desktop/widgets/render.js@@ -0,0 +1,517 @@+// One renderer per widget type. `renderWidget(body, w, api)` fills `body`+// (the card under its header) for widget `w` ({ type, size, data }) and+// returns a cleanup function. Every value comes from a feed in data.js or from+// the device itself; a feed that fails shows what went wrong and a Retry.++import { icon } from '../icons.js';+import { describeEvent } from '../../field/logic.js';+import { refresh, subscribe, searchPlaces, locate, setPlace, THREE_MINT } from './data.js';+import { fmtBytes, fmtCompact, fmtPct, fmtPrice, monthGrid, relTime, sparkPath, weatherInfo, weekStartFor } from './logic.js';++const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+const LOCALE = navigator.language || 'en-US';+let uid = 0;++// ---------- shared states ----------++function skeleton(body, rows = 3) {+ body.innerHTML = `<div class="wgx-skel" aria-hidden="true">${'<i></i>'.repeat(rows)}</div>`;+ body.setAttribute('aria-busy', 'true');+}+function failed(body, msg, key) {+ body.removeAttribute('aria-busy');+ body.innerHTML = `<div class="wgx-off"><b>${icon('cloud', 18)} Offline</b><span>${esc(msg)}</span><button type="button" class="wgx-btn">Retry</button></div>`;+ body.querySelector('button').addEventListener('click', () => refresh(key));+}+/** Subscribe `paint(data)` to a feed with the skeleton, error and stale states handled. */+function bind(body, key, paint, rows) {+ let painted = false;+ return subscribe(key, (s) => {+ if (s.data === undefined) {+ if (s.error) failed(body, s.error, key);+ else if (!painted) skeleton(body, rows);+ return;+ }+ body.removeAttribute('aria-busy');+ paint(s.data);+ painted = true;+ body.closest('.wgx')?.classList.toggle('stale', !!s.error);+ });+}+const initial = (name) => esc(String(name || '?').trim().slice(0, 1).toUpperCase() || '?');+const thumb = (url, name, cls = 'wgx-av') =>+ url ? `<img class="${cls}" src="${esc(url)}" alt="" loading="lazy" decoding="async" referrerpolicy="no-referrer" data-ph="${initial(name)}">` : `<i class="${cls} ph">${initial(name)}</i>`;++/**+ * One capture-phase listener per widget host: a broken avatar becomes its+ * initial, a broken news photo is dropped.+ */+export function handleBrokenImages(host) {+ host.addEventListener(+ 'error',+ (e) => {+ const img = e.target;+ if (!(img instanceof HTMLImageElement) || !host.contains(img)) return;+ if (img.dataset.ph == null) return img.remove();+ const i = document.createElement('i');+ i.className = `${img.className} ph`;+ i.textContent = img.dataset.ph;+ img.replaceWith(i);+ },+ true,+ );+}++// ---------- $THREE ----------++function three(body, w, api) {+ const id = `wgx-g${++uid}`;+ let token = null;+ let candles = null;+ body.classList.add('wgx-three');+ const paint = () => {+ if (!token) return;+ const up = Number(token.price_change_24h) >= 0;+ const closes = (candles || []).map((c) => c.c);+ const W = w.size === 's' ? 136 : 300;+ const H = w.size === 'l' ? 120 : w.size === 's' ? 40 : 58;+ const p = sparkPath(closes, W, H);+ const chart = p.line+ ? `<svg class="wgx-spark" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img" aria-label="$THREE price over the last 24 hours"><defs><linearGradient id="${id}" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="currentColor" stop-opacity=".35"/><stop offset="1" stop-color="currentColor" stop-opacity="0"/></linearGradient></defs><path d="${p.area}" fill="url(#${id})"/><path d="${p.line}" fill="none" stroke="currentColor" stroke-width="2" vector-effect="non-scaling-stroke" stroke-linejoin="round"/></svg>`+ : candles+ ? '<p class="wgx-mute wgx-nochart">No trades in the last 24 hours to chart.</p>'+ : '<div class="wgx-skel"><i></i></div>';+ const facts =+ w.size === 's'+ ? ''+ : `<dl class="wgx-facts"><div><dt>Mkt cap</dt><dd>${fmtCompact(token.market_cap, '$')}</dd></div><div><dt>Vol 24h</dt><dd>${fmtCompact(token.volume_24h, '$')}</dd></div><div><dt>Holders</dt><dd>${fmtCompact(token.holders)}</dd></div>${w.size === 'l' ? `<div><dt>Liquidity</dt><dd>${fmtCompact(token.liquidity, '$')}</dd></div>` : ''}</dl>`;+ const actions =+ w.size === 'l'+ ? `<div class="wgx-row-btns"><button type="button" class="wgx-btn primary" data-act="trade">${icon('pulse', 15)}Open Trenches</button><button type="button" class="wgx-btn" data-act="copy">${icon('save', 15)}Copy address</button></div>`+ : '';+ body.innerHTML =+ `<div class="wgx-price"><b>${fmtPrice(token.price_usd)}</b><span class="wgx-chg ${up ? 'up' : 'down'}">${fmtPct(token.price_change_24h)}</span></div>` ++ `<div class="wgx-chart ${up ? 'up' : 'down'}">${chart}</div>${facts}${actions}`;+ body.querySelector('[data-act="trade"]')?.addEventListener('click', () => api.launchId('trenches'));+ body.querySelector('[data-act="copy"]')?.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(THREE_MINT);+ api.toast('$THREE contract address copied');+ } catch {+ api.toast(THREE_MINT);+ }+ });+ };+ const a = bind(body, 'token', (d) => {+ token = d;+ paint();+ });+ const b = subscribe('history', (s) => {+ if (s.data) {+ candles = s.data.candles;+ paint();+ }+ });+ return () => {+ a();+ b();+ };+}++// ---------- weather ----------++function weatherArt(kind, size = 64) {+ const g = `wgx-w${++uid}`;+ const sun = `<circle cx="26" cy="26" r="11" fill="url(#${g}s)"/><g stroke="#ffc94a" stroke-width="2.6" stroke-linecap="round">${[0, 45, 90, 135, 180, 225, 270, 315].map((a) => `<path transform="rotate(${a} 26 26)" d="M26 6.5v4"/>`).join('')}</g>`;+ const moon = `<path d="M34 11a15 15 0 1 0 12 21A12 12 0 0 1 34 11z" fill="url(#${g}m)"/>`;+ const cloud = (x = 0, y = 0, op = 1) => `<path transform="translate(${x} ${y})" opacity="${op}" d="M20 50h26a10 10 0 0 0 1-20 14 14 0 0 0-27-3A11 11 0 0 0 20 50z" fill="url(#${g}c)"/>`;+ const defs = `<defs><radialGradient id="${g}s"><stop offset="0" stop-color="#ffe680"/><stop offset="1" stop-color="#ffab2e"/></radialGradient><linearGradient id="${g}m" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#fff4c2"/><stop offset="1" stop-color="#cdb6ff"/></linearGradient><linearGradient id="${g}c" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#ffffff"/><stop offset="1" stop-color="#c9d6ec"/></linearGradient></defs>`;+ const drops = `<g stroke="#5fb4ff" stroke-width="2.6" stroke-linecap="round"><path d="M22 54l-2 6M31 54l-2 6M40 54l-2 6"/></g>`;+ const flakes = `<g fill="#e8f3ff"><circle cx="22" cy="57" r="2.2"/><circle cx="31" cy="60" r="2.2"/><circle cx="40" cy="57" r="2.2"/></g>`;+ const bolt = `<path d="M33 48l-7 10h6l-3 8 9-12h-6l3-6z" fill="#ffd43b"/>`;+ const body = {+ sun,+ moon,+ partly: `${sun}${cloud(6, 6)}`,+ 'partly-night': `<g transform="translate(-4 -4)">${moon}</g>${cloud(6, 6)}`,+ cloud: `${cloud(-6, -4, 0.55)}${cloud(4, 2)}`,+ fog: `${cloud(0, -6, 0.8)}<g stroke="#dfe7f3" stroke-width="2.6" stroke-linecap="round"><path d="M12 50h36M16 57h30"/></g>`,+ rain: `${cloud(0, -6)}${drops}`,+ snow: `${cloud(0, -6)}${flakes}`,+ storm: `${cloud(0, -8)}${bolt}`,+ }[kind] || cloud();+ return `<svg class="wgx-wart" width="${size}" height="${size}" viewBox="0 0 64 64" aria-hidden="true">${defs}${body}</svg>`;+}++function placePicker(body, onDone) {+ body.innerHTML =+ `<div class="wgx-place"><p>Weather for any city, live from Open-Meteo.</p>` ++ `<div class="wgx-place-row"><input type="search" placeholder="Search a city" aria-label="Search a city" autocomplete="off"><button type="button" class="wgx-btn icon" title="Use my location" aria-label="Use my location">${icon('compass', 16)}</button></div>` ++ `<ul role="listbox" aria-label="Cities"></ul><small class="wgx-mute" aria-live="polite"></small></div>`;+ const input = body.querySelector('input');+ const list = body.querySelector('ul');+ const note = body.querySelector('small');+ let t = 0;+ let seq = 0;+ input.addEventListener('input', () => {+ clearTimeout(t);+ t = setTimeout(async () => {+ const my = ++seq;+ try {+ const hits = await searchPlaces(input.value);+ if (my !== seq) return;+ note.textContent = input.value.trim().length > 1 && !hits.length ? 'No city by that name.' : '';+ list.replaceChildren(+ ...hits.map((p) => {+ const li = document.createElement('li');+ li.innerHTML = `<button type="button" role="option"><b>${esc(p.name)}</b><span>${esc(p.region)}</span></button>`;+ li.firstChild.addEventListener('click', () => {+ setPlace(p);+ onDone();+ });+ return li;+ }),+ );+ } catch (e) {+ note.textContent = e.message;+ }+ }, 250);+ });+ body.querySelector('.wgx-place-row button').addEventListener('click', async () => {+ note.textContent = 'Finding you...';+ try {+ setPlace(await locate());+ onDone();+ } catch (e) {+ note.textContent = e.message;+ }+ });+ setTimeout(() => input.focus({ preventScroll: true }), 30);+}++function weather(body, w, api) {+ let picking = false;+ let last = null;+ const card = () => body.closest('.wgx');+ const paint = (d) => {+ last = d;+ if (picking) return;+ if (!d.place || !d.current) {+ card()?.removeAttribute('data-sky');+ return placePicker(body, () => (picking = false));+ }+ const c = d.current;+ const info = weatherInfo(c.weather_code, !!c.is_day);+ card()?.setAttribute('data-sky', `${info.icon}${c.is_day ? '' : ' night'}`);+ const deg = (v) => `${Math.round(v)}°`;+ const today = d.days[0];+ const hours =+ w.size === 's'+ ? ''+ : `<ol class="wgx-hours">${d.hours+ .slice(0, w.size === 'l' ? 6 : 5)+ .map((h) => `<li><small>${new Date(h.t).toLocaleTimeString(LOCALE, { hour: 'numeric' })}</small>${w.size === 'l' ? weatherArt(weatherInfo(h.code, h.day).icon, 26) : ''}<b>${deg(h.temp)}</b></li>`)+ .join('')}</ol>`;+ const days =+ w.size === 'l'+ ? `<ol class="wgx-days">${d.days+ .slice(1, 5)+ .map((x) => `<li><span>${new Date(`${x.date}T12:00`).toLocaleDateString(LOCALE, { weekday: 'short' })}</span>${weatherArt(weatherInfo(x.code).icon, 22)}<b>${deg(x.hi)}</b><small>${deg(x.lo)}</small></li>`)+ .join('')}</ol>`+ : '';+ body.innerHTML =+ `<div class="wgx-wx-top"><div><button type="button" class="wgx-place-btn" title="Change city">${esc(d.place.name)}${icon('chevron', 12)}</button>` ++ `<div class="wgx-temp">${deg(c.temperature_2m)}<sup>${esc(d.unit.replace('°', ''))}</sup></div>` ++ `<div class="wgx-wx-label">${esc(info.label)}${today ? ` <span>${deg(today.hi)} / ${deg(today.lo)}${w.size === 'm' ? ` · Feels ${deg(c.apparent_temperature)}` : ''}</span>` : ''}</div></div>${weatherArt(info.icon, w.size === 's' ? 46 : 64)}</div>` ++ (w.size !== 'l' ? '' : `<div class="wgx-wx-meta"><span>Feels ${deg(c.apparent_temperature)}</span><span>Humidity ${Math.round(c.relative_humidity_2m)}%</span><span>Wind ${Math.round(c.wind_speed_10m)} ${esc(d.wind)}</span></div>`) ++ hours ++ days;+ body.querySelector('.wgx-place-btn').addEventListener('click', (e) => {+ e.stopPropagation();+ picking = true;+ card()?.removeAttribute('data-sky');+ placePicker(body, () => {+ picking = false;+ });+ const back = document.createElement('button');+ back.type = 'button';+ back.className = 'wgx-btn ghost wgx-place-cancel';+ back.textContent = 'Cancel';+ back.addEventListener('click', () => {+ picking = false;+ paint(last);+ });+ body.querySelector('.wgx-place').append(back);+ });+ };+ void api;+ return bind(body, 'weather', paint, 4);+}++// ---------- clock ----------++function clock(body, w) {+ const ticks = Array.from({ length: 12 }, (_, i) => `<path transform="rotate(${i * 30} 50 50)" d="M50 ${i % 3 ? 9 : 7}v${i % 3 ? 4 : 7}" />`).join('');+ body.classList.add('wgx-clock', `sz-${w.size}`);+ body.innerHTML =+ `<svg class="wgx-face" viewBox="0 0 100 100" role="img"><circle cx="50" cy="50" r="46" class="rim"/><g class="ticks">${ticks}</g>` ++ `<path class="hh" d="M50 50V28"/><path class="mh" d="M50 50V16"/><path class="sh" d="M50 58V12"/><circle cx="50" cy="50" r="3" class="hub"/></svg>` ++ `<div class="wgx-clock-txt"><b></b><span></span><small></small></div>`;+ const svg = body.querySelector('svg');+ const [hh, mh, sh] = ['.hh', '.mh', '.sh'].map((s) => body.querySelector(s));+ const b = body.querySelector('b');+ const span = body.querySelector('span');+ const small = body.querySelector('small');+ small.textContent = Intl.DateTimeFormat().resolvedOptions().timeZone.replace(/_/g, ' ');+ let timer = 0;+ const tick = () => {+ const d = new Date();+ const s = d.getSeconds();+ const m = d.getMinutes() + s / 60;+ const h = (d.getHours() % 12) + m / 60;+ hh.setAttribute('transform', `rotate(${h * 30} 50 50)`);+ mh.setAttribute('transform', `rotate(${m * 6} 50 50)`);+ sh.setAttribute('transform', `rotate(${s * 6} 50 50)`);+ b.textContent = d.toLocaleTimeString(LOCALE, { hour: 'numeric', minute: '2-digit' });+ span.textContent = d.toLocaleDateString(LOCALE, { weekday: 'long', month: 'long', day: 'numeric' });+ svg.setAttribute('aria-label', `The time is ${b.textContent}`);+ timer = setTimeout(tick, 1000 - (Date.now() % 1000) + 5);+ };+ tick();+ return () => clearTimeout(timer);+}++// ---------- calendar ----------++function calendar(body, w) {+ let view = new Date();+ const ws = weekStartFor(LOCALE);+ body.classList.add('wgx-cal');+ let timer = 0;+ const paint = () => {+ const today = new Date();+ if (w.size === 'm') {+ const cells = monthGrid(today, ws, today);+ const at = cells.findIndex((c) => c.today);+ const week = cells.slice(at - (at % 7), at - (at % 7) + 7);+ body.innerHTML =+ `<div class="wgx-cal-today"><b>${today.getDate()}</b><span>${today.toLocaleDateString(LOCALE, { weekday: 'long' })}<small>${today.toLocaleDateString(LOCALE, { month: 'long', year: 'numeric' })}</small></span></div>` ++ `<ol class="wgx-cal-week">${week.map((c) => `<li class="${c.today ? 'today' : ''}${c.inMonth ? '' : ' mute'}"><small>${new Date(c.y, c.m, c.d).toLocaleDateString(LOCALE, { weekday: 'narrow' })}</small><b>${c.d}</b></li>`).join('')}</ol>`;+ } else {+ const cells = monthGrid(view, ws, today);+ const dow = cells.slice(0, 7).map((c) => `<i>${new Date(c.y, c.m, c.d).toLocaleDateString(LOCALE, { weekday: 'narrow' })}</i>`).join('');+ body.innerHTML =+ `<div class="wgx-cal-head"><b>${view.toLocaleDateString(LOCALE, { month: 'long', year: 'numeric' })}</b><span>` ++ `<button type="button" class="wgx-btn icon" data-d="-1" aria-label="Previous month"><span style="display:inline-flex;transform:rotate(180deg)">${icon('chevron', 14)}</span></button>` ++ `<button type="button" class="wgx-btn icon" data-d="1" aria-label="Next month">${icon('chevron', 14)}</button></span></div>` ++ `<div class="wgx-cal-grid">${dow}${cells.map((c) => `<b class="${c.today ? 'today' : ''}${c.inMonth ? '' : ' mute'}">${c.d}</b>`).join('')}</div>`;+ body.querySelectorAll('[data-d]').forEach((btn) =>+ btn.addEventListener('click', (e) => {+ e.stopPropagation();+ view = new Date(view.getFullYear(), view.getMonth() + Number(btn.dataset.d), 1);+ paint();+ }),+ );+ }+ };+ paint();+ // Repaint just after midnight so "today" moves on its own.+ const arm = () => {+ const n = new Date();+ timer = setTimeout(() => {+ view = new Date();+ paint();+ arm();+ }, new Date(n.getFullYear(), n.getMonth(), n.getDate() + 1, 0, 0, 5) - n);+ };+ arm();+ return () => clearTimeout(timer);+}++// ---------- agents ----------++function agents(body, w, api) {+ return bind(body, 'agents', (list) => {+ if (!list.length) {+ body.innerHTML = `<div class="wgx-empty"><span>No public agents yet.</span><button type="button" class="wgx-btn primary">Create one</button></div>`;+ body.querySelector('button').addEventListener('click', () => api.launchId('create'));+ return;+ }+ const n = w.size === 'l' ? 6 : 4;+ const items = list.slice(0, n);+ body.innerHTML =+ w.size === 'l'+ ? `<ul class="wgx-list">${items.map((a, i) => `<li><button type="button" data-i="${i}">${thumb(a.avatar_thumbnail, a.name)}<span><b>${esc(a.name)}</b><small>${esc(a.description || 'A new three.ws agent')}</small></span><time>${relTime(a.created_at)}</time></button></li>`).join('')}</ul>`+ : `<ul class="wgx-faces">${items.map((a, i) => `<li><button type="button" data-i="${i}" title="${esc(a.name)}">${thumb(a.avatar_thumbnail, a.name, 'wgx-fav')}<span>${esc(a.name)}</span></button></li>`).join('')}</ul>`;+ body.querySelectorAll('[data-i]').forEach((b) => b.addEventListener('click', () => api.launchId(`page:${items[b.dataset.i].home_url || `/agents/${items[b.dataset.i].id}`}`)));+ });+}++// ---------- pulse ----------++function pulse(body, w) {+ return bind(+ body,+ 'pulse',+ (events) => {+ if (!events.length) {+ body.innerHTML = '<div class="wgx-empty"><span>No agent wallet moves yet. They appear here the moment one lands.</span></div>';+ return;+ }+ const items = events.slice(0, w.size === 'l' ? 5 : 2);+ body.innerHTML = `<ul class="wgx-list">${items+ .map(+ (e) =>+ `<li><a href="${esc(e.explorer || '#')}" target="_blank" rel="noopener noreferrer">${thumb(e.agent?.avatar_thumbnail_url, e.agent?.name)}<span><b>${esc(describeEvent(e))}</b><small>${esc(e.kind)}${e.usd ? ` · $${Number(e.usd).toFixed(2)}` : ''}</small></span><time>${relTime(e.ts)}</time></a></li>`,+ )+ .join('')}</ul>`;+ },+ 4,+ );+}++// ---------- launches ----------++function launches(body, w, api) {+ return bind(+ body,+ 'launches',+ (list) => {+ if (!list.length) {+ body.innerHTML = `<div class="wgx-empty"><span>No agent launches yet.</span><button type="button" class="wgx-btn primary">Open the Launchpad</button></div>`;+ body.querySelector('button').addEventListener('click', () => api.launchId('launcher'));+ return;+ }+ const items = list.slice(0, w.size === 'l' ? 5 : 2);+ body.innerHTML = `<ul class="wgx-list">${items+ .map(+ (l, i) =>+ `<li><button type="button" data-i="${i}">${thumb(l.agent?.avatar_thumbnail_url, l.name)}<span><b>${esc(l.name)} <em>$${esc(String(l.symbol || '').toUpperCase())}</em></b><small>by ${esc(l.agent?.name || 'an agent')}</small></span><time>${relTime(l.created_at)}</time></button></li>`,+ )+ .join('')}</ul>`;+ body.querySelectorAll('[data-i]').forEach((b) => {+ const l = items[b.dataset.i];+ b.addEventListener('click', () => api.launchId(`page:${l.agent?.url || '/launches'}`));+ });+ },+ 4,+ );+}++// ---------- platform ----------++function platform(body, w) {+ return bind(body, 'stats', (s) => {+ const rows = [+ ['Agents', s.agents?.value, 'cube'],+ ['Coins launched', s.launches?.value, 'rocket'],+ ['Live strategies', s.active_strategies?.value, 'pulse'],+ ].filter((r) => Number.isFinite(r[1]));+ body.innerHTML = `<ul class="wgx-stats ${w.size === 's' ? 'tight' : ''}">${rows.map(([k, v, ic]) => `<li>${icon(ic, 16)}<b>${Number(v).toLocaleString(LOCALE)}</b><span>${k}</span></li>`).join('')}</ul>`;+ });+}++// ---------- news ----------++function news(body, w) {+ return bind(+ body,+ 'news',+ (list) => {+ if (!list.length) {+ body.innerHTML = '<div class="wgx-empty"><span>The news desk has nothing new right now.</span></div>';+ return;+ }+ const items = list.slice(0, w.size === 'l' ? 4 : 2);+ const lead = items[0];+ body.innerHTML =+ (w.size === 'l' && lead.image+ ? `<a class="wgx-lead" href="${esc(lead.link)}" target="_blank" rel="noopener noreferrer"><img src="${esc(lead.image)}" alt="" loading="lazy" referrerpolicy="no-referrer"><span><b>${esc(lead.title)}</b><small>${esc(lead.source)} · ${relTime(lead.pub_date)}</small></span></a>`+ : '') ++ `<ul class="wgx-news">${items+ .slice(w.size === 'l' && lead.image ? 1 : 0)+ .map((a) => `<li><a href="${esc(a.link)}" target="_blank" rel="noopener noreferrer"><b>${esc(a.title)}</b><small>${esc(a.source)} · ${relTime(a.pub_date)}</small></a></li>`)+ .join('')}</ul>`;+ },+ 4,+ );+}++// ---------- system ----------++function system(body, w) {+ body.classList.add('wgx-sys');+ let battery = null;+ let storage = null;+ let timer = 0;+ const conn = navigator.connection;+ const paint = () => {+ const rows = [];+ if (battery) {+ const pct = Math.round(battery.level * 100);+ rows.push(['battery', 'Battery', `${pct}%${battery.charging ? ', charging' : ''}`, pct]);+ }+ rows.push(['wifi', 'Network', navigator.onLine ? `Online${conn?.effectiveType ? `, ${conn.effectiveType.toUpperCase()}` : ''}${conn?.downlink ? `, ${conn.downlink} Mb/s` : ''}` : 'Offline', null]);+ if (storage?.quota) rows.push(['save', 'Site storage', `${fmtBytes(storage.usage)} of ${fmtBytes(storage.quota)}`, Math.max(1, Math.round((storage.usage / storage.quota) * 100))]);+ const mem = navigator.deviceMemory;+ rows.push(['cpu', 'Processor', `${navigator.hardwareConcurrency || '?'} threads${mem ? `, ${mem} GB+ memory` : ''}`, null]);+ const shown = w.size === 's' ? rows.slice(0, 2) : rows;+ body.innerHTML = `<ul class="wgx-sysl">${shown.map(([ic, k, v, pct]) => `<li>${icon(ic, 16)}<span><small>${k}</small><b>${esc(v)}</b>${pct != null ? `<i class="wgx-meter"><s style="width:${pct}%"></s></i>` : ''}</span></li>`).join('')}</ul>`;+ };+ const onNet = () => paint();+ addEventListener('online', onNet);+ addEventListener('offline', onNet);+ conn?.addEventListener?.('change', onNet);+ navigator.getBattery?.().then((b) => {+ battery = b;+ ['levelchange', 'chargingchange'].forEach((ev) => b.addEventListener(ev, paint));+ paint();+ }).catch(() => {});+ const est = () =>+ navigator.storage?.estimate?.().then((s) => {+ storage = s;+ paint();+ }).catch(() => {});+ est();+ timer = setInterval(est, 30_000);+ paint();+ return () => {+ clearInterval(timer);+ removeEventListener('online', onNet);+ removeEventListener('offline', onNet);+ conn?.removeEventListener?.('change', onNet);+ battery && ['levelchange', 'chargingchange'].forEach((ev) => battery.removeEventListener(ev, paint));+ };+}++// ---------- note ----------++function note(body, w, api) {+ body.classList.add('wgx-note');+ const ta = document.createElement('textarea');+ ta.placeholder = 'Write a note...';+ ta.setAttribute('aria-label', 'Sticky note');+ ta.maxLength = 4000;+ ta.value = w.data?.text || '';+ let t = 0;+ ta.addEventListener('input', () => {+ clearTimeout(t);+ t = setTimeout(() => api.save({ text: ta.value }), 300);+ });+ ta.addEventListener('pointerdown', (e) => e.stopPropagation());+ body.replaceChildren(ta);+ return () => {+ clearTimeout(t);+ if ((w.data?.text || '') !== ta.value) api.save({ text: ta.value });+ };+}++const RENDER = { three, weather, clock, calendar, agents, pulse, launches, platform, news, system, note };++export function renderWidget(body, w, api) {+ const fn = RENDER[w.type];+ if (!fn) return () => {};+ return fn(body, w, api) || (() => {});+}++export const WIDGET_ICONS = { three: 'gem', weather: 'cloud', clock: 'clock', calendar: 'grid', agents: 'cube', pulse: 'pulse', launches: 'rocket', platform: 'radar', news: 'list', system: 'cpu', note: 'note' };diff --git a/src/desktop/widgets/widgets.css b/src/desktop/widgets/widgets.cssnew file mode 100644index 000000000..126b049a5--- /dev/null+++ b/src/desktop/widgets/widgets.css@@ -0,0 +1,1603 @@+/*+ * Desktop widgets: frosted cards on the desktop and on the widgets board.+ * Colours come from the .os theme tokens (theme.css) so light and dark follow+ * the shell; the weather card paints its own sky from data-sky.+ */++.os {+ --wgx-radius: 20px;+ --wgx-glass: color-mix(in srgb, var(--card) 72%, transparent);+ --wgx-glass-2: color-mix(in srgb, var(--card) 88%, transparent);+ --wgx-line: color-mix(in srgb, var(--text) 10%, transparent);+ --wgx-soft: color-mix(in srgb, var(--text) 6%, transparent);+ --wgx-up: #2fbf71;+ --wgx-down: #f0524f;+ --wgx-shadow: 0 1px 0 color-mix(in srgb, #fff 8%, transparent) inset, 0 12px 32px -12px rgb(0 0 0 / 0.45);+}+[data-theme='light'] .os {+ --wgx-glass: color-mix(in srgb, #fff 66%, transparent);+ --wgx-glass-2: color-mix(in srgb, #fff 86%, transparent);+ --wgx-up: #12894c;+ --wgx-down: #c62f2c;+ --wgx-shadow: 0 1px 0 rgb(255 255 255 / 0.7) inset, 0 12px 30px -14px rgb(20 30 60 / 0.35);+}++/* ---------- the card ---------- */++.wgx {+ position: relative;+ display: flex;+ flex-direction: column;+ min-width: 0;+ overflow: hidden;+ color: var(--text);+ background: var(--wgx-glass);+ backdrop-filter: blur(28px) saturate(1.6);+ -webkit-backdrop-filter: blur(28px) saturate(1.6);+ border: 1px solid var(--wgx-line);+ border-radius: var(--wgx-radius);+ box-shadow: var(--wgx-shadow);+ font-size: 13px;+ line-height: 1.35;+ transition:+ box-shadow 0.18s,+ transform 0.18s,+ border-color 0.18s;+}+.wgx:hover {+ border-color: color-mix(in srgb, var(--text) 18%, transparent);+}+.wgx:focus-within {+ border-color: color-mix(in srgb, var(--accent) 55%, transparent);+}+.wgx > header {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 8px 8px 0 12px;+ min-height: 34px;+ flex: none;+}+.wgx-title {+ display: inline-flex;+ align-items: center;+ gap: 7px;+ min-width: 0;+ padding: 3px 6px 3px 0;+ border: 0;+ background: none;+ color: var(--text2);+ font: inherit;+ font-size: 12px;+ cursor: pointer;+ border-radius: 6px;+}+.wgx-title b {+ font-weight: 600;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.wgx-title:not(:disabled):hover {+ color: var(--text);+}+.wgx-title:disabled {+ cursor: default;+}+.wgx-more {+ margin-left: auto;+ display: grid;+ place-items: center;+ width: 28px;+ height: 26px;+ border: 0;+ border-radius: 8px;+ background: none;+ color: var(--text2);+ cursor: pointer;+ opacity: 0;+ transition:+ opacity 0.15s,+ background 0.15s;+}+.wgx:hover .wgx-more,+.wgx:focus-within .wgx-more,+.wgx-more[aria-expanded='true'] {+ opacity: 1;+}+.wgx-more:hover {+ background: var(--wgx-soft);+ color: var(--text);+}+.wgx-more:active {+ transform: scale(0.94);+}+.wgx-body {+ flex: 1;+ min-height: 0;+ padding: 6px 14px 14px;+ display: flex;+ flex-direction: column;+ gap: 8px;+ overflow: hidden;+}+.wgx.stale > header::after {+ content: 'Stale';+ margin-left: 6px;+ padding: 1px 6px;+ border-radius: 99px;+ font-size: 10px;+ color: var(--text2);+ background: var(--wgx-soft);+}+.wgx :focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}++/* ---------- shared bits ---------- */++.wgx-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 6px;+ height: 32px;+ padding: 0 12px;+ border-radius: 10px;+ border: 1px solid var(--wgx-line);+ background: var(--wgx-soft);+ color: var(--text);+ font: inherit;+ font-size: 12.5px;+ font-weight: 600;+ cursor: pointer;+ white-space: nowrap;+ transition:+ background 0.15s,+ border-color 0.15s,+ transform 0.1s;+}+.wgx-btn:hover {+ background: color-mix(in srgb, var(--text) 11%, transparent);+}+.wgx-btn:active {+ transform: scale(0.97);+}+.wgx-btn:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}+.wgx-btn.primary {+ background: var(--accent);+ border-color: transparent;+ color: #fff;+}+.wgx-btn.primary:hover {+ background: color-mix(in srgb, var(--accent) 86%, #fff);+}+.wgx-btn.icon {+ width: 32px;+ padding: 0;+}+.wgx-btn.ghost {+ background: none;+ border-color: transparent;+ color: var(--text2);+}+.wgx-btn.ghost:hover {+ color: var(--text);+ background: var(--wgx-soft);+}+.wgx-mute {+ color: var(--text2);+ margin: 0;+ font-size: 12px;+}++.wgx-skel {+ display: grid;+ gap: 9px;+ padding-top: 4px;+}+.wgx-skel i {+ display: block;+ height: 14px;+ border-radius: 7px;+ background: linear-gradient(90deg, var(--wgx-soft) 0%, color-mix(in srgb, var(--text) 13%, transparent) 50%, var(--wgx-soft) 100%);+ background-size: 200% 100%;+ animation: wgx-shimmer 1.3s linear infinite;+}+.wgx-skel i:first-child {+ height: 26px;+ width: 62%;+}+.wgx-skel i:nth-child(3n) {+ width: 80%;+}+.wgx-skel.news i {+ height: 64px;+ width: auto;+ border-radius: 12px;+}+@keyframes wgx-shimmer {+ to {+ background-position: -200% 0;+ }+}++.wgx-off,+.wgx-empty {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ justify-content: center;+ gap: 8px;+ color: var(--text2);+ font-size: 12.5px;+}+.wgx-off b {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ color: var(--text);+ font-size: 13px;+}+.wgx-empty.big {+ align-items: center;+ text-align: center;+ padding: 40px 12px;+ grid-column: 1 / -1;+}++/* ---------- $THREE ---------- */++.wgx-price {+ display: flex;+ align-items: baseline;+ gap: 10px;+ flex-wrap: wrap;+}+.wgx-price b {+ font-size: 28px;+ font-weight: 650;+ letter-spacing: -0.02em;+ font-variant-numeric: tabular-nums;+}+.sz-s .wgx-price b {+ font-size: 21px;+}+.wgx-chg {+ padding: 2px 8px;+ border-radius: 99px;+ font-size: 12px;+ font-weight: 650;+ font-variant-numeric: tabular-nums;+}+.wgx-chg.up {+ color: var(--wgx-up);+ background: color-mix(in srgb, var(--wgx-up) 15%, transparent);+}+.wgx-chg.down {+ color: var(--wgx-down);+ background: color-mix(in srgb, var(--wgx-down) 15%, transparent);+}+.wgx-chart {+ flex: 1;+ min-height: 36px;+ display: flex;+ margin: 0 -14px;+}+.wgx-chart.up {+ color: var(--wgx-up);+}+.wgx-chart.down {+ color: var(--wgx-down);+}+.wgx-spark {+ width: 100%;+ height: 100%;+ display: block;+}+.wgx-nochart {+ align-self: center;+ padding: 0 14px;+}+.wgx-facts {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(70px, 1fr));+ gap: 6px;+ margin: 0;+}+.wgx-facts div {+ min-width: 0;+}+.wgx-facts dt {+ color: var(--text2);+ font-size: 11px;+}+.wgx-facts dd {+ margin: 0;+ font-weight: 650;+ font-variant-numeric: tabular-nums;+}+.wgx-row-btns {+ display: flex;+ gap: 8px;+}+.wgx-row-btns .wgx-btn {+ flex: 1;+}++/* ---------- weather ---------- */++.t-weather {+ --sky-a: #3d7fd9;+ --sky-b: #78b6f5;+}+.t-weather[data-sky] {+ color: #fff;+ background: linear-gradient(160deg, var(--sky-a), var(--sky-b));+ border-color: rgb(255 255 255 / 0.18);+}+.t-weather[data-sky] .wgx-title,+.t-weather[data-sky] .wgx-more,+.t-weather[data-sky] .wgx-wx-meta,+.t-weather[data-sky] .wgx-hours small,+.t-weather[data-sky] .wgx-days small,+.t-weather[data-sky] .wgx-wx-label span {+ color: rgb(255 255 255 / 0.82);+}+.t-weather[data-sky] .wgx-more:hover {+ background: rgb(255 255 255 / 0.16);+ color: #fff;+}+.t-weather[data-sky^='sun'] {+ --sky-a: #2f80ed;+ --sky-b: #6fc3ff;+}+.t-weather[data-sky^='partly'] {+ --sky-a: #4a7fc8;+ --sky-b: #93bde8;+}+.t-weather[data-sky^='cloud'],+.t-weather[data-sky^='fog'] {+ --sky-a: #5f7088;+ --sky-b: #9aa9bd;+}+.t-weather[data-sky^='rain'] {+ --sky-a: #3a4e6e;+ --sky-b: #6b819f;+}+.t-weather[data-sky^='snow'] {+ --sky-a: #7a93b6;+ --sky-b: #c3d3e8;+}+.t-weather[data-sky^='storm'] {+ --sky-a: #2b2f4a;+ --sky-b: #555a7a;+}+.t-weather[data-sky$='night'],+.t-weather[data-sky^='moon'] {+ --sky-a: #141b3a;+ --sky-b: #3a3f7a;+}+.wgx-wx-top {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ gap: 8px;+}+.wgx-wart {+ flex: none;+ filter: drop-shadow(0 4px 10px rgb(0 0 0 / 0.18));+}+.wgx-place-btn {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ max-width: 100%;+ padding: 2px 6px 2px 0;+ border: 0;+ border-radius: 6px;+ background: none;+ color: inherit;+ font: inherit;+ font-weight: 600;+ cursor: pointer;+}+.wgx-place-btn:hover {+ text-decoration: underline;+ text-underline-offset: 3px;+}+.wgx-place-btn .ico {+ transform: rotate(90deg);+}+.wgx-temp {+ font-size: 40px;+ font-weight: 300;+ line-height: 1.05;+ letter-spacing: -0.03em;+ font-variant-numeric: tabular-nums;+}+.sz-s .wgx-temp,+.t-weather.sz-m .wgx-temp {+ font-size: 34px;+}+.t-weather.sz-m .wgx-body {+ gap: 6px;+}+.t-weather.sz-m .wgx-hours {+ margin-top: auto;+}+.wgx-temp sup {+ font-size: 15px;+ font-weight: 500;+ vertical-align: top;+ margin-left: 2px;+ position: relative;+ top: 6px;+}+.wgx-wx-label {+ font-weight: 600;+}+.wgx-wx-label span {+ font-weight: 400;+ margin-left: 4px;+}+.wgx-wx-meta {+ display: flex;+ flex-wrap: wrap;+ gap: 4px 12px;+ font-size: 12px;+ color: var(--text2);+}+.wgx-hours,+.wgx-days {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ justify-content: space-between;+ gap: 4px;+}+.wgx-hours li {+ display: grid;+ justify-items: center;+ gap: 2px;+ font-size: 12px;+}+.wgx-days {+ flex-direction: column;+ gap: 2px;+ margin-top: auto;+}+.wgx-days li {+ display: grid;+ grid-template-columns: 1fr auto 40px 34px;+ align-items: center;+ gap: 8px;+ font-size: 12.5px;+}+.wgx-days b,+.wgx-days small {+ text-align: right;+ font-variant-numeric: tabular-nums;+}+.wgx-place {+ display: grid;+ gap: 8px;+ align-content: start;+ font-size: 12.5px;+}+.wgx-place p {+ margin: 0;+ color: var(--text2);+}+.wgx-place-row {+ display: flex;+ gap: 6px;+}+.wgx-place input {+ flex: 1;+ min-width: 0;+ height: 32px;+ padding: 0 10px;+ border-radius: 10px;+ border: 1px solid var(--wgx-line);+ background: var(--wgx-glass-2);+ color: var(--text);+ font: inherit;+}+.wgx-place input:focus {+ outline: 2px solid var(--accent);+ outline-offset: 0;+}+.wgx-place ul {+ list-style: none;+ margin: 0;+ padding: 0;+ display: grid;+ gap: 2px;+ max-height: 132px;+ overflow: auto;+}+.wgx-place li button {+ width: 100%;+ display: flex;+ gap: 6px;+ align-items: baseline;+ padding: 6px 8px;+ border: 0;+ border-radius: 8px;+ background: none;+ color: var(--text);+ font: inherit;+ text-align: left;+ cursor: pointer;+}+.wgx-place li button:hover {+ background: var(--wgx-soft);+}+.wgx-place li span {+ color: var(--text2);+ font-size: 11.5px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.wgx-place-cancel {+ justify-self: start;+}++/* ---------- clock ---------- */++.wgx-clock {+ flex-direction: row;+ align-items: center;+ gap: 16px;+}+.wgx-clock.sz-s {+ flex-direction: column;+ justify-content: center;+ gap: 6px;+}+.wgx-clock .wgx-face {+ flex: none;+ width: 112px;+ height: 112px;+}+.wgx-clock.sz-s .wgx-face {+ width: 86px;+ height: 86px;+}+.wgx-clock.sz-l .wgx-face {+ width: 210px;+ height: 210px;+}+.wgx-clock.sz-l {+ flex-direction: column;+ justify-content: center;+}+.wgx-face .rim {+ fill: color-mix(in srgb, var(--text) 5%, transparent);+ stroke: color-mix(in srgb, var(--text) 14%, transparent);+ stroke-width: 1.5;+}+.wgx-face .ticks path {+ stroke: var(--text2);+ stroke-width: 2;+ stroke-linecap: round;+}+.wgx-face .hh,+.wgx-face .mh {+ stroke: var(--text);+ stroke-linecap: round;+}+.wgx-face .hh {+ stroke-width: 4.5;+}+.wgx-face .mh {+ stroke-width: 3;+}+.wgx-face .sh {+ stroke: var(--accent);+ stroke-width: 1.5;+ stroke-linecap: round;+}+.wgx-face .hub {+ fill: var(--accent);+}+.wgx-clock-txt {+ display: grid;+ gap: 2px;+ min-width: 0;+}+.wgx-clock-txt b {+ font-size: 26px;+ font-weight: 600;+ letter-spacing: -0.02em;+ font-variant-numeric: tabular-nums;+}+.wgx-clock-txt span {+ color: var(--text2);+}+.wgx-clock-txt small {+ color: var(--text2);+ font-size: 11px;+}+.wgx-clock.sz-s .wgx-clock-txt {+ text-align: center;+}+.wgx-clock.sz-s .wgx-clock-txt b {+ font-size: 15px;+}+.wgx-clock.sz-s .wgx-clock-txt span,+.wgx-clock.sz-s .wgx-clock-txt small {+ display: none;+}+.wgx-clock.sz-l .wgx-clock-txt {+ text-align: center;+}++/* ---------- calendar ---------- */++.wgx-cal-today {+ display: flex;+ align-items: center;+ gap: 12px;+}+.wgx-cal-today b {+ font-size: 40px;+ font-weight: 300;+ line-height: 1;+ color: var(--accent);+}+.wgx-cal-today span {+ display: grid;+ font-weight: 600;+}+.wgx-cal-today small {+ font-weight: 400;+ color: var(--text2);+}+.wgx-cal-week {+ list-style: none;+ margin: auto 0 0;+ padding: 0;+ display: grid;+ grid-template-columns: repeat(7, 1fr);+ gap: 2px;+ text-align: center;+}+.wgx-cal-week li {+ display: grid;+ gap: 2px;+ padding: 6px 0;+ border-radius: 10px;+}+.wgx-cal-week small {+ color: var(--text2);+ font-size: 11px;+}+.wgx-cal-week .today {+ background: var(--accent);+ color: #fff;+}+.wgx-cal-week .today small {+ color: rgb(255 255 255 / 0.85);+}+.wgx-cal-week .mute {+ opacity: 0.5;+}+.wgx-cal-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+}+.wgx-cal-head > span {+ display: flex;+ gap: 2px;+}+.wgx-cal-head .wgx-btn {+ width: 28px;+ height: 28px;+ background: none;+ border-color: transparent;+}+.wgx-cal-head .wgx-btn:hover {+ background: var(--wgx-soft);+}+.wgx-cal-grid {+ flex: 1;+ display: grid;+ grid-template-columns: repeat(7, 1fr);+ grid-auto-rows: 1fr;+ align-items: center;+ text-align: center;+ font-size: 12px;+ font-variant-numeric: tabular-nums;+}+.wgx-cal-grid i {+ font-style: normal;+ color: var(--text2);+ font-size: 11px;+}+.wgx-cal-grid b {+ font-weight: 500;+ justify-self: center;+ display: grid;+ place-items: center;+ width: 26px;+ height: 26px;+ border-radius: 50%;+}+.wgx-cal-grid b.mute {+ opacity: 0.4;+}+.wgx-cal-grid b.today {+ background: var(--accent);+ color: #fff;+ font-weight: 700;+}++/* ---------- lists (agents, pulse, launches, news) ---------- */++.wgx-list,+.wgx-news,+.wgx-faces,+.wgx-stats,+.wgx-sysl {+ list-style: none;+ margin: 0;+ padding: 0;+}+.wgx-list {+ display: grid;+ gap: 2px;+ margin: 0 -8px;+}+.wgx-list a,+.wgx-list button {+ width: 100%;+ display: grid;+ grid-template-columns: 32px 1fr auto;+ align-items: center;+ gap: 10px;+ padding: 6px 8px;+ border: 0;+ border-radius: 10px;+ background: none;+ color: var(--text);+ font: inherit;+ text-align: left;+ text-decoration: none;+ cursor: pointer;+}+.wgx-list a:hover,+.wgx-list button:hover {+ background: var(--wgx-soft);+}+.wgx-list a:active,+.wgx-list button:active {+ background: color-mix(in srgb, var(--text) 10%, transparent);+}+.wgx-list span {+ display: grid;+ min-width: 0;+}+.wgx-list b,+.wgx-list small {+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.wgx-list b {+ font-weight: 600;+}+.wgx-list b em {+ font-style: normal;+ font-weight: 500;+ color: var(--text2);+ font-size: 11.5px;+}+.wgx-list small,+.wgx-list time {+ color: var(--text2);+ font-size: 11.5px;+}+.wgx-av,+.wgx-fav {+ width: 32px;+ height: 32px;+ border-radius: 10px;+ object-fit: cover;+ background: var(--wgx-soft);+}+.wgx-av.ph,+.wgx-fav.ph {+ display: grid;+ place-items: center;+ font-style: normal;+ font-weight: 700;+ color: #fff;+ background: linear-gradient(135deg, var(--theme-1, #ad6eca), var(--theme-2, #3b91d8));+}+.wgx-faces {+ flex: 1;+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ align-content: center;+ gap: 6px;+}+.wgx-faces button {+ width: 100%;+ display: grid;+ justify-items: center;+ gap: 6px;+ padding: 6px 2px;+ border: 0;+ border-radius: 12px;+ background: none;+ color: var(--text);+ font: inherit;+ font-size: 11.5px;+ cursor: pointer;+}+.wgx-faces button:hover {+ background: var(--wgx-soft);+}+.wgx-faces .wgx-fav {+ width: 48px;+ height: 48px;+ border-radius: 14px;+ font-size: 18px;+}+.wgx-faces span {+ max-width: 100%;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++/* ---------- platform ---------- */++.wgx-stats {+ flex: 1;+ display: grid;+ align-content: center;+ gap: 8px;+}+.wgx-stats li {+ display: grid;+ grid-template-columns: 18px auto 1fr;+ align-items: baseline;+ gap: 8px;+ color: var(--text2);+}+.wgx-stats li .ico {+ align-self: center;+ color: var(--accent);+}+.wgx-stats b {+ color: var(--text);+ font-size: 20px;+ font-weight: 650;+ font-variant-numeric: tabular-nums;+}+.wgx-stats.tight {+ gap: 3px;+}+.wgx-stats.tight li {+ grid-template-columns: 16px auto;+ row-gap: 0;+}+.wgx-stats.tight b {+ font-size: 16px;+ line-height: 1.2;+}+.wgx-stats.tight span {+ grid-column: 2;+ font-size: 10.5px;+ line-height: 1.2;+}++/* ---------- news ---------- */++.wgx-lead {+ position: relative;+ display: block;+ flex: none;+ height: 150px;+ margin: 0 -6px;+ border-radius: 14px;+ overflow: hidden;+ color: #fff;+ text-decoration: none;+ background: var(--wgx-soft);+}+.wgx-lead img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ transition: transform 0.4s;+}+.wgx-lead:hover img {+ transform: scale(1.04);+}+.wgx-lead span {+ position: absolute;+ inset: auto 0 0;+ display: grid;+ gap: 2px;+ padding: 28px 12px 10px;+ background: linear-gradient(transparent, rgb(0 0 0 / 0.78));+}+.wgx-lead b {+ font-size: 13.5px;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}+.wgx-lead small {+ opacity: 0.85;+ font-size: 11px;+}+.wgx-news {+ display: grid;+ gap: 2px;+ margin: 0 -8px;+}+.wgx-news a {+ display: grid;+ gap: 2px;+ padding: 6px 8px;+ border-radius: 10px;+ color: var(--text);+ text-decoration: none;+}+.wgx-news a:hover {+ background: var(--wgx-soft);+}+.wgx-news b {+ font-weight: 600;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}+.wgx-news small {+ color: var(--text2);+ font-size: 11px;+}++/* ---------- system ---------- */++.wgx-sysl {+ display: grid;+ gap: 10px;+ align-content: center;+ flex: 1;+}+.wgx-sysl li {+ display: grid;+ grid-template-columns: 18px 1fr;+ gap: 10px;+ align-items: start;+}+.wgx-sysl li .ico {+ color: var(--accent);+ margin-top: 2px;+}+.wgx-sysl span {+ display: grid;+ gap: 2px;+ min-width: 0;+}+.wgx-sysl small {+ color: var(--text2);+ font-size: 11px;+}+.wgx-sysl b {+ font-weight: 600;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.wgx-meter {+ display: block;+ height: 5px;+ border-radius: 3px;+ background: var(--wgx-soft);+ overflow: hidden;+ margin-top: 3px;+}+.wgx-meter s {+ display: block;+ height: 100%;+ border-radius: inherit;+ background: linear-gradient(90deg, var(--theme-1, #ad6eca), var(--theme-2, #3b91d8));+}++/* ---------- note ---------- */++.t-note {+ background: color-mix(in srgb, #ffd95a 30%, var(--wgx-glass));+}+.wgx-note {+ padding: 4px 8px 8px;+}+.wgx-note textarea {+ flex: 1;+ width: 100%;+ resize: none;+ padding: 6px;+ border: 0;+ border-radius: 10px;+ background: none;+ color: var(--text);+ font: inherit;+ font-size: 14px;+ line-height: 1.5;+}+.wgx-note textarea:focus {+ outline: none;+ background: var(--wgx-soft);+}+.wgx-note textarea::placeholder {+ color: var(--text2);+}++/* ---------- desktop layer ---------- */++.wgx-desk {+ position: absolute;+ inset: 12px 12px 84px 120px;+ pointer-events: none;+ z-index: 1;+}+.wgx-desk > .wgx {+ position: absolute;+ pointer-events: auto;+ animation: wgx-in 0.32s cubic-bezier(0.2, 0.8, 0.2, 1) both;+ transition:+ right 0.24s cubic-bezier(0.2, 0.8, 0.2, 1),+ top 0.24s cubic-bezier(0.2, 0.8, 0.2, 1),+ width 0.24s,+ height 0.24s,+ box-shadow 0.18s,+ border-color 0.18s;+}+.wgx-desk > .wgx > header {+ cursor: grab;+ touch-action: none;+}+.wgx-desk > .wgx.dragging {+ transition: none;+ z-index: 3;+ cursor: grabbing;+ box-shadow: 0 28px 60px -18px rgb(0 0 0 / 0.55);+ transform: scale(1.02);+}+.wgx-desk > .wgx.dragging > header {+ cursor: grabbing;+}+@keyframes wgx-in {+ from {+ opacity: 0;+ transform: translateY(8px) scale(0.97);+ }+}+.wgx-ghost {+ position: absolute;+ border-radius: var(--wgx-radius);+ border: 2px dashed color-mix(in srgb, var(--accent) 70%, transparent);+ background: color-mix(in srgb, var(--accent) 12%, transparent);+ opacity: 0;+ pointer-events: none;+ transition: opacity 0.12s;+}+.wgx-ghost.on {+ opacity: 1;+}+.wgx-x {+ position: absolute;+ top: 8px;+ right: 8px;+ z-index: 2;+ display: none;+ place-items: center;+ width: 24px;+ height: 24px;+ border-radius: 50%;+ border: 1px solid var(--wgx-line);+ background: var(--wgx-glass-2);+ color: var(--text);+ cursor: pointer;+}+.wgx-x:hover {+ background: var(--wgx-down);+ border-color: transparent;+ color: #fff;+}+.wgx-desk.editing > .wgx {+ outline: 2px dashed color-mix(in srgb, var(--accent) 60%, transparent);+ outline-offset: 3px;+}+.wgx-desk.editing .wgx-x {+ display: grid;+}+.wgx-desk.editing .wgx-more {+ opacity: 1;+ margin-right: 26px;+}+.wgx-editbar {+ position: absolute;+ left: 50%;+ bottom: 8px;+ display: flex;+ gap: 8px;+ padding: 8px;+ border-radius: 16px;+ background: var(--wgx-glass-2);+ backdrop-filter: blur(28px) saturate(1.6);+ -webkit-backdrop-filter: blur(28px) saturate(1.6);+ border: 1px solid var(--wgx-line);+ box-shadow: var(--wgx-shadow);+ pointer-events: auto;+ transform: translate(-50%, 16px);+ opacity: 0;+ visibility: hidden;+ transition:+ transform 0.2s,+ opacity 0.2s,+ visibility 0.2s;+}+.wgx-desk.editing .wgx-editbar {+ transform: translate(-50%, 0);+ opacity: 1;+ visibility: visible;+}+.wgx-desk.editing.empty .wgx-editbar::before {+ content: 'Your desktop has no widgets.';+ align-self: center;+ padding: 0 6px;+ color: var(--text2);+ font-size: 12.5px;+}++/* ---------- menu ---------- */++.wgx-menu {+ position: fixed;+ z-index: 10010;+ min-width: 200px;+ padding: 5px;+ border-radius: 12px;+ background: var(--wgx-glass-2);+ backdrop-filter: blur(30px) saturate(1.6);+ -webkit-backdrop-filter: blur(30px) saturate(1.6);+ border: 1px solid var(--wgx-line);+ box-shadow: 0 16px 40px -12px rgb(0 0 0 / 0.5);+ animation: wgx-pop 0.14s ease-out;+ color: var(--text);+}+.wgx-menu button {+ width: 100%;+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 7px 10px;+ border: 0;+ border-radius: 8px;+ background: none;+ color: inherit;+ font: inherit;+ font-size: 13px;+ text-align: left;+ cursor: pointer;+}+.wgx-menu button span {+ flex: 1;+}+.wgx-menu button:hover,+.wgx-menu button:focus-visible {+ background: var(--wgx-soft);+ outline: none;+}+.wgx-menu button:active {+ background: color-mix(in srgb, var(--text) 12%, transparent);+}+.wgx-menu button.on > .ico:last-child {+ color: var(--accent);+}+.wgx-menu hr {+ border: 0;+ border-top: 1px solid var(--wgx-line);+ margin: 4px 6px;+}+@keyframes wgx-pop {+ from {+ opacity: 0;+ transform: scale(0.97);+ }+}++/* ---------- Add widget gallery ---------- */++.wgx-gallery-back {+ position: fixed;+ inset: 0;+ z-index: 10012;+ display: grid;+ place-items: center;+ padding: 16px;+ background: rgb(0 0 0 / 0.32);+ animation: wgx-fade 0.16s ease-out;+}+@keyframes wgx-fade {+ from {+ opacity: 0;+ }+}+.wgx-gallery {+ width: min(760px, 100%);+ max-height: min(600px, 100%);+ display: flex;+ flex-direction: column;+ border-radius: 18px;+ background: var(--wgx-glass-2);+ backdrop-filter: blur(40px) saturate(1.6);+ -webkit-backdrop-filter: blur(40px) saturate(1.6);+ border: 1px solid var(--wgx-line);+ box-shadow: 0 30px 80px -20px rgb(0 0 0 / 0.6);+ color: var(--text);+ overflow: hidden;+ animation: wgx-pop 0.18s ease-out;+}+.wgx-gallery > header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 14px 14px 10px 20px;+ font-size: 15px;+}+.wgx-gal-main {+ flex: 1;+ min-height: 0;+ display: grid;+ grid-template-columns: 250px 1fr;+ border-top: 1px solid var(--wgx-line);+}+.wgx-gal-list {+ list-style: none;+ margin: 0;+ padding: 8px;+ overflow: auto;+ border-right: 1px solid var(--wgx-line);+}+.wgx-gal-list button {+ width: 100%;+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 8px 10px;+ border: 0;+ border-radius: 10px;+ background: none;+ color: var(--text);+ font: inherit;+ text-align: left;+ cursor: pointer;+}+.wgx-gal-list button > .ico {+ flex: none;+ color: var(--accent);+}+.wgx-gal-list button span {+ display: grid;+ min-width: 0;+}+.wgx-gal-list small {+ color: var(--text2);+ font-size: 11.5px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.wgx-gal-list button:hover {+ background: var(--wgx-soft);+}+.wgx-gal-list button[aria-selected='true'] {+ background: color-mix(in srgb, var(--accent) 16%, transparent);+}+.wgx-gal-preview {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 16px;+ padding: 20px;+ min-height: 0;+ overflow: auto;+ background:+ radial-gradient(circle at 30% 20%, color-mix(in srgb, var(--theme-1, #ad6eca) 22%, transparent), transparent 60%),+ radial-gradient(circle at 80% 90%, color-mix(in srgb, var(--theme-2, #3b91d8) 22%, transparent), transparent 60%);+}+.wgx-gal-stage {+ display: grid;+ place-items: center;+ min-height: 350px;+}+.wgx-gal-stage .wgx {+ width: 168px;+ height: 168px;+}+.wgx-gal-stage .wgx.sz-m {+ width: 350px;+}+.wgx-gal-stage .wgx.sz-l {+ width: 350px;+ height: 350px;+}+.wgx-gal-sizes {+ display: flex;+ gap: 4px;+ padding: 3px;+ border-radius: 11px;+ background: var(--wgx-soft);+}+.wgx-gal-sizes button {+ padding: 5px 14px;+ border: 0;+ border-radius: 8px;+ background: none;+ color: var(--text2);+ font: inherit;+ font-size: 12.5px;+ cursor: pointer;+}+.wgx-gal-sizes button:hover {+ color: var(--text);+}+.wgx-gal-sizes button[aria-checked='true'] {+ background: var(--wgx-glass-2);+ color: var(--text);+ font-weight: 600;+ box-shadow: 0 1px 3px rgb(0 0 0 / 0.2);+}++/* ---------- widgets board ---------- */++.wgx-board {+ position: absolute;+ left: 50%;+ z-index: 10001;+ width: min(900px, calc(100vw - 16px));+ display: grid;+ grid-template-columns: auto 1fr;+ gap: 0;+ border-radius: 22px;+ background: color-mix(in srgb, var(--bg) 52%, transparent);+ backdrop-filter: blur(48px) saturate(1.8);+ -webkit-backdrop-filter: blur(48px) saturate(1.8);+ border: 1px solid var(--wgx-line);+ box-shadow: 0 30px 80px -20px rgb(0 0 0 / 0.6);+ overflow: hidden;+ transform: translate(-50%, 24px);+ opacity: 0;+ transition:+ transform 0.24s cubic-bezier(0.2, 0.8, 0.2, 1),+ opacity 0.2s;+}+.wgx-board.in {+ transform: translate(-50%, 0);+ opacity: 1;+}+.wgx-board.out {+ transform: translate(-50%, 18px);+ opacity: 0;+ transition-duration: 0.16s;+}+.wgx-col {+ display: flex;+ flex-direction: column;+ min-height: 0;+ min-width: 0;+}+.wgx-col-w {+ width: calc(168px * 2 + 14px + 36px);+ border-right: 1px solid var(--wgx-line);+}+.wgx-bar {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ padding: 16px 18px 10px;+ flex: none;+}+.wgx-hello {+ display: grid;+ min-width: 0;+}+.wgx-hello b {+ font-size: 17px;+ font-weight: 650;+}+.wgx-hello small {+ color: var(--text2);+ font-size: 12px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.wgx-grid {+ display: grid;+ grid-template-columns: repeat(2, 168px);+ grid-auto-rows: 168px;+ grid-auto-flow: row dense;+ gap: 14px;+ padding: 4px 18px 18px;+ overflow: auto;+ overscroll-behavior: contain;+ scrollbar-width: thin;+}+.wgx-grid > .wgx.sz-m {+ grid-column: span 2;+}+.wgx-grid > .wgx.sz-l {+ grid-column: span 2;+ grid-row: span 2;+}+.wgx-feed {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));+ align-content: start;+ gap: 12px;+ padding: 4px 18px 18px;+ overflow: auto;+ overscroll-behavior: contain;+ scrollbar-width: thin;+}+.wgx-feed > .wgx-skel,+.wgx-feed > .wgx-off,+.wgx-feed > .wgx-empty {+ grid-column: 1 / -1;+}+.wgx-story {+ display: flex;+ flex-direction: column;+ border-radius: 16px;+ overflow: hidden;+ background: var(--wgx-glass);+ border: 1px solid var(--wgx-line);+ color: var(--text);+ text-decoration: none;+ transition:+ transform 0.18s,+ border-color 0.18s,+ background 0.18s;+}+.wgx-story:hover {+ transform: translateY(-2px);+ border-color: color-mix(in srgb, var(--text) 20%, transparent);+ background: var(--wgx-glass-2);+}+.wgx-story:active {+ transform: none;+}+.wgx-story:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}+.wgx-story img {+ width: 100%;+ aspect-ratio: 16 / 9;+ object-fit: cover;+ background: var(--wgx-soft);+}+.wgx-story > span {+ display: grid;+ gap: 4px;+ padding: 10px 12px 12px;+}+.wgx-story small {+ color: var(--text2);+ font-size: 11px;+}+.wgx-story b {+ font-size: 13.5px;+ font-weight: 600;+ line-height: 1.35;+ display: -webkit-box;+ -webkit-line-clamp: 3;+ -webkit-box-orient: vertical;+ overflow: hidden;+}+.wgx-story em {+ font-style: normal;+ color: var(--text2);+ font-size: 12px;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}+.wgx-story.lead {+ grid-column: 1 / -1;+ position: relative;+}+.wgx-story.lead img {+ aspect-ratio: 21 / 9;+}+.wgx-story.lead b {+ font-size: 17px;+}++/* ---------- small screens ---------- */++@media (max-width: 860px) {+ .wgx-board {+ grid-template-columns: 1fr;+ overflow: auto;+ }+ .wgx-col-w {+ width: auto;+ border-right: 0;+ border-bottom: 1px solid var(--wgx-line);+ }+ .wgx-grid,+ .wgx-feed {+ overflow: visible;+ }+ .wgx-grid {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ grid-auto-rows: minmax(150px, auto);+ }+ .wgx-grid > .wgx.sz-l {+ grid-row: span 2;+ }+}+@media (max-width: 640px) {+ .wgx-desk {+ display: none;+ }+ .wgx-gal-main {+ grid-template-columns: 1fr;+ overflow: auto;+ }+ .wgx-gal-list {+ border-right: 0;+ border-bottom: 1px solid var(--wgx-line);+ max-height: 220px;+ }+ .wgx-gal-stage {+ min-height: 0;+ transform: scale(0.85);+ }+ .wgx-gal-stage .wgx.sz-m,+ .wgx-gal-stage .wgx.sz-l {+ width: min(350px, 86vw);+ }+}++@media (prefers-reduced-motion: reduce) {+ .wgx,+ .wgx-desk > .wgx,+ .wgx-board,+ .wgx-editbar,+ .wgx-story,+ .wgx-lead img,+ .wgx-menu,+ .wgx-gallery,+ .wgx-gallery-back {+ animation: none;+ transition: none;+ }+ .wgx-skel i {+ animation: none;+ }+}diff --git a/src/field/README.md b/src/field/README.mdindex c03d91f18..807596cd6 100644--- a/src/field/README.md+++ b/src/field/README.md@@ -5,7 +5,7 @@ product surface. Feature doc: [docs/field.md](../../docs/field.md).| File | Role || --- | --- |-| `entry.js` | Loaded by `pages/desktop.html`. Mounts the Field, or the legacy desktop and campus (`src/desktop/main.js`) when the URL asks for them (`?view=desktop`, `?world=1`, `?boot`). |+| `entry.js` | Loaded by `pages/desktop.html`. Mounts the desktop (`src/desktop/main.js`) by default, or the Field when the URL asks for it (`?view=field`). || `logic.js` | Pure functions with no DOM: district layout and rings, agent spiral, camera math (`zoomAt`, `fitRect`, `zoomPath`), level of detail, event routing, formatting, search ranking and deep-link parsing. Covered by `tests/field-logic.test.js`. || `data.js` | The live feeds: `/api/stats`, `/api/three-token/stats`, `/api/agents/public`, `/api/avatars/public`, `/api/pump/launches`, `/api/pulse`, `/api/auth/me`, and the site nav (`/nav-data.js`) for search. || `field.js` | `mountField(root)`: builds the DOM world and canvas sky, runs the camera, input, polling, comets and surfaces. Returns `{ flyTo, dive, close }`. |diff --git a/src/field/entry.js b/src/field/entry.jsindex 58538d2f8..d863c3440 100644--- a/src/field/entry.js+++ b/src/field/entry.js@@ -1,9 +1,9 @@-// `/` entry. The Field is home; the windowed desktop and the walkable campus-// still answer at `?view=desktop` and `?world=1`.+// `/` entry. The desktop is home (with its campus at `?world=1`); the Field,+// the zoomable map of every agent and surface, answers at `?view=field`.-import { wantsLegacy } from './logic.js';+import { wantsField } from './logic.js';-if (wantsLegacy(location.search)) {+if (!wantsField(location.search)) {import('../desktop/main.js');} else {import('./field.js')@@ -11,6 +11,6 @@ if (wantsLegacy(location.search)) {.catch((err) => {console.error('[field] failed to start', err);const root = document.getElementById('os');- if (root) root.insertAdjacentHTML('afterbegin', '<p style="padding:24px;color:#fff;font:15px system-ui">The map could not start. Every page is linked below, or <a style="color:#b8a6ff" href="/?view=desktop">open the desktop</a>.</p>');+ if (root) root.insertAdjacentHTML('afterbegin', '<p style="padding:24px;color:#fff;font:15px system-ui">The map could not start. <a style="color:#b8a6ff" href="/">Open the desktop</a> instead.</p>');});}diff --git a/src/field/field.js b/src/field/field.jsindex 39b027270..ea092ef4a 100644--- a/src/field/field.js+++ b/src/field/field.js@@ -98,7 +98,7 @@ export function mountField(root) {<a class="fd-brand" href="/" aria-label="three.ws, back to the whole map"><b>three.ws</b><span class="fd-crumb" aria-live="polite">Field</span></a><nav class="fd-actions" aria-label="Other ways in"><a class="fd-btn fd-ghost" href="/?world=1" title="Walk the 3D campus as your avatar">Walk in</a>- <a class="fd-btn fd-ghost fd-hide-sm" href="/?view=desktop" title="The windowed desktop">Desktop</a>+ <a class="fd-btn fd-ghost fd-hide-sm" href="/" title="The windowed desktop">Desktop</a><span class="fd-acct"></span></nav></header>diff --git a/src/field/logic.js b/src/field/logic.jsindex 9a12407f3..4c2e20f7b 100644--- a/src/field/logic.js+++ b/src/field/logic.js@@ -324,8 +324,7 @@ export function deepLink(search, ids) {return null;}-/** The legacy desktop and campus still live at `?view=desktop` and `?world=1`. */-export function wantsLegacy(search) {- const p = new URLSearchParams(search || '');- return p.get('view') === 'desktop' || p.has('world') || p.has('boot');+/** `/` opens the desktop; the Field answers at `?view=field`. */+export function wantsField(search) {+ return new URLSearchParams(search || '').get('view') === 'field';}diff --git a/tests/desktop-assistant.test.js b/tests/desktop-assistant.test.jsnew file mode 100644index 000000000..295339724--- /dev/null+++ b/tests/desktop-assistant.test.js@@ -0,0 +1,65 @@+import { describe, it, expect } from 'vitest';+import { HISTORY_MAX, SUGGESTIONS, THREE_CA, hidePartialTag, parseActions, renderMarkdown, systemPrompt, trimHistory } from '../src/desktop/assistant/logic.js';+import { ALL_APPS } from '../src/desktop/apps.js';++describe('assistant prompt', () => {+ it('fits the API limit with the full app list and names $THREE', () => {+ const p = systemPrompt(ALL_APPS);+ expect(p.length).toBeLessThanOrEqual(2000);+ expect(p).toContain(THREE_CA);+ expect(p).toContain('create: Create');+ expect(p.endsWith('Do not use any other app id.')).toBe(true);+ });+ it('drops apps rather than overflow', () => {+ const many = Array.from({ length: 200 }, (_, i) => ({ id: `app${i}`, title: `App ${i}`, desc: 'x'.repeat(40) }));+ const p = systemPrompt(many);+ expect(p.length).toBeLessThanOrEqual(2000);+ expect(p).toContain('app0: App 0');+ expect(p).not.toContain('app199');+ });+ it('speaks as a chosen agent', () => {+ const p = systemPrompt([], { agent: { name: 'Nova' } });+ expect(p).toMatch(/^You are Nova/);+ expect(p).not.toContain('[[open:');+ });+});++describe('assistant actions', () => {+ it('keeps known app ids once and strips every tag', () => {+ const r = parseActions('Try Forge.\n\n[[open:forge]] [[open:forge]] [[open:nope]]', ['forge', 'create']);+ expect(r).toEqual({ text: 'Try Forge.', actions: ['forge'] });+ });+ it('hides a tag still streaming in', () => {+ expect(hidePartialTag('Open it [[open:for')).toBe('Open it ');+ expect(hidePartialTag('Done [[open:forge]]')).toBe('Done [[open:forge]]');+ });+});++describe('assistant history', () => {+ it('keeps the last 20 valid turns', () => {+ const msgs = [{ role: 'system', content: 'x' }, { role: 'user', content: ' ' }, ...Array.from({ length: 30 }, (_, i) => ({ role: i % 2 ? 'assistant' : 'user', content: `m${i}`, extra: 1 }))];+ const h = trimHistory(msgs);+ expect(h).toHaveLength(HISTORY_MAX);+ expect(h[0]).toEqual({ role: 'user', content: 'm10' });+ expect(trimHistory(null)).toEqual([]);+ });+});++describe('assistant markdown', () => {+ it('escapes html and formats the basics', () => {+ expect(renderMarkdown('<img src=x onerror=alert(1)> **bold** `a<b`')).toBe('<p><img src=x onerror=alert(1)> <strong>bold</strong> <code>a<b</code></p>');+ });+ it('renders lists, headings and code fences', () => {+ expect(renderMarkdown('## Steps\n1. One\n2. Two\n\n- a\n- b')).toBe('<h4>Steps</h4><ol><li>One</li><li>Two</li></ol><ul><li>a</li><li>b</li></ul>');+ expect(renderMarkdown('```\n<x>\n```')).toBe('<pre><code><x></code></pre>');+ });+ it('links only http(s) and same-site paths', () => {+ expect(renderMarkdown('[go](/forge)')).toContain('<a href="/forge"');+ expect(renderMarkdown('[x](javascript:alert(1))')).not.toContain('<a');+ expect(renderMarkdown('[x](//evil.example)')).not.toContain('<a');+ expect(renderMarkdown('see https://three.ws.')).toContain('<a href="https://three.ws"');+ });+ it('ships starter prompts', () => {+ expect(SUGGESTIONS.length).toBeGreaterThan(2);+ });+});diff --git a/tests/desktop-widgets.test.js b/tests/desktop-widgets.test.jsnew file mode 100644index 000000000..5727c021e--- /dev/null+++ b/tests/desktop-widgets.test.js@@ -0,0 +1,190 @@+import { describe, it, expect } from 'vitest';+import {+ CATALOG,+ DEFAULT_LAYOUT,+ SIZES,+ STEP,+ UNIT,+ GAP,+ catalogItem,+ cellAt,+ firstFit,+ fits,+ fmtBytes,+ fmtCompact,+ fmtPct,+ fmtPrice,+ gridFor,+ monthGrid,+ pixelBox,+ relTime,+ settle,+ sparkPath,+ tzCity,+ usesFahrenheit,+ weatherInfo,+ weekStartFor,+} from '../src/desktop/widgets/logic.js';++const cells = (list) => {+ const taken = new Set();+ for (const w of list.filter((x) => !x.hidden)) {+ const s = SIZES[w.size];+ for (let c = w.col; c < w.col + s.w; c++) for (let r = w.row; r < w.row + s.h; r++) {+ const k = `${c},${r}`;+ if (taken.has(k)) return null;+ taken.add(k);+ }+ }+ return taken;+};++describe('widget catalog', () => {+ it('has unique types with a valid default size', () => {+ const types = CATALOG.map((c) => c.type);+ expect(new Set(types).size).toBe(types.length);+ for (const c of CATALOG) {+ expect(c.sizes.length).toBeGreaterThan(0);+ for (const s of c.sizes) expect(SIZES[s], `${c.type}:${s}`).toBeTruthy();+ }+ });+ it('starts from widgets that exist', () => {+ for (const w of DEFAULT_LAYOUT) expect(catalogItem(w.type)?.sizes).toContain(w.size);+ });+});++describe('widget grid', () => {+ it('measures how many units fit', () => {+ expect(gridFor(UNIT, UNIT)).toEqual({ cols: 1, rows: 1 });+ expect(gridFor(UNIT * 2 + GAP, UNIT * 3 + GAP * 2)).toEqual({ cols: 2, rows: 3 });+ expect(gridFor(UNIT - 1, 10)).toEqual({ cols: 0, rows: 0 });+ });+ it('packs the default layout into a laptop work area without overlap', () => {+ const grid = gridFor(1440 - 140, 900 - 80);+ const laid = settle(DEFAULT_LAYOUT, grid);+ expect(laid.every((w) => !w.hidden)).toBe(true);+ expect(cells(laid)).not.toBeNull();+ for (const w of laid) {+ const s = SIZES[w.size];+ expect(w.col + s.w).toBeLessThanOrEqual(grid.cols);+ expect(w.row + s.h).toBeLessThanOrEqual(grid.rows);+ }+ });+ it('fills from the right edge, top to bottom', () => {+ const grid = { cols: 4, rows: 3 };+ expect(firstFit({ id: 'a', size: 's' }, [], grid)).toEqual({ col: 0, row: 0 });+ const others = [{ id: 'x', size: 'l', col: 0, row: 0 }];+ expect(firstFit({ id: 'a', size: 's' }, others, grid)).toEqual({ col: 0, row: 2 });+ expect(firstFit({ id: 'a', size: 'm' }, others, grid)).toEqual({ col: 0, row: 2 });+ });+ it('rejects cells off the grid or under another widget', () => {+ const grid = { cols: 3, rows: 2 };+ const other = { id: 'o', size: 's', col: 1, row: 0 };+ expect(fits({ id: 'a', size: 'm' }, 0, 0, [other], grid)).toBe(false);+ expect(fits({ id: 'a', size: 'm' }, 0, 1, [other], grid)).toBe(true);+ expect(fits({ id: 'a', size: 'm' }, 2, 1, [], grid)).toBe(false);+ expect(fits({ id: 'o', size: 's' }, 1, 0, [other], grid)).toBe(true);+ });+ it('re-places stored widgets that collide and hides what cannot fit', () => {+ const grid = { cols: 2, rows: 2 };+ const laid = settle(+ [+ { id: 'a', type: 'pulse', size: 'l', col: 0, row: 0 },+ { id: 'b', type: 'clock', size: 's', col: 0, row: 0 },+ ],+ grid,+ );+ expect(laid[0]).toMatchObject({ id: 'a', col: 0, row: 0 });+ expect(laid[1]).toMatchObject({ id: 'b', hidden: true });+ });+ it('drops junk, unknown types and bad sizes from storage', () => {+ const laid = settle([null, 4, { type: 'nope' }, { type: 'clock', size: 'xl' }, { type: 'note', size: 'm', id: '<script>', data: { text: 'hi' } }], { cols: 6, rows: 4 });+ expect(laid.map((w) => w.type)).toEqual(['clock', 'note']);+ expect(laid[0].size).toBe('s');+ expect(laid[1].id).toMatch(/^[\w-]+$/);+ expect(laid[1].data).toEqual({ text: 'hi' });+ expect(settle('garbage', { cols: 2, rows: 2 })).toEqual([]);+ });+ it('converts between cells and pixels', () => {+ expect(pixelBox({ size: 'l', col: 1, row: 2 })).toEqual({ right: STEP, top: STEP * 2, width: UNIT * 2 + GAP, height: UNIT * 2 + GAP });+ expect(cellAt(STEP * 1.4, STEP * 0.6)).toEqual({ col: 1, row: 1 });+ expect(cellAt(-50, -50)).toEqual({ col: 0, row: 0 });+ });+});++describe('widget formatting', () => {+ it('prices sub-cent tokens with significant digits', () => {+ expect(fmtPrice(0.0005026)).toBe('$0.000503');+ expect(fmtPrice(0.12)).toBe('$0.120');+ expect(fmtPrice(1234.5)).toBe('$1,234.50');+ expect(fmtPrice(0)).toBe('$0.00');+ expect(fmtPrice('x')).toBe('');+ });+ it('compacts big numbers', () => {+ expect(fmtCompact(502446, '$')).toBe('$502K');+ expect(fmtCompact(15159)).toBe('15.2K');+ expect(fmtCompact(4468)).toBe('4.5K');+ expect(fmtCompact(1_500_000)).toBe('1.5M');+ expect(fmtCompact(90)).toBe('90');+ });+ it('signs percentages', () => {+ expect(fmtPct(-3.64)).toBe('-3.6%');+ expect(fmtPct(12.01)).toBe('+12.0%');+ expect(fmtPct(0)).toBe('0.0%');+ expect(fmtPct(null)).toBe('');+ });+ it('formats relative ages', () => {+ const now = Date.parse('2026-10-11T12:00:00Z');+ expect(relTime('2026-10-11T11:59:30Z', now)).toBe('now');+ expect(relTime('2026-10-11T11:00:00Z', now)).toBe('1h');+ expect(relTime('bad', now)).toBe('');+ });+ it('formats bytes', () => {+ expect(fmtBytes(512)).toBe('512 B');+ expect(fmtBytes(1536)).toBe('1.5 KB');+ expect(fmtBytes(8 * 1024 ** 3)).toBe('8.0 GB');+ });+});++describe('widget sparkline', () => {+ it('spans the box and inverts y', () => {+ const { line, area } = sparkPath([1, 3, 2], 100, 40, 0);+ expect(line).toBe('M0.0 40.0L50.0 0.0L100.0 20.0');+ expect(area.endsWith('L100 40L0 40Z')).toBe(true);+ });+ it('needs two points and survives a flat series', () => {+ expect(sparkPath([5], 10, 10).line).toBe('');+ expect(sparkPath([2, 2, 2], 10, 10, 0).line).toBe('M0.0 10.0L5.0 10.0L10.0 10.0');+ });+});++describe('widget weather and calendar', () => {+ it('maps weather codes and night icons', () => {+ expect(weatherInfo(0)).toEqual({ label: 'Clear', icon: 'sun' });+ expect(weatherInfo(0, false).icon).toBe('moon');+ expect(weatherInfo(63).label).toBe('Rain');+ expect(weatherInfo(999).label).toBe('Unknown');+ });+ it('reads a city out of a time zone', () => {+ expect(tzCity('America/New_York')).toBe('New York');+ expect(tzCity('Etc/GMT+3')).toBe('');+ expect(tzCity('UTC')).toBe('');+ });+ it('picks Fahrenheit only where it is used', () => {+ expect(usesFahrenheit('en-US')).toBe(true);+ expect(usesFahrenheit('en-GB')).toBe(false);+ });+ it('lays out a month starting on the right weekday', () => {+ const oct = monthGrid(new Date(2026, 9, 11), 1, new Date(2026, 9, 11));+ expect(oct).toHaveLength(42);+ // 1 Oct 2026 is a Thursday: Monday-first weeks lead with 3 September days.+ expect(oct.slice(0, 4).map((c) => [c.d, c.inMonth])).toEqual([[28, false], [29, false], [30, false], [1, true]]);+ expect(oct.filter((c) => c.today)).toEqual([{ y: 2026, m: 9, d: 11, inMonth: true, today: true }]);+ const sun = monthGrid(new Date(2026, 9, 1), 0);+ expect(sun[4]).toMatchObject({ d: 1, inMonth: true });+ });+ it('knows a sensible first weekday', () => {+ expect([0, 1, 6]).toContain(weekStartFor('en-US'));+ expect(weekStartFor('de-DE')).toBe(1);+ });+});diff --git a/tests/field-logic.test.js b/tests/field-logic.test.jsindex 35d245653..29e1c197f 100644--- a/tests/field-logic.test.js+++ b/tests/field-logic.test.js@@ -23,7 +23,7 @@ import {screenToWorld,searchField,trailAlpha,- wantsLegacy,+ wantsField,worldBounds,worldToScreen,zoomAt,@@ -211,10 +211,11 @@ describe('field search and links', () => {expect(deepLink('?go=https://evil.example', [])).toBeNull();expect(deepLink('?go=//evil.example', [])).toBeNull();});- it('keeps the desktop and campus reachable', () => {- expect(wantsLegacy('?view=desktop')).toBe(true);- expect(wantsLegacy('?world=1')).toBe(true);- expect(wantsLegacy('?app=forge')).toBe(false);- expect(wantsLegacy('')).toBe(false);+ it('opens the desktop at / and keeps the Field one link away', () => {+ expect(wantsField('?view=field')).toBe(true);+ expect(wantsField('')).toBe(false);+ expect(wantsField('?view=desktop')).toBe(false);+ expect(wantsField('?world=1')).toBe(false);+ expect(wantsField('?app=forge')).toBe(false);});});