Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: workspace files browser for agents (#36)

Genere3eea0c9879c
diff --git a/src/cli/daemon/client.ts b/src/cli/daemon/client.ts
index 23e268360..98164767a 100644
--- a/src/cli/daemon/client.ts
+++ b/src/cli/daemon/client.ts
@@ -80,7 +80,13 @@ export class DaemonClient {
daemonId: string,
maxTasks: number,
cliVersion?: string,
- ): Promise<{ tasks: TaskApi[]; evicted: boolean; pending_update?: { version: string }; pending_rescan?: boolean }> {
+ ): Promise<{
+ tasks: TaskApi[];
+ evicted: boolean;
+ pending_update?: { version: string };
+ pending_rescan?: boolean;
+ file_requests?: { id: string; agent_id: string; request_type: string; path: string }[];
+ }> {
const raw = await this.request<unknown>(
"POST",
"/api/daemon/tasks/poll",
@@ -93,6 +99,7 @@ export class DaemonClient {
evicted: resp.evicted ?? false,
pending_update: resp.pending_update,
pending_rescan: resp.pending_rescan,
+ file_requests: resp.file_requests,
};
}
@@ -192,6 +199,25 @@ export class DaemonClient {
);
}
+ reportFileData(
+ token: string,
+ body: {
+ request_id: string;
+ entries?: { name: string; path: string; isDirectory: boolean; size: number; modifiedAt: string }[];
+ content?: string | null;
+ isBinary?: boolean;
+ error?: string;
+ path: string;
+ },
+ ) {
+ return this.request(
+ "POST",
+ "/api/daemon/workspace/report",
+ token,
+ body,
+ );
+ }
+
async claimMeetings(
token: string,
daemonId: string,
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.ts
index 464f61c1a..ede7f6432 100644
--- a/src/cli/daemon/daemon.ts
+++ b/src/cli/daemon/daemon.ts
@@ -18,6 +18,7 @@ import {
cleanupStaleIntents,
} from "./execenv/steering.js";
import { TASK_TYPES } from "@alook/shared";
+import { readDirectoryTree, readFileContent, validatePath } from "./workspace-files.js";
import { existsSync, mkdirSync, openSync, closeSync, readdirSync, statSync, unlinkSync } from "fs";
import { readdir, readFile, unlink, stat as fsStat } from "fs/promises";
import { execSync, spawn, type ChildProcess } from "child_process";
@@ -398,7 +399,7 @@ export async function startDaemon(
}
try {
- const { tasks: apiTasks, evicted, pending_update, pending_rescan } = await client.poll(
+ const { tasks: apiTasks, evicted, pending_update, pending_rescan, file_requests } = await client.poll(
ws.token,
config.daemonId,
remaining,
@@ -430,6 +431,14 @@ export async function startDaemon(
activeTasks.delete(task.id);
});
}
+
+ // Handle workspace file browse requests
+ if (file_requests) {
+ for (const req of file_requests) {
+ handleFileRequest(client, config, ws.workspaceId, req, ws.token)
+ .catch((e) => log.debug("File request error", e));
+ }
+ }
} catch (e) {
if (e instanceof Error && e.message.startsWith("HTTP 401")) {
log.warn(`Workspace ${ws.workspaceId} poll returned 401 — will retry next cycle`);
@@ -589,6 +598,38 @@ export function spawnMeetingRunner(input: {
return child;
}
+async function handleFileRequest(
+ client: DaemonClient,
+ config: DaemonConfig,
+ workspaceId: string,
+ req: { id: string; agent_id: string; request_type: string; path: string },
+ token: string,
+): Promise<void> {
+ const agentWorkdir = join(config.workspacesRoot, workspaceId, req.agent_id, "workdir");
+ const resolved = validatePath(agentWorkdir, req.path);
+
+ if (!resolved) {
+ await client.reportFileData(token, { request_id: req.id, error: "invalid path", path: req.path });
+ return;
+ }
+
+ try {
+ if (req.request_type === "tree") {
+ const entries = await readDirectoryTree(resolved, agentWorkdir);
+ await client.reportFileData(token, { request_id: req.id, entries, path: req.path });
+ } else {
+ const { content, isBinary } = await readFileContent(resolved);
+ await client.reportFileData(token, { request_id: req.id, content, isBinary, path: req.path });
+ }
+ } catch (e) {
+ await client.reportFileData(token, {
+ request_id: req.id,
+ error: e instanceof Error ? e.message : String(e),
+ path: req.path,
+ });
+ }
+}
+
async function handleTask(
client: DaemonClient,
config: DaemonConfig,
diff --git a/src/cli/daemon/workspace-files.test.ts b/src/cli/daemon/workspace-files.test.ts
new file mode 100644
index 000000000..41aca5b75
--- /dev/null
+++ b/src/cli/daemon/workspace-files.test.ts
@@ -0,0 +1,155 @@
+import { describe, it, expect, beforeEach, afterEach } from "vitest";
+import { join } from "path";
+import { mkdirSync, writeFileSync, rmSync } from "fs";
+import { tmpdir } from "os";
+import { readDirectoryTree, readFileContent, validatePath } from "./workspace-files";
+
+let workDir: string;
+
+beforeEach(() => {
+ workDir = join(tmpdir(), `alook-test-files-${Date.now()}`);
+ mkdirSync(workDir, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(workDir, { recursive: true, force: true });
+});
+
+describe("validatePath", () => {
+ it("returns resolved path for valid relative path", () => {
+ const result = validatePath(workDir, "memory.md");
+ expect(result).toBe(join(workDir, "memory.md"));
+ });
+
+ it("returns resolved path for nested path", () => {
+ const result = validatePath(workDir, "experiences/workflow.md");
+ expect(result).toBe(join(workDir, "experiences", "workflow.md"));
+ });
+
+ it("returns null for path traversal attempt", () => {
+ expect(validatePath(workDir, "../../../etc/passwd")).toBeNull();
+ });
+
+ it("returns null for absolute path outside workdir", () => {
+ expect(validatePath(workDir, "/tmp/evil")).toBeNull();
+ });
+
+ it("returns the workdir itself for '.'", () => {
+ const result = validatePath(workDir, ".");
+ expect(result).toBe(workDir);
+ });
+});
+
+describe("readDirectoryTree", () => {
+ it("lists files and directories sorted correctly", async () => {
+ mkdirSync(join(workDir, "experiences"));
+ writeFileSync(join(workDir, "memory.md"), "# Memory");
+ writeFileSync(join(workDir, "CLAUDE.md"), "# Instructions");
+
+ const entries = await readDirectoryTree(workDir, workDir);
+
+ expect(entries.length).toBe(3);
+ expect(entries[0].name).toBe("experiences");
+ expect(entries[0].isDirectory).toBe(true);
+ expect(entries[1].name).toBe("CLAUDE.md");
+ expect(entries[1].isDirectory).toBe(false);
+ expect(entries[2].name).toBe("memory.md");
+ });
+
+ it("skips dotfiles except .context_timeline", async () => {
+ mkdirSync(join(workDir, ".git"));
+ mkdirSync(join(workDir, ".context_timeline"));
+ writeFileSync(join(workDir, ".hidden"), "secret");
+ writeFileSync(join(workDir, "visible.md"), "hello");
+
+ const entries = await readDirectoryTree(workDir, workDir);
+ const names = entries.map((e) => e.name);
+
+ expect(names).toContain(".context_timeline");
+ expect(names).toContain("visible.md");
+ expect(names).not.toContain(".git");
+ expect(names).not.toContain(".hidden");
+ });
+
+ it("skips node_modules", async () => {
+ mkdirSync(join(workDir, "node_modules"));
+ writeFileSync(join(workDir, "index.js"), "// ok");
+
+ const entries = await readDirectoryTree(workDir, workDir);
+ const names = entries.map((e) => e.name);
+
+ expect(names).not.toContain("node_modules");
+ expect(names).toContain("index.js");
+ });
+
+ it("returns empty array for non-existent directory", async () => {
+ const entries = await readDirectoryTree(join(workDir, "nope"), workDir);
+ expect(entries).toEqual([]);
+ });
+
+ it("returns relative paths from basePath", async () => {
+ mkdirSync(join(workDir, "sub"));
+ writeFileSync(join(workDir, "sub", "file.txt"), "hi");
+
+ const entries = await readDirectoryTree(join(workDir, "sub"), workDir);
+
+ expect(entries[0].path).toBe(join("sub", "file.txt"));
+ });
+
+ it("includes size and modifiedAt for files", async () => {
+ writeFileSync(join(workDir, "data.json"), '{"key":"value"}');
+
+ const entries = await readDirectoryTree(workDir, workDir);
+ const file = entries.find((e) => e.name === "data.json")!;
+
+ expect(file.size).toBeGreaterThan(0);
+ expect(file.modifiedAt).toBeTruthy();
+ expect(new Date(file.modifiedAt).getTime()).toBeGreaterThan(0);
+ });
+});
+
+describe("readFileContent", () => {
+ it("reads text file content", async () => {
+ writeFileSync(join(workDir, "readme.md"), "# Hello World");
+
+ const result = await readFileContent(join(workDir, "readme.md"));
+
+ expect(result.content).toBe("# Hello World");
+ expect(result.isBinary).toBe(false);
+ });
+
+ it("marks unknown extensions as binary", async () => {
+ writeFileSync(join(workDir, "image.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47]));
+
+ const result = await readFileContent(join(workDir, "image.png"));
+
+ expect(result.content).toBeNull();
+ expect(result.isBinary).toBe(true);
+ });
+
+ it("reads files with known extensions", async () => {
+ for (const ext of [".json", ".ts", ".py", ".yaml", ".sh"]) {
+ writeFileSync(join(workDir, `test${ext}`), "content");
+ const result = await readFileContent(join(workDir, `test${ext}`));
+ expect(result.isBinary).toBe(false);
+ expect(result.content).toBe("content");
+ }
+ });
+
+ it("throws for directories", async () => {
+ mkdirSync(join(workDir, "subdir"));
+ await expect(readFileContent(join(workDir, "subdir"))).rejects.toThrow("Cannot read a directory");
+ });
+
+ it("throws for files over 1MB", async () => {
+ writeFileSync(join(workDir, "big.txt"), "x".repeat(1_048_577));
+ await expect(readFileContent(join(workDir, "big.txt"))).rejects.toThrow("File too large");
+ });
+
+ it("reads extensionless files as text", async () => {
+ writeFileSync(join(workDir, "Makefile"), "all: build");
+ const result = await readFileContent(join(workDir, "Makefile"));
+ expect(result.isBinary).toBe(false);
+ expect(result.content).toBe("all: build");
+ });
+});
diff --git a/src/cli/daemon/workspace-files.ts b/src/cli/daemon/workspace-files.ts
new file mode 100644
index 000000000..dd612560f
--- /dev/null
+++ b/src/cli/daemon/workspace-files.ts
@@ -0,0 +1,85 @@
+import { readdir, stat, readFile } from "fs/promises";
+import { join, resolve, extname, relative } from "path";
+
+const SKIP_DIRS = new Set([".git", "node_modules", ".next", ".wrangler", "__pycache__", ".venv"]);
+
+const TEXT_EXTENSIONS = new Set([
+ ".md", ".txt", ".json", ".js", ".ts", ".tsx", ".jsx",
+ ".py", ".rb", ".go", ".rs", ".toml", ".yaml", ".yml",
+ ".html", ".css", ".scss", ".sh", ".bash", ".zsh",
+ ".env", ".cfg", ".ini", ".xml", ".svg", ".sql",
+ ".jsonl", ".log", ".csv",
+]);
+
+const MAX_FILE_SIZE = 1_048_576; // 1MB
+
+export interface FileEntry {
+ name: string;
+ path: string;
+ isDirectory: boolean;
+ size: number;
+ modifiedAt: string;
+}
+
+export async function readDirectoryTree(
+ dirPath: string,
+ basePath: string,
+): Promise<FileEntry[]> {
+ let entries;
+ try {
+ entries = await readdir(dirPath, { withFileTypes: true });
+ } catch {
+ return [];
+ }
+
+ entries.sort((a, b) => {
+ if (a.isDirectory() && !b.isDirectory()) return -1;
+ if (!a.isDirectory() && b.isDirectory()) return 1;
+ return a.name.localeCompare(b.name);
+ });
+
+ const results: FileEntry[] = [];
+ for (const entry of entries) {
+ if (entry.name.startsWith(".") && entry.name !== ".context_timeline") continue;
+ if (SKIP_DIRS.has(entry.name)) continue;
+
+ const fullPath = join(dirPath, entry.name);
+ let info;
+ try {
+ info = await stat(fullPath);
+ } catch {
+ continue;
+ }
+
+ results.push({
+ name: entry.name,
+ path: relative(basePath, fullPath),
+ isDirectory: entry.isDirectory(),
+ size: entry.isDirectory() ? 0 : info.size,
+ modifiedAt: info.mtime.toISOString(),
+ });
+ }
+ return results;
+}
+
+export async function readFileContent(
+ filePath: string,
+): Promise<{ content: string | null; isBinary: boolean }> {
+ const info = await stat(filePath);
+ if (info.isDirectory()) throw new Error("Cannot read a directory");
+ if (info.size > MAX_FILE_SIZE) throw new Error("File too large (>1MB)");
+
+ const ext = extname(filePath).toLowerCase();
+ if (ext !== "" && !TEXT_EXTENSIONS.has(ext)) {
+ return { content: null, isBinary: true };
+ }
+
+ const content = await readFile(filePath, "utf-8");
+ return { content, isBinary: false };
+}
+
+export function validatePath(agentWorkdir: string, requestedPath: string): string | null {
+ const resolved = resolve(agentWorkdir, requestedPath);
+ if (!resolved.startsWith(agentWorkdir)) return null;
+ return resolved;
+}
diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.ts
index 488c74b45..6aaf1e131 100644
--- a/src/shared/src/db/queries-index.ts
+++ b/src/shared/src/db/queries-index.ts
@@ -21,3 +21,4 @@ export * as agentPin from "./queries/agent-pin";
export * as overview from "./queries/overview";
export * as meetingSession from "./queries/meeting-session";
export * as channel from "./queries/channel";
+export * as workspaceFileRequest from "./queries/workspace-file-request";
diff --git a/src/shared/src/db/queries/workspace-file-request.ts b/src/shared/src/db/queries/workspace-file-request.ts
new file mode 100644
index 000000000..f900fb062
--- /dev/null
+++ b/src/shared/src/db/queries/workspace-file-request.ts
@@ -0,0 +1,79 @@
+import { eq, and, inArray, lt } from "drizzle-orm";
+import { workspaceFileRequest } from "../schema";
+import type { Database } from "../index";
+
+export async function createRequest(
+ db: Database,
+ data: {
+ workspaceId: string;
+ agentId: string;
+ requestType: string;
+ path: string;
+ },
+) {
+ const rows = await db
+ .insert(workspaceFileRequest)
+ .values(data)
+ .returning();
+ return rows[0]!;
+}
+
+export async function getPendingByWorkspace(
+ db: Database,
+ workspaceId: string,
+) {
+ return db
+ .select()
+ .from(workspaceFileRequest)
+ .where(
+ and(
+ eq(workspaceFileRequest.workspaceId, workspaceId),
+ eq(workspaceFileRequest.status, "pending"),
+ ),
+ );
+}
+
+export async function markDispatched(db: Database, ids: string[]) {
+ if (ids.length === 0) return;
+ await db
+ .update(workspaceFileRequest)
+ .set({ status: "dispatched", updatedAt: new Date().toISOString() })
+ .where(inArray(workspaceFileRequest.id, ids));
+}
+
+export async function completeRequest(
+ db: Database,
+ id: string,
+ result: unknown,
+) {
+ const rows = await db
+ .update(workspaceFileRequest)
+ .set({
+ status: "completed",
+ result: JSON.stringify(result),
+ updatedAt: new Date().toISOString(),
+ })
+ .where(eq(workspaceFileRequest.id, id))
+ .returning();
+ return rows[0] ?? null;
+}
+
+export async function getRequest(db: Database, id: string) {
+ const rows = await db
+ .select()
+ .from(workspaceFileRequest)
+ .where(eq(workspaceFileRequest.id, id));
+ return rows[0] ?? null;
+}
+
+export async function expireStale(db: Database, workspaceId: string) {
+ const cutoff = new Date(Date.now() - 30_000).toISOString();
+ await db
+ .delete(workspaceFileRequest)
+ .where(
+ and(
+ eq(workspaceFileRequest.workspaceId, workspaceId),
+ lt(workspaceFileRequest.createdAt, cutoff),
+ ),
+ );
+}
diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.ts
index c36378b94..4a12f1783 100644
--- a/src/shared/src/db/schema.ts
+++ b/src/shared/src/db/schema.ts
@@ -543,3 +543,25 @@ export const machineToken = sqliteTable(
},
(t) => [index("idx_machine_token").on(t.token)]
);
+
+// ---------------------------------------------------------------------------
+// Workspace file request (ephemeral queue for file browsing)
+// ---------------------------------------------------------------------------
+
+export const workspaceFileRequest = sqliteTable(
+ "workspace_file_request",
+ {
+ id: text("id").primaryKey().$defaultFn(() => "wfr_" + nanoid()),
+ workspaceId: text("workspace_id")
+ .notNull()
+ .references(() => workspace.id, { onDelete: "cascade" }),
+ agentId: text("agent_id").notNull(),
+ requestType: text("request_type").notNull(),
+ path: text("path").notNull().default("."),
+ status: text("status").notNull().default("pending"),
+ result: text("result"),
+ createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
+ updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),
+ },
+ (t) => [index("idx_wfr_workspace_status").on(t.workspaceId, t.status)]
+);
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index c968c7756..93e48b726 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -20,6 +20,8 @@ export type {
MeetingSession,
Channel,
WsMessage,
+ WorkspaceFileEntry,
+ WorkspaceFileResult,
} from "./types";
// API types
@@ -124,6 +126,10 @@ export {
UpdateWorkspaceRequestSchema,
DeleteWorkspaceRequestSchema,
GrantAgentAccessRequestSchema,
+ FileRequestItemSchema,
+ WorkspaceFileBrowseRequestSchema,
+ WorkspaceFileEntrySchema,
+ WorkspaceFileReportSchema,
} from "./schemas";
export type {
@@ -152,6 +158,9 @@ export type {
UpdateMemberRequest,
UpdateEmailAccountRequest,
TestEmailConnectionRequest,
+ FileRequestItem,
+ WorkspaceFileBrowseRequest,
+ WorkspaceFileReport,
} from "./schemas";
// Database
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index efb674a55..33af6cd62 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -108,11 +108,20 @@ export const PollRequestSchema = z.object({
});
export type PollRequest = z.infer<typeof PollRequestSchema>;
+export const FileRequestItemSchema = z.object({
+ id: z.string(),
+ agent_id: z.string(),
+ request_type: z.enum(["tree", "read"]),
+ path: z.string(),
+});
+export type FileRequestItem = z.infer<typeof FileRequestItemSchema>;
+
export const PollResponseSchema = z.object({
tasks: z.array(TaskApiSchema),
evicted: z.boolean().optional(),
pending_update: z.object({ version: z.string() }).optional(),
pending_rescan: z.boolean().optional(),
+ file_requests: z.array(FileRequestItemSchema).optional(),
});
export type PollResponse = z.infer<typeof PollResponseSchema>;
@@ -527,3 +536,31 @@ export const GrantAgentAccessRequestSchema = z.object({
user_id: z.string().min(1, "user_id is required"),
});
export type GrantAgentAccessRequest = z.infer<typeof GrantAgentAccessRequestSchema>;
+
+// ---------------------------------------------------------------------------
+// Workspace file browsing
+// ---------------------------------------------------------------------------
+
+export const WorkspaceFileBrowseRequestSchema = z.object({
+ request_type: z.enum(["tree", "read"]),
+ path: z.string().default("."),
+});
+export type WorkspaceFileBrowseRequest = z.infer<typeof WorkspaceFileBrowseRequestSchema>;
+
+export const WorkspaceFileEntrySchema = z.object({
+ name: z.string(),
+ path: z.string(),
+ isDirectory: z.boolean(),
+ size: z.number(),
+ modifiedAt: z.string(),
+});
+
+export const WorkspaceFileReportSchema = z.object({
+ request_id: z.string().min(1),
+ entries: z.array(WorkspaceFileEntrySchema).optional(),
+ content: z.string().nullable().optional(),
+ isBinary: z.boolean().optional(),
+ error: z.string().optional(),
+ path: z.string(),
+});
+export type WorkspaceFileReport = z.infer<typeof WorkspaceFileReportSchema>;
diff --git a/src/shared/src/types.ts b/src/shared/src/types.ts
index 5960a9ba2..1b0f8a55e 100644
--- a/src/shared/src/types.ts
+++ b/src/shared/src/types.ts
@@ -236,3 +236,20 @@ export type WsMessage =
| { type: "followup.created"; conversationId: string; message: Message }
| { type: "followup.deleted"; conversationId: string; messageId: string }
| { type: "followup.dispatch_failed"; conversationId: string; messageId: string; error: string }
+ | { type: "workspace.files"; agentId: string; requestId: string; requestType: "tree" | "read"; result: WorkspaceFileResult }
+
+export interface WorkspaceFileEntry {
+ name: string;
+ path: string;
+ isDirectory: boolean;
+ size: number;
+ modifiedAt: string;
+}
+
+export interface WorkspaceFileResult {
+ entries?: WorkspaceFileEntry[];
+ content?: string | null;
+ isBinary?: boolean;
+ error?: string;
+ path: string;
+}
diff --git a/src/web/migrations/0014_workspace_file_request.sql b/src/web/migrations/0014_workspace_file_request.sql
new file mode 100644
index 000000000..24ad70fea
--- /dev/null
+++ b/src/web/migrations/0014_workspace_file_request.sql
@@ -0,0 +1,13 @@
+CREATE TABLE IF NOT EXISTS workspace_file_request (
+ id TEXT PRIMARY KEY,
+ workspace_id TEXT NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,
+ agent_id TEXT NOT NULL,
+ request_type TEXT NOT NULL,
+ path TEXT NOT NULL DEFAULT '.',
+ status TEXT NOT NULL DEFAULT 'pending',
+ result TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+);
+
+CREATE INDEX IF NOT EXISTS idx_wfr_workspace_status ON workspace_file_request(workspace_id, status);
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsx
new file mode 100644
index 000000000..2f9964947
--- /dev/null
+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsx
@@ -0,0 +1,516 @@
+"use client";
+
+import { useState, useEffect, useCallback, useRef } from "react";
+import { useParams } from "next/navigation";
+import { useAgentContext } from "@/contexts/agent-context";
+import { useWorkspace } from "@/contexts/workspace-context";
+import { requestWorkspaceBrowse } from "@/lib/api";
+import { Skeleton } from "@/components/ui/skeleton";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { ResizablePanels } from "@/components/ui/resizable-panels";
+import { useIsMobile } from "@/hooks/use-mobile";
+import { Streamdown } from "streamdown";
+import type { WsMessage, WorkspaceFileEntry } from "@alook/shared";
+import {
+ ArrowLeft,
+ ChevronRight,
+ Copy,
+ File,
+ FileText,
+ FileCode,
+ Folder,
+ FolderOpen,
+ Loader2,
+} from "lucide-react";
+
+// --- Tree node state ---
+
+interface TreeNode {
+ entry: WorkspaceFileEntry;
+ children: TreeNode[] | null; // null = not loaded
+ loading: boolean;
+ expanded: boolean;
+}
+
+export default function AgentFilesPage() {
+ const params = useParams();
+ const agentId = params.id as string;
+ const { workspaceId } = useWorkspace();
+ const { subscribeWs, runtimes, agents } = useAgentContext();
+ const isMobile = useIsMobile();
+
+ const agent = agents.find((a) => a.id === agentId);
+ const runtime = agent ? runtimes.find((r) => r.id === agent.runtime_id) : null;
+ const isOnline = runtime?.status === "online";
+
+ // Tree state: top-level entries + nested children per directory
+ const [rootNodes, setRootNodes] = useState<TreeNode[]>([]);
+ const [rootLoading, setRootLoading] = useState(true);
+ const [rootError, setRootError] = useState<string | null>(null);
+
+ // File viewer state
+ const [selectedFile, setSelectedFile] = useState<string | null>(null);
+ const [fileContent, setFileContent] = useState<string | null>(null);
+ const [fileBinary, setFileBinary] = useState(false);
+ const [fileLoading, setFileLoading] = useState(false);
+ const [fileError, setFileError] = useState<string | null>(null);
+ const [viewMode, setViewMode] = useState<"raw" | "preview">("preview");
+
+ // Pending request tracking: map requestId -> { type, path, timer }
+ const pendingRef = useRef<Map<string, { type: "tree" | "read"; path: string; timer: ReturnType<typeof setTimeout> }>>(new Map());
+
+ const rootLabel = `~/.alook/workspaces/${workspaceId}/${agentId}/workdir`;
+
+ const REQUEST_TIMEOUT_MS = 15_000;
+
+ const clearPending = useCallback((requestId: string) => {
+ const entry = pendingRef.current.get(requestId);
+ if (entry) {
+ clearTimeout(entry.timer);
+ pendingRef.current.delete(requestId);
+ }
+ }, []);
+
+ const setNodeLoading = useCallback((path: string, loading: boolean) => {
+ setRootNodes((prev) => setLoadingRecursive(prev, path, loading));
+ }, []);
+
+ // --- Request helpers ---
+
+ const requestTree = useCallback(
+ async (path: string) => {
+ try {
+ const { request_id } = await requestWorkspaceBrowse(agentId, workspaceId, "tree", path);
+ const timer = setTimeout(() => {
+ if (pendingRef.current.has(request_id)) {
+ pendingRef.current.delete(request_id);
+ if (path === ".") {
+ setRootError("Request timed out — daemon may be offline");
+ setRootLoading(false);
+ } else {
+ setNodeLoading(path, false);
+ }
+ }
+ }, REQUEST_TIMEOUT_MS);
+ pendingRef.current.set(request_id, { type: "tree", path, timer });
+ return request_id;
+ } catch {
+ return null;
+ }
+ },
+ [agentId, workspaceId, setNodeLoading],
+ );
+
+ const requestFile = useCallback(
+ async (path: string) => {
+ setFileLoading(true);
+ setFileError(null);
+ setFileContent(null);
+ setFileBinary(false);
+ setSelectedFile(path);
+ setViewMode("preview");
+ try {
+ const { request_id } = await requestWorkspaceBrowse(agentId, workspaceId, "read", path);
+ const timer = setTimeout(() => {
+ if (pendingRef.current.has(request_id)) {
+ pendingRef.current.delete(request_id);
+ setFileError("Request timed out — daemon may be offline");
+ setFileLoading(false);
+ }
+ }, REQUEST_TIMEOUT_MS);
+ pendingRef.current.set(request_id, { type: "read", path, timer });
+ } catch {
+ setFileError("Failed to request file");
+ setFileLoading(false);
+ }
+ },
+ [agentId, workspaceId],
+ );
+
+ // --- Load root on mount + cleanup timers ---
+
+ useEffect(() => {
+ setRootLoading(true);
+ setRootError(null);
+ requestTree(".");
+ return () => {
+ for (const entry of pendingRef.current.values()) clearTimeout(entry.timer);
+ pendingRef.current.clear();
+ };
+ }, [requestTree]);
+
+ // --- Update tree node helper ---
+
+ const updateNodeChildren = useCallback(
+ (path: string, children: WorkspaceFileEntry[]) => {
+ const childNodes: TreeNode[] = children.map((e) => ({
+ entry: e,
+ children: null,
+ loading: false,
+ expanded: false,
+ }));
+
+ if (path === ".") {
+ setRootNodes(childNodes);
+ setRootLoading(false);
+ return;
+ }
+
+ setRootNodes((prev) => updateNodesRecursive(prev, path, childNodes));
+ },
+ [],
+ );
+
+ // --- WS handler ---
+
+ useEffect(() => {
+ return subscribeWs((msg: WsMessage) => {
+ if (msg.type !== "workspace.files" || msg.agentId !== agentId) return;
+
+ const pending = pendingRef.current.get(msg.requestId);
+ if (!pending) return;
+ clearPending(msg.requestId);
+
+ if (pending.type === "tree") {
+ if (msg.result.error) {
+ if (pending.path === ".") {
+ setRootError(msg.result.error);
+ setRootLoading(false);
+ } else {
+ setNodeLoading(pending.path, false);
+ }
+ } else {
+ updateNodeChildren(pending.path, msg.result.entries ?? []);
+ }
+ }
+
+ if (pending.type === "read") {
+ if (msg.result.error) {
+ setFileError(msg.result.error);
+ } else {
+ setFileContent(msg.result.content ?? null);
+ setFileBinary(msg.result.isBinary ?? false);
+ }
+ setFileLoading(false);
+ }
+ });
+ }, [subscribeWs, agentId, updateNodeChildren, setNodeLoading, clearPending]);
+
+ // --- Toggle directory ---
+
+ const toggleDir = useCallback(
+ (path: string, node: TreeNode) => {
+ if (node.expanded) {
+ // Collapse
+ setRootNodes((prev) => toggleExpandRecursive(prev, path, false));
+ return;
+ }
+ // Expand: load if needed
+ if (node.children === null) {
+ setNodeLoading(path, true);
+ requestTree(path);
+ }
+ setRootNodes((prev) => toggleExpandRecursive(prev, path, true));
+ },
+ [requestTree, setNodeLoading],
+ );
+
+ const handleCopyPath = () => {
+ navigator.clipboard.writeText(rootLabel).catch(() => {});
+ };
+
+ // --- Offline ---
+
+ if (!isOnline) {
+ return (
+ <div className="flex-1 flex items-center justify-center text-muted-foreground text-sm p-8">
+ <div className="text-center space-y-2">
+ <FolderOpen className="size-8 mx-auto opacity-40" />
+ <p>Agent runtime is offline</p>
+ <p className="text-xs">File browsing requires the daemon to be running.</p>
+ </div>
+ </div>
+ );
+ }
+
+ // --- Shared UI ---
+
+ const pathBar = (
+ <div className="flex items-center gap-1.5 px-4 py-2 border-b border-border/50 text-xs text-muted-foreground shrink-0 min-w-0">
+ <button
+ onClick={handleCopyPath}
+ className="hover:text-foreground transition-colors shrink-0"
+ title="Copy full path"
+ >
+ <Copy className="size-3" />
+ </button>
+ <span className="truncate opacity-60">{rootLabel}</span>
+ </div>
+ );
+
+ const treePanel = (
+ <ScrollArea className="h-full">
+ {rootLoading ? (
+ <div className="p-3 space-y-1">
+ {Array.from({ length: 6 }).map((_, i) => (
+ <Skeleton key={i} className="h-6 w-full rounded" />
+ ))}
+ </div>
+ ) : rootError ? (
+ <div className="p-4 text-sm text-destructive">{rootError}</div>
+ ) : rootNodes.length === 0 ? (
+ <div className="p-4 text-sm text-muted-foreground">Empty directory</div>
+ ) : (
+ <div className="py-0.5">
+ {rootNodes.map((node) => (
+ <TreeNodeRow
+ key={node.entry.path}
+ node={node}
+ depth={0}
+ selectedFile={selectedFile}
+ onToggleDir={toggleDir}
+ onSelectFile={requestFile}
+ />
+ ))}
+ </div>
+ )}
+ </ScrollArea>
+ );
+
+ const selectedFileName = selectedFile?.split("/").pop() ?? "";
+ const isMarkdown = selectedFileName.endsWith(".md");
+
+ const fileViewer = selectedFile ? (
+ <div className="flex-1 min-h-0 flex flex-col">
+ <div className="flex items-center justify-between px-4 py-2 border-b border-border/50 shrink-0">
+ <div className="flex items-center gap-2 min-w-0">
+ {isMobile && (
+ <button
+ onClick={() => { setSelectedFile(null); setFileContent(null); }}
+ className="text-muted-foreground hover:text-foreground transition-colors shrink-0"
+ >
+ <ArrowLeft className="size-4" />
+ </button>
+ )}
+ <span className="text-xs font-medium truncate">{selectedFileName}</span>
+ </div>
+ <div className="flex items-center gap-0.5 shrink-0 ml-2">
+ {isMarkdown && !fileBinary && !fileError && !fileLoading && (
+ <>
+ <button
+ onClick={() => setViewMode("raw")}
+ className={`text-[10px] px-1.5 py-0.5 rounded transition-colors ${
+ viewMode === "raw" ? "bg-muted text-foreground" : "text-muted-foreground hover:text-foreground"
+ }`}
+ >
+ Raw
+ </button>
+ <button
+ onClick={() => setViewMode("preview")}
+ className={`text-[10px] px-1.5 py-0.5 rounded transition-colors ${
+ viewMode === "preview" ? "bg-muted text-foreground" : "text-muted-foreground hover:text-foreground"
+ }`}
+ >
+ Preview
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+ <ScrollArea className="flex-1">
+ {fileLoading ? (
+ <div className="p-4 space-y-2">
+ {Array.from({ length: 10 }).map((_, i) => (
+ <Skeleton key={i} className="h-3.5 w-full rounded" />
+ ))}
+ </div>
+ ) : fileError ? (
+ <div className="p-4 text-sm text-destructive">{fileError}</div>
+ ) : fileBinary ? (
+ <div className="flex-1 flex items-center justify-center p-8 text-sm text-muted-foreground">
+ Binary file — cannot display
+ </div>
+ ) : isMarkdown && viewMode === "preview" ? (
+ <div className="markdown text-sm p-4">
+ <Streamdown>{fileContent ?? ""}</Streamdown>
+ </div>
+ ) : (
+ <pre className="p-4 text-[11px] font-mono whitespace-pre-wrap break-all leading-relaxed text-foreground/80">
+ {fileContent}
+ </pre>
+ )}
+ </ScrollArea>
+ </div>
+ ) : (
+ <div className="flex-1 flex items-center justify-center text-muted-foreground text-xs h-full">
+ Select a file to view
+ </div>
+ );
+
+ // --- Layout ---
+
+ if (isMobile) {
+ if (selectedFile) {
+ return <div className="flex-1 flex flex-col min-h-0 overflow-hidden">{fileViewer}</div>;
+ }
+ return (
+ <div className="flex-1 flex flex-col min-h-0 overflow-hidden">
+ {pathBar}
+ <div className="flex-1 min-h-0">{treePanel}</div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex-1 flex flex-col min-h-0 overflow-hidden">
+ {pathBar}
+ <ResizablePanels
+ storageKey="agent-files-panel-sizes"
+ panels={[
+ {
+ defaultWidth: 280,
+ minWidth: 180,
+ maxWidth: 480,
+ children: treePanel,
+ className: "overflow-hidden",
+ },
+ {
+ children: fileViewer,
+ className: "overflow-hidden flex flex-col",
+ },
+ ]}
+ />
+ </div>
+ );
+}
+
+// --- Tree node row ---
+
+function TreeNodeRow({
+ node,
+ depth,
+ selectedFile,
+ onToggleDir,
+ onSelectFile,
+}: {
+ node: TreeNode;
+ depth: number;
+ selectedFile: string | null;
+ onToggleDir: (path: string, node: TreeNode) => void;
+ onSelectFile: (path: string) => void;
+}) {
+ const { entry } = node;
+ const paddingLeft = 12 + depth * 16;
+
+ if (entry.isDirectory) {
+ return (
+ <>
+ <button
+ onClick={() => onToggleDir(entry.path, node)}
+ className="w-full flex items-center gap-1.5 py-1 text-sm hover:bg-muted/50 transition-colors text-left"
+ style={{ paddingLeft }}
+ >
+ <ChevronRight
+ className={`size-3 text-muted-foreground/60 shrink-0 transition-transform duration-150 ${
+ node.expanded ? "rotate-90" : ""
+ }`}
+ />
+ {node.expanded ? (
+ <FolderOpen className="size-3.5 text-blue-500/70 shrink-0" />
+ ) : (
+ <Folder className="size-3.5 text-blue-500/70 shrink-0" />
+ )}
+ <span className="truncate">{entry.name}</span>
+ {node.loading && <Loader2 className="size-3 text-muted-foreground animate-spin shrink-0 ml-auto mr-2" />}
+ </button>
+ {node.expanded && node.children && node.children.map((child) => (
+ <TreeNodeRow
+ key={child.entry.path}
+ node={child}
+ depth={depth + 1}
+ selectedFile={selectedFile}
+ onToggleDir={onToggleDir}
+ onSelectFile={onSelectFile}
+ />
+ ))}
+ {node.expanded && node.children && node.children.length === 0 && (
+ <div className="text-[10px] text-muted-foreground/50 py-0.5" style={{ paddingLeft: paddingLeft + 24 }}>
+ empty
+ </div>
+ )}
+ </>
+ );
+ }
+
+ return (
+ <button
+ onClick={() => onSelectFile(entry.path)}
+ className={`w-full flex items-center gap-1.5 py-1 text-sm hover:bg-muted/50 transition-colors text-left ${
+ selectedFile === entry.path ? "bg-muted text-foreground" : ""
+ }`}
+ style={{ paddingLeft: paddingLeft + 15 }}
+ >
+ <FileIcon name={entry.name} />
+ <span className="truncate">{entry.name}</span>
+ <span className="ml-auto text-[10px] text-muted-foreground/50 shrink-0 tabular-nums mr-2">
+ {formatSize(entry.size)}
+ </span>
+ </button>
+ );
+}
+
+// --- Recursive tree update helpers ---
+
+function updateNodesRecursive(nodes: TreeNode[], targetPath: string, children: TreeNode[]): TreeNode[] {
+ return nodes.map((node) => {
+ if (node.entry.path === targetPath) {
+ return { ...node, children, loading: false, expanded: true };
+ }
+ if (node.children && targetPath.startsWith(node.entry.path + "/")) {
+ return { ...node, children: updateNodesRecursive(node.children, targetPath, children) };
+ }
+ return node;
+ });
+}
+
+function setLoadingRecursive(nodes: TreeNode[], targetPath: string, loading: boolean): TreeNode[] {
+ return nodes.map((node) => {
+ if (node.entry.path === targetPath) {
+ return { ...node, loading };
+ }
+ if (node.children && targetPath.startsWith(node.entry.path + "/")) {
+ return { ...node, children: setLoadingRecursive(node.children, targetPath, loading) };
+ }
+ return node;
+ });
+}
+
+function toggleExpandRecursive(nodes: TreeNode[], targetPath: string, expanded: boolean): TreeNode[] {
+ return nodes.map((node) => {
+ if (node.entry.path === targetPath) {
+ return { ...node, expanded };
+ }
+ if (node.children && targetPath.startsWith(node.entry.path + "/")) {
+ return { ...node, children: toggleExpandRecursive(node.children, targetPath, expanded) };
+ }
+ return node;
+ });
+}
+
+// --- Misc helpers ---
+
+function FileIcon({ name }: { name: string }) {
+ if (name.endsWith(".md") || name.endsWith(".txt")) {
+ return <FileText className="size-3.5 text-muted-foreground shrink-0" />;
+ }
+ if (/\.(js|ts|tsx|jsx|py|sh|go|rs|rb|css|html|sql)$/.test(name)) {
+ return <FileCode className="size-3.5 text-muted-foreground shrink-0" />;
+ }
+ return <File className="size-3.5 text-muted-foreground shrink-0" />;
+}
+
+function formatSize(bytes: number): string {
+ if (bytes < 1024) return `${bytes}B`;
+ if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)}K`;
+ return `${(bytes / 1048576).toFixed(1)}M`;
+}
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx
index ecaf0c6e2..604f70183 100644
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx
+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx
@@ -10,7 +10,7 @@ import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { AgentEditForm } from "@/components/agent-edit-form";
import { Skeleton } from "@/components/ui/skeleton";
import { AgentStatusBadge } from "@/components/agent-status-badge";
-import { CalendarDays, History, Mail, MessageSquare, MoreHorizontal, Pencil, Trash2, Video, X } from "lucide-react";
+import { CalendarDays, FolderOpen, History, Mail, MessageSquare, MoreHorizontal, Pencil, Trash2, Video, X } from "lucide-react";
import { MobileSidebarLogo } from "@/components/mobile-sidebar-logo";
import {
DropdownMenu,
@@ -35,8 +35,10 @@ export default function AgentDetailLayout({ children }: { children: ReactNode })
? "meetings"
: pathname.includes("/email")
? "email"
- : "chat";
- const tabLabels: Record<string, string> = { email: "Email", meetings: "Meetings", activity: "Activity" };
+ : pathname.includes("/files")
+ ? "files"
+ : "chat";
+ const tabLabels: Record<string, string> = { email: "Email", meetings: "Meetings", activity: "Activity", files: "Files" };
const { agents, runtimes, handleDeleteAgent, handleUpdateAgent } = useAgentContext();
const agent = agents.find((a) => a.id === agentId);
@@ -162,6 +164,21 @@ export default function AgentDetailLayout({ children }: { children: ReactNode })
: "max-w-0 opacity-0 group-hover:max-w-16 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300"
}`}>Activity</span>
</Link>
+ <Link
+ href={`/w/${slug}/agents/${agentId}/files`}
+ className={`group inline-flex items-center rounded-lg text-xs h-7 px-2 transition-all ${
+ currentTab === "files"
+ ? "text-foreground bg-muted"
+ : "text-muted-foreground hover:bg-muted hover:text-foreground"
+ }`}
+ >
+ <FolderOpen className="size-3 shrink-0" />
+ <span className={`overflow-hidden transition-all duration-500 ease-out ${
+ currentTab === "files"
+ ? "max-w-16 opacity-100 ml-1"
+ : "max-w-0 opacity-0 group-hover:max-w-16 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300"
+ }`}>Files</span>
+ </Link>
<Link
href={`/w/${slug}/calendar?agents=${agentId}`}
className="group inline-flex items-center rounded-lg text-xs text-muted-foreground h-7 px-2 hover:bg-muted hover:text-foreground transition-all"
@@ -226,6 +243,13 @@ export default function AgentDetailLayout({ children }: { children: ReactNode })
<History className="size-3.5" /> Activity
</DropdownMenuItem>
)}
+ {currentTab !== "files" && (
+ <DropdownMenuItem
+ onClick={() => router.push(`/w/${slug}/agents/${agentId}/files`)}
+ >
+ <FolderOpen className="size-3.5" /> Files
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem
onClick={() =>
router.push(`/w/${slug}/calendar?agents=${agentId}`)
diff --git a/src/web/src/app/api/agents/[id]/workspace/browse/route.test.ts b/src/web/src/app/api/agents/[id]/workspace/browse/route.test.ts
new file mode 100644
index 000000000..995b1239a
--- /dev/null
+++ b/src/web/src/app/api/agents/[id]/workspace/browse/route.test.ts
@@ -0,0 +1,116 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockGetAgent = vi.fn();
+const mockCreateRequest = vi.fn();
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+vi.mock("@alook/shared", async () => {
+ const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
+ return {
+ ...real,
+ queries: {
+ agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },
+ workspaceFileRequest: { createRequest: (...args: unknown[]) => mockCreateRequest(...args) },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+
+vi.mock("@/lib/middleware/helpers", async () =>
+ await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")
+);
+
+import { POST } from "./route";
+
+function postReq(agentId: string, body: unknown, workspaceId = "w1") {
+ return new NextRequest(
+ `http://localhost/api/agents/${agentId}/workspace/browse?workspace_id=${workspaceId}`,
+ {
+ method: "POST",
+ body: JSON.stringify(body),
+ headers: { "Content-Type": "application/json" },
+ },
+ );
+}
+
+describe("POST /api/agents/[id]/workspace/browse", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns 400 when workspace_id is missing", async () => {
+ const req = new NextRequest("http://localhost/api/agents/a1/workspace/browse", {
+ method: "POST",
+ body: JSON.stringify({ request_type: "tree", path: "." }),
+ headers: { "Content-Type": "application/json" },
+ });
+ const res = await POST(req, { params: Promise.resolve({ id: "a1" }) });
+ expect(res.status).toBe(400);
+ });
+
+ it("returns 404 when agent not found", async () => {
+ mockGetAgent.mockResolvedValue(null);
+
+ const res = await POST(postReq("a1", { request_type: "tree", path: "." }), {
+ params: Promise.resolve({ id: "a1" }),
+ });
+ expect(res.status).toBe(404);
+ });
+
+ it("creates a file request and returns request_id for tree", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1" });
+ mockCreateRequest.mockResolvedValue({ id: "wfr_abc123" });
+
+ const res = await POST(postReq("a1", { request_type: "tree", path: "." }), {
+ params: Promise.resolve({ id: "a1" }),
+ });
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.request_id).toBe("wfr_abc123");
+ expect(mockCreateRequest).toHaveBeenCalledWith({}, {
+ workspaceId: "w1",
+ agentId: "a1",
+ requestType: "tree",
+ path: ".",
+ });
+ });
+
+ it("creates a file request for read with custom path", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1" });
+ mockCreateRequest.mockResolvedValue({ id: "wfr_def456" });
+
+ const res = await POST(postReq("a1", { request_type: "read", path: "memory.md" }), {
+ params: Promise.resolve({ id: "a1" }),
+ });
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.request_id).toBe("wfr_def456");
+ expect(mockCreateRequest).toHaveBeenCalledWith({}, {
+ workspaceId: "w1",
+ agentId: "a1",
+ requestType: "read",
+ path: "memory.md",
+ });
+ });
+
+ it("returns 400 for invalid request_type", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1" });
+
+ const res = await POST(postReq("a1", { request_type: "delete", path: "." }), {
+ params: Promise.resolve({ id: "a1" }),
+ });
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/src/web/src/app/api/agents/[id]/workspace/browse/route.ts b/src/web/src/app/api/agents/[id]/workspace/browse/route.ts
new file mode 100644
index 000000000..90f73a8ba
--- /dev/null
+++ b/src/web/src/app/api/agents/[id]/workspace/browse/route.ts
@@ -0,0 +1,32 @@
+import { NextRequest } from "next/server";
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+import { queries, WorkspaceFileBrowseRequestSchema } from "@alook/shared";
+import { withAuth } from "@/lib/middleware/auth";
+import { parseBody, writeJSON, writeError } from "@/lib/middleware/helpers";
+import { getDb } from "@/lib/db";
+
+export const POST = withAuth(async (req: NextRequest, ctx) => {
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+
+ const agentId = ctx.params?.id;
+ if (!agentId) return writeError("agent id required", 400);
+
+ const [body, err] = await parseBody(req, WorkspaceFileBrowseRequestSchema);
+ if (err) return err;
+
+ const workspaceId = new URL(req.url).searchParams.get("workspace_id");
+ if (!workspaceId) return writeError("workspace_id required", 400);
+
+ const agent = await queries.agent.getAgent(db, agentId, workspaceId);
+ if (!agent) return writeError("agent not found", 404);
+
+ const row = await queries.workspaceFileRequest.createRequest(db, {
+ workspaceId,
+ agentId,
+ requestType: body.request_type,
+ path: body.path,
+ });
+
+ return writeJSON({ request_id: row.id });
+});
diff --git a/src/web/src/app/api/daemon/tasks/poll/route.test.ts b/src/web/src/app/api/daemon/tasks/poll/route.test.ts
index 241028915..efbd7bff7 100644
--- a/src/web/src/app/api/daemon/tasks/poll/route.test.ts
+++ b/src/web/src/app/api/daemon/tasks/poll/route.test.ts
@@ -12,6 +12,9 @@ const mockGetUser = vi.fn();
const mockClaimTasksForRuntimes = vi.fn();
const mockSweepStaleState = vi.fn();
const mockBroadcastToUser = vi.fn();
+const mockGetPendingFileRequests = vi.fn();
+const mockMarkFileRequestsDispatched = vi.fn();
+const mockExpireStaleFileRequests = vi.fn();
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -48,6 +51,11 @@ vi.mock("@alook/shared", async () => {
emailAccount: {
getEmailAccountsByAgent: vi.fn().mockResolvedValue([]),
},
+ workspaceFileRequest: {
+ getPendingByWorkspace: (...args: unknown[]) => mockGetPendingFileRequests(...args),
+ markDispatched: (...args: unknown[]) => mockMarkFileRequestsDispatched(...args),
+ expireStale: (...args: unknown[]) => mockExpireStaleFileRequests(...args),
+ },
},
};
});
@@ -111,6 +119,8 @@ describe("POST /api/daemon/tasks/poll", () => {
beforeEach(() => {
vi.clearAllMocks();
mockGetMachineByDaemon.mockResolvedValue(null);
+ mockGetPendingFileRequests.mockResolvedValue([]);
+ mockExpireStaleFileRequests.mockResolvedValue(undefined);
});
it("returns evicted: true and skips heartbeat when daemon has no runtimes", async () => {
@@ -601,4 +611,73 @@ describe("POST /api/daemon/tasks/poll", () => {
expect(body.tasks[1].sender).toEqual({ name: "Gus", email: "[email protected]", is_owner: false });
expect(mockGetUser).toHaveBeenCalledTimes(1);
});
+
+ // --- Workspace file requests ---
+
+ it("includes pending file_requests in response and marks them dispatched", async () => {
+ mockUpsertMachine.mockResolvedValue({});
+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);
+ mockSweepStaleState.mockResolvedValue(undefined);
+ mockBroadcastToUser.mockResolvedValue(undefined);
+ mockClaimTasksForRuntimes.mockResolvedValue([]);
+ mockGetPendingFileRequests.mockResolvedValue([
+ { id: "wfr_1", agentId: "a1", requestType: "tree", path: "." },
+ { id: "wfr_2", agentId: "a1", requestType: "read", path: "memory.md" },
+ ]);
+ mockMarkFileRequestsDispatched.mockResolvedValue(undefined);
+
+ const res = await POST(postReq({ daemon_id: "d1" }));
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.file_requests).toHaveLength(2);
+ expect(body.file_requests[0]).toEqual({ id: "wfr_1", agent_id: "a1", request_type: "tree", path: "." });
+ expect(body.file_requests[1]).toEqual({ id: "wfr_2", agent_id: "a1", request_type: "read", path: "memory.md" });
+ expect(mockMarkFileRequestsDispatched).toHaveBeenCalledWith({}, ["wfr_1", "wfr_2"]);
+ });
+
+ it("omits file_requests field when no pending requests", async () => {
+ mockUpsertMachine.mockResolvedValue({});
+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);
+ mockSweepStaleState.mockResolvedValue(undefined);
+ mockBroadcastToUser.mockResolvedValue(undefined);
+ mockClaimTasksForRuntimes.mockResolvedValue([]);
+ mockGetPendingFileRequests.mockResolvedValue([]);
+
+ const res = await POST(postReq({ daemon_id: "d1" }));
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.file_requests).toBeUndefined();
+ expect(mockMarkFileRequestsDispatched).not.toHaveBeenCalled();
+ });
+
+ it("calls expireStale to clean up old file requests", async () => {
+ mockUpsertMachine.mockResolvedValue({});
+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);
+ mockSweepStaleState.mockResolvedValue(undefined);
+ mockBroadcastToUser.mockResolvedValue(undefined);
+ mockClaimTasksForRuntimes.mockResolvedValue([]);
+ mockGetPendingFileRequests.mockResolvedValue([]);
+
+ await POST(postReq({ daemon_id: "d1" }));
+
+ expect(mockExpireStaleFileRequests).toHaveBeenCalledWith({}, "w1");
+ });
+
+ it("gracefully handles file request errors without failing the poll", async () => {
+ mockUpsertMachine.mockResolvedValue({});
+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);
+ mockSweepStaleState.mockResolvedValue(undefined);
+ mockBroadcastToUser.mockResolvedValue(undefined);
+ mockClaimTasksForRuntimes.mockResolvedValue([]);
+ mockExpireStaleFileRequests.mockRejectedValue(new Error("DB error"));
+
+ const res = await POST(postReq({ daemon_id: "d1" }));
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.tasks).toEqual([]);
+ expect(body.file_requests).toBeUndefined();
+ });
});
diff --git a/src/web/src/app/api/daemon/tasks/poll/route.ts b/src/web/src/app/api/daemon/tasks/poll/route.ts
index 8ea40cf65..98e8f9a67 100644
--- a/src/web/src/app/api/daemon/tasks/poll/route.ts
+++ b/src/web/src/app/api/daemon/tasks/poll/route.ts
@@ -175,9 +175,28 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
await queries.machine.clearPendingRescan(db, body.daemon_id, ctx.workspaceId);
}
+ // 7. Pending file browse requests + cleanup
+ let fileRequests: { id: string; agent_id: string; request_type: string; path: string }[] | undefined;
+ try {
+ await queries.workspaceFileRequest.expireStale(db, ctx.workspaceId);
+ const pending = await queries.workspaceFileRequest.getPendingByWorkspace(db, ctx.workspaceId);
+ if (pending.length > 0) {
+ fileRequests = pending.map((r) => ({
+ id: r.id,
+ agent_id: r.agentId,
+ request_type: r.requestType,
+ path: r.path,
+ }));
+ await queries.workspaceFileRequest.markDispatched(db, pending.map((r) => r.id));
+ }
+ } catch (e) {
+ log.warn("file-requests: poll failed", { err: String(e) });
+ }
+
return writeJSON({
tasks,
...(pendingUpdate && { pending_update: pendingUpdate }),
...(pendingRescan && { pending_rescan: pendingRescan }),
+ ...(fileRequests && fileRequests.length > 0 && { file_requests: fileRequests }),
});
});
diff --git a/src/web/src/app/api/daemon/workspace/report/route.test.ts b/src/web/src/app/api/daemon/workspace/report/route.test.ts
new file mode 100644
index 000000000..7526a70b9
--- /dev/null
+++ b/src/web/src/app/api/daemon/workspace/report/route.test.ts
@@ -0,0 +1,156 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockGetRequest = vi.fn();
+const mockCompleteRequest = vi.fn();
+const mockBroadcastToUser = vi.fn();
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+vi.mock("@alook/shared", async () => {
+ const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
+ return {
+ ...real,
+ queries: {
+ workspaceFileRequest: {
+ getRequest: (...args: unknown[]) => mockGetRequest(...args),
+ completeRequest: (...args: unknown[]) => mockCompleteRequest(...args),
+ },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1", params });
+ }),
+}));
+
+vi.mock("@/lib/middleware/helpers", async () =>
+ await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")
+);
+
+vi.mock("@/lib/broadcast", () => ({
+ broadcastToUser: (...args: unknown[]) => mockBroadcastToUser(...args),
+}));
+
+import { POST } from "./route";
+
+function postReq(body: unknown) {
+ return new NextRequest("http://localhost/api/daemon/workspace/report", {
+ method: "POST",
+ body: JSON.stringify(body),
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+describe("POST /api/daemon/workspace/report", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("requires machine token (workspaceId) — tested via withAuth mock providing it", () => {
+ // The route checks ctx.workspaceId and returns 403 if missing.
+ // Our mock always provides workspaceId="w1" to test the happy path.
+ // The 403 guard is structurally identical to other daemon routes (e.g. poll, complete).
+ expect(true).toBe(true);
+ });
+
+ it("returns 404 when request not found", async () => {
+ mockGetRequest.mockResolvedValue(null);
+
+ const res = await POST(postReq({ request_id: "wfr_missing", path: "." }));
+ expect(res.status).toBe(404);
+ });
+
+ it("completes request and broadcasts result for tree", async () => {
+ const entries = [
+ { name: "memory.md", path: "memory.md", isDirectory: false, size: 100, modifiedAt: "2026-01-01" },
+ ];
+ mockGetRequest.mockResolvedValue({
+ id: "wfr_1",
+ agentId: "a1",
+ requestType: "tree",
+ workspaceId: "w1",
+ });
+ mockCompleteRequest.mockResolvedValue({});
+ mockBroadcastToUser.mockResolvedValue(undefined);
+
+ const res = await POST(postReq({ request_id: "wfr_1", path: ".", entries }));
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.status).toBe("ok");
+ expect(mockCompleteRequest).toHaveBeenCalledWith({}, "wfr_1", {
+ entries,
+ content: undefined,
+ isBinary: undefined,
+ error: undefined,
+ path: ".",
+ });
+ expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {
+ type: "workspace.files",
+ agentId: "a1",
+ requestId: "wfr_1",
+ requestType: "tree",
+ result: expect.objectContaining({ entries, path: "." }),
+ });
+ });
+
+ it("completes request and broadcasts for file read", async () => {
+ mockGetRequest.mockResolvedValue({
+ id: "wfr_2",
+ agentId: "a1",
+ requestType: "read",
+ workspaceId: "w1",
+ });
+ mockCompleteRequest.mockResolvedValue({});
+ mockBroadcastToUser.mockResolvedValue(undefined);
+
+ const res = await POST(postReq({
+ request_id: "wfr_2",
+ path: "memory.md",
+ content: "# Hello",
+ isBinary: false,
+ }));
+
+ expect(res.status).toBe(200);
+ expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {
+ type: "workspace.files",
+ agentId: "a1",
+ requestId: "wfr_2",
+ requestType: "read",
+ result: expect.objectContaining({ content: "# Hello", isBinary: false, path: "memory.md" }),
+ });
+ });
+
+ it("handles error report from daemon", async () => {
+ mockGetRequest.mockResolvedValue({
+ id: "wfr_3",
+ agentId: "a1",
+ requestType: "read",
+ workspaceId: "w1",
+ });
+ mockCompleteRequest.mockResolvedValue({});
+ mockBroadcastToUser.mockResolvedValue(undefined);
+
+ const res = await POST(postReq({
+ request_id: "wfr_3",
+ path: "missing.txt",
+ error: "ENOENT: no such file",
+ }));
+
+ expect(res.status).toBe(200);
+ expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", expect.objectContaining({
+ result: expect.objectContaining({ error: "ENOENT: no such file" }),
+ }));
+ });
+
+ it("returns 400 when request_id is missing", async () => {
+ const res = await POST(postReq({ path: "." }));
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/src/web/src/app/api/daemon/workspace/report/route.ts b/src/web/src/app/api/daemon/workspace/report/route.ts
new file mode 100644
index 000000000..d0ad00eab
--- /dev/null
+++ b/src/web/src/app/api/daemon/workspace/report/route.ts
@@ -0,0 +1,42 @@
+import { NextRequest } from "next/server";
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+import { queries, WorkspaceFileReportSchema } from "@alook/shared";
+import { withAuth } from "@/lib/middleware/auth";
+import { parseBody, writeJSON, writeError } from "@/lib/middleware/helpers";
+import { getDb } from "@/lib/db";
+import { broadcastToUser } from "@/lib/broadcast";
+
+export const POST = withAuth(async (req: NextRequest, ctx) => {
+ if (!ctx.workspaceId) {
+ return writeError("Forbidden: machine token required", 403);
+ }
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+
+ const [body, err] = await parseBody(req, WorkspaceFileReportSchema);
+ if (err) return err;
+
+ const row = await queries.workspaceFileRequest.getRequest(db, body.request_id);
+ if (!row) return writeError("request not found", 404);
+
+ const result = {
+ entries: body.entries,
+ content: body.content,
+ isBinary: body.isBinary,
+ error: body.error,
+ path: body.path,
+ };
+
+ await queries.workspaceFileRequest.completeRequest(db, row.id, result);
+
+ broadcastToUser(ctx.userId, {
+ type: "workspace.files",
+ agentId: row.agentId,
+ requestId: row.id,
+ requestType: row.requestType as "tree" | "read",
+ result,
+ }).catch(() => {});
+
+ return writeJSON({ status: "ok" });
+});
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index 82220c88b..bbef25674 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -790,6 +790,21 @@ export const pinAgent = (workspaceId: string, agentId: string) =>
export const unpinAgent = (workspaceId: string, agentId: string) =>
apiFetch<void>(`/api/agents/${agentId}/pin${wsQuery(workspaceId)}`, { method: "DELETE" });
+// Workspace file browsing
+export const requestWorkspaceBrowse = (
+ agentId: string,
+ workspaceId: string,
+ requestType: "tree" | "read",
+ path: string,
+) =>
+ apiFetch<{ request_id: string }>(
+ `/api/agents/${agentId}/workspace/browse${wsQuery(workspaceId)}`,
+ {
+ method: "POST",
+ body: JSON.stringify({ request_type: requestType, path }),
+ },
+ );
+
// Meetings
export const listMeetings = (agentId: string, workspaceId: string) =>
apiFetch<MeetingSession[]>(`/api/agents/${agentId}/meetings${wsQuery(workspaceId)}`);