NeonClary Cursor commited on
Commit
64d902c
·
1 Parent(s): a763505

Surface Credential Summary in settings + exports

Browse files

Add a transparency section so users can see and download the
orchestrator-generated Credential Summary (per-participant
expertise, debating style, credibility on this question, biases to
watch). Built after Phase 1 and refreshed once after Phase 2.

Backend:
- New GET /api/chat/{session_id}/credentials endpoint.
- Credentials block included in TXT and MD exports after the
participants list, omitted cleanly when the summary isn't built
yet.
- CSV table gains four columns (Expertise, Style, Credibility 0-1,
Bias to watch) inserted between Participant and First opinion so
the row reads as a self-contained narrative.
- New `credentials_updated` SSE event fires after the Phase-1.5
build and after the Phase-3 refresh (only when the payload
actually changes), so the frontend can cache the latest snapshot
without polling.

Frontend:
- New CredentialSummaryModal: per-participant cards with name,
expertise, style, bias, and a 0-1 credibility bar.
- "View Credential Summary..." item in DevMenu under a new
Transparency section. Disabled until a session exists; tooltip
explains when it becomes available.
- App.js caches the SSE-pushed snapshot, re-fetches via
fetchCredentials on modal open and on user-initiated refresh,
and resets cache on each new chat start.

Tests: 49/49 backend pytests pass. New CSV/TXT/MD coverage for
the credential block (presence, omission when empty, RFC-4180
field-count stability with the wider schema).

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

backend/app/api/chat.py CHANGED
@@ -365,6 +365,23 @@ async def api_export_chat(session_id: str, fmt: str = "txt"):
365
  return _export_txt(session)
366
 
367
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
  @router.get("/chat/{session_id}/api-log")
369
  async def api_export_log(session_id: str):
370
  session = get_session(session_id)
@@ -426,6 +443,88 @@ def _format_participants_block(session: Session) -> list[str]:
426
  ]
427
 
428
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
429
  def _export_txt(session: Session) -> dict:
430
  lines = ["CCAI Conversation Log", "=" * 40, ""]
431
  lines.append("Question:")
@@ -434,6 +533,9 @@ def _export_txt(session: Session) -> dict:
434
  lines.append("Participants:")
435
  lines.extend(_format_participants_block(session))
436
  lines.append("")
 
 
 
437
  for m in session.messages:
438
  speaker = m.get("speaker_name") or "(anon)"
439
  if m.get("role") == "orchestrator":
@@ -457,7 +559,12 @@ def _export_md(session: Session) -> dict:
457
  lines.append("")
458
  for p in session.participants:
459
  lines.append(f"- **{p.name}** (*{p.display_name}*)")
460
- lines.append("\n---\n")
 
 
 
 
 
461
  for m in session.messages:
462
  speaker = m.get("speaker_name") or "(anon)"
463
  is_orch = m.get("role") == "orchestrator"
@@ -478,7 +585,12 @@ def _export_md(session: Session) -> dict:
478
 
479
 
480
  def _export_csv_table(session: Session) -> dict:
481
- """RFC-4180 compliant CSV. csv.writer handles quoting/escaping."""
 
 
 
 
 
482
  buf = io.StringIO()
483
  writer = csv.writer(buf, quoting=csv.QUOTE_MINIMAL, lineterminator="\n")
484
 
@@ -488,14 +600,23 @@ def _export_csv_table(session: Session) -> dict:
488
  writer.writerow([])
489
  writer.writerow([
490
  "Participant",
 
 
 
 
491
  "First opinion",
492
  "Conversation contribution",
493
  "Revised opinion",
494
  "Final opinion",
495
  ])
496
  for p in session.participants:
 
497
  writer.writerow([
498
  p.name,
 
 
 
 
499
  (session.initial_opinions or {}).get(p.participant_id, ""),
500
  (session.contribution_summaries or {}).get(p.participant_id, ""),
501
  (session.final_opinions or {}).get(p.participant_id, ""),
 
365
  return _export_txt(session)
366
 
367
 
368
+ @router.get("/chat/{session_id}/credentials")
369
+ async def api_credentials(session_id: str):
370
+ """Return the orchestrator-generated Credential Summary for the
371
+ current session. Built after Phase 1 and refreshed once after Phase 2
372
+ critique - so the response can be empty if the user opens the modal
373
+ before Phase 1 finishes.
374
+ """
375
+ session = get_session(session_id)
376
+ if not session:
377
+ raise HTTPException(404, "Session not found")
378
+ return {
379
+ "session_id": session_id,
380
+ "question": session.question,
381
+ "credentials": session.credential_summary or [],
382
+ }
383
+
384
+
385
  @router.get("/chat/{session_id}/api-log")
386
  async def api_export_log(session_id: str):
387
  session = get_session(session_id)
 
443
  ]
444
 
445
 
446
+ def _credentials_intro_line() -> str:
447
+ """One-liner that explains where this block came from. Repeated in TXT
448
+ and MD exports so the file is self-explanatory without the UI."""
449
+ return (
450
+ "Orchestrator-generated assessments of each participant's "
451
+ "expertise, debating style, credibility on this question, and "
452
+ "biases to watch. Built after Phase 1 (initial opinions) and "
453
+ "refreshed once after Phase 2 (critique)."
454
+ )
455
+
456
+
457
+ def _format_credential_block_txt(session: Session) -> list[str]:
458
+ """Plain-text Credential Summary section. Returns [] if no summary
459
+ has been built yet (e.g. user exports mid-Phase-1)."""
460
+ creds = session.credential_summary or []
461
+ if not creds:
462
+ return []
463
+ lines = ["Credential Summary", "-" * 40, _credentials_intro_line(), ""]
464
+ for c in creds:
465
+ name = c.get("name") or c.get("participant_id") or "(unknown)"
466
+ lines.append(f"{name}")
467
+ if c.get("expertise"):
468
+ lines.append(f" Expertise: {c['expertise']}")
469
+ if c.get("personality"):
470
+ lines.append(f" Style: {c['personality']}")
471
+ if c.get("credibility_for_question") is not None:
472
+ try:
473
+ score = float(c["credibility_for_question"])
474
+ lines.append(f" Credibility: {score:.2f} (0-1)")
475
+ except (TypeError, ValueError):
476
+ pass
477
+ if c.get("bias_to_watch"):
478
+ lines.append(f" Bias: {c['bias_to_watch']}")
479
+ lines.append("")
480
+ return lines
481
+
482
+
483
+ def _format_credential_block_md(session: Session) -> list[str]:
484
+ """Markdown Credential Summary section. Returns [] when empty."""
485
+ creds = session.credential_summary or []
486
+ if not creds:
487
+ return []
488
+ lines = ["## Credential Summary", "", f"_{_credentials_intro_line()}_", ""]
489
+ for c in creds:
490
+ name = c.get("name") or c.get("participant_id") or "(unknown)"
491
+ lines.append(f"### {name}")
492
+ lines.append("")
493
+ if c.get("expertise"):
494
+ lines.append(f"- **Expertise:** {c['expertise']}")
495
+ if c.get("personality"):
496
+ lines.append(f"- **Style:** {c['personality']}")
497
+ if c.get("credibility_for_question") is not None:
498
+ try:
499
+ score = float(c["credibility_for_question"])
500
+ lines.append(f"- **Credibility on this question:** {score:.2f} (0-1)")
501
+ except (TypeError, ValueError):
502
+ pass
503
+ if c.get("bias_to_watch"):
504
+ lines.append(f"- **Bias to watch:** {c['bias_to_watch']}")
505
+ lines.append("")
506
+ return lines
507
+
508
+
509
+ def _credential_for(session: Session, participant_id: str) -> dict:
510
+ """Lookup helper used by the CSV writer. Empty dict if not built yet."""
511
+ for c in session.credential_summary or []:
512
+ if c.get("participant_id") == participant_id:
513
+ return c
514
+ return {}
515
+
516
+
517
+ def _format_credibility_score(value: object) -> str:
518
+ """CSV-safe formatting for the credibility number (rounded float).
519
+ Returns "" when the value is missing or not numeric."""
520
+ if value is None:
521
+ return ""
522
+ try:
523
+ return f"{float(value):.2f}"
524
+ except (TypeError, ValueError):
525
+ return ""
526
+
527
+
528
  def _export_txt(session: Session) -> dict:
529
  lines = ["CCAI Conversation Log", "=" * 40, ""]
530
  lines.append("Question:")
 
533
  lines.append("Participants:")
534
  lines.extend(_format_participants_block(session))
535
  lines.append("")
536
+ cred_lines = _format_credential_block_txt(session)
537
+ if cred_lines:
538
+ lines.extend(cred_lines)
539
  for m in session.messages:
540
  speaker = m.get("speaker_name") or "(anon)"
541
  if m.get("role") == "orchestrator":
 
559
  lines.append("")
560
  for p in session.participants:
561
  lines.append(f"- **{p.name}** (*{p.display_name}*)")
562
+ lines.append("")
563
+ cred_lines = _format_credential_block_md(session)
564
+ if cred_lines:
565
+ lines.extend(cred_lines)
566
+ lines.append("---")
567
+ lines.append("")
568
  for m in session.messages:
569
  speaker = m.get("speaker_name") or "(anon)"
570
  is_orch = m.get("role") == "orchestrator"
 
585
 
586
 
587
  def _export_csv_table(session: Session) -> dict:
588
+ """RFC-4180 compliant CSV. csv.writer handles quoting/escaping.
589
+
590
+ Columns include the orchestrator-generated Credential Summary so
591
+ the table is self-contained: who each participant is (per the
592
+ orchestrator's read), then what they said and how it evolved.
593
+ """
594
  buf = io.StringIO()
595
  writer = csv.writer(buf, quoting=csv.QUOTE_MINIMAL, lineterminator="\n")
596
 
 
600
  writer.writerow([])
601
  writer.writerow([
602
  "Participant",
603
+ "Expertise (orchestrator's read)",
604
+ "Style",
605
+ "Credibility on this question (0-1)",
606
+ "Bias to watch",
607
  "First opinion",
608
  "Conversation contribution",
609
  "Revised opinion",
610
  "Final opinion",
611
  ])
612
  for p in session.participants:
613
+ cred = _credential_for(session, p.participant_id)
614
  writer.writerow([
615
  p.name,
616
+ cred.get("expertise", ""),
617
+ cred.get("personality", ""),
618
+ _format_credibility_score(cred.get("credibility_for_question")),
619
+ cred.get("bias_to_watch", ""),
620
  (session.initial_opinions or {}).get(p.participant_id, ""),
621
  (session.contribution_summaries or {}).get(p.participant_id, ""),
622
  (session.final_opinions or {}).get(p.participant_id, ""),
backend/app/services/orchestrator.py CHANGED
@@ -522,6 +522,13 @@ async def _phase_initial_opinions(session: Session) -> AsyncIterator[str]:
522
  )
523
  _bump_orchestrator_count(session)
524
  session.credential_summary = creds
 
 
 
 
 
 
 
525
 
526
 
527
  async def _phase_critique(session: Session, round_number: int) -> AsyncIterator[str]:
@@ -607,7 +614,12 @@ async def _phase_status_assessment(session: Session) -> AsyncIterator[str]:
607
  api_log=session.api_log,
608
  )
609
  _bump_orchestrator_count(session)
610
- session.credential_summary = refreshed
 
 
 
 
 
611
  cred_block = credentials_to_block(session.credential_summary)
612
 
613
  for iteration in range(3):
 
522
  )
523
  _bump_orchestrator_count(session)
524
  session.credential_summary = creds
525
+ # Surface the freshly-built summary so the frontend can enable the
526
+ # "View Credential Summary" menu item and cache its snapshot. The
527
+ # full list also stays available via GET /api/chat/{id}/credentials.
528
+ yield _sse("credentials_updated", {
529
+ "stage": "built",
530
+ "credentials": session.credential_summary,
531
+ })
532
 
533
 
534
  async def _phase_critique(session: Session, round_number: int) -> AsyncIterator[str]:
 
614
  api_log=session.api_log,
615
  )
616
  _bump_orchestrator_count(session)
617
+ if refreshed != session.credential_summary:
618
+ session.credential_summary = refreshed
619
+ yield _sse("credentials_updated", {
620
+ "stage": "refreshed",
621
+ "credentials": session.credential_summary,
622
+ })
623
  cred_block = credentials_to_block(session.credential_summary)
624
 
625
  for iteration in range(3):
backend/tests/test_csv_export.py CHANGED
@@ -1,9 +1,18 @@
1
- from app.api.chat import _export_csv_table
 
 
 
 
2
  from app.services.models import Phase, Session
3
  from app.services.models import Participant
4
 
5
 
6
- def _mk_session():
 
 
 
 
 
7
  s = Session()
8
  s.question = "Will \"AI\" change, education? Yes, no, maybe.\nNew lines too."
9
  p1 = Participant(
@@ -48,16 +57,35 @@ def _mk_session():
48
  },
49
  ]
50
  s.final_report = {"kind": "majority", "text": "Group decided X."}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  return s
52
 
53
 
54
  def test_csv_export_roundtrips_through_csv_module():
55
  """Ensure values containing commas, quotes, and newlines get quoted
56
- correctly per RFC 4180."""
57
  import csv
58
  import io
59
 
60
- s = _mk_session()
61
  out = _export_csv_table(s)
62
  assert out["filename"] == "ccai_chat_table.csv"
63
  parsed = list(csv.reader(io.StringIO(out["content"])))
@@ -71,6 +99,10 @@ def test_csv_export_roundtrips_through_csv_module():
71
  # column header row
72
  assert parsed[3] == [
73
  "Participant",
 
 
 
 
74
  "First opinion",
75
  "Conversation contribution",
76
  "Revised opinion",
@@ -78,21 +110,87 @@ def test_csv_export_roundtrips_through_csv_module():
78
  ]
79
  alice_row = parsed[4]
80
  assert alice_row[0] == "Alice"
81
- assert "\"quotes\"" in alice_row[1] # csv module preserved the quotes
 
 
 
 
 
 
82
  bob_row = parsed[5]
83
  assert bob_row[0] == "Bob, Ph.D."
84
- assert "multi-line" in bob_row[1]
 
85
 
86
 
87
  def test_csv_export_no_field_count_drift():
88
- """Every row after the header should have exactly 5 columns even when
89
- payload contains pathological characters."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  import csv
91
  import io
92
 
93
- s = _mk_session()
94
  out = _export_csv_table(s)
95
  rows = list(csv.reader(io.StringIO(out["content"])))
96
- data_rows = rows[4:]
97
- for row in data_rows:
98
- assert len(row) == 5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.api.chat import (
2
+ _export_csv_table,
3
+ _export_md,
4
+ _export_txt,
5
+ )
6
  from app.services.models import Phase, Session
7
  from app.services.models import Participant
8
 
9
 
10
+ # Number of columns in the CSV table (kept here for tests to assert
11
+ # field-count stability if the schema ever shifts).
12
+ EXPECTED_CSV_COLUMNS = 9
13
+
14
+
15
+ def _mk_session(*, with_credentials: bool = False) -> Session:
16
  s = Session()
17
  s.question = "Will \"AI\" change, education? Yes, no, maybe.\nNew lines too."
18
  p1 = Participant(
 
57
  },
58
  ]
59
  s.final_report = {"kind": "majority", "text": "Group decided X."}
60
+ if with_credentials:
61
+ s.credential_summary = [
62
+ {
63
+ "participant_id": "extra_a",
64
+ "name": "Alice",
65
+ "expertise": "Comparative education researcher.",
66
+ "personality": "Calm, evidence-driven.",
67
+ "credibility_for_question": 0.78,
68
+ "bias_to_watch": "Tends to over-trust meta-analyses.",
69
+ },
70
+ {
71
+ "participant_id": "expert_b",
72
+ "name": "Bob, Ph.D.",
73
+ "expertise": "K-12 classroom teacher, 20 years.",
74
+ "personality": "Combative; debates loudly.",
75
+ "credibility_for_question": 0.62,
76
+ "bias_to_watch": "Anchors on personal anecdotes.",
77
+ },
78
+ ]
79
  return s
80
 
81
 
82
  def test_csv_export_roundtrips_through_csv_module():
83
  """Ensure values containing commas, quotes, and newlines get quoted
84
+ correctly per RFC 4180, and that credential columns are populated."""
85
  import csv
86
  import io
87
 
88
+ s = _mk_session(with_credentials=True)
89
  out = _export_csv_table(s)
90
  assert out["filename"] == "ccai_chat_table.csv"
91
  parsed = list(csv.reader(io.StringIO(out["content"])))
 
99
  # column header row
100
  assert parsed[3] == [
101
  "Participant",
102
+ "Expertise (orchestrator's read)",
103
+ "Style",
104
+ "Credibility on this question (0-1)",
105
+ "Bias to watch",
106
  "First opinion",
107
  "Conversation contribution",
108
  "Revised opinion",
 
110
  ]
111
  alice_row = parsed[4]
112
  assert alice_row[0] == "Alice"
113
+ # credential columns
114
+ assert alice_row[1] == "Comparative education researcher."
115
+ assert alice_row[2] == "Calm, evidence-driven."
116
+ assert alice_row[3] == "0.78"
117
+ assert alice_row[4] == "Tends to over-trust meta-analyses."
118
+ # opinion columns - "First opinion" still preserves quotes/commas/newlines
119
+ assert "\"quotes\"" in alice_row[5]
120
  bob_row = parsed[5]
121
  assert bob_row[0] == "Bob, Ph.D."
122
+ assert bob_row[3] == "0.62"
123
+ assert "multi-line" in bob_row[5]
124
 
125
 
126
  def test_csv_export_no_field_count_drift():
127
+ """Every data row should have exactly EXPECTED_CSV_COLUMNS columns,
128
+ matching the header row, even with pathological characters and even
129
+ when credentials are missing."""
130
+ import csv
131
+ import io
132
+
133
+ s = _mk_session(with_credentials=False)
134
+ out = _export_csv_table(s)
135
+ rows = list(csv.reader(io.StringIO(out["content"])))
136
+ header = rows[3]
137
+ assert len(header) == EXPECTED_CSV_COLUMNS
138
+ for row in rows[4:]:
139
+ assert len(row) == EXPECTED_CSV_COLUMNS
140
+
141
+
142
+ def test_csv_export_blank_credentials_when_summary_missing():
143
+ """When the orchestrator hasn't built a Credential Summary yet, the
144
+ credential columns should be present but empty - never crash."""
145
  import csv
146
  import io
147
 
148
+ s = _mk_session(with_credentials=False)
149
  out = _export_csv_table(s)
150
  rows = list(csv.reader(io.StringIO(out["content"])))
151
+ alice_row = rows[4]
152
+ # cols 1..4 are credential columns (Expertise, Style, Credibility, Bias)
153
+ assert alice_row[1] == ""
154
+ assert alice_row[2] == ""
155
+ assert alice_row[3] == ""
156
+ assert alice_row[4] == ""
157
+ # but the opinion columns should still be populated
158
+ assert "Alice" in alice_row[0]
159
+ assert alice_row[6] == "Stayed firm." # contribution summary
160
+
161
+
162
+ def test_txt_export_includes_credential_block_when_present():
163
+ s = _mk_session(with_credentials=True)
164
+ out = _export_txt(s)
165
+ body = out["content"]
166
+ assert "Credential Summary" in body
167
+ assert "Comparative education researcher." in body
168
+ assert "0.78" in body
169
+ assert "Tends to over-trust meta-analyses." in body
170
+ # Block precedes the conversation transcript
171
+ cred_idx = body.index("Credential Summary")
172
+ msg_idx = body.index("Final consensus statement A")
173
+ assert cred_idx < msg_idx
174
+
175
+
176
+ def test_txt_export_omits_credential_block_when_empty():
177
+ s = _mk_session(with_credentials=False)
178
+ out = _export_txt(s)
179
+ assert "Credential Summary" not in out["content"]
180
+
181
+
182
+ def test_md_export_includes_credential_block_when_present():
183
+ s = _mk_session(with_credentials=True)
184
+ out = _export_md(s)
185
+ body = out["content"]
186
+ assert "## Credential Summary" in body
187
+ assert "### Alice" in body
188
+ assert "### Bob, Ph.D." in body
189
+ assert "**Credibility on this question:** 0.78" in body
190
+ assert "**Bias to watch:**" in body
191
+
192
+
193
+ def test_md_export_omits_credential_block_when_empty():
194
+ s = _mk_session(with_credentials=False)
195
+ out = _export_md(s)
196
+ assert "## Credential Summary" not in out["content"]
frontend/src/App.js CHANGED
@@ -5,11 +5,13 @@ import ChatControls from './components/ChatControls';
5
  import ChatArea from './components/ChatArea';
6
  import ExpertPersonaModal from './components/ExpertPersonaModal';
7
  import ChatTableView from './components/ChatTableView';
 
8
  import {
9
  fetchModels, fetchPersonas, fetchDemoQuestions,
10
  startChat, continueChat, getOrchestrator, setOrchestrator,
11
  getSpeedPriority, setSpeedPriority, getAuthStatus,
12
- exportChat, exportApiLog, fetchTableView, getRateLimitStatus,
 
13
  } from './utils/api';
14
  import * as storage from './utils/storage';
15
  import './styles/variables.css';
@@ -66,6 +68,11 @@ export default function App() {
66
  const [expertEditing, setExpertEditing] = useState(null);
67
  const [tableData, setTableData] = useState(null);
68
  const [tableOpen, setTableOpen] = useState(false);
 
 
 
 
 
69
 
70
  const abortRef = useRef(null);
71
 
@@ -285,6 +292,27 @@ export default function App() {
285
  } catch (err) { console.error('Table fetch failed:', err); }
286
  }, [sessionId]);
287
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288
  // ─── Build start payload ────────────────────────────────────────
289
  const buildStartPayload = useCallback((theQuestion) => {
290
  const enabledParticipants = selectedParticipants.filter(
@@ -348,6 +376,7 @@ export default function App() {
348
  setSessionParticipants([]);
349
  setPause(null);
350
  setActiveQuestion(theQuestion.trim());
 
351
 
352
  try {
353
  await startChat(
@@ -393,6 +422,17 @@ export default function App() {
393
  onOrchestratorCapPause: (data) => {
394
  setPause({ reason: 'orchestrator', ...data });
395
  },
 
 
 
 
 
 
 
 
 
 
 
396
  onDone: () => {
397
  setIsRunning(false);
398
  setStatusText('');
@@ -460,6 +500,8 @@ export default function App() {
460
  modelAssignments={modelAssignments}
461
  onModelAssignmentChange={handleModelAssignmentChange}
462
  onShowTableView={handleShowTableView}
 
 
463
  onDownloadChatTxt={handleDownloadTxt}
464
  onDownloadChatMd={handleDownloadMd}
465
  onDownloadCsvTable={handleDownloadCsvTable}
@@ -520,6 +562,12 @@ export default function App() {
520
  onExportCsv={handleDownloadCsvTable}
521
  />
522
  )}
 
 
 
 
 
 
523
  </div>
524
  );
525
  }
 
5
  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';
17
  import './styles/variables.css';
 
68
  const [expertEditing, setExpertEditing] = useState(null);
69
  const [tableData, setTableData] = useState(null);
70
  const [tableOpen, setTableOpen] = useState(false);
71
+ // Credential Summary: cached snapshot fed by SSE `credentials_updated`
72
+ // events, plus an open/closed flag and a question echo for the modal
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
 
 
292
  } catch (err) { console.error('Table fetch failed:', err); }
293
  }, [sessionId]);
294
 
295
+ // ─── Credential Summary view ────────────────────────────────────
296
+ // Always re-fetch on open so the modal reflects the very latest
297
+ // server-side state (the Phase-3 refresh may have run after the SSE
298
+ // event was missed by a stale tab).
299
+ const handleShowCredentials = useCallback(async () => {
300
+ if (!sessionId) return;
301
+ try {
302
+ const data = await fetchCredentials(sessionId);
303
+ setCredentialsData(data);
304
+ setCredentialsOpen(true);
305
+ } catch (err) { console.error('Credentials fetch failed:', err); }
306
+ }, [sessionId]);
307
+
308
+ const handleRefreshCredentials = useCallback(async () => {
309
+ if (!sessionId) return;
310
+ try {
311
+ const data = await fetchCredentials(sessionId);
312
+ setCredentialsData(data);
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(
 
376
  setSessionParticipants([]);
377
  setPause(null);
378
  setActiveQuestion(theQuestion.trim());
379
+ setCredentialsData(null);
380
 
381
  try {
382
  await startChat(
 
422
  onOrchestratorCapPause: (data) => {
423
  setPause({ reason: 'orchestrator', ...data });
424
  },
425
+ onCredentialsUpdated: (data) => {
426
+ // Backend emits this after the Phase-1.5 build and (when
427
+ // it changes) after the Phase-3 refresh. We cache the
428
+ // payload so the modal opens instantly without a round trip.
429
+ setCredentialsData({
430
+ session_id: data.session_id,
431
+ question: theQuestion.trim(),
432
+ credentials: data.credentials || [],
433
+ stage: data.stage || 'built',
434
+ });
435
+ },
436
  onDone: () => {
437
  setIsRunning(false);
438
  setStatusText('');
 
500
  modelAssignments={modelAssignments}
501
  onModelAssignmentChange={handleModelAssignmentChange}
502
  onShowTableView={handleShowTableView}
503
+ onShowCredentials={handleShowCredentials}
504
+ hasCredentials={!!sessionId}
505
  onDownloadChatTxt={handleDownloadTxt}
506
  onDownloadChatMd={handleDownloadMd}
507
  onDownloadCsvTable={handleDownloadCsvTable}
 
562
  onExportCsv={handleDownloadCsvTable}
563
  />
564
  )}
565
+ <CredentialSummaryModal
566
+ isOpen={credentialsOpen}
567
+ data={credentialsData}
568
+ onClose={() => setCredentialsOpen(false)}
569
+ onRefresh={handleRefreshCredentials}
570
+ />
571
  </div>
572
  );
573
  }
frontend/src/components/CredentialSummaryModal.js ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+
3
+ /**
4
+ * Read-only modal that surfaces the orchestrator-generated Credential
5
+ * Summary - the per-participant assessment of expertise, debating
6
+ * style, credibility on this question, and biases to watch.
7
+ *
8
+ * Built once after Phase 1 (initial opinions) and refreshed once after
9
+ * Phase 2 (critique). The modal pulls a fresh snapshot via GET
10
+ * /api/chat/{id}/credentials each time it's opened, so the user sees
11
+ * the latest version regardless of when they peek.
12
+ *
13
+ * Layout mirrors ChatTableView (overlay + card + close button) for
14
+ * consistency with the existing transparency surfaces.
15
+ */
16
+ export default function CredentialSummaryModal({
17
+ isOpen,
18
+ data,
19
+ onClose,
20
+ onRefresh,
21
+ }) {
22
+ if (!isOpen) return null;
23
+
24
+ const credentials = (data && data.credentials) || [];
25
+ const question = data?.question || '';
26
+
27
+ return (
28
+ <div className="ccai-credentials-overlay">
29
+ <div className="ccai-credentials-card">
30
+ <div className="ccai-credentials-header">
31
+ <div>
32
+ <h2>Credential Summary</h2>
33
+ <div className="ccai-credentials-subtitle">
34
+ The orchestrator's neutral assessment of each participant.
35
+ Built after Phase 1 and refreshed once after Phase 2 critique.
36
+ </div>
37
+ </div>
38
+ <div className="ccai-tab-spacer" />
39
+ {onRefresh && (
40
+ <button
41
+ className="btn-sm btn-outline"
42
+ onClick={onRefresh}
43
+ title="Re-fetch from the server"
44
+ >
45
+ Refresh
46
+ </button>
47
+ )}
48
+ <button className="modal-close" onClick={onClose}>&times;</button>
49
+ </div>
50
+
51
+ {question && (
52
+ <div className="ccai-credentials-question">
53
+ <strong>Question:</strong>
54
+ <div>{question}</div>
55
+ </div>
56
+ )}
57
+
58
+ <div className="ccai-credentials-body">
59
+ {credentials.length === 0 ? (
60
+ <div className="ccai-credentials-empty">
61
+ No Credential Summary has been generated yet. The
62
+ orchestrator builds it after Phase 1 (initial opinions).
63
+ </div>
64
+ ) : (
65
+ credentials.map((c) => (
66
+ <CredentialCard key={c.participant_id} cred={c} />
67
+ ))
68
+ )}
69
+ </div>
70
+ </div>
71
+ </div>
72
+ );
73
+ }
74
+
75
+ function CredentialCard({ cred }) {
76
+ const score = toScore(cred.credibility_for_question);
77
+ return (
78
+ <div className="ccai-credential-card">
79
+ <div className="ccai-credential-card-head">
80
+ <div className="ccai-credential-name">
81
+ {cred.name || cred.participant_id}
82
+ </div>
83
+ {score !== null && (
84
+ <div className="ccai-credibility-wrap" title={`Credibility ${score.toFixed(2)} of 1.0`}>
85
+ <span className="ccai-credibility-label">Credibility</span>
86
+ <div className="ccai-credibility-bar">
87
+ <div
88
+ className="ccai-credibility-fill"
89
+ style={{ width: `${Math.round(score * 100)}%` }}
90
+ />
91
+ </div>
92
+ <span className="ccai-credibility-num">{score.toFixed(2)}</span>
93
+ </div>
94
+ )}
95
+ </div>
96
+ <FieldRow label="Expertise" value={cred.expertise} />
97
+ <FieldRow label="Style" value={cred.personality} />
98
+ <FieldRow label="Bias to watch" value={cred.bias_to_watch} />
99
+ </div>
100
+ );
101
+ }
102
+
103
+ function FieldRow({ label, value }) {
104
+ if (!value) return null;
105
+ return (
106
+ <div className="ccai-credential-row">
107
+ <div className="ccai-credential-row-label">{label}</div>
108
+ <div className="ccai-credential-row-value">{value}</div>
109
+ </div>
110
+ );
111
+ }
112
+
113
+ function toScore(value) {
114
+ if (value === null || value === undefined) return null;
115
+ const n = Number(value);
116
+ if (Number.isNaN(n)) return null;
117
+ return Math.max(0, Math.min(1, n));
118
+ }
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,
5
  } from 'lucide-react';
6
 
7
  /**
@@ -33,6 +33,8 @@ export default function DevMenu({
33
  onModelAssignmentChange,
34
  onOpenExpertModal,
35
  onShowTableView,
 
 
36
  onDownloadChatTxt,
37
  onDownloadChatMd,
38
  onDownloadCsvTable,
@@ -208,6 +210,22 @@ export default function DevMenu({
208
  Chat stats after end
209
  </button>
210
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  <div className="dev-panel-divider" />
212
  <button disabled={!hasChat} className="dev-panel-download-item" onClick={() => { onDownloadChatTxt(); setOpen(false); }}>
213
  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,
5
  } from 'lucide-react';
6
 
7
  /**
 
33
  onModelAssignmentChange,
34
  onOpenExpertModal,
35
  onShowTableView,
36
+ onShowCredentials,
37
+ hasCredentials,
38
  onDownloadChatTxt,
39
  onDownloadChatMd,
40
  onDownloadCsvTable,
 
210
  Chat stats after end
211
  </button>
212
 
213
+ <div className="dev-panel-divider" />
214
+ <div className="dev-panel-label">Transparency</div>
215
+ <button
216
+ disabled={!hasCredentials}
217
+ onClick={() => { onShowCredentials?.(); setOpen(false); }}
218
+ title={
219
+ hasCredentials
220
+ ? "View the orchestrator's per-participant Credential Summary"
221
+ : "Credential Summary is built after Phase 1 (initial opinions). Start a chat first."
222
+ }
223
+ >
224
+ <ScrollText size={14} className="dev-check-icon" />
225
+ View Credential Summary…
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
frontend/src/styles/ccai.css CHANGED
@@ -566,6 +566,191 @@
566
  }
567
 
568
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
569
  /* ── Orchestrator messages ─────────────────────────────────────── */
570
 
571
  .ccai-orchestrator-msg {
 
566
  }
567
 
568
 
569
+ /* ── Credential Summary modal ──────────────────────────────────────
570
+ Surfaces the orchestrator's per-participant assessment built after
571
+ Phase 1 and refreshed after Phase 2 critique. Reuses the table
572
+ modal's overlay/card chrome for visual consistency.
573
+ ──────────────────────────────────────────────────────────────── */
574
+
575
+ .ccai-credentials-overlay {
576
+ position: fixed;
577
+ inset: 0;
578
+ background: rgba(0, 0, 0, 0.5);
579
+ display: flex;
580
+ align-items: center;
581
+ justify-content: center;
582
+ z-index: 1000;
583
+ }
584
+
585
+ .ccai-credentials-card {
586
+ background: var(--bg-primary);
587
+ border: 1px solid var(--border-primary);
588
+ border-radius: 12px;
589
+ width: min(880px, 95vw);
590
+ max-height: 90vh;
591
+ display: flex;
592
+ flex-direction: column;
593
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
594
+ }
595
+
596
+ .ccai-credentials-header {
597
+ display: flex;
598
+ align-items: flex-start;
599
+ gap: 12px;
600
+ padding: 16px 20px;
601
+ border-bottom: 1px solid var(--border-primary);
602
+ }
603
+
604
+ .ccai-credentials-header h2 {
605
+ margin: 0;
606
+ font-size: 16px;
607
+ font-weight: 600;
608
+ color: var(--text-primary);
609
+ }
610
+
611
+ .ccai-credentials-subtitle {
612
+ margin-top: 4px;
613
+ font-size: 12px;
614
+ color: var(--text-tertiary);
615
+ line-height: 1.4;
616
+ max-width: 560px;
617
+ }
618
+
619
+ .ccai-credentials-question {
620
+ margin: 0 20px;
621
+ padding: 10px 12px;
622
+ background: var(--bg-secondary);
623
+ border-radius: 8px;
624
+ font-size: 13px;
625
+ color: var(--text-secondary);
626
+ }
627
+
628
+ .ccai-credentials-question strong {
629
+ display: block;
630
+ font-size: 11px;
631
+ text-transform: uppercase;
632
+ color: var(--text-tertiary);
633
+ letter-spacing: 0.04em;
634
+ margin-bottom: 4px;
635
+ }
636
+
637
+ .ccai-credentials-body {
638
+ padding: 16px 20px;
639
+ display: flex;
640
+ flex-direction: column;
641
+ gap: 12px;
642
+ overflow-y: auto;
643
+ }
644
+
645
+ .ccai-credentials-empty {
646
+ padding: 24px;
647
+ text-align: center;
648
+ font-size: 13px;
649
+ color: var(--text-tertiary);
650
+ border: 1px dashed var(--border-primary);
651
+ border-radius: 8px;
652
+ }
653
+
654
+ .ccai-credential-card {
655
+ padding: 12px 14px;
656
+ border: 1px solid var(--border-primary);
657
+ border-radius: 10px;
658
+ background: var(--bg-secondary);
659
+ }
660
+
661
+ .ccai-credential-card-head {
662
+ display: flex;
663
+ align-items: center;
664
+ gap: 12px;
665
+ margin-bottom: 8px;
666
+ flex-wrap: wrap;
667
+ }
668
+
669
+ .ccai-credential-name {
670
+ font-size: 14px;
671
+ font-weight: 600;
672
+ color: var(--text-primary);
673
+ }
674
+
675
+ .ccai-credibility-wrap {
676
+ display: inline-flex;
677
+ align-items: center;
678
+ gap: 6px;
679
+ margin-left: auto;
680
+ }
681
+
682
+ .ccai-credibility-label {
683
+ font-size: 10px;
684
+ text-transform: uppercase;
685
+ letter-spacing: 0.04em;
686
+ color: var(--text-tertiary);
687
+ }
688
+
689
+ .ccai-credibility-bar {
690
+ width: 120px;
691
+ height: 6px;
692
+ background: var(--border-primary);
693
+ border-radius: 3px;
694
+ overflow: hidden;
695
+ }
696
+
697
+ .ccai-credibility-fill {
698
+ height: 100%;
699
+ background: linear-gradient(
700
+ 90deg,
701
+ var(--accent-primary, #6366F1),
702
+ var(--accent-primary, #6366F1)
703
+ );
704
+ transition: width 0.3s ease;
705
+ }
706
+
707
+ .ccai-credibility-num {
708
+ font-size: 12px;
709
+ font-weight: 600;
710
+ font-variant-numeric: tabular-nums;
711
+ color: var(--text-secondary);
712
+ min-width: 32px;
713
+ text-align: right;
714
+ }
715
+
716
+ .ccai-credential-row {
717
+ display: grid;
718
+ grid-template-columns: 110px 1fr;
719
+ gap: 8px;
720
+ padding: 4px 0;
721
+ font-size: 13px;
722
+ line-height: 1.45;
723
+ }
724
+
725
+ .ccai-credential-row-label {
726
+ font-size: 10px;
727
+ text-transform: uppercase;
728
+ letter-spacing: 0.04em;
729
+ color: var(--text-tertiary);
730
+ font-weight: 600;
731
+ padding-top: 2px;
732
+ }
733
+
734
+ .ccai-credential-row-value {
735
+ color: var(--text-primary);
736
+ }
737
+
738
+ @media (max-width: 600px) {
739
+ .ccai-credentials-card {
740
+ max-height: 100vh;
741
+ border-radius: 0;
742
+ width: 100vw;
743
+ }
744
+ .ccai-credential-row {
745
+ grid-template-columns: 1fr;
746
+ gap: 2px;
747
+ }
748
+ .ccai-credibility-bar {
749
+ width: 80px;
750
+ }
751
+ }
752
+
753
+
754
  /* ── Orchestrator messages ─────────────────────────────────────── */
755
 
756
  .ccai-orchestrator-msg {
frontend/src/utils/api.js CHANGED
@@ -115,6 +115,7 @@ function eventHandlerKey(eventType) {
115
  case 'failsafe_pause': return 'onFailsafePause';
116
  case 'orchestrator_cap_pause': return 'onOrchestratorCapPause';
117
  case 'participant_error': return 'onParticipantError';
 
118
  default: return null;
119
  }
120
  }
@@ -178,6 +179,15 @@ export async function fetchTableView(sessionId) {
178
  return resp.json();
179
  }
180
 
 
 
 
 
 
 
 
 
 
181
  export async function getAuthStatus() {
182
  const resp = await fetch(`${API_BASE}/api/auth/status`, { credentials: 'include' });
183
  if (!resp.ok) return { logged_in: false, remaining_conversations: -1 };
 
115
  case 'failsafe_pause': return 'onFailsafePause';
116
  case 'orchestrator_cap_pause': return 'onOrchestratorCapPause';
117
  case 'participant_error': return 'onParticipantError';
118
+ case 'credentials_updated': return 'onCredentialsUpdated';
119
  default: return null;
120
  }
121
  }
 
179
  return resp.json();
180
  }
181
 
182
+ export async function fetchCredentials(sessionId) {
183
+ const resp = await fetch(
184
+ `${API_BASE}/api/chat/${sessionId}/credentials`,
185
+ { cache: 'no-store' },
186
+ );
187
+ if (!resp.ok) throw new Error('Credentials fetch failed');
188
+ return resp.json();
189
+ }
190
+
191
  export async function getAuthStatus() {
192
  const resp = await fetch(`${API_BASE}/api/auth/status`, { credentials: 'include' });
193
  if (!resp.ok) return { logged_in: false, remaining_conversations: -1 };