param([Parameter(Mandatory=$true)][string]$RequestFile, [Parameter(Mandatory=$true)][string]$OutputFile, [switch]$ExportCurrent, [switch]$ProbeFocus) $ErrorActionPreference = 'Stop' Add-Type -AssemblyName UIAutomationClient Add-Type -AssemblyName UIAutomationTypes Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing Add-Type -Path (Join-Path $PSScriptRoot 'chrome-keyboard.cs') Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public class ChatGptWindow { [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h); [DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context); [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h,out uint pid); [DllImport("user32.dll")] public static extern bool SetProcessDPIAware(); [DllImport("user32.dll")] public static extern bool SetCursorPos(int x,int y); [DllImport("user32.dll")] public static extern void mouse_event(uint flags,uint x,uint y,uint data,UIntPtr extra); [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h,int c); [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h); }' [ChatGptWindow]::SetProcessDPIAware() | Out-Null [ChatGptWindow]::SetThreadDpiAwarenessContext([IntPtr](-4)) | Out-Null $request = Get-Content -LiteralPath $RequestFile -Raw -Encoding UTF8 | ConvertFrom-Json $interactiveChromeIds = @(Get-CimInstance Win32_Process -Filter "Name = 'chrome.exe'" | Where-Object { $_.CommandLine -notmatch '--headless' } | Select-Object -ExpandProperty ProcessId) $browser = Get-Process chrome -ErrorAction SilentlyContinue | Where-Object { $_.Id -in $interactiveChromeIds -and $_.MainWindowHandle -ne 0 -and [ChatGptWindow]::IsWindowVisible($_.MainWindowHandle) -and -not [string]::IsNullOrWhiteSpace($_.MainWindowTitle) } | Select-Object -First 1 if (-not $browser) { throw 'Open normal Chrome and log in to https://chatgpt.com/ first.' } $shellControl = New-Object -ComObject WScript.Shell $previousClipboard = $null if ($env:CHATGPT_IMAGE_EXPORT -eq 'clipboard') { $previousClipboard = [System.Windows.Forms.Clipboard]::GetDataObject() } $deadline = [DateTime]::UtcNow.AddSeconds(215) $script:panelMode = $false function Focus-Chrome { [ChromeKeyboard]::ActivateWindow($browser.MainWindowHandle) Start-Sleep -Milliseconds 300 [uint32]$foregroundProcessId = 0 [ChatGptWindow]::GetWindowThreadProcessId([ChatGptWindow]::GetForegroundWindow(),[ref]$foregroundProcessId) | Out-Null if ($foregroundProcessId -ne $browser.Id) { throw "Chrome could not take foreground focus; refusing to send keystrokes to another application." } } function Get-Controls { $root = [System.Windows.Automation.AutomationElement]::FromHandle($browser.MainWindowHandle) if ($script:panelMode) { $documents = $root.FindAll([System.Windows.Automation.TreeScope]::Descendants,[System.Windows.Automation.PropertyCondition]::new([System.Windows.Automation.AutomationElement]::ControlTypeProperty,[System.Windows.Automation.ControlType]::Document)) $windowBounds = $root.Current.BoundingRectangle $panel = $documents | Where-Object { $_.Current.Name -eq 'ChatGPT' -and $_.Current.BoundingRectangle.Left -gt ($windowBounds.Left + $windowBounds.Width / 2) -and $_.Current.BoundingRectangle.Width -lt ($windowBounds.Width * 0.6) } | Select-Object -First 1 if (-not $panel) { return @() } $panelBounds = $panel.Current.BoundingRectangle return $root.FindAll([System.Windows.Automation.TreeScope]::Descendants,[System.Windows.Automation.Condition]::TrueCondition) | Where-Object { $_.Current.BoundingRectangle.Left -ge $panelBounds.Left -and $_.Current.BoundingRectangle.Top -ge $panelBounds.Top -and $_.Current.BoundingRectangle.Right -le $panelBounds.Right -and $_.Current.BoundingRectangle.Bottom -le $panelBounds.Bottom } } return $root.FindAll([System.Windows.Automation.TreeScope]::Descendants,[System.Windows.Automation.Condition]::TrueCondition) } function Find-Control($type, $pattern) { foreach ($control in (Get-Controls)) { if ($control.Current.ControlType -eq $type -and $control.Current.Name -match $pattern) { return $control } } return $null } function Invoke-Control($control) { $invoke = $null if ($control.TryGetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern,[ref]$invoke)) { $invoke.Invoke() } else { if (-not $control.Current.IsEnabled -or $control.Current.IsOffscreen) { throw 'Chrome control is not available for interaction.' } $bounds = $control.Current.BoundingRectangle [ChatGptWindow]::SetCursorPos([int]($bounds.Left + $bounds.Width / 2),[int]($bounds.Top + $bounds.Height / 2)) | Out-Null [ChatGptWindow]::mouse_event(2,0,0,0,[UIntPtr]::Zero) [ChatGptWindow]::mouse_event(4,0,0,0,[UIntPtr]::Zero) } } try { [ChatGptWindow]::ShowWindow($browser.MainWindowHandle,3) | Out-Null Focus-Chrome if ($ProbeFocus) { Write-Output 'Interactive Chrome foreground focus verified.'; exit 0 } if (($env:CHATGPT_SURFACE -ne 'tab')) { $extension = Find-Control ([System.Windows.Automation.ControlType]::Button) '^ChatGPT(?:[.]|\r|\n|$)' if (-not $extension) { throw 'Open the ChatGPT Chrome extension side panel first.' } $script:panelMode = $true if (@(Get-Controls).Count -eq 0) { $bounds = $extension.Current.BoundingRectangle [ChatGptWindow]::SetCursorPos([int]($bounds.Left + $bounds.Width / 2),[int]($bounds.Top + $bounds.Height / 2)) | Out-Null [ChatGptWindow]::mouse_event(2,0,0,0,[UIntPtr]::Zero) [ChatGptWindow]::mouse_event(4,0,0,0,[UIntPtr]::Zero) } Start-Sleep -Milliseconds 1000 if (-not $ExportCurrent) { $closePreview = Find-Control ([System.Windows.Automation.ControlType]::Button) '^(ปิด|Close|Close preview|Close image preview|ปิดตัวอย่างภาพ|ปิดตัวแสดงผล)$' if ($closePreview) { Invoke-Control $closePreview; Start-Sleep -Milliseconds 500 } $newChat = Find-Control ([System.Windows.Automation.ControlType]::Button) '^(แชตใหม่|New chat)$' if (-not $newChat) { $sidebar = Find-Control ([System.Windows.Automation.ControlType]::Button) '^(แสดงไซด์บาร์|Show sidebar)$' if ($sidebar) { Invoke-Control $sidebar; Start-Sleep -Milliseconds 500 } $newChat = Find-Control ([System.Windows.Automation.ControlType]::Button) '^(แชตใหม่|New chat)$' } if ($newChat) { Invoke-Control $newChat; Start-Sleep -Milliseconds 700 } else { $existingMessage = Find-Control ([System.Windows.Automation.ControlType]::Text) '^(คุณพูดว่า:|You said:)$' $existingImage = Find-Control ([System.Windows.Automation.ControlType]::Button) '^(รูปภาพที่สร้าง|Generated image|Image generated)\s*1$' if ($existingMessage -or $existingImage) { throw 'Start a new chat in the extension before submitting another job.' } } } } else { $newTab = Find-Control ([System.Windows.Automation.ControlType]::Button) '^New Tab$' if (-not $newTab) { throw 'Chrome new-tab control unavailable.' } Invoke-Control $newTab Start-Sleep -Milliseconds 700 Focus-Chrome $address = Find-Control ([System.Windows.Automation.ControlType]::Edit) '^Address and search bar$' if (-not $address) { throw 'Chrome address bar unavailable.' } $addressValue = $address.GetCurrentPattern([System.Windows.Automation.ValuePattern]::Pattern) $addressValue.SetValue('https://chatgpt.com/') $address.SetFocus() $shellControl.SendKeys('{ENTER}') } if (-not $ExportCurrent) { $editor = $null while ([DateTime]::UtcNow -lt $deadline) { if (Find-Control ([System.Windows.Automation.ControlType]::Button) '^(Log in|เข้าสู่ระบบ)$') { throw 'ChatGPT login required in normal Chrome.' } $editor = Find-Control ([System.Windows.Automation.ControlType]::Edit) '^(ถาม ChatGPT|Ask ChatGPT|Message ChatGPT)$' if ($editor) { break } Start-Sleep -Milliseconds 700 } if (-not $editor) { throw 'Chat composer unavailable. Check login or manual browser verification.' } Focus-Chrome $editor = Find-Control ([System.Windows.Automation.ControlType]::Edit) '^(ถาม ChatGPT|Ask ChatGPT|Message ChatGPT)$' $editor.SetFocus() $editorBounds = $editor.Current.BoundingRectangle [ChatGptWindow]::SetCursorPos([int]($editorBounds.Left + $editorBounds.Width / 2),[int]($editorBounds.Top + $editorBounds.Height / 2)) | Out-Null [ChatGptWindow]::mouse_event(2,0,0,0,[UIntPtr]::Zero) [ChatGptWindow]::mouse_event(4,0,0,0,[UIntPtr]::Zero) Start-Sleep -Milliseconds 300 Focus-Chrome [ChromeKeyboard]::TypeText([string]$request.prompt) $send = $null $sendDeadline = [DateTime]::UtcNow.AddSeconds(15) while ([DateTime]::UtcNow -lt $sendDeadline) { $send = Find-Control ([System.Windows.Automation.ControlType]::Button) '^(Send|Send prompt|ส่ง|ส่งพรอมต์|ส่งข้อความ)$' if ($send -and $send.Current.IsEnabled) { break } Start-Sleep -Milliseconds 500 } if (-not $send -or -not $send.Current.IsEnabled) { throw 'Send button unavailable; prompt was not submitted.' } Invoke-Control $send Write-Output 'Image prompt submitted to normal Chrome.' } $imageButton = $null while ([DateTime]::UtcNow -lt $deadline) { $imageButton = Find-Control ([System.Windows.Automation.ControlType]::Button) '^(รูปภาพที่สร้าง|Generated image|Image generated)\s*1$' if ($imageButton) { break } Start-Sleep -Milliseconds 1000 } if (-not $imageButton) { throw 'Image generation timed out; inspect the ChatGPT tab before retrying.' } # Read only the new generated image, never an old clipboard image or a screenshot. Focus-Chrome $copy = $null if ($env:CHATGPT_IMAGE_EXPORT -eq 'clipboard') { $copy = Find-Control ([System.Windows.Automation.ControlType]::Button) '^(คัดลอกรูปภาพ|Copy image)$' } if ($copy) { [System.Windows.Forms.Clipboard]::Clear() Invoke-Control $copy $copyDeadline = [DateTime]::UtcNow.AddSeconds(8) while ([DateTime]::UtcNow -lt $copyDeadline) { if ([System.Windows.Forms.Clipboard]::ContainsImage()) { $bitmap = [System.Windows.Forms.Clipboard]::GetImage() try { $bitmap.Save($OutputFile,[System.Drawing.Imaging.ImageFormat]::Png) } finally { $bitmap.Dispose() } Write-Output 'Generated image saved.' exit 0 } Start-Sleep -Milliseconds 500 } } # Clipboard permissions can fail even after generation succeeds. Export the same image instead. Focus-Chrome $download = Find-Control ([System.Windows.Automation.ControlType]::Button) '^(ดาวน์โหลด|Download|Download image)$' if (-not $download) { $imageButton = Find-Control ([System.Windows.Automation.ControlType]::Button) '^(รูปภาพที่สร้าง|Generated image|Image generated)\s*1$' if (-not $imageButton) { throw 'The generated image is no longer visible.' } Invoke-Control $imageButton $exportDeadline = [DateTime]::UtcNow.AddSeconds(15) while ([DateTime]::UtcNow -lt $exportDeadline) { $download = Find-Control ([System.Windows.Automation.ControlType]::Button) '^(ดาวน์โหลด|Download|Download image)$' if ($download) { break } Start-Sleep -Milliseconds 500 } } if (-not $download) { throw 'Image export controls unavailable; inspect the generated image before retrying.' } $deadline = [DateTime]::UtcNow.AddSeconds(35) $downloads = (Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders').'{374DE290-123F-4565-9164-39C4925E467B}' if (-not $downloads) { $downloads = Join-Path ([Environment]::GetFolderPath('UserProfile')) 'Downloads' } $downloads = [Environment]::ExpandEnvironmentVariables($downloads) $existing = @(Get-ChildItem -LiteralPath $downloads -File | Select-Object -ExpandProperty FullName) Invoke-Control $download Start-Sleep -Milliseconds 500 $downloadItem = Find-Control ([System.Windows.Automation.ControlType]::MenuItem) '^(ดาวน์โหลดรูปภาพ|Download image)$' if ($downloadItem) { Invoke-Control $downloadItem } while ([DateTime]::UtcNow -lt $deadline) { $file = Get-ChildItem -LiteralPath $downloads -File | Where-Object { $_.FullName -notin $existing -and $_.Extension -match '^\.(png|jpg|jpeg|webp)$' } | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1 if ($file) { try { $bitmap = [System.Drawing.Image]::FromFile($file.FullName) try { $bitmap.Save($OutputFile,[System.Drawing.Imaging.ImageFormat]::Png) } finally { $bitmap.Dispose() } Write-Output 'Generated image downloaded and saved.' exit 0 } catch { Start-Sleep -Milliseconds 500 } } Start-Sleep -Milliseconds 500 } throw 'Image download did not finish; check Chrome download permissions.' } finally { if ($previousClipboard) { [System.Windows.Forms.Clipboard]::SetDataObject($previousClipboard,$true) } }