feat: implement file upload functionality in ChatInterface and enhance sub-agent activity tracking

This commit is contained in:
Xi Zhang
2026-06-02 02:20:09 +01:00
parent 98f6681bb1
commit ee2bcea3a4
6 changed files with 664 additions and 36 deletions
+227
View File
@@ -0,0 +1,227 @@
import { promises as fs } from "fs";
import { homedir } from "os";
import { basename, dirname, join, resolve } from "path";
import { NextRequest, NextResponse } from "next/server";
export const runtime = "nodejs";
const WORKSPACE_SIDECAR = join(
homedir(),
".config",
"evoscientist",
"langgraph_dev.workspace.json"
);
const MAX_FILE_BYTES = 50 * 1024 * 1024;
const MAX_TOTAL_BYTES = 100 * 1024 * 1024;
const MAX_FILES = 20;
interface WorkspaceSidecar {
workspace?: unknown;
pid?: unknown;
}
/** True if the name contains any C0 control char (< 0x20) or DEL (0x7f). A
* newline in a filename would otherwise be spliced into the prompt sent to the
* agent (instruction injection); control chars have no place in a filename. */
function hasControlChar(name: string): boolean {
for (let i = 0; i < name.length; i += 1) {
const code = name.charCodeAt(i);
if (
code < 0x20 || // C0 controls (incl. NUL, tab, newline)
code === 0x7f || // DEL
(code >= 0x80 && code <= 0x9f) || // C1 controls
code === 0x2028 || // line separator
code === 0x2029 // paragraph separator
) {
return true;
}
}
return false;
}
/** True if a process with `pid` is currently running (signal 0 = existence probe). */
function isProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch (error) {
// EPERM means the process exists but we may not signal it — still alive.
return (error as NodeJS.ErrnoException).code === "EPERM";
}
}
/**
* Resolve the workspace of the *currently running* EvoScientist deployment.
*
* The sidecar records `{ workspace, pid }` of the langgraph dev that owns this
* workspace. We only trust it when that pid is still alive — a stale sidecar
* from a crashed/previous session must not silently redirect uploads to a
* directory the live deployment no longer uses. Falls back to the launcher env.
*/
async function getWorkspaceDir() {
let workspace: string | undefined;
try {
const sidecar = JSON.parse(
await fs.readFile(WORKSPACE_SIDECAR, "utf-8")
) as WorkspaceSidecar;
const ws = sidecar.workspace;
const pid = sidecar.pid;
if (typeof ws === "string" && ws.trim()) {
const hasPid = typeof pid === "number" && pid > 0;
// With a recorded backend pid, only trust the sidecar while that process
// is alive; older sidecars without one fall back to trusting it as before.
if (!hasPid || isProcessAlive(pid as number)) workspace = ws;
}
} catch {
// Older/manual setups may not have a sidecar. Fall back to the launcher env.
}
workspace ||= process.env.EVOSCIENTIST_WORKSPACE_DIR;
if (!workspace) {
throw new Error(
"No active EvoScientist workspace found. Start the backend with `EvoSci deploy` first."
);
}
const workspaceDir = resolve(workspace);
const stat = await fs.stat(workspaceDir);
if (!stat.isDirectory()) {
throw new Error("The active EvoScientist workspace is not a directory.");
}
return workspaceDir;
}
function sanitizeFileName(name: string) {
const fileName = basename(name.replaceAll("\\", "/")).trim();
if (
!fileName ||
fileName === "." ||
fileName === ".." ||
hasControlChar(fileName)
) {
throw new Error("Invalid file name.");
}
return fileName;
}
function addSuffix(fileName: string, index: number) {
const dotIndex = fileName.lastIndexOf(".");
const stem = dotIndex > 0 ? fileName.slice(0, dotIndex) : fileName;
const extension = dotIndex > 0 ? fileName.slice(dotIndex) : "";
return `${stem} (${index})${extension}`;
}
async function writeUniqueFile(
workspaceDir: string,
fileName: string,
content: Uint8Array
) {
for (let index = 1; ; index += 1) {
const candidate = index === 1 ? fileName : addSuffix(fileName, index);
const target = resolve(workspaceDir, candidate);
if (dirname(target) !== workspaceDir) {
throw new Error("Invalid file path.");
}
try {
// `wx` never overwrites an existing file (so an upload can't clobber the
// deployment's own files); collisions get a numeric suffix instead.
await fs.writeFile(target, content, { flag: "wx" });
return candidate;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
}
}
}
export async function POST(request: NextRequest) {
try {
const origin = request.headers.get("origin");
if (origin && origin !== request.nextUrl.origin) {
return NextResponse.json(
{ error: "Cross-origin workspace uploads are not allowed." },
{ status: 403 }
);
}
// Reject oversized bodies before buffering the whole multipart payload.
// (Best-effort — Content-Length is advisory; the per-file checks below are
// the real enforcement.)
const declaredLength = Number(request.headers.get("content-length") ?? "");
if (
Number.isFinite(declaredLength) &&
declaredLength > MAX_TOTAL_BYTES + 1024 * 1024
) {
return NextResponse.json(
{ error: "The selected files exceed the 100 MB upload limit." },
{ status: 413 }
);
}
const formData = await request.formData();
const files = formData
.getAll("files")
.filter((value): value is File => typeof value !== "string");
if (files.length === 0) {
return NextResponse.json(
{ error: "Choose at least one file to upload." },
{ status: 400 }
);
}
if (files.length > MAX_FILES) {
return NextResponse.json(
{ error: `Upload at most ${MAX_FILES} files at a time.` },
{ status: 400 }
);
}
let totalBytes = 0;
const validatedFiles = files.map((file) => {
if (file.size > MAX_FILE_BYTES) {
throw new Error(`${file.name} is larger than the 50 MB upload limit.`);
}
totalBytes += file.size;
if (totalBytes > MAX_TOTAL_BYTES) {
throw new Error("The selected files exceed the 100 MB upload limit.");
}
return { file, fileName: sanitizeFileName(file.name) };
});
// Lands in the working directory of the currently running deployment, so the
// agent can read the files via its workspace file tools.
const workspaceDir = await getWorkspaceDir();
const uploadedFiles: { name: string; path: string; size: number }[] = [];
const writtenPaths: string[] = [];
try {
for (const { file, fileName } of validatedFiles) {
const savedName = await writeUniqueFile(
workspaceDir,
fileName,
new Uint8Array(await file.arrayBuffer())
);
writtenPaths.push(resolve(workspaceDir, savedName));
uploadedFiles.push({
name: savedName,
path: `/${savedName}`,
size: file.size,
});
}
} catch (error) {
// Roll back files already written so a partial upload doesn't linger.
// allSettled so a cleanup failure can't mask the original error.
await Promise.allSettled(
writtenPaths.map((p) => fs.rm(p, { force: true }))
);
throw error;
}
return NextResponse.json({ files: uploadedFiles });
} catch (error) {
return NextResponse.json(
{
error:
error instanceof Error ? error.message : "Failed to upload files.",
},
{ status: 400 }
);
}
}
+219 -27
View File
@@ -20,6 +20,8 @@ import {
ShieldCheck,
Sparkles,
TriangleAlert,
Paperclip,
X,
} from "lucide-react";
import { ChatMessage } from "@/app/components/ChatMessage";
import {
@@ -37,6 +39,7 @@ import { extractStringFromMessageContent } from "@/app/utils/utils";
import { useChatContext } from "@/providers/ChatProvider";
import { cn } from "@/lib/utils";
import { formatModel } from "@/lib/model";
import { lastTextOf, type SubAgentStep } from "@/lib/subAgentActivity";
import { useStickToBottom } from "use-stick-to-bottom";
import { FilesPopover } from "@/app/components/TasksFilesSidebar";
import {
@@ -48,6 +51,7 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { useQueryState } from "nuqs";
import { toast } from "sonner";
interface ChatInterfaceProps {
assistant: Assistant | null;
@@ -59,6 +63,12 @@ const SUGGESTED_PROMPTS = [
"Brainstorm research directions",
];
interface UploadedWorkspaceFile {
name: string;
path: string;
size: number;
}
const getStatusIcon = (status: TodoItem["status"], className?: string) => {
switch (status) {
case "completed":
@@ -89,8 +99,11 @@ export const ChatInterface = React.memo<ChatInterfaceProps>(({ assistant }) => {
const [metaOpen, setMetaOpen] = useState<"tasks" | "files" | null>(null);
const tasksContainerRef = useRef<HTMLDivElement | null>(null);
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
const uploadInputRef = useRef<HTMLInputElement | null>(null);
const [input, setInput] = useState("");
const [pendingFiles, setPendingFiles] = useState<UploadedWorkspaceFile[]>([]);
const [isUploadingFiles, setIsUploadingFiles] = useState(false);
const [autoApprove, setAutoApprove] = useState(false);
const [autoApproveDialogOpen, setAutoApproveDialogOpen] = useState(false);
const autoApprovedRef = useRef<unknown>(null);
@@ -112,6 +125,7 @@ export const ChatInterface = React.memo<ChatInterfaceProps>(({ assistant }) => {
sendMessage,
stopStream,
resumeInterrupt,
subAgentActivity,
} = useChatContext();
// The model behind the latest assistant reply (read from message metadata).
@@ -128,6 +142,56 @@ export const ChatInterface = React.memo<ChatInterfaceProps>(({ assistant }) => {
return null;
}, [messages]);
// Bind captured sub-agent activity (keyed by subgraph namespace) to each task
// tool call → its live steps. B': match a finished sub-agent to a task by its
// final text == the task's result; assign still-running sub-agents to the
// remaining task calls in order. Returns { taskToolCallId: SubAgentStep[] }.
const subAgentSteps = useMemo(() => {
const out: Record<string, SubAgentStep[]> = {};
const nsKeys = Object.keys(subAgentActivity);
if (nsKeys.length === 0) return out;
const taskIds: string[] = [];
const results: Record<string, string> = {};
for (const m of messages) {
if (m.type === "ai") {
const tcs = (m as { tool_calls?: { id?: string; name?: string }[] })
.tool_calls;
for (const tc of tcs ?? []) {
if (tc.name === "task" && tc.id) taskIds.push(tc.id);
}
} else if (m.type === "tool") {
const id = (m as { tool_call_id?: string }).tool_call_id;
if (id) results[id] = extractStringFromMessageContent(m);
}
}
const norm = (s: string) => s.replace(/\s+/g, " ").trim();
const claimed = new Set<string>();
// 1) Finished tasks: match by output text.
for (const id of taskIds) {
const r = norm(results[id] ?? "");
if (!r) continue;
const key = nsKeys.find((k) => {
if (claimed.has(k)) return false;
const last = norm(lastTextOf(subAgentActivity[k]));
return last !== "" && (r.includes(last) || last.includes(r));
});
if (key) {
out[id] = subAgentActivity[key];
claimed.add(key);
}
}
// 2) Running tasks (no result yet): take remaining namespaces in order.
const remaining = nsKeys.filter((k) => !claimed.has(k));
let ri = 0;
for (const id of taskIds) {
if (out[id] || results[id]) continue;
if (ri < remaining.length) out[id] = subAgentActivity[remaining[ri++]];
}
return out;
}, [messages, subAgentActivity]);
// While the agent waits on an *actionable* interrupt (approval or ask_user),
// lock the composer so the user answers via the in-message controls — a free
// message would cancel the pending tool call and corrupt the thread.
@@ -140,7 +204,6 @@ export const ChatInterface = React.memo<ChatInterfaceProps>(({ assistant }) => {
(Array.isArray(interruptValue?.action_requests) &&
interruptValue.action_requests.length > 0);
const submitDisabled = isLoading || !assistant || hasPendingInterrupt;
const turnOffAutoApprove = useCallback(() => {
setAutoApprove(false);
setAutoApproveDialogOpen(false);
@@ -158,27 +221,82 @@ export const ChatInterface = React.memo<ChatInterfaceProps>(({ assistant }) => {
if (!preserveForNewThread) turnOffAutoApprove();
setPendingFiles([]);
preserveAutoApproveForNewThreadRef.current = false;
previousThreadIdRef.current = threadId;
}, [threadId, turnOffAutoApprove]);
const handleFilesSelected = useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
const selectedFiles = Array.from(event.target.files ?? []);
event.target.value = "";
if (selectedFiles.length === 0) return;
setIsUploadingFiles(true);
try {
const formData = new FormData();
selectedFiles.forEach((file) => formData.append("files", file));
const response = await fetch("/api/workspace/upload", {
method: "POST",
body: formData,
});
const data = (await response.json()) as {
files?: UploadedWorkspaceFile[];
error?: string;
};
if (!response.ok || !data.files) {
throw new Error(data.error || "Failed to upload files.");
}
setPendingFiles((currentFiles) => [...currentFiles, ...data.files!]);
toast.success(
`${data.files.length} file${
data.files.length === 1 ? "" : "s"
} uploaded to the workspace.`
);
} catch (error) {
toast.error(
error instanceof Error ? error.message : "Failed to upload files."
);
} finally {
setIsUploadingFiles(false);
}
},
[]
);
const removePendingFile = useCallback((filePath: string) => {
setPendingFiles((currentFiles) =>
currentFiles.filter((file) => file.path !== filePath)
);
}, []);
const handleSubmit = useCallback(
(e?: FormEvent) => {
if (e) {
e.preventDefault();
}
const messageText = input.trim();
if (!messageText || isLoading || submitDisabled) return;
if (!messageText || isLoading || isUploadingFiles || submitDisabled)
return;
if (!threadId && autoApprove) {
preserveAutoApproveForNewThreadRef.current = true;
}
sendMessage(messageText);
const workspaceFiles =
pendingFiles.length > 0
? `\n\nWorkspace files uploaded for this request:\n${pendingFiles
.map((file) => `- ${file.path}`)
.join("\n")}`
: "";
sendMessage(`${messageText}${workspaceFiles}`);
setInput("");
setPendingFiles([]);
},
[
autoApprove,
input,
isLoading,
isUploadingFiles,
pendingFiles,
sendMessage,
setInput,
submitDisabled,
@@ -269,7 +387,18 @@ export const ChatInterface = React.memo<ChatInterfaceProps>(({ assistant }) => {
string,
{ message: Message; toolCalls: ToolCall[] }
>();
messages.forEach((message: Message) => {
// Sub-agent (subgraph) messages stream in alongside the main conversation
// when streamSubgraphs is on. They carry a NESTED langgraph_checkpoint_ns
// ("tools:<id>|…") while the main agent's own messages are single-segment.
// Keep them OUT of the main flow — they render under each sub-agent block's
// "Steps" instead. (streamMetadata is live-only; once complete these messages
// aren't in thread state anyway.)
const visibleMessages = messages.filter((message: Message) => {
const meta = stream.getMessagesMetadata(message)?.streamMetadata;
const ns = meta?.["langgraph_checkpoint_ns"];
return !(typeof ns === "string" && ns.includes("|"));
});
visibleMessages.forEach((message: Message) => {
if (message.type === "ai") {
const toolCallsInMessage: Array<{
id?: string;
@@ -361,7 +490,7 @@ export const ChatInterface = React.memo<ChatInterfaceProps>(({ assistant }) => {
showAvatar: data.message.type !== prevMessage?.type,
};
});
}, [messages, interrupt]);
}, [messages, interrupt, stream]);
const groupedTodos = {
in_progress: todos.filter((t) => t.status === "in_progress"),
@@ -493,6 +622,7 @@ export const ChatInterface = React.memo<ChatInterfaceProps>(({ assistant }) => {
graphId={assistant?.graph_id}
onEditMessage={handleEditMessage}
autoApprove={autoApprove}
subAgentSteps={subAgentSteps}
/>
);
})}
@@ -763,6 +893,42 @@ export const ChatInterface = React.memo<ChatInterfaceProps>(({ assistant }) => {
onSubmit={handleSubmit}
className="flex flex-col"
>
{pendingFiles.length > 0 && (
<div
aria-label="Attached files"
className="flex flex-wrap gap-2 border-b border-border px-3 py-2"
>
{pendingFiles.map((file) => (
<span
key={file.path}
className="inline-flex max-w-full items-center gap-1.5 rounded-md border border-border bg-muted px-2 py-1 text-xs text-foreground"
>
<FileIcon
className="size-3.5 shrink-0 text-muted-foreground"
aria-hidden="true"
/>
<span
className="max-w-48 truncate"
title={file.path}
>
{file.name}
</span>
<button
type="button"
onClick={() => removePendingFile(file.path)}
aria-label={`Remove ${file.name} from this message`}
title={`Remove ${file.name} from this message`}
className="rounded-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<X
className="size-3.5"
aria-hidden="true"
/>
</button>
</span>
))}
</div>
)}
<textarea
ref={textareaRef}
value={input}
@@ -781,34 +947,60 @@ export const ChatInterface = React.memo<ChatInterfaceProps>(({ assistant }) => {
rows={1}
/>
<div className="flex items-center justify-between gap-2 p-3">
<button
type="button"
onClick={() =>
autoApprove
? turnOffAutoApprove()
: setAutoApproveDialogOpen(true)
}
aria-pressed={autoApprove}
title="Auto-approve all tool actions in this conversation"
className={cn(
"inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium transition-colors",
autoApprove
? "bg-amber-600 text-white hover:bg-amber-700"
: "text-muted-foreground hover:bg-accent hover:text-foreground"
)}
>
<ShieldCheck
className="size-3.5"
aria-hidden="true"
<div className="flex items-center gap-1">
<input
ref={uploadInputRef}
type="file"
multiple
onChange={handleFilesSelected}
disabled={submitDisabled || isUploadingFiles}
className="hidden"
/>
{autoApprove ? "Auto-approve On" : "Auto-approve"}
</button>
<button
type="button"
onClick={() => uploadInputRef.current?.click()}
disabled={submitDisabled || isUploadingFiles}
aria-label="Upload files to workspace"
title="Upload files to workspace (max 50 MB each)"
className="inline-flex size-8 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
>
<Paperclip
className="size-4"
aria-hidden="true"
/>
</button>
<button
type="button"
onClick={() =>
autoApprove
? turnOffAutoApprove()
: setAutoApproveDialogOpen(true)
}
aria-pressed={autoApprove}
title="Auto-approve all tool actions in this conversation"
className={cn(
"inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium transition-colors",
autoApprove
? "bg-amber-600 text-white hover:bg-amber-700"
: "text-muted-foreground hover:bg-accent hover:text-foreground"
)}
>
<ShieldCheck
className="size-3.5"
aria-hidden="true"
/>
{autoApprove ? "Auto-approve On" : "Auto-approve"}
</button>
</div>
<div className="flex justify-end gap-2">
<Button
type={isLoading ? "button" : "submit"}
variant={isLoading ? "destructive" : "default"}
onClick={isLoading ? stopStream : handleSubmit}
disabled={!isLoading && (submitDisabled || !input.trim())}
disabled={
!isLoading &&
(submitDisabled || isUploadingFiles || !input.trim())
}
>
{isLoading ? (
<>
+85 -2
View File
@@ -11,6 +11,7 @@ import type {
ReviewConfig,
} from "@/app/types/types";
import { Message } from "@langchain/langgraph-sdk";
import type { SubAgentStep } from "@/lib/subAgentActivity";
import { Brain, Check, ChevronRight, Copy, Pencil } from "lucide-react";
import {
extractSubAgentContent,
@@ -30,6 +31,70 @@ interface ChatMessageProps {
graphId?: string;
onEditMessage?: (content: string) => void;
autoApprove?: boolean;
/** Live intermediate steps per task tool-call id (sub-agent activity). */
subAgentSteps?: Record<string, SubAgentStep[]>;
}
/** A sub-agent's live steps: clickable tool-call boxes (each paired with its
* result) interleaved with the sub-agent's own text, reusing the same
* ToolCallBox the main agent uses. */
function SubAgentSteps({
steps,
hideFinalText,
}: {
steps: SubAgentStep[];
hideFinalText?: boolean;
}) {
const resultByCallId = new Map<string, string>();
for (const s of steps) {
if (s.kind === "tool_result" && s.toolCallId) {
resultByCallId.set(s.toolCallId, s.text);
}
}
// The sub-agent's final text is shown below as the task Output; once the task
// is complete, drop that trailing text step here so it isn't duplicated.
let lastTextIdx = -1;
if (hideFinalText) {
for (let i = steps.length - 1; i >= 0; i--) {
if (steps[i].kind === "text") {
lastTextIdx = i;
break;
}
}
}
return (
<div className="flex flex-col gap-1">
{steps.map((s, i) => {
if (i === lastTextIdx) return null;
if (s.kind === "tool_call") {
const toolCall: ToolCall = {
id: s.id,
name: s.name,
args: s.args,
result: resultByCallId.get(s.id),
status: resultByCallId.has(s.id) ? "completed" : "pending",
};
return (
<ToolCallBox
key={s.id || `tc-${i}`}
toolCall={toolCall}
/>
);
}
if (s.kind === "text") {
return (
<div
key={`txt-${i}`}
className="px-2 text-sm"
>
<MarkdownContent content={s.text} />
</div>
);
}
return null;
})}
</div>
);
}
export const ChatMessage = React.memo<ChatMessageProps>(
@@ -45,6 +110,7 @@ export const ChatMessage = React.memo<ChatMessageProps>(
graphId,
onEditMessage,
autoApprove,
subAgentSteps,
}) => {
const isUser = message.type === "human";
const messageContent = extractStringFromMessageContent(message);
@@ -95,13 +161,17 @@ export const ChatMessage = React.memo<ChatMessageProps>(
Record<string, boolean>
>({});
const isSubAgentExpanded = useCallback(
(id: string) => expandedSubAgents[id] ?? true,
// Collapsed by default — while running the pill shows a spinner; click to
// expand and watch the sub-agent's steps.
(id: string) => expandedSubAgents[id] ?? false,
[expandedSubAgents]
);
const toggleSubAgent = useCallback((id: string) => {
// Default is collapsed (?? false), so an untouched block must expand on the
// FIRST click — toggle off the same default the renderer uses.
setExpandedSubAgents((prev) => ({
...prev,
[id]: prev[id] === undefined ? false : !prev[id],
[id]: !(prev[id] ?? false),
}));
}, []);
@@ -279,6 +349,19 @@ export const ChatMessage = React.memo<ChatMessageProps>(
content={extractSubAgentContent(subAgent.input)}
/>
</div>
{(subAgentSteps?.[subAgent.id]?.length ?? 0) > 0 && (
<>
<h4 className="text-primary/70 mb-2 text-xs font-semibold uppercase tracking-wider">
Steps
</h4>
<div className="mb-4">
<SubAgentSteps
steps={subAgentSteps![subAgent.id]}
hideFinalText={!!subAgent.output}
/>
</div>
</>
)}
{subAgent.output && (
<>
<h4 className="text-primary/70 mb-2 text-xs font-semibold uppercase tracking-wider">
+13 -5
View File
@@ -2,7 +2,7 @@
import React from "react";
import { Button } from "@/components/ui/button";
import { Bot, ChevronDown, ChevronUp } from "lucide-react";
import { Bot, ChevronDown, ChevronUp, Loader2 } from "lucide-react";
import type { SubAgent } from "@/app/types/types";
interface SubAgentIndicatorProps {
@@ -13,6 +13,7 @@ interface SubAgentIndicatorProps {
export const SubAgentIndicator = React.memo<SubAgentIndicatorProps>(
({ subAgent, onClick, isExpanded = true }) => {
const running = subAgent.status === "pending";
return (
<div className="w-fit max-w-[70vw] overflow-hidden rounded-lg bg-card">
<Button
@@ -22,10 +23,17 @@ export const SubAgentIndicator = React.memo<SubAgentIndicatorProps>(
className="flex w-full items-center justify-between gap-2 px-3 py-2 text-left"
>
<span className="bg-[var(--brand)]/10 flex size-5 shrink-0 items-center justify-center rounded-md text-[var(--brand)]">
<Bot
className="size-3.5"
aria-hidden="true"
/>
{running ? (
<Loader2
className="size-3.5 animate-spin"
aria-hidden="true"
/>
) : (
<Bot
className="size-3.5"
aria-hidden="true"
/>
)}
</span>
<span className="truncate text-sm font-semibold text-foreground">
{subAgent.subAgentName}
+34 -2
View File
@@ -1,6 +1,6 @@
"use client";
import { useCallback } from "react";
import { useCallback, useState } from "react";
import { useStream } from "@langchain/langgraph-sdk/react";
import { type Message, type Assistant } from "@langchain/langgraph-sdk";
import { v4 as uuidv4 } from "uuid";
@@ -8,6 +8,10 @@ import type { UseStreamThread } from "@langchain/langgraph-sdk/react";
import type { TodoItem } from "@/app/types/types";
import { useClient } from "@/providers/ClientProvider";
import { useQueryState } from "nuqs";
import {
extractSubAgentSteps,
type SubAgentStep,
} from "@/lib/subAgentActivity";
export type StateType = {
messages: Message[];
@@ -33,6 +37,13 @@ export function useChat({
const [threadId, setThreadId] = useQueryState("threadId");
const client = useClient();
// Live sub-agent activity captured from subgraph stream events, keyed by the
// subgraph namespace (e.g. "tools:<id>"). Ephemeral: it resets when the chat
// session remounts on thread switch, and is not persisted (lost on reload).
const [subAgentActivity, setSubAgentActivity] = useState<
Record<string, SubAgentStep[]>
>({});
const stream = useStream<StateType>({
assistantId: activeAssistant?.assistant_id || "",
client: client ?? undefined,
@@ -46,6 +57,20 @@ export function useChat({
onFinish: onHistoryRevalidate,
onError: onHistoryRevalidate,
onCreated: onHistoryRevalidate,
// Capture sub-agent (subgraph) node outputs as they stream. `namespace` is
// non-empty (e.g. ["tools:<id>"]) for subgraphs and empty for the main graph,
// which we skip.
onUpdateEvent: (data, options) => {
const ns = options?.namespace;
if (!ns || ns.length === 0) return;
const steps = extractSubAgentSteps(data);
if (steps.length === 0) return;
const key = ns.join("|");
setSubAgentActivity((prev) => ({
...prev,
[key]: [...(prev[key] ?? []), ...steps],
}));
},
experimental_thread: thread,
});
@@ -59,6 +84,8 @@ export function useChat({
messages: [...(prev.messages ?? []), newMessage],
}),
config: { ...(activeAssistant?.config ?? {}), recursion_limit: 100 },
streamSubgraphs: true,
streamMode: ["updates"],
}
);
// Update thread list immediately when sending a message
@@ -79,7 +106,11 @@ export function useChat({
const resumeInterrupt = useCallback(
(value: any) => {
stream.submit(null, { command: { resume: value } });
stream.submit(null, {
command: { resume: value },
streamSubgraphs: true,
streamMode: ["updates"],
});
// Update thread list when resuming from interrupt
onHistoryRevalidate?.();
},
@@ -104,5 +135,6 @@ export function useChat({
sendMessage,
stopStream,
resumeInterrupt,
subAgentActivity,
};
}
+86
View File
@@ -0,0 +1,86 @@
// Live sub-agent activity captured from subgraph stream events.
//
// With `streamSubgraphs: true`, useStream's `onUpdateEvent(data, { namespace })`
// fires for sub-agent (subgraph) node outputs. `namespace` looks like
// ["tools:<id>"]; `data` is `{ <nodeName>: { messages: [...] } }`. We turn those
// node outputs into a flat list of steps to render inside the sub-agent block.
//
// This data is LIVE-ONLY: it isn't persisted to thread state, so it's gone after
// a page reload (the block falls back to its INPUT/OUTPUT). Async sub-agents that
// run as separate deployed graphs aren't subgraphs of this run and won't appear.
export type SubAgentStep =
| {
kind: "tool_call";
id: string;
name: string;
args: Record<string, unknown>;
}
| { kind: "tool_result"; toolCallId: string; name: string; text: string }
| { kind: "text"; text: string };
function extractText(content: unknown): string {
if (typeof content === "string") return content;
if (Array.isArray(content)) {
return content
.map((part) =>
part && typeof part === "object" && "text" in part
? String((part as { text?: unknown }).text ?? "")
: ""
)
.join("");
}
return "";
}
/** Parse one subgraph update payload into renderable steps (empty nodes skipped). */
export function extractSubAgentSteps(data: unknown): SubAgentStep[] {
const steps: SubAgentStep[] = [];
if (!data || typeof data !== "object") return steps;
for (const node of Object.values(data as Record<string, unknown>)) {
const msgs = (node as { messages?: unknown })?.messages;
if (!Array.isArray(msgs)) continue;
for (const raw of msgs) {
const m = raw as {
type?: string;
content?: unknown;
name?: string;
tool_call_id?: string;
tool_calls?: { id?: string; name?: string; args?: unknown }[];
};
if (m.type === "ai" && m.tool_calls && m.tool_calls.length > 0) {
for (const tc of m.tool_calls) {
steps.push({
kind: "tool_call",
id: tc.id ?? "",
name: tc.name ?? "tool",
args:
tc.args && typeof tc.args === "object"
? (tc.args as Record<string, unknown>)
: {},
});
}
} else if (m.type === "ai") {
const text = extractText(m.content).trim();
if (text) steps.push({ kind: "text", text });
} else if (m.type === "tool") {
steps.push({
kind: "tool_result",
toolCallId: m.tool_call_id ?? "",
name: m.name ?? "tool",
text: extractText(m.content).trim(),
});
}
}
}
return steps;
}
/** The last assistant text a sub-agent produced — used to bind it to a task block. */
export function lastTextOf(steps: SubAgentStep[]): string {
for (let i = steps.length - 1; i >= 0; i--) {
const s = steps[i];
if (s.kind === "text") return s.text;
}
return "";
}