import subprocess,time,sys,pathlib

out=pathlib.Path(sys.argv[1]); session='evidence-28523'
for i in range(12):
 a=out.with_name(out.stem+'-stability-a.png'); b=out.with_name(out.stem+'-stability-b.png')
 subprocess.run(['agent-device','screenshot',str(a),'--session',session],check=True,capture_output=True)
 time.sleep(.5)
 subprocess.run(['agent-device','screenshot',str(b),'--session',session],check=True,capture_output=True)
 # Compare full raw screenshots, including status bar.
 if subprocess.run(['compare','-metric','AE',str(a),str(b),'null:'],capture_output=True).returncode == 0:
  out.write_bytes(b.read_bytes());print('Identical screenshots 500 ms apart:',out.name);break
else: raise SystemExit('Screenshots did not stabilize')
