This commit is contained in:
Your Name
2026-11-12 16:11:43 +08:00
parent 775d955577
commit 08892f4270
9 changed files with 788 additions and 139 deletions
+1 -1
View File
@@ -3,7 +3,7 @@
__all__ = ["DEBUG_MODE", "ONLINE_API_BASE_URL", "__version__"]
# Single source of truth for runtime, package, installer, and executable versions.
__version__ = "1.5.3"
__version__ = "1.5.4"
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。
+20 -8
View File
@@ -347,7 +347,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
call_error = Signal(str) # type: ignore[misc]
_start_completed = Signal(bool) # type: ignore[misc]
_policy_completed = Signal(str, object) # type: ignore[misc]
_room_completed = Signal(str, bool, str) # type: ignore[misc]
_room_completed = Signal(object, str, bool, str) # type: ignore[misc]
_screenshot_completed = Signal(bool, str) # type: ignore[misc]
_transcription_completed = Signal(str, str, str, bool, str, str) # type: ignore[misc]
_local_transcription_event = Signal(object) # type: ignore[misc]
@@ -723,12 +723,14 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
)
return
room_id = message.get("roomId", message.get("room_id"))
if room_id not in (None, ""):
if (room_id not in (None, "") and self._start_requested
and not self._call_cycle_closed and not self._shutdown_requested):
clean_room_id = str(room_id).strip()
future = self.lifecycle.bind_room(clean_room_id)
lifecycle = self.lifecycle
future = lifecycle.bind_room(clean_room_id)
future.add_done_callback(
lambda completed, current_room_id=clean_room_id: (
self._notify_room_completed(current_room_id, completed)
lambda completed, current_lifecycle=lifecycle, current_room_id=clean_room_id: (
self._notify_room_completed(current_lifecycle, current_room_id, completed)
)
)
if event == "room":
@@ -911,7 +913,12 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
extra={"video_call": self.request.safe_log_context()},
)
def _notify_room_completed(self, room_id: str, future: Future[bool]) -> None:
def _notify_room_completed(
self,
lifecycle: OrderedCallLifecycle,
room_id: str,
future: Future[bool],
) -> None:
try:
succeeded = bool(future.result())
except Exception as error:
@@ -924,15 +931,20 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
else "通话房间尚未绑定,云端视频和本机录音无法关联通话记录。"
)
with suppress(RuntimeError):
self._room_completed.emit(room_id, succeeded, message)
self._room_completed.emit(lifecycle, room_id, succeeded, message)
def _on_room_completed(
self,
lifecycle: OrderedCallLifecycle,
room_id: str,
succeeded: bool,
message: str,
) -> None:
if self._closing:
# A worker may finish before redial, but its queued Qt signal can
# arrive afterwards. Compare call identity on the UI thread.
if (self._closing or self._released or self._shutdown_requested
or lifecycle is not self.lifecycle or not self._start_requested
or self._call_cycle_closed):
return
room_payload = json.dumps(str(room_id)[:160], ensure_ascii=True)
payload = json.dumps(str(message)[:200], ensure_ascii=True)
@@ -0,0 +1,166 @@
"""Exercise persisted cloud captions across redials using the real lifecycle worker."""
from __future__ import annotations
import logging
from itertools import count
from queue import Queue
from threading import Event
from types import MethodType
from unittest.mock import Mock
import pytest
from test_cloud_transcription_bridge import (
SIMPLIFIED,
TIMESTAMP,
host,
segment_message,
transcription_result,
)
from doctor_workstation.video import window
from doctor_workstation.video.launcher import VideoCallRequest
from doctor_workstation.video.lifecycle import OrderedCallLifecycle
pytestmark = pytest.mark.skipif(not window.WEBENGINE_AVAILABLE, reason="optional QtWebEngine")
@pytest.fixture
def cycle_host():
record_ids = count(701)
repository = Mock()
repository.start_call.side_effect = lambda **_payload: {"call_record_id": next(record_ids)}
repository.start_call_transcription.return_value = True
repository.upsert_call_transcript_segments.return_value = True
repository.finish_call_transcription.return_value = True
request = VideoCallRequest(
sdk_app_id=1400123456, user_id="doctor_test", user_sig="test-ticket",
target_user_id="patient_test", diagnosis_id=123, patient_id=8,
)
item = host(
request=request, repository=repository, _start_requested=False,
open_im=True, call_ended=Mock(), _start_completed=Mock(),
start_acks=Queue(), transcription_acks=Queue(), release_storage=Event(),
)
item._lifecycle_factory = lambda: OrderedCallLifecycle(
request, repository, logging.getLogger(__name__),
)
item.lifecycle = item._lifecycle_factory()
item._lifecycles = [item.lifecycle]
for name in (
"_prepare_call_cycle", "_start_call_cycle", "_notify_start_completed",
"_on_lifecycle_started",
):
setattr(item, name, MethodType(getattr(window._EmbeddedVideoWindow, name), item))
# A worker may complete while its Qt signal remains queued for the UI thread.
item._start_completed.emit.side_effect = lambda *args: item.start_acks.put(args)
item._transcription_completed.emit.side_effect = lambda *args: item.transcription_acks.put(args)
try:
yield item
finally:
item.release_storage.set()
for lifecycle in item._lifecycles:
lifecycle.end("test-cleanup").result(timeout=2)
assert lifecycle.wait(2)
def start_cycle(item, session_id):
item._handle_bridge_message({"event": "call-start-request"})
acknowledgement = item.start_acks.get(timeout=2)
assert acknowledgement == (True,)
item._on_lifecycle_started(*acknowledgement)
item._handle_bridge_message({
"event": "transcription-start-request", "sessionId": session_id,
})
acknowledgement = item.transcription_acks.get(timeout=2)
assert acknowledgement[:4] == ("start", session_id, "", True)
item._on_transcription_completed(*acknowledgement)
item._live_ai.bind.assert_called_with(item.lifecycle.call_record_id, session_id)
item._page.runJavaScript.reset_mock()
item._live_ai.reset_mock()
return item.lifecycle
def assert_caption_ack(item, session_id, acknowledgement):
assert acknowledgement[:4] == ("segment", session_id, "cloud-segment-1", True)
item._on_transcription_completed(*acknowledgement)
assert transcription_result(item) == [
"segment", session_id, "cloud-segment-1", True, "",
{"segmentId": "cloud-segment-1", "speakerUserId": "patient_test",
"sourceText": SIMPLIFIED, "timestamp": TIMESTAMP, "isCompleted": True},
]
item._live_ai.changed.assert_called_once_with(session_id)
def test_three_calls_save_reused_segment_id_and_ack_simplified_captions(cycle_host):
item = cycle_host
for record_id, session_id in ((701, "tr-first"), (702, "tr-second"), (703, "tr-third")):
lifecycle = start_cycle(item, session_id)
assert lifecycle.call_record_id == record_id
item._handle_bridge_message(segment_message(sessionId=session_id))
acknowledgement = item.transcription_acks.get(timeout=2)
# Saving on the worker must finish before normalized text reaches the page.
item._page.runJavaScript.assert_not_called()
item._live_ai.changed.assert_not_called()
saved = item.repository.upsert_call_transcript_segments.call_args.kwargs
assert (saved["call_record_id"], saved["transcription_session_id"]) == (record_id, session_id)
assert saved["segments"][0]["text"] == SIMPLIFIED
assert saved["segments"][0]["segment_id"] == "cloud-segment-1"
assert_caption_ack(item, session_id, acknowledgement)
item._handle_bridge_message({"event": "transcription-stop", "sessionId": session_id})
acknowledgement = item.transcription_acks.get(timeout=2)
assert acknowledgement[:4] == ("stop", session_id, "", True)
item._on_transcription_completed(*acknowledgement)
item._handle_bridge_message({"event": "hangup"})
assert lifecycle.wait(2)
assert len({id(lifecycle) for lifecycle in item._lifecycles}) == 3
assert item.repository.upsert_call_transcript_segments.call_count == 3
assert [call.kwargs["call_record_id"] for call in item.repository.end_call.call_args_list] == [701, 702, 703]
@pytest.mark.parametrize("worker_finishes_before_redial", [False, True])
@pytest.mark.parametrize("storage_succeeds", [False, True])
def test_old_segment_ack_keeps_old_session_and_cannot_dirty_redial(
cycle_host, worker_finishes_before_redial, storage_succeeds,
):
item = cycle_host
entered = Event()
def save_segment(**payload):
if payload["call_record_id"] == 701:
entered.set()
if not worker_finishes_before_redial:
assert item.release_storage.wait(5), "test did not release the old write"
if not storage_succeeds:
raise RuntimeError("old call storage failure")
return True
item.repository.upsert_call_transcript_segments.side_effect = save_segment
previous = start_cycle(item, "tr-old")
item._handle_bridge_message(segment_message(sessionId="tr-old"))
assert entered.wait(2)
if worker_finishes_before_redial:
old_ack = item.transcription_acks.get(timeout=2)
item._handle_bridge_message({"event": "hangup"})
current = start_cycle(item, "tr-current")
assert current is not previous
if not worker_finishes_before_redial:
item.release_storage.set()
old_ack = item.transcription_acks.get(timeout=2)
assert old_ack[:4] == ("segment", "tr-old", "cloud-segment-1", storage_succeeds)
item._on_transcription_completed(*old_ack)
# The companion filters ACKs by this session; the host must never retag them.
assert transcription_result(item)[:4] == ["segment", "tr-old", "cloud-segment-1", storage_succeeds]
assert item.lifecycle is current
assert current.transcription_session_id == "tr-current"
assert not item._asr_partial
assert item._live_ai.mock_calls == []
item._handle_bridge_message(segment_message(sessionId="tr-current"))
assert_caption_ack(item, "tr-current", item.transcription_acks.get(timeout=2))
saved = item.repository.upsert_call_transcript_segments.call_args.kwargs
assert (saved["call_record_id"], saved["transcription_session_id"]) == (702, "tr-current")
+203
View File
@@ -0,0 +1,203 @@
"""Exercise room binding across redials without creating a Qt window."""
from __future__ import annotations
import logging
from collections.abc import Iterator
from itertools import count
from queue import Queue
from threading import Event
from types import MethodType
from typing import Any
from unittest.mock import Mock
import pytest
from doctor_workstation.video import window
from doctor_workstation.video.launcher import VideoCallRequest
from doctor_workstation.video.lifecycle import OrderedCallLifecycle
pytestmark = pytest.mark.skipif(not window.WEBENGINE_AVAILABLE, reason="optional QtWebEngine")
class _QueuedSignal:
"""Keep worker completion separate from delivery on the simulated UI thread."""
def __init__(self) -> None:
self.queue: Queue[tuple[Any, ...]] = Queue()
def emit(self, *args: Any) -> None:
self.queue.put(args)
def take(self) -> tuple[Any, ...]:
return self.queue.get(timeout=2)
class _Repository:
def __init__(self) -> None:
self.events: list[tuple[Any, ...]] = []
self.record_ids = count(701)
self.block_record_id: int | None = None
self.bind_entered = Event()
self.release_bind = Event()
def start_call(self, diagnosis_id: int, patient_id: int, **kwargs: Any) -> dict[str, int]:
assert (diagnosis_id, patient_id, kwargs["call_type"]) == (123, 8, 2)
record_id = next(self.record_ids)
self.events.append(("start", record_id))
return {"call_record_id": record_id}
def bind_call_room(self, diagnosis_id: int, room_id: str, *, call_record_id: int) -> None:
assert diagnosis_id == 123
if call_record_id == self.block_record_id:
self.bind_entered.set()
assert self.release_bind.wait(5), "test did not release the pending room bind"
self.events.append(("bind", call_record_id, room_id))
def end_call(self, diagnosis_id: int, *, call_record_id: int) -> None:
assert diagnosis_id == 123
self.events.append(("end", call_record_id))
class _Host:
def __init__(self) -> None:
self.repository = _Repository()
self.request = VideoCallRequest(
sdk_app_id=1400123456,
user_id="doctor_42",
user_sig="test-ticket",
target_user_id="patient_8",
diagnosis_id=123,
patient_id=8,
)
self.lifecycle = self._lifecycle_factory()
self._lifecycles = [self.lifecycle]
self._closing = False
self._released = False
self._shutdown_requested = False
self._start_requested = False
self._call_cycle_closed = False
self.open_im = True
self._page = Mock()
self.call_ended = Mock()
self._start_completed = _QueuedSignal()
self._room_completed = _QueuedSignal()
for name in (
"_handle_bridge_message", "_prepare_call_cycle", "_start_call_cycle",
"_notify_start_completed", "_on_lifecycle_started",
"_notify_room_completed", "_on_room_completed",
):
setattr(self, name, MethodType(getattr(window._EmbeddedVideoWindow, name), self))
def _lifecycle_factory(self) -> OrderedCallLifecycle:
return OrderedCallLifecycle(self.request, self.repository, logging.getLogger(__name__))
def start(self) -> OrderedCallLifecycle:
self._handle_bridge_message({"event": "call-start-request"})
assert self._start_completed.take() == (True,)
self._on_lifecycle_started(True)
self._page.runJavaScript.assert_called_with(
"window.doctorConsultation?.hostCallReady?.(true, '');"
)
self._page.reset_mock()
return self.lifecycle
def room(self, room_id: str) -> None:
self._handle_bridge_message({"event": "room", "roomId": room_id})
def hangup(self) -> None:
self._handle_bridge_message({"event": "hangup"})
@pytest.fixture
def host() -> Iterator[_Host]:
current = _Host()
try:
yield current
finally:
current.repository.release_bind.set()
for lifecycle in current._lifecycles:
lifecycle.end("test-cleanup").result(timeout=2)
assert lifecycle.wait(2)
def test_three_calls_in_one_im_window_bind_their_own_record_and_room(host: _Host) -> None:
for record_id, room_id in ((701, "r1"), (702, "r2"), (703, "r3")):
lifecycle = host.start()
assert lifecycle.call_record_id == record_id
host.room(room_id)
acknowledgement = host._room_completed.take()
assert acknowledgement[:3] == (lifecycle, room_id, True)
host._on_room_completed(*acknowledgement)
script = host._page.runJavaScript.call_args.args[0]
assert f'roomBindingResult?.("{room_id}", true,' in script
host.hangup()
assert lifecycle.wait(2)
assert len({id(lifecycle) for lifecycle in host._lifecycles}) == 3
assert host.repository.events == [
("start", 701), ("bind", 701, "r1"), ("end", 701),
("start", 702), ("bind", 702, "r2"), ("end", 702),
("start", 703), ("bind", 703, "r3"), ("end", 703),
]
@pytest.mark.parametrize("next_room", ["r1", "r2"])
@pytest.mark.parametrize("worker_finishes_before_redial", [False, True])
def test_old_room_ack_cannot_reach_next_call_even_when_room_is_reused(
host: _Host, next_room: str, worker_finishes_before_redial: bool,
) -> None:
previous = host.start()
if not worker_finishes_before_redial:
host.repository.block_record_id = 701
host.room("r1")
if worker_finishes_before_redial:
old_ack = host._room_completed.take()
else:
assert host.repository.bind_entered.wait(2)
host.hangup()
current = host.start()
assert current is not previous
if not worker_finishes_before_redial:
host.repository.release_bind.set()
old_ack = host._room_completed.take()
assert old_ack[:3] == (previous, "r1", True)
host._on_room_completed(*old_ack)
host._page.runJavaScript.assert_not_called()
host.room(next_room)
current_ack = host._room_completed.take()
assert current_ack[:3] == (current, next_room, True)
host._on_room_completed(*current_ack)
assert host._page.runJavaScript.call_count == 1
assert current.bound_room_id == next_room
assert ("bind", 702, next_room) in host.repository.events
def test_ended_call_drops_room_ack_queued_before_hangup(host: _Host) -> None:
host.start()
host.room("r1")
acknowledgement = host._room_completed.take()
host.hangup()
host._on_room_completed(*acknowledgement)
host._page.runJavaScript.assert_not_called()
@pytest.mark.parametrize("state", ["ready", "ended", "prepared"])
def test_room_event_without_active_call_cannot_create_a_record(host: _Host, state: str) -> None:
if state != "ready":
host.start()
host.hangup()
assert host.lifecycle.wait(2)
if state == "prepared":
# Policy refresh prepares a new lifecycle before call-start-request.
host._prepare_call_cycle()
before = list(host.repository.events)
host.room("late-room")
host.lifecycle.end("test-barrier").result(timeout=2)
assert host.lifecycle.wait(2)
assert host.repository.events == before
assert host.lifecycle.current_room_id is None
assert host._room_completed.queue.empty()
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -6,7 +6,7 @@
<meta name="color-scheme" content="light" />
<link rel="icon" type="image/png" href="./favicon.png" />
<title>视频面诊</title>
<script type="module" crossorigin src="./assets/index-B6TT7yDM.js"></script>
<script type="module" crossorigin src="./assets/index-D15F7NRw.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-Do0GoLfO.css">
</head>
<body>
+44 -20
View File
@@ -151,6 +151,7 @@ interface RealtimeTranscriberManager {
removeListener(listener: RealtimeTranscriberListener): void
startRealtimeTranscriber(config: { sourceLanguage: string }): Promise<string>
stopRealtimeTranscriber(robotId: string): Promise<void>
destroy?(): void
}
interface PendingTranscriptionReply {
@@ -1485,9 +1486,9 @@ function subscribeTranscriber(): {
manager: RealtimeTranscriberManager
listener: RealtimeTranscriberListener
} {
if (transcriberManager && transcriberListener) {
return { manager: transcriberManager, listener: transcriberListener }
}
// Every startup owns a fresh listener closure for the current session. An
// SDK stop can fail after leaving the room; never reuse its old subscription.
unsubscribeTranscriber()
const manager = getTranscriberManager()
const sessionId = transcriptionSessionId
const listener: RealtimeTranscriberListener = {
@@ -1534,6 +1535,10 @@ function unsubscribeTranscriber(
manager = transcriberManager,
listener = transcriberListener,
): void {
if (transcriberManager === manager && transcriberListener === listener) {
transcriberManager = null
transcriberListener = null
}
if (manager && listener) {
try {
manager.removeListener(listener)
@@ -1541,9 +1546,12 @@ function unsubscribeTranscriber(
// A destroyed call engine has already released the listener.
}
}
if (transcriberManager === manager && transcriberListener === listener) {
transcriberManager = null
transcriberListener = null
try {
// TRTCCloud creates a manager per getter call. removeListener only removes
// message delivery; destroy also releases this manager's SDK state listener.
manager?.destroy?.()
} catch {
// Releasing an already destroyed SDK must not block the next call.
}
}
@@ -1692,7 +1700,9 @@ async function stopTranscription(
transcriberRobotId = ''
}
const segmentsComplete = await waitForPendingSegments()
if (sdkStopped) unsubscribeTranscriber()
// Drain final messages first, but never retain a listener across calls just
// because stop failed after hangup. Preserve the partial archive status.
if (sdkStopped || transcriptionFinalizeRequested) unsubscribeTranscriber()
if (!transcriptionFinalizeRequested) {
// An interrupted cloud robot is recoverable within this same call and
// storage session. The final hangup remains the only store finalizer.
@@ -1859,12 +1869,17 @@ function currentCallEngine(): CallEngineLike | null {
* TRTC 实例上的进房参数是最早、最可靠的房间号来源;离房后旧房间号仍留在实例上,只在
* 仍在房间里时才采信,避免把上一通的房间绑到这一通。
*/
function readRoomIdFromEngine(): string {
function readRoomIdFromEngine(): string | null {
const engine = currentCallEngine()
if (!engine || typeof engine.getTRTCCloudInstance !== 'function') return ''
if (!engine || typeof engine.getTRTCCloudInstance !== 'function') return null
try {
const trtc = engine.getTRTCCloudInstance() as Record<string, unknown> | null | undefined
if (!trtc || typeof trtc !== 'object') return ''
const cloud = engine.getTRTCCloudInstance() as Record<string, unknown> | null | undefined
if (!cloud || typeof cloud !== 'object') return null
// CallEngine 3.5.9 返回 TRTCCloud 包装层,房间状态在它的 v5 实例 _trtc 上。
// 同时兼容直接返回 v5 实例的引擎;离房后保留的进房参数仍不能作为当前房间。
const trtc = cloud._trtc && typeof cloud._trtc === 'object'
? cloud._trtc as Record<string, unknown>
: cloud
const room = trtc._room
const joined = !!room && typeof room === 'object' && (room as Record<string, unknown>).isJoined === true
if (!joined) return ''
@@ -1879,7 +1894,7 @@ function readRoomIdFromEngine(): string {
} catch {
// TRTC 实例字段不可访问时只用 Store。
}
return ''
return null
}
/** 引擎的 onCallBegin / onCallReceived / onCallEnd 事件自带房间号,不经过 Store,也不依赖 calls() 返回。 */
@@ -1902,13 +1917,17 @@ function bindEngineRoomEvents(): void {
}
function readRoomId(): string {
return normalizeRoomScalar(TUIStore.getData(StoreName.CALL, NAME.ROOM_ID)) || readRoomIdFromEngine()
// 旧 calls() 完成时会先写 Store 再返回。真实进房状态优先,明确未进房时
// 返回空值;只有引擎不可读取(null)时才使用 Store,避免重拨误绑旧房间。
return readRoomIdFromEngine() ?? normalizeRoomScalar(TUIStore.getData(StoreName.CALL, NAME.ROOM_ID))
}
function observeRoomId(rawRoomId: unknown): boolean {
if (!activeConfig || endNotified) return false
const roomId = normalizeRoomId(rawRoomId)
if (!roomId) return false
const currentRoomId = readRoomIdFromEngine()
if (currentRoomId !== null && roomId !== currentRoomId) return false
if (boundRoomId) return boundRoomId === roomId
const now = Date.now()
@@ -1981,6 +2000,9 @@ function handleStatusChanged(payload: unknown): void {
phase.value = 'dialing'
statusText.value = '正在等待患者接听'
appendVideoCallStatus('dialing', '正在等待患者接听')
// SDK 发出拨号状态前,通话守卫已创建本轮宿主记录。立即监听进房,
// 不等待可能迟迟不返回的 calls(),未接通/很快挂断的呼叫也能绑定房间。
void pollRoomId()
} else if (status === 'idle' && activeConfig && !starting) {
void notifyHangup(status)
}
@@ -2059,10 +2081,17 @@ async function startVideo(): Promise<void> {
hangupNotification = null
callCycleGeneration += 1
cycle = callCycleGeneration
emittedRoomId = ''
pendingRoomId = ''
boundRoomId = ''
roomBindingSentAt = 0
roomBindingAttempts = 0
endNotified = false
phase.value = 'starting'
statusText.value = '正在创建安全视频通话'
appendVideoCallStatus('starting', '正在创建安全视频通话')
unsubscribeTranscriber()
transcriptionGeneration += 1
transcriptionState.value = 'idle'
transcriptionSessionId = ''
transcriptionStorageReady = false
@@ -2091,18 +2120,13 @@ async function startVideo(): Promise<void> {
phase.value = 'dialing'
statusText.value = '正在呼叫患者'
appendVideoCallStatus('dialing', '正在呼叫患者')
emittedRoomId = ''
pendingRoomId = ''
boundRoomId = ''
roomBindingSentAt = 0
roomBindingAttempts = 0
const callResult: unknown = await TUICallKitAPI.calls({
userIDList: [activeConfig.targetUserId],
type: TUICallType.VIDEO_CALL,
})
// CallKit 封装的 calls() 可能到对方接听、甚至这通结束后才返回;返回时若已是下一通,
// 这里的任何状态都不能再碰,否则会把上一通的房间号绑到新通话上。
if (cycle !== callCycleGeneration) return
if (activeConfig !== config || generation !== contextGeneration || cycle !== callCycleGeneration || endNotified) return
// 房间不绑定,服务端就不会发起云端录制,这次面诊的回放会直接丢失。
observeRoomId(extractRoomFromEngineResult(callResult) || readRoomId())
void pollRoomId()
@@ -2176,7 +2200,7 @@ function recordingResult(ok: boolean, message: string): void {
function roomBindingResult(roomId: string, ok: boolean, message: string): void {
const normalized = normalizeRoomId(roomId)
if (!normalized || (emittedRoomId && normalized !== emittedRoomId)) return
if (!activeConfig || endNotified || !emittedRoomId || normalized !== emittedRoomId) return
if (ok) {
boundRoomId = normalized
pendingRoomId = ''
@@ -12,6 +12,7 @@ const names = new Set([
'reportTranscriptionError', 'unsubscribeTranscriber', 'transcriptionTokenIsCurrent',
'waitForPendingSegments', 'performStartTranscription', 'startTranscription',
'stopTranscription', 'transcriptionResult',
'startVideo', 'notifyHangup', 'handleStatusChanged',
])
const declarations = ast.statements.filter(node => ts.isFunctionDeclaration(node) && names.has(node.name?.text))
assert.equal(declarations.length, names.size)
@@ -29,8 +30,17 @@ function harness(options = {}) {
let transcriptionFinalized=false,transcriptionFinalizeRequested=false,transcriptionHadInterruption=false;
let transcriberRunning=false, transcriberManager=null, transcriberListener=null, transcriberRobotId='';
let transcriptionStartPromise=null, transcriptionStopPromise=null, lastTranscriberMessageAt=0, transcriberStoppedAt=0;
let starting=false, hangupNotification=null, contextGeneration=1, callCycleGeneration=0, chat=null;
let emittedRoomId='', pendingRoomId='', boundRoomId='', roomBindingSentAt=0, roomBindingAttempts=0;
let autoTranscriptionAttemptedGeneration=-1, autoLocalRecordingAttemptedGeneration=-1;
const statusText={value:''},mode={value:'chat'},localRecordingState={value:'idle'};
let localRecordingSessionId='',localRecordingMimeType='';
const patientFrameCapture={cancel(){}},tongueScreenshot={cancel(){}};
const appendVideoCallStatus=()=>{},nextTick=async()=>{},bindEngineRoomEvents=()=>{},pollRoomId=async()=>{};
const extractRoomFromEngineResult=()=>'',readRoomId=()=>'';
const startLocalRecording=async()=>{},stopLocalRecording=async()=>{},TUICallType={VIDEO_CALL:2};
const pendingTranscriptionStarts=new Map(),pendingTranscriptionStops=new Map(),pendingSegments=new Map(),acknowledgedSegmentIds=new Set();
const events=[],cloudCalls=[],removed=[],listeners=[],rooms=[],timers=new Map(); let timerId=0,sessionSequence=0,robotSequence=0,now=100000;
const events=[],cloudCalls=[],removed=[],listeners=[],rooms=[],destroyed=[],timers=new Map(); let timerId=0,sessionSequence=0,robotSequence=0,now=100000;
const native={session:'',ready:false,sealed:false,violations:[]};
const Date=class extends globalThis.Date { constructor(...args){super(...(args.length?args:[now]))} static now(){return now} };
const window={qtVideoBridge:{notify(){}},setTimeout(fn,ms){const id=++timerId;timers.set(id,{fn,at:now+ms});return id},clearTimeout(id){timers.delete(id)}};
@@ -53,14 +63,24 @@ function harness(options = {}) {
const safeErrorMessage=(error,fallback)=>error?.message||fallback;
const observeRoomId=room=>rooms.push(room);
const newTranscriptionSessionId=()=> 'tr-test-'+(++sessionSequence);
const manager={
const createManager=()=>({
addListener(listener){listeners.push(listener)},removeListener(listener){removed.push(listener)},
async startRealtimeTranscriber(config){cloudCalls.push({operation:'start',config});return options.start?options.start(): 'robot-'+(++robotSequence)},
async stopRealtimeTranscriber(robotId){cloudCalls.push({operation:'stop',robotId});options.onStop?.(listeners.at(-1));if(options.stopError)throw new Error('stop failed')},
destroy(){destroyed.push(this)},
});
const TUICallKitAPI={
getTUICallEngineInstance:()=>({getTRTCCloudInstance:()=>({getAITranscriberManager:()=>options.noManager?null:createManager()})}),
init:async()=>{},calls:async()=>handleStatusChanged({newStatus:'connected'}),
};
const TUICallKitAPI={getTUICallEngineInstance:()=>({getTRTCCloudInstance:()=>({getAITranscriberManager:()=>options.noManager?null:manager})})};
return {
start:startTranscription,stop:stopTranscription,events,cloudCalls,removed,listeners,rooms,timers,
start:startTranscription,stop:stopTranscription,events,cloudCalls,removed,listeners,rooms,timers,destroyed,
beginCall(){
native.session='';native.ready=false;native.sealed=false;
endNotified=true;
return startVideo();
},
endCall:()=>notifyHangup('remote-hangup'),
ack:transcriptionResult, pendingStop:()=>transcriptionStopPromise,native,
startAck(ok=true){const e=events.filter(e=>e.event==='transcription-start-request').at(-1);const accepted=ok&&native.session===e.sessionId&&!native.sealed;if(accepted)native.ready=true;transcriptionResult('start',e.sessionId,'',accepted,'')},
stopAck(ok=true){const e=events.filter(e=>e.event==='transcription-stop').at(-1);transcriptionResult('stop',e.sessionId,'',ok,'')},
@@ -357,3 +377,41 @@ test('a missing finish ACK times out and retries without clearing the current se
assert.equal(h.state().state,'idle')
assert.deepEqual(h.native.violations,[])
})
for (const stopError of [false, true]) {
test(`three calls in the same page each persist and render new captions (SDK stop fails=${stopError})`, async () => {
const h=harness({stopError})
const sessions=[]
let previousListener
for (let index=0;index<3;index++) {
await h.beginCall()
h.startAck()
await settle()
assert.equal(h.state().state,'recording')
const session=h.state().session
sessions.push(session)
assert.equal(h.state().captions.length,0)
const before=h.events.filter(e=>e.event==='transcription-segment').length
previousListener?.onReceiveTranscriberMessage('old-room',raw('stale'))
// SDK segment IDs may repeat across calls. They must use the new session.
h.segment(raw('repeat-1'))
const segments=h.events.filter(e=>e.event==='transcription-segment')
assert.equal(segments.length,before+1)
assert.equal(segments.at(-1).sessionId,session)
h.ack('segment',sessions[index-1]||'old-session','repeat-1',true,'',normalized('repeat-1'))
assert.equal(h.state().captions.length,0)
h.ack('segment',session,'repeat-1',true,'',normalized('repeat-1'))
assert.equal(h.state().captions[0].text,'头痛,没有发烧。')
previousListener=h.listeners.at(-1)
const ended=h.endCall()
await settle();await h.advance(600)
assert.equal(h.events.at(-1).status,stopError?'partial':'completed')
h.stopAck();await ended
}
assert.equal(new Set(sessions).size,3)
assert.equal(h.listeners.length,3)
assert.equal(h.removed.length,3)
assert.equal(h.destroyed.length,3)
assert.deepEqual(h.native.violations,[])
})
}
+188 -2
View File
@@ -56,14 +56,16 @@ function trtcEngine(room, params) {
return { getTRTCCloudInstance: () => ({ enterRoomParams: params, _room: room }) }
}
test('store room id wins, the TRTC instance is the fallback only while joined', () => {
test('the joined TRTC room wins over stale Store data, with Store fallback only without an engine', () => {
const joined = { isJoined: true, roomId: '123' }
assert.equal(harness({ store: '77', engine: trtcEngine(joined, { roomId: 123 }) }).readRoomId(), '77')
assert.equal(harness({ store: '77', engine: trtcEngine(joined, { roomId: 123 }) }).readRoomId(), '123')
assert.equal(harness({ store: '77', engine: null }).readRoomId(), '77')
assert.equal(harness({ store: 0, engine: trtcEngine(joined, { roomId: 123 }) }).readRoomId(), '123')
assert.equal(harness({ store: undefined, engine: trtcEngine({ isJoined: true }, { strRoomId: 'str-room' }) }).readRoomId(), 'str-room')
assert.equal(harness({ store: 0, engine: trtcEngine({ isJoined: true, roomId: 456 }, undefined) }).readRoomId(), '456')
// The previous call's room lingers on the TRTC instance after leaving: never bind it to the next call.
assert.equal(harness({ store: 0, engine: trtcEngine({ isJoined: false, roomId: '123' }, { roomId: 123 }) }).readRoomId(), '')
assert.equal(harness({ store: '123', engine: trtcEngine({ isJoined: false }, { roomId: 123 }) }).readRoomId(), '')
assert.equal(harness({ store: 0, engine: trtcEngine(undefined, { roomId: 123 }) }).readRoomId(), '')
assert.equal(harness({ store: '', engine: { getTRTCCloudInstance: () => null } }).readRoomId(), '')
assert.equal(harness({ store: '', engine: { getTRTCCloudInstance() { throw new Error('gone') } } }).readRoomId(), '')
@@ -72,6 +74,20 @@ test('store room id wins, the TRTC instance is the fallback only while joined',
assert.equal(harness({ store: '', engine: null }).readRoomId(), '')
})
test('the installed TRTCCloud wrapper exposes each call room on its inner v5 instance', () => {
const inner = { _room: { isJoined: true, roomId: '901' }, enterRoomParams: { roomId: 901 } }
const engine = { getTRTCCloudInstance: () => ({ _trtc: inner }) }
const h = harness({ store: 0, engine })
assert.equal(h.readRoomId(), '901')
// TRTC keeps the previous enter parameters after leaving the room.
inner._room.isJoined = false
assert.equal(h.readRoomId(), '')
inner.enterRoomParams = { roomId: 902 }
inner._room = { isJoined: true, roomId: '902' }
assert.equal(h.readRoomId(), '902')
})
test('engine call events bind the room even when the Store never learns it', () => {
const registered = []
const handlers = new Map()
@@ -138,3 +154,173 @@ test('empty room ids and finished calls never emit a bind request', () => {
assert.equal(h.observeRoomId('900'), false)
assert.equal(h.events.length, 0)
})
test('an unsolicited or ended-call binding acknowledgement cannot stop room discovery', () => {
const h = harness()
h.roomBindingResult('old-room', true, 'old acknowledgement')
assert.equal(h.bound(), '')
assert.equal(h.notice(), '')
h.observeRoomId('current-room')
h.end()
h.roomBindingResult('current-room', true, 'late acknowledgement')
assert.equal(h.bound(), '')
})
function callCycleHarness() {
const cycleNames = new Set(['startVideo', 'handleStatusChanged', 'pollRoomId', 'notifyHangup'])
const cycleSource = ast.statements
.filter(node => ts.isFunctionDeclaration(node) && cycleNames.has(node.name?.text))
.map(node => node.getText(ast)).join('\n')
const cycleCompiled = ts.transpileModule(cycleSource, {
compilerOptions: { target: ts.ScriptTarget.ES2022 },
}).outputText
return new Function(`${compiled}\n${cycleCompiled}
let activeConfig={SDKAppID:1,userID:'doctor_1',targetUserId:'patient_1',diagnosisId:501};
let endNotified=true, starting=false, hangupNotification=null, contextGeneration=1, callCycleGeneration=0;
let emittedRoomId='', pendingRoomId='', boundRoomId='', roomBindingSentAt=0, roomBindingAttempts=0;
let engineRoomEventsBound=null, chat=null, autoTranscriptionAttemptedGeneration=-1, autoLocalRecordingAttemptedGeneration=-1;
const phase={value:'ready'}, statusText={value:''}, mode={value:'chat'}, notice={value:''};
const transcriptionState={value:'idle'}, transcriptionError={value:''}, localRecordingState={value:'idle'};
let transcriptionSessionId='', transcriptionStorageReady=false, transcriptionFinalized=false;
let transcriptionFinalizeRequested=false, transcriptionHadInterruption=false, transcriberRunning=false, transcriberRobotId='';
let localRecordingSessionId='', localRecordingMimeType='';
const acknowledgedSegmentIds=new Set(), pendingSegments=new Map();
const clearLiveCaptions=()=>{}, appendVideoCallStatus=()=>{}, nextTick=async()=>{}, unsubscribeTranscriber=()=>{};
let transcriptionGeneration=0;
const patientFrameCapture={cancel(){}}, tongueScreenshot={cancel(){}};
const startTranscription=async()=>{}, startLocalRecording=async()=>{};
const stopTranscription=async()=>{}, stopLocalRecording=async()=>{};
const safeErrorMessage=(error)=>error.message;
let now=100000, onInit=()=>{};
const Date=class extends globalThis.Date { static now(){return now} };
const timers=[];
const window={setTimeout(callback, delay){timers.push({callback, at:now+delay})}};
const events=[], calls=[], emit=event=>events.push(event);
const inner={_room:{isJoined:false}, enterRoomParams:{roomId:0}};
const engine={getTRTCCloudInstance:()=>({_trtc:inner})};
const StoreName={CALL:'call'}, NAME={ROOM_ID:'roomId'}, TUICallType={VIDEO_CALL:2};
let storeRoomId=0;
const TUIStore={getData:()=>storeRoomId};
const TUICallKitAPI={
init:async()=>onInit(), getTUICallEngineInstance:()=>engine,
calls(params){
handleStatusChanged({newStatus:'dialing-c2c'});
return new Promise(resolve=>calls.push({params,resolve}));
},
};
return {
events, calls, startVideo, roomBindingResult, bound:()=>boundRoomId,
onInit(callback){onInit=callback},
updateStore(roomId){storeRoomId=roomId;emitRoomId()},
engineEvent:handleEngineRoomEvent,
join(roomId){inner._room={isJoined:true,roomId};inner.enterRoomParams={roomId}},
end(){inner._room.isJoined=false;handleStatusChanged({newStatus:'idle'})},
advance(ms){
now+=ms;
const due=timers.filter(timer=>timer.at<=now);
for(const timer of due){timers.splice(timers.indexOf(timer),1);timer.callback()}
},
};
`)()
}
const flushPromises = () => new Promise(resolve => setImmediate(resolve))
test('three calls in one open page each bind their room while calls() and Store stay pending', async () => {
const h = callCycleHarness()
const pendingCalls = []
for (const room of [901, 902, 903]) {
pendingCalls.push(h.startVideo())
await flushPromises()
assert.equal(h.calls.length, room - 900)
// The SDK has dispatched but neither resolved calls() nor emitted a room event.
assert.equal(h.events.filter(e => e.event === 'room').length, room - 901)
h.join(room)
h.advance(250)
await flushPromises()
const binding = h.events.filter(e => e.event === 'room').at(-1)
assert.equal(binding.roomId, String(room))
assert.equal(binding.diagnosisId, 501)
h.roomBindingResult(String(room), true, '')
assert.equal(h.bound(), String(room))
h.end()
await flushPromises()
}
assert.deepEqual(h.events.filter(e => e.event === 'room').map(e => e.roomId), ['901', '902', '903'])
// Delayed SDK completions after hangup must not report rooms or restore dialing.
const eventCount = h.events.length
h.calls.forEach((call, index) => call.resolve({ roomID: 901 + index }))
await Promise.all(pendingCalls)
assert.equal(h.events.length, eventCount)
})
test('redial ignores previous completion and acknowledgement, retries only the new room', async () => {
const h = callCycleHarness()
const first = h.startVideo()
await flushPromises()
h.join(901)
h.advance(250)
await flushPromises()
h.roomBindingResult('901', true, '')
h.end()
await flushPromises()
h.onInit(() => h.roomBindingResult('901', true, 'late first-call acknowledgement'))
const second = h.startVideo()
await flushPromises()
assert.equal(h.bound(), '')
h.calls[0].resolve({ roomID: 901 })
await first
h.join(902)
h.advance(250)
await flushPromises()
h.roomBindingResult('901', true, '')
assert.equal(h.bound(), '')
h.roomBindingResult('902', false, 'temporary failure')
h.advance(2000)
await flushPromises()
assert.deepEqual(h.events.filter(e => e.event === 'room').map(e => e.roomId), ['901', '902', '902'])
h.roomBindingResult('902', true, '')
assert.equal(h.bound(), '902')
h.end()
await flushPromises()
h.advance(20000)
await flushPromises()
h.calls[1].resolve()
await second
assert.equal(h.events.filter(e => e.event === 'room').length, 3)
})
for (const oldStoreArrivesAfterJoin of [false, true]) {
test(`old SDK completion cannot bind its Store room to a redial (joined=${oldStoreArrivesAfterJoin})`, async () => {
const h = callCycleHarness()
const first = h.startVideo()
await flushPromises()
h.join(901)
h.advance(250)
await flushPromises()
h.roomBindingResult('901', true, '')
h.end()
await flushPromises()
const second = h.startVideo()
await flushPromises()
if (oldStoreArrivesAfterJoin) h.join(902)
// CallKit updates ROOM_ID before the outer calls() Promise resolves. Its
// Store watcher must not relabel the previous room as this call's room.
h.updateStore(901)
h.engineEvent({ roomID: 901 })
h.calls[0].resolve()
await first
h.join(902)
h.advance(250)
await flushPromises()
assert.deepEqual(h.events.filter(e => e.event === 'room').map(e => e.roomId), ['901', '902'])
h.roomBindingResult('902', true, '')
assert.equal(h.bound(), '902')
h.end()
await flushPromises()
h.calls[1].resolve()
await second
})
}