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
Test the commit-og lane and CoinGecko stale-on-error cache
nirholasf66b262a5231
diff --git a/api/_lib/commit-feed-push.js b/api/_lib/commit-feed-push.jsindex edade0ea0..8149b7aab 100644--- a/api/_lib/commit-feed-push.js+++ b/api/_lib/commit-feed-push.js@@ -93,7 +93,7 @@ const escapeHtml = (s) =>// body. Subjects without that convention get a generic "New commit" headline.// Only the subject line is ever posted: full commit bodies are hard-wrapped// by git and written for engineers, not holders, so they stay on GitHub.-function splitSubject(subjectLine) {+export function splitSubject(subjectLine) {const idx = subjectLine.indexOf(': ');if (idx > 0 && idx < 60) {return { headline: subjectLine.slice(0, idx), body: subjectLine.slice(idx + 2) };@@ -101,6 +101,47 @@ function splitSubject(subjectLine) {return { headline: 'New commit', body: subjectLine };}+// Conventional-commit type prefixes are written for engineers ("feat", "fix",+// "perf"). Holders following the feed read plain words, so map the known types+// to friendly labels. Anything not in the map — a real scope like "Avatar+// Studio" or "/cookbook" — is already readable and passes through untouched.+const TYPE_LABELS = {+ feat: 'Feature',+ fix: 'Fix',+ perf: 'Performance',+ refactor: 'Refactor',+ docs: 'Docs',+ test: 'Tests',+ tests: 'Tests',+ build: 'Build',+ ci: 'CI',+ chore: 'Chore',+ style: 'Style',+ revert: 'Revert',+};++export function prettyHeadline(headline) {+ return TYPE_LABELS[String(headline).toLowerCase()] || headline;+}++// three.ws-branded social-share landing for one commit. Telegram scrapes its+// OG tags to render the poster card, then redirects a human click to GitHub.+// The GitHub link still lives in the message text, so both paths work.+export function commitPreviewUrl(commit) {+ const subjectLine = (commit.commit?.message || '').split('\n')[0];+ const { headline, body } = splitSubject(subjectLine);+ const author = commit.author?.login || commit.commit?.author?.name || 'unknown';+ const date = (commit.commit?.author?.date || '').slice(0, 10);+ const params = new URLSearchParams({+ sha: commit.sha,+ t: prettyHeadline(headline),+ d: body,+ date,+ author,+ });+ return `${BASE}/api/commit-og?${params.toString()}`;+}+export function formatTelegramMessage(commit) {const shortSha = commit.sha.slice(0, 7);const subjectLine = (commit.commit?.message || '').split('\n')[0];@@ -110,7 +151,7 @@ export function formatTelegramMessage(commit) {const url = commit.html_url || `https://github.com/${REPO}/commit/${commit.sha}`;const linkText = `github.com/${REPO}/commit/${shortSha}`;return [- `<b>${escapeHtml(headline)}</b>`,+ `<b>${escapeHtml(prettyHeadline(headline))}</b>`,'',escapeHtml(body),'',@@ -118,7 +159,7 @@ export function formatTelegramMessage(commit) {].join('\n');}-async function sendTelegram(botToken, chatId, text) {+async function sendTelegram(botToken, chatId, text, previewUrl) {const res = await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, {method: 'POST',headers: { 'content-type': 'application/json' },@@ -126,7 +167,9 @@ async function sendTelegram(botToken, chatId, text) {chat_id: chatId,text,parse_mode: 'HTML',- link_preview_options: { is_disabled: true },+ // Preview the branded three.ws poster (not the GitHub link that also+ // sits in the text), rendered below the message like the changelog feed.+ link_preview_options: { is_disabled: false, url: previewUrl, show_above_text: false },}),});const body = await res.json().catch(() => ({}));@@ -158,7 +201,7 @@ export async function pushTelegramLane() {let lastSha = state.lastSha;try {for (const commit of capped) {- await sendTelegram(botToken, chatId, formatTelegramMessage(commit));+ await sendTelegram(botToken, chatId, formatTelegramMessage(commit), commitPreviewUrl(commit));lastSha = commit.sha;sent++;await setState(STATE_KEY, { lastSha });diff --git a/tests/api/coingecko-stale.test.js b/tests/api/coingecko-stale.test.jsnew file mode 100644index 000000000..75d0e1728--- /dev/null+++ b/tests/api/coingecko-stale.test.js@@ -0,0 +1,69 @@+// geckoFetch stale-on-error behavior (api/_lib/coingecko.js).+//+// CoinGecko's free/demo tier caps at ~30 req/min. Broad /coin/:id crawling+// saturates it, and before this a 429 threw straight through detail.js into a+// user-facing 502. These tests pin the contract: a value fetched once keeps+// serving (slightly stale) through a rate-limit / upstream / network storm,+// while a genuine 404 still propagates so "unknown coin" stays a real 404.+//+// No live network: global.fetch is stubbed per case. Each test uses a unique+// path so the module-level cache never bleeds between cases.++import { describe, it, expect, afterEach, vi } from 'vitest';+import { geckoFetch } from '../../api/_lib/coingecko.js';++const realFetch = global.fetch;+afterEach(() => {+ global.fetch = realFetch;+ vi.restoreAllMocks();+});++const ok = (body) => ({ ok: true, status: 200, json: async () => body });+const fail = (status) => ({ ok: false, status, json: async () => ({ error: status }) });++describe('geckoFetch — stale-on-error', () => {+ it('serves the last-good value when the upstream is rate-limited (429)', async () => {+ const path = `/coins/stale-429-${Math.round(performance.now())}`;+ global.fetch = vi.fn().mockResolvedValueOnce(ok({ id: 'warm', price: 100 }));+ // Fresh fetch, then expire immediately so the next call re-hits upstream.+ const first = await geckoFetch(path, { ttlMs: 0 });+ expect(first).toEqual({ id: 'warm', price: 100 });++ global.fetch = vi.fn().mockResolvedValue(fail(429));+ const second = await geckoFetch(path, { ttlMs: 0 });+ expect(second).toEqual({ id: 'warm', price: 100 }); // stale, not a throw+ expect(global.fetch).toHaveBeenCalledTimes(1);+ });++ it('serves stale on a network failure / timeout', async () => {+ const path = `/coins/stale-net-${Math.round(performance.now())}`;+ global.fetch = vi.fn().mockResolvedValueOnce(ok({ id: 'warm2' }));+ await geckoFetch(path, { ttlMs: 0 });++ global.fetch = vi.fn().mockRejectedValue(Object.assign(new Error('aborted'), { name: 'TimeoutError' }));+ await expect(geckoFetch(path, { ttlMs: 0 })).resolves.toEqual({ id: 'warm2' });+ });++ it('propagates a 404 as a real error even when a stale value exists', async () => {+ const path = `/coins/stale-404-${Math.round(performance.now())}`;+ global.fetch = vi.fn().mockResolvedValueOnce(ok({ id: 'was-here' }));+ await geckoFetch(path, { ttlMs: 0 });++ global.fetch = vi.fn().mockResolvedValue(fail(404));+ await expect(geckoFetch(path, { ttlMs: 0 })).rejects.toMatchObject({ status: 404 });+ });++ it('throws on the first-ever fetch when there is no stale buffer to fall back on', async () => {+ const path = `/coins/cold-429-${Math.round(performance.now())}`;+ global.fetch = vi.fn().mockResolvedValue(fail(429));+ await expect(geckoFetch(path)).rejects.toMatchObject({ status: 429 });+ });++ it('returns fresh cache without re-hitting upstream inside the TTL', async () => {+ const path = `/coins/fresh-${Math.round(performance.now())}`;+ global.fetch = vi.fn().mockResolvedValue(ok({ id: 'cached' }));+ await geckoFetch(path, { ttlMs: 60_000 });+ await geckoFetch(path, { ttlMs: 60_000 });+ expect(global.fetch).toHaveBeenCalledTimes(1);+ });+});diff --git a/tests/commit-feed-push.test.js b/tests/commit-feed-push.test.jsnew file mode 100644index 000000000..070e35fa4--- /dev/null+++ b/tests/commit-feed-push.test.js@@ -0,0 +1,124 @@+import { describe, it, expect } from 'vitest';+import {+ splitSubject,+ prettyHeadline,+ commitPreviewUrl,+ formatTelegramMessage,+} from '../api/_lib/commit-feed-push.js';+import commitOg from '../api/commit-og.js';++const commit = (over = {}) => ({+ sha: 'abcdef1234567890abcdef1234567890abcdef12',+ html_url: 'https://github.com/nirholas/three.ws/commit/abcdef1234567890abcdef1234567890abcdef12',+ commit: {+ message: 'feat: add a thing\n\nlonger body ignored',+ author: { name: 'nirholas', date: '2026-07-22T12:00:00Z' },+ },+ author: { login: 'nirholas' },+ ...over,+});++describe('splitSubject', () => {+ it('splits scope: description on an early colon', () => {+ expect(splitSubject('feat: add a thing')).toEqual({ headline: 'feat', body: 'add a thing' });+ expect(splitSubject('Avatar Studio: 122 sliders')).toEqual({+ headline: 'Avatar Studio',+ body: '122 sliders',+ });+ });+ it('falls back to New commit when there is no early colon', () => {+ expect(splitSubject('Escape a raw NUL byte in the test')).toEqual({+ headline: 'New commit',+ body: 'Escape a raw NUL byte in the test',+ });+ });+ it('does not split on a late colon', () => {+ const s = 'this is a very long subject line that carries its only colon well past sixty: nope';+ expect(splitSubject(s).headline).toBe('New commit');+ });+});++describe('prettyHeadline', () => {+ it('maps conventional-commit types to friendly labels', () => {+ expect(prettyHeadline('feat')).toBe('Feature');+ expect(prettyHeadline('fix')).toBe('Fix');+ expect(prettyHeadline('PERF')).toBe('Performance');+ });+ it('passes real scopes through untouched', () => {+ expect(prettyHeadline('Avatar Studio')).toBe('Avatar Studio');+ expect(prettyHeadline('/cookbook')).toBe('/cookbook');+ expect(prettyHeadline('New commit')).toBe('New commit');+ });+});++describe('formatTelegramMessage', () => {+ it('uses the prettified headline as the bold title', () => {+ const msg = formatTelegramMessage(commit());+ expect(msg).toContain('<b>Feature</b>');+ expect(msg).toContain('add a thing');+ expect(msg).toContain('github.com/nirholas/three.ws/commit/abcdef1');+ });+ it('escapes HTML in the subject body', () => {+ const msg = formatTelegramMessage(commit({ commit: { message: 'fix: guard <script> & co', author: {} } }));+ expect(msg).toContain('guard <script> & co');+ expect(msg).not.toContain('<script>');+ });+});++describe('commitPreviewUrl', () => {+ it('points at the branded commit-og landing with the sha and pretty headline', () => {+ const u = new URL(commitPreviewUrl(commit()));+ expect(u.origin + u.pathname).toBe('https://three.ws/api/commit-og');+ expect(u.searchParams.get('sha')).toBe('abcdef1234567890abcdef1234567890abcdef12');+ expect(u.searchParams.get('t')).toBe('Feature');+ expect(u.searchParams.get('d')).toBe('add a thing');+ expect(u.searchParams.get('author')).toBe('nirholas');+ });+});++// Minimal ServerResponse stub for the HTML handler.+function capture() {+ const res = {+ statusCode: 0,+ headers: {},+ body: '',+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ end(s) {+ this.body = s || '';+ },+ };+ return res;+}++describe('commit-og handler', () => {+ it('emits OG tags and a validated GitHub redirect', () => {+ const res = capture();+ commitOg(+ { url: '/api/commit-og?sha=abcdef1234567&t=Feature&d=add%20a%20thing&date=2026-07-22&author=nirholas' },+ res,+ );+ expect(res.statusCode).toBe(200);+ expect(res.headers['content-type']).toContain('text/html');+ expect(res.body).toContain('<meta property="og:title" content="Feature">');+ expect(res.body).toContain('property="og:image" content="https://three.ws/api/page-og?s=commit');+ expect(res.body).toContain('github.com/nirholas/three.ws/commit/abcdef1234567');+ // redirect target is the commit, not a caller-supplied url+ expect(res.body).toContain('url=https://github.com/nirholas/three.ws/commit/abcdef1234567');+ });++ it('rejects a non-hex sha and falls back to the commits page (no open redirect)', () => {+ const res = capture();+ commitOg({ url: '/api/commit-og?sha=https://evil.example/pwn&t=x' }, res);+ expect(res.body).not.toContain('evil.example');+ expect(res.body).toContain('github.com/nirholas/three.ws/commits/main');+ });++ it('escapes HTML in OG attribute values', () => {+ const res = capture();+ commitOg({ url: '/api/commit-og?sha=abcdef1&t=' + encodeURIComponent('a" onload="x') }, res);+ expect(res.body).not.toContain('onload="x"');+ expect(res.body).toContain('"');+ });+});