import pytest

from Mudabbir.agents.loop import AgentLoop


def test_sanitize_stream_chunk_hides_mcp_noise() -> None:
    noisy = 'mcp_sequential-thinking__sequentialthinking<｜tool▁sep｜>{"thought":"x"}'
    assert AgentLoop._sanitize_stream_chunk(noisy) == ""


def test_timeout_message_is_provider_aware() -> None:
    loop = AgentLoop()
    text = loop._timeout_message(backend="open_interpreter", provider="ollama")
    assert "Ollama" in text
    assert "Claude Code CLI" not in text


@pytest.mark.asyncio
async def test_global_fastpath_volume_get(monkeypatch: pytest.MonkeyPatch) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "volume"
            assert kwargs.get("mode") == "get"
            return '{"level_percent": 37, "muted": false}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)

    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="كم نسبة الصوت", session_key="s1"
    )
    assert handled is True
    assert "37" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_destructive_confirmation_flow(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    calls: list[tuple[str, dict]] = []

    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            calls.append((action, kwargs))
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)

    loop = AgentLoop()
    first_handled, first_reply = await loop._try_global_windows_fastpath(
        text="shutdown now", session_key="s2"
    )
    assert first_handled is True
    assert "destructive" in str(first_reply).lower() or "خط" in str(first_reply)
    assert calls == []

    second_handled, second_reply = await loop._try_global_windows_fastpath(
        text="yes", session_key="s2"
    )
    assert second_handled is True
    assert calls
    assert isinstance(second_reply, str)


@pytest.mark.asyncio
async def test_global_fastpath_brightness_get(monkeypatch: pytest.MonkeyPatch) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "brightness"
            assert kwargs.get("mode") == "get"
            return '{"brightness_percent": 62}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="كم نسبة الاضاءة", session_key="s3"
    )
    assert handled is True
    assert "62" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_battery_get(monkeypatch: pytest.MonkeyPatch) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "system_info"
            assert kwargs.get("mode") == "battery"
            return '{"available": true, "percent": 81, "plugged": false}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="كم نسبة البطارية", session_key="s4"
    )
    assert handled is True
    assert "81" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_app_tools_human_reply(monkeypatch: pytest.MonkeyPatch) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "app_tools"
            assert kwargs.get("mode") == "open_task_manager"
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="افتح مدير المهام", session_key="s5"
    )
    assert handled is True
    assert "مدير المهام" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_shell_tools_human_reply(monkeypatch: pytest.MonkeyPatch) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "shell_tools"
            assert kwargs.get("mode") == "quick_settings"
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="افتح الاعدادات السريعة", session_key="s6"
    )
    assert handled is True
    assert "السريعة" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_network_tools_human_reply(monkeypatch: pytest.MonkeyPatch) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "network_tools"
            assert kwargs.get("mode") == "wifi_on"
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="شغل الواي فاي", session_key="s7"
    )
    assert handled is True
    assert "الواي فاي" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_network_block_unblock_app_replies(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "network_tools"
            mode = kwargs.get("mode")
            if mode == "block_app_network":
                assert str(kwargs.get("name") or "").lower() == "chrome"
                return '{"ok": true, "mode": "block_app_network", "app": "chrome", "rule_name": "Mudabbir_App_Net_chrome"}'
            if mode == "unblock_app_network":
                assert str(kwargs.get("name") or "").lower() == "chrome"
                return '{"ok": true, "mode": "unblock_app_network", "app": "chrome", "rule_name": "Mudabbir_App_Net_chrome"}'
            if mode == "limit_app_bandwidth":
                assert str(kwargs.get("name") or "").lower() == "chrome"
                assert int(kwargs.get("limit_kbps") or 0) == 2048
                return '{"ok": true, "mode": "limit_app_bandwidth", "app": "chrome", "policy_name": "Mudabbir_App_QoS_chrome", "limit_kbps": 2048}'
            if mode == "unlimit_app_bandwidth":
                assert str(kwargs.get("name") or "").lower() == "chrome"
                return '{"ok": true, "mode": "unlimit_app_bandwidth", "app": "chrome", "policy_name": "Mudabbir_App_QoS_chrome"}'
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_block, reply_block = await loop._try_global_windows_fastpath(
        text="قطع الانترنت عن برنامج chrome", session_key="s7block1"
    )
    assert handled_block is True
    assert ("حظر" in str(reply_block)) or ("blocked" in str(reply_block).lower())

    handled_unblock, reply_unblock = await loop._try_global_windows_fastpath(
        text="allow app network chrome", session_key="s7block2"
    )
    assert handled_unblock is True
    assert ("إعادة" in str(reply_unblock)) or ("restored" in str(reply_unblock).lower())

    handled_limit, reply_limit = await loop._try_global_windows_fastpath(
        text="حدد سرعة النت لبرنامج chrome 2048", session_key="s7block3"
    )
    assert handled_limit is True
    assert ("تحديد سرعة" in str(reply_limit)) or ("bandwidth" in str(reply_limit).lower())

    handled_unlimit, reply_unlimit = await loop._try_global_windows_fastpath(
        text="remove app bandwidth limit chrome", session_key="s7block4"
    )
    assert handled_unlimit is True
    assert ("إلغاء" in str(reply_unlimit)) or ("removed" in str(reply_unlimit).lower())


@pytest.mark.asyncio
async def test_global_fastpath_network_diagnostics_replies(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "network_tools"
            assert kwargs.get("mode") in {"ipconfig_all", "tracert", "pathping", "nslookup", "netstat_active", "display_dns", "getmac", "arp_table", "nbtstat_cache", "nbtstat_host", "net_view", "netstat_binary", "wifi_profiles"}
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_ipall, reply_ipall = await loop._try_global_windows_fastpath(
        text="ipconfig /all", session_key="s7i"
    )
    assert handled_ipall is True
    assert "شبك" in str(reply_ipall) or "network" in str(reply_ipall).lower()

    handled_tracert, reply_tracert = await loop._try_global_windows_fastpath(
        text="تتبع المسار google.com", session_key="s7t"
    )
    assert handled_tracert is True
    assert "تتبع" in str(reply_tracert) or "trace" in str(reply_tracert).lower()

    handled_pathping, reply_pathping = await loop._try_global_windows_fastpath(
        text="pathping google.com", session_key="s7p"
    )
    assert handled_pathping is True
    assert "فقدان" in str(reply_pathping) or "path ping" in str(reply_pathping).lower()

    handled_nslookup, reply_nslookup = await loop._try_global_windows_fastpath(
        text="nslookup google.com", session_key="s7n"
    )
    assert handled_nslookup is True
    assert "dns" in str(reply_nslookup).lower() or "استعلام" in str(reply_nslookup)

    handled_netstat, reply_netstat = await loop._try_global_windows_fastpath(
        text="الاتصالات النشطة", session_key="s7s"
    )
    assert handled_netstat is True
    assert "نشط" in str(reply_netstat) or "active" in str(reply_netstat).lower()

    handled_dns, reply_dns = await loop._try_global_windows_fastpath(
        text="عرض dns", session_key="s7d"
    )
    assert handled_dns is True
    assert "dns" in str(reply_dns).lower()

    handled_getmac, reply_getmac = await loop._try_global_windows_fastpath(
        text="getmac", session_key="s7m"
    )
    assert handled_getmac is True
    assert "mac" in str(reply_getmac).lower()

    handled_arp, reply_arp = await loop._try_global_windows_fastpath(
        text="جدول arp", session_key="s7a"
    )
    assert handled_arp is True
    assert "arp" in str(reply_arp).lower()

    handled_nbt, reply_nbt = await loop._try_global_windows_fastpath(
        text="nbtstat -c", session_key="s7b"
    )
    assert handled_nbt is True
    assert "netbios" in str(reply_nbt).lower() or "bios" in str(reply_nbt).lower()

    handled_nbthost, reply_nbthost = await loop._try_global_windows_fastpath(
        text="nbtstat -a FILESRV", session_key="s7bh"
    )
    assert handled_nbthost is True
    assert "netbios" in str(reply_nbthost).lower() or "bios" in str(reply_nbthost).lower()

    handled_netview, reply_netview = await loop._try_global_windows_fastpath(
        text="net view", session_key="s7v"
    )
    assert handled_netview is True
    assert "شبك" in str(reply_netview) or "network" in str(reply_netview).lower()

    handled_netstatb, reply_netstatb = await loop._try_global_windows_fastpath(
        text="netstat -b", session_key="s7vb"
    )
    assert handled_netstatb is True
    assert (
        "program" in str(reply_netstatb).lower()
        or "executable" in str(reply_netstatb).lower()
        or "البرامج" in str(reply_netstatb)
    )

    handled_wlan, reply_wlan = await loop._try_global_windows_fastpath(
        text="netsh wlan show profiles", session_key="s7vw"
    )
    assert handled_wlan is True
    assert "wifi" in str(reply_wlan).lower() or "wi-fi" in str(reply_wlan).lower() or "واي فاي" in str(reply_wlan)


@pytest.mark.asyncio
async def test_global_fastpath_media_and_window_replies(monkeypatch: pytest.MonkeyPatch) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            if action == "media_control":
                assert kwargs.get("mode") == "next"
            if action == "window_control":
                assert kwargs.get("mode") in {"minimize", "show_desktop_verified"}
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_media, reply_media = await loop._try_global_windows_fastpath(
        text="المقطع التالي", session_key="s8"
    )
    assert handled_media is True
    assert "التالي" in str(reply_media)

    handled_window, reply_window = await loop._try_global_windows_fastpath(
        text="تصغير النافذة", session_key="s9"
    )
    assert handled_window is True
    assert "تصغير" in str(reply_window)

    handled_show_desktop, reply_show_desktop = await loop._try_global_windows_fastpath(
        text="صغر كل النوافذ", session_key="s9d"
    )
    assert handled_show_desktop is True
    assert "سطح المكتب" in str(reply_show_desktop) or "show desktop" in str(reply_show_desktop).lower()


@pytest.mark.asyncio
async def test_global_fastpath_process_top_cpu_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "top_cpu"
            return '{"ok": true, "mode": "top_cpu", "items": [{"pid": 1234, "name": "chrome.exe", "cpu": 67.5}]}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="اكثر العمليات استهلاكا للمعالج", session_key="s10"
    )
    assert handled is True
    assert "chrome.exe" in str(reply)
    assert "1234" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_process_kill_by_pid_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "kill_pid"
            assert kwargs.get("pid") == 1234
            return '{"ok": true, "mode": "kill_pid", "pid": 1234}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="kill pid 1234", session_key="s10pid"
    )
    assert handled is True
    assert ("yes" in str(reply).lower()) or ("نعم" in str(reply))

    handled2, reply2 = await loop._try_global_windows_fastpath(
        text="yes", session_key="s10pid"
    )
    assert handled2 is True
    assert ("pid" in str(reply2).lower()) or ("عملية" in str(reply2))


@pytest.mark.asyncio
async def test_global_fastpath_process_kill_by_name_confirmation_flow(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "kill_name"
            assert str(kwargs.get("name") or "").lower() == "chrome"
            return '{"ok": true, "mode": "kill_name", "name": "chrome", "killed": 2}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled_wait, reply_wait = await loop._try_global_windows_fastpath(
        text="kill process chrome", session_key="s10name1"
    )
    assert handled_wait is True
    assert ("yes" in str(reply_wait).lower()) or ("تأكيد" in str(reply_wait))

    handled_exec, reply_exec = await loop._try_global_windows_fastpath(
        text="yes", session_key="s10name1"
    )
    assert handled_exec is True
    assert ("name" in str(reply_exec).lower()) or ("الاسم" in str(reply_exec)) or ("عملية" in str(reply_exec))


@pytest.mark.asyncio
async def test_global_fastpath_process_set_priority_by_pid_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "set_priority"
            assert kwargs.get("pid") == 1234
            assert kwargs.get("priority") == "high"
            return '{"ok": true, "mode": "set_priority", "pid": 1234, "priority": "high"}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="set priority pid 1234 high", session_key="s10prio"
    )
    assert handled is True
    assert ("priority" in str(reply).lower()) or ("أولوية" in str(reply))


@pytest.mark.asyncio
async def test_global_fastpath_process_kill_unresponsive_confirmation_flow(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "kill_unresponsive"
            return '{"ok": true, "mode": "kill_unresponsive", "killed": 2}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_wait, reply_wait = await loop._try_global_windows_fastpath(
        text="kill unresponsive process", session_key="s10unresp"
    )
    assert handled_wait is True
    assert "yes" in str(reply_wait).lower() or "تأكيد" in str(reply_wait)

    handled_exec, reply_exec = await loop._try_global_windows_fastpath(
        text="yes", session_key="s10unresp"
    )
    assert handled_exec is True
    assert ("unresponsive" in str(reply_exec).lower()) or ("غير المستجيبة" in str(reply_exec))


@pytest.mark.asyncio
async def test_global_fastpath_process_blacklist_and_whitelist_app_replies(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            mode = kwargs.get("mode")
            if mode == "blacklist_app":
                assert str(kwargs.get("name") or "").lower() == "chrome"
                return '{"ok": true, "mode": "blacklist_app", "name": "chrome"}'
            if mode == "whitelist_app":
                assert str(kwargs.get("name") or "").lower() == "chrome"
                return '{"ok": true, "mode": "whitelist_app", "name": "chrome"}'
            if mode == "list_blacklist_apps":
                return '{"ok": true, "mode": "list_blacklist_apps", "items": ["chrome"], "count": 1}'
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_blacklist, reply_blacklist = await loop._try_global_windows_fastpath(
        text="blacklist app chrome", session_key="s10blk1"
    )
    assert handled_blacklist is True
    assert ("blacklist" in str(reply_blacklist).lower()) or ("الحظر" in str(reply_blacklist))

    handled_whitelist, reply_whitelist = await loop._try_global_windows_fastpath(
        text="whitelist app chrome", session_key="s10blk2"
    )
    assert handled_whitelist is True
    assert ("removed" in str(reply_whitelist).lower()) or ("إزالة" in str(reply_whitelist)) or ("ازالة" in str(reply_whitelist))

    handled_list, reply_list = await loop._try_global_windows_fastpath(
        text="list blacklisted apps", session_key="s10blk3"
    )
    assert handled_list is True
    assert ("blacklist" in str(reply_list).lower()) or ("المحظور" in str(reply_list))


@pytest.mark.asyncio
async def test_global_fastpath_process_monitor_until_exit_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "monitor_until_exit"
            assert str(kwargs.get("name") or "").lower() == "chrome"
            assert kwargs.get("seconds") == 5
            return '{"ok": true, "mode": "monitor_until_exit", "name": "chrome", "exited": false, "elapsed_seconds": 5, "timeout_seconds": 5}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="monitor process chrome 5", session_key="s10mon1"
    )
    assert handled is True
    assert ("running" in str(reply).lower()) or ("شغالة" in str(reply))


@pytest.mark.asyncio
async def test_global_fastpath_process_monitor_until_exit_with_notify_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "monitor_until_exit"
            assert str(kwargs.get("name") or "").lower() == "chrome"
            assert kwargs.get("seconds") == 3
            assert kwargs.get("notify") is True
            return '{"ok": true, "mode": "monitor_until_exit", "name": "chrome", "exited": true, "elapsed_seconds": 2.1, "timeout_seconds": 3, "notified": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="monitor process chrome 3 notify", session_key="s10mon2"
    )
    assert handled is True
    assert ("alert sent" in str(reply).lower()) or ("تنبيه" in str(reply))


@pytest.mark.asyncio
async def test_global_fastpath_process_path_by_name_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "path_by_name"
            assert str(kwargs.get("name") or "").lower() == "chrome"
            return (
                '{"ok": true, "mode": "path_by_name", "query": "chrome", "count": 1, '
                '"items": [{"pid": 1234, "name": "chrome.exe", "path": "C:\\\\Program Files\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe"}]}'
            )

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="process path chrome", session_key="s10path1"
    )
    assert handled is True
    assert "chrome.exe" in str(reply).lower() or "chrome" in str(reply).lower()
    assert "program files" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_process_app_memory_total_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "app_memory_total"
            assert kwargs.get("name") == "Cursor"
            return '{"ok": true, "mode": "app_memory_total", "query": "Cursor", "process_count": 24, "total_ram_mb": 4058.4}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="كل عمليات تطبيق Cursor سوا كم تستهلك", session_key="s10a"
    )
    assert handled is True
    assert "Cursor" in str(reply)
    assert "4058.4" in str(reply)
    assert "24" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_process_app_process_count_total_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "app_process_count_total"
            assert kwargs.get("name") == "Cursor"
            return '{"ok": true, "mode": "app_process_count_total", "query": "Cursor", "process_count": 24, "total_ram_mb": 4062.0}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="كم عملية لتطبيق Cursor شغالة وكلهم سوا كم يستهلك", session_key="s10aa"
    )
    assert handled is True
    assert "Cursor" in str(reply)
    assert "4062.0" in str(reply)
    assert "24" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_microphone_mute_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "microphone_control"
            assert kwargs.get("mode") == "mute"
            return '{"ok": true, "mode": "mute", "muted": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="كتم الميكروفون", session_key="s10mic"
    )
    assert handled is True
    assert "الميكروفون" in str(reply) or "microphone" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_microphone_status_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "microphone_control"
            assert kwargs.get("mode") == "get"
            return '{"ok": true, "mode": "get", "muted": false}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="حالة الميكروفون", session_key="s10mic2"
    )
    assert handled is True
    assert "microphone" in str(reply).lower() or "الميكروفون" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_connect_wifi_verified_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "network_tools"
            assert kwargs.get("mode") == "connect_wifi"
            assert kwargs.get("host") == "MyWifi"
            return '{"ok": true, "mode": "connect_wifi", "requested_ssid": "MyWifi", "connected": true, "connected_ssid": "MyWifi"}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="connect wifi MyWifi", session_key="s10wifi"
    )
    assert handled is True
    assert "wifi" in str(reply).lower() or "الشبكة" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_process_app_cpu_total_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "app_cpu_total"
            assert kwargs.get("name") == "Cursor"
            return '{"ok": true, "mode": "app_cpu_total", "query": "Cursor", "process_count": 24, "total_cpu_percent": 18.7}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="اجمالي cpu تطبيق Cursor", session_key="s10b"
    )
    assert handled is True
    assert "Cursor" in str(reply)
    assert "18.7" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_process_app_disk_total_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "app_disk_total"
            assert kwargs.get("name") == "Cursor"
            return '{"ok": true, "mode": "app_disk_total", "query": "Cursor", "process_count": 24, "total_disk_mb": 921.5}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="app total disk Cursor", session_key="s10c"
    )
    assert handled is True
    assert "Cursor" in str(reply)
    assert "921.5" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_process_app_network_total_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "app_network_total"
            assert kwargs.get("name") == "Cursor"
            return (
                '{"ok": true, "mode": "app_network_total", "query": "Cursor", '
                '"process_count": 24, "total_connections": 31, "established_connections": 12, "unique_remote_ips": 7}'
            )

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="app total network Cursor", session_key="s10d"
    )
    assert handled is True
    assert "Cursor" in str(reply)
    assert "31" in str(reply)
    assert "12" in str(reply)
    assert "7" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_process_app_resource_summary_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "app_resource_summary"
            assert kwargs.get("name") == "Cursor"
            return (
                '{"ok": true, "mode": "app_resource_summary", "query": "Cursor", '
                '"process_count": 24, "total_ram_mb": 4058.4, "total_cpu_percent": 18.7, '
                '"total_disk_mb": 921.5, "total_connections": 31}'
            )

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="ملخص استهلاك تطبيق Cursor", session_key="s10e"
    )
    assert handled is True
    assert "Cursor" in str(reply)
    assert "4058.4" in str(reply)
    assert "18.7" in str(reply)
    assert "921.5" in str(reply)
    assert "31" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_process_app_compare_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "app_compare"
            assert kwargs.get("name") == "Cursor"
            assert kwargs.get("target") == "Ollama"
            return (
                '{"ok": true, "mode": "app_compare", '
                '"left": {"ok": true, "query": "Cursor", "total_ram_mb": 4058.4, "total_cpu_percent": 18.7, "total_disk_mb": 921.5, "total_connections": 31}, '
                '"right": {"ok": true, "query": "Ollama", "total_ram_mb": 502.5, "total_cpu_percent": 4.1, "total_disk_mb": 110.0, "total_connections": 3}, '
                '"winners": {"ram":"Cursor","cpu":"Cursor","disk":"Cursor","network":"Cursor"}, '
                '"recommendations": ["ram_hotspot=Cursor","cpu_hotspot=Cursor"]}'
            )

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="قارن بين Cursor و Ollama", session_key="s10f"
    )
    assert handled is True
    assert "Cursor" in str(reply)
    assert "Ollama" in str(reply)
    assert "4058.4" in str(reply)
    assert "502.5" in str(reply)
    assert "CPU" in str(reply) or "cpu" in str(reply)
    assert "Heavier" in str(reply) or "الأثقل" in str(reply)
    assert "Recommendation" in str(reply) or "التوصية" in str(reply)
    assert "Practical action" in str(reply) or "إجراء عملي" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_process_app_reduce_ram_plan_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "app_reduce_ram_plan"
            assert kwargs.get("name") == "Cursor"
            return (
                '{"ok": true, "mode": "app_reduce_ram_plan", "query": "Cursor", '
                '"process_count": 24, "total_ram_mb": 4058.4, "reclaimable_mb_estimate": 1100.0, '
                '"top_processes": [{"pid": 1, "name": "Cursor.exe", "ram_mb": 1355.3}, {"pid": 2, "name": "Cursor.exe", "ram_mb": 357.1}]}'
            )

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="قلل استهلاك تطبيق Cursor", session_key="s10g"
    )
    assert handled is True
    assert "Cursor" in str(reply)
    assert "4058.4" in str(reply)
    assert "1100.0" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_process_app_reduce_ram_execute_confirmation_flow(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "app_reduce_ram_execute"
            assert kwargs.get("name") == "Cursor"
            return (
                '{"ok": true, "mode": "app_reduce_ram_execute", "query": "Cursor", '
                '"killed_count": 5, "protected_name": "Cursor.exe", "protected_pid": 12712}'
            )

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_wait, reply_wait = await loop._try_global_windows_fastpath(
        text="نفذ تخفيف تطبيق Cursor", session_key="s10h"
    )
    assert handled_wait is True
    assert "yes" in str(reply_wait).lower() or "تأكيد" in str(reply_wait)

    handled_exec, reply_exec = await loop._try_global_windows_fastpath(
        text="نعم", session_key="s10h"
    )
    assert handled_exec is True
    assert "Cursor" in str(reply_exec)
    assert "5" in str(reply_exec)


@pytest.mark.asyncio
async def test_global_fastpath_process_app_reduce_ram_execute_preview_with_limit(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "app_reduce_ram_execute"
            assert kwargs.get("name") == "Cursor"
            assert kwargs.get("dry_run") is True
            assert kwargs.get("max_kill") == 3
            return (
                '{"ok": true, "mode": "app_reduce_ram_execute", "query": "Cursor", '
                '"dry_run": true, "max_kill": 3, "killed_count": 3, "protected_name": "Cursor.exe", "protected_pid": 12712}'
            )

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_exec, reply_exec = await loop._try_global_windows_fastpath(
        text="preview app ram reduction Cursor max_kill 3", session_key="s10i"
    )
    assert handled_exec is True
    assert "Previewed" in str(reply_exec) or "معاينة" in str(reply_exec)
    assert "3" in str(reply_exec)


@pytest.mark.asyncio
async def test_global_fastpath_preview_close_all_apps_without_confirmation(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "app_tools"
            assert kwargs.get("mode") == "close_all_apps"
            assert kwargs.get("dry_run") is True
            assert kwargs.get("max_kill") == 2
            return '{"ok": true, "mode": "close_all_apps", "dry_run": true, "max_kill": 2, "count": 2}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="preview close all apps max_kill 2", session_key="s10j"
    )
    assert handled is True
    assert "Preview" in str(reply) or "معاينة" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_preview_kill_high_cpu_without_confirmation(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "kill_high_cpu"
            assert kwargs.get("dry_run") is True
            assert kwargs.get("threshold") == 60
            return '{"ok": true, "mode": "kill_high_cpu", "dry_run": true, "threshold": 60, "count": 4}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="preview kill high cpu 60", session_key="s10k"
    )
    assert handled is True
    assert "Previewed" in str(reply) or "معاينة" in str(reply)
    assert "60" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_process_app_reduce_cpu_plan_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "app_reduce_cpu_plan"
            assert kwargs.get("name") == "Cursor"
            return '{"ok": true, "mode": "app_reduce_cpu_plan", "query": "Cursor", "process_count": 24, "total_cpu_percent": 28.4, "reclaimable_cpu_estimate": 11.2}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="reduce app cpu Cursor", session_key="s10l"
    )
    assert handled is True
    assert "Cursor" in str(reply)
    assert "28.4" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_process_app_reduce_cpu_execute_preview_no_confirmation(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "app_reduce_cpu_execute"
            assert kwargs.get("name") == "Cursor"
            assert kwargs.get("dry_run") is True
            assert kwargs.get("threshold") == 25
            assert kwargs.get("max_kill") == 2
            return '{"ok": true, "mode": "app_reduce_cpu_execute", "query": "Cursor", "dry_run": true, "threshold": 25, "killed_count": 2, "protected_name": "Cursor.exe", "protected_pid": 12712}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="preview app cpu reduction Cursor 25 max_kill 2", session_key="s10m"
    )
    assert handled is True
    assert "Previewed" in str(reply) or "معاينة" in str(reply)
    assert "25" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_process_app_reduce_disk_plan_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "app_reduce_disk_plan"
            assert kwargs.get("name") == "Cursor"
            return '{"ok": true, "mode": "app_reduce_disk_plan", "query": "Cursor", "process_count": 24, "total_disk_mb": 921.5, "reclaimable_disk_estimate": 312.0}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="reduce app disk Cursor", session_key="s10m1"
    )
    assert handled is True
    assert "Cursor" in str(reply)
    assert "921.5" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_process_app_reduce_disk_execute_confirmation_flow(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "app_reduce_disk_execute"
            assert kwargs.get("name") == "Cursor"
            return '{"ok": true, "mode": "app_reduce_disk_execute", "query": "Cursor", "threshold": 80, "killed_count": 2, "protected_name": "Cursor.exe", "protected_pid": 12712}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_wait, reply_wait = await loop._try_global_windows_fastpath(
        text="execute app disk reduction Cursor 80", session_key="s10m2"
    )
    assert handled_wait is True
    assert "yes" in str(reply_wait).lower() or "تأكيد" in str(reply_wait)

    handled_exec, reply_exec = await loop._try_global_windows_fastpath(
        text="yes", session_key="s10m2"
    )
    assert handled_exec is True
    assert "Cursor" in str(reply_exec)
    assert "80" in str(reply_exec)


@pytest.mark.asyncio
async def test_global_fastpath_process_app_reduce_network_execute_preview_no_confirmation(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "app_reduce_network_execute"
            assert kwargs.get("name") == "Cursor"
            assert kwargs.get("dry_run") is True
            assert kwargs.get("threshold") == 4
            assert kwargs.get("max_kill") == 2
            return '{"ok": true, "mode": "app_reduce_network_execute", "query": "Cursor", "dry_run": true, "threshold": 4, "killed_count": 2, "protected_name": "Cursor.exe", "protected_pid": 12712}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="preview app network reduction Cursor 4 max_kill 2", session_key="s10m3"
    )
    assert handled is True
    assert "Previewed" in str(reply) or "معاينة" in str(reply)
    assert "4" in str(reply)


@pytest.mark.asyncio
async def test_global_fastpath_process_app_reduce_generic_plan_route(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "process_tools"
            assert kwargs.get("mode") == "app_reduce"
            assert kwargs.get("name") == "Cursor"
            assert kwargs.get("resource") == "ram"
            assert kwargs.get("stage") == "plan"
            return '{"ok": true, "mode": "app_reduce", "resource": "ram", "stage": "plan"}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="app reduce plan Cursor ram", session_key="s10n"
    )
    assert handled is True
    assert "success" in str(reply).lower() or "plan" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_service_and_security_replies(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            if action == "service_tools":
                assert kwargs.get("mode") == "restart"
                assert kwargs.get("name") == "Spooler"
                return '{"ok": true}'
            if action == "security_tools":
                assert kwargs.get("mode") == "firewall_status"
                return '{"ok": true, "mode": "firewall_status"}'
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_service, reply_service = await loop._try_global_windows_fastpath(
        text="اعادة تشغيل خدمة Spooler", session_key="s11"
    )
    assert handled_service is True
    assert "Spooler" in str(reply_service)

    handled_security, reply_security = await loop._try_global_windows_fastpath(
        text="حالة الجدار الناري", session_key="s12"
    )
    assert handled_security is True
    assert "جدار" in str(reply_security)


@pytest.mark.asyncio
async def test_global_fastpath_service_list_and_dependencies_replies(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "service_tools"
            mode = kwargs.get("mode")
            if mode == "list":
                return '{"ok": true, "mode":"list", "data":[]}'
            if mode == "dependencies":
                assert kwargs.get("name") == "Spooler"
                return '{"ok": true, "mode":"dependencies", "data":{}}'
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_list, reply_list = await loop._try_global_windows_fastpath(
        text="قائمة الخدمات", session_key="s12a"
    )
    assert handled_list is True
    assert "الخدمات" in str(reply_list) or "services" in str(reply_list).lower()

    handled_deps, reply_deps = await loop._try_global_windows_fastpath(
        text="تبعيات الخدمة Spooler", session_key="s12b"
    )
    assert handled_deps is True
    assert "تبعيات" in str(reply_deps) or "dependencies" in str(reply_deps).lower()


@pytest.mark.asyncio
async def test_global_fastpath_startup_background_and_performance_replies(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            if action == "startup_tools":
                assert kwargs.get("mode") == "startup_list"
                return '{"ok": true, "items": []}'
            if action == "background_tools":
                assert kwargs.get("mode") == "count_background"
                return '{"ok": true, "total": 120, "background": 87}'
            if action == "performance_tools":
                assert kwargs.get("mode") == "total_cpu_percent"
                return '{"ok": true, "percent": 41.2}'
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_startup, reply_startup = await loop._try_global_windows_fastpath(
        text="قائمة برامج بدء التشغيل", session_key="s13"
    )
    assert handled_startup is True
    assert "بدء التشغيل" in str(reply_startup)

    handled_bg, reply_bg = await loop._try_global_windows_fastpath(
        text="تعداد التطبيقات المشغلة في الخلفية", session_key="s14"
    )
    assert handled_bg is True
    assert "الخلفية" in str(reply_bg)

    handled_perf, reply_perf = await loop._try_global_windows_fastpath(
        text="اجمالي استهلاك المعالج", session_key="s15"
    )
    assert handled_perf is True
    assert "41.2" in str(reply_perf)


@pytest.mark.asyncio
async def test_global_fastpath_browser_task_user_replies(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            if action == "browser_control":
                assert kwargs.get("mode") in {
                    "new_tab",
                    "reopen_tab",
                    "history",
                    "downloads",
                    "zoom_in",
                    "zoom_out",
                    "zoom_reset",
                    "save_pdf",
                }
                return '{"ok": true}'
            if action == "task_tools":
                assert kwargs.get("mode") in {"running", "last_run", "run", "end", "enable", "disable"}
                if kwargs.get("mode") in {"run", "end", "enable", "disable"}:
                    assert kwargs.get("name") == "BackupTask"
                return '{"ok": true}'
            if action == "user_tools":
                assert kwargs.get("mode") == "delete"
                assert kwargs.get("username") == "TestUser"
                return '{"ok": true}'
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_browser, reply_browser = await loop._try_global_windows_fastpath(
        text="فتح تبويب جديد", session_key="s16"
    )
    assert handled_browser is True
    assert "تبويب" in str(reply_browser)

    handled_reopen, reply_reopen = await loop._try_global_windows_fastpath(
        text="إعادة فتح التبويب المغلق", session_key="s16r"
    )
    assert handled_reopen is True
    assert "تبويب" in str(reply_reopen) or "tab" in str(reply_reopen).lower()

    handled_history, reply_history = await loop._try_global_windows_fastpath(
        text="سجل التصفح", session_key="s16h"
    )
    assert handled_history is True
    assert "سجل" in str(reply_history) or "history" in str(reply_history).lower()

    handled_downloads, reply_downloads = await loop._try_global_windows_fastpath(
        text="تنزيلات المتصفح", session_key="s16d"
    )
    assert handled_downloads is True
    assert "تنزيل" in str(reply_downloads) or "download" in str(reply_downloads).lower()

    handled_zoom_in, reply_zoom_in = await loop._try_global_windows_fastpath(
        text="تكبير الصفحة", session_key="s16zi"
    )
    assert handled_zoom_in is True
    assert "تكبير" in str(reply_zoom_in) or "zoom" in str(reply_zoom_in).lower()

    handled_zoom_out, reply_zoom_out = await loop._try_global_windows_fastpath(
        text="تصغير الصفحة", session_key="s16zo"
    )
    assert handled_zoom_out is True
    assert "تصغير" in str(reply_zoom_out) or "zoom" in str(reply_zoom_out).lower()

    handled_zoom_reset, reply_zoom_reset = await loop._try_global_windows_fastpath(
        text="ارجاع الزوم 100", session_key="s16zr"
    )
    assert handled_zoom_reset is True
    assert "100" in str(reply_zoom_reset) or "zoom" in str(reply_zoom_reset).lower()

    handled_save_pdf, reply_save_pdf = await loop._try_global_windows_fastpath(
        text="حفظ الصفحة pdf", session_key="s16p"
    )
    assert handled_save_pdf is True
    assert "pdf" in str(reply_save_pdf).lower() or "صفحة" in str(reply_save_pdf)

    handled_task, reply_task = await loop._try_global_windows_fastpath(
        text="تشغيل مهمة مجدولة BackupTask", session_key="s17"
    )
    assert handled_task is True
    assert "BackupTask" in str(reply_task)

    handled_task_running, reply_task_running = await loop._try_global_windows_fastpath(
        text="المهام المجدولة الجارية", session_key="s17r"
    )
    assert handled_task_running is True
    assert "المهام" in str(reply_task_running) or "tasks" in str(reply_task_running).lower()

    handled_task_last_run, reply_task_last_run = await loop._try_global_windows_fastpath(
        text="آخر تشغيل للمهام", session_key="s17lr"
    )
    assert handled_task_last_run is True
    assert "تشغيل" in str(reply_task_last_run) or "last run" in str(reply_task_last_run).lower()

    handled_task_end, reply_task_end = await loop._try_global_windows_fastpath(
        text="إنهاء مهمة مجدولة BackupTask", session_key="s17e"
    )
    assert handled_task_end is True
    assert "BackupTask" in str(reply_task_end)

    handled_task_enable, reply_task_enable = await loop._try_global_windows_fastpath(
        text="تمكين مهمة مجدولة BackupTask", session_key="s17en"
    )
    assert handled_task_enable is True
    assert "BackupTask" in str(reply_task_enable)

    handled_task_disable, reply_task_disable = await loop._try_global_windows_fastpath(
        text="تعطيل مهمة مجدولة BackupTask", session_key="s17d"
    )
    assert handled_task_disable is True
    assert "BackupTask" in str(reply_task_disable)

    handled_user, reply_user = await loop._try_global_windows_fastpath(
        text="حذف مستخدم TestUser", session_key="s18"
    )
    assert handled_user is True
    assert "خط" in str(reply_user) or "yes" in str(reply_user).lower()
    handled_user_confirm, reply_user_confirm = await loop._try_global_windows_fastpath(
        text="نعم", session_key="s18"
    )
    assert handled_user_confirm is True
    assert "TestUser" in str(reply_user_confirm)


@pytest.mark.asyncio
async def test_global_fastpath_update_remote_disk_registry_replies(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            if action == "update_tools":
                assert kwargs.get("mode") == "check_updates"
                return '{"ok": true, "mode": "check_updates"}'
            if action == "remote_tools":
                assert kwargs.get("mode") == "vpn_connect"
                assert kwargs.get("host") == "OfficeVPN"
                return '{"ok": true, "mode": "vpn_connect"}'
            if action == "disk_tools":
                assert kwargs.get("mode") == "temp_files_clean"
                return '{"ok": true, "mode": "temp_files_clean"}'
            if action == "registry_tools":
                assert kwargs.get("mode") == "backup"
                return '{"ok": true, "mode": "backup"}'
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_update, reply_update = await loop._try_global_windows_fastpath(
        text="فحص التحديثات", session_key="s19"
    )
    assert handled_update is True
    assert "تحديث" in str(reply_update)

    handled_remote, reply_remote = await loop._try_global_windows_fastpath(
        text="تشغيل vpn OfficeVPN", session_key="s20"
    )
    assert handled_remote is True
    assert "OfficeVPN" in str(reply_remote)

    handled_disk, reply_disk = await loop._try_global_windows_fastpath(
        text="تنظيف الملفات المؤقتة", session_key="s21"
    )
    assert handled_disk is True
    assert "المؤقتة" in str(reply_disk) or "temp" in str(reply_disk).lower()

    handled_reg, reply_reg = await loop._try_global_windows_fastpath(
        text="registry backup HKCU\\Software", session_key="s22"
    )
    assert handled_reg is True
    assert "سجل" in str(reply_reg) or "registry" in str(reply_reg).lower()


@pytest.mark.asyncio
async def test_global_fastpath_safe_eject_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "disk_tools"
            assert kwargs.get("mode") == "safe_eject"
            assert kwargs.get("drive") == "E:"
            return '{"ok": true, "mode": "safe_eject", "drives": ["E:"], "count": 1}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled, reply = await loop._try_global_windows_fastpath(
        text="إخراج آمن E:", session_key="s22eject"
    )
    assert handled is True
    assert ("أمان" in str(reply)) or ("آمن" in str(reply)) or ("eject" in str(reply).lower())


@pytest.mark.asyncio
async def test_global_fastpath_network_security_search_web_api_replies(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            if action == "network_tools":
                assert kwargs.get("mode") == "open_ports"
                return '{"ok": true}'
            if action == "security_tools":
                assert kwargs.get("mode") == "disable_usb"
                return '{"ok": true}'
            if action == "search_tools":
                assert kwargs.get("mode") == "find_images"
                return '{"ok": true, "count": 12}'
            if action == "web_tools":
                assert kwargs.get("mode") == "open_url"
                return '{"ok": true}'
            if action == "api_tools":
                assert kwargs.get("mode") == "currency"
                return '{"ok": true}'
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_network, reply_network = await loop._try_global_windows_fastpath(
        text="المنافذ المفتوحة", session_key="s23"
    )
    assert handled_network is True
    assert "منافذ" in str(reply_network) or "ports" in str(reply_network).lower()

    handled_security, reply_security = await loop._try_global_windows_fastpath(
        text="تعطيل منافذ usb", session_key="s24"
    )
    assert handled_security is True
    assert "خط" in str(reply_security) or "destructive" in str(reply_security).lower()
    handled_security_confirm, reply_security_confirm = await loop._try_global_windows_fastpath(
        text="نعم", session_key="s24"
    )
    assert handled_security_confirm is True
    assert "usb" in str(reply_security_confirm).lower() or "منافذ" in str(reply_security_confirm)

    handled_search, reply_search = await loop._try_global_windows_fastpath(
        text="ايجاد جميع الصور", session_key="s25"
    )
    assert handled_search is True
    assert "الصور" in str(reply_search) or "image" in str(reply_search).lower()

    handled_web, reply_web = await loop._try_global_windows_fastpath(
        text="افتح رابط https://example.com", session_key="s26"
    )
    assert handled_web is True
    assert "رابط" in str(reply_web) or "url" in str(reply_web).lower()

    handled_api, reply_api = await loop._try_global_windows_fastpath(
        text="اسعار العملات", session_key="s27"
    )
    assert handled_api is True
    assert "عملات" in str(reply_api) or "currency" in str(reply_api).lower()


@pytest.mark.asyncio
async def test_global_fastpath_browserdeep_office_driver_info_replies(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            if action == "browser_deep_tools":
                assert kwargs.get("mode") == "clear_chrome_cache"
                return '{"ok": true}'
            if action == "office_tools":
                assert kwargs.get("mode") == "open_word_new"
                return '{"ok": true}'
            if action == "driver_tools":
                assert kwargs.get("mode") == "drivers_list"
                return '{"ok": true}'
            if action == "info_tools":
                assert kwargs.get("mode") == "system_language"
                return '{"ok": true}'
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_deep, reply_deep = await loop._try_global_windows_fastpath(
        text="مسح الكاش لمتصفح chrome", session_key="s28"
    )
    assert handled_deep is True
    assert "chrome" in str(reply_deep).lower() or "كاش" in str(reply_deep)

    handled_office, reply_office = await loop._try_global_windows_fastpath(
        text="فتح ملف word جديد", session_key="s29"
    )
    assert handled_office is True
    assert "word" in str(reply_office).lower() or "ورد" in str(reply_office)

    handled_driver, reply_driver = await loop._try_global_windows_fastpath(
        text="قائمة التعريفات المثبتة", session_key="s30"
    )
    assert handled_driver is True
    assert "تعريفات" in str(reply_driver) or "driver" in str(reply_driver).lower()

    handled_info, reply_info = await loop._try_global_windows_fastpath(
        text="لغة النظام الحالية", session_key="s31"
    )
    assert handled_info is True
    assert "لغة" in str(reply_info) or "language" in str(reply_info).lower()


@pytest.mark.asyncio
async def test_global_fastpath_control_panel_and_mmc_replies(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            if action == "app_tools":
                assert kwargs.get("mode") == "open_sound_cpl"
                return '{"ok": true}'
            if action == "dev_tools":
                assert kwargs.get("mode") == "open_task_scheduler"
                return '{"ok": true}'
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_app, reply_app = await loop._try_global_windows_fastpath(
        text="افتح mmsys.cpl", session_key="s32"
    )
    assert handled_app is True
    assert "الصوت" in str(reply_app) or "sound" in str(reply_app).lower()

    handled_dev, reply_dev = await loop._try_global_windows_fastpath(
        text="taskschd.msc", session_key="s33"
    )
    assert handled_dev is True
    assert "المهام" in str(reply_dev) or "scheduler" in str(reply_dev).lower()


@pytest.mark.asyncio
async def test_global_fastpath_event_errors_and_bsod_replies(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "dev_tools"
            assert kwargs.get("mode") in {"event_errors", "analyze_bsod"}
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_events, reply_events = await loop._try_global_windows_fastpath(
        text="آخر أخطاء النظام", session_key="s33e"
    )
    assert handled_events is True
    assert "خط" in str(reply_events) or "event" in str(reply_events).lower()

    handled_bsod, reply_bsod = await loop._try_global_windows_fastpath(
        text="تحليل شاشة الموت", session_key="s33b"
    )
    assert handled_bsod is True
    assert "bsod" in str(reply_bsod).lower() or "انهيار" in str(reply_bsod)


@pytest.mark.asyncio
async def test_global_fastpath_app_tools_extra_replies(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "app_tools"
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled_mixer, reply_mixer = await loop._try_global_windows_fastpath(
        text="volume mixer", session_key="s34"
    )
    assert handled_mixer is True
    assert "mixer" in str(reply_mixer).lower() or "خالط" in str(reply_mixer)

    handled_mic, reply_mic = await loop._try_global_windows_fastpath(
        text="microphone settings", session_key="s35"
    )
    assert handled_mic is True
    assert "microphone" in str(reply_mic).lower() or "الميكروفون" in str(reply_mic)

    handled_music, reply_music = await loop._try_global_windows_fastpath(
        text="open music player", session_key="s35m"
    )
    assert handled_music is True
    assert "music" in str(reply_music).lower() or "الموسيقى" in str(reply_music)

    handled_inetcpl, reply_inetcpl = await loop._try_global_windows_fastpath(
        text="inetcpl.cpl", session_key="s35i"
    )
    assert handled_inetcpl is True
    assert "internet" in str(reply_inetcpl).lower() or "الإنترنت" in str(reply_inetcpl) or "الانترنت" in str(reply_inetcpl)

    handled_deskcpl, reply_deskcpl = await loop._try_global_windows_fastpath(
        text="desk.cpl", session_key="s35d"
    )
    assert handled_deskcpl is True
    assert "display" in str(reply_deskcpl).lower() or "العرض" in str(reply_deskcpl)

    handled_appwiz, reply_appwiz = await loop._try_global_windows_fastpath(
        text="appwiz.cpl", session_key="s36"
    )
    assert handled_appwiz is True
    assert "programs" in str(reply_appwiz).lower() or "البرامج" in str(reply_appwiz)

    handled_mouse, reply_mouse = await loop._try_global_windows_fastpath(
        text="control mouse", session_key="s36m"
    )
    assert handled_mouse is True
    assert "mouse" in str(reply_mouse).lower() or "فأرة" in str(reply_mouse) or "الفاره" in str(reply_mouse)

    handled_keyboard, reply_keyboard = await loop._try_global_windows_fastpath(
        text="control keyboard", session_key="s36k"
    )
    assert handled_keyboard is True
    assert "keyboard" in str(reply_keyboard).lower() or "لوحة المفاتيح" in str(reply_keyboard)

    handled_printers, reply_printers = await loop._try_global_windows_fastpath(
        text="control printers", session_key="s36p"
    )
    assert handled_printers is True
    assert "printer" in str(reply_printers).lower() or "طابعات" in str(reply_printers)

    handled_users, reply_users = await loop._try_global_windows_fastpath(
        text="control userpasswords2", session_key="s36u"
    )
    assert handled_users is True
    assert "user" in str(reply_users).lower() or "حساب" in str(reply_users)

    handled_users2, reply_users2 = await loop._try_global_windows_fastpath(
        text="control userpasswords", session_key="s36u2"
    )
    assert handled_users2 is True
    assert "user" in str(reply_users2).lower() or "حساب" in str(reply_users2)

    handled_bt, reply_bt = await loop._try_global_windows_fastpath(
        text="bthprops.cpl", session_key="s36bt"
    )
    assert handled_bt is True
    assert "bluetooth" in str(reply_bt).lower() or "بلوتوث" in str(reply_bt)

    handled_access, reply_access = await loop._try_global_windows_fastpath(
        text="access.cpl", session_key="s36ac"
    )
    assert handled_access is True
    assert "access" in str(reply_access).lower() or "الوصول" in str(reply_access)

    handled_admintools, reply_admintools = await loop._try_global_windows_fastpath(
        text="control admintools", session_key="s36a"
    )
    assert handled_admintools is True
    assert "administrative" in str(reply_admintools).lower() or "اداري" in str(reply_admintools) or "إداري" in str(reply_admintools)

    handled_schedtasks, reply_schedtasks = await loop._try_global_windows_fastpath(
        text="control schedtasks", session_key="s36s"
    )
    assert handled_schedtasks is True
    assert "task" in str(reply_schedtasks).lower() or "المهام" in str(reply_schedtasks)

    handled_netconn, reply_netconn = await loop._try_global_windows_fastpath(
        text="control netconnections", session_key="s36n"
    )
    assert handled_netconn is True
    assert "network" in str(reply_netconn).lower() or "الشبكة" in str(reply_netconn)

    handled_folders, reply_folders = await loop._try_global_windows_fastpath(
        text="control folders", session_key="s36f"
    )
    assert handled_folders is True
    assert "folder" in str(reply_folders).lower() or "مجلد" in str(reply_folders)

    handled_color, reply_color = await loop._try_global_windows_fastpath(
        text="control color", session_key="s36c"
    )
    assert handled_color is True
    assert "color" in str(reply_color).lower() or "لون" in str(reply_color) or "ألوان" in str(reply_color)

    handled_desktop, reply_desktop = await loop._try_global_windows_fastpath(
        text="control desktop", session_key="s36d"
    )
    assert handled_desktop is True
    assert "desktop" in str(reply_desktop).lower() or "سطح المكتب" in str(reply_desktop)


@pytest.mark.asyncio
async def test_global_fastpath_open_settings_page_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "open_settings_page"
            assert kwargs.get("page") == "privacy"
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="افتح إعدادات الخصوصية", session_key="s37"
    )
    assert handled is True
    assert "الخصوصية" in str(reply) or "privacy" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_open_settings_page_update_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "open_settings_page"
            assert kwargs.get("page") == "windowsupdate"
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="افتح تحديثات ويندوز", session_key="s38"
    )
    assert handled is True
    assert "تحديثات" in str(reply) or "update" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_vision_describe_screen_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "vision_tools"
            assert kwargs.get("mode") == "describe_screen"
            return '{"ok": true, "ocr_text_preview": "Task Manager - Processes"}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="انظر إلى الشاشة", session_key="s39"
    )
    assert handled is True
    assert "الشاشة" in str(reply) or "screen" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_screenshot_window_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "screenshot_tools"
            assert kwargs.get("mode") == "window_active"
            return '{"ok": true, "mode": "window_active", "path": "C:/tmp/window.png"}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="أخذ لقطة لنافذة محددة", session_key="s39ss"
    )
    assert handled is True
    assert "لقطة" in str(reply) or "captured" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_screen_record_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "media_tools"
            assert kwargs.get("mode") == "screen_record"
            return '{"ok": true, "mode": "screen_record", "seconds": 5, "path": "C:/Users/Admin/Videos/screen_record_test.mp4"}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="سجل الشاشة 5 ثواني", session_key="s39rec"
    )
    assert handled is True
    assert "🎥" in str(reply) or "record" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_browser_mute_only_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "media_tools"
            assert kwargs.get("mode") == "mute_browser_only"
            return '{"ok": true, "mode": "mute_browser_only", "changed_sessions": 2, "browsers": ["chrome.exe"]}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="كتم صوت المتصفح فقط", session_key="s39muteb"
    )
    assert handled is True
    assert "🔇" in str(reply) or "browser" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_returns_failure_when_tool_ok_false(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "window_control"
            return '{"ok": false, "error": "verification failed"}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="صغر كل النوافذ", session_key="s39f"
    )
    assert handled is True
    assert "فشل التنفيذ" in str(reply) or "failed" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_repeat_last_without_history(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="كرر", session_key="s39r0"
    )
    assert handled is True
    assert "ما في أمر" in str(reply) or "no previous command" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_repeat_last_replays_previous_command(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    calls: list[tuple[str, dict]] = []

    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            calls.append((action, dict(kwargs)))
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled1, _reply1 = await loop._try_global_windows_fastpath(
        text="اكتم الصوت", session_key="s39r1"
    )
    handled2, _reply2 = await loop._try_global_windows_fastpath(
        text="كرر", session_key="s39r1"
    )

    assert handled1 is True
    assert handled2 is True
    assert len(calls) >= 2
    assert calls[0][0] == "volume"
    assert calls[1][0] == "volume"
    assert calls[0][1].get("mode") == "mute"
    assert calls[1][1].get("mode") == "mute"


@pytest.mark.asyncio
async def test_global_fastpath_repeat_last_with_count_replays_multiple_times(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    calls: list[tuple[str, dict]] = []

    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            calls.append((action, dict(kwargs)))
            return '{"ok": true}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()

    handled1, _reply1 = await loop._try_global_windows_fastpath(
        text="اكتم الصوت", session_key="s39r2"
    )
    handled2, _reply2 = await loop._try_global_windows_fastpath(
        text="كرر اخر امر 3 مرات", session_key="s39r2"
    )

    assert handled1 is True
    assert handled2 is True
    assert len(calls) == 4
    assert all(call[0] == "volume" for call in calls)
    assert all(call[1].get("mode") == "mute" for call in calls)


@pytest.mark.asyncio
async def test_global_fastpath_popup_message_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "automation_tools"
            assert kwargs.get("mode") == "popup"
            return '{"ok": true, "mode": "popup"}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text='اظهر رسالة "تم النسخ"', session_key="s39popup"
    )
    assert handled is True
    assert "رسالة" in str(reply) or "popup" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_tts_to_file_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "automation_tools"
            assert kwargs.get("mode") == "tts_to_file"
            assert "مرحبا" in str(kwargs.get("text") or "")
            return '{"ok": true, "mode": "tts_to_file", "path": "C:/Users/Admin/Music/tts_test.wav", "format": "wav"}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text='تحويل النص الى ملف صوتي "مرحبا"', session_key="s39ttsfile"
    )
    assert handled is True
    assert "tts_test.wav" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_set_app_volume_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "media_tools"
            assert kwargs.get("mode") == "app_volume_set"
            assert str(kwargs.get("name", "")).lower() == "chrome"
            assert int(kwargs.get("level")) == 30
            return '{"ok": true, "mode": "app_volume_set", "name": "chrome.exe", "level": 30, "changed_sessions": 2}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="خلي صوت تطبيق Chrome 30", session_key="s39appv"
    )
    assert handled is True
    assert "30" in str(reply)
    assert "chrome" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_raise_app_volume_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "media_tools"
            assert kwargs.get("mode") == "app_volume_up"
            assert str(kwargs.get("name", "")).lower() == "chrome"
            assert int(kwargs.get("level")) == 15
            return '{"ok": true, "mode": "app_volume_up", "name": "chrome.exe", "delta": 15, "level": 52, "changed_sessions": 2}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="رفع صوت تطبيق Chrome 15", session_key="s39appvup"
    )
    assert handled is True
    assert "15" in str(reply)
    assert "chrome" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_mute_app_volume_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "media_tools"
            assert kwargs.get("mode") == "app_volume_mute"
            assert str(kwargs.get("name", "")).lower() == "chrome"
            return '{"ok": true, "mode": "app_volume_mute", "name": "chrome.exe", "muted": true, "changed_sessions": 1}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="كتم صوت تطبيق Chrome", session_key="s39appvmute"
    )
    assert handled is True
    assert "chrome" in str(reply).lower()
    assert ("كتم" in str(reply)) or ("muted" in str(reply).lower())


@pytest.mark.asyncio
async def test_global_fastpath_now_playing_info_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "media_tools"
            assert kwargs.get("mode") == "now_playing_info"
            return (
                '{"ok": true, "mode": "now_playing_info", "title": "Numb", '
                '"artist": "Linkin Park", "playback_status": "Playing", "app": "Spotify.exe"}'
            )

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="شو الأغنية المشغلة", session_key="s39nowplay"
    )
    assert handled is True
    assert "numb" in str(reply).lower()
    assert "spotify" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_camera_snapshot_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "media_tools"
            assert kwargs.get("mode") == "camera_snapshot"
            return '{"ok": true, "mode": "camera_snapshot", "path": "C:/Users/Admin/Pictures/camera_test.jpg"}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="التقاط صورة من الكاميرا", session_key="s39cam"
    )
    assert handled is True
    assert ("كاميرا" in str(reply)) or ("camera" in str(reply).lower())


@pytest.mark.asyncio
async def test_global_fastpath_vision_click_target_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "vision_tools"
            assert kwargs.get("mode") == "locate_ui_target"
            assert kwargs.get("interaction") == "click"
            return '{"ok": true, "mode": "locate_ui_target", "matched_label": "زر التالي", "action_done": "click"}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="انقر على زر التالي", session_key="s39visionc"
    )
    assert handled is True
    assert "النقر" in str(reply) or "clicked" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_vision_double_click_target_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "vision_tools"
            assert kwargs.get("mode") == "locate_ui_target"
            assert kwargs.get("interaction") == "double_click"
            return '{"ok": true, "mode": "locate_ui_target", "matched_label": "أيقونة كروم", "action_done": "double_click"}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="دبل كليك على أيقونة كروم", session_key="s39visiondc"
    )
    assert handled is True
    assert "دبل كليك" in str(reply) or "double-clicked" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_vision_right_click_target_human_reply(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            assert action == "vision_tools"
            assert kwargs.get("mode") == "locate_ui_target"
            assert kwargs.get("interaction") == "right_click"
            return '{"ok": true, "mode": "locate_ui_target", "matched_label": "ملف التقرير", "action_done": "right_click"}'

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    loop = AgentLoop()
    handled, reply = await loop._try_global_windows_fastpath(
        text="كليك يمين على ملف التقرير", session_key="s39visionrc"
    )
    assert handled is True
    assert "يمين" in str(reply) or "right-clicked" in str(reply).lower()


@pytest.mark.asyncio
async def test_global_fastpath_repeat_last_interval_replays_multiple_times(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    calls: list[tuple[str, dict]] = []

    class DummyDesktopTool:
        async def execute(self, action: str, **kwargs):
            calls.append((action, dict(kwargs)))
            return '{"ok": true}'

    async def _fake_sleep(_seconds: float) -> None:
        return None

    monkeypatch.setattr("Mudabbir.tools.builtin.desktop.DesktopTool", DummyDesktopTool)
    monkeypatch.setattr("Mudabbir.agents.loop.asyncio.sleep", _fake_sleep)
    loop = AgentLoop()

    handled1, _reply1 = await loop._try_global_windows_fastpath(
        text="اكتم الصوت", session_key="s39ri1"
    )
    handled2, reply2 = await loop._try_global_windows_fastpath(
        text="كرر آخر أمر كل 2 ثواني 3 مرات", session_key="s39ri1"
    )

    assert handled1 is True
    assert handled2 is True
    assert "🔁" in str(reply2) or "repeated" in str(reply2).lower()
    assert len(calls) == 4
    assert all(call[0] == "volume" for call in calls)
    assert all(call[1].get("mode") == "mute" for call in calls)
