Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add artifact upload, storage, and preview for agent conversations

Gusb03ef894f04a
diff --git a/src/cli/commands/sync.ts b/src/cli/commands/sync.ts
new file mode 100644
index 000000000..7b2f3b836
--- /dev/null
+++ b/src/cli/commands/sync.ts
@@ -0,0 +1,102 @@
+import { Command } from "commander";
+import { readFileSync, statSync } from "fs";
+import { basename } from "path";
+import { APIClient } from "../lib/client.js";
+import { loadCLIConfigForProfile } from "../lib/config.js";
+import { printJSON } from "../lib/output.js";
+import { cmdPrefix } from "../lib/env.js";
+
+const MIME_BY_EXT: Record<string, string> = {
+ ".pdf": "application/pdf",
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".txt": "text/plain",
+ ".html": "text/html",
+ ".json": "application/json",
+ ".csv": "text/csv",
+ ".md": "text/markdown",
+ ".ts": "text/typescript",
+ ".js": "text/javascript",
+ ".yaml": "text/yaml",
+ ".yml": "text/yaml",
+ ".svg": "image/svg+xml",
+ ".xml": "application/xml",
+ ".zip": "application/zip",
+};
+
+function guessContentType(filename: string): string {
+ const idx = filename.lastIndexOf(".");
+ if (idx < 0) return "application/octet-stream";
+ const ext = filename.slice(idx).toLowerCase();
+ return MIME_BY_EXT[ext] ?? "application/octet-stream";
+}
+
+function resolveClientOpts(command: Command, agentId: string) {
+ const parentOpts = command.parent?.parent?.opts() || {};
+ const profile: string | undefined = parentOpts.profile;
+ const cfg = loadCLIConfigForProfile(profile);
+ const serverUrl = parentOpts.server || cfg.server_url;
+ const workspaces = cfg.watched_workspaces || [];
+
+ const ws = workspaces.find((w) => w.agent_ids?.includes(agentId));
+ if (!ws || !ws.token) {
+ console.error(
+ `Error: no registered workspace contains agent ${agentId}. Run '${cmdPrefix()} register --token <token>' first.`
+ );
+ process.exit(1);
+ }
+ return { serverUrl, token: ws.token, workspaceId: ws.id };
+}
+
+export function syncCommand(): Command {
+ const cmd = new Command("sync").description("File sync utilities");
+
+ cmd
+ .command("upload-artifact")
+ .description("Upload a file artifact to a conversation")
+ .requiredOption("--agent_id <id>", "Agent ID")
+ .requiredOption("--conversation_id <id>", "Conversation ID")
+ .requiredOption("--file <path>", "Path to file to upload")
+ .action(async (opts, command) => {
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, opts.agent_id);
+ const client = new APIClient(serverUrl, token, workspaceId);
+
+ let bytes: Buffer;
+ let size: number;
+ try {
+ const stat = statSync(opts.file);
+ size = stat.size;
+ bytes = readFileSync(opts.file);
+ } catch (err) {
+ console.error(`Error: cannot read file "${opts.file}": ${(err as Error).message}`);
+ process.exit(1);
+ }
+
+ const filename = basename(opts.file);
+ const contentType = guessContentType(filename);
+
+ const form = new FormData();
+ form.append(
+ "file",
+ new Blob([new Uint8Array(bytes)], { type: contentType }),
+ filename
+ );
+ form.append("agent_id", opts.agent_id);
+ form.append("conversation_id", opts.conversation_id);
+
+ try {
+ const result = await client.postMultipart<Record<string, unknown>>(
+ "/api/artifacts/upload",
+ form
+ );
+ printJSON(result);
+ } catch (err) {
+ console.error(`Error uploading artifact: ${(err as Error).message}`);
+ process.exit(1);
+ }
+ });
+
+ return cmd;
+}
diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.ts
index 05d93144d..8a5a89205 100644
--- a/src/cli/daemon/execenv/context.ts
+++ b/src/cli/daemon/execenv/context.ts
@@ -112,6 +112,14 @@ To reply to an email, add '--in-reply-to <EMAIL_ID>' to the send command. This s
`;
}
+ content += `\n### Artifacts
+Upload files for your owner to review in the app.
+- Your current conversation id is available via env var: $ALOOK_CONVERSATION_ID
+- Run 'npx @alook/cli sync upload-artifact --agent_id ${task.agentId} --conversation_id $ALOOK_CONVERSATION_ID --file <PATH>'
+- Use this after generating plans, reports, or any file the owner should review.
+---
+`;
+
content += `\n### Calendar
You have your own calendar to setup daily routines and reminders.
Schedule future tasks for yourself. At the scheduled time, a new task is dispatched to you with the event as the prompt (task type 'calendar_event').
diff --git a/src/cli/src/index.ts b/src/cli/src/index.ts
index bb5694cb7..e73d94372 100644
--- a/src/cli/src/index.ts
+++ b/src/cli/src/index.ts
@@ -8,6 +8,7 @@ import { emailCommand } from "../commands/email.js";
import { calendarCommand } from "../commands/calendar.js";
import { versionCommand } from "../commands/version.js";
import { updateCommand } from "../commands/update.js";
+import { syncCommand } from "../commands/sync.js";
const program = new Command();
@@ -25,5 +26,6 @@ program.addCommand(calendarCommand());
program.addCommand(configCommand());
program.addCommand(versionCommand());
program.addCommand(updateCommand());
+program.addCommand(syncCommand());
program.parse();
diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.ts
index 61de12764..90515978c 100644
--- a/src/shared/src/db/queries-index.ts
+++ b/src/shared/src/db/queries-index.ts
@@ -13,3 +13,4 @@ export * as whitelist from "./queries/whitelist";
export * as email from "./queries/email";
export * as session from "./queries/session";
export * as calendarEvent from "./queries/calendar-event";
+export * as artifact from "./queries/artifact";
diff --git a/src/shared/src/db/queries/artifact.ts b/src/shared/src/db/queries/artifact.ts
new file mode 100644
index 000000000..a85c0d96c
--- /dev/null
+++ b/src/shared/src/db/queries/artifact.ts
@@ -0,0 +1,58 @@
+import { eq, desc, and } from "drizzle-orm";
+import { artifact } from "../schema";
+import type { Database } from "../index";
+import type { Artifact } from "../../types";
+
+export async function createArtifact(
+ db: Database,
+ data: {
+ id?: string;
+ conversationId: string;
+ agentId: string;
+ workspaceId: string;
+ filename: string;
+ contentType: string;
+ size: number;
+ r2Key: string;
+ }
+) {
+ const rows = await db.insert(artifact).values(data).returning();
+ return rows[0]!;
+}
+
+export async function listArtifactsByConversation(
+ db: Database,
+ conversationId: string,
+ workspaceId: string
+) {
+ return db
+ .select()
+ .from(artifact)
+ .where(
+ and(
+ eq(artifact.conversationId, conversationId),
+ eq(artifact.workspaceId, workspaceId)
+ )
+ )
+ .orderBy(desc(artifact.createdAt));
+}
+
+export async function getArtifact(db: Database, id: string, workspaceId: string) {
+ const rows = await db
+ .select()
+ .from(artifact)
+ .where(and(eq(artifact.id, id), eq(artifact.workspaceId, workspaceId)));
+ return rows[0] ?? null;
+}
+
+export function artifactToResponse(row: typeof artifact.$inferSelect): Artifact {
+ return {
+ id: row.id,
+ conversation_id: row.conversationId,
+ agent_id: row.agentId,
+ filename: row.filename,
+ content_type: row.contentType,
+ size: row.size,
+ created_at: row.createdAt,
+ };
+}
diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.ts
index 80a043579..1e8b5b68b 100644
--- a/src/shared/src/db/schema.ts
+++ b/src/shared/src/db/schema.ts
@@ -328,6 +328,32 @@ export const calendarEvent = sqliteTable(
]
);
+export const artifact = sqliteTable(
+ "artifact",
+ {
+ id: text("id").primaryKey().$defaultFn(() => "art_" + nanoid()),
+ conversationId: text("conversation_id")
+ .notNull()
+ .references(() => conversation.id, { onDelete: "cascade" }),
+ agentId: text("agent_id").notNull(),
+ workspaceId: text("workspace_id")
+ .notNull()
+ .references(() => workspace.id, { onDelete: "cascade" }),
+ filename: text("filename").notNull(),
+ contentType: text("content_type").notNull().default("application/octet-stream"),
+ size: integer("size").notNull(),
+ r2Key: text("r2_key").notNull(),
+ createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
+ },
+ (t) => [
+ index("idx_artifact_conversation").on(t.conversationId),
+ foreignKey({
+ columns: [t.agentId, t.workspaceId],
+ foreignColumns: [agent.id, agent.workspaceId],
+ }).onDelete("cascade"),
+ ]
+);
+
export const machineToken = sqliteTable(
"machine_token",
{
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 919d072a8..29a6fb23f 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -11,6 +11,7 @@ export type {
MachineToken,
Email,
EmailAttachment,
+ Artifact,
LoginResponse,
CreateAgentRequest,
CalendarEvent,
diff --git a/src/shared/src/types.ts b/src/shared/src/types.ts
index 876bd6f91..4043dc7b6 100644
--- a/src/shared/src/types.ts
+++ b/src/shared/src/types.ts
@@ -138,6 +138,16 @@ export interface Email {
created_at: string;
}
+export interface Artifact {
+ id: string;
+ conversation_id: string;
+ agent_id: string;
+ filename: string;
+ content_type: string;
+ size: number;
+ created_at: string;
+}
+
export interface LoginResponse {
token: string;
user: User;
@@ -161,3 +171,4 @@ export type WsMessage =
| { type: "task.updated"; taskId: string; status: string }
| { type: "task.messages"; taskId: string; messages: TaskMessage[] }
| { type: "email.received"; agentId: string }
+ | { type: "artifact.uploaded"; conversationId: string; artifact: Artifact }
diff --git a/src/web/migrations/0002_artifacts.sql b/src/web/migrations/0002_artifacts.sql
new file mode 100644
index 000000000..04f5ad525
--- /dev/null
+++ b/src/web/migrations/0002_artifacts.sql
@@ -0,0 +1,14 @@
+CREATE TABLE IF NOT EXISTS artifact (
+ id TEXT PRIMARY KEY,
+ conversation_id TEXT NOT NULL REFERENCES conversation(id) ON DELETE CASCADE,
+ agent_id TEXT NOT NULL,
+ workspace_id TEXT NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,
+ filename TEXT NOT NULL,
+ content_type TEXT NOT NULL DEFAULT 'application/octet-stream',
+ size INTEGER NOT NULL,
+ r2_key TEXT NOT NULL,
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
+ FOREIGN KEY (agent_id, workspace_id) REFERENCES agent(id, workspace_id) ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS idx_artifact_conversation ON artifact(conversation_id);
diff --git a/src/web/src/app/api/artifacts/[id]/content/route.ts b/src/web/src/app/api/artifacts/[id]/content/route.ts
new file mode 100644
index 000000000..5b2a1c0b4
--- /dev/null
+++ b/src/web/src/app/api/artifacts/[id]/content/route.ts
@@ -0,0 +1,39 @@
+import { NextRequest } from "next/server";
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+import { createDb, queries } from "@alook/shared";
+import { withAuth } from "@/lib/middleware/auth";
+import { withWorkspaceMember } from "@/lib/middleware/workspace";
+import { writeError } from "@/lib/middleware/helpers";
+
+export const GET = withAuth(async (req: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const id = ctx.params?.id as string;
+ const { env } = getCloudflareContext();
+ const db = createDb((env as Env).DB);
+ const bucket = (env as Env).EMAIL_BUCKET;
+
+ const row = await queries.artifact.getArtifact(db, id, ws.workspaceId);
+ if (!row) {
+ return writeError("artifact not found", 404);
+ }
+
+ const object = await bucket.get(row.r2Key);
+ if (!object) {
+ return writeError("artifact content not found", 404);
+ }
+
+ const download = req.nextUrl.searchParams.get("download");
+ const headers: Record<string, string> = {
+ "Content-Type": row.contentType,
+ "Content-Length": String(row.size),
+ };
+ if (download !== null) {
+ headers["Content-Disposition"] = `attachment; filename="${row.filename.replace(/"/g, '\\"')}"`;
+ } else {
+ headers["Content-Disposition"] = `inline; filename="${row.filename.replace(/"/g, '\\"')}"`;
+ }
+
+ return new Response(object.body, { headers });
+});
diff --git a/src/web/src/app/api/artifacts/route.ts b/src/web/src/app/api/artifacts/route.ts
new file mode 100644
index 000000000..035c3943a
--- /dev/null
+++ b/src/web/src/app/api/artifacts/route.ts
@@ -0,0 +1,27 @@
+import { NextRequest } from "next/server";
+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";
+
+export const GET = withAuth(async (req: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const conversationId = req.nextUrl.searchParams.get("conversation_id");
+ if (!conversationId) {
+ return writeError("conversation_id is required", 400);
+ }
+
+ const { env } = getCloudflareContext();
+ const db = createDb((env as Env).DB);
+
+ const rows = await queries.artifact.listArtifactsByConversation(
+ db,
+ conversationId,
+ ws.workspaceId
+ );
+
+ return writeJSON(rows.map(queries.artifact.artifactToResponse));
+});
diff --git a/src/web/src/app/api/artifacts/upload/route.ts b/src/web/src/app/api/artifacts/upload/route.ts
new file mode 100644
index 000000000..16576befd
--- /dev/null
+++ b/src/web/src/app/api/artifacts/upload/route.ts
@@ -0,0 +1,82 @@
+import { NextRequest } from "next/server";
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+import { createDb, queries } from "@alook/shared";
+import { nanoid } from "nanoid";
+import { withAuth } from "@/lib/middleware/auth";
+import { withWorkspaceMember } from "@/lib/middleware/workspace";
+import { writeJSON, writeError } from "@/lib/middleware/helpers";
+import { broadcastToUser } from "@/lib/broadcast";
+
+const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
+
+function sanitizeFilename(name: string): string {
+ return name.replace(/[/\\]/g, "_").replace(/\.\./g, "_").slice(0, 255) || "file";
+}
+
+export const POST = withAuth(async (req: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const bucket = (env as Env).EMAIL_BUCKET;
+ const db = createDb((env as Env).DB);
+
+ let formData: FormData;
+ try {
+ formData = await req.formData();
+ } catch {
+ return writeError("invalid form data", 400);
+ }
+
+ const file = formData.get("file");
+ if (!file || !(file instanceof File)) {
+ return writeError("file is required", 400);
+ }
+
+ const conversationId = formData.get("conversation_id");
+ if (!conversationId || typeof conversationId !== "string") {
+ return writeError("conversation_id is required", 400);
+ }
+
+ if (file.size > MAX_FILE_SIZE) {
+ return writeError("file exceeds 10 MB limit", 413);
+ }
+
+ const conv = await queries.conversation.getConversation(db, conversationId, ws.workspaceId);
+ if (!conv) {
+ return writeError("conversation not found", 404);
+ }
+
+ const agentId = conv.agentId;
+ const filename = sanitizeFilename(file.name);
+ const contentType = file.type || "application/octet-stream";
+ const artifactId = "art_" + nanoid();
+ const r2Key = `artifacts/${ws.workspaceId}/${agentId}/${conversationId}/${artifactId}/${filename}`;
+
+ await bucket.put(r2Key, await file.arrayBuffer(), {
+ httpMetadata: { contentType },
+ });
+
+ const row = await queries.artifact.createArtifact(db, {
+ id: artifactId,
+ conversationId,
+ agentId,
+ workspaceId: ws.workspaceId,
+ filename,
+ contentType,
+ size: file.size,
+ r2Key,
+ });
+ const response = queries.artifact.artifactToResponse(row);
+
+ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId);
+ if (agent?.ownerId) {
+ broadcastToUser(agent.ownerId, {
+ type: "artifact.uploaded",
+ conversationId,
+ artifact: response,
+ }).catch(() => {});
+ }
+
+ return writeJSON(response);
+});
diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsx
index 094ffe47c..483b2f8a0 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -1,6 +1,6 @@
"use client";
-import React, { useEffect, useState, useRef, useCallback } from "react";
+import React, { useEffect, useState, useRef, useCallback, useMemo } from "react";
import { useParams } from "next/navigation";
import { useWorkspace } from "@/contexts/workspace-context";
import { Button } from "@/components/ui/button";
@@ -13,13 +13,16 @@ import {
getTaskMessages,
getActiveTask,
deleteConversation,
+ listArtifacts,
} from "@/lib/api";
-import type { Conversation, Message, TaskApi as Task, TaskMessage, WsMessage } from "@alook/shared";
+import type { Artifact, Conversation, Message, TaskApi as Task, TaskMessage, WsMessage } from "@alook/shared";
import { useAgentContext } from "@/contexts/agent-context";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";
-import { ArrowUp, Loader2, RotateCcw } from "lucide-react";
+import { ArrowUp, Box, FileText, Loader2, RotateCcw } from "lucide-react";
+import { ArtifactSheet, formatSize } from "@/components/agent-chat/artifact-sheet";
+import { isPreviewable, getArtifactUrl } from "@/components/artifact-content-renderer";
import {
Dialog,
DialogContent,
@@ -49,6 +52,42 @@ export function mergeMessages(existing: Message[], incoming: Message[]): Message
return sortMessages([...merged.values()]);
}
+type TimelineItem =
+ | { kind: "message"; data: Message }
+ | { kind: "artifact"; data: Artifact };
+
+function buildTimeline(messages: Message[], artifacts: Artifact[]): TimelineItem[] {
+ const items: TimelineItem[] = [
+ ...messages.map((m): TimelineItem => ({ kind: "message", data: m })),
+ ...artifacts.map((a): TimelineItem => ({ kind: "artifact", data: a })),
+ ];
+ return items.sort((a, b) => {
+ const cmp = a.data.created_at.localeCompare(b.data.created_at);
+ if (cmp !== 0) return cmp;
+ if (a.kind !== b.kind) return a.kind === "message" ? -1 : 1;
+ return a.data.id.localeCompare(b.data.id);
+ });
+}
+
+function ArtifactCard({ artifact, onClick }: { artifact: Artifact; onClick: (a: Artifact) => void }) {
+ return (
+ <button
+ onClick={() => onClick(artifact)}
+ className={cn(
+ "flex items-center gap-3 w-full max-w-sm rounded-lg border border-border/60 bg-muted/30",
+ "px-3.5 py-2.5 text-left transition-colors duration-150",
+ "hover:bg-muted/60 hover:border-border"
+ )}
+ >
+ <FileText className="size-4 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium truncate">{artifact.filename}</p>
+ <p className="text-xs text-muted-foreground">{formatSize(artifact.size)}</p>
+ </div>
+ </button>
+ );
+}
+
export function AgentChatView() {
const params = useParams();
const { workspaceId } = useWorkspace();
@@ -68,6 +107,20 @@ export function AgentChatView() {
const [connectionLost, setConnectionLost] = useState(false);
const [hasMore, setHasMore] = useState(false);
const [loadingMore, setLoadingMore] = useState(false);
+ const [artifacts, setArtifacts] = useState<Artifact[]>([]);
+ const [artifactSheetOpen, setArtifactSheetOpen] = useState(false);
+ const [selectedArtifact, setSelectedArtifact] = useState<Artifact | null>(null);
+
+ const timeline = useMemo(() => buildTimeline(messages, artifacts), [messages, artifacts]);
+
+ const handleArtifactClick = useCallback((artifact: Artifact) => {
+ if (isPreviewable(artifact)) {
+ setSelectedArtifact(artifact);
+ setArtifactSheetOpen(true);
+ } else {
+ window.open(getArtifactUrl(artifact.id, workspaceId, true), "_blank");
+ }
+ }, [workspaceId]);
const scrollRef = useRef<HTMLDivElement>(null);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
@@ -103,8 +156,12 @@ export function AgentChatView() {
try {
const conv = await getOrCreateAgentConversation(agentId, workspaceId);
setConversation(conv);
- const msgs = await listMessages(conv.id, workspaceId, { limit: MESSAGE_LIMIT });
+ const [msgs, arts] = await Promise.all([
+ listMessages(conv.id, workspaceId, { limit: MESSAGE_LIMIT }),
+ listArtifacts(conv.id, workspaceId),
+ ]);
setMessages(msgs);
+ setArtifacts(arts);
setHasMore(msgs.length >= MESSAGE_LIMIT);
// Recover active task (e.g. after page refresh)
@@ -305,8 +362,14 @@ export function AgentChatView() {
lastSeqRef.current = Math.max(...incoming.map((m) => m.seq), lastSeqRef.current);
}
}
+ if (msg.type === "artifact.uploaded" && msg.conversationId === conversation?.id) {
+ setArtifacts((prev) => {
+ if (prev.some((a) => a.id === msg.artifact.id)) return prev;
+ return [...prev, msg.artifact];
+ });
+ }
});
- }, [subscribeWs]);
+ }, [subscribeWs, conversation?.id]);
const handleSend = async () => {
const content = input.trim();
@@ -365,6 +428,7 @@ export function AgentChatView() {
setMessages([]);
setActiveTask(null);
setTaskMessages([]);
+ setArtifacts([]);
lastSeqRef.current = 0;
setConnectionLost(false);
setHasMore(false);
@@ -470,7 +534,18 @@ export function AgentChatView() {
</p>
)}
- {messages.map((msg) => {
+ {timeline.map((item) => {
+ if (item.kind === "artifact") {
+ return (
+ <ArtifactCard
+ key={`artifact-${item.data.id}`}
+ artifact={item.data}
+ onClick={handleArtifactClick}
+ />
+ );
+ }
+
+ const msg = item.data;
const hasTaskStream =
activeTask &&
msg.role === "assistant" &&
@@ -479,7 +554,6 @@ export function AgentChatView() {
return (
<React.Fragment key={msg.id}>
- {/* Show full trace (including text) for completed tasks */}
{hasTaskStream && (
<TaskStream
task={activeTask}
@@ -517,7 +591,7 @@ export function AgentChatView() {
{/* Input */}
<div className="px-5 py-3">
- <div className="mx-auto max-w-2xl">
+ <div className="mx-auto max-w-2xl relative">
<div
className={cn(
"relative flex flex-col rounded-xl border bg-background/60 transition-colors duration-200",
@@ -539,20 +613,36 @@ export function AgentChatView() {
)}
/>
<div className="flex items-center justify-between px-2 pb-2 pt-0.5">
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={handleReset}
- disabled={resetting || !conversation || messages.length === 0}
- className="rounded-lg text-muted-foreground/60 hover:text-foreground transition-colors duration-200"
- title="New conversation"
- >
- {resetting ? (
- <Loader2 className="size-3.5 animate-spin" />
- ) : (
- <RotateCcw className="size-3.5" />
- )}
- </Button>
+ <div className="flex items-center gap-1">
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={handleReset}
+ disabled={resetting || !conversation || messages.length === 0}
+ className="rounded-lg text-muted-foreground/60 hover:text-foreground transition-colors duration-200"
+ title="New conversation"
+ >
+ {resetting ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <RotateCcw className="size-3.5" />
+ )}
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => setArtifactSheetOpen(true)}
+ className="relative rounded-lg text-muted-foreground/60 hover:text-foreground transition-colors duration-200"
+ title="View artifacts"
+ >
+ <Box className="size-3.5" />
+ {artifacts.length > 0 && (
+ <span className="absolute -top-0.5 -right-0.5 flex size-3.5 items-center justify-center rounded-full bg-primary text-[9px] font-medium text-primary-foreground">
+ {artifacts.length}
+ </span>
+ )}
+ </Button>
+ </div>
<Button
size="icon-sm"
onClick={handleSend}
@@ -614,6 +704,17 @@ export function AgentChatView() {
</DialogFooter>
</DialogContent>
</Dialog>
+
+ <ArtifactSheet
+ open={artifactSheetOpen}
+ onOpenChange={(v) => {
+ setArtifactSheetOpen(v);
+ if (!v) setSelectedArtifact(null);
+ }}
+ artifacts={artifacts}
+ workspaceId={workspaceId}
+ initialArtifact={selectedArtifact}
+ />
</>
);
}
diff --git a/src/web/src/components/agent-chat/artifact-sheet.tsx b/src/web/src/components/agent-chat/artifact-sheet.tsx
new file mode 100644
index 000000000..d014c78ba
--- /dev/null
+++ b/src/web/src/components/agent-chat/artifact-sheet.tsx
@@ -0,0 +1,136 @@
+"use client";
+
+import React, { useState, useEffect, useRef, useCallback } from "react";
+import {
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ SheetBody,
+} from "@/components/ui/sheet";
+import type { Artifact } from "@alook/shared";
+import { FileText, Download } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { ArtifactContentRenderer, getArtifactUrl } from "@/components/artifact-content-renderer";
+
+export function formatSize(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+interface ArtifactSheetProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ artifacts: Artifact[];
+ workspaceId: string;
+ initialArtifact?: Artifact | null;
+}
+
+const MIN_WIDTH = 320;
+const MAX_WIDTH_RATIO = 0.8;
+const DEFAULT_WIDTH = 448;
+
+export function ArtifactSheet({ open, onOpenChange, artifacts, workspaceId, initialArtifact = null }: ArtifactSheetProps) {
+ const [selectedArtifact, setSelectedArtifact] = useState<Artifact | null>(null);
+ const [width, setWidth] = useState(DEFAULT_WIDTH);
+ const dragging = useRef(false);
+
+ useEffect(() => {
+ if (open && initialArtifact) {
+ setSelectedArtifact(initialArtifact);
+ }
+ }, [open, initialArtifact]);
+
+ const handleOpenChange = (v: boolean) => {
+ if (!v) {
+ setSelectedArtifact(null);
+ }
+ onOpenChange(v);
+ };
+
+ const onPointerDown = useCallback((e: React.PointerEvent) => {
+ e.preventDefault();
+ dragging.current = true;
+ (e.target as HTMLElement).setPointerCapture(e.pointerId);
+ }, []);
+
+ const onPointerMove = useCallback((e: React.PointerEvent) => {
+ if (!dragging.current) return;
+ const maxW = window.innerWidth * MAX_WIDTH_RATIO;
+ setWidth(Math.min(maxW, Math.max(MIN_WIDTH, window.innerWidth - e.clientX)));
+ }, []);
+
+ const onPointerUp = useCallback(() => {
+ dragging.current = false;
+ }, []);
+
+ return (
+ <Sheet open={open} onOpenChange={handleOpenChange}>
+ <SheetContent
+ side="right"
+ showCloseButton={false}
+ style={{ width, maxWidth: "none" }}
+ className="data-[side=right]:inset-y-2 data-[side=right]:right-2 data-[side=right]:h-auto data-[side=right]:rounded-xl data-[side=right]:border data-[side=right]:border-l"
+ >
+ <div
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ className="absolute left-0 top-0 bottom-0 w-1.5 cursor-col-resize z-10 hover:bg-primary/20 active:bg-primary/30 transition-colors rounded-l-xl"
+ />
+ {selectedArtifact ? (
+ <>
+ <SheetHeader>
+ <div className="flex items-center gap-2">
+ <SheetTitle className="truncate flex-1">{selectedArtifact.filename}</SheetTitle>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="shrink-0"
+ onClick={() => window.open(getArtifactUrl(selectedArtifact.id, workspaceId, true), "_blank")}
+ >
+ <Download className="size-4" />
+ </Button>
+ </div>
+ </SheetHeader>
+ <SheetBody className="thin-scrollbar">
+ <ArtifactContentRenderer artifact={selectedArtifact} workspaceId={workspaceId} />
+ </SheetBody>
+ </>
+ ) : (
+ <>
+ <SheetHeader>
+ <SheetTitle>Artifacts</SheetTitle>
+ </SheetHeader>
+ <SheetBody className="thin-scrollbar">
+ {artifacts.length === 0 ? (
+ <p className="text-sm text-muted-foreground py-8 text-center">
+ No artifacts uploaded yet.
+ </p>
+ ) : (
+ <div className="space-y-1">
+ {artifacts.map((a) => (
+ <button
+ key={a.id}
+ onClick={() => setSelectedArtifact(a)}
+ className="flex items-start gap-3 w-full rounded-lg px-3 py-2.5 text-left hover:bg-muted/50 transition-colors"
+ >
+ <FileText className="size-4 mt-0.5 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium truncate">{a.filename}</p>
+ <p className="text-xs text-muted-foreground">
+ {formatSize(a.size)} &middot; {new Date(a.created_at).toLocaleString()}
+ </p>
+ </div>
+ </button>
+ ))}
+ </div>
+ )}
+ </SheetBody>
+ </>
+ )}
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/src/web/src/components/artifact-content-renderer.tsx b/src/web/src/components/artifact-content-renderer.tsx
new file mode 100644
index 000000000..94937ebd5
--- /dev/null
+++ b/src/web/src/components/artifact-content-renderer.tsx
@@ -0,0 +1,113 @@
+"use client";
+
+import React, { useEffect, useState } from "react";
+import { getArtifactContent } from "@/lib/api";
+import type { Artifact } from "@alook/shared";
+import { Loader2, Download } from "lucide-react";
+import { Streamdown } from "streamdown";
+
+const TEXT_TYPES = new Set([
+ "application/json",
+ "application/xml",
+ "application/javascript",
+ "application/typescript",
+ "application/x-yaml",
+ "application/toml",
+ "application/sql",
+]);
+
+export function isTextType(contentType: string): boolean {
+ if (contentType.startsWith("text/")) return true;
+ if (TEXT_TYPES.has(contentType)) return true;
+ return false;
+}
+
+export function isImageType(contentType: string): boolean {
+ return contentType.startsWith("image/");
+}
+
+export function isPreviewable(artifact: Artifact): boolean {
+ return isTextType(artifact.content_type) || isImageType(artifact.content_type);
+}
+
+export function getArtifactUrl(id: string, workspaceId: string, download?: boolean): string {
+ const params = new URLSearchParams({ workspace_id: workspaceId });
+ if (download) params.set("download", "1");
+ return `/api/artifacts/${id}/content?${params}`;
+}
+
+function isMarkdown(filename: string): boolean {
+ return /\.md$/i.test(filename);
+}
+
+interface ArtifactContentRendererProps {
+ artifact: Artifact;
+ workspaceId: string;
+}
+
+export function ArtifactContentRenderer({ artifact, workspaceId }: ArtifactContentRendererProps) {
+ const [content, setContent] = useState<string | null>(null);
+ const [loading, setLoading] = useState(false);
+
+ const url = getArtifactUrl(artifact.id, workspaceId);
+
+ useEffect(() => {
+ if (isTextType(artifact.content_type)) {
+ setLoading(true);
+ setContent(null);
+ getArtifactContent(artifact.id, workspaceId)
+ .then(setContent)
+ .catch(() => setContent("(failed to load content)"))
+ .finally(() => setLoading(false));
+ }
+ }, [artifact.id, artifact.content_type, workspaceId]);
+
+ if (loading) {
+ return (
+ <div className="flex justify-center py-8">
+ <Loader2 className="size-5 animate-spin text-muted-foreground" />
+ </div>
+ );
+ }
+
+ if (isImageType(artifact.content_type)) {
+ return (
+ <div className="flex justify-center">
+ <img
+ src={url}
+ alt={artifact.filename}
+ className="max-w-full rounded-md"
+ />
+ </div>
+ );
+ }
+
+ if (isTextType(artifact.content_type)) {
+ if (isMarkdown(artifact.filename)) {
+ return (
+ <div className="markdown text-sm">
+ <Streamdown>{content ?? ""}</Streamdown>
+ </div>
+ );
+ }
+ return (
+ <pre className="whitespace-pre-wrap text-sm font-mono text-foreground">{content}</pre>
+ );
+ }
+
+ return (
+ <div className="flex flex-col items-center gap-3 py-8 text-center">
+ <p className="text-sm text-muted-foreground">
+ This file type cannot be previewed.
+ </p>
+ <a
+ href={getArtifactUrl(artifact.id, workspaceId, true)}
+ download={artifact.filename}
+ className="inline-flex items-center gap-1.5 rounded-md border border-input bg-background px-3 py-1.5 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-colors"
+ >
+ <Download className="size-3.5" />
+ Download
+ </a>
+ </div>
+ );
+}
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index 527064d3f..51e8d5d06 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -1,6 +1,7 @@
import type {
Agent,
AgentRuntime,
+ Artifact,
CalendarEvent,
Conversation,
CreateAgentRequest,
@@ -330,6 +331,17 @@ export const removeWhitelistEmail = (agentId: string, whitelistId: string, works
method: "DELETE",
});
+// Artifacts
+export const listArtifacts = (conversationId: string, workspaceId: string) =>
+ apiFetch<Artifact[]>(`/api/artifacts${wsQuery(workspaceId, { conversation_id: conversationId })}`);
+
+export const getArtifactContent = async (id: string, workspaceId: string): Promise<string> => {
+ const params = new URLSearchParams({ workspace_id: workspaceId });
+ const res = await fetch(`/api/artifacts/${id}/content?${params}`, { credentials: "include" });
+ if (!res.ok) return "(content not available)";
+ return res.text();
+};
+
// Auth (Better Auth — redirect helpers only, actual auth via Better Auth client)
export const signOut = async () => {
if (typeof window !== "undefined") {