oxios 1.12.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
import { useNavigate } from '@tanstack/react-router'
import type { TFunction } from 'i18next'
import { Bell, Check, Plus, X } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { EventDetail } from '@/components/calendar/event-detail'
import { EventEditor } from '@/components/calendar/event-editor'
import { MiniCalendar } from '@/components/calendar/mini-calendar'
import { Button } from '@/components/ui/button'
import { ScrollArea } from '@/components/ui/scroll-area'
import {
  useCalendarCreate,
  useCalendarDelete,
  useCalendarEvents,
  useCalendarUpdate,
} from '@/hooks/use-calendar'
import { cn } from '@/lib/utils'
import { type CenterTab, useNotificationCenter } from '@/stores/notification-center'
import {
  type Notification,
  type NotificationSeverity,
  useNotificationStore,
} from '@/stores/notifications'
import type { CalendarEvent, CreateEventRequest, UpdateEventRequest } from '@/types/calendar'

// ─── Notifications-tab helpers (ported from the old inline bell dropdown) ──

const SEVERITY_DOT: Record<NotificationSeverity, string> = {
  info: 'bg-info',
  warning: 'bg-warning',
  error: 'bg-error',
  success: 'bg-success',
}

/** i18n-aware relative time formatter. */
function timeAgo(iso: string, t: TFunction): string {
  const diff = Date.now() - new Date(iso).getTime()
  if (diff < 60_000) return t('common.justNow', 'just now')
  if (diff < 3_600_000) return t('common.minutesAgo', { count: Math.floor(diff / 60_000) })
  if (diff < 86_400_000) return t('common.hoursAgo', { count: Math.floor(diff / 3_600_000) })
  return t('common.daysAgo', { count: Math.floor(diff / 86_400_000) })
}

// ─── Date helpers ─────────────────────────────────────────────────────────

function isSameDay(a: Date, b: Date): boolean {
  return (
    a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth() &&
    a.getDate() === b.getDate()
  )
}

/** First cell (Sunday) of the 6×7 grid for the month of `anchor`. */
function gridStart(anchor: Date): Date {
  const first = new Date(anchor.getFullYear(), anchor.getMonth(), 1)
  return new Date(first.getFullYear(), first.getMonth(), first.getDate() - first.getDay())
}

/** `YYYY-MM-DD` local key (own local time, no TZ shift). */
function dateKey(d: Date): string {
  const p = (n: number) => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`
}

// ─── Shell ─────────────────────────────────────────────────────────────────

/**
 * Notification Center — macOS-style right slide-over unifying the schedule
 * (calendar) and the notification feed behind two tabs.
 *
 * Always mounted (so the slide transition can play on close); the tab content
 * is cheap enough to keep warm, giving instant data when opened.
 */
export function NotificationCenter() {
  const { t } = useTranslation()
  const open = useNotificationCenter((s) => s.open)
  const activeTab = useNotificationCenter((s) => s.activeTab)
  const setTab = useNotificationCenter((s) => s.setTab)
  const closeCenter = useNotificationCenter((s) => s.closeCenter)
  const unreadCount = useNotificationStore((s) => s.unreadCount)

  // Escape closes — only while open.
  useEffect(() => {
    if (!open) return
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') closeCenter()
    }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [open, closeCenter])

  const tabs: { id: CenterTab; label: string; badge?: number }[] = [
    { id: 'schedule', label: t('notificationCenter.schedule') },
    { id: 'notifications', label: t('notificationCenter.notifications'), badge: unreadCount },
  ]

  return (
    <>
      {/* Backdrop */}
      <div
        role="presentation"
        aria-hidden={!open}
        onClick={closeCenter}
        className={cn(
          'fixed inset-0 z-40 bg-black/40 backdrop-blur-[2px]',
          'transition-opacity duration-300 ease-[var(--animate-in-easing)]',
          open ? 'opacity-100' : 'pointer-events-none opacity-0',
        )}
      />

      {/* Slide-over panel */}
      <aside
        role="dialog"
        aria-modal="false"
        aria-label={t('notificationCenter.title')}
        className={cn(
          'fixed inset-y-0 right-0 z-50 flex w-[380px] max-w-[calc(100vw-1.5rem)] flex-col',
          'border-l bg-background shadow-2xl',
          'transition-transform duration-300 ease-[var(--animate-in-easing)] will-change-transform',
          'pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]',
          open ? 'translate-x-0' : 'pointer-events-none translate-x-full',
        )}
      >
        {/* Header: tabs */}
        <div className="flex items-center gap-1 border-b px-3 py-2">
          <div className="flex flex-1 items-center gap-1">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                type="button"
                onClick={() => setTab(tab.id)}
                className={cn(
                  'relative rounded-md px-3 py-1.5 text-sm transition-colors',
                  'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
                  activeTab === tab.id
                    ? 'bg-accent text-accent-foreground font-medium'
                    : 'text-muted-foreground hover:bg-accent/50',
                )}
              >
                {tab.label}
                {tab.badge ? (
                  <span className="ml-1.5 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-destructive px-1 text-2xs font-bold text-destructive-foreground">
                    {tab.badge > 99 ? '99+' : tab.badge}
                  </span>
                ) : null}
              </button>
            ))}
          </div>
          <Button variant="ghost" size="icon" className="h-8 w-8" onClick={closeCenter}>
            <X className="h-4 w-4" />
          </Button>
        </div>

        {/* Body */}
        <ScrollArea className="flex-1 min-h-0">
          {activeTab === 'schedule' ? <ScheduleTab /> : <NotificationsTab />}
        </ScrollArea>
      </aside>
    </>
  )
}

// ─── Schedule tab ──────────────────────────────────────────────────────────

function ScheduleTab() {
  const { t, i18n } = useTranslation()
  const now = useMemo(() => new Date(), [])
  const [viewAnchor, setViewAnchor] = useState(() => new Date())
  const [selectedDate, setSelectedDate] = useState<Date>(now)
  const [editorOpen, setEditorOpen] = useState(false)
  const [editingEvent, setEditingEvent] = useState<CalendarEvent | undefined>()
  const [defaultStart, setDefaultStart] = useState<Date | undefined>()
  const [detailEvent, setDetailEvent] = useState<CalendarEvent | null>(null)

  // Query the full 6×7 grid span so every visible cell has event data.
  const { from, to } = useMemo(() => {
    const start = gridStart(viewAnchor)
    const end = new Date(start)
    end.setDate(start.getDate() + 42)
    return { from: start.toISOString(), to: end.toISOString() }
  }, [viewAnchor])

  const { data, isLoading } = useCalendarEvents(from, to)
  const events = useMemo(() => (Array.isArray(data?.events) ? data.events : []), [data])

  const createMutation = useCalendarCreate()
  const updateMutation = useCalendarUpdate()
  const deleteMutation = useCalendarDelete()

  // Agenda: events on the selected day, sorted by start time.
  const dayEvents = useMemo(() => {
    const key = dateKey(selectedDate)
    return events
      .filter((e) => dateKey(new Date(e.start)) === key)
      .sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime())
  }, [events, selectedDate])

  // Next upcoming event across the loaded window.
  const nextEvent = useMemo(() => {
    const upcoming = events
      .filter((e) => new Date(e.start).getTime() >= now.getTime())
      .sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime())
    return upcoming[0]
  }, [events, now])

  const openCreate = (date?: Date) => {
    setEditingEvent(undefined)
    setDefaultStart(date ?? selectedDate)
    setEditorOpen(true)
  }

  const handleSubmit = (data: CreateEventRequest | UpdateEventRequest) => {
    if (editingEvent) {
      updateMutation.mutate(
        { uid: editingEvent.uid, ...(data as UpdateEventRequest) },
        { onSuccess: () => setEditorOpen(false) },
      )
    } else {
      createMutation.mutate(data as CreateEventRequest, { onSuccess: () => setEditorOpen(false) })
    }
  }

  const isToday = isSameDay(selectedDate, now)
  const selectedLabel = selectedDate.toLocaleDateString(i18n.language, {
    month: 'long',
    day: 'numeric',
    weekday: 'long',
  })

  return (
    <div className="space-y-3 p-3">
      <MiniCalendar
        events={events}
        viewAnchor={viewAnchor}
        onViewAnchorChange={setViewAnchor}
        selectedDate={selectedDate}
        onSelectDate={setSelectedDate}
      />

      {/* Next event banner */}
      {nextEvent && (
        <div className="rounded-lg border bg-accent/30 px-3 py-2">
          <p className="text-2xs font-medium uppercase tracking-wide text-muted-foreground">
            {t('notificationCenter.nextEvent')}
          </p>
          <p className="mt-0.5 truncate text-sm font-medium">{nextEvent.title}</p>
          <p className="text-xs text-muted-foreground">
            {new Date(nextEvent.start).toLocaleString(i18n.language, {
              month: 'short',
              day: 'numeric',
              hour: '2-digit',
              minute: '2-digit',
            })}
          </p>
        </div>
      )}

      {/* Agenda for selected day */}
      <div>
        <div className="mb-1.5 flex items-center justify-between">
          <span className="text-xs font-medium text-muted-foreground">
            {isToday ? t('calendar.today') : selectedLabel}
          </span>
          <Button
            variant="ghost"
            size="sm"
            className="h-6 px-2 text-xs"
            onClick={() => openCreate()}
          >
            <Plus className="mr-1 h-3 w-3" /> {t('calendar.newEvent')}
          </Button>
        </div>

        {isLoading ? (
          <p className="py-4 text-center text-sm text-muted-foreground">{t('calendar.loading')}</p>
        ) : dayEvents.length === 0 ? (
          <p className="py-4 text-center text-sm text-muted-foreground">
            {t('notificationCenter.noUpcoming')}
          </p>
        ) : (
          <div className="space-y-1">
            {dayEvents.map((ev) => (
              <button
                key={ev.uid}
                type="button"
                onClick={() => setDetailEvent(ev)}
                className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors hover:bg-accent/50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
              >
                <span
                  className={cn(
                    'h-2 w-2 shrink-0 rounded-full',
                    ev.source === 'agent'
                      ? 'bg-info'
                      : ev.source === 'cron'
                        ? 'bg-warning'
                        : 'bg-primary',
                  )}
                />
                <span className="shrink-0 text-xs tabular-nums text-muted-foreground">
                  {ev.all_day
                    ? t('calendar.allDay')
                    : new Date(ev.start).toLocaleTimeString(i18n.language, {
                        hour: '2-digit',
                        minute: '2-digit',
                      })}
                </span>
                <span className="min-w-0 flex-1 truncate text-sm">{ev.title}</span>
              </button>
            ))}
          </div>
        )}
      </div>

      <EventEditor
        open={editorOpen}
        onClose={() => setEditorOpen(false)}
        event={editingEvent}
        defaultStart={defaultStart}
        onSubmit={handleSubmit}
        isLoading={createMutation.isPending || updateMutation.isPending}
      />

      {detailEvent && (
        <EventDetail
          event={detailEvent}
          onEdit={() => {
            setEditingEvent(detailEvent)
            setDefaultStart(new Date(detailEvent.start))
            setDetailEvent(null)
            setEditorOpen(true)
          }}
          onDelete={() => {
            deleteMutation.mutate(detailEvent.uid, { onSuccess: () => setDetailEvent(null) })
          }}
          onClose={() => setDetailEvent(null)}
        />
      )}
    </div>
  )
}

// ─── Notifications tab ────────────────────────────────────────────────────

function NotificationsTab() {
  const { t } = useTranslation()
  const navigate = useNavigate()
  const closeCenter = useNotificationCenter((s) => s.closeCenter)

  const notifications = useNotificationStore((s) => s.notifications)
  const unreadCount = useNotificationStore((s) => s.unreadCount)
  const markRead = useNotificationStore((s) => s.markRead)
  const markAllRead = useNotificationStore((s) => s.markAllRead)
  const dismiss = useNotificationStore((s) => s.dismiss)

  const handleClick = (n: Notification) => {
    markRead(n.id)
    if (n.link) {
      closeCenter()
      navigate({ to: n.link })
    }
  }

  return (
    <div className="flex flex-col">
      <div className="flex items-center justify-between border-b px-3 py-2">
        <span className="text-xs text-muted-foreground">
          {unreadCount > 0 ? t('notifications.unreadCount', { count: unreadCount }) : null}
        </span>
        {unreadCount > 0 && (
          <Button variant="ghost" size="sm" className="h-6 text-xs" onClick={markAllRead}>
            <Check className="mr-1 h-3 w-3" /> {t('notifications.markAllRead')}
          </Button>
        )}
      </div>

      {notifications.length === 0 ? (
        <div className="flex flex-col items-center justify-center gap-2 py-12 text-muted-foreground">
          <Bell className="h-8 w-8 opacity-30" />
          <p className="text-sm">{t('notifications.noNotifications')}</p>
        </div>
      ) : (
        <div className="divide-y">
          {notifications.map((n) => (
            // biome-ignore lint/a11y/useSemanticElements: nested dismiss button; div is correct
            <div
              key={n.id}
              className={cn(
                'group flex gap-2 px-3 py-2.5 transition-all cursor-pointer hover:bg-accent/50',
                !n.read && 'bg-accent/20',
              )}
              onClick={() => handleClick(n)}
              role="button"
              tabIndex={0}
              onKeyDown={(e) => {
                if (e.key === 'Enter') handleClick(n)
              }}
            >
              <div
                className={cn('mt-0.5 h-2 w-2 shrink-0 rounded-full', SEVERITY_DOT[n.severity])}
              />
              <div className="min-w-0 flex-1">
                <p className="truncate text-sm font-medium leading-tight">{n.title}</p>
                {n.message && (
                  <p className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">{n.message}</p>
                )}
                <p className="mt-1 text-2xs text-muted-foreground/60">{timeAgo(n.timestamp, t)}</p>
              </div>
              <button
                type="button"
                onClick={(e) => {
                  e.stopPropagation()
                  dismiss(n.id)
                }}
                className="shrink-0 rounded p-0.5 opacity-0 transition-opacity hover:bg-muted group-hover:opacity-100"
                aria-label={t('common.dismiss')}
              >
                <X className="h-3 w-3" />
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}