Open-source SEO, GEO, and marketing skills for AI agents.
perf(chat): fix missing replies + pool gateway WS + add timing profiler
Yuting Zhongd6a05c1248f1
diff --git a/src/app/api/chat/route.ts b/src/app/api/chat/route.tsindex f5ce1987..ab91621d 100644--- a/src/app/api/chat/route.ts+++ b/src/app/api/chat/route.ts@@ -10,6 +10,35 @@ import {export const dynamic = "force-dynamic";export const runtime = "nodejs";+/**+ * Lightweight per-request profiler. Records ms-offsets from request start so+ * we can attribute end-to-end latency to a stage (route boot, gateway open,+ * model first-token, etc.). Marks are emitted to stdout and to the client as+ * an SSE `perf` event so they show up in both the dev terminal and the browser+ * console. Toggle off with `NOTFAIR_CHAT_PERF=0`.+ */+const PERF_ON = process.env.NOTFAIR_CHAT_PERF !== "0";++function makePerf(tag: string) {+ const start = performance.now();+ const marks: Array<{ name: string; at: number; delta: number }> = [];+ let last = start;+ const mark = (name: string) => {+ if (!PERF_ON) return;+ const now = performance.now();+ const at = now - start;+ const delta = now - last;+ last = now;+ marks.push({ name, at, delta });+ // eslint-disable-next-line no-console+ console.log(+ `[chat-perf ${tag}] +${at.toFixed(1)}ms (Δ${delta.toFixed(1)}ms) ${name}`,+ );+ };+ const summary = () => marks;+ return { mark, summary };+}+type ChatPostBody = {message: string;agent?: string;@@ -25,7 +54,10 @@ type ChatPostBody = {};export async function POST(request: Request) {+ const perf = makePerf("route");+ perf.mark("route_start");const project = await getActiveProject();+ perf.mark("active_project_resolved");if (!project) {return NextResponse.json({ error: "No active project. Create one first." },@@ -39,12 +71,14 @@ export async function POST(request: Request) {} catch {return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });}+ perf.mark("body_parsed");if (!body?.message?.trim()) {return NextResponse.json({ error: "message is required" }, { status: 400 });}const requestedSlug = (body.agent ?? "cmo").trim();const resolved = await resolveAgentBySlug(project.slug, requestedSlug);+ perf.mark("agent_resolved");if (!resolved) {return NextResponse.json({ error: `Unknown agent: '${requestedSlug}'` },@@ -69,6 +103,7 @@ export async function POST(request: Request) {const known = findSessionBySessionId(agentName, sessionId);sessionKey = known?.sessionKey ?? buildPendingSessionKey(agentName, sessionId);}+ perf.mark("session_resolved");const encoder = new TextEncoder();@@ -83,7 +118,9 @@ export async function POST(request: Request) {const abortCtl = new AbortController();request.signal?.addEventListener("abort", () => abortCtl.abort(), { once: true });+ let firstSseDeltaSent = false;try {+ perf.mark("stream_start");send("meta", {project_slug: project.slug,agent: agentName,@@ -95,14 +132,21 @@ export async function POST(request: Request) {sessionId,message: body.message,signal: abortCtl.signal,+ perf,})) {if (evt.kind === "delta") {+ if (!firstSseDeltaSent) {+ firstSseDeltaSent = true;+ perf.mark("first_sse_delta_sent");+ }send("text", { chunk: evt.text });} else if (evt.kind === "error") {send("error", { message: evt.message });}// "final" implicitly ends the loop after; no separate signal needed.}+ perf.mark("stream_done");+ send("perf", { marks: perf.summary() });send("done", {});} catch (err) {send("error", {diff --git a/src/components/agent-chat.tsx b/src/components/agent-chat.tsxindex 158d60c2..1ce1f413 100644--- a/src/components/agent-chat.tsx+++ b/src/components/agent-chat.tsx@@ -172,6 +172,9 @@ export function AgentChat({const ctrl = new AbortController();abortRef.current = ctrl;+ const perf = makeClientPerf();+ perf.mark("send_click");+try {const res = await fetch("/api/chat", {method: "POST",@@ -179,6 +182,7 @@ export function AgentChat({body: JSON.stringify({ message: text, agent: agentSlug, sessionId, sessionKey }),signal: ctrl.signal,});+ perf.mark("fetch_headers");if (!res.ok || !res.body) {throw new Error((await res.text()) || `HTTP ${res.status}`);}@@ -187,10 +191,16 @@ export function AgentChat({const decoder = new TextDecoder();let buffer = "";let receivedText = false;+ let firstByteSeen = false;+ let firstTextSeen = false;for (;;) {const { value, done } = await reader.read();if (done) break;+ if (!firstByteSeen) {+ firstByteSeen = true;+ perf.mark("first_sse_byte");+ }buffer += decoder.decode(value, { stream: true });const events = buffer.split("\n\n");buffer = events.pop() ?? "";@@ -209,11 +219,20 @@ export function AgentChat({if (evt === "text") {const chunk = (data as { chunk: string }).chunk;if (chunk.length > 0) receivedText = true;+ if (!firstTextSeen && chunk.length > 0) {+ firstTextSeen = true;+ perf.mark("first_text_chunk");+ }setMessages((m) =>m.map((msg) =>msg.id === assistantId ? { ...msg, body: msg.body + chunk } : msg,),);+ } else if (evt === "perf") {+ perf.recordServer(+ (data as { marks: Array<{ name: string; at: number; delta: number }> })+ .marks,+ );} else if (evt === "error") {const msg = (data as { message: string }).message;receivedText = true;@@ -228,6 +247,8 @@ export function AgentChat({}}}+ perf.mark("stream_done");+ perf.report();// Slash commands forwarded to OpenClaw (compact, model, think, etc.)// sometimes complete with zero stdout. Leave a quiet acknowledgement so@@ -460,3 +481,58 @@ function formatAgentError(raw: string): string {}return raw;}++/**+ * Client-side chat profiler. Records ms-offsets from send-click. At the end+ * of a turn `report()` prints a single `console.table` with both client marks+ * and the merged server timeline so a developer can attribute slow turns to+ * a stage (network, gateway open, model first-token, etc.) without leaving+ * DevTools. Disable via `localStorage.setItem("notfair.chat.perf", "0")`.+ */+function makeClientPerf() {+ const enabled =+ typeof window === "undefined"+ ? false+ : window.localStorage.getItem("notfair.chat.perf") !== "0";+ const start = performance.now();+ const marks: Array<{ name: string; at: number; delta: number }> = [];+ let lastAt = start;+ let serverMarks: Array<{ name: string; at: number; delta: number }> = [];+ const mark = (name: string) => {+ if (!enabled) return;+ const now = performance.now();+ const at = now - start;+ const delta = now - lastAt;+ lastAt = now;+ marks.push({ name, at, delta });+ };+ const recordServer = (s: Array<{ name: string; at: number; delta: number }>) => {+ serverMarks = s;+ };+ const report = () => {+ if (!enabled) return;+ // eslint-disable-next-line no-console+ console.group("[chat-perf] turn complete");+ // eslint-disable-next-line no-console+ console.table(+ marks.map((m) => ({+ stage: `client:${m.name}`,+ "+from start (ms)": Number(m.at.toFixed(1)),+ "Δ from prev (ms)": Number(m.delta.toFixed(1)),+ })),+ );+ if (serverMarks.length > 0) {+ // eslint-disable-next-line no-console+ console.table(+ serverMarks.map((m) => ({+ stage: `server:${m.name}`,+ "+from start (ms)": Number(m.at.toFixed(1)),+ "Δ from prev (ms)": Number(m.delta.toFixed(1)),+ })),+ );+ }+ // eslint-disable-next-line no-console+ console.groupEnd();+ };+ return { mark, recordServer, report };+}diff --git a/src/server/openclaw/gateway-client.ts b/src/server/openclaw/gateway-client.tsindex 3fd90826..7484a0cd 100644--- a/src/server/openclaw/gateway-client.ts+++ b/src/server/openclaw/gateway-client.ts@@ -212,6 +212,10 @@ export class GatewayClient {this.eventListeners.clear();}+ isOpen(): boolean {+ return this.connected && !!this.ws && this.ws.readyState === WebSocket.OPEN;+ }+request<T = unknown>(method: string, params?: unknown): Promise<T> {const ws = this.ws;if (!ws || ws.readyState !== WebSocket.OPEN) {@@ -282,6 +286,12 @@ export type StreamChatInput = {message: string;/** Cancellation signal. When aborted, we issue chat.abort and stop. */signal?: AbortSignal;+ /** Optional profiler — caller passes a ChatPerf to receive timing marks. */+ perf?: ChatPerf;+};++export type ChatPerf = {+ mark(name: string): void;};export type ChatStreamEvent =@@ -289,27 +299,65 @@ export type ChatStreamEvent =| { kind: "final"; text: string }| { kind: "error"; message: string };+/**+ * Process-wide singleton gateway client.+ *+ * Why: opening a fresh WebSocket per chat turn was costing ~10-30 ms for the+ * TCP+WS handshake plus a `connect`/hello round-trip (see `[chat-perf]`+ * traces). Reusing one connection across turns eliminates that overhead.+ *+ * Resilience: if the underlying socket closes (OpenClaw restarted), `isOpen()`+ * returns false and we lazily reconnect on the next call.+ */+let sharedClient: GatewayClient | null = null;++async function getSharedClient(): Promise<GatewayClient> {+ if (sharedClient && sharedClient.isOpen()) return sharedClient;+ sharedClient = new GatewayClient();+ await sharedClient.open();+ return sharedClient;+}+/*** Stream a chat turn from OpenClaw. Yields incremental delta text events as* the agent produces tokens, then a final event with the full text once done.*- * Strategy: subscribe to `event: "chat"` frames filtered to our runId. Each- * payload carries the merged text in message.content[0].text; we compute the- * delta against what we've already yielded so the consumer sees pure new- * characters per event (cleaner than relying on the gateway's optional- * `deltaText` field which can have buffering quirks).+ * Three text channels are coalesced into a single monotonically-growing+ * transcript and surfaced as delta events:+ * 1. `event: "agent"`, `stream: "assistant"` — true token-by-token streaming+ * from providers that support it. Carries `data.delta` (incremental) or+ * `data.text` (full text-so-far when `replace: true`).+ * 2. `event: "chat"`, `state: "delta"` — provider-buffered streaming with+ * the merged text in `message.content[0].text`.+ * 3. `chat.history` fallback — for deltaless providers (codex/gpt-5.5) the+ * assistant text only appears in the persisted transcript. After the+ * terminal `chat` event we poll `chat.history` until an assistant message+ * timestamped at-or-after `turnStartedAt` shows up.*/export async function* streamChatViaGateway(input: StreamChatInput,): AsyncGenerator<ChatStreamEvent, void, void> {- const client = new GatewayClient();- await client.open();+ const perf = input.perf;+ perf?.mark("gw_open_start");+ let client: GatewayClient;+ try {+ client = await getSharedClient();+ } catch (err) {+ // First-time failure means the cached null instance is fine — the next+ // call will retry. Surface error to the caller.+ sharedClient = null;+ throw err;+ }+ perf?.mark("gw_open_end");const runId = randomUUID();+ const turnStartedAt = Date.now();const events: ChatStreamEvent[] = [];let done = false;let lastEmittedLen = 0;let resolveWait: (() => void) | null = null;+ let firstEventSeen = false;+ let firstDeltaEmitted = false;const wake = () => {if (resolveWait) {@@ -319,30 +367,87 @@ export async function* streamChatViaGateway(}};+ // Helper: emit a delta consisting of the suffix beyond what we've already+ // shown the client. Coalesces text coming from agent-stream events (live+ // tokens), chat-state delta events (provider-buffered), and the final+ // chat.history fallback into a single monotonically-growing transcript.+ const emitMergedText = (merged: string) => {+ if (merged.length <= lastEmittedLen) return;+ const delta = merged.slice(lastEmittedLen);+ lastEmittedLen = merged.length;+ if (!firstDeltaEmitted) {+ firstDeltaEmitted = true;+ perf?.mark("gw_first_delta");+ }+ events.push({ kind: "delta", text: delta });+ wake();+ };++ // Agent text deltas: OpenClaw streams live assistant tokens via+ // `event: "agent"` with `stream: "assistant"`, payload.data.delta = the new+ // characters. Older bursts (e.g., the first chunk on a deltaless provider)+ // arrive as data.text containing the full text-so-far instead. Handle both.+ let agentAssistantBuffer = "";+const unsubscribe = client.addEventListener((evt) => {- if (evt.event !== "chat") return;const payload = evt.payload as| {runId?: string;+ sessionKey?: string;+ stream?: string;state?: string;deltaText?: string;replace?: boolean;+ data?: { delta?: string; text?: string; replace?: boolean };message?: { content?: Array<{ type?: string; text?: string }> };}| undefined;if (!payload || payload.runId !== runId) return;- const merged = extractText(payload.message?.content);- if (merged.length > lastEmittedLen) {- const delta = merged.slice(lastEmittedLen);- lastEmittedLen = merged.length;- events.push({ kind: "delta", text: delta });- wake();+ if (!firstEventSeen) {+ firstEventSeen = true;+ perf?.mark("gw_first_event");}++ if (evt.event === "agent" && payload.stream === "assistant") {+ const d = payload.data ?? {};+ if (d.replace === true && typeof d.text === "string") {+ agentAssistantBuffer = d.text;+ } else if (typeof d.delta === "string") {+ agentAssistantBuffer = agentAssistantBuffer + d.delta;+ } else if (typeof d.text === "string" && d.text.length > agentAssistantBuffer.length) {+ agentAssistantBuffer = d.text;+ }+ emitMergedText(agentAssistantBuffer);+ return;+ }++ if (evt.event !== "chat") return;++ const merged = extractText(payload.message?.content);+ emitMergedText(merged);+if (payload.state === "final" || payload.state === "complete") {- events.push({ kind: "final", text: merged });- done = true;- wake();+ perf?.mark("gw_final");+ // If nothing was streamed (deltaless provider AND empty final.message),+ // fall back to chat.history to pull the persisted assistant reply so+ // the user actually sees the text.+ if (lastEmittedLen === 0) {+ fetchHistoryFallback(client, input.sessionKey, turnStartedAt)+ .then((text) => {+ if (text && text.length > 0) emitMergedText(text);+ })+ .catch(() => {})+ .finally(() => {+ events.push({ kind: "final", text: merged });+ done = true;+ wake();+ });+ } else {+ events.push({ kind: "final", text: merged });+ done = true;+ wake();+ }}});@@ -360,6 +465,7 @@ export async function* streamChatViaGateway(try {// Fire the request. The promise resolves quickly with the runId-or-ack// payload; streaming text arrives as events.+ perf?.mark("gw_chat_send_start");void client.request("chat.send", {sessionKey: input.sessionKey,@@ -368,6 +474,9 @@ export async function* streamChatViaGateway(deliver: false,idempotencyKey: runId,})+ .then(() => {+ perf?.mark("gw_chat_send_ack");+ }).catch((err: Error) => {events.push({ kind: "error", message: err.message });done = true;@@ -393,7 +502,7 @@ export async function* streamChatViaGateway(} finally {unsubscribe();if (input.signal) input.signal.removeEventListener("abort", onAbort);- client.close();+ // Do NOT close the shared client — subsequent turns reuse it.}}@@ -404,3 +513,57 @@ function extractText(content: Array<{ type?: string; text?: string }> | undefine.map((c) => c.text as string).join("");}++/**+ * On terminal `chat` events with empty content (codex and other deltaless+ * providers), the assistant reply lives only in the persisted transcript.+ * The OpenClaw web UI handles this by calling `chat.history` after the final+ * event, and so do we — but transcript persistence happens asynchronously,+ * milliseconds after the final event fires, so a naive call returns the+ * previous turn's reply. Retry briefly until we see an assistant message+ * whose timestamp is at or after `notBefore` (the moment we sent the turn).+ *+ * Returns "" if no fresh assistant message appears within the retry budget.+ */+async function fetchHistoryFallback(+ client: GatewayClient,+ sessionKey: string,+ notBefore: number,+): Promise<string> {+ type HistoryMessage = {+ role?: string;+ content?: Array<{ type?: string; text?: string }>;+ text?: string;+ timestamp?: number;+ };+ type HistoryResponse = { messages?: HistoryMessage[] };++ const findLatestAssistant = (msgs: HistoryMessage[]) => {+ for (let i = msgs.length - 1; i >= 0; i--) {+ const m = msgs[i];+ if (m?.role !== "assistant") continue;+ const text = extractText(m.content) || (typeof m.text === "string" ? m.text : "");+ if (!text.trim()) continue;+ return { text, timestamp: typeof m.timestamp === "number" ? m.timestamp : 0 };+ }+ return null;+ };++ const MAX_ATTEMPTS = 8;+ const DELAY_MS = 80;+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {+ try {+ const res = (await client.request("chat.history", {+ sessionKey,+ limit: 8,+ })) as HistoryResponse | undefined;+ const msgs = Array.isArray(res?.messages) ? res!.messages : [];+ const hit = findLatestAssistant(msgs);+ if (hit && hit.timestamp >= notBefore) return hit.text;+ } catch {+ // swallow and retry+ }+ await new Promise((r) => setTimeout(r, DELAY_MS));+ }+ return "";+}