@huaqiu/dsh-hardware-ui 0.7.18 → 0.7.19

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,620 @@
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
+ /** Verdict of a validate / save round trip. */
124
+ export interface ValidationOutcome {
125
+ readonly ok: boolean
126
+ readonly installPath?: string
127
+ readonly cliPath?: string
128
+ readonly appPath?: string
129
+ readonly version?: string
130
+ readonly error?: string
131
+ }
132
+
133
+ /** Result of a native browse request (§6.2). */
134
+ export interface BrowseOutcome {
135
+ readonly kind: 'picked' | 'cancelled' | 'unsupported'
136
+ readonly path?: string
137
+ readonly mechanism?: string
138
+ readonly message?: string
139
+ }
140
+
141
+ /** Tone of one transient notice (§11 — never a modal for an ordinary failure). */
142
+ export type ToastTone = 'ok' | 'warn' | 'error' | 'info'
143
+
144
+ export interface ToastItem {
145
+ readonly id: number
146
+ readonly tone: ToastTone
147
+ readonly text: string
148
+ }
149
+
150
+ /** Immutable render state; identity changes only when something changed. */
151
+ export interface ToolchainSnapshot {
152
+ readonly status?: ToolchainStatus
153
+ readonly loading: boolean
154
+ readonly error?: string
155
+ /** Tool whose save round trip is in flight, for per-card button state. */
156
+ readonly saving?: ToolchainId
157
+ /**
158
+ * Install jobs by tool. Keyed by tool, not "the current job": both tools can
159
+ * download at the same time, and each card owns its own bar.
160
+ */
161
+ readonly jobs: Readonly<Partial<Record<ToolchainId, InstallJob>>>
162
+ /** Path currently held in each card's input, kept here so both surfaces agree. */
163
+ readonly drafts: Readonly<Record<ToolchainId, string>>
164
+ readonly toasts: readonly ToastItem[]
165
+ /** Open executable picker (Browse), if any. */
166
+ readonly picker?: ToolchainPicker
167
+ }
168
+
169
+ /** The Host calls the controller needs; injectable so tests need no HTTP. */
170
+ export interface ToolchainTransport {
171
+ status(jobIds?: readonly string[]): Promise<ToolchainStatus>
172
+ validate(tool: ToolchainId, path: string): Promise<ValidationOutcome>
173
+ save(tool: ToolchainId, path: string, source: ToolSource): Promise<ValidationOutcome>
174
+ browse(tool: ToolchainId): Promise<BrowseOutcome>
175
+ install(tool: ToolchainId): Promise<InstallJob | undefined>
176
+ cancel(id: string): Promise<boolean>
177
+ discover(tool?: ToolchainId): Promise<void>
178
+ }
179
+
180
+ /** Real transport: the plugin's own route prefix, via `transport.ts`. */
181
+ export const HOST_TRANSPORT: ToolchainTransport = {
182
+ status: jobIds => loadToolchainStatus(jobIds),
183
+ validate: (tool, path) => validateToolchain(tool, path),
184
+ save: (tool, path, source) => saveToolchain(tool, path, source),
185
+ browse: tool => browseToolchain(tool),
186
+ install: tool => installToolchain(tool),
187
+ cancel: id => cancelToolchain(id),
188
+ discover: tool => startToolchainDiscovery(tool),
189
+ }
190
+
191
+ /** How long one toast stays before it fades on its own. */
192
+ const TOAST_MS = 7000
193
+ /** Poll cadence while a job or a discovery run is live. */
194
+ const POLL_MS = 700
195
+
196
+ const EMPTY_DRAFTS: Readonly<Record<ToolchainId, string>> = { kicad: '', solidcraft: '' }
197
+
198
+ /** Is this job still doing work? */
199
+ export function jobRunning(job: InstallJob | undefined): boolean {
200
+ if (job === undefined) return false
201
+ return job.phase !== 'done' && job.phase !== 'failed' && job.phase !== 'cancelled'
202
+ }
203
+
204
+ /**
205
+ * Merge the jobs a poll returned into the per-tool map.
206
+ *
207
+ * The Host answers only about the ids we asked for, so anything it omits is kept
208
+ * from the previous snapshot — a poll that races the end of a run must not blank
209
+ * the other card's bar. Incoming jobs win for their own tool.
210
+ */
211
+ function collectJobs(
212
+ status: ToolchainStatus,
213
+ previous: Readonly<Partial<Record<ToolchainId, InstallJob>>>,
214
+ ): Readonly<Partial<Record<ToolchainId, InstallJob>>> {
215
+ const incoming = status.jobs ?? (status.job === undefined ? [] : [status.job])
216
+ if (incoming.length === 0) return previous
217
+ const next = { ...previous }
218
+ for (const job of incoming) next[job.tool] = job
219
+ return next
220
+ }
221
+
222
+ /** Whole-percent progress, derived when the Host has no reliable total. */
223
+ export function jobPercent(job: InstallJob | undefined): number | undefined {
224
+ if (job === undefined) return undefined
225
+ if (job.percent !== undefined) return job.percent
226
+ if (job.total === undefined || job.total <= 0) return undefined
227
+ return Math.min(100, Math.round((job.received / job.total) * 100))
228
+ }
229
+
230
+ /** Both tools configured and validated — the condition that ends the nudges. */
231
+ export function setupComplete(status: ToolchainStatus | undefined): boolean {
232
+ return status?.kicad.state === 'configured' && status.solidcraft.state === 'configured'
233
+ }
234
+
235
+ /** True while any tool still needs the user (§10.4 sidebar dot). */
236
+ export function setupIncomplete(status: ToolchainStatus | undefined): boolean {
237
+ if (status === undefined) return false
238
+ return status.kicad.state !== 'configured' || status.solidcraft.state !== 'configured'
239
+ }
240
+
241
+ /** One status line for the sidebar indicator's tooltip. */
242
+ export function setupSummary(status: ToolchainStatus | undefined): string {
243
+ if (status === undefined) return COPY.toolchain.checking
244
+ const kicad = status.kicad.state === 'configured' ? `KiCad v${status.kicad.version ?? '?'}` : COPY.toolchain.kicadMissing
245
+ const solidcraft = status.solidcraft.state === 'configured'
246
+ ? `SolidCraft v${status.solidcraft.version ?? '?'}`
247
+ : COPY.toolchain.solidcraftMissing
248
+ return `${kicad} · ${solidcraft}`
249
+ }
250
+
251
+ type Listener = () => void
252
+
253
+ /**
254
+ * The one toolchain state machine of the browser half.
255
+ *
256
+ * Writes are serialised by the Host (validate/save/install each answer before
257
+ * the next poll), so the controller keeps no queue: it refreshes after every
258
+ * write it issues and lets the poll be the arbiter. Polling stops as soon as
259
+ * nothing is running, which keeps an idle settings panel free of requests.
260
+ */
261
+ export class ToolchainController {
262
+ private snapshot: ToolchainSnapshot = { loading: true, jobs: {}, drafts: EMPTY_DRAFTS, toasts: [] }
263
+ private readonly listeners = new Set<Listener>()
264
+ private toastSeq = 0
265
+ private timer?: ReturnType<typeof setTimeout>
266
+ private readonly timers = new Map<number, ReturnType<typeof setTimeout>>()
267
+ private stopped = false
268
+ private started = false
269
+ /** §11 notices fire once per phase *per tool*, so two downloads cannot mute each other. */
270
+ private readonly phases = new Map<ToolchainId, InstallPhase>()
271
+ /** The job id each tool's card is watching; the poll asks for all of them at once. */
272
+ private readonly watched = new Map<ToolchainId, string>()
273
+
274
+ constructor(
275
+ private readonly transport: ToolchainTransport = HOST_TRANSPORT,
276
+ private readonly pollMs = POLL_MS,
277
+ ) {}
278
+
279
+ subscribe = (listener: Listener): (() => void) => {
280
+ this.listeners.add(listener)
281
+ return () => { this.listeners.delete(listener) }
282
+ }
283
+
284
+ getSnapshot = (): ToolchainSnapshot => this.snapshot
285
+
286
+ private set(patch: Partial<ToolchainSnapshot>): void {
287
+ this.snapshot = { ...this.snapshot, ...patch }
288
+ for (const listener of this.listeners) listener()
289
+ }
290
+
291
+ /**
292
+ * Boot the capability once per client session: read the status, then start
293
+ * discovery in the background (§4.2 — the wizard opens first, discovery
294
+ * answers later). Safe to call twice: the second call is a no-op.
295
+ */
296
+ start(): void {
297
+ if (this.started) return
298
+ this.started = true
299
+ void this.refresh()
300
+ void this.transport.discover().catch(() => { /* discovery failure is a state, not an error */ })
301
+ }
302
+
303
+ /** Stop polling and drop timers (plugin unload). */
304
+ stop(): void {
305
+ this.stopped = true
306
+ if (this.timer !== undefined) clearTimeout(this.timer)
307
+ this.timer = undefined
308
+ for (const timer of this.timers.values()) clearTimeout(timer)
309
+ this.timers.clear()
310
+ this.listeners.clear()
311
+ }
312
+
313
+ /** Read the Host status, asking about every job a card is watching. */
314
+ async refresh(jobIds?: readonly string[]): Promise<void> {
315
+ if (this.stopped) return
316
+ const asked = jobIds ?? [...this.watched.values()]
317
+ try {
318
+ const status = await this.transport.status(asked.length === 0 ? undefined : asked)
319
+ if (this.stopped) return
320
+ // Keep the drafts in step with authoritative paths, but never overwrite
321
+ // text the user is typing: only a changed stored root moves the input.
322
+ let drafts = this.snapshot.drafts
323
+ const kicad = this.syncDraft('kicad', status.kicad.installPath)
324
+ if (kicad !== undefined) drafts = { ...drafts, kicad }
325
+ const solidcraft = this.syncDraft('solidcraft', status.solidcraft.installPath)
326
+ if (solidcraft !== undefined) drafts = { ...drafts, solidcraft }
327
+ const jobs = collectJobs(status, this.snapshot.jobs)
328
+ this.set({ status, loading: false, error: undefined, drafts, jobs })
329
+ for (const job of Object.values(jobs)) {
330
+ if (job !== undefined) this.noteJob(job)
331
+ }
332
+ // Stop asking about runs that are over — but only when we actually know
333
+ // that. A poll that arrives before the Host reports a just-started job (or
334
+ // answers nothing about it) must not silently drop the bar it is drawing.
335
+ for (const [tool, id] of this.watched) {
336
+ const seen = jobs[tool]
337
+ if (seen !== undefined && seen.id === id && jobRunning(seen)) continue
338
+ if (seen !== undefined && seen.id !== id && jobRunning(seen)) {
339
+ this.watched.set(tool, seen.id)
340
+ continue
341
+ }
342
+ this.watched.delete(tool)
343
+ }
344
+ this.scheduleIfBusy()
345
+ } catch (error) {
346
+ if (this.stopped) return
347
+ this.set({ loading: false, error: messageOf(error) })
348
+ }
349
+ }
350
+
351
+ /** Last authoritative root seen per tool; the draft follows it, not the other way round. */
352
+ private roots: Record<ToolchainId, string> = { kicad: '', solidcraft: '' }
353
+
354
+ /**
355
+ * Move the input with the authoritative root, unless the user owns the text.
356
+ *
357
+ * The input follows a changed stored root only while it is empty or still shows
358
+ * the previous root. Anything the user typed — or picked in the executable
359
+ * picker — is theirs until they save it, so a poll (or the rescan the picker
360
+ * itself triggers) cannot erase it.
361
+ */
362
+ private syncDraft(tool: ToolchainId, installPath: string | undefined): string | undefined {
363
+ const next = installPath ?? ''
364
+ const previous = this.roots[tool]
365
+ if (next === previous) return undefined
366
+ this.roots[tool] = next
367
+ const draft = this.snapshot.drafts[tool]
368
+ if (draft !== '' && draft !== previous) return undefined
369
+ return next
370
+ }
371
+
372
+ /** One card's input text, with the other tool's text untouched. */
373
+ private withDraft(tool: ToolchainId, value: string): Readonly<Record<ToolchainId, string>> {
374
+ return tool === 'kicad'
375
+ ? { ...this.snapshot.drafts, kicad: value }
376
+ : { ...this.snapshot.drafts, solidcraft: value }
377
+ }
378
+
379
+
380
+ /** Poll again while anything is live; sleep otherwise. */
381
+ private scheduleIfBusy(): void {
382
+ if (this.stopped) return
383
+ if (this.timer !== undefined) clearTimeout(this.timer)
384
+ this.timer = undefined
385
+ const busy = Object.values(this.snapshot.jobs).some(jobRunning)
386
+ || jobRunning(this.snapshot.status?.job)
387
+ || this.snapshot.status?.kicad.discovery.state === 'running'
388
+ || this.snapshot.status?.solidcraft.discovery.state === 'running'
389
+ if (!busy) return
390
+ this.timer = setTimeout(() => {
391
+ this.timer = undefined
392
+ void this.refresh()
393
+ }, this.pollMs)
394
+ }
395
+
396
+ /** One notice, deduplicated by text so a poll cannot spam the overlay. */
397
+ toast(tone: ToastTone, text: string): void {
398
+ if (this.snapshot.toasts.some(item => item.text === text)) return
399
+ this.toastSeq += 1
400
+ const id = this.toastSeq
401
+ this.set({ toasts: [...this.snapshot.toasts, { id, tone, text }].slice(-3) })
402
+ this.timers.set(id, setTimeout(() => {
403
+ this.timers.delete(id)
404
+ this.dismiss(id)
405
+ }, TOAST_MS))
406
+ }
407
+
408
+ /** Drop one notice (the overlay's own close button). */
409
+ dismiss(id: number): void {
410
+ const timer = this.timers.get(id)
411
+ if (timer !== undefined) {
412
+ clearTimeout(timer)
413
+ this.timers.delete(id)
414
+ }
415
+ if (!this.snapshot.toasts.some(item => item.id === id)) return
416
+ this.set({ toasts: this.snapshot.toasts.filter(item => item.id !== id) })
417
+ }
418
+
419
+ /** Fire the transitions §11 allows; nothing else notifies. */
420
+ private noteJob(job: InstallJob): void {
421
+ const previous = this.phases.get(job.tool)
422
+ if (previous === job.phase) return
423
+ this.phases.set(job.tool, job.phase)
424
+ const name = job.tool === 'kicad' ? 'KiCad' : 'SolidCraft'
425
+ if (job.phase === 'verify') this.toast('info', COPY.toolchain.toastDownloaded(name, job.version))
426
+ else if (job.phase === 'extract' || job.phase === 'layout' || job.phase === 'promote') {
427
+ if (previous !== 'extract' && previous !== 'layout' && previous !== 'promote') {
428
+ this.toast('info', COPY.toolchain.toastExtracting(name))
429
+ }
430
+ } else if (job.phase === 'done') {
431
+ this.toast('ok', COPY.toolchain.toastInstalled(name, job.version))
432
+ } else if (job.phase === 'failed') {
433
+ this.toast('error', job.errorCode === 'checksum-mismatch'
434
+ ? COPY.toolchain.toastChecksum(name)
435
+ : COPY.toolchain.toastFailed(name, job.error ?? job.message))
436
+ } else if (job.phase === 'cancelled') {
437
+ this.toast('warn', COPY.toolchain.toastCancelled(name))
438
+ }
439
+ }
440
+
441
+ /** Start the manifest-provided download for one tool (§7.4). */
442
+ async install(tool: ToolchainId): Promise<void> {
443
+ const name = tool === 'kicad' ? 'KiCad' : 'SolidCraft'
444
+ try {
445
+ const job = await this.transport.install(tool)
446
+ if (job === undefined) {
447
+ this.toast('warn', COPY.toolchain.downloadUnavailable(name))
448
+ return
449
+ }
450
+ // Watch this tool's job; the other card keeps watching its own, so two
451
+ // simultaneous downloads both keep a live bar.
452
+ this.watched.set(tool, job.id)
453
+ this.phases.delete(tool)
454
+ // Record it locally even when no status is known yet: the bar has to exist
455
+ // between the `install` answer and the first poll that mentions the job.
456
+ const current = this.snapshot.status
457
+ this.set({
458
+ jobs: { ...this.snapshot.jobs, [tool]: job },
459
+ ...(current === undefined ? {} : { status: { ...current, job } }),
460
+ })
461
+ this.toast('info', COPY.toolchain.toastStarted(name, job.version))
462
+ this.scheduleIfBusy()
463
+ void this.refresh([...this.watched.values()])
464
+ } catch (error) {
465
+ this.toast('warn', COPY.toolchain.downloadUnavailableWith(name, messageOf(error)))
466
+ }
467
+ }
468
+
469
+ /** Stop a running download or extraction. */
470
+ async cancel(id: string): Promise<void> {
471
+ try {
472
+ await this.transport.cancel(id)
473
+ } catch (error) {
474
+ this.toast('error', messageOf(error))
475
+ }
476
+ for (const [tool, jobId] of this.watched) {
477
+ if (jobId === id) this.watched.delete(tool)
478
+ }
479
+ await this.refresh()
480
+ }
481
+
482
+ /** Native chooser; a picked path lands in that card's input, not in config. */
483
+ async browse(tool: ToolchainId): Promise<string | undefined> {
484
+ try {
485
+ const outcome = await this.transport.browse(tool)
486
+ if (outcome.kind === 'picked' && outcome.path !== undefined) {
487
+ this.set({ drafts: this.withDraft(tool, outcome.path) })
488
+ return outcome.path
489
+ }
490
+ if (outcome.kind === 'unsupported') {
491
+ this.toast('warn', COPY.toolchain.browseUnsupported(outcome.message ?? ''))
492
+ }
493
+ return undefined
494
+ } catch (error) {
495
+ this.toast('error', messageOf(error))
496
+ return undefined
497
+ }
498
+ }
499
+
500
+ /** Open the executable picker for one tool (the card's Browse). */
501
+ openPicker(tool: ToolchainId): void {
502
+ const discovery = this.snapshot.status?.[tool].discovery
503
+ this.set({
504
+ picker: {
505
+ tool,
506
+ candidates: discovery?.candidates ?? [],
507
+ nativePending: false,
508
+ refreshing: false,
509
+ },
510
+ })
511
+ // A fresh profile may still be scanning, and an all-invalid list is worth
512
+ // re-checking: the picker opens at once and fills in as the scan answers.
513
+ if (discovery === undefined || discovery.state !== 'done' || discovery.candidates.length === 0) {
514
+ void this.refreshPicker()
515
+ }
516
+ }
517
+
518
+ closePicker(): void {
519
+ if (this.snapshot.picker === undefined) return
520
+ this.set({ picker: undefined })
521
+ }
522
+
523
+ /** Highlight one row (the footer path field follows it). */
524
+ choosePick(path: string): void {
525
+ const picker = this.snapshot.picker
526
+ if (picker === undefined) return
527
+ this.set({ picker: { ...picker, chosen: path } })
528
+ }
529
+
530
+ /** Re-run discovery from inside the picker, then re-list what it found. */
531
+ async refreshPicker(): Promise<void> {
532
+ const picker = this.snapshot.picker
533
+ if (picker === undefined) return
534
+ this.set({ picker: { ...picker, refreshing: true } })
535
+ try {
536
+ await this.transport.discover(picker.tool)
537
+ } catch (error) {
538
+ this.toast('warn', messageOf(error))
539
+ }
540
+ await this.refresh()
541
+ const current = this.snapshot.picker
542
+ if (current === undefined || current.tool !== picker.tool) return
543
+ this.set({
544
+ picker: {
545
+ ...current,
546
+ candidates: this.snapshot.status?.[picker.tool].discovery.candidates ?? current.candidates,
547
+ refreshing: false,
548
+ },
549
+ })
550
+ }
551
+
552
+ /** Take the highlighted row into the card's input and close the picker. */
553
+ confirmPick(): void {
554
+ const picker = this.snapshot.picker
555
+ if (picker === undefined || picker.chosen === undefined) return
556
+ this.setDraft(picker.tool, picker.chosen)
557
+ this.set({ picker: undefined })
558
+ }
559
+
560
+ /** The picker's "Open Native OS Picker" link: the real dialog decides. */
561
+ async nativePick(): Promise<void> {
562
+ const picker = this.snapshot.picker
563
+ if (picker === undefined || picker.nativePending) return
564
+ this.set({ picker: { ...picker, nativePending: true } })
565
+ const picked = await this.browse(picker.tool)
566
+ const current = this.snapshot.picker
567
+ if (current === undefined) return
568
+ this.set({ picker: picked === undefined ? { ...current, nativePending: false } : undefined })
569
+ }
570
+
571
+ /** Type a path without persisting it. */
572
+ setDraft(tool: ToolchainId, value: string): void {
573
+ this.set({ drafts: this.withDraft(tool, value) })
574
+ }
575
+
576
+ /** Validate and persist one path through the Host (§6.3). */
577
+ async save(tool: ToolchainId, path: string, source: ToolSource = 'manual'): Promise<ValidationOutcome> {
578
+ const name = tool === 'kicad' ? 'KiCad' : 'SolidCraft'
579
+ this.set({ saving: tool })
580
+ try {
581
+ const outcome = await this.transport.save(tool, path, source)
582
+ if (outcome.ok) {
583
+ this.toast('ok', COPY.toolchain.toastSaved(name, outcome.version ?? '?'))
584
+ } else {
585
+ this.toast('warn', COPY.toolchain.toastInvalid(name, outcome.error ?? COPY.toolchain.notDetected))
586
+ }
587
+ await this.refresh()
588
+ return outcome
589
+ } catch (error) {
590
+ this.toast('error', messageOf(error))
591
+ return { ok: false, error: messageOf(error) }
592
+ } finally {
593
+ this.set({ saving: undefined })
594
+ }
595
+ }
596
+
597
+ /** Check a path without persisting anything (the input's own verdict). */
598
+ async validate(tool: ToolchainId, path: string): Promise<ValidationOutcome> {
599
+ try {
600
+ return await this.transport.validate(tool, path)
601
+ } catch (error) {
602
+ return { ok: false, error: messageOf(error) }
603
+ }
604
+ }
605
+
606
+ /** Re-run discovery on demand (the card's "check again"). */
607
+ async discover(tool?: ToolchainId): Promise<void> {
608
+ try {
609
+ await this.transport.discover(tool)
610
+ } catch (error) {
611
+ this.toast('warn', messageOf(error))
612
+ }
613
+ await this.refresh()
614
+ }
615
+
616
+ /** Adopt a discovered candidate into that card's input (§4.3). */
617
+ adopt(tool: ToolchainId, path: string): void {
618
+ this.setDraft(tool, path)
619
+ }
620
+ }