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): turn / into a web desktop with marquee-select icons, All Apps, a real Settings app and a session saved in the browser
nirholas400f8196ff62
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 9c72c5b15..10b691213 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -19,6 +19,7 @@ bottom.| Agent shell (companion identity + agentic ⌘K + persistent navigation) | [src/agents/guest-agent.js](src/agents/guest-agent.js), [src/shared/agent-names.js](src/shared/agent-names.js), [src/walk-companion-identity.js](src/walk-companion-identity.js), [public/search.js](public/search.js), [src/view-transitions.js](src/view-transitions.js), [src/shell/page-lifecycle.js](src/shell/page-lifecycle.js) | Live | The agent IS the interface: every visitor gets a named ephemeral agent in the first five seconds (auto-summoned corner companion with an identity chip; “Claim →” prefills /create-agent and POST /api/agents makes it real); the ⌘K palette executes real commands in place (forge → free text→3D lane, digest → clustered news, price → live market data, ask → streamed /api/chat) and announces completions so the companion reacts; pages marked data-shell (`/markets`, `/coins`) navigate by swapping only the main element so the agent and shell never unload (page modules re-init via onPageReady). Docs: [docs/agent-shell.md](docs/agent-shell.md). Tests: [tests/search-commands.test.js](tests/search-commands.test.js), [tests/guest-agent.test.js](tests/guest-agent.test.js), [tests/agent-names.test.js](tests/agent-names.test.js) || Event Markets core | [api/_lib/event-markets/index.js](api/_lib/event-markets/index.js), [odds.js](api/_lib/event-markets/odds.js), [config.js](api/_lib/event-markets/config.js), [view.js](api/_lib/event-markets/view.js), [routes.js](api/_lib/event-markets/routes.js), [api/event-markets/[...path].js](api/event-markets/[...path].js), [api/_mcpagent/event-markets-tools.js](api/_mcpagent/event-markets-tools.js), [data/event-markets.json](data/event-markets.json) | Live once migration 20261011020000 is applied | Markets, outcomes, picks, implied odds, lock boundary, season points budget, void refunds, history from the pick log, admin create/edit/lock/void/resolve, MCP `event_markets_list` / `event_market` / `event_market_pick`. Docs: [docs/event-markets.md](docs/event-markets.md#markets-picks-and-odds-core). Tests: [tests/event-markets.test.js](tests/event-markets.test.js), [tests/event-markets-mcp.test.js](tests/event-markets-mcp.test.js) || Event Market announcements | [api/_lib/event-markets/announce.js](api/_lib/event-markets/announce.js), [review.js](api/_lib/event-markets/review.js), [poster.js](api/_lib/event-markets/poster.js), [api/event-markets/announcements.js](api/event-markets/announcements.js), [api/cron/event-market-announce.js](api/cron/event-market-announce.js), [pages/event-market-announcements.html](pages/event-market-announcements.html) `→ /admin/event-market-announcements` | Live, posting off until the owner enables it | Cron writes drafts per market lifecycle change; admin queue approves, edits, rejects; poster is the only sender and refuses anything not approved (flag `EVENT_MARKET_ANNOUNCE_POST`, daily cap). Entrants tagged only with self-linked X handles. Docs: [docs/event-markets.md](docs/event-markets.md). Tests: [tests/event-market-announcements.test.js](tests/event-market-announcements.test.js) |+| Web desktop (homepage as an OS) | Page [pages/desktop.html](pages/desktop.html) `→ /`, code [src/desktop/](src/desktop) ([README](src/desktop/README.md)), previous homepage [pages/home.html](pages/home.html) `→ /classic` | Built and verified locally | Taskbar, Start, widgets and snappable windows framing real three.ws pages in the CTRL Mica theme. Desktop icons on a snap grid with marquee selection ([icon-layer.js](src/desktop/icon-layer.js)), All Apps, a Settings app (profile, accent, wallpaper, icon size) and a session saved 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-layout.test.js](tests/desktop-layout.test.js), [tests/desktop-page.test.js](tests/desktop-page.test.js), browser drive [scripts/desktop-interact.mjs](scripts/desktop-interact.mjs) || Event Market auto-open | [api/_lib/event-markets/auto-open.js](api/_lib/event-markets/auto-open.js), [sources/](api/_lib/event-markets/sources/), [api/cron/event-markets-open.js](api/cron/event-markets-open.js), [api/ops/event-markets.js](api/ops/event-markets.js), [pages/event-markets-admin.html](pages/event-markets-admin.html) `→ /admin/event-markets` | Live once migration 20261012010000 is applied | Opens a market per Arena tournament, platform event, build round and bounty; adds late entrants pre-lock; logs skips; writes the `event_market.opened` outbox row. Docs: [docs/event-markets.md](docs/event-markets.md). Tests: [tests/event-markets-auto-open.test.js](tests/event-markets-auto-open.test.js) || Event Market resolution | [api/_lib/event-markets/resolvers/](api/_lib/event-markets/resolvers/), [lifecycle.js](api/_lib/event-markets/lifecycle.js), [override.js](api/_lib/event-markets/override.js), [api/cron/event-markets-resolve.js](api/cron/event-markets-resolve.js), [api/ops/event-market-override.js](api/ops/event-market-override.js), [data/event-market-resolution.json](data/event-market-resolution.json) | Live once migration 20261012130000 is applied | Locks at `locks_at`, resolves from our own arena, event, launch, round and bounty records with the evidence stored on the market, retries while pending, voids on tie, no data, cancellation or timeout; admin override needs a written reason. Docs: [docs/event-markets.md](docs/event-markets.md#how-markets-resolve). Tests: [tests/event-market-resolvers.test.js](tests/event-market-resolvers.test.js), [tests/event-market-lifecycle.test.js](tests/event-market-lifecycle.test.js) || Event Market pages and share cards | [pages/event-markets.html](pages/event-markets.html) `→ /event-markets`, [pages/event-market.html](pages/event-market.html) `→ /event-markets/<slug>`, [src/event-markets/](src/event-markets/), [api/event-market-og.js](api/event-market-og.js), [api/event-market-share.js](api/event-market-share.js), [api/_lib/event-market-card.js](api/_lib/event-market-card.js) | Live | Browse and detail pages, pick flow, odds chart, per-market SVG share card and crawlable meta page, entry strips on Arena, event, launches and home. Docs: [docs/event-markets.md](docs/event-markets.md#pages-and-share-cards). Tests: [tests/event-market-card.test.js](tests/event-market-card.test.js) |diff --git a/data/changelog.json b/data/changelog.jsonindex ca53ee8cc..5ae614333 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,25 @@{"$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": "The desktop behaves like a real computer",+ "link": "/docs/desktop",+ "summary": "Drag a selection box across the desktop, move icons on a snap grid, right-click for view options, and open every app from desktop icons or All Apps. Settings now covers your profile, theme, accent colour, wallpaper (including your own photo), icon size and taskbar, and the whole session (windows, icon layout, preferences) is saved in your browser, with export, import and reset.",+ "tags": [+ "feature",+ "desktop"+ ]+ },+ {+ "date": "2026-10-11",+ "title": "three.ws is now a desktop",+ "link": "/docs/desktop",+ "summary": "The homepage is a web desktop with a taskbar, Start menu, widgets and draggable, snappable windows that open every part of the platform, in the CTRL Windows-style Mica theme. The original homepage is kept as the classic view at /classic, one click from the taskbar.",+ "tags": [+ "feature"+ ]+ },{"date": "2026-10-11","title": "API keys can no longer arm spenders or move payout addresses without the wallet scope",diff --git a/data/pages.json b/data/pages.jsonindex 5211be552..ed90d3b05 100644--- a/data/pages.json+++ b/data/pages.json@@ -52,11 +52,19 @@{"path": "/","title": "Home",- "description": "Landing page. 3D AI agents that think on IBM watsonx.ai (Granite): the pitch, live agent demos, and the front door to every flow.",+ "description": "The three.ws web desktop: a taskbar, Start menu and windows that open every part of the platform, from making a 3D agent to the marketplace.","priority": 1,"changefreq": "weekly","added": "2026-04-16"},+ {+ "path": "/classic",+ "title": "Classic Home",+ "description": "The original three.ws landing page: the pitch, live agent demos and the front door to every flow, kept as the classic view of the desktop.",+ "priority": 0.5,+ "changefreq": "weekly",+ "added": "2026-10-11"+ },{"path": "/discover","title": "Discover",@@ -3670,6 +3678,14 @@"changefreq": "monthly","added": "2026-10-10"},+ {+ "path": "/docs/desktop",+ "title": "Web Desktop",+ "description": "How the three.ws web desktop works: the CTRL Mica theme, taskbar and Start menu, snappable windows that frame real pages, deep links, saved layout, the classic view and how to add an app.",+ "priority": 0.5,+ "changefreq": "monthly",+ "added": "2026-10-11"+ },{"path": "/docs/how-forge-works","title": "Docs · How the Forge works, in plain language",diff --git a/docs/desktop.md b/docs/desktop.mdnew file mode 100644index 000000000..8e13ee116--- /dev/null+++ b/docs/desktop.md@@ -0,0 +1,65 @@+# three.ws Desktop++`/` is a web desktop. Every window frames a real three.ws page, so nothing is+mocked and every existing surface works unchanged. The previous homepage is+kept at `/classic`.++## What is in it++- **Theme.** The CTRL design system (Windows-12 lineage): Mica gradients, glass+ and blur presets, the CTRL token names, light and dark. Dark is the default.+ Light follows the site-wide `twx_theme` switch, so the desktop and every+ framed page flip together. Tokens: `src/desktop/theme.css`.+- **Shell.** Taskbar with pinned and running apps, Start menu (search, pinned,+ recommended, all apps), widgets panel with a resident `<agent-3d>`, calendar,+ desktop icons, right-click menu, toasts. `src/desktop/shell.js`.+- **Windows.** Drag, eight-handle resize, snap to left, right or top edge,+ minimize, maximize, Alt+Tab, Alt+W. On a phone every window is full screen.+ `src/desktop/wm.js`; geometry in `src/desktop/layout.js` (unit tested).+- **Apps.** The curated set in `src/desktop/apps.js`, plus every internal page in+ `public/nav-data.js`, so the launcher cannot drift from the site navigation.+ Search with Ctrl+K or the Start menu.++## Working like a computer++- **Icons.** Every app has a desktop icon on a snap grid. Click selects, Ctrl or Shift extends the selection, double-click (or Enter) opens, and a tap opens on touch. Drag to move one icon or a whole selection; drops land on the nearest free cell. Arrow keys move focus, Ctrl+Arrow nudges, Ctrl+A selects all, Delete removes an icon from the desktop.+- **Rubber band.** Drag on the empty desktop to draw a selection box; Ctrl or Shift adds to the current selection.+- **Right-click.** The desktop menu sets icon size, sorts by name, auto-arranges, refreshes, and opens All Apps and Personalize. Icon menus open or remove the selection.+- **All Apps.** A native app listing every app and page from the site navigation, with Open and Add to desktop for each.+- **Settings.** Profile (name, avatar colour), Personalization (dark, light or match system, six accents, five wallpapers or your own photo), Desktop and taskbar (icon size, taskbar alignment, 24-hour clock), and Session and storage.+- **Session.** Open windows and their geometry, icon layout, preferences, recent apps and the custom wallpaper are saved in this browser (`tws:desktop`, `tws:icons`, `tws:prefs`, `tws:recent` in localStorage; the wallpaper image in IndexedDB database `tws-desktop`) and restored on reload. Settings can export the session to a JSON file, import one (only known `tws:` keys are accepted, files over 2 MB are refused), close all windows, or reset everything. Nothing is sent to a server.++## URLs and preferences++| What | How |+| --- | --- |+| Open an app on load | `/?app=forge` or `/#app=forge` |+| Force the desktop | `/?view=desktop` (also remembers the choice) |+| Classic site | `/classic`, or the taskbar button. Remembered in `tws:view` |+| Session | Window layout is saved in `tws:desktop` and restored on reload |++## How a framed page behaves++The iframe is named `tws-os:<app>`. `public/nav.js` sees that name and drops the+site header, footer and floating widgets in that frame (class `tws-in-os`), so a+window is all content. The same page opened in a normal tab is unchanged.++## Adding an app++Add an entry to `APPS` in `src/desktop/apps.js` (id, title, href, hue, icon,+size) and an icon glyph in `src/desktop/icons.js` if needed. Add the page link+to the no-JS list in `pages/desktop.html`; `tests/desktop-page.test.js` fails+until the two agree. A new skeleton or page needs no other wiring.++## Verify++`npm run dev`, then `node scripts/desktop-smoke.mjs http://localhost:3000` boots+the desktop in a real browser, opens the Start menu and an app, and reports+console errors and failed requests. `npx vitest run tests/desktop-layout.test.js+tests/desktop-page.test.js`.++## Provenance++The visual design language and token values are ported from CTRL+(`nirholas/CTRL`), whose theme descends from the open-source Win12 project. The+DOM and JavaScript here are written for three.ws and share no code with it.diff --git a/pages/desktop.html b/pages/desktop.htmlnew file mode 100644index 000000000..3d85dfb97--- /dev/null+++ b/pages/desktop.html@@ -0,0 +1,55 @@+<!doctype html>+<html lang="en">+<head>+ <script>/* three.ws theme boot, no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <script>/* View preference: visitors who chose the classic site land there. ?view=desktop overrides and re-selects the desktop. */(function(){try{var q=new URLSearchParams(location.search).get('view');if(q==='desktop'){localStorage.setItem('tws:view','desktop');}else if(localStorage.getItem('tws:view')==='classic'){location.replace('/classic'+location.search+location.hash);}}catch(e){}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover" />+ <title>three.ws: The 3D Agent Layer of the Internet</title>+ <meta name="description" content="three.ws is a web desktop for 3D AI agents. Make an agent from a selfie, forge 3D models from a prompt, and open every part of the platform as a window. Embed your agent anywhere with one HTML tag." />+ <link rel="canonical" href="https://three.ws/" />+ <link rel="alternate" type="text/plain" title="llms.txt" href="/llms.txt" />+ <meta name="theme-color" content="#101010" />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/" />+ <meta property="og:title" content="three.ws: The 3D Agent Layer of the Internet" />+ <meta property="og:description" content="A web desktop for 3D AI agents. Make one from a selfie, embed it anywhere." />+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&t=Home&d=The+3D+agent+layer+of+the+internet&p=%2F" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="three.ws: The 3D Agent Layer of the Internet" />+ <meta name="twitter:description" content="A web desktop for 3D AI agents. Make one from a selfie, embed it anywhere." />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://three.ws/#organization","name":"three.ws","url":"https://three.ws","logo":"https://three.ws/og-image.png","description":"three.ws is the AI-agent layer for the open web: build, embed, monetize, and trade autonomous agents with real 3D avatars, on-chain identity (ERC-8004), pay-per-call (x402), and pump.fun token launches.","sameAs":["https://x.com/trythreews","https://github.com/nirholas/three.ws","https://www.coingecko.com/en/coins/three-ws","https://www.npmjs.com/package/three.ws","https://registry.modelcontextprotocol.io/?q=threews","https://coinmarketcap.com/community/profile/three_ws","https://hackernoon.com/u/three-ws","https://t.me/three_ws"]},{"@type":"WebSite","@id":"https://three.ws/#website","name":"three.ws","url":"https://three.ws","description":"Give your AI a body.","publisher":{"@id":"https://three.ws/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://three.ws/discover?q={search_term_string}"},"query-input":"required name=search_term_string"}}]}</script>+</head>+<body>+ <div id="os" aria-label="three.ws desktop">+ <h1>three.ws: The 3D Agent Layer of the Internet</h1>+ <p>Make a living 3D AI agent from a selfie, forge 3D models from a prompt, and embed your agent on any site.</p>+ <ul>+ <li><a href="/create">Create</a>: Make an agent, avatar, 3D model or token world</li>+ <li><a href="/forge">Forge</a>: Type a prompt, get a textured 3D model</li>+ <li><a href="/discover">Discover</a>: Browse every registered agent on Solana and EVM</li>+ <li><a href="/chat">Chat</a>: Talk to an agent</li>+ <li><a href="/marketplace">Marketplace</a>: Buy and sell agent skills</li>+ <li><a href="/agent-studio">Agent Studio</a>: Author brains, skills and personality</li>+ <li><a href="/mine">My Creations</a>: Everything you have made, newest first</li>+ <li><a href="/gallery">Gallery</a>: Every public 3D avatar</li>+ <li><a href="/pulse">Pulse</a>: Live feed of agent wallet activity</li>+ <li><a href="/trenches">Trenches</a>: Live Solana launches, runners and smart money</li>+ <li><a href="/dashboard">Console</a>: Your agents, wallets and usage</li>+ <li><a href="/tour">Tour</a>: A guided walk through the platform</li>+ </ul>+ <p><a href="/classic">Classic website</a></p>+ <noscript><p>The desktop needs JavaScript. The links above work without it.</p></noscript>+ </div>+ <script type="module" src="/src/desktop/main.js"></script>+</body>+</html>diff --git a/pages/home.html b/pages/home.htmlindex 7e48bceed..24cac12c9 100644--- a/pages/home.html+++ b/pages/home.html@@ -3930,5 +3930,16 @@ import { attendRotation } from '/src/shared/attended-rotation.js';</script><!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. --><script type="module" src="/i18n.js"></script>+ <!-- Classic view -> desktop. The choice is remembered (tws:view) and honoured by the "/" route. -->+ <a id="to-desktop" href="/?view=desktop" aria-label="Switch to the three.ws desktop">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8 20h8M12 16v4"/></svg>+ Try the desktop+ </a>+ <style>+ #to-desktop{position:fixed;left:16px;bottom:16px;z-index:60;display:inline-flex;align-items:center;gap:8px;height:38px;padding:0 16px;border-radius:19px;font:500 13px/1 Inter,system-ui,sans-serif;color:#fff;text-decoration:none;background:linear-gradient(90deg,#ad6eca,#3b91d8);box-shadow:0 6px 24px rgba(0,0,0,.35);transition:transform .15s,filter .15s}+ #to-desktop:hover{filter:brightness(1.1);transform:translateY(-1px)}+ #to-desktop:active{transform:scale(.97)}+ #to-desktop:focus-visible{outline:2px solid #fff;outline-offset:3px}+ </style></body></html>diff --git a/public/nav.js b/public/nav.jsindex 84827dbb2..1ff899f7c 100644--- a/public/nav.js+++ b/public/nav.js@@ -276,7 +276,30 @@ function loadAgentBusDebug() {document.head.appendChild(s);}+// A page framed by the desktop shell (src/desktop/wm.js names its iframe+// "tws-os:<app>") drops the site header, footer and floating widgets: the+// desktop's own taskbar is the navigation, and a second header would eat the+// window. Theme still follows the site setting.+function inDesktopWindow() {+ try {+ return window.name.startsWith('tws-os:') && window.parent !== window;+ } catch {+ return false;+ }+}++function bootInDesktopWindow() {+ document.documentElement.classList.add('tws-in-os');+ const style = document.createElement('style');+ style.textContent =+ '.tws-in-os #nav-container,.tws-in-os header:has(>#nav-container),.tws-in-os #footer-container,' ++ '.tws-in-os .h-footer,.tws-in-os #to-desktop,.tws-in-os .skip-link{display:none!important}';+ document.head.appendChild(style);+ loadThemeSwitcher();+}+function boot() {+ if (inDesktopWindow()) return bootInDesktopWindow();ensureSkipLink();loadCornerStack();loadGlossary();diff --git a/scripts/audit-links.mjs b/scripts/audit-links.mjsindex d3bf68e4d..2d83b0857 100644--- a/scripts/audit-links.mjs+++ b/scripts/audit-links.mjs@@ -131,7 +131,7 @@ const GENERATED_DESTS = new Set(['/news/index.html']);// Does a clean path resolve to a real source file (what the catch-all serves)?function fileForCleanPath(path) {const p = path.replace(/^\/+/, '').replace(/\/+$/, '');- if (p === '') return 'pages/home.html'; // root served from a real homepage+ if (p === '') return 'pages/desktop.html'; // root is the web desktop; /classic keeps the old homepage// /src/** and /node_modules/** are served straight from the repo by vite in dev// and rewritten to hashed assets at build time — resolve against the real tree.if (p.startsWith('src/') || p.startsWith('node_modules/')) {diff --git a/scripts/check-dist.mjs b/scripts/check-dist.mjsindex c087f1954..6c05bf293 100644--- a/scripts/check-dist.mjs+++ b/scripts/check-dist.mjs@@ -128,11 +128,11 @@ for (const { rel, min } of distLibChecks) {const criticalStaticPages = ['/', '/dashboard', '/pump-dashboard', '/dashboard-next', '/create', '/discover', '/chat'];function resolvesToFile(pagePath) {- // vercel.json rewrites "/" -> "/home.html" (server/index.mjs's phase1Routes,+ // vercel.json rewrites "/" -> "/desktop.html" (server/index.mjs's phase1Routes,// exact literal src, no /? suffix) rather than serving dist/index.html.const candidates =pagePath === '/'- ? ['home.html']+ ? ['desktop.html']: [pagePath, `${pagePath}/index.html`, `${pagePath}.html`];for (const rel of candidates) {const abs = resolve(root, 'dist', rel.replace(/^\//, ''));diff --git a/scripts/desktop-interact.mjs b/scripts/desktop-interact.mjsnew file mode 100644index 000000000..e2ec4d480--- /dev/null+++ b/scripts/desktop-interact.mjs@@ -0,0 +1,104 @@+// Drives the desktop's real-computer behaviour: marquee selection, icon drag,+// settings, and session persistence across a reload.+// Usage: node scripts/desktop-interact.mjs [baseUrl] [screenshotDir]+import { chromium } from 'playwright';++const base = process.argv[2] || 'http://localhost:3000';+const shots = process.argv[3] || '';+const browser = await chromium.launch();+const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });+const page = await ctx.newPage();+const problems = [];+const fails = [];+page.on('console', (m) => m.type() === 'error' && problems.push(`console: ${m.text()}`));+page.on('pageerror', (e) => problems.push(`pageerror: ${e.message}`));+const shot = (n) => shots && page.screenshot({ path: `${shots}/${n}.png` });+const check = (name, ok, extra = '') => {+ console.log(`${ok ? 'PASS' : 'FAIL'} ${name} ${extra}`);+ if (!ok) fails.push(name);+};+const selected = () => page.locator('.os-icon.is-sel').count();++await page.goto(`${base}/?view=desktop`, { waitUntil: 'networkidle' });+await page.waitForSelector('.os-icon');+await page.evaluate(() => localStorage.setItem('tws:welcomed', '1'));+await page.reload({ waitUntil: 'networkidle' });+await page.waitForSelector('.os-icon');+const total = await page.locator('.os-icon').count();+check('every app on the desktop', total >= 14, `(${total})`);++// context menu on the empty desktop, then clear the board+await page.mouse.click(1300, 780, { button: 'right' });+await page.waitForSelector('.ctx');+check('desktop context menu has view options', (await page.locator('.ctx button').count()) >= 8);+await page.click('.ctx button:has-text("Close all windows")');+await page.waitForTimeout(500);+check('windows closed', (await page.locator('.win').count()) === 0);++// marquee+await page.mouse.move(700, 500);+await page.mouse.down();+await page.mouse.move(500, 300, { steps: 4 });+await page.mouse.move(8, 8, { steps: 6 });+await shot('i1-marquee');+check('marquee visible while dragging', await page.locator('.os-marquee:not([hidden])').count() === 1);+await page.mouse.up();+const sel = await selected();+check('marquee selected icons', sel > 0, `(${sel})`);+await page.mouse.click(1000, 600);+check('click empty desktop clears selection', (await selected()) === 0);++// drag one icon+const first = page.locator('.os-icon').first();+const before = await first.boundingBox();+await page.mouse.move(before.x + 30, before.y + 30);+await page.mouse.down();+await page.mouse.move(before.x + 300, before.y + 200, { steps: 8 });+await page.mouse.up();+const after = await first.boundingBox();+check('icon dragged to a new cell', Math.abs(after.x - before.x) > 150, `(${Math.round(after.x - before.x)}px)`);+const saved = await page.evaluate(() => localStorage.getItem('tws:icons'));+check('icon layout persisted', !!saved && saved.includes('"col"'));++// settings+await page.click('.os-tb.start');+await page.click('.sm-user');+await page.waitForSelector('.win[data-app=settings] .set-pane');+await page.fill('.win[data-app=settings] input.os-field', 'Ada Lovelace');+await page.click('.win[data-app=settings] .set-nav [data-section=personalize]');+await page.click('.win[data-app=settings] .swatch:nth-child(3)');+await page.click('.win[data-app=settings] [data-wall=ember]');+await page.click('.win[data-app=settings] .set-nav [data-section=desktop]');+await page.click('.win[data-app=settings] .seg button:has-text("Large")');+await shot('i2-settings');+const p = await page.evaluate(() => JSON.parse(localStorage.getItem('tws:prefs')));+check('prefs saved', p.name === 'Ada Lovelace' && p.wall === 'ember' && p.iconSize === 'large' && p.accent === '#e5484d', JSON.stringify(p));++// reload restores the whole session+await page.reload({ waitUntil: 'networkidle' });+await page.waitForSelector('.os-icon');+check('settings window restored', await page.locator('.win[data-app=settings]').count() === 1);+check('wallpaper restored', (await page.getAttribute('.os', 'data-wall')) === 'ember');+check('accent restored', (await page.evaluate(() => document.querySelector('.os').style.getPropertyValue('--accent'))) === '#e5484d');+const again = await page.locator('.os-icon').first().boundingBox();+check('large icons restored', again.width > 100, `(${Math.round(again.width)}px)`);+await page.click('.os-tb.start');+check('profile name on Start', (await page.textContent('.sm-user span')) === 'Ada Lovelace');+await shot('i3-restored');++// export+await page.keyboard.press('Escape');+await page.click('.win[data-app=settings] .set-nav [data-section=session]');+const [dl] = await Promise.all([page.waitForEvent('download'), page.click('.win[data-app=settings] button:has-text("Export")')]);+check('session export downloads', /three-ws-desktop-.*\.json$/.test(dl.suggestedFilename()));++// All Apps pin/unpin+await page.click('.os-tb.start');+await page.fill('.start-menu input', 'All Apps');+await page.click('.start-menu .sm-row:has-text("All Apps")');+await page.waitForSelector('.win[data-app=apps] .app-row');+check('all apps lists catalog', (await page.locator('.win[data-app=apps] .app-row').count()) > 14);++console.log('problems', problems.length ? problems : 'none');+await browser.close();+process.exit(fails.length || problems.length ? 1 : 0);diff --git a/scripts/desktop-smoke.mjs b/scripts/desktop-smoke.mjsnew file mode 100644index 000000000..a073a70f6--- /dev/null+++ b/scripts/desktop-smoke.mjs@@ -0,0 +1,53 @@+// Drives the web desktop in a real browser: boots it, opens the Start menu,+// launches apps, and reports console errors and failed requests.+// Usage: node scripts/desktop-smoke.mjs [baseUrl] [screenshotDir]+import { chromium } from 'playwright';++const base = process.argv[2] || 'http://localhost:3000';+const shots = process.argv[3] || '';+const browser = await chromium.launch();+const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });+const problems = [];+page.on('console', (m) => m.type() === 'error' && problems.push(`console: ${m.text()}`));+page.on('pageerror', (e) => problems.push(`pageerror: ${e.message}`));+page.on('requestfailed', (r) => !/ERR_ABORTED/.test(r.failure()?.errorText || '') && problems.push(`failed: ${r.url()}`));+const shot = (n) => shots && page.screenshot({ path: `${shots}/${n}.png` });++await page.goto(`${base}/?view=desktop`, { waitUntil: 'networkidle' });+await page.waitForSelector('.os-task');+await shot('1-boot');+console.log('icons', await page.locator('.os-icon').count(), 'welcome win', await page.locator('.win[data-app=welcome]').count());++await page.click('.os-tb.start');+await page.waitForSelector('.start-menu');+await page.fill('.start-menu input', 'forge');+await shot('2-start-search');+await page.keyboard.press('Enter');+await page.waitForSelector('.win[data-app=forge] iframe');+await page.waitForTimeout(3000);+console.log('forge title', await page.locator('.win[data-app=forge] .win-name').textContent());+console.log('nav hidden in frame', await page.frameLocator('.win[data-app=forge] iframe').locator('html.tws-in-os').count());+await shot('3-forge');++await page.dblclick('.os-icon:nth-child(3)').catch(() => {});+await page.click('.os-tb[aria-label^="Widgets"]');+await page.waitForSelector('.widgets');+await shot('4-widgets');+await page.keyboard.press('Escape');+await page.click('.os-clock');+await shot('5-calendar');+await page.keyboard.press('Escape');+await page.click('.win[data-app=forge] .win-maxbtn');+await shot('6-max');+await page.click('.win[data-app=forge] .win-min');+console.log('running buttons', await page.locator('.os-tb.run').count());++await page.reload({ waitUntil: 'networkidle' });+await page.waitForSelector('.os-task');+console.log('restored windows', await page.locator('.win').count());++await page.setViewportSize({ width: 390, height: 780 });+await page.waitForTimeout(400);+await shot('7-mobile');+console.log(problems.length ? `PROBLEMS:\n${problems.join('\n')}` : 'no console errors');+await browser.close();diff --git a/scripts/inject-seo-meta.mjs b/scripts/inject-seo-meta.mjsindex 02add4258..ca3b07fbc 100644--- a/scripts/inject-seo-meta.mjs+++ b/scripts/inject-seo-meta.mjs@@ -139,7 +139,7 @@ function resolveFile(p, router) {`pages/${flat}.html`,`public/${flat}.html`,];- if (p === '/') candidates.unshift('pages/home.html', 'public/index.html');+ if (p === '/') candidates.unshift('pages/desktop.html', 'public/index.html');for (const c of candidates) {const f = path.join(ROOT, c);if (existsSync(f)) return f;diff --git a/scripts/verify-routes.mjs b/scripts/verify-routes.mjsindex f886c8fdf..b9d907a02 100644--- a/scripts/verify-routes.mjs+++ b/scripts/verify-routes.mjs@@ -128,7 +128,7 @@ const API_ROOT = resolve(ROOT, 'api');// Does the filesystem serve `path`? (path is dist-relative, leading slash stripped)function fileServes(path) {const clean = path.replace(/^\//, '').split('?')[0];- if (clean === '') return served.has('home.html') || served.has('index.html');+ if (clean === '') return served.has('desktop.html') || served.has('index.html');if (served.has(clean)) return true;// NOTE: no bare-`.html` extension resolution here. This project pins routing// with a legacy `routes` array in vercel.json, which opts out of Vercel'sdiff --git a/src/desktop/README.md b/src/desktop/README.mdnew file mode 100644index 000000000..4c7fb99f5--- /dev/null+++ b/src/desktop/README.md@@ -0,0 +1,14 @@+# src/desktop++The web desktop served at `/` (page: `pages/desktop.html`). See+[docs/desktop.md](../../docs/desktop.md).++| File | Role |+| --- | --- |+| `main.js` | Entry: boot, restore session, deep links |+| `shell.js` | Taskbar, Start, widgets, calendar, menus, native apps |+| `wm.js` | Window manager (drag, resize, snap, focus, persistence hooks) |+| `layout.js` | Pure geometry, search ranking, state validation (unit tested) |+| `apps.js` | App registry and wallpapers |+| `icons.js` | Stroke glyphs |+| `theme.css`, `desktop.css` | CTRL tokens; shell and window styles |diff --git a/src/desktop/apps.js b/src/desktop/apps.jsnew file mode 100644index 000000000..87d80c962--- /dev/null+++ b/src/desktop/apps.js@@ -0,0 +1,206 @@+// The desktop's app registry. Every windowed app is a real three.ws surface+// served from the same origin and framed in a window; the two native apps+// (Settings, Welcome) are rendered by the shell itself. The long tail of+// destinations comes from public/nav-data.js at runtime (see catalog() in+// shell.js), so the launcher can never drift from the site's own navigation.++export const APPS = [+ {+ id: 'create',+ title: 'Create',+ href: '/create',+ hue: 262,+ icon: 'sparkle',+ size: { w: 1040, h: 700 },+ dock: true,+ desktop: true,+ desc: 'Make an agent, avatar, 3D model or token world',+ keywords: ['agent', 'avatar', 'new', 'build', 'selfie'],+ },+ {+ id: 'forge',+ title: 'Forge',+ href: '/forge',+ hue: 24,+ icon: 'cube',+ size: { w: 1080, h: 720 },+ dock: true,+ desktop: true,+ desc: 'Type a prompt, get a textured 3D model',+ keywords: ['text to 3d', 'model', 'glb', 'generate', 'mesh'],+ },+ {+ id: 'discover',+ title: 'Discover',+ href: '/discover',+ hue: 200,+ icon: 'compass',+ size: { w: 1100, h: 720 },+ dock: true,+ desktop: true,+ desc: 'Browse every registered agent on Solana and EVM',+ keywords: ['agents', 'directory', 'search', 'explore'],+ },+ {+ id: 'chat',+ title: 'Chat',+ href: '/chat',+ hue: 152,+ icon: 'chat',+ size: { w: 920, h: 700 },+ dock: true,+ desktop: true,+ desc: 'Talk to an agent',+ keywords: ['assistant', 'talk', 'ai', 'conversation'],+ },+ {+ id: 'marketplace',+ title: 'Marketplace',+ href: '/marketplace',+ hue: 44,+ icon: 'store',+ size: { w: 1100, h: 720 },+ dock: true,+ desktop: true,+ desc: 'Buy and sell agent skills',+ keywords: ['skills', 'buy', 'sell', 'x402', 'store'],+ },+ {+ id: 'studio',+ title: 'Agent Studio',+ href: '/agent-studio',+ hue: 292,+ icon: 'brain',+ size: { w: 1120, h: 740 },+ dock: true,+ desktop: true,+ desc: 'Author brains, skills and personality',+ keywords: ['persona', 'prompt', 'skills', 'author'],+ },+ {+ id: 'mine',+ title: 'My Creations',+ href: '/mine',+ hue: 330,+ icon: 'folder',+ size: { w: 980, h: 660 },+ dock: false,+ desktop: true,+ desc: 'Everything you have made, newest first',+ keywords: ['files', 'library', 'models', 'avatars'],+ },+ {+ id: 'gallery',+ title: 'Gallery',+ href: '/gallery',+ hue: 180,+ icon: 'image',+ size: { w: 1000, h: 680 },+ dock: false,+ desktop: true,+ desc: 'Every public 3D avatar',+ keywords: ['avatars', 'browse'],+ },+ {+ id: 'pulse',+ title: 'Pulse',+ href: '/pulse',+ hue: 340,+ icon: 'pulse',+ size: { w: 1000, h: 680 },+ dock: false,+ desktop: true,+ desc: 'Live feed of agent wallet activity',+ keywords: ['feed', 'wallet', 'activity', 'live', 'money'],+ },+ {+ id: 'trenches',+ title: 'Trenches',+ href: '/trenches',+ hue: 128,+ icon: 'radar',+ size: { w: 1120, h: 740 },+ dock: false,+ desktop: true,+ desc: 'Live Solana launches, runners and smart money',+ keywords: ['solana', 'pump', 'launches', 'tokens', 'wallets'],+ },+ {+ id: 'console',+ title: 'Console',+ href: '/dashboard',+ hue: 220,+ icon: 'terminal',+ size: { w: 1120, h: 740 },+ dock: true,+ desktop: true,+ desc: 'Your agents, wallets and usage',+ keywords: ['dashboard', 'account', 'keys', 'billing'],+ },+ {+ id: 'tour',+ title: 'Tour',+ href: '/tour',+ hue: 100,+ icon: 'play',+ size: { w: 960, h: 660 },+ dock: false,+ desktop: true,+ desc: 'A guided walk through the platform',+ keywords: ['help', 'learn', 'guide', 'tutorial'],+ },+];++export const NATIVE_APPS = [+ {+ id: 'settings',+ title: 'Settings',+ hue: 215,+ icon: 'gear',+ size: { w: 560, h: 560 },+ native: true,+ dock: true,+ desktop: true,+ desc: 'Your profile, personalization, and saved session',+ keywords: ['wallpaper', 'theme', 'preferences', 'classic', 'reset', 'profile', 'accent', 'export', 'storage', 'name'],+ },+ {+ id: 'apps',+ title: 'All Apps',+ hue: 200,+ icon: 'grid',+ size: { w: 720, h: 600 },+ native: true,+ dock: false,+ desktop: true,+ desc: 'Every three.ws app and page, with shortcuts for your desktop',+ keywords: ['files', 'explorer', 'pin', 'shortcut', 'launcher', 'catalog'],+ },+ {+ id: 'welcome',+ title: 'Welcome',+ hue: 262,+ icon: 'logo',+ size: { w: 640, h: 520 },+ native: true,+ dock: false,+ desktop: false,+ desc: 'What three.ws is and where to start',+ keywords: ['about', 'intro', 'start'],+ },+];++export const ALL_APPS = [...APPS, ...NATIVE_APPS];++export function appById(id) {+ return ALL_APPS.find((a) => a.id === id) || null;+}++export const WALLPAPERS = [+ { id: 'aurora', label: 'Aurora' },+ { id: 'midnight', label: 'Midnight' },+ { id: 'solana', label: 'Solana' },+ { id: 'ember', label: 'Ember' },+ { id: 'graphite', label: 'Graphite' },+];+export const CUSTOM_WALL = 'custom';diff --git a/src/desktop/desktop.css b/src/desktop/desktop.cssnew file mode 100644index 000000000..77ad186e9--- /dev/null+++ b/src/desktop/desktop.css@@ -0,0 +1,1350 @@+/* three.ws Desktop: Windows-style shell (taskbar, Start, widgets, Mica windows).+ * Tokens come from theme.css. Everything is scoped under .os. */++html,+body {+ margin: 0;+ height: 100%;+ overflow: hidden;+ background: #000;+}++.os {+ --task-h: 48px;+ --accent: var(--theme-2);+ --accent-2: var(--theme-1);+ position: fixed;+ inset: 0;+ overflow: hidden;+ color: var(--text);+ font: 14px/1.4 'Inter', system-ui, -apple-system, 'Segoe UI', sans-serif;+ -webkit-font-smoothing: antialiased;+ user-select: none;+ -webkit-user-select: none;+}+.os *,+.os *::before,+.os *::after {+ box-sizing: border-box;+}+.os :where(button) {+ font: inherit;+ color: inherit;+ background: none;+ border: 0;+ padding: 0;+ cursor: pointer;+}+.os .ico {+ display: block;+ flex: none;+}+.os :focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}+.os [hidden] {+ display: none !important;+}+.os-sr {+ position: absolute;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+}++/* ---------- Wallpapers ---------- */+.os-wall {+ position: absolute;+ inset: 0;+ background-size: cover;+ transition: background 0.6s;+}+.os[data-wall='aurora'] .os-wall {+ background: radial-gradient(60% 55% at 22% 18%, #7a3fa8aa, transparent 70%),+ radial-gradient(55% 60% at 82% 78%, #1f6fbfaa, transparent 70%), var(--mica);+}+.os[data-wall='midnight'] .os-wall {+ background: radial-gradient(70% 60% at 50% 0%, #1d2b5a, transparent 70%), #05060d;+}+.os[data-wall='solana'] .os-wall {+ background: radial-gradient(55% 55% at 15% 85%, #14f19577, transparent 70%),+ radial-gradient(55% 55% at 85% 15%, #9945ff88, transparent 70%), #0b0616;+}+.os[data-wall='ember'] .os-wall {+ background: radial-gradient(60% 60% at 80% 100%, #ff6a2c88, transparent 70%),+ radial-gradient(50% 50% at 10% 10%, #7a1f4a88, transparent 70%), #160a0d;+}+.os[data-wall='graphite'] .os-wall {+ background: linear-gradient(160deg, #2a2d33, #0d0e11);+}+[data-theme='light'] .os[data-wall='midnight'] .os-wall {+ background: radial-gradient(70% 60% at 50% 0%, #b8c8ff, transparent 70%), #e8ecfa;+}+[data-theme='light'] .os[data-wall='graphite'] .os-wall {+ background: linear-gradient(160deg, #e2e5ea, #b9bec7);+}++/* ---------- Desktop icons ---------- */+.os-icons {+ position: absolute;+ top: 12px;+ left: 12px;+ bottom: calc(var(--task-h) + 12px);+ display: grid;+ grid-auto-flow: column;+ grid-template-rows: repeat(auto-fill, 92px);+ grid-auto-columns: 88px;+ gap: 4px;+ align-content: start;+}+.os-icon {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 6px;+ padding: 8px 4px;+ border-radius: var(--siz-radius2);+ text-align: center;+ font-size: 12px;+ color: #fff;+ text-shadow: 0 1px 3px #000a;+ transition: background 0.15s;+}+.os-icon:hover {+ background: #ffffff1c;+}+.os-icon:active,+.os-icon:focus-visible {+ background: #ffffff30;+}+.os-icon .os-label {+ max-width: 80px;+ overflow: hidden;+ text-overflow: ellipsis;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+}+.app-tile {+ display: grid;+ place-items: center;+ width: 44px;+ height: 44px;+ border-radius: 12px;+ color: #fff;+ background: linear-gradient(145deg, hsl(var(--hue) 70% 58%), hsl(calc(var(--hue) + 38) 70% 38%));+ box-shadow: 0 4px 12px #0005, inset 0 1px 0 #fff4;+}+.app-tile.sm {+ width: 32px;+ height: 32px;+ border-radius: 9px;+}+.app-tile.xs {+ width: 26px;+ height: 26px;+ border-radius: 8px;+}++/* ---------- Window layer ---------- */+.os-layer {+ position: absolute;+ inset: 0 0 var(--task-h) 0;+ pointer-events: none;+}+.os-layer > * {+ pointer-events: auto;+}+.os-layer.is-dragging .win-frame {+ pointer-events: none;+}+.win {+ position: absolute;+ display: flex;+ flex-direction: column;+ min-width: 0;+ border-radius: 10px;+ overflow: hidden;+ background: var(--unfoc);+ border: 1px solid var(--hr);+ box-shadow: var(--shadow-md);+ transition: box-shadow 0.2s, opacity 0.2s, transform 0.2s;+}+.win.is-focused {+ box-shadow: var(--shadow-focus);+ border-color: var(--glass-border-col);+}+.win.is-moving,+.win.is-moving * {+ transition: none;+}+.win.is-max {+ border-radius: 0;+ border-width: 0;+}+.win.is-opening {+ animation: win-in 0.22s var(--ease-decel);+}+.win.is-closing {+ animation: win-out 0.18s ease-in forwards;+ pointer-events: none;+}+.win.is-min {+ display: none;+}+@keyframes win-in {+ from {+ opacity: 0;+ transform: scale(0.94) translateY(10px);+ }+}+@keyframes win-out {+ to {+ opacity: 0;+ transform: scale(0.95);+ }+}+.win-bar {+ display: flex;+ align-items: center;+ height: 38px;+ flex: none;+ background: var(--unfoc);+ border-bottom: 1px solid var(--hr);+ cursor: default;+ touch-action: none;+}+.win.is-focused .win-bar {+ background: var(--mica);+}+.win.is-focused .win-bar::before {+ content: '';+ position: absolute;+ inset: 0 0 auto 0;+ height: 38px;+ background: var(--material-base);+ backdrop-filter: var(--blur-light);+ pointer-events: none;+}+.win-bar > * {+ position: relative;+}+.win-title {+ display: flex;+ align-items: center;+ gap: 8px;+ padding-left: 12px;+ min-width: 0;+ flex: 1;+ font-size: 13px;+}+.win-name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.win-glyph {+ display: grid;+ place-items: center;+ color: hsl(var(--hue) 80% 70%);+}+.win-tools {+ display: flex;+ gap: 2px;+ padding-right: 6px;+}+.win-tool,+.win-btn {+ display: grid;+ place-items: center;+ color: var(--text);+ opacity: 0.8;+ transition: background 0.12s, opacity 0.12s;+}+.win-tool {+ width: 28px;+ height: 28px;+ border-radius: var(--siz-radius2);+}+.win-ctl {+ display: flex;+ align-self: stretch;+}+.win-btn {+ width: 46px;+}+.win-tool:hover,+.win-btn:hover {+ background: var(--hover-b);+ opacity: 1;+}+.win-tool:active,+.win-btn:active {+ background: var(--fill);+}+.win-btn.win-close:hover {+ background: #c42b1c;+ color: #fff;+}+.win-btn.win-close:active {+ background: #b22a1d;+}+.win-body {+ position: relative;+ flex: 1;+ min-height: 0;+ background: var(--bg);+}+.win-frame {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ border: 0;+ background: var(--bg);+ color-scheme: normal;+}+.win-loading {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 14px;+ background: var(--bg);+ color: var(--text2);+ pointer-events: none;+}+.win-loading-bar {+ width: 160px;+ height: 3px;+ border-radius: 2px;+ background: var(--hr);+ overflow: hidden;+ position: relative;+}+.win-loading-bar::after {+ content: '';+ position: absolute;+ inset: 0;+ width: 40%;+ border-radius: 2px;+ background: linear-gradient(90deg, var(--theme-1), var(--theme-2));+ animation: win-slide 1.1s var(--ease-decel) infinite;+}+@keyframes win-slide {+ from {+ transform: translateX(-100%);+ }+ to {+ transform: translateX(260%);+ }+}+.win-grip {+ position: absolute;+ z-index: 3;+}+.win.is-max .win-grip {+ display: none;+}+.win-grip-n,+.win-grip-s {+ left: 8px;+ right: 8px;+ height: 6px;+ cursor: ns-resize;+}+.win-grip-n {+ top: -3px;+}+.win-grip-s {+ bottom: -3px;+}+.win-grip-e,+.win-grip-w {+ top: 8px;+ bottom: 8px;+ width: 6px;+ cursor: ew-resize;+}+.win-grip-e {+ right: -3px;+}+.win-grip-w {+ left: -3px;+}+.win-grip-ne,+.win-grip-nw,+.win-grip-se,+.win-grip-sw {+ width: 14px;+ height: 14px;+}+.win-grip-ne {+ top: -3px;+ right: -3px;+ cursor: nesw-resize;+}+.win-grip-sw {+ bottom: -3px;+ left: -3px;+ cursor: nesw-resize;+}+.win-grip-nw {+ top: -3px;+ left: -3px;+ cursor: nwse-resize;+}+.win-grip-se {+ bottom: -3px;+ right: -3px;+ cursor: nwse-resize;+}+.win-snap {+ position: absolute;+ border-radius: 10px;+ background: #ffffff1c;+ border: 1px solid #ffffff55;+ backdrop-filter: var(--blur-light);+ pointer-events: none;+ z-index: 9999;+ transition: all 0.12s;+}++/* ---------- Taskbar ---------- */+.os-task {+ position: absolute;+ left: 0;+ right: 0;+ bottom: 0;+ height: var(--task-h);+ display: grid;+ grid-template-columns: 1fr auto 1fr;+ align-items: center;+ padding: 0 8px;+ background: var(--bg70);+ backdrop-filter: var(--blur-medium);+ border-top: 1px solid var(--hr);+ z-index: 10000;+}+.os-task-left {+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+}+.os-task-mid {+ display: flex;+ align-items: center;+ gap: 4px;+ max-width: 100%;+}+.os-task-right {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: 2px;+ min-width: 0;+}+.os-tb {+ position: relative;+ display: grid;+ place-items: center;+ width: 42px;+ height: 40px;+ border-radius: var(--siz-radius2);+ transition: background 0.12s, transform 0.12s;+}+.os-tb:hover {+ background: var(--hover-b);+}+.os-tb:active {+ background: var(--fill);+ transform: scale(0.94);+}+.os-tb[aria-pressed='true'],+.os-tb[aria-expanded='true'] {+ background: var(--hover-b);+}+.os-tb.start {+ color: var(--theme-2);+}+.os-tb.start .ico {+ filter: drop-shadow(0 0 6px var(--theme-1));+}+.os-tb.run::after {+ content: '';+ position: absolute;+ bottom: 2px;+ left: 50%;+ width: 6px;+ height: 3px;+ margin-left: -3px;+ border-radius: 2px;+ background: var(--text2);+ transition: width 0.2s, margin 0.2s, background 0.2s;+}+.os-tb.run.on::after {+ width: 16px;+ margin-left: -8px;+ background: var(--accent);+}+.os-tb.run.on {+ background: var(--hover-half);+}+.os-tray {+ display: flex;+ align-items: center;+ gap: 2px;+}+.os-clock {+ display: flex;+ flex-direction: column;+ align-items: flex-end;+ justify-content: center;+ height: 40px;+ padding: 0 10px;+ border-radius: var(--siz-radius2);+ font-size: 12px;+ line-height: 1.25;+}+.os-clock:hover {+ background: var(--hover-b);+}+.os-chip {+ color: inherit;+ text-decoration: none;+ display: flex;+ align-items: center;+ gap: 6px;+ height: 40px;+ padding: 0 10px;+ border-radius: var(--siz-radius2);+ font-size: 12px;+ max-width: 150px;+}+.os-chip:hover {+ background: var(--hover-b);+}+.os-chip span {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++/* ---------- Popovers (Start, widgets, calendar, context menu) ---------- */+.os-pop {+ position: absolute;+ z-index: 10001;+ background: var(--cm);+ backdrop-filter: var(--blur-heavy);+ border: 1px solid var(--hr);+ border-radius: 12px;+ box-shadow: var(--shadow-lg);+ transform-origin: bottom center;+ animation: pop-in 0.2s var(--ease-decel);+}+@keyframes pop-in {+ from {+ opacity: 0;+ transform: translateY(14px) scale(0.98);+ }+}+.start-menu {+ left: 50%;+ bottom: calc(var(--task-h) + 10px);+ width: min(640px, calc(100vw - 16px));+ margin-left: calc(min(640px, 100vw - 16px) / -2);+ max-height: calc(100vh - var(--task-h) - 24px);+ display: flex;+ flex-direction: column;+ padding: 18px 20px 0;+ overflow: hidden;+}+.sm-search {+ display: flex;+ align-items: center;+ gap: 10px;+ height: 40px;+ padding: 0 14px;+ border-radius: 20px;+ background: var(--bg30);+ border: 1px solid var(--hr);+ color: var(--text2);+}+.sm-search:focus-within {+ border-color: var(--accent);+}+.sm-search input {+ flex: 1;+ min-width: 0;+ background: none;+ border: 0;+ outline: 0;+ color: var(--text);+ font: inherit;+ user-select: text;+}+.sm-body {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ margin: 14px -8px 0;+ padding: 0 8px 12px;+ scrollbar-width: thin;+}+.sm-h {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin: 6px 4px 8px;+ font-size: 13px;+ font-weight: 600;+}+.sm-h button {+ font-weight: 400;+ font-size: 12px;+ padding: 3px 10px;+ border-radius: var(--siz-radius2);+ background: var(--hover-half);+}+.sm-h button:hover {+ background: var(--hover-b);+}+.sm-grid {+ display: grid;+ grid-template-columns: repeat(6, 1fr);+ gap: 2px;+ margin-bottom: 14px;+}+.sm-app {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 6px;+ padding: 10px 2px;+ border-radius: var(--siz-radius2);+ font-size: 12px;+ text-align: center;+}+.sm-app:hover,+.sm-row:hover,+.sm-app.is-sel,+.sm-row.is-sel {+ background: var(--hover-b);+}+.sm-app:active,+.sm-row:active {+ background: var(--fill);+}+.sm-app span {+ max-width: 84px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.sm-list {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 2px;+ margin-bottom: 14px;+}+.sm-list.one {+ grid-template-columns: 1fr;+}+.sm-row {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 7px 8px;+ border-radius: var(--siz-radius2);+ text-align: left;+ min-width: 0;+}+.sm-row div {+ min-width: 0;+}+.sm-row b {+ display: block;+ font-weight: 500;+ font-size: 13px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.sm-row small {+ display: block;+ color: var(--text2);+ font-size: 11px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.sm-empty {+ padding: 28px 8px;+ text-align: center;+ color: var(--text2);+}+.sm-foot {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin: 0 -20px;+ padding: 10px 20px;+ background: var(--bg30);+ border-top: 1px solid var(--hr);+}+.sm-user {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 6px 10px;+ border-radius: var(--siz-radius2);+ font-size: 13px;+}+.sm-user:hover,+.sm-pwr:hover {+ background: var(--hover-b);+}+.sm-pwr {+ display: grid;+ place-items: center;+ width: 38px;+ height: 34px;+ border-radius: var(--siz-radius2);+}++.widgets {+ left: 8px;+ bottom: calc(var(--task-h) + 10px);+ width: min(420px, calc(100vw - 16px));+ max-height: calc(100vh - var(--task-h) - 24px);+ overflow-y: auto;+ padding: 14px;+ display: flex;+ flex-direction: column;+ gap: 12px;+ transform-origin: bottom left;+ scrollbar-width: thin;+}+.wg-card {+ border-radius: 10px;+ background: var(--card);+ border: 1px solid var(--hr);+ padding: 14px;+}+.wg-card h3 {+ margin: 0 0 4px;+ font-size: 13px;+ font-weight: 600;+}+.wg-card p {+ margin: 0;+ color: var(--text2);+ font-size: 12.5px;+}+.wg-agent {+ display: grid;+ grid-template-columns: 130px 1fr;+ gap: 12px;+ align-items: center;+}+.wg-agent agent-3d {+ width: 130px;+ height: 170px;+ display: block;+ border-radius: 8px;+ overflow: hidden;+ background: var(--bg30);+}+.wg-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ margin-top: 10px;+}+.os-btn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 32px;+ padding: 0 14px;+ border-radius: var(--siz-radius2);+ background: var(--hover-b);+ border: 1px solid var(--hr);+ font-size: 13px;+ transition: background 0.12s, transform 0.12s;+}+.os-btn:hover {+ background: var(--fill);+}+.os-btn:active {+ transform: scale(0.97);+}+.os-btn.primary {+ color: #fff;+ border-color: transparent;+ background: linear-gradient(90deg, var(--theme-1), var(--theme-2));+}+.os-btn.primary:hover {+ filter: brightness(1.1);+}+.wg-quick {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 6px;+}+.wg-quick button {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 6px;+ padding: 10px 4px;+ border-radius: var(--siz-radius2);+ font-size: 12px;+}+.wg-quick button:hover {+ background: var(--hover-b);+}++.calendar {+ right: 8px;+ bottom: calc(var(--task-h) + 10px);+ width: 300px;+ padding: 14px;+ transform-origin: bottom right;+}+.cal-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-bottom: 8px;+ font-weight: 600;+}+.cal-head button {+ display: grid;+ place-items: center;+ width: 28px;+ height: 28px;+ border-radius: var(--siz-radius2);+}+.cal-head button:hover {+ background: var(--hover-b);+}+.cal-grid {+ display: grid;+ grid-template-columns: repeat(7, 1fr);+ gap: 2px;+ text-align: center;+ font-size: 12px;+}+.cal-grid i {+ font-style: normal;+ color: var(--text2);+ padding: 4px 0;+}+.cal-grid b {+ font-weight: 400;+ padding: 6px 0;+ border-radius: 50%;+}+.cal-grid b.mute {+ color: var(--text2);+ opacity: 0.5;+}+.cal-grid b.today {+ background: var(--accent);+ color: #fff;+ font-weight: 600;+}++.ctx {+ min-width: 200px;+ padding: 5px;+ transform-origin: top left;+ animation-name: ctx-in;+}+@keyframes ctx-in {+ from {+ opacity: 0;+ transform: scale(0.96);+ }+}+.ctx button {+ display: flex;+ align-items: center;+ gap: 10px;+ width: 100%;+ padding: 7px 10px;+ border-radius: var(--siz-radius3);+ text-align: left;+ font-size: 13px;+}+.ctx button:hover,+.ctx button:focus-visible {+ background: var(--hover-b);+}+.ctx hr {+ border: 0;+ border-top: 1px solid var(--hr);+ margin: 4px 6px;+}++/* ---------- Toasts ---------- */+.os-toasts {+ position: absolute;+ right: 12px;+ bottom: calc(var(--task-h) + 12px);+ display: flex;+ flex-direction: column;+ gap: 8px;+ z-index: 10002;+ pointer-events: none;+}+.os-toast {+ max-width: 340px;+ padding: 10px 14px;+ border-radius: 10px;+ background: var(--cm);+ backdrop-filter: var(--blur-heavy);+ border: 1px solid var(--hr);+ box-shadow: var(--shadow-md);+ font-size: 13px;+ animation: pop-in 0.25s var(--ease-decel);+}++/* ---------- Native app bodies ---------- */+.native {+ height: 100%;+ overflow-y: auto;+ padding: 22px 24px;+ background: var(--bg);+ user-select: text;+}+.native h2 {+ margin: 0 0 6px;+ font-size: 22px;+ font-weight: 600;+}+.native h3 {+ margin: 20px 0 8px;+ font-size: 13px;+ font-weight: 600;+ color: var(--text2);+ text-transform: uppercase;+ letter-spacing: 0.04em;+}+.native p {+ margin: 0 0 10px;+ color: var(--text2);+}+.walls {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(96px, 1fr));+ gap: 10px;+}+.wall-opt {+ border-radius: 8px;+ border: 2px solid transparent;+ overflow: hidden;+ text-align: center;+ font-size: 12px;+ background: var(--card);+}+.wall-opt i {+ display: block;+ height: 56px;+}+.wall-opt:hover {+ border-color: var(--hr);+}+.wall-opt[aria-pressed='true'] {+ border-color: var(--accent);+}+.wall-opt span {+ display: block;+ padding: 5px 0;+}+.set-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 12px 14px;+ margin-bottom: 6px;+ border-radius: 8px;+ background: var(--card);+ border: 1px solid var(--hr);+}+.set-row b {+ display: block;+ font-weight: 500;+}+.set-row small {+ color: var(--text2);+}+.steps {+ display: grid;+ gap: 8px;+ margin: 14px 0;+}+.step {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 10px 12px;+ border-radius: 8px;+ background: var(--card);+ border: 1px solid var(--hr);+ text-align: left;+ width: 100%;+}+.step:hover {+ background: var(--hover-b);+}+.step b {+ display: block;+ font-weight: 600;+}+.step small {+ color: var(--text2);+}++/* ---------- Small screens ---------- */+@media (max-width: 720px) {+ .os-task {+ grid-template-columns: auto 1fr auto;+ }+ .os-task-mid {+ overflow-x: auto;+ scrollbar-width: none;+ }+ .os-tb.run {+ display: none;+ }+ .os-tb.run.on {+ display: grid;+ }+ .os-chip span,+ .os-tb.hide-sm {+ display: none;+ }+ .sm-grid {+ grid-template-columns: repeat(4, 1fr);+ }+ .sm-list {+ grid-template-columns: 1fr;+ }+ .win {+ border-radius: 0;+ border-width: 0;+ }+ .win-grip {+ display: none;+ }+ .os-icons {+ grid-auto-columns: 78px;+ }+}+@media (prefers-reduced-motion: reduce) {+ .os *,+ .os *::before,+ .os *::after {+ animation-duration: 0.01ms !important;+ transition-duration: 0.01ms !important;+ }+}++/* ---------- Desktop icon layer (grid, selection, marquee) ---------- */+.os-icons {+ inset: 0 0 var(--task-h) 0;+ top: 0;+ left: 0;+ bottom: auto;+ display: block;+ height: calc(100% - var(--task-h));+ --icon-w: 92px;+ --icon-h: 100px;+ --icon-tile: 44px;+}+.os-icons .os-icon {+ position: absolute;+ left: 0;+ top: 0;+ width: var(--icon-w);+ height: var(--icon-h);+ padding: 6px 4px;+ border: 1px solid transparent;+ touch-action: none;+ transition: background 0.12s, border-color 0.12s;+}+.os-icons .os-icon .app-tile {+ width: var(--icon-tile);+ height: var(--icon-tile);+ flex: none;+}+.os-icons .os-icon .os-label {+ max-width: calc(var(--icon-w) - 12px);+}+.os-icons .os-icon.is-sel {+ background: color-mix(in srgb, var(--accent) 38%, transparent);+ border-color: color-mix(in srgb, var(--accent) 80%, white);+}+.os-icons .os-icon.is-drag {+ z-index: 5;+ opacity: 0.8;+ transition: none;+ pointer-events: none;+}+.os-icons.is-moving {+ cursor: grabbing;+}+.os-marquee {+ position: absolute;+ z-index: 4;+ pointer-events: none;+ border: 1px solid color-mix(in srgb, var(--accent) 85%, white);+ background: color-mix(in srgb, var(--accent) 24%, transparent);+ border-radius: 2px;+}+.os-marquee[hidden] {+ display: none;+}+.os-wall[data-custom] {+ background-size: cover;+ background-position: center;+}++/* ---------- Settings app ---------- */+.native.settings {+ display: grid;+ grid-template-columns: 168px 1fr;+ padding: 0;+ overflow: hidden;+}+.set-nav {+ display: flex;+ flex-direction: column;+ gap: 2px;+ padding: 12px 8px;+ background: var(--card);+ border-right: 1px solid var(--hr);+ overflow-y: auto;+}+.set-nav button {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 8px 10px;+ border-radius: var(--siz-radius2);+ text-align: left;+ font-size: 13px;+}+.set-nav button:hover {+ background: var(--hover-b);+}+.set-nav button[aria-current='page'] {+ background: var(--hover-b);+ box-shadow: inset 3px 0 0 var(--accent);+}+.set-pane {+ overflow-y: auto;+ padding: 22px 24px;+}+.set-pane h3:first-of-type {+ margin-top: 4px;+}+.set-profile {+ display: flex;+ align-items: center;+ gap: 16px;+ margin-bottom: 14px;+}+.avatar {+ display: grid;+ place-items: center;+ flex: none;+ width: 64px;+ height: 64px;+ border-radius: 50%;+ font-size: 22px;+ font-weight: 600;+ color: #fff;+ background: linear-gradient(145deg, hsl(var(--hue) 70% 58%), hsl(calc(var(--hue) + 40) 70% 36%));+ box-shadow: var(--shadow-sm), inset 0 1px 0 #fff4;+}+.avatar.sm {+ width: 28px;+ height: 28px;+ font-size: 11px;+}+.os-field {+ width: 100%;+ padding: 8px 10px;+ border-radius: var(--siz-radius2);+ border: 1px solid var(--hr);+ background: var(--bg);+ color: var(--text);+ font: inherit;+ user-select: text;+}+.os-field:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 1px;+}+.os-range {+ width: 100%;+ accent-color: var(--accent);+}+.swatches,+.seg {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+}+.swatch {+ width: 30px;+ height: 30px;+ border-radius: 50%;+ border: 2px solid transparent;+ outline: 1px solid var(--hr);+ background: var(--c);+}+.swatch:hover {+ transform: scale(1.1);+}+.swatch[aria-pressed='true'] {+ border-color: var(--bg);+ outline: 2px solid var(--c);+}+.seg button {+ padding: 6px 14px;+ border-radius: var(--siz-radius2);+ border: 1px solid var(--hr);+ background: var(--card);+ font-size: 13px;+}+.seg button:hover {+ background: var(--hover-b);+}+.seg button[aria-pressed='true'] {+ background: var(--accent);+ border-color: var(--accent);+ color: #fff;+}+.set-switch {+ position: relative;+ width: 42px;+ height: 24px;+ border-radius: 12px;+ border: 1px solid var(--hr);+ background: var(--hover-b);+ flex: none;+}+.set-switch::after {+ content: '';+ position: absolute;+ top: 2px;+ left: 2px;+ width: 18px;+ height: 18px;+ border-radius: 50%;+ background: #fff;+ box-shadow: var(--shadow-sm);+ transition: transform 0.15s;+}+.set-switch[aria-checked='true'] {+ background: var(--accent);+ border-color: var(--accent);+}+.set-switch[aria-checked='true']::after {+ transform: translateX(18px);+}+.meter {+ height: 8px;+ border-radius: 4px;+ background: var(--hover-b);+ overflow: hidden;+ margin: 8px 0 4px;+}+.meter i {+ display: block;+ height: 100%;+ background: var(--accent);+}+.os-btn.danger {+ color: var(--col-bad);+}+.app-list {+ display: grid;+ gap: 4px;+}+.app-row {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 8px 10px;+ border-radius: var(--siz-radius2);+}+.app-row:hover {+ background: var(--hover-b);+}+.app-row > div {+ flex: 1;+ min-width: 0;+}+.app-row b,+.app-row small {+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.app-row small {+ color: var(--text2);+}+.apps-bar {+ display: flex;+ gap: 8px;+ margin-bottom: 12px;+}+.sm-user .avatar.sm {+ width: 24px;+ height: 24px;+ font-size: 10px;+}+.os-task.left {+ grid-template-columns: auto auto 1fr;+}+.os-task.left .os-task-mid {+ order: 1;+}+.os-task.left .os-task-left {+ order: 2;+}+.os-task.left .os-task-right {+ order: 3;+ justify-self: end;+}+@media (max-width: 720px) {+ .native.settings {+ grid-template-columns: 1fr;+ grid-template-rows: auto 1fr;+ }+ .set-nav {+ flex-direction: row;+ overflow-x: auto;+ border-right: 0;+ border-bottom: 1px solid var(--hr);+ }+ .set-nav button span {+ display: none;+ }+}+.os-btn {+ white-space: nowrap;+}diff --git a/src/desktop/icon-layer.js b/src/desktop/icon-layer.jsnew file mode 100644index 000000000..b9575461d--- /dev/null+++ b/src/desktop/icon-layer.js@@ -0,0 +1,344 @@+// Desktop icon layer: grid-snapped icons with click/Ctrl/Shift selection,+// rubber-band (marquee) selection on the empty desktop, group drag and drop,+// keyboard navigation and persisted placement. Geometry lives in layout.js.++import {+ ICON_SIZES,+ addIcons,+ arrangeIcons,+ cellAt,+ gridSize,+ iconsInRect,+ marqueeRect,+ moveIcons,+ reflowIcons,+ sanitizeIcons,+} from './layout.js';++const PAD = 8;+const DRAG_PX = 5;++export function createIconLayer({ host, resolve, isKnown, defaults, load, save, launch, menu, size }) {+ let items = [];+ let selected = new Set();+ let anchor = null;+ let grid = { cols: 1, rows: 1 };+ let cell = ICON_SIZES[size] || ICON_SIZES.medium;+ let tileFn = () => '';+ const els = new Map();++ const marquee = document.createElement('div');+ marquee.className = 'os-marquee';+ marquee.hidden = true;++ const area = () => ({ w: Math.max(0, host.clientWidth - PAD * 2), h: Math.max(0, host.clientHeight - PAD * 2) });+ const origin = { x: PAD, y: PAD };+ const local = (e) => {+ const r = host.getBoundingClientRect();+ return { x: e.clientX - r.left, y: e.clientY - r.top };+ };+ const persist = () => save(items.map(({ id, col, row }) => ({ id, col, row })));++ function measure() {+ cell = ICON_SIZES[size] || ICON_SIZES.medium;+ const a = area();+ grid = gridSize(a.w, a.h, cell);+ host.style.setProperty('--icon-w', `${cell.w}px`);+ host.style.setProperty('--icon-h', `${cell.h}px`);+ host.style.setProperty('--icon-tile', `${cell.tile}px`);+ }++ function place(el, it) {+ el.style.transform = `translate(${origin.x + it.col * cell.w}px, ${origin.y + it.row * cell.h}px)`;+ }++ function paintSelection() {+ els.forEach((el, id) => {+ const on = selected.has(id);+ el.classList.toggle('is-sel', on);+ el.setAttribute('aria-selected', String(on));+ });+ }++ function build(it) {+ const app = resolve(it.id);+ if (!app) return null;+ const b = document.createElement('button');+ b.type = 'button';+ b.className = 'os-icon';+ b.dataset.id = it.id;+ b.setAttribute('role', 'option');+ b.innerHTML = `${tileFn(app)}<span class="os-label"></span>`;+ b.querySelector('.os-label').textContent = app.title;+ b.title = app.desc || app.title;+ return b;+ }++ function render() {+ measure();+ const live = new Set(items.map((i) => i.id));+ els.forEach((el, id) => {+ if (!live.has(id)) {+ el.remove();+ els.delete(id);+ }+ });+ items.forEach((it) => {+ let el = els.get(it.id);+ if (!el) {+ el = build(it);+ if (!el) return;+ els.set(it.id, el);+ host.append(el);+ }+ place(el, it);+ });+ selected = new Set([...selected].filter((id) => els.has(id)));+ paintSelection();+ }++ function reseat() {+ measure();+ items = reflowIcons(items, grid);+ render();+ persist();+ }++ function select(ids, additive) {+ selected = additive ? new Set([...selected, ...ids]) : new Set(ids);+ paintSelection();+ }++ // ---------- pointer: icon click, group drag ----------+ host.addEventListener('pointerdown', (e) => {+ if (e.button !== 0) return;+ const el = e.target.closest('.os-icon');+ if (el) return iconDown(e, el);+ if (e.target !== host && e.target !== marquee) return;+ marqueeDown(e);+ });++ function iconDown(e, el) {+ const id = el.dataset.id;+ const toggle = e.ctrlKey || e.metaKey;+ if (e.shiftKey && anchor && els.has(anchor)) {+ const order = items.slice().sort((a, b) => a.col - b.col || a.row - b.row).map((i) => i.id);+ const [a, b] = [order.indexOf(anchor), order.indexOf(id)].sort((x, y) => x - y);+ select(order.slice(a, b + 1), false);+ } else if (toggle) {+ if (selected.has(id)) selected.delete(id);+ else selected.add(id);+ anchor = id;+ paintSelection();+ } else {+ if (!selected.has(id)) select([id], false);+ anchor = id;+ }+ el.focus({ preventScroll: true });+ if (toggle || e.shiftKey) return;+ const start = local(e);+ const startCell = cellAt(start.x, start.y, cell, grid, origin);+ let dragging = false;+ let ghost = [];+ const move = (ev) => {+ const p = local(ev);+ if (!dragging && Math.hypot(p.x - start.x, p.y - start.y) < DRAG_PX) return;+ if (!dragging) {+ dragging = true;+ ghost = [...selected].map((sid) => els.get(sid)).filter(Boolean);+ ghost.forEach((g) => g.classList.add('is-drag'));+ host.classList.add('is-moving');+ }+ const dx = p.x - start.x;+ const dy = p.y - start.y;+ ghost.forEach((g) => {+ const it = items.find((i) => i.id === g.dataset.id);+ g.style.transform = `translate(${origin.x + it.col * cell.w + dx}px, ${origin.y + it.row * cell.h + dy}px)`;+ });+ };+ const up = (ev) => {+ removeEventListener('pointermove', move);+ removeEventListener('pointerup', up);+ removeEventListener('pointercancel', up);+ if (!dragging) return;+ host.classList.remove('is-moving');+ ghost.forEach((g) => g.classList.remove('is-drag'));+ const p = local(ev);+ const to = cellAt(p.x, p.y, cell, grid, origin);+ items = moveIcons(items, [...selected], to.col - startCell.col, to.row - startCell.row, grid);+ render();+ persist();+ };+ addEventListener('pointermove', move);+ addEventListener('pointerup', up);+ addEventListener('pointercancel', up);+ }++ // ---------- pointer: rubber band ----------+ function marqueeDown(e) {+ const additive = e.ctrlKey || e.metaKey || e.shiftKey;+ const base = additive ? new Set(selected) : new Set();+ if (!additive) {+ selected = new Set();+ paintSelection();+ }+ const a = local(e);+ let active = false;+ if (!marquee.isConnected) host.append(marquee);+ const move = (ev) => {+ const p = local(ev);+ if (!active && Math.hypot(p.x - a.x, p.y - a.y) < 3) return;+ active = true;+ const r = marqueeRect(a.x, a.y, p.x, p.y);+ marquee.hidden = false;+ marquee.style.cssText = `left:${r.x}px;top:${r.y}px;width:${r.w}px;height:${r.h}px`;+ const hit = iconsInRect(r, items, cell, origin);+ selected = new Set([...base, ...hit]);+ paintSelection();+ };+ const up = () => {+ removeEventListener('pointermove', move);+ removeEventListener('pointerup', up);+ removeEventListener('pointercancel', up);+ marquee.hidden = true;+ if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur?.();+ };+ addEventListener('pointermove', move);+ addEventListener('pointerup', up);+ addEventListener('pointercancel', up);+ }++ // ---------- open, context menu, keyboard ----------+ const openIcon = (id) => launch(resolve(id));+ host.addEventListener('dblclick', (e) => {+ const el = e.target.closest('.os-icon');+ if (el) openIcon(el.dataset.id);+ });+ host.addEventListener('click', (e) => {+ const el = e.target.closest('.os-icon');+ if (!el) return;+ // Touch has no double-click: a single tap opens.+ if (matchMedia('(pointer: coarse)').matches || innerWidth <= 720) openIcon(el.dataset.id);+ });+ host.addEventListener('contextmenu', (e) => {+ const el = e.target.closest('.os-icon');+ if (!el) return;+ e.preventDefault();+ e.stopPropagation();+ const id = el.dataset.id;+ if (!selected.has(id)) select([id], false);+ const many = selected.size > 1;+ menu(e.clientX, e.clientY, [+ [many ? `Open ${selected.size} apps` : 'Open', 'external', () => [...selected].forEach(openIcon)],+ '-',+ [many ? 'Remove from desktop' : 'Remove from desktop', 'close', () => remove([...selected])],+ ]);+ });+ host.addEventListener('keydown', (e) => {+ const el = e.target.closest('.os-icon');+ if (!el) return;+ const id = el.dataset.id;+ if (e.key === 'Enter') {+ e.preventDefault();+ [...(selected.size ? selected : new Set([id]))].forEach(openIcon);+ } else if (e.key === 'Delete') {+ remove(selected.size ? [...selected] : [id]);+ } else if (e.key === ' ') {+ e.preventDefault();+ select([id], false);+ anchor = id;+ } else if (e.key.startsWith('Arrow')) {+ e.preventDefault();+ const cur = items.find((i) => i.id === id);+ const d = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[e.key];+ let best = null;+ let bestD = Infinity;+ for (const it of items) {+ if (it === cur) continue;+ const dc = it.col - cur.col;+ const dr = it.row - cur.row;+ if (dc * d[0] + dr * d[1] <= 0) continue;+ const dist = dc * dc + dr * dr;+ if (dist < bestD) {+ best = it;+ bestD = dist;+ }+ }+ if (!best) return;+ if (e.ctrlKey || e.metaKey) {+ // Ctrl+Arrow nudges the selection one cell.+ items = moveIcons(items, [...(selected.size ? selected : [id])], d[0], d[1], grid);+ render();+ persist();+ els.get(id)?.focus();+ return;+ }+ select([best.id], e.shiftKey);+ anchor = best.id;+ els.get(best.id)?.focus();+ } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'a') {+ e.preventDefault();+ select(items.map((i) => i.id), false);+ }+ });++ function remove(ids) {+ const gone = new Set(ids);+ items = items.filter((i) => !gone.has(i.id));+ selected = new Set([...selected].filter((i) => !gone.has(i)));+ render();+ persist();+ }++ return {+ /** Load persisted placement (or defaults on first run) and draw it. */+ init(tile) {+ tileFn = tile;+ measure();+ const saved = load();+ items = saved == null ? [] : sanitizeIcons(saved, isKnown);+ if (saved == null) items = addIcons(items, defaults(), grid);+ items = reflowIcons(items, grid);+ render();+ persist();+ },+ reseat,+ setSize(next) {+ if (!ICON_SIZES[next] || next === size) return;+ size = next;+ reseat();+ },+ arrange(ids) {+ const order = ids || items.slice().sort((a, b) => a.col - b.col || a.row - b.row).map((i) => i.id);+ items = arrangeIcons(order, grid).map((p) => ({ ...p }));+ render();+ persist();+ },+ sortByName() {+ const names = items.map((i) => [i.id, (resolve(i.id)?.title || i.id).toLowerCase()]);+ names.sort((a, b) => a[1].localeCompare(b[1]));+ this.arrange(names.map((n) => n[0]));+ },+ add(id) {+ if (items.some((i) => i.id === id) || !resolve(id)) return false;+ const next = addIcons(items, [id], grid);+ if (next.length === items.length) return false;+ items = next;+ render();+ persist();+ return true;+ },+ remove,+ has: (id) => items.some((i) => i.id === id),+ refresh() {+ render();+ },+ selectAll() {+ select(items.map((i) => i.id), false);+ },+ clearSelection() {+ select([], false);+ },+ ids: () => items.map((i) => i.id),+ };+}diff --git a/src/desktop/icons.js b/src/desktop/icons.jsnew file mode 100644index 000000000..baa6be557--- /dev/null+++ b/src/desktop/icons.js@@ -0,0 +1,44 @@+// Glyphs for dock, desktop and window chrome. 24px grid, stroke-based, no fills,+// so they inherit currentColor and stay crisp at every size.++const P = {+ logo: '<path d="M12 3 3.5 8v8L12 21l8.5-5V8z"/><path d="M12 3v18M3.5 8 12 13l8.5-5"/>',+ sparkle: '<path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5 18 18M18 6l-2.5 2.5M8.5 15.5 6 18"/>',+ cube: '<path d="M12 3 4 7.5v9L12 21l8-4.5v-9z"/><path d="M12 12 4 7.5M12 12l8-4.5M12 12v9"/>',+ compass: '<circle cx="12" cy="12" r="9"/><path d="m15.5 8.5-2 5-5 2 2-5z"/>',+ chat: '<path d="M4 5h16v11H9l-5 4z"/>',+ store: '<path d="M4 9 5.5 4h13L20 9M4 9v11h16V9M4 9c0 1.7 1.3 3 3 3s3-1.3 3-3c0 1.7 1.3 3 3 3s3-1.3 3-3c0 1.7 1.3 3 3 3"/>',+ brain: '<path d="M9 4a3 3 0 0 0-3 3v1a3 3 0 0 0-2 2.8A3 3 0 0 0 6 14v1a3 3 0 0 0 3 3h1V4zM15 4a3 3 0 0 1 3 3v1a3 3 0 0 1 2 2.8 3 3 0 0 1-2 3.2v1a3 3 0 0 1-3 3h-1V4z"/>',+ folder: '<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>',+ image: '<rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="9" cy="10" r="1.6"/><path d="m21 16-5-5-8 8"/>',+ pulse: '<path d="M3 12h4l2.5-7 5 14L17 12h4"/>',+ radar: '<circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="4.5"/><path d="M12 12 18 6"/>',+ terminal: '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="m7 9 3 3-3 3M13 15h4"/>',+ play: '<circle cx="12" cy="12" r="9"/><path d="m10 8.5 6 3.5-6 3.5z"/>',+ gear: '<circle cx="12" cy="12" r="3"/><path d="M12 3v2.5M12 18.5V21M3 12h2.5M18.5 12H21M5.6 5.6l1.8 1.8M16.6 16.6l1.8 1.8M18.4 5.6l-1.8 1.8M7.4 16.6l-1.8 1.8"/>',+ grid: '<rect x="4" y="4" width="6" height="6" rx="1.2"/><rect x="14" y="4" width="6" height="6" rx="1.2"/><rect x="4" y="14" width="6" height="6" rx="1.2"/><rect x="14" y="14" width="6" height="6" rx="1.2"/>',+ search: '<circle cx="11" cy="11" r="6.5"/><path d="m20 20-4.2-4.2"/>',+ sun: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4"/>',+ moon: '<path d="M20 14.5A8 8 0 1 1 9.5 4 6.5 6.5 0 0 0 20 14.5z"/>',+ external: '<path d="M14 4h6v6M20 4 10 14M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/>',+ reload: '<path d="M20 11a8 8 0 1 0-2.3 5.7M20 4v7h-7"/>',+ classic: '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 9h18"/>',+ desktop: '<rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8 20h8M12 16v4"/>',+ user: '<circle cx="12" cy="8" r="3.5"/><path d="M5 20c0-3.6 3.1-6 7-6s7 2.4 7 6"/>',+ minimize: '<path d="M5 12h14"/>',+ maximize: '<rect x="5" y="5" width="14" height="14" rx="1.5"/>',+ restore: '<rect x="4.5" y="8.5" width="11" height="11" rx="1.5"/><path d="M8.5 8.5V5.5a1 1 0 0 1 1-1h9a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1h-3"/>',+ widgets: '<rect x="3.5" y="3.5" width="7" height="7" rx="1.5"/><rect x="13.5" y="3.5" width="7" height="7" rx="1.5"/><rect x="3.5" y="13.5" width="7" height="7" rx="1.5"/><path d="M17 13.5v7M13.5 17h7"/>',+ power: '<path d="M12 3v8M6.3 6.8a8 8 0 1 0 11.4 0"/>',+ chevron: '<path d="m9 6 6 6-6 6"/>',+ close: '<path d="m6 6 12 12M18 6 6 18"/>',+};++export function icon(name, size = 20) {+ const body = P[name] || P.logo;+ return (+ `<svg class="ico" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" ` ++ `stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" ` ++ `aria-hidden="true" focusable="false">${body}</svg>`+ );+}diff --git a/src/desktop/layout.js b/src/desktop/layout.jsnew file mode 100644index 000000000..480afece7--- /dev/null+++ b/src/desktop/layout.js@@ -0,0 +1,402 @@+// Pure geometry, search and persistence helpers for the three.ws desktop shell.+// No DOM access here so every rule can be unit-tested (tests/desktop-layout.test.js).++export const MIN_W = 320;+export const MIN_H = 220;+export const SNAP_EDGE = 10;+export const MAX_WINDOWS = 8;+export const STATE_VERSION = 1;++/** The usable region for windows: below the menu bar, above the dock. */+export function workArea(vw, vh, menuH, dockH) {+ return { x: 0, y: menuH, w: vw, h: Math.max(MIN_H, vh - menuH - dockH) };+}++/** Keep a window reachable: its title bar must stay inside the work area. */+export function clampRect(rect, area) {+ const w = Math.min(Math.max(rect.w, MIN_W), area.w);+ const h = Math.min(Math.max(rect.h, MIN_H), area.h);+ const grab = 96;+ const x = Math.min(Math.max(rect.x, area.x - w + grab), area.x + area.w - grab);+ const y = Math.min(Math.max(rect.y, area.y), area.y + area.h - 36);+ return { x: Math.round(x), y: Math.round(y), w: Math.round(w), h: Math.round(h) };+}++/** Which snap zone, if any, the pointer is in while dragging a window. */+export function snapZone(px, py, area) {+ if (py <= area.y + SNAP_EDGE) return 'max';+ if (px <= area.x + SNAP_EDGE) return 'left';+ if (px >= area.x + area.w - SNAP_EDGE) return 'right';+ return null;+}++export function snapRect(zone, area) {+ if (zone === 'max') return { x: area.x, y: area.y, w: area.w, h: area.h };+ const half = Math.floor(area.w / 2);+ if (zone === 'left') return { x: area.x, y: area.y, w: half, h: area.h };+ if (zone === 'right') return { x: area.x + half, y: area.y, w: area.w - half, h: area.h };+ return null;+}++/** Staggered placement for the nth open window so new ones never sit exactly on top. */+export function cascadeRect(n, area, want) {+ const w = Math.min(want.w, area.w - 24);+ const h = Math.min(want.h, area.h - 24);+ const step = 28;+ const slots = Math.max(1, Math.floor(Math.min(area.w - w, area.h - h) / step));+ const k = n % slots;+ const x = area.x + Math.max(12, Math.floor((area.w - w) / 2) - Math.floor((slots * step) / 4)) + k * step;+ const y = area.y + 14 + k * step;+ return clampRect({ x, y, w, h }, area);+}++/** Apply a pointer delta to a rect for one of the eight resize handles. */+export function resizeRect(start, handle, dx, dy, area) {+ let { x, y, w, h } = start;+ if (handle.includes('e')) w = start.w + dx;+ if (handle.includes('s')) h = start.h + dy;+ if (handle.includes('w')) {+ w = start.w - dx;+ x = start.x + dx;+ }+ if (handle.includes('n')) {+ h = start.h - dy;+ y = start.y + dy;+ }+ if (w < MIN_W) {+ if (handle.includes('w')) x -= MIN_W - w;+ w = MIN_W;+ }+ if (h < MIN_H) {+ if (handle.includes('n')) y -= MIN_H - h;+ h = MIN_H;+ }+ if (y < area.y) {+ if (handle.includes('n')) h -= area.y - y;+ y = area.y;+ }+ return { x: Math.round(x), y: Math.round(y), w: Math.round(w), h: Math.round(h) };+}++/** A path is framable as a window only when it is a same-origin absolute path. */+export function isInternalPath(href) {+ return typeof href === 'string' && /^\/(?!\/)/.test(href) && !/[\u0000-\u001f\\]/.test(href);+}++/** Strip the site suffix pages put in <title> so a window title stays short. */+export function cleanTitle(raw, fallback) {+ const t = String(raw || '')+ .replace(/\s*[·|\u2013\u2014-]\s*three\.ws.*$/i, '')+ .replace(/^three\.ws\s*[·|\u2013\u2014-]\s*/i, '')+ .trim();+ return t || fallback;+}++/**+ * Rank launchable items for a query. Title prefix beats word prefix beats+ * keyword beats substring beats description. Empty query keeps input order.+ */+export function rankItems(query, items) {+ const q = String(query || '').trim().toLowerCase();+ if (!q) return items.slice();+ const scored = [];+ items.forEach((it, i) => {+ const title = String(it.title || '').toLowerCase();+ const kw = (it.keywords || []).map((k) => String(k).toLowerCase());+ const desc = String(it.desc || '').toLowerCase();+ let s = 0;+ if (title === q) s = 100;+ else if (title.startsWith(q)) s = 80;+ else if (title.split(/[\s/\-_.]+/).some((w) => w.startsWith(q))) s = 60;+ else if (kw.some((k) => k.startsWith(q))) s = 50;+ else if (title.includes(q)) s = 40;+ else if (kw.some((k) => k.includes(q))) s = 30;+ else if (desc.includes(q)) s = 10;+ if (s) scored.push({ it, s, i });+ });+ scored.sort((a, b) => b.s - a.s || a.i - b.i);+ return scored.map((r) => r.it);+}++/** `?app=forge` (or `#app=forge`) opens that app on load. */+export function deepLinkApp(search, hash) {+ const fromQuery = new URLSearchParams(search || '').get('app');+ if (fromQuery) return fromQuery.toLowerCase();+ const m = /^#app=([a-z0-9-]+)$/i.exec(hash || '');+ return m ? m[1].toLowerCase() : null;+}++const num = (v) => typeof v === 'number' && Number.isFinite(v);++/**+ * Validate persisted desktop state. Anything malformed, from an older version+ * or naming an unknown app is dropped, so a corrupt blob can never brick boot.+ */+export const PAGE_PREFIX = 'page:';++/** Any same-origin page can be launched as a window; its id carries its path. */+export function pageAppId(path) {+ return `${PAGE_PREFIX}${path}`;+}++export function pagePathOf(id) {+ if (typeof id !== 'string' || !id.startsWith(PAGE_PREFIX)) return null;+ const p = id.slice(PAGE_PREFIX.length);+ return isInternalPath(p) ? p : null;+}++export function sanitizeState(raw, knownIds) {+ const empty = { windows: [], focus: null };+ let data = raw;+ if (typeof raw === 'string') {+ try {+ data = JSON.parse(raw);+ } catch {+ return empty;+ }+ }+ if (!data || data.v !== STATE_VERSION || !Array.isArray(data.windows)) return empty;+ const seen = new Set();+ const windows = [];+ for (const w of data.windows) {+ if (!w || typeof w.app !== 'string' || !(knownIds.has(w.app) || pagePathOf(w.app)) || seen.has(w.app)) continue;+ if (![w.x, w.y, w.w, w.h].every(num)) continue;+ seen.add(w.app);+ windows.push({+ app: w.app,+ x: w.x,+ y: w.y,+ w: w.w,+ h: w.h,+ max: w.max === true,+ min: w.min === true,+ path: isInternalPath(w.path) ? w.path : null,+ });+ if (windows.length >= MAX_WINDOWS) break;+ }+ const focus = typeof data.focus === 'string' && seen.has(data.focus) ? data.focus : null;+ return { windows, focus };+}++// ---------------------------------------------------------------------------+// Desktop icon grid, rubber-band selection and preferences+// ---------------------------------------------------------------------------++export const ICON_SIZES = {+ small: { w: 76, h: 84, tile: 36 },+ medium: { w: 92, h: 100, tile: 44 },+ large: { w: 112, h: 120, tile: 56 },+};+export const ACCENTS = ['#3b91d8', '#ad6eca', '#e5484d', '#f08a24', '#2fb67c', '#d6409f'];+export const MODES = ['dark', 'light', 'auto'];+export const PREFS_VERSION = 1;+export const DEFAULT_PREFS = {+ wall: 'aurora',+ accent: ACCENTS[0],+ mode: 'dark',+ iconSize: 'medium',+ clock24: false,+ taskbarAlign: 'center',+ name: '',+ avatarHue: 262,+};++/** Normalise a rectangle given two corner points (any drag direction). */+export function marqueeRect(ax, ay, bx, by) {+ return { x: Math.min(ax, bx), y: Math.min(ay, by), w: Math.abs(ax - bx), h: Math.abs(ay - by) };+}++export function rectsIntersect(a, b) {+ return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;+}++/** Ids of every icon whose cell overlaps the marquee. */+export function iconsInRect(rect, items, cell, origin = { x: 0, y: 0 }) {+ return items+ .filter((it) =>+ rectsIntersect(rect, { x: origin.x + it.col * cell.w, y: origin.y + it.row * cell.h, w: cell.w, h: cell.h }),+ )+ .map((it) => it.id);+}++/** Grid dimensions that fit a desktop area (always at least 1x1). */+export function gridSize(areaW, areaH, cell) {+ return { cols: Math.max(1, Math.floor(areaW / cell.w)), rows: Math.max(1, Math.floor(areaH / cell.h)) };+}++export function cellAt(px, py, cell, grid, origin = { x: 0, y: 0 }) {+ const col = Math.min(grid.cols - 1, Math.max(0, Math.floor((px - origin.x) / cell.w)));+ const row = Math.min(grid.rows - 1, Math.max(0, Math.floor((py - origin.y) / cell.h)));+ return { col, row };+}++const key = (c, r) => `${c},${r}`;++/** The free cell closest to (col,row), scanning outward; null when the grid is full. */+export function nearestFreeCell(col, row, grid, taken) {+ let best = null;+ let bestD = Infinity;+ for (let c = 0; c < grid.cols; c++) {+ for (let r = 0; r < grid.rows; r++) {+ if (taken.has(key(c, r))) continue;+ const d = (c - col) ** 2 + (r - row) ** 2;+ if (d < bestD || (d === bestD && best && (c < best.col || (c === best.col && r < best.row)))) {+ best = { col: c, row: r };+ bestD = d;+ }+ }+ }+ return best;+}++/** Column-major auto arrange: top to bottom, then the next column (Windows order). */+export function arrangeIcons(ids, grid) {+ return ids.map((id, i) => ({ id, col: Math.floor(i / grid.rows), row: i % grid.rows }));+}++/**+ * Move the selected icons by a cell delta. Every icon lands on a free cell,+ * nearest to where it was dropped; icons that are not moving keep their cell.+ */+export function moveIcons(items, movingIds, dCol, dRow, grid) {+ const moving = new Set(movingIds);+ const taken = new Set(items.filter((it) => !moving.has(it.id)).map((it) => key(it.col, it.row)));+ const placed = new Map();+ const order = items+ .filter((it) => moving.has(it.id))+ .sort((a, b) => a.col - b.col || a.row - b.row);+ for (const it of order) {+ const wantC = Math.min(grid.cols - 1, Math.max(0, it.col + dCol));+ const wantR = Math.min(grid.rows - 1, Math.max(0, it.row + dRow));+ const free = nearestFreeCell(wantC, wantR, grid, taken) || { col: it.col, row: it.row };+ taken.add(key(free.col, free.row));+ placed.set(it.id, free);+ }+ return items.map((it) => (placed.has(it.id) ? { ...it, ...placed.get(it.id) } : it));+}++/**+ * Re-seat icons after the grid changed size (window resize, icon size change):+ * keep cells that still fit, move the rest to the nearest free cell.+ */+export function reflowIcons(items, grid) {+ const taken = new Set();+ const out = [];+ const overflow = [];+ for (const it of items) {+ if (it.col < grid.cols && it.row < grid.rows && !taken.has(key(it.col, it.row))) {+ taken.add(key(it.col, it.row));+ out.push(it);+ } else overflow.push(it);+ }+ for (const it of overflow) {+ const free = nearestFreeCell(Math.min(it.col, grid.cols - 1), Math.min(it.row, grid.rows - 1), grid, taken);+ if (!free) continue; // more icons than cells: the extras stay reachable from Start+ taken.add(key(free.col, free.row));+ out.push({ ...it, ...free });+ }+ const order = new Map(items.map((it, i) => [it.id, i]));+ return out.sort((a, b) => order.get(a.id) - order.get(b.id));+}++/** Add icons that are missing (new defaults, new shortcuts) into free cells. */+export function addIcons(items, ids, grid) {+ const have = new Set(items.map((it) => it.id));+ const taken = new Set(items.map((it) => key(it.col, it.row)));+ const out = items.slice();+ for (const id of ids) {+ if (have.has(id)) continue;+ const free = nearestFreeCell(0, 0, grid, taken);+ if (!free) break;+ taken.add(key(free.col, free.row));+ out.push({ id, ...free });+ }+ return out;+}++/** Validate persisted icon placement. Unknown ids and duplicate cells are dropped. */+export function sanitizeIcons(raw, isKnown) {+ if (!Array.isArray(raw)) return [];+ const seenId = new Set();+ const seenCell = new Set();+ const out = [];+ for (const it of raw) {+ if (!it || typeof it.id !== 'string' || !isKnown(it.id) || seenId.has(it.id)) continue;+ if (!Number.isInteger(it.col) || !Number.isInteger(it.row) || it.col < 0 || it.row < 0) continue;+ if (seenCell.has(key(it.col, it.row))) continue;+ seenId.add(it.id);+ seenCell.add(key(it.col, it.row));+ out.push({ id: it.id, col: it.col, row: it.row });+ }+ return out;+}++/** Validate persisted preferences, falling back per field so one bad value never resets the rest. */+export function sanitizePrefs(raw, wallpaperIds) {+ let data = raw;+ if (typeof raw === 'string') {+ try {+ data = JSON.parse(raw);+ } catch {+ data = null;+ }+ }+ const d = data && typeof data === 'object' ? data : {};+ const name = typeof d.name === 'string' ? d.name.replace(/[\u0000-\u001f<>]/g, '').trim().slice(0, 40) : '';+ const hue = Number.isFinite(d.avatarHue) ? Math.round(((d.avatarHue % 360) + 360) % 360) : DEFAULT_PREFS.avatarHue;+ return {+ wall: wallpaperIds.includes(d.wall) ? d.wall : DEFAULT_PREFS.wall,+ accent: /^#[0-9a-f]{6}$/i.test(d.accent || '') ? d.accent.toLowerCase() : DEFAULT_PREFS.accent,+ mode: MODES.includes(d.mode) ? d.mode : DEFAULT_PREFS.mode,+ iconSize: d.iconSize in ICON_SIZES ? d.iconSize : DEFAULT_PREFS.iconSize,+ clock24: d.clock24 === true,+ taskbarAlign: d.taskbarAlign === 'left' ? 'left' : 'center',+ name,+ avatarHue: hue,+ };+}++/** Initials for the profile avatar. */+export function initialsOf(name) {+ const parts = String(name || '')+ .trim()+ .split(/\s+/)+ .filter(Boolean);+ if (!parts.length) return '?';+ return (parts[0][0] + (parts.length > 1 ? parts[parts.length - 1][0] : '')).toUpperCase();+}++/** Bytes of localStorage used by keys with the given prefix (UTF-16, as browsers count). */+export function storageBytes(entries, prefix) {+ let n = 0;+ for (const [k, v] of entries) if (k.startsWith(prefix)) n += (k.length + String(v).length) * 2;+ return n;+}++export function formatBytes(n) {+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;+ return `${(n / 1024 / 1024).toFixed(2)} MB`;+}++export const EXPORT_PREFIX = 'tws:';+export const EXPORT_MAX_BYTES = 2 * 1024 * 1024;+/** Keys a session export may restore. Anything else in an imported file is ignored. */+export const EXPORT_KEYS = ['tws:desktop', 'tws:prefs', 'tws:icons', 'tws:recent', 'tws:notes', 'tws:welcomed', 'tws:wall'];++export function parseSessionImport(text) {+ if (typeof text !== 'string' || text.length > EXPORT_MAX_BYTES) return { ok: false, error: 'That file is too large to be a desktop session.' };+ let data;+ try {+ data = JSON.parse(text);+ } catch {+ return { ok: false, error: 'That file is not valid JSON.' };+ }+ if (!data || data.kind !== 'three.ws-desktop-session' || data.v !== 1 || typeof data.items !== 'object' || !data.items) {+ return { ok: false, error: 'That file is not a three.ws desktop session export.' };+ }+ const items = {};+ for (const k of EXPORT_KEYS) if (typeof data.items[k] === 'string') items[k] = data.items[k];+ if (!Object.keys(items).length) return { ok: false, error: 'The export contains no desktop data.' };+ return { ok: true, items };+}diff --git a/src/desktop/main.js b/src/desktop/main.jsnew file mode 100644index 000000000..81937bca8--- /dev/null+++ b/src/desktop/main.js@@ -0,0 +1,31 @@+// Desktop entry: boot the shell, restore the last session, honour deep links.++import './theme.css';+import './desktop.css';+import { createShell } from './shell.js';+import { deepLinkApp } from './layout.js';++async function main() {+ const root = document.getElementById('os');+ if (!root) return;+ const shell = await createShell(root);+ document.documentElement.classList.add('os-ready');++ const restored = shell.restore();+ const wanted = deepLinkApp(location.search, location.hash);+ if (wanted && shell.hasApp(wanted)) shell.launchId(wanted);+ else if (!restored) shell.welcomeIfFirst();++ // `?app=` is a one-shot: drop it so a reload restores the saved layout.+ if (wanted) history.replaceState(null, '', location.pathname);++ addEventListener('storage', (e) => {+ if (e.key === shell.KEY.view && e.newValue === 'classic') location.assign('/classic');+ });+}++main().catch((err) => {+ console.error('[desktop] boot failed', err);+ const root = document.getElementById('os');+ if (root) root.innerHTML = '<p style="padding:24px;color:#fff;font:15px system-ui">The desktop could not start. <a style="color:#4cc2ff" href="/classic">Open the classic site</a>.</p>';+});diff --git a/src/desktop/shell.js b/src/desktop/shell.jsnew file mode 100644index 000000000..a88bb46da--- /dev/null+++ b/src/desktop/shell.js@@ -0,0 +1,1182 @@+// The three.ws desktop shell: wallpaper, icons, taskbar, Start menu, widgets,+// calendar, context menu and the two native apps. Windows are owned by wm.js;+// pure rules live in layout.js.++import { ALL_APPS, APPS, CUSTOM_WALL, WALLPAPERS, appById } from './apps.js';+import { icon } from './icons.js';+import { createIconLayer } from './icon-layer.js';+import { createWM } from './wm.js';+import {+ ACCENTS,+ DEFAULT_PREFS,+ EXPORT_KEYS,+ ICON_SIZES,+ STATE_VERSION,+ cleanTitle,+ formatBytes,+ initialsOf,+ isInternalPath,+ pageAppId,+ pagePathOf,+ parseSessionImport,+ rankItems,+ sanitizePrefs,+ sanitizeState,+ storageBytes,+} from './layout.js';++const TASK_H = 48;+const NAV_DATA = '/nav-data.js';+const KEY = {+ state: 'tws:desktop',+ wall: 'tws:wall',+ view: 'tws:view',+ recent: 'tws:recent',+ welcomed: 'tws:welcomed',+ prefs: 'tws:prefs',+ icons: 'tws:icons',+};+const THEME_KEY = 'twx_theme';+const WALL_IDS = [...WALLPAPERS.map((w) => w.id), CUSTOM_WALL];++// Large binary state (the custom wallpaper) does not belong in localStorage.+const idb = {+ open() {+ return new Promise((res, rej) => {+ const r = indexedDB.open('tws-desktop', 1);+ r.onupgradeneeded = () => r.result.createObjectStore('kv');+ r.onsuccess = () => res(r.result);+ r.onerror = () => rej(r.error);+ });+ },+ async get(k) {+ try {+ const db = await this.open();+ return await new Promise((res) => {+ const q = db.transaction('kv').objectStore('kv').get(k);+ q.onsuccess = () => res(q.result ?? null);+ q.onerror = () => res(null);+ });+ } catch {+ return null;+ }+ },+ async set(k, v) {+ const db = await this.open();+ await new Promise((res, rej) => {+ const t = db.transaction('kv', 'readwrite');+ t.objectStore('kv').put(v, k);+ t.oncomplete = res;+ t.onerror = () => rej(t.error);+ });+ },+ async del(k) {+ try {+ const db = await this.open();+ await new Promise((res) => {+ const t = db.transaction('kv', 'readwrite');+ t.objectStore('kv').delete(k);+ t.oncomplete = res;+ t.onerror = res;+ });+ } catch {+ /* nothing to delete */+ }+ },+};++/** Downscale an uploaded image so a wallpaper never costs more than a few hundred KB. */+async function shrinkImage(file, maxW = 2560) {+ const bmp = await createImageBitmap(file);+ const k = Math.min(1, maxW / bmp.width);+ const c = document.createElement('canvas');+ c.width = Math.round(bmp.width * k);+ c.height = Math.round(bmp.height * k);+ c.getContext('2d').drawImage(bmp, 0, 0, c.width, c.height);+ return new Promise((res, rej) => c.toBlob((b) => (b ? res(b) : rej(new Error('encode'))), 'image/jpeg', 0.85));+}++const store = {+ get(k) {+ try {+ return localStorage.getItem(k);+ } catch {+ return null;+ }+ },+ set(k, v) {+ try {+ localStorage.setItem(k, v);+ } catch {+ /* private mode or quota: preferences simply do not persist */+ }+ },+ del(k) {+ try {+ localStorage.removeItem(k);+ } catch {+ /* nothing to remove */+ }+ },+};++const h = (tag, cls, html) => {+ const el = document.createElement(tag);+ if (cls) el.className = cls;+ if (html != null) el.innerHTML = html;+ return el;+};+const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+const tile = (app, size = 'sm', glyph = 18) =>+ `<span class="app-tile ${size}" style="--hue:${app.hue}">${icon(app.icon, glyph)}</span>`;++/** Build launchable "page apps" from the site's own navigation data. */+async function loadCatalog() {+ try {+ // public/ files are served as-is; a variable keeps vite from bundling it.+ const mod = await import(/* @vite-ignore */ NAV_DATA);+ const seen = new Set(APPS.map((a) => a.href));+ const out = [];+ const take = (it) => {+ if (!it || !isInternalPath(it.href) || seen.has(it.href.split('#')[0])) return;+ seen.add(it.href.split('#')[0]);+ const hue = [...it.href].reduce((n, c) => (n * 31 + c.charCodeAt(0)) % 360, 7);+ out.push({+ id: pageAppId(it.href),+ title: cleanTitle(it.title, it.href),+ href: it.href,+ hue,+ icon: 'grid',+ size: { w: 1040, h: 700 },+ desc: it.desc || '',+ keywords: [],+ page: true,+ });+ };+ for (const g of mod.NAV_GROUPS || []) {+ (g.items || []).forEach(take);+ (g.columns || []).forEach((c) => (c.items || []).forEach(take));+ }+ return out;+ } catch {+ return [];+ }+}++export async function createShell(root, opts = {}) {+ const catalog = await loadCatalog();+ const resolveApp = (id) => appById(id) || catalog.find((a) => a.id === id) || pageFromId(id);+ function pageFromId(id) {+ const p = pagePathOf(id);+ if (!p) return null;+ return { id, title: cleanTitle(p.replace(/^\//, '').replace(/[-_/]/g, ' '), p), href: p, hue: 210, icon: 'grid', size: { w: 1040, h: 700 }, page: true };+ }+ const known = new Set(ALL_APPS.map((a) => a.id));++ root.classList.add('os');+ root.innerHTML = '';+ const wall = h('div', 'os-wall');+ const icons = h('nav', 'os-icons');+ icons.setAttribute('aria-label', 'Desktop');+ const layer = h('div', 'os-layer');+ const task = h('footer', 'os-task');+ const toasts = h('div', 'os-toasts');+ toasts.setAttribute('role', 'status');+ toasts.setAttribute('aria-live', 'polite');+ root.append(wall, icons, layer, task, toasts);++ // ---------- preferences (the user profile and personalization) ----------+ const loadPrefs = () => {+ const raw = store.get(KEY.prefs);+ const p = sanitizePrefs(raw, WALL_IDS);+ if (!raw) {+ // Carry over choices made before the settings app existed.+ const w = store.get(KEY.wall);+ if (WALL_IDS.includes(w)) p.wall = w;+ p.mode = store.get(THEME_KEY) === 'light' ? 'light' : 'dark';+ }+ return p;+ };+ let prefs = loadPrefs();+ let wallUrl = '';+ const prefsListeners = new Set();+ const dark = matchMedia('(prefers-color-scheme: dark)');+ const effectiveTheme = () => (prefs.mode === 'auto' ? (dark.matches ? 'dark' : 'light') : prefs.mode);+ let tickClock = null;+ let deskIcons = null;++ async function applyWall() {+ if (prefs.wall === CUSTOM_WALL) {+ const blob = await idb.get(CUSTOM_WALL);+ if (blob) {+ if (wallUrl) URL.revokeObjectURL(wallUrl);+ wallUrl = URL.createObjectURL(blob);+ wall.style.backgroundImage = `url("${wallUrl}")`;+ wall.dataset.custom = '1';+ root.dataset.wall = CUSTOM_WALL;+ return;+ }+ prefs.wall = DEFAULT_PREFS.wall;+ }+ wall.style.backgroundImage = '';+ delete wall.dataset.custom;+ root.dataset.wall = prefs.wall;+ }+ function applyPrefs() {+ root.style.setProperty('--accent', prefs.accent);+ root.style.setProperty('--theme-2', prefs.accent);+ task.classList.toggle('left', prefs.taskbarAlign === 'left');+ const theme = effectiveTheme();+ document.documentElement.setAttribute('data-theme', theme);+ store.set(THEME_KEY, theme);+ root.querySelectorAll('.win-frame').forEach((f) => {+ try {+ f.contentDocument.documentElement.setAttribute('data-theme', theme);+ } catch {+ /* cross-origin frame */+ }+ });+ tickClock?.();+ prefsListeners.forEach((fn) => fn(prefs));+ }+ function setPrefs(patch) {+ prefs = sanitizePrefs({ ...prefs, ...patch }, WALL_IDS);+ store.set(KEY.prefs, JSON.stringify(prefs));+ store.set(KEY.wall, prefs.wall === CUSTOM_WALL ? DEFAULT_PREFS.wall : prefs.wall);+ if ('wall' in patch) applyWall();+ if ('iconSize' in patch) deskIcons?.setSize(prefs.iconSize);+ applyPrefs();+ }+ dark.addEventListener?.('change', () => prefs.mode === 'auto' && applyPrefs());++ function toast(msg) {+ const t = h('div', 'os-toast');+ t.textContent = msg;+ toasts.append(t);+ setTimeout(() => t.remove(), 4200);+ }++ // ---------- recent ----------+ const recent = () => {+ try {+ const r = JSON.parse(store.get(KEY.recent) || '[]');+ return Array.isArray(r) ? r.filter((x) => typeof x === 'string') : [];+ } catch {+ return [];+ }+ };+ function pushRecent(id) {+ const next = [id, ...recent().filter((x) => x !== id)].slice(0, 8);+ store.set(KEY.recent, JSON.stringify(next));+ }++ // ---------- window manager ----------+ let running = [];+ let focusId = null;+ let saveTimer = 0;+ const wm = createWM({+ layer,+ getMetrics: () => ({ vw: innerWidth, vh: innerHeight, menuH: 0, dockH: TASK_H, mobile: innerWidth <= 720 }),+ renderNative: (app, body) => renderNative(app, body),+ notify: toast,+ onChange: ({ windows, focus }) => {+ running = windows;+ focusId = focus;+ renderTask();+ clearTimeout(saveTimer);+ saveTimer = setTimeout(save, 300);+ },+ });+ function save() {+ store.set(KEY.state, JSON.stringify({ v: STATE_VERSION, ...wm.snapshot() }));+ }+ addEventListener('pagehide', save);++ function launch(app, o = {}) {+ if (!app) return;+ closePops();+ if (app.id === 'settings' && o.section) {+ if (wm.has('settings') && settingsGo) settingsGo(o.section);+ else pendingSection = o.section;+ }+ pushRecent(app.id);+ wm.open(app, o);+ }+ const launchId = (id, o) => launch(resolveApp(id), o);++ // ---------- taskbar ----------+ const pinned = [...APPS, ...ALL_APPS.filter((a) => a.native)].filter((a) => a.dock);+ const btnStart = h('button', 'os-tb start', icon('logo', 24));+ btnStart.type = 'button';+ btnStart.setAttribute('aria-label', 'Start');+ btnStart.setAttribute('aria-haspopup', 'dialog');+ btnStart.setAttribute('aria-expanded', 'false');+ btnStart.title = 'Start';+ const btnWidgets = h('button', 'os-tb', icon('widgets', 22));+ btnWidgets.type = 'button';+ btnWidgets.setAttribute('aria-label', 'Widgets and your agent');+ btnWidgets.setAttribute('aria-expanded', 'false');+ btnWidgets.title = 'Widgets';+ const btnSearch = h('button', 'os-tb hide-sm', icon('search', 20));+ btnSearch.type = 'button';+ btnSearch.setAttribute('aria-label', 'Search apps and pages');+ btnSearch.title = 'Search';++ const left = h('div', 'os-task-left');+ left.append(btnWidgets);+ const mid = h('div', 'os-task-mid');+ const right = h('div', 'os-task-right');+ task.append(left, mid, right);++ function renderTask() {+ mid.replaceChildren(btnStart, btnSearch);+ const byId = new Map(running.map((w) => [w.id, w]));+ const list = [...pinned];+ running.forEach((w) => {+ if (!list.some((a) => a.id === w.id)) list.push(w.app);+ });+ list.forEach((app) => {+ const w = byId.get(app.id);+ const b = h('button', `os-tb run${w ? ' open' : ''}${w && !w.minimized && focusId === app.id ? ' on' : ''}`, tile(app, 'xs', 15));+ b.type = 'button';+ b.title = w ? w.title : app.title;+ b.setAttribute('aria-label', w ? `${w.title}, ${w.minimized ? 'minimized' : 'open'}` : `Open ${app.title}`);+ b.addEventListener('click', () => {+ if (!w) return launch(app);+ if (w.minimized) wm.focus(app.id);+ else if (focusId === app.id) wm.minimize(app.id);+ else wm.focus(app.id);+ });+ b.addEventListener('contextmenu', (e) => {+ e.preventDefault();+ e.stopPropagation();+ menu(e.clientX, e.clientY, [+ w ? ['Close window', 'close', () => wm.close(app.id)] : ['Open', 'external', () => launch(app)],+ ]);+ });+ mid.append(b);+ });+ }++ // tray+ const tray = h('div', 'os-tray');+ const btnTheme = h('button', 'os-tb', '');+ btnTheme.type = 'button';+ const btnClassic = h('button', 'os-tb hide-sm', icon('classic', 20));+ btnClassic.type = 'button';+ btnClassic.title = 'Classic view';+ btnClassic.setAttribute('aria-label', 'Switch to the classic website');+ const chip = h('a', 'os-chip', `${icon('user', 18)}<span>Sign in</span>`);+ chip.href = '/login';+ chip.title = 'Account';+ chip.addEventListener('click', (e) => {+ if (e.metaKey || e.ctrlKey) return;+ e.preventDefault();+ launch(resolveApp(chip.dataset.signedIn ? 'console' : pageAppId('/login')));+ });+ const clock = h('button', 'os-clock');+ clock.type = 'button';+ clock.setAttribute('aria-haspopup', 'dialog');+ clock.setAttribute('aria-expanded', 'false');+ tray.append(btnTheme, btnClassic, chip, clock);+ right.append(tray);++ const isLight = () => document.documentElement.getAttribute('data-theme') === 'light';+ function syncTheme() {+ btnTheme.innerHTML = icon(isLight() ? 'moon' : 'sun', 20);+ const next = isLight() ? 'dark' : 'light';+ btnTheme.title = `Switch to ${next} mode`;+ btnTheme.setAttribute('aria-label', `Switch to ${next} mode`);+ }+ btnTheme.addEventListener('click', () => setPrefs({ mode: isLight() ? 'dark' : 'light' }));+ new MutationObserver(syncTheme).observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });+ syncTheme();++ btnClassic.addEventListener('click', goClassic);+ function goClassic() {+ save();+ store.set(KEY.view, 'classic');+ location.assign('/classic');+ }++ tickClock = function () {+ const d = new Date();+ clock.innerHTML = `<span>${d.toLocaleTimeString([], { hour: prefs.clock24 ? '2-digit' : 'numeric', minute: '2-digit', hour12: !prefs.clock24 })}</span><span>${d.toLocaleDateString([], { month: 'numeric', day: 'numeric', year: 'numeric' })}</span>`;+ clock.setAttribute('aria-label', `${d.toLocaleString()}. Open calendar`);+ };+ tickClock();+ setInterval(tickClock, 15000);++ // auth chip (server session is the truth)+ fetch('/api/auth/me', { credentials: 'include' })+ .then((r) => (r.ok ? r.json() : null))+ .then((data) => {+ const u = data && data.user;+ if (!u) return;+ chip.dataset.signedIn = '1';+ chip.querySelector('span').textContent = u.display_name || u.username || 'Account';+ chip.title = 'Open your console';+ userName = u.display_name || u.username || 'Account';+ paintUser();+ })+ .catch(() => {+ /* signed-out view is already correct */+ });+ let userName = '';+ let startUserEl = null;+ const displayName = () => userName || prefs.name || 'Guest';+ function paintUser() {+ if (!startUserEl) return;+ startUserEl.querySelector('span').textContent = displayName();+ const av = startUserEl.querySelector('.avatar');+ av.textContent = initialsOf(userName || prefs.name);+ av.style.setProperty('--hue', prefs.avatarHue);+ }+ prefsListeners.add(paintUser);++ // ---------- popovers ----------+ let pop = null;+ function closePops() {+ if (pop) {+ pop.el.remove();+ pop.trigger?.setAttribute('aria-expanded', 'false');+ pop.onClose?.();+ pop = null;+ }+ }+ function openPop(kind, el, trigger, onClose) {+ const same = pop && pop.kind === kind;+ closePops();+ if (same) return false;+ root.append(el);+ trigger?.setAttribute('aria-expanded', 'true');+ pop = { kind, el, trigger, onClose };+ return true;+ }+ addEventListener(+ 'pointerdown',+ (e) => {+ if (!pop) return;+ if (pop.el.contains(e.target) || pop.trigger?.contains(e.target)) return;+ closePops();+ },+ true,+ );+ // A click inside an iframe never reaches us; the window blur is the signal.+ addEventListener('blur', () => {+ setTimeout(() => {+ if (pop && document.activeElement?.tagName === 'IFRAME') closePops();+ }, 0);+ });+ addEventListener('keydown', (e) => {+ if (e.key === 'Escape' && pop) {+ const t = pop.trigger;+ closePops();+ t?.focus();+ }+ });++ // ---------- Start menu ----------+ function toggleStart(query = '') {+ const el = h('div', 'os-pop start-menu');+ el.setAttribute('role', 'dialog');+ el.setAttribute('aria-label', 'Start');+ const search = h('label', 'sm-search', `${icon('search', 18)}<input type="search" placeholder="Search apps and pages" aria-label="Search apps and pages" autocomplete="off" spellcheck="false">`);+ const input = search.querySelector('input');+ const body = h('div', 'sm-body');+ const foot = h('div', 'sm-foot');+ const user = h('button', 'sm-user', `<i class="avatar sm"></i><span></span>`);+ user.type = 'button';+ user.title = 'Your profile and settings';+ startUserEl = user;+ paintUser();+ user.addEventListener('click', () => launchId('settings', { section: 'profile' }));+ const pwr = h('button', 'sm-pwr', icon('classic', 20));+ pwr.type = 'button';+ pwr.title = 'Classic view';+ pwr.setAttribute('aria-label', 'Switch to the classic website');+ pwr.addEventListener('click', goClassic);+ foot.append(user, pwr);+ el.append(search, body, foot);++ let selectable = [];+ let sel = -1;+ const everything = () => [...ALL_APPS.filter((a) => !a.native || a.id === 'settings' || a.id === 'apps'), ...catalog];+ function row(app) {+ const r = h('button', 'sm-row', `${tile(app, 'sm', 17)}<div><b>${esc(app.title)}</b><small>${esc(app.desc || app.href || '')}</small></div>`);+ r.type = 'button';+ r.addEventListener('click', () => launch(app));+ selectable.push(r);+ return r;+ }+ function appBtn(app) {+ const b = h('button', 'sm-app', `${tile(app, '', 22)}<span>${esc(app.title)}</span>`);+ b.type = 'button';+ b.addEventListener('click', () => launch(app));+ selectable.push(b);+ return b;+ }+ let showAll = false;+ function paint() {+ selectable = [];+ sel = -1;+ body.replaceChildren();+ const q = input.value.trim();+ if (q) {+ const hits = rankItems(q, everything()).slice(0, 24);+ if (!hits.length) {+ body.append(h('div', 'sm-empty', `Nothing matches "${esc(q)}". Try an app name like Forge or Chat.`));+ return;+ }+ body.append(h('div', 'sm-h', '<span>Best matches</span>'));+ const list = h('div', 'sm-list one');+ hits.forEach((a) => list.append(row(a)));+ body.append(list);+ return;+ }+ const hd = h('div', 'sm-h', `<span>${showAll ? 'All apps' : 'Pinned'}</span>`);+ const toggle = h('button', '', showAll ? 'Back' : `All apps ${'›'}`);+ toggle.type = 'button';+ toggle.addEventListener('click', () => {+ showAll = !showAll;+ paint();+ });+ hd.append(toggle);+ body.append(hd);+ if (showAll) {+ const list = h('div', 'sm-list');+ everything().forEach((a) => list.append(row(a)));+ body.append(list);+ return;+ }+ const grid = h('div', 'sm-grid');+ [...APPS, ALL_APPS.find((a) => a.id === 'settings'), ALL_APPS.find((a) => a.id === 'apps')].forEach((a) => grid.append(appBtn(a)));+ body.append(grid);+ const rec = recent().map(resolveApp).filter(Boolean).slice(0, 6);+ body.append(h('div', 'sm-h', '<span>Recommended</span>'));+ if (rec.length) {+ const list = h('div', 'sm-list');+ rec.forEach((a) => list.append(row(a)));+ body.append(list);+ } else {+ const list = h('div', 'sm-list');+ ['create', 'forge', 'discover', 'chat'].forEach((id) => list.append(row(appById(id))));+ body.append(list);+ }+ }+ input.addEventListener('input', () => {+ showAll = false;+ paint();+ });+ input.addEventListener('keydown', (e) => {+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {+ e.preventDefault();+ if (!selectable.length) return;+ sel = (sel + (e.key === 'ArrowDown' ? 1 : -1) + selectable.length) % selectable.length;+ selectable.forEach((s, i) => s.classList.toggle('is-sel', i === sel));+ selectable[sel].scrollIntoView({ block: 'nearest' });+ } else if (e.key === 'Enter') {+ e.preventDefault();+ (selectable[sel >= 0 ? sel : 0])?.click();+ }+ });+ if (!openPop('start', el, btnStart, () => (startUserEl = null))) return;+ input.value = query;+ paint();+ input.focus({ preventScroll: true });+ }+ btnStart.addEventListener('click', () => toggleStart());+ btnSearch.addEventListener('click', () => toggleStart());++ // ---------- Widgets ----------+ let agentLoaded = false;+ btnWidgets.addEventListener('click', () => {+ const el = h('div', 'os-pop widgets');+ el.setAttribute('role', 'dialog');+ el.setAttribute('aria-label', 'Widgets');+ const agent = h('div', 'wg-card wg-agent');+ const stage = h('div', '', '');+ agent.append(stage);+ const info = h('div', '', '<h3>Your resident agent</h3><p>A living 3D agent, running on the same web component you can embed on any site.</p>');+ const acts = h('div', 'wg-actions');+ const talk = h('button', 'os-btn primary', `${icon('chat', 16)}Talk`);+ talk.type = 'button';+ talk.addEventListener('click', () => launchId('chat'));+ const make = h('button', 'os-btn', `${icon('sparkle', 16)}Make your own`);+ make.type = 'button';+ make.addEventListener('click', () => launchId('create'));+ acts.append(talk, make);+ info.append(acts);+ agent.append(info);++ const quick = h('div', 'wg-card');+ quick.append(h('h3', '', 'Jump in'));+ const q = h('div', 'wg-quick');+ ['forge', 'discover', 'marketplace', 'pulse', 'trenches', 'tour'].forEach((id) => {+ const a = appById(id);+ const b = h('button', '', `${tile(a, 'sm', 17)}<span>${esc(a.title)}</span>`);+ b.type = 'button';+ b.addEventListener('click', () => launch(a));+ q.append(b);+ });+ quick.append(q);++ const about = h('div', 'wg-card', '<h3>three.ws</h3><p>The 3D agent layer of the internet. Every window here is a real three.ws page. Prefer the original site? Use the classic view in the taskbar.</p>');+ el.append(agent, quick, about);+ if (!openPop('widgets', el, btnWidgets)) return;+ mountAgent(stage);+ });+ function mountAgent(stage) {+ const mk = () => {+ const a = document.createElement('agent-3d');+ a.setAttribute('src', 'https://three.ws/avatars/michelle.glb');+ a.setAttribute('aria-label', 'Resident 3D agent');+ stage.replaceChildren(a);+ };+ if (agentLoaded || customElements.get('agent-3d')) return mk();+ agentLoaded = true;+ const s = document.createElement('script');+ s.type = 'module';+ s.src = 'https://three.ws/agent-3d/latest/agent-3d.js';+ s.onload = mk;+ s.onerror = () => {+ stage.innerHTML = '<p>The 3D agent could not load. Check your connection and reopen Widgets.</p>';+ };+ document.head.append(s);+ }++ // ---------- Calendar ----------+ clock.addEventListener('click', () => {+ let view = new Date();+ view.setDate(1);+ const el = h('div', 'os-pop calendar');+ el.setAttribute('role', 'dialog');+ el.setAttribute('aria-label', 'Calendar');+ function paint() {+ const today = new Date();+ const first = new Date(view.getFullYear(), view.getMonth(), 1);+ const start = new Date(first);+ start.setDate(1 - first.getDay());+ const cells = [];+ for (let i = 0; i < 42; i++) {+ const d = new Date(start);+ d.setDate(start.getDate() + i);+ const cls = [d.getMonth() !== view.getMonth() ? 'mute' : '', d.toDateString() === today.toDateString() ? 'today' : ''].join(' ');+ cells.push(`<b class="${cls}">${d.getDate()}</b>`);+ }+ const dow = ['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((d) => `<i>${d}</i>`).join('');+ el.innerHTML =+ `<div class="cal-head"><span>${view.toLocaleDateString([], { month: 'long', year: 'numeric' })}</span><span>` ++ `<button type="button" data-d="-1" aria-label="Previous month">${icon('chevron', 14).replace('<svg', '<svg style="transform:rotate(180deg)"')}</button>` ++ `<button type="button" data-d="1" aria-label="Next month">${icon('chevron', 14)}</button></span></div>` ++ `<div class="cal-grid">${dow}${cells.join('')}</div>`;+ el.querySelectorAll('[data-d]').forEach((b) =>+ b.addEventListener('click', () => {+ view = new Date(view.getFullYear(), view.getMonth() + Number(b.dataset.d), 1);+ paint();+ }),+ );+ }+ paint();+ openPop('calendar', el, clock);+ });++ // ---------- context menu ----------+ function menu(x, y, items) {+ closePops();+ const el = h('div', 'os-pop ctx');+ el.setAttribute('role', 'menu');+ items.forEach((it) => {+ if (it === '-') return el.append(h('hr'));+ const [label, ic, fn] = it;+ const b = h('button', '', `${icon(ic, 16)}<span>${esc(label)}</span>`);+ b.type = 'button';+ b.setAttribute('role', 'menuitem');+ b.addEventListener('click', () => {+ closePops();+ fn();+ });+ el.append(b);+ });+ root.append(el);+ const r = el.getBoundingClientRect();+ el.style.left = `${Math.max(4, Math.min(x, innerWidth - r.width - 4))}px`;+ el.style.top = `${Math.max(4, Math.min(y, innerHeight - r.height - TASK_H - 4))}px`;+ el.style.bottom = 'auto';+ pop = { kind: 'ctx', el, trigger: null };+ el.querySelector('button')?.focus();+ }+ root.addEventListener('contextmenu', (e) => {+ if (e.target.closest('.win, .os-task, .os-pop')) return;+ e.preventDefault();+ menu(e.clientX, e.clientY, [+ ['Select all', 'grid', () => deskIcons.selectAll()],+ ['Small icons', 'grid', () => setPrefs({ iconSize: 'small' })],+ ['Medium icons', 'grid', () => setPrefs({ iconSize: 'medium' })],+ ['Large icons', 'grid', () => setPrefs({ iconSize: 'large' })],+ ['Sort by name', 'folder', () => deskIcons.sortByName()],+ ['Auto arrange', 'folder', () => deskIcons.arrange()],+ ['Refresh', 'reload', () => deskIcons.refresh()],+ '-',+ ['All Apps', 'search', () => launchId('apps')],+ ['Personalize', 'gear', () => launchId('settings', { section: 'personalize' })],+ ['Open Start', 'logo', () => toggleStart()],+ '-',+ ['Switch to classic view', 'classic', goClassic],+ ['Close all windows', 'close', () => wm.closeAll()],+ ]);+ });++ // ---------- desktop icons ----------+ deskIcons = createIconLayer({+ host: icons,+ resolve: resolveApp,+ isKnown: (id) => !!resolveApp(id),+ defaults: () => [...APPS, ...ALL_APPS.filter((a) => a.native)].filter((a) => a.desktop).map((a) => a.id),+ load: () => {+ const raw = store.get(KEY.icons);+ if (raw == null) return null;+ try {+ return JSON.parse(raw);+ } catch {+ return null;+ }+ },+ save: (list) => store.set(KEY.icons, JSON.stringify(list)),+ launch,+ menu,+ size: prefs.iconSize,+ });+ icons.setAttribute('role', 'listbox');+ icons.setAttribute('aria-label', 'Desktop');+ icons.setAttribute('aria-multiselectable', 'true');+ deskIcons.init((app) => tile(app, '', 24));+ icons.addEventListener('pointerdown', (e) => {+ if (e.target === icons) closePops();+ });++ // ---------- keyboard ----------+ addEventListener('keydown', (e) => {+ const mod = e.metaKey || e.ctrlKey;+ if (mod && e.key.toLowerCase() === 'k') {+ e.preventDefault();+ closePops();+ toggleStart();+ } else if (e.altKey && e.key === 'Tab') {+ e.preventDefault();+ wm.cycle(e.shiftKey ? -1 : 1);+ } else if (e.altKey && e.key.toLowerCase() === 'w' && wm.focused()) {+ e.preventDefault();+ wm.close(wm.focused());+ }+ });+ let resizeT = 0;+ addEventListener('resize', () => {+ wm.relayout();+ clearTimeout(resizeT);+ resizeT = setTimeout(() => deskIcons.reseat(), 120);+ });++ // ---------- native apps ----------+ const WALL_PREVIEW = {+ aurora: 'linear-gradient(215deg,#7a3fa8,#1f6fbf)',+ midnight: 'linear-gradient(180deg,#1d2b5a,#05060d)',+ solana: 'linear-gradient(135deg,#14f195,#9945ff)',+ ember: 'linear-gradient(135deg,#ff6a2c,#7a1f4a)',+ graphite: 'linear-gradient(160deg,#2a2d33,#0d0e11)',+ };+ let settingsGo = null;+ let pendingSection = null;++ function download(name, text, type = 'application/json') {+ const url = URL.createObjectURL(new Blob([text], { type }));+ const a = h('a');+ a.href = url;+ a.download = name;+ root.append(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(url), 2000);+ }+ function sessionExport() {+ const items = {};+ EXPORT_KEYS.forEach((k) => {+ const v = store.get(k);+ if (v != null) items[k] = v;+ });+ return JSON.stringify({ kind: 'three.ws-desktop-session', v: 1, exported: new Date().toISOString(), items }, null, 2);+ }+ function localEntries() {+ const out = [];+ try {+ for (let i = 0; i < localStorage.length; i++) {+ const k = localStorage.key(i);+ out.push([k, localStorage.getItem(k)]);+ }+ } catch {+ /* storage unavailable */+ }+ return out;+ }+ async function storageSummary() {+ const used = storageBytes(localEntries(), 'tws:');+ let quota = 0;+ let usage = 0;+ try {+ const est = await navigator.storage.estimate();+ quota = est.quota || 0;+ usage = est.usage || 0;+ } catch {+ /* estimate unsupported */+ }+ return { used, quota, usage };+ }+ function resetEverything() {+ wm.closeAll();+ [KEY.state, KEY.recent, KEY.prefs, KEY.icons, KEY.wall, KEY.welcomed, 'tws:notes'].forEach((k) => store.del(k));+ idb.del(CUSTOM_WALL);+ location.reload();+ }++ function setRow(title, sub, control) {+ const r = h('div', 'set-row', `<div><b>${esc(title)}</b><small>${esc(sub)}</small></div>`);+ r.append(control);+ return r;+ }+ function btn(label, fn, cls = 'os-btn') {+ const b = h('button', cls, label);+ b.type = 'button';+ b.addEventListener('click', fn);+ return b;+ }+ function seg(options, current, onPick) {+ const wrap = h('div', 'seg');+ wrap.setAttribute('role', 'group');+ options.forEach(([val, label]) => {+ const b = h('button', '', esc(label));+ b.type = 'button';+ b.setAttribute('aria-pressed', String(current === val));+ b.addEventListener('click', () => {+ onPick(val);+ wrap.querySelectorAll('button').forEach((o) => o.setAttribute('aria-pressed', String(o === b)));+ });+ wrap.append(b);+ });+ return wrap;+ }+ function toggle(on, onChange, label) {+ const t = h('button', 'set-switch');+ t.type = 'button';+ t.setAttribute('role', 'switch');+ t.setAttribute('aria-label', label);+ t.setAttribute('aria-checked', String(on));+ t.addEventListener('click', () => {+ const next = t.getAttribute('aria-checked') !== 'true';+ t.setAttribute('aria-checked', String(next));+ onChange(next);+ });+ return t;+ }++ function renderSettings(wrap) {+ wrap.classList.add('settings');+ const nav = h('nav', 'set-nav');+ nav.setAttribute('aria-label', 'Settings sections');+ const pane = h('div', 'set-pane');+ wrap.append(nav, pane);+ const sections = [+ ['profile', 'user', 'Profile'],+ ['personalize', 'image', 'Personalization'],+ ['desktop', 'desktop', 'Desktop and taskbar'],+ ['session', 'folder', 'Session and storage'],+ ];+ let current = 'profile';+ const panes = { profile: paintProfile, personalize: paintPersonalize, desktop: paintDesktop, session: paintSession };+ sections.forEach(([id, ic, label]) => {+ const b = h('button', '', `${icon(ic, 16)}<span>${label}</span>`);+ b.type = 'button';+ b.dataset.section = id;+ b.addEventListener('click', () => go(id));+ nav.append(b);+ });+ function go(id) {+ if (!panes[id]) return;+ current = id;+ nav.querySelectorAll('button').forEach((b) => b.toggleAttribute('aria-current', false));+ const active = nav.querySelector(`[data-section="${id}"]`);+ active.setAttribute('aria-current', 'page');+ pane.replaceChildren();+ panes[id]();+ pane.scrollTop = 0;+ }+ settingsGo = go;++ function paintProfile() {+ pane.append(h('h2', '', 'Profile'), h('p', '', 'Your name and avatar are stored in this browser and shown on Start. Signing in to three.ws uses your account name instead.'));+ const top = h('div', 'set-profile');+ const av = h('i', 'avatar');+ const paintAv = () => {+ av.textContent = initialsOf(userName || prefs.name);+ av.style.setProperty('--hue', prefs.avatarHue);+ };+ paintAv();+ const col = h('div');+ col.style.flex = '1';+ const field = h('input', 'os-field');+ field.type = 'text';+ field.maxLength = 40;+ field.placeholder = 'Your name';+ field.setAttribute('aria-label', 'Your name');+ field.value = prefs.name;+ field.addEventListener('input', () => {+ setPrefs({ name: field.value });+ paintAv();+ });+ col.append(field);+ top.append(av, col);+ pane.append(top);+ pane.append(h('h3', '', 'Avatar colour'));+ const hue = h('input', 'os-range');+ hue.type = 'range';+ hue.min = '0';+ hue.max = '359';+ hue.value = String(prefs.avatarHue);+ hue.setAttribute('aria-label', 'Avatar colour');+ hue.addEventListener('input', () => {+ setPrefs({ avatarHue: Number(hue.value) });+ paintAv();+ });+ pane.append(hue);+ pane.append(h('h3', '', 'Account'));+ pane.append(+ setRow(+ chip.dataset.signedIn ? `Signed in as ${userName}` : 'Not signed in',+ chip.dataset.signedIn ? 'Your agents, wallets and usage live in the Console.' : 'Sign in to sync your agents and wallets across devices.',+ btn(chip.dataset.signedIn ? 'Open Console' : 'Sign in', () => launch(resolveApp(chip.dataset.signedIn ? 'console' : pageAppId('/login')))),+ ),+ );+ }++ function paintPersonalize() {+ pane.append(h('h2', '', 'Personalization'));+ pane.append(h('h3', '', 'Theme'));+ pane.append(seg([['dark', 'Dark'], ['light', 'Light'], ['auto', 'Match system']], prefs.mode, (v) => setPrefs({ mode: v })));+ pane.append(h('h3', '', 'Accent colour'));+ const sw = h('div', 'swatches');+ ACCENTS.forEach((c) => {+ const b = h('button', 'swatch');+ b.type = 'button';+ b.style.setProperty('--c', c);+ b.setAttribute('aria-label', `Accent ${c}`);+ b.setAttribute('aria-pressed', String(prefs.accent === c));+ b.addEventListener('click', () => {+ setPrefs({ accent: c });+ sw.querySelectorAll('.swatch').forEach((o) => o.setAttribute('aria-pressed', String(o === b)));+ });+ sw.append(b);+ });+ pane.append(sw);+ pane.append(h('h3', '', 'Wallpaper'));+ const grid = h('div', 'walls');+ const opts = [...WALLPAPERS.map((w) => ({ id: w.id, label: w.label, bg: WALL_PREVIEW[w.id] }))];+ opts.forEach((w) => {+ const b = h('button', 'wall-opt', `<i style="background:${w.bg}"></i><span>${w.label}</span>`);+ b.type = 'button';+ b.dataset.wall = w.id;+ b.setAttribute('aria-pressed', String(prefs.wall === w.id));+ b.addEventListener('click', () => {+ setPrefs({ wall: w.id });+ grid.querySelectorAll('.wall-opt').forEach((o) => o.setAttribute('aria-pressed', String(o === b)));+ });+ grid.append(b);+ });+ const custom = h('button', 'wall-opt', `<i style="background:var(--hover-b);display:grid;place-items:center">${icon('image', 22)}</i><span>Your photo</span>`);+ custom.type = 'button';+ custom.setAttribute('aria-pressed', String(prefs.wall === CUSTOM_WALL));+ const file = h('input');+ file.type = 'file';+ file.accept = 'image/*';+ file.hidden = true;+ file.addEventListener('change', async () => {+ const f = file.files && file.files[0];+ if (!f) return;+ try {+ const blob = await shrinkImage(f);+ await idb.set(CUSTOM_WALL, blob);+ setPrefs({ wall: CUSTOM_WALL });+ grid.querySelectorAll('.wall-opt').forEach((o) => o.setAttribute('aria-pressed', String(o === custom)));+ toast('Wallpaper set.');+ } catch {+ toast('That image could not be used. Try a PNG or JPEG.');+ }+ file.value = '';+ });+ custom.addEventListener('click', () => file.click());+ grid.append(custom, file);+ pane.append(grid);+ }++ function paintDesktop() {+ pane.append(h('h2', '', 'Desktop and taskbar'));+ pane.append(h('h3', '', 'Desktop icons'));+ pane.append(+ setRow('Icon size', 'Applies to every icon on the desktop.', seg(Object.keys(ICON_SIZES).map((k) => [k, k[0].toUpperCase() + k.slice(1)]), prefs.iconSize, (v) => setPrefs({ iconSize: v }))),+ setRow('Arrange icons', 'Sort the desktop icons by name into a tidy grid.', btn('Sort by name', () => deskIcons.sortByName())),+ setRow('Restore default icons', 'Bring back every standard app on the desktop.', btn('Restore', () => {+ deskIcons.add && [...APPS, ...ALL_APPS.filter((a) => a.native)].filter((a) => a.desktop).forEach((a) => deskIcons.add(a.id));+ toast('Default icons restored.');+ })),+ );+ pane.append(h('h3', '', 'Taskbar'));+ pane.append(+ setRow('Alignment', 'Centre the Start button or keep it on the left.', seg([['center', 'Centre'], ['left', 'Left']], prefs.taskbarAlign, (v) => setPrefs({ taskbarAlign: v }))),+ setRow('24-hour clock', 'Show the time as 14:30 instead of 2:30 PM.', toggle(prefs.clock24, (v) => setPrefs({ clock24: v }), '24-hour clock')),+ );+ pane.append(h('h3', '', 'View'));+ pane.append(setRow('Classic website', 'The original three.ws homepage. Your choice is remembered until you switch back.', btn('Open classic', goClassic)));+ }++ function paintSession() {+ pane.append(h('h2', '', 'Session and storage'), h('p', '', 'Like a real computer, your desktop remembers its open windows, icon layout, preferences and recent apps in this browser. Nothing here is sent to a server.'));+ const meter = h('div', '', '');+ const label = h('small', '', 'Calculating...');+ const bar = h('div', 'meter', '<i style="width:0%"></i>');+ meter.append(label, bar);+ storageSummary().then(({ used, quota, usage }) => {+ label.textContent = quota+ ? `Desktop data: ${formatBytes(used)}. This site uses ${formatBytes(usage)} of ${formatBytes(quota)} available to the browser.`+ : `Desktop data: ${formatBytes(used)}.`;+ bar.firstChild.style.width = `${quota ? Math.max(1, Math.min(100, (usage / quota) * 100)) : 1}%`;+ });+ pane.append(meter);+ pane.append(h('h3', '', 'Back up and restore'));+ const file = h('input');+ file.type = 'file';+ file.accept = 'application/json,.json';+ file.hidden = true;+ file.addEventListener('change', async () => {+ const f = file.files && file.files[0];+ file.value = '';+ if (!f) return;+ const r = parseSessionImport(await f.text());+ if (!r.ok) return toast(r.error);+ Object.entries(r.items).forEach(([k, v]) => store.set(k, v));+ toast('Session restored. Reloading the desktop.');+ setTimeout(() => location.reload(), 600);+ });+ pane.append(+ setRow('Export session', 'Download your layout, windows and preferences as a file.', btn('Export', () => {+ save();+ download(`three-ws-desktop-${new Date().toISOString().slice(0, 10)}.json`, sessionExport());+ })),+ setRow('Import session', 'Restore a session you exported earlier, on this or another browser.', btn('Import', () => file.click())),+ );+ pane.append(file);+ pane.append(h('h3', '', 'Reset'));+ pane.append(+ setRow('Close all windows', 'Keep your preferences and icons, close every open window.', btn('Close all', () => {+ wm.closeAll();+ toast('All windows closed.');+ })),+ setRow('Reset the desktop', 'Forget windows, icons, preferences and your profile. Cannot be undone.', btn('Reset everything', () => {+ if (confirm('Reset the desktop? Your windows, icon layout, preferences and profile will be erased from this browser.')) resetEverything();+ }, 'os-btn danger')),+ );+ }+ go(pendingSection || 'profile');+ pendingSection = null;+ }++ function renderApps(wrap) {+ wrap.append(h('h2', '', 'All Apps'), h('p', '', 'Every three.ws app and page. Open one, or keep a shortcut on your desktop.'));+ const bar = h('div', 'apps-bar');+ const q = h('input', 'os-field');+ q.type = 'search';+ q.placeholder = 'Search apps and pages';+ q.setAttribute('aria-label', 'Search apps and pages');+ bar.append(q);+ const list = h('div', 'app-list');+ wrap.append(bar, list);+ const all = [...ALL_APPS.filter((a) => a.id !== 'welcome'), ...catalog];+ function paint() {+ const term = q.value.trim();+ const rows = term ? rankItems(term, all) : all;+ list.replaceChildren();+ if (!rows.length) {+ list.append(h('p', '', `Nothing matches "${esc(term)}".`));+ return;+ }+ rows.forEach((app) => {+ const r = h('div', 'app-row', `${tile(app, 'sm', 17)}<div><b>${esc(app.title)}</b><small>${esc(app.desc || app.href || '')}</small></div>`);+ const open = btn('Open', () => launch(app));+ const pin = btn(deskIcons.has(app.id) ? 'On desktop' : 'Add to desktop', () => {+ if (deskIcons.has(app.id)) {+ deskIcons.remove([app.id]);+ pin.textContent = 'Add to desktop';+ } else if (deskIcons.add(app.id)) {+ pin.textContent = 'On desktop';+ } else {+ toast('The desktop is full. Remove an icon first.');+ }+ });+ r.append(open, pin);+ list.append(r);+ });+ }+ q.addEventListener('input', paint);+ paint();+ }++ function renderNative(app, body) {+ const wrap = h('div', 'native');+ body.append(wrap);+ if (app.id === 'settings') return renderSettings(wrap);+ if (app.id === 'apps') return renderApps(wrap);+ wrap.innerHTML = '<h2>Welcome to three.ws</h2><p>The 3D agent layer of the internet, now as a desktop. Every window is a real three.ws page: drag, resize, snap to an edge, or minimize to the taskbar.</p>';+ const steps = h('div', 'steps');+ [+ ['create', 'Make your agent', 'Start from a selfie, a prompt or a model.'],+ ['forge', 'Forge a 3D model', 'Type a prompt and get a textured GLB.'],+ ['discover', 'Meet other agents', 'Browse every registered agent.'],+ ].forEach(([id, t, s]) => {+ const a = appById(id);+ const b = h('button', 'step', `${tile(a, 'sm', 17)}<div><b>${t}</b><small>${s}</small></div>`);+ b.type = 'button';+ b.addEventListener('click', () => launch(a));+ steps.append(b);+ });+ wrap.append(steps);+ wrap.append(h('p', '', 'Drag on the desktop to select icons, right-click for options, and open Settings to make it yours. Press Ctrl+K to search everything.'));+ }++ // ---------- boot ----------+ renderTask();+ applyWall();+ applyPrefs();+ function restore() {+ const raw = store.get(KEY.state);+ const s = sanitizeState(raw, known);+ s.windows.forEach((w) => {+ const app = resolveApp(w.app);+ if (!app) return;+ wm.open(app, { rect: { x: w.x, y: w.y, w: w.w, h: w.h }, max: w.max, min: w.min, path: w.path, quiet: true });+ });+ if (s.focus && wm.has(s.focus)) wm.focus(s.focus);+ return s.windows.length;+ }+ return {+ wm,+ launch,+ launchId,+ restore,+ hasApp: (id) => !!resolveApp(id),+ welcomeIfFirst() {+ if (store.get(KEY.welcomed)) return;+ store.set(KEY.welcomed, '1');+ launchId('welcome');+ },+ toast,+ store,+ KEY,+ };+}diff --git a/src/desktop/theme.css b/src/desktop/theme.cssnew file mode 100644index 000000000..7bdc559ba--- /dev/null+++ b/src/desktop/theme.css@@ -0,0 +1,155 @@+/* three.ws Desktop theme: the CTRL design system (Windows-12 lineage).+ *+ * Token names and values follow CTRL's ctrl.css so a CTRL app or theme pack+ * reads the same variables here: the semantic surface set (--bg, --card,+ * --hover, --bd, --hr ...), Mica gradients, glass and blur presets, shadows,+ * radii and the easing curves. Dark is the default; light follows the site's+ * [data-theme='light'] switch (theme-switcher.js), so the desktop and every+ * framed page flip together.+ *+ * The three.ws accent (--theme-1/--theme-2) replaces CTRL's purple-blue pair+ * only through --accent overrides in desktop.css, never here, so this file+ * stays a faithful copy of the upstream palette.+ */++.os {+ --font-size-base: 1rem;++ /* Core palette (dark) */+ --col-bg1: #101010;+ --col-bg2: #171717;+ --col-bg3: #262626;+ --col-bgh: #44403c;+ --col-txt1: #ffffff;+ --col-txt2: #dddddd;+ --col-txth: #ffffff;+ --col-good: #5be45b;+ --col-bad: #d44343;++ /* Semantic surfaces (dark) */+ --bg: #000000;+ --bg50: #00000065;+ --bg70: #111111c5;+ --sd: #00000055;+ --card: #202020;+ --hover: #2a2a2a;+ --hover-half: #2a2a2a60;+ --hover-b: #333333;+ --unfoc: #1a1a1a;+ --msg: #333333;+ --hr: #ffffff20;+ --bd: #333333;+ --cm: #292929bb;+ --bar: #00000060;+ --fill: #ffffff25;+ --mm: #7f7f7f10;+ --s3d: #ffffff05;+ --href: #4cc2ff;+ --bg30: #00000030;+ --bggrey: #444444;+ --text: #eeeeee;+ --text2: #aaaaaa;++ /* Accent gradient */+ --theme-1: #ad6eca;+ --theme-2: #3b91d8;++ /* Mica material */+ --mica: linear-gradient(215deg, #3a2434, #1a2a4f);++ /* Glass */+ --glass-bg: rgba(26, 26, 46, 0.75);+ --glass-border: 1px solid rgba(255, 255, 255, 0.08);+ --glass-border-col: rgba(255, 255, 255, 0.08);+ --material-base: rgba(16, 16, 16, 0.6);+ --material-thick: rgba(20, 20, 32, 0.8);++ /* Blur presets */+ --blur-light: blur(12px) saturate(1.3);+ --blur-medium: blur(20px) saturate(1.5);+ --blur-heavy: blur(60px) saturate(3) contrast(0.8);++ /* Shadows */+ --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.15);+ --shadow-md: 0 8px 32px rgba(0, 0, 0, 0.3);+ --shadow-lg: 0 16px 64px rgba(0, 0, 0, 0.5);+ --shadow-focus: 0 12px 48px rgba(0, 0, 0, 0.6), 0 4px 16px rgba(0, 0, 0, 0.3);++ /* Sizing */+ --sizing-normal: 0.5rem;+ --sizing-huge: 1rem;+ --sizing-nano: 0.3rem;+ --siz-radius1: 0.5em;+ --siz-radius2: 0.35em;+ --siz-radius3: 0.2em;+ --spacing-normal: 0.3rem;+ --spacing-gap: 6px;++ /* Easing */+ --time1: 0.3s cubic-bezier(0.36, 0.38, 0, 0.94);+ --time2: 0.3s cubic-bezier(0.42, 1.67, 0.21, 0.9);+ --ease-decel: cubic-bezier(0.9, 0, 0.1, 1);++ /* Decor */+ --box-crisp: 1px solid #ffffff0c;+ --box-crisp-col: #ffffff0c;+ --colors-accent: rgb(97, 121, 255);++ --font-size-small: calc(var(--font-size-base) * 0.85);+ --font-size-normal: var(--font-size-base);+ --font-size-subheading: calc(var(--font-size-base) * 1.25);+ --font-size-big: calc(var(--font-size-base) * 2);++ color-scheme: dark;+}++[data-theme='light'] .os {+ --col-bg1: #f5f5f5;+ --col-bg2: #ececec;+ --col-bg3: #e0e0e0;+ --col-bgh: #d0d0d0;+ --col-txt1: #1a1a1a;+ --col-txt2: #444444;+ --col-txth: #000000;++ --bg: #ffffff;+ --bg50: #ffffff90;+ --bg70: #fefefeb7;+ --sd: #00000015;+ --card: #f6f6f6;+ --hover: #eaeaea;+ --hover-half: #eaeaea60;+ --hover-b: #dedede;+ --unfoc: #fbfbfb;+ --msg: #eeeeee;+ --hr: #6f6f6f20;+ --bd: #e5e5e5;+ --cm: #f7f7f7bb;+ --bar: #ffffff60;+ --fill: #ffffff80;+ --mm: #9f9f9f10;+ --s3d: #00000020;+ --href: #0067c0;+ --bg30: #ffffff30;+ --bggrey: #dddddd;+ --text: #000000;+ --text2: #444444;++ --mica: linear-gradient(215deg, #ffe7f6, #a9c3ff);++ --glass-bg: rgba(255, 255, 255, 0.75);+ --glass-border: 1px solid rgba(0, 0, 0, 0.06);+ --glass-border-col: rgba(0, 0, 0, 0.06);+ --material-base: rgba(245, 245, 245, 0.6);+ --material-thick: rgba(250, 250, 250, 0.85);++ --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.06);+ --shadow-md: 0 8px 24px rgba(0, 0, 0, 0.1);+ --shadow-lg: 0 12px 48px rgba(0, 0, 0, 0.15);+ --shadow-focus: 0 12px 40px rgba(0, 0, 0, 0.18), 0 4px 12px rgba(0, 0, 0, 0.08);++ --box-crisp: 1px solid rgba(0, 0, 0, 0.08);+ --box-crisp-col: rgba(0, 0, 0, 0.08);++ color-scheme: light;+}diff --git a/src/desktop/wm.js b/src/desktop/wm.jsnew file mode 100644index 000000000..6d613d316--- /dev/null+++ b/src/desktop/wm.js@@ -0,0 +1,472 @@+// Window manager: real draggable, resizable, snappable windows that frame+// same-origin three.ws pages (or render a native shell panel). Geometry and+// persistence rules live in layout.js so they stay unit-tested.++import {+ MAX_WINDOWS,+ clampRect,+ cascadeRect,+ cleanTitle,+ isInternalPath,+ resizeRect,+ snapRect,+ snapZone,+ workArea,+} from './layout.js';+import { icon } from './icons.js';++const HANDLES = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'];++export function createWM({ layer, getMetrics, renderNative, onChange, notify }) {+ const wins = new Map(); // app id -> window record+ let zTop = 10;+ let opened = 0;+ let focusedId = null;++ const snapGhost = document.createElement('div');+ snapGhost.className = 'win-snap';+ snapGhost.hidden = true;+ layer.append(snapGhost);++ const isMobile = () => getMetrics().mobile;+ const area = () => {+ const m = getMetrics();+ return workArea(m.vw, m.vh, m.menuH, m.dockH);+ };++ function emit() {+ onChange({+ windows: [...wins.values()].map(publicView),+ focus: focusedId,+ });+ }++ const publicView = (w) => ({+ id: w.app.id,+ app: w.app,+ title: w.title,+ minimized: w.min,+ maximized: w.max,+ rect: { ...w.rect },+ path: w.path,+ z: w.z,+ });++ function applyRect(w) {+ const r = isMobile() || w.max ? area() : w.rect;+ const s = w.el.style;+ s.left = `${r.x}px`;+ s.top = `${r.y}px`;+ s.width = `${r.w}px`;+ s.height = `${r.h}px`;+ w.el.classList.toggle('is-max', isMobile() || w.max);+ }++ function focus(id) {+ const w = wins.get(id);+ if (!w) return;+ if (w.min) restore(id);+ wins.forEach((o) => o.el.classList.toggle('is-focused', o === w));+ w.z = ++zTop;+ w.el.style.zIndex = String(w.z);+ w.lastFocus = Date.now();+ focusedId = id;+ // Pointer events inside an iframe never reach the parent document, so+ // give the frame real keyboard focus once the window is on top.+ if (w.frame && document.activeElement !== w.frame && !w.suppressFrameFocus) {+ try {+ w.frame.focus({ preventScroll: true });+ } catch {+ /* a frame that is not yet attached cannot take focus */+ }+ }+ emit();+ }++ function pickNextFocus() {+ const open = [...wins.values()].filter((w) => !w.min).sort((a, b) => b.z - a.z);+ focusedId = open[0] ? open[0].app.id : null;+ wins.forEach((o) => o.el.classList.toggle('is-focused', o.app.id === focusedId));+ }++ function minimize(id) {+ const w = wins.get(id);+ if (!w || w.min) return;+ w.min = true;+ w.el.classList.add('is-min');+ w.el.setAttribute('aria-hidden', 'true');+ w.el.inert = true;+ if (focusedId === id) pickNextFocus();+ emit();+ }++ function restore(id) {+ const w = wins.get(id);+ if (!w || !w.min) return;+ w.min = false;+ w.el.classList.remove('is-min');+ w.el.removeAttribute('aria-hidden');+ w.el.inert = false;+ }++ function toggleMax(id) {+ const w = wins.get(id);+ if (!w) return;+ w.max = !w.max;+ applyRect(w);+ w.maxBtn.setAttribute('aria-label', w.max ? 'Restore window' : 'Maximize window');+ w.maxBtn.title = w.max ? 'Restore' : 'Maximize';+ w.maxBtn.innerHTML = icon(w.max ? 'restore' : 'maximize', 13);+ emit();+ }++ function close(id) {+ const w = wins.get(id);+ if (!w) return;+ w.el.classList.add('is-closing');+ wins.delete(id);+ const done = () => w.el.remove();+ if (matchMedia('(prefers-reduced-motion: reduce)').matches) done();+ else {+ w.el.addEventListener('animationend', done, { once: true });+ setTimeout(done, 260);+ }+ if (focusedId === id) pickNextFocus();+ emit();+ }++ function evictIfFull() {+ if (wins.size < MAX_WINDOWS) return;+ const victim = [...wins.values()].sort((a, b) => (a.min === b.min ? a.lastFocus - b.lastFocus : a.min ? -1 : 1))[0];+ if (!victim) return;+ notify(`Closed ${victim.title} to keep the desktop responsive (${MAX_WINDOWS} windows max).`);+ close(victim.app.id);+ }++ function frameUrl(app, path) {+ return isInternalPath(path) ? path : app.href;+ }++ function buildWindow(app, opts) {+ const w = {+ app,+ title: app.title,+ path: app.native ? null : frameUrl(app, opts.path),+ min: false,+ max: !!opts.max,+ lastFocus: Date.now(),+ z: 0,+ rect: null,+ frame: null,+ };+ const el = document.createElement('section');+ el.className = 'win';+ el.dataset.app = app.id;+ el.style.setProperty('--hue', String(app.hue));+ el.setAttribute('role', 'dialog');+ el.setAttribute('aria-label', app.title);++ const bar = document.createElement('header');+ bar.className = 'win-bar';+ bar.innerHTML =+ `<div class="win-title"><span class="win-glyph">${icon(app.icon, 15)}</span><span class="win-name"></span></div>` ++ `<div class="win-tools"></div>` ++ `<div class="win-ctl">` ++ `<button type="button" class="win-btn win-min" aria-label="Minimize window" title="Minimize">${icon('minimize', 14)}</button>` ++ `<button type="button" class="win-btn win-maxbtn" aria-label="Maximize window" title="Maximize">${icon('maximize', 13)}</button>` ++ `<button type="button" class="win-btn win-close" aria-label="Close window" title="Close">${icon('close', 15)}</button>` ++ `</div>`;+ bar.querySelector('.win-name').textContent = app.title;+ const tools = bar.querySelector('.win-tools');+ w.maxBtn = bar.querySelector('.win-maxbtn');++ if (!app.native) {+ const reload = document.createElement('button');+ reload.type = 'button';+ reload.className = 'win-tool';+ reload.title = 'Reload';+ reload.setAttribute('aria-label', 'Reload');+ reload.innerHTML = icon('reload', 15);+ reload.addEventListener('click', () => reloadFrame(w));+ const ext = document.createElement('a');+ ext.className = 'win-tool';+ ext.title = 'Open in a browser tab';+ ext.setAttribute('aria-label', 'Open in a browser tab');+ ext.target = '_blank';+ ext.rel = 'noopener';+ ext.href = w.path;+ ext.innerHTML = icon('external', 15);+ w.extLink = ext;+ tools.append(reload, ext);+ }++ const body = document.createElement('div');+ body.className = 'win-body';+ el.append(bar, body);+ HANDLES.forEach((h) => {+ const g = document.createElement('div');+ g.className = `win-grip win-grip-${h}`;+ g.dataset.handle = h;+ el.append(g);+ });++ if (app.native) {+ renderNative(app, body, w);+ } else {+ const skeleton = document.createElement('div');+ skeleton.className = 'win-loading';+ skeleton.innerHTML = `<span class="win-loading-bar"></span><span class="win-loading-label">Opening ${escapeHtml(app.title)}</span>`;+ const frame = document.createElement('iframe');+ frame.className = 'win-frame';+ // The name is how a framed page knows it is inside the desktop and+ // drops its own site header (public/nav.js).+ frame.name = `tws-os:${app.id}`;+ frame.title = app.title;+ frame.allow = 'clipboard-read; clipboard-write; fullscreen; microphone; camera; xr-spatial-tracking; web-share';+ frame.setAttribute('allowfullscreen', '');+ frame.addEventListener('load', () => onFrameLoad(w, skeleton));+ frame.src = w.path;+ w.frame = frame;+ w.skeleton = skeleton;+ body.append(frame, skeleton);+ }++ w.el = el;+ w.bar = bar;+ w.body = body;+ wireChrome(w);+ return w;+ }++ function reloadFrame(w) {+ if (!w.frame) return;+ w.skeleton.hidden = false;+ w.skeleton.classList.remove('is-error');+ try {+ w.frame.contentWindow.location.reload();+ } catch {+ w.frame.src = w.path;+ }+ }++ function onFrameLoad(w, skeleton) {+ skeleton.hidden = true;+ try {+ const doc = w.frame.contentDocument;+ const loc = w.frame.contentWindow.location;+ if (loc.origin !== location.origin) return;+ const next = loc.pathname + loc.search + loc.hash;+ if (isInternalPath(next) && next !== 'about:blank') {+ w.path = next;+ w.extLink.href = next;+ }+ const t = cleanTitle(doc.title, w.app.title);+ w.title = t;+ w.bar.querySelector('.win-name').textContent = t;+ w.el.setAttribute('aria-label', t);+ // Links inside a window that point at the desktop root would nest the+ // desktop inside itself; send those to the top frame.+ if (loc.pathname === '/' && doc.getElementById('os')) {+ w.frame.src = w.app.href;+ }+ } catch {+ /* cross-origin navigation: keep the app title */+ }+ emit();+ }++ function wireChrome(w) {+ const { el, bar } = w;+ const id = w.app.id;+ bar.querySelector('.win-close').addEventListener('click', () => close(id));+ bar.querySelector('.win-min').addEventListener('click', () => minimize(id));+ w.maxBtn.addEventListener('click', () => toggleMax(id));+ bar.addEventListener('dblclick', (e) => {+ if (!e.target.closest('.win-ctl, .win-tools')) toggleMax(id);+ });+ el.addEventListener('pointerdown', () => focus(id), true);+ el.addEventListener('keydown', (e) => {+ if (e.key === 'Escape' && w.app.native) close(id);+ });++ bar.addEventListener('pointerdown', (e) => {+ if (e.button !== 0 || e.target.closest('.win-ctl, .win-tools') || isMobile()) return;+ startDrag(w, e);+ });+ el.querySelectorAll('.win-grip').forEach((g) =>+ g.addEventListener('pointerdown', (e) => {+ if (e.button !== 0 || w.max || isMobile()) return;+ startResize(w, g.dataset.handle, e);+ }),+ );+ }++ function startDrag(w, e) {+ const a = area();+ const wasMax = w.max;+ let origin = { ...w.rect };+ const px = e.clientX;+ const py = e.clientY;+ if (wasMax) {+ // Dragging a maximized window pulls it back to its restored size,+ // keeping the grab point proportional under the cursor.+ const ratio = (px - a.x) / a.w;+ origin = { ...w.rect, x: Math.round(px - w.rect.w * ratio), y: py - 16 };+ w.max = false;+ applyRect(w);+ }+ let zone = null;+ layer.classList.add('is-dragging');+ w.el.classList.add('is-moving');+ w.bar.setPointerCapture(e.pointerId);+ const move = (ev) => {+ const next = clampRect({ ...origin, x: origin.x + (ev.clientX - px), y: origin.y + (ev.clientY - py) }, a);+ w.rect = next;+ applyRect(w);+ zone = snapZone(ev.clientX, ev.clientY, a);+ const g = snapRect(zone, a);+ snapGhost.hidden = !g;+ if (g) Object.assign(snapGhost.style, { left: `${g.x}px`, top: `${g.y}px`, width: `${g.w}px`, height: `${g.h}px` });+ };+ const up = () => {+ w.bar.releasePointerCapture(e.pointerId);+ w.bar.removeEventListener('pointermove', move);+ w.bar.removeEventListener('pointerup', up);+ w.bar.removeEventListener('pointercancel', up);+ layer.classList.remove('is-dragging');+ w.el.classList.remove('is-moving');+ snapGhost.hidden = true;+ if (zone === 'max') {+ w.max = true;+ } else if (zone) {+ w.rect = snapRect(zone, a);+ }+ applyRect(w);+ emit();+ };+ w.bar.addEventListener('pointermove', move);+ w.bar.addEventListener('pointerup', up);+ w.bar.addEventListener('pointercancel', up);+ }++ function startResize(w, handle, e) {+ const a = area();+ const start = { ...w.rect };+ const px = e.clientX;+ const py = e.clientY;+ const grip = e.currentTarget;+ layer.classList.add('is-dragging');+ grip.setPointerCapture(e.pointerId);+ const move = (ev) => {+ w.rect = resizeRect(start, handle, ev.clientX - px, ev.clientY - py, a);+ applyRect(w);+ };+ const up = () => {+ grip.releasePointerCapture(e.pointerId);+ grip.removeEventListener('pointermove', move);+ grip.removeEventListener('pointerup', up);+ grip.removeEventListener('pointercancel', up);+ layer.classList.remove('is-dragging');+ emit();+ };+ grip.addEventListener('pointermove', move);+ grip.addEventListener('pointerup', up);+ grip.addEventListener('pointercancel', up);+ }++ function open(app, opts = {}) {+ const existing = wins.get(app.id);+ if (existing) {+ if (opts.path && !app.native && isInternalPath(opts.path) && opts.path !== existing.path) {+ existing.path = opts.path;+ existing.frame.src = opts.path;+ existing.extLink.href = opts.path;+ }+ focus(app.id);+ return existing;+ }+ evictIfFull();+ const w = buildWindow(app, opts);+ const a = area();+ w.rect = opts.rect ? clampRect(opts.rect, a) : cascadeRect(opened++, a, app.size);+ wins.set(app.id, w);+ applyRect(w);+ layer.append(w.el);+ if (opts.min) {+ w.min = true;+ w.el.classList.add('is-min');+ w.el.inert = true;+ }+ if (!opts.quiet) w.el.classList.add('is-opening');+ w.suppressFrameFocus = !!opts.quiet;+ if (!opts.min && !opts.quiet) focus(app.id);+ else emit();+ return w;+ }++ function relayout() {+ const a = area();+ wins.forEach((w) => {+ if (!w.max) w.rect = clampRect(w.rect, a);+ applyRect(w);+ });+ }++ function snapshot() {+ return {+ windows: [...wins.values()]+ .sort((x, y) => x.z - y.z)+ .map((w) => ({+ app: w.app.id,+ ...w.rect,+ max: w.max,+ min: w.min,+ path: w.app.native ? null : w.path,+ })),+ focus: focusedId,+ };+ }++ function cycle(dir = 1) {+ const order = [...wins.values()].sort((a, b) => a.lastFocus - b.lastFocus);+ if (order.length < 2) return;+ const next = dir > 0 ? order[0] : order[order.length - 2];+ focus(next.app.id);+ }++ // A click inside an iframe moves document focus to the frame without any+ // pointer event reaching us, so follow focus to keep z-order truthful.+ window.addEventListener('blur', () => {+ setTimeout(() => {+ const a = document.activeElement;+ if (!a || a.tagName !== 'IFRAME') return;+ const owner = [...wins.values()].find((w) => w.frame === a);+ if (owner && owner.app.id !== focusedId) {+ owner.suppressFrameFocus = true;+ focus(owner.app.id);+ owner.suppressFrameFocus = false;+ }+ }, 0);+ });++ return {+ open,+ close,+ minimize,+ restore,+ focus,+ toggleMax,+ cycle,+ relayout,+ snapshot,+ reload: (id) => wins.has(id) && reloadFrame(wins.get(id)),+ has: (id) => wins.has(id),+ focused: () => focusedId,+ list: () => [...wins.values()].map(publicView),+ closeAll: () => [...wins.keys()].forEach(close),+ };+}++function escapeHtml(s) {+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+}diff --git a/tests/desktop-layout.test.js b/tests/desktop-layout.test.jsnew file mode 100644index 000000000..7d67ce98b--- /dev/null+++ b/tests/desktop-layout.test.js@@ -0,0 +1,358 @@+import { describe, it, expect } from 'vitest';+import {+ workArea,+ clampRect,+ snapZone,+ snapRect,+ cascadeRect,+ resizeRect,+ isInternalPath,+ cleanTitle,+ rankItems,+ deepLinkApp,+ sanitizeState,+ pageAppId,+ pagePathOf,+ MIN_W,+ MIN_H,+ MAX_WINDOWS,+} from '../src/desktop/layout.js';++const area = workArea(1440, 900, 30, 84);++describe('desktop layout geometry', () => {+ it('reserves room for the menu bar and the dock', () => {+ expect(area).toEqual({ x: 0, y: 30, w: 1440, h: 786 });+ });++ it('keeps a dragged window reachable by its title bar', () => {+ const r = clampRect({ x: -5000, y: -400, w: 600, h: 400 }, area);+ expect(r.y).toBe(area.y);+ expect(r.x + r.w).toBeGreaterThanOrEqual(96);+ const far = clampRect({ x: 9000, y: 9000, w: 600, h: 400 }, area);+ expect(far.x).toBeLessThanOrEqual(area.w - 96);+ expect(far.y).toBeLessThanOrEqual(area.y + area.h - 36);+ });++ it('enforces minimum and maximum window sizes', () => {+ const tiny = clampRect({ x: 10, y: 40, w: 10, h: 10 }, area);+ expect([tiny.w, tiny.h]).toEqual([MIN_W, MIN_H]);+ const huge = clampRect({ x: 0, y: 40, w: 99999, h: 99999 }, area);+ expect([huge.w, huge.h]).toEqual([area.w, area.h]);+ });++ it('detects snap zones at the edges only', () => {+ expect(snapZone(700, 32, area)).toBe('max');+ expect(snapZone(2, 400, area)).toBe('left');+ expect(snapZone(1438, 400, area)).toBe('right');+ expect(snapZone(700, 400, area)).toBeNull();+ });++ it('snaps to halves that tile the work area exactly', () => {+ const l = snapRect('left', area);+ const r = snapRect('right', area);+ expect(l.w + r.w).toBe(area.w);+ expect(r.x).toBe(l.x + l.w);+ expect(snapRect('max', area)).toEqual({ x: 0, y: 30, w: 1440, h: 786 });+ expect(snapRect(null, area)).toBeNull();+ });++ it('cascades new windows to different positions that stay on screen', () => {+ const seen = new Set();+ for (let n = 0; n < MAX_WINDOWS; n++) {+ const r = cascadeRect(n, area, { w: 900, h: 600 });+ seen.add(`${r.x},${r.y}`);+ expect(r.x).toBeGreaterThanOrEqual(0);+ expect(r.y).toBeGreaterThanOrEqual(area.y);+ expect(r.y + r.h).toBeLessThanOrEqual(area.y + area.h);+ }+ expect(seen.size).toBeGreaterThan(1);+ });++ it('shrinks a window larger than a small viewport instead of overflowing', () => {+ const small = workArea(390, 700, 30, 70);+ const r = cascadeRect(0, small, { w: 900, h: 600 });+ expect(r.w).toBeLessThanOrEqual(small.w);+ expect(r.h).toBeLessThanOrEqual(small.h);+ });+});++describe('resizeRect', () => {+ const start = { x: 200, y: 100, w: 600, h: 400 };+ it('grows from the south-east corner', () => {+ expect(resizeRect(start, 'se', 50, 30, area)).toEqual({ x: 200, y: 100, w: 650, h: 430 });+ });+ it('moves the origin when dragging the west or north edge', () => {+ const r = resizeRect(start, 'nw', -40, -20, area);+ expect(r).toEqual({ x: 160, y: 80, w: 640, h: 420 });+ });+ it('never shrinks below the minimum and pins the opposite edge', () => {+ const r = resizeRect(start, 'w', 5000, 0, area);+ expect(r.w).toBe(MIN_W);+ expect(r.x + r.w).toBe(start.x + start.w);+ });+ it('never lets the top edge cross the menu bar', () => {+ const r = resizeRect({ x: 0, y: 40, w: 600, h: 400 }, 'n', 0, -500, area);+ expect(r.y).toBe(area.y);+ });+});++describe('internal paths and titles', () => {+ it('accepts same-origin absolute paths only', () => {+ expect(isInternalPath('/forge')).toBe(true);+ expect(isInternalPath('/discover?q=a')).toBe(true);+ expect(isInternalPath('//evil.example/x')).toBe(false);+ expect(isInternalPath('https://example.com')).toBe(false);+ expect(isInternalPath('javascript:alert(1)')).toBe(false);+ expect(isInternalPath('/a\\b')).toBe(false);+ expect(isInternalPath(null)).toBe(false);+ });++ it('shortens page titles for window chrome', () => {+ expect(cleanTitle('Forge · three.ws', 'x')).toBe('Forge');+ expect(cleanTitle('Marketplace | three.ws', 'x')).toBe('Marketplace');+ expect(cleanTitle('three.ws - Pricing', 'x')).toBe('Pricing');+ expect(cleanTitle('', 'Fallback')).toBe('Fallback');+ });+});++describe('rankItems', () => {+ const items = [+ { title: 'Marketplace', keywords: ['skills', 'buy'], desc: 'Buy agent skills' },+ { title: 'Forge', keywords: ['text to 3d', 'model'], desc: 'Generate models' },+ { title: 'Agent Studio', keywords: ['persona'], desc: 'Author brains' },+ { title: 'Create', keywords: ['agent', 'avatar'], desc: 'Make an agent' },+ ];+ it('keeps input order for an empty query', () => {+ expect(rankItems(' ', items).map((i) => i.title)).toEqual(items.map((i) => i.title));+ });+ it('puts a title prefix ahead of keyword and description hits', () => {+ const out = rankItems('agent', items).map((i) => i.title);+ expect(out[0]).toBe('Agent Studio');+ expect(out).toContain('Create');+ expect(out).toContain('Marketplace');+ });+ it('matches keywords and drops non-matches', () => {+ expect(rankItems('model', items).map((i) => i.title)).toEqual(['Forge']);+ expect(rankItems('zzzz', items)).toEqual([]);+ });+});++describe('deep links', () => {+ it('reads ?app= and #app=', () => {+ expect(deepLinkApp('?app=Forge', '')).toBe('forge');+ expect(deepLinkApp('', '#app=discover')).toBe('discover');+ expect(deepLinkApp('?x=1', '#nope')).toBeNull();+ });+});++describe('sanitizeState', () => {+ const known = new Set(['forge', 'create', 'chat']);+ const good = { app: 'forge', x: 10, y: 40, w: 800, h: 500 };++ it('round-trips a valid state', () => {+ const s = sanitizeState({ v: 1, windows: [good], focus: 'forge' }, known);+ expect(s.windows).toHaveLength(1);+ expect(s.focus).toBe('forge');+ });+ it('survives garbage, wrong versions and bad JSON', () => {+ expect(sanitizeState('{not json', known).windows).toEqual([]);+ expect(sanitizeState({ v: 99, windows: [good] }, known).windows).toEqual([]);+ expect(sanitizeState(null, known).windows).toEqual([]);+ expect(sanitizeState({ v: 1, windows: 'x' }, known).windows).toEqual([]);+ });+ it('drops unknown apps, duplicates, non-numeric rects and external paths', () => {+ const s = sanitizeState(+ {+ v: 1,+ windows: [+ { ...good, app: 'nope' },+ good,+ good,+ { ...good, app: 'create', x: 'a' },+ { ...good, app: 'chat', path: 'https://evil.example' },+ ],+ focus: 'create',+ },+ known,+ );+ expect(s.windows.map((w) => w.app)).toEqual(['forge', 'chat']);+ expect(s.windows[1].path).toBeNull();+ expect(s.focus).toBeNull();+ });+ it('restores generic page windows only for same-origin paths', () => {+ const s = sanitizeState(+ {+ v: 1,+ windows: [+ { ...good, app: 'page:/pricing' },+ { ...good, app: 'page://evil.example/x' },+ { ...good, app: 'page:https://evil.example' },+ ],+ },+ known,+ );+ expect(s.windows.map((w) => w.app)).toEqual(['page:/pricing']);+ expect(pagePathOf('page:/pricing')).toBe('/pricing');+ expect(pagePathOf('forge')).toBeNull();+ expect(pageAppId('/pricing')).toBe('page:/pricing');+ });+ it('caps the number of restored windows', () => {+ const ids = new Set(Array.from({ length: 20 }, (_, i) => `a${i}`));+ const windows = [...ids].map((app) => ({ ...good, app }));+ expect(sanitizeState({ v: 1, windows }, ids).windows).toHaveLength(MAX_WINDOWS);+ });+});++import {+ marqueeRect,+ rectsIntersect,+ iconsInRect,+ gridSize,+ cellAt,+ nearestFreeCell,+ arrangeIcons,+ moveIcons,+ reflowIcons,+ addIcons,+ sanitizeIcons,+ sanitizePrefs,+ initialsOf,+ storageBytes,+ formatBytes,+ parseSessionImport,+ DEFAULT_PREFS,+} from '../src/desktop/layout.js';++describe('desktop icon grid', () => {+ const cell = { w: 100, h: 100 };+ const grid = { cols: 4, rows: 3 };++ it('builds a marquee from any drag direction', () => {+ expect(marqueeRect(50, 80, 10, 20)).toEqual({ x: 10, y: 20, w: 40, h: 60 });+ });+ it('detects overlap but not mere touching', () => {+ expect(rectsIntersect({ x: 0, y: 0, w: 10, h: 10 }, { x: 9, y: 9, w: 5, h: 5 })).toBe(true);+ expect(rectsIntersect({ x: 0, y: 0, w: 10, h: 10 }, { x: 10, y: 0, w: 5, h: 5 })).toBe(false);+ });+ it('selects the icons under the marquee', () => {+ const items = [+ { id: 'a', col: 0, row: 0 },+ { id: 'b', col: 1, row: 0 },+ { id: 'c', col: 3, row: 2 },+ ];+ expect(iconsInRect({ x: 50, y: 10, w: 100, h: 30 }, items, cell)).toEqual(['a', 'b']);+ expect(iconsInRect({ x: 350, y: 250, w: 10, h: 10 }, items, cell)).toEqual(['c']);+ });+ it('sizes the grid and clamps pointer positions into it', () => {+ expect(gridSize(450, 320, cell)).toEqual(grid);+ expect(gridSize(10, 10, cell)).toEqual({ cols: 1, rows: 1 });+ expect(cellAt(9999, -50, cell, grid)).toEqual({ col: 3, row: 0 });+ });+ it('finds the nearest free cell and reports a full grid', () => {+ const taken = new Set(['1,1']);+ expect(nearestFreeCell(1, 1, grid, taken)).toEqual({ col: 0, row: 1 });+ const all = new Set();+ for (let c = 0; c < 4; c++) for (let r = 0; r < 3; r++) all.add(`${c},${r}`);+ expect(nearestFreeCell(0, 0, grid, all)).toBeNull();+ });+ it('arranges column-major', () => {+ expect(arrangeIcons(['a', 'b', 'c', 'd'], grid)).toEqual([+ { id: 'a', col: 0, row: 0 },+ { id: 'b', col: 0, row: 1 },+ { id: 'c', col: 0, row: 2 },+ { id: 'd', col: 1, row: 0 },+ ]);+ });+ it('moves a group by a delta without ever stacking two icons', () => {+ const items = arrangeIcons(['a', 'b', 'c'], grid);+ const out = moveIcons(items, ['a', 'b'], 1, 0, grid);+ expect(out.find((i) => i.id === 'a')).toMatchObject({ col: 1, row: 0 });+ expect(out.find((i) => i.id === 'c')).toMatchObject({ col: 0, row: 2 });+ const cells = new Set(out.map((i) => `${i.col},${i.row}`));+ expect(cells.size).toBe(3);+ });+ it('drops onto an occupied cell by taking the nearest free one', () => {+ const items = [+ { id: 'a', col: 0, row: 0 },+ { id: 'b', col: 1, row: 0 },+ ];+ const out = moveIcons(items, ['a'], 1, 0, grid);+ expect(`${out[0].col},${out[0].row}`).not.toBe('1,0');+ });+ it('reflows icons that no longer fit after the grid shrinks', () => {+ const items = [+ { id: 'a', col: 0, row: 0 },+ { id: 'b', col: 3, row: 2 },+ ];+ const out = reflowIcons(items, { cols: 2, rows: 2 });+ expect(out).toHaveLength(2);+ out.forEach((i) => {+ expect(i.col).toBeLessThan(2);+ expect(i.row).toBeLessThan(2);+ });+ });+ it('adds only missing icons', () => {+ const out = addIcons([{ id: 'a', col: 0, row: 0 }], ['a', 'b'], grid);+ expect(out.map((i) => i.id)).toEqual(['a', 'b']);+ });+ it('rejects corrupt persisted placement', () => {+ const known = (id) => ['a', 'b'].includes(id);+ const out = sanitizeIcons(+ [+ { id: 'a', col: 0, row: 0 },+ { id: 'a', col: 1, row: 1 },+ { id: 'b', col: 0, row: 0 },+ { id: 'zz', col: 2, row: 2 },+ { id: 'b', col: -1, row: 0 },+ { id: 'b', col: 1.5, row: 0 },+ { id: 'b', col: 2, row: 1 },+ ],+ known,+ );+ expect(out).toEqual([+ { id: 'a', col: 0, row: 0 },+ { id: 'b', col: 2, row: 1 },+ ]);+ expect(sanitizeIcons('nope', known)).toEqual([]);+ });+});++describe('preferences and session export', () => {+ const walls = ['aurora', 'midnight'];+ it('falls back per field and clamps the name', () => {+ const p = sanitizePrefs({ wall: 'nope', accent: 'red', mode: 'light', iconSize: 'huge', name: ' <b>Ada</b> '.repeat(10), avatarHue: -30 }, walls);+ expect(p.wall).toBe(DEFAULT_PREFS.wall);+ expect(p.accent).toBe(DEFAULT_PREFS.accent);+ expect(p.mode).toBe('light');+ expect(p.iconSize).toBe('medium');+ expect(p.name.length).toBeLessThanOrEqual(40);+ expect(p.name).not.toMatch(/[<>]/);+ expect(p.avatarHue).toBe(330);+ });+ it('survives bad JSON', () => {+ expect(sanitizePrefs('{oops', walls)).toEqual(DEFAULT_PREFS);+ expect(sanitizePrefs(null, walls)).toEqual(DEFAULT_PREFS);+ });+ it('derives initials', () => {+ expect(initialsOf('ada lovelace')).toBe('AL');+ expect(initialsOf('Ada')).toBe('A');+ expect(initialsOf('')).toBe('?');+ });+ it('counts and formats storage', () => {+ expect(storageBytes([['tws:a', 'xy'], ['other', 'zzzz']], 'tws:')).toBe((5 + 2) * 2);+ expect(formatBytes(512)).toBe('512 B');+ expect(formatBytes(2048)).toBe('2.0 KB');+ expect(formatBytes(3 * 1024 * 1024)).toBe('3.00 MB');+ });+ it('only accepts a well-formed session export and ignores foreign keys', () => {+ const good = JSON.stringify({ kind: 'three.ws-desktop-session', v: 1, items: { 'tws:prefs': '{}', 'twx_theme': 'light', 'evil': 'x' } });+ const r = parseSessionImport(good);+ expect(r.ok).toBe(true);+ expect(Object.keys(r.items)).toEqual(['tws:prefs']);+ expect(parseSessionImport('{').ok).toBe(false);+ expect(parseSessionImport(JSON.stringify({ kind: 'x', v: 1, items: {} })).ok).toBe(false);+ expect(parseSessionImport(JSON.stringify({ kind: 'three.ws-desktop-session', v: 1, items: { evil: 'x' } })).ok).toBe(false);+ expect(parseSessionImport('x'.repeat(3 * 1024 * 1024)).ok).toBe(false);+ });+});diff --git a/tests/desktop-page.test.js b/tests/desktop-page.test.jsnew file mode 100644index 000000000..10711efe3--- /dev/null+++ b/tests/desktop-page.test.js@@ -0,0 +1,42 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import { APPS, NATIVE_APPS, ALL_APPS } from '../src/desktop/apps.js';+import { isInternalPath } from '../src/desktop/layout.js';++const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const read = (p) => readFileSync(resolve(root, p), 'utf8');+const vercel = JSON.parse(read('vercel.json'));++describe('desktop page', () => {+ const html = read('pages/desktop.html');++ it('lists every windowed app as a crawlable link', () => {+ for (const app of APPS) expect(html, app.title).toContain(`href="${app.href}"`);+ expect(html).toContain('href="/classic"');+ });++ it('only registers apps with same-origin paths and unique ids', () => {+ for (const a of APPS) expect(isInternalPath(a.href), a.id).toBe(true);+ const ids = ALL_APPS.map((a) => a.id);+ expect(new Set(ids).size).toBe(ids.length);+ NATIVE_APPS.forEach((a) => expect(a.native).toBe(true));+ });++ it('honours the saved classic-view preference', () => {+ expect(html).toContain("localStorage.getItem('tws:view')==='classic'");+ expect(html).toContain("localStorage.setItem('tws:view','desktop')");+ });+});++describe('desktop routing', () => {+ const route = (src) => vercel.routes.find((r) => r.src === src);+ it('serves the desktop at / and the previous homepage at /classic', () => {+ expect(route('/').dest).toBe('/desktop.html');+ expect(route('/classic/?').dest).toBe('/home.html');+ });+ it('offers the way back from the classic page', () => {+ expect(read('pages/home.html')).toContain('href="/?view=desktop"');+ });+});diff --git a/vercel.json b/vercel.jsonindex 6fdd91d88..47a550531 100644--- a/vercel.json+++ b/vercel.json@@ -6561,6 +6561,10 @@},{"src": "/",+ "dest": "/desktop.html"+ },+ {+ "src": "/classic/?","dest": "/home.html"},{diff --git a/vite.config.js b/vite.config.jsindex 2bfbeb1f3..91eee772f 100644--- a/vite.config.js+++ b/vite.config.js@@ -691,6 +691,7 @@ const appConfig = {preflight: resolve(__dirname, 'pages/preflight.html'),'app-next': resolve(__dirname, 'pages/app-next.html'),home: resolve(__dirname, 'pages/home.html'),+ desktop: resolve(__dirname, 'pages/desktop.html'),'what-is': resolve(__dirname, 'pages/what-is.html'),atlas: resolve(__dirname, 'pages/atlas.html'),tour: resolve(__dirname, 'pages/tour.html'),@@ -2089,7 +2090,9 @@ const appConfig = {'/demo/avatar-os/': resolve(root, 'public/demo/avatar-os/index.html'),'/demo/coin': resolve(root, 'public/demo/coin/index.html'),'/demo/coin/': resolve(root, 'public/demo/coin/index.html'),- '/': resolve(root, 'pages/home.html'),+ '/': resolve(root, 'pages/desktop.html'),+ '/classic': resolve(root, 'pages/home.html'),+ '/classic/': resolve(root, 'pages/home.html'),'/home': resolve(root, 'pages/home.html'),'/what-is': resolve(root, 'pages/what-is.html'),'/what-is/': resolve(root, 'pages/what-is.html'),@@ -2996,6 +2999,7 @@ const appConfig = {'agent-token-page.html','nav.html','footer.html',+ 'desktop.html',]);const filename = (ctx.filename || ctx.path || '').replace(/\\/g, '/')@@ -3222,6 +3226,7 @@ const appConfig = {// inline script; fragments must never get it.'nav.html','footer.html',+ 'desktop.html',]);const filename = (ctx.filename || ctx.path || '').replace(/\\/g, '/')