File size: 10,623 Bytes
7540aea
 
 
 
 
 
1f28fab
7540aea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f28fab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7540aea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec449f9
 
 
 
 
 
 
 
 
1f28fab
 
 
 
 
 
ec449f9
1f28fab
 
 
ec449f9
 
1f28fab
 
7540aea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f28fab
7540aea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { cn } from "@/lib/utils";
import { User, Bot, Copy, Check, RotateCcw, Pencil, Minimize2 } from "lucide-react";
import { useState } from "react";
import { ToolCallCard } from "./ToolCallCard";
import { ThinkingBlock, extractThinkingBlocks } from "./ThinkingBlock";
import { Streamdown } from "streamdown";
import type { ChatMessage, ContentSegment } from "@/hooks/useChat";

export function MessageBubble({
  message,
  onRetry,
  onEdit,
}: {
  message: ChatMessage;
  onRetry?: () => void;
  onEdit?: (content: string) => void;
}) {
  const [copied, setCopied] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editValue, setEditValue] = useState(message.content);
  const isUser = message.role === "user";
  const isSystem = message.role === "system";

  const copyContent = () => {
    if (message.content) {
      navigator.clipboard.writeText(message.content);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  const handleEdit = () => {
    setIsEditing(true);
    setEditValue(message.content);
  };

  const submitEdit = () => {
    if (onEdit && editValue.trim()) {
      onEdit(editValue.trim());
    }
    setIsEditing(false);
  };

  if (isSystem) {
    // Detect compact report (matches original format_compact_report)
    const isCompactReport = message.content.startsWith("Compact\n");
    if (isCompactReport) {
      return (
        <div className="flex justify-center my-3">
          <div className="flex items-center gap-2 text-xs text-amber-400/80 bg-amber-500/10 border border-amber-500/20 px-4 py-2 rounded-lg max-w-xl font-mono">
            <Minimize2 className="size-3.5 shrink-0" />
            <pre className="whitespace-pre text-[11px] leading-relaxed">{message.content}</pre>
          </div>
        </div>
      );
    }
    return (
      <div className="flex justify-center my-2">
        <div className="text-xs text-muted-foreground bg-accent/30 px-3 py-1.5 rounded-full max-w-xl">
          <Streamdown>{message.content}</Streamdown>
        </div>
      </div>
    );
  }

  // ─── Segmented rendering for assistant messages ───────────────────
  // If we have contentSegments, render them in order (interleaved text + tools).
  // Otherwise fall back to legacy rendering (all tools then all text).
  const hasSegments = !isUser && message.contentSegments && message.contentSegments.length > 0;
  const toolCalls = message.toolCalls || [];

  const renderSegmentedContent = () => {
    if (!message.contentSegments) return null;

    return message.contentSegments.map((segment: ContentSegment, i: number) => {
      if (segment.type === "text") {
        const text = segment.content?.trim();
        if (!text) return null;
        return (
          <div
            key={`seg-text-${i}`}
            className="text-sm leading-relaxed text-foreground/90 prose prose-invert prose-sm max-w-none mt-1.5"
          >
            <Streamdown>{segment.content}</Streamdown>
          </div>
        );
      }
      if (segment.type === "tool") {
        const tool = toolCalls[segment.toolIndex];
        if (!tool) return null;
        return (
          <div key={`seg-tool-${i}`} className="mt-1.5">
            <ToolCallCard tool={tool} />
          </div>
        );
      }
      return null;
    });
  };

  const renderLegacyContent = () => {
    return (
      <>
        {/* Tool calls β€” show BEFORE message text */}
        {toolCalls.length > 0 && (
          <div className="mt-2 space-y-1">
            {toolCalls.map((tool) => (
              <ToolCallCard key={tool.id} tool={tool} />
            ))}
          </div>
        )}

        {/* Message text β€” after tool calls */}
        {isEditing ? (
          <div className="inline-block text-left max-w-[85%]">
            <textarea
              value={editValue}
              onChange={(e) => setEditValue(e.target.value)}
              className="w-full bg-input border border-border rounded-lg px-3 py-2 text-sm font-mono outline-none focus:border-primary resize-none min-h-[60px]"
              autoFocus
              onKeyDown={(e) => {
                if (e.key === "Enter" && !e.shiftKey) {
                  e.preventDefault();
                  submitEdit();
                }
                if (e.key === "Escape") setIsEditing(false);
              }}
            />
            <div className="flex gap-1.5 mt-1 justify-end">
              <button
                onClick={() => setIsEditing(false)}
                className="text-xs px-2 py-1 rounded bg-muted text-muted-foreground hover:bg-accent"
              >
                Cancel
              </button>
              <button
                onClick={submitEdit}
                className="text-xs px-2 py-1 rounded bg-primary text-primary-foreground hover:bg-primary/90"
              >
                Save
              </button>
            </div>
          </div>
        ) : message.content ? (
          <div
            className={cn(
              "text-sm leading-relaxed",
              isUser
                ? "bg-primary/10 rounded-2xl rounded-tr-sm px-4 py-2.5 inline-block text-left max-w-[85%]"
                : "text-foreground/90 prose prose-invert prose-sm max-w-none",
              toolCalls.length > 0 ? "mt-2" : ""
            )}
          >
            {isUser ? (
              <span className="whitespace-pre-wrap">{message.content}</span>
            ) : (
              <Streamdown>{message.content}</Streamdown>
            )}
            {message.isStreaming && <span className="streaming-cursor" />}
          </div>
        ) : null}
      </>
    );
  };

  return (
    <div
      className={cn(
        "group flex gap-3 py-4 px-4",
        isUser ? "flex-row-reverse" : ""
      )}
    >
      {/* Avatar */}
      <div
        className={cn(
          "size-7 rounded-lg shrink-0 flex items-center justify-center mt-0.5",
          isUser
            ? "bg-primary/20 text-primary"
            : "bg-accent text-accent-foreground"
        )}
      >
        {isUser ? <User className="size-4" /> : <Bot className="size-4" />}
      </div>

      {/* Content */}
      <div className={cn("flex-1 min-w-0", isUser ? "text-right" : "")}>
        <div
          className={cn(
            "flex items-center gap-2 mb-1",
            isUser ? "justify-end" : ""
          )}
        >
          <span className="text-xs font-medium text-muted-foreground">
            {isUser ? "You" : "Claw"}
          </span>
          {message.model && (
            <span className="text-[10px] text-muted-foreground/60 font-mono">
              {message.model}
            </span>
          )}
          {/* Action buttons */}
          <div className="opacity-0 group-hover:opacity-100 transition-opacity flex items-center gap-1">
            {message.content && (
              <button
                onClick={copyContent}
                className="text-muted-foreground hover:text-foreground transition-colors"
                title="Copy"
              >
                {copied ? (
                  <Check className="size-3" />
                ) : (
                  <Copy className="size-3" />
                )}
              </button>
            )}
            {isUser && onEdit && (
              <button
                onClick={handleEdit}
                className="text-muted-foreground hover:text-foreground transition-colors"
                title="Edit"
              >
                <Pencil className="size-3" />
              </button>
            )}
            {!isUser && onRetry && (
              <button
                onClick={onRetry}
                className="text-muted-foreground hover:text-foreground transition-colors"
                title="Retry"
              >
                <RotateCcw className="size-3" />
              </button>
            )}
          </div>
        </div>

        {/* Thinking blocks β€” show first (model reasoning) */}
        {!isUser && message.thinkingBlocks && message.thinkingBlocks.length > 0 && (
          <div className="mt-1">
            {message.thinkingBlocks.map((block: any, i: number) => (
              <ThinkingBlock key={i} thinking={block.thinking} durationMs={block.durationMs} />
            ))}
          </div>
        )}

        {/* ─── Main content area ─── */}
        {hasSegments ? (
          // New: Interleaved rendering β€” text and tools in the order they arrived
          <div className="mt-1">
            {renderSegmentedContent()}
            {message.isStreaming && <span className="streaming-cursor" />}
          </div>
        ) : (
          // Legacy: all tools first, then all text
          renderLegacyContent()
        )}

        {/* Editing UI for user messages */}
        {isUser && isEditing && (
          <div className="inline-block text-left max-w-[85%]">
            <textarea
              value={editValue}
              onChange={(e) => setEditValue(e.target.value)}
              className="w-full bg-input border border-border rounded-lg px-3 py-2 text-sm font-mono outline-none focus:border-primary resize-none min-h-[60px]"
              autoFocus
              onKeyDown={(e) => {
                if (e.key === "Enter" && !e.shiftKey) {
                  e.preventDefault();
                  submitEdit();
                }
                if (e.key === "Escape") setIsEditing(false);
              }}
            />
            <div className="flex gap-1.5 mt-1 justify-end">
              <button
                onClick={() => setIsEditing(false)}
                className="text-xs px-2 py-1 rounded bg-muted text-muted-foreground hover:bg-accent"
              >
                Cancel
              </button>
              <button
                onClick={submitEdit}
                className="text-xs px-2 py-1 rounded bg-primary text-primary-foreground hover:bg-primary/90"
              >
                Save
              </button>
            </div>
          </div>
        )}

        {/* Usage info */}
        {message.cost !== undefined && message.cost > 0 && (
          <div className="mt-1 flex items-center gap-2 text-[10px] text-muted-foreground/60">
            {message.promptTokens && (
              <span>{message.promptTokens.toLocaleString()} in</span>
            )}
            {message.completionTokens && (
              <span>{message.completionTokens.toLocaleString()} out</span>
            )}
            <span>${message.cost.toFixed(6)}</span>
          </div>
        )}
      </div>
    </div>
  );
}