{"record":{"id":"e375dd699a3f3559","repo":"Hmbown/CodeWhale","slug":"display-index-must-be-a-positive-integer","errorCode":null,"errorMessage":"display index must be a positive integer","messagePattern":"display index must be a positive integer","errorType":"validation","errorClass":"ExecError","httpStatus":null,"severity":"error","filePath":"crates/tui/plugins/computer-use/src/backends/win32.mjs","lineNumber":406,"sourceCode":"    try { $acts = @($cur.GetSupportedPatterns() | ForEach-Object { $_.ProgrammaticName -replace 'PatternIdentifiers\\\\.Pattern$','' -replace 'Pattern$','' }) } catch {}\n    $value = ''; $vp = $null;\n    if (-not $cur.Current.IsPassword -and $cur.TryGetCurrentPattern([System.Windows.Automation.ValuePattern]::Pattern, [ref]$vp)) { $value = [string]$vp.Current.Value }\n    [void]$els.Add([pscustomobject]@{ index = $els.Count; path = @($path); runtime_id = @($cur.GetRuntimeId()); window_runtime_id = $windowId; role = [string]$cur.Current.ControlType.ProgrammaticName; label = [string]$cur.Current.Name; value = $value.Substring(0, [Math]::Min(120, $value.Length)); enabled = $cur.Current.IsEnabled;\n      x = [int]$rect.X; y = [int]$rect.Y; w = [int]$rect.Width; h = [int]$rect.Height; actions = $acts });\n    $kids = $cur.FindAll([System.Windows.Automation.TreeScope]::Children, [System.Windows.Automation.Condition]::TrueCondition);\n    for ($i = $kids.Count - 1; $i -ge 0; $i--) { $stack.Push(@($kids[$i], ($path + $i))) }\n  }\n  break;\n}\n$result = [pscustomobject]@{ found = $found; name = $appName; truncated = $truncated; elements = @($els | ForEach-Object { [pscustomobject]@{ index = $_.index; path = @($_.path); runtime_id = $_.runtime_id; window_runtime_id = $_.window_runtime_id; role = ($_.role -replace 'ControlType.',''); label = $_.label; value = $_.value; enabled = $_.enabled; position = [pscustomobject]@{ x = $_.x; y = $_.y }; size = [pscustomobject]@{ w = $_.w; h = $_.h }; actions = $_.actions } }) };\nWrite-Output ($result | ConvertTo-Json -Depth 6 -Compress);`, { timeoutMs: 60_000 });\n      if (!j.found) throw new ExecError(\"application window not found in UIA tree — pass app_ref.name as the exact window title from list_windows or list_apps.title\");\n      return j;\n    },\n    screenshot: async (args = {}) => {\n      if (Object.hasOwn(args, \"app_ref\") || Object.hasOwn(args, \"window_id\")) throw unsupportedSelector(\"Windows screenshot does not support app_ref or window_id; omit them for a desktop screenshot\");\n      const { display = activeDisplay, region, path: outPath } = args;\n      if (display != null && (!Number.isInteger(display) || display < 1)) throw new ExecError(\"display index must be a positive integer\");\n      if (region != null && (!Array.isArray(region) || region.length !== 4 || !region.every(Number.isInteger) || region[2] <= 0 || region[3] <= 0)) throw new ExecError(\"region must be integer [x,y,width,height] with positive size\");\n      const dir = recordingsDir();\n      fs.mkdirSync(dir, { recursive: true });\n      const file = path.resolve(outPath || path.join(dir, `shot-${crypto.randomBytes(6).toString(\"hex\")}.png`));\n      const meta = await psJson(`Add-Type -AssemblyName System.Windows.Forms; Add-Type -AssemblyName System.Drawing;\n$bounds = [System.Windows.Forms.SystemInformation]::VirtualScreen;\n${display == null ? \"\" : `$screens = [System.Windows.Forms.Screen]::AllScreens; if (${display} -gt $screens.Count) { throw 'display index is out of range' }; $bounds = $screens[${display - 1}].Bounds;`}\n${region == null ? \"\" : `$crop = New-Object System.Drawing.Rectangle(${region.join(\",\")}); if (-not $bounds.Contains($crop)) { throw 'region is outside capture bounds' }; $bounds = $crop;`}\n$bmp = New-Object System.Drawing.Bitmap($bounds.Width, $bounds.Height);\ntry {\n  $g = [System.Drawing.Graphics]::FromImage($bmp);\n  try { $g.CopyFromScreen($bounds.X, $bounds.Y, 0, 0, $bounds.Size); } finally { $g.Dispose(); }\n  $bmp.Save('${file.replace(/'/g, \"''\")}', [System.Drawing.Imaging.ImageFormat]::Png);\n} finally { $bmp.Dispose(); }\n@{ x = $bounds.X; y = $bounds.Y; w = $bounds.Width; h = $bounds.Height } | ConvertTo-Json -Compress;`, { timeoutMs: 30_000 });\n      if (!fs.existsSync(file) || ![meta.x, meta.y, meta.w, meta.h].every(Number.isFinite) || meta.w <= 0 || meta.h <= 0) throw new ExecError(\"screenshot did not return a valid raster\");\n      lastRaster = { file, bytes: fs.statSync(file).size, points: { x: meta.x, y: meta.y, w: meta.w, h: meta.h }, pixels: { w: meta.w, h: meta.h }, scale: 1, capturedAt: new Date().toISOString() };\n      return { ...lastRaster };","sourceCodeStart":388,"sourceCodeEnd":424,"githubUrl":"https://github.com/Hmbown/CodeWhale/blob/73e0f67d83c59909b571efdfc88c4bc28c309cb1/crates/tui/plugins/computer-use/src/backends/win32.mjs#L388-L424","documentation":"screenshot validates the display parameter before capturing: if provided, it must be a positive integer (1-based). It throws this ExecError for null-adjacent bad values like 0, negative numbers, floats, or non-numeric strings, preventing a bogus index from reaching the PowerShell capture script.","triggerScenarios":"Calling screenshot({display: 0}) (forgetting indexes are 1-based), display: \"2\" (string), display: 1.5, or display from unvalidated external input.","commonSituations":"0-based/1-based confusion when porting from other screen APIs; passing IDs instead of ordinals; agents guessing display values without calling list_displays.","solutions":["Use 1-based integers: display: 1 for the first monitor","Omit display entirely to capture the whole virtual screen","Validate with Number.isInteger(d) && d >= 1 before calling","Call list_displays() and use its returned index values"],"exampleFix":"// before\nawait screenshot({ display: 0 });\n// after\nawait screenshot({ display: 1 });","handlingStrategy":"type-guard","validationCode":"const isValidDisplay = (d) => d == null || (Number.isInteger(d) && d >= 1);\n// usage\nif (!isValidDisplay(display)) throw new TypeError(\"display must be a positive integer (1-based) or omitted\");","typeGuard":"const isDisplayIndex = (v) => Number.isInteger(v) && v >= 1;","tryCatchPattern":"try {\n  return await backend.screenshot({ display });\n} catch (e) {\n  if (String(e.message) === \"display index must be a positive integer\") {\n    return await backend.screenshot(); // full virtual screen fallback\n  }\n  throw e;\n}","preventionTips":["Use 1-based integers for displays","Omit display to capture the entire virtual screen","Convert string inputs with Number() and re-check integrality","Source indexes from list_displays output"],"tags":["display","validation","screenshot"],"backgroundTag":"invalid-argument-value","analyzedSha":"73e0f67d83c59909b571efdfc88c4bc28c309cb1","analyzedAt":"2026-09-22T01:30:00.501Z","contentChangedAt":"2026-09-22T01:30:00.501Z","schemaVersion":2},"datasetVersion":"2026-09-22T11:17:16.035Z"}