Files
xieyi-weixin-/tools/preview_console_design.py
2026-11-02 14:05:03 +08:00

103 lines
7.7 KiB
Python

"""Render the real desktop UI with synthetic data; never attach a live bridge."""
import json
import os
from pathlib import Path
import sys
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
os.environ.setdefault("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu")
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from tools.test_proactive_console import LocalOnly, Page
from PySide6.QtCore import QEventLoop, QTimer, QUrl
from PySide6.QtWidgets import QApplication
from PySide6.QtWebEngineCore import QWebEngineProfile
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtTest import QTest
def fixture():
names = ["林女士", "陈先生", "周女士", "许先生", "王女士", "李先生"]
people = [dict(key=f"M:{n}", name="示例 · "+name, status="待审核" if n==0 else "等待中",
wait=f"{n+1} 分钟", avatar=name[0], bubbles=1, active=n==0) for n,name in enumerate(names)]
customers = [dict(id=f"c{n}", account="演示账号", conversation=f"M:{n}", name="示例 · "+name,
patient_name="示例患者"+str(n+1),patient_id=100+n,valid=True,
template="您好,想了解一下您最近的情况,方便时请回复。" if n<3 else "") for n,name in enumerate(names)]
conversations=[dict(id=f"M:{n}",name="示例 · "+name,kind="微信客户",messageCount=8,
lastTime="2026-11-02 10:20",preview="收到,谢谢关心。",lastDirection="收到") for n,name in enumerate(names)]
return dict(demo=False,view="auto",listening=True,statusLabel="监听中",wecomConnected=True,aiOk=True,
wecomLabel="企业微信已连接",aiLabel="AI 服务正常",sendMode="auto",selectedKey="M:0",people=people,
metrics=dict(waiting="6",queue="6",today="24",failed="0",processing="1",review="1",human="0",retry="0",avgWait="30s"),
attention=dict(review=1,human=0,total=1),system=dict(scale="自动",version="1.5.5",tray=True),
task=dict(key="M:0",name="示例 · 林女士",messages=[dict(time="10:20",text="您好,我已经收到了,谢谢关心。")],
answer="收到您的反馈了。如果有需要了解的情况,随时留言,我们会及时跟进。",awaitingReview=True,
canApprove=True,reviewReason="此条回复需要您核对后发送。",stepIndex=3,steps=[],schedule={},isProtocol=True),
journey=[dict(title=title,status="已完成" if n<3 else "待审核" if n==3 else "等待",time="—",done=n<3,active=n==3,wait=n>3)
for n,title in enumerate(["发现客户消息","读取会话内容","生成回复草稿","人工核对","发送并归档"])],
logs=[dict(time="10:20",title="回复已生成",detail="示例客户的回复草稿等待审核",state="待审核",tone="orange",icon="message",category="识别")],
proactive=dict(customers=customers,tasks=[],enabled=True,busy=False,message="仅已绑定有效患者的客户可以加入。",
candidates=dict(offset=0,total=6,has_more=False,items=[dict(account=c['account'],conversation=c['conversation'],name=c['name'],
bindings=[dict(id='b'+c['id'],patient_id=c['patient_id'],patient_name=c['patient_name'])],reason="") for c in customers])),
wechatDb=dict(loading=False,query="",selectedAccount="1",selectedConversation="M:0",accounts=[dict(id="1",name="演示账号")],
accountCount=1,conversations=conversations,conversationDetails=conversations[0],conversationTotal=6,conversationLimit=50,
messageTotal=3,messageLimit=80,messageLoadDirection="newest",messages=[dict(id=str(n),sender="示例客户",direction="inbound" if n%2==0 else "outbound",
time="10:20",type="文字",content=text) for n,text in enumerate(["您好,想了解一下后续如何安排。","已收到,我们会为您跟进。","好的,谢谢。"])]))
def main():
app=QApplication.instance() or QApplication([])
view=QWebEngineView(); profile=QWebEngineProfile(view)
interceptor=LocalOnly(profile);profile.setUrlRequestInterceptor(interceptor)
page=Page(profile,view);view.setPage(page);view.resize(1440,1000);view.show()
wait=QEventLoop();loaded=[]
page.loadFinished.connect(lambda ok:(loaded.append(ok),wait.quit()))
page.load(QUrl.fromLocalFile(str(ROOT/'assets/ui/zhenyang-ai-console.html')))
QTimer.singleShot(15000,wait.quit);wait.exec();assert loaded==[True]
def js(script):
results=[];loop=QEventLoop()
page.runJavaScript('(()=>{try{'+script+'}catch(e){return "ERROR:"+String(e)}})()',lambda result:(results.append(result),loop.quit()))
QTimer.singleShot(10000,loop.quit);loop.exec()
assert results and not str(results[0]).startswith('ERROR:'), results
return results[0]
js('window.qtBridge={navigate:()=>{},proactiveCommand:()=>{}};window.applyState('+json.dumps(fixture(),ensure_ascii=False)+');return true;')
output=ROOT/'tmp'/'ui-refined';output.mkdir(parents=True,exist_ok=True)
checks=[]; issues=[]
for width,height in [(1440,1000),(1366,768),(1024,768),(800,600),(480,640)]:
view.resize(width,height)
# Chromium reports resized viewport dimensions asynchronously.
for attempt in range(40):
QTest.qWait(100)
if js(f'return innerWidth==={width} && innerHeight==={height};'):
break
else:raise AssertionError(('viewport did not resize',width,height))
for name in ['auto','queue','proactive','wechatdb','archive','ai','automation','logs','blacklist','system']:
js('document.activeElement?.blur();window.applyState({view:'+json.dumps(name)+'});fit();return true;')
QTest.qWait(75)
metrics=json.loads(js('fit();const main=document.getElementById("main"),nav=document.querySelector(".rail"),sys=document.querySelector(".system-btn");'
'return JSON.stringify({overflow:main.scrollWidth-main.clientWidth,main:main.clientWidth,navBottom:sys.getBoundingClientRect().bottom,height:innerHeight,heading:!!main.querySelector("h1")});'))
checks.append(dict(view=name,width=width,**metrics))
assert metrics['heading'], (name,metrics)
if metrics['overflow'] > 2 or metrics['navBottom'] > height+2:
issues.append((width,name,metrics))
if (width==1440 and name in ['auto','proactive','wechatdb','ai','system']) or (width==800 and name=='proactive'):
# A one-pixel capture marker verifies Chromium painted this state,
# rather than saving a stale native surface from the preceding tab.
marker=40+len(checks)*3
js('let marker=document.getElementById("capture-marker");if(!marker){marker=document.createElement("div");marker.id="capture-marker";document.body.append(marker)}'
'marker.style.cssText="position:fixed;right:0;bottom:0;width:1px;height:1px;z-index:99999;background:rgb('+str(marker)+',31,73)";return true;')
for attempt in range(12):
view.resize(width+1,height);QTest.qWait(120);view.resize(width,height);view.update();QTest.qWait(220)
pixmap=view.grab();color=pixmap.toImage().pixelColor(width-1,height-1)
if (color.red(),color.green(),color.blue())==(marker,31,73):
assert pixmap.save(str(output/f'{name}-{width}.png'))
break
else:raise AssertionError(('stale capture',name,width))
assert not page.errors,page.errors
(output/'layout-checks.json').write_text(json.dumps(checks,ensure_ascii=False,indent=2),encoding='utf-8')
assert not issues,issues
print(json.dumps(dict(ok=True,checks=len(checks),screenshots=str(output)),ensure_ascii=False))
view.close();view.deleteLater();QTest.qWait(30)
if __name__=='__main__':
main()