For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: 让 Windows source Helper 通过 WGC 完成显示器截图、遮挡窗口截图、get_app_state 附图以及 state_image / screenshot 坐标闭环。
Architecture: 在现有 ax_native.node 中增加独立的 C++/WinRT + D3D11 + WIC 单帧捕获模块,通过三个成组 additive N-API 导出暴露 Promise ABI。TypeScript 以一个 Windows-only bridge 校验 capability/outcome;显示器截图进入现有 backend,窗口截图注入 createAxWinReadOnlySource,实际截图 bounds 贯穿 broker、state cache 和视觉坐标映射。
Tech Stack: TypeScript 5.9、Vitest 4、Node-API / node-addon-api、C++17、C++/WinRT、Windows Graphics Capture、D3D11、WIC、MSVC / node-gyp、Sharp、Windows named-pipe broker。
C:\Users\dev\zcode-cua 的本地 Windows source Helper 和 C:\Users\dev\z-code 的事实/计划文档;不启动或修改 SSH、WSL、Docker、remote workspace、手机 /remote。desktopCapturer 和私有二进制 fallback。isScreenCaptureSupported()、captureMonitorPngAsync(bounds)、captureWindowPngVerifiedAsync(windowId,pid,expectedCanonicalBundleId,expectedBounds?);三个导出必须成组存在。{ok:true,format:"png",data,width,height,bounds};failure 只返回固定 error code,不泄漏 HRESULT 文本、窗口标题、可执行路径、图像内容、token 或 pipe。Napi::AsyncWorker 中执行;C++/WinRT 异常在 worker 内捕获,不能越过 N-API。std::timed_mutex;admission 最多 250ms;第一帧最多 2000ms;最大单边 16384;最大总像素 33554432;最大 PNG 128 MiB。CreateFreeThreaded,只复制 ContentSize。IsWindow、PID、canonical exe、完整性级别、IsIconic 和 GetWindowRect;变化返回 target_changed,不能拼接 UIA tree 与不同观察时刻的图像。bounds 是已复核的桌面物理坐标范围;width/height 是 PNG 像素尺寸。二者不一致时显式缩放,禁止假设 1:1。state_id 和最新 visual-frame;不新增 screenshotId,不修改 30-tool surface、tier 或 annotation。supportsScreenCapture=true;旧/半实现/malformed addon fail closed。invalid_target / target_changed 使 app observation 失败并要求 reobserve;其余 transient window capture failure 保留 UIA tree,但 screenshot=null、screenshot_error 非空且不得建立 state_image target。finally 恢复/关闭所有资源;输出不得包含截图、marker、窗口标题、路径、token 或 pipe。pnpm test:unit:affected 的非 CUA baseline 仍要重跑并逐项记录,不能把非零结果称为通过。C:\Users\dev\zcode-cuasrc/native/windowsScreenCapture.ts — Windows 三导出成组 gate、outcome runtime validation、固定错误类型。src/native/types.ts — Windows screen capture outcome、success DTO 与 additive native methods。src/broker/server/nativeAxSource.ts — raw Helper addon 的 additive Windows ABI,以及 screenshot_bounds / screenshot_error broker-neutral字段。src/broker/server/nodeAutomationAdapter.ts — Windows monitor capture、capability/status 和 native error → broker error 映射。src/native/win.ts — async captureApp 附加 verified WGC window PNG,并区分 identity failure 与 transient failure。src/broker/server/platformAxSource.ts — 将 Windows bridge callback 注入 createAxWinReadOnlySource。src/broker/server/axReadOnly.ts — 透传 screenshot_bounds / screenshot_error。src/targeting/types.ts — state image 的独立 image_bounds。src/targeting/snapshot.ts — 摄取 screenshot_bounds。src/targeting/resolver.ts — state_image 使用 image_bounds ?? window.bounds。src/broker/server/electronNativeBackend.ts — screenshot reply 附加当前 selected-display bounds。src/backend/broker-client.ts — 保留 additive screenshot bounds。src/tools/observation.ts — visual-frame 使用 broker 返回的 selected-display bounds/origin,并展示 screenshot_error。src/native/screen_capture_win.h — WGC N-API entrypoint 和 shutdown seam。src/native/screen_capture_win.cc — WGC target validation、D3D11 single-frame、WIC PNG、worker/outcome。src/native/ax_win.cc — 引用 WGC module、状态、exports、terminal shutdown。binding.gyp — Windows source、C++ exceptions 和 D3D/WIC/WinRT libraries。test/windows-native-screen-capture-adapter.test.ts — bridge、adapter capability、outcome 和平台隔离。test/windows-app-state-screen-capture.test.ts — Windows source 附图、错误与 bounds。test/windows-capability-truthfulness.test.ts — 新能力真值与 broker screenshot。test/observation-tools.test.ts — selected-display origin。test/targeting-resolver.test.ts — screenshot_bounds → state image mapping。test/native/windows-wgc-screen-capture.test.ts — native source contract 和 compiled ABI。scripts/fixtures/windows-capture-smoke-window.ps1 — 只供 opt-in smoke 使用的受控 WPF target/occluder。scripts/windows-screen-capture-live-smoke.mjs — 显示器、遮挡 HWND、app state、state-image、最小化与 clean exit。test/windows-screen-capture-live-smoke.test.ts — 默认关闭和 preflight 证据。package.json — smoke:windows:screen-capture。docs/platforms.md — Windows WGC 当前能力和限制。dist/** only through pnpm build.C:\Users\dev\z-codedocs/cua/windows-source-development.md — source 构建、自动门禁、live smoke 与已知风险。screenshot
|
+--> backend selected display bounds
|
+--> WindowsScreenCaptureBridge.captureMonitor(bounds)
|
+--> native WGC AsyncWorker
+--> PNG + width/height + verified bounds
|
+--> broker reply {format,data,bounds}
|
+--> visual-frame
pointer = bounds width/height
origin = bounds x/y
get_app_state(include_screenshot=true)
|
+--> UIA snapshot {pid, exe, hwnd, window bounds}
|
+--> WindowsScreenCaptureBridge.captureWindow(...)
|
+--> pre-validate identity/bounds
+--> WGC first frame
+--> post-validate identity/bounds
|
+--> {screenshot,screenshot_bounds}
|
+--> state_id
|
+--> state_image:
image pixel -> screenshot_bounds -> screen point
native error app-state behavior screenshot behavior
invalid_target fail observation / reobserve explicit broker error
target_changed fail observation / reobserve explicit broker error
unsupported capability false not_authorized
unavailable screenshot=null + warning internal
busy / timeout screenshot=null + warning timeout
device_lost screenshot=null + warning retryable internal
too_large screenshot=null + warning invalid_request
capture/encode_failed screenshot=null + warning sanitized internal
malformed / rejection screenshot=null + warning sanitized internal
Files:
C:\Users\dev\zcode-cua\src\native\windowsScreenCapture.tsC:\Users\dev\zcode-cua\src\native\types.tsC:\Users\dev\zcode-cua\src\broker\server\nativeAxSource.tsC:\Users\dev\zcode-cua\test\windows-native-screen-capture-adapter.test.tsInterfaces:
AxWinScreenCaptureOutcome, WindowsScreenCaptureError, createWindowsScreenCaptureBridge(native).bridge.available is true only when all three exports are functions and isScreenCaptureSupported() === true.bridge.captureMonitor(bounds) and bridge.captureWindow(...) return validated success DTOs or throw fixed-code WindowsScreenCaptureError.
[ ] Step 1: Write failing bridge tests
Create fakes for complete, partial, malformed and rejecting addons. Pin these assertions:
expect(createWindowsScreenCaptureBridge(complete).available).toBe(true);
expect(
createWindowsScreenCaptureBridge({
...complete,
captureWindowPngVerifiedAsync: undefined,
}).available,
).toBe(false);
await expect(bridge.captureMonitor([-1920, 0, 1920, 1080])).resolves.toMatchObject({
format: "png",
width: 1920,
height: 1080,
bounds: [-1920, 0, 1920, 1080],
});
await expect(malformed.captureMonitor([0, 0, 1, 1])).rejects.toMatchObject({
name: "WindowsScreenCaptureError",
code: "capture_failed",
});
Run:
pnpm exec vitest run test/windows-native-screen-capture-adapter.test.ts
Expected: FAIL because windowsScreenCapture.ts and the three native methods do not exist.
Add to src/native/types.ts and mirror the methods on HelperNativeAddon:
export type AxWinScreenCaptureErrorCode =
| "unsupported"
| "unavailable"
| "busy"
| "timeout"
| "invalid_target"
| "target_changed"
| "too_large"
| "device_lost"
| "capture_failed"
| "encode_failed";
export type AxWinScreenCaptureOutcome =
| {
ok: true;
format: "png";
data: Uint8Array;
width: number;
height: number;
bounds: [number, number, number, number];
}
| { ok: false; error: AxWinScreenCaptureErrorCode };
isScreenCaptureSupported?(): boolean;
captureMonitorPngAsync?(
bounds: [number, number, number, number],
): Promise<AxWinScreenCaptureOutcome>;
captureWindowPngVerifiedAsync?(
windowId: number,
pid: number,
expectedCanonicalBundleId: string,
expectedBounds?: [number, number, number, number],
): Promise<AxWinScreenCaptureOutcome>;
createWindowsScreenCaptureBridge must:
const hasCompleteAbi =
typeof native.isScreenCaptureSupported === "function" &&
typeof native.captureMonitorPngAsync === "function" &&
typeof native.captureWindowPngVerifiedAsync === "function";
const available = hasCompleteAbi && safeSupported(native) === true;
Success validation must require PNG signature-bearing non-empty Uint8Array, positive safe integer dimensions, finite four-number bounds, and exact "png" format. Failure validation accepts only the ten fixed codes. Synchronous throw, Promise rejection and malformed outcome become WindowsScreenCaptureError("capture_failed"); no original message is retained.
Run:
pnpm exec vitest run test/windows-native-screen-capture-adapter.test.ts
pnpm typecheck
Expected: PASS; typecheck exit 0.
[ ] Step 6: Commit
git add -- src/native/types.ts src/native/windowsScreenCapture.ts src/broker/server/nativeAxSource.ts test/windows-native-screen-capture-adapter.test.ts
git commit -m "feat(windows): define native screen capture bridge"
Files:
C:\Users\dev\zcode-cua\src\broker\server\nodeAutomationAdapter.tsC:\Users\dev\zcode-cua\test\windows-native-screen-capture-adapter.test.tsC:\Users\dev\zcode-cua\test\windows-capability-truthfulness.test.tsC:\Users\dev\zcode-cua\test\broker\windowsSystemSurface.test.tsInterfaces:
createWindowsScreenCaptureBridge.Produces truthful ElectronAutomationAdapter.supportsScreenCapture, status and captureScreenPng(area).
[ ] Step 1: Add RED adapter tests
Assert:
expect(adapter.supportsScreenCapture).toBe(true);
expect(adapter.getScreenMediaAccessStatus()).toBe("granted");
await expect(
adapter.captureScreenPng({
x: -1920,
y: 0,
width: 1920,
height: 1080,
}),
).resolves.toEqual(PNG_BYTES);
expect(native.captureMonitorPngAsync).toHaveBeenCalledWith([-1920, 0, 1920, 1080]);
Also pin:
busy → BrokerError.code === "timeout";too_large → invalid_request;unsupported → not_authorized;internal;darwin/linux still use system.captureScreenPng.
[ ] Step 2: Run and observe RED
pnpm exec vitest run test/windows-native-screen-capture-adapter.test.ts test/windows-capability-truthfulness.test.ts test/broker/windowsSystemSurface.test.ts
Expected: new Windows capability and dispatch assertions fail.
Inside createNodeAutomationAdapter:
const windowsCapture =
platform === "win32"
? createWindowsScreenCaptureBridge(native as unknown as AxWinNativeAddon)
: null;
const supportsScreenCapture =
platform === "win32"
? windowsCapture?.available === true
: system.supportsScreenCapture !== false;
For Windows, getScreenMediaAccessStatus returns "granted" only when the bridge is available; otherwise native "denied" is preserved and all other cases are "unknown". captureScreenPng(area) chooses the supplied area or current primary display bounds, awaits captureMonitor, and returns only its data. Do not call WindowsNodeSystemSurface.captureScreenPng.
Add screenCaptureError(operation, code):
busy | timeout -> BrokerError("timeout")
too_large -> BrokerError("invalid_request")
unsupported -> BrokerError("not_authorized")
invalid_target |
target_changed -> BrokerError("element_unavailable")
unavailable |
device_lost |
capture_failed |
encode_failed -> BrokerError("internal")
Messages may name the operation and fixed code only.
[ ] Step 5: Run focused tests and typecheck
pnpm exec vitest run test/windows-native-screen-capture-adapter.test.ts test/windows-capability-truthfulness.test.ts test/broker/windowsSystemSurface.test.ts
pnpm typecheck
Expected: PASS; Windows SystemSurface remains false while complete native adapter is true.
[ ] Step 6: Commit
git add -- src/broker/server/nodeAutomationAdapter.ts test/windows-native-screen-capture-adapter.test.ts test/windows-capability-truthfulness.test.ts test/broker/windowsSystemSurface.test.ts
git commit -m "feat(windows): route monitor capture through native WGC"
Files:
C:\Users\dev\zcode-cua\src\native\win.tsC:\Users\dev\zcode-cua\src\broker\server\platformAxSource.tsC:\Users\dev\zcode-cua\src\broker\server\axReadOnly.tsC:\Users\dev\zcode-cua\src\broker\ax-types.tsC:\Users\dev\zcode-cua\src\targeting\types.tsC:\Users\dev\zcode-cua\src\targeting\snapshot.tsC:\Users\dev\zcode-cua\src\targeting\resolver.tsC:\Users\dev\zcode-cua\test\windows-app-state-screen-capture.test.tsC:\Users\dev\zcode-cua\test\targeting-resolver.test.tsInterfaces:
createAxWinReadOnlySource(native, {captureWindowPngVerified}).AxRawSnapshot.screenshot_bounds?: Bounds.AxRawSnapshot.screenshot_error?: string.AppState.image_bounds?: Bounds.
[ ] Step 1: Write RED source/state tests
Test a native UIA snapshot with HWND 42, pid 4321, exe path and bounds. Assert:
const result = await source.captureApp({ pid: 4321, window_id: 42 }, { includeScreenshot: true });
expect(captureWindowPngVerified).toHaveBeenCalledWith({
windowId: 42,
pid: 4321,
expectedCanonicalBundleId: "C:\\Apps\\Target.exe",
expectedBounds: [100, 80, 800, 600],
});
expect(result).toMatchObject({
screenshot: { format: "png" },
screenshot_bounds: [102, 82, 796, 596],
});
Also assert:
includeScreenshot:false never invokes WGC;invalid_target / target_changed rejects the whole observation;busy / timeout / device_lost / capture/encode failure returns UIA tree, screenshot:null, fixed screenshot_error;resolver maps state-image corners through image_bounds, not window.bounds.
[ ] Step 2: Run and verify RED
pnpm exec vitest run test/windows-app-state-screen-capture.test.ts test/targeting-resolver.test.ts
Expected: FAIL because the callback and image bounds fields do not exist.
Add:
interface AxRawSnapshot {
screenshot?: AxImagePayload | null;
screenshot_bounds?: [number, number, number, number];
screenshot_error?: string;
}
interface AppState {
image_bounds?: Bounds;
}
ingestCaptureAppResult validates screenshot_bounds with asBounds only when a nonblank decodable image exists. resolveStateImageCoordinate uses:
const [wx, wy, ww, wh] = state.image_bounds ?? state.window.bounds;
The source captures UIA first, then invokes the injected callback using the exact snapshot identity:
captureApp: async (appRef, options) => {
const snap = native.captureApp(pid, requestedWindowId);
const adapted = adaptSnapshot(snap);
if (options?.includeScreenshot === false) return adapted;
const captured = await options.captureWindowPngVerified?.({
windowId: snap.window.window_id,
pid: snap.app.pid,
expectedCanonicalBundleId: snap.app.bundle_id,
expectedBounds: snap.window.bounds,
});
return {
...adapted,
screenshot: {
format: "png",
data: Buffer.from(captured.data).toString("base64"),
},
screenshot_bounds: captured.bounds,
};
};
Catch only WindowsScreenCaptureError. Re-throw invalid_target and target_changed as elementUnavailable; return fixed screenshot_error for transient codes. Never catch UIA errors or arbitrary programmer errors.
selectPlatformAxSource creates a Windows bridge and passes captureWindow only when available. axReadOnly copies screenshot_bounds and screenshot_error into the broker response. mapRawCaptureAppResult adds a text block:
[screenshot_error] Windows window pixels were unavailable (<fixed-code>).
The accessibility tree is still valid; call get_app_state again before using state_image coordinates.
It must not echo arbitrary native messages.
[ ] Step 6: Run focused tests and typecheck
pnpm exec vitest run test/windows-app-state-screen-capture.test.ts test/targeting-resolver.test.ts test/observation-tools.test.ts test/native/capture-app-window-id.test.ts
pnpm typecheck
Expected: PASS.
[ ] Step 7: Commit
git add -- src/native/win.ts src/broker/server/platformAxSource.ts src/broker/server/axReadOnly.ts src/broker/ax-types.ts src/targeting/types.ts src/targeting/snapshot.ts src/targeting/resolver.ts src/tools/observation.ts test/windows-app-state-screen-capture.test.ts test/targeting-resolver.test.ts test/observation-tools.test.ts
git commit -m "feat(windows): attach verified window images to app state"
Files:
C:\Users\dev\zcode-cua\src\broker\server\electronNativeBackend.tsC:\Users\dev\zcode-cua\src\backend\broker-client.tsC:\Users\dev\zcode-cua\src\tools\observation.tsC:\Users\dev\zcode-cua\test\observation-tools.test.tsC:\Users\dev\zcode-cua\test\targeting-screenshot-space.test.tsC:\Users\dev\zcode-cua\test\windows-capability-truthfulness.test.tsInterfaces:
{format,data,bounds:[x,y,w,h]}.Old Helper replies without bounds keep the current primary-display fallback.
[ ] Step 1: Add RED negative-origin tests
Set display 2 to [-1920,0,1920,1080], call set_display({index:2}), then assert backend screenshot returns that bounds. Feed the reply to the MCP screenshot handler and assert:
expect(getDefaultSession().getVisualFrame()).toMatchObject({
pointer: { width: 1920, height: 1080 },
origin: { x: -1920, y: 0 },
});
expect(visualFrameToScreen(frame, frame.agent.width - 1, frame.agent.height - 1)).toEqual({
x: -1,
y: 1079,
});
[ ] Step 2: Run and observe RED
pnpm exec vitest run test/observation-tools.test.ts test/targeting-screenshot-space.test.ts test/windows-capability-truthfulness.test.ts
Expected: backend/client discard bounds and handler records origin (0,0).
Backend:
const selected = displaySelection.current();
const png = await adapter.captureScreenPng(selected.bounds);
return {
format: "png",
data: toBase64(png),
bounds: [selected.bounds.x, selected.bounds.y, selected.bounds.width, selected.bounds.height],
};
Client validates finite positive bounds when present and preserves them. Handler uses bounds width/height as pointer and x/y as origin; only absent/invalid legacy bounds call fetchMainDisplaySize and use (0,0).
[ ] Step 4: Run focused tests and typecheck
pnpm exec vitest run test/observation-tools.test.ts test/targeting-screenshot-space.test.ts test/windows-capability-truthfulness.test.ts
pnpm typecheck
Expected: PASS, including legacy no-bounds reply.
[ ] Step 5: Commit
git add -- src/broker/server/electronNativeBackend.ts src/backend/broker-client.ts src/tools/observation.ts test/observation-tools.test.ts test/targeting-screenshot-space.test.ts test/windows-capability-truthfulness.test.ts
git commit -m "fix(cua): preserve selected display screenshot origin"
Files:
C:\Users\dev\zcode-cua\src\native\screen_capture_win.hC:\Users\dev\zcode-cua\src\native\screen_capture_win.ccC:\Users\dev\zcode-cua\src\native\ax_win.ccC:\Users\dev\zcode-cua\binding.gypC:\Users\dev\zcode-cua\test\native\windows-wgc-screen-capture.test.tsC:\Users\dev\zcode-cua\test\native\windows-capability-truthfulness.test.tsInterfaces:
IsScreenCaptureSupportedNow, the three N-API callbacks, and BeginScreenCaptureShutdown.Native worker always resolves a structured outcome; invalid input never crashes or leaks raw errors.
[ ] Step 1: Write RED native source/ABI tests
Read the new source/header/binding as UTF-8 and pin:
expect(binding).toContain('"src/native/screen_capture_win.cc"');
expect(binding).toContain('"d3d11.lib"');
expect(binding).toContain('"windowscodecs.lib"');
expect(binding).toContain('"runtimeobject.lib"');
expect(source).toContain("IGraphicsCaptureItemInterop");
expect(source).toContain("CreateForMonitor");
expect(source).toContain("CreateForWindow");
expect(source).toContain("CreateFreeThreaded");
expect(source).toContain("D3D11_CPU_ACCESS_READ");
expect(source).toContain("GUID_ContainerFormatPng");
expect(source).toContain("std::timed_mutex");
expect(source).toContain("milliseconds(250)");
expect(source).toContain("milliseconds(2000)");
expect(source).not.toContain("BitBlt");
expect(source).not.toContain("PrintWindow");
Compiled checks require the three functions and verify invalid bounds/HWND resolve {ok:false} without throwing.
[ ] Step 2: Run source tests and observe RED
pnpm exec vitest run test/native/windows-wgc-screen-capture.test.ts test/native/windows-capability-truthfulness.test.ts
Expected: FAIL because the native module and exports do not exist.
Windows binding.gyp:
sources += src/native/screen_capture_win.cc
libraries += d3d11.lib, dxgi.lib, runtimeobject.lib, windowscodecs.lib, WindowsApp.lib
VCCLCompilerTool.ExceptionHandling = 1
Keep NAPI_DISABLE_CPP_EXCEPTIONS, /utf-8, C++17 and all existing libraries. /EHsc is required only so C++/WinRT exceptions can be caught inside the worker.
IsScreenCaptureSupportedNow must require:
default;LockApp.exe, LogonUI.exe or winlogon.exe;GraphicsCaptureSession::IsSupported();IGraphicsCaptureItemInterop.Monitor resolution enumerates displays and requires exact RECT equality. Window validation runs before and after capture and returns only:
struct VerifiedWindow {
HWND hwnd;
DWORD pid;
std::wstring executable;
RECT bounds;
};
It rejects self PID, elevated PID, invalid/minimized/zero-area window and expected identity/bounds mismatch.
Exact lifecycle:
CoInitializeEx(COINIT_MULTITHREADED)
try_lock_for(250ms)
D3D11CreateDevice(HARDWARE, BGRA)
-> retry D3D_DRIVER_TYPE_WARP
CreateDirect3D11DeviceFromDXGIDevice
CreateForMonitor / CreateForWindow
Direct3D11CaptureFramePool::CreateFreeThreaded(..., B8G8R8A8, 2, item.Size())
FrameArrived + Closed signals
StartCapture
wait_until(now + 2000ms)
TryGetNextFrame
copy ContentSize to staging D3D11_TEXTURE2D
Map(D3D11_MAP_READ)
WIC PNG encoder -> IStream/HGLOBAL -> bounded vector
Unmap + session.Close + pool.Close + release
post-validate target
CoUninitialize when owned
All cleanup uses RAII. Check the terminal shutdown flag before session creation and after frame receipt.
ScreenCaptureWorker owns copied primitives only; no N-API values are read in Execute. OnOK creates either:
{ ok: true, format: "png", data: Buffer, width, height, bounds }
or:
{ ok: false, error: "<fixed code>" }
ax_win.cc:
exports.Set("isScreenCaptureSupported",
Napi::Function::New(env, IsScreenCaptureSupported));
exports.Set("captureMonitorPngAsync",
Napi::Function::New(env, CaptureMonitorPngAsync));
exports.Set("captureWindowPngVerifiedAsync",
Napi::Function::New(env, CaptureWindowPngVerifiedAsync));
ScreenCaptureStatus returns granted only when IsScreenCaptureSupportedNow(); CancelPendingInputHolds also calls BeginScreenCaptureShutdown().
[ ] Step 7: Rebuild and run compiled tests
pnpm rebuild:native
pnpm exec vitest run test/native/windows-wgc-screen-capture.test.ts test/native/windows-capability-truthfulness.test.ts
Expected: node-gyp exit 0; compiled export and invalid-target tests PASS.
[ ] Step 8: Run all focused visual tests
pnpm exec vitest run test/windows-native-screen-capture-adapter.test.ts test/windows-app-state-screen-capture.test.ts test/windows-capability-truthfulness.test.ts test/observation-tools.test.ts test/targeting-resolver.test.ts test/targeting-screenshot-space.test.ts test/native/windows-wgc-screen-capture.test.ts test/native/windows-capability-truthfulness.test.ts
pnpm typecheck
Expected: PASS.
[ ] Step 9: Commit
git add -- binding.gyp src/native/screen_capture_win.h src/native/screen_capture_win.cc src/native/ax_win.cc test/native/windows-wgc-screen-capture.test.ts test/native/windows-capability-truthfulness.test.ts
git commit -m "feat(windows): implement WGC visual capture"
Files:
C:\Users\dev\zcode-cua\scripts\fixtures\windows-capture-smoke-window.ps1C:\Users\dev\zcode-cua\scripts\windows-screen-capture-live-smoke.mjsC:\Users\dev\zcode-cua\test\windows-screen-capture-live-smoke.test.tsC:\Users\dev\zcode-cua\package.jsonInterfaces:
ZCODE_CUA_WINDOWS_SCREEN_CAPTURE_LIVE=1.Smoke controls only its two fixture processes.
[ ] Step 1: Write RED guard tests
Spawn the smoke without opt-in and assert exit code 2, no Helper/fixture marker, and message naming only the opt-in variable. Add a test-only preflight override to simulate lockscreen and assert it exits before spawning anything.
[ ] Step 2: Run and observe RED
pnpm exec vitest run test/windows-screen-capture-live-smoke.test.ts
Expected: FAIL because the smoke does not exist.
The target mode renders a deterministic green/magenta checkerboard plus one safe button; occluder mode renders opaque blue. Both use caller-provided geometry and title-independent private handshake files. Do not read clipboard, user windows or user documents.
Before any spawn:
win32
AND opt-in == 1
AND dist/windows-helper.js exists
AND build/Release/ax_native.node exists
AND current input desktop == default
AND foreground pid exists
AND foreground exe not LockApp/LogonUI/winlogon
Use random temp paths and a random broker token. In finally, signal and terminate only the fixture/helper PIDs created by this run, remove private temp files, and verify the Helper PID is gone.
The smoke must automatically prove:
broker_info.capabilities.screen === true and screenshot === true;capture_app(include_screenshot=true) returns image/bounds;get_app_state 返回 state_id 后,left_click(space:"state_image") 的安全按钮点击只改变 fixture-owned state;Only booleans, dimensions, fixed result codes and process-exit facts may be printed.
[ ] Step 6: Add package command and run guard test
"smoke:windows:screen-capture": "node scripts/windows-screen-capture-live-smoke.mjs"
Run:
pnpm exec vitest run test/windows-screen-capture-live-smoke.test.ts
Expected: PASS; without opt-in no GUI process starts.
[ ] Step 7: Attempt live smoke
$env:ZCODE_CUA_WINDOWS_SCREEN_CAPTURE_LIVE='1'
pnpm smoke:windows:screen-capture
Remove-Item Env:ZCODE_CUA_WINDOWS_SCREEN_CAPTURE_LIVE
Expected on ordinary unlocked desktop: exit 0 and every fixed acceptance boolean true. On LockApp/noninteractive desktop: exit 2 before Helper/fixture startup; record as environment-blocked, not passed.
[ ] Step 8: Commit
git add -- package.json scripts/fixtures/windows-capture-smoke-window.ps1 scripts/windows-screen-capture-live-smoke.mjs test/windows-screen-capture-live-smoke.test.ts
git commit -m "test(windows): add WGC live acceptance"
Files:
C:\Users\dev\zcode-cua\docs\platforms.mdC:\Users\dev\z-code\docs\cua\windows-source-development.mdRegenerate: C:\Users\dev\zcode-cua\dist\**
[ ] Step 1: Update platform facts
Document implemented WGC monitor/window/app-state paths, default system border, SDR/HDR limitation, minimized fail-closed, native ABI, opt-in command and source-only status. Explicitly retain remote/mobile/packaging as out of scope.
[ ] Step 2: Build generated artifacts
pnpm build
Expected: exit 0; dist/windows-helper.js contains the new TypeScript path while native source remains in package files.
[ ] Step 3: Verify docs contain no stale “WGC unimplemented” claim
rg -n "WGC|screen capture|screenshot|截图|未实现|pending" docs README.md
Expected: remaining pending claims refer only to packaging/HDR/border or other explicit non-goals.
In zcode-cua:
git add -- docs/platforms.md dist
git commit -m "docs(windows): record WGC visual support"
In z-code:
git add -- docs/cua/windows-source-development.md
git commit -m "docs(cua): record Windows WGC source flow"
Files:
No planned source edits. Any failure follows superpowers:systematic-debugging; do not patch by guess.
[x] Step 1: Run zcode-cua focused verification
pnpm exec vitest run test/windows-native-screen-capture-adapter.test.ts test/windows-app-state-screen-capture.test.ts test/windows-capability-truthfulness.test.ts test/observation-tools.test.ts test/targeting-resolver.test.ts test/targeting-screenshot-space.test.ts test/native/windows-wgc-screen-capture.test.ts test/native/windows-capability-truthfulness.test.ts test/windows-screen-capture-live-smoke.test.ts
pnpm rebuild:native
pnpm build
pnpm typecheck
pnpm lint
Expected: every command exit 0.
[x] Step 2: Run zcode-cua full suite
pnpm test
Expected: exit 0; platform/live skips are explicit.
Use the existing source-helper environment and execute:
pnpm exec vitest run packages/services/test/cuaPermissionBroker.server.win32.test.ts packages/services/test/cuaPermissionBrokerNodeHelper.test.ts packages/services/test/cuaPermissionBroker.platformAxSource.test.ts packages/services/test/cuaPermissionBroker.electronBackend.test.ts
pnpm --filter @zcode/zcode-cua-plugin test
pnpm typecheck
pnpm lint
pnpm test:unit:affected
Expected: focused/plugin/typecheck/lint exit 0. Record test:unit:affected exact failures; only previously evidenced non-CUA baseline may remain.
On an ordinary unlocked desktop:
$env:ZCODE_CUA_WINDOWS_SCREEN_CAPTURE_LIVE='1'
$env:ZCODE_CUA_WINDOWS_POINTER_LIVE='1'
$env:ZCODE_CUA_WINDOWS_CLIPBOARD_LIVE='1'
pnpm smoke:windows:screen-capture
pnpm smoke:windows:pointer
pnpm smoke:windows:clipboard
Remove all three environment variables in finally. Expected: exit 0; clipboard restores original text; pointer and visual tests mutate only spawned fixtures; no Helper orphan.
For every broker capability/tool family, collect current evidence:
observation: list_apps, list_windows, get_app_state, screenshot, zoom,
list_displays, switch_display, cursor_position
pointer: click variants, move, scroll, drag, mouse down/up
keyboard: type, press, key down/up, hold
elements: press, focus, set_value, select_text, perform_action
system: clipboard read/write, open_application, access/readiness
Mark each as proved, contradicted, missing or only indirectly covered. Do not mark the goal complete while any required Windows local operation lacks source, automated test and ordinary-desktop runtime evidence.
If all requirements and live evidence pass, update the persistent goal to complete. If only the desktop is locked, leave the goal active and report the exact pending live acceptance without redefining implementation completion.
The Task 8 audit found that every public tool has source and automated coverage, but several local Windows operations still have only indirect ordinary-desktop evidence. Add one opt-in acceptance that exercises the official MCP handlers against a fixture-owned WPF window; reuse the dedicated visual, pointer and clipboard smokes as independent evidence instead of controlling user apps or files.
Files:
C:\Users\dev\zcode-cua\scripts\fixtures\windows-tool-surface-smoke-window.ps1C:\Users\dev\zcode-cua\scripts\windows-tool-surface-live-smoke.mjsC:\Users\dev\zcode-cua\test\windows-tool-surface-live-smoke.test.tsC:\Users\dev\zcode-cua\package.jsonC:\Users\dev\zcode-cua\docs\platforms.mdC:\Users\dev\z-code\docs\cua\windows-source-development.mdState and event chain:
opt-in parent
|
+--> fixture-owned WPF window
| +--> UIA elements: text box + action button
| +--> pointer/key event counters
| `--> private JSON state + close signal
|
+--> source windows-helper.js
| `--> named pipe -> Windows native UIA / SendInput / WGC
|
`--> official buildServer + in-memory MCP client
|
+--> observation/runtime tool results
+--> element tokens from one get_app_state
`--> pointer/keyboard/semantic actions
|
`--> fixture event/state change -> bounded verification
The smoke must keep the desktop-local boundary: no SSH, WSL, Docker, remote
workspace, phone /remote, user documents, or uncontrolled process cleanup.
It may move the pointer only inside its own window, must restore the original
cursor and clipboard text, release any held input in finally, close only
children it spawned, and print only booleans/counts/fixed status codes.
Lock:
ZCODE_CUA_WINDOWS_TOOL_SURFACE_LIVE=1 before any child spawn;2 before any child spawn;clipboard and cursor restoration are mandatory success fields.
[x] Step 2: Implement the WPF fixture
Expose deterministic UIA names and bounds for:
The fixture must use PMv2 DPI awareness before creating its first HWND and write physical PID/HWND/bounds in its private handshake.
Call every previously indirect public operation through buildServer:
list_apps, PID-form open_application, list_windows,
get_app_state, screenshot, zoom, list_displays, switch_display,
cursor_position;scroll, left_click_drag,
mouse_move, left_mouse_down, left_mouse_up;type, set_value, select_text, key, hold_key,
perform_action;request_access, bounded wait, stop_computer_control.The dedicated clipboard smoke remains authoritative for
read_clipboard/write_clipboard, and the dedicated visual smoke remains the
authoritative state_image/WGC/minimized-window proof. The new smoke records
those companion commands as required evidence and fails if its own official
MCP invocation set plus the two companion tool names do not equal the canonical
30-tool manifest.
[x] Step 4: Run live acceptance and companion smokes
$env:ZCODE_CUA_WINDOWS_TOOL_SURFACE_LIVE='1'
pnpm smoke:windows:tool-surface
Remove-Item Env:ZCODE_CUA_WINDOWS_TOOL_SURFACE_LIVE
Then rerun screen capture, pointer and clipboard live smokes with their existing opt-ins. Expected: every boolean true; clipboard/cursor restored; no Helper or fixture orphan.
Record one row per canonical tool with source, automated and ordinary-desktop runtime evidence. Do not replace explicit missing evidence with group-level claims. Commit the acceptance and documentation before rerunning Task 8's full repository gates.
Completion evidence (2026-07-29):
0; focused Windows
verification was 16 files / 158 tests, and the full suite was 122 passed /
6 skipped files with 2105 passed / 67 skipped / 18 todo tests;state_image event input,
minimized-window fail-closed, cursor restoration and clean child exit;0;
clipboard text and cursor were restored, and no owned Helper/fixture remained;0;pnpm test:unit:affected remained a documented non-CUA repository baseline:
13 failed files / 20 failed tests, 940 passed files / 8132 passed tests.
None of the failing files were CUA source or CUA tests.Both PowerShell fixtures must retain a UTF-8 BOM. Windows PowerShell 5.1 otherwise decodes UTF-8-without-BOM Chinese comments through the legacy ANSI code page; with LF input, a multibyte tail can swallow the following newline and turn the next statement into part of the comment. Dispatcher callbacks also use explicit script-scope HWND/window/timer state because StrictMode event delegates do not provide a reliable local-variable closure boundary.