import json, pathlib, subprocess, sys, time
from PIL import Image, ImageDraw, ImageFont, ImageChops
out=pathlib.Path(sys.argv[1]); session=sys.argv[2]
def run(*args, **kwargs):
    return subprocess.run(['agent-device', *args, '--session', session], check=True, **kwargs)
with open(str(out)+'-tree.json','w') as f:
    run('snapshot','--json',stdout=f)
nodes=json.loads(pathlib.Path(str(out)+'-tree.json').read_text())['data']['nodes']
n=next(n for n in nodes if n.get('label','').startswith('Open agents,'))
r=n['rect']; box=(r['x']-30,r['y']-20,r['x']+r['width']+30,r['y']+r['height']+20)
run('screenshot',str(out)+'-raw-a.png'); time.sleep(.5); run('screenshot',str(out)+'-raw-b.png')
a=Image.open(str(out)+'-raw-a.png').crop(box).convert('RGB'); b=Image.open(str(out)+'-raw-b.png').crop(box).convert('RGB')
if ImageChops.difference(a,b).getbbox(): raise RuntimeError('Control pixels changed between captures')
canvas=Image.new('RGB',(1080,420),'#f8f8fa');canvas.paste(b,((1080-b.width)//2,40))
d=ImageDraw.Draw(canvas); font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',28)
d.text((40,220),'Accessibility label (from native tree):',font=font,fill='#454545')
d.text((40,280),n['label'],font=font,fill='#111111')
d.text((40,350),'Pixel 9 • Android API 36 • English • Light theme',font=font,fill='#454545')
canvas.save(str(out)+'-label.png')
print(n['label']);print('Stable control pixels confirmed; screenshot crop with native-label annotation saved.')
