Files
PAGIVA/scripts/chatgpt-chrome.ps1
Loma Bot Ops 4c93bf0a11 Add brand visual style to page profile and logo palette to image prompts
Adds PageProfile.visualStyle (with migration), feeds it into every AI
prompt route, and samples a logo palette for image generation. Also
hardens Chrome focus handling and image copy in the ChatGPT driver.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 20:58:06 +07:00

251 lines
17 KiB
PowerShell

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 {
$focusDeadline = [DateTime]::UtcNow.AddSeconds(3)
do {
[ChatGptWindow]::ShowWindow($browser.MainWindowHandle,3) | Out-Null
$shellControl.AppActivate($browser.Id) | Out-Null
[ChromeKeyboard]::ActivateWindow($browser.MainWindowHandle)
Start-Sleep -Milliseconds 150
$foregroundWindow = [ChatGptWindow]::GetForegroundWindow()
if ($foregroundWindow -eq $browser.MainWindowHandle) { return }
} while ([DateTime]::UtcNow -lt $focusDeadline)
[uint32]$foregroundProcessId = 0
[ChatGptWindow]::GetWindowThreadProcessId($foregroundWindow,[ref]$foregroundProcessId) | Out-Null
throw "Chrome could not take foreground focus (target=$($browser.Id), foreground=$foregroundProcessId); 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 Find-GlobalControl($type, $pattern) {
$root = [System.Windows.Automation.AutomationElement]::FromHandle($browser.MainWindowHandle)
foreach ($control in $root.FindAll([System.Windows.Automation.TreeScope]::Descendants,[System.Windows.Automation.Condition]::TrueCondition)) {
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
if ($ProbeFocus) { Focus-Chrome; 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)
}
$panelDeadline = [DateTime]::UtcNow.AddSeconds(10)
while (@(Get-Controls).Count -eq 0 -and [DateTime]::UtcNow -lt $panelDeadline) { Start-Sleep -Milliseconds 250 }
if (@(Get-Controls).Count -eq 0) { throw 'ChatGPT extension side panel did not open.' }
$chatMode = Find-Control ([System.Windows.Automation.ControlType]::Button) '^Chat$'
if ($chatMode) { Invoke-Control $chatMode; Start-Sleep -Milliseconds 500 }
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.' }
$editor = Find-Control ([System.Windows.Automation.ControlType]::Edit) '^(ถาม ChatGPT|Ask ChatGPT|Message ChatGPT)$'
$editorValue = $null
if ($editor.TryGetCurrentPattern([System.Windows.Automation.ValuePattern]::Pattern,[ref]$editorValue)) {
$editorValue.SetValue([string]$request.prompt)
} else {
Focus-Chrome
$editor.SetFocus()
[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.
# Current ChatGPT builds expose Copy image directly while Download may only
# appear in some preview variants. Prefer the direct control and retain the
# download path as a fallback when clipboard access is unavailable.
$copyControlDeadline = [DateTime]::UtcNow.AddSeconds(15)
while ([DateTime]::UtcNow -lt $copyControlDeadline) {
$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
}
break
}
Start-Sleep -Milliseconds 500
}
# Some extension builds hide Copy image but expose it in the image context
# menu. This still copies the original bitmap and avoids download policy.
$generatedImage = Find-Control ([System.Windows.Automation.ControlType]::Image) '^(รูปภาพที่สร้าง|Generated image|Image generated)\s*\d+$'
if ($generatedImage -and -not $generatedImage.Current.IsOffscreen) {
Focus-Chrome
$bounds = $generatedImage.Current.BoundingRectangle
[ChatGptWindow]::SetCursorPos([int]($bounds.Left + $bounds.Width / 2),[int]($bounds.Top + $bounds.Height / 2)) | Out-Null
[ChatGptWindow]::mouse_event(8,0,0,0,[UIntPtr]::Zero)
[ChatGptWindow]::mouse_event(16,0,0,0,[UIntPtr]::Zero)
Start-Sleep -Milliseconds 500
$copyMenu = Find-GlobalControl ([System.Windows.Automation.ControlType]::MenuItem) '^(คัดลอกรูปภาพ|Copy image)$'
if ($copyMenu) {
[System.Windows.Forms.Clipboard]::Clear()
Invoke-Control $copyMenu
$copyDeadline = [DateTime]::UtcNow.AddSeconds(15)
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 from context menu.'
exit 0
}
Start-Sleep -Milliseconds 500
}
}
}
# Clipboard permissions can fail even after generation succeeds. Export the same image instead.
$download = Find-Control ([System.Windows.Automation.ControlType]::Button) '^(ดาวน์โหลด|Download|Download image)$'
if (-not $download) {
$imageButton = $null
$imageDeadline = [DateTime]::UtcNow.AddSeconds(10)
while ([DateTime]::UtcNow -lt $imageDeadline) {
$imageButton = Find-Control ([System.Windows.Automation.ControlType]::Button) '^(รูปภาพที่สร้าง|Generated image|Image generated)\s*1$'
if ($imageButton) { break }
Start-Sleep -Milliseconds 500
}
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) }
}