summaryrefslogtreecommitdiffhomepage
path: root/packages/app/src/components/dialog-select-server.tsx
blob: 90f3721288835adb22ade329c280028a1190ee95 (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
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
import { createResource, createEffect, createMemo, onCleanup, Show } from "solid-js"
import { createStore, reconcile } from "solid-js/store"
import { useDialog } from "@opencode-ai/ui/context/dialog"
import { Dialog } from "@opencode-ai/ui/dialog"
import { List } from "@opencode-ai/ui/list"
import { TextField } from "@opencode-ai/ui/text-field"
import { Button } from "@opencode-ai/ui/button"
import { IconButton } from "@opencode-ai/ui/icon-button"
import { normalizeServerUrl, serverDisplayName, useServer } from "@/context/server"
import { usePlatform } from "@/context/platform"
import { createOpencodeClient } from "@opencode-ai/sdk/v2/client"
import { useNavigate } from "@solidjs/router"

type ServerStatus = { healthy: boolean; version?: string }

async function checkHealth(url: string, fetch?: typeof globalThis.fetch): Promise<ServerStatus> {
  const sdk = createOpencodeClient({
    baseUrl: url,
    fetch,
    signal: AbortSignal.timeout(3000),
  })
  return sdk.global
    .health()
    .then((x) => ({ healthy: x.data?.healthy === true, version: x.data?.version }))
    .catch(() => ({ healthy: false }))
}

export function DialogSelectServer() {
  const navigate = useNavigate()
  const dialog = useDialog()
  const server = useServer()
  const platform = usePlatform()
  const [store, setStore] = createStore({
    url: "",
    adding: false,
    error: "",
    status: {} as Record<string, ServerStatus | undefined>,
  })
  const [defaultUrl, defaultUrlActions] = createResource(() => platform.getDefaultServerUrl?.())
  const isDesktop = platform.platform === "desktop"

  const items = createMemo(() => {
    const current = server.url
    const list = server.list
    if (!current) return list
    if (!list.includes(current)) return [current, ...list]
    return [current, ...list.filter((x) => x !== current)]
  })

  const current = createMemo(() => items().find((x) => x === server.url) ?? items()[0])

  const sortedItems = createMemo(() => {
    const list = items()
    if (!list.length) return list
    const active = current()
    const order = new Map(list.map((url, index) => [url, index] as const))
    const rank = (value?: ServerStatus) => {
      if (value?.healthy === true) return 0
      if (value?.healthy === false) return 2
      return 1
    }
    return list.slice().sort((a, b) => {
      if (a === active) return -1
      if (b === active) return 1
      const diff = rank(store.status[a]) - rank(store.status[b])
      if (diff !== 0) return diff
      return (order.get(a) ?? 0) - (order.get(b) ?? 0)
    })
  })

  async function refreshHealth() {
    const results: Record<string, ServerStatus> = {}
    await Promise.all(
      items().map(async (url) => {
        results[url] = await checkHealth(url, platform.fetch)
      }),
    )
    setStore("status", reconcile(results))
  }

  createEffect(() => {
    items()
    refreshHealth()
    const interval = setInterval(refreshHealth, 10_000)
    onCleanup(() => clearInterval(interval))
  })

  function select(value: string, persist?: boolean) {
    if (!persist && store.status[value]?.healthy === false) return
    dialog.close()
    if (persist) {
      server.add(value)
      navigate("/")
      return
    }
    server.setActive(value)
    navigate("/")
  }

  async function handleSubmit(e: SubmitEvent) {
    e.preventDefault()
    const value = normalizeServerUrl(store.url)
    if (!value) return

    setStore("adding", true)
    setStore("error", "")

    const result = await checkHealth(value, platform.fetch)
    setStore("adding", false)

    if (!result.healthy) {
      setStore("error", "Could not connect to server")
      return
    }

    setStore("url", "")
    select(value, true)
  }

  async function handleRemove(url: string) {
    server.remove(url)
  }

  return (
    <Dialog title="Servers" description="Switch which OpenCode server this app connects to.">
      <div class="flex flex-col gap-4 pb-4">
        <List
          search={{ placeholder: "Search servers", autofocus: true }}
          emptyMessage="No servers yet"
          items={sortedItems}
          key={(x) => x}
          current={current()}
          onSelect={(x) => {
            if (x) select(x)
          }}
        >
          {(i) => (
            <div class="flex items-center gap-2 min-w-0 flex-1 group/item">
              <div
                class="flex items-center gap-2 min-w-0 flex-1"
                classList={{ "opacity-50": store.status[i]?.healthy === false }}
              >
                <div
                  classList={{
                    "size-1.5 rounded-full shrink-0": true,
                    "bg-icon-success-base": store.status[i]?.healthy === true,
                    "bg-icon-critical-base": store.status[i]?.healthy === false,
                    "bg-border-weak-base": store.status[i] === undefined,
                  }}
                />
                <span class="truncate">{serverDisplayName(i)}</span>
                <span class="text-text-weak">{store.status[i]?.version}</span>
              </div>
              <Show when={current() !== i && server.list.includes(i)}>
                <IconButton
                  icon="circle-x"
                  variant="ghost"
                  class="bg-transparent transition-opacity shrink-0 hover:scale-110"
                  onClick={(e) => {
                    e.stopPropagation()
                    handleRemove(i)
                  }}
                />
              </Show>
            </div>
          )}
        </List>

        <div class="mt-6 px-3 flex flex-col gap-1.5">
          <div class="px-3">
            <h3 class="text-14-regular text-text-weak">Add a server</h3>
          </div>
          <form onSubmit={handleSubmit}>
            <div class="flex items-start gap-2">
              <div class="flex-1 min-w-0 h-auto">
                <TextField
                  type="text"
                  label="Server URL"
                  hideLabel
                  placeholder="http://localhost:4096"
                  value={store.url}
                  onChange={(v) => {
                    setStore("url", v)
                    setStore("error", "")
                  }}
                  validationState={store.error ? "invalid" : "valid"}
                  error={store.error}
                />
              </div>
              <Button type="submit" variant="secondary" icon="plus-small" size="large" disabled={store.adding}>
                {store.adding ? "Checking..." : "Add"}
              </Button>
            </div>
          </form>
        </div>

        <Show when={isDesktop}>
          <div class="mt-6 px-3 flex flex-col gap-1.5">
            <div class="px-3">
              <h3 class="text-14-regular text-text-weak">Default server</h3>
              <p class="text-12-regular text-text-weak mt-1">
                Connect to this server on app launch instead of starting a local server. Requires restart.
              </p>
            </div>
            <div class="flex items-center gap-2 px-3 py-2">
              <Show
                when={defaultUrl()}
                fallback={
                  <Show
                    when={server.url}
                    fallback={<span class="text-14-regular text-text-weak">No server selected</span>}
                  >
                    <Button
                      variant="secondary"
                      size="small"
                      onClick={async () => {
                        await platform.setDefaultServerUrl?.(server.url)
                        defaultUrlActions.refetch(server.url)
                      }}
                    >
                      Set current server as default
                    </Button>
                  </Show>
                }
              >
                <div class="flex items-center gap-2 flex-1 min-w-0">
                  <span class="truncate text-14-regular">{serverDisplayName(defaultUrl()!)}</span>
                </div>
                <Button
                  variant="ghost"
                  size="small"
                  onClick={async () => {
                    await platform.setDefaultServerUrl?.(null)
                    defaultUrlActions.refetch()
                  }}
                >
                  Clear
                </Button>
              </Show>
            </div>
          </div>
        </Show>
      </div>
    </Dialog>
  )
}