👾 Open Computer Use – Open-Source Alternative to Codex Computer Use
Swift accessibilityai-agentai-agentsclaude-codecodexcodex-computer-usecomputer-usecomputer-use-agentcross-platformcuadesktop-automationgemini-cligui-automationmacosmcpmodel-context-protocolopen-computer-useopen-computer-use-mcpopenai-codexopencode
fix(windows): reject degenerate screenshots
Leo83a521e54610
diff --git a/apps/OpenComputerUseWindows/main.go b/apps/OpenComputerUseWindows/main.goindex 5ebaf99..fb51a73 100644--- a/apps/OpenComputerUseWindows/main.go+++ b/apps/OpenComputerUseWindows/main.go@@ -1,11 +1,14 @@package mainimport (+ "bytes""context"_ "embed"+ "encoding/base64""encoding/json""errors""fmt"+ "image/png""io""math""os"@@ -21,10 +24,15 @@ var version = "0.3.6"var clickMethodValues = []string{"auto", "accessibility", "app_post", "sky_click", "global"}+const (+ minimumScreenshotDimension = 64+ minimumScreenshotArea = 20_000+)+//go:embed runtime.ps1var windowsRuntimeScript string-const serverInstructions = "Computer Use tools let you interact with Windows apps by performing UI actions.\n\nBegin by calling `get_app_state` every turn you want to use Computer Use to get the latest state before acting. The available tools are list_apps, get_app_state, click, perform_secondary_action, scroll, drag, type_text, press_key, and set_value.\n\nPrefer element-targeted interactions over coordinate clicks when an index for the targeted element is available. Windows actions use UI Automation patterns first and fall back to window messages when an app does not expose the needed pattern. The Windows runtime does not auto-launch apps, perform SetFocus, or use UIA text fallback by default, so background-capable actions do not intentionally steal the user's foreground focus."+const serverInstructions = "Computer Use tools let you interact with Windows apps by performing UI actions.\n\nBegin by calling `get_app_state` every turn you want to use Computer Use to get the latest state before acting. The available tools are list_apps, get_app_state, click, perform_secondary_action, scroll, drag, type_text, press_key, and set_value.\n\nPrefer element-targeted interactions over coordinate clicks when an index for the targeted element is available. Screenshot-coordinate actions require get_app_state to return a usable image; hidden, minimized, cloaked, off-screen, or degenerate windows may return only the accessibility tree. Windows actions use UI Automation patterns first and fall back to window messages when an app does not expose the needed pattern. The Windows runtime does not auto-launch apps, perform SetFocus, or use UIA text fallback by default, so background-capable actions do not intentionally steal the user's foreground focus."type toolDefinition struct {Name string `json:"name"`@@ -109,6 +117,9 @@ func (s *appSnapshot) renderedText() string {fmt.Sprintf("Window: %q, App: %s.", title, s.App.Name),}lines = append(lines, s.TreeLines...)+ if !s.hasUsableScreenshot() {+ lines = append(lines, "", "Screenshot unavailable. Restore a visible, non-minimized, on-screen window before using screenshot-coordinate actions; element_index actions may still work.")+ }if strings.TrimSpace(s.SelectedText) != "" {lines = append(lines, "", fmt.Sprintf("Selected text: [%s]", s.SelectedText))} else if strings.TrimSpace(s.FocusedSummary) != "" {@@ -118,19 +129,70 @@ func (s *appSnapshot) renderedText() string {}func (s *appSnapshot) result() toolCallResult {+ s.sanitizeScreenshot()result := toolCallResult{Content: []contentItem{{Type: "text", Text: s.renderedText()}},}- if s != nil && s.ScreenshotPNGBase64 != "" {+ if screenshot := s.usableScreenshotPNGBase64(); screenshot != "" {result.Content = append(result.Content, contentItem{Type: "image",- Data: s.ScreenshotPNGBase64,+ Data: screenshot,MimeType: "image/png",})}return result}+func (s *appSnapshot) usableScreenshotPNGBase64() string {+ if !s.hasUsableScreenshot() {+ return ""+ }+ return s.ScreenshotPNGBase64+}++func (s *appSnapshot) hasUsableScreenshot() bool {+ return s != nil && isUsableScreenshotFrame(s.WindowBounds) && s.ScreenshotPNGBase64 != ""+}++func (s *appSnapshot) sanitizeScreenshot() {+ if s == nil {+ return+ }+ if !isUsableScreenshotFrame(s.WindowBounds) {+ s.ScreenshotPNGBase64 = ""+ return+ }+ s.ScreenshotPNGBase64 = validateScreenshotPNGBase64(s.ScreenshotPNGBase64)+}++func isUsableScreenshotFrame(bounds *frame) bool {+ if bounds == nil || math.IsNaN(bounds.Width) || math.IsNaN(bounds.Height) || math.IsInf(bounds.Width, 0) || math.IsInf(bounds.Height, 0) {+ return false+ }+ return bounds.Width >= minimumScreenshotDimension &&+ bounds.Height >= minimumScreenshotDimension &&+ bounds.Width*bounds.Height >= minimumScreenshotArea+}++func validateScreenshotPNGBase64(encoded string) string {+ encoded = strings.TrimSpace(encoded)+ if encoded == "" {+ return ""+ }+ data, err := base64.StdEncoding.DecodeString(encoded)+ if err != nil {+ return ""+ }+ configuration, err := png.DecodeConfig(bytes.NewReader(data))+ if err != nil || configuration.Width < minimumScreenshotDimension || configuration.Height < minimumScreenshotDimension {+ return ""+ }+ if int64(configuration.Width)*int64(configuration.Height) < minimumScreenshotArea {+ return ""+ }+ return encoded+}+type psRequest struct {Tool string `json:"tool"`App string `json:"app,omitempty"`@@ -302,6 +364,9 @@ func (s *service) click(app, elementIndex string, x, y *float64, clickCount int,if snapshot == nil {return textResult("No app state is available for "+app+". Run get_app_state before action tools.", true)}+ if (elementIndex == "" || clickMethod == "app_post") && !snapshot.hasUsableScreenshot() {+ return screenshotCoordinatesUnavailableResult(app)+ }request := psRequest{Tool: "click",App: app,@@ -388,9 +453,16 @@ func (s *service) drag(app string, fromX, fromY, toX, toY *float64) toolCallResuif snapshot == nil {return textResult("No app state is available for "+app+". Run get_app_state before action tools.", true)}+ if !snapshot.hasUsableScreenshot() {+ return screenshotCoordinatesUnavailableResult(app)+ }return s.actionResult(app, psRequest{Tool: "drag", App: app, FromX: fromX, FromY: fromY, ToX: toX, ToY: toY, WindowBounds: snapshot.WindowBounds})}+func screenshotCoordinatesUnavailableResult(app string) toolCallResult {+ return textResult("No usable screenshot is available for "+app+". Restore a visible, non-minimized, on-screen window and run get_app_state again before using screenshot coordinates.", true)+}+func (s *service) typeText(app, text string) toolCallResult {if app == "" {return textResult("Missing required argument: app", true)@@ -458,6 +530,7 @@ func (s *service) refreshSnapshot(app string, request psRequest) (*appSnapshot,if response.Snapshot == nil {return nil, textResult("Windows runtime did not return an app snapshot.", true)}+ response.Snapshot.sanitizeScreenshot()s.rememberSnapshot(app, response.Snapshot)return response.Snapshot, toolCallResult{}}diff --git a/apps/OpenComputerUseWindows/main_test.go b/apps/OpenComputerUseWindows/main_test.goindex c70def2..8bc1700 100644--- a/apps/OpenComputerUseWindows/main_test.go+++ b/apps/OpenComputerUseWindows/main_test.go@@ -2,7 +2,10 @@ package mainimport ("bytes"+ "encoding/base64""encoding/json"+ "image"+ "image/png""strings""testing")@@ -297,6 +300,100 @@ func TestWindowsRuntimeTreeBudgetDefaultsMatchMacOS(t *testing.T) {}}+func TestWindowsScreenshotValidationRejectsDegenerateImages(t *testing.T) {+ for name, encoded := range map[string]string{+ "one pixel": pngBase64(t, 1, 1),+ "narrow": pngBase64(t, minimumScreenshotDimension-1, 400),+ "small area": pngBase64(t, 100, 100),+ "invalid base64": "not base64",+ "invalid PNG data": base64.StdEncoding.EncodeToString([]byte("not a png")),+ } {+ t.Run(name, func(t *testing.T) {+ if got := validateScreenshotPNGBase64(encoded); got != "" {+ t.Fatalf("validateScreenshotPNGBase64() = %q, want empty", got)+ }+ })+ }++ valid := pngBase64(t, 100, 200)+ if got := validateScreenshotPNGBase64(valid); got != valid {+ t.Fatal("a screenshot at the minimum area should remain available")+ }+}++func TestWindowsSnapshotOmitsUnusableScreenshot(t *testing.T) {+ snapshot := &appSnapshot{+ App: appDescriptor{Name: "fixture", BundleIdentifier: "fixture", PID: 42},+ WindowBounds: &frame{Width: 1, Height: 1},+ ScreenshotPNGBase64: pngBase64(t, 1, 1),+ }+ result := snapshot.result()+ if result.IsError || len(result.Content) != 1 || result.Content[0].Type != "text" {+ t.Fatalf("degenerate screenshot result = %#v", result)+ }+ if snapshot.ScreenshotPNGBase64 != "" {+ t.Fatal("degenerate screenshot should be removed from the remembered snapshot")+ }+ if !strings.Contains(result.Content[0].Text, "Screenshot unavailable") {+ t.Fatalf("missing screenshot guidance: %q", result.Content[0].Text)+ }++ snapshot.WindowBounds = &frame{Width: 100, Height: 200}+ snapshot.ScreenshotPNGBase64 = pngBase64(t, 100, 200)+ result = snapshot.result()+ if result.IsError || len(result.Content) != 2 || result.Content[1].Type != "image" {+ t.Fatalf("valid screenshot result = %#v", result)+ }+}++func TestWindowsCoordinateActionsRequireUsableScreenshot(t *testing.T) {+ svc := newService()+ svc.snapshots["fixture"] = &appSnapshot{+ App: appDescriptor{Name: "fixture", PID: 42},+ WindowBounds: &frame{Width: 1, Height: 1},+ Elements: []elementRecord{{Index: 0}},+ }+ x, y := 1.0, 1.0+ clickResult := svc.click("fixture", "", &x, &y, 1, "left", "auto")+ if !clickResult.IsError || !strings.Contains(clickResult.Content[0].Text, "No usable screenshot is available") {+ t.Fatalf("coordinate click result = %#v", clickResult)+ }+ appPostResult := svc.click("fixture", "0", nil, nil, 1, "left", "app_post")+ if !appPostResult.IsError || !strings.Contains(appPostResult.Content[0].Text, "No usable screenshot is available") {+ t.Fatalf("app_post click result = %#v", appPostResult)+ }+ dragResult := svc.drag("fixture", &x, &y, &x, &y)+ if !dragResult.IsError || !strings.Contains(dragResult.Content[0].Text, "No usable screenshot is available") {+ t.Fatalf("coordinate drag result = %#v", dragResult)+ }+}++func TestWindowsRuntimeFiltersUncapturableWindows(t *testing.T) {+ for _, snippet := range []string{+ "$MinimumScreenshotDimension = 64",+ "$MinimumScreenshotArea = 20000",+ "[OCUWin32]::IsWindowVisible($hwnd)",+ "[OCUWin32]::IsIconic($hwnd)",+ "[OCUWin32]::DwmGetWindowAttribute($hwnd, 14",+ "Test-FrameIntersectsVirtualScreen $frame",+ "if (-not (Test-CapturableFrame $bounds))",+ "Get-CapturableWindowFrame ([IntPtr]$process.MainWindowHandle)",+ } {+ if !strings.Contains(windowsRuntimeScript, snippet) {+ t.Fatalf("Windows runtime missing screenshot guard %q", snippet)+ }+ }+}++func pngBase64(t *testing.T, width, height int) string {+ t.Helper()+ var buffer bytes.Buffer+ if err := png.Encode(&buffer, image.NewRGBA(image.Rect(0, 0, width, height))); err != nil {+ t.Fatal(err)+ }+ return base64.StdEncoding.EncodeToString(buffer.Bytes())+}+func findToolDefinition(t *testing.T, name string) toolDefinition {t.Helper()for _, tool := range toolDefinitions() {diff --git a/apps/OpenComputerUseWindows/runtime.ps1 b/apps/OpenComputerUseWindows/runtime.ps1index 720e9d5..3cf4df0 100644--- a/apps/OpenComputerUseWindows/runtime.ps1+++ b/apps/OpenComputerUseWindows/runtime.ps1@@ -7,6 +7,8 @@ $ErrorActionPreference = "Stop"$DefaultTextLimit = 500$AccessibilityTreeMaxNodeCount = 1200$AccessibilityTreeMaxDepth = 64+$MinimumScreenshotDimension = 64+$MinimumScreenshotArea = 20000# Set output encoding to UTF-8 to properly handle non-ASCII characters$OutputEncoding = [System.Text.Encoding]::UTF8@@ -38,6 +40,18 @@ public static class OCUWin32 {[DllImport("user32.dll")]public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);+ [DllImport("user32.dll")]+ public static extern bool IsWindowVisible(IntPtr hWnd);++ [DllImport("user32.dll")]+ public static extern bool IsIconic(IntPtr hWnd);++ [DllImport("user32.dll")]+ public static extern int GetSystemMetrics(int index);++ [DllImport("dwmapi.dll")]+ public static extern int DwmGetWindowAttribute(IntPtr hWnd, int attribute, out int value, int valueSize);+[DllImport("user32.dll")]public static extern bool ScreenToClient(IntPtr hWnd, ref POINT point);@@ -107,6 +121,71 @@ function Get-WindowRectFrame([IntPtr]$hwnd) {return $null}+function Get-VirtualScreenFrame {+ $x = [OCUWin32]::GetSystemMetrics(76)+ $y = [OCUWin32]::GetSystemMetrics(77)+ $width = [OCUWin32]::GetSystemMetrics(78)+ $height = [OCUWin32]::GetSystemMetrics(79)+ if ($width -le 0 -or $height -le 0) {+ return $null+ }+ return New-Frame $x $y $width $height+}++function Test-FrameIntersectsVirtualScreen($frame) {+ if ($null -eq $frame) {+ return $false+ }+ $virtualScreen = Get-VirtualScreenFrame+ if ($null -eq $virtualScreen) {+ return $false+ }+ return (+ $frame.x -lt ($virtualScreen.x + $virtualScreen.width) -and+ ($frame.x + $frame.width) -gt $virtualScreen.x -and+ $frame.y -lt ($virtualScreen.y + $virtualScreen.height) -and+ ($frame.y + $frame.height) -gt $virtualScreen.y+ )+}++function Test-CapturableFrame($frame) {+ if ($null -eq $frame) {+ return $false+ }+ if ($frame.width -lt $MinimumScreenshotDimension -or $frame.height -lt $MinimumScreenshotDimension) {+ return $false+ }+ if (($frame.width * $frame.height) -lt $MinimumScreenshotArea) {+ return $false+ }+ return Test-FrameIntersectsVirtualScreen $frame+}++function Get-CapturableWindowFrame([IntPtr]$hwnd) {+ if ($hwnd -eq [IntPtr]::Zero) {+ return $null+ }+ if (-not [OCUWin32]::IsWindowVisible($hwnd) -or [OCUWin32]::IsIconic($hwnd)) {+ return $null+ }+ try {+ [int]$cloaked = 0+ $result = [OCUWin32]::DwmGetWindowAttribute($hwnd, 14, [ref]$cloaked, 4)+ if ($result -ne 0 -or $cloaked -ne 0) {+ return $null+ }+ } catch {+ # An unknown DWM visibility state is not a trustworthy screenshot+ # source. Keep the accessibility tree, but fail closed for the image.+ return $null+ }+ $frame = Get-WindowRectFrame $hwnd+ if (-not (Test-CapturableFrame $frame)) {+ return $null+ }+ return $frame+}+function Get-ElementFrame($element, $windowBounds) {try {$rect = $element.Current.BoundingRectangle@@ -123,8 +202,9 @@ function Get-ElementFrame($element, $windowBounds) {}function Get-ScreenPoint($localFrame, $windowBounds) {- if ($null -eq $localFrame -or $null -eq $windowBounds) {- return $null+ Assert-UsableWindowBounds $windowBounds+ if ($null -eq $localFrame) {+ throw "No usable element frame is available for screenshot-coordinate input."}[pscustomobject]@{x = [int][math]::Round($windowBounds.x + $localFrame.x + ($localFrame.width / 2))@@ -132,6 +212,12 @@ function Get-ScreenPoint($localFrame, $windowBounds) {}}+function Assert-UsableWindowBounds($windowBounds) {+ if (-not (Test-CapturableFrame $windowBounds)) {+ throw "No usable screenshot coordinates are available. Restore a visible, non-minimized, on-screen window and run get_app_state again."+ }+}+function Send-MouseClick([IntPtr]$hwnd, [int]$screenX, [int]$screenY, [string]$button, [int]$count) {$point = New-Object OCUWin32+POINT$point.X = $screenX@@ -343,20 +429,7 @@ function Get-MainElement($process) {function Get-WindowBounds($process, $element) {$hwnd = [IntPtr]$process.MainWindowHandle- if ($hwnd -ne [IntPtr]::Zero) {- $fromWin32 = Get-WindowRectFrame $hwnd- if ($null -ne $fromWin32) {- return $fromWin32- }- }- try {- $rect = $element.Current.BoundingRectangle- if (-not $rect.IsEmpty -and $rect.Width -gt 0 -and $rect.Height -gt 0) {- return New-Frame $rect.X $rect.Y $rect.Width $rect.Height- }- } catch {- }- return $null+ return Get-CapturableWindowFrame $hwnd}function Get-PatternNames($element) {@@ -563,22 +636,26 @@ function Render-Tree($element, $windowBounds, $TextLimit = $script:DefaultTextLi}function Capture-WindowPngBase64($bounds) {- if ($null -eq $bounds -or $bounds.width -le 0 -or $bounds.height -le 0) {+ if (-not (Test-CapturableFrame $bounds)) {return $null}+ $bitmap = $null+ $graphics = $null+ $stream = $nulltry {$bitmap = New-Object System.Drawing.Bitmap ([int][math]::Round($bounds.width)), ([int][math]::Round($bounds.height))$graphics = [System.Drawing.Graphics]::FromImage($bitmap)$graphics.CopyFromScreen([int][math]::Round($bounds.x), [int][math]::Round($bounds.y), 0, 0, $bitmap.Size)$stream = New-Object System.IO.MemoryStream$bitmap.Save($stream, [System.Drawing.Imaging.ImageFormat]::Png)- $graphics.Dispose()- $bitmap.Dispose()$bytes = $stream.ToArray()- $stream.Dispose()return [Convert]::ToBase64String($bytes)} catch {return $null+ } finally {+ if ($null -ne $graphics) { $graphics.Dispose() }+ if ($null -ne $bitmap) { $bitmap.Dispose() }+ if ($null -ne $stream) { $stream.Dispose() }}}@@ -639,6 +716,9 @@ function Build-Snapshot([string]$query, $TextLimit = $script:DefaultTextLimit, [function List-Apps {$lines = New-Object System.Collections.Generic.List[string]foreach ($process in (Get-Process | Where-Object { $_.MainWindowHandle -ne 0 } | Sort-Object ProcessName, Id)) {+ if ($null -eq (Get-CapturableWindowFrame ([IntPtr]$process.MainWindowHandle))) {+ continue+ }$title = $process.MainWindowTitleif ([string]::IsNullOrWhiteSpace($title)) {$title = "untitled"@@ -923,6 +1003,7 @@ try {throw "click_method 'accessibility' could not click the requested element"}} elseif ($clickMethod -eq "app_post") {+ Assert-UsableWindowBounds $windowBoundsif ($null -ne $operation.element -and $null -ne $operation.element.frame) {$point = Get-ScreenPoint $operation.element.frame $windowBounds} else {@@ -942,6 +1023,7 @@ try {$handled = Invoke-PreferredClick $element}if (-not $handled) {+ Assert-UsableWindowBounds $windowBoundsif ($null -ne $operation.element -and $null -ne $operation.element.frame) {$point = Get-ScreenPoint $operation.element.frame $windowBounds} else {@@ -966,11 +1048,13 @@ try {$handled = Invoke-Scroll $element $operation.direction ([double]$operation.pages)}if (-not $handled) {+ Assert-UsableWindowBounds $windowBounds$point = Get-ScreenPoint $operation.element.frame $windowBoundsSend-Scroll $hwnd $point.x $point.y $operation.direction ([double]$operation.pages)}}"drag" {+ Assert-UsableWindowBounds $windowBoundsSend-Drag $hwnd ([int][math]::Round($windowBounds.x + [double]$operation.from_x)) ([int][math]::Round($windowBounds.y + [double]$operation.from_y)) ([int][math]::Round($windowBounds.x + [double]$operation.to_x)) ([int][math]::Round($windowBounds.y + [double]$operation.to_y))}"type_text" {diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex f6bc3da..7042651 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -117,6 +117,7 @@- 构建入口是 `scripts/build-open-computer-use-windows.sh --arch arm64|amd64`,默认输出到 `dist/windows/<arch>/open-computer-use.exe`;npm release package 会把两个 Windows artifact 内置到已有 root/alias packages,Node launcher 按 `process.platform/process.arch` 自动选择。- Go runtime 通过 `go:embed` 带上 `runtime.ps1`,执行 tool call 时临时落盘并调用 Windows PowerShell。PowerShell bridge 使用 `System.Windows.Automation` 做 app/window/element discovery、tree rendering、UIA pattern action、ValuePattern set value 和 ScrollPattern scroll;当目标 app 不暴露对应 pattern 时,fallback 到 `PostMessage` / `SendMessage` 形式的 Win32 window message。- Windows runtime 默认只连接已经运行的 app,不会在 `get_app_state` 找不到进程时自动 `Start-Process`,也不会默认允许 `SetFocus` secondary action;这两条前台抢占路径分别需要 `OPEN_COMPUTER_USE_WINDOWS_ALLOW_APP_LAUNCH=1` 和 `OPEN_COMPUTER_USE_WINDOWS_ALLOW_FOCUS_ACTIONS=1` 显式打开。`type_text` 默认优先对可写文本控件的 child HWND 发送 `EM_SETSEL` / `EM_REPLACESEL`,不再默认走可能触发前台激活的 UIA `ValuePattern.SetValue` fallback;需要旧行为时必须设置 `OPEN_COMPUTER_USE_WINDOWS_ALLOW_UIA_TEXT_FALLBACK=1`。UIA pattern 和 Win32 message fallback 本身仍是 best-effort:很多控件可以在后台响应,但 Windows 没有一套对所有 GUI toolkit 都等价于 macOS AX 的后台键鼠输入模型。+- Windows screenshot 会先检查主窗口可见、未最小化、未被 DWM cloaked、与 virtual screen 相交,并要求窗口宽高至少 64 像素且面积至少 20,000 像素;`list_apps` 也只列出通过这组可捕获性检查的窗口。PowerShell bridge 通过后,Go 层还会解码 PNG header 并用同一尺寸门槛复核。任一检查失败时 snapshot 仍可返回 UI Automation tree,但省略 MCP `image` block;coordinate click / drag 会明确失败,element-targeted action 仍可尝试。实现不会为退化窗口放大、补边或生成占位截图。- 这 9 个 tool 的协议面与 macOS 主线保持一致:`list_apps`、`get_app_state`、`click`、`perform_secondary_action`、`scroll`、`drag`、`type_text`、`press_key`、`set_value`。其中 element-targeted action 会优先复用上一轮 `get_app_state` 的 runtime id / automation metadata,coordinate action 使用 screenshot/window-relative 坐标。- Windows `click_method=accessibility` 映射到 UI Automation pattern,`app_post` 映射到 HWND `PostMessage`;macOS-only 的 `sky_click` 和没有实现的 `global` 都会在 snapshot lookup 前明确返回 unsupported。`auto` 仍保持 UIA 优先、window message fallback 的现有行为。- Windows UI Automation 需要运行在已登录用户的桌面 session 里。通过 SSH 作为脱离桌面的后台进程运行时,PowerShell 可以启动并返回 JSON,但系统可能不给它暴露顶层窗口;这种情况下 `list_apps` 会是空,`get_app_state` 可能返回 `appNotFound(...)`。diff --git a/docs/QUALITY_SCORE.md b/docs/QUALITY_SCORE.mdindex f5b3a47..f0548fc 100644--- a/docs/QUALITY_SCORE.md+++ b/docs/QUALITY_SCORE.md@@ -12,7 +12,7 @@| 区域 | 评分 | 原因 | 下一步 || --- | --- | --- | --- || 产品面 | B | 已经有 Swift 本地 `computer-use` MCP server、默认 app 模式权限引导,以及一轮按官方 surface / result 行为收敛过的 9 个 tools。 | 继续收敛复杂 AX 场景下的 state rendering 细节、权限 UI 和更清晰的用户错误提示。 |-| Windows runtime | C | 已新增独立 Go `.exe`,通过 Windows UI Automation + Win32 window message 暴露同样 9 个 tools、MCP server 和 `call --calls`;默认不再自动启动 app、执行 `SetFocus`,或让 `type_text` 走可能抢前台的 UIA text fallback,并已接入 npm bundled artifact 分发,但仍是功能性第一版。 | 补交互式桌面 smoke、Windows fixture、installer/signing,以及更原生的 Go UIA 实现或更稳定的 bridge。 |+| Windows runtime | C | 已新增独立 Go `.exe`,通过 Windows UI Automation + Win32 window message 暴露同样 9 个 tools、MCP server 和 `call --calls`;默认不再自动启动 app、执行 `SetFocus`,或让 `type_text` 走可能抢前台的 UIA text fallback;截图会过滤隐藏、最小化、cloaked、离屏和退化窗口,并在 Go 层复核 PNG,但整体仍是功能性第一版。 | 把当前实机 screenshot 边界用例收敛成仓库内 Windows fixture / 交互式 smoke,再补 installer/signing,以及更原生的 Go UIA 实现或更稳定的 bridge。 || Linux runtime | C | 已新增独立 Go binary,通过 Python GI / AT-SPI2 暴露同样 9 个 tools、MCP server 和 `call --calls`;Ubuntu GNOME VM 已跑通 `list_apps`、MCP tools list 和 Text Editor 8-tool sequence,并已接入 npm bundled artifact 分发,但截图在 GNOME Wayland 下仍只能 best-effort,coordinate input 也不是通用后台模型。 | 补 Linux fixture、可重复 smoke runner、portal/compositor screenshot 路径,以及更原生的 Go D-Bus/libatspi bridge。 || 架构文档 | B | 顶层结构、fixture bridge、app 模式和验证路径已经落文档。 | 后续补 release artifact、code signing / notarization 和 host 集成方式。 || 测试 | B | `swift test` + smoke suite 已覆盖 9 个 tools 的回归,并新增了针对“前台焦点是否被抢占”的手工对比样本沉淀。 | 增加更多普通 app 的录制回归,减少只依赖 fixture 和一次性手工检查。 |diff --git a/docs/RELIABILITY.md b/docs/RELIABILITY.mdindex 689cf56..5cd8610 100644--- a/docs/RELIABILITY.md+++ b/docs/RELIABILITY.md@@ -8,6 +8,7 @@- 端到端 smoke:`./scripts/run-tool-smoke-tests.sh`- macOS SkyLight 实机回归:`OPEN_COMPUTER_USE_RUN_SKY_CLICK_LIVE_TEST=1 swift test --filter SkyClickLiveTests`- Linux runtime:`(cd apps/OpenComputerUseLinux && go test ./...)`、`./scripts/build-open-computer-use-linux.sh --arch arm64`+- Windows runtime:`(cd apps/OpenComputerUseWindows && go test ./...)`、`./scripts/build-open-computer-use-windows.sh --arch amd64`;截图相关变更还要在 Windows 交互桌面验证正常窗口有 image、1x1/minimized/cloaked 窗口无 image。- 本地诊断:- `open-computer-use doctor`- `open-computer-use snapshot <app>`@@ -32,7 +33,8 @@4. 如果只有 `sky_click` 失败,先重新执行 `get_app_state`,确认窗口仍为 on-screen、未隐藏/最小化且没有切换 Space;错误里出现 `missing SkyLight symbols` 时不要改用隐式 fallback,应按当前 macOS 版本重新验证私有 SPI。被遮挡的 Chromium 页面仍无效果时,再用受控页面区分 renderer 策略变化与坐标/window-local 映射问题。5. 如果只想验证仓库基线,直接跑 fixture + smoke,不要先在复杂第三方 app 上排查。6. 排查 Linux runtime 时,先确认目标命令是否由桌面用户运行,再用 `open-computer-use call list_apps` 和 `open-computer-use snapshot <app>` 区分 session/env 问题与 AT-SPI tree/action 问题。如果是 Codex MCP,重新执行 `open-computer-use install-codex-mcp` 后重启 Codex,确认配置仍是 `open-computer-use mcp`。-7. 排查 `ocu js` / `ocu repl` 时先执行 `ocu capabilities --json`。缺少 adapter、kernel 或 native artifact 时重新安装 npm 包;若 shell 报 `node: command not found`,说明 npm launcher 本身尚未启动,需要先安装 Node 或等待未来 native bootstrap 方案。+7. Windows snapshot 返回 accessibility tree 但没有 image 时,先确认窗口可见、未最小化、未 cloaked、位于 virtual screen 内且不是退化小窗口;无 image 时不要调用 coordinate click / drag,优先使用 `element_index`。+8. 排查 `ocu js` / `ocu repl` 时先执行 `ocu capabilities --json`。缺少 adapter、kernel 或 native artifact 时重新安装 npm 包;若 shell 报 `node: command not found`,说明 npm launcher 本身尚未启动,需要先安装 Node 或等待未来 native bootstrap 方案。## 后续补强方向diff --git a/docs/SECURITY.md b/docs/SECURITY.mdindex 0a20dc4..b98c84b 100644--- a/docs/SECURITY.md+++ b/docs/SECURITY.md@@ -12,6 +12,7 @@## 数据处理- 普通 app 的 screenshot 默认只在内存中编码成 PNG,并通过 MCP `image` content block 直接回传;默认不长期持久化。+- Windows runtime 对隐藏、最小化、DWM cloaked、离屏或退化小窗口 fail closed:保留可读的 UI Automation tree,但不返回 image block,也不允许在缺少有效截图时执行 coordinate click / drag;不会用放大、补边或占位图伪造可用截图。- Linux runtime 的 screenshot 是 best-effort;如果 GNOME Wayland 返回黑图,bridge 会省略 image block,避免把无效截图误当成真实画面。- fixture app 的合成状态只写到本地临时 JSON 文件,目的是支撑 deterministic smoke test;当前写入走原子替换,减少测试期间的读写竞争。- 当前仓库不引入第三方服务,也不上传截图、AX tree 或输入内容。diff --git a/docs/exec-plans/completed/20261009-windows-degenerate-screenshot-guard.md b/docs/exec-plans/completed/20261009-windows-degenerate-screenshot-guard.mdnew file mode 100644index 0000000..a4c7e48--- /dev/null+++ b/docs/exec-plans/completed/20261009-windows-degenerate-screenshot-guard.md@@ -0,0 +1,49 @@+# Windows 退化截图保护++## 目标++Windows runtime 在目标窗口不可稳定截图时只返回文本与 UI Automation 树,绝不向 MCP host 返回 1x1、极小、最小化、cloaked 或离屏窗口生成的无效 PNG,同时阻止失去截图坐标基础的 coordinate action。++## 范围++- 包含:Windows 窗口可捕获性检查、PNG 像素级兜底、coordinate action fail-closed、单元测试、Windows 交互桌面回归、架构/可靠性/安全/skill/release/history 文档。+- 不包含:替换 `CopyFromScreen`、支持被其他窗口遮挡时的离屏合成、修改 macOS 或 Linux 截图实现、版本发布。++## 背景++- 相关文档:`docs/ARCHITECTURE.md`、`docs/RELIABILITY.md`、`docs/SECURITY.md`、`docs/QUALITY_SCORE.md`。+- 相关代码路径:`apps/OpenComputerUseWindows/runtime.ps1`、`apps/OpenComputerUseWindows/main.go`、`apps/OpenComputerUseWindows/main_test.go`。+- 已知约束:Windows runtime 必须运行在已登录交互桌面;极端情况下允许没有 screenshot,但不能伪造、放大或补边一个不可操作的小图。++## 风险++- 风险:过滤过严会让合法的小工具窗口不再返回截图。+- 缓解方式:以 macOS 已使用的 20,000 像素候选面积为语义基线,同时要求宽高至少 64 像素;仍保留 accessibility tree 和 element-targeted action。+- 风险:PowerShell bridge 回归后仍可能返回异常图片。+- 缓解方式:Go 层再次解码 PNG header 并应用同一尺寸门槛,coordinate action 也以通过校验的截图为前提。++## 里程碑++1. 收敛窗口与截图有效性规则。+2. 实现 PowerShell 与 Go 双层保护并补测试。+3. 在 Windows 交互桌面验证正常窗口与 1x1/minimized/cloaked 边界。+4. 完成文档、history 与 PR 交付准备。++## 验证方式++- 命令:`(cd apps/OpenComputerUseWindows && go test ./...)`、`./scripts/build-open-computer-use-windows.sh --arch amd64`、`make check-docs`、`git diff --check`。+- 手工检查:Windows DevBox 交互桌面运行正常窗口 snapshot,并用受控 1x1 fixture 断言结果不含 image block。+- 观测检查:最小化、cloaked、离屏或过小窗口不再进入 `list_apps` 的可截图集合;缺截图时 coordinate click/drag 明确失败。++## 进度记录++- [x] 在 Windows DevBox 用原实现复现 1x1 PNG。+- [x] 完成双层有效性保护和回归测试。+- [x] 完成 Windows 实机复验。+- [x] 完成文档、history 与 PR 交付准备。++## 决策记录++- 2026-10-09:无效截图采用 fail-closed,不做放大、补边或占位图;截图缺失时仍返回 accessibility tree。+- 2026-10-09:窗口截图最低要求统一为宽高各 64 像素且面积至少 20,000 像素,与 macOS 正常窗口候选的面积基线对齐。+- 2026-10-09:实机验证覆盖正常、1x1、minimized、DWM-cloaked 和无图 coordinate click,固定当前 fail-closed 边界。diff --git a/docs/histories/2026-10/20261009-2103-windows-degenerate-screenshot-guard.md b/docs/histories/2026-10/20261009-2103-windows-degenerate-screenshot-guard.mdnew file mode 100644index 0000000..3c106e2--- /dev/null+++ b/docs/histories/2026-10/20261009-2103-windows-degenerate-screenshot-guard.md@@ -0,0 +1,40 @@+## [2026-10-09 21:03] | Task: 拒绝 Windows 退化截图++### 🤖 Execution Context+* **Agent ID**: `/root`+* **Base Model**: `GPT-5`+* **Runtime**: `TRAE CLI / macOS arm64 + Windows 10 interactive DevBox`++### 📥 User Query+> 修复 Windows Computer Use 偶发返回 1x1 screenshot、导致部分 LLM 拒绝图片的问题;极端情况下可以没有截图,但不能伪造 1x1,并统一优化窗口有效性判断后提交 PR。++### 🛠 Changes Overview+**Scope:** Windows Go runtime、PowerShell UI Automation bridge、测试与截图行为文档。++**Key Actions:**+- **Window capture gate**: 截图前要求主窗口可见、未最小化、未被 DWM cloaked、与 virtual screen 相交,且宽高至少 64 像素、面积至少 20,000 像素;`list_apps` 使用同一规则过滤退化窗口。+- **PNG defense in depth**: Go 层在构造 MCP result 前再次解码 PNG header,并结合 window bounds 应用同一尺寸门槛;无效图片会从 snapshot cache 和 image content 中移除,不做放大、补边或占位图。+- **Fail-closed coordinates**: 缺少有效截图时仍返回 accessibility tree 和说明,但 coordinate click / drag 明确失败;element-targeted UI Automation action 仍可尝试,发生 coordinate fallback 时 PowerShell 也会再次检查 bounds。+- **Resource safety**: Windows bitmap、graphics 和 memory stream 在成功或异常路径都通过 `finally` 释放。+- **Regression coverage**: 新增 PNG 尺寸/格式、snapshot image omission、coordinate action 和 PowerShell guard 回归测试,并在 Windows 交互桌面验证真实 binary。++### 🧠 Design Intent (Why)+截图坐标只有在画面真实、可见且尺寸足以操作时才有意义。对 1x1 或无效窗口生成一个格式合法的 PNG 会把底层窗口状态问题推迟成上游模型错误,也可能让坐标动作落到错误位置。因此实现选择保留可用的语义树、明确省略图片并阻止 coordinate action,而不是伪造视觉状态。++### 📁 Files Modified+- `apps/OpenComputerUseWindows/main.go`+- `apps/OpenComputerUseWindows/main_test.go`+- `apps/OpenComputerUseWindows/runtime.ps1`+- `docs/ARCHITECTURE.md`+- `docs/QUALITY_SCORE.md`+- `docs/RELIABILITY.md`+- `docs/SECURITY.md`+- `skills/open-computer-use/references/troubleshooting.md`+- `docs/releases/feature-release-notes.md`+- `docs/exec-plans/completed/20261009-windows-degenerate-screenshot-guard.md`++### ✅ Validation+- `(cd apps/OpenComputerUseWindows && go test ./...)` 通过。+- `./scripts/build-open-computer-use-windows.sh --arch amd64` 通过。+- Windows 10 build 19045 交互桌面实测当前 binary SHA-256 与本地构建一致:正常 320x240 fixture 返回 320x240 PNG;1x1 和 minimized fixture 均保留文本/树但无 image,并包含 `Screenshot unavailable` 说明。+- 同一实测中,`list_apps` 保留正常 fixture,过滤 1x1、minimized 和 DWM-cloaked `TextInputHost`;1x1 snapshot 后 coordinate click 返回 `No usable screenshot is available`。diff --git a/docs/releases/feature-release-notes.md b/docs/releases/feature-release-notes.mdindex aadbdde..4a24607 100644--- a/docs/releases/feature-release-notes.md+++ b/docs/releases/feature-release-notes.md@@ -1,5 +1,11 @@# 功能发布记录+## 2026-10++| 日期 | 功能域 | 用户价值 | 变更摘要 |+| --- | --- | --- | --- |+| 2026-10-09 | Windows 截图可靠性 | 极小、最小化、隐藏、cloaked 或离屏窗口不会再向模型返回不可用的 PNG;极端情况下仍可读取 accessibility tree,并明确限制依赖截图坐标的操作。 | Windows bridge 在截图前校验窗口状态、virtual screen 交集和最小尺寸,Go 层再次解码 PNG header 复核;无有效截图时省略 image block,coordinate click / drag fail closed,不做放大、补边或占位图。 |+## 2026-09| 日期 | 功能域 | 用户价值 | 变更摘要 |diff --git a/skills/open-computer-use/references/troubleshooting.md b/skills/open-computer-use/references/troubleshooting.mdindex 7853816..b1aac84 100644--- a/skills/open-computer-use/references/troubleshooting.md+++ b/skills/open-computer-use/references/troubleshooting.md@@ -47,6 +47,8 @@ Common causes:Ask the user to bring the target app/window into a visible state when automation cannot do so safely.+On Windows, `get_app_state` may intentionally return the accessibility tree without an image when the main window is hidden, minimized, DWM-cloaked, off-screen, or too small to be a trustworthy Computer Use screenshot. Do not synthesize, upscale, or pad an image. Use `element_index` actions when the returned tree is sufficient; screenshot-coordinate click and drag require a later state result that contains a usable image.+## Truncated TextSnapshot text is limited to 500 characters by default. If a visible chat message, email body, document paragraph, or form value ends with `...`, do not assume the page itself is missing content.