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.

feat(x-grok): build the X gateway adapter, dry run by default

nirholase663459cdbb0
diff --git a/api/_lib/gateway/adapters/x.js b/api/_lib/gateway/adapters/x.js
new file mode 100644
index 000000000..15c218757
--- /dev/null
+++ b/api/_lib/gateway/adapters/x.js
@@ -0,0 +1,163 @@
+// @ts-check
+// The X adapter for the chat gateway core (api/_lib/gateway/core.js docblock):
+// it turns one decided mention reply into the platform calls that answer it.
+//
+// Unlike the Telegram and Discord adapters (workers/agent-gateway/src/adapters/),
+// which open one long-lived gateway and dispatch many events through it, an X
+// mention is a single request/response: read one mention, decide once, answer
+// once. So this adapter is a factory per mention, closed over the specific
+// tweet being answered, rather than a shared gateway keyed by a chat id. There
+// is no X equivalent of a chat id to route on: in_reply_to_tweet_id is always
+// the mention itself (or the previous part of this same reply chain).
+//
+// X has no inline buttons, so sendButtons is text plus one link back to
+// three.ws where the actual choice is made. typing is a no-op: X has no
+// typing indicator for a reply that has not been posted yet.
+//
+// Dry run (x-grok design rule 3) is the default and the only mode this order
+// ships: X_MENTION_BOT_LIVE must be exactly '1', and the caller may still
+// force dry run underneath that (an agent's own mention-reply policy, order
+// 060, once it exists) by passing `live: false` explicitly. In dry run,
+// nothing reaches X: every send writes the would-be reply onto the mention's
+// already-recorded x_mention_events row (x-mention-store.js) and returns a
+// synthetic delivery record instead of a real tweet id.
+//
+// A mention must already be recorded (x-mention-store.recordMention) before
+// an adapter is used to answer it; this module only ever updates that row.
+
+import { postOne, uploadMediaV2 } from '../../x-post.js';
+import { updateDecision } from '../../x-mention-store.js';
+import { appOrigin } from '../format.js';
+import { chunkForX, MAX_WEIGHTED_LENGTH } from '../x-text-weight.js';
+
+export class XAdapterError extends Error {
+ /** @param {string} message @param {string} code */
+ constructor(message, code) {
+ super(message);
+ this.name = 'XAdapterError';
+ this.code = code;
+ }
+}
+
+/** True only when the deployment-wide switch (owner action, order 928) is on. */
+export function isXMentionBotLive(env = process.env) {
+ return env.X_MENTION_BOT_LIVE === '1';
+}
+
+function syntheticId(mentionId, index) {
+ return `dry_run:${mentionId}:${index}`;
+}
+
+/**
+ * @param {object} opts
+ * @param {object} opts.mention a normalized mention (x-mentions.js), already recorded
+ * @param {string} [opts.accessToken] the resolved OAuth2 token to post with; required when live
+ * @param {boolean|null} [opts.live] overrides X_MENTION_BOT_LIVE when false (a dry-run policy); null defers to the env flag
+ * @param {Record<string,string|undefined>} [opts.env]
+ */
+export function createXAdapter({ mention, accessToken = null, live = null, env = process.env } = {}) {
+ if (!mention?.id) throw new XAdapterError('the X adapter needs the mention being replied to', 'bad_mention');
+ const isLive = live != null ? !!live : isXMentionBotLive(env);
+ if (isLive && !accessToken) throw new XAdapterError('live sends need an accessToken', 'no_token');
+
+ let chainTip = String(mention.id);
+ /** @type {{id:string, text:string}[]} */
+ const parts = [];
+
+ async function postPart(text, mediaIds = null) {
+ if (!isLive) {
+ const id = syntheticId(mention.id, parts.length);
+ parts.push({ id, text });
+ return { id, dryRun: true };
+ }
+ const posted = await postOne({ accessToken, text, replyTo: chainTip, mediaIds });
+ chainTip = String(posted.id);
+ parts.push({ id: chainTip, text });
+ return { id: chainTip, dryRun: false };
+ }
+
+ async function recordReply(fields) {
+ const row = await updateDecision(mention.id, {
+ decision: 'reply',
+ dryRun: !isLive,
+ replyTweetId: parts[0]?.id ?? null,
+ ...fields,
+ });
+ if (!row) throw new XAdapterError(`mention ${mention.id} was never recorded; call recordMention first`, 'not_recorded');
+ return row;
+ }
+
+ async function recordFailure(err) {
+ try {
+ await updateDecision(mention.id, { decision: 'error', dryRun: !isLive, error: String(err?.message || err).slice(0, 2000) });
+ } catch {
+ // The original error is the one that matters; a failed failure-record
+ // (e.g. the mention truly was never recorded) must not hide it.
+ }
+ }
+
+ /**
+ * Reply to the mention with `text`, threaded as at most two posts
+ * (x-text-weight.chunkForX). Returns the first reply's id (real or
+ * synthetic) and every part actually sent.
+ * @param {string} text
+ */
+ async function sendText(text) {
+ const chunks = chunkForX(text, MAX_WEIGHTED_LENGTH);
+ if (!chunks.length) throw new XAdapterError('sendText needs non-empty text', 'empty_text');
+ try {
+ for (const chunk of chunks) await postPart(chunk);
+ await recordReply({ replyText: chunks.join('\n\n') });
+ } catch (err) {
+ await recordFailure(err);
+ throw err;
+ }
+ return { id: parts[0].id, dryRun: !isLive, parts: parts.map((p) => ({ ...p })) };
+ }
+
+ /**
+ * Reply with one attached image/video/gif and an optional caption.
+ * Live posting needs the bytes up front (`buffer`/`mimeType`): this
+ * adapter never fetches a caller-supplied URL itself, so a remote media
+ * source is never a path to an SSRF-style request on our behalf. `url`
+ * is recorded for the dry-run review console and the delivered reply.
+ * @param {{ url: string, buffer?: Buffer, mimeType?: string, caption?: string }} media
+ */
+ async function sendMedia(media) {
+ const caption = media?.caption ? String(media.caption).trim() : '';
+ if (!media?.url) throw new XAdapterError('sendMedia needs a media url to record', 'no_media_url');
+ try {
+ let mediaIds = null;
+ if (isLive) {
+ if (!media.buffer || !media.mimeType) throw new XAdapterError('sendMedia needs buffer+mimeType to upload live', 'no_media_bytes');
+ mediaIds = [await uploadMediaV2({ accessToken, buffer: media.buffer, mimeType: media.mimeType })];
+ }
+ const text = caption ? chunkForX(caption, MAX_WEIGHTED_LENGTH)[0] || '' : '';
+ await postPart(text, mediaIds);
+ await recordReply({ replyText: text || null, replyMediaUrl: media.url });
+ } catch (err) {
+ await recordFailure(err);
+ throw err;
+ }
+ return { id: parts[0].id, dryRun: !isLive, parts: parts.map((p) => ({ ...p })) };
+ }
+
+ /**
+ * X has no inline buttons: render the choices as a plain list plus one
+ * link back to three.ws, where the actual action happens.
+ * @param {string} text
+ * @param {{id:string, label:string}[]} [choices]
+ * @param {{url?: string}} [opts]
+ */
+ async function sendButtons(text, choices = [], opts = {}) {
+ const url = opts.url || (mention.account?.kind === 'agent' ? `${appOrigin()}/agents/${mention.account.ref}` : appOrigin());
+ const list = (choices || []).map((c) => `- ${c.label}`).join('\n');
+ const body = [String(text || '').trim(), list, `Continue: ${url}`].filter(Boolean).join('\n\n');
+ return sendText(body);
+ }
+
+ /** X has no typing indicator for an unsent reply. */
+ async function typing() {}
+
+ return { platform: 'x', dryRun: !isLive, sendText, sendMedia, sendButtons, typing };
+}
diff --git a/api/_lib/gateway/x-text-weight.js b/api/_lib/gateway/x-text-weight.js
new file mode 100644
index 000000000..520ba0f7a
--- /dev/null
+++ b/api/_lib/gateway/x-text-weight.js
@@ -0,0 +1,131 @@
+// @ts-check
+// X's documented "weighted length" counting (config v3: scale 100, default
+// weight 200, a set of ranges weighted 100), the same rule x.com's own
+// composer and every first-party client enforce. A post is valid when its
+// weighted length is at most 280.
+//
+// We do not depend on the `twitter-text` npm package for this: its last
+// publish was 2022-06-28 (verified against the npm registry on 2026-10-11,
+// over four years stale against CLAUDE.md's open-source-first bar), it pulls
+// core-js, @babel/runtime and twemoji-parser for a counting function, and the
+// weighting rule itself is a short, stable, publicly documented table. A
+// faithful reimplementation is smaller and has no transitive dependencies to
+// go stale under us.
+//
+// PURE. No network, no clock.
+
+export const MAX_WEIGHTED_LENGTH = 280;
+export const TRANSFORMED_URL_LENGTH = 23;
+
+const SCALE = 100;
+const DEFAULT_WEIGHT = 200;
+// Codepoints in these ranges weigh 100 (1 weighted char): Basic Latin through
+// Arabic Extended-A. Everything else, including CJK ideographs and emoji,
+// falls through to DEFAULT_WEIGHT (2 weighted chars).
+const RANGES = [
+ { start: 0, end: 4351, weight: 100 },
+ { start: 8192, end: 8205, weight: 100 },
+ { start: 8208, end: 8223, weight: 100 },
+ { start: 8242, end: 8247, weight: 100 },
+];
+
+const URL_RE = /https?:\/\/[^\s<>()[\]{}"']+/gi;
+
+function weightFor(codePoint) {
+ for (const r of RANGES) if (codePoint >= r.start && codePoint <= r.end) return r.weight;
+ return DEFAULT_WEIGHT;
+}
+
+/** Non-overlapping, ordered spans of every http(s) URL in `str`. PURE. */
+function urlSpans(str) {
+ const spans = [];
+ URL_RE.lastIndex = 0;
+ let m;
+ while ((m = URL_RE.exec(str))) spans.push({ start: m.index, end: m.index + m[0].length });
+ return spans;
+}
+
+/**
+ * X's weighted length of `text`: most scripts count 1 per character, CJK and
+ * other wide scripts count 2, and any http(s) URL counts as exactly
+ * TRANSFORMED_URL_LENGTH regardless of its real length (X rewrites it to a
+ * t.co link of that length). PURE.
+ * @param {string} text
+ */
+export function weightedLength(text) {
+ const str = String(text ?? '');
+ const spans = urlSpans(str);
+ let total = 0;
+ let pos = 0;
+ let spanIdx = 0;
+ while (pos < str.length) {
+ const span = spans[spanIdx];
+ if (span && pos === span.start) {
+ total += TRANSFORMED_URL_LENGTH * SCALE;
+ pos = span.end;
+ spanIdx += 1;
+ continue;
+ }
+ const cp = str.codePointAt(pos);
+ total += weightFor(cp);
+ pos += cp > 0xffff ? 2 : 1;
+ }
+ return Math.ceil(total / SCALE);
+}
+
+/** Whether `text` fits in one post of X's documented 280-weighted-character cap. */
+export function fitsInTweet(text, max = MAX_WEIGHTED_LENGTH) {
+ return weightedLength(text) <= max;
+}
+
+/**
+ * The longest prefix of `str` whose weighted length is at most `maxWeight`,
+ * preferring to break on whitespace near that boundary so words are not cut
+ * mid-way. PURE.
+ */
+export function sliceToWeight(str, maxWeight) {
+ if (maxWeight <= 0) return '';
+ if (weightedLength(str) <= maxWeight) return str;
+ let lo = 0;
+ let hi = str.length;
+ while (lo < hi) {
+ const mid = Math.ceil((lo + hi) / 2);
+ if (weightedLength(str.slice(0, mid)) <= maxWeight) lo = mid;
+ else hi = mid - 1;
+ }
+ let cut = lo;
+ // Never split a UTF-16 surrogate pair.
+ if (cut > 0 && cut < str.length) {
+ const code = str.charCodeAt(cut - 1);
+ if (code >= 0xd800 && code <= 0xdbff) cut -= 1;
+ }
+ const searchFrom = Math.max(0, cut - 40);
+ const lastSpace = str.lastIndexOf(' ', cut);
+ if (lastSpace > searchFrom) cut = lastSpace;
+ return str.slice(0, cut).trimEnd();
+}
+
+const ELLIPSIS = '...';
+
+/**
+ * Split `text` into at most two posts, each within `limit` weighted
+ * characters. A reply that still overflows after two parts is truncated with
+ * an ellipsis on the second part rather than growing a longer chain: a
+ * mention reply is a short answer, not a thread. PURE.
+ * @param {string} text
+ * @param {number} [limit]
+ * @returns {string[]} 0, 1 or 2 non-empty posts
+ */
+export function chunkForX(text, limit = MAX_WEIGHTED_LENGTH) {
+ const str = String(text ?? '').trim();
+ if (!str) return [];
+ if (fitsInTweet(str, limit)) return [str];
+
+ const first = sliceToWeight(str, limit);
+ const rest = str.slice(first.length).trim();
+ if (!rest) return [first];
+ if (fitsInTweet(rest, limit)) return [first, rest];
+
+ const second = sliceToWeight(rest, Math.max(0, limit - weightedLength(ELLIPSIS)));
+ return [first, `${second.trimEnd()}${ELLIPSIS}`];
+}
diff --git a/api/_lib/x-post.js b/api/_lib/x-post.js
index 735dc216a..f0edfd602 100644
--- a/api/_lib/x-post.js
+++ b/api/_lib/x-post.js
@@ -84,7 +84,7 @@ export async function refreshIfNeeded(conn) {
return tok.access_token;
}
-async function postOne({ accessToken, text, replyTo, mediaIds = null }) {
+export async function postOne({ accessToken, text, replyTo, mediaIds = null }) {
const body = {};
if (text) body.text = text;
if (replyTo) body.reply = { in_reply_to_tweet_id: replyTo };
diff --git a/tests/x-gateway-adapter-x.test.js b/tests/x-gateway-adapter-x.test.js
new file mode 100644
index 000000000..44e28de69
--- /dev/null
+++ b/tests/x-gateway-adapter-x.test.js
@@ -0,0 +1,240 @@
+// The X adapter (api/_lib/gateway/adapters/x.js) against a real x_mention_events
+// row (PGlite, schema from the migration file itself) and a stubbed fetch at
+// the HTTP boundary, the same patterns tests/x-mention-store.test.js and
+// tests/upstream-fetch.test.js already use.
+
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { PGlite } from '@electric-sql/pglite';
+
+const dbState = { pg: null };
+
+vi.mock('../api/_lib/db.js', () => {
+ const sql = async (strings, ...values) => {
+ const text = strings.reduce((acc, part, i) => acc + part + (i < values.length ? `$${i + 1}` : ''), '');
+ const out = await dbState.pg.query(text, values);
+ return out.rows;
+ };
+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };
+});
+
+const { _resetBreakers } = await import('../api/_lib/resilience.js');
+const { createXAdapter, isXMentionBotLive, XAdapterError } = await import('../api/_lib/gateway/adapters/x.js');
+const store = await import('../api/_lib/x-mention-store.js');
+const { normalizeMentions } = await import('../api/_lib/x-mentions.js');
+const { parseMentionIntent } = await import('../api/_lib/x-mention-intents.js');
+
+const MIG = new URL('../api/_lib/migrations/', import.meta.url);
+const MIGRATION = readFileSync(new URL('20261008170000_x_mention_events.sql', MIG), 'utf8');
+const APP_SETTINGS = (() => {
+ const src = readFileSync(new URL('20260922210000_free_tier_models.sql', MIG), 'utf8');
+ const start = src.indexOf('CREATE TABLE IF NOT EXISTS app_settings');
+ return src.slice(start, src.indexOf(');', start) + 2);
+})();
+
+const COMPANY = { kind: 'company', ref: 'trythreews', userId: '1700000000000000001', handle: 'trythreews' };
+const page = JSON.parse(readFileSync(join(process.cwd(), 'tests', 'fixtures', 'x-mentions', 'timeline-page.fixture.json'), 'utf8'));
+const MENTIONS = normalizeMentions(page, COMPANY);
+const byId = (id) => MENTIONS.find((m) => m.id === id);
+const record = (m) => store.recordMention({ mention: m, parsed: parseMentionIntent(m) });
+
+const json = (body, init = {}) => new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' }, ...init });
+
+let origFetch;
+beforeEach(async () => {
+ dbState.pg = new PGlite();
+ await dbState.pg.exec(APP_SETTINGS);
+ await dbState.pg.exec(MIGRATION);
+ origFetch = global.fetch;
+ _resetBreakers();
+});
+
+describe('isXMentionBotLive', () => {
+ it('is live only when the flag is exactly "1"', () => {
+ expect(isXMentionBotLive({})).toBe(false);
+ expect(isXMentionBotLive({ X_MENTION_BOT_LIVE: 'true' })).toBe(false);
+ expect(isXMentionBotLive({ X_MENTION_BOT_LIVE: '1' })).toBe(true);
+ });
+});
+
+describe('dry run (the default and the only mode this order ships)', () => {
+ it('posts nothing: zero fetch calls for a text reply', async () => {
+ const m = byId('1800000000000000101');
+ await record(m);
+ const fetchMock = vi.fn();
+ global.fetch = fetchMock;
+ const gw = createXAdapter({ mention: m, env: {} });
+ expect(gw.dryRun).toBe(true);
+ const result = await gw.sendText('Here is your cat in 3D.');
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(result.dryRun).toBe(true);
+ expect(result.id).toMatch(/^dry_run:/);
+ global.fetch = origFetch;
+ });
+
+ it('leaves a complete row in x_mention_events', async () => {
+ const m = byId('1800000000000000101');
+ await record(m);
+ global.fetch = vi.fn();
+ const gw = createXAdapter({ mention: m, env: {} });
+ await gw.sendText('Here is your cat in 3D.');
+ global.fetch = origFetch;
+
+ const row = await store.getMentionEvent(m.id);
+ expect(row).toMatchObject({
+ decision: 'reply',
+ reply_text: 'Here is your cat in 3D.',
+ dry_run: true,
+ });
+ expect(row.reply_tweet_id).toMatch(/^dry_run:/);
+ expect(row.decided_at).not.toBeNull();
+ expect(row.replied_at).not.toBeNull();
+ });
+
+ it('also dry-runs when the owner policy forces it even if the env flag is live', async () => {
+ const m = byId('1800000000000000104');
+ await record(m);
+ global.fetch = vi.fn();
+ const gw = createXAdapter({ mention: m, live: false, env: { X_MENTION_BOT_LIVE: '1' } });
+ await gw.sendText('hi');
+ global.fetch = origFetch;
+ expect(gw.dryRun).toBe(true);
+ const row = await store.getMentionEvent(m.id);
+ expect(row.dry_run).toBe(true);
+ });
+
+ it('sendMedia records the media url and posts nothing', async () => {
+ const m = byId('1800000000000000104');
+ await record(m);
+ global.fetch = vi.fn();
+ const gw = createXAdapter({ mention: m, env: {} });
+ const result = await gw.sendMedia({ url: 'https://three.ws/render/abc.png', caption: 'your lighthouse' });
+ global.fetch = origFetch;
+ expect(result.dryRun).toBe(true);
+ const row = await store.getMentionEvent(m.id);
+ expect(row.reply_media_url).toBe('https://three.ws/render/abc.png');
+ expect(row.reply_text).toBe('your lighthouse');
+ });
+
+ it('sendButtons renders choices as a list plus one three.ws link, no buttons', async () => {
+ const m = byId('1800000000000000105');
+ const notRetweet = { ...m, isRetweet: false };
+ await record(notRetweet);
+ global.fetch = vi.fn();
+ const gw = createXAdapter({ mention: notRetweet, env: {} });
+ await gw.sendButtons('Pick one', [{ id: 'a', label: 'Make it 3D' }, { id: 'b', label: 'Launch it' }]);
+ global.fetch = origFetch;
+ const row = await store.getMentionEvent(notRetweet.id);
+ expect(row.reply_text).toContain('Pick one');
+ expect(row.reply_text).toContain('- Make it 3D');
+ expect(row.reply_text).toContain('- Launch it');
+ expect(row.reply_text).toContain('Continue: https://three.ws');
+ });
+
+ it('typing is a no-op', async () => {
+ const m = byId('1800000000000000106');
+ global.fetch = vi.fn();
+ const gw = createXAdapter({ mention: m, env: {} });
+ await expect(gw.typing()).resolves.toBeUndefined();
+ expect(global.fetch).not.toHaveBeenCalled();
+ global.fetch = origFetch;
+ });
+
+ it('refuses to send for a mention that was never recorded', async () => {
+ const m = byId('1800000000000000107');
+ global.fetch = vi.fn();
+ const gw = createXAdapter({ mention: m, env: {} });
+ await expect(gw.sendText('hi')).rejects.toThrow(XAdapterError);
+ global.fetch = origFetch;
+ });
+});
+
+describe('live mode: real request shape at the HTTP boundary', () => {
+ it('requires an accessToken to construct a live adapter', () => {
+ const m = byId('1800000000000000101');
+ expect(() => createXAdapter({ mention: m, live: true, env: {} })).toThrow(/accessToken/);
+ });
+
+ it('sendText posts one reply with in_reply_to_tweet_id set to the mention', async () => {
+ const m = byId('1800000000000000101');
+ await record(m);
+ const fetchMock = vi.fn(async (url, init) => {
+ expect(url).toBe('https://api.twitter.com/2/tweets');
+ expect(init.method).toBe('POST');
+ expect(init.headers.authorization).toBe('Bearer test-token');
+ const body = JSON.parse(init.body);
+ expect(body).toEqual({ text: 'Here is your cat in 3D.', reply: { in_reply_to_tweet_id: m.id } });
+ return json({ data: { id: '9000000000000000001' } });
+ });
+ global.fetch = fetchMock;
+ const gw = createXAdapter({ mention: m, accessToken: 'test-token', live: true, env: {} });
+ const result = await gw.sendText('Here is your cat in 3D.');
+ global.fetch = origFetch;
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(result).toEqual({ id: '9000000000000000001', dryRun: false, parts: [{ id: '9000000000000000001', text: 'Here is your cat in 3D.' }] });
+ const row = await store.getMentionEvent(m.id);
+ expect(row).toMatchObject({ decision: 'reply', dry_run: false, reply_tweet_id: '9000000000000000001' });
+ });
+
+ it('a two-part reply threads the second part onto the first, not the mention', async () => {
+ const m = byId('1800000000000000104');
+ await record(m);
+ const ids = ['9000000000000000010', '9000000000000000011'];
+ const seen = [];
+ global.fetch = vi.fn(async (url, init) => {
+ const body = JSON.parse(init.body);
+ seen.push(body.reply.in_reply_to_tweet_id);
+ return json({ data: { id: ids[seen.length - 1] } });
+ });
+ const longText = `${'first part filler text that keeps going. '.repeat(10)} SPLIT_HERE ${'second part filler text that keeps going. '.repeat(10)}`;
+ const gw = createXAdapter({ mention: m, accessToken: 'test-token', live: true, env: {} });
+ const result = await gw.sendText(longText);
+ global.fetch = origFetch;
+
+ expect(seen).toEqual([m.id, ids[0]]);
+ expect(result.parts).toHaveLength(2);
+ expect(result.id).toBe(ids[0]);
+ });
+
+ it('sendMedia uploads via the v2 media endpoint then replies with the media attached', async () => {
+ const m = byId('1800000000000000105');
+ const notRetweet = { ...m, isRetweet: false };
+ await record(notRetweet);
+ const calls = [];
+ global.fetch = vi.fn(async (url, init) => {
+ calls.push(String(url));
+ if (String(url).startsWith('https://api.x.com/2/media/upload')) {
+ const command = init.body?.get ? init.body.get('command') : new URLSearchParams(String(url).split('?')[1]).get('command');
+ if (command === 'INIT') return json({ data: { id: '800000001' } });
+ if (command === 'APPEND') return new Response('', { status: 200 });
+ if (command === 'FINALIZE') return json({ data: { id: '800000001' } });
+ }
+ return json({ data: { id: '9000000000000000099' } });
+ });
+ const gw = createXAdapter({ mention: notRetweet, accessToken: 'test-token', live: true, env: {} });
+ const result = await gw.sendMedia({ url: 'https://three.ws/render/abc.png', buffer: Buffer.from([1, 2, 3]), mimeType: 'image/png', caption: 'your render' });
+ global.fetch = origFetch;
+
+ expect(calls).toEqual([
+ 'https://api.x.com/2/media/upload',
+ 'https://api.x.com/2/media/upload',
+ 'https://api.x.com/2/media/upload',
+ 'https://api.twitter.com/2/tweets',
+ ]);
+ expect(result.dryRun).toBe(false);
+ const row = await store.getMentionEvent(notRetweet.id);
+ expect(row).toMatchObject({ reply_media_url: 'https://three.ws/render/abc.png', reply_text: 'your render', reply_tweet_id: '9000000000000000099' });
+ });
+
+ it('sendMedia refuses to upload live without bytes', async () => {
+ const m = byId('1800000000000000106');
+ await record(m);
+ global.fetch = vi.fn();
+ const gw = createXAdapter({ mention: m, accessToken: 'test-token', live: true, env: {} });
+ await expect(gw.sendMedia({ url: 'https://three.ws/render/abc.png' })).rejects.toThrow(/buffer\+mimeType/);
+ expect(global.fetch).not.toHaveBeenCalled();
+ global.fetch = origFetch;
+ });
+});
diff --git a/tests/x-text-weight.test.js b/tests/x-text-weight.test.js
new file mode 100644
index 000000000..736257854
--- /dev/null
+++ b/tests/x-text-weight.test.js
@@ -0,0 +1,105 @@
+// X's weighted-length rule (api/_lib/gateway/x-text-weight.js), reimplemented
+// from the documented config (scale 100, default weight 200, Latin-ish
+// ranges weighted 100, any http(s) URL fixed at 23) rather than depending on
+// the unmaintained `twitter-text` package. See the module header for why.
+
+import { describe, it, expect } from 'vitest';
+import { weightedLength, fitsInTweet, sliceToWeight, chunkForX, MAX_WEIGHTED_LENGTH, TRANSFORMED_URL_LENGTH } from '../api/_lib/gateway/x-text-weight.js';
+
+describe('weightedLength', () => {
+ it('counts plain ASCII as 1 per character', () => {
+ expect(weightedLength('hello world')).toBe(11);
+ });
+
+ it('counts Latin accents and Cyrillic/Hebrew/Arabic as 1 per character', () => {
+ expect(weightedLength('café')).toBe(4);
+ expect(weightedLength('привет')).toBe(6);
+ expect(weightedLength('שלום')).toBe(4);
+ });
+
+ it('counts CJK ideographs as 2 per character', () => {
+ expect(weightedLength('你好')).toBe(4);
+ expect(weightedLength('こんにちは')).toBe(10);
+ });
+
+ it('counts an emoji (outside the Basic Multilingual Plane) as 2', () => {
+ expect(weightedLength('🚀')).toBe(2);
+ });
+
+ it('counts any http(s) URL as exactly 23 regardless of its real length', () => {
+ const short = weightedLength('see https://x.co');
+ const long = weightedLength('see https://example.com/a/very/long/path/that/keeps/going?x=1&y=2');
+ expect(short).toBe('see '.length + TRANSFORMED_URL_LENGTH);
+ expect(long).toBe('see '.length + TRANSFORMED_URL_LENGTH);
+ });
+
+ it('counts multiple URLs independently', () => {
+ const text = 'https://a.example/one and https://b.example/two';
+ expect(weightedLength(text)).toBe(TRANSFORMED_URL_LENGTH + ' and '.length + TRANSFORMED_URL_LENGTH);
+ });
+
+ it('treats null/undefined/empty as zero', () => {
+ expect(weightedLength('')).toBe(0);
+ expect(weightedLength(null)).toBe(0);
+ expect(weightedLength(undefined)).toBe(0);
+ });
+});
+
+describe('fitsInTweet', () => {
+ it('accepts exactly 280 and rejects 281', () => {
+ expect(fitsInTweet('a'.repeat(280))).toBe(true);
+ expect(fitsInTweet('a'.repeat(281))).toBe(false);
+ });
+
+ it('a CJK string hits the cap at half the codepoint count', () => {
+ expect(fitsInTweet('你'.repeat(140))).toBe(true);
+ expect(fitsInTweet('你'.repeat(141))).toBe(false);
+ });
+});
+
+describe('sliceToWeight', () => {
+ it('returns the whole string when it already fits', () => {
+ expect(sliceToWeight('short', 280)).toBe('short');
+ });
+
+ it('breaks on a word boundary near the limit', () => {
+ const words = Array.from({ length: 50 }, (_, i) => `word${i}`).join(' ');
+ const cut = sliceToWeight(words, 30);
+ expect(weightedLength(cut)).toBeLessThanOrEqual(30);
+ expect(words.startsWith(cut)).toBe(true);
+ expect(cut.endsWith(' ')).toBe(false);
+ });
+
+ it('never splits a surrogate pair', () => {
+ const text = '🚀'.repeat(20);
+ const cut = sliceToWeight(text, 7);
+ expect(weightedLength(cut)).toBeLessThanOrEqual(7);
+ expect([...cut].every((ch) => [...ch].length === 1)).toBe(true);
+ });
+});
+
+describe('chunkForX', () => {
+ it('returns one chunk for short text', () => {
+ expect(chunkForX('hello there')).toEqual(['hello there']);
+ });
+
+ it('returns an empty array for blank input', () => {
+ expect(chunkForX('')).toEqual([]);
+ expect(chunkForX(' ')).toEqual([]);
+ });
+
+ it('splits text that needs two posts', () => {
+ const text = `${'a'.repeat(300)} ${'b'.repeat(100)}`;
+ const chunks = chunkForX(text);
+ expect(chunks).toHaveLength(2);
+ for (const c of chunks) expect(fitsInTweet(c)).toBe(true);
+ });
+
+ it('never yields a third part: a huge reply is truncated into exactly two', () => {
+ const text = Array.from({ length: 30 }, (_, i) => `sentence number ${i} keeps going on and on.`).join(' ');
+ const chunks = chunkForX(text);
+ expect(chunks.length).toBeLessThanOrEqual(2);
+ for (const c of chunks) expect(fitsInTweet(c)).toBe(true);
+ expect(chunks[1].endsWith('...')).toBe(true);
+ });
+});