File size: 11,489 Bytes
a763505
53edcb8
c44fab6
0bb4dfa
 
11bf9b7
 
4944128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c44fab6
0bb4dfa
 
 
 
 
53edcb8
 
 
 
 
0bb4dfa
 
 
 
 
4944128
0bb4dfa
 
 
 
 
 
11bf9b7
 
 
 
53edcb8
 
 
 
 
 
0bb4dfa
 
 
 
 
 
 
 
 
a763505
 
 
 
 
 
 
 
4944128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0bb4dfa
 
c44fab6
 
0bb4dfa
 
 
 
 
 
c44fab6
 
 
 
 
 
4944128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c44fab6
 
0bb4dfa
9a51d6a
 
 
 
 
 
 
0bb4dfa
9a51d6a
0bb4dfa
 
a763505
0bb4dfa
 
 
 
 
a763505
 
 
0bb4dfa
 
 
 
11bf9b7
 
 
 
 
 
 
 
 
 
 
0bb4dfa
c44fab6
 
 
 
 
 
 
 
 
0bb4dfa
c44fab6
 
53edcb8
4944128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53edcb8
 
0bb4dfa
11bf9b7
c44fab6
 
 
 
 
11bf9b7
c44fab6
 
 
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
import React, { useMemo } from 'react';
import { Table2, FileText, FileCode, FileSpreadsheet, History } from 'lucide-react';
import MessageBubble from './MessageBubble';
import OrchestratorMessage from './OrchestratorMessage';
import FailsafePauseBanner from './FailsafePauseBanner';
import HumanInputSlot from './HumanInputSlot';
import HumanTurnIndicator from './HumanTurnIndicator';
import { DEFAULT_DEMO_PERSONAS, DEFAULT_PARTICIPANT_IDS } from '../utils/storage';

/** Update when the Neon contact destination changes on the redesigned site. */
const NEON_CONTACT_URL = 'https://www.neon.ai/contact';

const [ELENA_ID, MARCUS_ID, AMIRA_ID] = DEFAULT_PARTICIPANT_IDS;

/** Dialogue-only turns for the empty-state sample; speaker ids come from the demo trio. */
const SAMPLE_PREVIEW_TURNS = [
  {
    kind: 'orchestrator',
    text:
      'Question: Should a company build its own AI system or rely on a third-party provider? '
      + 'Each participant: share your initial view.',
  },
  {
    kind: 'participant',
    speakerId: ELENA_ID,
    text:
      'Third-party APIs keep upfront cost low, but per-seat and per-token fees compound fast at scale — '
      + 'above a few million in annual AI spend, owning the stack often wins on total cost over three to five years.',
  },
  {
    kind: 'participant',
    speakerId: MARCUS_ID,
    text:
      'Build gives you control over models, prompts, and integrations; buy gets you to production in weeks. '
      + "I'd only build if the product is the AI itself, not if AI is supporting something else.",
  },
  {
    kind: 'participant',
    speakerId: AMIRA_ID,
    addressedTo: MARCUS_ID,
    replyingTo: [MARCUS_ID],
    text:
      'Where data lives matters more than who hosts the model. A vendor with strong certifications can beat a sloppy '
      + 'in-house deployment — but regulated workloads need clarity on retention, subprocessors, and whether prompts leave your boundary.',
  },
  {
    kind: 'orchestrator',
    text:
      'No single answer fits every company — the panel leans toward buy for speed and lower early risk, build when AI is '
      + 'core IP or scale makes vendor fees dominate, with privacy and compliance as the tiebreaker.',
  },
];

function buildSamplePreviewMessages(nameById) {
  return SAMPLE_PREVIEW_TURNS.map((turn) => {
    if (turn.kind === 'orchestrator') {
      return { kind: 'orchestrator', text: turn.text };
    }
    const speaker_id = turn.speakerId;
    return {
      kind: 'participant',
      role: 'participant',
      speaker_id,
      speaker_name: nameById[speaker_id] || '',
      text: turn.text,
      ...(turn.addressedTo
        ? { addressed_to: turn.addressedTo, replying_to: turn.replyingTo }
        : {}),
    };
  });
}

/**
 * Renders the conversation: a mix of participant bubbles, orchestrator
 * status banners, and the failsafe-pause continue control. Participant
 * coloring is derived from each participant's index in the active
 * roster, so colors are stable per-participant for the whole chat.
 *
 * After "End of Chat" arrives we also render a download strip below the
 * stats line that mirrors the header DownloadMenu items 1:1 (Summary
 * table view, .txt, .md, .csv, full API log). Per UX request these
 * stack vertically on narrow viewports.
 */
export default function ChatArea({
  messages,
  systemMessages,
  isRunning,
  hasEnoughParticipantsToStart,
  statusText,
  pause,
  onContinuePause,
  participants,
  showResponseTime,
  showChatStats,
  awaitingHuman,
  humanSubmitting,
  onHumanSubmit,
  onHumanSkip,
  onShowTableView,
  onDownloadChatTxt,
  onDownloadChatMd,
  onDownloadCsvTable,
  onDownloadApiLog,
  hasApiLog,
}) {
  const speakerIdxFor = useMemo(() => {
    const map = {};
    (participants || []).forEach((p, i) => {
      map[p.participant_id] = i;
    });
    return map;
  }, [participants]);

  const participantNameById = useMemo(() => {
    const m = {};
    (participants || []).forEach((p) => {
      m[p.participant_id] = p.name;
    });
    return m;
  }, [participants]);

  const defaultDemoNameById = useMemo(() => {
    const m = {};
    DEFAULT_DEMO_PERSONAS.forEach((p) => {
      m[p.participant_id] = p.name;
    });
    return m;
  }, []);

  /** Names for sample bubbles: live roster when present, else catalog mirror in storage. */
  const previewNameById = useMemo(() => {
    const m = { ...defaultDemoNameById };
    DEFAULT_PARTICIPANT_IDS.forEach((id) => {
      if (participantNameById[id]) m[id] = participantNameById[id];
    });
    return m;
  }, [defaultDemoNameById, participantNameById]);

  /** Palette index: match sidebar roster order, fall back to default trio order. */
  const previewSpeakerIdxFor = useMemo(() => {
    const map = {};
    DEFAULT_PARTICIPANT_IDS.forEach((id, defaultIdx) => {
      map[id] = speakerIdxFor[id] ?? defaultIdx;
    });
    return map;
  }, [speakerIdxFor]);

  const samplePreviewMessages = useMemo(
    () => buildSamplePreviewMessages(previewNameById),
    [previewNameById],
  );

  const hasContent = (messages?.length || 0) + (systemMessages?.length || 0) > 0;
  const chatEnded = (systemMessages || []).some(s => s.text === 'End of Chat');

  const stats = useMemo(() => {
    if (!chatEnded || !messages || messages.length === 0) return null;
    const participantMsgs = messages.filter(m => m.role !== 'orchestrator');
    const totalTime = participantMsgs.reduce(
      (sum, m) => sum + (m.elapsed_seconds || 0), 0,
    );
    return { count: participantMsgs.length, totalTime: totalTime.toFixed(1) };
  }, [chatEnded, messages]);

  return (
    <div className="chat-area">
      {!hasContent && !isRunning && (
        <div className="chat-empty">
          <div className="chat-empty-copy">
            <p className="chat-empty-lead">
              Watch a panel of AI experts debate a question, challenge each other, and reason toward a more considered answer.
            </p>
            <p className="chat-empty-instruction">
              {hasEnoughParticipantsToStart
                ? 'Three expert personas are ready to go — press Start Chat, or add, remove, or edit them to fit your question.'
                : 'Add at least 2 participants from the header dropdown, then start a conversation.'}
            </p>
          </div>
          <div className="chat-empty-sample" aria-hidden="true">
            <p className="chat-empty-sample-label">Sample preview — not a live result</p>
            <div className="chat-empty-sample-panel">
              {samplePreviewMessages.map((msg, i) => {
                if (msg.kind === 'orchestrator') {
                  return (
                    <OrchestratorMessage
                      key={`preview-orch-${i}`}
                      message={{ text: msg.text }}
                      messageIdx={i}
                    />
                  );
                }
                const prev = i > 0 ? samplePreviewMessages[i - 1] : null;
                const prevParticipant =
                  prev?.kind === 'participant' ? prev : null;
                return (
                  <MessageBubble
                    key={`preview-${msg.speaker_id}-${i}`}
                    message={msg}
                    idx={previewSpeakerIdxFor[msg.speaker_id] ?? 0}
                    messageIdx={i}
                    prevMessage={prevParticipant}
                    participantNameById={previewNameById}
                    showResponseTime={false}
                  />
                );
              })}
            </div>
          </div>
        </div>
      )}
      {(messages || []).map((msg, i) => {
        if (msg.role === 'system') {
          return (
            <div key={msg.message_id || `sys-inline-${i}`} className="system-message">
              {msg.text}
            </div>
          );
        }
        if (msg.role === 'orchestrator') {
          return <OrchestratorMessage key={msg.message_id || i} message={msg} messageIdx={i} />;
        }
        const idx = speakerIdxFor[msg.speaker_id] ?? i;
        const prev = i > 0 ? messages[i - 1] : null;
        return (
          <MessageBubble
            key={i}
            message={msg}
            idx={idx}
            messageIdx={i}
            prevMessage={prev}
            participantNameById={participantNameById}
            showResponseTime={showResponseTime}
          />
        );
      })}
      {awaitingHuman && (
        <div data-human-slot>
          <HumanInputSlot
            awaiting={awaitingHuman}
            sending={humanSubmitting}
            onSubmit={onHumanSubmit}
            onSkip={onHumanSkip}
            allowSkip
          />
        </div>
      )}
      {(systemMessages || []).map((sys, i) => (
        <div
          key={`sys-${i}`}
          className={`system-message ${sys.text === 'End of Chat' ? 'end-of-chat' : ''}`}
        >
          {sys.text}
        </div>
      ))}
      {showChatStats && stats && (
        <div className="chat-stats">
          {stats.count} participant messages &middot; {stats.totalTime}s total generation time
        </div>
      )}
      {chatEnded && (
        <div className="chat-end-bar">
          <div className="chat-end-downloads" role="group" aria-label="Conversation downloads">
            <button
              type="button"
              className="btn-sm btn-outline chat-end-download-btn"
              onClick={onShowTableView}
              title="Open the conversation summary table"
            >
              <Table2 size={14} />
              Summary table…
            </button>
            <button
              type="button"
              className="btn-sm btn-outline chat-end-download-btn"
              onClick={onDownloadChatTxt}
            >
              <FileText size={14} />
              Chat as .txt
            </button>
            <button
              type="button"
              className="btn-sm btn-outline chat-end-download-btn"
              onClick={onDownloadChatMd}
            >
              <FileCode size={14} />
              Chat as .md
            </button>
            <button
              type="button"
              className="btn-sm btn-outline chat-end-download-btn"
              onClick={onDownloadCsvTable}
              title="Download the summary table as CSV"
            >
              <FileSpreadsheet size={14} />
              Summary table as .csv
            </button>
            <button
              type="button"
              className="btn-sm btn-outline chat-end-download-btn"
              onClick={onDownloadApiLog}
              disabled={!hasApiLog}
              title="Download the full backend API call history for this session"
            >
              <History size={14} />
              Full API history
            </button>
          </div>
          <p className="chat-end-cta">
            Want a panel like this running on your own infrastructure?{' '}
            <a
              href={NEON_CONTACT_URL}
              target="_blank"
              rel="noopener noreferrer"
            >
              Talk to Neon
            </a>
          </p>
        </div>
      )}
      <FailsafePauseBanner pause={pause} onContinue={onContinuePause} />
      {isRunning && statusText && !awaitingHuman && (
        <div className="status-bar">
          <div className="spinner" />
          <span>{statusText}</span>
        </div>
      )}
      <HumanTurnIndicator awaiting={awaitingHuman} />
    </div>
  );
}