Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add attachment

Gusa2d75d2c6370
diff --git a/src/cli/daemon/client.ts b/src/cli/daemon/client.ts
index ccbf6a248..41dc104d4 100644
--- a/src/cli/daemon/client.ts
+++ b/src/cli/daemon/client.ts
@@ -105,6 +105,33 @@ export class DaemonClient {
});
}
+ async getArtifactMeta(
+ token: string,
+ artifactId: string,
+ workspaceId: string,
+ ): Promise<{ id: string; filename: string; content_type: string; size: number }> {
+ return this.request(
+ "GET",
+ `/api/artifacts/${artifactId}?workspace_id=${encodeURIComponent(workspaceId)}`,
+ token,
+ );
+ }
+
+ async downloadArtifact(
+ token: string,
+ artifactId: string,
+ workspaceId: string,
+ ): Promise<ArrayBuffer> {
+ const res = await fetch(
+ `${this.baseURL}/api/artifacts/${artifactId}/content?workspace_id=${encodeURIComponent(workspaceId)}`,
+ { headers: { Authorization: `Bearer ${token}` } },
+ );
+ if (!res.ok) {
+ throw new Error(`artifact download failed: HTTP ${res.status}`);
+ }
+ return res.arrayBuffer();
+ }
+
reportMessages(
token: string,
taskId: string,
diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.ts
index 8a5a89205..7235dddfb 100644
--- a/src/cli/daemon/execenv/context.ts
+++ b/src/cli/daemon/execenv/context.ts
@@ -118,6 +118,11 @@ Upload files for your owner to review in the app.
- 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.
---
+
+### Attachments
+When your task includes attachments, their local paths are listed in the prompt JSON under "attachments".
+Use your Read tool to open them. Images and PDFs are read visually.
+---
`;
content += `\n### Calendar
diff --git a/src/cli/daemon/prompt.ts b/src/cli/daemon/prompt.ts
index a25d3fe0a..5ea91338f 100644
--- a/src/cli/daemon/prompt.ts
+++ b/src/cli/daemon/prompt.ts
@@ -1,5 +1,13 @@
-import type { Task } from "./types.js";
+import type { Task, Attachment } from "./types.js";
-export function buildPrompt(task: Task): string {
- return JSON.stringify({ type: task.type, instruction: task.prompt });
+export function buildPrompt(task: Task, attachments?: Attachment[]): string {
+ const obj: Record<string, unknown> = { type: task.type, instruction: task.prompt };
+ if (attachments && attachments.length > 0) {
+ obj.attachments = attachments.map((a) => ({
+ path: a.path,
+ content_type: a.content_type,
+ filename: a.filename,
+ }));
+ }
+ return JSON.stringify(obj);
}
diff --git a/src/cli/daemon/session-runner.test.ts b/src/cli/daemon/session-runner.test.ts
index 3932f3b24..d8fc4e67a 100644
--- a/src/cli/daemon/session-runner.test.ts
+++ b/src/cli/daemon/session-runner.test.ts
@@ -176,6 +176,7 @@ describe("session-runner runSession", () => {
expect(buildPrompt).toHaveBeenCalledWith(
expect.objectContaining({ id: "t1", prompt: "do the thing" }),
+ undefined,
);
});
diff --git a/src/cli/daemon/session-runner.ts b/src/cli/daemon/session-runner.ts
index 3431e38f2..fbf47c245 100644
--- a/src/cli/daemon/session-runner.ts
+++ b/src/cli/daemon/session-runner.ts
@@ -7,6 +7,8 @@
*/
import { createWriteStream } from "fs";
+import { mkdir, writeFile, rm } from "fs/promises";
+import path from "path";
import { DaemonClient } from "./client.js";
import { createBackend } from "./agent/index.js";
import { prepare } from "./execenv/index.js";
@@ -19,20 +21,76 @@ import {
} from "./execenv/timeline.js";
import { buildPrompt } from "./prompt.js";
import { log } from "../lib/logger.js";
-import type { SessionRunnerInput } from "./types.js";
+import type { SessionRunnerInput, Attachment } from "./types.js";
+
+const ATTACHMENTS_BASE = "/tmp/alook-attachments";
+
+function sanitizeFilename(name: string): string {
+ return path.basename(name).replace(/[/\\]/g, "_").replace(/\.\./g, "_").slice(0, 255) || "file";
+}
+
+async function cleanupAttachments(taskId: string): Promise<void> {
+ try {
+ await rm(path.join(ATTACHMENTS_BASE, taskId), { recursive: true, force: true });
+ } catch {
+ // best-effort
+ }
+}
+
+async function downloadAttachments(
+ client: DaemonClient,
+ token: string,
+ workspaceId: string,
+ taskId: string,
+ attachmentIds: string[],
+): Promise<Attachment[]> {
+ const dir = path.join(ATTACHMENTS_BASE, taskId);
+ await mkdir(dir, { recursive: true });
+
+ const attachments: Attachment[] = [];
+ for (const artId of attachmentIds) {
+ const meta = await client.getArtifactMeta(token, artId, workspaceId);
+ const content = await client.downloadArtifact(token, artId, workspaceId);
+ const filename = sanitizeFilename(meta.filename);
+ const localPath = path.join(dir, `${artId}_${filename}`);
+ await writeFile(localPath, Buffer.from(content));
+ attachments.push({
+ path: localPath,
+ content_type: meta.content_type,
+ filename: meta.filename,
+ });
+ }
+ return attachments;
+}
export async function runSession(input: SessionRunnerInput): Promise<void> {
const { task, provider, cliPath, model, serverURL, token, workspacesRoot, agentTimeout } = input;
const client = new DaemonClient(serverURL);
const backend = createBackend(provider, cliPath);
- const prompt = buildPrompt(task);
const { workDir, logFile, timelineDir, env } = prepare(
{ workspacesRoot },
task,
);
+ // Download attachments before building prompt
+ const attachmentIds = (task.context?.attachment_ids as string[]) ?? [];
+ let attachments: Attachment[] | undefined;
+ if (attachmentIds.length > 0) {
+ try {
+ attachments = await downloadAttachments(client, token, task.workspaceId, task.id, attachmentIds);
+ } catch (e) {
+ await cleanupAttachments(task.id);
+ const errMsg = `failed to download attachments: ${e}`;
+ log.error(`Task ${task.id} ${errMsg}`);
+ await client.failTask(token, task.id, errMsg);
+ return;
+ }
+ }
+
+ const prompt = buildPrompt(task, attachments);
+
const resumeSessionId = task.contextKey
? findResumableSessionByContextKey(timelineDir, task.contextKey, provider) ?? undefined
: undefined;
@@ -117,14 +175,17 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {
try { await flushMessages(); } catch { /* best-effort */ }
logStream?.end();
- // 3. Update timeline — status "killed"
+ // 3. Cleanup attachments
+ await cleanupAttachments(task.id);
+
+ // 4. Update timeline — status "killed"
updateEntry(timelineDir, task.id, (entry) => {
entry.pid = null;
entry.status = "killed";
entry.errmsg = "killed by signal";
});
- // 4. Report to server
+ // 5. Report to server
try {
await client.failTask(token, task.id, "killed by signal");
} catch { /* best-effort */ }
@@ -196,6 +257,9 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {
if (killed) return;
+ // Cleanup attachments after task completion
+ await cleanupAttachments(task.id);
+
// Timeline — finalize entry
if (result.status === "completed") {
updateEntry(timelineDir, task.id, (entry) => {
@@ -250,6 +314,7 @@ async function main(): Promise<void> {
await runSession(input);
} catch (e) {
log.error(`session-runner: unhandled error for task ${input.task.id}`, e);
+ await cleanupAttachments(input.task.id);
try {
await client.failTask(input.token, input.task.id, `session-runner crash: ${e}`);
} catch {
diff --git a/src/cli/daemon/types.ts b/src/cli/daemon/types.ts
index caa545683..c577549f1 100644
--- a/src/cli/daemon/types.ts
+++ b/src/cli/daemon/types.ts
@@ -9,11 +9,18 @@ export interface Task {
priority: number;
type: string;
contextKey?: string | null;
+ context?: Record<string, unknown>;
agent?: TaskAgentData;
repos?: RepoData[];
createdAt: string;
}
+export interface Attachment {
+ path: string;
+ content_type: string;
+ filename: string;
+}
+
export interface TaskAgentData {
id?: string;
name: string;
@@ -103,6 +110,7 @@ export function fromApiTask(api: import("@alook/shared").TaskApi): Task {
priority: api.priority,
type: api.type,
contextKey: api.context_key ?? null,
+ context: (api.context as Record<string, unknown>) ?? undefined,
agent: api.agent
? { name: api.agent.name, instructions: api.agent.instructions, emailHandle: api.agent.email_handle ?? undefined, userEmail: api.agent.user_email ?? undefined, runtimeConfig: api.agent.runtime_config ?? undefined }
: undefined,
diff --git a/src/shared/src/db/queries/artifact.ts b/src/shared/src/db/queries/artifact.ts
index a85c0d96c..1dea3b649 100644
--- a/src/shared/src/db/queries/artifact.ts
+++ b/src/shared/src/db/queries/artifact.ts
@@ -14,6 +14,7 @@ export async function createArtifact(
contentType: string;
size: number;
r2Key: string;
+ source?: string;
}
) {
const rows = await db.insert(artifact).values(data).returning();
@@ -23,17 +24,20 @@ export async function createArtifact(
export async function listArtifactsByConversation(
db: Database,
conversationId: string,
- workspaceId: string
+ workspaceId: string,
+ opts?: { source?: string },
) {
+ const conditions = [
+ eq(artifact.conversationId, conversationId),
+ eq(artifact.workspaceId, workspaceId),
+ ];
+ if (opts?.source) {
+ conditions.push(eq(artifact.source, opts.source));
+ }
return db
.select()
.from(artifact)
- .where(
- and(
- eq(artifact.conversationId, conversationId),
- eq(artifact.workspaceId, workspaceId)
- )
- )
+ .where(and(...conditions))
.orderBy(desc(artifact.createdAt));
}
@@ -53,6 +57,7 @@ export function artifactToResponse(row: typeof artifact.$inferSelect): Artifact
filename: row.filename,
content_type: row.contentType,
size: row.size,
+ source: row.source,
created_at: row.createdAt,
};
}
diff --git a/src/shared/src/db/queries/message.ts b/src/shared/src/db/queries/message.ts
index 07ede1f57..eb69f438e 100644
--- a/src/shared/src/db/queries/message.ts
+++ b/src/shared/src/db/queries/message.ts
@@ -9,6 +9,7 @@ export async function createMessage(
role: string;
content: string;
taskId?: string | null;
+ attachmentIds?: string | null;
}
) {
const rows = await db
@@ -18,6 +19,7 @@ export async function createMessage(
role: data.role,
content: data.content,
taskId: data.taskId ?? null,
+ attachmentIds: data.attachmentIds ?? null,
})
.returning();
return rows[0]!;
diff --git a/src/shared/src/db/queries/task.ts b/src/shared/src/db/queries/task.ts
index cd3c0db79..9a94a957f 100644
--- a/src/shared/src/db/queries/task.ts
+++ b/src/shared/src/db/queries/task.ts
@@ -15,6 +15,7 @@ export async function createTask(
type?: string;
contextKey?: string | null;
priority?: number;
+ context?: Record<string, unknown>;
}
) {
const rows = await db
@@ -28,6 +29,7 @@ export async function createTask(
type: data.type ?? TASK_TYPES.USER_DM_MESSAGE,
contextKey: data.contextKey ?? null,
priority: data.priority ?? 0,
+ context: data.context ?? undefined,
})
.returning();
return rows[0]!;
diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.ts
index 1e8b5b68b..2f4b875b0 100644
--- a/src/shared/src/db/schema.ts
+++ b/src/shared/src/db/schema.ts
@@ -210,6 +210,7 @@ export const message = sqliteTable("message", {
role: text("role").notNull(),
content: text("content").notNull().default(""),
taskId: text("task_id"),
+ attachmentIds: text("attachment_ids"),
createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
});
@@ -343,6 +344,7 @@ export const artifact = sqliteTable(
contentType: text("content_type").notNull().default("application/octet-stream"),
size: integer("size").notNull(),
r2Key: text("r2_key").notNull(),
+ source: text("source").notNull().default("agent"),
createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
},
(t) => [
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index e9efbca42..b23306077 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -74,6 +74,7 @@ export const TaskApiBaseSchema = z.object({
created_at: z.string(),
type: z.string(),
context_key: z.string().nullable().optional(),
+ context: z.unknown().nullable().optional(),
});
export type TaskApiBase = z.infer<typeof TaskApiBaseSchema>;
diff --git a/src/shared/src/types.ts b/src/shared/src/types.ts
index 4043dc7b6..fc7e271ac 100644
--- a/src/shared/src/types.ts
+++ b/src/shared/src/types.ts
@@ -82,6 +82,7 @@ export interface Message {
role: "user" | "assistant";
content: string;
task_id: string | null;
+ attachment_ids: string[] | null;
created_at: string;
}
@@ -145,6 +146,7 @@ export interface Artifact {
filename: string;
content_type: string;
size: number;
+ source: string;
created_at: string;
}
diff --git a/src/web/migrations/0003_message_attachments.sql b/src/web/migrations/0003_message_attachments.sql
new file mode 100644
index 000000000..b63a79a3f
--- /dev/null
+++ b/src/web/migrations/0003_message_attachments.sql
@@ -0,0 +1,2 @@
+ALTER TABLE message ADD COLUMN attachment_ids TEXT;
+ALTER TABLE artifact ADD COLUMN source TEXT NOT NULL DEFAULT 'agent';
\ No newline at end of file
diff --git a/src/web/src/app/api/artifacts/[id]/route.ts b/src/web/src/app/api/artifacts/[id]/route.ts
new file mode 100644
index 000000000..c26029dd9
--- /dev/null
+++ b/src/web/src/app/api/artifacts/[id]/route.ts
@@ -0,0 +1,22 @@
+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 id = ctx.params?.id as string;
+ const { env } = getCloudflareContext();
+ const db = createDb((env as Env).DB);
+
+ const row = await queries.artifact.getArtifact(db, id, ws.workspaceId);
+ if (!row) {
+ return writeError("artifact not found", 404);
+ }
+
+ return writeJSON(queries.artifact.artifactToResponse(row));
+});
diff --git a/src/web/src/app/api/artifacts/route.ts b/src/web/src/app/api/artifacts/route.ts
index 035c3943a..930acaf98 100644
--- a/src/web/src/app/api/artifacts/route.ts
+++ b/src/web/src/app/api/artifacts/route.ts
@@ -20,7 +20,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const rows = await queries.artifact.listArtifactsByConversation(
db,
conversationId,
- ws.workspaceId
+ ws.workspaceId,
);
return writeJSON(rows.map(queries.artifact.artifactToResponse));
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 301f659de..c81479400 100644
--- a/src/web/src/app/api/conversations/[id]/messages/route.ts
+++ b/src/web/src/app/api/conversations/[id]/messages/route.ts
@@ -1,6 +1,7 @@
import { NextRequest } from "next/server";
import { getCloudflareContext } from "@opennextjs/cloudflare"
import { createDb, queries, TASK_TYPES, buildContextKey } 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";
@@ -9,6 +10,9 @@ import { TaskService } from "@/lib/services/task";
import { log } from "@/lib/logger";
import { broadcastToUser } from "@/lib/broadcast";
+const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
+const MAX_FILES = 10;
+
function truncateTitle(text: string, maxLen = 50): string {
const trimmed = text.replace(/\s+/g, " ").trim();
if (trimmed.length <= maxLen) return trimmed;
@@ -18,6 +22,10 @@ function truncateTitle(text: string, maxLen = 50): string {
return title + "...";
}
+function sanitizeFilename(name: string): string {
+ return name.replace(/[/\\]/g, "_").replace(/\.\./g, "_").slice(0, 255) || "file";
+}
+
export const GET = withAuth(async (req, ctx) => {
const ws = await withWorkspaceMember(req, ctx);
if (ws instanceof Response) return ws;
@@ -51,33 +59,93 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const { env } = getCloudflareContext()
const db = createDb((env as Env).DB)
+ const bucket = (env as Env).EMAIL_BUCKET;
const id = ctx.params?.id;
if (!id) {
return writeError("conversation id is required", 400);
}
- let body: { content?: string };
- try {
- body = await req.json();
- } catch {
- return writeError("invalid request body", 400);
+ const contentType = req.headers.get("content-type") ?? "";
+ const isMultipart = contentType.includes("multipart/form-data");
+
+ let content: string;
+ let files: File[] = [];
+
+ if (isMultipart) {
+ let formData: FormData;
+ try {
+ formData = await req.formData();
+ } catch {
+ return writeError("invalid form data", 400);
+ }
+ content = (formData.get("content") as string) || "";
+ for (const [key, value] of formData.entries()) {
+ if (key === "file" && value instanceof File) {
+ files.push(value);
+ }
+ }
+ } else {
+ let body: { content?: string };
+ try {
+ body = await req.json();
+ } catch {
+ return writeError("invalid request body", 400);
+ }
+ content = body.content || "";
}
- const content = body.content || "";
if (!content) {
return writeError("content is required", 400);
}
+ // Validate files before any uploads
+ if (files.length > MAX_FILES) {
+ return writeError(`too many files (max ${MAX_FILES})`, 400);
+ }
+ for (const file of files) {
+ if (file.size > MAX_FILE_SIZE) {
+ return writeError(`file "${file.name}" exceeds 10 MB limit`, 413);
+ }
+ }
+
const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);
if (!conversation) {
return writeError("conversation not found", 404);
}
+ // Upload files to R2 and create artifact rows
+ const artifactIds: string[] = [];
+ for (const file of files) {
+ const filename = sanitizeFilename(file.name);
+ const fileContentType = file.type || "application/octet-stream";
+ const artifactId = "art_" + nanoid();
+ const r2Key = `artifacts/${ws.workspaceId}/${conversation.agentId}/${id}/${artifactId}/${filename}`;
+
+ await bucket.put(r2Key, await file.arrayBuffer(), {
+ httpMetadata: { contentType: fileContentType },
+ });
+
+ await queries.artifact.createArtifact(db, {
+ id: artifactId,
+ conversationId: id,
+ agentId: conversation.agentId,
+ workspaceId: ws.workspaceId,
+ filename,
+ contentType: fileContentType,
+ size: file.size,
+ r2Key,
+ source: "attachment",
+ });
+
+ artifactIds.push(artifactId);
+ }
+
const message = await queries.message.createMessage(db, {
conversationId: id,
role: "user",
content,
+ attachmentIds: artifactIds.length > 0 ? JSON.stringify(artifactIds) : null,
});
// Auto-title: conditional WHERE title = '' ensures only the first message sets it
@@ -92,7 +160,10 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
ws.workspaceId,
content,
TASK_TYPES.USER_DM_MESSAGE,
- { contextKey },
+ {
+ contextKey,
+ context: artifactIds.length > 0 ? { attachment_ids: artifactIds } : undefined,
+ },
);
broadcastToUser(ctx.userId, { type: "task.updated", taskId: task.id, status: "queued" }).catch(() => {});
return writeJSON(
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 094626365..826c02c53 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -20,7 +20,7 @@ import { useAgentContext } from "@/contexts/agent-context";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";
-import { ArrowUp, Box, FileText, Loader2, RotateCcw } from "lucide-react";
+import { ArrowUp, Box, FileText, Loader2, Paperclip, RotateCcw, X } from "lucide-react";
import { ArtifactSheet, formatSize } from "@/components/agent-chat/artifact-sheet";
import { isPreviewable, getArtifactUrl } from "@/components/artifact-content-renderer";
import {
@@ -34,6 +34,7 @@ import {
import { Streamdown } from "streamdown";
const MESSAGE_LIMIT = 20;
+const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
/** Sort messages by (created_at, id) ascending — guarantees chronological order. */
export function sortMessages(msgs: Message[]): Message[] {
@@ -88,6 +89,63 @@ function ArtifactCard({ artifact, onClick }: { artifact: Artifact; onClick: (a:
);
}
+function AttachmentChips({
+ attachmentIds,
+ artifacts,
+ onArtifactClick,
+}: {
+ attachmentIds: string[];
+ artifacts: Artifact[];
+ onArtifactClick: (a: Artifact) => void;
+}) {
+ const matched = attachmentIds
+ .map((id) => artifacts.find((a) => a.id === id))
+ .filter((a): a is Artifact => !!a);
+
+ if (matched.length === 0) return null;
+
+ return (
+ <div className="flex flex-wrap gap-1.5 mt-1.5">
+ {matched.map((a) => (
+ <button
+ key={a.id}
+ type="button"
+ onClick={(e) => { e.stopPropagation(); onArtifactClick(a); }}
+ className="inline-flex items-center gap-1 rounded-md bg-primary-foreground/10 border border-primary-foreground/20 px-2 py-0.5 text-xs text-primary-foreground/80 hover:bg-primary-foreground/20 transition-colors cursor-pointer"
+ >
+ <FileText className="size-3 shrink-0" />
+ <span className="truncate max-w-[150px]">{a.filename}</span>
+ </button>
+ ))}
+ </div>
+ );
+}
+
+function PendingFileChips({
+ pendingFiles,
+ messageId,
+}: {
+ pendingFiles: Map<string, File[]>;
+ messageId: string;
+}) {
+ const files = pendingFiles.get(messageId);
+ if (!files || files.length === 0) return null;
+
+ return (
+ <div className="flex flex-wrap gap-1.5 mt-1.5">
+ {files.map((f, i) => (
+ <span
+ key={i}
+ className="inline-flex items-center gap-1 rounded-md bg-primary-foreground/10 border border-primary-foreground/20 px-2 py-0.5 text-xs text-primary-foreground/80"
+ >
+ <FileText className="size-3 shrink-0" />
+ <span className="truncate max-w-[150px]">{f.name}</span>
+ </span>
+ ))}
+ </div>
+ );
+}
+
export function AgentChatView() {
const params = useParams();
const { workspaceId } = useWorkspace();
@@ -110,8 +168,13 @@ export function AgentChatView() {
const [artifacts, setArtifacts] = useState<Artifact[]>([]);
const [artifactSheetOpen, setArtifactSheetOpen] = useState(false);
const [selectedArtifact, setSelectedArtifact] = useState<Artifact | null>(null);
+ const [pendingFiles, setPendingFiles] = useState<File[]>([]);
+
+ const pendingFilesMapRef = useRef<Map<string, File[]>>(new Map());
- const timeline = useMemo(() => buildTimeline(messages, artifacts), [messages, artifacts]);
+ const agentArtifacts = useMemo(() => artifacts.filter((a) => a.source === "agent"), [artifacts]);
+
+ const timeline = useMemo(() => buildTimeline(messages, agentArtifacts), [messages, agentArtifacts]);
const handleArtifactClick = useCallback((artifact: Artifact) => {
if (isPreviewable(artifact)) {
@@ -130,6 +193,7 @@ export function AgentChatView() {
const loadingMoreRef = useRef(false);
const isNearBottom = useRef(true);
const startPollingRef = useRef<(taskId: string, conversationId: string, initialSeq?: number) => void>(null!);
+ const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
const key = `chat-draft:${agentId}`;
@@ -316,12 +380,19 @@ export function AgentChatView() {
// Keep taskMessages so the trace stays visible under the completed assistant reply.
const latest = await listMessages(conversationId, workspaceId);
setMessages((prev) => mergeMessages(prev, latest));
- requestAnimationFrame(() => {
- scrollRef.current?.scrollTo({
- top: scrollRef.current.scrollHeight,
- behavior: "instant",
+ // Refresh artifacts to pick up any new ones from the completed task
+ try {
+ const arts = await listArtifacts(conversationId, workspaceId);
+ setArtifacts(arts);
+ } catch { /* best-effort */ }
+ if (isNearBottom.current) {
+ requestAnimationFrame(() => {
+ scrollRef.current?.scrollTo({
+ top: scrollRef.current.scrollHeight,
+ behavior: "smooth",
+ });
});
- });
+ }
} catch {
toast.error("Failed to refresh messages");
}
@@ -378,35 +449,132 @@ export function AgentChatView() {
});
}, [subscribeWs, conversation?.id]);
+ const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
+ const fileList = e.target.files;
+ if (!fileList) return;
+
+ const valid: File[] = [];
+ for (const file of Array.from(fileList)) {
+ if (file.size > MAX_FILE_SIZE) {
+ toast.error(`"${file.name}" exceeds 10 MB limit`);
+ } else {
+ valid.push(file);
+ }
+ }
+ if (valid.length > 0) {
+ setPendingFiles((prev) => [...prev, ...valid]);
+ }
+ // Reset input so re-selecting the same file works
+ e.target.value = "";
+ }, []);
+
+ const removePendingFile = useCallback((index: number) => {
+ setPendingFiles((prev) => prev.filter((_, i) => i !== index));
+ }, []);
+
+ const [dragging, setDragging] = useState(false);
+ const dragCounter = useRef(0);
+
+ const handleDragEnter = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ dragCounter.current++;
+ if (e.dataTransfer.types.includes("Files")) {
+ setDragging(true);
+ }
+ }, []);
+
+ const handleDragLeave = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ dragCounter.current--;
+ if (dragCounter.current === 0) {
+ setDragging(false);
+ }
+ }, []);
+
+ const handleDragOver = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }, []);
+
+ const handleDrop = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setDragging(false);
+ dragCounter.current = 0;
+
+ const droppedFiles = Array.from(e.dataTransfer.files);
+ const valid: File[] = [];
+ for (const file of droppedFiles) {
+ if (file.size > MAX_FILE_SIZE) {
+ toast.error(`"${file.name}" exceeds 10 MB limit`);
+ } else {
+ valid.push(file);
+ }
+ }
+ if (valid.length > 0) {
+ setPendingFiles((prev) => [...prev, ...valid]);
+ }
+ }, []);
+
const handleSend = async () => {
const content = input.trim();
- if (!content || sending || !conversation) return;
+ if ((!content && pendingFiles.length === 0) || sending || !conversation) return;
+ if (!content) {
+ toast.error("Please type a message");
+ return;
+ }
+ const filesToSend = [...pendingFiles];
setInput("");
+ setPendingFiles([]);
setSending(true);
+ const optimisticId = `temp-${Date.now()}`;
const optimistic: Message = {
- id: `temp-${Date.now()}`,
+ id: optimisticId,
conversation_id: conversation.id,
role: "user",
content,
task_id: null,
+ attachment_ids: null,
created_at: new Date().toISOString(),
};
+
+ // Store pending files for the optimistic message rendering
+ if (filesToSend.length > 0) {
+ pendingFilesMapRef.current.set(optimisticId, filesToSend);
+ }
+
setMessages((prev) => [...prev, optimistic]);
scrollToBottom();
try {
- const { message, task } = await sendMessage(conversation.id, content, workspaceId);
+ const { message, task } = await sendMessage(
+ conversation.id,
+ content,
+ workspaceId,
+ filesToSend.length > 0 ? filesToSend : undefined,
+ );
+ // Clean up pending files ref
+ pendingFilesMapRef.current.delete(optimisticId);
setMessages((prev) =>
prev.map((m) => (m.id === optimistic.id ? message : m))
);
+ if (message.attachment_ids && message.attachment_ids.length > 0) {
+ listArtifacts(conversation.id, workspaceId)
+ .then((arts) => setArtifacts(arts))
+ .catch(() => {});
+ }
setActiveTask(task);
setTaskMessages([]);
startPolling(task.id, conversation.id);
} catch (err) {
+ pendingFilesMapRef.current.delete(optimisticId);
setMessages((prev) => prev.filter((m) => m.id !== optimistic.id));
setInput(content);
+ setPendingFiles(filesToSend);
toast.error(
err instanceof Error ? err.message : "Failed to send message"
);
@@ -436,6 +604,8 @@ export function AgentChatView() {
setActiveTask(null);
setTaskMessages([]);
setArtifacts([]);
+ setPendingFiles([]);
+ pendingFilesMapRef.current.clear();
lastSeqRef.current = 0;
setConnectionLost(false);
setHasMore(false);
@@ -466,6 +636,8 @@ export function AgentChatView() {
}
};
+ const isTaskActive = !!activeTask && activeTask.status !== "completed" && activeTask.status !== "failed";
+
if (loading) {
return (
<>
@@ -572,6 +744,12 @@ export function AgentChatView() {
<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}
+ {msg.attachment_ids && msg.attachment_ids.length > 0 && (
+ <AttachmentChips attachmentIds={msg.attachment_ids} artifacts={artifacts} onArtifactClick={handleArtifactClick} />
+ )}
+ {!msg.attachment_ids && (
+ <PendingFileChips pendingFiles={pendingFilesMapRef.current} messageId={msg.id} />
+ )}
</div>
</div>
) : !hasTaskStream ? (
@@ -603,22 +781,56 @@ export function AgentChatView() {
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"
+ (sending || isTaskActive) && "opacity-50",
+ dragging && "border-ring ring-3 ring-ring/50"
)}
+ onDragEnter={handleDragEnter}
+ onDragLeave={handleDragLeave}
+ onDragOver={handleDragOver}
+ onDrop={handleDrop}
>
+ {dragging && (
+ <div className="absolute inset-0 z-10 flex items-center justify-center rounded-xl bg-background/80 border-2 border-dashed border-ring pointer-events-none">
+ <p className="text-sm text-muted-foreground font-medium">Drop files here</p>
+ </div>
+ )}
<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")}
+ disabled={sending || isTaskActive}
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] thin-scrollbar"
)}
/>
+
+ {/* Pending file pills */}
+ {pendingFiles.length > 0 && (
+ <div className="flex flex-wrap gap-1.5 px-3.5 pb-1">
+ {pendingFiles.map((file, i) => (
+ <span
+ key={`${file.name}-${i}`}
+ className="inline-flex items-center gap-1.5 rounded-md bg-muted px-2 py-1 text-xs text-muted-foreground"
+ >
+ <FileText className="size-3 shrink-0" />
+ <span className="truncate max-w-[120px]">{file.name}</span>
+ <span className="text-muted-foreground/60">{formatSize(file.size)}</span>
+ <button
+ type="button"
+ onClick={() => removePendingFile(i)}
+ className="ml-0.5 rounded-sm p-0.5 hover:bg-muted-foreground/20 transition-colors"
+ >
+ <X className="size-3" />
+ </button>
+ </span>
+ ))}
+ </div>
+ )}
+
<div className="flex items-center justify-between px-2 pb-2 pt-0.5">
<div className="flex items-center gap-1">
<Button
@@ -643,28 +855,47 @@ export function AgentChatView() {
title="View artifacts"
>
<Box className="size-3.5" />
- {artifacts.length > 0 && (
+ {agentArtifacts.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}
+ {agentArtifacts.length}
</span>
)}
</Button>
</div>
- <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 className="flex items-center gap-1">
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ className="hidden"
+ onChange={handleFileSelect}
+ />
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => fileInputRef.current?.click()}
+ disabled={sending || isTaskActive}
+ className="rounded-lg text-muted-foreground/60 hover:text-foreground transition-colors duration-200"
+ title="Attach files"
+ >
+ <Paperclip className="size-3.5" />
+ </Button>
+ <Button
+ size="icon-sm"
+ onClick={handleSend}
+ disabled={!input.trim() || sending || isTaskActive}
+ 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>
@@ -716,9 +947,9 @@ export function AgentChatView() {
open={artifactSheetOpen}
onOpenChange={(v) => {
setArtifactSheetOpen(v);
- if (!v) setSelectedArtifact(null);
+ if (!v) setTimeout(() => setSelectedArtifact(null), 300);
}}
- artifacts={artifacts}
+ artifacts={agentArtifacts}
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
index f73e32890..a8fcd1669 100644
--- a/src/web/src/components/agent-chat/artifact-sheet.tsx
+++ b/src/web/src/components/agent-chat/artifact-sheet.tsx
@@ -44,10 +44,11 @@ export function ArtifactSheet({ open, onOpenChange, artifacts, workspaceId, init
}, [open, initialArtifact]);
const handleOpenChange = (v: boolean) => {
+ onOpenChange(v);
if (!v) {
- setSelectedArtifact(null);
+ // Defer clearing selected artifact until sheet closing animation completes
+ setTimeout(() => setSelectedArtifact(null), 300);
}
- onOpenChange(v);
};
const onPointerDown = useCallback((e: React.PointerEvent) => {
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index 51e8d5d06..0b85db8f6 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -178,14 +178,63 @@ export const listMessages = (
);
};
-export const sendMessage = (conversationId: string, content: string, workspaceId: string) =>
- apiFetch<{ message: Message; task: TaskApi }>(
- `/api/conversations/${conversationId}/messages${wsQuery(workspaceId)}`,
- {
- method: "POST",
- body: JSON.stringify({ content }),
+export const sendMessage = async (
+ conversationId: string,
+ content: string,
+ workspaceId: string,
+ files?: File[],
+): Promise<{ message: Message; task: TaskApi }> => {
+ if (!files || files.length === 0) {
+ return apiFetch<{ message: Message; task: TaskApi }>(
+ `/api/conversations/${conversationId}/messages${wsQuery(workspaceId)}`,
+ {
+ method: "POST",
+ body: JSON.stringify({ content }),
+ },
+ );
+ }
+
+ const fd = new FormData();
+ fd.append("content", content);
+ for (const file of files) {
+ fd.append("file", file);
+ }
+
+ let res: Response;
+ try {
+ res = await fetch(
+ `/api/conversations/${conversationId}/messages${wsQuery(workspaceId)}`,
+ { method: "POST", credentials: "include", body: fd },
+ );
+ } catch (err) {
+ if (err instanceof TypeError) {
+ throw new ApiError("Unable to connect — check your network", 0);
}
- );
+ throw err;
+ }
+
+ if (res.status === 401) {
+ if (typeof window !== "undefined") window.location.href = "/sign-in";
+ throw new ApiError("Unauthorized", 401);
+ }
+
+ if (!res.ok) {
+ let serverError: string | undefined;
+ let details: string[] | undefined;
+ try {
+ const body = (await res.json()) as { error?: string; details?: string[] };
+ serverError = body.error;
+ details = body.details;
+ } catch {
+ // non-JSON body
+ }
+ if (res.status === 429) throw new ApiError("Please wait a moment before trying again", 429);
+ if (res.status >= 500) throw new ApiError(serverError || "Something went wrong — please try again", res.status, details);
+ throw new ApiError(serverError || "Something went wrong", res.status, details);
+ }
+
+ return res.json() as Promise<{ message: Message; task: TaskApi }>;
+};
// Active task for conversation (recovery on page refresh)
export const getActiveTask = (conversationId: string, workspaceId: string) =>
diff --git a/src/web/src/lib/api/responses.test.ts b/src/web/src/lib/api/responses.test.ts
index dcb56cabf..65964785b 100644
--- a/src/web/src/lib/api/responses.test.ts
+++ b/src/web/src/lib/api/responses.test.ts
@@ -254,10 +254,10 @@ describe("taskToResponse Zod validation", () => {
).toThrow();
});
- it("strips context field from output", () => {
- const withContext = { ...validTask, context: { secret: true } };
+ it("preserves context field in output", () => {
+ const withContext = { ...validTask, context: { attachment_ids: ["art_1"] } };
const res = taskToResponse(withContext as any);
- expect("context" in res).toBe(false);
+ expect(res.context).toEqual({ attachment_ids: ["art_1"] });
});
it("produces snake_case keys in output", () => {
@@ -360,7 +360,7 @@ describe("MessageResponse shape", () => {
it("has expected keys: id, conversation_id, role, content, task_id, created_at", () => {
const res = messageToResponse({ id: "m1", conversationId: "c1", role: "user", content: "hi", taskId: "t1", createdAt: ts });
expect(Object.keys(res).sort()).toEqual(
- ["content", "conversation_id", "created_at", "id", "role", "task_id"]
+ ["attachment_ids", "content", "conversation_id", "created_at", "id", "role", "task_id"]
);
});
});
diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.ts
index a65e7363a..42d7f3a1a 100644
--- a/src/web/src/lib/api/responses.ts
+++ b/src/web/src/lib/api/responses.ts
@@ -76,6 +76,7 @@ export function taskToResponse(t: {
prompt: string;
type?: string;
contextKey?: string | null;
+ context?: unknown;
status: string;
priority: number;
dispatchedAt: Date | string | null;
@@ -94,6 +95,7 @@ export function taskToResponse(t: {
prompt: t.prompt,
type: t.type ?? TASK_TYPES.USER_DM_MESSAGE,
context_key: t.contextKey ?? null,
+ context: t.context ?? null,
status: t.status,
priority: t.priority,
dispatched_at: formatTimestampNullable(t.dispatchedAt),
@@ -126,6 +128,7 @@ export function messageToResponse(m: any) {
role: m.role,
content: m.content,
task_id: m.taskId || null,
+ attachment_ids: m.attachmentIds ? JSON.parse(m.attachmentIds) : null,
created_at: formatTimestamp(m.createdAt),
};
}
diff --git a/src/web/src/lib/services/task.ts b/src/web/src/lib/services/task.ts
index 1d849e5cf..46d88cfc7 100644
--- a/src/web/src/lib/services/task.ts
+++ b/src/web/src/lib/services/task.ts
@@ -15,7 +15,7 @@ export class TaskService {
workspaceId: string,
prompt: string,
type: string = TASK_TYPES.USER_DM_MESSAGE,
- opts?: { contextKey?: string | null },
+ opts?: { contextKey?: string | null; context?: Record<string, unknown> },
) {
const agent = await agentQueries.getAgent(this.db, agentId, workspaceId);
if (!agent) {
@@ -34,6 +34,7 @@ export class TaskService {
type,
contextKey: opts?.contextKey ?? null,
priority: 0,
+ context: opts?.context,
});
}