417 lines
28 KiB
Python
417 lines
28 KiB
Python
"""Render the real HTML in isolated Qt WebEngine; fake bridge, no customer I/O."""
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
from contextlib import ExitStack
|
|
from unittest.mock import patch
|
|
|
|
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
|
os.environ.setdefault("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu")
|
|
from PySide6.QtCore import QEventLoop, QTimer, QUrl, QObject, Signal, Slot
|
|
from PySide6.QtWebChannel import QWebChannel
|
|
from PySide6.QtWidgets import QApplication
|
|
from PySide6.QtWebEngineCore import QWebEnginePage, QWebEngineProfile, QWebEngineUrlRequestInterceptor
|
|
from PySide6.QtWebEngineWidgets import QWebEngineView
|
|
from PySide6.QtTest import QTest
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT))
|
|
|
|
|
|
class LocalOnly(QWebEngineUrlRequestInterceptor):
|
|
def interceptRequest(self, info):
|
|
if info.requestUrl().scheme() not in {"file", "qrc", "data", "about"}:
|
|
info.block(True)
|
|
|
|
|
|
class Page(QWebEnginePage):
|
|
def __init__(self, profile, parent):
|
|
super().__init__(profile, parent)
|
|
self.errors = []
|
|
|
|
def javaScriptConsoleMessage(self, level, message, line, source):
|
|
if level == QWebEnginePage.JavaScriptConsoleMessageLevel.ErrorMessageLevel:
|
|
self.errors.append(f"{source}:{line} {message}")
|
|
|
|
|
|
def main():
|
|
app = QApplication.instance() or QApplication([])
|
|
view = QWebEngineView()
|
|
profile = QWebEngineProfile(view) # Off-the-record; no user browser profile.
|
|
interceptor = LocalOnly(profile)
|
|
profile.setUrlRequestInterceptor(interceptor)
|
|
page = Page(profile, view)
|
|
view.setPage(page)
|
|
view.resize(1440, 1000)
|
|
view.show()
|
|
loop = QEventLoop()
|
|
loaded = []
|
|
page.loadFinished.connect(lambda ok: (loaded.append(ok), loop.quit()))
|
|
page.load(QUrl.fromLocalFile(str(ROOT / "assets/ui/zhenyang-ai-console.html")))
|
|
QTimer.singleShot(15000, loop.quit)
|
|
loop.exec()
|
|
assert loaded == [True], "HTML did not load"
|
|
|
|
def js(script):
|
|
result = []
|
|
wait = QEventLoop()
|
|
page.runJavaScript("(() => { try { " + script + " } catch(e) { return {error:String(e),stack:e.stack}; } })()",
|
|
lambda value: (result.append(value), wait.quit()))
|
|
QTimer.singleShot(10000, wait.quit)
|
|
wait.exec()
|
|
assert result, "JavaScript timed out"
|
|
value = result[0]
|
|
assert not (isinstance(value, dict) and value.get("error")), value
|
|
return value
|
|
|
|
def wait_until(check, message):
|
|
deadline = time.monotonic() + 12
|
|
while time.monotonic() < deadline:
|
|
if check():
|
|
return
|
|
QTest.qWait(25)
|
|
raise AssertionError(message)
|
|
|
|
def ack(**changes):
|
|
command = json.loads(js("return JSON.stringify(commands.at(-1))"))
|
|
op = dict(id=command["request_id"], action=command["action"], status="success",
|
|
title="操作已完成", message="操作完成")
|
|
payload = {"operation": op, "busy": False, **changes}
|
|
if command['action'] == 'candidates':
|
|
payload['candidateSearch'] = dict(id=command['request_id'], status='success')
|
|
js("window.applyState({view:'proactive',proactive:{...STATE.proactive,..." + json.dumps(payload, ensure_ascii=False) + "}});return true;")
|
|
|
|
def capture_current(path, selector):
|
|
# Force compositor work after async QWebChannel updates. DOM readiness
|
|
# alone does not guarantee that Windows offscreen WebEngine has painted.
|
|
for attempt in range(12):
|
|
js("window.__lastHtml='';render('proactive');return true;")
|
|
view.resize(1441 + attempt % 2, 1001)
|
|
QTest.qWait(100)
|
|
view.resize(1440, 1000)
|
|
view.update()
|
|
QTest.qWait(200)
|
|
pixmap = view.grab()
|
|
rect = json.loads(js("const r=document.querySelector(" + json.dumps(selector) + ").getBoundingClientRect();return JSON.stringify({x:r.x,y:r.y,w:r.width,h:r.height});"))
|
|
img = pixmap.toImage()
|
|
# Verify the creation card's green paint or the modal's dim backdrop;
|
|
# a blue pending button from an earlier frame is not a modal.
|
|
green = sum(1 for x in range(max(0,int(rect['x'])), min(img.width(),int(rect['x']+rect['w'])), 4)
|
|
for y in range(max(0,int(rect['y'])), min(img.height(),int(rect['y']+rect['h'])), 4)
|
|
if (c:=img.pixelColor(x,y)).green() > c.red()*1.15 and c.green() > c.blue()*1.05)
|
|
dim = 0
|
|
reply_green = 0
|
|
reply_painted = False
|
|
if selector == '.pc-created':
|
|
reply_rect = json.loads(js("const r=document.querySelector('.pc-reply-status').getBoundingClientRect();return JSON.stringify({x:r.x,y:r.y,w:r.width,h:r.height});"))
|
|
reply_green = sum(1 for x in range(max(0,int(reply_rect['x'])), min(img.width(),int(reply_rect['x']+reply_rect['w'])), 3)
|
|
for y in range(max(0,int(reply_rect['y'])), min(img.height(),int(reply_rect['y']+reply_rect['h'])), 3)
|
|
if (c:=img.pixelColor(x,y)).green() > c.red()*1.15 and c.green() > c.blue()*1.05)
|
|
sample = img.pixelColor(int(reply_rect['x']+reply_rect['w']/2), int(reply_rect['y']+reply_rect['h']-8))
|
|
reply_painted = sample.green() > sample.red()+8 and sample.green() > sample.blue()+4
|
|
if selector == '.pc-preview':
|
|
outer = json.loads(js("const r=document.querySelector('.pc-modal').getBoundingClientRect();return JSON.stringify({x:r.x,y:r.y,w:r.width,h:r.height});"))
|
|
for x in (int(outer['x']+8), int(outer['x']+outer['w']-8)):
|
|
for fraction in (.25,.5,.75):
|
|
y = int(outer['y']+outer['h']*fraction)
|
|
if 0 <= x < img.width() and 0 <= y < img.height() and max(img.pixelColor(x,y).getRgb()[:3]) < 215:
|
|
dim += 1
|
|
if (selector == '.pc-created' and green > 20 and reply_green > 20 and reply_painted) or (selector == '.pc-preview' and dim >= 5):
|
|
assert pixmap.save(str(path))
|
|
return
|
|
raise AssertionError(f"WebEngine did not paint current {selector} state")
|
|
|
|
fixture = dict(customers=[dict(id="c1", account="1", conversation="M:2", name="测试客户甲",
|
|
patient_name="测试患者甲", patient_id=123, valid=True, template="您好,{{客户名称}},方便了解一下近况吗?"),
|
|
dict(id="c2",account="1",conversation="M:3",name="测试客户乙",patient_name="测试患者乙",patient_id=456,valid=True,template="")],
|
|
tasks=[], enabled=True, busy=False, message="仅已绑定有效患者的客户可以加入。", candidates=dict(offset=0,total=2,has_more=False,items=[
|
|
dict(account="1",conversation="M:2",name="测试客户甲",bindings=[dict(id="b1",patient_id=123,patient_name="测试患者甲")],reason=""),
|
|
dict(account="1",conversation="M:3",name="未绑定客户 <img src=x onerror=alert(1)>",bindings=[],reason="未绑定患者,请先绑定")]))
|
|
js("window.commands=[]; window.replyStarts=0; window.qtBridge={proactiveCommand:p=>commands.push(JSON.parse(p)),navigate:()=>{},startListen:()=>replyStarts++}; "
|
|
"window.applyState(" + json.dumps(dict(view="proactive", demo=False, listening=False, proactive=fixture), ensure_ascii=False) + "); return true;")
|
|
assert js("return document.querySelector('h1').textContent") == "主动联系"
|
|
assert js("return document.querySelector('.pc-reply-status').textContent.includes('发送成功后会自动开启自动回复,无需手动点击')")
|
|
js("document.querySelector('[data-pc=start-replies]').click();return true;")
|
|
assert js("return replyStarts") == 1
|
|
js("window.applyState({...STATE,listening:true,sendMode:'review'});return true;")
|
|
assert js("return document.querySelector('.pc-reply-status').textContent.includes('审核模式')")
|
|
js("window.applyState({...STATE,listening:true,sendMode:'auto'});return true;")
|
|
assert js("return document.querySelector('.pc-reply-status').classList.contains('active')")
|
|
js("document.querySelector('[data-pc-customer]').click(); return true;")
|
|
assert js("return document.getElementById('pc-text').value") == fixture["customers"][0]["template"]
|
|
js("let el=document.getElementById('pc-text');el.value='批量测试文字';el.dispatchEvent(new Event('input',{bubbles:true}));document.querySelector('[data-pc=save-text]').click();return true;")
|
|
actual = js("return JSON.stringify(commands.at(-1))")
|
|
saved = json.loads(actual)
|
|
assert {k:v for k,v in saved.items() if k != "request_id"} == dict(action="text", ids=["c1"], text="批量测试文字"), actual
|
|
ack()
|
|
js("let el=document.getElementById('pc-kind');el.value='window';el.dispatchEvent(new Event('change',{bubbles:true}));return true;")
|
|
assert js("return document.querySelectorAll('[data-pc-day]').length") == 7
|
|
js("document.querySelector('[data-pc=preview]').click();return true;")
|
|
request = json.loads(js("return JSON.stringify(commands.at(-1))"))
|
|
assert request["action"] == "preview" and request["schedule"]["kind"] == "window"
|
|
assert request["text"] == "批量测试文字"
|
|
assert len(request["schedule"]["start_date"]) == 10
|
|
confirmation = dict(id="preview-1", tasks=[dict(name="测试客户甲",patient_name="测试患者甲",patient_id=123,
|
|
account="1",due=1793584800,text="逐人确认文字 💊")])
|
|
ack(preview=confirmation)
|
|
assert js("return document.querySelector('.pc-preview .pc-text').textContent") == "逐人确认文字 💊"
|
|
assert js("return document.querySelector('[role=dialog]').textContent.includes('尚未创建任务')")
|
|
js("document.querySelector('[data-pc=confirm]').click();return true;")
|
|
confirmed = json.loads(js("return JSON.stringify(commands.at(-1))"))
|
|
assert confirmed["action"] == "confirm" and confirmed["key"] == "preview-1"
|
|
count = js("return commands.length")
|
|
js("document.querySelector('[data-pc=confirm]').click();return true;")
|
|
assert js("return commands.length") == count, "double click submitted a second confirmation"
|
|
ack(operation=dict(id=confirmed["request_id"], action="confirm", status="error", title="创建失败 · 本次未创建任务", message="测试:患者绑定已变化"))
|
|
assert js("return document.querySelector('.pc-preview [role=alert]').textContent.includes('绑定已变化')")
|
|
js("document.querySelector('[data-pc=dismiss-preview]').click();return true;")
|
|
assert not js("return !!document.querySelector('[role=dialog]')")
|
|
js("let el=document.querySelector('[data-pc-field=interval]');el.value='40';el.dispatchEvent(new Event('input',{bubbles:true}));return true;")
|
|
assert not js("return !!document.querySelector('[data-pc=confirm]')")
|
|
# Offscreen WebEngine may be a compositor frame behind the DOM. Flush and
|
|
# reject empty captures rather than accepting a blank screenshot.
|
|
view.resize(1441, 1001)
|
|
QTest.qWait(200)
|
|
view.resize(1440, 1000)
|
|
output = ROOT / "tmp/proactive-contact-ui.png"
|
|
output.parent.mkdir(exist_ok=True)
|
|
for attempt in range(20):
|
|
QTest.qWait(150)
|
|
capture = view.grab()
|
|
painted = capture.toImage()
|
|
dark = sum(max(painted.pixelColor(x,y).getRgb()[:3]) < 175
|
|
for x in range(160,650,4) for y in range(25,150,4))
|
|
if dark >= 20:
|
|
break
|
|
js("window.__lastHtml='';render('proactive');return true;")
|
|
view.update()
|
|
assert dark >= 20, "WebEngine did not paint the main content"
|
|
assert capture.save(str(output))
|
|
js("document.querySelector('[data-pc=picker]').click();return true;")
|
|
assert js("return commands.at(-1).refresh_bindings===true")
|
|
ack()
|
|
assert js("return document.querySelectorAll('[data-pc-candidate]').length") == 1
|
|
assert js("return document.querySelector('[data-pc-search-status]').textContent.includes('本页显示 1 位已绑定客户')")
|
|
js("window.initialCandidates=STATE.proactive.candidates;window.boundExample=initialCandidates.items[0];"
|
|
"window.applyState({view:'proactive',proactive:{...STATE.proactive,candidates:{query:'',total:6,items:[...initialCandidates.items,"
|
|
"{...boundExample,conversation:'M:4',bindings:[],binding_loading:true},"
|
|
"{...boundExample,conversation:'M:5',bindings:[],binding_error:true},"
|
|
"{...boundExample,conversation:'M:6',bindings:[{id:'broken',patient_id:0,patient_name:''}]},"
|
|
"{...boundExample,conversation:'M:7',name:'多患者客户',bindings:[...boundExample.bindings,{id:'b2',patient_id:124,patient_name:'另一患者'}]}]},"
|
|
"candidateSearch:{...STATE.proactive.candidateSearch,count:6,checked:5}}});return true;")
|
|
assert js("return document.querySelectorAll('[data-pc-candidate]').length") == 2
|
|
assert js("return document.querySelectorAll('[data-pc-candidate]:disabled').length") == 0
|
|
assert js("return document.getElementById('pc-picker').textContent.includes('已绑定 2 位患者,请选择本次联系对象')")
|
|
js("document.querySelectorAll('[data-pc-candidate]')[1].click();window.beforeInvalidAdd=commands.length;"
|
|
"document.querySelector('[data-pc=add]').click();return true;")
|
|
assert js("return commands.length===beforeInvalidAdd && document.querySelector('[role=alert]').textContent.includes('多位患者')")
|
|
js("window.applyState({view:'proactive',proactive:{...STATE.proactive,candidates:initialCandidates,"
|
|
"candidateSearch:{...STATE.proactive.candidateSearch,count:2,checked:2}}});"
|
|
"document.querySelector('[data-pc-field=onlyBound]').click();return true;")
|
|
assert js("return document.querySelectorAll('[data-pc-candidate]:disabled').length") == 1
|
|
assert js("return document.querySelectorAll('.pc-table img').length") == 0
|
|
# Searching must stay usable while patient bindings arrive progressively.
|
|
js("window.searchInput=document.getElementById('pc-candidate-search');searchInput.focus();"
|
|
"window.searchCommandCount=commands.length;"
|
|
"for(const value of ['测','测试','测试客户甲']){searchInput.value=value;searchInput.dispatchEvent(new Event('input',{bubbles:true}));}return true;")
|
|
wait_until(lambda: js("return commands.length-searchCommandCount") > 0, 'search debounce did not run')
|
|
assert js("return commands.length-searchCommandCount") == 1
|
|
assert js("return commands.at(-1).query") == '测试客户甲'
|
|
assert js("return commands.at(-1).refresh_bindings!==true") # typing retains the fast cache
|
|
assert js("return document.querySelectorAll('[data-pc-candidate]').length") == 0 # no stale result rows
|
|
js("window.searchRequest=commands.at(-1).request_id;window.savedCandidates=STATE.proactive.candidates;"
|
|
"window.pendingCandidate={...savedCandidates.items[0],bindings:[],binding_loading:true,reason:'正在读取患者绑定…'};"
|
|
"window.applyState({view:'proactive',proactive:{...STATE.proactive,candidates:{query:'测试客户甲',items:[pendingCandidate],total:1},"
|
|
"candidateSearch:{id:searchRequest,status:'running',count:1,checked:0}}});return true;")
|
|
assert js("return document.activeElement===searchInput && document.getElementById('pc-candidate-search')===searchInput")
|
|
assert js("return document.querySelector('[data-pc-candidate]').disabled")
|
|
assert js("return document.querySelector('[data-pc-search-status]').textContent.includes('0/1')")
|
|
assert not js("return document.querySelector('[data-pc=preview]').disabled") # search does not lock task controls
|
|
js("window.applyState({view:'proactive',proactive:{...STATE.proactive,candidates:{query:'测试客户甲',items:[savedCandidates.items[0]],total:1},"
|
|
"candidateSearch:{id:searchRequest,status:'success',count:1,checked:1}}});return true;")
|
|
assert js("return document.activeElement===searchInput")
|
|
assert not js("return document.querySelector('[data-pc-candidate]').disabled")
|
|
# Enter starts a replacement query immediately; IME composition waits.
|
|
js("window.searchCommandCount=commands.length;searchInput.dispatchEvent(new CompositionEvent('compositionstart',{bubbles:true}));"
|
|
"searchInput.value='高';searchInput.dispatchEvent(new Event('input',{bubbles:true}));return true;")
|
|
QTest.qWait(350)
|
|
assert js("return commands.length===searchCommandCount")
|
|
js("searchInput.value='高瑞';searchInput.dispatchEvent(new CompositionEvent('compositionend',{bubbles:true}));return true;")
|
|
QTest.qWait(350)
|
|
assert js("return commands.at(-1).query") == '高瑞'
|
|
js("window.applyState({view:'proactive',proactive:{...STATE.proactive,"
|
|
"candidateSearch:{id:'binding-refresh',status:'success',serverInitiated:true}}});return true;")
|
|
js("searchInput.value='';searchInput.dispatchEvent(new Event('input',{bubbles:true}));"
|
|
"searchInput.dispatchEvent(new KeyboardEvent('keydown',{key:'Enter',bubbles:true}));"
|
|
"window.applyState({view:'proactive',proactive:{...STATE.proactive}});"
|
|
"window.applyState({view:'proactive',proactive:{...STATE.proactive,candidates:savedCandidates,"
|
|
"candidateSearch:{id:commands.at(-1).request_id,status:'success'}}});searchInput.blur();return true;")
|
|
assert not js("return document.querySelector('[data-pc-search-status]').textContent.includes('正在')")
|
|
assert js("return commands.at(-1).refresh_bindings===true") # Enter revalidates bindings
|
|
js("document.querySelector('[data-pc-candidate]:not(:disabled)').click();document.querySelector('[data-pc=add]').click();return true;")
|
|
request = json.loads(js("return JSON.stringify(commands.at(-1))"))
|
|
assert request["action"] == "add" and request["items"][0]["binding_id"] == "b1"
|
|
ack()
|
|
task = dict(id="t1",name="测试客户甲",patient_name="测试患者甲",patient_id=123,account="1",
|
|
text="已确认文字",status="delivery_unknown",due=1793584800,updated=1793584800,error="结果待核对")
|
|
js("STATE.proactive.tasks=" + json.dumps([task], ensure_ascii=False) + ";document.querySelector('[data-pc-tab=records]').click();return true;")
|
|
assert js("return !!document.querySelector('.pc-status.delivery_unknown')")
|
|
assert not js("return !!document.querySelector('[data-pc=resume]')")
|
|
assert js("return document.querySelector('.pc-task-notice').textContent.includes('可能已经发出')")
|
|
js("document.querySelector('[data-pc=reconcile]').click();return true;")
|
|
assert json.loads(js("return JSON.stringify(commands.at(-1))"))["action"] == "reconcile"
|
|
ack()
|
|
# Unknown and successful tasks can both be deleted; closing the dialog does nothing.
|
|
js("document.querySelector('[data-pc=delete-one]').click();return true;")
|
|
assert js("return document.querySelector('[role=dialog]').textContent.includes('确认删除 1 条任务')")
|
|
js("document.querySelector('[data-pc=dismiss-delete]').click();return true;")
|
|
assert js("return document.querySelectorAll('[data-pc-task]').length") == 1
|
|
second = {**task, 'id': 't2', 'status': 'succeeded'}
|
|
js("window.applyState({...STATE,proactive:{...STATE.proactive,tasks:" + json.dumps([task, second], ensure_ascii=False) + "}});document.querySelector('[data-pc=select-tasks]').click();document.querySelector('[data-pc=delete-selected]').click();return true;")
|
|
assert js("return document.querySelector('[role=dialog]').textContent.includes('确认删除 2 条任务')")
|
|
js("document.querySelector('[data-pc=confirm-delete]').click();return true;")
|
|
command = json.loads(js("return JSON.stringify(commands.at(-1))"))
|
|
assert command['action'] == 'delete' and set(command['ids']) == {'t1', 't2'}
|
|
ack(tasks=[])
|
|
assert not js("return !!document.querySelector('.pc-modal')")
|
|
assert js("return document.querySelectorAll('[data-pc-task]').length") == 0
|
|
# Same JS must respond to actual backend state changes, not only local redraws.
|
|
js("document.activeElement.blur();window.applyState({view:'proactive',proactive:{...STATE.proactive,operation:null,message:'状态更新成功'}});return true;")
|
|
assert js("return document.querySelector('[role=status]').textContent").startswith("状态更新成功")
|
|
view.resize(820, 700)
|
|
QTest.qWait(250)
|
|
assert js("return document.documentElement.scrollWidth <= innerWidth+1")
|
|
|
|
# Actual DOM -> QWebChannel -> worker -> service -> SQLite round trip.
|
|
# The only mocks are the patient/WeCom I/O boundaries; no real sends occur.
|
|
import proactive_contact_ui as controller_module
|
|
import proactive_contact_service as service_module
|
|
import wechat_gui_qt as gui
|
|
from types import SimpleNamespace
|
|
from proactive_contact_service import ContactService
|
|
from test_proactive_contact import FakeGateway, FakeTransport
|
|
|
|
class Bridge(QObject):
|
|
stateChanged = Signal(str)
|
|
|
|
def __init__(self, controller):
|
|
super().__init__()
|
|
self.controller = controller
|
|
self.commands = []
|
|
self.starts = []
|
|
self.host = SimpleNamespace(_running=False, _protocol_start_pending=False,
|
|
runtime_settings={'send_mode': 'auto'}, proactive_controller=controller,
|
|
start_monitoring=self.start_auto_replies, append_log=lambda *a: None,
|
|
_schedule_console_push=lambda **kw: self.publish(controller.state))
|
|
controller.changed.connect(self.publish)
|
|
controller.repliesRequested.connect(self.activate_replies)
|
|
|
|
@Slot(object)
|
|
def activate_replies(self, request):
|
|
gui.MainWindow._start_proactive_replies(self.host, request)
|
|
|
|
def start_auto_replies(self, *, background=False):
|
|
self.starts.append(background)
|
|
self.host._running = True
|
|
|
|
@Slot(object)
|
|
def publish(self, state):
|
|
self.stateChanged.emit(json.dumps(dict(view="proactive", demo=False, listening=self.host._running, sendMode='auto', proactive=state), ensure_ascii=False))
|
|
|
|
@Slot(str)
|
|
def proactiveCommand(self, payload):
|
|
self.commands.append(json.loads(payload))
|
|
self.controller.submit(payload)
|
|
|
|
@Slot()
|
|
def requestState(self):
|
|
self.controller.start()
|
|
|
|
@Slot(str)
|
|
def navigate(self, _view):
|
|
pass
|
|
|
|
with tempfile.TemporaryDirectory() as root, ExitStack() as stack:
|
|
gateway, transport = FakeGateway(), FakeTransport()
|
|
service = ContactService(root, gateway, transport)
|
|
service.add("owner", [dict(account="1", conversation="M:2", binding_id="binding")])
|
|
stack.enter_context(patch.object(controller_module, "PatientGateway", return_value=gateway))
|
|
stack.enter_context(patch.object(service_module, "PatientGateway", return_value=gateway))
|
|
stack.enter_context(patch.object(controller_module, "NativeContactTransport", return_value=transport))
|
|
controller = controller_module.ProactiveController(root)
|
|
bridge = Bridge(controller)
|
|
channel = QWebChannel(page)
|
|
channel.registerObject("bridge", bridge)
|
|
page.setWebChannel(channel)
|
|
try:
|
|
view.resize(1440, 1000)
|
|
reload_loop = QEventLoop()
|
|
page.loadFinished.connect(reload_loop.quit)
|
|
page.load(QUrl.fromLocalFile(str(ROOT / "assets/ui/zhenyang-ai-console.html")))
|
|
QTimer.singleShot(15000, reload_loop.quit)
|
|
reload_loop.exec()
|
|
page.loadFinished.disconnect(reload_loop.quit)
|
|
wait_until(lambda: js("return !!document.querySelector('[data-pc-customer]:not(:disabled)')"), "real bridge did not finish loading customer")
|
|
assert js("return document.querySelector('.pc-form').textContent.includes('消息在后台发送')")
|
|
assert not js("return document.querySelector('.pc-form').textContent.includes('空闲 5 秒')")
|
|
js("document.querySelector('[data-pc-customer]').click();document.querySelector('[data-pc=preview]').click();return true;")
|
|
assert js("return document.querySelector('.pc-form [role=alert]').textContent.includes('请先填写')")
|
|
assert not any(c["action"] == "preview" for c in bridge.commands)
|
|
js("let el=document.getElementById('pc-text');el.value='今天血糖测了吗';el.dispatchEvent(new Event('input',{bubbles:true}));document.querySelector('[data-pc=preview]').click();return true;")
|
|
wait_until(lambda: js("return !!document.querySelector('[data-pc=confirm]:not(:disabled)')"), "unsaved draft failed to preview")
|
|
assert service.store.tasks("owner") == []
|
|
assert transport.sent == []
|
|
assert bridge.starts == []
|
|
assert not any(c["action"] == "text" for c in bridge.commands), "preview required a separate save"
|
|
assert js("return document.querySelector('.pc-preview .pc-text').textContent") == "今天血糖测了吗"
|
|
assert js("return document.querySelector('.pc-preview').textContent.includes('尚未创建任务')")
|
|
preview_output = ROOT / "tmp/proactive-contact-preview.png"
|
|
capture_current(preview_output, '.pc-preview')
|
|
transport.before_send = lambda: setattr(transport, 'available', False)
|
|
js("document.querySelector('[data-pc=confirm]').click();document.querySelector('[data-pc=confirm]').click();return true;")
|
|
wait_until(lambda: js("return !!document.querySelector('.pc-created')"), "creation receipt missing")
|
|
wait_until(lambda: js("return !!document.querySelector('.pc-table .pc-status.queued')"), "last-moment transport contention did not stay queued")
|
|
assert js("return document.querySelector('.pc-task-notice').textContent.includes('条件满足后自动继续')")
|
|
assert service.store.tasks("owner")[0]["status"] == "queued"
|
|
assert transport.sent == []
|
|
transport.before_send = None
|
|
transport.available = True
|
|
wait_until(lambda: js("return !!document.querySelector('.pc-table .pc-status.succeeded')"), "completed task disappeared from plans")
|
|
wait_until(lambda: js("return document.querySelector('.pc-reply-status').classList.contains('active')"), "successful send did not automatically enable replies")
|
|
assert bridge.starts == [True], 'listener must start once in the background without a button click'
|
|
assert not js("return !!document.querySelector('.pc-task-notice')")
|
|
assert js("return document.querySelector('[data-pc-tab=plans]').classList.contains('active')")
|
|
assert js("return document.querySelector('.pc-created').textContent.includes('已创建 1 条任务')")
|
|
assert len(service.store.tasks("owner")) == 1
|
|
assert len(transport.sent) == 1 and transport.sent[0]["text"] == "今天血糖测了吗"
|
|
assert len([c for c in bridge.commands if c["action"] == "confirm"]) == 1
|
|
assert not any(c['action'] == 'resume' for c in bridge.commands), 'temporary wait required a manual resume'
|
|
capture_current(output, '.pc-created')
|
|
# Completed-task delete round trip through the real worker/store.
|
|
js("document.querySelector('[data-pc=delete-one]').click();return true;")
|
|
capture_current(ROOT/'tmp/proactive-contact-delete.png', '.pc-preview')
|
|
js("document.querySelector('[data-pc=confirm-delete]').click();return true;")
|
|
wait_until(lambda: js("return !document.querySelector('.pc-modal') && !document.querySelector('[data-pc-task]')"), "deleted task remained in the list")
|
|
assert service.store.tasks('owner') == []
|
|
assert len(service.store.tasks('owner', include_deleted=True)) == 1
|
|
assert len(transport.sent) == 1
|
|
assert bridge.starts == [True], 'refresh or delete unexpectedly restarted the listener'
|
|
assert not js("return !!document.querySelector('.pc-created')")
|
|
finally:
|
|
controller.close()
|
|
if controller._thread:
|
|
controller._thread.join(5)
|
|
app.processEvents()
|
|
page.setWebChannel(None)
|
|
assert not page.errors, page.errors
|
|
print(json.dumps({"ok": True, "screenshot": str(output)}, ensure_ascii=False))
|
|
view.close()
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|