summaryrefslogtreecommitdiffhomepage
path: root/packages/app/src/context/notification.tsx
blob: b876bd8627355fec72ed2834497cf290c9283f30 (plain)
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
import { createStore } from "solid-js/store"
import { createEffect, createMemo, onCleanup } from "solid-js"
import { useParams } from "@solidjs/router"
import { createSimpleContext } from "@opencode-ai/ui/context"
import { useGlobalSDK } from "./global-sdk"
import { useGlobalSync } from "./global-sync"
import { usePlatform } from "@/context/platform"
import { useLanguage } from "@/context/language"
import { useSettings } from "@/context/settings"
import { Binary } from "@opencode-ai/util/binary"
import { base64Encode } from "@opencode-ai/util/encode"
import { decode64 } from "@/utils/base64"
import { EventSessionError } from "@opencode-ai/sdk/v2"
import { Persist, persisted } from "@/utils/persist"
import { playSound, soundSrc } from "@/utils/sound"
import { buildNotificationIndex } from "./notification-index"

type NotificationBase = {
  directory?: string
  session?: string
  metadata?: any
  time: number
  viewed: boolean
}

type TurnCompleteNotification = NotificationBase & {
  type: "turn-complete"
}

type ErrorNotification = NotificationBase & {
  type: "error"
  error: EventSessionError["properties"]["error"]
}

export type Notification = TurnCompleteNotification | ErrorNotification

const MAX_NOTIFICATIONS = 500
const NOTIFICATION_TTL_MS = 1000 * 60 * 60 * 24 * 30

function pruneNotifications(list: Notification[]) {
  const cutoff = Date.now() - NOTIFICATION_TTL_MS
  const pruned = list.filter((n) => n.time >= cutoff)
  if (pruned.length <= MAX_NOTIFICATIONS) return pruned
  return pruned.slice(pruned.length - MAX_NOTIFICATIONS)
}

export const { use: useNotification, provider: NotificationProvider } = createSimpleContext({
  name: "Notification",
  init: () => {
    const params = useParams()
    const globalSDK = useGlobalSDK()
    const globalSync = useGlobalSync()
    const platform = usePlatform()
    const settings = useSettings()
    const language = useLanguage()

    const empty: Notification[] = []

    const currentDirectory = createMemo(() => {
      return decode64(params.dir)
    })

    const currentSession = createMemo(() => params.id)

    const [store, setStore, _, ready] = persisted(
      Persist.global("notification", ["notification.v1"]),
      createStore({
        list: [] as Notification[],
      }),
    )

    const meta = { pruned: false }

    createEffect(() => {
      if (!ready()) return
      if (meta.pruned) return
      meta.pruned = true
      setStore("list", pruneNotifications(store.list))
    })

    const append = (notification: Notification) => {
      setStore("list", (list) => pruneNotifications([...list, notification]))
    }

    const index = createMemo(() => buildNotificationIndex(store.list))

    const unsub = globalSDK.event.listen((e) => {
      const event = e.details
      if (event.type !== "session.idle" && event.type !== "session.error") return

      const directory = e.name
      const time = Date.now()
      const viewed = (sessionID?: string) => {
        const activeDirectory = currentDirectory()
        const activeSession = currentSession()
        if (!activeDirectory) return false
        if (!activeSession) return false
        if (!sessionID) return false
        if (directory !== activeDirectory) return false
        return sessionID === activeSession
      }
      switch (event.type) {
        case "session.idle": {
          const sessionID = event.properties.sessionID
          const [syncStore] = globalSync.child(directory, { bootstrap: false })
          const match = Binary.search(syncStore.session, sessionID, (s) => s.id)
          const session = match.found ? syncStore.session[match.index] : undefined
          if (session?.parentID) break

          playSound(soundSrc(settings.sounds.agent()))

          append({
            directory,
            time,
            viewed: viewed(sessionID),
            type: "turn-complete",
            session: sessionID,
          })

          const href = `/${base64Encode(directory)}/session/${sessionID}`
          if (settings.notifications.agent()) {
            void platform.notify(
              language.t("notification.session.responseReady.title"),
              session?.title ?? sessionID,
              href,
            )
          }
          break
        }
        case "session.error": {
          const sessionID = event.properties.sessionID
          const [syncStore] = globalSync.child(directory, { bootstrap: false })
          const match = sessionID ? Binary.search(syncStore.session, sessionID, (s) => s.id) : undefined
          const session = sessionID && match?.found ? syncStore.session[match.index] : undefined
          if (session?.parentID) break

          playSound(soundSrc(settings.sounds.errors()))

          const error = "error" in event.properties ? event.properties.error : undefined
          append({
            directory,
            time,
            viewed: viewed(sessionID),
            type: "error",
            session: sessionID ?? "global",
            error,
          })
          const description =
            session?.title ??
            (typeof error === "string" ? error : language.t("notification.session.error.fallbackDescription"))
          const href = sessionID ? `/${base64Encode(directory)}/session/${sessionID}` : `/${base64Encode(directory)}`
          if (settings.notifications.errors()) {
            void platform.notify(language.t("notification.session.error.title"), description, href)
          }
          break
        }
      }
    })
    onCleanup(unsub)

    return {
      ready,
      session: {
        all(session: string) {
          return index().session.all.get(session) ?? empty
        },
        unseen(session: string) {
          return index().session.unseen.get(session) ?? empty
        },
        unseenCount(session: string) {
          return index().session.unseenCount.get(session) ?? 0
        },
        unseenHasError(session: string) {
          return index().session.unseenHasError.get(session) ?? false
        },
        markViewed(session: string) {
          setStore("list", (n) => n.session === session, "viewed", true)
        },
      },
      project: {
        all(directory: string) {
          return index().project.all.get(directory) ?? empty
        },
        unseen(directory: string) {
          return index().project.unseen.get(directory) ?? empty
        },
        unseenCount(directory: string) {
          return index().project.unseenCount.get(directory) ?? 0
        },
        unseenHasError(directory: string) {
          return index().project.unseenHasError.get(directory) ?? false
        },
        markViewed(directory: string) {
          setStore("list", (n) => n.directory === directory, "viewed", true)
        },
      },
    }
  },
})