File size: 8,725 Bytes
63d0776
c69ef3e
c232e44
 
 
 
 
 
 
 
11e3c5e
 
0fd8446
c232e44
a1c5622
 
63d0776
 
c232e44
63d0776
 
 
 
 
 
c232e44
 
 
 
 
 
 
 
0fd8446
 
3ba9c0c
 
a1c5622
5613eec
3ba9c0c
 
92f037b
0fd8446
c232e44
 
0fd8446
c232e44
 
 
 
 
 
 
0fd8446
 
f80b091
0fd8446
c232e44
 
f80b091
0fd8446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f80b091
c232e44
 
 
 
 
0fd8446
c232e44
0fd8446
c232e44
 
 
 
 
 
 
 
 
 
 
0fd8446
c232e44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46f65e5
a1c5622
c232e44
 
 
 
 
 
 
 
 
 
11e3c5e
 
 
0fd8446
 
11e3c5e
 
 
 
 
 
 
0fd8446
 
11e3c5e
0fd8446
 
11e3c5e
 
 
 
 
c232e44
 
 
 
63d0776
 
c232e44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11e3c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c232e44
 
 
 
11e3c5e
0fd8446
 
11e3c5e
 
 
0fd8446
 
11e3c5e
0fd8446
 
11e3c5e
0fd8446
 
11e3c5e
 
 
0fd8446
 
11e3c5e
0fd8446
 
11e3c5e
 
c232e44
0fd8446
 
 
 
 
 
 
 
 
 
 
 
 
f80b091
 
c232e44
 
 
 
 
 
 
 
 
 
 
0fd8446
c232e44
 
 
 
a1c5622
c232e44
 
0fd8446
 
 
 
 
 
 
c232e44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useMemo, useState } from 'react';
import { CodeBlock } from '@/components/ui/CodeBlock';
import {
  IconCheckCircle,
  IconCodeWrap,
  IconCrossCircle,
  IconLandingAI,
  IconListUnordered,
  IconTerminalWindow,
  IconUser,
  IconOutput,
  IconLog,
  IconGlowingDot,
} from '@/components/ui/Icons';
import { MessageUI } from '@/lib/types';
import { ChunkBody, CodeResult, formatStreamLogs } from '@/lib/utils/content';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '../ui/Table';
import { Button } from '../ui/Button';
import { Separator } from '../ui/Separator';
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from '@/components/ui/Tooltip';

import { Dialog, DialogContent, DialogTrigger } from '../ui/Dialog';
import { Markdown } from './MemoizedReactMarkdown';
import Img from '../ui/Img';

export interface ChatMessageProps {
  message: MessageUI;
  isLoading: boolean;
}

export function ChatMessage({ message, isLoading }: ChatMessageProps) {
  const { role, content, mediaUrl } = message;

  return role === 'user' ? (
    <UserChatMessage content={content} mediaUrl={mediaUrl} />
  ) : (
    <AssistantChatMessage content={content} />
  );
}

const UserChatMessage: React.FC<{
  content: string;
  mediaUrl?: string;
}> = ({ content, mediaUrl }) => {
  return (
    <div className="group relative mb-6 flex rounded-md bg-muted p-6 ml-auto mr-0 w-3/5">
      <div className="flex size-8 shrink-0 select-none items-center justify-center rounded-md border shadow bg-background">
        <IconUser />
      </div>
      <div className="flex-1 px-1 ml-4 space-y-3 overflow-hidden">
        <p>{content}</p>
        {mediaUrl && (
          <>
            {mediaUrl?.endsWith('.mp4') ? (
              <video src={mediaUrl} controls width={500} height={500} />
            ) : (
              <Img
                src={mediaUrl}
                alt={mediaUrl}
                quality={100}
                sizes="(min-width: 66em) 15vw,
                        (min-width: 44em) 20vw,
                        100vw"
              />
            )}
          </>
        )}
      </div>
    </div>
  );
};

const ChunkStatusToIconDict: Record<ChunkBody['status'], React.ReactElement> = {
  started: <IconGlowingDot className="bg-yellow-500/80" />,
  completed: <IconCheckCircle className="text-green-500" />,
  running: <IconGlowingDot className="bg-teal-500/80" />,
  failed: <IconCrossCircle className="text-red-500" />,
};
const ChunkTypeToTextDict: Record<ChunkBody['type'], string> = {
  plans: 'Creating instructions',
  tools: 'Retrieving tools',
  code: 'Generating code',
  final_code: 'Final result',
};
const ChunkPayloadAction: React.FC<{
  payload: ChunkBody['payload'];
}> = ({ payload }) => {
  if (!payload) return null;
  if (Array.isArray(payload)) {
    // [{title: 123, content, 345}, {title: ..., content: ...}] => ['title', 'content']
    const keyArray = Array.from(
      payload.reduce((acc, curr) => {
        Object.keys(curr).forEach(key => acc.add(key));
        return acc;
      }, new Set<string>()),
    );

    return (
      <Dialog>
        <DialogTrigger asChild>
          <Button variant="ghost" size="icon">
            <IconListUnordered />
          </Button>
        </DialogTrigger>
        <DialogContent className="max-w-5xl" onOpenAutoFocus={e => e.preventDefault()}>
          <Table>
            <TableHeader>
              <TableRow className="border-primary/50">
                {keyArray.map(header => (
                  <TableHead key={header}>{header}</TableHead>
                ))}
              </TableRow>
            </TableHeader>
            <TableBody>
              {payload.map((line, index) => (
                <TableRow className="border-primary/50" key={index}>
                  {keyArray.map(header =>
                    header === 'documentation' ? (
                      <TableCell key={header}>
                        <Dialog>
                          <DialogTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="size-8 ml-[40%]"
                            >
                              <IconTerminalWindow className="text-teal-500 size-4" />
                            </Button>
                          </DialogTrigger>
                          <DialogContent className="max-w-5xl">
                            <CodeBlock language="md" value={line[header]} />
                          </DialogContent>
                        </Dialog>
                      </TableCell>
                    ) : (
                      <TableCell key={header}>{line[header]}</TableCell>
                    ),
                  )}
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </DialogContent>
      </Dialog>
    );
  } else {
    return (
      <Dialog>
        <DialogTrigger asChild>
          <Button variant="ghost" size="icon">
            <IconCodeWrap />
          </Button>
        </DialogTrigger>
        <DialogContent className="max-w-5xl">
          <CodeResultDisplay codeResult={payload as CodeResult} />
        </DialogContent>
      </Dialog>
    );
  }
};

const CodeResultDisplay: React.FC<{
  codeResult: CodeResult;
}> = ({ codeResult }) => {
  const { code, test, result } = codeResult;
  const getDetail = () => {
    if (!result) return {};
    try {
      const detail = JSON.parse(result);
      return {
        results: detail.results,
        stderr: detail.logs.stderr,
        stdout: detail.logs.stdout,
      };
    } catch {
      return {};
    }
  };

  const { results, stderr, stdout } = getDetail();

  return (
    <div className="rounded-lg overflow-hidden relative max-w-5xl">
      <CodeBlock language="python" value={code} />
      <div className="rounded-lg relative">
        <div className="absolute left-1/2 -translate-x-1/2 -top-4 z-10">
          <Dialog>
            <DialogTrigger asChild>
              <Button variant="ghost" size="icon" className="size-8">
                <IconTerminalWindow className="text-teal-500 size-4" />
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-5xl">
              <CodeBlock language="python" value={test} />
            </DialogContent>
          </Dialog>
          {Array.isArray(stderr) && (
            <Dialog>
              <DialogTrigger asChild>
                <Button variant="ghost" size="icon" className="size-8">
                  <IconLog className="text-gray-500 size-4" />
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-5xl">
                <CodeBlock language="vim" value={stderr.join('').trim()} />
              </DialogContent>
            </Dialog>
          )}
        </div>
      </div>
      {Array.isArray(stdout) && !!stdout.join('').trim() && (
        <>
          <Separator />
          <CodeBlock language="print" value={stdout.join('').trim()} />
        </>
      )}
      {!!results.length && (
        <>
          <Separator />
          <CodeBlock language="output" value={results} />
        </>
      )}
      <Separator />
    </div>
  );
};

const AssistantChatMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  const [formattedSections, codeResult] = useMemo(
    () => formatStreamLogs(content),
    [content],
  );

  return (
    <div className="group relative mb-6 flex rounded-md bg-muted p-6 w-full">
      <div className="flex size-8 shrink-0 select-none items-center justify-center rounded-md border shadow bg-primary text-primary-foreground">
        <IconLandingAI />
      </div>
      <div className="flex-1 px-1 space-y-4 ml-4 overflow-hidden">
        <Table className="w-[400px]">
          <TableBody>
            {formattedSections.map(section => (
              <TableRow
                className="border-primary/50 h-[56px]"
                key={section.type}
              >
                <TableCell className="text-center text-webkit-center">
                  {ChunkStatusToIconDict[section.status]}
                </TableCell>
                <TableCell className="font-medium">
                  {ChunkTypeToTextDict[section.type]}
                </TableCell>
                <TableCell className="text-right">
                  <ChunkPayloadAction payload={section.payload} />
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
        {codeResult && <CodeResultDisplay codeResult={codeResult} />}
      </div>
    </div>
  );
};

export default UserChatMessage;