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(agent-screen): keep periodic frames out of the 50-entry activity log

nirholas974150b0a632
diff --git a/api/agent-screen-push.js b/api/agent-screen-push.js
index 307d3ba9d..5a5ffe9ae 100644
--- a/api/agent-screen-push.js
+++ b/api/agent-screen-push.js
@@ -89,6 +89,16 @@ export function sanitizeMm(mm) {
return out;
}
+// A pixels-only push (a periodic screenshot with no activity text) belongs in
+// the frame slot, never in the 50-entry activity log: services/agent-screen-caster
+// pushes one every FRAME_INTERVAL_MS, so logging them evicts the agent's real
+// narration within seconds and leaves watchers reading blank lines. Log an entry
+// only when it carries something to read: activity text, or a structured
+// ride-along (PnL / forge meta / market-maker) the viewer renders on its own.
+export function shouldLogEntry({ activity, pnl, meta, mm }) {
+ return Boolean(activity || pnl || meta || mm);
+}
+
export default async function handleAgentScreenPush(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
if (!method(req, res, ['POST'])) return;
@@ -172,10 +182,14 @@ export default async function handleAgentScreenPush(req, res) {
// Log entry (no image — the activity log only needs text + metadata)
const logEntry = JSON.stringify({ ts: now, activity, type, ...(pnl ? { pnl } : {}), ...(meta ? { meta } : {}), ...(mm ? { mm } : {}) });
+ const logs = shouldLogEntry({ activity, pnl, meta, mm });
+
await Promise.all([
r.set(frameKey, frameRecord, { ex: FRAME_TTL }),
- r.lpush(logKey, logEntry).then(() => r.ltrim(logKey, 0, LOG_CAP - 1)),
- r.expire(logKey, FRAME_TTL * 5),
+ ...(logs ? [
+ r.lpush(logKey, logEntry).then(() => r.ltrim(logKey, 0, LOG_CAP - 1)),
+ r.expire(logKey, FRAME_TTL * 5),
+ ] : []),
// Track active agents in a sorted set (score = timestamp) so the walk
// scene can discover which agents have live streams to show desks for.
r.zadd('agent:screen:active', { score: now, member: agentId }),
diff --git a/api/agent-screen-stream.js b/api/agent-screen-stream.js
index d34c5df6b..6289742f7 100644
--- a/api/agent-screen-stream.js
+++ b/api/agent-screen-stream.js
@@ -61,6 +61,19 @@ function rowToEntry(row) {
return entry;
}
+// Decode one record read back out of Redis. The Upstash REST client
+// deserializes JSON responses by default, so a value written as a JSON string
+// comes back as an ALREADY-PARSED object; running JSON.parse over that throws
+// and the record is silently dropped. That is exactly what happened to every
+// live caster's activity log and to every viewer reaction: the frame poll below
+// handled both shapes, these two read paths did not, so the log arrived empty
+// and reactions never fanned out. Returns null only for genuinely unusable data.
+export function parseRedisRecord(value) {
+ if (value && typeof value === 'object') return value;
+ if (typeof value !== 'string') return null;
+ try { return JSON.parse(value); } catch { return null; }
+}
+
// Fetch the agent's most recent real activity from the database. Used as the
// always-available fallback when no live caster is pushing a structured log.
async function fetchDbActivity(agentId) {
@@ -132,12 +145,15 @@ export default async function handleAgentScreenStream(req, res) {
try {
const logKey = `agent:screen:${agentId}:log`;
const raw = await r.lrange(logKey, 0, 49);
- if (raw?.length) {
+ const entries = (raw || [])
+ .map(parseRedisRecord)
+ .filter(Boolean)
+ .reverse(); // oldest-first for display
+ // Only an entry we could actually decode counts as a live caster log.
+ // An undecodable list must fall through to the DB backfill rather than
+ // leave the panel blank behind a `hasRedisLog` flag it never earned.
+ if (entries.length) {
hasRedisLog = true;
- const entries = raw
- .map((s) => { try { return JSON.parse(s); } catch { return null; } })
- .filter(Boolean)
- .reverse(); // oldest-first for display
send('log', { entries });
}
} catch { /* non-fatal */ }
@@ -204,7 +220,7 @@ export default async function handleAgentScreenStream(req, res) {
try {
const raw = await r.get(frameKey);
if (raw) {
- const frame = typeof raw === 'string' ? JSON.parse(raw) : raw;
+ const frame = parseRedisRecord(raw);
if (frame?.ts && frame.ts !== lastTs) {
lastTs = frame.ts;
wasDark = false;
@@ -227,7 +243,7 @@ export default async function handleAgentScreenStream(req, res) {
const recent = await r.lrange(reactionKey, 0, REACTION_RECENT_CAP - 1);
if (recent?.length) {
const fresh = recent
- .map((s) => { try { return JSON.parse(s); } catch { return null; } })
+ .map(parseRedisRecord)
.filter((x) => x && Number(x.ts) > lastReactionTs)
.sort((a, b) => a.ts - b.ts);
if (fresh.length) {
diff --git a/services/agent-screen-caster/Dockerfile b/services/agent-screen-caster/Dockerfile
index df9238cc5..d3d591482 100644
--- a/services/agent-screen-caster/Dockerfile
+++ b/services/agent-screen-caster/Dockerfile
@@ -1,8 +1,11 @@
# syntax=docker/dockerfile:1
-# Agent Screen Caster — Playwright Chromium runner
+# Agent Screen Caster: Playwright Chromium runner.
# Base: official Playwright image ships Chromium + all system deps pre-installed.
-# Pin the version to match the playwright package version in package.json.
-FROM mcr.microsoft.com/playwright:v1.49.0-jammy
+# The tag MUST match the exact playwright version pinned in package.json. The
+# image bakes one Chromium build under /ms-playwright and the npm package only
+# looks for the revision it was published with, so a floating range here means
+# "Executable doesn't exist at /ms-playwright/chromium-<rev>" at container boot.
+FROM mcr.microsoft.com/playwright:v1.60.0-jammy
WORKDIR /app
diff --git a/services/agent-screen-caster/caster.js b/services/agent-screen-caster/caster.js
index 35654223f..b5a0db572 100644
--- a/services/agent-screen-caster/caster.js
+++ b/services/agent-screen-caster/caster.js
@@ -9,7 +9,7 @@
* const caster = new AgentScreenCaster({ agentId, bearerToken, pushUrl });
* await caster.launch();
* await caster.navigate('https://pump.fun');
- * await caster.act('buy', async () => { ... });
+ * await caster.act('buy', 'Buying the dip', async () => { ... });
* caster.startFrameLoop();
* // … later …
* await caster.close();
@@ -21,6 +21,15 @@ const DEFAULT_PUSH_URL = 'https://three.ws/api/agent-screen-push';
const DEFAULT_FRAME_INTERVAL = 400; // ms between periodic captures
const DEFAULT_JPEG_QUALITY = 72;
const DEFAULT_VIEWPORT = { width: 1280, height: 720 };
+const ACTIVITY_RETRIES = 2; // extra attempts for an activity push
+const RETRY_BACKOFF_MS = 500; // multiplied by the attempt number
+
+/** 429 and 5xx are worth another attempt; every other status is a verdict. */
+export function isRetryableStatus(status) {
+ return status === 429 || (status >= 500 && status <= 599);
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
export class AgentScreenCaster {
/**
@@ -46,11 +55,13 @@ export class AgentScreenCaster {
this.page = null;
this._timer = null;
this._pushing = false; // guard against overlapping push calls
+ this._closing = false; // set by close() so a racing capture stays quiet
}
// ── Lifecycle ──────────────────────────────────────────────────────────────
async launch(headless = true) {
+ this._closing = false;
this.browser = await chromium.launch({
headless,
args: [
@@ -77,6 +88,7 @@ export class AgentScreenCaster {
}
async close() {
+ this._closing = true;
this.stopFrameLoop();
try { await this.browser?.close(); } catch {}
this.browser = this.context = this.page = null;
@@ -130,7 +142,7 @@ export class AgentScreenCaster {
* Capture the current page as JPEG and POST it to screen-push as a data URL.
*/
async pushFrame() {
- if (!this.page) return;
+ if (!this.page || this._closing) return;
const buf = await this.page.screenshot({
type: 'jpeg',
@@ -138,10 +150,13 @@ export class AgentScreenCaster {
fullPage: false,
});
+ // Frames are not retried: a dropped screenshot is worthless a second
+ // later, the next capture is already on its way, and a retry backlog
+ // would outlive the frame interval it was meant to protect.
await this._post({
agentId: this.agentId,
frame: { data: `data:image/jpeg;base64,${buf.toString('base64')}`, type: 'screenshot' },
- });
+ }, { retries: 0 });
}
/**
@@ -154,10 +169,12 @@ export class AgentScreenCaster {
async pushActivity(actions) {
for (const a of actions || []) {
if (!a?.summary) continue;
+ // Activity is the semantic record of what the agent did, so unlike a
+ // frame it is worth retrying through a rate limit or a server blip.
await this._post({
agentId: this.agentId,
frame: { activity: String(a.summary), type: a.type },
- });
+ }, { retries: ACTIVITY_RETRIES });
}
}
@@ -165,32 +182,55 @@ export class AgentScreenCaster {
/** Non-throwing frame push — safe to call from event handlers and timers. */
async _safePushFrame() {
- if (this._pushing) return;
+ if (this._pushing || this._closing) return;
this._pushing = true;
try {
await this.pushFrame();
} catch (err) {
- console.error('[caster] frame push failed:', err?.message || err);
+ // A capture that loses the race with close() is expected teardown,
+ // not a failure worth printing on every shutdown.
+ if (!this._closing) console.error('[caster] frame push failed:', err?.message || err);
} finally {
this._pushing = false;
}
}
- async _post(body) {
- const res = await fetch(this.pushUrl, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${this.bearerToken}`,
- },
- body: JSON.stringify(body),
- });
-
- if (!res.ok) {
- const text = await res.text().catch(() => '');
- throw new Error(`screen-push ${res.status}: ${text}`);
+ /**
+ * POST to the push endpoint, retrying only what a retry can fix.
+ *
+ * A 4xx (bad token, agent not owned, malformed frame) is a permanent answer
+ * and throws immediately. A 429, a 5xx, or a network error is transient, and
+ * a long-running caster that dies on one of those loses the whole session.
+ *
+ * @param {object} body
+ * @param {{ retries?: number }} [opts]
+ */
+ async _post(body, { retries = 0 } = {}) {
+ let lastErr;
+ for (let attempt = 0; attempt <= retries; attempt++) {
+ if (attempt > 0) await sleep(RETRY_BACKOFF_MS * attempt);
+ try {
+ const res = await fetch(this.pushUrl, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${this.bearerToken}`,
+ },
+ body: JSON.stringify(body),
+ });
+
+ if (res.ok) return res.json();
+
+ const text = await res.text().catch(() => '');
+ const err = new Error(`screen-push ${res.status}: ${text}`);
+ err.status = res.status;
+ if (!isRetryableStatus(res.status)) throw err;
+ lastErr = err;
+ } catch (err) {
+ if (err?.status && !isRetryableStatus(err.status)) throw err;
+ lastErr = err;
+ }
}
-
- return res.json();
+ throw lastErr;
}
}
diff --git a/services/agent-screen-caster/index.js b/services/agent-screen-caster/index.js
index 01d0f0b85..cd89299a9 100644
--- a/services/agent-screen-caster/index.js
+++ b/services/agent-screen-caster/index.js
@@ -13,7 +13,8 @@
* Spin up additional AgentScreenCaster instances (each with their own
* agentId/bearerToken) and run their task functions concurrently.
*
- * Env vars (see .env.example for full list):
+ * Env vars (README.md holds the full table, including the trade task's
+ * WALLET_STORAGE_STATE_PATH):
* AGENT_ID UUID of the agent identity (required)
* AGENT_BEARER_TOKEN JWT or API key (required)
* PUSH_URL Override push endpoint (default: https://three.ws/api/agent-screen-push)
diff --git a/services/agent-screen-caster/package.json b/services/agent-screen-caster/package.json
index d538fadef..37d8f1d21 100644
--- a/services/agent-screen-caster/package.json
+++ b/services/agent-screen-caster/package.json
@@ -10,6 +10,6 @@
},
"engines": { "node": ">=20" },
"dependencies": {
- "playwright": "^1.49.0"
+ "playwright": "1.60.0"
}
}
diff --git a/services/agent-screen-caster/tasks/trade.js b/services/agent-screen-caster/tasks/trade.js
index 97a9cb050..ef5282619 100644
--- a/services/agent-screen-caster/tasks/trade.js
+++ b/services/agent-screen-caster/tasks/trade.js
@@ -111,7 +111,7 @@ async function executePumpTrade(caster, mint, amountSol) {
await caster.act('input', `Entering trade amount: ${amountSol} SOL`, async () => {
const input = await caster.page.waitForSelector(PUMP_SEL.amountInput, { timeout: 8000 });
- await input.triple_click?.() ?? await input.click({ clickCount: 3 });
+ await input.click({ clickCount: 3 });
await input.fill(String(amountSol));
await caster.page.waitForTimeout(300);
});