summaryrefslogtreecommitdiffhomepage
path: root/packages/app/src/testing/model-selection.ts
blob: d2770fe2892ce5839bd6a0e5a523a48cb80b4aff (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
type ModelKey = {
  providerID: string
  modelID: string
}

type ModelItem = ModelKey & {
  name: string
}

type AgentItem = {
  name: string
}

type State = {
  agent?: string
  model?: ModelKey | null
  variant?: string | null
}

export type ModelProbeState = {
  dir?: string
  sessionID?: string
  last?: {
    type: "agent" | "model" | "variant"
    agent?: string
    model?: ModelKey | null
    variant?: string | null
  }
  agent?: string
  model?: (ModelKey & { name?: string }) | undefined
  variant?: string | null
  selected?: string | null
  configured?: string
  pick?: State
  base?: State
  current?: string
  variants?: string[]
  models?: ModelItem[]
  agents?: AgentItem[]
}

export type ModelWindow = Window & {
  __opencode_e2e?: {
    model?: {
      enabled?: boolean
      current?: ModelProbeState
      controls?: {
        setAgent?: (name: string | undefined) => void
        setModel?: (value: ModelKey | undefined) => void
        setVariant?: (value: string | undefined) => void
      }
    }
  }
}

const clone = (state?: State) => {
  if (!state) return undefined
  return {
    ...state,
    model: state.model ? { ...state.model } : state.model,
  }
}

let active: symbol | undefined

export const modelEnabled = () => {
  if (typeof window === "undefined") return false
  return (window as ModelWindow).__opencode_e2e?.model?.enabled === true
}

const root = () => {
  if (!modelEnabled()) return
  return (window as ModelWindow).__opencode_e2e?.model
}

export const modelProbe = {
  bind(id: symbol, input: NonNullable<NonNullable<ModelWindow["__opencode_e2e"]>["model"]>["controls"]) {
    const state = root()
    if (!state) return
    active = id
    state.controls = input
  },
  set(id: symbol, input: ModelProbeState) {
    const state = root()
    if (!state || active !== id) return
    state.current = {
      ...input,
      model: input.model ? { ...input.model } : undefined,
      last: input.last
        ? {
            ...input.last,
            model: input.last.model ? { ...input.last.model } : input.last.model,
          }
        : undefined,
      pick: clone(input.pick),
      base: clone(input.base),
      variants: input.variants?.slice(),
      models: input.models?.map((item) => ({ ...item })),
      agents: input.agents?.map((item) => ({ ...item })),
    }
  },
  clear(id: symbol) {
    const state = root()
    if (!state || active !== id) return
    active = undefined
    state.current = undefined
    state.controls = undefined
  },
}