@huaqiu/dsh-hardware-ui 0.7.18 → 0.7.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,790 @@
1
+ /**
2
+ * Client-side toolchain state: one controller, shared by every surface.
3
+ *
4
+ * The wizard step and the Settings section must never disagree about what is
5
+ * configured (§10.5), so nothing here is duplicated per surface: both read this
6
+ * controller, which is the only thing that polls the Host, starts a download,
7
+ * or opens a native chooser. The controller holds no React state — it exposes a
8
+ * `useSyncExternalStore`-shaped snapshot — so it can live for the lifetime of
9
+ * the plugin, survive the settings dialog closing, and keep a download running
10
+ * while the user navigates away.
11
+ *
12
+ * Two kinds of fact arrive from the Host and are kept apart deliberately:
13
+ * - `status` is authoritative (the Host resolves paths with the same parser a
14
+ * manual save uses), and is re-read after every write;
15
+ * - `job` is a mirror of one install run, polled only while it is running.
16
+ *
17
+ * Everything the surfaces show about a tool is a projection of those two; none
18
+ * of them decides "configured" on its own.
19
+ *
20
+ * @module @huaqiu/dsh-hardware-ui/client/toolchain
21
+ */
22
+ import { COPY } from './copy.js'
23
+ import { messageOf } from './transport.js'
24
+ import {
25
+ browseToolchain, cancelToolchain, installToolchain, loadToolchainStatus,
26
+ saveToolchain, startToolchainDiscovery, validateToolchain,
27
+ } from './transport.js'
28
+
29
+ export type ToolchainId = 'kicad' | 'solidcraft'
30
+
31
+ /** §10.3 status semantics: green only ever follows a successful validation. */
32
+ export type ToolState = 'unconfigured' | 'validating' | 'configured' | 'invalid'
33
+
34
+ export type ToolSource = 'manual' | 'browse' | 'download' | 'detected'
35
+
36
+ export type InstallPhase =
37
+ | 'download' | 'verify' | 'extract' | 'layout' | 'promote' | 'done' | 'failed' | 'cancelled'
38
+
39
+ /** One directory discovery looked at, and what it found there. */
40
+ export interface DiscoveryCandidate {
41
+ readonly path: string
42
+ readonly origin: 'managed' | 'system' | 'user-local'
43
+ readonly valid: boolean
44
+ readonly version?: string
45
+ readonly cli?: string
46
+ readonly error?: string
47
+ }
48
+
49
+ /** Background discovery state for one tool (§4.2 — never blocks the UI). */
50
+ export interface ToolDiscoveryView {
51
+ readonly tool: ToolchainId
52
+ readonly state: 'idle' | 'running' | 'done' | 'failed'
53
+ readonly candidates: readonly DiscoveryCandidate[]
54
+ readonly selected?: DiscoveryCandidate
55
+ readonly error?: string
56
+ readonly finishedAt?: number
57
+ }
58
+
59
+ /** One tool's row in the two cards. */
60
+ export interface ToolStatus {
61
+ readonly tool: ToolchainId
62
+ readonly state: ToolState
63
+ readonly installPath?: string
64
+ readonly cliPath?: string
65
+ readonly appPath?: string
66
+ readonly version?: string
67
+ readonly source?: ToolSource
68
+ readonly validatedAt?: number
69
+ readonly error?: string
70
+ readonly discovery: ToolDiscoveryView
71
+ readonly download?: { readonly version: string; readonly url: string }
72
+ }
73
+
74
+ /**
75
+ * The executable picker the card's Browse opens (prototype §"SIMULATED OS SYSTEM
76
+ * FILE EXPLORER DIALOG"): the detected executables as a list, a path field, and a
77
+ * link that hands the choice to the real OS dialog.
78
+ */
79
+ export interface ToolchainPicker {
80
+ readonly tool: ToolchainId
81
+ /** Row the user clicked; mirrored into the footer's path field. */
82
+ readonly chosen?: string
83
+ /** The real OS chooser is open; the modal waits for it. */
84
+ readonly nativePending: boolean
85
+ /** Rows on offer, from the last discovery answer (invalid ones included, disabled). */
86
+ readonly candidates: readonly DiscoveryCandidate[]
87
+ readonly refreshing: boolean
88
+ }
89
+
90
+ /** Everything both surfaces need, from one poll. */
91
+ export interface ToolchainStatus {
92
+ readonly kicad: ToolStatus
93
+ readonly solidcraft: ToolStatus
94
+ readonly manifest:
95
+ | { readonly state: 'unknown' | 'loading' }
96
+ | { readonly state: 'ready'; readonly schemaVersion: number; readonly url: string }
97
+ | { readonly state: 'unavailable'; readonly code: string; readonly message: string }
98
+ readonly target: { readonly platform: string; readonly arch: string; readonly downloadsSupported: boolean }
99
+ readonly official: Readonly<Record<ToolchainId, string>>
100
+ /** Jobs the poll asked about, one per tool (both tools may install at once). */
101
+ readonly jobs?: readonly InstallJob[]
102
+ /** First of `jobs`; kept for callers that only ever watch one run. */
103
+ readonly job?: InstallJob
104
+ }
105
+
106
+ /** One install run, as the Host reports it. */
107
+ export interface InstallJob {
108
+ readonly id: string
109
+ readonly tool: ToolchainId
110
+ readonly version: string
111
+ readonly phase: InstallPhase
112
+ readonly received: number
113
+ readonly total?: number
114
+ readonly percent?: number
115
+ readonly message: string
116
+ readonly errorCode?: string
117
+ readonly error?: string
118
+ readonly installPath?: string
119
+ readonly startedAt: number
120
+ readonly finishedAt?: number
121
+ }
122
+
123
+ /**
124
+ * Verdict for the text currently in one card's input.
125
+ *
126
+ * The wizard's primary button must not pretend a typed path is usable, and the
127
+ * Settings verdict must not claim "not saved" about a path the Host just
128
+ * accepted, so the input's own validity is checked against the Host whenever the
129
+ * text settles ({@link ToolchainController.setDraft} debounces it).
130
+ */
131
+ export interface DraftCheck {
132
+ readonly state: 'pending' | 'valid' | 'invalid'
133
+ /** Root the Host normalised the text to; present when known. */
134
+ readonly installPath?: string
135
+ readonly version?: string
136
+ readonly error?: string
137
+ }
138
+
139
+ /** A save the Host just accepted, shown as the card's success badge until it fades. */
140
+ export interface SaveConfirmation {
141
+ readonly at: number
142
+ readonly version?: string
143
+ }
144
+
145
+ /** Verdict of a validate / save round trip. */
146
+ export interface ValidationOutcome {
147
+ readonly ok: boolean
148
+ readonly installPath?: string
149
+ readonly cliPath?: string
150
+ readonly appPath?: string
151
+ readonly version?: string
152
+ readonly error?: string
153
+ }
154
+
155
+ /** Result of a native browse request (§6.2). */
156
+ export interface BrowseOutcome {
157
+ readonly kind: 'picked' | 'cancelled' | 'unsupported'
158
+ readonly path?: string
159
+ readonly mechanism?: string
160
+ readonly message?: string
161
+ }
162
+
163
+ /** Tone of one transient notice (§11 — never a modal for an ordinary failure). */
164
+ export type ToastTone = 'ok' | 'warn' | 'error' | 'info'
165
+
166
+ export interface ToastItem {
167
+ readonly id: number
168
+ readonly tone: ToastTone
169
+ readonly text: string
170
+ }
171
+
172
+ /** Immutable render state; identity changes only when something changed. */
173
+ export interface ToolchainSnapshot {
174
+ readonly status?: ToolchainStatus
175
+ readonly loading: boolean
176
+ readonly error?: string
177
+ /** Tool whose save round trip is in flight, for per-card button state. */
178
+ readonly saving?: ToolchainId
179
+ /**
180
+ * Install jobs by tool. Keyed by tool, not "the current job": both tools can
181
+ * download at the same time, and each card owns its own bar.
182
+ */
183
+ readonly jobs: Readonly<Partial<Record<ToolchainId, InstallJob>>>
184
+ /** Path currently held in each card's input, kept here so both surfaces agree. */
185
+ readonly drafts: Readonly<Record<ToolchainId, string>>
186
+ /** Live verdict of each card's text, from the Host's own validation. */
187
+ readonly checks: Readonly<Partial<Record<ToolchainId, DraftCheck>>>
188
+ /** Saves the Host accepted recently; the card shows a badge, then it fades. */
189
+ readonly confirmed: Readonly<Partial<Record<ToolchainId, SaveConfirmation>>>
190
+ readonly toasts: readonly ToastItem[]
191
+ /** Open executable picker (Browse), if any. */
192
+ readonly picker?: ToolchainPicker
193
+ }
194
+
195
+ /** The Host calls the controller needs; injectable so tests need no HTTP. */
196
+ export interface ToolchainTransport {
197
+ status(jobIds?: readonly string[]): Promise<ToolchainStatus>
198
+ validate(tool: ToolchainId, path: string): Promise<ValidationOutcome>
199
+ save(tool: ToolchainId, path: string, source: ToolSource): Promise<ValidationOutcome>
200
+ browse(tool: ToolchainId): Promise<BrowseOutcome>
201
+ install(tool: ToolchainId): Promise<InstallJob | undefined>
202
+ cancel(id: string): Promise<boolean>
203
+ discover(tool?: ToolchainId): Promise<void>
204
+ }
205
+
206
+ /** Real transport: the plugin's own route prefix, via `transport.ts`. */
207
+ export const HOST_TRANSPORT: ToolchainTransport = {
208
+ status: jobIds => loadToolchainStatus(jobIds),
209
+ validate: (tool, path) => validateToolchain(tool, path),
210
+ save: (tool, path, source) => saveToolchain(tool, path, source),
211
+ browse: tool => browseToolchain(tool),
212
+ install: tool => installToolchain(tool),
213
+ cancel: id => cancelToolchain(id),
214
+ discover: tool => startToolchainDiscovery(tool),
215
+ }
216
+
217
+ /** How long one toast stays before it fades on its own. */
218
+ const TOAST_MS = 7000
219
+ /** Poll cadence while a job or a discovery run is live. */
220
+ const POLL_MS = 700
221
+ /** How long a typed path must settle before its validity is asked of the Host. */
222
+ const CHECK_MS = 500
223
+ /** How long the "saved" badge stays on a card after the Host accepted the write. */
224
+ const CONFIRM_MS = 6000
225
+
226
+ const EMPTY_DRAFTS: Readonly<Record<ToolchainId, string>> = { kicad: '', solidcraft: '' }
227
+
228
+ /** Is this job still doing work? */
229
+ export function jobRunning(job: InstallJob | undefined): boolean {
230
+ if (job === undefined) return false
231
+ return job.phase !== 'done' && job.phase !== 'failed' && job.phase !== 'cancelled'
232
+ }
233
+
234
+ /**
235
+ * Merge the jobs a poll returned into the per-tool map.
236
+ *
237
+ * The Host answers only about the ids we asked for, so anything it omits is kept
238
+ * from the previous snapshot — a poll that races the end of a run must not blank
239
+ * the other card's bar. Incoming jobs win for their own tool.
240
+ */
241
+ function collectJobs(
242
+ status: ToolchainStatus,
243
+ previous: Readonly<Partial<Record<ToolchainId, InstallJob>>>,
244
+ ): Readonly<Partial<Record<ToolchainId, InstallJob>>> {
245
+ const incoming = status.jobs ?? (status.job === undefined ? [] : [status.job])
246
+ if (incoming.length === 0) return previous
247
+ const next = { ...previous }
248
+ for (const job of incoming) next[job.tool] = job
249
+ return next
250
+ }
251
+
252
+ /** Whole-percent progress, derived when the Host has no reliable total. */
253
+ export function jobPercent(job: InstallJob | undefined): number | undefined {
254
+ if (job === undefined) return undefined
255
+ if (job.percent !== undefined) return job.percent
256
+ if (job.total === undefined || job.total <= 0) return undefined
257
+ return Math.min(100, Math.round((job.received / job.total) * 100))
258
+ }
259
+
260
+ /** Both tools configured and validated — the condition that ends the nudges. */
261
+ export function setupComplete(status: ToolchainStatus | undefined): boolean {
262
+ return status?.kicad.state === 'configured' && status.solidcraft.state === 'configured'
263
+ }
264
+
265
+ /** True while any tool still needs the user (§10.4 sidebar dot). */
266
+ export function setupIncomplete(status: ToolchainStatus | undefined): boolean {
267
+ if (status === undefined) return false
268
+ return status.kicad.state !== 'configured' || status.solidcraft.state !== 'configured'
269
+ }
270
+
271
+ /** One status line for the sidebar indicator's tooltip. */
272
+ export function setupSummary(status: ToolchainStatus | undefined): string {
273
+ if (status === undefined) return COPY.toolchain.checking
274
+ const kicad = status.kicad.state === 'configured' ? `KiCad v${status.kicad.version ?? '?'}` : COPY.toolchain.kicadMissing
275
+ const solidcraft = status.solidcraft.state === 'configured'
276
+ ? `SolidCraft v${status.solidcraft.version ?? '?'}`
277
+ : COPY.toolchain.solidcraftMissing
278
+ return `${kicad} · ${solidcraft}`
279
+ }
280
+
281
+ type Listener = () => void
282
+
283
+ /**
284
+ * The one toolchain state machine of the browser half.
285
+ *
286
+ * Writes are serialised by the Host (validate/save/install each answer before
287
+ * the next poll), so the controller keeps no queue: it refreshes after every
288
+ * write it issues and lets the poll be the arbiter. Polling stops as soon as
289
+ * nothing is running, which keeps an idle settings panel free of requests.
290
+ */
291
+ export class ToolchainController {
292
+ private snapshot: ToolchainSnapshot = {
293
+ loading: true, jobs: {}, drafts: EMPTY_DRAFTS, checks: {}, confirmed: {}, toasts: [],
294
+ }
295
+ private readonly listeners = new Set<Listener>()
296
+ private toastSeq = 0
297
+ private timer?: ReturnType<typeof setTimeout>
298
+ private readonly timers = new Map<number, ReturnType<typeof setTimeout>>()
299
+ private stopped = false
300
+ private started = false
301
+ /** §11 notices fire once per phase *per tool*, so two downloads cannot mute each other. */
302
+ private readonly phases = new Map<ToolchainId, InstallPhase>()
303
+ /** The job id each tool's card is watching; the poll asks for all of them at once. */
304
+ private readonly watched = new Map<ToolchainId, string>()
305
+ /** Debounce timers for the input's own validity check, one per tool. */
306
+ private readonly checkTimers = new Map<ToolchainId, ReturnType<typeof setTimeout>>()
307
+ /** Per-tool sequence so a late answer cannot overwrite a newer verdict. */
308
+ private readonly checkSeq = new Map<ToolchainId, number>()
309
+ /** Timers that retract the "saved" badge after {@link CONFIRM_MS}. */
310
+ private readonly confirmTimers = new Map<ToolchainId, ReturnType<typeof setTimeout>>()
311
+
312
+ constructor(
313
+ private readonly transport: ToolchainTransport = HOST_TRANSPORT,
314
+ private readonly pollMs = POLL_MS,
315
+ ) {}
316
+
317
+ subscribe = (listener: Listener): (() => void) => {
318
+ this.listeners.add(listener)
319
+ return () => { this.listeners.delete(listener) }
320
+ }
321
+
322
+ getSnapshot = (): ToolchainSnapshot => this.snapshot
323
+
324
+ private set(patch: Partial<ToolchainSnapshot>): void {
325
+ this.snapshot = { ...this.snapshot, ...patch }
326
+ for (const listener of this.listeners) listener()
327
+ }
328
+
329
+ /**
330
+ * Boot the capability once per client session: read the status, then start
331
+ * discovery in the background (§4.2 — the wizard opens first, discovery
332
+ * answers later). Safe to call twice: the second call is a no-op.
333
+ */
334
+ start(): void {
335
+ if (this.started) return
336
+ this.started = true
337
+ void this.refresh()
338
+ void this.transport.discover().catch(() => { /* discovery failure is a state, not an error */ })
339
+ }
340
+
341
+ /** Stop polling and drop timers (plugin unload). */
342
+ stop(): void {
343
+ this.stopped = true
344
+ if (this.timer !== undefined) clearTimeout(this.timer)
345
+ this.timer = undefined
346
+ for (const timer of this.timers.values()) clearTimeout(timer)
347
+ this.timers.clear()
348
+ for (const timer of this.checkTimers.values()) clearTimeout(timer)
349
+ this.checkTimers.clear()
350
+ for (const timer of this.confirmTimers.values()) clearTimeout(timer)
351
+ this.confirmTimers.clear()
352
+ this.listeners.clear()
353
+ }
354
+
355
+ /** Read the Host status, asking about every job a card is watching. */
356
+ async refresh(jobIds?: readonly string[]): Promise<void> {
357
+ if (this.stopped) return
358
+ const asked = jobIds ?? [...this.watched.values()]
359
+ try {
360
+ const status = await this.transport.status(asked.length === 0 ? undefined : asked)
361
+ if (this.stopped) return
362
+ // Keep the drafts in step with authoritative paths, but never overwrite
363
+ // text the user is typing: only a changed stored root moves the input.
364
+ let drafts = this.snapshot.drafts
365
+ const kicad = this.syncDraft('kicad', status.kicad.installPath)
366
+ if (kicad !== undefined) drafts = { ...drafts, kicad }
367
+ const solidcraft = this.syncDraft('solidcraft', status.solidcraft.installPath)
368
+ if (solidcraft !== undefined) drafts = { ...drafts, solidcraft }
369
+ const jobs = collectJobs(status, this.snapshot.jobs)
370
+ // A stored root the Host itself resolved is valid by definition; adopt its
371
+ // verdict so a configured tool needs no round trip to light up the button.
372
+ const checks = { ...this.snapshot.checks }
373
+ if ((kicad ?? solidcraft) !== undefined) {
374
+ if (kicad !== undefined) checks.kicad = { state: 'valid', installPath: kicad }
375
+ if (solidcraft !== undefined) checks.solidcraft = { state: 'valid', installPath: solidcraft }
376
+ }
377
+ this.set({ status, loading: false, error: undefined, drafts, jobs, checks })
378
+ for (const job of Object.values(jobs)) {
379
+ if (job !== undefined) this.noteJob(job)
380
+ }
381
+ // Stop asking about runs that are over — but only when we actually know
382
+ // that. A poll that arrives before the Host reports a just-started job (or
383
+ // answers nothing about it) must not silently drop the bar it is drawing.
384
+ for (const [tool, id] of this.watched) {
385
+ const seen = jobs[tool]
386
+ if (seen !== undefined && seen.id === id && jobRunning(seen)) continue
387
+ if (seen !== undefined && seen.id !== id && jobRunning(seen)) {
388
+ this.watched.set(tool, seen.id)
389
+ continue
390
+ }
391
+ this.watched.delete(tool)
392
+ }
393
+ this.scheduleIfBusy()
394
+ } catch (error) {
395
+ if (this.stopped) return
396
+ this.set({ loading: false, error: messageOf(error) })
397
+ }
398
+ }
399
+
400
+ /** Last authoritative root seen per tool; the draft follows it, not the other way round. */
401
+ private roots: Record<ToolchainId, string> = { kicad: '', solidcraft: '' }
402
+
403
+ /**
404
+ * Move the input with the authoritative root, unless the user owns the text.
405
+ *
406
+ * The input follows a changed stored root only while it is empty or still shows
407
+ * the previous root. Anything the user typed — or picked in the executable
408
+ * picker — is theirs until they save it, so a poll (or the rescan the picker
409
+ * itself triggers) cannot erase it.
410
+ */
411
+ private syncDraft(tool: ToolchainId, installPath: string | undefined): string | undefined {
412
+ const next = installPath ?? ''
413
+ const previous = this.roots[tool]
414
+ if (next === previous) return undefined
415
+ this.roots[tool] = next
416
+ const draft = this.snapshot.drafts[tool]
417
+ if (draft !== '' && draft !== previous) return undefined
418
+ return next
419
+ }
420
+
421
+ /** One card's input text, with the other tool's text untouched. */
422
+ private withDraft(tool: ToolchainId, value: string): Readonly<Record<ToolchainId, string>> {
423
+ return tool === 'kicad'
424
+ ? { ...this.snapshot.drafts, kicad: value }
425
+ : { ...this.snapshot.drafts, solidcraft: value }
426
+ }
427
+
428
+
429
+ /** Poll again while anything is live; sleep otherwise. */
430
+ private scheduleIfBusy(): void {
431
+ if (this.stopped) return
432
+ if (this.timer !== undefined) clearTimeout(this.timer)
433
+ this.timer = undefined
434
+ const busy = Object.values(this.snapshot.jobs).some(jobRunning)
435
+ || jobRunning(this.snapshot.status?.job)
436
+ || this.snapshot.status?.kicad.discovery.state === 'running'
437
+ || this.snapshot.status?.solidcraft.discovery.state === 'running'
438
+ if (!busy) return
439
+ this.timer = setTimeout(() => {
440
+ this.timer = undefined
441
+ void this.refresh()
442
+ }, this.pollMs)
443
+ }
444
+
445
+ /** One notice, deduplicated by text so a poll cannot spam the overlay. */
446
+ toast(tone: ToastTone, text: string): void {
447
+ if (this.snapshot.toasts.some(item => item.text === text)) return
448
+ this.toastSeq += 1
449
+ const id = this.toastSeq
450
+ this.set({ toasts: [...this.snapshot.toasts, { id, tone, text }].slice(-3) })
451
+ this.timers.set(id, setTimeout(() => {
452
+ this.timers.delete(id)
453
+ this.dismiss(id)
454
+ }, TOAST_MS))
455
+ }
456
+
457
+ /** Drop one notice (the overlay's own close button). */
458
+ dismiss(id: number): void {
459
+ const timer = this.timers.get(id)
460
+ if (timer !== undefined) {
461
+ clearTimeout(timer)
462
+ this.timers.delete(id)
463
+ }
464
+ if (!this.snapshot.toasts.some(item => item.id === id)) return
465
+ this.set({ toasts: this.snapshot.toasts.filter(item => item.id !== id) })
466
+ }
467
+
468
+ /** Fire the transitions §11 allows; nothing else notifies. */
469
+ private noteJob(job: InstallJob): void {
470
+ const previous = this.phases.get(job.tool)
471
+ if (previous === job.phase) return
472
+ this.phases.set(job.tool, job.phase)
473
+ const name = job.tool === 'kicad' ? 'KiCad' : 'SolidCraft'
474
+ if (job.phase === 'verify') this.toast('info', COPY.toolchain.toastDownloaded(name, job.version))
475
+ else if (job.phase === 'extract' || job.phase === 'layout' || job.phase === 'promote') {
476
+ if (previous !== 'extract' && previous !== 'layout' && previous !== 'promote') {
477
+ this.toast('info', COPY.toolchain.toastExtracting(name))
478
+ }
479
+ } else if (job.phase === 'done') {
480
+ this.toast('ok', COPY.toolchain.toastInstalled(name, job.version))
481
+ } else if (job.phase === 'failed') {
482
+ this.toast('error', job.errorCode === 'checksum-mismatch'
483
+ ? COPY.toolchain.toastChecksum(name)
484
+ : COPY.toolchain.toastFailed(name, job.error ?? job.message))
485
+ } else if (job.phase === 'cancelled') {
486
+ this.toast('warn', COPY.toolchain.toastCancelled(name))
487
+ }
488
+ }
489
+
490
+ /** Start the manifest-provided download for one tool (§7.4). */
491
+ async install(tool: ToolchainId): Promise<void> {
492
+ const name = tool === 'kicad' ? 'KiCad' : 'SolidCraft'
493
+ try {
494
+ const job = await this.transport.install(tool)
495
+ if (job === undefined) {
496
+ this.toast('warn', COPY.toolchain.downloadUnavailable(name))
497
+ return
498
+ }
499
+ // Watch this tool's job; the other card keeps watching its own, so two
500
+ // simultaneous downloads both keep a live bar.
501
+ this.watched.set(tool, job.id)
502
+ this.phases.delete(tool)
503
+ // Record it locally even when no status is known yet: the bar has to exist
504
+ // between the `install` answer and the first poll that mentions the job.
505
+ const current = this.snapshot.status
506
+ this.set({
507
+ jobs: { ...this.snapshot.jobs, [tool]: job },
508
+ ...(current === undefined ? {} : { status: { ...current, job } }),
509
+ })
510
+ this.toast('info', COPY.toolchain.toastStarted(name, job.version))
511
+ this.scheduleIfBusy()
512
+ void this.refresh([...this.watched.values()])
513
+ } catch (error) {
514
+ this.toast('warn', COPY.toolchain.downloadUnavailableWith(name, messageOf(error)))
515
+ }
516
+ }
517
+
518
+ /** Stop a running download or extraction. */
519
+ async cancel(id: string): Promise<void> {
520
+ try {
521
+ await this.transport.cancel(id)
522
+ } catch (error) {
523
+ this.toast('error', messageOf(error))
524
+ }
525
+ for (const [tool, jobId] of this.watched) {
526
+ if (jobId === id) this.watched.delete(tool)
527
+ }
528
+ await this.refresh()
529
+ }
530
+
531
+ /** Native chooser; a picked path lands in that card's input, not in config. */
532
+ async browse(tool: ToolchainId): Promise<string | undefined> {
533
+ try {
534
+ const outcome = await this.transport.browse(tool)
535
+ if (outcome.kind === 'picked' && outcome.path !== undefined) {
536
+ this.set({ drafts: this.withDraft(tool, outcome.path) })
537
+ return outcome.path
538
+ }
539
+ if (outcome.kind === 'unsupported') {
540
+ this.toast('warn', COPY.toolchain.browseUnsupported(outcome.message ?? ''))
541
+ }
542
+ return undefined
543
+ } catch (error) {
544
+ this.toast('error', messageOf(error))
545
+ return undefined
546
+ }
547
+ }
548
+
549
+ /** Open the executable picker for one tool (the card's Browse). */
550
+ openPicker(tool: ToolchainId): void {
551
+ const discovery = this.snapshot.status?.[tool].discovery
552
+ this.set({
553
+ picker: {
554
+ tool,
555
+ candidates: discovery?.candidates ?? [],
556
+ nativePending: false,
557
+ refreshing: false,
558
+ },
559
+ })
560
+ // A fresh profile may still be scanning, and an all-invalid list is worth
561
+ // re-checking: the picker opens at once and fills in as the scan answers.
562
+ if (discovery === undefined || discovery.state !== 'done' || discovery.candidates.length === 0) {
563
+ void this.refreshPicker()
564
+ }
565
+ }
566
+
567
+ closePicker(): void {
568
+ if (this.snapshot.picker === undefined) return
569
+ this.set({ picker: undefined })
570
+ }
571
+
572
+ /** Highlight one row (the footer path field follows it). */
573
+ choosePick(path: string): void {
574
+ const picker = this.snapshot.picker
575
+ if (picker === undefined) return
576
+ this.set({ picker: { ...picker, chosen: path } })
577
+ }
578
+
579
+ /** Re-run discovery from inside the picker, then re-list what it found. */
580
+ async refreshPicker(): Promise<void> {
581
+ const picker = this.snapshot.picker
582
+ if (picker === undefined) return
583
+ this.set({ picker: { ...picker, refreshing: true } })
584
+ try {
585
+ await this.transport.discover(picker.tool)
586
+ } catch (error) {
587
+ this.toast('warn', messageOf(error))
588
+ }
589
+ await this.refresh()
590
+ const current = this.snapshot.picker
591
+ if (current === undefined || current.tool !== picker.tool) return
592
+ this.set({
593
+ picker: {
594
+ ...current,
595
+ candidates: this.snapshot.status?.[picker.tool].discovery.candidates ?? current.candidates,
596
+ refreshing: false,
597
+ },
598
+ })
599
+ }
600
+
601
+ /** Take the highlighted row into the card's input and close the picker. */
602
+ confirmPick(): void {
603
+ const picker = this.snapshot.picker
604
+ if (picker === undefined || picker.chosen === undefined) return
605
+ this.setDraft(picker.tool, picker.chosen)
606
+ this.set({ picker: undefined })
607
+ }
608
+
609
+ /** The picker's "Open Native OS Picker" link: the real dialog decides. */
610
+ async nativePick(): Promise<void> {
611
+ const picker = this.snapshot.picker
612
+ if (picker === undefined || picker.nativePending) return
613
+ this.set({ picker: { ...picker, nativePending: true } })
614
+ const picked = await this.browse(picker.tool)
615
+ const current = this.snapshot.picker
616
+ if (current === undefined) return
617
+ this.set({ picker: picked === undefined ? { ...current, nativePending: false } : undefined })
618
+ }
619
+
620
+ /**
621
+ * Type a path without persisting it, and ask the Host whether it is usable.
622
+ *
623
+ * The verdict is not cosmetic: the wizard's primary button is enabled only
624
+ * when a tool is configured or one input has been verified, so this check is
625
+ * what keeps "greyed out" honest instead of guessing from the text.
626
+ */
627
+ setDraft(tool: ToolchainId, value: string): void {
628
+ this.set({ drafts: this.withDraft(tool, value) })
629
+ this.scheduleCheck(tool, value)
630
+ }
631
+
632
+ /** Debounce a validity check for the text that just changed. */
633
+ private scheduleCheck(tool: ToolchainId, value: string): void {
634
+ const pending = this.checkTimers.get(tool)
635
+ if (pending !== undefined) {
636
+ clearTimeout(pending)
637
+ this.checkTimers.delete(tool)
638
+ }
639
+ const text = value.trim()
640
+ if (text === '') {
641
+ this.patchCheck(tool, undefined)
642
+ return
643
+ }
644
+ // Text that still spells the stored root needs no round trip: the Host has
645
+ // already validated it, and a poll may not have landed yet.
646
+ const root = this.roots[tool]
647
+ if (root !== '' && text === root) {
648
+ this.patchCheck(tool, { state: 'valid', installPath: root })
649
+ return
650
+ }
651
+ const known = this.knownVersion(tool, text)
652
+ if (known !== undefined) {
653
+ this.patchCheck(tool, { state: 'valid', version: known })
654
+ return
655
+ }
656
+ this.patchCheck(tool, { state: 'pending' })
657
+ const timer = setTimeout(() => {
658
+ this.checkTimers.delete(tool)
659
+ void this.runCheck(tool, text)
660
+ }, CHECK_MS)
661
+ this.checkTimers.set(tool, timer)
662
+ }
663
+
664
+ /** A discovered, already-validated executable: no process needs to run again. */
665
+ private knownVersion(tool: ToolchainId, text: string): string | undefined {
666
+ const candidates = this.snapshot.status?.[tool].discovery.candidates ?? []
667
+ const match = candidates.find(candidate => candidate.valid && candidate.path === text)
668
+ return match?.version ?? (match === undefined ? undefined : '?')
669
+ }
670
+
671
+ /** Ask the Host about one path and record the verdict if it is still current. */
672
+ private async runCheck(tool: ToolchainId, text: string): Promise<void> {
673
+ if (this.stopped) return
674
+ const seq = (this.checkSeq.get(tool) ?? 0) + 1
675
+ this.checkSeq.set(tool, seq)
676
+ let outcome: ValidationOutcome
677
+ try {
678
+ outcome = await this.transport.validate(tool, text)
679
+ } catch (error) {
680
+ outcome = { ok: false, error: messageOf(error) }
681
+ }
682
+ if (this.stopped || this.checkSeq.get(tool) !== seq) return
683
+ // The input moved on while the answer was in flight: this verdict is stale.
684
+ if (this.snapshot.drafts[tool].trim() !== text) return
685
+ this.patchCheck(tool, outcome.ok
686
+ ? { state: 'valid', ...(outcome.installPath === undefined ? {} : { installPath: outcome.installPath }), ...(outcome.version === undefined ? {} : { version: outcome.version }) }
687
+ : { state: 'invalid', ...(outcome.error === undefined ? {} : { error: outcome.error }) })
688
+ }
689
+
690
+ /** Replace (or drop, with `undefined`) one tool's verdict. */
691
+ private patchCheck(tool: ToolchainId, check: DraftCheck | undefined): void {
692
+ const next = { ...this.snapshot.checks }
693
+ if (check === undefined) delete next[tool]
694
+ else next[tool] = check
695
+ this.set({ checks: next })
696
+ }
697
+
698
+ /**
699
+ * Show the success badge for a write the Host accepted, then retract it.
700
+ *
701
+ * The badge replaces the verdict line, so the card stops shouting the full
702
+ * executable path (or "not saved") about a path that is in fact saved.
703
+ */
704
+ private confirm(tool: ToolchainId, version: string | undefined): void {
705
+ this.clearConfirm(tool)
706
+ this.set({
707
+ confirmed: {
708
+ ...this.snapshot.confirmed,
709
+ [tool]: { at: Date.now(), ...(version === undefined ? {} : { version }) },
710
+ },
711
+ })
712
+ const timer = setTimeout(() => {
713
+ this.confirmTimers.delete(tool)
714
+ this.clearConfirm(tool)
715
+ }, CONFIRM_MS)
716
+ this.confirmTimers.set(tool, timer)
717
+ }
718
+
719
+ private clearConfirm(tool: ToolchainId): void {
720
+ const timer = this.confirmTimers.get(tool)
721
+ if (timer !== undefined) {
722
+ clearTimeout(timer)
723
+ this.confirmTimers.delete(tool)
724
+ }
725
+ if (this.snapshot.confirmed[tool] === undefined) return
726
+ const next = { ...this.snapshot.confirmed }
727
+ delete next[tool]
728
+ this.set({ confirmed: next })
729
+ }
730
+
731
+ /** Validate and persist one path through the Host (§6.3). */
732
+ async save(tool: ToolchainId, path: string, source: ToolSource = 'manual'): Promise<ValidationOutcome> {
733
+ const name = tool === 'kicad' ? 'KiCad' : 'SolidCraft'
734
+ this.set({ saving: tool })
735
+ this.clearConfirm(tool)
736
+ try {
737
+ const outcome = await this.transport.save(tool, path, source)
738
+ if (outcome.ok) {
739
+ // The Host stores the *root* it resolved, which is rarely what the user
740
+ // typed (an executable path, a `bin` directory). Adopting that root here
741
+ // is what ends the "not saved" state: the input then shows what is saved,
742
+ // and the verdict stops being a false alarm.
743
+ const accepted = outcome.installPath ?? path.trim()
744
+ this.roots[tool] = accepted
745
+ const draft = this.snapshot.drafts[tool]
746
+ if (draft.trim() !== accepted) this.set({ drafts: this.withDraft(tool, accepted) })
747
+ this.patchCheck(tool, {
748
+ state: 'valid', installPath: accepted,
749
+ ...(outcome.version === undefined ? {} : { version: outcome.version }),
750
+ })
751
+ this.confirm(tool, outcome.version)
752
+ this.toast('ok', COPY.toolchain.toastSaved(name, outcome.version ?? '?'))
753
+ } else {
754
+ this.patchCheck(tool, { state: 'invalid', ...(outcome.error === undefined ? {} : { error: outcome.error }) })
755
+ this.toast('warn', COPY.toolchain.toastInvalid(name, outcome.error ?? COPY.toolchain.notDetected))
756
+ }
757
+ await this.refresh()
758
+ return outcome
759
+ } catch (error) {
760
+ this.toast('error', messageOf(error))
761
+ return { ok: false, error: messageOf(error) }
762
+ } finally {
763
+ this.set({ saving: undefined })
764
+ }
765
+ }
766
+
767
+ /** Check a path without persisting anything (the input's own verdict). */
768
+ async validate(tool: ToolchainId, path: string): Promise<ValidationOutcome> {
769
+ try {
770
+ return await this.transport.validate(tool, path)
771
+ } catch (error) {
772
+ return { ok: false, error: messageOf(error) }
773
+ }
774
+ }
775
+
776
+ /** Re-run discovery on demand (the card's "check again"). */
777
+ async discover(tool?: ToolchainId): Promise<void> {
778
+ try {
779
+ await this.transport.discover(tool)
780
+ } catch (error) {
781
+ this.toast('warn', messageOf(error))
782
+ }
783
+ await this.refresh()
784
+ }
785
+
786
+ /** Adopt a discovered candidate into that card's input (§4.3). */
787
+ adopt(tool: ToolchainId, path: string): void {
788
+ this.setDraft(tool, path)
789
+ }
790
+ }