NeonClary Cursor commited on
Commit
1ec996f
·
1 Parent(s): 7223f36

feat(limits): expose repetition / failsafe limits in settings menu

Browse files

Hard-coded repetition counts in orchestrator (critique rounds,
status-assessment iterations, consensus turn budget, dyad cap, stall
recovery, auto-disable threshold) and the failsafe pause points are
now driven by a `ConversationLimits` dataclass on `Session`. Defaults
match the historical values; the API layer clamps user-supplied
overrides to per-field bounds.

Frontend: new "Conversation limits..." item under an "Advanced" section
in the settings menu, opens a modal with steppers + descriptions
grouped into Discussion structure / Reliability / Failsafes. Overrides
persist via localStorage and ride along on /chat/start.

Backend: GET /api/chat/limits/defaults serves defaults + bounds +
descriptions so the modal is server-driven; new
test_conversation_limits.py covers clamping behavior and endpoint
shape (60 backend tests pass).

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

backend/app/api/chat.py CHANGED
@@ -21,12 +21,16 @@ from app.middleware.rate_limit import (
21
  )
22
  from app.services.extra_personas import get_extra_persona
23
  from app.services.models import (
 
 
 
24
  DEFAULT_MAX_PARTICIPANTS,
25
  MAX_MAX_PARTICIPANTS,
26
  MIN_MAX_PARTICIPANTS,
27
  Participant,
28
  Phase,
29
  Session,
 
30
  )
31
  from app.services.orchestrator import (
32
  create_session,
@@ -103,6 +107,11 @@ class StartChatRequest(BaseModel):
103
  orchestrator_model_id: str | None = None
104
  summarizer_model_id: str | None = None
105
  max_participants: int = DEFAULT_MAX_PARTICIPANTS
 
 
 
 
 
106
 
107
 
108
  # ---------------------------------------------------------------------------
@@ -163,6 +172,36 @@ async def api_generate_role_freeform(req: GenerateRoleFreeformRequest):
163
  return result
164
 
165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  # ---------------------------------------------------------------------------
167
  # Demo questions
168
  # ---------------------------------------------------------------------------
@@ -310,6 +349,12 @@ async def api_start_chat(req: StartChatRequest, request: Request):
310
  session.orchestrator_model_id = req.orchestrator_model_id
311
  session.summarizer_model_id = req.summarizer_model_id
312
  session.max_participants = max_p
 
 
 
 
 
 
313
 
314
  async def event_stream():
315
  yield (
 
21
  )
22
  from app.services.extra_personas import get_extra_persona
23
  from app.services.models import (
24
+ CONVERSATION_LIMIT_BOUNDS,
25
+ CONVERSATION_LIMIT_DESCRIPTIONS,
26
+ ConversationLimits,
27
  DEFAULT_MAX_PARTICIPANTS,
28
  MAX_MAX_PARTICIPANTS,
29
  MIN_MAX_PARTICIPANTS,
30
  Participant,
31
  Phase,
32
  Session,
33
+ clamp_conversation_limits,
34
  )
35
  from app.services.orchestrator import (
36
  create_session,
 
107
  orchestrator_model_id: str | None = None
108
  summarizer_model_id: str | None = None
109
  max_participants: int = DEFAULT_MAX_PARTICIPANTS
110
+ # User-supplied overrides for the conversation's repetition /
111
+ # failsafe limits. Any field that is missing or out of range is
112
+ # silently clamped to the server-side default; see
113
+ # `clamp_conversation_limits` in services.models.
114
+ limits: dict[str, int] | None = None
115
 
116
 
117
  # ---------------------------------------------------------------------------
 
172
  return result
173
 
174
 
175
+ # ---------------------------------------------------------------------------
176
+ # Conversation limits (steppers in the settings menu)
177
+ # ---------------------------------------------------------------------------
178
+
179
+ @router.get("/chat/limits/defaults")
180
+ async def api_chat_limits_defaults():
181
+ """Return defaults, bounds, and human-readable descriptions for the
182
+ `ConversationLimits` knobs the user can tune in the settings menu.
183
+
184
+ The frontend uses the `defaults` to initialize the steppers, the
185
+ `bounds` to set min/max and clamp on input, and the `descriptions`
186
+ to render the section headers and per-field help text. Keeping
187
+ this server-driven means we add a knob in one place
188
+ (services.models) and the UI picks it up without a frontend
189
+ change beyond rendering.
190
+ """
191
+ defaults = ConversationLimits()
192
+ return {
193
+ "defaults": {
194
+ field_name: getattr(defaults, field_name)
195
+ for field_name in CONVERSATION_LIMIT_BOUNDS.keys()
196
+ },
197
+ "bounds": {
198
+ field_name: {"min": lo, "max": hi}
199
+ for field_name, (lo, hi) in CONVERSATION_LIMIT_BOUNDS.items()
200
+ },
201
+ "descriptions": CONVERSATION_LIMIT_DESCRIPTIONS,
202
+ }
203
+
204
+
205
  # ---------------------------------------------------------------------------
206
  # Demo questions
207
  # ---------------------------------------------------------------------------
 
349
  session.orchestrator_model_id = req.orchestrator_model_id
350
  session.summarizer_model_id = req.summarizer_model_id
351
  session.max_participants = max_p
352
+ # Attach the user-tunable limits and seed the runtime failsafe
353
+ # caps from them. clamp_conversation_limits silently coerces any
354
+ # missing or out-of-range values back to the defaults / bounds.
355
+ session.limits = clamp_conversation_limits(req.limits)
356
+ session.participant_message_cap = session.limits.participant_message_pause_at
357
+ session.orchestrator_call_cap = session.limits.orchestrator_call_pause_at
358
 
359
  async def event_stream():
360
  yield (
backend/app/services/models.py CHANGED
@@ -16,8 +16,13 @@ from app.services.context_budget import ContextSummary
16
 
17
  class Phase(str, Enum):
18
  INITIAL_OPINIONS = "initial_opinions"
 
 
 
19
  CRITIQUE_ROUND_1 = "critique_round_1"
20
  CRITIQUE_ROUND_2 = "critique_round_2"
 
 
21
  STATUS_ASSESSMENT = "status_assessment"
22
  FINALIZATION = "finalization"
23
  CONSENSUS = "consensus"
@@ -35,12 +40,192 @@ MAX_MAX_PARTICIPANTS = 9
35
 
36
  # Failsafe defaults from the plan: pause every N=60 participant messages
37
  # (then every +20), and every M=100 orchestrator calls (then every +50).
 
 
38
  PARTICIPANT_MESSAGE_PAUSE_AT = 60
39
  PARTICIPANT_MESSAGE_PAUSE_INC = 20
40
  ORCHESTRATOR_CALL_PAUSE_AT = 100
41
  ORCHESTRATOR_CALL_PAUSE_INC = 50
42
 
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  @dataclass
45
  class Participant:
46
  """One member of the CCAI forum.
@@ -122,7 +307,16 @@ class Session:
122
  # Per-participant contribution summaries for the table view
123
  contribution_summaries: dict[str, str] = field(default_factory=dict)
124
 
125
- # Failsafes
 
 
 
 
 
 
 
 
 
126
  total_participant_messages: int = 0
127
  participant_message_cap: int = PARTICIPANT_MESSAGE_PAUSE_AT
128
  orchestrator_call_count: int = 0
 
16
 
17
  class Phase(str, Enum):
18
  INITIAL_OPINIONS = "initial_opinions"
19
+ # Critique-round phases: up to 4 rounds are supported (matches the
20
+ # max value of `ConversationLimits.critique_rounds`). The state
21
+ # machine looks the active phase up via `_critique_phase_for(n)`.
22
  CRITIQUE_ROUND_1 = "critique_round_1"
23
  CRITIQUE_ROUND_2 = "critique_round_2"
24
+ CRITIQUE_ROUND_3 = "critique_round_3"
25
+ CRITIQUE_ROUND_4 = "critique_round_4"
26
  STATUS_ASSESSMENT = "status_assessment"
27
  FINALIZATION = "finalization"
28
  CONSENSUS = "consensus"
 
40
 
41
  # Failsafe defaults from the plan: pause every N=60 participant messages
42
  # (then every +20), and every M=100 orchestrator calls (then every +50).
43
+ # These remain the *defaults* for ConversationLimits; the runtime values
44
+ # come from Session.limits so the user can tune them per-conversation.
45
  PARTICIPANT_MESSAGE_PAUSE_AT = 60
46
  PARTICIPANT_MESSAGE_PAUSE_INC = 20
47
  ORCHESTRATOR_CALL_PAUSE_AT = 100
48
  ORCHESTRATOR_CALL_PAUSE_INC = 50
49
 
50
 
51
+ @dataclass
52
+ class ConversationLimits:
53
+ """Tunable repetition and failsafe limits for one CCAI session.
54
+
55
+ Defaults match the historical hard-coded values; the API layer
56
+ clamps user-supplied overrides via `clamp_conversation_limits` so
57
+ out-of-range values don't break the orchestrator. The frontend
58
+ gets the defaults + bounds + descriptions from
59
+ GET /api/chat/limits/defaults so the settings UI is server-driven.
60
+ """
61
+
62
+ # ── Discussion structure ──────────────────────────────────────
63
+ # How many critique turns each participant gets in Phase 2.
64
+ critique_rounds: int = 2
65
+ # How many times Phase 3 will surface a follow-up question
66
+ # (orchestrator-synthesized or relayed from a participant) before
67
+ # moving on to finalization. 0 skips Phase 3 entirely.
68
+ status_assessment_max: int = 3
69
+ # Phase 5 turn budget = this number x active participants. Higher
70
+ # means more back-and-forth before the conversation auto-ends.
71
+ consensus_turns_per_participant: int = 6
72
+ # In Phase 5, how many consecutive "addressed-to" routings (one
73
+ # participant addresses another, then is answered, etc.) before
74
+ # we force a round-robin pick. Prevents two participants from
75
+ # monopolizing the floor.
76
+ dyad_cap: int = 2
77
+ # If consensus fails the first time, how many additional attempts
78
+ # the orchestrator makes by surfacing a new factor for the group
79
+ # to consider. 0 disables retries.
80
+ stall_recovery_attempts: int = 1
81
+
82
+ # ── Reliability ──────────────────────────────────────────────
83
+ # If a participant's LLM call fails this many times in a row, the
84
+ # orchestrator auto-disables them for the rest of the chat.
85
+ auto_disable_failures: int = 3
86
+
87
+ # ── Failsafes ────────────────────────────────────────────────
88
+ # First pause point for participant messages (then increments).
89
+ participant_message_pause_at: int = PARTICIPANT_MESSAGE_PAUSE_AT
90
+ participant_message_pause_inc: int = PARTICIPANT_MESSAGE_PAUSE_INC
91
+ # First pause point for orchestrator-side LLM calls (then increments).
92
+ orchestrator_call_pause_at: int = ORCHESTRATOR_CALL_PAUSE_AT
93
+ orchestrator_call_pause_inc: int = ORCHESTRATOR_CALL_PAUSE_INC
94
+
95
+
96
+ # (min, max) bounds for each limit field. Any user-supplied value is
97
+ # clamped to this range server-side. Keep these conservative enough
98
+ # to stop runaway conversations and tight enough to keep behavior
99
+ # recognizable; widening is fine if a real use case emerges.
100
+ CONVERSATION_LIMIT_BOUNDS: dict[str, tuple[int, int]] = {
101
+ "critique_rounds": (1, 4),
102
+ "status_assessment_max": (0, 5),
103
+ "consensus_turns_per_participant": (2, 12),
104
+ "dyad_cap": (1, 5),
105
+ "stall_recovery_attempts": (0, 3),
106
+ "auto_disable_failures": (1, 10),
107
+ "participant_message_pause_at": (10, 500),
108
+ "participant_message_pause_inc": (5, 100),
109
+ "orchestrator_call_pause_at": (20, 500),
110
+ "orchestrator_call_pause_inc": (10, 200),
111
+ }
112
+
113
+
114
+ # Human-readable descriptions surfaced in the settings UI alongside
115
+ # each stepper. Group key controls the section header.
116
+ CONVERSATION_LIMIT_DESCRIPTIONS: dict[str, dict[str, str]] = {
117
+ "critique_rounds": {
118
+ "group": "Discussion structure",
119
+ "label": "Critique rounds",
120
+ "help": (
121
+ "How many times each participant speaks in Phase 2 "
122
+ "(critique). More rounds give the group more chances to "
123
+ "challenge each other; fewer rounds wraps faster."
124
+ ),
125
+ },
126
+ "status_assessment_max": {
127
+ "group": "Discussion structure",
128
+ "label": "Status-assessment iterations",
129
+ "help": (
130
+ "Max number of follow-up questions the orchestrator may "
131
+ "surface in Phase 3 before moving to opinion finalization. "
132
+ "Set to 0 to skip the follow-up phase entirely."
133
+ ),
134
+ },
135
+ "consensus_turns_per_participant": {
136
+ "group": "Discussion structure",
137
+ "label": "Consensus turns per participant",
138
+ "help": (
139
+ "Multiplier on the Phase 5 (consensus) turn budget. The "
140
+ "actual cap is this number times the count of active "
141
+ "participants. Higher = more debate before timeout."
142
+ ),
143
+ },
144
+ "dyad_cap": {
145
+ "group": "Discussion structure",
146
+ "label": "Dyad cap",
147
+ "help": (
148
+ "In Phase 5, how many consecutive addressed-to replies "
149
+ "(A->B->A->...) are allowed before the orchestrator forces "
150
+ "a round-robin pick. Keeps two voices from monopolizing."
151
+ ),
152
+ },
153
+ "stall_recovery_attempts": {
154
+ "group": "Discussion structure",
155
+ "label": "Stall recovery attempts",
156
+ "help": (
157
+ "If the group can't reach majority and the conversation "
158
+ "stalls, how many extra attempts the orchestrator makes "
159
+ "by surfacing a new factor for the group to consider."
160
+ ),
161
+ },
162
+ "auto_disable_failures": {
163
+ "group": "Reliability",
164
+ "label": "Auto-disable after N failures",
165
+ "help": (
166
+ "If a participant's LLM fails this many times in a row, "
167
+ "the orchestrator removes them from the rest of the chat "
168
+ "rather than keep trying."
169
+ ),
170
+ },
171
+ "participant_message_pause_at": {
172
+ "group": "Failsafes",
173
+ "label": "First pause: participant messages",
174
+ "help": (
175
+ "Total participant messages allowed before the "
176
+ "conversation pauses for a 'Continue' confirmation."
177
+ ),
178
+ },
179
+ "participant_message_pause_inc": {
180
+ "group": "Failsafes",
181
+ "label": "Each subsequent pause: +N messages",
182
+ "help": (
183
+ "After the first pause, this many additional participant "
184
+ "messages are allowed before the next pause."
185
+ ),
186
+ },
187
+ "orchestrator_call_pause_at": {
188
+ "group": "Failsafes",
189
+ "label": "First pause: orchestrator calls",
190
+ "help": (
191
+ "Total orchestrator-side LLM calls (assessments, "
192
+ "summaries, classifications) allowed before the "
193
+ "conversation pauses for a 'Continue' confirmation."
194
+ ),
195
+ },
196
+ "orchestrator_call_pause_inc": {
197
+ "group": "Failsafes",
198
+ "label": "Each subsequent pause: +N orchestrator calls",
199
+ "help": (
200
+ "After the first orchestrator-call pause, this many "
201
+ "additional calls are allowed before the next pause."
202
+ ),
203
+ },
204
+ }
205
+
206
+
207
+ def clamp_conversation_limits(payload: dict[str, Any] | None) -> ConversationLimits:
208
+ """Build a ConversationLimits from a partial dict. Each field is
209
+ clamped to its declared (min, max) range; missing or non-int values
210
+ fall back to the dataclass default. Never raises - any failure
211
+ silently degrades to the default for that one field.
212
+ """
213
+ limits = ConversationLimits()
214
+ if not payload:
215
+ return limits
216
+ for field_name, (lo, hi) in CONVERSATION_LIMIT_BOUNDS.items():
217
+ if field_name not in payload:
218
+ continue
219
+ raw = payload.get(field_name)
220
+ try:
221
+ v = int(raw)
222
+ except (TypeError, ValueError):
223
+ continue
224
+ v = max(lo, min(hi, v))
225
+ setattr(limits, field_name, v)
226
+ return limits
227
+
228
+
229
  @dataclass
230
  class Participant:
231
  """One member of the CCAI forum.
 
307
  # Per-participant contribution summaries for the table view
308
  contribution_summaries: dict[str, str] = field(default_factory=dict)
309
 
310
+ # User-tunable limits for this conversation. Defaults match the
311
+ # legacy hard-coded values; the API layer overrides via
312
+ # `clamp_conversation_limits` from the request payload. The
313
+ # orchestrator reads only from `session.limits.*`, never the
314
+ # module-level constants, so behavior is fully driven by config.
315
+ limits: ConversationLimits = field(default_factory=ConversationLimits)
316
+
317
+ # Failsafes (runtime state). The *_cap fields start at the limits'
318
+ # configured first-pause point and grow by the configured increment
319
+ # each time the user clicks Continue.
320
  total_participant_messages: int = 0
321
  participant_message_cap: int = PARTICIPANT_MESSAGE_PAUSE_AT
322
  orchestrator_call_count: int = 0
backend/app/services/orchestrator.py CHANGED
@@ -59,8 +59,6 @@ from app.services.models import (
59
  DEFAULT_MAX_PARTICIPANTS,
60
  MAX_MAX_PARTICIPANTS,
61
  MIN_MAX_PARTICIPANTS,
62
- ORCHESTRATOR_CALL_PAUSE_INC,
63
- PARTICIPANT_MESSAGE_PAUSE_INC,
64
  Participant,
65
  Phase,
66
  Session,
@@ -249,25 +247,30 @@ async def _wait_for_continue(
249
  session: Session,
250
  reason: str,
251
  ) -> AsyncIterator[str]:
252
- """Pause the state machine until the user clicks Continue."""
 
 
 
 
 
253
  session.paused_for_continue = True
254
  session.pause_reason = reason
255
  if reason == "messages":
 
256
  msg = (
257
  f"Conversation paused after {session.total_participant_messages} "
258
  "participant messages. Click Continue to allow another "
259
- f"{PARTICIPANT_MESSAGE_PAUSE_INC} messages."
260
  )
261
  evt = "failsafe_pause"
262
- bump_inc = PARTICIPANT_MESSAGE_PAUSE_INC
263
  else:
 
264
  msg = (
265
  f"Conversation paused after {session.orchestrator_call_count} "
266
  "orchestrator calls. Click Continue to allow another "
267
- f"{ORCHESTRATOR_CALL_PAUSE_INC} orchestrator calls."
268
  )
269
  evt = "orchestrator_cap_pause"
270
- bump_inc = ORCHESTRATOR_CALL_PAUSE_INC
271
 
272
  yield _sse(evt, {
273
  "reason": reason,
@@ -498,10 +501,13 @@ async def _phase_initial_opinions(session: Session) -> AsyncIterator[str]:
498
  "name": p.name,
499
  "phase": session.phase.value,
500
  })
501
- if p.consecutive_failures >= 3:
502
  p.enabled = False
503
  yield _sse("status", {
504
- "message": f"{p.name} auto-disabled after 3 failures.",
 
 
 
505
  })
506
  continue
507
  msg = _add_participant_message(session, p, text, phase=session.phase, elapsed=elapsed)
@@ -531,12 +537,27 @@ async def _phase_initial_opinions(session: Session) -> AsyncIterator[str]:
531
  })
532
 
533
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
534
  async def _phase_critique(session: Session, round_number: int) -> AsyncIterator[str]:
535
- session.phase = (
536
- Phase.CRITIQUE_ROUND_1 if round_number == 1 else Phase.CRITIQUE_ROUND_2
537
- )
538
  yield _sse("status", {
539
- "message": f"Phase 2: critique round {round_number} of 2...",
540
  })
541
  cred_block = credentials_to_block(session.credential_summary)
542
  actives = _active_participants(session)
@@ -549,6 +570,7 @@ async def _phase_critique(session: Session, round_number: int) -> AsyncIterator[
549
  pending_block = _format_pending_block(pending)
550
  prompt = CRITIQUE_PROMPT.format(
551
  round_number=round_number,
 
552
  question=session.question,
553
  credential_summary=cred_block,
554
  transcript=transcript,
@@ -565,9 +587,14 @@ async def _phase_critique(session: Session, round_number: int) -> AsyncIterator[
565
  "participant_id": p.participant_id, "name": p.name,
566
  "phase": session.phase.value,
567
  })
568
- if p.consecutive_failures >= 3:
569
  p.enabled = False
570
- yield _sse("status", {"message": f"{p.name} auto-disabled after 3 failures."})
 
 
 
 
 
571
  continue
572
 
573
  # Detect addressed_to so the consensus phase's targeted-response
@@ -622,7 +649,7 @@ async def _phase_status_assessment(session: Session) -> AsyncIterator[str]:
622
  })
623
  cred_block = credentials_to_block(session.credential_summary)
624
 
625
- for iteration in range(3):
626
  session.status_assessment_iterations = iteration + 1
627
  prompt = STATUS_ASSESSMENT_PROMPT.format(
628
  question=session.question,
@@ -814,17 +841,19 @@ async def _phase_consensus(session: Session) -> AsyncIterator[str]:
814
  # Round-robin among active participants, but yield to the addressed-to
815
  # target whenever the previous message named one explicitly. To keep
816
  # two participants from monopolizing the floor with an A->B->A->B
817
- # loop, we cap consecutive addressed-to routings at DYAD_CAP. After
818
- # that many in a row, we force a round-robin pick on the next turn.
819
  queue: list[Participant] = list(actives)
820
  last_addressed: str | None = None
821
  dyad_run: int = 0
822
- DYAD_CAP = 2 # one full A->B->A exchange, then rotate
823
 
824
  # Hard backstop on this phase: if we make a lot of consensus turns
825
  # without resolving, exit and let closure handle it. The orchestrator-
826
- # call cap will hit before this, but it's a clean upper bound.
827
- max_consensus_turns = 6 * len(actives)
 
 
828
  consensus_turns = 0
829
 
830
  while consensus_turns < max_consensus_turns:
@@ -833,7 +862,7 @@ async def _phase_consensus(session: Session) -> AsyncIterator[str]:
833
  # Pick speaker. Prefer the addressed-to target (dyadic exchange)
834
  # only while we're under the consecutive-routing cap. Once the
835
  # cap is hit, force a round-robin pick so a third voice can join.
836
- if last_addressed and dyad_run < DYAD_CAP:
837
  speaker = next(
838
  (p for p in actives if p.participant_id == last_addressed),
839
  None,
@@ -1093,8 +1122,10 @@ async def _phase_closure(session: Session) -> AsyncIterator[str]:
1093
  yield _sse("orchestrator", _msg_payload(msg))
1094
  return
1095
 
1096
- # Not productive / no majority. First time -> surface unaddressed factor.
1097
- if session.consensus_attempts < 1:
 
 
1098
  session.consensus_attempts += 1
1099
  factor = await find_unaddressed_factor(
1100
  orchestrator_model_id=_orchestrator_model_id(session),
@@ -1176,10 +1207,9 @@ async def run_conversation(session: Session) -> AsyncIterator[str]:
1176
  async for chunk in _phase_initial_opinions(session):
1177
  yield chunk
1178
 
1179
- async for chunk in _phase_critique(session, 1):
1180
- yield chunk
1181
- async for chunk in _phase_critique(session, 2):
1182
- yield chunk
1183
 
1184
  async for chunk in _phase_status_assessment(session):
1185
  yield chunk
 
59
  DEFAULT_MAX_PARTICIPANTS,
60
  MAX_MAX_PARTICIPANTS,
61
  MIN_MAX_PARTICIPANTS,
 
 
62
  Participant,
63
  Phase,
64
  Session,
 
247
  session: Session,
248
  reason: str,
249
  ) -> AsyncIterator[str]:
250
+ """Pause the state machine until the user clicks Continue.
251
+
252
+ Increment values come from `session.limits`, which the user can
253
+ tune via the settings menu. Defaults match the historical
254
+ PARTICIPANT_MESSAGE_PAUSE_INC / ORCHESTRATOR_CALL_PAUSE_INC.
255
+ """
256
  session.paused_for_continue = True
257
  session.pause_reason = reason
258
  if reason == "messages":
259
+ bump_inc = session.limits.participant_message_pause_inc
260
  msg = (
261
  f"Conversation paused after {session.total_participant_messages} "
262
  "participant messages. Click Continue to allow another "
263
+ f"{bump_inc} messages."
264
  )
265
  evt = "failsafe_pause"
 
266
  else:
267
+ bump_inc = session.limits.orchestrator_call_pause_inc
268
  msg = (
269
  f"Conversation paused after {session.orchestrator_call_count} "
270
  "orchestrator calls. Click Continue to allow another "
271
+ f"{bump_inc} orchestrator calls."
272
  )
273
  evt = "orchestrator_cap_pause"
 
274
 
275
  yield _sse(evt, {
276
  "reason": reason,
 
501
  "name": p.name,
502
  "phase": session.phase.value,
503
  })
504
+ if p.consecutive_failures >= session.limits.auto_disable_failures:
505
  p.enabled = False
506
  yield _sse("status", {
507
+ "message": (
508
+ f"{p.name} auto-disabled after "
509
+ f"{session.limits.auto_disable_failures} failures."
510
+ ),
511
  })
512
  continue
513
  msg = _add_participant_message(session, p, text, phase=session.phase, elapsed=elapsed)
 
537
  })
538
 
539
 
540
+ _CRITIQUE_PHASES = {
541
+ 1: Phase.CRITIQUE_ROUND_1,
542
+ 2: Phase.CRITIQUE_ROUND_2,
543
+ 3: Phase.CRITIQUE_ROUND_3,
544
+ 4: Phase.CRITIQUE_ROUND_4,
545
+ }
546
+
547
+
548
+ def _critique_phase_for(round_number: int) -> Phase:
549
+ """Map a critique round number to the matching Phase enum value.
550
+ Falls back to CRITIQUE_ROUND_2 for unknown numbers - the API layer
551
+ clamps `critique_rounds` to the bounds, so this fallback is purely
552
+ defensive."""
553
+ return _CRITIQUE_PHASES.get(round_number, Phase.CRITIQUE_ROUND_2)
554
+
555
+
556
  async def _phase_critique(session: Session, round_number: int) -> AsyncIterator[str]:
557
+ session.phase = _critique_phase_for(round_number)
558
+ round_total = session.limits.critique_rounds
 
559
  yield _sse("status", {
560
+ "message": f"Phase 2: critique round {round_number} of {round_total}...",
561
  })
562
  cred_block = credentials_to_block(session.credential_summary)
563
  actives = _active_participants(session)
 
570
  pending_block = _format_pending_block(pending)
571
  prompt = CRITIQUE_PROMPT.format(
572
  round_number=round_number,
573
+ round_total=round_total,
574
  question=session.question,
575
  credential_summary=cred_block,
576
  transcript=transcript,
 
587
  "participant_id": p.participant_id, "name": p.name,
588
  "phase": session.phase.value,
589
  })
590
+ if p.consecutive_failures >= session.limits.auto_disable_failures:
591
  p.enabled = False
592
+ yield _sse("status", {
593
+ "message": (
594
+ f"{p.name} auto-disabled after "
595
+ f"{session.limits.auto_disable_failures} failures."
596
+ ),
597
+ })
598
  continue
599
 
600
  # Detect addressed_to so the consensus phase's targeted-response
 
649
  })
650
  cred_block = credentials_to_block(session.credential_summary)
651
 
652
+ for iteration in range(session.limits.status_assessment_max):
653
  session.status_assessment_iterations = iteration + 1
654
  prompt = STATUS_ASSESSMENT_PROMPT.format(
655
  question=session.question,
 
841
  # Round-robin among active participants, but yield to the addressed-to
842
  # target whenever the previous message named one explicitly. To keep
843
  # two participants from monopolizing the floor with an A->B->A->B
844
+ # loop, we cap consecutive addressed-to routings at the configured
845
+ # `dyad_cap`. After that many in a row, we force a round-robin pick.
846
  queue: list[Participant] = list(actives)
847
  last_addressed: str | None = None
848
  dyad_run: int = 0
849
+ dyad_cap = session.limits.dyad_cap
850
 
851
  # Hard backstop on this phase: if we make a lot of consensus turns
852
  # without resolving, exit and let closure handle it. The orchestrator-
853
+ # call cap will usually hit before this, but it's a clean upper bound.
854
+ max_consensus_turns = (
855
+ session.limits.consensus_turns_per_participant * len(actives)
856
+ )
857
  consensus_turns = 0
858
 
859
  while consensus_turns < max_consensus_turns:
 
862
  # Pick speaker. Prefer the addressed-to target (dyadic exchange)
863
  # only while we're under the consecutive-routing cap. Once the
864
  # cap is hit, force a round-robin pick so a third voice can join.
865
+ if last_addressed and dyad_run < dyad_cap:
866
  speaker = next(
867
  (p for p in actives if p.participant_id == last_addressed),
868
  None,
 
1122
  yield _sse("orchestrator", _msg_payload(msg))
1123
  return
1124
 
1125
+ # Not productive / no majority. We may surface an unaddressed
1126
+ # factor and re-run consensus up to `stall_recovery_attempts` times
1127
+ # before giving up and emitting the no-consensus report.
1128
+ if session.consensus_attempts < session.limits.stall_recovery_attempts:
1129
  session.consensus_attempts += 1
1130
  factor = await find_unaddressed_factor(
1131
  orchestrator_model_id=_orchestrator_model_id(session),
 
1207
  async for chunk in _phase_initial_opinions(session):
1208
  yield chunk
1209
 
1210
+ for round_n in range(1, session.limits.critique_rounds + 1):
1211
+ async for chunk in _phase_critique(session, round_n):
1212
+ yield chunk
 
1213
 
1214
  async for chunk in _phase_status_assessment(session):
1215
  yield chunk
backend/app/services/prompts/critique.py CHANGED
@@ -1,7 +1,7 @@
1
  """Phase 2: each participant gets two turns of critique."""
2
 
3
  CRITIQUE_PROMPT = (
4
- "Phase 2 of the discussion: Critique (round {round_number} of 2).\n\n"
5
  "The group has been asked the following question:\n\n"
6
  "<<<\n{question}\n>>>\n\n"
7
  "Here is a Credential Summary the orchestrator built about each "
 
1
  """Phase 2: each participant gets two turns of critique."""
2
 
3
  CRITIQUE_PROMPT = (
4
+ "Phase 2 of the discussion: Critique (round {round_number} of {round_total}).\n\n"
5
  "The group has been asked the following question:\n\n"
6
  "<<<\n{question}\n>>>\n\n"
7
  "Here is a Credential Summary the orchestrator built about each "
backend/tests/test_conversation_limits.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the user-tunable repetition / failsafe limits exposed via
2
+ `ConversationLimits` and the `/api/chat/limits/defaults` endpoint.
3
+
4
+ These guard:
5
+ - defaults match the historical hard-coded values (no behavior change
6
+ for anyone who doesn't touch the new settings);
7
+ - clamping silently coerces missing / out-of-range / non-int values
8
+ back to the per-field defaults rather than raising;
9
+ - the defaults endpoint returns parallel `defaults` / `bounds` /
10
+ `descriptions` maps with the same field names so the frontend can
11
+ zip them into UI rows.
12
+ """
13
+ from fastapi.testclient import TestClient
14
+
15
+ from app.main import app
16
+ from app.services.models import (
17
+ CONVERSATION_LIMIT_BOUNDS,
18
+ CONVERSATION_LIMIT_DESCRIPTIONS,
19
+ ConversationLimits,
20
+ clamp_conversation_limits,
21
+ )
22
+
23
+
24
+ # ---------------------------------------------------------------------------
25
+ # Defaults
26
+ # ---------------------------------------------------------------------------
27
+
28
+ def test_defaults_match_historical_hardcoded_values():
29
+ """If anyone changes a default by accident, this test makes them
30
+ think twice. The values here are the ones the orchestrator used
31
+ before this knobs-as-settings refactor."""
32
+ limits = ConversationLimits()
33
+ assert limits.critique_rounds == 2
34
+ assert limits.status_assessment_max == 3
35
+ assert limits.consensus_turns_per_participant == 6
36
+ assert limits.dyad_cap == 2
37
+ assert limits.stall_recovery_attempts == 1
38
+ assert limits.auto_disable_failures == 3
39
+ assert limits.participant_message_pause_at == 60
40
+ assert limits.participant_message_pause_inc == 20
41
+ assert limits.orchestrator_call_pause_at == 100
42
+ assert limits.orchestrator_call_pause_inc == 50
43
+
44
+
45
+ def test_bounds_cover_every_dataclass_field():
46
+ """Every tunable field needs a (min, max) bound; otherwise the
47
+ clamp helper would silently leave it unprotected."""
48
+ field_names = set(ConversationLimits().__dict__.keys())
49
+ bound_names = set(CONVERSATION_LIMIT_BOUNDS.keys())
50
+ assert field_names == bound_names
51
+
52
+
53
+ def test_descriptions_cover_every_dataclass_field():
54
+ """The settings UI is server-driven; if a field has no description
55
+ block, the modal would render an empty row for it."""
56
+ field_names = set(ConversationLimits().__dict__.keys())
57
+ described = set(CONVERSATION_LIMIT_DESCRIPTIONS.keys())
58
+ assert field_names == described
59
+ for entry in CONVERSATION_LIMIT_DESCRIPTIONS.values():
60
+ assert "group" in entry
61
+ assert "label" in entry
62
+ assert "help" in entry
63
+
64
+
65
+ # ---------------------------------------------------------------------------
66
+ # clamp_conversation_limits
67
+ # ---------------------------------------------------------------------------
68
+
69
+ def test_clamp_returns_defaults_for_none_or_empty():
70
+ assert clamp_conversation_limits(None) == ConversationLimits()
71
+ assert clamp_conversation_limits({}) == ConversationLimits()
72
+
73
+
74
+ def test_clamp_clamps_too_large_values():
75
+ """A value above the field's upper bound is coerced to the upper
76
+ bound, not rejected. This keeps the API permissive."""
77
+ out = clamp_conversation_limits({"critique_rounds": 99})
78
+ assert out.critique_rounds == CONVERSATION_LIMIT_BOUNDS["critique_rounds"][1]
79
+
80
+
81
+ def test_clamp_clamps_too_small_values():
82
+ out = clamp_conversation_limits({"critique_rounds": -10})
83
+ assert out.critique_rounds == CONVERSATION_LIMIT_BOUNDS["critique_rounds"][0]
84
+
85
+
86
+ def test_clamp_ignores_unknown_fields():
87
+ out = clamp_conversation_limits({"there_is_no_such_field": 7})
88
+ assert out == ConversationLimits()
89
+
90
+
91
+ def test_clamp_silently_drops_non_int_values():
92
+ """Stringy garbage that can't be coerced should fall back to the
93
+ default for that one field, not raise."""
94
+ out = clamp_conversation_limits({"critique_rounds": "not-a-number"})
95
+ assert out.critique_rounds == ConversationLimits().critique_rounds
96
+
97
+
98
+ def test_clamp_preserves_partial_overrides():
99
+ """Only-some-fields-supplied is the common case (UI sends just
100
+ the overridden ones)."""
101
+ out = clamp_conversation_limits({"dyad_cap": 4})
102
+ assert out.dyad_cap == 4
103
+ # All other fields untouched.
104
+ base = ConversationLimits()
105
+ for field_name in CONVERSATION_LIMIT_BOUNDS.keys():
106
+ if field_name == "dyad_cap":
107
+ continue
108
+ assert getattr(out, field_name) == getattr(base, field_name)
109
+
110
+
111
+ def test_clamp_accepts_string_ints():
112
+ """JSON sometimes serializes numbers as strings - we should not
113
+ refuse a perfectly valid int just because it arrived as '4'."""
114
+ out = clamp_conversation_limits({"dyad_cap": "4"})
115
+ assert out.dyad_cap == 4
116
+
117
+
118
+ # ---------------------------------------------------------------------------
119
+ # /api/chat/limits/defaults endpoint
120
+ # ---------------------------------------------------------------------------
121
+
122
+ def test_limits_defaults_endpoint_returns_parallel_maps():
123
+ client = TestClient(app)
124
+ resp = client.get("/api/chat/limits/defaults")
125
+ assert resp.status_code == 200
126
+ body = resp.json()
127
+
128
+ assert set(body.keys()) == {"defaults", "bounds", "descriptions"}
129
+
130
+ # All three maps should agree on the same field set so the
131
+ # frontend can zip them per row.
132
+ field_names = set(ConversationLimits().__dict__.keys())
133
+ assert set(body["defaults"].keys()) == field_names
134
+ assert set(body["bounds"].keys()) == field_names
135
+ assert set(body["descriptions"].keys()) == field_names
136
+
137
+ # Bounds shape sanity-check.
138
+ for field_name, bound in body["bounds"].items():
139
+ assert "min" in bound and "max" in bound
140
+ assert bound["min"] < bound["max"]
141
+ assert bound["min"] <= body["defaults"][field_name] <= bound["max"]
frontend/src/App.js CHANGED
@@ -6,11 +6,13 @@ import ChatArea from './components/ChatArea';
6
  import ExpertPersonaModal from './components/ExpertPersonaModal';
7
  import ChatTableView from './components/ChatTableView';
8
  import CredentialSummaryModal from './components/CredentialSummaryModal';
 
9
  import {
10
  fetchModels, fetchPersonas, fetchDemoQuestions,
11
  startChat, continueChat, getOrchestrator, setOrchestrator,
12
  getSpeedPriority, setSpeedPriority, getAuthStatus,
13
  exportChat, exportApiLog, fetchTableView, fetchCredentials,
 
14
  getRateLimitStatus,
15
  } from './utils/api';
16
  import * as storage from './utils/storage';
@@ -73,6 +75,15 @@ export default function App() {
73
  // header. Reset on each new chat start.
74
  const [credentialsData, setCredentialsData] = useState(null);
75
  const [credentialsOpen, setCredentialsOpen] = useState(false);
 
 
 
 
 
 
 
 
 
76
 
77
  const abortRef = useRef(null);
78
 
@@ -313,6 +324,34 @@ export default function App() {
313
  } catch (err) { console.error('Credentials refresh failed:', err); }
314
  }, [sessionId]);
315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
  // ─── Build start payload ────────────────────────────────────────
317
  const buildStartPayload = useCallback((theQuestion) => {
318
  const enabledParticipants = selectedParticipants.filter(
@@ -342,8 +381,10 @@ export default function App() {
342
  orchestrator_model_id: orchestratorModel,
343
  summarizer_model_id: summarizerModel,
344
  max_participants: maxParticipants,
 
 
345
  };
346
- }, [selectedParticipants, enabledMap, modelAssignments, orchestratorModel, summarizerModel, maxParticipants]);
347
 
348
  // ─── Stop / continue ────────────────────────────────────────────
349
  const handleStop = useCallback(() => {
@@ -502,6 +543,8 @@ export default function App() {
502
  onShowTableView={handleShowTableView}
503
  onShowCredentials={handleShowCredentials}
504
  hasCredentials={!!sessionId}
 
 
505
  onDownloadChatTxt={handleDownloadTxt}
506
  onDownloadChatMd={handleDownloadMd}
507
  onDownloadCsvTable={handleDownloadCsvTable}
@@ -568,6 +611,14 @@ export default function App() {
568
  onClose={() => setCredentialsOpen(false)}
569
  onRefresh={handleRefreshCredentials}
570
  />
 
 
 
 
 
 
 
 
571
  </div>
572
  );
573
  }
 
6
  import ExpertPersonaModal from './components/ExpertPersonaModal';
7
  import ChatTableView from './components/ChatTableView';
8
  import CredentialSummaryModal from './components/CredentialSummaryModal';
9
+ import ConversationLimitsModal from './components/ConversationLimitsModal';
10
  import {
11
  fetchModels, fetchPersonas, fetchDemoQuestions,
12
  startChat, continueChat, getOrchestrator, setOrchestrator,
13
  getSpeedPriority, setSpeedPriority, getAuthStatus,
14
  exportChat, exportApiLog, fetchTableView, fetchCredentials,
15
+ fetchConversationLimitsDefaults,
16
  getRateLimitStatus,
17
  } from './utils/api';
18
  import * as storage from './utils/storage';
 
75
  // header. Reset on each new chat start.
76
  const [credentialsData, setCredentialsData] = useState(null);
77
  const [credentialsOpen, setCredentialsOpen] = useState(false);
78
+ // Conversation limits: schema (defaults + bounds + descriptions)
79
+ // pulled from /api/chat/limits/defaults, plus a sparse map of the
80
+ // user's overrides persisted to localStorage. Empty map means
81
+ // "use server defaults". The schema lazy-loads on first open.
82
+ const [limitsSchema, setLimitsSchema] = useState(null);
83
+ const [limitsOverrides, setLimitsOverrides] = useState(
84
+ persisted.conversation_limits || {},
85
+ );
86
+ const [limitsOpen, setLimitsOpen] = useState(false);
87
 
88
  const abortRef = useRef(null);
89
 
 
324
  } catch (err) { console.error('Credentials refresh failed:', err); }
325
  }, [sessionId]);
326
 
327
+ // ─── Conversation limits (settings) ────────────────────────────
328
+ // Lazy-load the schema on first open, then cache it for the rest
329
+ // of the session. The user's override map is already in state
330
+ // and persisted to localStorage; we hand it to the modal as the
331
+ // initial draft and re-persist on every change.
332
+ const handleShowConversationLimits = useCallback(async () => {
333
+ if (!limitsSchema) {
334
+ try {
335
+ const data = await fetchConversationLimitsDefaults();
336
+ setLimitsSchema(data);
337
+ } catch (err) {
338
+ console.error('Conversation-limit schema fetch failed:', err);
339
+ return;
340
+ }
341
+ }
342
+ setLimitsOpen(true);
343
+ }, [limitsSchema]);
344
+
345
+ const handleConversationLimitsChange = useCallback((next) => {
346
+ setLimitsOverrides(next);
347
+ storage.setConversationLimits(next);
348
+ }, []);
349
+
350
+ const handleConversationLimitsResetAll = useCallback(() => {
351
+ setLimitsOverrides({});
352
+ storage.setConversationLimits({});
353
+ }, []);
354
+
355
  // ─── Build start payload ────────────────────────────────────────
356
  const buildStartPayload = useCallback((theQuestion) => {
357
  const enabledParticipants = selectedParticipants.filter(
 
381
  orchestrator_model_id: orchestratorModel,
382
  summarizer_model_id: summarizerModel,
383
  max_participants: maxParticipants,
384
+ // Sparse override map; backend clamps and falls back per-field.
385
+ limits: limitsOverrides,
386
  };
387
+ }, [selectedParticipants, enabledMap, modelAssignments, orchestratorModel, summarizerModel, maxParticipants, limitsOverrides]);
388
 
389
  // ─── Stop / continue ────────────────────────────────────────────
390
  const handleStop = useCallback(() => {
 
543
  onShowTableView={handleShowTableView}
544
  onShowCredentials={handleShowCredentials}
545
  hasCredentials={!!sessionId}
546
+ onShowConversationLimits={handleShowConversationLimits}
547
+ conversationLimitsOverridden={Object.keys(limitsOverrides).length > 0}
548
  onDownloadChatTxt={handleDownloadTxt}
549
  onDownloadChatMd={handleDownloadMd}
550
  onDownloadCsvTable={handleDownloadCsvTable}
 
611
  onClose={() => setCredentialsOpen(false)}
612
  onRefresh={handleRefreshCredentials}
613
  />
614
+ <ConversationLimitsModal
615
+ isOpen={limitsOpen}
616
+ schema={limitsSchema}
617
+ overrides={limitsOverrides}
618
+ onClose={() => setLimitsOpen(false)}
619
+ onChange={handleConversationLimitsChange}
620
+ onResetAll={handleConversationLimitsResetAll}
621
+ />
622
  </div>
623
  );
624
  }
frontend/src/components/ConversationLimitsModal.js ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useMemo, useState } from 'react';
2
+ import { RotateCcw } from 'lucide-react';
3
+
4
+ /**
5
+ * Settings modal for the user-tunable repetition / failsafe limits.
6
+ *
7
+ * The schema (defaults, bounds, descriptions, group assignments) is
8
+ * fetched from GET /api/chat/limits/defaults so the entire UI is
9
+ * server-driven: adding a knob in `services.models.ConversationLimits`
10
+ * makes it appear here automatically. The user's overrides are
11
+ * persisted to localStorage and sent on the next /chat/start, where
12
+ * the backend re-clamps them to the declared bounds.
13
+ *
14
+ * "Effective" values shown to the user are: override (if set) ->
15
+ * server default. Values are pre-clamped client-side too so the
16
+ * stepper UI stays in range.
17
+ */
18
+ export default function ConversationLimitsModal({
19
+ isOpen,
20
+ schema,
21
+ overrides,
22
+ onClose,
23
+ onChange,
24
+ onResetAll,
25
+ }) {
26
+ const [draft, setDraft] = useState(() => ({ ...(overrides || {}) }));
27
+
28
+ // Reset draft whenever the modal is reopened so we don't leak edits
29
+ // from a previous open.
30
+ React.useEffect(() => {
31
+ if (isOpen) setDraft({ ...(overrides || {}) });
32
+ }, [isOpen, overrides]);
33
+
34
+ const grouped = useMemo(() => groupFields(schema), [schema]);
35
+
36
+ if (!isOpen) return null;
37
+
38
+ if (!schema) {
39
+ return (
40
+ <div className="ccai-credentials-overlay">
41
+ <div className="ccai-credentials-card">
42
+ <div className="ccai-credentials-header">
43
+ <div>
44
+ <h2>Conversation limits</h2>
45
+ </div>
46
+ <div className="ccai-tab-spacer" />
47
+ <button className="modal-close" onClick={onClose}>&times;</button>
48
+ </div>
49
+ <div className="ccai-credentials-body">
50
+ <div className="ccai-credentials-empty">Loading limits...</div>
51
+ </div>
52
+ </div>
53
+ </div>
54
+ );
55
+ }
56
+
57
+ const handleChange = (field, value) => {
58
+ const next = { ...draft, [field]: value };
59
+ setDraft(next);
60
+ onChange?.(next);
61
+ };
62
+
63
+ const handleResetField = (field) => {
64
+ const next = { ...draft };
65
+ delete next[field];
66
+ setDraft(next);
67
+ onChange?.(next);
68
+ };
69
+
70
+ const handleResetAll = () => {
71
+ setDraft({});
72
+ onResetAll?.();
73
+ };
74
+
75
+ return (
76
+ <div className="ccai-credentials-overlay">
77
+ <div className="ccai-credentials-card">
78
+ <div className="ccai-credentials-header">
79
+ <div>
80
+ <h2>Conversation limits</h2>
81
+ <div className="ccai-credentials-subtitle">
82
+ These knobs control how long each phase of the discussion
83
+ runs and when the conversation pauses for a Continue
84
+ confirmation. Changes apply to the next chat you start.
85
+ </div>
86
+ </div>
87
+ <div className="ccai-tab-spacer" />
88
+ <button
89
+ className="btn-sm btn-outline"
90
+ onClick={handleResetAll}
91
+ title="Restore every knob to the server default"
92
+ >
93
+ <RotateCcw size={14} style={{ marginRight: 4 }} />
94
+ Reset all
95
+ </button>
96
+ <button className="modal-close" onClick={onClose}>&times;</button>
97
+ </div>
98
+
99
+ <div className="ccai-credentials-body">
100
+ {grouped.map(({ group, fields }) => (
101
+ <div key={group} className="ccai-limits-group">
102
+ <div className="ccai-limits-group-title">{group}</div>
103
+ {fields.map((f) => (
104
+ <LimitRow
105
+ key={f.field}
106
+ field={f.field}
107
+ label={f.label}
108
+ help={f.help}
109
+ defaultValue={f.defaultValue}
110
+ min={f.min}
111
+ max={f.max}
112
+ override={draft[f.field]}
113
+ onChange={(v) => handleChange(f.field, v)}
114
+ onResetField={() => handleResetField(f.field)}
115
+ />
116
+ ))}
117
+ </div>
118
+ ))}
119
+ </div>
120
+ </div>
121
+ </div>
122
+ );
123
+ }
124
+
125
+ function LimitRow({
126
+ field,
127
+ label,
128
+ help,
129
+ defaultValue,
130
+ min,
131
+ max,
132
+ override,
133
+ onChange,
134
+ onResetField,
135
+ }) {
136
+ const isOverride = override !== undefined && override !== null;
137
+ const effective = isOverride ? override : defaultValue;
138
+
139
+ const setClamped = (raw) => {
140
+ if (raw === '' || raw === null || raw === undefined) {
141
+ // Empty input = revert to default for this field.
142
+ onResetField();
143
+ return;
144
+ }
145
+ let n = parseInt(raw, 10);
146
+ if (Number.isNaN(n)) return;
147
+ if (n < min) n = min;
148
+ if (n > max) n = max;
149
+ onChange(n);
150
+ };
151
+
152
+ return (
153
+ <div className="ccai-limit-row">
154
+ <div className="ccai-limit-row-head">
155
+ <label className="ccai-limit-label" htmlFor={`limit-${field}`}>
156
+ {label}
157
+ </label>
158
+ <div className="ccai-limit-stepper">
159
+ <input
160
+ id={`limit-${field}`}
161
+ type="number"
162
+ min={min}
163
+ max={max}
164
+ step={1}
165
+ value={effective}
166
+ onChange={(e) => setClamped(e.target.value)}
167
+ className="ccai-limit-input"
168
+ />
169
+ <span className="ccai-limit-range">
170
+ ({min}-{max}, default {defaultValue})
171
+ </span>
172
+ {isOverride && (
173
+ <button
174
+ className="ccai-limit-reset"
175
+ onClick={onResetField}
176
+ title="Reset this field to the default"
177
+ >
178
+ reset
179
+ </button>
180
+ )}
181
+ </div>
182
+ </div>
183
+ <div className="ccai-limit-help">{help}</div>
184
+ </div>
185
+ );
186
+ }
187
+
188
+ /**
189
+ * Convert the flat `descriptions` map into [{group, fields[]}] in
190
+ * the order the groups first appear, then the order each field is
191
+ * declared in `bounds` (which mirrors the dataclass field order).
192
+ */
193
+ function groupFields(schema) {
194
+ if (!schema) return [];
195
+ const { defaults, bounds, descriptions } = schema;
196
+ const orderedFields = Object.keys(bounds);
197
+ const seen = new Map();
198
+ for (const field of orderedFields) {
199
+ const desc = descriptions[field] || {};
200
+ const group = desc.group || 'Other';
201
+ if (!seen.has(group)) seen.set(group, []);
202
+ seen.get(group).push({
203
+ field,
204
+ label: desc.label || field,
205
+ help: desc.help || '',
206
+ defaultValue: defaults[field],
207
+ min: bounds[field].min,
208
+ max: bounds[field].max,
209
+ });
210
+ }
211
+ return Array.from(seen.entries()).map(([group, fields]) => ({ group, fields }));
212
+ }
frontend/src/components/DevMenu.js CHANGED
@@ -1,7 +1,7 @@
1
  import React, { useState, useMemo, useRef, useEffect } from 'react';
2
  import {
3
  ChevronRight, Download, Settings2, Search,
4
- Square, CheckSquare, UserPlus, Table2, ScrollText,
5
  } from 'lucide-react';
6
 
7
  /**
@@ -35,6 +35,8 @@ export default function DevMenu({
35
  onShowTableView,
36
  onShowCredentials,
37
  hasCredentials,
 
 
38
  onDownloadChatTxt,
39
  onDownloadChatMd,
40
  onDownloadCsvTable,
@@ -226,6 +228,29 @@ export default function DevMenu({
226
  <ChevronRight size={12} style={{ marginLeft: 'auto', opacity: 0.5 }} />
227
  </button>
228
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  <div className="dev-panel-divider" />
230
  <button disabled={!hasChat} className="dev-panel-download-item" onClick={() => { onDownloadChatTxt(); setOpen(false); }}>
231
  Download chat as .txt
 
1
  import React, { useState, useMemo, useRef, useEffect } from 'react';
2
  import {
3
  ChevronRight, Download, Settings2, Search,
4
+ Square, CheckSquare, UserPlus, Table2, ScrollText, SlidersHorizontal,
5
  } from 'lucide-react';
6
 
7
  /**
 
35
  onShowTableView,
36
  onShowCredentials,
37
  hasCredentials,
38
+ onShowConversationLimits,
39
+ conversationLimitsOverridden,
40
  onDownloadChatTxt,
41
  onDownloadChatMd,
42
  onDownloadCsvTable,
 
228
  <ChevronRight size={12} style={{ marginLeft: 'auto', opacity: 0.5 }} />
229
  </button>
230
 
231
+ <div className="dev-panel-divider" />
232
+ <div className="dev-panel-label">Advanced</div>
233
+ <button
234
+ onClick={() => { onShowConversationLimits?.(); setOpen(false); }}
235
+ title="View and adjust the per-phase repetition limits and failsafe pause points."
236
+ >
237
+ <SlidersHorizontal size={14} className="dev-check-icon" />
238
+ Conversation limits…
239
+ {conversationLimitsOverridden && (
240
+ <span
241
+ title="One or more limits are overridden from the defaults"
242
+ style={{
243
+ marginLeft: 6,
244
+ fontSize: 11,
245
+ color: 'var(--text-secondary)',
246
+ }}
247
+ >
248
+ (custom)
249
+ </span>
250
+ )}
251
+ <ChevronRight size={12} style={{ marginLeft: 'auto', opacity: 0.5 }} />
252
+ </button>
253
+
254
  <div className="dev-panel-divider" />
255
  <button disabled={!hasChat} className="dev-panel-download-item" onClick={() => { onDownloadChatTxt(); setOpen(false); }}>
256
  Download chat as .txt
frontend/src/styles/ccai.css CHANGED
@@ -1018,3 +1018,104 @@
1018
  width: 100vw;
1019
  }
1020
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1018
  width: 100vw;
1019
  }
1020
  }
1021
+
1022
+
1023
+ /* ── Conversation limits modal ────────────────────────────────────
1024
+ Re-uses .ccai-credentials-overlay/.ccai-credentials-card/.ccai-
1025
+ credentials-header/.ccai-credentials-body for the shell so the
1026
+ look matches the credential summary modal. The classes below
1027
+ style the per-section list and per-field stepper row. */
1028
+
1029
+ .ccai-limits-group {
1030
+ display: flex;
1031
+ flex-direction: column;
1032
+ gap: 10px;
1033
+ padding: 12px 14px;
1034
+ background: var(--bg-secondary);
1035
+ border: 1px solid var(--border-primary);
1036
+ border-radius: 10px;
1037
+ }
1038
+
1039
+ .ccai-limits-group + .ccai-limits-group {
1040
+ margin-top: 4px;
1041
+ }
1042
+
1043
+ .ccai-limits-group-title {
1044
+ font-size: 13px;
1045
+ font-weight: 600;
1046
+ color: var(--text-primary);
1047
+ text-transform: uppercase;
1048
+ letter-spacing: 0.04em;
1049
+ border-bottom: 1px solid var(--border-primary);
1050
+ padding-bottom: 6px;
1051
+ margin-bottom: 2px;
1052
+ }
1053
+
1054
+ .ccai-limit-row {
1055
+ display: flex;
1056
+ flex-direction: column;
1057
+ gap: 4px;
1058
+ padding: 6px 0;
1059
+ }
1060
+
1061
+ .ccai-limit-row + .ccai-limit-row {
1062
+ border-top: 1px dashed var(--border-primary);
1063
+ padding-top: 10px;
1064
+ }
1065
+
1066
+ .ccai-limit-row-head {
1067
+ display: flex;
1068
+ align-items: center;
1069
+ justify-content: space-between;
1070
+ gap: 12px;
1071
+ flex-wrap: wrap;
1072
+ }
1073
+
1074
+ .ccai-limit-label {
1075
+ font-size: 14px;
1076
+ font-weight: 600;
1077
+ color: var(--text-primary);
1078
+ }
1079
+
1080
+ .ccai-limit-stepper {
1081
+ display: inline-flex;
1082
+ align-items: center;
1083
+ gap: 8px;
1084
+ }
1085
+
1086
+ .ccai-limit-input {
1087
+ width: 64px;
1088
+ padding: 4px 6px;
1089
+ background: var(--bg-primary);
1090
+ border: 1px solid var(--border-primary);
1091
+ border-radius: 6px;
1092
+ color: var(--text-primary);
1093
+ font-size: 14px;
1094
+ text-align: right;
1095
+ }
1096
+
1097
+ .ccai-limit-range {
1098
+ font-size: 12px;
1099
+ color: var(--text-secondary);
1100
+ }
1101
+
1102
+ .ccai-limit-reset {
1103
+ font-size: 12px;
1104
+ background: transparent;
1105
+ border: 1px solid var(--border-primary);
1106
+ color: var(--text-secondary);
1107
+ padding: 2px 8px;
1108
+ border-radius: 6px;
1109
+ cursor: pointer;
1110
+ }
1111
+
1112
+ .ccai-limit-reset:hover {
1113
+ background: var(--card-bg);
1114
+ color: var(--text-primary);
1115
+ }
1116
+
1117
+ .ccai-limit-help {
1118
+ font-size: 12.5px;
1119
+ color: var(--text-secondary);
1120
+ line-height: 1.45;
1121
+ }
frontend/src/utils/api.js CHANGED
@@ -179,6 +179,21 @@ export async function fetchTableView(sessionId) {
179
  return resp.json();
180
  }
181
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  export async function fetchCredentials(sessionId) {
183
  const resp = await fetch(
184
  `${API_BASE}/api/chat/${sessionId}/credentials`,
 
179
  return resp.json();
180
  }
181
 
182
+ /**
183
+ * Fetch the user-tunable conversation-limit defaults, bounds, and
184
+ * descriptions. The frontend uses this to render the "Conversation
185
+ * limits" settings modal entirely from the server schema, so adding
186
+ * a new knob in the backend doesn't require a frontend change.
187
+ *
188
+ * Shape: { defaults: {field: int}, bounds: {field: {min, max}},
189
+ * descriptions: {field: {group, label, help}} }
190
+ */
191
+ export async function fetchConversationLimitsDefaults() {
192
+ const resp = await fetch(`${API_BASE}/api/chat/limits/defaults`, { cache: 'no-store' });
193
+ if (!resp.ok) throw new Error('Failed to fetch conversation-limit defaults');
194
+ return resp.json();
195
+ }
196
+
197
  export async function fetchCredentials(sessionId) {
198
  const resp = await fetch(
199
  `${API_BASE}/api/chat/${sessionId}/credentials`,
frontend/src/utils/storage.js CHANGED
@@ -19,6 +19,11 @@ const DEFAULTS = {
19
  summarizer_model_id: null,
20
  max_participants: 5,
21
  theme: null,
 
 
 
 
 
22
  };
23
 
24
  function readAll() {
@@ -87,3 +92,7 @@ export function setMaxParticipants(n) {
87
  export function setTheme(theme) {
88
  return patchState({ theme });
89
  }
 
 
 
 
 
19
  summarizer_model_id: null,
20
  max_participants: 5,
21
  theme: null,
22
+ // Sparse map of user overrides to ConversationLimits fields. Empty
23
+ // map = "use server defaults". The server clamps anything we send,
24
+ // so storing whatever the user typed (including stale values from
25
+ // an earlier session) is safe.
26
+ conversation_limits: {},
27
  };
28
 
29
  function readAll() {
 
92
  export function setTheme(theme) {
93
  return patchState({ theme });
94
  }
95
+
96
+ export function setConversationLimits(limitsMap) {
97
+ return patchState({ conversation_limits: limitsMap || {} });
98
+ }