Coverage for app / services / chat_socket.py: 97%

91 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1"""The websocket a chat turn reports to — and does not depend on. 

2 

3A chat turn is paid for from its first model call, and the person may close 

4the page before it ends. The turn runs to its end either way and is stored 

5exactly as it would have been, so they come back to the answer rather than 

6to a half-run that was paid for and thrown away. So nothing the socket does 

7reaches the turn: a send to a client that has gone is dropped, never raised. 

8 

9Leaving is not stopping. fe-core's Stop button sends ``{"type": "stop"}`` 

10before it closes the socket; that, or a Stop for the turn from another page 

11(``stop_soon``, through ``app/services/turns.py``), cancels the step the 

12turn is waiting on (``run``), which closes svc-ai's stream and with it the 

13graph run, and ends the turn with ``TurnStopped``. 

14 

15A pause for a person (``next_message``) is the one thing a turn cannot 

16finish alone: once the client has gone, or stopped, it is answered with 

17None and the route records the question as unanswered. 

18""" 

19 

20from __future__ import annotations 

21 

22import asyncio 

23import contextlib 

24import json 

25import logging 

26from collections.abc import Awaitable 

27from typing import Any, TypeVar 

28 

29from fastapi import WebSocket 

30 

31from app.services.turns import TurnStopped 

32 

33logger = logging.getLogger(__name__) 

34 

35T = TypeVar("T") 

36 

37#: The frame fe-core's Stop button sends before it closes the socket. 

38STOP = "stop" 

39 

40 

41class ChatSocket: 

42 """A turn's websocket: sends that cannot fail, and a reader for what the 

43 client sends while the turn runs (Stop, a pause's answers). 

44 

45 ``listen()`` once the opening frame has been read; ``close()`` when the 

46 turn is over. 

47 """ 

48 

49 def __init__(self, websocket: WebSocket) -> None: 

50 self._ws = websocket 

51 # What the client sent besides Stop, in order; None once nobody can 

52 # send anything more. 

53 self._inbox: asyncio.Queue[dict | None] = asyncio.Queue() 

54 self._reader: asyncio.Task | None = None 

55 self._loop: asyncio.AbstractEventLoop | None = None 

56 # The step Stop cancels, while the turn is waiting on one. 

57 self._step: asyncio.Future | None = None 

58 #: The client has closed the socket (or it failed). 

59 self.gone = False 

60 #: The client pressed Stop. 

61 self.stopped = False 

62 

63 async def send(self, frame: dict[str, Any]) -> None: 

64 """Send ``frame`` while anyone is reading; drop it once nobody is.""" 

65 if self.gone: 

66 return 

67 try: 

68 await self._ws.send_text(json.dumps(frame)) 

69 except Exception: # noqa: BLE001 — any failure means nobody is reading 

70 self._leave() 

71 

72 def listen(self) -> None: 

73 """Start reading what the client sends while the turn runs.""" 

74 if self._reader is None: 

75 self._loop = asyncio.get_running_loop() 

76 self._reader = asyncio.create_task(self._read()) 

77 

78 def stop_soon(self) -> None: 

79 """Stop the turn as if the client had pressed Stop — for a Stop from 

80 another page. Safe from any thread.""" 

81 if self._loop is not None and not self._loop.is_closed(): 

82 self._loop.call_soon_threadsafe(self._stop) 

83 

84 async def next_message(self) -> dict | None: 

85 """The next frame the client sent — a pause's answer — or None once 

86 it has stopped the turn or gone.""" 

87 if not self._inbox.empty(): 

88 return self._inbox.get_nowait() 

89 if self.gone or self.stopped: 

90 return None 

91 return await self._inbox.get() 

92 

93 async def run(self, step: Awaitable[T]) -> T: 

94 """Await ``step`` so that Stop can cancel it. 

95 

96 Raises ``TurnStopped`` when Stop cancelled it, or was pressed before 

97 it began (it is then never started). Any other cancellation — the 

98 server shutting down — propagates as it is. 

99 """ 

100 if self.stopped: 

101 if asyncio.iscoroutine(step): 

102 step.close() 

103 raise TurnStopped 

104 task = asyncio.ensure_future(step) 

105 self._step = task 

106 try: 

107 return await task 

108 except asyncio.CancelledError: 

109 current = asyncio.current_task() 

110 ours = self.stopped and task.cancelled() 

111 if ours and not (current is not None and current.cancelling()): 

112 raise TurnStopped from None 

113 raise 

114 finally: 

115 self._step = None 

116 

117 async def close(self) -> None: 

118 """Stop reading, and close the socket if the client has not.""" 

119 if self._reader is not None: 

120 self._reader.cancel() 

121 with contextlib.suppress(asyncio.CancelledError, Exception): 

122 await self._reader 

123 if not self.gone: 

124 with contextlib.suppress(Exception): 

125 await self._ws.close() 

126 

127 async def _read(self) -> None: 

128 try: 

129 while True: 

130 message = await self._ws.receive_json() 

131 if isinstance(message, dict) and message.get("type") == STOP: 

132 self._stop() 

133 return 

134 # Anything else is for the turn to judge: a pause's answer, 

135 # or not one (which the pause refuses). 

136 await self._inbox.put(message if isinstance(message, dict) else {}) 

137 except asyncio.CancelledError: 

138 raise 

139 except Exception: # noqa: BLE001 — a disconnect, or a frame that is not JSON 

140 self._leave() 

141 

142 def _stop(self) -> None: 

143 if self.stopped: 

144 return 

145 self.stopped = True 

146 logger.info("Chat turn stopped by the person; ending it.") 

147 if self._step is not None: 

148 self._step.cancel() 

149 self._inbox.put_nowait(None) 

150 

151 def _leave(self) -> None: 

152 if self.gone: 

153 return 

154 self.gone = True 

155 logger.info("Chat client left; the turn carries on and will be saved.") 

156 self._inbox.put_nowait(None)