diff --git a/src/app/api/workspace/upload/route.ts b/src/app/api/workspace/upload/route.ts new file mode 100644 index 0000000..451b82c --- /dev/null +++ b/src/app/api/workspace/upload/route.ts @@ -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 } + ); + } +} diff --git a/src/app/components/ChatInterface.tsx b/src/app/components/ChatInterface.tsx index f9080c2..4f91bf0 100644 --- a/src/app/components/ChatInterface.tsx +++ b/src/app/components/ChatInterface.tsx @@ -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(({ assistant }) => { const [metaOpen, setMetaOpen] = useState<"tasks" | "files" | null>(null); const tasksContainerRef = useRef(null); const textareaRef = useRef(null); + const uploadInputRef = useRef(null); const [input, setInput] = useState(""); + const [pendingFiles, setPendingFiles] = useState([]); + const [isUploadingFiles, setIsUploadingFiles] = useState(false); const [autoApprove, setAutoApprove] = useState(false); const [autoApproveDialogOpen, setAutoApproveDialogOpen] = useState(false); const autoApprovedRef = useRef(null); @@ -112,6 +125,7 @@ export const ChatInterface = React.memo(({ 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(({ 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 = {}; + const nsKeys = Object.keys(subAgentActivity); + if (nsKeys.length === 0) return out; + + const taskIds: string[] = []; + const results: Record = {}; + 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(); + // 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(({ 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(({ assistant }) => { if (!preserveForNewThread) turnOffAutoApprove(); + setPendingFiles([]); preserveAutoApproveForNewThreadRef.current = false; previousThreadIdRef.current = threadId; }, [threadId, turnOffAutoApprove]); + const handleFilesSelected = useCallback( + async (event: React.ChangeEvent) => { + 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(({ 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:|…") 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(({ 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(({ assistant }) => { graphId={assistant?.graph_id} onEditMessage={handleEditMessage} autoApprove={autoApprove} + subAgentSteps={subAgentSteps} /> ); })} @@ -763,6 +893,42 @@ export const ChatInterface = React.memo(({ assistant }) => { onSubmit={handleSubmit} className="flex flex-col" > + {pendingFiles.length > 0 && ( +
+ {pendingFiles.map((file) => ( + + + ))} +
+ )}