Skip to content

feat(windows): capture selected windows through owned helpers - #4143

Open
N0zoM1z0 wants to merge 5 commits into
mainfrom
feat/windows-window-capture-2183
Open

N0zoM1z0 wants to merge 5 commits into
mainfrom
feat/windows-window-capture-2183

Conversation

@N0zoM1z0

@N0zoM1z0 N0zoM1z0 commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes #2183. Continues the implementation from #2199 by @SoGeRiEn, with real Windows validation and corrections to rendering, resource ownership and delivery.

Problem and expected behavior

The original raw SendMessageTimeout(WM_PRINT) cross-process HDC was invalid in the target: the fixture observed GetObjectType=0, FillRect=0, Win32 error 6. It returned a valid all-black PNG and DPI-scaled dimensions. The new workflow must return pixels from the exact selected PE application's client area, preserve identity and fail within a bounded helper lifetime.

Change and scope

  • Use PrintWindow(PW_CLIENTONLY) inside one owned Windows Job Object helper, with a 5 s deadline, 64 MiB JavaScript heap and 256 MiB job commit limit. Reuse process supervision and retained cleanup owners.
  • Preserve exact PID/HWND, process start identity and executable file identity/SHA-256 checks. Keep DPI changes thread-local. Use copied ANSI caption length and preserve the fixed-stream capacity reason when WIC wraps it.
  • Return a retained metadata summary by default over MCP; explicit image views reuse that frame. CLI and detail: complete return full Evidence. Captures remain live; stable native admission is cached, frames are not reused for a new capture.
  • Bound source pixels, PNG bytes and JSON/base64 expansion before allocation. Add a real Windows GUI acceptance lane to CI.

Maintainer scope decision: @N0zoM1z0, the human owner and maintainer, explicitly selected this narrow feature from #2183 and authorized implementation, testing, PR and merge. This PR records that decision and the declared target-paint effects. No desktop selection, window enumeration, input, target launch or elevation is exposed.

Contract and boundary impact

  • Owner: Windows provider adapter and shared CLI/MCP Evidence contracts. New tool: capture_windows_window_screenshot; retained image view: windows-window / screenshot.
  • Windows x64 only, PE application target. macOS native UI contracts remain separate. Packaged worker bundles its schema dependency to reduce cold helper startup.
  • PrintWindow can execute existing target paint code and cause target UI/filesystem/network effects; effect metadata and limitations report this. Only the owned helper is terminated on timeout/cancellation. Failed cleanup keeps its owner for retry.
  • Generated catalogs and skills are regenerated from authored inputs; no binaries, screenshots, profiles, credentials or provider registration information are committed.

Evidence and regression coverage

Executed on a real Windows x64 interactive desktop, including a non-elevated, non-administrator token:

  • Source-owned GUI: independently compare decoded pixels with expected blue/green frames; verify physical source dimensions, fresh repaint, immutable retained frames, CLI/MCP contracts, ANSI captions, wrong PID, destroyed HWND, identical bytes in a different file, source/PNG limits, smaller-image retry, written-RPC cancellation/recovery and zero runtime leftovers.
  • Windows Character Map: exact owned PID/HWND, non-empty PNG, matching observed client dimensions, both public transports and unchanged executable digest. Observed MCP calls took about 0.75–1.28 s; cold one-shot CLI calls took 13.7–19.9 s including CLI/process startup.
  • Noisy 512-pixel frame: 793,362 PNG bytes; default MCP summary 8,421 bytes versus 2,123,115 bytes for explicit image delivery (about 252× less wire data).

Coverage limits: the new post-render bounds check refuses resizing, but the resize race was not deterministically forced locally. These runs do not prove complete rendering for GPU/protected/minimized/elevated windows or physical-display contents. ANSI capture passed; this host did not reproduce the documented DBCS length overestimate. Cancellation verifies a request written to the transport, not an observed blocked paint handler. Fresh Windows npm installs timed out during setup; the local packaged-runtime runs used unchanged packed CLI/MCP/helper/native leaves with reused dependencies whose versions match the lockfile. They are not fresh-install verification. CI separately exercises the complete built checkout and native artifact.

Observed noisy-frame MCP summary excerpt (other Evidence fields omitted):

{"normalized_result":{"kind":"summary","summary":{"screenshot":{"width":512,"height":512,"bytes":793362}}}}

Reading its parent_evidence_id with inspect_analysis_view and view: {"kind":"windows-window","facet":"screenshot"} returns the retained PNG without another capture.

Review follow-up and CI

bb9df948c sends a bounded UTF-8 JSON request over supervised stdin, passes the provider's selected environment, requires native protocol-stdin support, and refuses dimensions changed during rendering. Regressions cover a request larger than the Windows command-line limit, real input delivery, blocked-reader timeout, early-close cleanup and the complete provider environment path. The final packed runtime/native artifact passed the non-admin Windows matrix again.

First CI run: Windows GUI/package and all other selected lanes passed. Source tests failed because this PR omitted the new tool from the destructive-effects audit's expected list; the Portable tests aggregate reported that same failure. The list is corrected and its six checks pass locally. The corrected 62a20fff1 CI run passed every selected lane. Current-head CI is rerunning after the additional worker-admission fix below.

62a20fff1 removes the duplicate PNG-header interpretation and uses readPngHeaderDimensions. Both malformed IHDR-length and high-bit chunk-type cases were accepted before the fix and rejected afterward; 40 focused parser/provider/delivery checks pass.

dcccb4fca keeps full filesystem/process admission in the parent and validates only the artifact/capture facet inside the supervised worker. A real Windows TEMP/TMP-is-a-file case failed before this change and passes afterward; the new case is in the Windows CI verifier. The complete non-admin GUI/CLI/MCP/Character Map matrix passed with the new packed runtime. One earlier Character Map CLI attempt failed before exit diagnostics were retained; an unchanged-artifact retry with added diagnostics passed. Its cause remains unknown and is not classified as an infrastructure failure or a fixed product bug.

283292edd preserves failed readiness even when retryable, and reports session-close cleanup under combined selected-window resources. Both regressions failed before the change; 54 focused provider/loader/helper/lazy-client checks pass afterward. Capability declarations remain snapshots: a fresh declaration reports availability only after actual admission succeeds.

Validation performed

  • npm run check:fast — passed on the updated main base.
  • npm run test:local -- eight relevant source files — 127 passed initially; 53 focused follow-up checks passed (overlapping existing cases).
  • npm run test:focused -- CLI/MCP/runtime bundle boundaries — 5 passed; follow-up stdin/MCP checks passed 20 tests (18 owned-command, 2 MCP).
  • Maximum duplicated MCP response including escaped title/path metadata — passed.
  • npm run build:windows-native and npm run verify:windows-native:artifact — passed.
  • npm run docs:check — passed, including 5 README consistency tests.
  • npm run verify:test-discovery — 1,355 files discovered exactly once.
  • npm run knip, changed-file formatting and git diff --check — passed.
  • Real CLI/MCP GUI acceptance described above — passed against the final packed runtime/native artifact; the Windows CI lane also exercises the complete built checkout.

Compatibility, safety, and release

Additive capability; no migration. Output limits: 4,194,304 source pixels, maximum dimension 4,096 (default 2,048), retained PNG 3 MiB. Incomplete painting remains an explicit limitation. Screenshots and titles can contain application data and are retained through existing Evidence/session semantics. Local measurements use bounded CPU affinity and helper memory controls.

Author readiness

Human owner: @N0zoM1z0

The owner explicitly authorized recording these declarations on their behalf for this work.

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

Follow up #2199 and #2183. Replace invalid cross-process WM_PRINT DC delivery with PrintWindow in one owned, deadline- and memory-bounded helper. Return metadata summaries by default through MCP with explicit retained image reads.

Verified actual pixels through CLI and MCP on Windows x64, including a non-elevated desktop, live redraws, PNG capacity refusal and retry, and target identity rejection. Final expanded acceptance and CI results are recorded in the pull request.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T15:47:08.900310Z 283292e New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 61b6408bb7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@greptile-apps

greptile-apps Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[High impact] Adds Windows native window capture through new addon code.

Fix session-level readiness recovery before merging so a temporary native check failure does not permanently disable captures.

Findings

  1. P1 Captures stay disabled after recovery ▶
Fix with agent prompt
### Issue 1
src/windows/NativeWindowsUiProviderMetadata.ts:26
If the first native check fails temporarily, `nativeWindowsUiCapabilities` now returns `available: false`, and composition saves that result in `LazyAnalysisProvider`. Every later capture is rejected by `prepareSessionExecution` before the loader can retry. Fixing temporary-directory access or reopening the target does not refresh the saved result, so captures remain disabled for the session.

Keep admission fail-closed, but refresh retryable readiness before rejecting later calls. The new test calls the factory again; the session does not.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds selected-window screenshots for Windows PE applications through an owned, bounded helper.

  • Windows PE callers can capture a fresh PNG from one selected application window.
  • CLI and MCP callers can request a selected-window capture and read its retained image.
  • Each capture runs in a supervised helper with bounded time and memory.

The three earlier unnumbered threads are addressed: native capture refuses changed bounds, the helper receives the selected environment, and requests travel through stdin rather than arguments. None requires a numbered previous-finding entry.

Review used source inspection; no runtime tests were executed. Checking for a superseding PR was blocked because GitHub authentication was unavailable.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Create session] --> B[Check native capture readiness]
  B -->|Success| C[Save available capability]
  B -->|Retryable failure| D[Save unavailable capability]
  C --> E[Capture request]
  E --> F[Owned helper checks identity and captures PNG]
  F --> G[Retain frame and return summary]
  D --> H[Later capture request]
  H --> I[Execution gate rejects request]
  I -. Retry loader is never reached .-> D
Loading

Reviews (5) · Last reviewed commit: "fix(windows): preserve unresolved readin..." · Reviewed by Greptile

Comment thread native/windows/src/window_capture.cc Resolved
Send bounded UTF-8 requests through supervised stdin rather than expanded Windows command lines. Carry the selected provider environment to the helper and reject changed client dimensions after rendering.

Update the effects audit and test real command input delivery, blocked readers, early close, long request encoding and provider environment propagation. Real Windows non-admin CLI/MCP and Character Map validation passed for the stdin transport.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bb9df948cc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Reject malformed IHDR lengths and high-bit chunk names instead of interpreting them through lossy ASCII decoding. Reproduced both false accepts before the change; focused parser, capture and delivery checks pass after sharing the existing byte-level header owner.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 62a20fff19

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Keep filesystem and owned-process admission in the parent. The supervised worker verifies artifact identity and the in-memory capture facet without probing its selected temporary directory.

Reproduced failure with TEMP and TMP pointing to a source-owned file before the fix. The updated packed runtime passes that real Windows non-admin case plus the full CLI/MCP and Character Map matrix. One earlier Character Map CLI failure lacked exit diagnostics; unchanged-artifact retry passed, with the unexplained attempt retained in verification notes.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: dcccb4fca7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/windows/NativeWindowsUiProvider.ts Resolved
Do not report a retryable failed capture admission as available. A fresh capability declaration must observe actual admission success. Report combined window resources when closing a session, preserving helper and executable cleanup observations without assigning the wrong owner.

Both regressions fail before the change. Focused provider, loader, helper and lazy-client checks pass after the fixes.
): readonly CapabilityDescriptor[] => {
const loaded =
platform === "win32" && architecture === "x64" ? load() : undefined;
const captureReady = loaded?.available === true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Captures stay disabled after recovery

If the first native check fails temporarily, nativeWindowsUiCapabilities now returns available: false, and composition saves that result in LazyAnalysisProvider. Every later capture is rejected by prepareSessionExecution before the loader can retry. Fixing temporary-directory access or reopening the target does not refresh the saved result, so captures remain disabled for the session.

Keep admission fail-closed, but refresh retryable readiness before rejecting later calls. The new test calls the factory again; the session does not.

Knowledge Base Used: Native runtime and bridges

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/windows/NativeWindowsUiProviderMetadata.ts
Line: 26

Comment:
**Captures stay disabled after recovery**

If the first native check fails temporarily, `nativeWindowsUiCapabilities` now returns `available: false`, and composition saves that result in `LazyAnalysisProvider`. Every later capture is rejected by `prepareSessionExecution` before the loader can retry. Fixing temporary-directory access or reopening the target does not refresh the saved result, so captures remain disabled for the session.

Keep admission fail-closed, but refresh retryable readiness before rejecting later calls. The new test calls the factory again; the session does not.

**Knowledge Base Used:** [Native runtime and bridges](https://app.greptile.com/pre/-/custom-context/knowledge-base/morluto/rea/-/docs/native-runtime-and-bridges.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 283292edda

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

},
{
identity: NATIVE_WINDOWS_UI_PROVIDER_IDENTITY,
capabilities: nativeWindowsUiCapabilities(platform),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Re-probe retryable capture readiness before execution

If the initial native inspection fails transiently—for example while the temporary directory is briefly unavailable—this stores an unavailable descriptor for the lifetime of the CLI/MCP composition. prepareSessionExecution rejects unavailable descriptors before loading the provider, so systemWindowsWindowCaptureAuthority() is never queried again and its explicit retryable-cache path cannot recover after the condition clears. Refresh this descriptor or defer retryable admission so a later request can observe current readiness.

AGENTS.md reference: AGENTS.md:L46-L48

Useful? React with 👍 / 👎.

@baron baron left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed pinned head 283292eddac84ea5d4a044d44bac42df96ac4a4d; holding approval.

This is not just static inspection: PrintWindow invokes the selected target's paint handler, with possible target UI/filesystem/network effects. Killing the owned helper does not establish cancellation of target-side paint work. The PR correctly declares those effects, but its scope section records a claimed maintainer decision without linking the actual decision covering this final workflow. Linked #2183 and #2199 could not be retrieved through REST/GraphQL during this review (their comment endpoints remain readable); the accessible issue comments did not establish that decision. Please provide the traceable maintainer issue/design decision covering the final PrintWindow workflow, including that target/helper cancellation distinction, before integration. I have not treated CI or an implementation claim as authority approval.

The existing retryable readiness finding also remains valid at this head: composition freezes an unavailable capability in LazyAnalysisProvider, while prepareSessionExecution rejects it before the loader can retry. Reopening the target does not reconstruct that provider declaration. Keep fail-closed admission but refresh readiness at its owner; calling the capability factory again only in a test does not exercise session recovery. No duplicate inline finding added.

All 41 emitted current-head checks are successful, including the Windows capability/package lane. That does not resolve either hold. Stopped further implementation-level investigation at this material authority/verification gate. No target/provider execution, installation, builds, or local tests were performed; the reported real Windows matrix and blocked-paint cancellation coverage were not independently verified.

@morluto

morluto commented Nov 24, 2026

Copy link
Copy Markdown
Owner

@N0zoM1z0 thanks for the PR — there are 2 open review threads here:

Could you address or reply to these? Once they're resolved and CI is green we can take another look.
cc @gensokyo-dev @dandgabr

@morluto

morluto commented Nov 24, 2026

Copy link
Copy Markdown
Owner

@N0zoM1z0 also, this branch has merge conflicts with main — please resolve those along with the open threads.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: runtime Process capture and runtime observation enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(windows): capture target-bound native window evidence

3 participants