Files
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

249 lines
13 KiB
Python

#!/usr/bin/env python3
"""Serialize real-client tests, reuse world sessions, and bound UI reconnection.
All input uses client_ui's focus and credential guards. No secret input, raw OCR,
or arbitrary Lua is accepted by this controller. Northshire is the verified scene.
"""
import argparse
import fcntl
import json
import os
import re
from pathlib import Path
import subprocess
import time
import client_ui as ui
def classify(text):
# The disconnect modal overlays the login form; its underlay must never
# authorize typing credentials into the still-open modal.
if 'disconnected' in text.lower():return 'disconnected'
if ui.is_login_screen(text):return 'login'
text=text.lower()
words=re.sub(r'[^a-z]','',text)
# Roster cards include other characters' zones. Two original controls,
# independent of names/selected race, must outrank those world labels.
if ui.is_character_select_screen(text):return 'characters'
if any(control in words for control in ('enterworld','createcharacter','createnewcharacter','togglecharacterlist')):return 'loading-or-unknown'
if ui.is_world_screen(text):return 'world'
if 'normal' in text and ('select' in text or 'chooseyourgameplayruleset' in words):return 'ruleset'
return 'loading-or-unknown'
def stable_login_retry(state,authenticated,seconds):
return state=='login' and authenticated and seconds>=5
class Session:
def __init__(self,startup_pid=None):
self.input_backend=os.environ.get('GW_CLIENT_INPUT','uinput')
if self.input_backend not in('uinput','x11'):raise ValueError('Unsupported client input backend')
self.startup_pid=startup_pid if startup_pid is not None else ui.known_client_startup_pid()
self.partial_macro=False
def __enter__(self):
self.lock=(ui.ROOT/'runtime/client-session.lock').open('a')
try:return self._enter()
except BaseException:
# Recovery within a persistent controller must not leave a lock,
# X connection or held input device after a failed focus attempt.
if getattr(self,'device',None):self.device.close();ui.UI=None;ui.INPUT_WINDOW=None
elif getattr(self,'locked',False):ui.INPUT_WINDOW=None
if getattr(self,'d',None):self.d.close()
self.lock.close();raise
def _enter(self):
fcntl.flock(self.lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
self.locked=True
self.d=ui.display.Display()
# Wine can publish the process well before KWin publishes its window.
# Poll actual discovery, with a bounded startup allowance and no relaunch.
until=time.monotonic()+30
while True:
try:
self.win=ui.target(self.d);break
except ui.ClientWindowBlocked:raise
except RuntimeError:
running=False
for proc in Path('/proc').iterdir():
try:
if proc.name.isdigit() and (proc/'comm').read_text().strip()=='WowB.exe':running=True;break
except OSError:pass
# A newly spawned Wine child initially has comm=wine rather
# than WowB.exe. An explicitly owned live startup PID keeps
# discovery polling active through that pre-PE transition.
if self.startup_pid is not None and (Path('/proc')/str(self.startup_pid)).exists():running=True
if not running or time.monotonic()>=until:
raise
time.sleep(.1)
ui.ensure_focus(self.d,self.win)
ui.INPUT_WINDOW=self.win.id
self.device=ui.UInput({ui.ecodes.EV_KEY:list(range(1,248))+[ui.ecodes.BTN_LEFT,ui.ecodes.BTN_RIGHT],ui.ecodes.EV_REL:[ui.ecodes.REL_X,ui.ecodes.REL_Y]},name='Gateway persistent local test input')if self.input_backend=='uinput'else None
ui.UI=self.device
if self.device:time.sleep(.5) # Existing uinput device-enumeration allowance; not a screen wait.
return self
def __exit__(self,*exc):
if self.device:self.device.close()
ui.UI=None;ui.INPUT_WINDOW=None
self.d.close();self.lock.close()
def focus(self):
ui.ensure_focus(self.d,self.win)
def state(self,*,world_first=True):
# Retry only one discarded read-only capture after a focus transition.
# Never retry credential entry or relax the window/sensitive-frame guard.
for attempt in range(2):
self.focus()
try:return classify(ui.private_screen(self.d,self.win,world_first=world_first))
except RuntimeError as error:
if attempt or str(error)!='Focus changed during capture; image discarded':raise
def wait_world(self,timeout=5):
"""Bounded read-only readiness; never reconnect or type on uncertainty."""
if not 1<=timeout<=15:raise ValueError('World readiness bound1..15seconds')
deadline=time.monotonic()+timeout
while True:
state=self.state()
if state=='world':return
if state!='loading-or-unknown':raise RuntimeError('Require actual world; preserve '+state+' screen')
if time.monotonic()>=deadline:raise RuntimeError('Bounded world-label readiness expired; no input')
time.sleep(.05)
def wait_login(self,timeout=3):
"""Observe transient startup frames without replaying credential input."""
if not 1<=timeout<=5:raise ValueError('Login readiness bound1..5seconds')
deadline=time.monotonic()+timeout
while True:
# At startup, avoid up to nine minimap OCR attempts before the
# full login/modal readback. This is a hint, not state authority.
state=self.state(world_first=False)
if state=='login':return
if state!='loading-or-unknown':raise RuntimeError('Require original login; preserve '+state+' screen')
if time.monotonic()>=deadline:raise RuntimeError('Bounded login readiness expired; no credential input')
time.sleep(.05)
def ensure_world(self,timeout):
deadline=time.monotonic()+timeout;previous=None;last_action={};authenticated=False;state_since=time.monotonic()
with ui.timed('ensure-world'):
while time.monotonic()<deadline:
state=self.state()
if state!=previous:
print('Client session:',state,flush=True);previous=state;state_since=time.monotonic()
if state=='world':return
if state in ('ruleset','characters'):authenticated=True
if state=='disconnected':authenticated=False
# A rejected world handshake can return to an idle login form
# without a Disconnected modal. Previously authenticated=True
# prevented all recovery until the whole controller timed out.
# Require the same fresh login classification for the existing
# five-second retry interval; credential guards recheck focus,
# fields and masks immediately before submission.
if stable_login_retry(state,authenticated,time.monotonic()-state_since):
authenticated=False
# Each transition is re-observed before input; throttle retries only,
# rather than sleeping for an assumed load time.
if time.monotonic()-last_action.get(state,-1e9)>=5:
if state=='login' and not authenticated:
with ui.timed('login-fields-and-submit'):
try:ui.verified_login_fields(self.d,self.win)
except RuntimeError as exc:
# Recognition and action each use a fresh private
# capture. A loading transition can invalidate the
# earlier recognition before any typing begins.
if str(exc).startswith('Refusing credentials outside'):continue
raise
ui.key(self.d,'Return')
elif state=='ruleset':
with ui.timed('select-ruleset'):
ui.click_at(self.d,self.win,536,570);ui.click_at(self.d,self.win,1786,1040)
elif state=='characters':
# Original roster controls are visible; preserve the
# caller's selected character. Never create or delete.
with ui.timed('enter-world-submit'):
ui.click_at(self.d,self.win,960,1000)
elif state=='disconnected':ui.key(self.d,'Return')
last_action[state]=time.monotonic()
time.sleep(.15)
raise RuntimeError('Bounded session recovery expired; client preserved for inspection')
def macro(self,text):
if len(text)>255:raise ValueError('Macro exceeds actual client edit bound')
# This build binds the physical grave key even with Shift while chat
# has focus. Typing Lua's ~= would open the console midway through a
# command. Reject before any input; use `not (a==b)` in diagnostics.
if '`' in text or '~' in text:raise ValueError('Macro contains the Forever console toggle key')
self.focus()
if self.partial_macro or ui.chat_edit_open(self.d,self.win):
# Never submit a truncated prior command when a cleanup macro
# follows a focus-loss exception. Cancel that edit, not replay it.
ui.key(self.d,'Escape');self.partial_macro=False
ui.key(self.d,'Return');self.partial_macro=True
ui.wait_chat_edit(self.d,self.win,True)
# Escape can leave cancelled text retained by the original EditBox.
# Replace it rather than appending a new command to a stale fragment.
ui.clear_edit_selection(self.d)
# Literal paste is qualified in the actual70334 chat EditBox. Reuse
# the existing MIME-preserving transaction, and submit in this action.
with ui.private_login_clipboard() as clipboard:
ui.paste_login_clipboard(self.d,self.win,clipboard,text)
ui.key(self.d,'Return')
ui.wait_chat_edit(self.d,self.win,False)
self.partial_macro=False
def shot(self,path):
self.focus()
with ui.timed('session-screenshot'):
text=ui.capture_text(self.d,self.win,path,world_first=True)
if ui.is_login_screen(text):
path.unlink(missing_ok=True);raise RuntimeError('Credential frame discarded')
def run_group(self,name,directory):
if self.state()!='world':raise RuntimeError('World session lost before test group')
with ui.timed('group-'+name):
if name=='population':self.shot(directory/'population.png')
elif name=='character':
ui.key(self.d,'c');self.shot(directory/'character.png');ui.key(self.d,'c')
elif name=='spellbook':
ui.key(self.d,'p');self.shot(directory/'spellbook.png');ui.key(self.d,'p')
elif name=='talents':
ui.key(self.d,'n');self.shot(directory/'talents.png');ui.key(self.d,'Escape')
elif name=='resources':
self.macro('/run print("GW progression",UnitLevel("player"),UnitHealthMax("player"),UnitPowerMax("player"));print("GW config",C_ClassTalents.GetActiveConfigID())')
self.shot(directory/'resources.png')
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('action',choices=['ensure-world','run','status'])
parser.add_argument('--timeout',type=float,default=120)
parser.add_argument('--groups',default='population,character,spellbook,resources')
parser.add_argument('--output',type=Path,default=ui.ROOT/'runtime/session-tests')
args=parser.parse_args()
groups=args.groups.split(',')
if any(g not in ('population','character','spellbook','talents','resources') for g in groups):parser.error('Unknown test group')
if not 1<=args.timeout<=300:parser.error('Timeout outside 1..300 seconds')
directory=args.output.resolve()
if not directory.is_relative_to(ui.ROOT/'runtime'):parser.error('Evidence must stay inside runtime')
with Session() as session:
if args.action=='status':print('Client session:',session.state());return
session.ensure_world(args.timeout)
if args.action=='run':
directory.mkdir(parents=True,exist_ok=True,mode=0o700)
results=[]
with ui.timed('gameplay-cycle'):
for group in groups:
start=time.monotonic()
try:session.run_group(group,directory);result='captured-not-asserted'
except RuntimeError as exc:
# Retain independent evidence, but do not input into a lost session.
result='failed';print('Test group failed:',group,str(exc),flush=True)
results.append({'group':group,'result':result,'seconds':round(time.monotonic()-start,3)})
(directory/'results.json').write_text(json.dumps(results,indent=2)+'\n')
print(json.dumps(results),flush=True)
if __name__=='__main__':
with ui.timed('session-controller-total'):main()