File size: 15,098 Bytes
b976f1b
 
 
6277dae
 
 
2c01580
 
 
 
 
 
 
 
 
b976f1b
2c01580
 
 
 
 
b976f1b
 
 
 
34baa5d
4d3c21a
6f7cf01
 
34baa5d
 
 
2c01580
 
 
 
 
6f7cf01
4d3c21a
 
6f7cf01
4d3c21a
15402d8
 
2c01580
34baa5d
b976f1b
 
34baa5d
 
 
b976f1b
34baa5d
2c01580
 
 
 
 
 
 
34baa5d
 
2c01580
 
 
 
 
 
 
 
 
 
 
b976f1b
 
 
34baa5d
 
 
b976f1b
4d3c21a
 
6f7cf01
4d3c21a
 
34baa5d
2c01580
 
 
34baa5d
 
 
2c01580
 
 
b976f1b
34baa5d
 
b976f1b
 
2c01580
 
34baa5d
 
 
 
 
b976f1b
34baa5d
0ef5c60
 
b976f1b
34baa5d
 
 
 
b976f1b
34baa5d
 
 
 
 
15402d8
0ef5c60
 
34baa5d
 
 
b976f1b
34baa5d
0ef5c60
 
34baa5d
2c01580
 
 
0ef5c60
 
4d3c21a
6f7cf01
 
 
 
 
4d3c21a
 
 
 
6f7cf01
4d3c21a
6f7cf01
 
 
 
 
 
 
4d3c21a
 
 
6f7cf01
4d3c21a
 
6f7cf01
 
 
 
4d3c21a
6f7cf01
 
4d3c21a
 
 
6f7cf01
b976f1b
 
2c01580
 
 
 
b976f1b
2c01580
 
 
 
 
 
 
 
 
b976f1b
 
 
 
2c01580
 
 
 
 
b976f1b
 
 
 
 
 
 
9cc33f2
6f7cf01
b976f1b
6f7cf01
 
9cc33f2
 
8cf6e59
2c01580
9cc33f2
8cf6e59
 
 
 
6f7cf01
2c01580
 
 
 
8cf6e59
2c01580
6f7cf01
 
b976f1b
 
2c01580
b976f1b
 
15402d8
 
34baa5d
2c01580
 
 
 
 
34baa5d
 
b976f1b
34baa5d
6f7cf01
34baa5d
ecc7c65
34baa5d
b976f1b
 
 
 
34baa5d
 
 
ecc7c65
 
0ef5c60
34baa5d
 
 
 
 
0ef5c60
b976f1b
2c01580
 
 
b976f1b
34baa5d
2c01580
34baa5d
 
 
2c01580
 
 
 
 
34baa5d
0ef5c60
 
2c01580
 
 
 
 
 
 
b976f1b
15402d8
 
2c01580
4d3c21a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34baa5d
2c01580
34baa5d
 
 
 
6f7cf01
4d3c21a
 
34baa5d
 
 
 
 
 
 
 
 
 
 
 
2c01580
34baa5d
 
 
 
 
 
4d3c21a
 
 
34baa5d
 
 
 
b976f1b
34baa5d
 
 
 
 
 
 
 
2c01580
 
 
34baa5d
b976f1b
34baa5d
 
 
 
 
 
 
 
2c01580
 
 
34baa5d
b976f1b
34baa5d
 
 
 
 
 
 
 
 
2c01580
34baa5d
 
 
4d3c21a
 
 
 
 
 
 
 
 
34baa5d
 
 
b976f1b
34baa5d
 
 
 
b976f1b
34baa5d
 
 
 
 
 
 
0ef5c60
 
34baa5d
 
 
 
 
 
 
 
4d3c21a
0ef5c60
 
2c01580
 
 
4d3c21a
2c01580
4d3c21a
34baa5d
 
 
 
 
 
 
 
 
 
 
b976f1b
2c01580
 
 
34baa5d
 
 
 
 
 
 
 
0ef5c60
34baa5d
0ef5c60
6277dae
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// web/src/components/Message.tsx
import React, { useMemo, useState } from "react";
import { Button } from "./ui/button";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";

import {
  Copy,
  ThumbsUp,
  ThumbsDown,
  ChevronDown,
  ChevronUp,
  Check,
  X,
} from "lucide-react";
import { Badge } from "./ui/badge";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "./ui/collapsible";
import { Textarea } from "./ui/textarea";
import type { Message as MessageType } from "../App";
import { toast } from "sonner";
import clareAvatar from "../assets/dfe44dab3ad8cd93953eac4a3e68bd1a5f999653.png";

// ✅ NEW: real API call
import { apiFeedback } from "../lib/api";

interface MessageProps {
  key?: React.Key;
  message: MessageType;
  showSenderInfo?: boolean; // For group chat mode
  isFirstGreeting?: boolean; // Indicates if this is the first greeting message
  showNextButton?: boolean; // For quiz mode
  onNextQuestion?: () => void; // For quiz mode
  chatMode?: "ask" | "review" | "quiz"; // Current chat mode

  // ✅ NEW: for feedback submission
  currentUserId?: string;
  docType?: string;
  learningMode?: string;
}

// 反馈标签选项
const FEEDBACK_TAGS = {
  "not-helpful": [
    "Code was incorrect",
    "Shouldn't have used Memory",
    "Don't like the personality",
    "Don't like the style",
    "Not factually correct",
  ],
  helpful: [
    "Accurate and helpful",
    "Clear explanation",
    "Good examples",
    "Solved my problem",
    "Well structured",
  ],
};

// ---- Markdown list normalization ----
function normalizeMarkdownLists(input: string) {
  if (!input) return input;

  return (
    input
      .replace(/(^|\n)(\s*)(\d+\.)\s*\n+\s+/g, "$1$2$3 ")
      .replace(/(^|\n)(\s*)([-*+])\s*\n+\s+/g, "$1$2$3 ")
  );
}

export function Message({
  message,
  showSenderInfo = false,
  isFirstGreeting = false,
  showNextButton = false,
  onNextQuestion,
  chatMode = "ask",

  // ✅ NEW
  currentUserId,
  docType = "Syllabus",
  learningMode = "general",
}: MessageProps) {
  const [feedback, setFeedback] = useState<"helpful" | "not-helpful" | null>(
    null
  );
  const [copied, setCopied] = useState(false);
  const [referencesOpen, setReferencesOpen] = useState(false);
  const [showFeedbackArea, setShowFeedbackArea] = useState(false);
  const [feedbackType, setFeedbackType] = useState<
    "helpful" | "not-helpful" | null
  >(null);
  const [feedbackText, setFeedbackText] = useState("");
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [nextButtonClicked, setNextButtonClicked] = useState(false);

  const isUser = message.role === "user";
  const isWelcomeMessage =
    isFirstGreeting || message.id === "review-1" || message.id === "quiz-1";
  const shouldShowActions = isUser ? true : !isWelcomeMessage;

  const handleCopy = async () => {
    await navigator.clipboard.writeText(message.content);
    setCopied(true);
    toast.success("Message copied to clipboard");
    setTimeout(() => setCopied(false), 2000);
  };

  const handleFeedbackClick = (type: "helpful" | "not-helpful") => {
    if (feedback === type) {
      setFeedback(null);
      setShowFeedbackArea(false);
      setFeedbackType(null);
      setFeedbackText("");
      setSelectedTags([]);
    } else {
      setFeedback(type);
      setFeedbackType(type);
      setShowFeedbackArea(true);
    }
  };

  const handleFeedbackClose = () => {
    setShowFeedbackArea(false);
    setFeedbackType(null);
    setFeedbackText("");
    setSelectedTags([]);
  };

  const handleTagToggle = (tag: string) => {
    setSelectedTags((prev) =>
      prev.includes(tag) ? prev.filter((t) => t !== tag) : [...prev, tag]
    );
  };

  // ✅ REAL submit to backend -> LangSmith dataset
  const handleFeedbackSubmit = async () => {
    if (!currentUserId || !currentUserId.trim()) {
      toast.error("Missing user_id; cannot submit feedback.");
      return;
    }
    if (!feedbackType) {
      toast.error("Please select Helpful / Not helpful.");
      return;
    }

    // UI uses "not-helpful" (dash), backend expects "not_helpful" (underscore)
    const rating = feedbackType === "helpful" ? "helpful" : "not_helpful";

    try {
      await apiFeedback({
        user_id: currentUserId,
        rating,
        assistant_message_id: message.id,
        assistant_text: message.content,
        user_text: "", // optional; you can wire last user msg later if you want
        comment: feedbackText || "",
        tags: selectedTags,
        refs: message.references ?? [],
        learning_mode: chatMode === "ask" ? learningMode : chatMode,
        doc_type: docType,
        timestamp_ms: Date.now(),
      });

      toast.success("Thanks — feedback submitted.");
      handleFeedbackClose();
    } catch (e: any) {
      // eslint-disable-next-line no-console
      console.error("feedback submit failed:", e);
      toast.error(e?.message || "Failed to submit feedback.");
    }
  };

  const normalizedMarkdown = useMemo(() => {
    return normalizeMarkdownLists(message.content || "");
  }, [message.content]);

  const markdownClass = useMemo(() => {
    return [
      "text-base leading-relaxed break-words",
      " [&_p]:my-2",
      " [&_p:first-child]:mt-0",
      " [&_p:last-child]:mb-0",
      " [&_code]:px-1 [&_code]:py-0.5 [&_code]:rounded [&_code]:bg-black/5 dark:[&_code]:bg-white/10",
      " [&_pre]:my-2 [&_pre]:p-3 [&_pre]:rounded-lg [&_pre]:overflow-auto [&_pre]:bg-black/5 dark:[&_pre]:bg-white/10",
      " [&_a]:underline [&_a]:underline-offset-2",
    ].join("");
  }, []);

  const renderBubbleContent = () => {
    if (isUser) {
      return (
        <p className="whitespace-pre-wrap text-base break-words">
          {message.content}
        </p>
      );
    }

    return (
      <ReactMarkdown
        remarkPlugins={[remarkGfm]}
        className={markdownClass}
        components={{
          p: ({ children }) => (
            <p className="my-2 whitespace-pre-wrap break-words">{children}</p>
          ),
          ul: ({ children }) => <ul className="my-3 pl-6 space-y-2">{children}</ul>,
          ol: ({ children }) => <ol className="my-3 space-y-4">{children}</ol>,
          li: ({ children, node }) => {
            const parent = (node as any)?.parent?.tagName;
            if (parent === "ol") {
              return (
                <li className="list-none">
                  <div className="flex items-start">
                    <span className="w-6 text-right pr-2 flex-shrink-0 font-medium">
                      {(node as any)?.index + 1}.
                    </span>
                    <div className="min-w-0">{children}</div>
                  </div>
                </li>
              );
            }
            return <li>{children}</li>;
          },
          strong: ({ children }) => <strong className="font-semibold">{children}</strong>,
          em: ({ children }) => <em className="italic">{children}</em>,
        }}
      >
        {normalizedMarkdown}
      </ReactMarkdown>
    );
  };

  return (
    <div
      className={`flex gap-2 ${
        isUser && !showSenderInfo ? "justify-end" : "justify-start"
      } px-4`}
    >
      {/* Avatar */}
      {showSenderInfo && message.sender ? (
        <div className="w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 overflow-hidden bg-white">
          {message.sender.isAI ? (
            <img src={clareAvatar} alt="Clare" className="w-full h-full object-cover" />
          ) : (
            <img
              src={
                message.sender.avatar ||
                `https://api.dicebear.com/7.x/avataaars/svg?seed=${encodeURIComponent(
                  message.sender.email || message.sender.name
                )}`
              }
              alt={message.sender.name}
              className="w-full h-full object-cover"
            />
          )}
        </div>
      ) : !isUser ? (
        <div className="w-10 h-10 rounded-full overflow-hidden bg-white flex items-center justify-center flex-shrink-0">
          <img src={clareAvatar} alt="Clare" className="w-full h-full object-cover" />
        </div>
      ) : null}

      <div
        className={`group flex flex-col gap-2 ${
          isUser && !showSenderInfo ? "items-end" : "items-start"
        }`}
        style={{ maxWidth: "min(770px, calc(100% - 2rem))" }}
      >
        {/* Sender name in group chat */}
        {showSenderInfo && message.sender && (
          <div className="flex items-center gap-2 px-1">
            <span className="text-xs">{message.sender.name}</span>
            {message.sender.isAI && (
              <Badge variant="secondary" className="text-xs h-4 px-1">
                AI
              </Badge>
            )}
          </div>
        )}

        {/* Bubble */}
        <div
          className={`
            rounded-2xl px-4 py-3
            ${isUser && !showSenderInfo ? "bg-primary text-primary-foreground" : "bg-muted"}
          `}
        >
          {renderBubbleContent()}
        </div>

        {/* Next Question Button for Quiz Mode */}
        {!isUser &&
          showNextButton &&
          !nextButtonClicked &&
          chatMode === "quiz" &&
          onNextQuestion && (
            <div className="mt-2">
              <Button
                onClick={() => {
                  setNextButtonClicked(true);
                  onNextQuestion();
                }}
                className="bg-primary hover:bg-primary/90"
              >
                Next Question
              </Button>
            </div>
          )}

        {/* References */}
        {message.references && message.references.length > 0 && (
          <Collapsible open={referencesOpen} onOpenChange={setReferencesOpen}>
            <CollapsibleTrigger asChild>
              <Button variant="ghost" size="sm" className="gap-1 h-7 text-xs">
                {referencesOpen ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
                {message.references.length}{" "}
                {message.references.length === 1 ? "reference" : "references"}
              </Button>
            </CollapsibleTrigger>
            <CollapsibleContent className="space-y-1 mt-1">
              {message.references.map((ref, index) => (
                <Badge key={index} variant="outline" className="text-xs">
                  {ref}
                </Badge>
              ))}
            </CollapsibleContent>
          </Collapsible>
        )}

        {/* Message Actions */}
        {shouldShowActions && (
          <div className="flex items-center gap-1">
            <Button
              variant="ghost"
              size="icon"
              className={`h-7 w-7 rounded-md transition-all hover:bg-accent hover:scale-110 active:scale-95 ${
                copied
                  ? "bg-green-100 text-green-600 dark:bg-green-900/20 dark:text-green-400"
                  : ""
              }`}
              onClick={handleCopy}
              title="Copy"
            >
              {copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
            </Button>

            {!isUser && (
              <>
                <Button
                  variant="ghost"
                  size="icon"
                  className={`h-7 w-7 rounded-md transition-all hover:bg-accent hover:scale-110 active:scale-95 ${
                    feedback === "helpful"
                      ? "bg-green-100 text-green-600 dark:bg-green-900/20 dark:text-green-400"
                      : ""
                  }`}
                  onClick={() => handleFeedbackClick("helpful")}
                  title="Helpful"
                >
                  <ThumbsUp className="h-4 w-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="icon"
                  className={`h-7 w-7 rounded-md transition-all hover:bg-accent hover:scale-110 active:scale-95 ${
                    feedback === "not-helpful"
                      ? "bg-red-100 text-red-600 dark:bg-red-900/20 dark:text-red-400"
                      : ""
                  }`}
                  onClick={() => handleFeedbackClick("not-helpful")}
                  title="Not helpful"
                >
                  <ThumbsDown className="h-4 w-4" />
                </Button>
              </>
            )}
          </div>
        )}

        {/* Feedback Area */}
        {!isUser && showFeedbackArea && feedbackType && (
          <div className="w-full mt-2 bg-gray-50 dark:bg-gray-800/50 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
            <div className="flex items-start justify-between mb-4">
              <h4 className="text-sm font-medium text-gray-900 dark:text-gray-100">
                Tell us more:
              </h4>
              <Button
                variant="ghost"
                size="sm"
                className="h-6 w-6 p-0"
                onClick={handleFeedbackClose}
              >
                <X className="h-4 w-4" />
              </Button>
            </div>

            <div className="flex flex-wrap gap-2 mb-4">
              {FEEDBACK_TAGS[feedbackType].map((tag) => (
                <Button
                  key={tag}
                  variant={selectedTags.includes(tag) ? "default" : "outline"}
                  size="sm"
                  className="h-7 text-xs"
                  onClick={() => handleTagToggle(tag)}
                >
                  {tag}
                </Button>
              ))}
            </div>

            <Textarea
              className="min-h-[60px] mb-4 bg-gray-100/50 dark:bg-gray-700/50 border-gray-200 dark:border-gray-600"
              value={feedbackText}
              onChange={(e) => setFeedbackText(e.target.value)}
              placeholder="Additional feedback (optional)..."
            />

            <div className="flex justify-end gap-2">
              <Button variant="outline" size="sm" onClick={handleFeedbackClose}>
                Cancel
              </Button>
              <Button
                size="sm"
                onClick={handleFeedbackSubmit}
                disabled={selectedTags.length === 0 && !feedbackText.trim()}
              >
                Submit
              </Button>
            </div>
          </div>
        )}
      </div>

      {isUser && !showSenderInfo && (
        <div className="w-10 h-10 rounded-full overflow-hidden bg-white flex items-center justify-center flex-shrink-0">
          {message.sender ? (
            <img
              src={
                message.sender.avatar ||
                `https://api.dicebear.com/7.x/avataaars/svg?seed=${encodeURIComponent(
                  message.sender.email || message.sender.name
                )}`
              }
              alt={message.sender.name}
              className="w-full h-full object-cover"
            />
          ) : (
            <span className="text-base">👤</span>
          )}
        </div>
      )}
    </div>
  );
}