feat(FN-4012): restore workspace verification in chat room routes
The merge adds comprehensive test coverage for dashboard routing infrastructure — custom providers tests, setup routes tests, and chat manager tests — while making a minor adjustment to chat room route registration. The CLI side sees a small bundle output test update tied to the same FN-4012 work. Fusion-Task-Id: FN-4012
This commit is contained in:
@@ -2,8 +2,9 @@ import { mkdtempSync } from "node:fs";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { ChatStore, Database } from "@fusion/core";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { AgentStore, ChatStore, Database } from "@fusion/core";
|
||||
import { ChatManager } from "../chat.js";
|
||||
import { request } from "../test-request.js";
|
||||
import { RoomReplyGenerationError } from "../chat.js";
|
||||
|
||||
@@ -311,6 +312,74 @@ describe("Chat Room API Routes", () => {
|
||||
expect(missingMessage.status).toBe(404);
|
||||
});
|
||||
|
||||
it("resolves project-scoped room services for message replies", async () => {
|
||||
const scopedRoot = mkdtempSync(join(tmpdir(), "fusion-chat-room-scoped-"));
|
||||
const scopedFusionDir = join(scopedRoot, ".fusion");
|
||||
const scopedDb = new Database(scopedFusionDir, { inMemory: true });
|
||||
scopedDb.init();
|
||||
const scopedStore = new MockStore(scopedRoot, scopedDb);
|
||||
const scopedChatStore = new ChatStore(scopedFusionDir, scopedDb);
|
||||
|
||||
const scopedAgentStore = new AgentStore({ rootDir: scopedStore.getFusionDir() });
|
||||
await scopedAgentStore.init();
|
||||
const scopedAgent = await scopedAgentStore.createAgent({
|
||||
name: "agent room",
|
||||
role: "executor",
|
||||
status: "active",
|
||||
});
|
||||
|
||||
const room = scopedChatStore.createRoom({
|
||||
name: "Scoped Room",
|
||||
projectId: "proj-scope",
|
||||
memberAgentIds: [scopedAgent.id],
|
||||
});
|
||||
|
||||
const defaultChatManager = {
|
||||
sendRoomMessage: async () => {
|
||||
throw new Error("default chat manager should not handle scoped room sends");
|
||||
},
|
||||
};
|
||||
|
||||
const { createServer } = await import("../server.js");
|
||||
const appWithScopedEngine = createServer(store as any, {
|
||||
chatStore,
|
||||
chatManager: defaultChatManager as any,
|
||||
engineManager: {
|
||||
getEngine: (projectId: string) => {
|
||||
if (projectId !== "proj-scope") return undefined;
|
||||
return {
|
||||
getTaskStore: () => scopedStore,
|
||||
getMessageStore: () => undefined,
|
||||
};
|
||||
},
|
||||
ensureEngine: async () => undefined,
|
||||
} as any,
|
||||
});
|
||||
|
||||
const responderSpy = vi.spyOn(ChatManager.prototype as any, "generateRoomResponderReply").mockResolvedValue({
|
||||
content: "scoped reply",
|
||||
thinkingOutput: null,
|
||||
metadata: { roomId: room.id },
|
||||
});
|
||||
|
||||
const postRes = await request(
|
||||
appWithScopedEngine,
|
||||
"POST",
|
||||
`/api/chat/rooms/${room.id}/messages?projectId=proj-scope`,
|
||||
JSON.stringify({ content: "hello scoped room" }),
|
||||
{ "content-type": "application/json" },
|
||||
);
|
||||
|
||||
expect(postRes.status).toBe(201);
|
||||
const scopedMessages = scopedChatStore.getRoomMessages(room.id);
|
||||
expect(scopedMessages.some((message) => message.role === "assistant" && message.senderAgentId === scopedAgent.id)).toBe(true);
|
||||
expect(chatStore.getRoomMessages(room.id)).toHaveLength(0);
|
||||
|
||||
responderSpy.mockRestore();
|
||||
scopedDb.close();
|
||||
await rm(scopedRoot, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("rate-limits GET /chat/rooms", async () => {
|
||||
let status = 200;
|
||||
for (let i = 0; i < 1020; i++) {
|
||||
|
||||
@@ -48,9 +48,15 @@ vi.mock("@fusion/engine", () => ({
|
||||
createResolvedAgentSession: vi.fn(async () => ({
|
||||
session: {
|
||||
state: { messages: [] as Array<{ role: string; content: string }> },
|
||||
prompt: vi.fn(),
|
||||
prompt: vi.fn(async function (this: { state?: { messages?: Array<{ role: string; content: string }> } }, message: string) {
|
||||
const messages = this.state?.messages ?? [];
|
||||
messages.push({ role: "user", content: message });
|
||||
messages.push({ role: "assistant", content: JSON.stringify({ subtasks: [] }) });
|
||||
}),
|
||||
dispose: vi.fn(),
|
||||
},
|
||||
provider: "test",
|
||||
model: "test",
|
||||
})),
|
||||
AgentReflectionService: class {
|
||||
async generateReflection(): Promise<never> { throw new Error("Reflection service unavailable"); }
|
||||
|
||||
@@ -29,7 +29,11 @@ vi.mock("@fusion/core", async () => {
|
||||
|
||||
vi.mock("@fusion/engine", () => ({
|
||||
createFnAgent: vi.fn(async () => ({ session: { state: { messages: [] }, prompt: vi.fn(), dispose: vi.fn() } })),
|
||||
createResolvedAgentSession: vi.fn(async () => ({ session: { state: { messages: [] }, prompt: vi.fn(), dispose: vi.fn() } })),
|
||||
createResolvedAgentSession: vi.fn(async () => ({
|
||||
session: { state: { messages: [] }, prompt: vi.fn(), dispose: vi.fn() },
|
||||
provider: "test",
|
||||
model: "test",
|
||||
})),
|
||||
promptWithFallback: vi.fn(),
|
||||
}));
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ChatAttachment, ChatRoomCreateInput, ChatRoomStatus, ChatRoomUpdateInput } from "@fusion/core";
|
||||
import { RoomReplyGenerationError } from "../chat.js";
|
||||
import { AgentStore, ChatStore, type ChatAttachment, type ChatRoomCreateInput, type ChatRoomStatus, type ChatRoomUpdateInput } from "@fusion/core";
|
||||
import type { Request } from "express";
|
||||
import { ChatManager, RoomReplyGenerationError } from "../chat.js";
|
||||
import { ApiError, badRequest, internalError, notFound } from "../api-error.js";
|
||||
import { rateLimit, RATE_LIMITS } from "../rate-limit.js";
|
||||
import type { ApiRoutesContext } from "./types.js";
|
||||
@@ -10,7 +11,48 @@ function isSlugCollisionError(err: unknown): boolean {
|
||||
}
|
||||
|
||||
export function registerChatRoomRoutes(ctx: ApiRoutesContext): void {
|
||||
const { router, options, chatLogger, rethrowAsApiError } = ctx;
|
||||
const { router, options, chatLogger, rethrowAsApiError, getProjectContext } = ctx;
|
||||
const scopedRoomManagers = new Map<string, { chatStore: ChatStore; chatManager: ChatManager }>();
|
||||
|
||||
async function resolveRoomScopedServices(req: Request, roomProjectId: string | null | undefined): Promise<{ chatStore: ChatStore; chatManager: ChatManager }> {
|
||||
if (!roomProjectId) {
|
||||
const chatStore = options?.chatStore;
|
||||
const chatManager = options?.chatManager;
|
||||
if (!chatStore || !chatManager) {
|
||||
throw internalError("Chat store or manager not available");
|
||||
}
|
||||
return { chatStore, chatManager };
|
||||
}
|
||||
|
||||
const cached = scopedRoomManagers.get(roomProjectId);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const scopedReq = {
|
||||
...req,
|
||||
query: { ...(req.query as Record<string, unknown>), projectId: roomProjectId },
|
||||
body: typeof req.body === "object" && req.body !== null
|
||||
? { ...(req.body as Record<string, unknown>), projectId: roomProjectId }
|
||||
: { projectId: roomProjectId },
|
||||
} as unknown as Request;
|
||||
const { store: scopedStore, engine } = await getProjectContext(scopedReq);
|
||||
|
||||
const scopedChatStore = new ChatStore(scopedStore.getFusionDir(), scopedStore.getDatabase());
|
||||
const scopedAgentStore = new AgentStore({ rootDir: scopedStore.getFusionDir() });
|
||||
const scopedChatManager = new ChatManager(
|
||||
scopedChatStore,
|
||||
scopedStore.getRootDir(),
|
||||
scopedAgentStore,
|
||||
options?.pluginRunner,
|
||||
() => scopedStore.getSettings(),
|
||||
engine?.getMessageStore(),
|
||||
);
|
||||
|
||||
const resolved = { chatStore: scopedChatStore, chatManager: scopedChatManager };
|
||||
scopedRoomManagers.set(roomProjectId, resolved);
|
||||
return resolved;
|
||||
}
|
||||
|
||||
router.get("/chat/rooms", rateLimit(RATE_LIMITS.api), async (req, res) => {
|
||||
try {
|
||||
@@ -237,11 +279,15 @@ export function registerChatRoomRoutes(ctx: ApiRoutesContext): void {
|
||||
|
||||
router.post("/chat/rooms/:id/messages", rateLimit(RATE_LIMITS.mutation), async (req, res) => {
|
||||
try {
|
||||
const chatStore = options?.chatStore;
|
||||
if (!chatStore) throw internalError("Chat store not available");
|
||||
const defaultChatStore = options?.chatStore;
|
||||
if (!defaultChatStore) throw internalError("Chat store not available");
|
||||
|
||||
const roomId = String(req.params.id);
|
||||
const room = chatStore.getRoom(roomId);
|
||||
const hintedProjectId = typeof req.query.projectId === "string"
|
||||
? req.query.projectId
|
||||
: (typeof req.body?.projectId === "string" ? req.body.projectId : undefined);
|
||||
const room = defaultChatStore.getRoom(roomId)
|
||||
?? (hintedProjectId ? (await resolveRoomScopedServices(req, hintedProjectId)).chatStore.getRoom(roomId) : undefined);
|
||||
if (!room) throw notFound(`Chat room ${roomId} not found`);
|
||||
|
||||
const { content, senderAgentId, attachments } = req.body as {
|
||||
@@ -258,9 +304,7 @@ export function registerChatRoomRoutes(ctx: ApiRoutesContext): void {
|
||||
throw badRequest("senderAgentId is reserved for FN-3810; must be null or omitted");
|
||||
}
|
||||
|
||||
const chatManager = options?.chatManager;
|
||||
if (!chatManager) throw internalError("Chat manager not available");
|
||||
|
||||
const { chatManager } = await resolveRoomScopedServices(req, room.projectId);
|
||||
const result = await chatManager.sendRoomMessage(roomId, content.trim(), Array.isArray(attachments) ? attachments : undefined);
|
||||
|
||||
res.status(201).json({ message: result.userMessage });
|
||||
|
||||
Reference in New Issue
Block a user