Skip to content

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.

fix(settings): add the Connections tab so bot pairing, notification and X connect links stop landing on a 404

nirholasb6e90a07d8e7
diff --git a/data/changelog.json b/data/changelog.json
index dcc67aa26..43f80958e 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, 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-25",
+ "title": "Chat pairing and X connect returns land on a working Connections page",
+ "summary": "The /settings/connections link that the Telegram and Discord bots, the notification settings and the X connect flow all send people to returned a 404. Every /settings subpath now serves the settings app, and a new Connections tab lists paired chats, toggles notifications, picks the default agent, unpairs, issues a pairing code and redeems the code a bot prints.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/settings/connections"
+ },
{
"date": "2026-10-25",
"title": "Paid Solana routes fall back to self-pay instead of advertising a sponsor that cannot settle",
diff --git a/docs/ux-flows/11-account-dashboard.md b/docs/ux-flows/11-account-dashboard.md
index 92cddb789..a5bb0d71b 100644
--- a/docs/ux-flows/11-account-dashboard.md
+++ b/docs/ux-flows/11-account-dashboard.md
@@ -164,7 +164,7 @@ Shared auth concepts:
5a. **(optional) Sign-in methods** (`#sign-in-methods`): one row per way into the account (password, email code, wallets, Google, Telegram). **Link Google** is a top-level navigation to `/api/auth/google/start?intent=link` and back with `?google=<outcome>`, shown as a toast and then stripped from the URL. Telegram links in the browser (`/api/auth/telegram/start?intent=link`) or **from phone**: `POST /api/auth/telegram/magic` returns a one-time deep link and QR, and the page polls `/api/auth/telegram/poll` until the bot has seen it. **Unlink** (`POST /api/auth/google/unlink` or `/api/auth/telegram/unlink`) is refused when it is the only way in, and otherwise needs the password or a fresh re-authentication with that provider (`intent=reauth`).
5b. **(optional) Connected apps** (`#connected-apps`, deep-linked from the OAuth consent screen and three.ws Desktop): one row per app holding a live refresh token (the desktop app, the CLI, MCP clients) with its scopes in plain words, last used and authorized times. **Revoke** → confirm → `DELETE /api/oauth/grants?client_id=` → toast and the row drops; the app loses access when its current token expires (within an hour). Empty state: "No connected apps".
6. **(optional) Notifications:** "Mark all read" → `POST /api/notifications/read-all` → toast. The inbox covers the full bell vocabulary (sales, purchases, follows, remixes, DMs, coin-launch graduations, IRL, market, account).
- 6b. **(optional) Notification preferences:** a category × channel matrix driven by the server response (`categories` + `channels`, default channels in-app / push / email / Telegram / Discord / avatar). The **Avatar** column routes a category to the corner companion, which walks on screen and says the message out loud while the user is on the site; a hint line under the table explains it, and it can be muted per browser from the bubble's "Turn off" control. The response also carries `type_categories` (notification type → category), so the client-side herald (`src/notification-herald.js`) gates the avatar channel with the same mapping the server uses for push and email. Toggles flip locally; a single **Save notification preferences** button sends the whole matrix via `PUT /api/notifications/preferences` `{ categories }` → toast "Notification preferences saved". Per-category `lockedChannels` render disabled (in-app is typically locked on); the Telegram and Discord columns stay disabled until the account has a chat paired with notifications on through the chat gateways (`/api/gateway/connections`; the response's `gateways` block counts them) or, for Telegram only, a legacy `telegram_chat_id`. Their disabled tooltip reads "Pair a Telegram (or Discord) chat at /settings/connections to enable", but no page is served at that path yet, so pairing currently happens through the gateway API and the bot's `/link <code>` command. A footer reports subscribed push devices, counting Web Push subscriptions and iOS (APNs) devices together (`push.subscribed_devices`, with `push.ios_devices` broken out).
+ 6b. **(optional) Notification preferences:** a category × channel matrix driven by the server response (`categories` + `channels`, default channels in-app / push / email / Telegram / Discord / avatar). The **Avatar** column routes a category to the corner companion, which walks on screen and says the message out loud while the user is on the site; a hint line under the table explains it, and it can be muted per browser from the bubble's "Turn off" control. The response also carries `type_categories` (notification type → category), so the client-side herald (`src/notification-herald.js`) gates the avatar channel with the same mapping the server uses for push and email. Toggles flip locally; a single **Save notification preferences** button sends the whole matrix via `PUT /api/notifications/preferences` `{ categories }` → toast "Notification preferences saved". Per-category `lockedChannels` render disabled (in-app is typically locked on); the Telegram and Discord columns stay disabled until the account has a chat paired with notifications on through the chat gateways (`/api/gateway/connections`; the response's `gateways` block counts them) or, for Telegram only, a legacy `telegram_chat_id`. Their disabled tooltip reads "Pair a Telegram (or Discord) chat at /settings/connections to enable"; `/settings/connections` now serves the pairing UI directly (paired chats, notify toggle, default agent, unpair, issue a code, and redeem a bot code from `?code=`). A footer reports subscribed push devices, counting Web Push subscriptions and iOS (APNs) devices together (`push.subscribed_devices`, with `push.ios_devices` broken out).
6c. **(optional) Avatar storage (R2 vs IPFS):** one row per avatar the caller owns, listing its size, its R2 copy, and its IPFS state. `GET /api/avatars/mine` carries a flattened `storage` block (`primary`, `r2_present`, `ipfs_pinned`, `ipfs_cid`, `ipfs_pinned_at`) so the panel needs no per-avatar request. **Pin to IPFS** → `POST /api/avatars/:id/pin-ipfs` reads the object out of R2 and pins it through the provider chain (Pinata, then web3.storage), and the row repaints with the CID linked to a public gateway. A deployment with no pinning provider answers `stub: true` with a `stub:` pseudo-CID: that is a recorded content hash, not a pin, and the row says exactly that ("Content hash only") instead of linking a CID that resolves nowhere. The **R2 / IPFS** segmented control sets which copy a viewer resolves first; it re-reads `GET /api/avatars/:id/storage-mode` and writes the whole record back with `PUT`, because the schema is whole-object and the server owns the attestation block. The IPFS half stays disabled until a real pin exists.
7. **(optional) Default network:** Base/Solana/Polygon → `localStorage['twx_default_network']` + best-effort `PATCH /api/dashboard/prefs` `{ prefs: { default_network } }` → toast.
8. **(optional) Preferences:** toggle email notifications / show tips / compact sidebar → **Save preferences** → `PATCH /api/dashboard/prefs` `{ prefs }` → toast "Preferences saved".
diff --git a/prompts/finish/455-auto-settings-connections-404.md b/prompts/finish/455-auto-settings-connections-404.md
deleted file mode 100644
index 5ded87f3f..000000000
--- a/prompts/finish/455-auto-settings-connections-404.md
+++ /dev/null
@@ -1,84 +0,0 @@
-# 455. `/settings/connections` 404s: a fully-built chat-pairing API has no page to land on
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this repository and say "run this work order". Runnable now, no gate, no owner action required.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. CLAUDE.md overrides everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option list, or an unexecuted plan.
-- This is a bug fix (a live 404 on a path the server itself links to): follow the test-first rule (CLAUDE.md, "Bug fixes are test-first"). Write the failing test first, confirm it fails for the stated reason, then fix the code, then confirm it passes. Commit the test with the fix.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates (spend/on-chain writes, push/deploy, posting externally, committing content referencing a crypto project other than `$THREE`, destroying unrecoverable data). This order touches none of them.
-- Concurrent agents share this worktree: stage explicit paths only (never `git add -A` or `git add .`), re-check `git status` and `git diff --staged` before committing.
-- The em-dash and en-dash characters are banned in everything you write.
-
-## Why this matters (measured 2026-10-25)
-
-`GET https://three.ws/settings/connections` returns a live 404 today:
-
- curl -s -o /dev/null -w "%{http_code}\n" https://three.ws/settings/connections
-
-The mechanical cause is `vercel.json` (confirmed at the lines below, read today): the `/settings/` single-page app has exactly one static file, `public/settings/index.html` (`find public/settings -maxdepth 1 -iname "*.html"` returns only `index.html`), but its catch-all route treats any subpath as a literal file on disk instead of falling back to that one file:
-
- { "src": "/settings", "dest": "/settings/index.html" },
- { "src": "/settings/", "dest": "/settings/index.html" },
- { "src": "/settings/(.*)", "dest": "/settings/$1" }, // <-- line ~5735, the bug: looks for a file named "connections" that does not exist
-
-Contrast with `/dashboard/(.*)` a few hundred lines earlier, which uses the identical `dest: "/dashboard/$1"` pattern correctly, because `public/dashboard/` genuinely has one real HTML file per subpath (`actions.html`, `sessions.html`, `storage.html`, etc, confirmed via `find public/dashboard -maxdepth 1 -iname "*.html"`). `/settings/` is architecturally different: it is one hash-routed SPA (`public/settings/index.html`, 1712 lines, tab nav at lines 455-467, `navigate(tab)` router at lines 1673-1706), so its catch-all needs the SPA fallback, not the dashboard pattern. The two routes were written to look alike; only one of them is actually a multi-page directory.
-
-This 404 is not cosmetic. The exact path `/settings/connections` is hardcoded, live, and reached by real users and real bot messages across at least four independent flows, all pointing at a page that cannot load:
-
-1. **Telegram/Discord bot pairing.** `api/_lib/gateway/core.js`'s `pairingPrompt()` sends every person who starts a pairing flow in a bot DM a message containing `` `Open ${appOrigin()}/settings/connections?code=${code}` `` as the primary (only UI) way to redeem their pairing code. `api/_lib/gateway/commands.js` sends the same URL (no query) as the bot's "manage paired chats" help text. Both land on a 404 today.
-2. **Dashboard notification settings.** `src/dashboard-next/pages/settings.js` lines 720, 784, and 792 tell the user, in the UI itself, to "Pair a chat at /settings/connections" before the Telegram/Discord notification toggle will enable. Same 404.
-3. **Sign-in-with-X OAuth connect flow.** `api/auth/x/[action].js` line 160 allowlists `/settings/connections` as a valid OAuth return surface, and `connectReturnUrl()` (lines 175-191) builds `` `/settings/connections?${q}#x` `` for the `target === 'agent'` branch. Same 404. `api/_lib/x-agent-policy.js` lines 326 and 428 build the same return URL.
-4. **The backend feature itself is 100% built and already labeled "behind /settings/connections."** `api/gateway/connections.js` lines 1-13 (its own header comment) describe a complete REST surface: `GET` (list paired chats + the account's agents + bot usernames), `POST {action:'issue'}` (mint a pairing code), `POST {action:'redeem', code}` (pair the chat that printed it), `PATCH {id, notify, default_agent_id}`, `DELETE ?id=` (unpair). Confirmed today: `grep -rln "api/gateway/connections" src/` returns **zero matches** anywhere in the frontend. This is a fully working, authenticated, CSRF-gated, rate-limited API with no caller.
-
-`docs/ux-flows/11-account-dashboard.md` line 167 already documents this exact gap in its own words, written before this order: "Their disabled tooltip reads 'Pair a Telegram (or Discord) chat at /settings/connections to enable', but no page is served at that path yet, so pairing currently happens through the gateway API and the bot's `/link <code>` command." That sentence is itself now stale once this order ships (the page will exist), and must be updated.
-
-This is a new finding, not a duplicate: `grep -rln "settings/connections\|gateway/connections" prompts/finish/` before this order returns nothing. It outranks a new feature under the RUN-ORDER rule (live production defect, four independent call sites, backend already shipped) and it is Solana-neutral infrastructure (account/notification plumbing), so it does not compete with or displace Solana-first work.
-
-## Task
-
-1. Read `public/settings/index.html` in full (1712 lines), focusing on:
- - lines 455-467 (the `<aside>` tab nav: `<a href="#profile" data-tab="profile" ...>` through `<a href="#danger" data-tab="danger" ...>`)
- - the `tab-connected-accounts` panel markup starting at line 634, as the closest existing pattern (a panel that calls a backend list endpoint and renders rows with actions)
- - lines 1672-1706 (`navigate(tab)`, the click handler that does `history.pushState(null, '', '#' + tab)`, the `popstate` listener, and the init IIFE that resolves the starting tab from `?tab=` then `location.hash` then `'profile'`)
-2. Read `api/gateway/connections.js` in full (its header comment plus the handler body) to confirm the exact request/response shapes for `GET`, `POST {action:'issue'}`, `POST {action:'redeem', code}`, `PATCH`, and `DELETE`.
-3. Write the failing test first, in a new file `tests/settings-connections-route.test.js`: read `vercel.json`, locate the rule whose `src` is `"/settings/(.*)"`, and assert its `dest` is the literal string `"/settings/index.html"` (not `"/settings/$1"`). Follow the plain-JSON-read pattern already used in `tests/pages-routes.test.js` (`JSON.parse(readFileSync(...))`, no server boot). Run `npx vitest run tests/settings-connections-route.test.js` and confirm it fails against the current `"/settings/$1"` value.
-4. Fix `vercel.json`: change the `/settings/(.*)` rule's `dest` from `"/settings/$1"` to `"/settings/index.html"`. Do not touch the `/settings/api-keys/?` redirect rule or the plain `/settings` and `/settings/` rules immediately above it; they already work and must stay in the same relative order (the redirect rule must still be evaluated before the catch-all).
-5. Re-run `npx vitest run tests/settings-connections-route.test.js`; it must pass.
-6. Add a `connections` tab to `public/settings/index.html`, following the exact pattern of the existing tabs:
- - A new nav link in the `<aside>` block: `<a href="#connections" data-tab="connections" data-i18n="settings_index.connections">Connections</a>`, placed after the `#sessions` link and before `#danger` (matches the existing ordering: identity/security tabs first, danger zone last).
- - A new `<div class="page" id="tab-connections">` panel, placed after the `tab-sessions` panel, containing: a heading and one-line description ("Chats paired with your agents, and X accounts connected for memory seeding" or similar, matching the tone of the `connected-accounts` panel's description), a `data-slot="links-list"` container for paired chats (platform, chat title, paired agent, notify toggle, an "Unpair" button), a `data-slot="issue"` section with a button that calls `POST {action:'issue'}` and displays the returned pairing code plus the bot usernames from the `GET` response's `bots` field (so a user who lands on the page without a code can still start a pairing from here), and a `data-slot="redeem"` section that is only shown/used when the page loads with a `code` in the query string (see step 7).
- - Implement `loadConnections()` (mirroring `loadConnectedAccounts()`'s shape: fetch, render, wire button handlers with `fetch(..., {credentials:'include'})` and the existing CSRF/toast helpers already used elsewhere in this file) that calls `GET /api/gateway/connections` and renders the `links`, `agents`, and `bots` arrays into the panel.
- - Wire `PATCH` for the notify toggle and `DELETE` for the "Unpair" button on each row, following the same optimistic-update-plus-toast pattern `renderConnectedApps()` uses for its "Revoke" button (read that function in `src/dashboard-next/pages/settings.js` lines 572-626 for the pattern; it is a sibling page, not this one, but the fetch/toast/confirm idiom is the same project-wide convention).
- - Add `if (tab === 'connections') loadConnections();` inside `navigate(tab)` alongside the existing `if (tab === 'sessions') ...` and `if (tab === 'connected-accounts') ...` lines.
-7. Fix the tab-resolution collision this uncovers: the X-connect flow's `target === 'agent'` branch (`api/auth/x/[action].js` line 181) returns to `` `/settings/connections?${q}#x` ``, where `#x` is an outcome marker, not a tab name. Once `/settings/connections` serves the SPA, the init IIFE's existing priority (`?tab=` then `location.hash` then `'profile'`) would try to `navigate('x')`, find no `#tab-x` element, and leave the page blank. Fix this by adding a pathname check ahead of the hash check: if `location.pathname === '/settings/connections'` (or starts with it), resolve the starting tab as `'connections'` regardless of any trailing hash, and read `_urlP.get('x')` inside `loadConnections()` to show the appropriate X-connect outcome toast (reuse the existing outcome-to-message mapping style already used for Telegram outcomes at lines 309-324, or inline a small equivalent map for the `x` outcomes this endpoint sends: `linked`, `already_linked`, `failed`, etc, matching whatever `api/auth/x/[action].js` actually emits as `outcome` values, confirm by reading that file's `outcome` assignments). Also read `code` and `agent` query params the same way, for the bot-pairing and agent-prefill flows respectively.
-8. Confirm the three message-copy call sites do not need text changes now that the page is real: re-read `src/dashboard-next/pages/settings.js` lines 720, 784, 792, `api/_lib/gateway/core.js`'s `pairingPrompt()`, and `api/_lib/gateway/commands.js`'s help text. All of them already say exactly `/settings/connections` (with `pairingPrompt` additionally appending `?code=${code}`); once the route and page exist, these become correct as written and need no edits. State this explicitly in your report rather than silently skipping it.
-9. Update `docs/ux-flows/11-account-dashboard.md` line 167: remove the clause "but no page is served at that path yet, so pairing currently happens through the gateway API and the bot's `/link <code>` command" (now false) and replace it with a short accurate statement that `/settings/connections` now serves the pairing UI directly.
-10. Run `npm run check:rules -- --paths vercel.json public/settings/index.html tests/settings-connections-route.test.js docs/ux-flows/11-account-dashboard.md` and fix anything it flags.
-11. Add a `data/changelog.json` entry (tag `fix` or `feature`, whichever the existing convention uses for a previously-404ing settings surface, link `/settings/connections`) describing that chat pairing and X-connect returns now land on a working page, then run `npm run build:pages` and confirm only the expected generated files change.
-12. Read the full diff (`git diff vercel.json public/settings/index.html tests/settings-connections-route.test.js docs/ux-flows/11-account-dashboard.md data/changelog.json`) and confirm every changed line is one of the changes above.
-
-## Done when
-
-- `tests/settings-connections-route.test.js` exists, asserts the `/settings/(.*)` rule's `dest` is `"/settings/index.html"`, and is confirmed to have failed against the pre-fix `"/settings/$1"` value before the fix landed.
-- `curl -s -o /dev/null -w "%{http_code}" https://three.ws/settings/connections` cannot be tested against production from this session (no deploy), but `vercel.json`'s rule change is verified by the passing test above, and `server/index.mjs`'s route-table loader (confirmed it reads `vercel.json`'s `routes` array at boot) needs no separate change.
-- `public/settings/index.html` has a `data-tab="connections"` nav link, a `id="tab-connections"` panel, and a `loadConnections()` function that calls `GET /api/gateway/connections` and wires issue/redeem/patch/delete against the real endpoint (no mock data).
-- The pathname-based tab resolution added in step 7 is present and the `#x`/`code`/`agent` query params are read inside the `connections` tab's load path.
-- `docs/ux-flows/11-account-dashboard.md` line 167's stale "no page is served" clause is gone.
-- `npm run check:rules -- --paths vercel.json public/settings/index.html tests/settings-connections-route.test.js docs/ux-flows/11-account-dashboard.md` reports no violations.
-- A changelog entry exists and `npm run build:pages` ran cleanly.
-- `npx vitest run tests/settings-connections-route.test.js` passes.
-
-## Never blocked
-
-| Apparent blocker | Resolution |
-| --- | --- |
-| "Should this live at `/settings/connections` (a path) or as a `#connections` hash tab, since the rest of this SPA is hash-routed?" | Both: fix the route so the path resolves to the SPA shell (step 4), and make the SPA's own tab router recognize that path (step 7). Every existing hardcoded reference uses the full path, so the path must work; the hash-tab mechanism is this page's existing internal routing convention, so the tab must also exist in it. Do not invent a third convention. |
-| "Should per-API-key overrides, or a UI for `PATCH default_agent_id`, be in scope?" | `default_agent_id` PATCH: yes, it is a one-line addition to the row's edit affordance and the API already supports it. Per-API-key chat-pairing overrides: out of scope, not referenced by any of the four call sites this order fixes; chat pairing is inherently account-wide (a chat is paired with the account, then assigned a default agent), unlike the MCP tool-policy per-key overrides in a separate system. |
-| "The `#x` outcome vocabulary in `api/auth/x/[action].js` might not match what I guess." | Do not guess. Read the file's actual `outcome` literal assignments (`grep -n "outcome:" api/auth/x/\[action\].js` or equivalent) and use those exact strings. |
-| "This duplicates order 438/439/442/443/453/454." | No. Checked: none of those orders mention `/settings/connections`, `gateway/connections`, or the X-connect return-URL branches. This is a distinct, previously unfiled defect. |
-
-## Report format
-
-State: the vercel.json line changed (before/after `dest` value), the test file added and its pass/fail-then-pass sequence, which tabs/panels were added to `public/settings/index.html` with line ranges, the docs line fixed, the changelog entry, and the commit hash. Note explicitly that step 8's three message-copy sites needed no text changes (already correct once the route works).
diff --git a/public/settings/index.html b/public/settings/index.html
index 887513457..f578b92d5 100644
--- a/public/settings/index.html
+++ b/public/settings/index.html
@@ -457,6 +457,7 @@
<a href="#connected-accounts" data-tab="connected-accounts" data-i18n="settings_index.connected_accounts">Connected Accounts</a>
<a href="#privacy" data-tab="privacy" data-i18n="settings_index.privacy">Privacy</a>
<a href="#sessions" data-tab="sessions" data-i18n="settings_index.sessions">Sessions</a>
+ <a href="#connections" data-tab="connections">Connections</a>
<div class="aside-section">Workspace</div>
<a href="/dashboard#keys" data-i18n="settings_index.api_keys">API Keys ↗</a>
<a href="/dashboard#mcp" data-i18n="settings_index.mcp">MCP ↗</a>
@@ -630,6 +631,41 @@
</div>
</div>
+ <!-- ── Connections (paired chats) ───────────────────────── -->
+ <div class="page" id="tab-connections">
+ <h2>Connections</h2>
+ <p class="sub">Telegram and Discord chats paired with your agents</p>
+ <span class="inline-msg" id="conn-msg" style="display:none;margin-bottom:12px"></span>
+
+ <div class="section" data-slot="redeem" id="conn-redeem" style="display:none"></div>
+
+ <div class="section">
+ <h3>Paired chats</h3>
+ <div data-slot="links-list" id="conn-links" aria-live="polite">
+ <p class="muted">Loading connections…</p>
+ </div>
+ </div>
+
+ <hr class="divider" />
+
+ <div class="section" data-slot="issue" id="conn-issue">
+ <h3>Pair a new chat</h3>
+ <p class="muted" style="font-size:13px;margin:0 0 12px">Generate a code here, then send it to the bot as <code>/link CODE</code> from the chat you want to pair. Or start in the chat: the bot prints a code you can paste back here.</p>
+ <div id="conn-bots" class="muted" style="font-size:13px;margin-bottom:12px"></div>
+ <div class="row">
+ <button class="btn" id="conn-issue-btn">Generate pairing code</button>
+ </div>
+ <div id="conn-issued" style="display:none;margin-top:14px"></div>
+ <div class="row" style="margin-top:18px">
+ <label for="conn-code-input" class="visually-hidden">Code from the bot</label>
+ <input id="conn-code-input" type="text" placeholder="Code from the bot, e.g. ABCD-EFGH" maxlength="16" autocomplete="off" style="max-width:280px" />
+ <button class="btn sec" id="conn-preview-btn">Check code</button>
+ </div>
+ </div>
+
+ <div class="section" id="conn-x" style="display:none;margin-top:18px"></div>
+ </div>
+
<!-- ── Connected Accounts ────────────────────────────────── -->
<div class="page" id="tab-connected-accounts">
<h2 data-i18n="settings_index.connected_accounts_2">Connected Accounts</h2>
@@ -1669,6 +1705,201 @@
});
}
+ // ── Connections (paired chats) ────────────────────────────────
+ const CONN_PLATFORM = { telegram: 'Telegram', discord: 'Discord' };
+ const X_OUTCOMES = {
+ connected: ['ok', 'X account connected successfully.'],
+ denied: ['err', 'X connection cancelled.'],
+ unconfigured: ['err', 'X connections are not enabled on this deployment, so the connect could not start.'],
+ error: ['err', 'X connection failed. Try again.'],
+ };
+ let connState = { agents: [], bots: {} };
+ let connIntroDone = false;
+
+ function connMsg(type, text) {
+ showMsg(document.getElementById('conn-msg'), type, text);
+ }
+
+ function renderConnBots(bots) {
+ const parts = [];
+ if (bots.telegram?.available) parts.push(`<a href="${escHtml(bots.telegram.url)}" target="_blank" rel="noopener">@${escHtml(bots.telegram.username)} on Telegram</a>`);
+ if (bots.discord?.available) parts.push(`<a href="${escHtml(bots.discord.dm_url)}" target="_blank" rel="noopener">Message the Discord bot</a> or <a href="${escHtml(bots.discord.invite_url)}" target="_blank" rel="noopener">add it to a server</a>`);
+ document.getElementById('conn-bots').innerHTML = parts.length
+ ? 'Bots: ' + parts.join(' &middot; ')
+ : 'No chat bots are enabled on this deployment yet.';
+ }
+
+ function renderConnLinks(links) {
+ const el = document.getElementById('conn-links');
+ if (!links.length) {
+ el.innerHTML = '<p class="muted">No chats are paired yet. Generate a code below and send it to the bot with <code>/link CODE</code>.</p>';
+ return;
+ }
+ el.innerHTML = links.map(l => {
+ const opts = ['<option value="">Default agent</option>']
+ .concat(connState.agents.map(a => `<option value="${escHtml(a.id)}"${a.id === l.default_agent_id ? ' selected' : ''}>${escHtml(a.name)}</option>`)).join('');
+ const title = l.chat_title || l.platform_username || 'Direct chat';
+ return `
+ <div class="social-card" data-link-id="${escHtml(l.id)}" style="margin-bottom:10px;flex-wrap:wrap">
+ <div class="provider-info">
+ <div>
+ <div class="provider-name">${escHtml(CONN_PLATFORM[l.platform] || l.platform)}: ${escHtml(title)}</div>
+ <div class="provider-meta">Paired ${escHtml(new Date(l.created_at).toLocaleDateString())}${l.default_agent_name ? ' &middot; ' + escHtml(l.default_agent_name) : ''}</div>
+ </div>
+ </div>
+ <div class="actions" style="flex-wrap:wrap">
+ <label class="visually-hidden" for="conn-agent-${escHtml(l.id)}">Agent for this chat</label>
+ <select id="conn-agent-${escHtml(l.id)}" data-act="agent" style="max-width:200px">${opts}</select>
+ <label style="display:flex;align-items:center;gap:6px;font-size:13px;color:#ccc;cursor:pointer">
+ <input type="checkbox" data-act="notify"${l.notify ? ' checked' : ''} /> Notify
+ </label>
+ <button class="btn sec" data-act="unpair" style="font-size:12px;padding:5px 14px">Unpair</button>
+ </div>
+ </div>`;
+ }).join('');
+ }
+
+ async function connPatch(id, body, undo) {
+ try {
+ await apiJson('/api/gateway/connections', { method: 'PATCH', body: JSON.stringify({ id, ...body }) });
+ connMsg('ok', 'Saved.');
+ } catch (e) {
+ undo();
+ connMsg('err', e.data?.error_description || 'Could not save that change.');
+ }
+ }
+
+ document.getElementById('conn-links').addEventListener('change', (e) => {
+ const card = e.target.closest('[data-link-id]');
+ if (!card) return;
+ const id = card.dataset.linkId;
+ if (e.target.dataset.act === 'notify') {
+ const box = e.target;
+ connPatch(id, { notify: box.checked }, () => { box.checked = !box.checked; });
+ } else if (e.target.dataset.act === 'agent') {
+ const sel = e.target;
+ const prev = sel.dataset.prev ?? [...sel.options].find(o => o.defaultSelected)?.value ?? '';
+ connPatch(id, { default_agent_id: sel.value || null }, () => { sel.value = prev; });
+ sel.dataset.prev = sel.value;
+ }
+ });
+
+ document.getElementById('conn-links').addEventListener('click', async (e) => {
+ const btn = e.target.closest('[data-act="unpair"]');
+ if (!btn) return;
+ const card = btn.closest('[data-link-id]');
+ if (!confirm('Unpair this chat? It will stop receiving replies and notifications until you pair it again.')) return;
+ btn.disabled = true;
+ try {
+ await apiJson('/api/gateway/connections?id=' + encodeURIComponent(card.dataset.linkId), { method: 'DELETE' });
+ card.remove();
+ if (!document.querySelector('#conn-links [data-link-id]')) renderConnLinks([]);
+ connMsg('ok', 'Chat unpaired.');
+ } catch (err) {
+ btn.disabled = false;
+ connMsg('err', err.data?.error_description || 'Could not unpair that chat.');
+ }
+ });
+
+ document.getElementById('conn-issue-btn').addEventListener('click', async () => {
+ const btn = document.getElementById('conn-issue-btn');
+ const out = document.getElementById('conn-issued');
+ btn.disabled = true;
+ try {
+ const r = await apiJson('/api/gateway/connections', { method: 'POST', body: JSON.stringify({ action: 'issue' }) });
+ const mins = Math.max(1, Math.round((new Date(r.expires_at) - Date.now()) / 60000));
+ out.style.display = 'block';
+ out.innerHTML = `<div style="font-size:22px;font-weight:700;letter-spacing:.12em;font-family:monospace;color:#eee">${escHtml(r.code)}</div>
+ <p class="muted" style="font-size:13px;margin:6px 0 0">Send <code>/link ${escHtml(r.code)}</code> to the bot from the chat to pair. Expires in about ${mins} minute${mins === 1 ? '' : 's'}.</p>`;
+ } catch (e) {
+ connMsg('err', e.data?.error_description || 'Could not create a pairing code.');
+ } finally {
+ btn.disabled = false;
+ }
+ });
+
+ // Redeem is two steps on the server: preview shows which chat printed the
+ // code and mints a confirmation, redeem pairs that exact chat.
+ async function previewConnCode(rawCode) {
+ const box = document.getElementById('conn-redeem');
+ box.style.display = 'block';
+ box.innerHTML = '<p class="muted">Checking code…</p>';
+ try {
+ const r = await apiJson('/api/gateway/connections', { method: 'POST', body: JSON.stringify({ action: 'preview', code: rawCode }) });
+ const c = r.chat;
+ const name = c.chat_title || c.platform_username || 'a direct chat';
+ box.innerHTML = `
+ <h3>Pair this chat?</h3>
+ <p style="font-size:14px;color:#ddd;margin:0 0 12px">${escHtml(CONN_PLATFORM[c.platform] || c.platform)}: <strong>${escHtml(name)}</strong>${c.already_linked ? ' (already paired to your account)' : ''}. Anyone in this chat will be able to talk to your agents and approve actions they request.</p>
+ <div class="row">
+ <button class="btn" id="conn-redeem-btn">Pair this chat</button>
+ <button class="btn sec" id="conn-redeem-cancel">Cancel</button>
+ </div>`;
+ document.getElementById('conn-redeem-cancel').addEventListener('click', () => { box.style.display = 'none'; });
+ document.getElementById('conn-redeem-btn').addEventListener('click', async (ev) => {
+ ev.target.disabled = true;
+ try {
+ await apiJson('/api/gateway/connections', { method: 'POST', body: JSON.stringify({ action: 'redeem', code: rawCode, confirm: r.confirm }) });
+ box.style.display = 'none';
+ document.getElementById('conn-code-input').value = '';
+ connMsg('ok', 'Chat paired.');
+ loadConnections();
+ } catch (e) {
+ ev.target.disabled = false;
+ connMsg('err', e.data?.error_description || 'Could not pair that chat.');
+ }
+ });
+ } catch (e) {
+ box.innerHTML = `<p class="inline-msg err" style="display:inline-block">${escHtml(e.data?.error_description || 'That code did not work. Ask the bot for a new one.')}</p>`;
+ }
+ }
+
+ document.getElementById('conn-preview-btn').addEventListener('click', () => {
+ const v = document.getElementById('conn-code-input').value.trim();
+ if (v) previewConnCode(v);
+ else connMsg('err', 'Enter the code the bot gave you.');
+ });
+
+ async function loadConnections() {
+ const el = document.getElementById('conn-links');
+ try {
+ const data = await apiJson('/api/gateway/connections');
+ connState = { agents: data.agents || [], bots: data.bots || {} };
+ renderConnBots(connState.bots);
+ renderConnLinks(data.links || []);
+ } catch (e) {
+ el.innerHTML = `<p class="muted">${escHtml(e.data?.error_description || 'Could not load your connections.')} <button class="btn sec" id="conn-retry" style="font-size:12px;padding:5px 14px">Retry</button></p>`;
+ document.getElementById('conn-retry').addEventListener('click', loadConnections);
+ }
+ if (connIntroDone) return;
+ connIntroDone = true;
+ // Query params from the flows that land here: ?code= from the bot's
+ // pairing prompt, ?x=&agent= from the X connect return.
+ const code = _urlP.get('code');
+ if (code) {
+ document.getElementById('conn-code-input').value = code;
+ previewConnCode(code);
+ }
+ const xOutcome = _urlP.get('x');
+ if (xOutcome && X_OUTCOMES[xOutcome]) {
+ const agent = _urlP.get('agent');
+ connMsg(...X_OUTCOMES[xOutcome]);
+ const box = document.getElementById('conn-x');
+ box.style.display = 'block';
+ box.innerHTML = '<a class="btn sec" style="text-decoration:none;display:inline-block" href="/settings?tab=connected-accounts'
+ + (agent ? '&agent_id=' + encodeURIComponent(agent) : '') + '">Manage your X connection</a>';
+ }
+ }
+
+ // /settings/connections serves this same shell. Its trailing hash can be an
+ // outcome marker (#x) rather than a tab, so the path wins over the hash.
+ function startingTab() {
+ const hash = location.hash.slice(1);
+ if (/^\/settings\/connections\/?$/.test(location.pathname) && !document.getElementById('tab-' + hash)) return 'connections';
+ // Support ?tab= from OAuth redirects as well as #hash
+ return _urlP.get('tab') || hash || 'profile';
+ }
+
// ── Tab routing ───────────────────────────────────────────────
function navigate(tab) {
document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
@@ -1680,17 +1911,18 @@
if (link) link.classList.add('active');
if (tab === 'sessions') loadSessions();
if (tab === 'connected-accounts') loadConnectedAccounts();
+ if (tab === 'connections') loadConnections();
}
document.querySelectorAll('aside a[data-tab]').forEach(a => {
a.addEventListener('click', (e) => {
e.preventDefault();
- history.pushState(null, '', '#' + a.dataset.tab);
+ history.pushState(null, '', '/settings#' + a.dataset.tab);
navigate(a.dataset.tab);
});
});
- window.addEventListener('popstate', () => navigate(location.hash.slice(1) || 'profile'));
+ window.addEventListener('popstate', () => navigate(startingTab()));
// ── Init ──────────────────────────────────────────────────────
(async () => {
@@ -1700,9 +1932,7 @@
} catch {
return; // redirect already fired
}
- // Support ?tab= from OAuth redirects as well as #hash
- const tabFromQuery = _urlP.get('tab');
- navigate(tabFromQuery || location.hash.slice(1) || 'profile');
+ navigate(startingTab());
})();
</script>
<script src="/brand.js" defer></script>