import assert from "node:assert/strict";
import { describe, it, beforeEach, afterEach, mock } from "node:test";
import { AgentClient } from "./agent-client.js";
// Helper function to create a complete ProfileInfo
function createProfileInfo(overrides = {}) {
    return {
        id: "agent-1",
        displayName: "Agent One",
        roleName: "Backend Agent",
        prompt: "backend development",
        isOnline: true,
        onlineSince: new Date().toISOString(),
        createdAt: new Date().toISOString(),
        ...overrides,
    };
}
describe("AgentClient", () => {
    const originalEnv = { ...process.env };
    beforeEach(() => {
        delete process.env.AWS_SERVER_URL;
        delete process.env.AWS_HEARTBEAT_INTERVAL;
        delete process.env.AWS_WORKSPACE_PATH;
        delete process.env.AWS_ROLE_NAME;
        delete process.env.AWS_AGENT_ID;
        delete process.env.AWS_PROJECT_NAME;
        delete process.env.AWS_PROMPT;
        delete process.env.AWS_MCP_HTTP_URL;
        delete process.env.AWS_RUNTIME_BRIDGE_BASE_URL;
    });
    afterEach(() => {
        process.env = { ...originalEnv };
        mock.restoreAll();
    });
    describe("initialize", () => {
        it("should allow preset agentId without direct env token when no launch binding is available", async () => {
            process.env.AWS_AGENT_ID = "preset-agent-without-token";
            process.env.AWS_RUNTIME_BRIDGE_BASE_URL = "http://127.0.0.1:18081";
            mock.method(globalThis, "fetch", async () => new Response("", { status: 404 }));
            const client = new AgentClient();
            await client.initialize();
            assert.equal(client.getAgentConfig().agentId, "preset-agent-without-token");
        });
        it("should allow preset agentId when launch binding provides runtime token", async () => {
            process.env.AWS_AGENT_ID = "preset-agent-with-token";
            process.env.AWS_RUNTIME_BRIDGE_BASE_URL = "http://127.0.0.1:18081";
            mock.method(globalThis, "fetch", async () => new Response(JSON.stringify({
                agentId: "preset-agent-with-token",
                workspacePath: "/workspace/demo",
                runtimeAccessToken: "agent-token-1234567890",
                schedulerBaseUrl: "http://scheduler:7380",
            }), { status: 200, headers: { "Content-Type": "application/json" } }));
            const client = new AgentClient();
            await client.initialize();
            assert.equal(client.getAgentConfig().agentId, "preset-agent-with-token");
        });
    });
    describe("register", () => {
        it("should register as new agent when no preset agentId", async () => {
            process.env.AWS_ROLE_NAME = "test-role";
            process.env.AWS_PROJECT_NAME = "test-project";
            const client = new AgentClient();
            const registerResult = {
                agentId: "agent-new-123",
                displayName: "test-role-A1B2",
                status: "online",
                projectName: "test-project",
            };
            Reflect.set(client, "httpClient", {
                callTool: async () => registerResult,
            });
            Reflect.set(client, "wsClient", {
                connect: async () => { },
                disconnect: () => { },
                isConnected: () => true,
                on: () => { },
            });
            const result = await client.register();
            assert.equal(result.agentId, "agent-new-123");
            assert.equal(result.displayName, "test-role-A1B2");
            assert.equal(result.status, "online");
        });
        it("should use preset agentId when provided", async () => {
            process.env.AWS_AGENT_ID = "preset-agent-456";
            process.env.AWS_ROLE_NAME = "backend-expert";
            const client = new AgentClient();
            const profileInfo = createProfileInfo({
                id: "preset-agent-456",
                displayName: "Backend Expert-X7Y8",
                projectName: "demo",
                workspacePath: "/workspace/demo",
            });
            Reflect.set(client, "httpClient", {
                callTool: async (toolName) => {
                    if (toolName === "get_profile") {
                        return profileInfo;
                    }
                    return {};
                },
            });
            Reflect.set(client, "wsClient", {
                connect: async () => { },
                disconnect: () => { },
                isConnected: () => true,
                on: () => { },
            });
            const result = await client.register();
            assert.equal(result.agentId, "preset-agent-456");
        });
        it("should return online after reconnecting with preset agentId", async () => {
            process.env.AWS_AGENT_ID = "preset-agent-456";
            process.env.AWS_ROLE_NAME = "backend-expert";
            const client = new AgentClient();
            const offlineProfile = createProfileInfo({
                id: "preset-agent-456",
                displayName: "Backend Expert-X7Y8",
                projectName: "demo",
                workspacePath: "/workspace/demo",
                isOnline: false,
                onlineSince: null,
            });
            const onlineProfile = createProfileInfo({
                id: "preset-agent-456",
                displayName: "Backend Expert-X7Y8",
                projectName: "demo",
                workspacePath: "/workspace/demo",
                isOnline: true,
            });
            let getProfileCallCount = 0;
            Reflect.set(client, "httpClient", {
                callTool: async (toolName) => {
                    if (toolName === "get_profile") {
                        getProfileCallCount += 1;
                        return getProfileCallCount === 1 ? offlineProfile : onlineProfile;
                    }
                    return {};
                },
            });
            let connectCalled = false;
            Reflect.set(client, "wsClient", {
                connect: async () => {
                    connectCalled = true;
                },
                disconnect: () => { },
                isConnected: () => true,
                send: () => true,
                on: () => { },
            });
            const result = await client.register();
            assert.equal(connectCalled, true);
            assert.equal(getProfileCallCount, 2);
            assert.equal(result.agentId, "preset-agent-456");
            assert.equal(result.status, "online");
            assert.equal(result.projectName, "demo");
            assert.equal(result.workspacePath, "/workspace/demo");
        });
        it("should throw error when registration fails without agentId", async () => {
            process.env.AWS_ROLE_NAME = "test-role";
            const client = new AgentClient();
            Reflect.set(client, "httpClient", {
                callTool: async () => ({}),
            });
            await assert.rejects(async () => await client.register(), /agentId was not returned/);
        });
    });
    describe("unregister", () => {
        it("should call unregister tool and disconnect", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-to-unregister");
            let unregisterCalled = false;
            Reflect.set(client, "httpClient", {
                callTool: async (toolName) => {
                    if (toolName === "unregister") {
                        unregisterCalled = true;
                    }
                    return {};
                },
            });
            let disconnectCalled = false;
            Reflect.set(client, "wsClient", {
                disconnect: () => {
                    disconnectCalled = true;
                },
                isConnected: () => false,
            });
            await client.unregister();
            assert.equal(unregisterCalled, true);
            assert.equal(disconnectCalled, true);
        });
    });
    describe("sendGroupMessage", () => {
        it("should send group message with correct parameters", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            Reflect.set(client, "projectName", "demo");
            let capturedArgs;
            Reflect.set(client, "httpClient", {
                callTool: async (_toolName, args) => {
                    capturedArgs = args;
                    return { msgId: 1, timestamp: new Date().toISOString() };
                },
            });
            await client.sendGroupMessage("hello group", "demo", "project:demo");
            assert.equal(capturedArgs?.agentId, "agent-1");
            assert.equal(capturedArgs?.projectName, "demo");
            assert.equal(capturedArgs?.roomId, "project:demo");
            assert.equal(capturedArgs?.content, "hello group");
        });
        it("should throw when not registered", async () => {
            const client = new AgentClient();
            await assert.rejects(async () => await client.sendGroupMessage("hello"), /Agent is not registered/);
        });
    });
    describe("sendDirectMessage", () => {
        it("should send direct message with correct parameters", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            let capturedArgs;
            Reflect.set(client, "httpClient", {
                callTool: async (_toolName, args) => {
                    capturedArgs = args;
                    return { msgId: "dm-1", timestamp: new Date().toISOString() };
                },
            });
            await client.sendDirectMessage("target-user", "hello dm", true, undefined, 30000);
            assert.equal(capturedArgs?.agentId, "agent-1");
            assert.equal(capturedArgs?.targetId, "target-user");
            assert.equal(capturedArgs?.content, "hello dm");
            assert.equal(capturedArgs?.requireReply, true);
            assert.equal(capturedArgs?.timeoutMs, 30000);
        });
    });
    describe("sendCallAndWaitReply", () => {
        it("should return reply when received", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            const replyMessage = {
                msgId: "reply-1",
                senderId: "target-user",
                senderName: "Target User",
                content: "this is reply",
                requireReply: false,
                timestamp: new Date().toISOString(),
            };
            Reflect.set(client, "httpClient", {
                callTool: async () => ({
                    msgId: "dm-1",
                    reply: replyMessage,
                }),
            });
            const result = await client.sendCallAndWaitReply("target-user", "hello", 30000);
            assert.equal(result.msgId, "reply-1");
            assert.equal(result.content, "this is reply");
        });
        it("should throw when no reply received", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            Reflect.set(client, "httpClient", {
                callTool: async () => ({
                    msgId: "dm-1",
                    reply: null,
                }),
            });
            await assert.rejects(async () => await client.sendCallAndWaitReply("target-user", "hello"), /No reply received/);
        });
    });
    describe("discoverColleagues", () => {
        it("should call discover_colleague tool", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            const expectedResponse = {
                humans: [],
                agents: [
                    { id: "agent-2", displayName: "Agent Two", roleName: "Backend" },
                ],
            };
            let capturedArgs;
            Reflect.set(client, "httpClient", {
                callTool: async (_toolName, args) => {
                    capturedArgs = args;
                    return expectedResponse;
                },
            });
            const result = await client.discoverColleagues();
            assert.equal(capturedArgs?.agentId, "agent-1");
            assert.deepEqual(result, expectedResponse);
        });
    });
    describe("fetchUnreadMessages", () => {
        it("should call poll_message when pipeline task notifications are enabled", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            Reflect.set(client, "projectName", "demo");
            const calledTools = [];
            Reflect.set(client, "httpClient", {
                callTool: async (toolName) => {
                    calledTools.push(toolName);
                    if (toolName === "poll_message") {
                        return { messages: [] };
                    }
                    if (toolName === "discover_group_rooms") {
                        return { groups: [] };
                    }
                    return {};
                },
            });
            await client.fetchUnreadMessages({ includePipelineTasks: true });
            assert.equal(calledTools[0], "poll_message");
            assert.equal(calledTools.includes("get_dm_messages"), false);
        });
        it("should recover server poll_message 503 as empty result for local retry", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            Reflect.set(client, "projectName", "demo");
            const calledTools = [];
            Reflect.set(client, "httpClient", {
                callTool: async (toolName) => {
                    calledTools.push(toolName);
                    if (toolName === "poll_message") {
                        throw new Error('MCP tool poll_message call failed: 503 Service Unavailable - {"error":"Async request timed out"}');
                    }
                    if (toolName === "discover_group_rooms") {
                        return { groups: [] };
                    }
                    return {};
                },
            });
            const result = await client.fetchUnreadMessages({ includePipelineTasks: true });
            assert.deepEqual(result, { directMessages: [], groupMessages: [] });
            assert.deepEqual(calledTools, ["poll_message", "discover_group_rooms"]);
        });
        it("should recover client poll_message timeout as empty result for local retry", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            Reflect.set(client, "projectName", "demo");
            const calledTools = [];
            Reflect.set(client, "httpClient", {
                callTool: async (toolName) => {
                    calledTools.push(toolName);
                    if (toolName === "poll_message") {
                        throw new Error("MCP tool poll_message timed out after 120000ms");
                    }
                    if (toolName === "discover_group_rooms") {
                        return { groups: [] };
                    }
                    return {};
                },
            });
            const result = await client.fetchUnreadMessages({ includePipelineTasks: true });
            assert.deepEqual(result, { directMessages: [], groupMessages: [] });
            assert.deepEqual(calledTools, ["poll_message", "discover_group_rooms"]);
        });
        it("should not recover non-poll_message 503 errors", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            Reflect.set(client, "projectName", "demo");
            Reflect.set(client, "httpClient", {
                callTool: async (toolName) => {
                    if (toolName === "get_dm_messages") {
                        throw new Error("MCP tool get_dm_messages call failed: 503 Service Unavailable");
                    }
                    return {};
                },
            });
            await assert.rejects(() => client.fetchUnreadMessages(), /MCP tool get_dm_messages call failed: 503 Service Unavailable/);
        });
        it("should not recover poll_message non-503 errors", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            Reflect.set(client, "projectName", "demo");
            Reflect.set(client, "httpClient", {
                callTool: async (toolName) => {
                    if (toolName === "poll_message") {
                        throw new Error("MCP tool poll_message call failed: 500 Internal Server Error");
                    }
                    return {};
                },
            });
            await assert.rejects(() => client.fetchUnreadMessages({ includePipelineTasks: true }), /MCP tool poll_message call failed: 500 Internal Server Error/);
        });
        it("should keep get_dm_messages for non-claiming message fetches", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            Reflect.set(client, "projectName", "demo");
            const calledTools = [];
            Reflect.set(client, "httpClient", {
                callTool: async (toolName) => {
                    calledTools.push(toolName);
                    if (toolName === "get_dm_messages") {
                        return { messages: [] };
                    }
                    if (toolName === "discover_group_rooms") {
                        return { groups: [] };
                    }
                    return {};
                },
            });
            await client.fetchUnreadMessages();
            assert.equal(calledTools[0], "get_dm_messages");
            assert.equal(calledTools.includes("poll_message"), false);
        });
    });
    describe("discoverGroupRooms", () => {
        it("should call discover_group_rooms tool", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            const expectedResponse = {
                groups: [
                    {
                        id: "project:demo",
                        projectName: "demo",
                        roomType: "project",
                        scopeRefId: "demo",
                        name: "demo group",
                        memberUserIds: [],
                    },
                ],
            };
            Reflect.set(client, "httpClient", {
                callTool: async () => expectedResponse,
            });
            const result = await client.discoverGroupRooms();
            assert.deepEqual(result, expectedResponse);
        });
        it("should throw when not registered", async () => {
            const client = new AgentClient();
            await assert.rejects(async () => await client.discoverGroupRooms(), /Agent is not registered/);
        });
    });
    describe("hireColleague", () => {
        it("should call hire_colleague tool with correct parameters", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            const hireArgs = {
                roleName: "backend-developer",
                displayName: "Backend Dev-NEW",
                prompt: "backend expert",
                workspacePath: "/workspace/new",
            };
            const expectedResult = {
                id: "agent-new",
                displayName: "Backend Dev-NEW",
                roleName: "backend-developer",
                projectName: "demo",
                workspacePath: "/workspace/new",
                runtimeBridgeBaseUrl: "http://127.0.0.1:18081",
                runtimeStatus: "stopped",
            };
            let capturedArgs;
            Reflect.set(client, "httpClient", {
                callTool: async (_toolName, args) => {
                    capturedArgs = args;
                    return expectedResult;
                },
            });
            const result = await client.hireColleague(hireArgs);
            assert.equal(capturedArgs?.agentId, "agent-1");
            assert.equal(capturedArgs?.roleName, "backend-developer");
            assert.deepEqual(result, expectedResult);
        });
    });
    describe("hireColleaguesBatch", () => {
        it("should call hire_colleagues_batch tool with correct parameters", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            const batchArgs = {
                projectName: "demo",
                items: [
                    {
                        roleName: "backend-developer",
                        displayName: "Backend Dev-A",
                        prompt: "backend expert A",
                        workspacePath: "/workspace/backend-a",
                    },
                    {
                        newRoleName: "qa-engineer",
                        displayName: "QA Engineer-B",
                        prompt: "qa expert B",
                        workspacePath: "/workspace/qa-b",
                        runtimeMcpEnabled: true,
                    },
                ],
            };
            const expectedResult = {
                batchId: "batch-1",
                projectName: "demo",
                summary: {
                    total: 2,
                    approved: 1,
                    rejected: 1,
                    created: 1,
                    failed: 0,
                },
                results: [
                    {
                        itemId: "item-1",
                        decision: "APPROVED",
                        status: "CREATED",
                        createdAgent: {
                            id: "agent-new-1",
                            displayName: "Backend Dev-A",
                            roleName: "backend-developer",
                            projectName: "demo",
                            workspacePath: "/workspace/backend-a",
                        },
                    },
                    {
                        itemId: "item-2",
                        decision: "REJECTED",
                        status: "REJECTED",
                        reason: "headcount pending",
                    },
                ],
            };
            let capturedArgs;
            let capturedToolName;
            Reflect.set(client, "httpClient", {
                callTool: async (toolName, args) => {
                    capturedToolName = toolName;
                    capturedArgs = args;
                    return expectedResult;
                },
            });
            const result = await client.hireColleaguesBatch(batchArgs);
            assert.equal(capturedToolName, "hire_colleagues_batch");
            assert.equal(capturedArgs?.agentId, "agent-1");
            assert.equal(capturedArgs?.projectName, "demo");
            assert.deepEqual(capturedArgs?.items, batchArgs.items);
            assert.deepEqual(result, expectedResult);
        });
        it("should throw when batch hire is called before registration", async () => {
            const client = new AgentClient();
            await assert.rejects(async () => await client.hireColleaguesBatch({
                items: [
                    {
                        roleName: "backend-developer",
                        workspacePath: "/workspace/backend-a",
                    },
                ],
            }), /Agent is not registered/);
        });
    });
    describe("getProfile", () => {
        it("should return profile with describe", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            Reflect.set(client, "agentConfig", { describe: "test describe" });
            const profileInfo = createProfileInfo();
            Reflect.set(client, "httpClient", {
                callTool: async () => profileInfo,
            });
            const result = await client.getProfile();
            assert.equal(result.id, "agent-1");
            assert.equal(result.describe, "test describe");
        });
    });
    describe("getState", () => {
        it("should return current state", () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            Reflect.set(client, "displayName", "Agent One");
            Reflect.set(client, "projectName", "demo");
            Reflect.set(client, "isRunning", false);
            Reflect.set(client, "wsClient", {
                isConnected: () => true,
            });
            const state = client.getState();
            assert.equal(state.agentId, "agent-1");
            assert.equal(state.displayName, "Agent One");
            assert.equal(state.projectName, "demo");
            assert.equal(state.isConnected, true);
            assert.equal(state.isRunning, false);
        });
    });
    describe("start and stop", () => {
        it("should not start when already running", () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-1");
            Reflect.set(client, "isRunning", true);
            client.start(async () => "reply");
            assert.equal(Reflect.get(client, "isRunning"), true);
        });
        it("should throw when not registered on start", () => {
            const client = new AgentClient();
            assert.throws(() => client.start(async () => "reply"), /Agent is not registered/);
        });
        it("should stop message loop", () => {
            const client = new AgentClient();
            Reflect.set(client, "isRunning", true);
            client.stop();
            assert.equal(Reflect.get(client, "isRunning"), false);
        });
    });
    describe("profile caching", () => {
        it("should cache profile when profileHandler not set", () => {
            const client = new AgentClient();
            const cachedProfile = createProfileInfo();
            const handleProfileInfo = Reflect.get(client, "handleProfileInfo");
            handleProfileInfo.call(client, cachedProfile);
            const cached = Reflect.get(client, "cachedProfile");
            assert.deepEqual(cached, cachedProfile);
        });
        it("should invoke profileHandler immediately when set", () => {
            const client = new AgentClient();
            let receivedProfile = null;
            Reflect.set(client, "profileHandler", (profile) => {
                receivedProfile = profile;
            });
            const profile = createProfileInfo();
            const handleProfileInfo = Reflect.get(client, "handleProfileInfo");
            handleProfileInfo.call(client, profile);
            assert.deepEqual(receivedProfile, profile);
            assert.equal(Reflect.get(client, "cachedProfile"), null);
        });
    });
    describe("incoming message filtering", () => {
        it("should filter self-sent direct messages", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-self");
            let handlerCalled = false;
            Reflect.set(client, "messageHandler", async () => {
                handlerCalled = true;
                return "reply";
            });
            const selfMessage = {
                msgId: "dm-1",
                senderId: "agent-self",
                senderName: "Self",
                content: "self message",
                requireReply: false,
                timestamp: new Date().toISOString(),
            };
            const handleIncomingDm = Reflect.get(client, "handleIncomingDm");
            handleIncomingDm.call(client, selfMessage);
            assert.equal(handlerCalled, false);
        });
        it("should filter self-sent group messages", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-self");
            let handlerCalled = false;
            Reflect.set(client, "messageHandler", async () => {
                handlerCalled = true;
                return "reply";
            });
            const selfGroupMessage = {
                msgId: 1,
                senderId: "agent-self",
                senderName: "Self",
                content: "self group message",
                timestamp: new Date().toISOString(),
                projectName: "demo",
            };
            const handleIncomingGroup = Reflect.get(client, "handleIncomingGroup");
            handleIncomingGroup.call(client, selfGroupMessage);
            assert.equal(handlerCalled, false);
        });
    });
    describe("fetchUnreadMessages", () => {
        it("should ignore malformed group message responses instead of returning undefined entries", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-self");
            Reflect.set(client, "projectName", "demo");
            Reflect.set(client, "agentConfig", {
                roleName: "test-role",
                projectName: "demo",
                workspacePath: "/workspace/demo",
                prompt: "",
                describe: "",
            });
            const validGroupMessage = {
                msgId: 7,
                senderId: "agent-other",
                senderName: "Other",
                content: "hello",
                timestamp: new Date().toISOString(),
                projectName: "demo",
            };
            const groups = {
                groups: [
                    {
                        id: "project:demo",
                        projectName: "demo",
                        roomType: "project",
                        scopeRefId: "demo",
                        name: "demo 公共群聊",
                        memberUserIds: ["agent-self"],
                    },
                    {
                        id: "inner_group:g-1",
                        projectName: "demo",
                        roomType: "inner_group",
                        scopeRefId: "g-1",
                        name: "小组",
                        memberUserIds: ["agent-self"],
                    },
                ],
            };
            Reflect.set(client, "httpClient", {
                callTool: async (toolName, args) => {
                    if (toolName === "get_dm_messages") {
                        return { messages: [] };
                    }
                    if (toolName === "discover_group_rooms") {
                        return groups;
                    }
                    if (toolName === "get_group_messages" && args?.roomId === "project:demo") {
                        return { messages: [validGroupMessage] };
                    }
                    return { error: "transient room failure" };
                },
            });
            const result = await client.fetchUnreadMessages();
            assert.deepEqual(result.directMessages, []);
            assert.deepEqual(result.groupMessages, [validGroupMessage]);
        });
        it("should keep other room messages when one room unread fetch throws", async () => {
            const client = new AgentClient();
            Reflect.set(client, "agentId", "agent-self");
            Reflect.set(client, "projectName", "demo");
            Reflect.set(client, "agentConfig", {
                roleName: "test-role",
                projectName: "demo",
                workspacePath: "/workspace/demo",
                prompt: "",
                describe: "",
            });
            const validGroupMessage = {
                msgId: 8,
                senderId: "agent-other",
                senderName: "Other",
                content: "restored after restart",
                timestamp: new Date().toISOString(),
                projectName: "demo",
            };
            const groups = {
                groups: [
                    {
                        id: "project:demo",
                        projectName: "demo",
                        roomType: "project",
                        scopeRefId: "demo",
                        name: "demo 公共群聊",
                        memberUserIds: ["agent-self"],
                    },
                    {
                        id: "inner_group:g-1",
                        projectName: "demo",
                        roomType: "inner_group",
                        scopeRefId: "g-1",
                        name: "小组",
                        memberUserIds: ["agent-self"],
                    },
                ],
            };
            Reflect.set(client, "httpClient", {
                callTool: async (toolName, args) => {
                    if (toolName === "get_dm_messages") {
                        return { messages: [] };
                    }
                    if (toolName === "discover_group_rooms") {
                        return groups;
                    }
                    if (toolName === "get_group_messages" && args?.roomId === "project:demo") {
                        return { messages: [validGroupMessage] };
                    }
                    throw new Error("transient room failure");
                },
            });
            const consoleError = mock.method(console, "error", () => { });
            const result = await client.fetchUnreadMessages();
            assert.deepEqual(result.directMessages, []);
            assert.deepEqual(result.groupMessages, [validGroupMessage]);
            assert.equal(consoleError.mock.callCount(), 1);
        });
    });
    describe("project name update from profile", () => {
        it("should update projectName when receiving profile with projectName", () => {
            const client = new AgentClient();
            Reflect.set(client, "projectName", null);
            const profile = createProfileInfo({
                projectName: "server-assigned-project",
            });
            Reflect.set(client, "profileHandler", null);
            const handleProfileInfo = Reflect.get(client, "handleProfileInfo");
            handleProfileInfo.call(client, profile);
            assert.equal(Reflect.get(client, "projectName"), "server-assigned-project");
        });
    });
});
//# sourceMappingURL=agent-client.test.js.map