diff --git a/docs/v2/architecture.md b/docs/v2/architecture.md index 79e9766..3972d48 100644 --- a/docs/v2/architecture.md +++ b/docs/v2/architecture.md @@ -59,7 +59,8 @@ v1도 STT는 이미 faster-whisper입니다. 느린 진짜 이유는 엔진이 ├─ 채팅 채널 연결 (등록한 채널 읽기·보내기·수정·검색) ├─ 브라우저 에이전트 (Playwright + 봇용 크롬창, 백그라운드 가능) ├─ 게임·안티치트 감지 (게임 모드 전환, 자동 입력 차단) - └─ PC 제어 모듈 (전체·모니터별·창별 화면 캡처, 키보드/마우스 입력) + └─ PC 제어 모듈 (전체·모니터별·창별 화면 캡처, agent-desktop으로 프로그램 조작, + 접근성 정보가 없는 화면만 키보드/마우스 입력) │ │ 로컬 WebSocket (127.0.0.1, 앱이 발급한 토큰으로만 접속) ▼ @@ -82,6 +83,7 @@ v1도 STT는 이미 faster-whisper입니다. 느린 진짜 이유는 엔진이 | GUI 앱 | Electron + TypeScript (React UI) | 디스코드 음성 코어(discord.js), Playwright, 화면 캡처가 모두 Node 생태계라 한 언어로 묶입니다. v1 봇 코드(TypeScript)를 옮길 수 있습니다. Tauri는 가볍지만 Rust와 Node 사이드카를 따로 둬야 해서 복잡해집니다. | | 음성 워커 | Python (faster-whisper, MeloTTS, 기존 jarvis) | STT·TTS 모델과 기존 두뇌 코드(메모리, 도구, 스펙 문서)가 Python입니다. 다시 짜는 것보다 재사용이 안전합니다. | | LLM 엔진 | Strata (MIT) | Windows 설치 지원, RTX 50 지원, `--data-dir`로 저장 위치 지정, 헤드리스 실행(`--no-tui`). 앱에 포함해 배포해도 라이선스 문제가 없습니다. | +| PC 프로그램 조작 | agent-desktop (Apache-2.0) | Windows UI Automation으로 버튼·입력칸을 읽고 직접 누릅니다. 좌표 클릭보다 정확하고, 커서와 포커스를 뺏지 않습니다. 실행 파일 하나라 설치 파일에 넣기 쉽습니다. ([pc-features.md](pc-features.md#키보드마우스-제어와-안티치트)) | | LLM 예비 엔진 | OpenAI 호환 주소 직접 입력 | Strata에 문제가 생기면 llama.cpp, Ollama 같은 다른 로컬 엔진으로 바꿔 끼웁니다. | | Python 런타임 | uv + 독립 실행형 Python 3.12 | 사용자가 Python을 따로 깔 필요가 없고 시스템 Python과 섞이지 않습니다. 전부 데이터 폴더 안에 설치됩니다. | | 설치 파일 | NSIS (electron-builder) | 설치 파일은 약 200MB 내외로 두고, 모델과 런타임은 첫 실행 때 받습니다. | diff --git a/docs/v2/decisions.md b/docs/v2/decisions.md index 30af187..958fb5c 100644 --- a/docs/v2/decisions.md +++ b/docs/v2/decisions.md @@ -17,6 +17,7 @@ | 가상 디스플레이 드라이버 | 필요해지면 설치. 설치 때 관리자 권한 1회. 우리 설치 파일 하나로 어느 PC에서나 돼야 하므로 Parsec 드라이버는 제품에 쓰지 않음(M0 개념 확인용으로만 사용). 대상은 x64 Windows 10/11(S 모드 제외). ARM64는 WHQL 서명이 필요해 범위 밖. 배포할 드라이버는 오픈소스 Virtual Display Driver(MIT, SignPath 재단 서명, IddCx)를 설치 파일에 함께 넣음(사용자 선택). 자체 드라이버는 만들지 않음 | | 게임 모드 | 테두리 없는 창 게임도 감지. (a) RAM 위주로 / (b) 빠름 모델로 / (c) 일시정지 각각 켜기/끄기, 기본은 (a)만 ([pc-features.md](pc-features.md#게임-모드)) | | 안티치트 | 안티치트 게임 실행 중에는 키보드·마우스 제어를 막고 안티치트 이름으로 안내 | +| PC 프로그램 조작 | agent-desktop(Apache-2.0, Windows UI Automation)으로 버튼·입력칸을 직접 누르고 값을 넣음. 접근성 정보가 없는 화면만 Windows 입력 API. 두뇌에는 동작 몇 개만 가진 도구 하나로 보여 줌. 계속 켜 두는 방식(MCP)과 매번 실행하는 방식 중 무엇을 쓸지는 M0 `desktop` 단계 결과로 정함 ([pc-features.md](pc-features.md#키보드마우스-제어와-안티치트)) | | 다른 사람 화면공유 보기 | 자비스가 말로 창 분리(팝아웃)를 요청하고 분리된 창만 캡처. 디스코드 앱을 직접 조작하지 않음 ([pc-features.md](pc-features.md#다른-사람의-디스코드-화면공유-보기-창-분리-방식)) | | AI 채팅 채널 | GUI에서 채널 ID·이름·설명 편집, AI가 읽기·보내기·수정 등 수행 ([conversation.md](conversation.md#ai-채팅-채널)) | | 채팅 채널 이름·설명 반영 | 실제 디스코드 채널 이름·주제까지 바꿈. "디스코드에도 반영" 켜기/끄기, 기본 켜짐 | diff --git a/docs/v2/pc-features.md b/docs/v2/pc-features.md index ce6c4cc..9f20834 100644 --- a/docs/v2/pc-features.md +++ b/docs/v2/pc-features.md @@ -74,7 +74,16 @@ ## 키보드·마우스 제어와 안티치트 -- 키보드·마우스는 Windows 입력 API로 넣습니다. +- 프로그램 조작은 [agent-desktop](https://github.com/vercel-labs/agent-desktop)(Apache-2.0, Windows UI Automation)으로 합니다. 앱 설치 파일에 실행 파일(약 4MB)을 함께 넣습니다. + - 창의 버튼·입력칸·메뉴 목록을 글자로 읽고, 고른 항목을 직접 누르거나 값을 넣습니다. 화면 좌표를 쓰지 않으므로 해상도·배율·창 위치가 바뀌어도 맞게 누릅니다. + - 기본은 마우스 커서를 움직이지 않고 포커스도 가져오지 않습니다. 사용자가 다른 창에서 작업하는 중에도 뒤에 있는 창을 조작할 수 있습니다. 최소화된 창은 조작하지 못하므로 먼저 되돌립니다. + - 누르거나 넣은 뒤 화면을 다시 읽어 결과를 확인하고, 확인된 것만 "했습니다"라고 말합니다. + - Alt+F4, Win+R, Ctrl+Shift+Esc 같은 위험 단축키는 agent-desktop이 기본으로 막습니다. 이 막음을 푸는 옵션(`--force`)은 쓰지 않습니다. + - 관리자 권한으로 실행된 창은 Windows가 막아서 조작하지 못합니다. 그때는 못 한다고 답합니다. +- 접근성 정보가 없는 화면(게임, 그림으로만 그린 화면)에만 Windows 입력 API로 실제 키보드·마우스를 넣습니다. 이때는 커서와 포커스가 움직입니다. +- 두뇌에는 도구 하나(창 목록, 실행, 화면 항목 읽기, 누르기, 값 넣기, 키 누르기, 닫기)로만 보여 줍니다. agent-desktop의 MCP 서버를 그대로 붙이면 도구가 67개라 작은 모델이 고르기 어렵기 때문입니다. 실제 호출과 허용 범위·안티치트·비상 정지 검사는 PC 제어 모듈이 합니다. +- PC 제어 모듈이 agent-desktop을 계속 켜 두고 쓸지(MCP 서버), 매번 실행할지는 M0 `desktop` 단계에서 잰 속도로 정합니다. +- 읽은 화면 글자는 PC 안의 LLM에만 들어가고 로그와 결과 파일에는 남기지 않습니다. 로그에는 동작 이름과 결과 코드만 적습니다. - 자비스가 직접 조작할 때는 **허용 범위**와 **위험 동작 확인**을 거칩니다. 파일 삭제, 결제, 전송 등은 음성/GUI로 한 번 더 확인합니다. - **비상 정지 단축키**를 누르면 모든 자동 조작이 즉시 멈춥니다. diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index 7d2d797..be2d29a 100644 --- a/docs/v2/roadmap.md +++ b/docs/v2/roadmap.md @@ -4,7 +4,7 @@ | 단계 | 내용 | 완료 기준 | |---|---|---| -| M0 | 게임PC 사전 검증 | 측정 스크립트를 게임PC에서 직접 실행하고 결과 파일을 보내 주시는 방식입니다. 결과로 기본값을 확정합니다. 확인 항목은 아래 목록에 있습니다. 가상 모니터 확인을 뺀 모든 항목 측정 완료(2026-11-10). 가상 모니터 확인은 M6에서 합니다. 측정 키트: [scripts/m0/](../../scripts/m0/README.md) | +| M0 | 게임PC 사전 검증 | 측정 스크립트를 게임PC에서 직접 실행하고 결과 파일을 보내 주시는 방식입니다. 결과로 기본값을 확정합니다. 확인 항목은 아래 목록에 있습니다. 가상 모니터 확인을 뺀 모든 항목 측정 완료(2026-11-10). 가상 모니터 확인은 M6에서 합니다. 2026-11-10에 추가한 `desktop` 단계(agent-desktop)는 측정 대기입니다. 측정 키트: [scripts/m0/](../../scripts/m0/README.md) | | M1 | 음성 워커 | 화자별 스트리밍 STT(공용 모델, 배치), 문장 단위 TTS를 WebSocket으로 제공. 녹음 파일 10개 동시 입력 테스트 통과 | | M2 | 디스코드 음성 코어 이전 | v1 봇 코드를 Electron 안으로 이전. 입장/퇴장, 화자별 수신, 재생, 정지 명령 동작. 채팅 채널 연결(읽기·보내기) | | M3 | 두뇌 연결 | 기존 jarvis를 Ollama 대신 Strata 주소로 연결. 대화 기록 저장소와 지난 대화 전체 검색(본인 기록 + 등록한 채팅 채널 + 같은 음성 채널의 다른 사람 말). 채팅 채널 도구(읽기·검색·보내기·수정·반응·삭제·고정). 메모리, 날씨, 웹 검색, 식단, MCP 기존 테스트와 평가(evals) 통과 | @@ -25,6 +25,7 @@ M0에서 확인할 항목: - 봇용 크롬창의 Alt+Tab 숨김과 디스코드 화면공유 목록 표시 - 디스코드 분리 화면공유 창 식별과, 가려졌을 때 영상이 멈추는지 - 설치된 게임으로 테두리 없는 창 게임 감지와 안티치트 감지 +- agent-desktop으로 프로그램 조작(계산기 버튼 누르기, 브라우저 입력칸에 값 넣기), 디스코드 화면 읽기 시간, 계속 켜 두는 방식(MCP)과 매번 실행하는 방식의 속도 (`desktop` 단계) M7 완료 기준: @@ -33,7 +34,7 @@ M7 완료 기준: - 캡처 제외 목록 - 분리된 화면공유 창 보기 - 봇용 크롬창 화면공유 표시 -- 키보드·마우스 제어와 비상 정지 +- agent-desktop으로 프로그램 조작, 접근성 정보가 없는 화면만 키보드·마우스 제어, 비상 정지 - 안티치트 감지·차단 안내 - 게임 감지(테두리 없는 창 포함)와 게임 모드 (a)(b)(c) @@ -46,6 +47,8 @@ M0~M4는 "더 빠르고 똑똑한 음성 대화"의 핵심이고, M5~M8은 "설 | Strata가 도구 호출이나 동시 요청을 지원하지 않음 | M0에서 둘 다 지원 확인. 다만 빠름 모델이 "5분 타이머 맞춰 줘"에서 3번 모두 도구를 부르지 않고 "설정했습니다"라고만 답함(12번 중 9번 성공). 지시문 규칙과 "건너뛴 도구 직접 실행" 장치로 고쳤고 평가(`evals/test_tool_skip_confabulation.py`)에 넣음. 게임PC 두 모델 재측정은 측정 키트 `tools_fast`/`tools_recommended` 단계 | | 게임과 VRAM 경쟁 | 게임 모드(RAM 위주/빠름 모델/일시정지 각각 켜기), VRAM 사용량 실시간 표시 | | 테두리 없는 창 게임을 놓치거나 일반 프로그램을 게임으로 잘못 봄 | 창 모양 + GPU 사용량 + 게임 폴더를 같이 보고, 게임 목록·"게임 아님" 목록으로 바로잡음. 감지 이유를 대시보드에 표시 | +| agent-desktop.exe에 코드 서명이 없어 백신이나 SmartScreen이 막을 수 있음 | 우리 설치 파일 안에 넣어 따로 실행 경고가 뜨지 않게 하고, 버전을 고정해 해시를 확인함. 백신이 막으면 첫 실행 점검에서 안내 | +| 크롬·디스코드(크로미움) 화면은 처음 읽을 때 목록이 덜 채워짐(켠 직후 10~25초) | M0 `desktop` 단계에서 실제 시간을 잼. 자주 쓰는 창은 미리 한 번 읽어 둠 | | 안티치트 목록에 없는 게임에서 자동 입력 | GUI에서 직접 추가, 앱 업데이트로 목록 확장. 독점 전체화면 게임 중에는 자동 입력 기본 차단 유지 | | LLM이 이미지 입력을 지원하지 않거나 이미지 읽기가 느림 | M0에서 측정. 화질 단계 낮추기, 창 단위 캡처, 이미지 전용 소형 모델 예비안 | | 분리된 화면공유 창이 가려지면 영상이 멈춤 | M0에서 가려져도 계속 그려짐을 확인. 옮겨 둘 필요 없음 | diff --git a/scripts/m0/README.md b/scripts/m0/README.md index 91078ef..e3def28 100644 --- a/scripts/m0/README.md +++ b/scripts/m0/README.md @@ -34,6 +34,7 @@ LLM 단계는 8080 포트를 씁니다. 다른 프로그램이 이 포트를 쓰 | CosyVoice2 / CosyVoice3 | 한국어 첫 소리까지 시간, 합성 속도, VRAM | | STT | faster-whisper large-v3-turbo의 전사 시간, 정확도, 말하는 중 부분 전사, 10명 동시 처리 | | LLM 빠름 / 권장 | Strata로 Qwen3.6-35B-A3B(약 23GB)와 Qwen3.8-Flash-Next Q2_0(약 66GB)을 받아서 첫 토큰 시간(맥락 길이별), 생성 속도, 도구 호출, 이미지 읽기(화질 단계별), 한국어 답변, 동시 요청, 게임 모드용 VRAM 비우기와 모델 다시 시작·전환 시간 | +| PC 제어 도구 | agent-desktop으로 계산기 버튼을 눌러 12+3=15가 나오는지, 테스트용 브라우저 창(새 임시 프로필)의 입력칸에 글자를 넣고 다시 읽히는지, 디스코드·탐색기 화면을 읽는 시간, 계속 켜 두는 방식(MCP)과 매번 실행하는 방식의 명령 한 번 시간 | ## 개인정보 @@ -42,6 +43,7 @@ LLM 단계는 8080 포트를 씁니다. 다른 프로그램이 이 포트를 쓰 - 다른 프로그램의 창 제목은 저장하지 않습니다. 디스코드 분리 창 제목은 저장해도 되는지 물어본 뒤에만 넣습니다. - 게임 감지는 실행 중인 프로그램 이름과 창 모양만 봅니다. 게임 화면은 저장하지 않습니다. 설치된 게임은 이름과 안티치트 유무만 기록합니다. - 음성 테스트는 키트에 들어 있는 합성 음성만 씁니다. 마이크는 쓰지 않습니다. +- PC 제어 도구 단계는 다른 프로그램의 창 제목과 화면 글자를 저장하지 않습니다. 개수, 걸린 시간, 오류 코드, 계산기 결과 숫자만 저장합니다. 이미 켜 둔 계산기가 있으면 건드리지 않고 그 확인을 건너뛰며, 브라우저는 평소 쓰시는 프로필이 아닌 새 임시 프로필로 엽니다. ## 옵션 (PowerShell에서 직접 실행할 때) @@ -51,7 +53,7 @@ LLM 단계는 8080 포트를 씁니다. 다른 프로그램이 이 포트를 쓰 .\run_m0.ps1 -Only stt,tts_melo -Redo # 특정 단계만 다시 ``` -단계 이름: `sysinfo`, `winchecks`, `vdisplay`, `tts_melo`, `tts_cosy2`, `tts_cosy3`, `stt`, `llm_fast`, `llm_recommended`, `tools_fast`, `tools_recommended` +단계 이름: `sysinfo`, `winchecks`, `vdisplay`, `tts_melo`, `tts_cosy2`, `tts_cosy3`, `stt`, `llm_fast`, `llm_recommended`, `tools_fast`, `tools_recommended`, `desktop` `tools_fast`, `tools_recommended`는 도구 호출만 다시 잽니다. 처음과 같은 방식(고치기 전)과, 자비스의 수정(지시문 규칙, 계획 단계, 건너뛴 도구 직접 실행)을 넣은 방식을 같은 모델로 비교합니다. 이미 받은 모델을 쓰므로 모델 하나에 몇 분이면 끝납니다. @@ -59,4 +61,6 @@ LLM 단계는 8080 포트를 씁니다. 다른 프로그램이 이 포트를 쓰 `run_m0_tools.bat`을 더블클릭하면 이 두 단계만 돌고 결과 zip이 만들어집니다. 직접 답하실 부분은 없습니다. +`run_m0_desktop.bat`을 더블클릭하면 PC 제어 도구 단계(`desktop`)만 돕니다. agent-desktop(약 2MB)을 작업 폴더에 받아 쓰고, 1~2분이면 끝납니다. 계산기와 테스트용 브라우저 창이 잠깐 떴다가 닫히니 그동안 손대지 않으시면 됩니다. 입력칸이 값 넣기를 지원하지 않으면 키 입력으로 넣는데, 이때는 그 창이 잠깐 앞으로 나옵니다. + 다 끝나고 필요 없으면 작업 폴더(`\JarvisM0`)를 통째로 지우면 됩니다. Python, 모델, Strata(엔진과 설정 포함)는 모두 그 안에 설치하도록 지정해 두었습니다. diff --git a/scripts/m0/m0.py b/scripts/m0/m0.py index a1fbad3..e1424fc 100644 --- a/scripts/m0/m0.py +++ b/scripts/m0/m0.py @@ -40,6 +40,8 @@ STAGES = [ # Reuses the models the two stages above downloaded. ("tools_fast", "도구 호출 다시 재기: 빠름 모델", "base", "llm.py", ["model=fast", "only=tools"], 0), ("tools_recommended", "도구 호출 다시 재기: 권장 모델", "base", "llm.py", ["model=recommended", "only=tools"], 0), + # M7 PC control: agent-desktop (UI Automation) on calculator, a test page, Discord. + ("desktop", "PC 제어 도구(agent-desktop) 확인", "", "desktop.py", [], 0), ] diff --git a/scripts/m0/m0lib/desktop.py b/scripts/m0/m0lib/desktop.py new file mode 100644 index 0000000..ec0be3a --- /dev/null +++ b/scripts/m0/m0lib/desktop.py @@ -0,0 +1,422 @@ +"""Stage: agent-desktop (Windows UI Automation) as the M7 PC-control path. + +agent-desktop (github.com/vercel-labs/agent-desktop, Apache-2.0) reads a +program's accessibility tree and acts on its buttons and fields directly, +without moving the mouse or taking focus. This stage checks, on the gaming PC: + + basics the CLI runs, what it reports about permissions and surfaces + calculator click 1, 2, +, 3, = in Windows Calculator and read 15 back + (buttons are found by automation id, so the UI language does + not matter) + text_input set a value in an input on a test page in a throwaway browser + profile and read it back; also how long the Chromium tree takes + to settle after launch + apps how long reading Discord and Explorer takes (counts only) + mcp a warm `agent-desktop mcp` server against one CLI process per + call, for the voice-latency choice between the two + +Privacy: other programs' window titles, UI text and error messages are never +stored. Only counts, timings, error codes and the calculator's digits are. +""" + +from __future__ import annotations + +import hashlib +import io +import json +import os +import queue +import re +import shutil +import subprocess +import sys +import tarfile +import threading +import time +import urllib.request +from pathlib import Path +from typing import Any, Callable + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from m0lib.common import IS_WINDOWS, StageResult, say, stage_args, stats, step # noqa: E402 + +AD_VERSION = "1.2.0" +AD_URL = ("https://github.com/vercel-labs/agent-desktop/releases/download/" + f"v{AD_VERSION}/agent-desktop-v{AD_VERSION}-x86_64-pc-windows-msvc.tar.gz") +AD_SHA256 = "a4199f741a441cedd349bf56c5eba01783b1261258b498efeb7ec9945220c3e8" + +# 12 + 3 = 15, pressed by automation id (language independent). +CALC_BUTTONS = ["clearButton", "num1Button", "num2Button", "plusButton", "num3Button", "equalButton"] +CALC_EXPECTED = "15" +CALC_RESULT_ID = "CalculatorResults" + +PAGE_TITLE = "Jarvis 입력 테스트" +INPUT_NAME = "jarvis-m0-input" +INPUT_TEXT = "자비스 입력 테스트 15" + +READ_APPS = ["Discord", "explorer"] +REPEAT = 5 + + +class Desk: + """Runs agent-desktop commands and records how long each took.""" + + def __init__(self, cmd: list[str], log: Path, timeout: float = 60): + self.cmd = cmd + self.log = log + self.timeout = timeout + self.timings: dict[str, list[float]] = {} + + def __call__(self, *args: str) -> dict[str, Any]: + t0 = time.perf_counter() + try: + proc = subprocess.run(self.cmd + list(args), capture_output=True, text=True, encoding="utf-8", + errors="replace", timeout=self.timeout, stdin=subprocess.DEVNULL) + out = proc.stdout.strip() + env = json.loads(out.splitlines()[-1]) if out else {} + except subprocess.TimeoutExpired: + env = {"ok": False, "error": {"code": "M0_TIMEOUT"}} + except (ValueError, IndexError): + env = {"ok": False, "error": {"code": "M0_NO_JSON"}} + elapsed = time.perf_counter() - t0 + self.timings.setdefault(args[0], []).append(elapsed) + # Command names and codes only: arguments and output can carry UI text. + with open(self.log, "a", encoding="utf-8") as f: + f.write(f"{args[0]} ok={bool(env.get('ok'))} code={code(env)} {elapsed:.2f}s\n") + return env + + +def code(env: dict[str, Any]) -> str | None: + """The error code of an envelope (never the message: it can name windows).""" + if env.get("ok"): + return None + err = env.get("error") + return str(err.get("code")) if isinstance(err, dict) else "M0_UNKNOWN" + + +def first_match(env: dict[str, Any]) -> dict[str, Any] | None: + matches = (env.get("data") or {}).get("matches") or [] if env.get("ok") else [] + return matches[0] if matches else None + + +def windows(desk: Desk) -> list[dict[str, Any]]: + env = desk("list-windows") + data = env.get("data") if env.get("ok") else None + return data if isinstance(data, list) else [] + + +# -------------------------------------------------------------------------- + +def install(work: Path, log: Path, url: str = AD_URL, sha256: str = AD_SHA256) -> Path: + """Download the pinned Windows build into the work folder and verify it.""" + dest = work / "tools" / f"agent-desktop-{AD_VERSION}" + exe = dest / "agent-desktop.exe" + if exe.exists(): + return exe + say(f" agent-desktop {AD_VERSION} 받는 중") + with urllib.request.urlopen(url, timeout=300) as resp: + data = resp.read() + got = hashlib.sha256(data).hexdigest() + if got != sha256: + raise RuntimeError(f"agent-desktop archive hash mismatch: {got}") + tmp = dest.parent / (dest.name + ".tmp") + shutil.rmtree(tmp, ignore_errors=True) + tmp.mkdir(parents=True) + with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as tar: + member = next(m for m in tar.getmembers() if m.isfile() and Path(m.name).name == "agent-desktop.exe") + (tmp / "agent-desktop.exe").write_bytes(tar.extractfile(member).read()) + shutil.rmtree(dest, ignore_errors=True) + tmp.rename(dest) + with open(log, "a", encoding="utf-8") as f: + f.write(f"installed agent-desktop {AD_VERSION} sha256={got}\n") + return exe + + +def check_basics(desk: Desk) -> dict[str, Any]: + out: dict[str, Any] = {} + ver = desk("version") + out["version"] = (ver.get("data") or {}).get("version") if ver.get("ok") else None + st = desk("status") + if st.get("ok"): + d = st.get("data") or {} + out["platform"] = d.get("platform") + out["permissions"] = {k: (v or {}).get("state") for k, v in (d.get("permissions") or {}).items()} + out["surfaces"] = d.get("supported_surfaces") + else: + out["status_error"] = code(st) + wins = windows(desk) + out["window_count"] = len(wins) + out["accessible_windows"] = sum(1 for w in wins if w.get("accessible")) + out["ok"] = bool(out["version"]) and st.get("ok", False) + return out + + +def _calculator_app(desk: Desk, wait_s: float) -> str | None: + deadline = time.monotonic() + wait_s + while True: + for w in windows(desk): + name = str(w.get("app_name") or "") + if "calculator" in name.lower(): + return name + if time.monotonic() > deadline: + return None + time.sleep(0.5) + + +def check_calculator(desk: Desk, wait_s: float = 15) -> dict[str, Any]: + out: dict[str, Any] = {"ok": False} + if _calculator_app(desk, 0) is not None: + # The user's own calculator: do not press its buttons or close it. + out["skipped"] = "calculator already open" + return out + t0 = time.perf_counter() + launched = desk("launch", "calc", "--timeout", "20000") + out["launch_error"] = code(launched) + if not launched.get("ok") and IS_WINDOWS: + subprocess.run(["cmd", "/c", "start", "", "calculator:"], capture_output=True, timeout=30) + out["launch_fallback"] = "calculator: URI" + app = _calculator_app(desk, wait_s) + out["window_s"] = round(time.perf_counter() - t0, 2) + if not app: + out["error"] = "calculator window not found" + return out + out["app_name"] = app + try: + for bid in CALC_BUTTONS: + m = first_match(desk("find", "--app", app, "--native-id", bid)) + if not m: + if bid == "clearButton": + continue # optional: a fresh calculator already shows 0 + out["error"] = f"button {bid} not found" + return out + clicked = desk("click", m["ref_id"]) + if not clicked.get("ok"): + out["error"] = f"click {bid}: {code(clicked)}" + return out + m = first_match(desk("find", "--app", app, "--native-id", CALC_RESULT_ID)) + digits = "".join(re.findall(r"\d", str((m or {}).get("name") or ""))) + out["display_digits"] = digits + out["ok"] = digits.endswith(CALC_EXPECTED) and digits != "" + if not out["ok"]: + out["error"] = "display does not show the sum" + return out + finally: + out["close_error"] = code(desk("close-app", app)) + + +def _page(page_dir: Path) -> Path: + page_dir.mkdir(parents=True, exist_ok=True) + page = page_dir / "jarvis_m0_input.html" + page.write_text(f"""{PAGE_TITLE} +

M0 입력 테스트 (곧 닫힙니다)

+""", encoding="utf-8") + return page + + +def check_text_input(desk: Desk, open_page: Callable[[Path, str], Any], page_dir: Path, + wait_s: float = 40) -> dict[str, Any]: + out: dict[str, Any] = {"ok": False, "settle_s": None} + proc = open_page(_page(page_dir), PAGE_TITLE) + if proc is None: + out["error"] = "no Chrome or Edge found" + return out + try: + t0 = time.perf_counter() + ref = None + while time.perf_counter() - t0 < wait_s and not ref: + wid = next((w.get("id") for w in windows(desk) if PAGE_TITLE in str(w.get("title") or "")), None) + if wid: + m = first_match(desk("find", "--window-id", str(wid), "--role", "textfield", "--name", INPUT_NAME)) + ref = (m or {}).get("ref_id") + if not ref: + time.sleep(1) + if not ref: + out["error"] = "test input not found" + return out + out["settle_s"] = round(time.perf_counter() - t0, 2) + # set-value is semantic (no focus, no keystrokes). When the field does not + # support it, fall back to keystroke typing, which takes the foreground. + set_env = desk("set-value", ref, INPUT_TEXT) + out["set_error"] = code(set_env) + out["input_method"] = "set-value" + if not set_env.get("ok"): + set_env = desk("type", ref, INPUT_TEXT, "--headed") + out["type_error"] = code(set_env) + out["input_method"] = "type --headed" + got = desk("get", ref, "--property", "value") + out["read_back"] = bool(got.get("ok")) and (got.get("data") or {}).get("value") == INPUT_TEXT + out["ok"] = bool(set_env.get("ok")) and out["read_back"] + if not out["ok"]: + out["error"] = "value not read back" + return out + finally: + try: + proc.terminate() + except Exception: + pass + + +def check_apps(desk: Desk) -> dict[str, Any]: + env = desk("list-apps") + running = {str(a.get("name") or "").lower() for a in ((env.get("data") or {}).get("apps") or [])} \ + if env.get("ok") else set() + out: dict[str, Any] = {} + for app in READ_APPS: + if app.lower() not in running: + out[app] = {"running": False} + continue + t0 = time.perf_counter() + snap = desk("snapshot", "--app", app, "-i", "--compact", "--timeout-ms", "8000") + d = snap.get("data") or {} if snap.get("ok") else {} + out[app] = {"running": True, "ok": bool(snap.get("ok")), "error": code(snap), + "ref_count": d.get("ref_count"), "complete": d.get("complete"), + "seconds": round(time.perf_counter() - t0, 2)} + return out + + +class _Mcp: + def __init__(self, cmd: list[str]): + self.proc = subprocess.Popen(cmd + ["mcp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, text=True, encoding="utf-8", bufsize=1) + self.lines: queue.Queue[str] = queue.Queue() + threading.Thread(target=self._read, daemon=True).start() + self.next_id = 0 + + def _read(self) -> None: + assert self.proc.stdout is not None + for line in self.proc.stdout: + self.lines.put(line) + + def send(self, method: str, params: dict[str, Any] | None = None, notify: bool = False) -> Any: + msg: dict[str, Any] = {"jsonrpc": "2.0", "method": method, "params": params or {}} + if not notify: + self.next_id += 1 + msg["id"] = self.next_id + assert self.proc.stdin is not None + self.proc.stdin.write(json.dumps(msg) + "\n") + self.proc.stdin.flush() + if notify: + return None + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + try: + resp = json.loads(self.lines.get(timeout=max(0.1, deadline - time.monotonic()))) + except queue.Empty: + break + if resp.get("id") == msg["id"]: + if "error" in resp: + raise RuntimeError(f"mcp {method} error {resp['error'].get('code')}") + return resp.get("result") + raise RuntimeError(f"mcp {method} timed out") + + def close(self) -> None: + try: + self.proc.kill() + except Exception: + pass + + +def check_mcp(cmd: list[str], desk: Desk) -> dict[str, Any]: + out: dict[str, Any] = {"ok": False} + cli = [] + for _ in range(REPEAT): + t0 = time.perf_counter() + desk("list-windows") + cli.append(time.perf_counter() - t0) + out["cli_call_s"] = stats(cli) + server = _Mcp(cmd) + try: + t0 = time.perf_counter() + server.send("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "jarvis-m0", "version": "1"}}) + server.send("notifications/initialized", notify=True) + out["start_s"] = round(time.perf_counter() - t0, 3) + tools = (server.send("tools/list") or {}).get("tools") or [] + out["tool_count"] = len(tools) + name = next((t["name"] for t in tools if "list_windows" in t.get("name", "")), None) + if not name: + out["error"] = "no list-windows tool" + return out + warm = [] + for _ in range(REPEAT): + t0 = time.perf_counter() + server.send("tools/call", {"name": name, "arguments": {}}) + warm.append(time.perf_counter() - t0) + out["warm_call_s"] = stats(warm) + out["ok"] = True + except Exception as e: + out["error"] = type(e).__name__ + ": " + str(e)[:200] + finally: + server.close() + return out + + +def open_browser_page(profile: Path) -> Callable[[Path, str], Any]: + """Opens the test page in a throwaway Chrome/Edge profile (never the user's).""" + def _open(page: Path, title: str) -> Any: + cands = [os.path.expandvars(p) for p in ( + r"%ProgramFiles%\Google\Chrome\Application\chrome.exe", + r"%LOCALAPPDATA%\Google\Chrome\Application\chrome.exe", + r"%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe", + r"%ProgramFiles%\Microsoft\Edge\Application\msedge.exe")] + exe = next((p for p in cands if os.path.exists(p)), None) + if not exe: + return None + return subprocess.Popen([exe, f"--user-data-dir={profile}", "--no-first-run", "--no-default-browser-check", + "--new-window", page.as_uri()]) + return _open + + +def measure(cmd: list[str], work: Path, out_path: Path, open_page: Callable[[Path, str], Any]) -> str: + r = StageResult("desktop", out_path) + log = work / "logs" / "desktop.log" + log.parent.mkdir(parents=True, exist_ok=True) + desk = Desk(cmd, log) + r["agent_desktop_version"] = AD_VERSION + checks = [("basics", "기본 동작", lambda: check_basics(desk)), + ("calculator", "계산기 버튼 누르기", lambda: check_calculator(desk)), + ("text_input", "브라우저 입력칸에 글자 넣기", lambda: check_text_input( + desk, open_page, work / "cache" / "desktop")), + ("apps", "디스코드·탐색기 읽기 시간", lambda: check_apps(desk)), + ("mcp", "계속 켜 두는 방식(MCP) 속도", lambda: check_mcp(cmd, desk))] + for key, title, fn in checks: + say(f" {title}") + try: + r[key] = fn() + except Exception as e: + r[key] = {"ok": False} + r.error(key, f"{type(e).__name__}") + if key == "basics" and not r[key].get("ok"): + r["timings"] = {k: stats(v) for k, v in desk.timings.items()} + r.save("failed") + return "failed" + r["timings"] = {k: stats(v) for k, v in desk.timings.items()} + core_ok = r["calculator"].get("ok") and r["text_input"].get("ok") and r["mcp"].get("ok") + status = "ok" if core_ok else "partial" + r.save(status) + return status + + +def main() -> int: + out, work, _opts = stage_args() + step("PC 제어 도구(agent-desktop) 확인") + if not IS_WINDOWS: + r = StageResult("desktop", out) + r.note("Windows only") + r.save("skipped") + return 0 + say(" 계산기와 테스트용 브라우저 창이 잠깐 떴다가 닫힙니다. 손대지 않으셔도 됩니다.") + try: + exe = install(work, work / "logs" / "desktop.log") + except Exception as e: + r = StageResult("desktop", out) + r.error("install", e) + r.save("failed") + return 1 + status = measure([str(exe)], work, out, open_browser_page(work / "cache" / "desktop" / "browser-profile")) + say(f" 결과: {status}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/m0/run_m0_desktop.bat b/scripts/m0/run_m0_desktop.bat new file mode 100644 index 0000000..7ba16d0 --- /dev/null +++ b/scripts/m0/run_m0_desktop.bat @@ -0,0 +1,5 @@ +@echo off +chcp 65001 >nul +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0run_m0.ps1" -Only desktop %* +echo. +pause diff --git a/tests/test_m0_desktop.py b/tests/test_m0_desktop.py new file mode 100644 index 0000000..5feba84 --- /dev/null +++ b/tests/test_m0_desktop.py @@ -0,0 +1,266 @@ +"""Behaviour of the M0 ``desktop`` stage (agent-desktop on the gaming PC). + +The stage drives a real CLI on Windows, so these tests run it against a fake +``agent-desktop`` that speaks the same JSON envelope: a calculator that adds, +a browser test page with one input, a private document window whose title +must never reach the results, and an MCP server over stdio. +""" + +from __future__ import annotations + +import hashlib +import io +import json +import sys +import tarfile +import textwrap +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts" / "m0")) + +from m0lib import desktop # noqa: E402 + +pytestmark = pytest.mark.unit + +SECRET = "비밀계획서" + +FAKE_CLI = textwrap.dedent(r''' + import json, os, sys + STATE = os.environ["FAKE_AD_STATE"] + SECRET = os.environ["FAKE_AD_SECRET"] + MODE = os.environ.get("FAKE_AD_MODE", "") + + def load(): + try: + with open(STATE, encoding="utf-8") as f: + return json.load(f) + except FileNotFoundError: + return {} + + def save(s): + with open(STATE, "w", encoding="utf-8") as f: + json.dump(s, f) + + def ok(cmd, data): + print(json.dumps({"version": "2.6", "ok": True, "command": cmd, "data": data}, ensure_ascii=False)) + + def fail(cmd, code, message): + print(json.dumps({"version": "2.6", "ok": False, "command": cmd, + "error": {"code": code, "message": message}}, ensure_ascii=False)) + sys.exit(1) + + def opt(args, name): + return args[args.index(name) + 1] if name in args else None + + def windows(s): + w = [{"id": "w-1", "app_name": "WINWORD", "title": SECRET + ".docx - Word", "accessible": True}] + if s.get("calc"): + w.append({"id": "w-200", "app_name": "CalculatorApp", "title": "계산기", "accessible": True}) + if s.get("browser"): + w.append({"id": "w-100", "app_name": "chrome", "title": s["browser"] + " - Google Chrome", + "accessible": True}) + return w + + def mcp(): + tools = [{"name": "desktop_list_windows"}, {"name": "desktop_snapshot"}, {"name": "desktop_click"}] + for line in sys.stdin: + req = json.loads(line) + if "id" not in req: + continue + if req["method"] == "initialize": + result = {"protocolVersion": "2025-06-18", "capabilities": {"tools": {}}} + elif req["method"] == "tools/list": + result = {"tools": tools} + elif req["method"] == "tools/call": + text = json.dumps({"ok": True, "data": windows(load())}, ensure_ascii=False) + result = {"content": [{"type": "text", "text": text}]} + else: + result = {} + print(json.dumps({"jsonrpc": "2.0", "id": req["id"], "result": result}, ensure_ascii=False), flush=True) + + def main(): + a = sys.argv[1:] + cmd = a[0] + s = load() + if cmd == "mcp": + return mcp() + if cmd == "version": + return ok(cmd, {"os": "windows", "version": "1.2.0"}) + if cmd == "status": + return ok(cmd, {"platform": "windows", "permissions": {"accessibility": {"state": "granted"}}, + "supported_surfaces": ["window", "menu"]}) + if cmd == "list-apps": + return ok(cmd, {"apps": [{"name": "Discord"}, {"name": "explorer"}, {"name": "WINWORD"}]}) + if cmd == "list-windows": + return ok(cmd, windows(s)) + if cmd == "launch": + if a[1] == "calc": + s.update(calc=True, display="0", entry="", acc=None) + save(s) + return ok(cmd, {"app": "calc", "pid": 1}) + fail(cmd, "APP_NOT_FOUND", "no such app") + if cmd == "close-app": + s["calc"] = False + save(s) + return ok(cmd, {"app": a[1]}) + if cmd == "find": + if opt(a, "--native-id"): + nid = opt(a, "--native-id") + if opt(a, "--app") != "CalculatorApp" or not s.get("calc"): + return ok(cmd, {"matches": [], "total_matches": 0}) + name = ("표시는 %s입니다" % s["display"]) if nid == "CalculatorResults" else nid + return ok(cmd, {"matches": [{"ref_id": "@s1:" + nid, "name": name, "role": "button"}]}) + if opt(a, "--role") == "textfield": + if opt(a, "--window-id") == "w-100" and s.get("browser"): + return ok(cmd, {"matches": [{"ref_id": "@s2:e1", "name": opt(a, "--name"), + "role": "textfield"}]}) + return ok(cmd, {"matches": [], "total_matches": 0}) + if cmd == "click": + nid = a[1].split(":", 1)[1] + if MODE != "dead_clicks": + if nid.startswith("num"): + s["entry"] += nid[3] + s["display"] = s["entry"] + elif nid == "plusButton": + s["acc"], s["entry"] = int(s["entry"] or 0), "" + elif nid == "equalButton": + s["display"] = str((s["acc"] or 0) + int(s["entry"] or 0)) + elif nid == "clearButton": + s.update(display="0", entry="", acc=None) + save(s) + return ok(cmd, {"action": "click"}) + if cmd == "set-value": + if MODE != "lie": + s["value"] = a[2] + save(s) + return ok(cmd, {"action": "set-value"}) + if cmd == "get": + return ok(cmd, {"property": "value", "ref": a[1], "value": s.get("value", "")}) + if cmd == "snapshot": + app = opt(a, "--app") + if app == "explorer": + fail(cmd, "AMBIGUOUS_TARGET", "windows: " + SECRET + ".docx") + return ok(cmd, {"app": app, "ref_count": 120, "complete": True, + "tree": {"role": "window", "name": SECRET + " DM"}}) + fail(cmd, "INVALID_ARGS", "unknown " + cmd) + + main() +''') + + +@pytest.fixture +def fake(tmp_path, monkeypatch): + script = tmp_path / "fake_agent_desktop.py" + script.write_text(FAKE_CLI, encoding="utf-8") + state = tmp_path / "state.json" + monkeypatch.setenv("FAKE_AD_STATE", str(state)) + monkeypatch.setenv("FAKE_AD_SECRET", SECRET) + monkeypatch.delenv("FAKE_AD_MODE", raising=False) + + class Fake: + cmd = [sys.executable, str(script)] + log = tmp_path / "desktop.log" + + def desk(self): + return desktop.Desk(self.cmd, self.log) + + def open_page(self, page: Path, title: str): + # Stands in for the browser: the page's window appears in list-windows. + s = json.loads(state.read_text(encoding="utf-8")) if state.exists() else {} + s["browser"] = title + state.write_text(json.dumps(s), encoding="utf-8") + + class Proc: + def terminate(self): + s2 = json.loads(state.read_text(encoding="utf-8")) + s2.pop("browser", None) + state.write_text(json.dumps(s2), encoding="utf-8") + return Proc() + + return Fake() + + +def test_calculator_round_trip_passes_when_the_display_shows_the_sum(fake): + result = desktop.check_calculator(fake.desk()) + assert result["ok"] is True + assert result["display_digits"] == desktop.CALC_EXPECTED + + +def test_calculator_fails_when_the_clicks_do_not_reach_the_app(fake, monkeypatch): + monkeypatch.setenv("FAKE_AD_MODE", "dead_clicks") + result = desktop.check_calculator(fake.desk()) + assert result["ok"] is False + + +def test_text_input_reads_back_what_was_set(fake, tmp_path): + result = desktop.check_text_input(fake.desk(), fake.open_page, tmp_path) + assert result["ok"] is True + assert result["settle_s"] is not None + + +def test_text_input_fails_when_the_value_does_not_change(fake, tmp_path, monkeypatch): + monkeypatch.setenv("FAKE_AD_MODE", "lie") + result = desktop.check_text_input(fake.desk(), fake.open_page, tmp_path) + assert result["ok"] is False + + +def test_warm_mcp_server_lists_tools_and_answers_repeated_calls(fake): + result = desktop.check_mcp(fake.cmd, fake.desk()) + assert result["tool_count"] == 3 + assert result["warm_call_s"]["n"] == desktop.REPEAT + assert result["cli_call_s"]["n"] == desktop.REPEAT + + +def test_results_never_store_other_window_titles_or_ui_text(fake, tmp_path): + out = tmp_path / "results" / "desktop.json" + status = desktop.measure(fake.cmd, tmp_path, out, fake.open_page) + text = out.read_text(encoding="utf-8") + assert status == "ok" + data = json.loads(text) + assert data["calculator"]["ok"] and data["text_input"]["ok"] + assert SECRET not in text # private window title, snapshot names and error messages + + +def _archive(tmp_path: Path) -> tuple[str, str]: + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w:gz") as tar: + payload = b"MZ fake exe" + info = tarfile.TarInfo("agent-desktop.exe") + info.size = len(payload) + tar.addfile(info, io.BytesIO(payload)) + path = tmp_path / "ad.tar.gz" + path.write_bytes(buf.getvalue()) + return path.as_uri(), hashlib.sha256(buf.getvalue()).hexdigest() + + +def test_install_unpacks_the_pinned_archive(tmp_path): + url, sha = _archive(tmp_path) + exe = desktop.install(tmp_path / "work", tmp_path / "log.txt", url=url, sha256=sha) + assert exe.exists() and exe.name == "agent-desktop.exe" + + +def test_install_rejects_an_archive_with_the_wrong_hash(tmp_path): + url, _ = _archive(tmp_path) + with pytest.raises(RuntimeError): + desktop.install(tmp_path / "work", tmp_path / "log.txt", url=url, sha256="0" * 64) + assert not list((tmp_path / "work").rglob("agent-desktop.exe")) + + +def test_kit_has_a_desktop_stage_and_a_one_click_runner(): + import m0 + keys = [s[0] for s in m0.STAGES] + assert "desktop" in keys + assert (Path(m0.KIT) / "m0lib" / m0.STAGES[keys.index("desktop")][3]).exists() + bat = (Path(m0.KIT) / "run_m0_desktop.bat").read_text(encoding="utf-8") + assert "-Only desktop" in bat + + +def test_an_already_open_calculator_is_left_alone(fake, tmp_path): + state = tmp_path / "state.json" + state.write_text(json.dumps({"calc": True, "display": "777", "entry": "777", "acc": None}), encoding="utf-8") + result = desktop.check_calculator(fake.desk()) + assert result["ok"] is False and result["skipped"] + s = json.loads(state.read_text(encoding="utf-8")) + assert s["calc"] is True and s["display"] == "777" # not pressed, not closed