summaryrefslogtreecommitdiffhomepage
path: root/packages/app/src/components/session-context-usage.tsx
blob: c8e6918ca5f46f8def09473b1f7f7ecb92232a4f (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
import { createMemo, Show } from "solid-js"
import { Tooltip } from "@opencode-ai/ui/tooltip"
import { ProgressCircle } from "@opencode-ai/ui/progress-circle"
import { useSync } from "@/context/sync"
import { useParams } from "@solidjs/router"
import { AssistantMessage } from "@opencode-ai/sdk/v2"

export function SessionContextUsage() {
  const sync = useSync()
  const params = useParams()
  const messages = createMemo(() => (params.id ? (sync.data.message[params.id] ?? []) : []))

  const cost = createMemo(() => {
    const total = messages().reduce((sum, x) => sum + (x.role === "assistant" ? x.cost : 0), 0)
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: "USD",
    }).format(total)
  })

  const context = createMemo(() => {
    const last = messages().findLast((x) => x.role === "assistant" && x.tokens.output > 0) as AssistantMessage
    if (!last) return
    const total =
      last.tokens.input + last.tokens.output + last.tokens.reasoning + last.tokens.cache.read + last.tokens.cache.write
    const model = sync.data.provider.all.find((x) => x.id === last.providerID)?.models[last.modelID]
    return {
      tokens: total.toLocaleString(),
      percentage: model?.limit.context ? Math.round((total / model.limit.context) * 100) : null,
    }
  })

  return (
    <Show when={context?.()}>
      {(ctx) => (
        <Tooltip
          value={
            <div class="flex flex-col gap-1">
              <div class="flex gap-3">
                <span class="opacity-70 text-right flex-1">Tokens</span>
                <span class="text-left flex-1">{ctx().tokens}</span>
              </div>
              <div class="flex gap-3">
                <span class="opacity-70 text-right flex-1">Usage</span>
                <span class="text-left flex-1">{ctx().percentage ?? 0}%</span>
              </div>
              <div class="flex gap-3">
                <span class="opacity-70 text-right flex-1">Cost</span>
                <span class="text-left flex-1">{cost()}</span>
              </div>
            </div>
          }
          placement="top"
        >
          <div class="flex items-center gap-1.5">
            <ProgressCircle size={16} strokeWidth={2} percentage={ctx().percentage ?? 0} />
            {/* <span class="text-12-medium text-text-weak">{`${ctx().percentage ?? 0}%`}</span> */}
          </div>
        </Tooltip>
      )}
    </Show>
  )
}