Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

refactor(chat): unify free-form chat + task chat on LiveTranscript

Yuting Zhong2656edde7899
diff --git a/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx b/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx
index 7e865800..319df15c 100644
--- a/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx
+++ b/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx
@@ -8,13 +8,14 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
import { getActiveProject } from "@/server/active-project";
import { resolveAgentBySlug } from "@/server/agent-meta";
import {
+ buildPendingSessionKey,
findSessionBySessionId,
listSessionsForAgent,
} from "@/server/openclaw/sessions";
import { storedMcpKey } from "@/server/mcp-catalog";
import { getMcpStatus } from "@/server/mcp-state";
-import { loadThreadHistory } from "@/server/orchestration/thread-history";
-import { AgentChat } from "@/components/agent-chat";
+import { readTranscriptTail } from "@/server/openclaw/transcript-tail";
+import { LiveTranscript } from "@/components/live-transcript";
import { GoogleAdsMcpBanner } from "@/components/google-ads-mcp-banner";
import { McpFlashBanner } from "@/components/mcp-flash-banner";
import { ThreadSelector } from "@/components/thread-selector";
@@ -72,10 +73,14 @@ export default async function AgentChatThreadPage({
const allSessions = listSessionsForAgent(agentFullId);
const existing = findSessionBySessionId(agentFullId, threadId);
- // Both surfaces (this page + /tasks/[id]) load history via the shared
- // helper that resolves the URL threadId to OpenClaw's internal sessionId
- // before reading the transcript JSONL. See thread-history.ts.
- const { sessionKey, history } = loadThreadHistory(agentFullId, threadId);
+ // Pull the full transcript slice (text, tool calls, tool results) so the
+ // chat page renders the same rich JSONL view the task workspace shows.
+ // The sessionKey comes from OpenClaw's index when the thread already
+ // exists; pending threads get a derived key tied to the URL threadId.
+ const sessionKey =
+ existing?.sessionKey ?? buildPendingSessionKey(agentFullId, threadId);
+ const { events: initialEvents, byteOffset: initialByteOffset } =
+ readTranscriptTail(agentFullId, threadId, 0);
// For the dropdown: surface the pending thread at the top so the user sees
// it's "selected" even before sending the first message.
@@ -106,7 +111,8 @@ export default async function AgentChatThreadPage({
// sentinel (dropped by the onboarding audit). The agent's system prompt
// tells it to read the file + move it to MEMORY/ after, so subsequent
// sessions won't re-fire even though we keep the simple history-empty check.
- const autoKickoff = history.length === 0 && firstTurnPendingForAgent(agentFullId);
+ const autoKickoff =
+ initialEvents.length === 0 && firstTurnPendingForAgent(agentFullId);
return (
<div className="flex h-full flex-col">
@@ -130,15 +136,14 @@ export default async function AgentChatThreadPage({
</div>
<div className="min-h-0 flex-1">
- <AgentChat
+ <LiveTranscript
key={threadId}
- projectSlug={project.slug}
agentSlug={agentSlug}
agentDisplayName={resolved.display_name}
- sessionId={threadId}
+ threadId={threadId}
sessionKey={sessionKey}
- templateKey={resolved.template_key}
- initialMessages={history.map((m) => ({ id: m.id, role: m.role, body: m.body }))}
+ initialEvents={initialEvents}
+ initialByteOffset={initialByteOffset}
autoKickoff={autoKickoff}
/>
</div>
diff --git a/src/app/api/agents/[agent]/tasks/[id]/transcript/route.ts b/src/app/api/agents/[agent]/tasks/[id]/transcript/route.ts
deleted file mode 100644
index fe43d52b..00000000
--- a/src/app/api/agents/[agent]/tasks/[id]/transcript/route.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { NextResponse } from "next/server";
-import { getActiveProject } from "@/server/active-project";
-import { resolveAgentBySlug } from "@/server/agent-meta";
-import { getTask } from "@/server/db/tasks";
-import { readTranscriptTail } from "@/server/openclaw/transcript-tail";
-
-export const dynamic = "force-dynamic";
-export const runtime = "nodejs";
-
-/**
- * Returns the slice of the on-disk JSONL transcript that lives after the
- * client's last seen byte offset. The client appends `events` to its local
- * buffer and sends the returned `byteOffset` back on the next poll.
- *
- * `done: true` tells the client to stop polling — set when the task has
- * reached a terminal status. A null `byteOffset` means OpenClaw hasn't
- * written a transcript file yet (proposed task whose kickoff hasn't landed).
- */
-export async function GET(
- request: Request,
- context: { params: Promise<{ agent: string; id: string }> },
-) {
- const { agent: agentSlug, id: taskId } = await context.params;
-
- const project = await getActiveProject();
- if (!project) {
- return NextResponse.json({ error: "no active project" }, { status: 400 });
- }
-
- const resolved = await resolveAgentBySlug(project.slug, agentSlug);
- if (!resolved) {
- return NextResponse.json({ error: "unknown agent" }, { status: 404 });
- }
-
- const task = getTask(taskId);
- if (!task || task.project_slug !== project.slug) {
- return NextResponse.json({ error: "task not found" }, { status: 404 });
- }
- // Cross-agent task access guard — the URL agent must own this task.
- if (task.agent_id !== resolved.agent_id) {
- return NextResponse.json({ error: "task not on this agent" }, { status: 404 });
- }
- if (!task.thread_id) {
- // Thread isn't minted yet (task just created, never opened). Nothing on
- // disk to tail. Client will retry on the next poll tick.
- return NextResponse.json({
- events: [],
- byteOffset: 0,
- file_size: 0,
- done: false,
- status: task.status,
- });
- }
-
- const url = new URL(request.url);
- const offsetParam = url.searchParams.get("offset");
- const byteOffset = offsetParam ? Number(offsetParam) : 0;
- const validOffset = Number.isFinite(byteOffset) && byteOffset >= 0 ? byteOffset : 0;
-
- const { events, byteOffset: newOffset, fileSize } = readTranscriptTail(
- resolved.agent_id,
- task.thread_id,
- validOffset,
- );
-
- const terminal =
- task.status === "succeeded" ||
- task.status === "failed" ||
- task.status === "cancelled";
-
- return NextResponse.json({
- events,
- byteOffset: newOffset,
- file_size: fileSize,
- // Only stop polling AFTER the task is terminal AND we've drained the
- // file. Otherwise the last few events written between status-flip and
- // our read can get dropped.
- done: terminal && newOffset >= fileSize,
- status: task.status,
- });
-}
diff --git a/src/app/api/agents/[agent]/threads/[thread]/transcript/route.ts b/src/app/api/agents/[agent]/threads/[thread]/transcript/route.ts
new file mode 100644
index 00000000..b76c0958
--- /dev/null
+++ b/src/app/api/agents/[agent]/threads/[thread]/transcript/route.ts
@@ -0,0 +1,49 @@
+import { NextResponse } from "next/server";
+import { getActiveProject } from "@/server/active-project";
+import { resolveAgentBySlug } from "@/server/agent-meta";
+import { readTranscriptTail } from "@/server/openclaw/transcript-tail";
+
+export const dynamic = "force-dynamic";
+export const runtime = "nodejs";
+
+/**
+ * Generic transcript tail endpoint — agent + thread, no task lookup.
+ *
+ * Both surfaces (the task workspace and the free-form /chat/[thread] view)
+ * poll this with the byte offset they last saw; we return any events
+ * written since. Threads have no terminal state, so callers manage their
+ * own "stop polling" signal (the task workspace gates on task.status).
+ */
+export async function GET(
+ request: Request,
+ context: { params: Promise<{ agent: string; thread: string }> },
+) {
+ const { agent: agentSlug, thread: threadId } = await context.params;
+
+ const project = await getActiveProject();
+ if (!project) {
+ return NextResponse.json({ error: "no active project" }, { status: 400 });
+ }
+
+ const resolved = await resolveAgentBySlug(project.slug, agentSlug);
+ if (!resolved) {
+ return NextResponse.json({ error: "unknown agent" }, { status: 404 });
+ }
+
+ const url = new URL(request.url);
+ const offsetParam = url.searchParams.get("offset");
+ const byteOffset = offsetParam ? Number(offsetParam) : 0;
+ const validOffset = Number.isFinite(byteOffset) && byteOffset >= 0 ? byteOffset : 0;
+
+ const { events, byteOffset: newOffset, fileSize } = readTranscriptTail(
+ resolved.agent_id,
+ threadId,
+ validOffset,
+ );
+
+ return NextResponse.json({
+ events,
+ byteOffset: newOffset,
+ file_size: fileSize,
+ });
+}
diff --git a/src/app/api/chat/route.ts b/src/app/api/chat/route.ts
index 5a7a56be..29a49f58 100644
--- a/src/app/api/chat/route.ts
+++ b/src/app/api/chat/route.ts
@@ -115,8 +115,8 @@ export async function POST(request: Request) {
// and silently drop further sends. The agent run on OpenClaw keeps
// going, the assistantBuffer keeps accumulating, and orchestration
// still runs at the end. Persistence (JSONL) happens server-side
- // regardless, so when the user returns, loadThreadHistory shows the
- // full response.
+ // regardless, so when the user returns, the transcript-tail endpoint
+ // surfaces the full response on the next poll.
let clientOpen = true;
const send = (event: string, data: unknown) => {
if (!clientOpen) return;
diff --git a/src/components/agent-chat.tsx b/src/components/agent-chat.tsx
deleted file mode 100644
index abb7b849..00000000
--- a/src/components/agent-chat.tsx
+++ /dev/null
@@ -1,885 +0,0 @@
-"use client";
-
-import { useEffect, useLayoutEffect, useMemo, useRef, useState, useTransition } from "react";
-import { useRouter } from "next/navigation";
-import Link from "next/link";
-import {
- Send,
- AlertCircle,
- StopCircle,
- Loader2,
- CheckCircle2,
- Terminal,
- FileText,
- Edit3,
- Globe,
- Wrench,
- ListChecks,
- MessageSquare,
- HelpCircle,
- Shield,
-} from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { cn } from "@/lib/utils";
-import { toast } from "sonner";
-import { stripOrchestrationBlocks } from "@/server/orchestration/blocks";
-import {
- filterSlashCommands,
- executeLocalSlashCommand,
- parseSlashMessage,
- type SlashCommand,
-} from "@/lib/slash-commands";
-import { SlashCommandPopover } from "./slash-command-popover";
-import { Markdown } from "./markdown";
-
-type Step = {
- /** Stable per-invocation id from OpenClaw, used to update in-place. */
- toolCallId: string;
- /** Raw tool name (e.g. "exec", "read", "edit", "mcp:foo.bar"). */
- name: string;
- /** Pre-formatted one-liner from the server (command / path / etc.). */
- label?: string;
- /** start | update | result — drives the spinner vs check icon. */
- phase: "start" | "update" | "result";
-};
-
-type OrchestrationOutcome = {
- tasks_created: Array<{ id: string; title: string | null; assignee: string; status: string }>;
- task_status_updates: Array<{ task_id: string; status: string }>;
- comments_added: Array<{ task_id: string }>;
- ask_user: Array<{ task_id?: string; question: string }>;
- approvals_requested: Array<{ approval_id: string; action_type: string }>;
- errors: Array<{ kind: string; message: string }>;
-};
-
-type Message = {
- id: string;
- role: "user" | "assistant" | "error";
- body: string;
- /**
- * Tool/MCP invocations the agent made before/while producing this reply,
- * surfaced inline so the user can watch what's happening instead of
- * staring at "thinking…". Empty on user/error rows.
- */
- steps?: Step[];
- /**
- * Structured orchestration outcome the server extracted from the
- * assistant's reply (tasks created, status updates, etc.). Rendered as
- * a small summary card below the assistant text. Stripped from the
- * Markdown body so the user doesn't see raw <create_task> tags.
- */
- orchestration?: OrchestrationOutcome;
-};
-
-export type InitialMessage = {
- id: string;
- role: "user" | "assistant";
- body: string;
-};
-
-/**
- * Module-level dedup for the auto-kickoff. Keyed by sessionId so different
- * threads kick off independently, but a single thread's StrictMode-induced
- * double-mount only fires once.
- */
-const KICKOFF_FIRED = new Set<string>();
-
-type Props = {
- projectSlug: string;
- agentSlug: string;
- agentDisplayName: string;
- sessionId: string;
- /**
- * OpenClaw's canonical `agent:<agent>:<label>` key for this thread. For
- * existing threads, label might be `main` (not the sessionId UUID), so we
- * thread the resolved key through instead of reconstructing it server-side.
- */
- sessionKey: string;
- /**
- * Template key the agent was provisioned from (e.g. "google_ads"). Kept
- * for future per-template chat affordances; currently unused.
- */
- templateKey?: string;
- initialMessages?: InitialMessage[];
- /**
- * When true, the chat auto-sends a hidden kickoff on mount so the agent
- * produces its first turn without the user needing to type. Used after
- * onboarding when FIRST_TURN.md is sitting in the agent workspace and
- * the agent system prompt is set up to read it and greet (D19), and on
- * /tasks/[id] when the task's per-task thread is opened for the first
- * time and the brief is delivered via the kickoff message.
- */
- autoKickoff?: boolean;
- /**
- * Override the default "(session start)" kickoff message. Used to
- * deliver per-task briefs to a specialist on first open of a task's
- * thread: the brief itself goes through the chat as a hidden message
- * so the agent has the full PRD before its first reply. Ignored unless
- * autoKickoff is also true.
- */
- kickoffMessage?: string;
-};
-
-export function AgentChat({
- projectSlug: _projectSlug,
- agentSlug,
- agentDisplayName,
- sessionId,
- sessionKey,
- templateKey: _templateKey,
- initialMessages = [],
- autoKickoff = false,
- kickoffMessage,
-}: Props) {
- const [messages, setMessages] = useState<Message[]>(initialMessages);
- const [input, setInput] = useState("");
- const [pending, setPending] = useState(false);
- const [slashIndex, setSlashIndex] = useState(0);
- const scrollRef = useRef<HTMLDivElement>(null);
- const bottomRef = useRef<HTMLDivElement>(null);
- const abortRef = useRef<AbortController | null>(null);
- const textareaRef = useRef<HTMLTextAreaElement>(null);
- const router = useRouter();
- const [, startTransition] = useTransition();
-
- // Slash command autocomplete shows when the user's input starts with `/`
- // and has not yet been broken by a space (i.e., they're still composing the
- // command name, not its argument).
- const slashQuery = input.startsWith("/") && !input.includes(" ") ? input : null;
- const slashOpen = slashQuery !== null && !pending;
- const slashMatches = useMemo<SlashCommand[]>(
- () => (slashOpen ? filterSlashCommands(slashQuery!) : []),
- [slashOpen, slashQuery],
- );
- const safeSlashIndex = slashMatches.length === 0
- ? 0
- : Math.min(slashIndex, slashMatches.length - 1);
-
- function insertSlashCommand(cmd: SlashCommand) {
- // Catalog `name` is the command without the leading slash ("new", "clear").
- // Inserts must include it so the textarea ends up with "/new " — otherwise
- // the next Enter sends the bare word to the agent.
- const insert = cmd.insert ?? `/${cmd.name} `;
- setInput(insert);
- setSlashIndex(0);
- requestAnimationFrame(() => {
- const ta = textareaRef.current;
- if (ta) {
- ta.focus();
- ta.setSelectionRange(insert.length, insert.length);
- autoResize(ta);
- }
- });
- }
-
- // Auto-kickoff: on a brand-new thread when the server told us FIRST_TURN.md
- // is pending in the agent workspace, send a hidden first message so the
- // agent runs and produces its greeting (per D19). Dedup via a MODULE-level
- // Set keyed by sessionId — useRef doesn't survive React StrictMode dev
- // remounts (refs are reinitialized on every mount), so a ref guard fires
- // twice and triggers two concurrent chat requests, which can race the
- // gateway-client's connect handshake. The module-level set survives
- // remounts because the module isn't re-evaluated.
- useEffect(() => {
- if (!autoKickoff) return;
- if (KICKOFF_FIRED.has(sessionId)) return;
- if (messages.length > 0) return;
- if (pending) return;
- KICKOFF_FIRED.add(sessionId);
- // Hidden kickoff — the agent's system prompt routes from here. Default
- // is "(session start)" which trips FIRST_TURN.md handling; for task
- // threads the caller passes a kickoffMessage carrying the task brief.
- send(kickoffMessage ?? "(session start)", { hidden: true });
- // Intentionally do not depend on `send` (stable enough across renders) or
- // `messages` (would re-fire as the greeting streams in).
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [autoKickoff, sessionId]);
-
- // Keep the message thread pinned to the bottom on send / streaming updates.
- // Use the scroll container directly (not scrollIntoView on a sentinel) so we
- // don't accidentally scroll the whole page if the chat is nested.
- useLayoutEffect(() => {
- const el = scrollRef.current;
- if (!el) return;
- el.scrollTop = el.scrollHeight;
- }, [messages, pending]);
-
- // Auto-grow the textarea up to a cap so long composer drafts don't crowd
- // the message thread.
- function autoResize(el: HTMLTextAreaElement) {
- el.style.height = "auto";
- el.style.height = `${Math.min(el.scrollHeight, 200)}px`;
- }
-
- async function send(
- overrideText?: string,
- opts: { hidden?: boolean } = {},
- ) {
- // overrideText: bypass the composer and send a programmatic message
- // (e.g., the MCP connect kickoff, or the FIRST_TURN.md auto-kickoff).
- // When provided, we do NOT touch the input/textarea state so the user's
- // draft is preserved.
- // opts.hidden: don't render the user bubble in the chat — used for the
- // FIRST_TURN.md kickoff where the user shouldn't see "Hi" land before
- // the agent's greeting.
- const usingOverride = typeof overrideText === "string";
- const text = (usingOverride ? overrideText : input).trim();
- if (!text || pending) return;
-
- // Local-only slash commands (clear, new, stop, help) — mirror OpenClaw web
- // UI behavior: handle client-side, do NOT send to the agent. Skip when
- // sending programmatically: overrides are always plain prompts.
- const parsed = usingOverride ? null : parseSlashMessage(text);
- if (parsed) {
- const action = executeLocalSlashCommand(parsed.command);
- if (action) {
- setInput("");
- if (textareaRef.current) textareaRef.current.style.height = "auto";
- switch (action.kind) {
- case "clear":
- setMessages([]);
- return;
- case "new-session": {
- // Mint a fresh UUID and navigate — the new threaded URL becomes
- // the source of truth, no cookie roundtrip needed.
- const newId = crypto.randomUUID();
- startTransition(() => {
- router.push(`/agents/${agentSlug}/chat/${newId}`);
- });
- return;
- }
- case "stop":
- if (abortRef.current) abortRef.current.abort();
- return;
- case "help": {
- const helpId = `a-${Date.now()}`;
- setMessages((m) => [
- ...m,
- { id: `u-${Date.now()}`, role: "user", body: text },
- { id: helpId, role: "assistant", body: action.content },
- ]);
- return;
- }
- }
- }
- }
-
- const userMessage: Message = { id: `u-${Date.now()}`, role: "user", body: text };
- const assistantId = `a-${Date.now()}`;
- if (opts.hidden) {
- // Send the user message to the agent but suppress the bubble — only
- // the assistant placeholder appears, so the chat opens with the
- // greeting and not a synthetic user line.
- setMessages((m) => [...m, { id: assistantId, role: "assistant", body: "" }]);
- } else {
- setMessages((m) => [...m, userMessage, { id: assistantId, role: "assistant", body: "" }]);
- }
- if (!usingOverride) {
- setInput("");
- if (textareaRef.current) {
- textareaRef.current.style.height = "auto";
- }
- }
- setPending(true);
-
- const ctrl = new AbortController();
- abortRef.current = ctrl;
-
- const perf = makeClientPerf();
- perf.mark("send_click");
-
- try {
- const res = await fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- 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}`);
- }
-
- const reader = res.body.getReader();
- 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() ?? "";
- for (const raw of events) {
- const lines = raw.split("\n");
- const evtLine = lines.find((l) => l.startsWith("event: "));
- const dataLine = lines.find((l) => l.startsWith("data: "));
- if (!evtLine || !dataLine) continue;
- const evt = evtLine.slice("event: ".length);
- let data: unknown;
- try {
- data = JSON.parse(dataLine.slice("data: ".length));
- } catch {
- continue;
- }
- 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 === "tool") {
- // Live tool/MCP invocation. Update in place by toolCallId so a
- // start→result pair becomes one row that flips from spinner to
- // check, rather than two separate rows.
- const d = data as {
- phase: "start" | "update" | "result";
- tool_call_id: string;
- name: string;
- label?: string;
- };
- // Treat the first tool event as "we have visible progress" so the
- // empty-reply branch below doesn't blow away the step list with
- // the "(command handled by OpenClaw, no reply)" placeholder.
- receivedText = true;
- setMessages((m) =>
- m.map((msg) => {
- if (msg.id !== assistantId) return msg;
- const existing = msg.steps ?? [];
- const idx = existing.findIndex((s) => s.toolCallId === d.tool_call_id);
- if (idx < 0) {
- return {
- ...msg,
- steps: [
- ...existing,
- {
- toolCallId: d.tool_call_id,
- name: d.name,
- label: d.label,
- phase: d.phase,
- },
- ],
- };
- }
- const next = existing.slice();
- next[idx] = {
- ...next[idx],
- name: d.name,
- // Label only arrives on "start"; preserve it on update/result.
- label: d.label ?? next[idx].label,
- phase: d.phase,
- };
- return { ...msg, steps: next };
- }),
- );
- } else if (evt === "lifecycle") {
- // Lifecycle markers (start/end/error) don't render today — the
- // spinner on the assistant bubble already conveys "in progress"
- // and the closing of the SSE stream marks the end. Reserved for
- // future use (e.g. compaction toasts) so we accept-and-ignore
- // rather than logging an "unknown event" warning.
- } 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;
- setMessages((m) =>
- m.map((m2) =>
- m2.id === assistantId
- ? { ...m2, role: "error", body: formatAgentError(msg) }
- : m2,
- ),
- );
- toast.error(formatAgentError(msg));
- } else if (evt === "orchestration") {
- // Server extracted orchestration blocks from the agent's reply
- // and turned them into DB rows. Attach the outcome to this
- // assistant message so the UI can render a summary card below
- // the prose ("Created 3 tasks · View tasks →").
- const outcome = data as OrchestrationOutcome;
- setMessages((m) =>
- m.map((m2) =>
- m2.id === assistantId ? { ...m2, orchestration: outcome } : m2,
- ),
- );
- // Toast tasks_created so the user notices even if they're not
- // looking at the chat surface right now.
- if (outcome.tasks_created.length > 0) {
- toast.success(
- `Created ${outcome.tasks_created.length} task${outcome.tasks_created.length === 1 ? "" : "s"} for the specialist.`,
- );
- // Force the /tasks route to refetch since it's a server component
- // and won't auto-update otherwise.
- startTransition(() => router.refresh());
- }
- }
- }
- }
- 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
- // the bubble doesn't sit on "thinking…" forever.
- if (!receivedText) {
- setMessages((m) =>
- m.map((m2) =>
- m2.id === assistantId
- ? { ...m2, body: "(command handled by OpenClaw, no reply)" }
- : m2,
- ),
- );
- }
- } catch (err) {
- const isAbort = err instanceof DOMException && err.name === "AbortError";
- if (isAbort) {
- setMessages((m) =>
- m.map((m2) =>
- m2.id === assistantId
- ? { ...m2, body: (m2.body || "") + "\n\n(stopped)" }
- : m2,
- ),
- );
- } else {
- const msg = err instanceof Error ? err.message : String(err);
- setMessages((m) =>
- m.map((m2) =>
- m2.id === assistantId
- ? { ...m2, role: "error", body: formatAgentError(msg) }
- : m2,
- ),
- );
- toast.error(formatAgentError(msg));
- }
- } finally {
- setPending(false);
- abortRef.current = null;
- }
- }
-
- function onKey(e: React.KeyboardEvent<HTMLTextAreaElement>) {
- // Slash autocomplete: while the popover is open, Tab AND Enter both insert
- // the highlighted match. After insert the textarea ends in a space, which
- // closes the popover — a second Enter then submits the input as usual.
- if (slashOpen && slashMatches.length > 0) {
- if (e.key === "ArrowDown") {
- e.preventDefault();
- setSlashIndex((i) => (i + 1) % slashMatches.length);
- return;
- }
- if (e.key === "ArrowUp") {
- e.preventDefault();
- setSlashIndex((i) => (i - 1 + slashMatches.length) % slashMatches.length);
- return;
- }
- if (e.key === "Tab" || (e.key === "Enter" && !e.shiftKey)) {
- e.preventDefault();
- const picked = slashMatches[safeSlashIndex];
- if (picked) insertSlashCommand(picked);
- return;
- }
- if (e.key === "Escape") {
- e.preventDefault();
- setSlashIndex(0);
- setInput("");
- return;
- }
- }
- if (e.key === "Enter" && !e.shiftKey) {
- e.preventDefault();
- void send();
- }
- }
-
- return (
- <div className="flex h-full flex-col">
- {/* Scrollable message thread */}
- <div
- ref={scrollRef}
- className="min-h-0 flex-1 overflow-y-auto"
- role="log"
- aria-live="polite"
- >
- <div className="mx-auto w-full max-w-3xl px-6 py-8">
- {messages.length === 0 ? (
- <EmptyState agentDisplayName={agentDisplayName} />
- ) : (
- <div className="space-y-6">
- {messages.map((m) => (
- <MessageRow
- key={m.id}
- message={m}
- agentDisplayName={agentDisplayName}
- />
- ))}
- </div>
- )}
- <div ref={bottomRef} />
- </div>
- </div>
-
- {/* Composer — sits below the scroll area, full width with centered content */}
- <div className="border-t bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80">
- <div className="relative mx-auto w-full max-w-3xl px-6 py-4">
- {slashOpen && (
- <SlashCommandPopover
- commands={slashMatches}
- selectedIndex={safeSlashIndex}
- onSelect={insertSlashCommand}
- onHover={setSlashIndex}
- />
- )}
- <form
- className="flex items-end gap-2"
- onSubmit={(e) => {
- e.preventDefault();
- void send();
- }}
- >
- <textarea
- ref={textareaRef}
- className="flex min-h-[44px] flex-1 resize-none rounded-2xl border bg-background px-4 py-2.5 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
- placeholder={`Message ${agentDisplayName}… (type / for commands)`}
- value={input}
- onChange={(e) => {
- setInput(e.target.value);
- setSlashIndex(0);
- autoResize(e.target);
- }}
- onKeyDown={onKey}
- disabled={pending}
- rows={1}
- />
- {pending ? (
- <Button
- type="button"
- variant="outline"
- onClick={() => abortRef.current?.abort()}
- className="h-11 rounded-2xl"
- >
- <StopCircle className="size-4" />
- <span className="sr-only">Stop</span>
- </Button>
- ) : (
- <Button type="submit" className="h-11 rounded-2xl">
- <Send className="size-4" />
- <span className="sr-only">Send</span>
- </Button>
- )}
- </form>
- </div>
- <p className="pb-3 text-center text-[10px] text-muted-foreground">
- Enter to send · Shift+Enter for newline · / for slash commands
- </p>
- </div>
- </div>
- );
-}
-
-function EmptyState({ agentDisplayName }: { agentDisplayName: string }) {
- return (
- <div className="flex flex-col items-center justify-center py-24 text-center">
- <div className="space-y-2">
- <h2 className="text-lg font-medium text-foreground">
- Talk to {agentDisplayName}
- </h2>
- <p className="max-w-md text-sm text-muted-foreground">
- History persists per thread. Switch threads from the dropdown above.
- </p>
- </div>
- </div>
- );
-}
-
-function MessageRow({
- message,
- agentDisplayName,
-}: {
- message: Message;
- agentDisplayName: string;
-}) {
- if (message.role === "user") {
- return (
- <div className="flex justify-end">
- <div className="max-w-[85%] rounded-2xl bg-muted px-4 py-2.5 text-sm leading-relaxed whitespace-pre-wrap break-words">
- {message.body}
- </div>
- </div>
- );
- }
- if (message.role === "error") {
- return (
- <div className="flex items-start gap-2 rounded-md border border-destructive/50 bg-destructive/5 p-3 text-sm">
- <AlertCircle className="mt-0.5 size-4 shrink-0 text-destructive" />
- <div className="min-w-0 flex-1">
- <div className="font-medium text-destructive">
- Couldn&rsquo;t reach {agentDisplayName}.
- </div>
- <div className="mt-1 text-xs text-muted-foreground whitespace-pre-wrap break-words">
- {message.body}
- </div>
- </div>
- </div>
- );
- }
- // Assistant: rendered as markdown for code blocks, lists, bold, tables, etc.
- // Plain text falls through unchanged because markdown is a superset. While
- // streaming, partial markdown (e.g. an unclosed fence) is rendered as far as
- // remark can parse it — visually fine because the next chunk arrives within
- // milliseconds. Orchestration blocks (<create_task> etc.) are stripped before
- // rendering so the user sees clean prose, not raw tags.
- const hasSteps = (message.steps?.length ?? 0) > 0;
- // Strip orchestration tags as text streams in — during streaming partially-
- // received tags briefly render then disappear once their closing tag arrives.
- const cleanBody = stripOrchestrationBlocks(message.body);
- const isEmpty = cleanBody === "";
- return (
- <div className="group space-y-2">
- {hasSteps && <StepList steps={message.steps!} />}
- {isEmpty ? (
- !hasSteps && (
- <div className="text-sm italic text-muted-foreground">
- {`${agentDisplayName} is thinking…`}
- </div>
- )
- ) : (
- <Markdown>{cleanBody}</Markdown>
- )}
- {message.orchestration && <OrchestrationSummary outcome={message.orchestration} />}
- </div>
- );
-}
-
-function OrchestrationSummary({ outcome }: { outcome: OrchestrationOutcome }) {
- const items: React.ReactNode[] = [];
- if (outcome.tasks_created.length > 0) {
- items.push(
- <div key="tasks" className="flex items-start gap-2 text-xs">
- <ListChecks className="mt-0.5 size-3.5 shrink-0 text-emerald-600" aria-hidden />
- <div className="min-w-0">
- <div className="font-medium text-foreground">
- Created {outcome.tasks_created.length} task
- {outcome.tasks_created.length === 1 ? "" : "s"}
- </div>
- <ul className="mt-0.5 space-y-0.5">
- {outcome.tasks_created.map((t) => (
- <li key={t.id} className="text-muted-foreground">
- <Link
- href={`/tasks/${t.id}`}
- className="hover:text-foreground hover:underline"
- >
- {t.title ?? t.id.slice(0, 8)}
- </Link>{" "}
- <span className="text-[10px] tabular-nums">→ {t.assignee}</span>
- </li>
- ))}
- </ul>
- </div>
- </div>,
- );
- }
- if (outcome.task_status_updates.length > 0) {
- items.push(
- <div key="status" className="flex items-start gap-2 text-xs">
- <CheckCircle2 className="mt-0.5 size-3.5 shrink-0 text-emerald-600" aria-hidden />
- <div>
- <div className="font-medium text-foreground">
- Updated {outcome.task_status_updates.length} task status
- {outcome.task_status_updates.length === 1 ? "" : "es"}
- </div>
- <ul className="mt-0.5 space-y-0.5 text-muted-foreground">
- {outcome.task_status_updates.map((u) => (
- <li key={u.task_id}>
- <Link
- href={`/tasks/${u.task_id}`}
- className="hover:text-foreground hover:underline"
- >
- {u.task_id.slice(0, 8)}
- </Link>{" "}
- → {u.status}
- </li>
- ))}
- </ul>
- </div>
- </div>,
- );
- }
- if (outcome.comments_added.length > 0) {
- items.push(
- <div key="comments" className="flex items-start gap-2 text-xs text-muted-foreground">
- <MessageSquare className="mt-0.5 size-3.5 shrink-0" aria-hidden />
- <div>
- Posted {outcome.comments_added.length} comment
- {outcome.comments_added.length === 1 ? "" : "s"} on existing task
- {outcome.comments_added.length === 1 ? "" : "s"}.
- </div>
- </div>,
- );
- }
- if (outcome.ask_user.length > 0) {
- items.push(
- <div key="ask" className="flex items-start gap-2 text-xs text-amber-700 dark:text-amber-400">
- <HelpCircle className="mt-0.5 size-3.5 shrink-0" aria-hidden />
- <div>
- {outcome.ask_user.length === 1
- ? "Waiting on your answer"
- : `Waiting on your answer on ${outcome.ask_user.length} questions`}{" "}
- — view in /activity.
- </div>
- </div>,
- );
- }
- if (outcome.approvals_requested.length > 0) {
- items.push(
- <div key="approval" className="flex items-start gap-2 text-xs text-amber-700 dark:text-amber-400">
- <Shield className="mt-0.5 size-3.5 shrink-0" aria-hidden />
- <div>
- Requested {outcome.approvals_requested.length} approval
- {outcome.approvals_requested.length === 1 ? "" : "s"} —{" "}
- <Link href="/approvals" className="hover:text-foreground hover:underline">
- review in /approvals
- </Link>
- .
- </div>
- </div>,
- );
- }
- if (outcome.errors.length > 0) {
- items.push(
- <div key="errors" className="flex items-start gap-2 text-xs text-destructive">
- <AlertCircle className="mt-0.5 size-3.5 shrink-0" aria-hidden />
- <div>
- {outcome.errors.length} orchestration block{outcome.errors.length === 1 ? "" : "s"} failed to apply.
- </div>
- </div>,
- );
- }
- if (items.length === 0) return null;
- return (
- <div className="space-y-2 rounded-md border bg-muted/30 px-3 py-2.5">{items}</div>
- );
-}
-
-function StepList({ steps }: { steps: Step[] }) {
- return (
- <div className="space-y-1 rounded-md border bg-muted/30 px-3 py-2">
- {steps.map((s) => (
- <StepRow key={s.toolCallId} step={s} />
- ))}
- </div>
- );
-}
-
-function StepRow({ step }: { step: Step }) {
- const Icon = iconForTool(step.name);
- const done = step.phase === "result";
- return (
- <div className="flex items-center gap-2 text-xs">
- <span className="flex size-4 shrink-0 items-center justify-center text-muted-foreground">
- {done ? (
- <CheckCircle2 className="size-3.5 text-emerald-600" />
- ) : (
- <Loader2 className="size-3.5 animate-spin" />
- )}
- </span>
- <Icon className="size-3.5 shrink-0 text-muted-foreground" />
- <span className="font-mono text-[11px] font-medium text-foreground">
- {step.name}
- </span>
- {step.label && (
- <span className="truncate font-mono text-[11px] text-muted-foreground">
- {step.label}
- </span>
- )}
- </div>
- );
-}
-
-function iconForTool(name: string) {
- // Match icons to OpenClaw's built-in tool kinds. Anything else (MCP tools,
- // plugin tools) falls through to the generic Wrench icon.
- const n = name.toLowerCase();
- if (n === "exec" || n === "shell" || n.includes("bash")) return Terminal;
- if (n === "read" || n === "cat" || n === "open") return FileText;
- if (n === "write" || n === "edit" || n === "patch") return Edit3;
- if (n === "fetch" || n.includes("http") || n.includes("web")) return Globe;
- return Wrench;
-}
-
-function formatAgentError(raw: string): string {
- if (raw.includes("missing scope")) {
- return `${raw}\n\nHint: this OpenClaw slash command requires a permission your gateway token does not grant. Use the “New thread” button above for new conversations.`;
- }
- 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/components/agent-task-workspace.tsx b/src/components/agent-task-workspace.tsx
index 2e95b292..638fc582 100644
--- a/src/components/agent-task-workspace.tsx
+++ b/src/components/agent-task-workspace.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useMemo } from "react";
+import { useCallback, useMemo } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { CheckCircle2, Circle, CircleDot, Loader2, XCircle } from "lucide-react";
@@ -13,6 +13,8 @@ import { cn } from "@/lib/utils";
import type { TranscriptEvent } from "@/server/openclaw/transcript-tail";
import type { Task, TaskStatus } from "@/types";
+const TASK_IN_FLIGHT: TaskStatus[] = ["proposed", "approved", "running"];
+
const STATUS_GROUPS: Array<{ status: TaskStatus; label: string }> = [
{ status: "running", label: "Running" },
{ status: "proposed", label: "Proposed" },
@@ -213,17 +215,7 @@ export function AgentTaskWorkspace({
</header>
<div className="min-h-0 flex-1">
- <LiveTranscript
- key={selected.task.id}
- agentSlug={agentSlug}
- agentDisplayName={agentDisplayName}
- taskId={selected.task.id}
- taskStatus={selected.task.status}
- initialEvents={selected.initialEvents}
- initialByteOffset={selected.initialByteOffset}
- sessionId={selected.threadId}
- sessionKey={selected.sessionKey}
- />
+ <SelectedTaskPanel selected={selected} agentSlug={agentSlug} agentDisplayName={agentDisplayName} />
</div>
</>
) : (
@@ -237,6 +229,46 @@ export function AgentTaskWorkspace({
);
}
+function SelectedTaskPanel({
+ selected,
+ agentSlug,
+ agentDisplayName,
+}: {
+ selected: SelectedTaskBundle;
+ agentSlug: string;
+ agentDisplayName: string;
+}) {
+ const router = useRouter();
+ const isInFlight = TASK_IN_FLIGHT.includes(selected.task.status);
+ // Each time polling returns new events we refresh the server tree so
+ // the status badge in this panel's header + the task list grouping
+ // catch up to the JSONL — the LiveTranscript handles its own rendering
+ // updates, this hook just rebroadcasts to the rest of the page.
+ const onPolled = useCallback(
+ ({ newEvents }: { newEvents: number; fileSize: number }) => {
+ if (newEvents > 0) router.refresh();
+ // Return true to stop polling once the task is terminal AND the
+ // poll returned nothing new (transcript fully drained).
+ if (!isInFlight && newEvents === 0) return true;
+ return false;
+ },
+ [isInFlight, router],
+ );
+ return (
+ <LiveTranscript
+ key={selected.task.id}
+ agentSlug={agentSlug}
+ agentDisplayName={agentDisplayName}
+ threadId={selected.threadId}
+ sessionKey={selected.sessionKey}
+ initialEvents={selected.initialEvents}
+ initialByteOffset={selected.initialByteOffset}
+ composerDisabled={isInFlight}
+ onPolled={onPolled}
+ />
+ );
+}
+
function TaskRow({
task,
selected,
diff --git a/src/components/live-transcript.tsx b/src/components/live-transcript.tsx
index 98f53219..199a5ab5 100644
--- a/src/components/live-transcript.tsx
+++ b/src/components/live-transcript.tsx
@@ -31,50 +31,75 @@ import { RunningDot } from "@/components/running-dot";
import { cn } from "@/lib/utils";
import { stripOrchestrationBlocks } from "@/server/orchestration/blocks";
import type { TranscriptEvent } from "@/server/openclaw/transcript-tail";
-import type { TaskStatus } from "@/types";
-const POLL_INTERVAL_MS = 1_500;
-const POLL_MAX_DURATION_MS = 10 * 60 * 1000;
-
-const IN_FLIGHT_STATUSES: TaskStatus[] = ["proposed", "approved", "running"];
+const POLL_INTERVAL_MS = 2_000;
type Props = {
agentSlug: string;
agentDisplayName: string;
- taskId: string;
- taskStatus: TaskStatus;
+ /** OpenClaw thread (the URL label half of `agent:<agent>:<label>`). */
+ threadId: string;
+ /** Canonical sessionKey for /api/chat sends. */
+ sessionKey: string;
/** Server-rendered initial slice of the transcript. */
initialEvents: TranscriptEvent[];
/** Byte offset *after* `initialEvents` — polls start from here. */
initialByteOffset: number;
- /** sessionId / sessionKey for the per-task chat thread, used by /api/chat. */
- sessionId: string;
- sessionKey: string;
+ /**
+ * When true, disables the composer (e.g., task is running and the user
+ * shouldn't send mid-run input). Default: composer always enabled.
+ */
+ composerDisabled?: boolean;
+ /**
+ * When set, on each successful poll we call this so the parent can
+ * react to JSONL growth (e.g., trigger router.refresh to refetch task
+ * statuses). Returning true tells us to stop background polling.
+ */
+ onPolled?: (info: { newEvents: number; fileSize: number }) => boolean | void;
+ /**
+ * Auto-kickoff: when true AND the transcript is empty AND we're not
+ * already sending, fire a hidden first message so the agent runs
+ * without the user typing. Used by /chat after onboarding (the
+ * FIRST_TURN.md sentinel) so the CMO greets without a manual nudge.
+ */
+ autoKickoff?: boolean;
+ /** Override for the auto-kickoff message body. */
+ kickoffMessage?: string;
};
+/** Module-level guard so React StrictMode dev double-mounts don't double-fire. */
+const KICKOFF_FIRED = new Set<string>();
+
export function LiveTranscript({
agentSlug,
agentDisplayName,
- taskId,
- taskStatus,
+ threadId,
+ sessionKey,
initialEvents,
initialByteOffset,
- sessionId,
- sessionKey,
+ composerDisabled = false,
+ onPolled,
+ autoKickoff = false,
+ kickoffMessage,
}: Props) {
const router = useRouter();
const [events, setEvents] = useState<TranscriptEvent[]>(initialEvents);
const [byteOffset, setByteOffset] = useState(initialByteOffset);
- const [status, setStatus] = useState<TaskStatus>(taskStatus);
const [input, setInput] = useState("");
const [sendingChat, setSendingChat] = useState(false);
+ const [stopPolling, setStopPolling] = useState(false);
+
+ // Optimistic state for the active /api/chat send. Rendered after committed
+ // events so the user sees their message + the streaming response before
+ // polling materializes them from JSONL. Cleared once polling catches up.
+ const [pendingUserMsg, setPendingUserMsg] = useState<string | null>(null);
+ const [pendingAssistant, setPendingAssistant] = useState("");
+ const [pendingTools, setPendingTools] = useState<ToolEntry[]>([]);
+ const [pendingError, setPendingError] = useState<string | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
- const bottomSentinelRef = useRef<HTMLDivElement>(null);
const stickyBottomRef = useRef(true);
- const startedAtRef = useRef<number | null>(null);
-
- const isInFlight = IN_FLIGHT_STATUSES.includes(status);
+ const abortRef = useRef<AbortController | null>(null);
// ── Auto-scroll: only when the user is already near the bottom. ─────
function onScroll() {
@@ -88,104 +113,154 @@ export function LiveTranscript({
const el = scrollRef.current;
if (!el) return;
el.scrollTop = el.scrollHeight;
- }, [events, sendingChat]);
+ }, [events, sendingChat, pendingAssistant, pendingTools, pendingUserMsg]);
- // ── Live tail polling. Stops once the server reports `done: true`. ──
+ // ── Live tail polling. ─────────────────────────────────────────────
const pollOnce = useCallback(async () => {
try {
- const url = `/api/agents/${agentSlug}/tasks/${taskId}/transcript?offset=${byteOffset}`;
+ const url = `/api/agents/${agentSlug}/threads/${threadId}/transcript?offset=${byteOffset}`;
const res = await fetch(url, { cache: "no-store" });
- if (!res.ok) return { stop: false };
+ if (!res.ok) return { newEvents: 0 };
const data = (await res.json()) as {
events: TranscriptEvent[];
byteOffset: number;
- done: boolean;
- status: TaskStatus;
+ file_size: number;
};
if (data.events.length > 0) {
setEvents((prev) => [...prev, ...data.events]);
+ // Clear pending state: JSONL now has the canonical events so the
+ // optimistic placeholders are no longer needed.
+ setPendingUserMsg(null);
+ setPendingAssistant("");
+ setPendingTools([]);
+ setPendingError(null);
}
if (data.byteOffset !== byteOffset) setByteOffset(data.byteOffset);
- if (data.status !== status) {
- setStatus(data.status);
- // Status flipped — refresh the rest of the page (task list pills,
- // status badge in the brief header). Cheaper than a full reload.
- router.refresh();
- }
- return { stop: data.done };
+ const shouldStop = onPolled?.({
+ newEvents: data.events.length,
+ fileSize: data.file_size,
+ });
+ if (shouldStop) setStopPolling(true);
+ return { newEvents: data.events.length };
} catch {
- return { stop: false };
+ return { newEvents: 0 };
}
- }, [agentSlug, byteOffset, router, status, taskId]);
+ }, [agentSlug, byteOffset, onPolled, threadId]);
+ // Background polling: runs while mounted, paused during an active send so
+ // we don't double-render content we're already streaming via SSE.
useEffect(() => {
- if (!isInFlight) return;
- if (startedAtRef.current === null) startedAtRef.current = Date.now();
+ if (stopPolling) return;
+ if (sendingChat) return;
let cancelled = false;
let timer: ReturnType<typeof setTimeout> | null = null;
-
const tick = async () => {
if (cancelled) return;
- const elapsed = Date.now() - (startedAtRef.current ?? Date.now());
- if (elapsed > POLL_MAX_DURATION_MS) return;
- const { stop } = await pollOnce();
- if (cancelled || stop) return;
+ await pollOnce();
+ if (cancelled) return;
timer = setTimeout(tick, POLL_INTERVAL_MS);
};
-
timer = setTimeout(tick, POLL_INTERVAL_MS);
return () => {
cancelled = true;
if (timer) clearTimeout(timer);
};
- }, [isInFlight, pollOnce]);
+ }, [pollOnce, sendingChat, stopPolling]);
- // ── Pair tool_call with its eventual tool_result so they render as ONE row.
- const rendered = useMemo(() => collapseToolPairs(events), [events]);
+ // ── Send: optimistic user message + SSE-driven streaming reply. ─────
+ const send = useCallback(
+ async (overrideText?: string, opts: { hidden?: boolean } = {}) => {
+ const usingOverride = typeof overrideText === "string";
+ const text = (usingOverride ? overrideText : input).trim();
+ if (!text || sendingChat) return;
+ if (!usingOverride) setInput("");
+ setSendingChat(true);
+ setPendingUserMsg(opts.hidden ? null : text);
+ setPendingAssistant("");
+ setPendingTools([]);
+ setPendingError(null);
- // ── Composer: enabled only when the task isn't actively in flight. ──
- async function send() {
- const text = input.trim();
- if (!text || sendingChat) return;
- setInput("");
- setSendingChat(true);
- try {
- // Pipe through /api/chat exactly like AgentChat does — the response
- // streams to the JSONL we're already tailing, so the new turn lands
- // automatically once polling resumes (which we kick off below by
- // letting the task status flip back to running via the server).
- const res = await fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- message: text,
- agent: agentSlug,
- sessionId,
- sessionKey,
- }),
- });
- if (!res.ok || !res.body) {
- const err = await res.text();
- throw new Error(err || `HTTP ${res.status}`);
- }
- // Drain the SSE stream so the gateway run completes; we don't need
- // to render its events here (the JSONL tail will pick everything up
- // on the next poll). We just have to consume the body so the agent
- // turn doesn't stall on backpressure.
- const reader = res.body.getReader();
- while (true) {
- const { done } = await reader.read();
- if (done) break;
+ const ctrl = new AbortController();
+ abortRef.current = ctrl;
+
+ try {
+ const res = await fetch("/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ message: text,
+ agent: agentSlug,
+ sessionId: threadId,
+ sessionKey,
+ }),
+ signal: ctrl.signal,
+ });
+ if (!res.ok || !res.body) {
+ throw new Error((await res.text()) || `HTTP ${res.status}`);
+ }
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ const events = buffer.split("\n\n");
+ buffer = events.pop() ?? "";
+ for (const raw of events) {
+ handleSseEvent(raw, {
+ onText: (chunk) => setPendingAssistant((s) => s + chunk),
+ onTool: (evt) => {
+ setPendingTools((prev) =>
+ upsertToolEntry(prev, evt),
+ );
+ },
+ onError: (msg) => setPendingError(msg),
+ });
+ }
+ }
+ // Stream closed. Give OpenClaw a moment to flush the JSONL, then
+ // pull the committed events. pollOnce clears pending state when it
+ // returns new events; if it returns nothing yet, the regular
+ // polling effect picks it up on the next tick.
+ await new Promise((r) => setTimeout(r, 400));
+ const { newEvents } = await pollOnce();
+ if (newEvents === 0) {
+ // Re-try once more shortly. Avoids the case where OpenClaw is
+ // slow to flush and the user briefly sees pending state with no
+ // backing JSONL.
+ setTimeout(() => {
+ void pollOnce();
+ }, 1200);
+ }
+ } catch (err) {
+ const isAbort = err instanceof DOMException && err.name === "AbortError";
+ if (!isAbort) {
+ const msg = err instanceof Error ? err.message : String(err);
+ setPendingError(msg);
+ toast.error(msg);
+ }
+ } finally {
+ setSendingChat(false);
+ abortRef.current = null;
}
- // After the turn closes, prompt a re-poll so the new transcript bytes
- // show up immediately instead of waiting for the next tick.
- void pollOnce();
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "Send failed");
- } finally {
- setSendingChat(false);
- }
- }
+ },
+ [agentSlug, input, pollOnce, sendingChat, sessionKey, threadId],
+ );
+
+ // ── Auto-kickoff for FIRST_TURN-style flows. ────────────────────────
+ useEffect(() => {
+ if (!autoKickoff) return;
+ if (KICKOFF_FIRED.has(threadId)) return;
+ if (events.length > 0) return;
+ if (sendingChat) return;
+ KICKOFF_FIRED.add(threadId);
+ void send(kickoffMessage ?? "(session start)", { hidden: true });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [autoKickoff, threadId]);
+
+ const rendered = useMemo(() => collapseEvents(events), [events]);
+ const showThinking = sendingChat && pendingAssistant === "" && pendingTools.length === 0;
return (
<div className="flex h-full flex-col">
@@ -197,25 +272,42 @@ export function LiveTranscript({
aria-live="polite"
>
<div className="mx-auto w-full max-w-3xl px-6 py-6">
- {rendered.length === 0 ? (
- <TranscriptEmptyState
- status={status}
- agentDisplayName={agentDisplayName}
- />
+ {rendered.length === 0 && !pendingUserMsg && !sendingChat ? (
+ <TranscriptEmptyState agentDisplayName={agentDisplayName} />
) : (
<ol className="space-y-4">
{rendered.map((item) => (
<li key={item.key}>
- <RenderItem
- item={item}
- agentDisplayName={agentDisplayName}
- />
+ <RenderItem item={item} />
</li>
))}
+ {pendingUserMsg && (
+ <li>
+ <UserBubble body={pendingUserMsg} />
+ </li>
+ )}
+ {pendingTools.length > 0 && (
+ <li>
+ <ToolGroup tools={pendingTools} />
+ </li>
+ )}
+ {pendingAssistant && (
+ <li>
+ <AssistantText body={pendingAssistant} />
+ </li>
+ )}
+ {pendingError && (
+ <li>
+ <ErrorRow agentDisplayName={agentDisplayName} body={pendingError} />
+ </li>
+ )}
+ {showThinking && (
+ <li>
+ <ThinkingPulse agentDisplayName={agentDisplayName} />
+ </li>
+ )}
</ol>
)}
- {isInFlight && <ThinkingPulse agentDisplayName={agentDisplayName} />}
- <div ref={bottomSentinelRef} />
</div>
</div>
@@ -237,34 +329,43 @@ export function LiveTranscript({
void send();
}
}}
- disabled={isInFlight || sendingChat}
+ disabled={composerDisabled}
placeholder={
- isInFlight
- ? `${agentDisplayName} is working — the transcript updates live`
+ composerDisabled
+ ? `${agentDisplayName} is on a task — the transcript updates live`
: `Message ${agentDisplayName}…`
}
rows={1}
className="flex min-h-[40px] flex-1 resize-none rounded-xl border bg-background px-3.5 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
/>
- <Button
- type="submit"
- size="sm"
- disabled={isInFlight || sendingChat || !input.trim()}
- className="h-10 rounded-xl"
- >
- {sendingChat ? (
+ {sendingChat ? (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => abortRef.current?.abort()}
+ className="h-10 rounded-xl"
+ aria-label="Stop"
+ >
<StopCircle className="size-4" />
- ) : (
+ </Button>
+ ) : (
+ <Button
+ type="submit"
+ size="sm"
+ disabled={composerDisabled || !input.trim()}
+ className="h-10 rounded-xl"
+ aria-label="Send"
+ >
<Send className="size-4" />
- )}
- <span className="sr-only">Send</span>
- </Button>
+ </Button>
+ )}
</form>
<p className="pt-1.5 text-center text-[10px] text-muted-foreground">
- {isInFlight ? (
+ {sendingChat ? (
<span className="inline-flex items-center gap-1.5">
<RunningDot size="sm" aria-label="" />
- Live · polling every {Math.round(POLL_INTERVAL_MS / 1000)}s
+ Streaming — click stop to abort
</span>
) : (
<>Enter to send · Shift+Enter for newline</>
@@ -276,6 +377,76 @@ export function LiveTranscript({
);
}
+// ── SSE plumbing for the active send ────────────────────────────────────
+
+type SseToolEvent = {
+ phase: "start" | "update" | "result";
+ tool_call_id: string;
+ name: string;
+ label?: string;
+};
+
+function handleSseEvent(
+ raw: string,
+ handlers: {
+ onText: (chunk: string) => void;
+ onTool: (evt: SseToolEvent) => void;
+ onError: (msg: string) => void;
+ },
+) {
+ const lines = raw.split("\n");
+ const evtLine = lines.find((l) => l.startsWith("event: "));
+ const dataLine = lines.find((l) => l.startsWith("data: "));
+ if (!evtLine || !dataLine) return;
+ const evt = evtLine.slice("event: ".length);
+ let data: unknown;
+ try {
+ data = JSON.parse(dataLine.slice("data: ".length));
+ } catch {
+ return;
+ }
+ if (evt === "text") {
+ const chunk = (data as { chunk?: string }).chunk;
+ if (typeof chunk === "string") handlers.onText(chunk);
+ return;
+ }
+ if (evt === "tool") {
+ handlers.onTool(data as SseToolEvent);
+ return;
+ }
+ if (evt === "error") {
+ const msg = (data as { message?: string }).message ?? "unknown error";
+ handlers.onError(msg);
+ return;
+ }
+}
+
+function upsertToolEntry(prev: ToolEntry[], evt: SseToolEvent): ToolEntry[] {
+ const idx = prev.findIndex((t) => t.toolCallId === evt.tool_call_id);
+ if (idx < 0) {
+ return [
+ ...prev,
+ {
+ toolCallId: evt.tool_call_id,
+ name: evt.name,
+ label: evt.label ?? null,
+ result: null,
+ ok: true,
+ done: evt.phase === "result",
+ },
+ ];
+ }
+ const next = prev.slice();
+ const existing = next[idx]!;
+ next[idx] = {
+ ...existing,
+ name: evt.name,
+ label: evt.label ?? existing.label,
+ done: evt.phase === "result" ? true : existing.done,
+ };
+ return next;
+}
+
// ── Rendering helpers ──────────────────────────────────────────────────
type ToolEntry = {
@@ -298,13 +469,12 @@ type RenderedItem =
* sometimes interleaved across multiple message rows in one turn. We:
* 1. Pair calls with their later results by tool_call_id so each tool
* renders as one logical entry (spinner → check).
- * 2. Group runs of contiguous tool entries (no assistant_text or user_msg
- * between them) into a single collapsible "tool_group". Mirrors
- * Claude.ai's pattern — one card per cluster, summary shows the most
- * recent tool name, expand to see all of them.
+ * 2. Group runs of contiguous tool entries (no assistant_text or
+ * user_message between them) into a single collapsible "tool_group".
+ * Mirrors Claude.ai's pattern — one card per cluster, summary shows
+ * the most recent tool name, expand to see all of them.
*/
-function collapseToolPairs(events: TranscriptEvent[]): RenderedItem[] {
- // Pass 1: flatten + pair results into tool entries, preserving order.
+function collapseEvents(events: TranscriptEvent[]): RenderedItem[] {
type Step =
| { tag: "tool"; key: string; entry: ToolEntry }
| { tag: "msg"; item: RenderedItem };
@@ -339,7 +509,6 @@ function collapseToolPairs(events: TranscriptEvent[]): RenderedItem[] {
};
continue;
}
- // Orphan result — render standalone so the user still sees something.
steps.push({
tag: "tool",
key: e.id,
@@ -376,8 +545,6 @@ function collapseToolPairs(events: TranscriptEvent[]): RenderedItem[] {
continue;
}
}
-
- // Pass 2: group contiguous tool entries into a single tool_group item.
const out: RenderedItem[] = [];
let buffer: ToolEntry[] = [];
let bufferKey: string | null = null;
@@ -400,58 +567,46 @@ function collapseToolPairs(events: TranscriptEvent[]): RenderedItem[] {
return out;
}
-function RenderItem({
- item,
- agentDisplayName: _agentDisplayName,
-}: {
- item: RenderedItem;
- agentDisplayName: string;
-}) {
+function RenderItem({ item }: { item: RenderedItem }) {
if (item.kind === "user_message") {
- // Kickoff messages (the task brief + operating protocol that
- // buildTaskKickoffMessage produces, or FIRST_TURN session opens) are
- // technically user-role rows in OpenClaw, but they're system-injected
- // not user-typed. Collapse them so the transcript reads as "agent
- // acknowledged + did the work", not "USER DUMPED 30 LINES OF XML".
const isKickoff =
item.body.startsWith("(task assignment)") ||
item.body.startsWith("(session start)") ||
item.body.startsWith("TASK_BRIEF") ||
item.body.startsWith("FIRST_TURN");
- if (isKickoff) {
- return <KickoffBlock body={item.body} />;
- }
- return (
- <div className="flex justify-end">
- <div className="max-w-[85%] rounded-2xl bg-muted px-4 py-2 text-sm leading-relaxed whitespace-pre-wrap break-words">
- {item.body}
- </div>
- </div>
- );
+ if (isKickoff) return <KickoffBlock body={item.body} />;
+ return <UserBubble body={item.body} />;
}
if (item.kind === "assistant_text") {
- // Same orchestration-tag stripping the live chat applies — keeps the
- // raw <task_status>…</task_status>, <create_task>…</create_task> XML
- // out of the user-facing transcript. The structured outcome already
- // lives in the task DB row.
- const cleanBody = stripOrchestrationBlocks(item.body);
- if (cleanBody.trim() === "") return null;
- return (
- <div className="text-sm leading-relaxed">
- <Markdown>{cleanBody}</Markdown>
- </div>
- );
+ return <AssistantText body={item.body} />;
}
if (item.kind === "tool_group") {
return <ToolGroup tools={item.tools} />;
}
- // Unknown / system rows render as a thin divider so the eye can scan past.
return null;
}
+function UserBubble({ body }: { body: string }) {
+ return (
+ <div className="flex justify-end">
+ <div className="max-w-[85%] rounded-2xl bg-muted px-4 py-2 text-sm leading-relaxed whitespace-pre-wrap break-words">
+ {body}
+ </div>
+ </div>
+ );
+}
+
+function AssistantText({ body }: { body: string }) {
+ const cleanBody = stripOrchestrationBlocks(body);
+ if (cleanBody.trim() === "") return null;
+ return (
+ <div className="text-sm leading-relaxed">
+ <Markdown>{cleanBody}</Markdown>
+ </div>
+ );
+}
+
function KickoffBlock({ body }: { body: string }) {
- // Show the task brief as a collapsed system block — full text visible but
- // visually demoted so it doesn't dominate the transcript.
return (
<details className="group rounded-md border border-dashed border-muted-foreground/30 bg-muted/20 px-3 py-2 text-xs">
<summary className="flex cursor-pointer items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground select-none">
@@ -466,15 +621,8 @@ function KickoffBlock({ body }: { body: string }) {
}
function ToolGroup({ tools }: { tools: ToolEntry[] }) {
- // Auto-expand while any tool in the group is still in flight so the user
- // can watch progress; collapse on completion (user can re-open via the
- // chevron). The summary row always shows the most recent tool name +
- // running/done count — mirrors Claude.ai's web chat behavior.
const inFlightCount = tools.filter((t) => !t.done).length;
const isLive = inFlightCount > 0;
- // The "headline" is the newest tool: while running that's the in-flight
- // one; when done it's just the last entry. Either way the user sees the
- // most informative single line at a glance.
const headline =
tools.find((t) => !t.done) ?? tools[tools.length - 1] ?? null;
const hasError = tools.some((t) => t.done && !t.ok);
@@ -490,11 +638,6 @@ function ToolGroup({ tools }: { tools: ToolEntry[] }) {
? "text-destructive"
: "text-emerald-600";
- // `key` includes the open-by-default signal so React rebuilds the
- // <details> when liveness flips. Without this, a group that streamed in
- // expanded would stay expanded after completion; we want the inverse
- // (open while live, collapsed when done, but user choice always wins
- // within a single liveness phase).
return (
<details
key={isLive ? "live" : "done"}
@@ -582,32 +725,43 @@ function ToolRow({ entry }: { entry: ToolEntry }) {
function ThinkingPulse({ agentDisplayName }: { agentDisplayName: string }) {
return (
- <div className="mt-4 flex items-center gap-2 text-xs italic text-muted-foreground">
+ <div className="flex items-center gap-2 text-xs italic text-muted-foreground">
<RunningDot size="sm" aria-label="" />
{agentDisplayName} is working…
</div>
);
}
-function TranscriptEmptyState({
- status,
+function ErrorRow({
agentDisplayName,
+ body,
}: {
- status: TaskStatus;
agentDisplayName: string;
+ body: string;
}) {
- if (status === "proposed") {
- return (
- <div className="py-12 text-center text-sm text-muted-foreground">
- Waiting for {agentDisplayName} to pick this up. Hit{" "}
- <span className="font-mono text-xs">Start all</span> on the agent tasks
- page, or open this task to kick it off.
+ return (
+ <div className="flex items-start gap-2 rounded-md border border-destructive/50 bg-destructive/5 p-3 text-sm">
+ <AlertCircle className="mt-0.5 size-4 shrink-0 text-destructive" />
+ <div className="min-w-0 flex-1">
+ <div className="font-medium text-destructive">
+ Couldn&rsquo;t reach {agentDisplayName}.
+ </div>
+ <div className="mt-1 text-xs text-muted-foreground whitespace-pre-wrap break-words">
+ {body}
+ </div>
</div>
- );
- }
+ </div>
+ );
+}
+
+function TranscriptEmptyState({
+ agentDisplayName,
+}: {
+ agentDisplayName: string;
+}) {
return (
<div className="py-12 text-center text-sm text-muted-foreground">
- No transcript yet. Send a message below to start the conversation.
+ No messages yet. Say hi to {agentDisplayName} below.
</div>
);
}
diff --git a/src/components/slash-command-popover.tsx b/src/components/slash-command-popover.tsx
deleted file mode 100644
index 0456ab3e..00000000
--- a/src/components/slash-command-popover.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-"use client";
-
-import { useEffect, useRef } from "react";
-import { cn } from "@/lib/utils";
-import type { SlashCommand } from "@/lib/slash-commands";
-
-type Props = {
- commands: SlashCommand[];
- selectedIndex: number;
- onSelect: (command: SlashCommand) => void;
- onHover: (index: number) => void;
-};
-
-const CATEGORY_LABEL: Record<SlashCommand["category"], string> = {
- session: "Session",
- model: "Model",
- status: "Status",
- agents: "Agents",
- tools: "Tools",
- advanced: "Advanced",
-};
-
-const CATEGORY_ACCENT: Record<SlashCommand["category"], string> = {
- session: "text-blue-600 dark:text-blue-400",
- model: "text-emerald-600 dark:text-emerald-400",
- status: "text-zinc-500 dark:text-zinc-400",
- agents: "text-violet-600 dark:text-violet-400",
- tools: "text-cyan-600 dark:text-cyan-400",
- advanced: "text-amber-600 dark:text-amber-400",
-};
-
-export function SlashCommandPopover({
- commands,
- selectedIndex,
- onSelect,
- onHover,
-}: Props) {
- const listRef = useRef<HTMLUListElement>(null);
-
- // Keep the selected row in view as the user arrows through a long list.
- useEffect(() => {
- const list = listRef.current;
- if (!list) return;
- const row = list.children[selectedIndex] as HTMLElement | undefined;
- if (row) row.scrollIntoView({ block: "nearest" });
- }, [selectedIndex]);
-
- if (commands.length === 0) {
- return (
- <div
- className="absolute bottom-full left-0 right-0 mb-2 rounded-xl border bg-popover p-3 text-xs text-muted-foreground shadow-lg"
- role="listbox"
- aria-label="Slash commands"
- >
- No matching slash commands.
- </div>
- );
- }
-
- return (
- <div
- className="absolute bottom-full left-0 right-0 mb-2 overflow-hidden rounded-xl border bg-popover shadow-lg"
- role="listbox"
- aria-label="Slash commands"
- >
- <ul ref={listRef} className="max-h-72 overflow-y-auto py-1">
- {commands.map((c, idx) => {
- const isActive = idx === selectedIndex;
- return (
- <li key={c.name}>
- <button
- type="button"
- onMouseEnter={() => onHover(idx)}
- onClick={() => onSelect(c)}
- className={cn(
- "flex w-full items-center gap-3 px-3 py-2 text-left text-sm transition-colors",
- isActive ? "bg-accent" : "hover:bg-accent/50",
- )}
- role="option"
- aria-selected={isActive}
- >
- <span className="w-28 shrink-0 font-mono text-[13px] text-foreground">
- /{c.name}
- {c.args && (
- <span className="ml-1 text-muted-foreground">{c.args}</span>
- )}
- </span>
- <span className="flex-1 truncate text-xs text-muted-foreground">
- {c.description}
- </span>
- {c.executeLocal && (
- <span className="shrink-0 rounded border px-1 text-[9px] uppercase tracking-wide text-muted-foreground">
- local
- </span>
- )}
- <span
- className={cn(
- "shrink-0 text-[10px] uppercase tracking-wide",
- CATEGORY_ACCENT[c.category],
- )}
- >
- {CATEGORY_LABEL[c.category]}
- </span>
- </button>
- </li>
- );
- })}
- </ul>
- <div className="border-t bg-muted/30 px-3 py-1.5 text-[10px] text-muted-foreground">
- ↑↓ navigate · Enter / Tab to select · Enter again to send · Esc to clear
- </div>
- </div>
- );
-}
diff --git a/src/lib/slash-commands.ts b/src/lib/slash-commands.ts
deleted file mode 100644
index 9944ed9a..00000000
--- a/src/lib/slash-commands.ts
+++ /dev/null
@@ -1,281 +0,0 @@
-/**
- * Slash command catalog + local executor.
- *
- * Ported from OpenClaw's web UI:
- * - ui/src/ui/chat/slash-commands.ts (catalog + LOCAL_COMMANDS set)
- * - ui/src/ui/chat/slash-command-executor.ts (action-based dispatcher)
- *
- * Rules:
- * - executeLocal=true → command is handled by the client; not sent to the agent.
- * - Anything else → message goes to OpenClaw verbatim.
- *
- * For the V1 client we wire only the no-gateway-RPC locals (clear, new, help,
- * stop). The rest carry executeLocal=false and pass through to the agent.
- */
-
-export type SlashCommandCategory =
- | "session"
- | "model"
- | "status"
- | "agents"
- | "tools"
- | "advanced";
-
-export type SlashCommandTier = "essential" | "standard" | "power";
-
-export type SlashCommand = {
- /** Canonical key (matches OpenClaw registry where applicable). */
- key: string;
- /** Display name (without the leading slash). */
- name: string;
- /** Short description shown in the menu. */
- description: string;
- /** Optional argument hint shown beside the name. */
- args?: string;
- category: SlashCommandCategory;
- tier: SlashCommandTier;
- /** When true, AgentChat handles this client-side and does NOT call openclaw. */
- executeLocal?: boolean;
- /** Text inserted into the textarea when the user picks this. Defaults to `/${name} `. */
- insert?: string;
-};
-
-export const SLASH_COMMANDS: SlashCommand[] = [
- // Session — local-only in OpenClaw web UI
- {
- key: "clear",
- name: "clear",
- description: "Clear the visible chat buffer (trajectory on disk is kept).",
- category: "session",
- tier: "essential",
- executeLocal: true,
- },
- {
- key: "new",
- name: "new",
- description: "Start a new session (creates a fresh thread).",
- category: "session",
- tier: "essential",
- executeLocal: true,
- },
- {
- key: "stop",
- name: "stop",
- description: "Stop the in-flight response.",
- category: "session",
- tier: "essential",
- executeLocal: true,
- },
- {
- key: "help",
- name: "help",
- description: "Show available commands.",
- category: "status",
- tier: "essential",
- executeLocal: true,
- },
-
- // Status — sent to the agent / OpenClaw handles
- {
- key: "commands",
- name: "commands",
- description: "List all slash commands.",
- category: "status",
- tier: "power",
- },
- {
- key: "status",
- name: "status",
- description: "Show current status.",
- category: "status",
- tier: "essential",
- },
- {
- key: "whoami",
- name: "whoami",
- description: "Show your identity / caller.",
- category: "status",
- tier: "standard",
- },
- {
- key: "usage",
- name: "usage",
- description: "Show token / cost usage for this session.",
- category: "status",
- tier: "standard",
- },
-
- // Tools
- {
- key: "tools",
- name: "tools",
- description: "List available runtime tools.",
- category: "tools",
- tier: "standard",
- },
- {
- key: "skill",
- name: "skill",
- description: "Run a skill by name.",
- args: "<name>",
- category: "tools",
- tier: "standard",
- insert: "/skill ",
- },
-
- // Session / context management — pass through to OpenClaw
- {
- key: "compact",
- name: "compact",
- description: "Compact the session context to reduce token use.",
- category: "session",
- tier: "standard",
- },
- {
- key: "reset",
- name: "reset",
- description: "Reset the current session.",
- category: "session",
- tier: "standard",
- },
-
- // Model / behaviour directives — pass through to OpenClaw
- {
- key: "model",
- name: "model",
- description: "Override model for this turn.",
- args: "<id>",
- category: "model",
- tier: "standard",
- insert: "/model ",
- },
- {
- key: "think",
- name: "think",
- description: "Directive: enable extended thinking.",
- category: "model",
- tier: "standard",
- },
- {
- key: "fast",
- name: "fast",
- description: "Directive: disable thinking for fastest response.",
- category: "model",
- tier: "standard",
- },
- {
- key: "verbose",
- name: "verbose",
- description: "Directive: verbose progress output.",
- category: "model",
- tier: "standard",
- },
- {
- key: "trace",
- name: "trace",
- description: "Directive: include trace details.",
- category: "model",
- tier: "power",
- },
- {
- key: "reasoning",
- name: "reasoning",
- description: "Directive: surface reasoning steps.",
- category: "model",
- tier: "power",
- },
-
- // Advanced
- {
- key: "elevated",
- name: "elevated",
- description: "Directive: request elevated permissions (gateway-controlled).",
- category: "advanced",
- tier: "power",
- },
- {
- key: "exec",
- name: "exec",
- description: "Directive: allow exec tool use (gateway-controlled).",
- category: "advanced",
- tier: "power",
- },
- {
- key: "queue",
- name: "queue",
- description: "Directive: queue the turn instead of running inline.",
- category: "advanced",
- tier: "power",
- },
-];
-
-/**
- * Filter commands by what the user has typed after the leading `/`.
- * Prefix match wins; substring is a fallback so `/cm` still finds /compact + /commands.
- */
-export function filterSlashCommands(query: string): SlashCommand[] {
- const q = query.trim().toLowerCase();
- if (!q || q === "/") return SLASH_COMMANDS;
- const stripped = q.startsWith("/") ? q.slice(1) : q;
- const exact = SLASH_COMMANDS.filter((c) => c.name.toLowerCase().startsWith(stripped));
- if (exact.length > 0) return exact;
- return SLASH_COMMANDS.filter((c) => c.name.toLowerCase().includes(stripped));
-}
-
-/**
- * Parse a chat message into { command, args } if it starts with a slash.
- * Returns null for plain (non-slash) messages.
- */
-export function parseSlashMessage(text: string): { command: string; args: string } | null {
- const trimmed = text.trim();
- if (!trimmed.startsWith("/")) return null;
- const space = trimmed.indexOf(" ");
- if (space === -1) {
- return { command: trimmed.slice(1), args: "" };
- }
- return { command: trimmed.slice(1, space), args: trimmed.slice(space + 1).trim() };
-}
-
-export function findCommand(name: string): SlashCommand | undefined {
- return SLASH_COMMANDS.find((c) => c.name === name);
-}
-
-// --- Local command actions ---
-
-export type LocalSlashAction =
- | { kind: "clear" }
- | { kind: "new-session" }
- | { kind: "stop" }
- | { kind: "help"; content: string };
-
-/**
- * Execute a slash command locally if it's marked executeLocal. Returns null
- * when the command should be sent to the agent verbatim.
- */
-export function executeLocalSlashCommand(command: string): LocalSlashAction | null {
- const def = findCommand(command);
- if (!def?.executeLocal) return null;
- switch (command) {
- case "clear":
- return { kind: "clear" };
- case "new":
- return { kind: "new-session" };
- case "stop":
- return { kind: "stop" };
- case "help":
- return { kind: "help", content: renderHelp() };
- default:
- // executeLocal=true but no handler? Treat as pass-through.
- return null;
- }
-}
-
-function renderHelp(): string {
- const lines = ["**Available commands** (type `/` to open the menu):", ""];
- for (const c of SLASH_COMMANDS) {
- const args = c.args ? ` ${c.args}` : "";
- const local = c.executeLocal ? " · local" : " · sent to agent";
- lines.push(`• \`/${c.name}${args}\` — ${c.description}${local}`);
- }
- return lines.join("\n");
-}
diff --git a/src/server/openclaw/sessions.ts b/src/server/openclaw/sessions.ts
index ce369d84..71bcdebf 100644
--- a/src/server/openclaw/sessions.ts
+++ b/src/server/openclaw/sessions.ts
@@ -171,92 +171,6 @@ export async function getSessionsView(
return { active, all };
}
-export type ChatMessage = {
- /** Stable per-line key for React. */
- id: string;
- role: "user" | "assistant";
- body: string;
- /** Epoch ms; 0 if unknown. */
- timestamp: number;
-};
-
-/**
- * Read a session's history from OpenClaw's per-session JSONL trajectory.
- * Each line is a typed event; we only surface `type === "message"` entries
- * with role + text. Returns [] when the file does not exist yet (brand new
- * session that hasn't had its first turn).
- */
-export function loadSessionHistory(agentFullId: string, sessionId: string): ChatMessage[] {
- const path = join(OPENCLAW_HOME, "agents", agentFullId, "sessions", `${sessionId}.jsonl`);
- if (!existsSync(path)) return [];
- let raw: string;
- try {
- raw = readFileSync(path, "utf8");
- } catch {
- return [];
- }
-
- const messages: ChatMessage[] = [];
- let idx = 0;
- for (const line of raw.split("\n")) {
- const trimmed = line.trim();
- if (!trimmed) continue;
- let entry: Record<string, unknown>;
- try {
- entry = JSON.parse(trimmed) as Record<string, unknown>;
- } catch {
- continue;
- }
- if (entry.type !== "message") continue;
- const message = entry.message as
- | {
- role?: string;
- // OpenClaw persists user messages as a plain string and assistant
- // messages as a content-parts array. Accept either shape — see
- // extractText() below.
- content?: string | Array<{ type?: string; text?: string } | string>;
- timestamp?: number;
- }
- | undefined;
- if (!message || (message.role !== "user" && message.role !== "assistant")) continue;
- const text = extractText(message.content);
- if (!text) continue;
- messages.push({
- id: `${sessionId}-${idx++}`,
- role: message.role,
- body: stripUserTimestampPrefix(text, message.role),
- timestamp: typeof message.timestamp === "number" ? message.timestamp : 0,
- });
- }
- return messages;
-}
-
-function extractText(
- content: string | Array<{ type?: string; text?: string } | string> | undefined,
-): string {
- if (typeof content === "string") return content.trim();
- if (!Array.isArray(content)) return "";
- return content
- .map((c) => {
- if (typeof c === "string") return c;
- if (c?.type === "text" && typeof c.text === "string") return c.text;
- return "";
- })
- .filter((s) => s.length > 0)
- .join("\n")
- .trim();
-}
-
-/**
- * OpenClaw prefixes user messages with `[Day YYYY-MM-DD HH:MM TZ] ` to give
- * the model time context. Hide that in the UI so the user sees their original
- * message body.
- */
-function stripUserTimestampPrefix(text: string, role: string): string {
- if (role !== "user") return text;
- return text.replace(/^\[[A-Z][a-z]{2} \d{4}-\d{2}-\d{2} \d{2}:\d{2} [A-Z]{2,5}\] ?/, "");
-}
-
export async function setActiveSession(
project_slug: string,
agent_template_key: AgentTemplateKey,
diff --git a/src/server/orchestration/thread-history.test.ts b/src/server/orchestration/thread-history.test.ts
deleted file mode 100644
index 3a9171bf..00000000
--- a/src/server/orchestration/thread-history.test.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const findSessionBySessionIdMock = vi.fn();
-const loadSessionHistoryMock = vi.fn();
-vi.mock("@/server/openclaw/sessions", () => ({
- findSessionBySessionId: (agentFullId: string, threadId: string) =>
- findSessionBySessionIdMock(agentFullId, threadId),
- loadSessionHistory: (agentFullId: string, sessionId: string) =>
- loadSessionHistoryMock(agentFullId, sessionId),
- buildPendingSessionKey: (agentFullId: string, threadId: string) =>
- `agent:${agentFullId}:${threadId}`,
-}));
-
-import { loadThreadHistory } from "./thread-history";
-
-describe("loadThreadHistory", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("resolves threadId → OpenClaw sessionId, then loads history with sessionId (not threadId)", () => {
- // URL threadId is "thread-abc" but OpenClaw's internal sessionId for
- // that thread is "internal-xyz" — distinct values. Previous bug: we
- // called loadSessionHistory(threadId), got an empty file, kickoff
- // re-fired. Fix: resolve via findSessionBySessionId first.
- findSessionBySessionIdMock.mockReturnValueOnce({
- sessionId: "internal-xyz",
- label: "thread-abc",
- sessionKey: "agent:demo-google-ads:thread-abc",
- lastInteractionAt: 1,
- pending: false,
- });
- loadSessionHistoryMock.mockReturnValueOnce([
- { id: "0", role: "user", body: "(task assignment) ...", timestamp: 1 },
- { id: "1", role: "assistant", body: "On it.", timestamp: 2 },
- ]);
-
- const out = loadThreadHistory("demo-google-ads", "thread-abc");
-
- expect(loadSessionHistoryMock).toHaveBeenCalledWith(
- "demo-google-ads",
- "internal-xyz",
- );
- expect(loadSessionHistoryMock).not.toHaveBeenCalledWith(
- "demo-google-ads",
- "thread-abc",
- );
- expect(out.sessionKey).toBe("agent:demo-google-ads:thread-abc");
- expect(out.history).toHaveLength(2);
- });
-
- it("returns pending sessionKey + empty history when threadId is unknown to OpenClaw", () => {
- // First open of a freshly-minted thread — OpenClaw hasn't seen it
- // yet, so findSessionBySessionId returns null. Caller should treat
- // as pending (no history, sessionKey is a fresh pending one).
- findSessionBySessionIdMock.mockReturnValueOnce(null);
- const out = loadThreadHistory("demo-google-ads", "fresh-thread");
- expect(out.history).toEqual([]);
- expect(out.sessionKey).toBe("agent:demo-google-ads:fresh-thread");
- expect(loadSessionHistoryMock).not.toHaveBeenCalled();
- });
-});
diff --git a/src/server/orchestration/thread-history.ts b/src/server/orchestration/thread-history.ts
deleted file mode 100644
index 77fc2adf..00000000
--- a/src/server/orchestration/thread-history.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import {
- buildPendingSessionKey,
- findSessionBySessionId,
- loadSessionHistory,
- type ChatMessage,
-} from "@/server/openclaw/sessions";
-
-/**
- * Resolve `threadId → (sessionKey, history)` for an agent.
- *
- * Why this helper exists: the URL threadId we mint is the LABEL half of
- * OpenClaw's sessionKey (`agent:<agent>:<label>`), NOT OpenClaw's internal
- * `sessionId` (a different UUID OpenClaw assigns when it writes the
- * transcript JSONL on first turn). loadSessionHistory takes that internal
- * sessionId. Passing the URL threadId directly silently returns [] for any
- * existing thread — which then trips autoKickoff and re-runs the agent.
- *
- * Both the agent's per-thread chat page and the per-task chat thread on
- * /tasks/[id] use this helper so the discrepancy can't bite again.
- */
-export function loadThreadHistory(
- agentFullId: string,
- threadId: string,
-): { sessionKey: string; history: ChatMessage[] } {
- const existing = findSessionBySessionId(agentFullId, threadId);
- const sessionKey =
- existing?.sessionKey ?? buildPendingSessionKey(agentFullId, threadId);
- const history = existing
- ? loadSessionHistory(agentFullId, existing.sessionId)
- : [];
- return { sessionKey, history };
-}
-