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
fix(oracle): show the linked Telegram chat read-only in follow and arm panels with sign-in and link states
nirholas31bf05121861
diff --git a/api/oracle/telegram-chat.js b/api/oracle/telegram-chat.jsnew file mode 100644index 000000000..2d1b63806--- /dev/null+++ b/api/oracle/telegram-chat.js@@ -0,0 +1,27 @@+/**+ * Oracle: the Telegram chat the signed-in user has verified.+ *+ * GET /api/oracle/telegram-chat+ * 200 { linked: true, chat_id: "123456789" }+ * 200 { linked: false, chat_id: null }+ * 401 when not signed in+ *+ * /api/oracle/follow and /api/oracle/test-alert only accept this chat id, so+ * the follow and arm panels read it here to prefill and lock their input.+ * Auth: session cookie or bearer token.+ */++import { cors, json, method, wrap, error } from '../_lib/http.js';+import { resolveUserId, verifiedTelegramChatId } from '../_lib/oracle/verified-chat.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const userId = await resolveUserId(req);+ if (!userId) return error(res, 401, 'unauthorized', 'sign in to use Telegram alerts');++ const chatId = await verifiedTelegramChatId(userId);+ res.setHeader('cache-control', 'private, no-store');+ return json(res, 200, { linked: Boolean(chatId), chat_id: chatId });+});diff --git a/pages/arm.html b/pages/arm.htmlindex 2c608a5e3..696051220 100644--- a/pages/arm.html+++ b/pages/arm.html@@ -125,6 +125,9 @@/* telegram */.tg-row { display: flex; gap: 6px; align-items: center; }.tg-row input { flex: 1; min-width: 0; font-size: 12px; }+ .tg-state { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } .tg-state:empty { display: none; }+ .tg-body { font-size: 12px; line-height: 1.45; flex: 1 1 200px; } .tg-err { color: var(--amber); }+ .tg-state a.btn { text-decoration: none; } .tg-row button[hidden], .tg-row input[hidden] { display: none; }.tg-note { display: none; margin-top: 7px; font-size: 11.5px; line-height: 1.4; }.tg-note.ok { color: var(--up); } .tg-note.warn { color: var(--amber); }.opt { font: 600 10px/1 var(--mono); padding: 2px 7px; border-radius: 999px; background: rgba(255,255,255,.08); color: var(--muted); border: 1px solid var(--line); text-transform: uppercase; letter-spacing: .05em; }@@ -366,13 +369,14 @@<h3 data-i18n-html="arm.3_alerts_optional"><span class="stepno">3</span> Alerts <span class="opt">optional</span></h3><p class="sub" data-i18n="arm.get_a_personal_telegram_ping_whenever_a">Get a personal Telegram ping whenever a coin crosses your threshold — armed or not.</p><div class="field">- <label for="tgInput" data-i18n="arm.telegram_chat_id_or_channel">Telegram chat ID or @channel</label>+ <label for="tgInput">Telegram chat</label>+ <div id="tgState" class="tg-state" aria-live="polite"></div><div class="tg-row">- <input id="tgInput" type="text" placeholder="Your chat ID or @channel" autocomplete="off">+ <input id="tgInput" type="text" readonly hidden aria-label="Linked Telegram chat" autocomplete="off"><button id="tgTest" class="btn sm" type="button" data-i18n="arm.send_test">Send test</button></div><div class="tg-note" id="tgNote" role="status" aria-live="polite"></div>- <div class="field-hint">Chat <a href="https://t.me/three_ws_bot" target="_blank" rel="noopener" data-i18n="arm.three_ws_bot">@three_ws_bot</a> and send <code>/start</code> to get your chat ID.</div>+ <div class="field-hint">Alerts go to the Telegram account linked to your three.ws account. Chat <a href="https://t.me/three_ws_bot" target="_blank" rel="noopener" data-i18n="arm.three_ws_bot">@three_ws_bot</a> and send <code>/start</code> to link it.</div></div></div></div>diff --git a/pages/oracle.html b/pages/oracle.htmlindex b111f1c37..6a270d14f 100644--- a/pages/oracle.html+++ b/pages/oracle.html@@ -233,6 +233,13 @@.fp-label { font: 600 10px/1 var(--mono); text-transform: uppercase; letter-spacing: .07em; color: var(--faint); display: block; margin-bottom: 5px; }.fp-chat { width: 100%; background: rgba(255,255,255,0.04); border: 1px solid var(--line); border-radius: 7px; color: var(--ink); padding: 8px 10px; font: 600 13px/1 var(--mono); outline: none; }.fp-chat:focus { border-color: var(--cyan); }+ .fp-tg-body { font-size: 12px; line-height: 1.45; color: var(--ink); margin-bottom: 7px; }+ .fp-tg-body code { font: 600 12px/1 var(--mono); color: var(--cyan); }+ .fp-tg-ok { color: var(--up); font-weight: 600; }+ .fp-tg-err { color: var(--amber); }+ .fp-tg-action { display: inline-block; background: rgba(255,255,255,0.06); border: 1px solid var(--line); border-radius: 7px; color: var(--ink); padding: 6px 12px; font: 600 12px/1.2 var(--mono); text-decoration: none; cursor: pointer; }+ .fp-tg-action:hover { border-color: var(--cyan); } .fp-tg-action:active { background: rgba(255,255,255,0.1); } .fp-tg-action:focus-visible { outline: 2px solid var(--cyan); outline-offset: 2px; }+ .fp-sub:disabled, .fp-unsub:disabled { opacity: .45; cursor: not-allowed; }.fp-score-field { display: flex; flex-direction: column; }.fp-score { width: 100%; accent-color: var(--cyan); }.fp-score-val { color: var(--cyan); }diff --git a/src/arm.js b/src/arm.jsindex ea468e956..7ccff6c07 100644--- a/src/arm.js+++ b/src/arm.js@@ -4,6 +4,7 @@import { ensureRiskAck } from './shared/risk-ack.js';import { proxiedImageURL } from './ipfs.js';+import { loadTelegramChat, telegramLoginUrl, TELEGRAM_LINK_URL } from './oracle-telegram.js';const NETWORK = 'mainnet';const $ = (s, r = document) => r.querySelector(s);@@ -28,6 +29,37 @@ function ago(ts) {const state = { agents: [], agentId: null, watch: null, minScore: 72, wallet: null, feed: [], feedAt: null, feedError: false, edge: null };let feedTimer = null;+let tgChat = { status: 'loading' };++// The alert chat is the Telegram identity the user linked: the API refuses any+// other chat id, so the panel shows it read-only instead of offering a free-text box.+async function refreshTelegram() {+ tgChat = { status: 'loading' };+ renderTelegram();+ tgChat = await loadTelegramChat(api);+ renderTelegram();+}++function renderTelegram() {+ const linked = tgChat.status === 'linked';+ const input = $('#tgInput');+ input.value = linked ? tgChat.chatId : '';+ input.hidden = !linked;+ $('#tgTest').disabled = !linked;+ $('#tgTest').hidden = !linked;+ const box = $('#tgState');+ if (linked) { box.innerHTML = ''; return; }+ if (tgChat.status === 'loading') {+ box.innerHTML = '<div class="tg-body">Checking your Telegram link\u2026</div>';+ } else if (tgChat.status === 'signed_out') {+ box.innerHTML = `<div class="tg-body">Sign in to receive alerts on Telegram.</div><a class="btn sm" href="${esc(telegramLoginUrl(location.pathname + location.search))}">Sign in</a>`;+ } else if (tgChat.status === 'unlinked') {+ box.innerHTML = `<div class="tg-body">Link your Telegram account so alerts go only to a chat you control.</div><a class="btn sm" href="${TELEGRAM_LINK_URL}">Link Telegram</a>`;+ } else {+ box.innerHTML = `<div class="tg-body tg-err" role="alert">${esc(tgChat.message)}</div><button class="btn sm" type="button" id="tgRetry">Retry</button>`;+ $('#tgRetry').addEventListener('click', refreshTelegram);+ }+}async function api(path, opts = {}) {const ctrl = new AbortController();@@ -178,7 +210,7 @@ function wireStaticControls() {$('#saveBtn').addEventListener('click', saveWatch);$('#tgTest').addEventListener('click', sendTelegramTest);- $('#tgInput').addEventListener('input', markDirty);+ refreshTelegram();}function wireSwitch(sel, cb) {@@ -482,7 +514,6 @@ async function loadWatch(agentId) {const cats = new Set(w?.categories || []);$$('#catChips .cchip').forEach((b) => b.classList.toggle('on', cats.has(b.dataset.cat)));- $('#tgInput').value = w?.telegram_chat_id || '';renderScaleSub();renderRisk();@@ -514,7 +545,7 @@ async function saveWatch() {max_open: Number($('#fOpen').value) || 5,require_smart_money: isOn('#smartToggle'),size_scaling: isOn('#scaleToggle'),- telegram_chat_id: ($('#tgInput').value || '').trim() || null,+ telegram_chat_id: tgChat.status === 'linked' ? tgChat.chatId : null,};const { ok, data } = await api('/api/oracle/watch', {method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload),@@ -547,12 +578,12 @@ async function saveWatch() {}async function sendTelegramTest() {- const chatId = ($('#tgInput').value || '').trim();+ const chatId = tgChat.status === 'linked' ? tgChat.chatId : '';const note = $('#tgNote');note.style.display = 'block';if (!chatId) {note.className = 'tg-note warn';- note.textContent = 'Enter your Telegram chat ID or @channel first.';+ note.textContent = 'Link Telegram to your account first.';return;}const btn = $('#tgTest');diff --git a/src/oracle-telegram.js b/src/oracle-telegram.jsnew file mode 100644index 000000000..86a63084b--- /dev/null+++ b/src/oracle-telegram.js@@ -0,0 +1,44 @@+// Telegram chat state for the Oracle follow and arm panels.+//+// /api/oracle/follow and /api/oracle/test-alert only accept the chat id of the+// Telegram identity the user linked, so the panels do not offer a free-text+// input. They resolve one of four states from /api/oracle/telegram-chat and+// render accordingly.++export const TELEGRAM_LINK_URL = '/dashboard/settings#sign-in-methods';++export function telegramLoginUrl(next) {+ return `/login?next=${encodeURIComponent(next)}`;+}++/**+ * Turn the transport result of GET /api/oracle/telegram-chat into a state:+ * { status: 'linked', chatId } chat verified, panel can act+ * { status: 'unlinked' } signed in, no Telegram identity linked+ * { status: 'signed_out' } no session+ * { status: 'error', message } request failed, retry+ */+export function telegramChatState({ ok, status, data }) {+ if (status === 401) return { status: 'signed_out' };+ if (!ok) {+ const message = !status+ ? 'Could not reach three.ws. Check your connection, then retry.'+ : status === 429+ ? 'Too many requests. Wait a few seconds, then retry.'+ : `Could not check your Telegram link (HTTP ${status}). Retry in a moment.`;+ return { status: 'error', message };+ }+ if (data?.linked && data.chat_id) return { status: 'linked', chatId: String(data.chat_id) };+ return { status: 'unlinked' };+}++export async function loadTelegramChat(api) {+ return telegramChatState(await api('/api/oracle/telegram-chat'));+}++/** Server error text for a rejected follow or test-alert call, with a fallback. */+export function telegramActionError(result, fallback) {+ if (result?.status === 401) return 'Sign in to use Telegram alerts.';+ if (result?.status === 403 && result?.data?.error_description) return result.data.error_description;+ return result?.data?.error_description || result?.data?.message || fallback;+}diff --git a/src/oracle.js b/src/oracle.jsindex 937feadad..cad3e615c 100644--- a/src/oracle.js+++ b/src/oracle.js@@ -12,6 +12,7 @@import { proxiedImageURL } from './ipfs.js';import { gmgnTokenUrl } from './shared/trading-terminals.js';import { shortAddress as shortAddr } from './shared/address.js';+import { loadTelegramChat, telegramLoginUrl, telegramActionError, TELEGRAM_LINK_URL } from './oracle-telegram.js';const NETWORK = 'mainnet';const $ = (s, r = document) => r.querySelector(s);@@ -1272,7 +1273,7 @@ function bindFollowHandlers(wrap) {const opening = panel.hidden;panel.hidden = !opening;btn.setAttribute('aria-expanded', String(opening));- if (opening) panel.querySelector('.fp-chat')?.focus();+ if (opening) panel.querySelector('.fp-chat, .fp-tg-action, .fp-sub:not([disabled])')?.focus();});wrap.addEventListener('input', (e) => {@@ -1288,13 +1289,12 @@ function bindFollowHandlers(wrap) {e.preventDefault();const entry = form.closest('.al-entry');const agentId = entry?.dataset.agentId;- const chatId = form.querySelector('.fp-chat')?.value.trim();+ const chatId = form.dataset.chat || '';const minScore = Number(form.querySelector('.fp-score')?.value) || 54;const msg = form.querySelector('.fp-msg');- if (!chatId) { showFpMsg(msg, 'Enter your Telegram chat ID or @handle', 'err'); return; }- localStorage.setItem('oracle_follow_chat', chatId);+ if (!chatId) { showFpMsg(msg, 'Link Telegram to your account first', 'err'); return; }showFpMsg(msg, 'Subscribing…', '');- const { ok, data } = await api('/api/oracle/follow', {+ const { ok, status, data } = await api('/api/oracle/follow', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ agent_id: agentId, chat_id: chatId, min_score: minScore }),@@ -1302,7 +1302,7 @@ function bindFollowHandlers(wrap) {if (ok) {showFpMsg(msg, data?.action === 'updated' ? 'Updated ✓' : 'Subscribed ✓', 'ok');} else {- showFpMsg(msg, data?.message || 'Failed', 'err');+ showFpMsg(msg, telegramActionError({ status, data }, 'Could not subscribe. Try again.'), 'err');}});@@ -1312,16 +1312,16 @@ function bindFollowHandlers(wrap) {const form = btn.closest('.follow-form');const entry = form?.closest('.al-entry');const agentId = entry?.dataset.agentId;- const chatId = form?.querySelector('.fp-chat')?.value.trim();+ const chatId = form?.dataset.chat || '';const msg = form?.querySelector('.fp-msg');- if (!chatId) { showFpMsg(msg, 'Enter your chat ID first', 'err'); return; }+ if (!chatId) { showFpMsg(msg, 'Link Telegram to your account first', 'err'); return; }showFpMsg(msg, 'Unsubscribing…', '');- const { ok } = await api('/api/oracle/follow', {+ const { ok, status, data: unsubData } = await api('/api/oracle/follow', {method: 'DELETE',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ agent_id: agentId, chat_id: chatId }),});- showFpMsg(msg, ok ? 'Unsubscribed' : 'Failed', ok ? 'ok' : 'err');+ showFpMsg(msg, ok ? 'Unsubscribed' : telegramActionError({ status, data: unsubData }, 'Could not unsubscribe. Try again.'), ok ? 'ok' : 'err');});}@@ -1331,30 +1331,50 @@ function showFpMsg(el, text, cls) {el.className = `fp-msg${cls ? ` fp-msg-${cls}` : ''}`;}+function renderFollowTelegram(panel, st, retry) {+ const form = panel.querySelector('.follow-form');+ const box = panel.querySelector('.fp-tg');+ if (!form || !box) return;+ const linked = st.status === 'linked';+ form.dataset.chat = linked ? st.chatId : '';+ panel.querySelectorAll('.fp-sub, .fp-unsub').forEach((b) => { b.disabled = !linked; });+ box.dataset.state = st.status;+ const label = '<span class="fp-label">Telegram</span>';+ if (linked) {+ box.innerHTML = `${label}<div class="fp-tg-body"><span class="fp-tg-ok">Linked</span> <code>${esc(st.chatId)}</code></div>`;+ } else if (st.status === 'signed_out') {+ box.innerHTML = `${label}<div class="fp-tg-body">Sign in to get this agent's signals on Telegram.</div>+ <a class="fp-tg-action" href="${esc(telegramLoginUrl(location.pathname + location.search))}">Sign in</a>`;+ } else if (st.status === 'unlinked') {+ box.innerHTML = `${label}<div class="fp-tg-body">Link your Telegram account so alerts go only to a chat you control.</div>+ <a class="fp-tg-action" href="${TELEGRAM_LINK_URL}">Link Telegram</a>`;+ } else {+ box.innerHTML = `${label}<div class="fp-tg-body fp-tg-err" role="alert">${esc(st.message)}</div>+ <button type="button" class="fp-tg-action fp-tg-retry">Retry</button>`;+ box.querySelector('.fp-tg-retry').addEventListener('click', retry);+ }+}+async function initFollowPanel(agentId, panel) {if (!agentId) return;- const chatInput = panel.querySelector('.fp-chat');- const savedChat = localStorage.getItem('oracle_follow_chat') || '';- if (chatInput && savedChat) {- chatInput.value = savedChat;- // Also cache for next open- chatInput.addEventListener('change', () => {- if (chatInput.value.trim()) localStorage.setItem('oracle_follow_chat', chatInput.value.trim());- });- }- if (!savedChat) return;- const { ok, data } = await api(- `/api/oracle/follow?agent_id=${encodeURIComponent(agentId)}&chat_id=${encodeURIComponent(savedChat)}&network=${NETWORK}`- );- if (!ok || !data?.following) return;- const msg = panel.querySelector('.fp-msg');- if (msg) showFpMsg(msg, 'Already following', 'ok');- if (data.min_score != null) {- const slider = panel.querySelector('.fp-score');- const val = panel.querySelector('.fp-score-val');- if (slider) slider.value = String(data.min_score);- if (val) val.textContent = String(data.min_score);- }+ const resolve = async () => {+ const st = await loadTelegramChat(api);+ renderFollowTelegram(panel, st, resolve);+ if (st.status !== 'linked') return;+ const { ok, data } = await api(+ `/api/oracle/follow?agent_id=${encodeURIComponent(agentId)}&chat_id=${encodeURIComponent(st.chatId)}&network=${NETWORK}`+ );+ if (!ok || !data?.following) return;+ const msg = panel.querySelector('.fp-msg');+ if (msg) showFpMsg(msg, 'Already following', 'ok');+ if (data.min_score != null) {+ const slider = panel.querySelector('.fp-score');+ const val = panel.querySelector('.fp-score-val');+ if (slider) slider.value = String(data.min_score);+ if (val) val.textContent = String(data.min_score);+ }+ };+ await resolve();}function agentLeadRow(a, i) {@@ -1386,17 +1406,17 @@ function agentLeadRow(a, i) {</div><div class="follow-panel" hidden><form class="follow-form" autocomplete="off">- <div class="fp-field">- <label class="fp-label">Telegram chat ID or @handle</label>- <input type="text" class="fp-chat" placeholder="@handle or -100…" spellcheck="false" />+ <div class="fp-field fp-tg" data-state="loading" aria-live="polite">+ <span class="fp-label">Telegram</span>+ <div class="fp-tg-body">Checking your Telegram link…</div></div><div class="fp-field fp-score-field"><label class="fp-label">Min conviction score: <b class="fp-score-val">54</b></label><input type="range" class="fp-score" min="36" max="100" value="54" step="1" /></div><div class="fp-actions">- <button type="submit" class="fp-sub">Subscribe</button>- <button type="button" class="fp-unsub">Unsubscribe</button>+ <button type="submit" class="fp-sub" disabled>Subscribe</button>+ <button type="button" class="fp-unsub" disabled>Unsubscribe</button><span class="fp-msg"></span></div></form>diff --git a/tests/oracle-telegram-state.test.js b/tests/oracle-telegram-state.test.jsnew file mode 100644index 000000000..94674540d--- /dev/null+++ b/tests/oracle-telegram-state.test.js@@ -0,0 +1,49 @@+import { describe, it, expect } from 'vitest';+import {+ telegramChatState,+ loadTelegramChat,+ telegramLoginUrl,+ telegramActionError,+} from '../src/oracle-telegram.js';++describe('telegramChatState', () => {+ it('is linked when the server returns a verified chat id', () => {+ expect(telegramChatState({ ok: true, status: 200, data: { linked: true, chat_id: 42 } })).toEqual({+ status: 'linked',+ chatId: '42',+ });+ });+ it('is unlinked when signed in without a Telegram identity', () => {+ expect(telegramChatState({ ok: true, status: 200, data: { linked: false, chat_id: null } })).toEqual({+ status: 'unlinked',+ });+ });+ it('is signed_out on 401', () => {+ expect(telegramChatState({ ok: false, status: 401, data: null }).status).toBe('signed_out');+ });+ it('maps transport and server failures to actionable errors', () => {+ expect(telegramChatState({ ok: false, status: 0, data: null }).message).toMatch(/connection/);+ expect(telegramChatState({ ok: false, status: 429, data: null }).message).toMatch(/Wait/);+ expect(telegramChatState({ ok: false, status: 500, data: null }).message).toMatch(/HTTP 500/);+ });+});++describe('helpers', () => {+ it('loadTelegramChat calls the endpoint through the supplied api function', async () => {+ const seen = [];+ const st = await loadTelegramChat(async (p) => {+ seen.push(p);+ return { ok: true, status: 200, data: { linked: true, chat_id: '7' } };+ });+ expect(seen).toEqual(['/api/oracle/telegram-chat']);+ expect(st.chatId).toBe('7');+ });+ it('login url round-trips the return path', () => {+ expect(telegramLoginUrl('/oracle/arm?x=1')).toBe('/login?next=%2Foracle%2Farm%3Fx%3D1');+ });+ it('prefers the server description for action errors', () => {+ expect(telegramActionError({ status: 403, data: { error_description: 'link first' } }, 'Failed')).toBe('link first');+ expect(telegramActionError({ status: 500, data: null }, 'Failed')).toBe('Failed');+ expect(telegramActionError({ status: 401 }, 'Failed')).toMatch(/Sign in/);+ });+});diff --git a/tests/safe-next.test.js b/tests/safe-next.test.jsindex 9ec4353e9..b582f65dd 100644--- a/tests/safe-next.test.js+++ b/tests/safe-next.test.js@@ -118,3 +118,13 @@ describe('inline copies stay in sync with src/safe-next.js', () => {}}});++describe('safeNext with nested query strings (extension sign-in round trip)', () => {+ it('keeps the extension state inside next, encoded or not', () => {+ const encoded = '/extension/auth-callback?state=ab12%3D%26cd';+ expect(safeNext(encoded)).toBe(encoded);+ const nested = `/login?next=${encodeURIComponent('/extension/auth-callback?state=xyz')}`;+ expect(safeNext(nested)).toBe(nested);+ expect(new URL(safeNext(encoded), 'https://three.ws').searchParams.get('state')).toBe('ab12=&cd');+ });+});