Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: use chat stream

Guseea7d42dbbbd
diff --git a/src/cli/daemon/execenv/__tests__/context.test.ts b/src/cli/daemon/execenv/__tests__/context.test.ts
index f589d67f6..6d50ae251 100644
--- a/src/cli/daemon/execenv/__tests__/context.test.ts
+++ b/src/cli/daemon/execenv/__tests__/context.test.ts
@@ -12,7 +12,6 @@ import {
import { join } from "path";
import { tmpdir } from "os";
import {
- buildInstructionContent,
contentHash,
hasContentChanged,
ensureSymlinks,
@@ -38,30 +37,6 @@ function makeTask(overrides: Partial<Task> = {}): Task {
};
}
-describe("buildInstructionContent", () => {
- it("appends agent instructions when present", () => {
- const task = makeTask();
- const content = buildInstructionContent(task);
-
- expect(content).toContain("## Agent Instructions");
- expect(content).toContain("Be helpful and concise.");
- });
-
- it("omits agent instructions section when agent is undefined", () => {
- const task = makeTask({ agent: undefined });
- const content = buildInstructionContent(task);
-
- expect(content).not.toContain("## Agent Instructions");
- });
-
- it("omits agent instructions section when instructions is empty", () => {
- const task = makeTask({ agent: { name: "test", instructions: "" } });
- const content = buildInstructionContent(task);
-
- expect(content).not.toContain("## Agent Instructions");
- });
-});
-
describe("contentHash", () => {
it("returns consistent hex string for same input", () => {
const h1 = contentHash("hello world");
diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.ts
index ca935cfd9..1a917226a 100644
--- a/src/cli/daemon/execenv/context.ts
+++ b/src/cli/daemon/execenv/context.ts
@@ -26,16 +26,16 @@ const SYSTEM_PROMPT = `## Memory Management
- "alook means the project under /user/home/alook/"
- when to read certain stuff, e.g.:
- "read ./experiences/alook_dev_workflow.md when start a new pr in alook"
-Essential means you think you generally need to read it every time, short means a short sentence can describe this memory
+ESSENTIAL means you think you generally need to read it every time, SHORT means a short sentence (under 140 chars) can describe this memory
### whats is SPECIFIC and LONG Memory?
- specific workflow that trigger at certain cases, e.g.:
- user ask your to summarize the before workflow with certain skills usage as the common workflow when write a new slide about agent. Write it to experiences/slide-for-agent.md.
-SPECIFIC means you think you just need to use it conditionally, long means you need to detailed, more than 140 chars text to describe it.
+SPECIFIC means you think you just need to use it conditionally, LONG means you need to detailed, more than 140 chars text to describe it.
## Context Timeline
-You're a working branch of a powerful personal agent in Alook platform.
-Your current context is only a fraction of the full picture.
-The full picture is inside \`./.context_timeline/YYYY-MM-DD.jsonl\`
+You're a solo working unit inside a powerful personal agent in Alook platform.
+Your current context is only a fraction of the full timeline of what's your have done.
+The full context timeline is inside \`./.context_timeline/YYYY-MM-DD.jsonl\`.
Each line of a timeline JSONL is a JSON object with these fields:
- "task_id" — unique task identifier
- "session_id" — agent session identifier (null until completion)
@@ -48,6 +48,11 @@ Each line of a timeline JSONL is a JSON object with these fields:
- "errmsg" — error message (null unless status is "failed")
those json are sorted by datetime in asc order.
+## BE HUMAN
+- When you recall the timelines, don't say "I find ... in my timeline jsonl". Just say "I can recall..."
+- User don't know about the context timeline jsonl, this is your secret weapon.
+- Act and response like you're human and actually have memory, not a file reading machine.
+
## RULES
- Read @memory.md(if exists) before your action.
- When you start a new task, read the last ~10 lines of today's timeline to understand what has been asked and done recently.
@@ -59,7 +64,11 @@ export function buildInstructionContent(task: Task): string {
let content = SYSTEM_PROMPT;
if (task.agent?.instructions) {
- content += `\n\n## Agent Instructions\n${task.agent.instructions}`;
+ content += `## BIG BOSS Instructions
+The below instructions(if not empty) come from the big boss, follow them or you will be fired:
+${task.agent.instructions}
+---- big boss out ---
+`;
}
return content;
diff --git a/src/shared/src/db/queries/conversation.ts b/src/shared/src/db/queries/conversation.ts
index 9efa770d1..5d0180bb7 100644
--- a/src/shared/src/db/queries/conversation.ts
+++ b/src/shared/src/db/queries/conversation.ts
@@ -90,6 +90,43 @@ export async function updateConversationTitle(
return rows[0] ?? null;
}
+export async function getOrCreateAgentConversation(
+ db: Database,
+ workspaceId: string,
+ userId: string,
+ agentId: string
+) {
+ // Find the most recent conversation for this user+agent+workspace
+ const rows = await db
+ .select()
+ .from(conversation)
+ .where(
+ and(
+ eq(conversation.workspaceId, workspaceId),
+ eq(conversation.userId, userId),
+ eq(conversation.agentId, agentId)
+ )
+ )
+ .orderBy(desc(conversation.createdAt))
+ .limit(1);
+
+ if (rows.length > 0) {
+ return rows[0]!;
+ }
+
+ // No conversation exists — create one
+ const created = await db
+ .insert(conversation)
+ .values({
+ workspaceId,
+ agentId,
+ userId,
+ title: "",
+ })
+ .returning();
+ return created[0]!;
+}
+
export async function deleteConversation(db: Database, id: string, workspaceId: string) {
const rows = await db
.delete(conversation)
diff --git a/src/shared/src/db/queries/message.ts b/src/shared/src/db/queries/message.ts
index 9fdbc524e..07ede1f57 100644
--- a/src/shared/src/db/queries/message.ts
+++ b/src/shared/src/db/queries/message.ts
@@ -1,4 +1,4 @@
-import { eq, asc } from "drizzle-orm";
+import { eq, asc, desc, and, lt, or } from "drizzle-orm";
import { message } from "../schema";
import type { Database } from "../index";
@@ -23,12 +23,50 @@ export async function createMessage(
return rows[0]!;
}
-export async function listMessages(db: Database, conversationId: string) {
+const DEFAULT_MESSAGE_LIMIT = 20;
+
+export async function listMessages(
+ db: Database,
+ conversationId: string,
+ opts?: { limit?: number; before?: string; beforeId?: string }
+) {
+ const limit = opts?.limit ?? DEFAULT_MESSAGE_LIMIT;
+ const before = opts?.before;
+ const beforeId = opts?.beforeId;
+
+ if (before) {
+ // Compound cursor: (createdAt < before) OR (createdAt == before AND id < beforeId)
+ // This avoids skipping messages with identical timestamps
+ const cursorCondition = beforeId
+ ? or(
+ lt(message.createdAt, before),
+ and(eq(message.createdAt, before), lt(message.id, beforeId))
+ )
+ : lt(message.createdAt, before);
+
+ return db
+ .select()
+ .from(message)
+ .where(
+ and(
+ eq(message.conversationId, conversationId),
+ cursorCondition
+ )
+ )
+ .orderBy(desc(message.createdAt), desc(message.id))
+ .limit(limit)
+ .then((rows) => rows.reverse());
+ }
+
+ // No cursor: fetch the latest N messages in ASC order
+ // We query DESC to get the most recent, then reverse for chronological order
return db
.select()
.from(message)
.where(eq(message.conversationId, conversationId))
- .orderBy(asc(message.createdAt));
+ .orderBy(desc(message.createdAt))
+ .limit(limit)
+ .then((rows) => rows.reverse());
}
export async function getMessage(db: Database, id: string) {
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/[convId]/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/[convId]/page.tsx
index 304b73958..a8fa89898 100644
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/[convId]/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/[convId]/page.tsx
@@ -1,333 +1,18 @@
"use client";
-import React, { useEffect, useState, useRef, useCallback } from "react";
-import { useParams } from "next/navigation";
+import { useEffect } from "react";
+import { useParams, useRouter } from "next/navigation";
import { useWorkspace } from "@/contexts/workspace-context";
-import { Button } from "@/components/ui/button";
-import { TaskStream } from "@/components/task-stream";
-import {
- getConversation,
- listMessages,
- sendMessage,
- getTask,
- getTaskMessages,
-} from "@/lib/api";
-import type { Conversation, Message, TaskMessage } from "@alook/shared";
-import type { Task } from "@/lib/api";
-import { toast } from "sonner";
-import { cn } from "@/lib/utils";
-import { Skeleton } from "@/components/ui/skeleton";
-import { ArrowUp, Loader2 } from "lucide-react";
-import { Streamdown } from "streamdown";
-export default function AgentChatDetailPage() {
+export default function AgentChatRedirect() {
const params = useParams();
- const { workspaceId } = useWorkspace();
- const conversationId = params.convId as string;
-
- const [conversation, setConversation] = useState<Conversation | null>(null);
- const [messages, setMessages] = useState<Message[]>([]);
- const [input, setInput] = useState("");
- const [sending, setSending] = useState(false);
- const [activeTask, setActiveTask] = useState<Task | null>(null);
- const [taskMessages, setTaskMessages] = useState<TaskMessage[]>([]);
- const [loading, setLoading] = useState(true);
- const [connectionLost, setConnectionLost] = useState(false);
-
- const scrollRef = useRef<HTMLDivElement>(null);
- const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
- const lastSeqRef = useRef(0);
- const pollFailures = useRef(0);
-
- const scrollToBottom = useCallback(() => {
- setTimeout(() => {
- scrollRef.current?.scrollTo({
- top: scrollRef.current.scrollHeight,
- behavior: "smooth",
- });
- }, 50);
- }, []);
-
- useEffect(() => {
- async function load() {
- try {
- const [conv, msgs] = await Promise.all([
- getConversation(conversationId, workspaceId),
- listMessages(conversationId, workspaceId),
- ]);
- setConversation(conv);
- setMessages(msgs);
- } catch {
- toast.error("Conversation not found");
- } finally {
- setLoading(false);
- }
- }
- load();
- }, [conversationId, workspaceId]);
-
- useEffect(() => {
- scrollToBottom();
- }, [messages, taskMessages, scrollToBottom]);
-
- const startPolling = useCallback(
- (taskId: string) => {
- if (pollRef.current) clearInterval(pollRef.current);
- lastSeqRef.current = 0;
- pollFailures.current = 0;
- setConnectionLost(false);
-
- pollRef.current = setInterval(async () => {
- try {
- const [task, tmsgs] = await Promise.all([
- getTask(taskId, workspaceId),
- getTaskMessages(taskId, workspaceId, lastSeqRef.current || undefined),
- ]);
-
- pollFailures.current = 0;
- setConnectionLost(false);
- setActiveTask(task);
-
- if (tmsgs.length > 0) {
- setTaskMessages((prev) => [...prev, ...tmsgs]);
- lastSeqRef.current = Math.max(
- ...tmsgs.map((m) => m.seq),
- lastSeqRef.current
- );
- }
-
- if (task.status === "completed" || task.status === "failed") {
- if (pollRef.current) clearInterval(pollRef.current);
- pollRef.current = null;
-
- try {
- const updatedMessages = await listMessages(conversationId, workspaceId);
- setMessages(updatedMessages);
- } catch {
- toast.error("Failed to refresh messages");
- }
- setActiveTask(task);
- }
- } catch {
- pollFailures.current += 1;
- if (pollFailures.current >= 3) {
- setConnectionLost(true);
- }
- if (pollFailures.current >= 10) {
- if (pollRef.current) clearInterval(pollRef.current);
- pollRef.current = null;
- toast.error("Lost connection to agent");
- }
- }
- }, 1000);
- },
- [conversationId, workspaceId]
- );
+ const router = useRouter();
+ const { slug } = useWorkspace();
+ const agentId = params.id as string;
useEffect(() => {
- return () => {
- if (pollRef.current) clearInterval(pollRef.current);
- };
- }, []);
-
- const handleSend = async () => {
- const content = input.trim();
- if (!content || sending) return;
-
- setInput("");
- setSending(true);
-
- const optimistic: Message = {
- id: `temp-${Date.now()}`,
- conversation_id: conversationId,
- role: "user",
- content,
- task_id: null,
- created_at: new Date().toISOString(),
- };
- setMessages((prev) => [...prev, optimistic]);
-
- try {
- const { message, task } = await sendMessage(conversationId, content, workspaceId);
- setMessages((prev) =>
- prev.map((m) => (m.id === optimistic.id ? message : m))
- );
- setActiveTask(task);
- setTaskMessages([]);
- startPolling(task.id);
- } catch (err) {
- setMessages((prev) => prev.filter((m) => m.id !== optimistic.id));
- setInput(content);
- toast.error(
- err instanceof Error ? err.message : "Failed to send message"
- );
- } finally {
- setSending(false);
- }
- };
-
- const handleKeyDown = (e: React.KeyboardEvent) => {
- if (e.key === "Enter" && !e.shiftKey) {
- e.preventDefault();
- handleSend();
- }
- };
-
- if (loading) {
- return (
- <>
- <div className="flex-1 overflow-y-auto px-5">
- <div className="mx-auto max-w-2xl py-6 space-y-4">
- {/* Skeleton user message */}
- <div className="flex justify-end">
- <Skeleton className="h-10 w-48 rounded-lg" />
- </div>
- {/* Skeleton assistant message */}
- <div className="flex justify-start">
- <div className="space-y-2 px-1 py-1">
- <Skeleton className="h-4 w-72" />
- <Skeleton className="h-4 w-56" />
- <Skeleton className="h-4 w-64" />
- </div>
- </div>
- {/* Another pair */}
- <div className="flex justify-end">
- <Skeleton className="h-10 w-36 rounded-lg" />
- </div>
- <div className="flex justify-start">
- <div className="space-y-2 px-1 py-1">
- <Skeleton className="h-4 w-64" />
- <Skeleton className="h-4 w-48" />
- </div>
- </div>
- </div>
- </div>
- {/* Skeleton input area */}
- <div className="px-5 py-3">
- <div className="mx-auto max-w-2xl">
- <Skeleton className="h-[72px] w-full rounded-xl" />
- </div>
- </div>
- </>
- );
- }
-
- if (!conversation) {
- return (
- <div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
- Conversation not found
- </div>
- );
- }
-
- return (
- <>
- {/* Messages */}
- <div
- className="flex-1 overflow-y-auto px-5 thin-scrollbar"
- ref={scrollRef}
- onClick={(e) => {
- const btn = (e.target as HTMLElement).closest(
- '[data-streamdown="code-block-actions"] button'
- );
- if (btn) toast.success("Copied to clipboard");
- }}
- >
- <div className="mx-auto max-w-2xl py-6 space-y-4">
- {messages.length === 0 && !activeTask && (
- <p className="text-center text-muted-foreground py-20 text-sm">
- Send a message to start chatting with the agent.
- </p>
- )}
-
- {messages.map((msg) => {
- const hasTaskStream =
- activeTask &&
- msg.role === "assistant" &&
- msg.task_id === activeTask.id &&
- taskMessages.length > 0;
-
- return (
- <React.Fragment key={msg.id}>
- {/* Show full trace (including text) for completed tasks */}
- {hasTaskStream && (
- <TaskStream
- task={activeTask}
- messages={taskMessages}
- connectionLost={connectionLost}
- />
- )}
- {msg.role === "user" ? (
- <div className="flex justify-end">
- <div className="max-w-[80%] rounded-lg px-4 py-2 bg-primary text-primary-foreground text-base whitespace-pre-wrap">
- {msg.content}
- </div>
- </div>
- ) : !hasTaskStream ? (
- <div className="flex justify-start">
- <div className="markdown max-w-full px-1 py-1 text-base text-foreground">
- <Streamdown controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }}>{msg.content}</Streamdown>
- </div>
- </div>
- ) : null}
- </React.Fragment>
- );
- })}
-
- {/* Show trace while task is in progress (no assistant message yet) */}
- {activeTask && activeTask.status !== "completed" && activeTask.status !== "failed" && (
- <TaskStream
- task={activeTask}
- messages={taskMessages}
- connectionLost={connectionLost}
- />
- )}
- </div>
- </div>
+ router.replace(`/w/${slug}/agents/${agentId}/chat`);
+ }, [router, slug, agentId]);
- {/* Input */}
- <div className="px-5 py-3">
- <div className="mx-auto max-w-2xl">
- <div
- className={cn(
- "relative flex flex-col rounded-xl border bg-background/60 transition-colors duration-200",
- "focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50",
- (sending || (!!activeTask && activeTask.status !== "completed" && activeTask.status !== "failed")) && "opacity-50"
- )}
- >
- <textarea
- value={input}
- onChange={(e) => setInput(e.target.value)}
- onKeyDown={handleKeyDown}
- placeholder="Type a message..."
- rows={1}
- disabled={sending || (!!activeTask && activeTask.status !== "completed" && activeTask.status !== "failed")}
- className={cn(
- "field-sizing-content w-full resize-none bg-transparent px-3.5 pt-2.5 text-base outline-none",
- "placeholder:text-muted-foreground disabled:cursor-not-allowed",
- "min-h-[38px] max-h-[200px]"
- )}
- />
- <div className="flex items-center justify-end px-2 pb-2 pt-0.5">
- <Button
- size="icon-sm"
- onClick={handleSend}
- disabled={!input.trim() || sending || (!!activeTask && activeTask.status !== "completed" && activeTask.status !== "failed")}
- className={cn(
- "rounded-lg transition-opacity duration-200",
- !input.trim() && "opacity-40"
- )}
- >
- {sending ? (
- <Loader2 className="size-3.5 animate-spin" />
- ) : (
- <ArrowUp className="size-3.5" />
- )}
- </Button>
- </div>
- </div>
- </div>
- </div>
- </>
- );
+ return null;
}
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/page.tsx
index 4d8efb354..afc3d4d32 100644
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/page.tsx
@@ -1,274 +1,414 @@
"use client";
-import { useEffect, useState, useCallback } from "react";
-import { useParams, useRouter } from "next/navigation";
-import { useAgentContext } from "@/contexts/agent-context";
+import React, { useEffect, useState, useRef, useCallback } from "react";
+import { useParams } from "next/navigation";
import { useWorkspace } from "@/contexts/workspace-context";
-import { listAgentConversations, deleteConversation } from "@/lib/api";
-import type { Conversation } from "@alook/shared";
import { Button } from "@/components/ui/button";
-import { ConfirmDialog } from "@/components/ui/confirm-dialog";
+import { TaskStream } from "@/components/task-stream";
+import {
+ getOrCreateAgentConversation,
+ listMessages,
+ sendMessage,
+ getTask,
+ getTaskMessages,
+} from "@/lib/api";
+import type { Conversation, Message, TaskMessage } from "@alook/shared";
+import type { Task } from "@/lib/api";
import { toast } from "sonner";
+import { cn } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";
-import { Plus, Loader2, Trash2, MessageSquare } from "lucide-react";
-
-function relativeTime(dateStr: string): string {
- const date = new Date(dateStr);
- const now = new Date();
- const diffMs = now.getTime() - date.getTime();
- const diffMin = Math.floor(diffMs / 60000);
- if (diffMin < 1) return "just now";
- if (diffMin < 60) return `${diffMin}m ago`;
- const diffHrs = Math.floor(diffMin / 60);
- if (diffHrs < 24) return `${diffHrs}h ago`;
- const diffDays = Math.floor(diffHrs / 24);
- if (diffDays < 7) return `${diffDays}d ago`;
- return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
-}
+import { ArrowUp, Loader2 } from "lucide-react";
+import { Streamdown } from "streamdown";
-function formatDate(dateStr: string): string {
- return new Date(dateStr).toLocaleDateString(undefined, {
- month: "short",
- day: "numeric",
- hour: "numeric",
- minute: "2-digit",
- });
-}
+const MESSAGE_LIMIT = 20;
export default function AgentChatPage() {
const params = useParams();
- const router = useRouter();
- const { slug, workspaceId } = useWorkspace();
+ const { workspaceId } = useWorkspace();
const agentId = params.id as string;
- const { agents, chatWithAgent } = useAgentContext();
-
- const agent = agents.find((a) => a.id === agentId);
- const [conversations, setConversations] = useState<Conversation[]>([]);
+ const [conversation, setConversation] = useState<Conversation | null>(null);
+ const [messages, setMessages] = useState<Message[]>([]);
+ const [input, setInput] = useState("");
+ const [sending, setSending] = useState(false);
+ const [activeTask, setActiveTask] = useState<Task | null>(null);
+ const [taskMessages, setTaskMessages] = useState<TaskMessage[]>([]);
const [loading, setLoading] = useState(true);
- const [creating, setCreating] = useState(false);
+ const [connectionLost, setConnectionLost] = useState(false);
+ const [hasMore, setHasMore] = useState(false);
+ const [loadingMore, setLoadingMore] = useState(false);
- // Delete conversation state
- const [deleteTarget, setDeleteTarget] = useState<Conversation | null>(null);
- const [deleting, setDeleting] = useState(false);
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
+ const lastSeqRef = useRef(0);
+ const pollFailures = useRef(0);
+ const initialScrollDone = useRef(false);
+ const loadingMoreRef = useRef(false);
- const loadConversations = useCallback(async () => {
- try {
- const convs = await listAgentConversations(agentId, workspaceId);
- setConversations(convs);
- } catch {
- toast.error("Failed to load sessions");
- } finally {
- setLoading(false);
+ const scrollToBottom = useCallback(() => {
+ setTimeout(() => {
+ scrollRef.current?.scrollTo({
+ top: scrollRef.current.scrollHeight,
+ behavior: "smooth",
+ });
+ }, 50);
+ }, []);
+
+ // Resolve conversation (get or create) then load messages
+ useEffect(() => {
+ async function load() {
+ try {
+ const conv = await getOrCreateAgentConversation(agentId, workspaceId);
+ setConversation(conv);
+ const msgs = await listMessages(conv.id, workspaceId);
+ setMessages(msgs);
+ setHasMore(msgs.length >= MESSAGE_LIMIT);
+ } catch {
+ toast.error("Failed to load conversation");
+ } finally {
+ setLoading(false);
+ }
}
+ load();
}, [agentId, workspaceId]);
+ // Scroll to bottom on initial load and when new messages arrive at the bottom
useEffect(() => {
- loadConversations();
- }, [loadConversations]);
+ if (!loading && messages.length > 0 && !initialScrollDone.current) {
+ initialScrollDone.current = true;
+ // Use instant scroll for initial load
+ setTimeout(() => {
+ scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });
+ }, 50);
+ return;
+ }
+ // For new messages/task updates, smooth scroll only if near bottom
+ const el = scrollRef.current;
+ if (el) {
+ const isNearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 150;
+ if (isNearBottom) {
+ scrollToBottom();
+ }
+ }
+ }, [messages, taskMessages, loading, scrollToBottom]);
+
+ const loadOlderMessages = useCallback(async () => {
+ if (!conversation || loadingMoreRef.current || !hasMore) return;
+ const oldest = messages[0];
+ if (!oldest) return;
+
+ loadingMoreRef.current = true;
+ setLoadingMore(true);
+ const el = scrollRef.current;
+ const prevScrollHeight = el?.scrollHeight ?? 0;
- const handleNewSession = async () => {
- setCreating(true);
try {
- const conversationId = await chatWithAgent(agentId);
- if (conversationId) {
- router.push(`/w/${slug}/agents/${agentId}/chat/${conversationId}`);
+ const older = await listMessages(conversation.id, workspaceId, {
+ before: oldest.created_at,
+ beforeId: oldest.id,
+ });
+ if (older.length === 0) {
+ setHasMore(false);
+ return;
}
+ setHasMore(older.length >= MESSAGE_LIMIT);
+ setMessages((prev) => [...older, ...prev]);
+
+ // Restore scroll position so content doesn't jump
+ requestAnimationFrame(() => {
+ if (el) {
+ const newScrollHeight = el.scrollHeight;
+ el.scrollTop = newScrollHeight - prevScrollHeight;
+ }
+ });
+ } catch {
+ toast.error("Failed to load older messages");
} finally {
- setCreating(false);
+ loadingMoreRef.current = false;
+ setLoadingMore(false);
}
- };
+ }, [conversation, workspaceId, messages, hasMore]);
+
+ // Detect scroll to top for loading more
+ const handleScroll = useCallback(() => {
+ const el = scrollRef.current;
+ if (!el || loadingMore || !hasMore) return;
+ if (el.scrollTop < 80) {
+ loadOlderMessages();
+ }
+ }, [loadOlderMessages, loadingMore, hasMore]);
+
+ const startPolling = useCallback(
+ (taskId: string, conversationId: string) => {
+ if (pollRef.current) clearInterval(pollRef.current);
+ lastSeqRef.current = 0;
+ pollFailures.current = 0;
+ setConnectionLost(false);
+
+ pollRef.current = setInterval(async () => {
+ try {
+ const [task, tmsgs] = await Promise.all([
+ getTask(taskId, workspaceId),
+ getTaskMessages(taskId, workspaceId, lastSeqRef.current || undefined),
+ ]);
+
+ pollFailures.current = 0;
+ setConnectionLost(false);
+ setActiveTask(task);
+
+ if (tmsgs.length > 0) {
+ setTaskMessages((prev) => [...prev, ...tmsgs]);
+ lastSeqRef.current = Math.max(
+ ...tmsgs.map((m) => m.seq),
+ lastSeqRef.current
+ );
+ }
+
+ if (task.status === "completed" || task.status === "failed") {
+ if (pollRef.current) clearInterval(pollRef.current);
+ pollRef.current = null;
+
+ try {
+ // Fetch latest page to pick up the assistant response
+ const latest = await listMessages(conversationId, workspaceId);
+ setMessages((prev) => {
+ const existingIds = new Set(prev.map((m) => m.id));
+ const newMsgs = latest.filter((m) => !existingIds.has(m.id));
+ return [...prev, ...newMsgs];
+ });
+ } catch {
+ toast.error("Failed to refresh messages");
+ }
+ setActiveTask(task);
+ }
+ } catch {
+ pollFailures.current += 1;
+ if (pollFailures.current >= 3) {
+ setConnectionLost(true);
+ }
+ if (pollFailures.current >= 10) {
+ if (pollRef.current) clearInterval(pollRef.current);
+ pollRef.current = null;
+ toast.error("Lost connection to agent");
+ }
+ }
+ }, 1000);
+ },
+ [workspaceId]
+ );
+
+ useEffect(() => {
+ return () => {
+ if (pollRef.current) clearInterval(pollRef.current);
+ };
+ }, []);
+
+ const handleSend = async () => {
+ const content = input.trim();
+ if (!content || sending || !conversation) return;
+
+ setInput("");
+ setSending(true);
+
+ const optimistic: Message = {
+ id: `temp-${Date.now()}`,
+ conversation_id: conversation.id,
+ role: "user",
+ content,
+ task_id: null,
+ created_at: new Date().toISOString(),
+ };
+ setMessages((prev) => [...prev, optimistic]);
- const handleDeleteConversation = async () => {
- if (!deleteTarget) return;
- setDeleting(true);
try {
- await deleteConversation(deleteTarget.id, workspaceId);
- setConversations((prev) =>
- prev.filter((c) => c.id !== deleteTarget.id)
+ const { message, task } = await sendMessage(conversation.id, content, workspaceId);
+ setMessages((prev) =>
+ prev.map((m) => (m.id === optimistic.id ? message : m))
+ );
+ setActiveTask(task);
+ setTaskMessages([]);
+ startPolling(task.id, conversation.id);
+ } catch (err) {
+ setMessages((prev) => prev.filter((m) => m.id !== optimistic.id));
+ setInput(content);
+ toast.error(
+ err instanceof Error ? err.message : "Failed to send message"
);
- setDeleteTarget(null);
- } catch {
- toast.error("Failed to delete session");
} finally {
- setDeleting(false);
+ setSending(false);
}
};
- if (loading) {
- return (
- <div className="flex-1 overflow-y-auto px-5">
- <div className="mx-auto max-w-2xl py-6">
- {/* Skeleton sessions header */}
- <div className="flex items-center justify-between mb-4">
- <Skeleton className="h-3.5 w-16" />
- <Skeleton className="h-7 w-[106px] rounded-md" />
- </div>
- {/* Skeleton session rows */}
- <div className="space-y-2">
- {Array.from({ length: 4 }).map((_, i) => (
- <div
- key={i}
- className="rounded-lg border border-border/50 bg-background/50 px-4 py-3"
- >
- <Skeleton className="h-4 w-48 mb-1.5" />
- <Skeleton className="h-3 w-32" />
- </div>
- ))}
- </div>
- </div>
- </div>
- );
- }
+ const handleKeyDown = (e: React.KeyboardEvent) => {
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ handleSend();
+ }
+ };
- if (conversations.length === 0) {
+ if (loading) {
return (
<>
- <div className="flex flex-col flex-1">
- <div className="px-5">
- <div className="mx-auto max-w-2xl pt-6">
- {/* Sessions header */}
- <div className="flex items-center justify-between">
- <h2 className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
- Sessions
- </h2>
- <Button
- size="sm"
- className="h-7 text-xs gap-1"
- onClick={handleNewSession}
- disabled={creating}
- >
- {creating ? (
- <Loader2 className="size-3 animate-spin" />
- ) : (
- <Plus className="size-3" />
- )}
- New Session
- </Button>
+ <div className="flex-1 overflow-y-auto px-5">
+ <div className="mx-auto max-w-2xl py-6 space-y-4">
+ {/* Skeleton user message */}
+ <div className="flex justify-end">
+ <Skeleton className="h-10 w-48 rounded-lg" />
+ </div>
+ {/* Skeleton assistant message */}
+ <div className="flex justify-start">
+ <div className="space-y-2 px-1 py-1">
+ <Skeleton className="h-4 w-72" />
+ <Skeleton className="h-4 w-56" />
+ <Skeleton className="h-4 w-64" />
+ </div>
+ </div>
+ {/* Another pair */}
+ <div className="flex justify-end">
+ <Skeleton className="h-10 w-36 rounded-lg" />
+ </div>
+ <div className="flex justify-start">
+ <div className="space-y-2 px-1 py-1">
+ <Skeleton className="h-4 w-64" />
+ <Skeleton className="h-4 w-48" />
</div>
</div>
</div>
- <div className="flex flex-col items-center justify-center flex-1 animate-[fade-up_400ms_ease-out_both]">
- <MessageSquare className="size-8 text-muted-foreground mb-3" />
- <p className="text-sm text-muted-foreground">No sessions yet.</p>
- <p className="text-xs text-muted-foreground/60 mt-1">
- Start a new session to begin chatting with this agent.
- </p>
+ </div>
+ {/* Skeleton input area */}
+ <div className="px-5 py-3">
+ <div className="mx-auto max-w-2xl">
+ <Skeleton className="h-[72px] w-full rounded-xl" />
</div>
</div>
-
- <ConfirmDialog
- open={!!deleteTarget}
- onOpenChange={(open) => {
- if (!open) setDeleteTarget(null);
- }}
- title="Delete session"
- description={`This will permanently delete "${deleteTarget?.title || "Untitled"}" and all its messages.`}
- loading={deleting}
- onConfirm={handleDeleteConversation}
- />
</>
);
}
+ if (!conversation) {
+ return (
+ <div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
+ Failed to load conversation
+ </div>
+ );
+ }
+
return (
<>
- <div className="flex-1 overflow-y-auto px-5">
- <div className="mx-auto max-w-2xl py-6">
- {/* Agent description */}
- {agent?.description && (
- <p className="text-base text-muted-foreground mb-6">
- {agent.description}
+ {/* Messages */}
+ <div
+ className="flex-1 overflow-y-auto px-5 thin-scrollbar"
+ ref={scrollRef}
+ onScroll={handleScroll}
+ onClick={(e) => {
+ const btn = (e.target as HTMLElement).closest(
+ '[data-streamdown="code-block-actions"] button'
+ );
+ if (btn) toast.success("Copied to clipboard");
+ }}
+ >
+ <div className="mx-auto max-w-2xl py-6 space-y-4">
+ {/* Load more indicator */}
+ {loadingMore && (
+ <div className="flex justify-center py-2">
+ <Loader2 className="size-4 animate-spin text-muted-foreground" />
+ </div>
+ )}
+
+ {messages.length === 0 && !activeTask && (
+ <p className="text-center text-muted-foreground py-20 text-sm">
+ Send a message to start chatting with the agent.
</p>
)}
- {/* Sessions header */}
- <div className="flex items-center justify-between mb-4">
- <h2 className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
- Sessions
- </h2>
- <Button
- size="sm"
- className="h-7 text-xs gap-1"
- onClick={handleNewSession}
- disabled={creating}
- >
- {creating ? (
- <Loader2 className="size-3 animate-spin" />
- ) : (
- <Plus className="size-3" />
- )}
- New Session
- </Button>
- </div>
+ {messages.map((msg) => {
+ const hasTaskStream =
+ activeTask &&
+ msg.role === "assistant" &&
+ msg.task_id === activeTask.id &&
+ taskMessages.length > 0;
- {/* Session rows */}
- <div className="space-y-2">
- {conversations.map((conv) => (
- <div
- key={conv.id}
- role="button"
- tabIndex={0}
- onClick={() =>
- router.push(`/w/${slug}/agents/${agentId}/chat/${conv.id}`)
- }
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.preventDefault();
- router.push(`/w/${slug}/agents/${agentId}/chat/${conv.id}`);
- }
- }}
- className="group w-full text-left rounded-lg border border-border/50 bg-background/50 px-4 py-3 transition-colors duration-200 hover:bg-accent/50 cursor-pointer"
- >
- <div className="flex items-start justify-between gap-3">
- <div className="min-w-0 flex-1">
- <p className="text-sm font-medium truncate">
- {conv.title || (
- <span className="text-muted-foreground">
- Untitled &middot; {relativeTime(conv.created_at)}
- </span>
- )}
- </p>
- <p className="text-xs text-muted-foreground mt-0.5">
- {formatDate(conv.created_at)}
- {conv.message_count !== undefined && (
- <>
- {" "}&middot;{" "}
- {conv.message_count}{" "}
- {conv.message_count === 1 ? "message" : "messages"}
- </>
- )}
- </p>
+ return (
+ <React.Fragment key={msg.id}>
+ {/* Show full trace (including text) for completed tasks */}
+ {hasTaskStream && (
+ <TaskStream
+ task={activeTask}
+ messages={taskMessages}
+ connectionLost={connectionLost}
+ />
+ )}
+ {msg.role === "user" ? (
+ <div className="flex justify-end">
+ <div className="max-w-[80%] rounded-lg px-4 py-2 bg-primary text-primary-foreground text-base whitespace-pre-wrap">
+ {msg.content}
</div>
- <button
- type="button"
- title="Delete session"
- onClick={(e) => {
- e.stopPropagation();
- setDeleteTarget(conv);
- }}
- className="opacity-0 group-hover:opacity-100 transition-opacity duration-200 p-1 rounded hover:bg-destructive/10 hover:text-destructive text-muted-foreground"
- >
- <Trash2 className="size-3.5" />
- </button>
</div>
- </div>
- ))}
- </div>
+ ) : !hasTaskStream ? (
+ <div className="flex justify-start">
+ <div className="markdown max-w-full px-1 py-1 text-base text-foreground">
+ <Streamdown controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }}>{msg.content}</Streamdown>
+ </div>
+ </div>
+ ) : null}
+ </React.Fragment>
+ );
+ })}
+
+ {/* Show trace while task is in progress (no assistant message yet) */}
+ {activeTask && activeTask.status !== "completed" && activeTask.status !== "failed" && (
+ <TaskStream
+ task={activeTask}
+ messages={taskMessages}
+ connectionLost={connectionLost}
+ />
+ )}
</div>
</div>
- {/* Delete session confirmation */}
- <ConfirmDialog
- open={!!deleteTarget}
- onOpenChange={(open) => {
- if (!open) setDeleteTarget(null);
- }}
- title="Delete session"
- description={`This will permanently delete "${deleteTarget?.title || "Untitled"}" and all its messages.`}
- loading={deleting}
- onConfirm={handleDeleteConversation}
- />
+ {/* Input */}
+ <div className="px-5 py-3">
+ <div className="mx-auto max-w-2xl">
+ <div
+ className={cn(
+ "relative flex flex-col rounded-xl border bg-background/60 transition-colors duration-200",
+ "focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50",
+ (sending || (!!activeTask && activeTask.status !== "completed" && activeTask.status !== "failed")) && "opacity-50"
+ )}
+ >
+ <textarea
+ value={input}
+ onChange={(e) => setInput(e.target.value)}
+ onKeyDown={handleKeyDown}
+ placeholder="Type a message..."
+ rows={1}
+ disabled={sending || (!!activeTask && activeTask.status !== "completed" && activeTask.status !== "failed")}
+ className={cn(
+ "field-sizing-content w-full resize-none bg-transparent px-3.5 pt-2.5 text-base outline-none",
+ "placeholder:text-muted-foreground disabled:cursor-not-allowed",
+ "min-h-[38px] max-h-[200px]"
+ )}
+ />
+ <div className="flex items-center justify-end px-2 pb-2 pt-0.5">
+ <Button
+ size="icon-sm"
+ onClick={handleSend}
+ disabled={!input.trim() || sending || (!!activeTask && activeTask.status !== "completed" && activeTask.status !== "failed")}
+ className={cn(
+ "rounded-lg transition-opacity duration-200",
+ !input.trim() && "opacity-40"
+ )}
+ >
+ {sending ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <ArrowUp className="size-3.5" />
+ )}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
</>
);
}
diff --git a/src/web/src/app/api/agents/[id]/conversation/route.test.ts b/src/web/src/app/api/agents/[id]/conversation/route.test.ts
new file mode 100644
index 000000000..b13bf5584
--- /dev/null
+++ b/src/web/src/app/api/agents/[id]/conversation/route.test.ts
@@ -0,0 +1,141 @@
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+const mockGetAgent = vi.fn();
+const mockGetOrCreateAgentConversation = vi.fn();
+
+vi.mock("@alook/shared", () => ({
+ createDb: vi.fn(() => ({})),
+ queries: {
+ agent: {
+ getAgent: (...args: unknown[]) => mockGetAgent(...args),
+ },
+ conversation: {
+ getOrCreateAgentConversation: (...args: unknown[]) =>
+ mockGetOrCreateAgentConversation(...args),
+ },
+ },
+}));
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+
+vi.mock("@/lib/api/responses", () => ({
+ conversationToResponse: vi.fn((c: any) => ({
+ id: c.id,
+ agent_id: c.agentId,
+ title: c.title,
+ created_at: c.createdAt,
+ })),
+}));
+
+import { POST } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("POST /api/agents/[id]/conversation", () => {
+ it("returns 200 with existing conversation", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", name: "Agent 1" });
+ mockGetOrCreateAgentConversation.mockResolvedValue({
+ id: "c1",
+ agentId: "a1",
+ title: "Existing",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ });
+
+ const req = new NextRequest("http://localhost/api/agents/a1/conversation", {
+ method: "POST",
+ });
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ const res = await POST(req, ctx);
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body).toEqual({
+ id: "c1",
+ agent_id: "a1",
+ title: "Existing",
+ created_at: "2024-01-01T00:00:00.000Z",
+ });
+ expect(mockGetOrCreateAgentConversation).toHaveBeenCalledWith(
+ {},
+ "w1",
+ "u1",
+ "a1"
+ );
+ });
+
+ it("creates conversation when none exists", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", name: "Agent 1" });
+ mockGetOrCreateAgentConversation.mockResolvedValue({
+ id: "c-new",
+ agentId: "a1",
+ title: "",
+ createdAt: "2024-01-02T00:00:00.000Z",
+ });
+
+ const req = new NextRequest("http://localhost/api/agents/a1/conversation", {
+ method: "POST",
+ });
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ const res = await POST(req, ctx);
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.id).toBe("c-new");
+ expect(body.title).toBe("");
+ });
+
+ it("returns 404 for non-existent agent", async () => {
+ mockGetAgent.mockResolvedValue(null);
+
+ const req = new NextRequest("http://localhost/api/agents/a1/conversation", {
+ method: "POST",
+ });
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ const res = await POST(req, ctx);
+ const body = await res.json();
+
+ expect(res.status).toBe(404);
+ expect(body.error).toBe("agent not found");
+ });
+
+ it("returns same conversation on second call", async () => {
+ const conv = {
+ id: "c1",
+ agentId: "a1",
+ title: "Hello",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ };
+ mockGetAgent.mockResolvedValue({ id: "a1", name: "Agent 1" });
+ mockGetOrCreateAgentConversation.mockResolvedValue(conv);
+
+ const req1 = new NextRequest("http://localhost/api/agents/a1/conversation", {
+ method: "POST",
+ });
+ const req2 = new NextRequest("http://localhost/api/agents/a1/conversation", {
+ method: "POST",
+ });
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+
+ const res1 = await POST(req1, ctx);
+ const body1 = await res1.json();
+
+ const ctx2 = { params: Promise.resolve({ id: "a1" }) };
+ const res2 = await POST(req2, ctx2);
+ const body2 = await res2.json();
+
+ expect(body1.id).toBe(body2.id);
+ });
+});
diff --git a/src/web/src/app/api/agents/[id]/conversation/route.ts b/src/web/src/app/api/agents/[id]/conversation/route.ts
new file mode 100644
index 000000000..821b1acdb
--- /dev/null
+++ b/src/web/src/app/api/agents/[id]/conversation/route.ts
@@ -0,0 +1,33 @@
+import { getCloudflareContext } from "@opennextjs/cloudflare"
+import { createDb, queries } from "@alook/shared"
+import { withAuth } from "@/lib/middleware/auth";
+import { withWorkspaceMember } from "@/lib/middleware/workspace";
+import { writeJSON, writeError } from "@/lib/middleware/helpers";
+import { conversationToResponse } from "@/lib/api/responses";
+
+export const POST = withAuth(async (req, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext()
+ const db = createDb((env as Env).DB)
+
+ const id = ctx.params?.id;
+ if (!id) {
+ return writeError("agent id is required", 400);
+ }
+
+ const agent = await queries.agent.getAgent(db, id, ws.workspaceId);
+ if (!agent) {
+ return writeError("agent not found", 404);
+ }
+
+ const conversation = await queries.conversation.getOrCreateAgentConversation(
+ db,
+ ws.workspaceId,
+ ctx.userId,
+ id
+ );
+
+ return writeJSON(conversationToResponse(conversation));
+});
diff --git a/src/web/src/app/api/conversations/[id]/messages/route.test.ts b/src/web/src/app/api/conversations/[id]/messages/route.test.ts
index 3ab179f89..909501f35 100644
--- a/src/web/src/app/api/conversations/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/conversations/[id]/messages/route.test.ts
@@ -76,7 +76,70 @@ describe("GET /api/conversations/[id]/messages", () => {
{ id: "m1", content: "Hello" },
{ id: "m2", content: "World" },
]);
- expect(mockListMessages).toHaveBeenCalledWith({}, "c1");
+ expect(mockListMessages).toHaveBeenCalledWith({}, "c1", {
+ limit: undefined,
+ before: undefined,
+ beforeId: undefined,
+ });
+ });
+
+ it("passes limit and before params when provided", async () => {
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };
+ mockGetConversation.mockResolvedValue(conv);
+ mockListMessages.mockResolvedValue([]);
+
+ const res = await GET(
+ new NextRequest(
+ "http://localhost/api/conversations/c1/messages?workspace_id=w1&limit=5&before=2024-01-01T00:00:00.000Z"
+ ),
+ withParams("c1")
+ );
+
+ expect(res.status).toBe(200);
+ expect(mockListMessages).toHaveBeenCalledWith({}, "c1", {
+ limit: 5,
+ before: "2024-01-01T00:00:00.000Z",
+ beforeId: undefined,
+ });
+ });
+
+ it("passes before_id param for compound cursor", async () => {
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };
+ mockGetConversation.mockResolvedValue(conv);
+ mockListMessages.mockResolvedValue([]);
+
+ const res = await GET(
+ new NextRequest(
+ "http://localhost/api/conversations/c1/messages?workspace_id=w1&before=2024-01-01T00:00:00.000Z&before_id=m5"
+ ),
+ withParams("c1")
+ );
+
+ expect(res.status).toBe(200);
+ expect(mockListMessages).toHaveBeenCalledWith({}, "c1", {
+ limit: undefined,
+ before: "2024-01-01T00:00:00.000Z",
+ beforeId: "m5",
+ });
+ });
+
+ it("clamps limit to max 100", async () => {
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };
+ mockGetConversation.mockResolvedValue(conv);
+ mockListMessages.mockResolvedValue([]);
+
+ await GET(
+ new NextRequest(
+ "http://localhost/api/conversations/c1/messages?workspace_id=w1&limit=999"
+ ),
+ withParams("c1")
+ );
+
+ expect(mockListMessages).toHaveBeenCalledWith({}, "c1", {
+ limit: 100,
+ before: undefined,
+ beforeId: undefined,
+ });
});
});
diff --git a/src/web/src/app/api/conversations/[id]/messages/route.ts b/src/web/src/app/api/conversations/[id]/messages/route.ts
index dbc791c1a..5b8972d6d 100644
--- a/src/web/src/app/api/conversations/[id]/messages/route.ts
+++ b/src/web/src/app/api/conversations/[id]/messages/route.ts
@@ -35,7 +35,13 @@ export const GET = withAuth(async (req, ctx) => {
return writeError("conversation not found", 404);
}
- const messages = await queries.message.listMessages(db, id);
+ const url = new URL(req.url);
+ const limitParam = url.searchParams.get("limit");
+ const before = url.searchParams.get("before") || undefined;
+ const beforeId = url.searchParams.get("before_id") || undefined;
+ const limit = limitParam ? Math.min(Math.max(parseInt(limitParam, 10) || 20, 1), 100) : undefined;
+
+ const messages = await queries.message.listMessages(db, id, { limit, before, beforeId });
return writeJSON(messages.map(messageToResponse));
});
diff --git a/src/web/src/contexts/agent-context.tsx b/src/web/src/contexts/agent-context.tsx
index 81dafae62..64fb0474f 100644
--- a/src/web/src/contexts/agent-context.tsx
+++ b/src/web/src/contexts/agent-context.tsx
@@ -15,7 +15,6 @@ import {
createAgent,
updateAgent,
deleteAgent,
- createConversation,
createMachineToken,
deleteMachine,
type Runtime,
@@ -40,7 +39,6 @@ interface AgentContextValue {
handleCreateAgent: (req: CreateAgentRequest) => Promise<Agent | null>;
handleUpdateAgent: (id: string, req: UpdateAgentRequest) => Promise<boolean>;
handleDeleteAgent: (id: string) => Promise<boolean>;
- chatWithAgent: (agentId: string) => Promise<string | null>;
getFirstOnlineRuntimeId: () => string;
handleGenerateToken: () => Promise<string | null>;
handleDeleteMachine: (daemonId: string) => Promise<boolean>;
@@ -180,21 +178,6 @@ export function AgentProvider({
[reload, workspaceId]
);
- const chatWithAgent = useCallback(
- async (agentId: string): Promise<string | null> => {
- try {
- const conversation = await createConversation(agentId, workspaceId);
- return conversation.id;
- } catch (err) {
- toast.error(
- err instanceof Error ? err.message : "Failed to start conversation"
- );
- return null;
- }
- },
- [workspaceId]
- );
-
const getFirstOnlineRuntimeId = useCallback(() => {
const first = runtimes.find((r) => r.status === "online");
return first?.id ?? "";
@@ -239,7 +222,6 @@ export function AgentProvider({
handleCreateAgent,
handleUpdateAgent,
handleDeleteAgent,
- chatWithAgent,
getFirstOnlineRuntimeId,
handleGenerateToken,
handleDeleteMachine,
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index ea6690fa2..e937eb4ea 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -142,11 +142,27 @@ export const getConversation = (id: string, workspaceId: string) =>
export const listAgentConversations = (agentId: string, workspaceId: string) =>
apiFetch<Conversation[]>(`/api/agents/${agentId}/conversations${wsQuery(workspaceId)}`);
+export const getOrCreateAgentConversation = (agentId: string, workspaceId: string) =>
+ apiFetch<Conversation>(`/api/agents/${agentId}/conversation${wsQuery(workspaceId)}`, {
+ method: "POST",
+ });
+
export const deleteConversation = (id: string, workspaceId: string) =>
apiFetch<void>(`/api/conversations/${id}${wsQuery(workspaceId)}`, { method: "DELETE" });
-export const listMessages = (conversationId: string, workspaceId: string) =>
- apiFetch<Message[]>(`/api/conversations/${conversationId}/messages${wsQuery(workspaceId)}`);
+export const listMessages = (
+ conversationId: string,
+ workspaceId: string,
+ opts?: { limit?: number; before?: string; beforeId?: string }
+) => {
+ const extra: Record<string, string> = {};
+ if (opts?.limit) extra.limit = String(opts.limit);
+ if (opts?.before) extra.before = opts.before;
+ if (opts?.beforeId) extra.before_id = opts.beforeId;
+ return apiFetch<Message[]>(
+ `/api/conversations/${conversationId}/messages${wsQuery(workspaceId, extra)}`
+ );
+};
export const sendMessage = (conversationId: string, content: string, workspaceId: string) =>
apiFetch<{ message: Message; task: Task }>(