Coverage for app / services / turns.py: 95%
86 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""The chat turns running in this process, and how to stop one.
3A chat turn runs to its end on the server whether or not the person is still
4on the page (``app/services/chat_socket.py``). So a page they come back to
5has to be able to learn that an answer is still being written — and Stop has
6to reach a turn that another page, or an earlier visit, started. This
7registry is both: every running turn, whose it is, which conversation it
8will be stored in, what it is doing, and a way to stop it.
10It is held in memory because a turn is: a turn is a task in this process and
11ends with it. svc-core runs as one process (one uvicorn worker, one
12replica); serving it from more than one would need this registry, and the
13stop signal with it, behind a store they share.
15A turn is registered when it starts and leaves the registry only once it has
16been stored, so a page that sees a turn disappear can read the conversation
17and find the answer there.
18"""
20from __future__ import annotations
22import threading
23from collections.abc import Callable, Iterator
24from contextlib import contextmanager
25from dataclasses import dataclass, field
26from datetime import datetime
27from typing import Any, Literal
28from uuid import UUID, uuid4
30from app.util.time import aware_utcnow
32TurnKind = Literal["agent", "model"]
33TurnStatus = Literal["running", "awaiting_input"]
35#: What a turn stopped before it wrote anything is stored as — what fe-core
36#: shows for it at the moment of stopping (agent ``Chat.tsx`` ``handleStop``).
37STOPPED_TEXT = "*Generation stopped.*"
39#: Why a second turn in a conversation is refused while one is running: its
40#: history would not hold the first one's answer.
41CONFLICT_MESSAGE = (
42 "This conversation is still answering an earlier message. Wait for it "
43 "to finish, or stop it, before sending another."
44)
47class TurnStopped(Exception):
48 """The person pressed Stop: the turn ends where it is.
50 ``partial`` is what it had written by then, when the code that stopped it
51 collected it.
52 """
54 def __init__(self, partial: str = "") -> None:
55 super().__init__("The turn was stopped.")
56 self.partial = partial
59class TurnConflict(Exception):
60 """A turn is already running in this conversation for this person."""
62 def __init__(self, running: RunningTurn) -> None:
63 super().__init__(CONFLICT_MESSAGE)
64 self.running = running
67@dataclass(eq=False)
68class RunningTurn:
69 """One turn while it runs. ``prompt`` and ``meta`` are the person's
70 message as it will be stored — set once the input rules have run, so a
71 page shows what the conversation will hold, redactions included."""
73 id: str
74 kind: TurnKind
75 user_id: str
76 target_id: str
77 conversation_id: str
78 workspace: str | None
79 started_at: datetime
80 status: TurnStatus = "running"
81 prompt: str | None = None
82 meta: dict[str, Any] | None = None
83 #: Stop was asked for; the turn is winding down.
84 stopping: bool = False
85 _hook: Callable[[], None] | None = field(default=None, repr=False)
86 _lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
88 def on_stop(self, hook: Callable[[], None] | None) -> None:
89 """What Stop does to this turn now — cancel the step it is waiting
90 on. Run at once when Stop was already asked for. The hook may be
91 called from any thread, so it must hand work to its own loop."""
92 with self._lock:
93 self._hook = hook
94 fire = hook is not None and self.stopping
95 if fire and hook is not None:
96 hook()
98 def stop(self) -> None:
99 """Ask the turn to stop. Once is enough; later asks change nothing."""
100 with self._lock:
101 if self.stopping:
102 return
103 self.stopping = True
104 hook = self._hook
105 if hook is not None:
106 hook()
109class TurnRegistry:
110 """The running turns, by id. Safe to use from any thread."""
112 def __init__(self) -> None:
113 self._lock = threading.Lock()
114 self._turns: dict[str, RunningTurn] = {}
116 def start(
117 self,
118 *,
119 kind: TurnKind,
120 user_id: str,
121 target_id: str,
122 conversation_id: str,
123 workspace: str | None = None,
124 turn_id: str | UUID | None = None,
125 ) -> RunningTurn:
126 """Register a turn that is starting.
128 ``turn_id`` is the client's own, when it minted one to stop the turn
129 by. Raises ``TurnConflict`` when this person already has a turn
130 running in the conversation (one being stopped does not count), and
131 ``ValueError`` for an id already in use.
132 """
133 turn = RunningTurn(
134 id=str(turn_id or uuid4()),
135 kind=kind,
136 user_id=str(user_id),
137 target_id=str(target_id),
138 conversation_id=str(conversation_id),
139 workspace=workspace,
140 started_at=aware_utcnow(),
141 )
142 with self._lock:
143 if turn.id in self._turns:
144 raise ValueError(f"Turn id {turn.id} is already in use.")
145 for running in self._turns.values():
146 if (
147 running.user_id == turn.user_id
148 and running.conversation_id == turn.conversation_id
149 and not running.stopping
150 ):
151 raise TurnConflict(running)
152 self._turns[turn.id] = turn
153 return turn
155 def finish(self, turn: RunningTurn) -> None:
156 """The turn is stored (or given up): it is no longer running."""
157 with self._lock:
158 if self._turns.get(turn.id) is turn:
159 del self._turns[turn.id]
161 @contextmanager
162 def track(self, **start: Any) -> Iterator[RunningTurn]:
163 """``start`` a turn for the block, and ``finish`` it however the
164 block ends."""
165 turn = self.start(**start)
166 try:
167 yield turn
168 finally:
169 self.finish(turn)
171 def running(
172 self,
173 user_id: str,
174 *,
175 kind: TurnKind | None = None,
176 target_id: str | None = None,
177 workspace: str | None = None,
178 ) -> list[RunningTurn]:
179 """This person's running turns, oldest first, narrowed to a kind,
180 a target and — for a turn that has one — a workspace."""
181 with self._lock:
182 turns = list(self._turns.values())
183 return sorted(
184 (
185 t
186 for t in turns
187 if t.user_id == str(user_id)
188 and (kind is None or t.kind == kind)
189 and (target_id is None or t.target_id == str(target_id))
190 and (workspace is None or t.workspace in (None, workspace))
191 ),
192 key=lambda t: t.started_at,
193 )
195 def stop(self, turn_id: str, user_id: str) -> bool:
196 """Stop this person's turn ``turn_id``; False when they have none
197 running by that id."""
198 with self._lock:
199 turn = self._turns.get(str(turn_id))
200 if turn is None or turn.user_id != str(user_id):
201 return False
202 turn.stop()
203 return True
206#: The process's registry.
207registry = TurnRegistry()