File size: 12,832 Bytes
3e05655
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import fuzzysort from "fuzzysort"
import type {
  WslInstalledDistro,
  WslOnlineDistro,
  WslOpencodeCheck,
  WslServersPlatform,
  WslServerRuntime,
  WslServersState,
} from "./types"

export type AddServerText = {
  key: string
  params?: Record<string, string>
}

export type DistroStatusTone = "success" | "warning" | "muted"

export type DistroStatus = {
  label: AddServerText
  tone: DistroStatusTone
}

export type AddServerPrimaryButton = {
  variant: "neutral" | "contrast"
  label: AddServerText
  disabled: boolean
  action: "install-opencode" | "add" | null
  loading: boolean
  width: string | null
}

export type AddServerRuntimeState = "loading" | "pendingRestart" | "checking" | "unavailable" | "ready"

export type AddableProbePlan = {
  key: string
  distros: string[]
}

export type AutoProbePlan = { key: "runtime"; action: "probeRuntime" } | { key: "distros"; action: "refreshDistros" }

export type AddServerProbePlan =
  | { kind: "auto"; key: string; plan: AutoProbePlan }
  | { kind: "addable"; key: string; plan: AddableProbePlan }

export type WslAddServerView = "main" | "catalog"

function isHiddenDistro(name: string) {
  return /^docker-desktop(?:-data)?$/i.test(name)
}

export const wslRuntimeRetryable = (runtime: WslServerRuntime) =>
  runtime.kind === "failed" || runtime.kind === "stopped"

export function wslOpencodeAction(check?: WslOpencodeCheck) {
  if (!check) return
  if (!check.resolvedPath) return "wsl.onboarding.installOpencode"
  if (check.matchesDesktop === false) return "wsl.onboarding.updateOpencode"
}

export function wslDistroReady(state: WslServersState | undefined, name: string) {
  const installed = state?.installed.find((item) => item.name === name)
  const probe = state?.distroProbes[name]
  if (!probe || !installed) return false
  if (installed.version === 1) return false
  return probe.canExecute && probe.hasBash && probe.hasCurl
}

export function addServerViewModel(input: {
  state: WslServersState | undefined
  view: WslAddServerView
  selectedDistro: string | null
  catalogSearch: string
  catalogTarget: string | null
  adding: boolean
  probingAddable: boolean
}) {
  const state = input.state
  const visibleInstalledDistros = (state?.installed ?? []).filter((item) => !isHiddenDistro(item.name))
  const visibleOnlineDistros = (state?.online ?? []).filter((item) => !isHiddenDistro(item.name))
  const existingServerDistros = new Set((state?.servers ?? []).map((item) => item.config.distro))
  const addableInstalledDistros = visibleInstalledDistros.filter((item) => !existingServerDistros.has(item.name))
  const selectedDistro = addServerSelectedDistro(input.selectedDistro, visibleInstalledDistros, addableInstalledDistros)
  const opencodeCheck = selectedDistro ? (state?.opencodeChecks[selectedDistro] ?? null) : null
  const installableDistros = addServerInstallableDistros(visibleInstalledDistros, visibleOnlineDistros)
  const filteredInstallableDistros = addServerFilteredInstallableDistros(installableDistros, input.catalogSearch)
  const catalogTarget = addServerCatalogTarget(input.catalogTarget, filteredInstallableDistros)
  const busy = !!state?.job || input.adding || input.probingAddable

  return {
    busy,
    runtimeState: addServerRuntimeState(state),
    visibleInstalledDistros,
    visibleOnlineDistros,
    addableInstalledDistros,
    selectedDistro,
    opencodeCheck,
    wslReady: !!state?.runtime?.available && !state?.pendingRestart,
    distroStatuses: Object.fromEntries(
      addableInstalledDistros.flatMap((item) => {
        const status = addServerDistroStatus({ state, name: item.name, probingAddable: input.probingAddable })
        if (!status) return []
        return [[item.name, status]]
      }),
    ) as Record<string, DistroStatus | undefined>,
    primaryButton: addServerPrimaryButton({
      state,
      selectedDistro,
      opencodeCheck,
      adding: input.adding,
      probingAddable: input.probingAddable,
    }),
    installableDistros,
    filteredInstallableDistros,
    catalogTarget,
    installingCatalogDistro: state?.job?.kind === "install-distro",
  }
}

function addServerSelectedDistro(
  selected: string | null,
  visibleInstalledDistros: WslInstalledDistro[],
  addableInstalledDistros: WslInstalledDistro[],
) {
  if (selected && addableInstalledDistros.some((item) => item.name === selected && item.version !== 1)) return selected
  const defaultDistro = visibleInstalledDistros.find((item) => item.isDefault)
  if (
    defaultDistro &&
    defaultDistro.version !== 1 &&
    addableInstalledDistros.some((item) => item.name === defaultDistro.name)
  ) {
    return defaultDistro.name
  }
  return addableInstalledDistros.find((item) => item.version !== 1)?.name ?? null
}

function addServerRuntimeState(state: WslServersState | undefined): AddServerRuntimeState {
  if (!state) return "loading"
  if (state.pendingRestart) return "pendingRestart"
  if (!state.runtime) return "checking"
  if (!state.runtime.available) return "unavailable"
  return "ready"
}

function addServerDistroStatus(input: {
  state: WslServersState | undefined
  name: string
  probingAddable: boolean
}): DistroStatus | undefined {
  const installed = input.state?.installed.find((item) => item.name === input.name)
  if (installed?.version === 1) return { label: { key: "wsl.onboarding.distroStatus.unsupported" }, tone: "muted" }
  const job = input.state?.job
  const probe = input.state?.distroProbes[input.name]
  if (!probe) {
    if (input.probingAddable || (job?.kind === "probe-addable" && job.distros.includes(input.name))) {
      return checkingStatus()
    }
    return
  }
  if (!probe.canExecute) {
    if (!installed) {
      return { label: { key: "wsl.onboarding.distroNotInstalled", params: { distro: input.name } }, tone: "warning" }
    }
    return { label: { key: "wsl.onboarding.openDistroOnce", params: { distro: input.name } }, tone: "warning" }
  }
  if (!probe.hasBash || !probe.hasCurl) {
    return { label: { key: "wsl.onboarding.distroStatus.missingTools" }, tone: "warning" }
  }
  const check = input.state?.opencodeChecks[input.name]
  if (!check) {
    if (input.probingAddable || (job?.kind === "probe-addable" && job.distros.includes(input.name))) {
      return checkingStatus()
    }
    return
  }
  if (check.matchesDesktop === false) return { label: { key: "wsl.onboarding.updateOpencode" }, tone: "warning" }
  if (!check.resolvedPath) return { label: { key: "wsl.onboarding.distroStatus.opencodeMissing" }, tone: "warning" }
  if (check.error) return { label: { key: "wsl.onboarding.installOpencode" }, tone: "warning" }
  return { label: { key: "wsl.onboarding.distroStatus.ready" }, tone: "success" }
}

function checkingStatus(): DistroStatus {
  return { label: { key: "wsl.onboarding.distroStatus.checking" }, tone: "muted" }
}

function addServerPrimaryButton(input: {
  state: WslServersState | undefined
  selectedDistro: string | null
  opencodeCheck: WslOpencodeCheck | null
  adding: boolean
  probingAddable: boolean
}): AddServerPrimaryButton {
  const ready = !!input.selectedDistro && wslDistroReady(input.state, input.selectedDistro)
  const probingSelected = input.probingAddable && !addServerSelectedDistroSettled(input.state, input.selectedDistro)
  const probingOpencode =
    probingSelected ||
    (ready &&
      (!input.opencodeCheck ||
        (!!input.selectedDistro &&
          input.state?.job?.kind === "probe-addable" &&
          input.state.job.distros.includes(input.selectedDistro))))
  const installingOpencode =
    input.state?.job?.kind === "install-opencode" && input.state.job.distro === input.selectedDistro
  if (!ready || probingOpencode) {
    return {
      variant: "contrast",
      label: probingSelected ? { key: "wsl.onboarding.distroStatus.checking" } : { key: "wsl.server.add" },
      disabled: true,
      action: null,
      loading: probingSelected,
      width: null,
    }
  }
  if (!addServerOpencodeReady(input.opencodeCheck)) {
    const update = !!input.opencodeCheck?.resolvedPath && input.opencodeCheck.matchesDesktop === false
    return {
      variant: "neutral",
      label: installingOpencode
        ? { key: "wsl.onboarding.updatingOpencode" }
        : update
          ? { key: "wsl.onboarding.updateOpencode" }
          : { key: "wsl.onboarding.installOpencode" },
      disabled: !!input.state?.job || input.adding,
      action: "install-opencode",
      loading: installingOpencode,
      width: update ? "138px" : "129px",
    }
  }
  return {
    variant: "contrast",
    label: input.adding ? { key: "wsl.onboarding.adding" } : { key: "wsl.server.add" },
    disabled: input.adding || !!input.state?.job,
    action: "add",
    loading: input.adding,
    width: null,
  }
}

function addServerOpencodeReady(check: WslOpencodeCheck | null) {
  return !!check?.resolvedPath && check.matchesDesktop !== false && !check.error
}

function addServerSelectedDistroSettled(state: WslServersState | undefined, selectedDistro: string | null) {
  if (!selectedDistro) return false
  const installed = state?.installed.find((item) => item.name === selectedDistro)
  if (installed?.version === 1) return false
  if (!state?.distroProbes[selectedDistro]) return false
  if (!wslDistroReady(state, selectedDistro)) return true
  return !!state.opencodeChecks[selectedDistro]
}

function addServerInstallableDistros(installedDistros: WslInstalledDistro[], onlineDistros: WslOnlineDistro[]) {
  const installed = new Set(installedDistros.map((item) => item.name))
  const hasVersionedUbuntu = onlineDistros.some((item) => /^Ubuntu-\d/.test(item.name))
  return onlineDistros
    .filter((item) => !installed.has(item.name))
    .filter((item) => item.name !== "Ubuntu" || !hasVersionedUbuntu)
}

function addServerFilteredInstallableDistros(installableDistros: WslOnlineDistro[], search: string) {
  const query = search.trim()
  if (!query) return installableDistros
  return fuzzysort.go(query, installableDistros, { keys: ["label", "name"] }).map((item) => item.obj)
}

function addServerCatalogTarget(target: string | null, distros: WslOnlineDistro[]) {
  if (target && distros.some((item) => item.name === target)) return target
  return distros[0]?.name ?? null
}

export function addableProbePlan(input: {
  state: WslServersState | undefined
  view: WslAddServerView
  adding: boolean
  selectedDistro: string | null
  addableInstalledDistros: WslInstalledDistro[]
}) {
  const state = input.state
  if (!state?.runtime?.available || state.pendingRestart || input.view !== "main" || input.adding) return
  if (state.job) return
  const ordered = input.selectedDistro
    ? [
        ...input.addableInstalledDistros.filter((item) => item.name === input.selectedDistro),
        ...input.addableInstalledDistros.filter((item) => item.name !== input.selectedDistro),
      ]
    : input.addableInstalledDistros
  const pending = ordered.flatMap((item) => {
    if (item.version === 1) return []
    if (!state.distroProbes[item.name]) return [`distro:${item.name}`]
    if (wslDistroReady(state, item.name) && !state.opencodeChecks[item.name]) return [`opencode:${item.name}`]
    return []
  })
  if (!pending.length) return
  return {
    key: pending.join("|"),
    distros: ordered.filter((item) => item.version !== 1).map((item) => item.name),
  } satisfies AddableProbePlan
}

export function autoProbePlan(input: { state: WslServersState | undefined; busy: boolean }) {
  if (!input.state || input.busy || input.state.pendingRestart) return
  if (!input.state.runtime) return { key: "runtime", action: "probeRuntime" } satisfies AutoProbePlan
  if (!input.state.runtime.available) return
  if (input.state.installed.length || input.state.online.length) return
  return { key: "distros", action: "refreshDistros" } satisfies AutoProbePlan
}

export function addServerProbePlan(input: {
  state: WslServersState | undefined
  view: WslAddServerView
  adding: boolean
  busy: boolean
  selectedDistro: string | null
  addableInstalledDistros: WslInstalledDistro[]
}) {
  const auto = autoProbePlan({ state: input.state, busy: input.busy })
  if (auto) return { kind: "auto", key: `auto:${auto.key}`, plan: auto } satisfies AddServerProbePlan
  const addable = addableProbePlan(input)
  if (addable) return { kind: "addable", key: `addable:${addable.key}`, plan: addable } satisfies AddServerProbePlan
}

export function createProbeFailureGate() {
  let failed: string | undefined
  return {
    accepts(key: string) {
      return key !== failed
    },
    settle(key: string, error?: unknown) {
      if (error) failed = key
    },
    reset() {
      failed = undefined
    },
  }
}

export async function runAddableProbePlan(input: {
  plan: AddableProbePlan
  api: Pick<WslServersPlatform, "probeAddable">
}) {
  await input.api.probeAddable(input.plan.distros)
}