feat(FN-1741): add memory compaction feature
- Add MemoryCompaction service in core for compacting agent memory stores - Add POST /api/memory/compact route handler in dashboard server - Add compactMemory frontend API wrapper in dashboard app - Add Compact Memory button to SettingsModal UI - Add comprehensive tests for the compaction service and routes
This commit is contained in:
@@ -3499,6 +3499,87 @@ describe("fetchMemoryBackendStatus", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("compactMemory", () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
beforeEach(() => {
|
||||
globalThis.fetch = vi.fn();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
});
|
||||
|
||||
it("calls POST /api/memory/compact without projectId", async () => {
|
||||
const { compactMemory } = await import("./api");
|
||||
|
||||
const mockResponse = { content: "# Compacted Memory\n\nImportant content here." };
|
||||
(globalThis.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
headers: {
|
||||
get: (name: string) =>
|
||||
name.toLowerCase() === "content-type" ? "application/json" : null,
|
||||
},
|
||||
json: () => Promise.resolve(mockResponse),
|
||||
text: () => Promise.resolve(JSON.stringify(mockResponse)),
|
||||
} as unknown as Response);
|
||||
|
||||
const result = await compactMemory();
|
||||
|
||||
expect(result).toEqual(mockResponse);
|
||||
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
|
||||
const call = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
|
||||
expect(call[0]).toContain("/api/memory/compact");
|
||||
expect(call[1].method).toBe("POST");
|
||||
});
|
||||
|
||||
it("calls POST /api/memory/compact with projectId", async () => {
|
||||
const { compactMemory } = await import("./api");
|
||||
|
||||
const mockResponse = { content: "# Compacted Memory\n\nImportant content here." };
|
||||
(globalThis.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
headers: {
|
||||
get: (name: string) =>
|
||||
name.toLowerCase() === "content-type" ? "application/json" : null,
|
||||
},
|
||||
json: () => Promise.resolve(mockResponse),
|
||||
text: () => Promise.resolve(JSON.stringify(mockResponse)),
|
||||
} as unknown as Response);
|
||||
|
||||
const result = await compactMemory("proj_abc");
|
||||
|
||||
expect(result).toEqual(mockResponse);
|
||||
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
|
||||
const call = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
|
||||
expect(call[0]).toContain("/api/memory/compact");
|
||||
expect(call[0]).toContain("projectId=proj_abc");
|
||||
expect(call[1].method).toBe("POST");
|
||||
});
|
||||
|
||||
it("throws on error response", async () => {
|
||||
const { compactMemory } = await import("./api");
|
||||
|
||||
(globalThis.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
ok: false,
|
||||
status: 503,
|
||||
statusText: "Service Unavailable",
|
||||
headers: {
|
||||
get: (name: string) =>
|
||||
name.toLowerCase() === "content-type" ? "application/json" : null,
|
||||
},
|
||||
json: () => Promise.resolve({ error: "AI service temporarily unavailable" }),
|
||||
text: () => Promise.resolve(JSON.stringify({ error: "AI service temporarily unavailable" })),
|
||||
} as unknown as Response);
|
||||
|
||||
await expect(compactMemory()).rejects.toThrow("AI service temporarily unavailable");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Roadmap API wrappers", () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
|
||||
@@ -323,6 +323,18 @@ export function saveMemory(content: string, projectId?: string): Promise<{ succe
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact memory content using AI to distill it down to the most important insights.
|
||||
* Reads current memory, compacts it via AI, and writes the result back.
|
||||
* @param projectId - Optional project ID for multi-project support
|
||||
* @returns Promise resolving to the compacted memory content
|
||||
*/
|
||||
export function compactMemory(projectId?: string): Promise<{ content: string }> {
|
||||
return api<{ content: string }>(withProjectId("/memory/compact", projectId), {
|
||||
method: "POST",
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Memory backend capabilities returned by the backend status API.
|
||||
*/
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback, useRef } from "react";
|
||||
import { Globe, Folder } from "lucide-react";
|
||||
import { THINKING_LEVELS, PROMPT_KEY_CATALOG, isGlobalSettingsKey, isProjectSettingsKey } from "@fusion/core";
|
||||
import type { Settings, GlobalSettings, ThemeMode, ColorTheme, ModelPreset, NtfyNotificationEvent, PromptKey, AgentPromptsConfig } from "@fusion/core";
|
||||
import { fetchSettings, fetchSettingsByScope, updateSettings, updateGlobalSettings, fetchAuthStatus, loginProvider, logoutProvider, saveApiKey, clearApiKey, fetchModels, testNtfyNotification, fetchBackups, createBackup, exportSettings, importSettings, fetchMemory, saveMemory, fetchGlobalConcurrency, updateGlobalConcurrency } from "../api";
|
||||
import { fetchSettings, fetchSettingsByScope, updateSettings, updateGlobalSettings, fetchAuthStatus, loginProvider, logoutProvider, saveApiKey, clearApiKey, fetchModels, testNtfyNotification, fetchBackups, createBackup, exportSettings, importSettings, fetchMemory, saveMemory, fetchGlobalConcurrency, updateGlobalConcurrency, compactMemory } from "../api";
|
||||
import type { AuthProvider, ModelInfo, BackupListResponse, SettingsExportData, MemoryBackendCapabilities } from "../api";
|
||||
import { useMemoryBackendStatus } from "../hooks/useMemoryBackendStatus";
|
||||
import type { ToastType } from "../hooks/useToast";
|
||||
@@ -151,6 +151,7 @@ export function SettingsModal({
|
||||
const [memoryContent, setMemoryContent] = useState("");
|
||||
const [memoryLoading, setMemoryLoading] = useState(false);
|
||||
const [memoryDirty, setMemoryDirty] = useState(false);
|
||||
const [compactLoading, setCompactLoading] = useState(false);
|
||||
|
||||
// Global concurrency state
|
||||
const [globalMaxConcurrent, setGlobalMaxConcurrent] = useState<number | undefined>(4);
|
||||
@@ -777,6 +778,20 @@ export function SettingsModal({
|
||||
}
|
||||
}, [memoryContent, projectId, addToast]);
|
||||
|
||||
const handleCompactMemory = useCallback(async () => {
|
||||
setCompactLoading(true);
|
||||
try {
|
||||
const { content } = await compactMemory(projectId);
|
||||
setMemoryContent(content);
|
||||
setMemoryDirty(true);
|
||||
addToast("Memory compacted successfully", "success");
|
||||
} catch (err: any) {
|
||||
addToast(err?.message || "Failed to compact memory", "error");
|
||||
} finally {
|
||||
setCompactLoading(false);
|
||||
}
|
||||
}, [projectId, addToast]);
|
||||
|
||||
const savePresetDraft = () => {
|
||||
if (!presetDraft) return;
|
||||
|
||||
@@ -2072,6 +2087,19 @@ export function SettingsModal({
|
||||
<small className="field-error">Cannot save: {isMemoryEnabled ? "Backend is read-only" : "Memory is disabled"}</small>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isEditingAllowed && (
|
||||
<div className="form-group">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary btn-sm"
|
||||
onClick={handleCompactMemory}
|
||||
disabled={compactLoading}
|
||||
>
|
||||
{compactLoading ? "Compacting…" : "Compact Memory"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -70,6 +70,7 @@ vi.mock("../../api", () => ({
|
||||
importSettings: vi.fn(() => Promise.resolve({ success: true, globalCount: 0, projectCount: 0 })),
|
||||
fetchMemory: vi.fn(() => Promise.resolve({ content: "" })),
|
||||
saveMemory: vi.fn(() => Promise.resolve({ success: true })),
|
||||
compactMemory: vi.fn(() => Promise.resolve({ content: "# Compacted Memory\n\nImportant content." })),
|
||||
}));
|
||||
|
||||
// Mock useMemoryBackendStatus hook
|
||||
@@ -3686,4 +3687,129 @@ describe("Prompts section", () => {
|
||||
expect(globalPayload.defaultModelId).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Memory section - Compact Memory", () => {
|
||||
it("renders Compact Memory button in memory section", async () => {
|
||||
render(<SettingsModal onClose={onClose} addToast={addToast} />);
|
||||
await waitFor(() => expect(fetchSettings).toHaveBeenCalled());
|
||||
|
||||
// Navigate to Memory section
|
||||
const memorySection = screen.getByText("Memory");
|
||||
fireEvent.click(memorySection);
|
||||
|
||||
await waitFor(() => {
|
||||
// Should show Compact Memory button
|
||||
expect(screen.getByText("Compact Memory")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("calls compactMemory when Compact Memory button is clicked", async () => {
|
||||
const { compactMemory } = await import("../../api");
|
||||
(compactMemory as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
content: "# Compacted Memory\n\nImportant content.",
|
||||
});
|
||||
|
||||
render(<SettingsModal onClose={onClose} addToast={addToast} />);
|
||||
await waitFor(() => expect(fetchSettings).toHaveBeenCalled());
|
||||
|
||||
// Navigate to Memory section
|
||||
const memorySection = screen.getByText("Memory");
|
||||
fireEvent.click(memorySection);
|
||||
|
||||
await waitFor(() => {
|
||||
// Click Compact Memory button
|
||||
const compactBtn = screen.getByText("Compact Memory");
|
||||
fireEvent.click(compactBtn);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(compactMemory).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("updates editor content after successful compaction", async () => {
|
||||
const { compactMemory } = await import("../../api");
|
||||
const newContent = "# Compacted Memory\n\nImportant content.";
|
||||
(compactMemory as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
content: newContent,
|
||||
});
|
||||
|
||||
render(<SettingsModal onClose={onClose} addToast={addToast} />);
|
||||
await waitFor(() => expect(fetchSettings).toHaveBeenCalled());
|
||||
|
||||
// Navigate to Memory section
|
||||
const memorySection = screen.getByText("Memory");
|
||||
fireEvent.click(memorySection);
|
||||
|
||||
await waitFor(() => {
|
||||
// Click Compact Memory button
|
||||
const compactBtn = screen.getByText("Compact Memory");
|
||||
fireEvent.click(compactBtn);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
// Should show success toast
|
||||
expect(addToast).toHaveBeenCalledWith("Memory compacted successfully", "success");
|
||||
});
|
||||
});
|
||||
|
||||
it("disables button while compacting", async () => {
|
||||
let resolveCompact: (value: { content: string }) => void;
|
||||
const { compactMemory } = await import("../../api");
|
||||
(compactMemory as ReturnType<typeof vi.fn>).mockImplementation(
|
||||
() => new Promise((resolve) => { resolveCompact = resolve; })
|
||||
);
|
||||
|
||||
render(<SettingsModal onClose={onClose} addToast={addToast} />);
|
||||
await waitFor(() => expect(fetchSettings).toHaveBeenCalled());
|
||||
|
||||
// Navigate to Memory section
|
||||
const memorySection = screen.getByText("Memory");
|
||||
fireEvent.click(memorySection);
|
||||
|
||||
await waitFor(() => {
|
||||
// Click Compact Memory button
|
||||
const compactBtn = screen.getByText("Compact Memory");
|
||||
fireEvent.click(compactBtn);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
// Button should show loading text
|
||||
expect(screen.getByText("Compacting…")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Complete the promise
|
||||
resolveCompact!({ content: "# Compacted Memory\n\nImportant content." });
|
||||
|
||||
await waitFor(() => {
|
||||
// Button should be back to normal
|
||||
expect(screen.getByText("Compact Memory")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("shows error toast when compaction fails", async () => {
|
||||
const { compactMemory } = await import("../../api");
|
||||
(compactMemory as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
|
||||
new Error("AI service unavailable")
|
||||
);
|
||||
|
||||
render(<SettingsModal onClose={onClose} addToast={addToast} />);
|
||||
await waitFor(() => expect(fetchSettings).toHaveBeenCalled());
|
||||
|
||||
// Navigate to Memory section
|
||||
const memorySection = screen.getByText("Memory");
|
||||
fireEvent.click(memorySection);
|
||||
|
||||
await waitFor(() => {
|
||||
// Click Compact Memory button
|
||||
const compactBtn = screen.getByText("Compact Memory");
|
||||
fireEvent.click(compactBtn);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
// Should show error toast
|
||||
expect(addToast).toHaveBeenCalledWith("AI service unavailable", "error");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user