feat(FN-1980): add project markdown files to Documents view
- Add backend Markdown scanner and /project-files/md endpoint with directory exclusions, depth/size limits, and search filtering - Extend dashboard API and useDocuments hook to fetch task documents and project markdown files in parallel with resilient partial-failure handling - Update Documents view with a collapsible Project Files section, inline metadata previews, and on-demand file content expansion from workspace API - Add and refresh hook and file-service tests to cover markdown scanning, query propagation, project scoping, and fetch error behavior - Add token-based styles for project file cards and responsive mobile adjustments in the documents panel
This commit is contained in:
@@ -751,6 +751,14 @@ export interface FetchAllDocumentsOptions {
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
export interface MarkdownFileEntry {
|
||||
path: string;
|
||||
name: string;
|
||||
size: number;
|
||||
mtime: string;
|
||||
contentPreview: string;
|
||||
}
|
||||
|
||||
export async function fetchAllDocuments(
|
||||
options?: FetchAllDocumentsOptions,
|
||||
projectId?: string,
|
||||
@@ -764,6 +772,19 @@ export async function fetchAllDocuments(
|
||||
return api<TaskDocumentWithTask[]>(withProjectId(path, projectId));
|
||||
}
|
||||
|
||||
export function fetchProjectMarkdownFiles(
|
||||
options?: { q?: string },
|
||||
projectId?: string,
|
||||
): Promise<MarkdownFileEntry[]> {
|
||||
const params = new URLSearchParams();
|
||||
if (options?.q) {
|
||||
params.set("q", options.q);
|
||||
}
|
||||
const queryString = params.toString();
|
||||
const path = `/project-files/md${queryString ? `?${queryString}` : ""}`;
|
||||
return api<MarkdownFileEntry[]>(withProjectId(path, projectId));
|
||||
}
|
||||
|
||||
export function putTaskDocument(
|
||||
taskId: string,
|
||||
key: string,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useState, useMemo, useCallback } from "react";
|
||||
import { FileText, ChevronDown, ChevronUp, ChevronRight, RefreshCw, Search, X } from "lucide-react";
|
||||
import type { TaskDocumentWithTask, TaskDetail } from "@fusion/core";
|
||||
import type { ToastType } from "../hooks/useToast";
|
||||
import { fetchTaskDetail } from "../api";
|
||||
import { fetchTaskDetail, fetchWorkspaceFileContent, type MarkdownFileEntry } from "../api";
|
||||
import { useDocuments } from "../hooks/useDocuments";
|
||||
|
||||
export interface DocumentsViewProps {
|
||||
@@ -16,11 +16,32 @@ interface DocumentCardProps {
|
||||
onOpenTask: (taskId: string) => void;
|
||||
}
|
||||
|
||||
interface ProjectFileCardProps {
|
||||
file: MarkdownFileEntry;
|
||||
expanded: boolean;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
content: string;
|
||||
onOpen: (filePath: string) => Promise<void>;
|
||||
}
|
||||
|
||||
function formatTimestamp(iso?: string): string {
|
||||
if (!iso) return "";
|
||||
return new Date(iso).toLocaleString();
|
||||
}
|
||||
|
||||
function formatFileSize(bytes: number): string {
|
||||
if (bytes < 1024) {
|
||||
return `${bytes} B`;
|
||||
}
|
||||
|
||||
if (bytes < 1024 * 1024) {
|
||||
return `${(bytes / 1024).toFixed(bytes >= 10 * 1024 ? 0 : 1)} KB`;
|
||||
}
|
||||
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
function getContentPreview(content: string, maxLength: number = 200): string {
|
||||
if (content.length <= maxLength) return content;
|
||||
return content.substring(0, maxLength) + "…";
|
||||
@@ -70,6 +91,57 @@ function DocumentCard({ document, onOpenTask }: DocumentCardProps) {
|
||||
);
|
||||
}
|
||||
|
||||
function ProjectFileCard({ file, expanded, loading, error, content, onOpen }: ProjectFileCardProps) {
|
||||
const preview = getContentPreview(file.contentPreview, 200);
|
||||
const isExpanded = expanded;
|
||||
|
||||
return (
|
||||
<div className="documents-project-file">
|
||||
<button
|
||||
className="documents-project-file-card"
|
||||
onClick={() => void onOpen(file.path)}
|
||||
aria-expanded={isExpanded}
|
||||
aria-label={`${isExpanded ? "Collapse" : "Open"} project file ${file.path}`}
|
||||
>
|
||||
<div className="documents-project-file-header">
|
||||
<div className="documents-project-file-title">
|
||||
<FileText size={14} />
|
||||
<span>{file.name}</span>
|
||||
</div>
|
||||
<span className="documents-project-file-toggle">
|
||||
{isExpanded ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p className="documents-project-file-path">{file.path}</p>
|
||||
|
||||
<div className="documents-project-file-meta">
|
||||
<span>{formatFileSize(file.size)}</span>
|
||||
<span>·</span>
|
||||
<span>{formatTimestamp(file.mtime)}</span>
|
||||
</div>
|
||||
|
||||
<p className="documents-project-file-preview">
|
||||
{preview || "No preview available."}
|
||||
{file.contentPreview.length >= 200 ? "…" : ""}
|
||||
</p>
|
||||
</button>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="documents-project-file-content">
|
||||
{loading ? (
|
||||
<p className="documents-project-file-content-state">Loading file content…</p>
|
||||
) : error ? (
|
||||
<p className="documents-project-file-content-state documents-project-file-content-state--error">{error}</p>
|
||||
) : (
|
||||
<pre className="documents-project-file-content-text">{content}</pre>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface TaskGroupProps {
|
||||
taskId: string;
|
||||
taskTitle?: string;
|
||||
@@ -122,7 +194,13 @@ function TaskGroup({ taskId, taskTitle, documents, onOpenTask }: TaskGroupProps)
|
||||
|
||||
export function DocumentsView({ projectId, addToast, onOpenDetail }: DocumentsViewProps) {
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const { documents, loading, error, refresh } = useDocuments({
|
||||
const [projectFilesExpanded, setProjectFilesExpanded] = useState(true);
|
||||
const [openProjectFilePath, setOpenProjectFilePath] = useState<string | null>(null);
|
||||
const [openProjectFileContent, setOpenProjectFileContent] = useState("");
|
||||
const [openProjectFileLoading, setOpenProjectFileLoading] = useState(false);
|
||||
const [openProjectFileError, setOpenProjectFileError] = useState<string | null>(null);
|
||||
|
||||
const { documents, projectFiles, loading, error, refresh } = useDocuments({
|
||||
projectId,
|
||||
searchQuery: searchQuery || undefined,
|
||||
});
|
||||
@@ -153,16 +231,46 @@ export function DocumentsView({ projectId, addToast, onOpenDetail }: DocumentsVi
|
||||
setSearchQuery("");
|
||||
}, []);
|
||||
|
||||
const toggleProjectFilesExpanded = useCallback(() => {
|
||||
setProjectFilesExpanded((current) => !current);
|
||||
}, []);
|
||||
|
||||
// Wrapper to open task detail by fetching full task first
|
||||
const handleOpenTask = useCallback(async (taskId: string) => {
|
||||
try {
|
||||
const task = await fetchTaskDetail(taskId, projectId);
|
||||
onOpenDetail(task);
|
||||
} catch (err) {
|
||||
} catch {
|
||||
addToast(`Failed to open task ${taskId}`, "error");
|
||||
}
|
||||
}, [projectId, onOpenDetail, addToast]);
|
||||
|
||||
const handleOpenProjectFile = useCallback(async (filePath: string) => {
|
||||
if (openProjectFilePath === filePath) {
|
||||
setOpenProjectFilePath(null);
|
||||
setOpenProjectFileContent("");
|
||||
setOpenProjectFileError(null);
|
||||
setOpenProjectFileLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setOpenProjectFilePath(filePath);
|
||||
setOpenProjectFileLoading(true);
|
||||
setOpenProjectFileError(null);
|
||||
setOpenProjectFileContent("");
|
||||
|
||||
try {
|
||||
const file = await fetchWorkspaceFileContent("project", filePath, projectId);
|
||||
setOpenProjectFileContent(file.content);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : `Failed to open ${filePath}`;
|
||||
setOpenProjectFileError(message);
|
||||
addToast(message, "error");
|
||||
} finally {
|
||||
setOpenProjectFileLoading(false);
|
||||
}
|
||||
}, [openProjectFilePath, projectId, addToast]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="documents-view">
|
||||
@@ -186,7 +294,7 @@ export function DocumentsView({ projectId, addToast, onOpenDetail }: DocumentsVi
|
||||
Documents
|
||||
</h2>
|
||||
<span className="documents-view-count">
|
||||
{loading ? "…" : `${documents.length} total`}
|
||||
{loading ? "…" : `${documents.length + projectFiles.length} total`}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -217,31 +325,73 @@ export function DocumentsView({ projectId, addToast, onOpenDetail }: DocumentsVi
|
||||
<div className="documents-view-loading">
|
||||
<p>Loading documents…</p>
|
||||
</div>
|
||||
) : groupedDocuments.length === 0 ? (
|
||||
<div className="documents-view-empty">
|
||||
{searchQuery ? (
|
||||
<p>No documents match "{searchQuery}".</p>
|
||||
) : (
|
||||
<>
|
||||
<FileText size={48} className="documents-view-empty-icon" />
|
||||
<p>No documents yet.</p>
|
||||
<p className="documents-view-empty-hint">
|
||||
Documents are created in task detail tabs.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="documents-view-list">
|
||||
{groupedDocuments.map(({ taskId, taskTitle, documents: taskDocs }) => (
|
||||
<TaskGroup
|
||||
key={taskId}
|
||||
taskId={taskId}
|
||||
taskTitle={taskTitle}
|
||||
documents={taskDocs}
|
||||
onOpenTask={handleOpenTask}
|
||||
/>
|
||||
))}
|
||||
<div className="documents-view-sections">
|
||||
<section className="documents-project-files" aria-label="Project files section">
|
||||
<button
|
||||
className="documents-project-files-header"
|
||||
onClick={toggleProjectFilesExpanded}
|
||||
aria-expanded={projectFilesExpanded}
|
||||
>
|
||||
<span className="documents-project-files-toggle">
|
||||
{projectFilesExpanded ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
|
||||
</span>
|
||||
<span className="documents-project-files-title">Project Files</span>
|
||||
<span className="documents-project-files-count">
|
||||
{projectFiles.length} file{projectFiles.length !== 1 ? "s" : ""}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{projectFilesExpanded && (
|
||||
projectFiles.length === 0 ? (
|
||||
<p className="documents-project-files-empty">
|
||||
No Markdown files found in the project directory.
|
||||
</p>
|
||||
) : (
|
||||
<div className="documents-project-files-list">
|
||||
{projectFiles.map((file) => (
|
||||
<ProjectFileCard
|
||||
key={file.path}
|
||||
file={file}
|
||||
expanded={openProjectFilePath === file.path}
|
||||
loading={openProjectFileLoading && openProjectFilePath === file.path}
|
||||
error={openProjectFilePath === file.path ? openProjectFileError : null}
|
||||
content={openProjectFilePath === file.path ? openProjectFileContent : ""}
|
||||
onOpen={handleOpenProjectFile}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</section>
|
||||
|
||||
{groupedDocuments.length === 0 ? (
|
||||
<div className="documents-view-empty">
|
||||
{searchQuery ? (
|
||||
<p>No task documents match "{searchQuery}".</p>
|
||||
) : (
|
||||
<>
|
||||
<FileText size={48} className="documents-view-empty-icon" />
|
||||
<p>No task documents yet.</p>
|
||||
<p className="documents-view-empty-hint">
|
||||
Documents are created in task detail tabs.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="documents-view-list">
|
||||
{groupedDocuments.map(({ taskId, taskTitle, documents: taskDocs }) => (
|
||||
<TaskGroup
|
||||
key={taskId}
|
||||
taskId={taskId}
|
||||
taskTitle={taskTitle}
|
||||
documents={taskDocs}
|
||||
onOpenTask={handleOpenTask}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { renderHook, act, waitFor } from "@testing-library/react";
|
||||
import { useDocuments } from "../useDocuments";
|
||||
import type { TaskDocumentWithTask } from "@fusion/core";
|
||||
import type { MarkdownFileEntry } from "../../api";
|
||||
|
||||
function mockFetchResponse(
|
||||
ok: boolean,
|
||||
@@ -22,9 +23,80 @@ function mockFetchResponse(
|
||||
} as unknown as Response);
|
||||
}
|
||||
|
||||
function createDocumentsFetchMock(options: {
|
||||
documents: TaskDocumentWithTask[];
|
||||
projectFiles: MarkdownFileEntry[];
|
||||
failProjectFiles?: boolean;
|
||||
failDocuments?: boolean;
|
||||
}) {
|
||||
return vi.fn().mockImplementation((input: RequestInfo | URL) => {
|
||||
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
|
||||
if (url.includes("/project-files/md")) {
|
||||
if (options.failProjectFiles) {
|
||||
return mockFetchResponse(false, { error: "Project files failed" }, 500);
|
||||
}
|
||||
return mockFetchResponse(true, options.projectFiles);
|
||||
}
|
||||
|
||||
if (url.includes("/documents")) {
|
||||
if (options.failDocuments) {
|
||||
return mockFetchResponse(false, { error: "Documents failed" }, 500);
|
||||
}
|
||||
return mockFetchResponse(true, options.documents);
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected fetch URL: ${url}`);
|
||||
});
|
||||
}
|
||||
|
||||
describe("useDocuments", () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
const mockDocuments: TaskDocumentWithTask[] = [
|
||||
{
|
||||
id: "doc-1",
|
||||
taskId: "KB-001",
|
||||
key: "plan",
|
||||
content: "Plan content",
|
||||
revision: 1,
|
||||
author: "user",
|
||||
createdAt: "2024-01-01T00:00:00.000Z",
|
||||
updatedAt: "2024-01-01T00:00:00.000Z",
|
||||
taskTitle: "Task One",
|
||||
taskColumn: "triage",
|
||||
},
|
||||
{
|
||||
id: "doc-2",
|
||||
taskId: "KB-002",
|
||||
key: "notes",
|
||||
content: "Notes content",
|
||||
revision: 1,
|
||||
author: "agent",
|
||||
createdAt: "2024-01-02T00:00:00.000Z",
|
||||
updatedAt: "2024-01-02T00:00:00.000Z",
|
||||
taskTitle: "Task Two",
|
||||
taskColumn: "in-progress",
|
||||
},
|
||||
];
|
||||
|
||||
const mockProjectFiles: MarkdownFileEntry[] = [
|
||||
{
|
||||
path: "README.md",
|
||||
name: "README.md",
|
||||
size: 1024,
|
||||
mtime: "2024-01-03T00:00:00.000Z",
|
||||
contentPreview: "# Project README",
|
||||
},
|
||||
{
|
||||
path: "docs/CONTRIBUTING.md",
|
||||
name: "CONTRIBUTING.md",
|
||||
size: 900,
|
||||
mtime: "2024-01-04T00:00:00.000Z",
|
||||
contentPreview: "Contribution guide",
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true });
|
||||
});
|
||||
@@ -34,44 +106,41 @@ describe("useDocuments", () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("loads documents on mount", async () => {
|
||||
const mockDocuments: TaskDocumentWithTask[] = [
|
||||
{
|
||||
id: "doc-1",
|
||||
taskId: "KB-001",
|
||||
key: "plan",
|
||||
content: "Plan content",
|
||||
revision: 1,
|
||||
author: "user",
|
||||
createdAt: "2024-01-01T00:00:00.000Z",
|
||||
updatedAt: "2024-01-01T00:00:00.000Z",
|
||||
taskTitle: "Task One",
|
||||
taskColumn: "triage",
|
||||
},
|
||||
{
|
||||
id: "doc-2",
|
||||
taskId: "KB-002",
|
||||
key: "notes",
|
||||
content: "Notes content",
|
||||
revision: 1,
|
||||
author: "agent",
|
||||
createdAt: "2024-01-02T00:00:00.000Z",
|
||||
updatedAt: "2024-01-02T00:00:00.000Z",
|
||||
taskTitle: "Task Two",
|
||||
taskColumn: "in-progress",
|
||||
},
|
||||
];
|
||||
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(mockFetchResponse(true, mockDocuments));
|
||||
it("loads task documents and project markdown files on mount", async () => {
|
||||
globalThis.fetch = createDocumentsFetchMock({
|
||||
documents: mockDocuments,
|
||||
projectFiles: mockProjectFiles,
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDocuments());
|
||||
|
||||
// Initially loading should be true
|
||||
expect(result.current.loading).toBe(true);
|
||||
expect(result.current.documents).toEqual([]);
|
||||
expect(result.current.projectFiles).toEqual([]);
|
||||
|
||||
await act(async () => {
|
||||
await vi.runAllTimersAsync();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.error).toBeNull();
|
||||
expect(result.current.documents).toHaveLength(2);
|
||||
expect(result.current.projectFiles).toHaveLength(2);
|
||||
expect(result.current.projectFiles[0].name).toBe("README.md");
|
||||
});
|
||||
|
||||
it("continues rendering documents when project file fetch fails", async () => {
|
||||
globalThis.fetch = createDocumentsFetchMock({
|
||||
documents: mockDocuments,
|
||||
projectFiles: [],
|
||||
failProjectFiles: true,
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDocuments());
|
||||
|
||||
// Wait for the initial fetch to complete
|
||||
await act(async () => {
|
||||
await vi.runAllTimersAsync();
|
||||
});
|
||||
@@ -81,12 +150,16 @@ describe("useDocuments", () => {
|
||||
});
|
||||
|
||||
expect(result.current.documents).toHaveLength(2);
|
||||
expect(result.current.documents[0].key).toBe("plan");
|
||||
expect(result.current.documents[0].taskTitle).toBe("Task One");
|
||||
expect(result.current.projectFiles).toEqual([]);
|
||||
expect(result.current.error).toBeNull();
|
||||
});
|
||||
|
||||
it("handles empty documents list", async () => {
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(mockFetchResponse(true, []));
|
||||
it("surfaces task document fetch errors", async () => {
|
||||
globalThis.fetch = createDocumentsFetchMock({
|
||||
documents: [],
|
||||
projectFiles: mockProjectFiles,
|
||||
failDocuments: true,
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDocuments());
|
||||
|
||||
@@ -98,143 +171,44 @@ describe("useDocuments", () => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.error).toBe("Documents failed");
|
||||
expect(result.current.documents).toEqual([]);
|
||||
expect(result.current.projectFiles).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("handles fetch error", async () => {
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(mockFetchResponse(false, { error: "Server error" }, 500));
|
||||
|
||||
const { result } = renderHook(() => useDocuments());
|
||||
|
||||
await act(async () => {
|
||||
await vi.runAllTimersAsync();
|
||||
it("passes search query to both document and project file endpoints", async () => {
|
||||
globalThis.fetch = createDocumentsFetchMock({
|
||||
documents: mockDocuments,
|
||||
projectFiles: mockProjectFiles,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.error).toBe("Server error");
|
||||
expect(result.current.documents).toEqual([]);
|
||||
});
|
||||
|
||||
it("refreshes documents manually", async () => {
|
||||
const initialDocs: TaskDocumentWithTask[] = [
|
||||
{
|
||||
id: "doc-1",
|
||||
taskId: "KB-001",
|
||||
key: "plan",
|
||||
content: "Initial content",
|
||||
revision: 1,
|
||||
author: "user",
|
||||
createdAt: "2024-01-01T00:00:00.000Z",
|
||||
updatedAt: "2024-01-01T00:00:00.000Z",
|
||||
},
|
||||
];
|
||||
|
||||
const updatedDocs: TaskDocumentWithTask[] = [
|
||||
...initialDocs,
|
||||
{
|
||||
id: "doc-2",
|
||||
taskId: "KB-001",
|
||||
key: "notes",
|
||||
content: "New content",
|
||||
revision: 1,
|
||||
author: "user",
|
||||
createdAt: "2024-01-02T00:00:00.000Z",
|
||||
updatedAt: "2024-01-02T00:00:00.000Z",
|
||||
},
|
||||
];
|
||||
|
||||
// Mock for initial fetch + debounce effect (2 calls)
|
||||
globalThis.fetch = vi.fn()
|
||||
.mockResolvedValueOnce(mockFetchResponse(true, initialDocs))
|
||||
.mockResolvedValueOnce(mockFetchResponse(true, initialDocs))
|
||||
.mockResolvedValueOnce(mockFetchResponse(true, updatedDocs));
|
||||
|
||||
const { result } = renderHook(() => useDocuments());
|
||||
|
||||
await act(async () => {
|
||||
await vi.runAllTimersAsync();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.documents).toHaveLength(1);
|
||||
|
||||
// Trigger refresh
|
||||
await act(async () => {
|
||||
await result.current.refresh();
|
||||
});
|
||||
|
||||
expect(result.current.documents).toHaveLength(2);
|
||||
// Loading should still be false after manual refresh
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
|
||||
it("filters documents by search query with debounce", async () => {
|
||||
const allDocs: TaskDocumentWithTask[] = [
|
||||
{
|
||||
id: "doc-1",
|
||||
taskId: "KB-001",
|
||||
key: "plan",
|
||||
content: "Plan content",
|
||||
revision: 1,
|
||||
author: "user",
|
||||
createdAt: "2024-01-01T00:00:00.000Z",
|
||||
updatedAt: "2024-01-01T00:00:00.000Z",
|
||||
taskTitle: "Task One",
|
||||
},
|
||||
{
|
||||
id: "doc-2",
|
||||
taskId: "KB-002",
|
||||
key: "notes",
|
||||
content: "Notes content",
|
||||
revision: 1,
|
||||
author: "user",
|
||||
createdAt: "2024-01-02T00:00:00.000Z",
|
||||
updatedAt: "2024-01-02T00:00:00.000Z",
|
||||
taskTitle: "Task Two",
|
||||
},
|
||||
];
|
||||
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(mockFetchResponse(true, allDocs));
|
||||
|
||||
const { result, rerender } = renderHook(
|
||||
const { rerender } = renderHook(
|
||||
({ searchQuery }) => useDocuments({ searchQuery }),
|
||||
{ initialProps: { searchQuery: undefined as string | undefined } }
|
||||
{ initialProps: { searchQuery: undefined as string | undefined } },
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
await vi.runAllTimersAsync();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
rerender({ searchQuery: "readme" });
|
||||
|
||||
expect(result.current.documents).toHaveLength(2);
|
||||
|
||||
// Update search query - this triggers debounce
|
||||
rerender({ searchQuery: "plan" });
|
||||
|
||||
// Advance past the debounce timer (300ms)
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(350);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
const urls = globalThis.fetch.mock.calls.map((call) => String(call[0]));
|
||||
expect(urls.some((url) => url.includes("/documents?q=readme"))).toBe(true);
|
||||
expect(urls.some((url) => url.includes("/project-files/md?q=readme"))).toBe(true);
|
||||
});
|
||||
|
||||
// Should have called fetch multiple times (initial + debounced)
|
||||
expect(globalThis.fetch).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses projectId for scoped fetching", async () => {
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(mockFetchResponse(true, []));
|
||||
it("uses projectId for both document and project file requests", async () => {
|
||||
globalThis.fetch = createDocumentsFetchMock({
|
||||
documents: mockDocuments,
|
||||
projectFiles: mockProjectFiles,
|
||||
});
|
||||
|
||||
renderHook(() => useDocuments({ projectId: "proj-123" }));
|
||||
|
||||
@@ -243,20 +217,16 @@ describe("useDocuments", () => {
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(globalThis.fetch).toHaveBeenCalled();
|
||||
const urls = globalThis.fetch.mock.calls.map((call) => String(call[0]));
|
||||
expect(urls.some((url) => url.includes("/documents") && url.includes("projectId=proj-123"))).toBe(true);
|
||||
expect(urls.some((url) => url.includes("/project-files/md") && url.includes("projectId=proj-123"))).toBe(true);
|
||||
});
|
||||
|
||||
// Verify the URL contains the projectId
|
||||
const fetchCall = globalThis.fetch.mock.calls[0][0] as Request;
|
||||
const url = fetchCall instanceof Request ? fetchCall.url : fetchCall;
|
||||
expect(String(url)).toContain("projectId=proj-123");
|
||||
});
|
||||
|
||||
it("cancels in-flight request on unmount", async () => {
|
||||
const abortMock = vi.fn();
|
||||
const originalAbortController = globalThis.AbortController;
|
||||
|
||||
// Mock AbortController to track abort calls
|
||||
globalThis.AbortController = vi.fn().mockImplementation(() => ({
|
||||
signal: {},
|
||||
abort: abortMock,
|
||||
@@ -264,8 +234,8 @@ describe("useDocuments", () => {
|
||||
|
||||
globalThis.fetch = vi.fn().mockReturnValue(
|
||||
new Promise(() => {
|
||||
// Never resolve - simulating a pending request
|
||||
})
|
||||
// Keep pending to simulate in-flight requests
|
||||
}),
|
||||
);
|
||||
|
||||
const { unmount } = renderHook(() => useDocuments());
|
||||
@@ -278,7 +248,6 @@ describe("useDocuments", () => {
|
||||
|
||||
expect(abortMock).toHaveBeenCalled();
|
||||
|
||||
// Restore
|
||||
globalThis.AbortController = originalAbortController;
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { useState, useEffect, useRef, useCallback } from "react";
|
||||
import type { TaskDocumentWithTask } from "@fusion/core";
|
||||
import { fetchAllDocuments } from "../api";
|
||||
import { fetchAllDocuments, fetchProjectMarkdownFiles, type MarkdownFileEntry } from "../api";
|
||||
|
||||
export interface UseDocumentsResult {
|
||||
/** List of all documents across tasks */
|
||||
documents: TaskDocumentWithTask[];
|
||||
/** List of markdown files discovered in the project workspace */
|
||||
projectFiles: MarkdownFileEntry[];
|
||||
/** Loading state - true only for initial fetch, false during refresh/search */
|
||||
loading: boolean;
|
||||
/** Error message if fetch failed */
|
||||
/** Error message if task document fetch failed */
|
||||
error: string | null;
|
||||
/** Refresh documents from the server */
|
||||
refresh: () => Promise<void>;
|
||||
@@ -29,6 +31,7 @@ export function useDocuments(options?: {
|
||||
}): UseDocumentsResult {
|
||||
const { projectId, searchQuery } = options ?? {};
|
||||
const [documents, setDocuments] = useState<TaskDocumentWithTask[]>([]);
|
||||
const [projectFiles, setProjectFiles] = useState<MarkdownFileEntry[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const abortRef = useRef<AbortController | null>(null);
|
||||
@@ -46,7 +49,9 @@ export function useDocuments(options?: {
|
||||
if (abortRef.current) {
|
||||
abortRef.current.abort();
|
||||
}
|
||||
abortRef.current = new AbortController();
|
||||
|
||||
const requestController = new AbortController();
|
||||
abortRef.current = requestController;
|
||||
|
||||
// Only set loading on initial load
|
||||
const isInitial = !initialLoadCompleteRef.current;
|
||||
@@ -55,23 +60,44 @@ export function useDocuments(options?: {
|
||||
}
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await fetchAllDocuments(
|
||||
searchQuery ? { q: searchQuery } : undefined,
|
||||
projectId,
|
||||
);
|
||||
setDocuments(result);
|
||||
const documentFetchPromise = fetchAllDocuments(
|
||||
searchQuery ? { q: searchQuery } : undefined,
|
||||
projectId,
|
||||
);
|
||||
|
||||
const projectFileFetchPromise = fetchProjectMarkdownFiles(
|
||||
searchQuery ? { q: searchQuery } : undefined,
|
||||
projectId,
|
||||
);
|
||||
|
||||
const [documentResult, projectFileResult] = await Promise.allSettled([
|
||||
documentFetchPromise,
|
||||
projectFileFetchPromise,
|
||||
]);
|
||||
|
||||
if (requestController.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
|
||||
let documentError: string | null = null;
|
||||
|
||||
if (documentResult.status === "fulfilled") {
|
||||
setDocuments(documentResult.value);
|
||||
initialLoadCompleteRef.current = true;
|
||||
} else {
|
||||
documentError = documentResult.reason instanceof Error
|
||||
? documentResult.reason.message
|
||||
: String(documentResult.reason);
|
||||
}
|
||||
|
||||
if (projectFileResult.status === "fulfilled") {
|
||||
setProjectFiles(projectFileResult.value);
|
||||
}
|
||||
|
||||
setError(documentError);
|
||||
|
||||
if (isInitial) {
|
||||
setLoading(false);
|
||||
} catch (err) {
|
||||
if (abortRef.current?.signal.aborted) {
|
||||
// Request was cancelled - ignore
|
||||
return;
|
||||
}
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
if (isInitial) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
}, [projectId, searchQuery]);
|
||||
|
||||
@@ -101,11 +127,11 @@ export function useDocuments(options?: {
|
||||
abortRef.current.abort();
|
||||
}
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/no-use-before-define
|
||||
}, []);
|
||||
|
||||
return {
|
||||
documents,
|
||||
projectFiles,
|
||||
loading,
|
||||
error,
|
||||
refresh,
|
||||
|
||||
@@ -27385,6 +27385,179 @@ html .column.drag-over * {
|
||||
gap: var(--space-md);
|
||||
}
|
||||
|
||||
.documents-view-sections {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-md);
|
||||
}
|
||||
|
||||
.documents-project-files {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
background: var(--card);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.documents-project-files-header {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-sm);
|
||||
padding: var(--space-md);
|
||||
background: var(--surface);
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
transition: background var(--transition-fast);
|
||||
min-height: 44px;
|
||||
}
|
||||
|
||||
.documents-project-files-header:hover {
|
||||
background: var(--surface-hover, color-mix(in srgb, var(--text) 4%, transparent));
|
||||
}
|
||||
|
||||
.documents-project-files-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.documents-project-files-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.documents-project-files-count {
|
||||
margin-left: auto;
|
||||
font-size: 12px;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.documents-project-files-empty {
|
||||
margin: 0;
|
||||
padding: var(--space-md);
|
||||
color: var(--text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.documents-project-files-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-sm);
|
||||
padding: var(--space-md);
|
||||
}
|
||||
|
||||
.documents-project-file {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
overflow: hidden;
|
||||
background: var(--card);
|
||||
}
|
||||
|
||||
.documents-project-file-card {
|
||||
width: 100%;
|
||||
border: none;
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
padding: var(--space-md);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-xs);
|
||||
cursor: pointer;
|
||||
transition: background var(--transition-fast);
|
||||
}
|
||||
|
||||
.documents-project-file-card:hover {
|
||||
background: var(--card-hover);
|
||||
}
|
||||
|
||||
.documents-project-file-card:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: var(--focus-ring-strong);
|
||||
}
|
||||
|
||||
.documents-project-file-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-sm);
|
||||
}
|
||||
|
||||
.documents-project-file-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-xs);
|
||||
color: var(--text);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.documents-project-file-title svg {
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.documents-project-file-toggle {
|
||||
color: var(--text-muted);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.documents-project-file-path {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
font-family: var(--font-mono);
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.documents-project-file-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-xs);
|
||||
font-size: 12px;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.documents-project-file-preview {
|
||||
margin: 0;
|
||||
color: var(--text-muted);
|
||||
font-size: 13px;
|
||||
line-height: 1.4;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.documents-project-file-content {
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
padding: var(--space-md);
|
||||
}
|
||||
|
||||
.documents-project-file-content-state {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.documents-project-file-content-state--error {
|
||||
color: var(--color-error);
|
||||
}
|
||||
|
||||
.documents-project-file-content-text {
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: var(--text);
|
||||
font-family: var(--font-primary);
|
||||
}
|
||||
|
||||
/* Document Group */
|
||||
.documents-group {
|
||||
border: 1px solid var(--border);
|
||||
@@ -27743,6 +27916,30 @@ html .column.drag-over * {
|
||||
.document-card-key-text {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.documents-project-files-header {
|
||||
min-height: 36px;
|
||||
padding: var(--space-sm) var(--space-md);
|
||||
}
|
||||
|
||||
.documents-project-files-list {
|
||||
padding: var(--space-sm);
|
||||
}
|
||||
|
||||
.documents-project-file-card {
|
||||
padding: var(--space-sm);
|
||||
}
|
||||
|
||||
.documents-project-file-path,
|
||||
.documents-project-file-meta {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.documents-project-file-preview,
|
||||
.documents-project-file-content-state,
|
||||
.documents-project-file-content-text {
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
/* === Active Agents Panel === */
|
||||
|
||||
Reference in New Issue
Block a user