@huaqiu/dsh-hardware-ui 0.7.13 → 0.7.14

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.
@@ -1,7 +1,14 @@
1
1
  /**
2
- * Hardware Engineering UI components. All state reaches them through the
3
- * standard slot props (`useStore`, `actions`) and one injected hook bundle;
4
- * nothing here imports Node APIs or reaches into another plugin's singleton.
2
+ * Hardware Engineering UI components.
3
+ *
4
+ * Props come from three declared sources and nothing else:
5
+ * - the slot store seat (`useStore`, `actions`),
6
+ * - the registrant's inject face (the {@link HardwareController} members,
7
+ * delivered verbatim — never through a `hooks` compartment),
8
+ * - the framework standard kit (`sessionId`, `useSessions`, `useTabInfo`).
9
+ *
10
+ * Importing nothing from Node keeps the client bundle loadable by the DSH
11
+ * ModuleLoader; every host read goes through `./transport.ts`.
5
12
  */
6
13
  import {
7
14
  createElement, useEffect, useMemo, useState, useSyncExternalStore,
@@ -9,79 +16,149 @@ import {
9
16
  } from 'react'
10
17
  import {
11
18
  applicationFor, DESTINATIONS, DESTINATION_LABELS,
12
- type HardwareActions, type HardwareArtifactInfo, type HardwareDestination,
13
- type HardwareInjected, type HardwareInstallationConfig, type HardwareState,
19
+ type ConfigFormLike, type HardwareActions, type HardwareArtifactInfo, type HardwareController,
20
+ type HardwareDestination, type HardwareInstallationConfig, type HardwareState,
21
+ type ViewerNavigationParams,
14
22
  } from './model.js'
15
23
  import { HardwarePreview } from './preview.js'
24
+ import { OnboardingWizard } from './wizard.js'
25
+ import {
26
+ buttonStyle, C, cardStyle, disabled, DOT_COLORS, dotStyle, INPUT, MUTED, MONO, MONO_TEXT,
27
+ pillStyle, R, SECTION_TITLE,
28
+ } from './theme.js'
16
29
 
17
30
  type UseStore = <S>(selector: (state: HardwareState) => S) => S
18
31
 
19
- interface SlotProps {
32
+ /** Tab information the `sidebar.right.pane.tab` seat supplies as `useTabInfo`. */
33
+ export interface TabInfo {
34
+ readonly tab: {
35
+ readonly id: string
36
+ readonly navigation: {
37
+ readonly params?: Readonly<Record<string, unknown>>
38
+ readonly revision?: number
39
+ }
40
+ readonly signal?: AbortSignal
41
+ readonly visible?: boolean
42
+ }
43
+ }
44
+
45
+ export interface SlotProps {
20
46
  readonly useStore: UseStore
21
47
  readonly actions: HardwareActions
22
- readonly hooks: HardwareInjected
48
+ /** Slot-delivered hook; absent only in non-DSH test harnesses. */
49
+ readonly useTabInfo?: () => TabInfo
50
+ readonly sessionId?: string
51
+ readonly useSessions?: (selector: (state: {
52
+ readonly ids: readonly string[]
53
+ readonly byId: Readonly<Record<string, { readonly cwd?: string }>>
54
+ }) => string | undefined) => string | undefined
23
55
  readonly t?: (key: string) => string
24
56
  }
25
57
 
26
- const ROW: CSSProperties = { display: 'flex', alignItems: 'center', gap: 4, flexWrap: 'wrap' }
27
- const NAV: CSSProperties = { ...ROW, minWidth: 0, fontSize: 12 }
28
- const TAB: CSSProperties = {
29
- border: '1px solid var(--dsw-alias-border-default, rgba(127,127,127,0.3))',
30
- borderRadius: 6, background: 'transparent', color: 'var(--dsw-alias-label-secondary)',
31
- padding: '3px 8px', cursor: 'pointer', font: 'inherit', whiteSpace: 'nowrap',
58
+ /** Full component props: slot props plus the controller's verbatim members. */
59
+ export type HardwareProps = SlotProps & HardwareController
60
+
61
+ const EMPTY_TAB: TabInfo = { tab: { id: '', navigation: {} } }
62
+ const useEmptyTab = (): TabInfo => EMPTY_TAB
63
+
64
+ const ROW: CSSProperties = { display: 'flex', alignItems: 'center', gap: 4, flexWrap: 'wrap', minWidth: 0 }
65
+
66
+ const NAV: CSSProperties = {
67
+ display: 'flex', alignItems: 'center', gap: 3, minWidth: 0, fontSize: 12,
68
+ position: 'relative', flexWrap: 'nowrap',
69
+ }
70
+ const NAV_ITEM: CSSProperties = {
71
+ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 8px', borderRadius: R.md,
72
+ border: '1px solid transparent', background: 'transparent', color: C.text2,
73
+ cursor: 'pointer', font: 'inherit', fontSize: 11.5, whiteSpace: 'nowrap', flex: '0 0 auto',
74
+ transition: 'background 120ms ease, color 120ms ease, border-color 120ms ease',
75
+ }
76
+ const NAV_ITEM_ACTIVE: CSSProperties = {
77
+ ...NAV_ITEM,
78
+ color: C.text,
79
+ background: C.card,
80
+ border: `1px solid ${C.border}`,
32
81
  }
33
- const ACTIVE: CSSProperties = {
34
- ...TAB, color: 'var(--dsw-alias-label-primary)', borderColor: 'var(--dsw-alias-brand-primary, currentColor)',
35
- background: 'color-mix(in srgb, var(--dsw-alias-brand-primary, currentColor) 10%, transparent)',
82
+ const BRAND: CSSProperties = {
83
+ display: 'flex', alignItems: 'center', gap: 6, paddingRight: 8, flex: '0 0 auto',
84
+ borderRight: `1px solid ${C.border}`, marginRight: 3,
36
85
  }
37
- const PATH: CSSProperties = {
38
- minWidth: 0, maxWidth: 260, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
39
- color: 'var(--dsw-alias-label-tertiary)', fontSize: 11,
86
+ const BRAND_MARK: CSSProperties = {
87
+ width: 19, height: 19, borderRadius: R.sm, display: 'flex', alignItems: 'center', justifyContent: 'center',
88
+ fontSize: 9.5, fontWeight: 700, color: '#fff', background: C.accent,
89
+ boxShadow: '0 2px 8px rgba(225,37,27,0.35)',
40
90
  }
41
- const ROOT: CSSProperties = {
42
- display: 'flex', flexDirection: 'column', height: '100%', minWidth: 0,
43
- boxSizing: 'border-box', padding: 12, gap: 10,
44
- color: 'var(--dsw-alias-label-primary)', overflow: 'auto',
91
+ const BRAND_NAME: CSSProperties = { fontSize: 10.5, fontWeight: 600, whiteSpace: 'nowrap', color: C.text }
92
+ const CHIP: CSSProperties = {
93
+ minWidth: 0, maxWidth: 168, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
94
+ color: C.text3, fontSize: 10, fontFamily: MONO, flex: '0 1 auto',
45
95
  }
46
- const HEADER: CSSProperties = { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }
47
- const TITLE: CSSProperties = { margin: 0, fontSize: 14, fontWeight: 600 }
48
- const BUTTON: CSSProperties = {
49
- ...TAB, padding: '5px 10px', color: 'var(--dsw-alias-label-primary)',
96
+ const PANEL_ROOT: CSSProperties = {
97
+ display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0, minWidth: 0,
98
+ boxSizing: 'border-box', background: C.base, color: C.text,
50
99
  }
51
- const FIELD: CSSProperties = { display: 'flex', flexDirection: 'column', gap: 4, fontSize: 12 }
52
- const INPUT: CSSProperties = {
53
- width: '100%', boxSizing: 'border-box', padding: '6px 8px', borderRadius: 6,
54
- border: '1px solid var(--dsw-alias-border-default, rgba(127,127,127,0.3))',
55
- background: 'transparent', color: 'inherit', font: 'inherit',
100
+ const STRIP: CSSProperties = {
101
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 6,
102
+ padding: '5px 8px', background: C.panel, borderBottom: `1px solid ${C.border}`,
103
+ flex: '0 0 auto', minWidth: 0,
56
104
  }
57
- const MUTED: CSSProperties = { color: 'var(--dsw-alias-label-tertiary)', fontSize: 12, margin: 0 }
58
- const SELECT: CSSProperties = { ...INPUT, cursor: 'pointer' }
105
+ const STRIP_GROUP: CSSProperties = { ...ROW, gap: 2, flexWrap: 'nowrap', overflowX: 'auto', minWidth: 0 }
106
+ const META: CSSProperties = {
107
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8,
108
+ padding: '4px 10px', background: C.base, borderBottom: `1px solid ${C.borderSoft}`,
109
+ flex: '0 0 auto', minWidth: 0, fontSize: 10, color: C.text3,
110
+ }
111
+ const META_PATH: CSSProperties = {
112
+ ...MONO_TEXT, fontSize: 10, color: C.text2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
113
+ minWidth: 0,
114
+ }
115
+ const BODY: CSSProperties = { flex: '1 1 0', minHeight: 0, display: 'flex', flexDirection: 'column', padding: 10, gap: 8 }
59
116
 
60
- function option(value: string, label: string, selected: boolean): ReactNode {
61
- return createElement('option', { key: value, value, selected }, label)
117
+ function option(value: string, label: string): ReactNode {
118
+ return createElement('option', { key: value, value }, label)
62
119
  }
63
120
 
64
- function artworkOptions(artifacts: readonly HardwareArtifactInfo[] | undefined, kind: string): ReactNode[] {
65
- return (artifacts ?? []).filter(artifact => artifact.kind === kind)
66
- .map(artifact => option(artifact.path, artifact.title || artifact.path, false))
121
+ function basename(path: string): string {
122
+ const parts = path.split(/[\\/]/u)
123
+ return parts[parts.length - 1] ?? path
67
124
  }
68
125
 
69
- /** Five persistent destinations in the conversation header's leading seat. */
70
- export function EngineeringNav({
71
- useStore, actions, hooks, useSessions,
72
- }: SlotProps & {
73
- useSessions?: (selector: (state: {
74
- readonly ids: readonly string[]
75
- readonly byId: Readonly<Record<string, { readonly cwd?: string }>>
76
- }) => string | undefined) => string | undefined
77
- }): ReactNode {
126
+ /** Read the viewer navigation params carried by one `openTab` call. */
127
+ export function navigationParams(info: TabInfo | undefined): ViewerNavigationParams | undefined {
128
+ const params = info?.tab.navigation.params
129
+ if (params === undefined || typeof params.destination !== 'string') return undefined
130
+ if (!(DESTINATIONS as readonly string[]).includes(params.destination)) return undefined
131
+ return params as unknown as ViewerNavigationParams
132
+ }
133
+
134
+ /**
135
+ * One product navigation row: brand, the five persistent destinations, and the
136
+ * selected project. The first-run wizard renders from this root-scope seat
137
+ * because it must be able to run before any session exists.
138
+ */
139
+ export function EngineeringNav(props: HardwareProps): ReactNode {
140
+ const { useStore, actions, useSessions, discover, openDestination } = props
78
141
  const active = useStore(state => state.activeDestination)
79
142
  const projectPath = useStore(state => state.projectPath)
143
+ const selected = useStore(state => state.discovery?.selected)
144
+ // The navigation row is a `root` seat, so it has no session of its own; the
145
+ // first listed session stands in for "the workspace this product is showing".
146
+ const sessionId = useSessions?.(state => state.ids[0])
80
147
  const cwd = useSessions?.(state => {
81
148
  const id = state.ids[0]
82
149
  return id === undefined ? undefined : state.byId[id]?.cwd
83
150
  })
84
- useEffect(() => { void hooks.refreshDiscovery(cwd) }, [cwd, hooks])
151
+
152
+ useEffect(() => {
153
+ let live = true
154
+ discover(cwd, undefined, sessionId)
155
+ .then((discovery) => { if (live) actions.setDiscovery(discovery) })
156
+ .catch((error: unknown) => { if (live) actions.setNotice(`Artifact discovery failed: ${String(error)}`) })
157
+ return () => { live = false }
158
+ }, [cwd, sessionId, discover, actions])
159
+
160
+ const projectName = selected?.name ?? (projectPath === undefined ? undefined : basename(projectPath))
161
+
85
162
  return createElement(
86
163
  'div',
87
164
  { style: NAV, 'data-hardware-nav': true },
@@ -89,17 +166,24 @@ export function EngineeringNav({
89
166
  'button',
90
167
  {
91
168
  key: destination, type: 'button',
92
- style: destination === active ? ACTIVE : TAB,
169
+ style: destination === active ? NAV_ITEM_ACTIVE : NAV_ITEM,
93
170
  'aria-pressed': destination === active,
94
171
  'data-destination': destination,
172
+ title: DESTINATION_LABELS[destination],
95
173
  onClick: () => {
96
174
  actions.setActive(destination)
97
- hooks.openDestination(destination)
175
+ openDestination(destination)
98
176
  },
99
177
  },
178
+ createElement('span', { style: dotStyle(DOT_COLORS[destination], 6) }),
100
179
  DESTINATION_LABELS[destination],
101
180
  )),
102
- ...(projectPath === undefined ? [] : [createElement('span', { key: 'path', style: PATH, title: projectPath }, projectPath)]),
181
+ ...(projectName === undefined
182
+ ? []
183
+ : [createElement('span', {
184
+ key: 'project', style: { ...CHIP, paddingLeft: 4 }, title: projectPath ?? projectName,
185
+ }, projectName)]),
186
+ createElement(OnboardingWizard, props),
103
187
  )
104
188
  }
105
189
 
@@ -108,20 +192,19 @@ export function selectedArtifact(state: HardwareState, destination: HardwareDest
108
192
  const project = state.discovery?.selected
109
193
  const schematic: HardwareArtifactInfo | undefined = state.schematicPath === undefined
110
194
  ? project?.schematic
111
- : { id: `schematic:${state.schematicPath}`, kind: 'schematic', path: state.schematicPath, title: state.schematicPath.split(/[\\/]/u).pop() ?? state.schematicPath }
195
+ : { id: `schematic:${state.schematicPath}`, kind: 'schematic', path: state.schematicPath, title: basename(state.schematicPath) }
112
196
  const board: HardwareArtifactInfo | undefined = state.pcbPath === undefined
113
197
  ? project?.boards?.find(candidate => candidate.path === project?.defaultBoard) ?? project?.boards?.[0]
114
- : { id: `pcb:${state.pcbPath}`, kind: 'pcb', path: state.pcbPath, title: state.pcbPath.split(/[\\/]/u).pop() ?? state.pcbPath }
198
+ : { id: `pcb:${state.pcbPath}`, kind: 'pcb', path: state.pcbPath, title: basename(state.pcbPath) }
115
199
  if (destination === 'schematic' || destination === 'bom') return schematic
116
- if (destination === 'pcb' || destination === '3d') return board
117
200
  return board
118
201
  }
119
202
 
120
203
  function missingReason(state: HardwareState, destination: HardwareDestination): string | undefined {
121
204
  const discovery = state.discovery
122
205
  if (discovery === undefined) return undefined
123
- if (discovery.issue?.code === 'selection-required' && discovery.projects !== undefined && discovery.projects.length > 1) {
124
- return `${discovery.projects.length} projects found; choose one explicitly.`
206
+ if (discovery.issue?.code === 'selection-required' && (discovery.projects?.length ?? 0) > 1) {
207
+ return `${String(discovery.projects?.length)} hardware projects found; choose one explicitly.`
125
208
  }
126
209
  if (discovery.selected === undefined) return 'No hardware project selected. Open or select a hardware project.'
127
210
  if (destination === 'schematic' || destination === 'bom') {
@@ -136,182 +219,373 @@ function missingReason(state: HardwareState, destination: HardwareDestination):
136
219
  return undefined
137
220
  }
138
221
 
139
- /** Right-panel body: one destination at a time, with explicit selectors. */
140
- export function HardwareViewerBody({
141
- useStore, actions, hooks, tab,
142
- }: SlotProps & {
143
- tab?: {
144
- readonly navigation?: {
145
- readonly params?: Readonly<Record<string, unknown>>
146
- readonly revision?: number
147
- }
148
- }
149
- }): ReactNode {
222
+ /** Native-open affordance for the artifact currently on screen. */
223
+ function nativeAction(
224
+ active: HardwareDestination,
225
+ artifact: HardwareArtifactInfo | undefined,
226
+ configured: boolean,
227
+ notice: (message: string) => void,
228
+ openNative: HardwareController['openNative'],
229
+ ): ReactNode {
230
+ const application = applicationFor(active)
231
+ if (application === undefined) return null
232
+ const canOpen = configured && artifact !== undefined
233
+ return createElement(
234
+ 'button',
235
+ {
236
+ type: 'button',
237
+ style: { ...buttonStyle(canOpen ? 'secondary' : 'quiet'), fontSize: 10.5, padding: '2px 7px', ...disabled(!canOpen) },
238
+ disabled: !canOpen,
239
+ 'data-hardware-native-open': true,
240
+ title: canOpen
241
+ ? `Open ${artifact.path} in KiCad`
242
+ : configured ? 'Select an artifact first' : 'Configure KiCad in Settings → Hardware Engineering',
243
+ onClick: () => {
244
+ if (artifact === undefined) return
245
+ openNative({
246
+ application,
247
+ artifactPath: artifact.path,
248
+ kind: active === '3d' ? 'pcb-3d' : active === 'bom' ? 'bom' : artifact.kind,
249
+ }).catch((error: unknown) => { notice(String(error)) })
250
+ },
251
+ },
252
+ createElement('span', { style: dotStyle(configured ? C.ok : C.text3, 6) }),
253
+ 'Open in KiCad',
254
+ )
255
+ }
256
+
257
+ /** Keyframes the stages reference; rendered once per panel. */
258
+ const PANEL_STYLE = `
259
+ @keyframes dsh-hw-spin { to { transform: rotate(360deg) } }
260
+ `
261
+
262
+ /**
263
+ * Right-panel body: one destination at a time, driven by the tab's navigation
264
+ * params so a navigation with unchanged params still refreshes (the revision
265
+ * changes), and so the viewer never depends on a remount.
266
+ */
267
+ export function HardwareViewerBody(props: HardwareProps): ReactNode {
268
+ const {
269
+ useStore, actions, useTabInfo, sessionId, useSessions, discover, installations,
270
+ openDestination, openNative,
271
+ } = props
272
+ const info = (useTabInfo ?? useEmptyTab)()
273
+ const navigation = info.tab.navigation
274
+ const params = useMemo(() => navigationParams(info), [navigation.params, navigation.revision])
275
+ const navRevision = navigation.revision ?? 0
276
+
150
277
  const active = useStore(state => state.activeDestination)
151
278
  const discovery = useStore(state => state.discovery)
152
279
  const projectPath = useStore(state => state.projectPath)
153
280
  const schematicPath = useStore(state => state.schematicPath)
154
281
  const pcbPath = useStore(state => state.pcbPath)
155
- const notice = useStore(state => state.notice)
156
- const installations = useStore(state => state.installations)
157
- const revision = tab?.navigation?.revision ?? 0
158
- const selectedProject = discovery?.selected
159
-
160
- useEffect(() => { void hooks.fetchInstallations() }, [hooks])
161
-
282
+ const noticeText = useStore(state => state.notice)
283
+ const installed = useStore(state => state.installations)
162
284
  const artifact = useStore(state => selectedArtifact(state, active))
163
285
  const reason = useStore(state => missingReason(state, active))
164
- const application = applicationFor(active)
165
- const kicadConfigured = installations?.kicad?.configured ?? false
166
- const nativeLabel = application === 'kicad' ? 'Open in KiCad' : 'No native action'
167
- const canOpenNative = application !== undefined && kicadConfigured && artifact !== undefined && active !== 'order'
286
+ const workspaceRoot = useStore(state => state.workspaceRoot)
287
+ const cwd = useSessions?.(state => {
288
+ if (sessionId === undefined) return undefined
289
+ return state.byId[sessionId]?.cwd
290
+ })
291
+
292
+ // Adopt the navigation, then refresh discovery without clobbering it.
293
+ useEffect(() => {
294
+ if (params !== undefined) actions.applyNavigation(params)
295
+ }, [navRevision, params, actions])
296
+
297
+ useEffect(() => {
298
+ let live = true
299
+ discover(cwd, params?.projectPath, sessionId)
300
+ .then((result) => { if (live) actions.setDiscovery(result, params?.path !== undefined) })
301
+ .catch((error: unknown) => { if (live) actions.setNotice(`Artifact discovery failed: ${String(error)}`) })
302
+ return () => { live = false }
303
+ }, [cwd, sessionId, params?.projectPath, actions, discover])
304
+
305
+ useEffect(() => {
306
+ let live = true
307
+ installations()
308
+ .then((result) => { if (live) actions.setInstallations(result) })
309
+ .catch((error: unknown) => { if (live) actions.setNotice(`Installation check failed: ${String(error)}`) })
310
+ return () => { live = false }
311
+ }, [actions, installations])
312
+
313
+ const selectedProject = discovery?.selected
314
+ const kicadConfigured = installed?.kicad?.configured ?? false
315
+ const notice = (message: string): void => { actions.setNotice(message) }
316
+ const go = (destination: HardwareDestination): void => {
317
+ actions.setActive(destination)
318
+ openDestination(destination, destination === 'schematic' || destination === 'bom' ? schematicPath : pcbPath)
319
+ }
168
320
 
169
- const header = createElement(
321
+ const strip = createElement(
170
322
  'div',
171
- { style: HEADER },
172
- createElement('h2', { style: TITLE }, DESTINATION_LABELS[active]),
173
- ...(application === undefined ? [] : [createElement(
174
- 'button',
175
- {
176
- key: 'native', type: 'button', style: BUTTON, disabled: !canOpenNative,
177
- title: canOpenNative
178
- ? `${nativeLabel}: ${artifact?.path ?? ''}`
179
- : kicadConfigured
180
- ? 'Select an artifact before opening it in KiCad.'
181
- : 'Configure KiCad in Settings → Hardware Engineering.',
182
- 'data-hardware-native-open': true,
183
- onClick: () => { void hooks.openNative(application, artifact?.path).catch(error => actions.setNotice(String(error))) },
184
- },
185
- nativeLabel,
186
- )]),
323
+ { style: STRIP, 'data-hardware-destinations': true },
324
+ createElement(
325
+ 'div',
326
+ { style: STRIP_GROUP },
327
+ ...DESTINATIONS.map(destination => createElement(
328
+ 'button',
329
+ {
330
+ key: destination, type: 'button',
331
+ style: destination === active ? { ...NAV_ITEM_ACTIVE, fontSize: 11 } : { ...NAV_ITEM, fontSize: 11 },
332
+ 'aria-pressed': destination === active,
333
+ onClick: () => { go(destination) },
334
+ },
335
+ createElement('span', { style: dotStyle(DOT_COLORS[destination], 6) }),
336
+ DESTINATION_LABELS[destination],
337
+ )),
338
+ ),
339
+ nativeAction(active, artifact, kicadConfigured, notice, openNative),
340
+ )
341
+
342
+ const meta = createElement(
343
+ 'div',
344
+ { style: META },
345
+ createElement('span', { style: META_PATH, title: artifact?.path ?? '' },
346
+ artifact === undefined ? 'no artifact selected' : artifact.path),
347
+ createElement(
348
+ 'span',
349
+ { style: { display: 'flex', alignItems: 'center', gap: 4, flex: '0 0 auto' } },
350
+ ...(selectedProject === undefined ? [] : [createElement('span', { key: 'project', style: pillStyle('muted') }, selectedProject.name)]),
351
+ ...(kicadConfigured
352
+ ? [createElement('span', { key: 'kicad', style: pillStyle('ok') }, `KiCad ${installed?.kicad?.version ?? ''}`.trim())]
353
+ : [createElement('span', { key: 'kicad', style: pillStyle('warn'), title: installed?.kicad?.error ?? '' }, 'KiCad missing')]),
354
+ ),
187
355
  )
188
356
 
189
357
  const selectors: ReactNode[] = []
190
- if (discovery !== undefined && (discovery.projects?.length ?? 0) > 0) {
358
+ const selectStyle: CSSProperties = { ...INPUT, width: 'auto', maxWidth: 220, fontSize: 10.5 }
359
+ if ((discovery?.projects?.length ?? 0) > 1 || discovery?.issue?.code === 'selection-required') {
191
360
  selectors.push(createElement(
192
- 'label',
193
- { key: 'project', style: FIELD },
194
- 'Project',
195
- createElement('select', {
196
- style: SELECT, value: projectPath ?? '',
361
+ 'select',
362
+ {
363
+ key: 'project', style: selectStyle, value: projectPath ?? '', 'aria-label': 'Project',
197
364
  onChange: (event: ChangeEvent<HTMLSelectElement>) => {
198
- actions.selectProject(event.currentTarget.value)
199
- void hooks.refreshDiscovery(undefined, event.currentTarget.value)
365
+ const path = event.currentTarget.value
366
+ actions.selectProject(path)
367
+ discover(cwd, path, sessionId)
368
+ .then(result => actions.setDiscovery(result))
369
+ .catch((error: unknown) => actions.setNotice(String(error)))
200
370
  },
201
371
  },
202
- option('', 'Select a project…', projectPath === undefined),
203
- ...(discovery?.projects ?? []).map(project => option(project.path, project.name, project.path === projectPath))),
372
+ option('', 'Select a project…'),
373
+ ...(discovery?.projects ?? []).map(project => option(project.path, project.name)),
204
374
  ))
205
375
  }
206
376
  if ((active === 'schematic' || active === 'bom') && selectedProject !== undefined) {
207
377
  const candidates: HardwareArtifactInfo[] = [selectedProject.schematic, ...(selectedProject.sheets ?? [])]
208
378
  .filter((candidate): candidate is HardwareArtifactInfo => candidate !== undefined)
209
- selectors.push(createElement(
210
- 'label',
211
- { key: 'sheet', style: FIELD },
212
- 'Schematic / sheet',
213
- createElement('select', {
214
- style: SELECT, value: schematicPath ?? '',
215
- onChange: (event: ChangeEvent<HTMLSelectElement>) => {
216
- actions.selectArtifact(event.currentTarget.value, 'schematic')
217
- hooks.openDestination(active, event.currentTarget.value)
379
+ if (candidates.length > 1) {
380
+ selectors.push(createElement(
381
+ 'select',
382
+ {
383
+ key: 'sheet', style: selectStyle, value: schematicPath ?? '', 'aria-label': 'Schematic sheet',
384
+ onChange: (event: ChangeEvent<HTMLSelectElement>) => {
385
+ const path = event.currentTarget.value
386
+ actions.selectArtifact(path, 'schematic')
387
+ openDestination(active, path)
388
+ },
218
389
  },
219
- },
220
- option('', 'Select a schematic…', schematicPath === undefined),
221
- ...candidates.map(candidate => option(candidate.path, candidate.title, false))),
222
- ))
390
+ ...candidates.map(candidate => option(candidate.path, candidate.title)),
391
+ ))
392
+ }
223
393
  }
224
394
  if ((active === 'pcb' || active === '3d' || active === 'order') && selectedProject !== undefined) {
225
- selectors.push(createElement(
226
- 'label',
227
- { key: 'board', style: FIELD },
228
- 'Board',
229
- createElement('select', {
230
- style: SELECT, value: pcbPath ?? '',
231
- onChange: (event: ChangeEvent<HTMLSelectElement>) => {
232
- actions.selectArtifact(event.currentTarget.value, 'pcb')
233
- hooks.openDestination(active, event.currentTarget.value)
395
+ if ((selectedProject.boards?.length ?? 0) > 1) {
396
+ selectors.push(createElement(
397
+ 'select',
398
+ {
399
+ key: 'board', style: selectStyle, value: pcbPath ?? '', 'aria-label': 'Board',
400
+ onChange: (event: ChangeEvent<HTMLSelectElement>) => {
401
+ const path = event.currentTarget.value
402
+ actions.selectArtifact(path, 'pcb')
403
+ openDestination(active, path)
404
+ },
234
405
  },
235
- },
236
- option('', 'Select a board…', pcbPath === undefined),
237
- ...artworkOptions(selectedProject.boards, 'pcb')),
238
- ))
406
+ ...(selectedProject.boards ?? []).map(board => option(board.path, board.title || board.path)),
407
+ ))
408
+ }
239
409
  }
240
410
 
241
- return createElement(
411
+ const banner = createElement(
242
412
  'div',
243
- { style: ROOT, 'data-hardware-destination': active },
244
- header,
245
- ...(notice === undefined ? [] : [createElement('p', { key: 'notice', style: MUTED, role: 'status' }, notice)]),
246
- ...(discovery?.issue === undefined || discovery.issue.code === 'selection-required' && (discovery.projects?.length ?? 0) <= 1
247
- ? []
248
- : [createElement('p', { key: 'issue', style: MUTED, role: 'status' }, discovery.issue.message)]),
249
- createElement('p', { key: 'project-path', style: MUTED },
250
- projectPath === undefined ? 'No canonical KiCad project selected.' : `Project: ${projectPath}`),
413
+ { style: { ...ROW, gap: 6, padding: '0 2px', flex: '0 0 auto' } },
251
414
  ...selectors,
252
- ...(reason === undefined
253
- ? [createElement(HardwarePreview, {
254
- key: `preview:${revision}`,
255
- destination: active,
256
- artifact,
257
- projectPath,
258
- revision: revision,
259
- notice,
260
- })]
261
- : [createElement('p', { key: 'reason', style: MUTED, role: 'status', 'data-hardware-state': 'missing' }, reason)]),
262
- ...(application === undefined || kicadConfigured ? [] : [createElement('p', {
263
- key: 'unconfigured', style: MUTED,
264
- }, 'Configure KiCad in Settings → Hardware Engineering to enable previews and native open.')]),
265
- ...(artifact === undefined || reason !== undefined ? [] : [createElement('p', {
266
- key: 'identity', style: MUTED, 'data-hardware-identity': true,
267
- }, `Selected: ${artifact.path}`)]),
415
+ ...(noticeText === undefined
416
+ ? []
417
+ : [createElement('span', { key: 'notice', role: 'status', style: { ...MUTED, color: C.warn } }, noticeText)]),
418
+ ...(discovery?.issue === undefined || discovery.issue.code === 'selection-required'
419
+ ? []
420
+ : [createElement('span', { key: 'issue', role: 'status', style: MUTED }, discovery.issue.message)]),
421
+ )
422
+
423
+ return createElement(
424
+ 'div',
425
+ { style: PANEL_ROOT, 'data-hardware-destination': active },
426
+ createElement('style', null, PANEL_STYLE),
427
+ strip,
428
+ meta,
429
+ selectors.length === 0 && noticeText === undefined && (discovery?.issue === undefined || discovery.issue.code === 'selection-required')
430
+ ? null
431
+ : createElement('div', { style: { padding: '6px 10px 0' } }, banner),
432
+ createElement(
433
+ 'div',
434
+ { style: { ...BODY, overflow: active === 'order' || active === 'bom' ? 'auto' : 'hidden' } },
435
+ ...(reason === undefined
436
+ ? [createElement(HardwarePreview, {
437
+ key: `preview:${info.tab.id}:${String(navRevision)}:${active}:${artifact?.path ?? ''}`,
438
+ destination: active,
439
+ artifact,
440
+ ...(schematicPath === undefined ? {} : { schematicPath }),
441
+ ...(workspaceRoot === undefined ? {} : { workspaceRoot }),
442
+ ...(sessionId === undefined ? {} : { session: sessionId }),
443
+ revision: navRevision,
444
+ configured: kicadConfigured,
445
+ })]
446
+ : [createElement('div', {
447
+ key: 'reason',
448
+ style: cardStyle({ alignItems: 'center', justifyContent: 'center', flex: '1 1 0', gap: 6 }),
449
+ 'data-hardware-state': 'missing',
450
+ },
451
+ createElement('span', { style: pillStyle('warn') }, 'nothing to show'),
452
+ createElement('p', { role: 'status', style: { ...MUTED, textAlign: 'center', maxWidth: 320 } }, reason))]),
453
+ ),
268
454
  )
269
455
  }
270
456
 
271
- /** Settings section for the two CAD installation roots. */
272
- export function HardwareSettingsSection({ hooks }: { readonly hooks: HardwareInjected }): ReactNode {
273
- const form = hooks.useConfigForm?.()
274
- const emptySnapshot: { value?: HardwareInstallationConfig } = {}
457
+ /** Settings section: the two CAD installation roots, host-validated. */
458
+ export function HardwareSettingsSection(props: HardwareProps): ReactNode {
459
+ const { useStore, actions, configForm, saveInstallation, installations } = props
460
+ const installed = useStore(state => state.installations)
461
+ const form = configForm()
462
+ const empty = useMemo<{ value?: HardwareInstallationConfig }>(() => ({}), [])
275
463
  const snapshot = useSyncExternalStore<{ value?: HardwareInstallationConfig }>(
276
- form?.subscribe.bind(form) ?? (() => () => {}),
277
- form?.getSnapshot.bind(form) ?? (() => emptySnapshot),
278
- form?.getSnapshot.bind(form) ?? (() => emptySnapshot),
464
+ form === undefined ? () => () => {} : listener => form.subscribe(listener),
465
+ form === undefined ? () => empty : () => form.getSnapshot(),
466
+ form === undefined ? () => empty : () => form.getSnapshot(),
279
467
  )
280
- const value = snapshot.value
281
- const [kicadRoot, setKicadRoot] = useState(value?.kicadRoot ?? '')
282
- const [solidcraftRoot, setSolidcraftRoot] = useState(value?.solidcraftRoot ?? '')
468
+ const [kicadRoot, setKicadRoot] = useState(snapshot.value?.kicadRoot ?? '')
469
+ const [solidcraftRoot, setSolidcraftRoot] = useState(snapshot.value?.solidcraftRoot ?? '')
283
470
  const [message, setMessage] = useState('')
471
+ const [busy, setBusy] = useState<'kicad' | 'solidcraft' | undefined>()
472
+
473
+ useEffect(() => { setKicadRoot(snapshot.value?.kicadRoot ?? '') }, [snapshot.value?.kicadRoot])
474
+ useEffect(() => { setSolidcraftRoot(snapshot.value?.solidcraftRoot ?? '') }, [snapshot.value?.solidcraftRoot])
475
+
284
476
  useEffect(() => {
285
- setKicadRoot(value?.kicadRoot ?? '')
286
- setSolidcraftRoot(value?.solidcraftRoot ?? '')
287
- }, [value?.kicadRoot, value?.solidcraftRoot])
477
+ let live = true
478
+ installations()
479
+ .then((result) => { if (live) actions.setInstallations(result) })
480
+ .catch(() => { /* the wizard and viewer surface the same failure */ })
481
+ return () => { live = false }
482
+ }, [actions, installations])
288
483
 
289
484
  const save = async (application: 'kicad' | 'solidcraft', root: string): Promise<void> => {
485
+ setBusy(application)
290
486
  try {
291
- await hooks.saveInstallation(application, root)
292
- await hooks.fetchInstallations()
293
- setMessage(`${application === 'kicad' ? 'KiCad' : 'SolidCraft'} installation saved and validated.`)
487
+ await saveInstallation(application, root)
488
+ const refreshed = await installations()
489
+ actions.setInstallations(refreshed)
490
+ const state = application === 'kicad' ? refreshed.kicad : refreshed.solidcraft
491
+ setMessage(state?.configured === true
492
+ ? `${application === 'kicad' ? 'KiCad' : 'SolidCraft'} validated and saved.`
493
+ : `${application === 'kicad' ? 'KiCad' : 'SolidCraft'} saved, but validation failed: ${state?.error ?? 'not detected'}`)
294
494
  } catch (error) {
295
495
  setMessage(String(error))
496
+ } finally {
497
+ setBusy(undefined)
296
498
  }
297
499
  }
298
500
 
299
- return createElement(
501
+ const kicad = installed?.kicad
502
+ const solidcraft = installed?.solidcraft
503
+
504
+ const installationCard = (input: {
505
+ key: 'kicad' | 'solidcraft'
506
+ letter: string
507
+ color: string
508
+ title: string
509
+ blurb: string
510
+ value: string
511
+ placeholder: string
512
+ ok: boolean
513
+ status: string
514
+ detail?: string
515
+ onChange: (value: string) => void
516
+ }): ReactNode => createElement(
300
517
  'div',
301
- { style: { ...ROOT, height: 'auto' }, 'data-hardware-settings': true },
302
- createElement('h2', { style: TITLE }, 'Hardware Engineering'),
303
- createElement('label', { style: FIELD }, 'KiCad installation root or kicad-cli path',
304
- createElement('input', { style: INPUT, value: kicadRoot, onChange: event => setKicadRoot(event.currentTarget.value) }),
518
+ { key: input.key, style: cardStyle() },
519
+ createElement(
520
+ 'div',
521
+ { style: { ...ROW, justifyContent: 'space-between', gap: 8 } },
522
+ createElement(
523
+ 'div',
524
+ { style: { ...ROW, gap: 7 } },
525
+ createElement('span', {
526
+ style: {
527
+ width: 22, height: 22, borderRadius: R.sm, display: 'flex', alignItems: 'center',
528
+ justifyContent: 'center', fontSize: 10, fontWeight: 700, fontFamily: MONO,
529
+ color: input.color, background: `color-mix(in srgb, ${input.color} 18%, transparent)`,
530
+ border: `1px solid color-mix(in srgb, ${input.color} 40%, transparent)`,
531
+ },
532
+ }, input.letter),
533
+ createElement('span', { style: { fontSize: 12, fontWeight: 600 } }, input.title),
534
+ ),
535
+ createElement('span', { style: pillStyle(input.ok ? 'ok' : 'warn') }, input.status),
305
536
  ),
306
- createElement('button', { type: 'button', style: BUTTON, onClick: () => { void save('kicad', kicadRoot) } }, 'Validate / Save KiCad'),
307
- createElement('p', { style: MUTED },
308
- 'Used for PCB GLB export, native artifact opening, and the agent environment context.'),
309
- createElement('label', { style: FIELD }, 'SolidCraft installation root or executable path',
310
- createElement('input', { style: INPUT, value: solidcraftRoot, onChange: event => setSolidcraftRoot(event.currentTarget.value) }),
537
+ createElement('p', { style: MUTED }, input.blurb),
538
+ createElement('input', {
539
+ style: INPUT, value: input.value, placeholder: input.placeholder, spellCheck: false,
540
+ 'aria-label': `${input.title} path`,
541
+ onChange: (event: ChangeEvent<HTMLInputElement>) => input.onChange(event.currentTarget.value),
542
+ }),
543
+ createElement(
544
+ 'div',
545
+ { style: { ...ROW, justifyContent: 'space-between' } },
546
+ createElement('button', {
547
+ type: 'button', style: { ...buttonStyle('secondary'), ...disabled(busy !== undefined) },
548
+ disabled: busy !== undefined,
549
+ onClick: () => { void save(input.key, input.value) },
550
+ }, busy === input.key ? 'Validating…' : 'Validate / save'),
551
+ input.detail === undefined
552
+ ? null
553
+ : createElement('span', { style: { ...MUTED, ...MONO_TEXT, fontSize: 10, maxWidth: 240, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, input.detail),
311
554
  ),
312
- createElement('button', { type: 'button', style: BUTTON, onClick: () => { void save('solidcraft', solidcraftRoot) } }, 'Validate / Save SolidCraft'),
555
+ )
556
+
557
+ return createElement(
558
+ 'div',
559
+ { style: { display: 'flex', flexDirection: 'column', gap: 10 }, 'data-hardware-settings': true },
560
+ createElement('h2', { style: { margin: 0, fontSize: 15, fontWeight: 600 } }, 'Hardware Engineering'),
313
561
  createElement('p', { style: MUTED },
314
- 'SolidCraft is agent environment context only in this POC; it has no native open action.'),
315
- ...(message === '' ? [] : [createElement('p', { style: MUTED, role: 'status' }, message)]),
562
+ 'Local EDA and MCAD executables used for previews, fabrication packaging, one-click native open, and the agent environment context.'),
563
+ installationCard({
564
+ key: 'kicad',
565
+ letter: 'Ki',
566
+ color: C.info,
567
+ title: 'KiCad EDA suite',
568
+ blurb: 'Accepts a KiCad installation root or a kicad-cli path. Drives .kicad_sch / .kicad_pcb preview, GLB export, BOM, gerber packaging and native open.',
569
+ value: kicadRoot,
570
+ placeholder: 'C:\\Program Files\\KiCad\\8.0\\ or /usr/bin/kicad-cli',
571
+ ok: kicad?.configured === true,
572
+ status: kicad?.configured ? `v${kicad.version ?? '?'}` : 'not configured',
573
+ ...(kicad?.cli === undefined ? {} : { detail: kicad.cli }),
574
+ onChange: setKicadRoot,
575
+ }),
576
+ installationCard({
577
+ key: 'solidcraft',
578
+ letter: 'Sc',
579
+ color: C.warn,
580
+ title: 'SolidCraft 3D CAD',
581
+ blurb: 'Agent environment context only in this POC. No native launch and no mechanical preview; the 3D destination renders the selected PCB.',
582
+ value: solidcraftRoot,
583
+ placeholder: 'C:\\Program Files\\SolidCraft\\bin\\SolidCraft.exe',
584
+ ok: solidcraft?.configured === true,
585
+ status: solidcraft?.configured ? 'configured' : 'not configured',
586
+ ...(solidcraft?.executable === undefined ? {} : { detail: solidcraft.executable }),
587
+ onChange: setSolidcraftRoot,
588
+ }),
589
+ ...(message === '' ? [] : [createElement('p', { role: 'status', style: { ...MUTED, color: C.text2 } }, message)]),
316
590
  )
317
591
  }