oxios 1.23.0

Oxios Agent OS — Agent Operating System powered by oxi-sdk
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
import type { LucideIcon } from 'lucide-react'
import {
  BookOpen,
  CheckSquare,
  Clock,
  CornerDownLeft,
  Inbox,
  MessageSquare,
  Newspaper,
  ShoppingCart,
  Square,
  Trash2,
  Tv,
  X,
} from 'lucide-react'
import md5 from 'md5'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import {
  useChatAppend,
  useChatDelete,
  useChatMessages,
  useChecklistAdd,
  useJournalAdd,
} from '@/hooks/use-knowledge'
import { cn } from '@/lib/utils'

// ── Types ─────────────────────────────────────────────────────

interface ParsedMessage {
  /** Original index in the raw array */
  index: number
  /** Whether `[x]` (done) or `[ ]` (pending) */
  done: boolean
  /** The `HH:MM` timestamp, if present */
  timestamp: string
  /** The message body text */
  text: string
  /** Date header this message belongs to */
  date: string
  /** The raw string from the backend */
  raw: string
}

interface DateGroup {
  date: string
  messages: ParsedMessage[]
}

/** Capture-time routing destinations. */
type RouteKey = 'Later' | 'Read' | 'Shop' | 'Watch' | 'Journal'

interface CaptureRoute {
  key: RouteKey
  labelKey: string
  icon: LucideIcon
  /** Checklist file path; absent for Journal (uses journal_add). */
  path?: string
}

// ── Parsing ───────────────────────────────────────────────────

const DONE_RE = /^- \[([xX ])\] (?:`(\d{2}:\d{2})` )?(.+)$/
const DATE_HEADER_RE = /^#### (.+)$/

function parseMessage(raw: string, index: number): ParsedMessage | null {
  const m = raw.match(DONE_RE)
  if (!m) return null
  return {
    index,
    done: m[1] === 'x' || m[1] === 'X',
    timestamp: m[2] ?? '',
    text: m[3] ?? '',
    date: '',
    raw,
  }
}

function isDateHeader(raw: string): string | null {
  const m = raw.match(DATE_HEADER_RE)
  return m?.[1] ?? null
}

/**
 * Group raw backend strings into date buckets with parsed messages.
 * Non-parseable lines (not date headers or checklist items) are skipped.
 */
function groupMessages(raws: string[]): DateGroup[] {
  const groups: DateGroup[] = []
  let currentDate = 'Today'

  for (let i = 0; i < raws.length; i++) {
    const raw = raws[i]
    const headerText = isDateHeader(raw!)
    if (headerText) {
      currentDate = headerText
      continue
    }
    const parsed = parseMessage(raw!, i)
    if (!parsed) continue
    parsed.date = currentDate

    let group = groups[groups.length - 1]
    if (!group || group.date !== currentDate) {
      group = { date: currentDate, messages: [] }
      groups.push(group)
    }
    group.messages.push(parsed)
  }

  return groups
}

// ── Simple hash for msg_hash ─────────────────────────────────
// Computes the same MD5(first_line)[..11] hash that the backend uses.
// Backend: oxios-markdown/src/fs.rs → hash_filename() → MD5 → first 11 hex chars.

export async function msgHash(raw: string): Promise<string> {
  const stripped = raw.replace(/^- \[[ xX]\] /, '')
  const firstLine = stripped.split('\n')[0] ?? ''
  return md5(firstLine).slice(0, 11)
}

// ── Destinations ──────────────────────────────────────────────

/** Per-row "move out of inbox" targets (checklist files). */
const CHECKLIST_TARGETS = [
  { labelKey: 'knowledge.later', icon: Clock, path: 'Later.md' },
  { labelKey: 'knowledge.read', icon: Newspaper, path: 'Read.md' },
  { labelKey: 'knowledge.shop', icon: ShoppingCart, path: 'Shop.md' },
  { labelKey: 'knowledge.watch', icon: Tv, path: 'Watch.md' },
] as const

/** Capture-time routes (slash menu). Journal routes via journal_add. */
const CAPTURE_ROUTES: CaptureRoute[] = [
  { key: 'Later', labelKey: 'knowledge.later', icon: Clock, path: 'Later.md' },
  { key: 'Read', labelKey: 'knowledge.read', icon: Newspaper, path: 'Read.md' },
  { key: 'Shop', labelKey: 'knowledge.shop', icon: ShoppingCart, path: 'Shop.md' },
  { key: 'Watch', labelKey: 'knowledge.watch', icon: Tv, path: 'Watch.md' },
  { key: 'Journal', labelKey: 'knowledge.toJournal', icon: BookOpen },
]

/** Tint classes per route for chips/badges. */
const ROUTE_TINT: Record<RouteKey, string> = {
  Later: 'text-info bg-info-muted',
  Read: 'text-warning bg-warning-muted',
  Shop: 'text-destructive bg-destructive/10',
  Watch: 'text-chart-4 bg-chart-4/10',
  Journal: 'text-success bg-success-muted',
}

// ── Component ─────────────────────────────────────────────────

export function KnowledgeChat() {
  const { t } = useTranslation()
  const { data: rawMessages, isLoading } = useChatMessages()
  const chatAppend = useChatAppend()
  const chatDelete = useChatDelete()
  const journalAdd = useJournalAdd()
  const checklistAdd = useChecklistAdd()

  const [input, setInput] = useState('')
  const [route, setRoute] = useState<RouteKey | null>(null)
  const [routeMenuOpen, setRouteMenuOpen] = useState(false)
  const [hoveredIndex, setHoveredIndex] = useState<number | null>(null)
  const [selectedIndices, setSelectedIndices] = useState<Set<number>>(new Set())
  const [lastClickedIndex, setLastClickedIndex] = useState<number | null>(null)

  const scrollRef = useRef<HTMLDivElement>(null)
  const textareaRef = useRef<HTMLTextAreaElement>(null)
  const barRef = useRef<HTMLDivElement>(null)
  const isDragging = useRef(false)
  const dragStart = useRef<number | null>(null)
  const prevCountRef = useRef(0)

  // ── Grouped messages ──────────────────────────────────────

  const groups = useMemo(() => {
    if (!rawMessages) return []
    return groupMessages(rawMessages)
  }, [rawMessages])

  // Flat parsed list (original order) for selection lookups / bulk ops.
  const flatMessages = useMemo(() => groups.flatMap((g) => g.messages), [groups])

  // Display order: newest-first. Full reverse (group order + within-group)
  // is a strictly-monotone remap of flatMessages, so index-based selection
  // (min/max over msg.index) stays correct without re-mapping.
  const displayGroups = useMemo(
    () => groups.map((g) => ({ ...g, messages: [...g.messages].reverse() })).reverse(),
    [groups],
  )

  // ── Auto-scroll to top when inbox grows ───────────────────
  // Newest sits at the top now, so pin to top on mount and after appends.
  useEffect(() => {
    const count = flatMessages.length
    if (count > prevCountRef.current) {
      scrollRef.current?.scrollTo({ top: 0 })
    }
    prevCountRef.current = count
  }, [flatMessages.length])

  // ── Auto-resize textarea ──────────────────────────────────

  useEffect(() => {
    const el = textareaRef.current
    if (!el) return
    el.style.height = 'auto'
    el.style.height = `${Math.min(el.scrollHeight, 160)}px`
  }, [input])

  // ── Close route menu on outside click ─────────────────────

  useEffect(() => {
    if (!routeMenuOpen) return
    const onDown = (e: MouseEvent) => {
      if (barRef.current && !barRef.current.contains(e.target as Node)) {
        setRouteMenuOpen(false)
      }
    }
    document.addEventListener('mousedown', onDown)
    return () => document.removeEventListener('mousedown', onDown)
  }, [routeMenuOpen])

  // ── Send / shortcuts ──────────────────────────────────────

  const handleSend = useCallback(async () => {
    const text = input.trim()
    if (!text) return

    // Legacy journal shortcut: "some text jj"
    if (text.toLowerCase().endsWith(' jj')) {
      const record = text.slice(0, -3).trim()
      if (record) await journalAdd.mutateAsync(record)
    } else if (route === 'Journal') {
      await journalAdd.mutateAsync(text)
    } else if (route) {
      const target = CAPTURE_ROUTES.find((r) => r.key === route)
      if (target?.path) {
        await checklistAdd.mutateAsync({ path: target.path, item: text })
      } else {
        await chatAppend.mutateAsync(text)
      }
    } else {
      await chatAppend.mutateAsync(text)
    }

    setInput('')
    setRoute(null)
    setRouteMenuOpen(false)
    textareaRef.current?.focus()
  }, [input, route, chatAppend, journalAdd, checklistAdd])

  const pickRoute = useCallback((key: RouteKey | null) => {
    setRoute(key)
    setRouteMenuOpen(false)
    // Strip the leading `/` the user typed to summon the menu.
    setInput((v) => v.replace(/^\//, ''))
    textareaRef.current?.focus()
  }, [])

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault()
        handleSend()
      } else if (e.key === 'Escape') {
        setRouteMenuOpen(false)
        if (route) setRoute(null)
      }
    },
    [handleSend, route],
  )

  const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const v = e.target.value
    setInput(v)
    if (v === '/' && !route) setRouteMenuOpen(true)
  }

  // ── Selection ─────────────────────────────────────────────

  const handleMessageClick = useCallback(
    (msg: ParsedMessage, e: React.MouseEvent) => {
      e.stopPropagation()

      setSelectedIndices((prev) => {
        const next = new Set(prev)

        if (e.shiftKey && lastClickedIndex !== null) {
          // Range select
          const from = Math.min(lastClickedIndex, msg.index)
          const to = Math.max(lastClickedIndex, msg.index)
          for (let i = from; i <= to; i++) next.add(i)
        } else if (e.metaKey || e.ctrlKey) {
          // Toggle individual
          if (next.has(msg.index)) {
            next.delete(msg.index)
          } else {
            next.add(msg.index)
          }
        } else {
          // Single select / deselect
          if (next.size === 1 && next.has(msg.index)) {
            next.clear()
          } else {
            next.clear()
            next.add(msg.index)
          }
        }
        return next
      })

      setLastClickedIndex(msg.index)
    },
    [lastClickedIndex],
  )

  // Clear selection on background click
  const handleBackgroundClick = useCallback(() => {
    setSelectedIndices(new Set())
    setLastClickedIndex(null)
  }, [])

  // ── Drag selection ────────────────────────────────────────

  const handleDragStart = useCallback((msg: ParsedMessage) => {
    isDragging.current = true
    dragStart.current = msg.index
    setSelectedIndices(new Set([msg.index]))
  }, [])

  const handleDragEnter = useCallback((msg: ParsedMessage) => {
    if (!isDragging.current || dragStart.current === null) return
    const from = Math.min(dragStart.current, msg.index)
    const to = Math.max(dragStart.current, msg.index)
    const next = new Set<number>()
    for (let i = from; i <= to; i++) next.add(i)
    setSelectedIndices(next)
  }, [])

  const handleDragEnd = useCallback(() => {
    isDragging.current = false
    dragStart.current = null
  }, [])

  // ── Actions ───────────────────────────────────────────────

  const moveToJournal = useCallback(
    async (msg: ParsedMessage) => {
      await journalAdd.mutateAsync(msg.text)
      await chatDelete.mutateAsync(await msgHash(msg.raw))
    },
    [journalAdd, chatDelete],
  )

  const moveToChecklist = useCallback(
    async (path: string, msg: ParsedMessage) => {
      await checklistAdd.mutateAsync({ path, item: msg.text })
      await chatDelete.mutateAsync(await msgHash(msg.raw))
    },
    [checklistAdd, chatDelete],
  )

  const deleteMessage = useCallback(
    async (msg: ParsedMessage) => {
      await chatDelete.mutateAsync(await msgHash(msg.raw))
    },
    [chatDelete],
  )

  // Bulk actions on selected messages
  const bulkMoveToChecklist = useCallback(
    async (path: string) => {
      const targets = flatMessages.filter((m) => selectedIndices.has(m.index))
      for (const msg of targets) {
        await checklistAdd.mutateAsync({ path, item: msg.text })
        await chatDelete.mutateAsync(await msgHash(msg.raw))
      }
      setSelectedIndices(new Set())
    },
    [flatMessages, selectedIndices, checklistAdd, chatDelete],
  )

  const bulkMoveToJournal = useCallback(async () => {
    const targets = flatMessages.filter((m) => selectedIndices.has(m.index))
    for (const msg of targets) {
      await journalAdd.mutateAsync(msg.text)
      await chatDelete.mutateAsync(await msgHash(msg.raw))
    }
    setSelectedIndices(new Set())
  }, [flatMessages, selectedIndices, journalAdd, chatDelete])

  const bulkDelete = useCallback(async () => {
    const targets = flatMessages.filter((m) => selectedIndices.has(m.index))
    for (const msg of targets) {
      await chatDelete.mutateAsync(await msgHash(msg.raw))
    }
    setSelectedIndices(new Set())
  }, [flatMessages, selectedIndices, chatDelete])

  const hasSelection = selectedIndices.size > 0
  const activeRoute = route ? CAPTURE_ROUTES.find((r) => r.key === route) : null

  // ── Render ────────────────────────────────────────────────

  return (
    <div className="flex flex-col flex-1 h-full">
      {/* Mode signal — this is the capture inbox; opening a file switches to the editor */}
      <div className="flex items-center gap-2 px-4 pt-3 text-xs text-muted-foreground">
        <Inbox className="h-3.5 w-3.5" />
        <span className="font-medium">{t('knowledge.inboxMode')}</span>
        <span className="opacity-70">· {t('knowledge.inboxModeHint')}</span>
      </div>
      {/* Command bar (top) */}
      <div ref={barRef} className="relative shrink-0 border-b px-4 py-3">
        <div
          className={cn(
            'flex items-start gap-1.5 rounded-lg border bg-background px-2.5 py-1.5 transition-shadow',
            'focus-within:border-ring/50 focus-within:ring-2 focus-within:ring-ring/30',
          )}
        >
          {activeRoute && (
            <button
              type="button"
              onClick={() => pickRoute(null)}
              className={cn(
                'mt-0.5 inline-flex shrink-0 items-center gap-1 rounded-md px-1.5 py-1 text-xs font-medium',
                ROUTE_TINT[activeRoute.key],
              )}
            >
              <activeRoute.icon className="h-3.5 w-3.5" />
              {t(activeRoute.labelKey)}
              <X className="h-3 w-3 opacity-60" />
            </button>
          )}

          <Textarea
            ref={textareaRef}
            value={input}
            onChange={handleInputChange}
            onKeyDown={handleKeyDown}
            placeholder={t('knowledge.chatPlaceholder')}
            className="min-h-0 flex-1 resize-none border-0 bg-transparent px-0 py-1 text-sm shadow-none focus-visible:ring-0"
            rows={1}
          />
        </div>

        {/* Hint row — doubles as route-menu toggle */}
        <div className="mt-1.5 flex items-center justify-between px-1">
          <button
            type="button"
            onClick={() => setRouteMenuOpen((o) => !o)}
            className="inline-flex items-center gap-1 text-[11px] text-muted-foreground transition-colors hover:text-foreground"
          >
            <span className="font-mono">/</span>
            {route ? (
              <span className="text-foreground">{t(activeRoute!.labelKey)}</span>
            ) : (
              t('knowledge.routeHint')
            )}
          </button>
          <span className="inline-flex items-center gap-1 text-[11px] text-muted-foreground">
            <CornerDownLeft className="h-3 w-3" />
            {t('knowledge.pressEnterToSend')}
          </span>
        </div>

        {/* Route menu popover */}
        {routeMenuOpen && (
          <div className="absolute left-4 top-full z-20 mt-1 w-56 overflow-hidden rounded-lg border bg-popover p-1 shadow-lg">
            <button
              type="button"
              onClick={() => pickRoute(null)}
              className={cn(
                'flex w-full items-center gap-2.5 rounded-md px-2.5 py-1.5 text-sm transition-colors hover:bg-accent',
                !route && 'bg-accent',
              )}
            >
              <Inbox className="h-4 w-4 text-muted-foreground" />
              <span className="flex-1 text-left">{t('knowledge.inbox')}</span>
              {!route && <CheckSquare className="h-3.5 w-3.5 text-muted-foreground" />}
            </button>
            {CAPTURE_ROUTES.map((r) => {
              const Icon = r.icon
              return (
                <button
                  key={r.key}
                  type="button"
                  onClick={() => pickRoute(r.key)}
                  className={cn(
                    'flex w-full items-center gap-2.5 rounded-md px-2.5 py-1.5 text-sm transition-colors hover:bg-accent',
                    route === r.key && 'bg-accent',
                  )}
                >
                  <Icon className="h-4 w-4 text-muted-foreground" />
                  <span className="flex-1 text-left">{t(r.labelKey)}</span>
                  {route === r.key && <CheckSquare className="h-3.5 w-3.5 text-muted-foreground" />}
                </button>
              )
            })}
          </div>
        )}
      </div>

      {/* Bulk action bar */}
      {hasSelection && (
        <div className="px-4 py-2 border-b bg-muted/50 flex items-center gap-1.5 shrink-0 overflow-x-auto">
          <span className="text-xs text-muted-foreground shrink-0 mr-1">
            {selectedIndices.size} {t('knowledge.selected')}
          </span>
          <Button
            variant="ghost"
            size="sm"
            className="h-7 px-2 text-xs shrink-0"
            onClick={bulkMoveToJournal}
          >
            <BookOpen className="h-3 w-3 mr-1" />
            {t('knowledge.toJournal')}
          </Button>
          {CHECKLIST_TARGETS.map((ct) => (
            <Button
              key={ct.path}
              variant="ghost"
              size="sm"
              className="h-7 px-2 text-xs shrink-0"
              onClick={() => bulkMoveToChecklist(ct.path)}
            >
              <ct.icon className="h-3 w-3 mr-1" />
              {t(ct.labelKey)}
            </Button>
          ))}
          <div className="flex-1 min-w-4" />
          <Button
            variant="ghost"
            size="sm"
            className="h-7 px-2 text-xs text-destructive shrink-0"
            onClick={bulkDelete}
          >
            <Trash2 className="h-3 w-3 mr-1" />
            {t('common.delete')}
          </Button>
        </div>
      )}

      {/* Messages area — newest-first */}
      <div
        ref={scrollRef}
        className="flex-1 overflow-y-auto p-4 select-none"
        onClick={handleBackgroundClick}
      >
        {isLoading ? (
          <div className="text-center text-muted-foreground py-12">{t('knowledge.loading')}</div>
        ) : displayGroups.length === 0 ? (
          <div className="flex flex-col items-center text-muted-foreground py-16">
            <MessageSquare className="h-10 w-10 opacity-20 mb-4" />
            <p className="font-medium text-foreground">{t('knowledge.noFilesYet')}</p>
            <p className="text-sm mt-1">{t('knowledge.dropMindHint')}</p>
          </div>
        ) : (
          <div className="space-y-6">
            {displayGroups.map((group) => (
              <div key={group.date}>
                {/* Date header */}
                <div className="sticky top-0 z-10 bg-background/80 backdrop-blur-sm py-1 mb-2">
                  <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                    {group.date}
                  </p>
                </div>

                {/* Messages */}
                <div className="space-y-1">
                  {group.messages.map((msg) => {
                    const isHovered = hoveredIndex === msg.index
                    const isSelected = selectedIndices.has(msg.index)
                    const isPending =
                      chatDelete.isPending || checklistAdd.isPending || journalAdd.isPending

                    return (
                      <div
                        key={msg.index}
                        className={cn(
                          'group relative flex items-start gap-2 rounded-lg px-3 py-2 text-sm transition-colors cursor-pointer select-none',
                          isSelected
                            ? 'bg-primary/10 ring-1 ring-primary/30'
                            : 'hover:bg-accent/40',
                        )}
                        onClick={(e) => handleMessageClick(msg, e)}
                        onMouseEnter={() => setHoveredIndex(msg.index)}
                        onMouseLeave={() => setHoveredIndex(null)}
                        draggable
                        onDragStart={() => handleDragStart(msg)}
                        onDragEnter={() => handleDragEnter(msg)}
                        onDragEnd={handleDragEnd}
                      >
                        {/* Completion state — visual only (no in-place toggle endpoint) */}
                        <span className="mt-0.5 shrink-0 text-muted-foreground">
                          {msg.done ? (
                            <CheckSquare className="h-4 w-4 text-success" />
                          ) : (
                            <Square className="h-4 w-4" />
                          )}
                        </span>

                        {/* Timestamp */}
                        {msg.timestamp && (
                          <span className="shrink-0 text-xs text-muted-foreground font-mono tabular-nums mt-0.5">
                            {msg.timestamp}
                          </span>
                        )}

                        {/* Text */}
                        <span
                          className={cn(
                            'flex-1 whitespace-pre-wrap break-words',
                            msg.done && 'line-through text-muted-foreground',
                          )}
                        >
                          {msg.text}
                        </span>

                        {/* Hover/touch actions */}
                        {((isHovered && !hasSelection) || (isSelected && !isHovered)) &&
                          !isPending && (
                            <div className="flex items-center gap-0.5 shrink-0">
                              {/* To Journal */}
                              <Button
                                variant="ghost"
                                size="icon"
                                className="h-6 w-6"
                                title={t('knowledge.toJournal')}
                                onClick={(e) => {
                                  e.stopPropagation()
                                  moveToJournal(msg)
                                }}
                              >
                                <BookOpen className="h-3.5 w-3.5" />
                              </Button>

                              {/* Checklist targets */}
                              {CHECKLIST_TARGETS.map((ct) => (
                                <Button
                                  key={ct.path}
                                  variant="ghost"
                                  size="icon"
                                  className="h-6 w-6"
                                  title={t(ct.labelKey)}
                                  onClick={(e) => {
                                    e.stopPropagation()
                                    moveToChecklist(ct.path, msg)
                                  }}
                                >
                                  <ct.icon className="h-3.5 w-3.5" />
                                </Button>
                              ))}

                              {/* Delete */}
                              <Button
                                variant="ghost"
                                size="icon"
                                className="h-6 w-6 text-destructive"
                                title={t('common.delete')}
                                onClick={(e) => {
                                  e.stopPropagation()
                                  deleteMessage(msg)
                                }}
                              >
                                <Trash2 className="h-3.5 w-3.5" />
                              </Button>
                            </div>
                          )}
                      </div>
                    )
                  })}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}