NeonClary Cursor commited on
Commit
9a51d6a
·
1 Parent(s): d58dc6d

perf(orchestrator): prefetch human-phase opinions and tighten context budget

Browse files

Fire all LLM initial-opinion calls in parallel while waiting on the human participant, compress embedded transcript blocks when over budget, surface phase banners and inline system notes in the chat timeline, and propagate Neon vLLM error metadata for resilience.

Co-authored-by: Cursor <cursoragent@cursor.com>

backend/app/clients/llm_router.py CHANGED
@@ -180,6 +180,9 @@ async def _call_neon_direct_vllm(
180
  "response": strip_thinking(result.get("response", "")),
181
  "elapsed_seconds": result.get("elapsed_seconds", 0),
182
  "model": resolved["model_id"],
 
 
 
183
  }
184
 
185
 
 
180
  "response": strip_thinking(result.get("response", "")),
181
  "elapsed_seconds": result.get("elapsed_seconds", 0),
182
  "model": resolved["model_id"],
183
+ "error": result.get("error", False),
184
+ "error_kind": result.get("error_kind", ""),
185
+ "error_status": result.get("error_status"),
186
  }
187
 
188
 
backend/app/services/context_budget.py CHANGED
@@ -175,6 +175,87 @@ def build_compressed_messages(
175
  return head + [summary_msg] + tail
176
 
177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  # ---------------------------------------------------------------------------
179
  # Run a summarize call against the configured summarizer model
180
  # ---------------------------------------------------------------------------
 
175
  return head + [summary_msg] + tail
176
 
177
 
178
+ # ---------------------------------------------------------------------------
179
+ # Compress transcript embedded inside a single user prompt (CCAI pattern)
180
+ # ---------------------------------------------------------------------------
181
+ #
182
+ # Phase prompts bake the full transcript into one user message, e.g.
183
+ # "Conversation so far:\n{transcript}\n\nIn 4-8 sentences:…". The AskJerry
184
+ # multi-message trim path never fires because api_messages only has
185
+ # [system, user]. These helpers swap the transcript body for summary+tail.
186
+
187
+ _TRANSCRIPT_HEADERS: tuple[str, ...] = (
188
+ "Conversation so far:\n",
189
+ "Full conversation so far:\n",
190
+ "Full transcript:\n",
191
+ "Full conversation:\n",
192
+ )
193
+
194
+ # Section headers that typically follow the transcript block in phase prompts.
195
+ _TRANSCRIPT_FOOTERS: tuple[str, ...] = (
196
+ "\n\nOpen threads",
197
+ "\n\nIn ",
198
+ "\n\nFIRST",
199
+ "\n\nThe orchestrator",
200
+ "\n\nRight now",
201
+ "\n\nPhase ",
202
+ "\n\nQuestion:\n",
203
+ "\n\nCredential Summary:\n",
204
+ "\n\nBelow is",
205
+ "\n\nTargeted question:\n",
206
+ )
207
+
208
+
209
+ def replace_embedded_transcript(user_prompt: str, new_transcript: str) -> str:
210
+ """Replace the transcript body inside a phase prompt, if a known header exists."""
211
+ for header in _TRANSCRIPT_HEADERS:
212
+ idx = user_prompt.find(header)
213
+ if idx < 0:
214
+ continue
215
+ start = idx + len(header)
216
+ rest = user_prompt[start:]
217
+ end = len(rest)
218
+ for footer in _TRANSCRIPT_FOOTERS:
219
+ pos = rest.find(footer)
220
+ if pos >= 0:
221
+ end = min(end, pos)
222
+ return user_prompt[:start] + new_transcript + rest[end:]
223
+ return user_prompt
224
+
225
+
226
+ def build_compressed_transcript_block(
227
+ summary: ContextSummary,
228
+ recent_transcript: str,
229
+ ) -> str:
230
+ """AskJerry-style block: running summary + recent tail."""
231
+ recent = (recent_transcript or "").strip()
232
+ if summary.is_active():
233
+ body = (
234
+ "[Earlier discussion summary]\n"
235
+ + summary.summary_text.strip()
236
+ )
237
+ if recent:
238
+ body += "\n\n[Recent messages]\n" + recent
239
+ return body
240
+ if recent:
241
+ return "[Recent messages — auto-trimmed for context]\n" + recent
242
+ return ""
243
+
244
+
245
+ def cap_max_tokens_for_window(
246
+ model_id: str,
247
+ api_messages: list[dict[str, Any]],
248
+ requested_max_tokens: int,
249
+ ) -> int:
250
+ """Shrink reply budget so input + output fits the model window (AskJerry)."""
251
+ window = context_window_for(model_id)
252
+ est = estimate_messages_tokens(api_messages)
253
+ headroom = window - est - 64
254
+ if headroom < 256:
255
+ return max(64, min(requested_max_tokens, headroom))
256
+ return min(requested_max_tokens, headroom)
257
+
258
+
259
  # ---------------------------------------------------------------------------
260
  # Run a summarize call against the configured summarizer model
261
  # ---------------------------------------------------------------------------
backend/app/services/orchestrator.py CHANGED
@@ -43,9 +43,11 @@ from app.services.context_budget import (
43
  ContextSummary,
44
  DEFAULT_REPLY_BUDGET,
45
  KEEP_RECENT_MESSAGES,
46
- build_compressed_messages,
 
47
  context_window_for,
48
  estimate_messages_tokens,
 
49
  run_summarize,
50
  select_summarizer_model_id,
51
  should_summarize,
@@ -61,6 +63,7 @@ from app.services.orchestrator_speed import (
61
  _AiTurnSpec,
62
  compact_transcript_for_orchestrator,
63
  orchestrator_fast_model_id,
 
64
  run_roster_ai_turns_parallel,
65
  )
66
  from app.services.resilience import run_resilient_turn
@@ -298,7 +301,8 @@ async def _wait_for_continue(
298
  else:
299
  session.orchestrator_call_cap += bump_inc
300
  session.pause_reason = None
301
- yield _sse("status", {"message": "Resuming conversation..."})
 
302
 
303
 
304
  # ---------------------------------------------------------------------------
@@ -546,13 +550,38 @@ async def _call_participant(
546
 
547
  await _maybe_summarize_for_participant(session, participant, api_messages)
548
 
549
- needs_sum, needs_trim, _ = should_summarize(
550
  participant.model_id, api_messages, participant.summary,
551
  )
552
- if needs_trim:
553
- api_messages = build_compressed_messages(
554
- api_messages, participant.summary, needs_trim,
 
 
 
 
 
 
 
 
555
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
556
 
557
  resolved = {
558
  "model_id": participant.model_id,
@@ -699,13 +728,53 @@ def _msg_payload(msg: dict[str, Any]) -> dict[str, Any]:
699
  return msg
700
 
701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
702
  # ---------------------------------------------------------------------------
703
  # Phase implementations
704
  # ---------------------------------------------------------------------------
705
 
706
  async def _phase_initial_opinions(session: Session) -> AsyncIterator[str]:
707
  session.phase = Phase.INITIAL_OPINIONS
708
- yield _sse("status", {"message": "Phase 1: collecting independent first opinions..."})
 
 
 
709
 
710
  actives = _active_participants(session)
711
 
@@ -734,10 +803,9 @@ async def _phase_initial_opinions(session: Session) -> AsyncIterator[str]:
734
  max_tokens=700,
735
  )
736
 
737
- async for chunk in run_roster_ai_turns_parallel(
738
  session,
739
  actives,
740
- phase=session.phase,
741
  build_spec=_build_initial_spec,
742
  call_participant=_call_participant,
743
  on_human_turn=_human_initial,
@@ -745,7 +813,8 @@ async def _phase_initial_opinions(session: Session) -> AsyncIterator[str]:
745
  ):
746
  yield chunk
747
 
748
- yield _sse("status", {"message": "Building Credential Summary..."})
 
749
  creds = await build_credential_summary(
750
  orchestrator_model_id=_orchestrator_model_id(session),
751
  question=session.question,
@@ -784,9 +853,11 @@ def _critique_phase_for(round_number: int) -> Phase:
784
  async def _phase_critique(session: Session, round_number: int) -> AsyncIterator[str]:
785
  session.phase = _critique_phase_for(round_number)
786
  round_total = session.limits.critique_rounds
787
- yield _sse("status", {
788
- "message": f"Phase 2: critique round {round_number} of {round_total}...",
789
- })
 
 
790
  cred_block = credentials_to_block(session.credential_summary)
791
  actives = _active_participants(session)
792
  # Freeze transcript + pending threads at round start so parallel
@@ -859,7 +930,10 @@ async def _phase_critique(session: Session, round_number: int) -> AsyncIterator[
859
 
860
  async def _phase_status_assessment(session: Session) -> AsyncIterator[str]:
861
  session.phase = Phase.STATUS_ASSESSMENT
862
- yield _sse("status", {"message": "Phase 3: assessing whether more questions are needed..."})
 
 
 
863
 
864
  cred_block = credentials_to_block(session.credential_summary)
865
  cred_refreshed = False
@@ -996,10 +1070,8 @@ async def _phase_status_assessment(session: Session) -> AsyncIterator[str]:
996
  for ev in turn.sse_events:
997
  yield ev
998
  if not turn.ok:
999
- yield _sse("participant_error", {
1000
- "participant_id": target.participant_id, "name": target.name,
1001
- "phase": session.phase.value,
1002
- })
1003
  continue
1004
  speaker = turn.speaker
1005
  text, elapsed = turn.text, turn.elapsed
@@ -1031,7 +1103,8 @@ async def _phase_status_assessment(session: Session) -> AsyncIterator[str]:
1031
 
1032
  async def _phase_finalization(session: Session) -> AsyncIterator[str]:
1033
  session.phase = Phase.FINALIZATION
1034
- yield _sse("status", {"message": "Phase 4: opinion finalization..."})
 
1035
 
1036
  cred_block = credentials_to_block(session.credential_summary)
1037
  actives = _active_participants(session)
@@ -1089,7 +1162,8 @@ async def _phase_finalization(session: Session) -> AsyncIterator[str]:
1089
 
1090
  async def _phase_consensus(session: Session) -> AsyncIterator[str]:
1091
  session.phase = Phase.CONSENSUS
1092
- yield _sse("status", {"message": "Phase 5: consensus gathering..."})
 
1093
 
1094
  cred_block = credentials_to_block(session.credential_summary)
1095
  actives = _active_participants(session)
@@ -1108,7 +1182,12 @@ async def _phase_consensus(session: Session) -> AsyncIterator[str]:
1108
  # Render alliance group members using the same display names shown
1109
  # in the sidebar (Participant.name), not raw participant_ids.
1110
  id_to_name = {p.participant_id: p.name for p in actives}
1111
- announce = "Alliance groups detected: " + "; ".join(
 
 
 
 
 
1112
  f"\"{g.get('stance', '')}\" -> ["
1113
  + ", ".join(
1114
  id_to_name.get(m, m) for m in (g.get("members") or [])
@@ -1139,6 +1218,10 @@ async def _phase_consensus(session: Session) -> AsyncIterator[str]:
1139
 
1140
  while consensus_turns < max_consensus_turns:
1141
  consensus_turns += 1
 
 
 
 
1142
 
1143
  # Pick speaker. Prefer the addressed-to target (dyadic exchange)
1144
  # only while we're under the consecutive-routing cap. Once the
@@ -1216,10 +1299,8 @@ async def _phase_consensus(session: Session) -> AsyncIterator[str]:
1216
  for ev in turn.sse_events:
1217
  yield ev
1218
  if not turn.ok:
1219
- yield _sse("participant_error", {
1220
- "participant_id": speaker.participant_id, "name": speaker.name,
1221
- "phase": session.phase.value,
1222
- })
1223
  continue
1224
  # Consensus phase doesn't swap participants, only LLMs behind
1225
  # them, so turn.speaker is the same instance as `speaker`. Use
@@ -1394,7 +1475,8 @@ def _build_consensus_prompt(
1394
 
1395
  async def _phase_closure(session: Session) -> AsyncIterator[str]:
1396
  session.phase = Phase.CLOSURE
1397
- yield _sse("status", {"message": "Phase 6: closure..."})
 
1398
 
1399
  cred_block = credentials_to_block(session.credential_summary)
1400
  transcript = await compact_transcript_for_orchestrator(
 
43
  ContextSummary,
44
  DEFAULT_REPLY_BUDGET,
45
  KEEP_RECENT_MESSAGES,
46
+ build_compressed_transcript_block,
47
+ cap_max_tokens_for_window,
48
  context_window_for,
49
  estimate_messages_tokens,
50
+ replace_embedded_transcript,
51
  run_summarize,
52
  select_summarizer_model_id,
53
  should_summarize,
 
63
  _AiTurnSpec,
64
  compact_transcript_for_orchestrator,
65
  orchestrator_fast_model_id,
66
+ run_initial_opinions_roster,
67
  run_roster_ai_turns_parallel,
68
  )
69
  from app.services.resilience import run_resilient_turn
 
301
  else:
302
  session.orchestrator_call_cap += bump_inc
303
  session.pause_reason = None
304
+ for chunk in _orchestrator_banner_sse(session, "Resuming conversation..."):
305
+ yield chunk
306
 
307
 
308
  # ---------------------------------------------------------------------------
 
550
 
551
  await _maybe_summarize_for_participant(session, participant, api_messages)
552
 
553
+ needs_sum, needs_trim, input_budget = should_summarize(
554
  participant.model_id, api_messages, participant.summary,
555
  )
556
+
557
+ # CCAI embeds the transcript inside the user prompt. When over budget,
558
+ # swap that block for summary + recent tail (AskJerry pattern).
559
+ if needs_sum or needs_trim:
560
+ recent_transcript = _format_history(
561
+ session.messages[-KEEP_RECENT_MESSAGES:],
562
+ include_orchestrator=False,
563
+ )
564
+ compressed_block = build_compressed_transcript_block(
565
+ participant.summary,
566
+ recent_transcript,
567
  )
568
+ if compressed_block:
569
+ new_prompt = replace_embedded_transcript(user_prompt, compressed_block)
570
+ user_prompt = new_prompt
571
+ api_messages[1] = {"role": "user", "content": user_prompt}
572
+ elif len(user_prompt) > input_budget * 4:
573
+ # Last-resort: keep prompt head + tail if no transcript header matched.
574
+ keep = max(512, input_budget * 2)
575
+ user_prompt = (
576
+ user_prompt[:keep]
577
+ + "\n\n[…middle truncated for context…]\n\n"
578
+ + user_prompt[-keep:]
579
+ )
580
+ api_messages[1] = {"role": "user", "content": user_prompt}
581
+
582
+ max_tokens = cap_max_tokens_for_window(
583
+ participant.model_id, api_messages, max_tokens,
584
+ )
585
 
586
  resolved = {
587
  "model_id": participant.model_id,
 
728
  return msg
729
 
730
 
731
+ def _orchestrator_banner_sse(
732
+ session: Session,
733
+ text: str,
734
+ *,
735
+ kind: str = "status",
736
+ extra: dict[str, Any] | None = None,
737
+ ) -> list[str]:
738
+ """Append an orchestrator line to the transcript and emit chat + status SSE."""
739
+ msg = _add_orchestrator_message(session, text, kind=kind, extra=extra)
740
+ return [
741
+ _sse("orchestrator", _msg_payload(msg)),
742
+ _sse("status", {"message": text}),
743
+ ]
744
+
745
+
746
+ def _participant_turn_failure_sse(
747
+ session: Session,
748
+ participant: Participant,
749
+ ) -> list[str]:
750
+ """Emit participant_error and auto-disable banner when threshold hit."""
751
+ out = [
752
+ _sse("participant_error", {
753
+ "participant_id": participant.participant_id,
754
+ "name": participant.name,
755
+ "phase": session.phase.value,
756
+ }),
757
+ ]
758
+ if participant.consecutive_failures >= session.limits.auto_disable_failures:
759
+ participant.enabled = False
760
+ out.extend(_orchestrator_banner_sse(
761
+ session,
762
+ f"{participant.name} auto-disabled after "
763
+ f"{session.limits.auto_disable_failures} consecutive failures.",
764
+ ))
765
+ return out
766
+
767
+
768
  # ---------------------------------------------------------------------------
769
  # Phase implementations
770
  # ---------------------------------------------------------------------------
771
 
772
  async def _phase_initial_opinions(session: Session) -> AsyncIterator[str]:
773
  session.phase = Phase.INITIAL_OPINIONS
774
+ for chunk in _orchestrator_banner_sse(
775
+ session, "Phase 1: collecting independent first opinions...",
776
+ ):
777
+ yield chunk
778
 
779
  actives = _active_participants(session)
780
 
 
803
  max_tokens=700,
804
  )
805
 
806
+ async for chunk in run_initial_opinions_roster(
807
  session,
808
  actives,
 
809
  build_spec=_build_initial_spec,
810
  call_participant=_call_participant,
811
  on_human_turn=_human_initial,
 
813
  ):
814
  yield chunk
815
 
816
+ for chunk in _orchestrator_banner_sse(session, "Building Credential Summary..."):
817
+ yield chunk
818
  creds = await build_credential_summary(
819
  orchestrator_model_id=_orchestrator_model_id(session),
820
  question=session.question,
 
853
  async def _phase_critique(session: Session, round_number: int) -> AsyncIterator[str]:
854
  session.phase = _critique_phase_for(round_number)
855
  round_total = session.limits.critique_rounds
856
+ for chunk in _orchestrator_banner_sse(
857
+ session,
858
+ f"Phase 2: critique round {round_number} of {round_total}...",
859
+ ):
860
+ yield chunk
861
  cred_block = credentials_to_block(session.credential_summary)
862
  actives = _active_participants(session)
863
  # Freeze transcript + pending threads at round start so parallel
 
930
 
931
  async def _phase_status_assessment(session: Session) -> AsyncIterator[str]:
932
  session.phase = Phase.STATUS_ASSESSMENT
933
+ for chunk in _orchestrator_banner_sse(
934
+ session, "Phase 3: assessing whether more questions are needed...",
935
+ ):
936
+ yield chunk
937
 
938
  cred_block = credentials_to_block(session.credential_summary)
939
  cred_refreshed = False
 
1070
  for ev in turn.sse_events:
1071
  yield ev
1072
  if not turn.ok:
1073
+ for chunk in _participant_turn_failure_sse(session, target):
1074
+ yield chunk
 
 
1075
  continue
1076
  speaker = turn.speaker
1077
  text, elapsed = turn.text, turn.elapsed
 
1103
 
1104
  async def _phase_finalization(session: Session) -> AsyncIterator[str]:
1105
  session.phase = Phase.FINALIZATION
1106
+ for chunk in _orchestrator_banner_sse(session, "Phase 4: opinion finalization..."):
1107
+ yield chunk
1108
 
1109
  cred_block = credentials_to_block(session.credential_summary)
1110
  actives = _active_participants(session)
 
1162
 
1163
  async def _phase_consensus(session: Session) -> AsyncIterator[str]:
1164
  session.phase = Phase.CONSENSUS
1165
+ for chunk in _orchestrator_banner_sse(session, "Phase 5: consensus gathering..."):
1166
+ yield chunk
1167
 
1168
  cred_block = credentials_to_block(session.credential_summary)
1169
  actives = _active_participants(session)
 
1182
  # Render alliance group members using the same display names shown
1183
  # in the sidebar (Participant.name), not raw participant_ids.
1184
  id_to_name = {p.participant_id: p.name for p in actives}
1185
+ alliance_prefix = (
1186
+ "Updated alliance groups detected: "
1187
+ if session.consensus_attempts > 0
1188
+ else "Alliance groups detected: "
1189
+ )
1190
+ announce = alliance_prefix + "; ".join(
1191
  f"\"{g.get('stance', '')}\" -> ["
1192
  + ", ".join(
1193
  id_to_name.get(m, m) for m in (g.get("members") or [])
 
1218
 
1219
  while consensus_turns < max_consensus_turns:
1220
  consensus_turns += 1
1221
+ actives = _active_participants(session)
1222
+ if len(actives) < 2:
1223
+ break
1224
+ queue = [p for p in queue if p.enabled]
1225
 
1226
  # Pick speaker. Prefer the addressed-to target (dyadic exchange)
1227
  # only while we're under the consecutive-routing cap. Once the
 
1299
  for ev in turn.sse_events:
1300
  yield ev
1301
  if not turn.ok:
1302
+ for chunk in _participant_turn_failure_sse(session, speaker):
1303
+ yield chunk
 
 
1304
  continue
1305
  # Consensus phase doesn't swap participants, only LLMs behind
1306
  # them, so turn.speaker is the same instance as `speaker`. Use
 
1475
 
1476
  async def _phase_closure(session: Session) -> AsyncIterator[str]:
1477
  session.phase = Phase.CLOSURE
1478
+ for chunk in _orchestrator_banner_sse(session, "Phase 6: closure..."):
1479
+ yield chunk
1480
 
1481
  cred_block = credentials_to_block(session.credential_summary)
1482
  transcript = await compact_transcript_for_orchestrator(
backend/app/services/orchestrator_speed.py CHANGED
@@ -177,6 +177,7 @@ async def run_roster_ai_turns_parallel(
177
  from app.services.orchestrator import (
178
  _msg_payload,
179
  _participant_msg_cap_hit,
 
180
  _sse,
181
  _wait_for_continue,
182
  )
@@ -237,6 +238,104 @@ async def run_roster_ai_turns_parallel(
237
  yield chunk
238
 
239
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  async def _emit_ai_turn_result(
241
  session: "Session",
242
  result: _AiTurnResult,
@@ -249,6 +348,7 @@ async def _emit_ai_turn_result(
249
  _add_participant_message,
250
  _msg_payload,
251
  _orchestrator_cap_hit,
 
252
  _replying_to_ids,
253
  _sse,
254
  _wait_for_continue,
@@ -259,19 +359,8 @@ async def _emit_ai_turn_result(
259
  for ev in turn.sse_events:
260
  yield ev
261
  if not turn.ok:
262
- yield _sse("participant_error", {
263
- "participant_id": p.participant_id,
264
- "name": p.name,
265
- "phase": phase.value,
266
- })
267
- if p.consecutive_failures >= session.limits.auto_disable_failures:
268
- p.enabled = False
269
- yield _sse("status", {
270
- "message": (
271
- f"{p.name} auto-disabled after "
272
- f"{session.limits.auto_disable_failures} failures."
273
- ),
274
- })
275
  return
276
 
277
  speaker = turn.speaker
 
177
  from app.services.orchestrator import (
178
  _msg_payload,
179
  _participant_msg_cap_hit,
180
+ _participant_turn_failure_sse,
181
  _sse,
182
  _wait_for_continue,
183
  )
 
238
  yield chunk
239
 
240
 
241
+ async def run_initial_opinions_roster(
242
+ session: "Session",
243
+ actives: list["Participant"],
244
+ *,
245
+ build_spec: Callable[["Participant"], _AiTurnSpec | None],
246
+ call_participant: CallParticipantFn,
247
+ on_human_turn: Callable[
248
+ ["Participant"],
249
+ AsyncIterator[str],
250
+ ],
251
+ post_process: PostProcessFn | None = None,
252
+ ) -> AsyncIterator[str]:
253
+ """Phase-1 roster walk with human-aware AI prefetch.
254
+
255
+ When a human is in the roster, every AI participant's initial-
256
+ opinion call is fired immediately (in parallel) so answers are ready
257
+ while the human types. SSE ``message`` events are still emitted in
258
+ roster order: any LLMs listed before the human appear as soon as
259
+ their prefetch completes, and LLMs after the human stay hidden until
260
+ the human submits (or skips).
261
+ """
262
+ from app.services.models import Phase
263
+ from app.services.orchestrator import (
264
+ _participant_msg_cap_hit,
265
+ _sse,
266
+ _wait_for_continue,
267
+ )
268
+
269
+ phase = Phase.INITIAL_OPINIONS
270
+ has_human = any(p.kind == "human" for p in actives)
271
+ if not has_human:
272
+ async for chunk in run_roster_ai_turns_parallel(
273
+ session,
274
+ actives,
275
+ phase=phase,
276
+ build_spec=build_spec,
277
+ call_participant=call_participant,
278
+ on_human_turn=on_human_turn,
279
+ post_process=post_process,
280
+ ):
281
+ yield chunk
282
+ return
283
+
284
+ pending: dict[str, asyncio.Task[_AiTurnResult]] = {}
285
+ for p in actives:
286
+ if p.kind == "human":
287
+ continue
288
+ spec = build_spec(p)
289
+ if spec is None:
290
+ continue
291
+ pending[p.participant_id] = asyncio.create_task(
292
+ _execute_ai_turn(session, spec, call_participant),
293
+ name=f"prefetch_initial:{p.participant_id}",
294
+ )
295
+
296
+ for p in actives:
297
+ if p.kind == "human":
298
+ async for chunk in on_human_turn(p):
299
+ yield chunk
300
+ if _participant_msg_cap_hit(session):
301
+ async for chunk in _wait_for_continue(session, "messages"):
302
+ yield chunk
303
+ continue
304
+
305
+ task = pending.pop(p.participant_id, None)
306
+ if task is None:
307
+ continue
308
+ try:
309
+ result = await task
310
+ except BaseException as exc:
311
+ LOG.exception(
312
+ "Prefetched initial opinion failed for %s: %s",
313
+ p.participant_id,
314
+ exc,
315
+ )
316
+ yield _sse("participant_error", {
317
+ "participant_id": p.participant_id,
318
+ "name": p.name,
319
+ "phase": phase.value,
320
+ })
321
+ continue
322
+
323
+ extra: dict[str, Any] | None = None
324
+ if post_process is not None:
325
+ extra = await post_process(result) or {}
326
+ async for chunk in _emit_ai_turn_result(
327
+ session, result, phase=phase, extra=extra,
328
+ ):
329
+ yield chunk
330
+ if _participant_msg_cap_hit(session):
331
+ async for chunk in _wait_for_continue(session, "messages"):
332
+ yield chunk
333
+
334
+ for pid, task in pending.items():
335
+ if not task.done():
336
+ task.cancel()
337
+
338
+
339
  async def _emit_ai_turn_result(
340
  session: "Session",
341
  result: _AiTurnResult,
 
348
  _add_participant_message,
349
  _msg_payload,
350
  _orchestrator_cap_hit,
351
+ _participant_turn_failure_sse,
352
  _replying_to_ids,
353
  _sse,
354
  _wait_for_continue,
 
359
  for ev in turn.sse_events:
360
  yield ev
361
  if not turn.ok:
362
+ for chunk in _participant_turn_failure_sse(session, p):
363
+ yield chunk
 
 
 
 
 
 
 
 
 
 
 
364
  return
365
 
366
  speaker = turn.speaker
frontend/src/App.js CHANGED
@@ -33,6 +33,16 @@ function pickRandom(list) {
33
  return list[Math.floor(Math.random() * list.length)];
34
  }
35
 
 
 
 
 
 
 
 
 
 
 
36
  export default function App() {
37
  // Persistent state
38
  const persisted = useMemo(() => storage.loadState(), []);
@@ -800,9 +810,6 @@ export default function App() {
800
  )));
801
  },
802
  onOrchestrator: (data) => {
803
- // Orchestrator events with kind == "status" but no text are
804
- // status banners; bubble them into a message-style entry so
805
- // they render with the orchestrator pill.
806
  if (data && data.text) {
807
  setMessages(prev => [...prev, { ...data, role: 'orchestrator' }]);
808
  } else if (data?.message) {
@@ -821,39 +828,35 @@ export default function App() {
821
  setSystemMessages(prev => [...prev, { text: `Error: ${data.message}` }]);
822
  },
823
  onParticipantError: (data) => {
824
- setSystemMessages(prev => [...prev, {
825
- text: `${data.name || 'A participant'} couldn't respond this turn.`,
826
- }]);
 
 
 
827
  },
828
  onParticipantSubstituted: (data) => {
829
- // Resilience layer swapped the backing LLM behind a
830
- // persona's prompt+name. Surface it as a system note so
831
- // the user can reconcile any change in voice / latency
832
- // with the chat metadata.
833
  const name = data.name || 'A participant';
834
  const toDisplay = data.to_model_display || data.to_model_id || 'a substitute model';
835
- setSystemMessages(prev => [...prev, {
836
- text: `${name}'s primary model didn't respond; continuing with ${toDisplay}.`,
837
- }]);
 
 
838
  },
839
  onParticipantReplaced: (data) => {
840
- // Phase 1 alternate kicked in. Replace the session
841
- // roster snapshot so the sidebar re-renders with the
842
- // new participant; also note the change in chat.
843
  if (Array.isArray(data?.roster)) {
844
  setSessionParticipants(data.roster);
845
  }
846
  const origName = data.original_name || 'A participant';
847
  const altName = data.new_name || 'an alternate';
848
- setSystemMessages(prev => [...prev, {
849
- text: `${origName} couldn't give an initial opinion; ${altName} is taking their place.`,
850
- }]);
 
 
851
  },
852
  onVoteCast: (data) => {
853
- // One per-ballot from a vote-based decision method. We
854
- // surface these as system notes so the user can follow
855
- // the tally as it happens; the final report message will
856
- // contain the canonical summary.
857
  const voter = data?.voter_name || 'A voter';
858
  let line;
859
  if (data?.vote) {
@@ -865,16 +868,15 @@ export default function App() {
865
  } else {
866
  line = `${voter} abstained or returned an invalid ballot.`;
867
  }
868
- setSystemMessages(prev => [...prev, { text: line }]);
869
  },
870
  onVoteTally: (data) => {
871
- // Final tally summary. The orchestrator message that
872
- // follows contains the rendered report, so we just log
873
- // a one-liner here for the system feed.
874
  const kind = data?.kind || 'vote';
875
- setSystemMessages(prev => [...prev, {
876
- text: `Vote complete (${kind}); see report below.`,
877
- }]);
 
 
878
  },
879
  onFailsafePause: (data) => {
880
  setPause({ reason: 'messages', ...data });
 
33
  return list[Math.floor(Math.random() * list.length)];
34
  }
35
 
36
+ /** Append a system note at the current point in the chat timeline (not end-of-feed). */
37
+ function appendInlineChatNote(setMessages, text, extra = {}) {
38
+ setMessages(prev => [...prev, {
39
+ role: 'system',
40
+ text,
41
+ timestamp: Date.now() / 1000,
42
+ ...extra,
43
+ }]);
44
+ }
45
+
46
  export default function App() {
47
  // Persistent state
48
  const persisted = useMemo(() => storage.loadState(), []);
 
810
  )));
811
  },
812
  onOrchestrator: (data) => {
 
 
 
813
  if (data && data.text) {
814
  setMessages(prev => [...prev, { ...data, role: 'orchestrator' }]);
815
  } else if (data?.message) {
 
828
  setSystemMessages(prev => [...prev, { text: `Error: ${data.message}` }]);
829
  },
830
  onParticipantError: (data) => {
831
+ const text = `${data.name || 'A participant'} couldn't respond this turn.`;
832
+ appendInlineChatNote(setMessages, text, {
833
+ kind: 'participant_error',
834
+ phase: data.phase,
835
+ participant_id: data.participant_id,
836
+ });
837
  },
838
  onParticipantSubstituted: (data) => {
 
 
 
 
839
  const name = data.name || 'A participant';
840
  const toDisplay = data.to_model_display || data.to_model_id || 'a substitute model';
841
+ appendInlineChatNote(
842
+ setMessages,
843
+ `${name}'s primary model didn't respond; continuing with ${toDisplay}.`,
844
+ { kind: 'participant_substituted', phase: data.phase },
845
+ );
846
  },
847
  onParticipantReplaced: (data) => {
 
 
 
848
  if (Array.isArray(data?.roster)) {
849
  setSessionParticipants(data.roster);
850
  }
851
  const origName = data.original_name || 'A participant';
852
  const altName = data.new_name || 'an alternate';
853
+ appendInlineChatNote(
854
+ setMessages,
855
+ `${origName} couldn't give an initial opinion; ${altName} is taking their place.`,
856
+ { kind: 'participant_replaced', phase: data.phase },
857
+ );
858
  },
859
  onVoteCast: (data) => {
 
 
 
 
860
  const voter = data?.voter_name || 'A voter';
861
  let line;
862
  if (data?.vote) {
 
868
  } else {
869
  line = `${voter} abstained or returned an invalid ballot.`;
870
  }
871
+ appendInlineChatNote(setMessages, line, { kind: 'vote_cast' });
872
  },
873
  onVoteTally: (data) => {
 
 
 
874
  const kind = data?.kind || 'vote';
875
+ appendInlineChatNote(
876
+ setMessages,
877
+ `Vote complete (${kind}); see report below.`,
878
+ { kind: 'vote_tally' },
879
+ );
880
  },
881
  onFailsafePause: (data) => {
882
  setPause({ reason: 'messages', ...data });
frontend/src/components/ChatArea.js CHANGED
@@ -74,8 +74,15 @@ export default function ChatArea({
74
  </div>
75
  )}
76
  {(messages || []).map((msg, i) => {
 
 
 
 
 
 
 
77
  if (msg.role === 'orchestrator') {
78
- return <OrchestratorMessage key={i} message={msg} messageIdx={i} />;
79
  }
80
  const idx = speakerIdxFor[msg.speaker_id] ?? i;
81
  const prev = i > 0 ? messages[i - 1] : null;
 
74
  </div>
75
  )}
76
  {(messages || []).map((msg, i) => {
77
+ if (msg.role === 'system') {
78
+ return (
79
+ <div key={msg.message_id || `sys-inline-${i}`} className="system-message">
80
+ {msg.text}
81
+ </div>
82
+ );
83
+ }
84
  if (msg.role === 'orchestrator') {
85
+ return <OrchestratorMessage key={msg.message_id || i} message={msg} messageIdx={i} />;
86
  }
87
  const idx = speakerIdxFor[msg.speaker_id] ?? i;
88
  const prev = i > 0 ? messages[i - 1] : null;