File size: 11,528 Bytes
11bf9b7
 
64d902c
 
 
 
 
 
d4017c8
 
 
64d902c
 
 
 
 
 
 
 
 
 
 
11bf9b7
 
64d902c
bb08a9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64d902c
 
 
 
 
bb08a9f
 
 
 
 
 
 
 
 
 
 
 
64d902c
 
 
 
 
 
 
 
d4017c8
64d902c
 
 
 
 
 
 
 
 
 
 
 
bb08a9f
 
 
 
 
 
 
 
 
64d902c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11bf9b7
 
 
 
 
 
 
 
 
 
 
 
64d902c
 
 
 
 
 
 
11bf9b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64d902c
11bf9b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64d902c
11bf9b7
 
 
 
 
 
64d902c
 
11bf9b7
 
 
64d902c
11bf9b7
 
 
64d902c
 
 
 
 
 
 
 
 
 
 
 
 
11bf9b7
 
 
 
 
 
 
 
 
 
 
64d902c
 
 
 
 
 
 
 
11bf9b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64d902c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb08a9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import React, { useMemo, useState, useEffect } from 'react';
import { Download, Edit2, Check, X, User } from 'lucide-react';

/**
 * Read-only modal that surfaces the orchestrator-generated Credential
 * Summary - the per-participant assessment of expertise, debating
 * style, credibility on this question, and biases to watch.
 *
 * Built concurrently during Phase 1 (as each initial opinion lands).
 * Rebuilt only if a participant's backing LLM model changes. The modal
 * pulls a fresh snapshot via GET
 * /api/chat/{id}/credentials each time it's opened, so the user sees
 * the latest version regardless of when they peek.
 *
 * Layout mirrors ChatTableView (overlay + card + close button) for
 * consistency with the existing transparency surfaces.
 */
export default function CredentialSummaryModal({
  isOpen,
  data,
  onClose,
  onRefresh,
  humanParticipantId,
  onEditHumanCredential,
}) {
  // Hooks must run on every render, so the filename memo lives ABOVE
  // the early return. The dependency on `isOpen` regenerates the
  // timestamp each time the modal opens (matches PromptCatalogModal).
  const filename = useMemo(() => {
    const now = new Date();
    const pad = (n) => String(n).padStart(2, '0');
    return (
      'ccai-credentials-'
      + `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`
      + `-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`
      + '.txt'
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen]);

  if (!isOpen) return null;

  const credentials = (data && data.credentials) || [];
  const question = data?.question || '';

  const handleDownload = () => {
    if (!credentials.length) return;
    const txt = renderCredentialsAsText(question, credentials);
    const blob = new Blob([txt], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="ccai-credentials-overlay">
      <div className="ccai-credentials-card">
        <div className="ccai-credentials-header">
          <div>
            <h2>Credential Summary</h2>
            <div className="ccai-credentials-subtitle">
              The orchestrator's neutral assessment of each participant.
              Built during Phase 1; updated only if a participant&apos;s model changes.
            </div>
          </div>
          <div className="ccai-tab-spacer" />
          {onRefresh && (
            <button
              className="btn-sm btn-outline"
              onClick={onRefresh}
              title="Re-fetch from the server"
            >
              Refresh
            </button>
          )}
          <button
            className="btn-sm btn-outline"
            onClick={handleDownload}
            disabled={credentials.length === 0}
            title="Download the credential summary as a .txt file"
          >
            <Download size={14} style={{ marginRight: 4 }} />
            Download as .txt
          </button>
          <button className="modal-close" onClick={onClose}>&times;</button>
        </div>

        {question && (
          <div className="ccai-credentials-question">
            <strong>Question:</strong>
            <div>{question}</div>
          </div>
        )}

        <div className="ccai-credentials-body">
          {credentials.length === 0 ? (
            <div className="ccai-credentials-empty">
              No Credential Summary has been generated yet. The
              orchestrator builds it after Phase 1 (initial opinions).
            </div>
          ) : (
            credentials.map((c) => {
              const isHuman = !!humanParticipantId
                && c.participant_id === humanParticipantId;
              return (
                <CredentialCard
                  key={c.participant_id}
                  cred={c}
                  isHuman={isHuman}
                  onEdit={isHuman ? onEditHumanCredential : null}
                />
              );
            })
          )}
        </div>
      </div>
    </div>
  );
}

function CredentialCard({ cred, isHuman, onEdit }) {
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState(() => ({
    name: cred.name || '',
    expertise: cred.expertise || '',
    personality: cred.personality || '',
    credibility_for_question:
      cred.credibility_for_question !== undefined
        ? cred.credibility_for_question
        : 0.5,
    bias_to_watch: cred.bias_to_watch || '',
  }));

  // Reset the draft whenever the underlying credential payload
  // changes (e.g. a Phase-3 refresh from the SSE stream).
  useEffect(() => {
    setDraft({
      name: cred.name || '',
      expertise: cred.expertise || '',
      personality: cred.personality || '',
      credibility_for_question:
        cred.credibility_for_question !== undefined
          ? cred.credibility_for_question
          : 0.5,
      bias_to_watch: cred.bias_to_watch || '',
    });
  }, [cred]);

  const score = toScore(cred.credibility_for_question);

  if (isHuman && editing) {
    return (
      <div className="ccai-credential-card ccai-credential-card-human ccai-credential-card-editing">
        <div className="ccai-credential-card-head">
          <div className="ccai-credential-name">
            <User size={14} style={{ marginRight: 4, verticalAlign: '-2px' }} />
            <input
              className="ccai-credential-edit-name"
              type="text"
              value={draft.name}
              onChange={e => setDraft(d => ({ ...d, name: e.target.value }))}
            />
            <span className="ccai-credential-human-tag">Human</span>
          </div>
        </div>
        <EditableRow
          label="Expertise"
          value={draft.expertise}
          onChange={v => setDraft(d => ({ ...d, expertise: v }))}
        />
        <EditableRow
          label="Style"
          value={draft.personality}
          onChange={v => setDraft(d => ({ ...d, personality: v }))}
        />
        <EditableScoreRow
          label="Credibility (0-1)"
          value={draft.credibility_for_question}
          onChange={v => setDraft(d => ({ ...d, credibility_for_question: v }))}
        />
        <EditableRow
          label="Bias to watch"
          value={draft.bias_to_watch}
          onChange={v => setDraft(d => ({ ...d, bias_to_watch: v }))}
        />
        <div className="ccai-credential-edit-actions">
          <button
            type="button"
            className="btn-sm btn-outline"
            onClick={() => setEditing(false)}
          >
            <X size={12} style={{ marginRight: 4 }} />
            Cancel
          </button>
          <button
            type="button"
            className="btn btn-primary btn-sm"
            onClick={async () => {
              await onEdit?.(draft);
              setEditing(false);
            }}
          >
            <Check size={12} style={{ marginRight: 4 }} />
            Save
          </button>
        </div>
      </div>
    );
  }

  return (
    <div
      className={
        'ccai-credential-card'
        + (isHuman ? ' ccai-credential-card-human' : '')
      }
    >
      <div className="ccai-credential-card-head">
        <div className="ccai-credential-name">
          {isHuman && (
            <User size={14} style={{ marginRight: 4, verticalAlign: '-2px' }} />
          )}
          {cred.name || cred.participant_id}
          {isHuman && (
            <span className="ccai-credential-human-tag">Human</span>
          )}
        </div>
        {score !== null && (
          <div className="ccai-credibility-wrap" title={`Credibility ${score.toFixed(2)} of 1.0`}>
            <span className="ccai-credibility-label">Credibility</span>
            <div className="ccai-credibility-bar">
              <div
                className="ccai-credibility-fill"
                style={{ width: `${Math.round(score * 100)}%` }}
              />
            </div>
            <span className="ccai-credibility-num">{score.toFixed(2)}</span>
          </div>
        )}
        {isHuman && onEdit && (
          <button
            type="button"
            className="btn-sm btn-outline ccai-credential-edit-btn"
            onClick={() => setEditing(true)}
            title="Edit your credential summary"
          >
            <Edit2 size={12} style={{ marginRight: 4 }} />
            Edit
          </button>
        )}
      </div>
      <FieldRow label="Expertise" value={cred.expertise} />
      <FieldRow label="Style" value={cred.personality} />
      <FieldRow label="Bias to watch" value={cred.bias_to_watch} />
    </div>
  );
}

function EditableRow({ label, value, onChange }) {
  return (
    <div className="ccai-credential-row ccai-credential-row-edit">
      <div className="ccai-credential-row-label">{label}</div>
      <textarea
        className="ccai-credential-row-input"
        rows={2}
        value={value}
        onChange={e => onChange(e.target.value)}
      />
    </div>
  );
}

function EditableScoreRow({ label, value, onChange }) {
  return (
    <div className="ccai-credential-row ccai-credential-row-edit">
      <div className="ccai-credential-row-label">{label}</div>
      <input
        type="number"
        min={0}
        max={1}
        step={0.05}
        value={value}
        className="ccai-credential-row-input ccai-credential-row-input-num"
        onChange={(e) => {
          const v = parseFloat(e.target.value);
          if (!Number.isNaN(v)) onChange(Math.max(0, Math.min(1, v)));
        }}
      />
    </div>
  );
}

function FieldRow({ label, value }) {
  if (!value) return null;
  return (
    <div className="ccai-credential-row">
      <div className="ccai-credential-row-label">{label}</div>
      <div className="ccai-credential-row-value">{value}</div>
    </div>
  );
}

function toScore(value) {
  if (value === null || value === undefined) return null;
  const n = Number(value);
  if (Number.isNaN(n)) return null;
  return Math.max(0, Math.min(1, n));
}

/**
 * Flat human-readable .txt dump used by the Download button. Same
 * banner/separator style as PromptCatalogModal.renderCatalogAsText so
 * the two transparency exports look like a matched set.
 */
function renderCredentialsAsText(question, credentials) {
  const now = new Date().toISOString();
  const lines = [];
  const banner = '═'.repeat(64);
  lines.push(banner);
  lines.push('Collaborative Conversational AI (CCAI) Demo — Credential Summary');
  lines.push(`Generated: ${now}`);
  lines.push(banner);
  lines.push('');

  if (question) {
    lines.push('Question:');
    for (const ln of String(question).split('\n')) {
      lines.push('    ' + ln);
    }
    lines.push('');
  }

  const sep = '─'.repeat(12);
  lines.push(`${sep} Participants ${sep}`);
  lines.push('');

  for (const cred of credentials) {
    const score = toScore(cred.credibility_for_question);
    const name = cred.name || cred.participant_id || '(unknown)';
    lines.push(`## ${name}`);
    if (score !== null) {
      lines.push(`Credibility: ${score.toFixed(2)} of 1.00`);
    }
    if (cred.expertise) lines.push(`Expertise: ${cred.expertise}`);
    if (cred.personality) lines.push(`Style: ${cred.personality}`);
    if (cred.bias_to_watch) lines.push(`Bias to watch: ${cred.bias_to_watch}`);
    lines.push('');
  }

  return lines.join('\n');
}