From fa1c3dc0ec30ae76aee979b9899c296485fab974 Mon Sep 17 00:00:00 2001 From: SAPHID Date: Sun, 22 Nov 2026 06:06:33 +0000 Subject: [PATCH] feat: inspect schematics, validate circuit paths, and simulate SPICE in an Electronics Workbench --- apps/server/src/auth/RpcAuthorization.ts | 9 + .../src/electronics/ElectronicsEngine.test.ts | 295 ++++ .../electronics/ElectronicsService.test.ts | 90 + .../src/electronics/ElectronicsService.ts | 648 +++++++ apps/server/src/electronics/mnaSolver.ts | 812 +++++++++ apps/server/src/electronics/parsers.ts | 1541 +++++++++++++++++ apps/server/src/electronics/pathTracer.ts | 349 ++++ apps/server/src/electronics/sexpr.ts | 132 ++ apps/server/src/electronics/toolchain.ts | 296 ++++ apps/server/src/electronics/validator.ts | 342 ++++ .../src/mcp/McpElectronicsToolkit.test.ts | 174 ++ apps/server/src/mcp/McpHttpServer.ts | 8 + .../src/mcp/toolkits/electronics/handlers.ts | 192 ++ .../src/mcp/toolkits/electronics/tools.ts | 154 ++ .../src/observability/RpcInstrumentation.ts | 9 + .../src/provider/AgentContextBudget.test.ts | 2 + .../src/provider/agentContextBudget.json | 2 +- apps/server/src/server.ts | 5 +- apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 14 + apps/web/src/closedViewStore.ts | 1 + apps/web/src/components/ChatView.tsx | 3 + apps/web/src/components/RightPanelTabs.tsx | 40 + .../chat/RightPanelSurfaceContent.tsx | 17 + .../components/chat/useRightPanelActions.ts | 6 + .../src/components/electronics/BomPanel.tsx | 106 ++ .../components/electronics/CircuitCanvas.tsx | 685 ++++++++ .../ElectronicsPanel.browser.test.tsx | 279 +++ .../electronics/ElectronicsPanel.tsx | 532 ++++++ .../electronics/ElectronicsSettings.tsx | 192 ++ .../electronics/PathTracerPanel.tsx | 200 +++ .../electronics/SimulationPanel.tsx | 368 ++++ .../electronics/ValidationPanel.tsx | 169 ++ .../components/preview/agentOpenedPreviews.ts | 37 +- .../settings/SettingsSidebarNav.tsx | 2 + .../src/components/settings/settingsSearch.ts | 22 + apps/web/src/i18n/translations/de.json | 124 +- apps/web/src/i18n/translations/en.json | 124 +- apps/web/src/i18n/translations/es.json | 124 +- apps/web/src/i18n/translations/fr.json | 124 +- apps/web/src/i18n/translations/ja.json | 124 +- apps/web/src/i18n/translations/ko.json | 124 +- apps/web/src/i18n/translations/pt-BR.json | 124 +- apps/web/src/i18n/translations/ru.json | 124 +- apps/web/src/i18n/translations/sv.json | 124 +- apps/web/src/i18n/translations/zh.json | 124 +- apps/web/src/rightPanelStore.ts | 4 + apps/web/src/routeTree.gen.ts | 21 + .../src/routes/_chat.settings.electronics.tsx | 6 + apps/web/src/state/electronics.ts | 39 + packages/client-runtime/package.json | 4 + packages/client-runtime/src/rpc/client.ts | 1 + .../client-runtime/src/state/electronics.ts | 51 + packages/contracts/src/electronics.ts | 464 +++++ packages/contracts/src/index.ts | 1 + packages/contracts/src/rpc.ts | 94 + packages/contracts/src/settings.ts | 15 + 57 files changed, 9542 insertions(+), 133 deletions(-) create mode 100644 apps/server/src/electronics/ElectronicsEngine.test.ts create mode 100644 apps/server/src/electronics/ElectronicsService.test.ts create mode 100644 apps/server/src/electronics/ElectronicsService.ts create mode 100644 apps/server/src/electronics/mnaSolver.ts create mode 100644 apps/server/src/electronics/parsers.ts create mode 100644 apps/server/src/electronics/pathTracer.ts create mode 100644 apps/server/src/electronics/sexpr.ts create mode 100644 apps/server/src/electronics/toolchain.ts create mode 100644 apps/server/src/electronics/validator.ts create mode 100644 apps/server/src/mcp/McpElectronicsToolkit.test.ts create mode 100644 apps/server/src/mcp/toolkits/electronics/handlers.ts create mode 100644 apps/server/src/mcp/toolkits/electronics/tools.ts create mode 100644 apps/web/src/components/electronics/BomPanel.tsx create mode 100644 apps/web/src/components/electronics/CircuitCanvas.tsx create mode 100644 apps/web/src/components/electronics/ElectronicsPanel.browser.test.tsx create mode 100644 apps/web/src/components/electronics/ElectronicsPanel.tsx create mode 100644 apps/web/src/components/electronics/ElectronicsSettings.tsx create mode 100644 apps/web/src/components/electronics/PathTracerPanel.tsx create mode 100644 apps/web/src/components/electronics/SimulationPanel.tsx create mode 100644 apps/web/src/components/electronics/ValidationPanel.tsx create mode 100644 apps/web/src/routes/_chat.settings.electronics.tsx create mode 100644 apps/web/src/state/electronics.ts create mode 100644 packages/client-runtime/src/state/electronics.ts create mode 100644 packages/contracts/src/electronics.ts diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index ffe84c428a67a..e733f98e16d5d 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -238,6 +238,15 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.deviceDetail]: AuthOrchestrationReadScope, [WS_METHODS.deviceAction]: AuthOrchestrationOperateScope, [WS_METHODS.subscribeDeviceState]: AuthOrchestrationReadScope, + [WS_METHODS.electronicsListFiles]: AuthFilesystemReadScope, + [WS_METHODS.electronicsInspect]: AuthFilesystemReadScope, + [WS_METHODS.electronicsTracePath]: AuthFilesystemReadScope, + [WS_METHODS.electronicsValidate]: AuthFilesystemReadScope, + [WS_METHODS.electronicsSimulate]: AuthFilesystemReadScope, + [WS_METHODS.electronicsToolchainStatus]: AuthOrchestrationReadScope, + [WS_METHODS.electronicsOpenPanel]: AuthOrchestrationOperateScope, + [WS_METHODS.electronicsClosePanel]: AuthOrchestrationOperateScope, + [WS_METHODS.subscribeElectronicsState]: AuthOrchestrationReadScope, [WS_METHODS.subscribeServerConfig]: AuthOrchestrationReadScope, [WS_METHODS.subscribeServerLifecycle]: AuthOrchestrationReadScope, [WS_METHODS.subscribeAuthAccess]: AuthAccessReadScope, diff --git a/apps/server/src/electronics/ElectronicsEngine.test.ts b/apps/server/src/electronics/ElectronicsEngine.test.ts new file mode 100644 index 0000000000000..9419fed03edf2 --- /dev/null +++ b/apps/server/src/electronics/ElectronicsEngine.test.ts @@ -0,0 +1,295 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { runBuiltinMnaSimulation } from "./mnaSolver.ts"; +import { parseElectronicsFile } from "./parsers.ts"; +import { traceCircuitPath } from "./pathTracer.ts"; +import { assembleValidationReport, runBuiltinCircuitValidation } from "./validator.ts"; + +const SAMPLE_KICAD_SCH = `(kicad_sch + (version 20231120) + (title_block (title "Sensor Power & Divider")) + (lib_symbols + (symbol "Device:R" + (symbol "R_1_1" + (pin passive line (at 0 3.81 270) (length 1.27) (name "~") (number "1")) + (pin passive line (at 0 -3.81 90) (length 1.27) (name "~") (number "2")) + ) + ) + (symbol "Regulator:LDO" + (symbol "LDO_1_1" + (pin power_in line (at -5.08 0 0) (length 2.54) (name "VIN") (number "1")) + (pin power_in line (at 0 -5.08 90) (length 2.54) (name "GND") (number "2")) + (pin power_out line (at 5.08 0 180) (length 2.54) (name "VOUT") (number "3")) + ) + ) + (symbol "power:+5V" + (symbol "+5V_1_1" + (pin power_in line (at 0 0 90) (length 0) (name "+5V") (number "1")) + ) + ) + (symbol "power:GND" + (symbol "GND_1_1" + (pin power_in line (at 0 0 270) (length 0) (name "GND") (number "1")) + ) + ) + ) + (symbol (lib_id "power:+5V") (at 20 30 0) + (property "Reference" "#PWR01") + (property "Value" "+5V") + ) + (symbol (lib_id "power:GND") (at 35 45 0) + (property "Reference" "#PWR02") + (property "Value" "GND") + ) + (symbol (lib_id "Regulator:LDO") (at 35 30 0) + (property "Reference" "U1") + (property "Value" "AMS1117-3.3") + (property "Footprint" "Package_TO_SOT_SMD:SOT-223-3_TabPin2") + ) + (symbol (lib_id "Device:R") (at 60 30 0) + (property "Reference" "R1") + (property "Value" "10k") + (property "Footprint" "Resistor_SMD:R_0603") + ) + (symbol (lib_id "Device:R") (at 60 45 0) + (property "Reference" "R2") + (property "Value" "10k") + (property "Footprint" "Resistor_SMD:R_0603") + ) + (wire (pts (xy 20 30) (xy 29.92 30))) + (wire (pts (xy 35 35.08) (xy 35 45))) + (wire (pts (xy 40.08 30) (xy 60 26.19))) + (wire (pts (xy 60 33.81) (xy 60 41.19))) + (wire (pts (xy 60 48.81) (xy 35 45))) + (label "+3V3" (at 45 28 0)) + (wire (pts (xy 45 28) (xy 40.08 30))) + (label "VSENSE" (at 60 37.5 0)) + (junction (at 60 37.5)) +)`; + +const SAMPLE_KICAD_PCB = `(kicad_pcb + (version 20240108) + (title_block (title "Mini Filter Board")) + (layers + (0 "F.Cu" signal) + (31 "B.Cu" signal) + (44 "Edge.Cuts" user) + ) + (net 0 "") + (net 1 "+5V") + (net 2 "VOUT") + (net 3 "GND") + (gr_rect (start 0 0) (end 40 25) (layer "Edge.Cuts")) + (footprint "Resistor_SMD:R_0603" (layer "F.Cu") (at 10 10 0) + (property "Reference" "R1") + (property "Value" "1k") + (pad "1" smd rect (at -0.8 0) (net 1 "+5V")) + (pad "2" smd rect (at 0.8 0) (net 2 "VOUT")) + ) + (footprint "Capacitor_SMD:C_0603" (layer "F.Cu") (at 20 10 0) + (property "Reference" "C1") + (property "Value" "100n") + (pad "1" smd rect (at -0.8 0) (net 2 "VOUT")) + (pad "2" smd rect (at 0.8 0) (net 3 "GND")) + ) + (segment (start 10.8 10) (end 19.2 10) (width 0.25) (layer "F.Cu") (net 2)) +)`; + +const SAMPLE_SPICE_RC = `* RC Low-Pass Filter & Divider +V1 vin 0 DC 5 AC 1 +R1 vin vout 1k +C1 vout 0 100n +.end +`; + +const SAMPLE_SPICE_DIVIDER = `* 5V Resistive Voltage Divider +V1 vin 0 5 +R1 vin mid 10k +R2 mid 0 10k +.end +`; + +const SAMPLE_CIRCUIT_JSON = JSON.stringify([ + { type: "pcb_board", center: { x: 0, y: 0 }, width: 30, height: 20 }, + { + type: "source_component", + source_component_id: "sc_r1", + name: "R1", + ftype: "simple_resistor", + display_value: "4.7k", + }, + { + type: "source_component", + source_component_id: "sc_r2", + name: "R2", + ftype: "simple_resistor", + display_value: "4.7k", + }, + { + type: "source_port", + source_port_id: "sp_r1_1", + source_component_id: "sc_r1", + name: "pin1", + pin_number: 1, + }, + { + type: "source_port", + source_port_id: "sp_r1_2", + source_component_id: "sc_r1", + name: "pin2", + pin_number: 2, + }, + { + type: "source_port", + source_port_id: "sp_r2_1", + source_component_id: "sc_r2", + name: "pin1", + pin_number: 1, + }, + { + type: "source_port", + source_port_id: "sp_r2_2", + source_component_id: "sc_r2", + name: "pin2", + pin_number: 2, + }, + { type: "source_net", source_net_id: "sn_vcc", name: "+3V3" }, + { type: "source_net", source_net_id: "sn_gnd", name: "GND" }, + { + type: "source_trace", + connected_source_port_ids: ["sp_r1_1"], + connected_source_net_ids: ["sn_vcc"], + display_name: "+3V3", + }, + { + type: "source_trace", + connected_source_port_ids: ["sp_r1_2", "sp_r2_1"], + display_name: "MID", + }, + { + type: "source_trace", + connected_source_port_ids: ["sp_r2_2"], + connected_source_net_ids: ["sn_gnd"], + display_name: "GND", + }, +]); + +describe("Electronics parsers, path tracer, validator, and MNA simulator", () => { + it("parses KiCad schematic connectivity, BOM, and traces multi-hop paths across resistors", () => { + const model = parseElectronicsFile("boards/power.kicad_sch", SAMPLE_KICAD_SCH); + expect(model.format).toBe("kicad_sch"); + expect(model.title).toBe("Sensor Power & Divider"); + expect(model.nets.map((n) => n.name)).toEqual( + expect.arrayContaining(["+5V", "+3V3", "VSENSE", "GND"]), + ); + + // BOM groups R1 and R2 (both 10k 0603) and excludes #PWR symbols + const rBom = model.bom.find((entry) => entry.value === "10k"); + expect(rBom?.quantity).toBe(2); + expect(rBom?.refs).toEqual(["R1", "R2"]); + + // Direct connection U1.VOUT -> R1.1 on +3V3 + const direct = traceCircuitPath(model, { from: "U1.VOUT", to: "R1.1" }); + expect(direct.connected).toBe(true); + expect(direct.directNet).toBe("+3V3"); + expect(direct.estimatedResistanceOhms).toBe(0); + + // Multi-hop connection U1.VOUT -> VSENSE through R1 (10k) + const multi = traceCircuitPath(model, { from: "U1.VOUT", to: "VSENSE" }); + expect(multi.connected).toBe(true); + expect(multi.hops.map((h) => h.name)).toEqual(["+3V3", "R1", "VSENSE"]); + expect(multi.estimatedResistanceOhms).toBe(10_000); + }); + + it("parses KiCad PCB footprints, pads, tracks, and verifies routed vs unrouted nets", () => { + const model = parseElectronicsFile("boards/filter.kicad_pcb", SAMPLE_KICAD_PCB); + expect(model.format).toBe("kicad_pcb"); + expect(model.boardOutline.length).toBe(4); + expect(model.wires.length).toBe(1); + expect(model.components.map((c) => c.ref)).toEqual(["R1", "C1"]); + + // VOUT is routed cleanly between R1.2 and C1.1 + const validation = runBuiltinCircuitValidation(model); + expect(validation.issues.some((i) => i.code === "unrouted_pcb_net")).toBe(false); + + // Break the track -> unrouted_pcb_net warning must trigger! + const brokenPcb = SAMPLE_KICAD_PCB.replace( + '(segment (start 10.8 10) (end 19.2 10) (width 0.25) (layer "F.Cu") (net 2))', + "", + ); + const brokenModel = parseElectronicsFile("boards/filter-broken.kicad_pcb", brokenPcb); + const brokenVal = runBuiltinCircuitValidation(brokenModel); + expect(brokenVal.issues.some((i) => i.code === "unrouted_pcb_net" && i.net === "VOUT")).toBe( + true, + ); + }); + + it("flags power rail shorts, duplicate designators, single-pin nets, and missing decoupling", () => { + const shortedSch = SAMPLE_KICAD_SCH.replace( + "(wire (pts (xy 60 48.81) (xy 35 45)))", + "(wire (pts (xy 60 48.81) (xy 35 45)))\n (wire (pts (xy 20 30) (xy 35 45)))", + ); + const model = parseElectronicsFile("boards/short.kicad_sch", shortedSch); + const { issues } = runBuiltinCircuitValidation(model); + const report = assembleValidationReport({ + model, + builtinIssues: issues, + externalIssues: [], + enginesUsed: ["builtin"], + notes: [], + }); + expect(report.passed).toBe(false); + expect(report.issues.some((i) => i.code === "power_rail_short")).toBe(true); + expect(report.issues.some((i) => i.code === "missing_decoupling")).toBe(true); + }); + + it("parses Circuit JSON and traces multi-hop paths", () => { + const model = parseElectronicsFile("demo.circuit.json", SAMPLE_CIRCUIT_JSON); + expect(model.format).toBe("circuit_json"); + expect(model.components.map((c) => c.ref)).toEqual(["R1", "R2"]); + expect(model.boardOutline.length).toBe(4); + const trace = traceCircuitPath(model, { from: "+3V3", to: "MID" }); + expect(trace.connected).toBe(true); + expect(trace.estimatedResistanceOhms).toBe(4700); + }); + + it("solves DC operating point accurately using built-in MNA solver", () => { + const model = parseElectronicsFile("sim/divider.cir", SAMPLE_SPICE_DIVIDER); + const dc = runBuiltinMnaSimulation(model, { kind: "dc_op", outputNode: "mid" }); + expect(dc.engine).toBe("builtin_mna"); + const mid = dc.nodeVoltages.find((n) => n.node === "mid"); + expect(mid?.voltageV).toBeCloseTo(2.5, 4); + const r1 = dc.componentReadings.find((c) => c.ref === "R1"); + expect(r1?.currentA).toBeCloseTo(0.00025, 6); + expect(r1?.powerW).toBeCloseTo(0.000625, 6); + }); + + it("computes accurate RC low-pass AC Bode sweep (-3 dB cutoff at 1/(2*pi*R*C)) and transient step response", () => { + const model = parseElectronicsFile("sim/rc_filter.cir", SAMPLE_SPICE_RC); + const ac = runBuiltinMnaSimulation(model, { + kind: "ac_sweep", + outputNode: "vout", + startFreqHz: 10, + stopFreqHz: 1_000_000, + pointsPerDecade: 20, + }); + expect(ac.series.length).toBe(1); + const cutoffMetric = ac.metrics.find((m) => m.name === "-3 dB Cutoff"); + // Exact fc = 1 / (2 * pi * 1000 * 100e-9) = 1591.55 Hz + expect(cutoffMetric).toBeDefined(); + expect(cutoffMetric!.value).toBeGreaterThan(1500); + expect(cutoffMetric!.value).toBeLessThan(1680); + + const tran = runBuiltinMnaSimulation(model, { + kind: "transient", + outputNode: "vout", + stopTimeSeconds: 1e-3, + }); + expect(tran.series.length).toBeGreaterThanOrEqual(1); + const outTrace = tran.series.find((s) => s.label === "V(vout)"); + expect(outTrace).toBeDefined(); + const finalV = outTrace!.points[outTrace!.points.length - 1]!.y; + // After 10*tau (tau = 0.1ms), capacitor charges to ~5V + expect(finalV).toBeGreaterThan(4.9); + }); +}); diff --git a/apps/server/src/electronics/ElectronicsService.test.ts b/apps/server/src/electronics/ElectronicsService.test.ts new file mode 100644 index 0000000000000..a5d8112bbb2c3 --- /dev/null +++ b/apps/server/src/electronics/ElectronicsService.test.ts @@ -0,0 +1,90 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { DEFAULT_SERVER_SETTINGS, ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +import * as ServerSettings from "../serverSettings.ts"; +import * as ElectronicsService from "./ElectronicsService.ts"; + +const makeTestLayer = (settingsOverride: Partial = {}) => { + const mockSettings = ServerSettings.layerTest(settingsOverride); + const mockSpawner = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.fail( + // Simulate binaries not installed so built-in engine is exercised cleanly + new Error("ENOENT") as never, + ), + ), + ); + return ElectronicsService.layer.pipe( + Layer.provide(mockSettings), + Layer.provide(mockSpawner), + Layer.provideMerge(NodeServices.layer), + ); +}; + +it.effect( + "discovers workspace electronics files, blocks path traversal, and streams thread sessions", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const service = yield* ElectronicsService.ElectronicsService; + + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-electronics-test-" }); + yield* fs.makeDirectory(path.join(dir, "hw"), { recursive: true }); + yield* fs.writeFileString( + path.join(dir, "hw", "divider.cir"), + "* Divider\nV1 in 0 5\nR1 in out 10k\nR2 out 0 10k\n.end\n", + ); + + const listed = yield* service.listFiles(dir); + expect(listed.files.map((f) => f.relativePath)).toEqual(["hw/divider.cir"]); + expect(listed.toolchain.enabled).toBe(true); + expect(listed.toolchain.kicadCli.available).toBe(false); + + // Path traversal must be rejected + const escapeResult = yield* service.inspect(dir, "../etc/passwd").pipe(Effect.flip); + expect(escapeResult.code).toBe("invalid_path"); + + // Inspect + trace + validate + simulate + openPanel + const model = yield* service.inspect(dir, "hw/divider.cir"); + expect(model.components.length).toBe(3); + + const threadId = ThreadId.make("thread-elec-1"); + const trace = yield* service.tracePath( + { cwd: dir, filePath: "hw/divider.cir", from: "V1.+", to: "out" }, + threadId, + ); + expect(trace.connected).toBe(true); + expect(trace.estimatedResistanceOhms).toBe(10_000); + + const sim = yield* service.simulate( + { cwd: dir, filePath: "hw/divider.cir", kind: "dc_op", outputNode: "out" }, + threadId, + ); + expect(sim.nodeVoltages.find((n) => n.node === "out")?.voltageV).toBeCloseTo(2.5, 4); + + const session = yield* service.getThreadSession(threadId); + expect(session?.filePath).toBe("hw/divider.cir"); + expect(session?.activeTab).toBe("simulate"); + + yield* service.closePanel(threadId); + expect(yield* service.getThreadSession(threadId)).toBeUndefined(); + }).pipe(Effect.scoped, Effect.provide(makeTestLayer())), +); + +it.effect("refuses operations when Electronics Workbench is disabled in settings", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const service = yield* ElectronicsService.ElectronicsService; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-electronics-off-" }); + const err = yield* service.listFiles(dir).pipe(Effect.flip); + expect(err.code).toBe("disabled"); + }).pipe(Effect.scoped, Effect.provide(makeTestLayer({ enableElectronicsWorkbench: false }))), +); diff --git a/apps/server/src/electronics/ElectronicsService.ts b/apps/server/src/electronics/ElectronicsService.ts new file mode 100644 index 0000000000000..033bbc078420b --- /dev/null +++ b/apps/server/src/electronics/ElectronicsService.ts @@ -0,0 +1,648 @@ +import { + type ElectronicsCircuitModel, + ElectronicsError, + type ElectronicsListFilesResult, + type ElectronicsPanelTab, + type ElectronicsServiceState, + type ElectronicsSimulateInput, + type ElectronicsSimulationResult, + type ElectronicsThreadSession, + type ElectronicsToolchainStatus, + type ElectronicsTracePathInput, + type ElectronicsTracePathResult, + type ElectronicsValidateInput, + type ElectronicsValidationReport, + type ElectronicsValidationSource, + type ElectronicsWorkspaceFile, + type ThreadId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as PubSub from "effect/PubSub"; +import * as Ref from "effect/Ref"; +import * as Stream from "effect/Stream"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +import * as ServerSettings from "../serverSettings.ts"; +import { runBuiltinMnaSimulation } from "./mnaSolver.ts"; +import { detectElectronicsFormat, parseElectronicsFile } from "./parsers.ts"; +import { traceCircuitPath } from "./pathTracer.ts"; +import { probeBinary, runKiCadExternalValidation, runNgspiceSimulation } from "./toolchain.ts"; +import { assembleValidationReport, runBuiltinCircuitValidation } from "./validator.ts"; + +const MAX_CIRCUIT_FILE_BYTES = 5 * 1024 * 1024; +const MAX_DISCOVERY_DEPTH = 6; +const MAX_DISCOVERY_FILES = 200; + +const IGNORED_DIRECTORIES: ReadonlySet = new Set([ + ".git", + ".hg", + ".svn", + "node_modules", + "dist", + "build", + ".next", + ".turbo", + ".t3", + ".venv", + "venv", + "__pycache__", + "target", + "coverage", +]); + +export interface ElectronicsServiceShape { + readonly getState: Effect.Effect; + readonly subscribeState: Stream.Stream; + readonly getToolchainStatus: ( + refresh?: boolean, + ) => Effect.Effect; + readonly listFiles: (cwd: string) => Effect.Effect; + readonly inspect: ( + cwd: string, + filePath: string, + ) => Effect.Effect; + readonly tracePath: ( + input: ElectronicsTracePathInput, + threadId?: ThreadId, + ) => Effect.Effect; + readonly validate: ( + input: ElectronicsValidateInput, + threadId?: ThreadId, + ) => Effect.Effect; + readonly simulate: ( + input: ElectronicsSimulateInput, + threadId?: ThreadId, + ) => Effect.Effect; + readonly openPanel: (input: { + readonly threadId: ThreadId; + readonly cwd: string; + readonly filePath: string; + readonly activeTab?: ElectronicsPanelTab | undefined; + readonly selectedNet?: string | undefined; + }) => Effect.Effect; + readonly closePanel: (threadId: ThreadId) => Effect.Effect; + readonly getThreadSession: ( + threadId: ThreadId, + ) => Effect.Effect; +} + +export class ElectronicsService extends Context.Service< + ElectronicsService, + ElectronicsServiceShape +>()("t3/electronics/ElectronicsService") {} + +export const layer = Layer.effect( + ElectronicsService, + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const serverSettings = yield* ServerSettings.ServerSettingsService; + + const sessionsRef = yield* Ref.make>(new Map()); + const toolchainCacheRef = yield* Ref.make(null); + const updates = yield* PubSub.unbounded(); + + const getSettings = serverSettings.getSettings.pipe( + Effect.mapError( + (err) => + new ElectronicsError({ + code: "internal", + message: `Unable to read server settings: ${err.message}`, + }), + ), + ); + + const ensureEnabled = Effect.gen(function* () { + const settings = yield* getSettings; + if (!settings.enableElectronicsWorkbench) { + return yield* new ElectronicsError({ + code: "disabled", + message: "Electronics Workbench is disabled in Settings → Electronics.", + }); + } + return settings; + }); + + const probeToolchain = Effect.fn("ElectronicsService.probeToolchain")(function* ( + forceRefresh = false, + ) { + const settings = yield* getSettings; + const cached = yield* Ref.get(toolchainCacheRef); + if ( + !forceRefresh && + cached !== null && + cached.enabled === settings.enableElectronicsWorkbench && + cached.allowExternalTools === settings.electronicsAllowExternalTools && + cached.agentAccessEnabled === settings.enableAgentElectronicsAccess + ) { + return cached; + } + const [kicadCli, ngspice] = settings.electronicsAllowExternalTools + ? yield* Effect.all([ + probeBinary("kicad-cli", settings.electronicsKicadCliPath).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ), + probeBinary("ngspice", settings.electronicsNgspicePath).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ), + ]) + : [ + { + name: "kicad-cli" as const, + available: false, + error: "External tools disabled in Settings → Electronics.", + }, + { + name: "ngspice" as const, + available: false, + error: "External tools disabled in Settings → Electronics.", + }, + ]; + + const status: ElectronicsToolchainStatus = { + enabled: settings.enableElectronicsWorkbench, + allowExternalTools: settings.electronicsAllowExternalTools, + agentAccessEnabled: settings.enableAgentElectronicsAccess, + kicadCli, + ngspice, + checkedAt: DateTime.formatIso(yield* DateTime.now), + }; + yield* Ref.set(toolchainCacheRef, status); + return status; + }); + + const buildState = Effect.gen(function* () { + const nowIso = DateTime.formatIso(yield* DateTime.now); + const toolchain = yield* probeToolchain(false).pipe( + Effect.orElseSucceed((): ElectronicsToolchainStatus => ({ + enabled: true, + allowExternalTools: true, + agentAccessEnabled: true, + kicadCli: { name: "kicad-cli", available: false }, + ngspice: { name: "ngspice", available: false }, + checkedAt: nowIso, + })), + ); + const sessions = Array.from((yield* Ref.get(sessionsRef)).values()); + return { toolchain, sessions } satisfies ElectronicsServiceState; + }); + + const broadcast = Effect.gen(function* () { + const state = yield* buildState; + yield* PubSub.publish(updates, state); + }); + + const resolveWorkspaceFile = Effect.fn("ElectronicsService.resolveWorkspaceFile")(function* ( + cwd: string, + requestedPath: string, + ) { + if (requestedPath.includes("\0")) { + return yield* new ElectronicsError({ + code: "invalid_path", + message: "Invalid file path.", + }); + } + const rootReal = yield* fs.realPath(cwd).pipe(Effect.orElseSucceed(() => path.resolve(cwd))); + const candidate = path.isAbsolute(requestedPath) + ? path.resolve(requestedPath) + : path.resolve(rootReal, requestedPath); + + const lexicalRelative = path.relative(rootReal, candidate); + if (lexicalRelative.startsWith("..") || path.isAbsolute(lexicalRelative)) { + return yield* new ElectronicsError({ + code: "invalid_path", + message: `Path "${requestedPath}" escapes the workspace root.`, + }); + } + + const exists = yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false)); + if (!exists) { + return yield* new ElectronicsError({ + code: "not_found", + message: `Electronics file "${requestedPath}" was not found in workspace.`, + }); + } + const targetReal = yield* fs.realPath(candidate).pipe(Effect.orElseSucceed(() => candidate)); + + const relative = path.relative(rootReal, targetReal); + if (relative.startsWith("..") || path.isAbsolute(relative)) { + return yield* new ElectronicsError({ + code: "invalid_path", + message: `Path "${requestedPath}" escapes the workspace root.`, + }); + } + + const stat = yield* fs.stat(targetReal).pipe( + Effect.mapError( + () => + new ElectronicsError({ + code: "not_found", + message: `Unable to stat "${requestedPath}".`, + }), + ), + ); + if (stat.type !== "File") { + return yield* new ElectronicsError({ + code: "invalid_path", + message: `"${requestedPath}" is not a regular file.`, + }); + } + if (Number(stat.size) > MAX_CIRCUIT_FILE_BYTES) { + return yield* new ElectronicsError({ + code: "parse_failed", + message: `File "${relative}" exceeds the ${MAX_CIRCUIT_FILE_BYTES / (1024 * 1024)} MB circuit file limit.`, + }); + } + const format = detectElectronicsFormat(relative); + if (!format) { + return yield* new ElectronicsError({ + code: "unsupported_format", + message: `Unsupported electronics file "${relative}". Supported: .kicad_sch, .kicad_pcb, .cir/.sp/.spice/.net, *.circuit.json.`, + }); + } + + return { + absolutePath: targetReal, + relativePath: relative.replaceAll("\\", "/"), + format, + }; + }); + + const loadAndParse = Effect.fn("ElectronicsService.loadAndParse")(function* ( + cwd: string, + requestedPath: string, + ) { + const resolved = yield* resolveWorkspaceFile(cwd, requestedPath); + const content = yield* fs.readFileString(resolved.absolutePath).pipe( + Effect.mapError( + (err) => + new ElectronicsError({ + code: "parse_failed", + message: `Failed reading "${resolved.relativePath}": ${String(err)}`, + }), + ), + ); + const model = yield* Effect.try({ + try: () => parseElectronicsFile(resolved.relativePath, content), + catch: (err) => + new ElectronicsError({ + code: "parse_failed", + message: err instanceof Error ? err.message : String(err), + }), + }); + return { ...resolved, content, model }; + }); + + const listFiles = Effect.fn("ElectronicsService.listFiles")(function* (cwd: string) { + yield* ensureEnabled; + const rootReal = yield* fs.realPath(cwd).pipe(Effect.orElseSucceed(() => path.resolve(cwd))); + const found: ElectronicsWorkspaceFile[] = []; + + const walk = Effect.fn("ElectronicsService.walk")(function* ( + dir: string, + depth: number, + ): Effect.fn.Return { + if (depth > MAX_DISCOVERY_DEPTH || found.length >= MAX_DISCOVERY_FILES) return; + const entries = yield* fs + .readDirectory(dir) + .pipe(Effect.orElseSucceed((): ReadonlyArray => [])); + for (const entry of entries) { + if (found.length >= MAX_DISCOVERY_FILES) break; + if (IGNORED_DIRECTORIES.has(entry)) continue; + const fullPath = path.join(dir, entry); + const stat = yield* fs.stat(fullPath).pipe(Effect.orElseSucceed(() => null)); + if (!stat) continue; + if (stat.type === "Directory") { + yield* walk(fullPath, depth + 1); + } else if (stat.type === "File") { + const format = detectElectronicsFormat(entry); + if (format) { + const rel = path.relative(rootReal, fullPath).replaceAll("\\", "/"); + found.push({ + relativePath: rel, + name: entry, + format, + sizeBytes: Number(stat.size), + }); + } + } + } + }); + + yield* walk(rootReal, 0); + found.sort((a, b) => a.relativePath.localeCompare(b.relativePath)); + const toolchain = yield* probeToolchain(false); + return { files: found, toolchain } satisfies ElectronicsListFilesResult; + }); + + const updateThreadSession = Effect.fn("ElectronicsService.updateThreadSession")(function* ( + threadId: ThreadId, + updater: (existing: ElectronicsThreadSession | undefined) => ElectronicsThreadSession, + ) { + let nextSession!: ElectronicsThreadSession; + yield* Ref.update(sessionsRef, (map) => { + const next = new Map(map); + nextSession = updater(next.get(threadId)); + next.set(threadId, nextSession); + return next; + }); + yield* broadcast; + return nextSession; + }); + + const inspect = Effect.fn("ElectronicsService.inspect")(function* ( + cwd: string, + filePath: string, + ) { + yield* ensureEnabled; + const loaded = yield* loadAndParse(cwd, filePath); + return loaded.model; + }); + + const tracePath = Effect.fn("ElectronicsService.tracePath")(function* ( + input: ElectronicsTracePathInput, + threadId?: ThreadId, + ) { + yield* ensureEnabled; + const loaded = yield* loadAndParse(input.cwd, input.filePath); + const result = traceCircuitPath(loaded.model, { + from: input.from, + ...(input.to !== undefined ? { to: input.to } : {}), + ...(input.traversePassives !== undefined + ? { traversePassives: input.traversePassives } + : {}), + ...(input.maxHops !== undefined ? { maxHops: input.maxHops } : {}), + }); + if (threadId !== undefined) { + const now = DateTime.formatIso(yield* DateTime.now); + yield* updateThreadSession(threadId, (existing) => ({ + threadId, + filePath: loaded.relativePath, + format: loaded.format, + activeTab: "trace", + ...(result.highlightedNets[0] !== undefined + ? { selectedNet: result.highlightedNets[0] } + : {}), + lastTrace: result, + ...(existing?.lastValidation !== undefined && existing.filePath === loaded.relativePath + ? { lastValidation: existing.lastValidation } + : {}), + ...(existing?.lastSimulation !== undefined && existing.filePath === loaded.relativePath + ? { lastSimulation: existing.lastSimulation } + : {}), + openedAt: existing?.openedAt ?? now, + updatedAt: now, + })); + } + return result; + }); + + const validate = Effect.fn("ElectronicsService.validate")(function* ( + input: ElectronicsValidateInput, + threadId?: ThreadId, + ) { + const settings = yield* ensureEnabled; + const loaded = yield* loadAndParse(input.cwd, input.filePath); + const builtin = runBuiltinCircuitValidation(loaded.model); + const enginesUsed: ElectronicsValidationSource[] = ["builtin"]; + const notes = [...builtin.notes]; + const externalIssues = []; + + const wantExternal = + (input.useExternalToolchain ?? true) && settings.electronicsAllowExternalTools; + + if (wantExternal && (loaded.format === "kicad_sch" || loaded.format === "kicad_pcb")) { + const toolchain = yield* probeToolchain(false); + if (toolchain.kicadCli.available) { + const ext = yield* runKiCadExternalValidation({ + absolutePath: loaded.absolutePath, + format: loaded.format, + ...(settings.electronicsKicadCliPath + ? { kicadCliPath: settings.electronicsKicadCliPath } + : {}), + }).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + if (ext.ran) { + enginesUsed.push(ext.source); + externalIssues.push(...ext.issues); + } else if (ext.note) { + notes.push(ext.note); + } + } else { + notes.push( + "kicad-cli is not installed on this environment; ran built-in pure-TypeScript electrical & layout checks.", + ); + } + } + + const report = assembleValidationReport({ + model: loaded.model, + builtinIssues: builtin.issues, + externalIssues, + enginesUsed, + notes, + }); + + if (threadId !== undefined) { + const now = DateTime.formatIso(yield* DateTime.now); + yield* updateThreadSession(threadId, (existing) => ({ + threadId, + filePath: loaded.relativePath, + format: loaded.format, + activeTab: "checks", + ...(existing?.selectedNet !== undefined && existing.filePath === loaded.relativePath + ? { selectedNet: existing.selectedNet } + : {}), + ...(existing?.lastTrace !== undefined && existing.filePath === loaded.relativePath + ? { lastTrace: existing.lastTrace } + : {}), + lastValidation: report, + ...(existing?.lastSimulation !== undefined && existing.filePath === loaded.relativePath + ? { lastSimulation: existing.lastSimulation } + : {}), + openedAt: existing?.openedAt ?? now, + updatedAt: now, + })); + } + + return report; + }); + + const simulate = Effect.fn("ElectronicsService.simulate")(function* ( + input: ElectronicsSimulateInput, + threadId?: ThreadId, + ) { + const settings = yield* ensureEnabled; + const loaded = yield* loadAndParse(input.cwd, input.filePath); + const kind = input.kind ?? "dc_op"; + + let result: ElectronicsSimulationResult | null = null; + const wantExternal = + (input.useExternalToolchain ?? true) && settings.electronicsAllowExternalTools; + + if (wantExternal && loaded.format === "spice") { + const toolchain = yield* probeToolchain(false); + if (toolchain.ngspice.available) { + result = yield* runNgspiceSimulation({ + model: loaded.model, + spiceSource: loaded.content, + kind, + ...(settings.electronicsNgspicePath + ? { ngspicePath: settings.electronicsNgspicePath } + : {}), + ...(input.outputNode !== undefined ? { outputNode: input.outputNode } : {}), + ...(input.startFreqHz !== undefined ? { startFreqHz: input.startFreqHz } : {}), + ...(input.stopFreqHz !== undefined ? { stopFreqHz: input.stopFreqHz } : {}), + ...(input.pointsPerDecade !== undefined + ? { pointsPerDecade: input.pointsPerDecade } + : {}), + ...(input.stopTimeSeconds !== undefined + ? { stopTimeSeconds: input.stopTimeSeconds } + : {}), + ...(input.stepTimeSeconds !== undefined + ? { stepTimeSeconds: input.stepTimeSeconds } + : {}), + }).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + } + } + + if (result === null) { + result = yield* Effect.try({ + try: () => + runBuiltinMnaSimulation(loaded.model, { + kind, + ...(input.outputNode !== undefined ? { outputNode: input.outputNode } : {}), + ...(input.startFreqHz !== undefined ? { startFreqHz: input.startFreqHz } : {}), + ...(input.stopFreqHz !== undefined ? { stopFreqHz: input.stopFreqHz } : {}), + ...(input.pointsPerDecade !== undefined + ? { pointsPerDecade: input.pointsPerDecade } + : {}), + ...(input.stopTimeSeconds !== undefined + ? { stopTimeSeconds: input.stopTimeSeconds } + : {}), + ...(input.stepTimeSeconds !== undefined + ? { stepTimeSeconds: input.stepTimeSeconds } + : {}), + }), + catch: (err) => + new ElectronicsError({ + code: "simulation_failed", + message: err instanceof Error ? err.message : String(err), + }), + }); + } + + if (threadId !== undefined) { + const now = DateTime.formatIso(yield* DateTime.now); + yield* updateThreadSession(threadId, (existing) => ({ + threadId, + filePath: loaded.relativePath, + format: loaded.format, + activeTab: "simulate", + ...(existing?.selectedNet !== undefined && existing.filePath === loaded.relativePath + ? { selectedNet: existing.selectedNet } + : {}), + ...(existing?.lastTrace !== undefined && existing.filePath === loaded.relativePath + ? { lastTrace: existing.lastTrace } + : {}), + ...(existing?.lastValidation !== undefined && existing.filePath === loaded.relativePath + ? { lastValidation: existing.lastValidation } + : {}), + lastSimulation: result, + openedAt: existing?.openedAt ?? now, + updatedAt: now, + })); + } + + return result; + }); + + const openPanel = Effect.fn("ElectronicsService.openPanel")(function* (input: { + readonly threadId: ThreadId; + readonly cwd: string; + readonly filePath: string; + readonly activeTab?: ElectronicsPanelTab | undefined; + readonly selectedNet?: string | undefined; + }) { + yield* ensureEnabled; + const loaded = yield* loadAndParse(input.cwd, input.filePath); + const now = DateTime.formatIso(yield* DateTime.now); + return yield* updateThreadSession(input.threadId, (existing) => ({ + threadId: input.threadId, + filePath: loaded.relativePath, + format: loaded.format, + activeTab: input.activeTab ?? "canvas", + ...(input.selectedNet && input.selectedNet.length > 0 + ? { selectedNet: input.selectedNet } + : existing?.selectedNet && existing.filePath === loaded.relativePath + ? { selectedNet: existing.selectedNet } + : {}), + ...(existing?.lastTrace !== undefined && existing.filePath === loaded.relativePath + ? { lastTrace: existing.lastTrace } + : {}), + ...(existing?.lastValidation !== undefined && existing.filePath === loaded.relativePath + ? { lastValidation: existing.lastValidation } + : {}), + ...(existing?.lastSimulation !== undefined && existing.filePath === loaded.relativePath + ? { lastSimulation: existing.lastSimulation } + : {}), + openedAt: existing?.openedAt ?? now, + updatedAt: now, + })); + }); + + const closePanel = Effect.fn("ElectronicsService.closePanel")(function* (threadId: ThreadId) { + yield* Ref.update(sessionsRef, (map) => { + const next = new Map(map); + next.delete(threadId); + return next; + }); + yield* broadcast; + }); + + const getThreadSession = (threadId: ThreadId) => + Ref.get(sessionsRef).pipe(Effect.map((map) => map.get(threadId))); + + const subscribeState: Stream.Stream = Stream.unwrap( + Effect.gen(function* () { + const initial = yield* buildState; + return Stream.concat(Stream.make(initial), Stream.fromPubSub(updates)); + }), + ); + + const getToolchainStatus = Effect.fn("ElectronicsService.getToolchainStatus")(function* ( + refresh = false, + ) { + const status = yield* probeToolchain(refresh); + if (refresh) yield* broadcast; + return status; + }); + + return ElectronicsService.of({ + getState: buildState, + subscribeState, + getToolchainStatus, + listFiles, + inspect, + tracePath, + validate, + simulate, + openPanel, + closePanel, + getThreadSession, + }); + }), +); diff --git a/apps/server/src/electronics/mnaSolver.ts b/apps/server/src/electronics/mnaSolver.ts new file mode 100644 index 0000000000000..4e66eb91a7062 --- /dev/null +++ b/apps/server/src/electronics/mnaSolver.ts @@ -0,0 +1,812 @@ +import * as DateTime from "effect/DateTime"; +import type { + ElectronicsCircuitModel, + ElectronicsSimulationComponentReading, + ElectronicsSimulationKind, + ElectronicsSimulationMetric, + ElectronicsSimulationNodeVoltage, + ElectronicsSimulationResult, + ElectronicsSimulationTraceSeries, +} from "@t3tools/contracts"; + +import { isGroundNetName, parseEngineeringNumber } from "./parsers.ts"; + +interface LinearElement { + readonly ref: string; + readonly valueText: string; + readonly type: "R" | "C" | "L" | "V" | "I"; + readonly n1: string; + readonly n2: string; + readonly numericValue: number; + readonly acMag: number; + readonly acPhaseRad: number; + readonly pulse?: { + readonly v1: number; + readonly v2: number; + readonly td: number; + readonly tr: number; + readonly pw: number; + readonly per: number; + }; + readonly sin?: { + readonly vo: number; + readonly va: number; + readonly freq: number; + }; +} + +function parseSourceSpec(raw: string): { + dc: number; + acMag: number; + acPhaseRad: number; + pulse?: LinearElement["pulse"]; + sin?: LinearElement["sin"]; +} { + let dc = 0; + let acMag = 0; + let acPhaseRad = 0; + let pulse: LinearElement["pulse"]; + let sin: LinearElement["sin"]; + + const pulseMatch = /PULSE\s*\(([^)]+)\)/iu.exec(raw); + if (pulseMatch) { + const nums = pulseMatch[1]! + .trim() + .split(/[\s,]+/u) + .map((t) => parseEngineeringNumber(t) ?? 0); + pulse = { + v1: nums[0] ?? 0, + v2: nums[1] ?? 5, + td: nums[2] ?? 0, + tr: Math.max(1e-12, nums[3] ?? 1e-6), + pw: nums[5] ?? 1e-3, + per: nums[6] ?? 2e-3, + }; + dc = pulse.v1; + } + + const sinMatch = /SIN\s*\(([^)]+)\)/iu.exec(raw); + if (sinMatch) { + const nums = sinMatch[1]! + .trim() + .split(/[\s,]+/u) + .map((t) => parseEngineeringNumber(t) ?? 0); + sin = { + vo: nums[0] ?? 0, + va: nums[1] ?? 1, + freq: nums[2] ?? 1000, + }; + dc = sin.vo; + } + + const acMatch = /\bAC\s+([^\s]+)(?:\s+([^\s]+))?/iu.exec(raw); + if (acMatch) { + acMag = parseEngineeringNumber(acMatch[1]!) ?? 1; + const phaseDeg = acMatch[2] ? (parseEngineeringNumber(acMatch[2]) ?? 0) : 0; + acPhaseRad = (phaseDeg * Math.PI) / 180; + } + + const dcMatch = /\bDC\s+([^\s]+)/iu.exec(raw); + if (dcMatch) { + dc = parseEngineeringNumber(dcMatch[1]!) ?? dc; + } else if (!pulse && !sin) { + // Plain numeric value like "5" or "3.3V" + const firstToken = raw.trim().split(/\s+/u)[0] ?? ""; + const parsed = parseEngineeringNumber(firstToken); + if (parsed !== null) dc = parsed; + } + + // If user didn't specify AC magnitude on a voltage source, default AC stimulus to 1V for AC sweep + if (acMag === 0 && !acMatch) { + acMag = 1; + } + + return { + dc, + acMag, + acPhaseRad, + ...(pulse !== undefined ? { pulse } : {}), + ...(sin !== undefined ? { sin } : {}), + }; +} + +function extractLinearElements(model: ElectronicsCircuitModel): { + elements: LinearElement[]; + skipped: string[]; +} { + const elements: LinearElement[] = []; + const skipped: string[] = []; + + for (const comp of model.components) { + if (comp.kind === "power_symbol" || comp.ref.startsWith("#")) continue; + if (comp.pins.length < 2) continue; + const n1 = comp.pins[0]!.net; + const n2 = comp.pins[1]!.net; + if (!n1 || !n2) { + skipped.push(`${comp.ref} (unconnected pin)`); + continue; + } + + const prefix = comp.ref[0]?.toUpperCase(); + if (comp.kind === "resistor" || prefix === "R") { + const val = parseEngineeringNumber(comp.value); + if (val !== null && val > 0) { + elements.push({ + ref: comp.ref, + valueText: comp.value, + type: "R", + n1, + n2, + numericValue: val, + acMag: 0, + acPhaseRad: 0, + }); + } else { + skipped.push(`${comp.ref} (unparseable resistance "${comp.value}")`); + } + } else if (comp.kind === "capacitor" || prefix === "C") { + const val = parseEngineeringNumber(comp.value); + if (val !== null && val > 0) { + elements.push({ + ref: comp.ref, + valueText: comp.value, + type: "C", + n1, + n2, + numericValue: val, + acMag: 0, + acPhaseRad: 0, + }); + } else { + skipped.push(`${comp.ref} (unparseable capacitance "${comp.value}")`); + } + } else if (comp.kind === "inductor" || prefix === "L") { + const val = parseEngineeringNumber(comp.value); + if (val !== null && val > 0) { + elements.push({ + ref: comp.ref, + valueText: comp.value, + type: "L", + n1, + n2, + numericValue: val, + acMag: 0, + acPhaseRad: 0, + }); + } else { + skipped.push(`${comp.ref} (unparseable inductance "${comp.value}")`); + } + } else if (comp.kind === "power_source" || prefix === "V" || prefix === "I") { + const spec = parseSourceSpec(comp.value); + elements.push({ + ref: comp.ref, + valueText: comp.value, + type: prefix === "I" ? "I" : "V", + n1, + n2, + numericValue: spec.dc, + acMag: spec.acMag, + acPhaseRad: spec.acPhaseRad, + ...(spec.pulse !== undefined ? { pulse: spec.pulse } : {}), + ...(spec.sin !== undefined ? { sin: spec.sin } : {}), + }); + } else { + skipped.push( + `${comp.ref} (${comp.kind}, nonlinear/active; requires ngspice for exact model)`, + ); + } + } + + return { elements, skipped }; +} + +function solveRealLinear(AInput: number[][], bInput: number[]): number[] { + const n = bInput.length; + const A = AInput.map((row) => [...row]); + const b = [...bInput]; + + for (let col = 0; col < n; col += 1) { + let pivotRow = col; + let maxAbs = Math.abs(A[col]![col]!); + for (let row = col + 1; row < n; row += 1) { + const v = Math.abs(A[row]![col]!); + if (v > maxAbs) { + maxAbs = v; + pivotRow = row; + } + } + if (maxAbs < 1e-18) { + throw new Error( + "Circuit matrix is singular (check for floating nodes or shorted voltage sources).", + ); + } + if (pivotRow !== col) { + const tmpRow = A[col]!; + A[col] = A[pivotRow]!; + A[pivotRow] = tmpRow; + const tmpB = b[col]!; + b[col] = b[pivotRow]!; + b[pivotRow] = tmpB; + } + const pivot = A[col]![col]!; + for (let row = col + 1; row < n; row += 1) { + const factor = A[row]![col]! / pivot; + if (factor === 0) continue; + for (let k = col; k < n; k += 1) { + A[row]![k] = A[row]![k]! - factor * A[col]![k]!; + } + b[row] = b[row]! - factor * b[col]!; + } + } + + const x = new Array(n).fill(0); + for (let row = n - 1; row >= 0; row -= 1) { + let sum = b[row]!; + for (let k = row + 1; k < n; k += 1) { + sum -= A[row]![k]! * x[k]!; + } + x[row] = sum / A[row]![row]!; + } + return x; +} + +interface Complex { + re: number; + im: number; +} + +const cAdd = (a: Complex, b: Complex): Complex => ({ re: a.re + b.re, im: a.im + b.im }); +const cSub = (a: Complex, b: Complex): Complex => ({ re: a.re - b.re, im: a.im - b.im }); +const cMul = (a: Complex, b: Complex): Complex => ({ + re: a.re * b.re - a.im * b.im, + im: a.re * b.im + a.im * b.re, +}); +const cDiv = (a: Complex, b: Complex): Complex => { + const denom = b.re * b.re + b.im * b.im; + return { + re: (a.re * b.re + a.im * b.im) / denom, + im: (a.im * b.re - a.re * b.im) / denom, + }; +}; +const cAbs = (a: Complex): number => Math.hypot(a.re, a.im); + +function solveComplexLinear(AInput: Complex[][], bInput: Complex[]): Complex[] { + const n = bInput.length; + const A = AInput.map((row) => row.map((c) => ({ re: c.re, im: c.im }))); + const b = bInput.map((c) => ({ re: c.re, im: c.im })); + + for (let col = 0; col < n; col += 1) { + let pivotRow = col; + let maxAbs = cAbs(A[col]![col]!); + for (let row = col + 1; row < n; row += 1) { + const v = cAbs(A[row]![col]!); + if (v > maxAbs) { + maxAbs = v; + pivotRow = row; + } + } + if (maxAbs < 1e-18) { + throw new Error("Complex AC circuit matrix is singular at this frequency."); + } + if (pivotRow !== col) { + const tmpRow = A[col]!; + A[col] = A[pivotRow]!; + A[pivotRow] = tmpRow; + const tmpB = b[col]!; + b[col] = b[pivotRow]!; + b[pivotRow] = tmpB; + } + const pivot = A[col]![col]!; + for (let row = col + 1; row < n; row += 1) { + const factor = cDiv(A[row]![col]!, pivot); + if (factor.re === 0 && factor.im === 0) continue; + for (let k = col; k < n; k += 1) { + A[row]![k] = cSub(A[row]![k]!, cMul(factor, A[col]![k]!)); + } + b[row] = cSub(b[row]!, cMul(factor, b[col]!)); + } + } + + const x: Complex[] = Array.from({ length: n }, () => ({ re: 0, im: 0 })); + for (let row = n - 1; row >= 0; row -= 1) { + let sum = b[row]!; + for (let k = row + 1; k < n; k += 1) { + sum = cSub(sum, cMul(A[row]![k]!, x[k]!)); + } + x[row] = cDiv(sum, A[row]![row]!); + } + return x; +} + +function sourceValueAtTime(el: LinearElement, t: number): number { + if (el.sin) { + return el.sin.vo + el.sin.va * Math.sin(2 * Math.PI * el.sin.freq * t); + } + if (el.pulse) { + const p = el.pulse; + if (t < p.td) return p.v1; + const phase = p.per > 0 ? (t - p.td) % p.per : t - p.td; + if (phase < p.tr) return p.v1 + ((p.v2 - p.v1) * phase) / p.tr; + if (phase < p.tr + p.pw) return p.v2; + if (phase < p.tr + p.pw + p.tr) { + return p.v2 - ((p.v2 - p.v1) * (phase - p.tr - p.pw)) / p.tr; + } + return p.v1; + } + // Step from 0 to DC at t >= 0 for transient visualization + return t === 0 ? 0 : el.numericValue; +} + +function chooseDefaultOutputNode( + nonGroundNodes: ReadonlyArray, + voltageSources: ReadonlyArray, +): string | undefined { + if (nonGroundNodes.length === 0) return undefined; + const preferred = nonGroundNodes.find((n) => /OUT|FILT|MID|DIV|LOAD/iu.test(n)); + if (preferred) return preferred; + const drivenByVSource = new Set(); + for (const vs of voltageSources) { + if (!isGroundNetName(vs.n1)) drivenByVSource.add(vs.n1); + } + return nonGroundNodes.find((n) => !drivenByVSource.has(n)) ?? nonGroundNodes[0]; +} + +export function runBuiltinMnaSimulation( + model: ElectronicsCircuitModel, + options: { + readonly kind?: ElectronicsSimulationKind; + readonly outputNode?: string; + readonly startFreqHz?: number; + readonly stopFreqHz?: number; + readonly pointsPerDecade?: number; + readonly stopTimeSeconds?: number; + readonly stepTimeSeconds?: number; + } = {}, +): ElectronicsSimulationResult { + const kind: ElectronicsSimulationKind = options.kind ?? "dc_op"; + const { elements, skipped } = extractLinearElements(model); + const notes: string[] = []; + if (skipped.length > 0) { + notes.push( + `Skipped non-linear/unparsed elements in built-in linear MNA solver: ${skipped.join(", ")}.`, + ); + } + + if (elements.length === 0) { + throw new Error("No simulatable linear elements (R, C, L, V, I) were found in this circuit."); + } + + // Gather non-ground nodes + const nodeIndex = new Map(); + const nonGroundNodes: string[] = []; + let hasGround = false; + for (const el of elements) { + for (const n of [el.n1, el.n2]) { + if (isGroundNetName(n)) { + hasGround = true; + } else if (!nodeIndex.has(n)) { + nodeIndex.set(n, nonGroundNodes.length); + nonGroundNodes.push(n); + } + } + } + if (!hasGround) { + throw new Error("Circuit requires a ground reference node (GND or 0) for nodal simulation."); + } + + const voltageSources = elements.filter((e) => e.type === "V"); + if (voltageSources.length === 0 && !elements.some((e) => e.type === "I")) { + throw new Error( + "Circuit requires at least one voltage (V*) or current (I*) source to simulate.", + ); + } + + const N = nonGroundNodes.length; + const M = voltageSources.length; + const size = N + M; + + const solveDc = (): { + nodeVoltages: ElectronicsSimulationNodeVoltage[]; + componentReadings: ElectronicsSimulationComponentReading[]; + voltageByNode: Map; + } => { + const A = Array.from({ length: size }, () => new Array(size).fill(0)); + const b = new Array(size).fill(0); + + const stampG = (n1: string, n2: string, g: number) => { + const i1 = isGroundNetName(n1) ? -1 : nodeIndex.get(n1)!; + const i2 = isGroundNetName(n2) ? -1 : nodeIndex.get(n2)!; + if (i1 >= 0) A[i1]![i1]! += g; + if (i2 >= 0) A[i2]![i2]! += g; + if (i1 >= 0 && i2 >= 0) { + A[i1]![i2]! -= g; + A[i2]![i1]! -= g; + } + }; + + // Tiny gmin to prevent floating capacitor islands from making DC singular + for (let i = 0; i < N; i += 1) A[i]![i]! += 1e-12; + + for (const el of elements) { + if (el.type === "R") { + stampG(el.n1, el.n2, 1 / el.numericValue); + } else if (el.type === "C") { + stampG(el.n1, el.n2, 1e-12); + } else if (el.type === "L") { + // DC short (1 mΩ) + stampG(el.n1, el.n2, 1e3); + } else if (el.type === "I") { + const i1 = isGroundNetName(el.n1) ? -1 : nodeIndex.get(el.n1)!; + const i2 = isGroundNetName(el.n2) ? -1 : nodeIndex.get(el.n2)!; + if (i1 >= 0) b[i1]! -= el.numericValue; + if (i2 >= 0) b[i2]! += el.numericValue; + } + } + + for (let s = 0; s < M; s += 1) { + const vs = voltageSources[s]!; + const row = N + s; + const i1 = isGroundNetName(vs.n1) ? -1 : nodeIndex.get(vs.n1)!; + const i2 = isGroundNetName(vs.n2) ? -1 : nodeIndex.get(vs.n2)!; + const rowArr = A[row]!; + if (i1 >= 0) { + rowArr[i1] = 1; + A[i1]![row] = 1; + } + if (i2 >= 0) { + rowArr[i2] = -1; + A[i2]![row] = -1; + } + b[row] = vs.numericValue; + } + + const x = solveRealLinear(A, b); + const voltageByNode = new Map(); + const nodeVoltages: ElectronicsSimulationNodeVoltage[] = nonGroundNodes.map((node, idx) => { + const v = Number(x[idx]!.toPrecision(6)); + voltageByNode.set(node, x[idx]!); + return { node, voltageV: v }; + }); + + const getV = (n: string) => (isGroundNetName(n) ? 0 : (voltageByNode.get(n) ?? 0)); + const componentReadings: ElectronicsSimulationComponentReading[] = []; + + for (const el of elements) { + const vDrop = getV(el.n1) - getV(el.n2); + let current = 0; + if (el.type === "R") { + current = vDrop / el.numericValue; + } else if (el.type === "L") { + current = vDrop * 1e3; + } else if (el.type === "I") { + current = el.numericValue; + } else if (el.type === "V") { + const sIdx = voltageSources.indexOf(el); + current = sIdx >= 0 ? -x[N + sIdx]! : 0; + } + const power = Math.abs(vDrop * current); + componentReadings.push({ + ref: el.ref, + value: el.valueText, + voltageDropV: Number(vDrop.toPrecision(5)), + currentA: Number(current.toPrecision(5)), + powerW: Number(power.toPrecision(5)), + }); + } + + return { nodeVoltages, componentReadings, voltageByNode }; + }; + + const dc = solveDc(); + const targetNode = + options.outputNode && nodeIndex.has(options.outputNode) + ? options.outputNode + : chooseDefaultOutputNode(nonGroundNodes, voltageSources); + + if (kind === "dc_op") { + const totalPowerW = dc.componentReadings + .filter((r) => !r.ref.toUpperCase().startsWith("V")) + .reduce((acc, r) => acc + r.powerW, 0); + const metrics: ElectronicsSimulationMetric[] = [ + { name: "Total dissipation", value: Number(totalPowerW.toPrecision(4)), unit: "W" }, + ]; + if (targetNode) { + const tv = dc.voltageByNode.get(targetNode) ?? 0; + metrics.unshift({ name: `V(${targetNode})`, value: Number(tv.toPrecision(5)), unit: "V" }); + } + return { + filePath: model.filePath, + kind: "dc_op", + engine: "builtin_mna", + xAxisLabel: "Node", + xAxisUnit: "", + xAxisLog: false, + nodeVoltages: dc.nodeVoltages, + componentReadings: dc.componentReadings, + series: [], + metrics, + notes, + simulatedAt: DateTime.formatIso(DateTime.nowUnsafe()), + }; + } + + if (kind === "ac_sweep") { + const startFreq = Math.max(0.1, options.startFreqHz ?? 10); + const stopFreq = Math.max(startFreq * 10, options.stopFreqHz ?? 1_000_000); + const ptsPerDecade = options.pointsPerDecade ?? 12; + const decades = Math.log10(stopFreq / startFreq); + const totalPts = Math.min(200, Math.max(10, Math.round(decades * ptsPerDecade) + 1)); + + const outNodes = targetNode ? [targetNode] : nonGroundNodes.slice(0, 3); + const seriesMap = new Map>(); + for (const n of outNodes) seriesMap.set(n, []); + + for (let k = 0; k < totalPts; k += 1) { + const frac = totalPts === 1 ? 0 : k / (totalPts - 1); + const freq = startFreq * Math.pow(stopFreq / startFreq, frac); + const omega = 2 * Math.PI * freq; + + const A: Complex[][] = Array.from({ length: size }, () => + Array.from({ length: size }, () => ({ re: 0, im: 0 })), + ); + const b: Complex[] = Array.from({ length: size }, () => ({ re: 0, im: 0 })); + + for (let i = 0; i < N; i += 1) A[i]![i]!.re += 1e-12; + + const stampY = (n1: string, n2: string, y: Complex) => { + const i1 = isGroundNetName(n1) ? -1 : nodeIndex.get(n1)!; + const i2 = isGroundNetName(n2) ? -1 : nodeIndex.get(n2)!; + if (i1 >= 0) A[i1]![i1] = cAdd(A[i1]![i1]!, y); + if (i2 >= 0) A[i2]![i2] = cAdd(A[i2]![i2]!, y); + if (i1 >= 0 && i2 >= 0) { + A[i1]![i2] = cSub(A[i1]![i2]!, y); + A[i2]![i1] = cSub(A[i2]![i1]!, y); + } + }; + + for (const el of elements) { + if (el.type === "R") { + stampY(el.n1, el.n2, { re: 1 / el.numericValue, im: 0 }); + } else if (el.type === "C") { + stampY(el.n1, el.n2, { re: 0, im: omega * el.numericValue }); + } else if (el.type === "L") { + stampY(el.n1, el.n2, { re: 0, im: -1 / (omega * el.numericValue) }); + } else if (el.type === "I") { + const i1 = isGroundNetName(el.n1) ? -1 : nodeIndex.get(el.n1)!; + const i2 = isGroundNetName(el.n2) ? -1 : nodeIndex.get(el.n2)!; + const val: Complex = { + re: el.acMag * Math.cos(el.acPhaseRad), + im: el.acMag * Math.sin(el.acPhaseRad), + }; + if (i1 >= 0) b[i1] = cSub(b[i1]!, val); + if (i2 >= 0) b[i2] = cAdd(b[i2]!, val); + } + } + + for (let s = 0; s < M; s += 1) { + const vs = voltageSources[s]!; + const row = N + s; + const i1 = isGroundNetName(vs.n1) ? -1 : nodeIndex.get(vs.n1)!; + const i2 = isGroundNetName(vs.n2) ? -1 : nodeIndex.get(vs.n2)!; + if (i1 >= 0) { + A[row]![i1] = { re: 1, im: 0 }; + A[i1]![row] = { re: 1, im: 0 }; + } + if (i2 >= 0) { + A[row]![i2] = { re: -1, im: 0 }; + A[i2]![row] = { re: -1, im: 0 }; + } + b[row] = { + re: vs.acMag * Math.cos(vs.acPhaseRad), + im: vs.acMag * Math.sin(vs.acPhaseRad), + }; + } + + const sol = solveComplexLinear(A, b); + for (const n of outNodes) { + const cVal = sol[nodeIndex.get(n)!]!; + const mag = Math.max(1e-12, cAbs(cVal)); + const db = 20 * Math.log10(mag); + const phaseDeg = (Math.atan2(cVal.im, cVal.re) * 180) / Math.PI; + seriesMap.get(n)!.push({ + x: Number(freq.toPrecision(5)), + y: Number(db.toFixed(3)), + phaseDeg: Number(phaseDeg.toFixed(2)), + }); + } + } + + const series: ElectronicsSimulationTraceSeries[] = outNodes.map((n) => ({ + label: `|V(${n})|`, + unit: "dB", + points: seriesMap.get(n)!, + })); + + const metrics: ElectronicsSimulationMetric[] = []; + const primary = series[0]?.points ?? []; + if (primary.length >= 2) { + const peakDb = Math.max(...primary.map((p) => p.y)); + metrics.push({ name: "Peak Gain", value: Number(peakDb.toFixed(2)), unit: "dB" }); + const targetDb = peakDb - 3.0103; + for (let i = 1; i < primary.length; i += 1) { + const prev = primary[i - 1]!; + const curr = primary[i]!; + if ( + (prev.y >= targetDb && curr.y <= targetDb) || + (prev.y <= targetDb && curr.y >= targetDb) + ) { + const frac = (targetDb - prev.y) / (curr.y - prev.y || 1); + const fc = prev.x * Math.pow(curr.x / prev.x, Math.max(0, Math.min(1, frac))); + metrics.push({ name: "-3 dB Cutoff", value: Number(fc.toPrecision(4)), unit: "Hz" }); + break; + } + } + } + + return { + filePath: model.filePath, + kind: "ac_sweep", + engine: "builtin_mna", + xAxisLabel: "Frequency", + xAxisUnit: "Hz", + xAxisLog: true, + nodeVoltages: dc.nodeVoltages, + componentReadings: dc.componentReadings, + series, + metrics, + notes, + simulatedAt: DateTime.formatIso(DateTime.nowUnsafe()), + }; + } + + // Transient analysis (Backward Euler companion models for C and L) + // Auto-pick a sensible stop time from dominant RC time constant if omitted + let estimatedTau = 1e-3; + const firstR = elements.find((e) => e.type === "R")?.numericValue; + const firstC = elements.find((e) => e.type === "C")?.numericValue; + if (firstR && firstC) { + estimatedTau = Math.max(1e-7, Math.min(1, firstR * firstC)); + } + const stopTime = options.stopTimeSeconds ?? estimatedTau * 5; + const steps = Math.min( + 240, + Math.max(40, options.stepTimeSeconds ? Math.round(stopTime / options.stepTimeSeconds) : 100), + ); + const dt = stopTime / steps; + + const outNodes = targetNode + ? Array.from( + new Set([ + ...voltageSources + .map((v) => v.n1) + .filter((n) => !isGroundNetName(n)) + .slice(0, 1), + targetNode, + ]), + ) + : nonGroundNodes.slice(0, 2); + + const seriesMap = new Map>(); + for (const n of outNodes) seriesMap.set(n, []); + + // State variables for capacitors (previous voltage) and inductors (previous current) + const capPrevV = new Map(); + const indPrevI = new Map(); + for (const el of elements) { + if (el.type === "C") capPrevV.set(el.ref, 0); + if (el.type === "L") indPrevI.set(el.ref, 0); + } + + for (let step = 0; step <= steps; step += 1) { + const t = step * dt; + const A = Array.from({ length: size }, () => new Array(size).fill(0)); + const b = new Array(size).fill(0); + for (let i = 0; i < N; i += 1) A[i]![i]! += 1e-12; + + const stampG = (n1: string, n2: string, g: number) => { + const i1 = isGroundNetName(n1) ? -1 : nodeIndex.get(n1)!; + const i2 = isGroundNetName(n2) ? -1 : nodeIndex.get(n2)!; + if (i1 >= 0) A[i1]![i1]! += g; + if (i2 >= 0) A[i2]![i2]! += g; + if (i1 >= 0 && i2 >= 0) { + A[i1]![i2]! -= g; + A[i2]![i1]! -= g; + } + }; + const stampI = (n1: string, n2: string, curr: number) => { + const i1 = isGroundNetName(n1) ? -1 : nodeIndex.get(n1)!; + const i2 = isGroundNetName(n2) ? -1 : nodeIndex.get(n2)!; + if (i1 >= 0) b[i1]! -= curr; + if (i2 >= 0) b[i2]! += curr; + }; + + for (const el of elements) { + if (el.type === "R") { + stampG(el.n1, el.n2, 1 / el.numericValue); + } else if (el.type === "C") { + const geq = el.numericValue / dt; + const ieq = -geq * (capPrevV.get(el.ref) ?? 0); + stampG(el.n1, el.n2, geq); + stampI(el.n1, el.n2, ieq); + } else if (el.type === "L") { + const geq = dt / el.numericValue; + const ieq = indPrevI.get(el.ref) ?? 0; + stampG(el.n1, el.n2, geq); + stampI(el.n1, el.n2, ieq); + } else if (el.type === "I") { + stampI(el.n1, el.n2, sourceValueAtTime(el, t)); + } + } + + for (let s = 0; s < M; s += 1) { + const vs = voltageSources[s]!; + const row = N + s; + const i1 = isGroundNetName(vs.n1) ? -1 : nodeIndex.get(vs.n1)!; + const i2 = isGroundNetName(vs.n2) ? -1 : nodeIndex.get(vs.n2)!; + const rowArr = A[row]!; + if (i1 >= 0) { + rowArr[i1] = 1; + A[i1]![row] = 1; + } + if (i2 >= 0) { + rowArr[i2] = -1; + A[i2]![row] = -1; + } + b[row] = sourceValueAtTime(vs, t); + } + + const sol = solveRealLinear(A, b); + const vAt = (n: string) => (isGroundNetName(n) ? 0 : sol[nodeIndex.get(n)!]!); + + for (const el of elements) { + if (el.type === "C") { + capPrevV.set(el.ref, vAt(el.n1) - vAt(el.n2)); + } else if (el.type === "L") { + const prevI = indPrevI.get(el.ref) ?? 0; + indPrevI.set(el.ref, prevI + ((vAt(el.n1) - vAt(el.n2)) * dt) / el.numericValue); + } + } + + for (const n of outNodes) { + seriesMap.get(n)!.push({ + x: Number((t * 1000).toPrecision(5)), + y: Number(vAt(n).toPrecision(5)), + }); + } + } + + const series: ElectronicsSimulationTraceSeries[] = outNodes.map((n) => ({ + label: `V(${n})`, + unit: "V", + points: seriesMap.get(n)!, + })); + + const primarySeries = + series.find((s) => targetNode && s.label === `V(${targetNode})`) ?? series[0]; + const metrics: ElectronicsSimulationMetric[] = []; + if (primarySeries && primarySeries.points.length > 0) { + const ys = primarySeries.points.map((p) => p.y); + const minV = Math.min(...ys); + const maxV = Math.max(...ys); + const finalV = ys[ys.length - 1]!; + metrics.push( + { name: "Final Value", value: Number(finalV.toPrecision(4)), unit: "V" }, + { name: "Peak-to-Peak", value: Number((maxV - minV).toPrecision(4)), unit: "V" }, + ); + } + + return { + filePath: model.filePath, + kind: "transient", + engine: "builtin_mna", + xAxisLabel: "Time", + xAxisUnit: "ms", + xAxisLog: false, + nodeVoltages: dc.nodeVoltages, + componentReadings: dc.componentReadings, + series, + metrics, + notes, + simulatedAt: DateTime.formatIso(DateTime.nowUnsafe()), + }; +} diff --git a/apps/server/src/electronics/parsers.ts b/apps/server/src/electronics/parsers.ts new file mode 100644 index 0000000000000..f3e20eb63e545 --- /dev/null +++ b/apps/server/src/electronics/parsers.ts @@ -0,0 +1,1541 @@ +import type { + ElectronicsBomEntry, + ElectronicsBounds, + ElectronicsCircuitModel, + ElectronicsComponent, + ElectronicsComponentKind, + ElectronicsDesignFormat, + ElectronicsLabelMarker, + ElectronicsNet, + ElectronicsNetPinRef, + ElectronicsPin, + ElectronicsPinElectricalType, + ElectronicsPoint, + ElectronicsVia, + ElectronicsWireSegment, +} from "@t3tools/contracts"; + +import { + atomNumber, + atomString, + findChild, + findChildren, + isSExprList, + parseSExpr, + type SExprList, +} from "./sexpr.ts"; + +export function detectElectronicsFormat(filePath: string): ElectronicsDesignFormat | null { + const lower = filePath.toLowerCase(); + if (lower.endsWith(".kicad_sch")) return "kicad_sch"; + if (lower.endsWith(".kicad_pcb")) return "kicad_pcb"; + if ( + lower.endsWith(".circuit.json") || + lower.endsWith("/circuit.json") || + lower === "circuit.json" + ) { + return "circuit_json"; + } + if ( + lower.endsWith(".cir") || + lower.endsWith(".sp") || + lower.endsWith(".spice") || + lower.endsWith(".net") + ) { + return "spice"; + } + return null; +} + +export function isGroundNetName(name: string): boolean { + const upper = name.trim().toUpperCase(); + if (upper === "0") return true; + return ( + upper === "GND" || + upper === "AGND" || + upper === "DGND" || + upper === "PGND" || + upper === "VSS" || + upper === "GNDA" || + upper === "GNDD" || + upper === "GNDREF" || + upper === "COM" || + upper.startsWith("GND_") || + upper.endsWith("_GND") + ); +} + +export function isPowerNetName(name: string): boolean { + if (isGroundNetName(name)) return false; + const upper = name.trim().toUpperCase(); + if (/^[+-]?\d+(\.\d+)?V\d*$/u.test(upper)) return true; + if (/^[+-]?\d+V\d+$/u.test(upper)) return true; + return ( + upper === "VCC" || + upper === "VDD" || + upper === "VIN" || + upper === "VOUT" || + upper === "VBUS" || + upper === "VBAT" || + upper === "VSYS" || + upper === "AVDD" || + upper === "DVDD" || + upper === "AVCC" || + upper === "VREF" || + upper.startsWith("VCC_") || + upper.startsWith("VDD_") || + upper.startsWith("+3V3") || + upper.startsWith("+5V") || + upper.startsWith("+12V") || + upper.startsWith("+24V") || + upper.startsWith("V3V3") || + upper.startsWith("V5V") + ); +} + +function inferComponentKind(ref: string, libId?: string, value?: string): ElectronicsComponentKind { + const upperRef = ref.trim().toUpperCase(); + const upperLib = (libId ?? "").toUpperCase(); + const libSymbolName = upperLib.includes(":") + ? upperLib.slice(upperLib.lastIndexOf(":") + 1) + : upperLib; + const upperVal = (value ?? "").toUpperCase(); + + if (upperRef.startsWith("#PWR") || upperLib.startsWith("POWER:")) return "power_symbol"; + if (/^R\d/u.test(upperRef) || upperRef === "R" || /^R($|_|_SMALL|_US)/u.test(libSymbolName)) { + return "resistor"; + } + if ( + /^C\d/u.test(upperRef) || + upperRef === "C" || + /^C($|_SMALL|_POLARIZED)/u.test(libSymbolName) + ) { + return "capacitor"; + } + if (/^L\d/u.test(upperRef) || upperRef === "L" || /^L($|_SMALL|_CORE)/u.test(libSymbolName)) { + return "inductor"; + } + if (/^FB\d/u.test(upperRef)) return "inductor"; + if (/^D\d/u.test(upperRef) || /^LED\d/u.test(upperRef) || libSymbolName === "LED") { + return "diode"; + } + if (/^[QM]\d/u.test(upperRef) || upperLib.includes("TRANSISTOR") || upperLib.includes("MOSFET")) { + return "transistor"; + } + if (/^[UJ]\d/u.test(upperRef)) { + if (upperRef.startsWith("J") || upperRef.startsWith("JP") || upperRef.startsWith("P")) { + return "connector"; + } + return "ic"; + } + if (/^JP\d/u.test(upperRef) || /^CON\d/u.test(upperRef) || /^P\d/u.test(upperRef)) { + return "connector"; + } + if (/^[VI]\d/u.test(upperRef) || /^BT\d/u.test(upperRef) || upperVal.includes("BATTERY")) { + return "power_source"; + } + if (/^SW\d/u.test(upperRef) || /^S\d/u.test(upperRef) || upperLib.includes("SWITCH")) { + return "switch"; + } + if (/^F\d/u.test(upperRef) || upperLib.includes("FUSE")) return "fuse"; + if (/^[YX]\d/u.test(upperRef) || upperLib.includes("CRYSTAL")) return "crystal"; + if (/^IC\d/u.test(upperRef)) return "ic"; + return "other"; +} + +function mapKiCadPinType(raw: string | undefined): ElectronicsPinElectricalType { + switch (raw) { + case "input": + return "input"; + case "output": + return "output"; + case "bidirectional": + return "bidirectional"; + case "tri_state": + return "tri_state"; + case "passive": + return "passive"; + case "power_in": + return "power_in"; + case "power_out": + return "power_out"; + case "open_collector": + return "open_collector"; + case "open_emitter": + return "open_emitter"; + case "unconnected": + case "no_connect": + return "unconnected"; + default: + return "unspecified"; + } +} + +export function parseEngineeringNumber(raw: string): number | null { + const cleaned = raw + .trim() + .replace(/Ω|OHMS?|OHM|F|H|V|A|HZ$/iu, "") + .trim(); + const match = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)\s*(meg|t|g|k|m|u|µ|n|p|f|r)?/iu.exec( + cleaned, + ); + if (!match) return null; + const base = Number(match[1]); + if (!Number.isFinite(base)) return null; + const suffix = (match[2] ?? "").toLowerCase(); + switch (suffix) { + case "t": + return base * 1e12; + case "g": + return base * 1e9; + case "meg": + return base * 1e6; + case "k": + return base * 1e3; + case "m": + return base * 1e-3; + case "u": + case "µ": + return base * 1e-6; + case "n": + return base * 1e-9; + case "p": + return base * 1e-12; + case "f": + return base * 1e-15; + case "r": + case "": + return base; + default: + return base; + } +} + +function computeBounds(input: { + readonly components: ReadonlyArray; + readonly wires: ReadonlyArray; + readonly vias: ReadonlyArray; + readonly labels: ReadonlyArray; + readonly boardOutline: ReadonlyArray; +}): ElectronicsBounds { + let minX = Number.POSITIVE_INFINITY; + let minY = Number.POSITIVE_INFINITY; + let maxX = Number.NEGATIVE_INFINITY; + let maxY = Number.NEGATIVE_INFINITY; + + const include = (x: number | undefined, y: number | undefined) => { + if (x === undefined || y === undefined || !Number.isFinite(x) || !Number.isFinite(y)) return; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + }; + + for (const c of input.components) { + include(c.x, c.y); + for (const p of c.pins) include(p.x, p.y); + } + for (const w of input.wires) { + include(w.x1, w.y1); + include(w.x2, w.y2); + } + for (const b of input.boardOutline) { + include(b.x1, b.y1); + include(b.x2, b.y2); + } + for (const v of input.vias) include(v.x, v.y); + for (const l of input.labels) include(l.x, l.y); + + if (!Number.isFinite(minX)) { + return { minX: 0, minY: 0, maxX: 100, maxY: 100 }; + } + const padX = Math.max(8, (maxX - minX) * 0.08); + const padY = Math.max(8, (maxY - minY) * 0.08); + return { + minX: Number((minX - padX).toFixed(3)), + minY: Number((minY - padY).toFixed(3)), + maxX: Number((maxX + padX).toFixed(3)), + maxY: Number((maxY + padY).toFixed(3)), + }; +} + +function buildBom(components: ReadonlyArray): ElectronicsBomEntry[] { + const groups = new Map< + string, + { + value: string; + footprint?: string; + libId?: string; + kind: ElectronicsComponentKind; + refs: string[]; + } + >(); + + for (const comp of components) { + if (comp.kind === "power_symbol" || comp.ref.startsWith("#")) continue; + const key = `${comp.value}||${comp.footprint ?? ""}||${comp.libId ?? ""}`; + const existing = groups.get(key); + if (existing) { + existing.refs.push(comp.ref); + } else { + groups.set(key, { + value: comp.value, + ...(comp.footprint !== undefined ? { footprint: comp.footprint } : {}), + ...(comp.libId !== undefined ? { libId: comp.libId } : {}), + kind: comp.kind, + refs: [comp.ref], + }); + } + } + + return Array.from(groups.values()) + .map((group) => ({ + value: group.value, + ...(group.footprint !== undefined ? { footprint: group.footprint } : {}), + ...(group.libId !== undefined ? { libId: group.libId } : {}), + kind: group.kind, + refs: group.refs.toSorted((a, b) => a.localeCompare(b, undefined, { numeric: true })), + quantity: group.refs.length, + })) + .toSorted((a, b) => a.refs[0]!.localeCompare(b.refs[0]!, undefined, { numeric: true })); +} + +class UnionFind { + readonly #parent = new Map(); + + find(id: number): number { + let cur = id; + while (this.#parent.has(cur) && this.#parent.get(cur) !== cur) { + cur = this.#parent.get(cur)!; + } + let walk = id; + while (walk !== cur) { + const next = this.#parent.get(walk)!; + this.#parent.set(walk, cur); + walk = next; + } + return cur; + } + + union(a: number, b: number): void { + const ra = this.find(a); + const rb = this.find(b); + if (ra !== rb) this.#parent.set(ra, rb); + } +} + +function pointKey(x: number, y: number): string { + // KiCad grid precision: 0.05 mm snap + const rx = Math.round(x * 20); + const ry = Math.round(y * 20); + return `${rx}:${ry}`; +} + +function isPointOnSegment(px: number, py: number, seg: ElectronicsWireSegment): boolean { + const tol = 0.08; + const minX = Math.min(seg.x1, seg.x2) - tol; + const maxX = Math.max(seg.x1, seg.x2) + tol; + const minY = Math.min(seg.y1, seg.y2) - tol; + const maxY = Math.max(seg.y1, seg.y2) + tol; + if (px < minX || px > maxX || py < minY || py > maxY) return false; + const dx = seg.x2 - seg.x1; + const dy = seg.y2 - seg.y1; + const lenSq = dx * dx + dy * dy; + if (lenSq < 1e-6) { + return Math.hypot(px - seg.x1, py - seg.y1) <= tol; + } + const cross = Math.abs((px - seg.x1) * dy - (py - seg.y1) * dx); + return cross / Math.sqrt(lenSq) <= tol; +} + +interface LibPinDef { + readonly number: string; + readonly name: string; + readonly electricalType: ElectronicsPinElectricalType; + readonly x: number; + readonly y: number; +} + +function extractLibSymbols(schRoot: SExprList): Map { + const libMap = new Map(); + const libSymbols = findChild(schRoot, "lib_symbols"); + if (!libSymbols) return libMap; + + for (const sym of findChildren(libSymbols, "symbol")) { + const libId = atomString(sym[1]); + if (!libId) continue; + const pins: LibPinDef[] = []; + + const collectPins = (node: SExprList) => { + for (const pin of findChildren(node, "pin")) { + const electricalType = mapKiCadPinType(atomString(pin[1])); + const at = findChild(pin, "at"); + const nameNode = findChild(pin, "name"); + const numNode = findChild(pin, "number"); + const number = atomString(numNode?.[1]) ?? ""; + const name = atomString(nameNode?.[1]) ?? ""; + const x = atomNumber(at?.[1]) ?? 0; + const y = atomNumber(at?.[2]) ?? 0; + if (number) { + pins.push({ number, name, electricalType, x, y }); + } + } + for (const sub of findChildren(node, "symbol")) { + collectPins(sub); + } + }; + + collectPins(sym); + libMap.set(libId, pins); + } + return libMap; +} + +function transformKiCadSchPin( + symX: number, + symY: number, + rotDeg: number, + mirror: string | undefined, + pinX: number, + pinY: number, +): { readonly x: number; readonly y: number } { + // KiCad schematic symbols have Y-up in lib_symbols and Y-down on the sheet canvas. + let lx = pinX; + let ly = -pinY; + if (mirror === "x") ly = -ly; + else if (mirror === "y") lx = -lx; + + const rad = (-rotDeg * Math.PI) / 180; + const cos = Math.cos(rad); + const sin = Math.sin(rad); + const rx = lx * cos - ly * sin; + const ry = lx * sin + ly * cos; + return { + x: Number((symX + rx).toFixed(3)), + y: Number((symY + ry).toFixed(3)), + }; +} + +function parseKiCadSchematic(filePath: string, content: string): ElectronicsCircuitModel { + const parsed = parseSExpr(content); + const root = parsed.find((n): n is SExprList => isSExprList(n) && n[0] === "kicad_sch"); + if (!root) { + throw new Error("File does not contain a top-level (kicad_sch ...) S-expression."); + } + + const parseWarnings: string[] = []; + const titleBlock = findChild(root, "title_block"); + const title = atomString(findChild(titleBlock ?? [], "title")?.[1]); + + const libMap = extractLibSymbols(root); + + const wires: ElectronicsWireSegment[] = []; + for (const wire of findChildren(root, "wire")) { + const pts = findChild(wire, "pts"); + if (!pts) continue; + const xys = findChildren(pts, "xy"); + for (let i = 0; i + 1 < xys.length; i += 1) { + const x1 = atomNumber(xys[i]?.[1]); + const y1 = atomNumber(xys[i]?.[2]); + const x2 = atomNumber(xys[i + 1]?.[1]); + const y2 = atomNumber(xys[i + 1]?.[2]); + if (x1 !== undefined && y1 !== undefined && x2 !== undefined && y2 !== undefined) { + wires.push({ x1, y1, x2, y2, layer: "wire" }); + } + } + } + + const junctions: ElectronicsPoint[] = []; + for (const j of findChildren(root, "junction")) { + const at = findChild(j, "at"); + const x = atomNumber(at?.[1]); + const y = atomNumber(at?.[2]); + if (x !== undefined && y !== undefined) junctions.push({ x, y }); + } + + const noConnects: ElectronicsPoint[] = []; + for (const nc of findChildren(root, "no_connect")) { + const at = findChild(nc, "at"); + const x = atomNumber(at?.[1]); + const y = atomNumber(at?.[2]); + if (x !== undefined && y !== undefined) noConnects.push({ x, y }); + } + + const labels: ElectronicsLabelMarker[] = []; + for (const [tag, kind] of [ + ["label", "local"], + ["global_label", "global"], + ["hierarchical_label", "hierarchical"], + ] as const) { + for (const lbl of findChildren(root, tag)) { + const text = atomString(lbl[1]); + const at = findChild(lbl, "at"); + const x = atomNumber(at?.[1]); + const y = atomNumber(at?.[2]); + if (text && x !== undefined && y !== undefined) { + labels.push({ text, kind, x, y }); + } + } + } + + interface MutableComp { + ref: string; + value: string; + kind: ElectronicsComponentKind; + libId?: string; + footprint?: string; + x: number; + y: number; + rotation: number; + pins: Array<{ + number: string; + name?: string; + electricalType: ElectronicsPinElectricalType; + net?: string; + x: number; + y: number; + }>; + } + + const components: MutableComp[] = []; + for (const sym of findChildren(root, "symbol")) { + const libId = atomString(findChild(sym, "lib_id")?.[1]); + const at = findChild(sym, "at"); + const x = atomNumber(at?.[1]) ?? 0; + const y = atomNumber(at?.[2]) ?? 0; + const rotation = atomNumber(at?.[3]) ?? 0; + const mirror = atomString(findChild(sym, "mirror")?.[1]); + + let ref = ""; + let value = ""; + let footprint: string | undefined; + for (const prop of findChildren(sym, "property")) { + const propName = atomString(prop[1]); + const propVal = atomString(prop[2]) ?? ""; + if (propName === "Reference") ref = propVal; + else if (propName === "Value") value = propVal; + else if (propName === "Footprint" && propVal.length > 0) footprint = propVal; + } + + if (!ref) ref = libId ?? `SYM_${components.length + 1}`; + if (!value) value = libId?.split(":").pop() ?? ref; + + const kind = inferComponentKind(ref, libId, value); + const libPins = libId ? (libMap.get(libId) ?? []) : []; + const pins = libPins.map((lp) => { + const pos = transformKiCadSchPin(x, y, rotation, mirror, lp.x, lp.y); + return { + number: lp.number, + ...(lp.name && lp.name !== "~" ? { name: lp.name } : {}), + electricalType: lp.electricalType, + x: pos.x, + y: pos.y, + }; + }); + + if (kind === "power_symbol") { + labels.push({ text: value, kind: "power", x, y }); + } + + components.push({ + ref, + value, + kind, + ...(libId !== undefined ? { libId } : {}), + ...(footprint !== undefined ? { footprint } : {}), + x, + y, + rotation, + pins, + }); + } + + // Build spatial connectivity graph + const uf = new UnionFind(); + const pointIds = new Map(); + let nextId = 1; + const getPointId = (x: number, y: number): number => { + const key = pointKey(x, y); + const existing = pointIds.get(key); + if (existing !== undefined) return existing; + const id = nextId; + nextId += 1; + pointIds.set(key, id); + return id; + }; + + // Connect wire endpoints + const wireStartIds: number[] = []; + for (const w of wires) { + const a = getPointId(w.x1, w.y1); + const b = getPointId(w.x2, w.y2); + uf.union(a, b); + wireStartIds.push(a); + } + + // Connect junctions lying on any wire segment + for (const j of junctions) { + const jId = getPointId(j.x, j.y); + for (let i = 0; i < wires.length; i += 1) { + if (isPointOnSegment(j.x, j.y, wires[i]!)) { + uf.union(jId, wireStartIds[i]!); + } + } + } + + // Connect pins and labels lying on wire endpoints or segments + for (const comp of components) { + for (const pin of comp.pins) { + const pId = getPointId(pin.x, pin.y); + for (let i = 0; i < wires.length; i += 1) { + if (isPointOnSegment(pin.x, pin.y, wires[i]!)) { + uf.union(pId, wireStartIds[i]!); + } + } + } + } + + const labelGroupsByName = new Map(); + for (const lbl of labels) { + const lId = getPointId(lbl.x, lbl.y); + for (let i = 0; i < wires.length; i += 1) { + if (isPointOnSegment(lbl.x, lbl.y, wires[i]!)) { + uf.union(lId, wireStartIds[i]!); + } + } + // Same-name labels connect electrically across the sheet + const prev = labelGroupsByName.get(lbl.text); + if (prev !== undefined) { + uf.union(lId, prev); + } else { + labelGroupsByName.set(lbl.text, lId); + } + } + + // Map each connected component root to preferred net name(s) + const rootLabelNames = new Map>(); + for (const lbl of labels) { + const rootId = uf.find(getPointId(lbl.x, lbl.y)); + let names = rootLabelNames.get(rootId); + if (!names) { + names = new Set(); + rootLabelNames.set(rootId, names); + } + names.add(lbl.text); + } + + const rootToNetName = new Map(); + const rootPins = new Map(); + const ncKeys = new Set(noConnects.map((nc) => pointKey(nc.x, nc.y))); + + for (const comp of components) { + for (const pin of comp.pins) { + if (comp.kind === "power_symbol") continue; + if (ncKeys.has(pointKey(pin.x, pin.y))) { + pin.electricalType = "unconnected"; + continue; + } + const rootId = uf.find(getPointId(pin.x, pin.y)); + let list = rootPins.get(rootId); + if (!list) { + list = []; + rootPins.set(rootId, list); + } + list.push({ + ref: comp.ref, + pin: pin.number, + ...(pin.name !== undefined ? { pinName: pin.name } : {}), + electricalType: pin.electricalType, + }); + } + } + + // Determine canonical net name for every root that has labels or >= 2 pins or wires + let autoNetIndex = 1; + const allRoots = new Set([...rootLabelNames.keys(), ...rootPins.keys()]); + for (const rootId of allRoots) { + const labelSet = rootLabelNames.get(rootId); + const pins = rootPins.get(rootId) ?? []; + if (labelSet && labelSet.size > 0) { + const sorted = Array.from(labelSet).toSorted((a, b) => a.localeCompare(b)); + // If multiple distinct power/ground labels landed on the same net, join them so validator flags a short! + const distinctRails = sorted.filter((n) => isGroundNetName(n) || isPowerNetName(n)); + if (distinctRails.length > 1) { + rootToNetName.set(rootId, distinctRails.join(" / ")); + } else { + rootToNetName.set(rootId, sorted[0]!); + } + } else if (pins.length >= 2) { + const first = pins[0]!; + rootToNetName.set(rootId, `Net-(${first.ref}-Pad${first.pin})`); + autoNetIndex += 1; + } else if (pins.length === 1) { + // Check if a wire actually touches this pin + const p = pins[0]!; + const comp = components.find((c) => c.ref === p.ref); + const pinObj = comp?.pins.find((candidate) => candidate.number === p.pin); + const hasWire = pinObj !== undefined && wireStartIds.some((wId) => uf.find(wId) === rootId); + if (hasWire) { + rootToNetName.set(rootId, `Net-(${p.ref}-Pad${p.pin})`); + autoNetIndex += 1; + } + } + } + void autoNetIndex; + + // Assign resolved net names back to pins and wires + for (const comp of components) { + for (const pin of comp.pins) { + if (comp.kind === "power_symbol") { + pin.net = comp.value; + continue; + } + if (ncKeys.has(pointKey(pin.x, pin.y))) continue; + const rootId = uf.find(getPointId(pin.x, pin.y)); + const netName = rootToNetName.get(rootId); + if (netName) pin.net = netName; + } + } + + const annotatedWires: ElectronicsWireSegment[] = wires.map((w, idx) => { + const netName = rootToNetName.get(uf.find(wireStartIds[idx]!)); + return netName ? { ...w, net: netName } : w; + }); + + const netsByName = new Map(); + for (const [rootId, netName] of rootToNetName.entries()) { + const pins = rootPins.get(rootId) ?? []; + const existing = netsByName.get(netName); + if (existing) existing.push(...pins); + else netsByName.set(netName, [...pins]); + } + + const nets: ElectronicsNet[] = Array.from(netsByName.entries()) + .map(([name, pins]) => { + const parts = name.split(" / "); + const hasGround = parts.some((p) => isGroundNetName(p)); + const hasPower = parts.some((p) => isPowerNetName(p)); + return { + name, + isPower: hasPower, + isGround: hasGround, + pins, + }; + }) + .toSorted((a, b) => a.name.localeCompare(b.name)); + + const finalComponents: ElectronicsComponent[] = components.map((c) => ({ + ref: c.ref, + value: c.value, + kind: c.kind, + ...(c.libId !== undefined ? { libId: c.libId } : {}), + ...(c.footprint !== undefined ? { footprint: c.footprint } : {}), + x: c.x, + y: c.y, + rotation: c.rotation, + pins: c.pins, + })); + + return { + format: "kicad_sch", + filePath, + ...(title !== undefined ? { title } : {}), + layers: ["schematic", "wire"], + bounds: computeBounds({ + components: finalComponents, + wires: annotatedWires, + vias: [], + labels, + boardOutline: [], + }), + components: finalComponents, + nets, + wires: annotatedWires, + vias: [], + junctions, + noConnects, + labels, + boardOutline: [], + bom: buildBom(finalComponents), + parseWarnings, + }; +} + +function parseKiCadPcb(filePath: string, content: string): ElectronicsCircuitModel { + const parsed = parseSExpr(content); + const root = parsed.find((n): n is SExprList => isSExprList(n) && n[0] === "kicad_pcb"); + if (!root) { + throw new Error("File does not contain a top-level (kicad_pcb ...) S-expression."); + } + + const parseWarnings: string[] = []; + const titleBlock = findChild(root, "title_block"); + const title = atomString(findChild(titleBlock ?? [], "title")?.[1]); + + const layers: string[] = []; + const layersNode = findChild(root, "layers"); + if (layersNode) { + for (let i = 1; i < layersNode.length; i += 1) { + const entry = layersNode[i]; + if (isSExprList(entry)) { + const layerName = atomString(entry[1]); + if (layerName) layers.push(layerName); + } + } + } + + const netIdToName = new Map(); + const netPinsMap = new Map(); + const netCodeMap = new Map(); + + for (const netNode of findChildren(root, "net")) { + const code = atomNumber(netNode[1]); + const name = atomString(netNode[2]) ?? ""; + if (code !== undefined && name.length > 0) { + netIdToName.set(code, name); + netCodeMap.set(name, code); + if (!netPinsMap.has(name)) netPinsMap.set(name, []); + } + } + + const components: ElectronicsComponent[] = []; + for (const fp of findChildren(root, "footprint")) { + const footprintName = atomString(fp[1]); + const layer = atomString(findChild(fp, "layer")?.[1]) ?? "F.Cu"; + const at = findChild(fp, "at"); + const fx = atomNumber(at?.[1]) ?? 0; + const fy = atomNumber(at?.[2]) ?? 0; + const rot = atomNumber(at?.[3]) ?? 0; + + let ref = ""; + let value = ""; + // KiCad 8+ uses (property "Reference" ...), KiCad 6/7 uses (fp_text reference ...) + for (const prop of findChildren(fp, "property")) { + const key = atomString(prop[1]); + const val = atomString(prop[2]) ?? ""; + if (key === "Reference") ref = val; + else if (key === "Value") value = val; + } + for (const txt of findChildren(fp, "fp_text")) { + const kind = atomString(txt[1]); + const val = atomString(txt[2]) ?? ""; + if (kind === "reference" && !ref) ref = val; + else if (kind === "value" && !value) value = val; + } + if (!ref) ref = `FP_${components.length + 1}`; + if (!value) value = footprintName ?? ref; + + const rad = (-rot * Math.PI) / 180; + const cos = Math.cos(rad); + const sin = Math.sin(rad); + + const pins: ElectronicsPin[] = []; + for (const pad of findChildren(fp, "pad")) { + const padNum = atomString(pad[1]) ?? ""; + const padAt = findChild(pad, "at"); + const pxLocal = atomNumber(padAt?.[1]) ?? 0; + const pyLocal = atomNumber(padAt?.[2]) ?? 0; + const wx = Number((fx + pxLocal * cos - pyLocal * sin).toFixed(3)); + const wy = Number((fy + pxLocal * sin + pyLocal * cos).toFixed(3)); + + const netNode = findChild(pad, "net"); + const netCode = atomNumber(netNode?.[1]); + const netName = + atomString(netNode?.[2]) ?? (netCode !== undefined ? netIdToName.get(netCode) : undefined); + + const cleanNet = netName && netName.length > 0 ? netName : undefined; + pins.push({ + number: padNum || String(pins.length + 1), + electricalType: "passive", + ...(cleanNet !== undefined ? { net: cleanNet } : {}), + x: wx, + y: wy, + }); + + if (cleanNet) { + let list = netPinsMap.get(cleanNet); + if (!list) { + list = []; + netPinsMap.set(cleanNet, list); + } + list.push({ + ref, + pin: padNum || String(pins.length), + electricalType: "passive", + }); + } + } + + components.push({ + ref, + value, + kind: inferComponentKind(ref, footprintName, value), + ...(footprintName !== undefined ? { footprint: footprintName } : {}), + x: fx, + y: fy, + rotation: rot, + layer, + pins, + }); + } + + const wires: ElectronicsWireSegment[] = []; + for (const seg of findChildren(root, "segment")) { + const start = findChild(seg, "start"); + const end = findChild(seg, "end"); + const x1 = atomNumber(start?.[1]); + const y1 = atomNumber(start?.[2]); + const x2 = atomNumber(end?.[1]); + const y2 = atomNumber(end?.[2]); + const width = atomNumber(findChild(seg, "width")?.[1]) ?? 0.25; + const layer = atomString(findChild(seg, "layer")?.[1]) ?? "F.Cu"; + const netCode = atomNumber(findChild(seg, "net")?.[1]); + const net = netCode !== undefined ? netIdToName.get(netCode) : undefined; + if (x1 !== undefined && y1 !== undefined && x2 !== undefined && y2 !== undefined) { + wires.push({ + x1, + y1, + x2, + y2, + layer, + width, + ...(net !== undefined ? { net } : {}), + }); + } + } + + const vias: ElectronicsVia[] = []; + for (const via of findChildren(root, "via")) { + const at = findChild(via, "at"); + const x = atomNumber(at?.[1]); + const y = atomNumber(at?.[2]); + const size = atomNumber(findChild(via, "size")?.[1]) ?? 0.6; + const drill = atomNumber(findChild(via, "drill")?.[1]); + const netCode = atomNumber(findChild(via, "net")?.[1]); + const net = netCode !== undefined ? netIdToName.get(netCode) : undefined; + if (x !== undefined && y !== undefined) { + vias.push({ + x, + y, + size, + ...(drill !== undefined ? { drill } : {}), + ...(net !== undefined ? { net } : {}), + }); + } + } + + const boardOutline: ElectronicsWireSegment[] = []; + for (const line of findChildren(root, "gr_line")) { + const layer = atomString(findChild(line, "layer")?.[1]); + if (layer !== "Edge.Cuts") continue; + const start = findChild(line, "start"); + const end = findChild(line, "end"); + const x1 = atomNumber(start?.[1]); + const y1 = atomNumber(start?.[2]); + const x2 = atomNumber(end?.[1]); + const y2 = atomNumber(end?.[2]); + if (x1 !== undefined && y1 !== undefined && x2 !== undefined && y2 !== undefined) { + boardOutline.push({ x1, y1, x2, y2, layer: "Edge.Cuts", width: 0.15 }); + } + } + for (const rect of findChildren(root, "gr_rect")) { + const layer = atomString(findChild(rect, "layer")?.[1]); + if (layer !== "Edge.Cuts") continue; + const start = findChild(rect, "start"); + const end = findChild(rect, "end"); + const x1 = atomNumber(start?.[1]); + const y1 = atomNumber(start?.[2]); + const x2 = atomNumber(end?.[1]); + const y2 = atomNumber(end?.[2]); + if (x1 !== undefined && y1 !== undefined && x2 !== undefined && y2 !== undefined) { + boardOutline.push( + { x1, y1, x2, y2: y1, layer: "Edge.Cuts", width: 0.15 }, + { x1: x2, y1, x2, y2, layer: "Edge.Cuts", width: 0.15 }, + { x1: x2, y1: y2, x2: x1, y2, layer: "Edge.Cuts", width: 0.15 }, + { x1, y1: y2, x2: x1, y2: y1, layer: "Edge.Cuts", width: 0.15 }, + ); + } + } + + const nets: ElectronicsNet[] = Array.from(netPinsMap.entries()) + .map(([name, pins]) => { + const code = netCodeMap.get(name); + return { + name, + ...(code !== undefined ? { code } : {}), + isPower: isPowerNetName(name), + isGround: isGroundNetName(name), + pins, + }; + }) + .toSorted((a, b) => a.name.localeCompare(b.name)); + + return { + format: "kicad_pcb", + filePath, + ...(title !== undefined ? { title } : {}), + layers: layers.length > 0 ? layers : ["F.Cu", "B.Cu", "Edge.Cuts"], + bounds: computeBounds({ + components, + wires, + vias, + labels: [], + boardOutline, + }), + components, + nets, + wires, + vias, + junctions: [], + noConnects: [], + labels: [], + boardOutline, + bom: buildBom(components), + parseWarnings, + }; +} + +function spicePinNamesForType( + prefix: string, +): ReadonlyArray<{ name: string; type: ElectronicsPinElectricalType }> { + switch (prefix) { + case "V": + case "I": + return [ + { name: "+", type: "power_out" }, + { name: "-", type: "passive" }, + ]; + case "D": + return [ + { name: "A", type: "passive" }, + { name: "K", type: "passive" }, + ]; + case "Q": + return [ + { name: "C", type: "passive" }, + { name: "B", type: "input" }, + { name: "E", type: "passive" }, + ]; + case "M": + return [ + { name: "D", type: "passive" }, + { name: "G", type: "input" }, + { name: "S", type: "passive" }, + { name: "B", type: "passive" }, + ]; + default: + return [ + { name: "1", type: "passive" }, + { name: "2", type: "passive" }, + ]; + } +} + +function parseSpiceNetlist(filePath: string, content: string): ElectronicsCircuitModel { + const rawLines = content.replace(/\r\n/g, "\n").split("\n"); + const logicalLines: string[] = []; + let title: string | undefined; + + for (let i = 0; i < rawLines.length; i += 1) { + const trimmed = rawLines[i]!.trim(); + if (i === 0 && trimmed.length > 0 && !trimmed.startsWith(".")) { + title = trimmed.replace(/^\*+\s*/u, "").trim(); + continue; + } + if (trimmed.length === 0 || trimmed.startsWith("*")) continue; + // Strip inline semicolon or '$' comments + const withoutComment = trimmed.replace(/\s+[;$].*$/u, "").trim(); + if (withoutComment.length === 0) continue; + if (withoutComment.startsWith("+") && logicalLines.length > 0) { + logicalLines[logicalLines.length - 1] += ` ${withoutComment.slice(1).trim()}`; + } else { + logicalLines.push(withoutComment); + } + } + + const components: ElectronicsComponent[] = []; + const netPinsMap = new Map(); + const parseWarnings: string[] = []; + const params = new Map(); + let inControlBlock = false; + let inSubckt = false; + + for (const line of logicalLines) { + const lower = line.toLowerCase(); + if (lower.startsWith(".control")) { + inControlBlock = true; + continue; + } + if (lower.startsWith(".endc")) { + inControlBlock = false; + continue; + } + if (inControlBlock) continue; + if (lower.startsWith(".subckt")) { + inSubckt = true; + continue; + } + if (lower.startsWith(".ends")) { + inSubckt = false; + continue; + } + if (inSubckt) continue; + if (lower.startsWith(".param")) { + const rest = line.slice(6); + for (const m of rest.matchAll(/([A-Za-z_]\w*)\s*=\s*([^\s]+)/gu)) { + params.set(m[1]!.toLowerCase(), m[2]!); + } + continue; + } + if (line.startsWith(".")) continue; + + const tokens = line.split(/\s+/u).filter(Boolean); + if (tokens.length < 4) continue; + const ref = tokens[0]!; + const prefix = ref[0]!.toUpperCase(); + + let nodeCount = 2; + if (prefix === "Q") nodeCount = 3; + else if (prefix === "M") nodeCount = 4; + else if (prefix === "X") nodeCount = Math.max(2, tokens.length - 2); + + if (tokens.length < nodeCount + 2) { + parseWarnings.push(`Skipped malformed SPICE element: ${line}`); + continue; + } + + const nodeNames = tokens.slice(1, 1 + nodeCount).map((n) => (n === "0" ? "GND" : n)); + let value = tokens.slice(1 + nodeCount).join(" "); + // Substitute simple {param} references + value = value.replace( + /\{([A-Za-z_]\w*)\}/gu, + (full, key: string) => params.get(key.toLowerCase()) ?? full, + ); + + const pinDefs = spicePinNamesForType(prefix); + const col = components.length % 4; + const row = Math.floor(components.length / 4); + const cx = 30 + col * 52; + const cy = 26 + row * 38; + + const pins: ElectronicsPin[] = nodeNames.map((netName, idx) => { + const def = pinDefs[idx] ?? { name: String(idx + 1), type: "passive" as const }; + const px = idx % 2 === 0 ? cx - 14 : cx + 14; + const py = cy + (idx >= 2 ? 10 : 0); + let list = netPinsMap.get(netName); + if (!list) { + list = []; + netPinsMap.set(netName, list); + } + list.push({ + ref, + pin: String(idx + 1), + pinName: def.name, + electricalType: def.type, + }); + return { + number: String(idx + 1), + name: def.name, + electricalType: def.type, + net: netName, + x: px, + y: py, + }; + }); + + components.push({ + ref, + value, + kind: inferComponentKind(ref, undefined, value), + x: cx, + y: cy, + rotation: 0, + pins, + }); + } + + // Synthesize orthogonal schematic wires connecting pins on the same net + const wires: ElectronicsWireSegment[] = []; + const labels: ElectronicsLabelMarker[] = []; + const pinPosByKey = new Map(); + for (const c of components) { + for (const p of c.pins) { + if (p.x !== undefined && p.y !== undefined) { + pinPosByKey.set(`${c.ref}:${p.number}`, { x: p.x, y: p.y }); + } + } + } + + for (const [netName, netPins] of netPinsMap.entries()) { + const pts = netPins + .map((np) => pinPosByKey.get(`${np.ref}:${np.pin}`)) + .filter((pt): pt is ElectronicsPoint => pt !== undefined); + if (pts.length > 0) { + labels.push({ + text: netName, + kind: isGroundNetName(netName) || isPowerNetName(netName) ? "power" : "local", + x: pts[0]!.x, + y: pts[0]!.y - 4, + }); + } + if (!isGroundNetName(netName)) { + for (let i = 0; i + 1 < pts.length; i += 1) { + const a = pts[i]!; + const b = pts[i + 1]!; + const midX = Number(((a.x + b.x) / 2).toFixed(3)); + wires.push( + { x1: a.x, y1: a.y, x2: midX, y2: a.y, layer: "wire", net: netName }, + { x1: midX, y1: a.y, x2: midX, y2: b.y, layer: "wire", net: netName }, + { x1: midX, y1: b.y, x2: b.x, y2: b.y, layer: "wire", net: netName }, + ); + } + } + } + + const nets: ElectronicsNet[] = Array.from(netPinsMap.entries()) + .map(([name, pins]) => ({ + name, + isPower: isPowerNetName(name), + isGround: isGroundNetName(name), + pins, + })) + .toSorted((a, b) => a.name.localeCompare(b.name)); + + return { + format: "spice", + filePath, + ...(title !== undefined && title.length > 0 ? { title } : {}), + layers: ["schematic", "wire"], + bounds: computeBounds({ + components, + wires, + vias: [], + labels, + boardOutline: [], + }), + components, + nets, + wires, + vias: [], + junctions: [], + noConnects: [], + labels, + boardOutline: [], + bom: buildBom(components), + parseWarnings, + }; +} + +interface RawCircuitJsonElement { + readonly type?: string; + readonly [key: string]: unknown; +} + +function parseCircuitJson(filePath: string, content: string): ElectronicsCircuitModel { + let raw: unknown; + try { + raw = JSON.parse(content); + } catch (err) { + throw new Error(`Invalid Circuit JSON: ${err instanceof Error ? err.message : String(err)}`, { + cause: err, + }); + } + + const elements: ReadonlyArray = Array.isArray(raw) + ? raw + : typeof raw === "object" && + raw !== null && + Array.isArray((raw as { elements?: unknown }).elements) + ? (raw as { elements: RawCircuitJsonElement[] }).elements + : []; + + if (elements.length === 0) { + throw new Error("Circuit JSON must be a non-empty array of Circuit JSON elements."); + } + + const sourceComponents = new Map(); + const sourcePorts = new Map(); + const sourceNets = new Map(); + const schComponents = new Map(); + const pcbComponents = new Map(); + const schPorts = new Map(); + const pcbPadsByPort = new Map(); + + for (const el of elements) { + if (!el || typeof el.type !== "string") continue; + if (el.type === "source_component" && typeof el.source_component_id === "string") { + sourceComponents.set(el.source_component_id, el); + } else if (el.type === "source_port" && typeof el.source_port_id === "string") { + sourcePorts.set(el.source_port_id, el); + } else if (el.type === "source_net" && typeof el.source_net_id === "string") { + sourceNets.set(el.source_net_id, typeof el.name === "string" ? el.name : el.source_net_id); + } else if (el.type === "schematic_component" && typeof el.source_component_id === "string") { + schComponents.set(el.source_component_id, el); + } else if (el.type === "pcb_component" && typeof el.source_component_id === "string") { + pcbComponents.set(el.source_component_id, el); + } else if (el.type === "schematic_port" && typeof el.source_port_id === "string") { + schPorts.set(el.source_port_id, el); + } else if ( + (el.type === "pcb_smtpad" || el.type === "pcb_plated_hole") && + typeof el.pcb_port_id === "string" + ) { + pcbPadsByPort.set(el.pcb_port_id, el); + } + } + + // Union-find across source_ports via source_trace + const portIndex = new Map(); + let nextPortId = 1; + const getPid = (id: string) => { + const existing = portIndex.get(id); + if (existing !== undefined) return existing; + const assigned = nextPortId; + nextPortId += 1; + portIndex.set(id, assigned); + return assigned; + }; + const uf = new UnionFind(); + const rootNetLabel = new Map(); + + for (const el of elements) { + if (el.type !== "source_trace") continue; + const connectedPorts = Array.isArray(el.connected_source_port_ids) + ? el.connected_source_port_ids.filter((id): id is string => typeof id === "string") + : []; + const connectedNets = Array.isArray(el.connected_source_net_ids) + ? el.connected_source_net_ids.filter((id): id is string => typeof id === "string") + : []; + + for (let i = 0; i + 1 < connectedPorts.length; i += 1) { + uf.union(getPid(connectedPorts[i]!), getPid(connectedPorts[i + 1]!)); + } + const explicitNetName = + (typeof el.display_name === "string" && el.display_name.trim().length > 0 + ? el.display_name.trim() + : undefined) ?? + connectedNets.map((nid) => sourceNets.get(nid)).find((n): n is string => Boolean(n)); + + if (explicitNetName && connectedPorts.length > 0) { + rootNetLabel.set(uf.find(getPid(connectedPorts[0]!)), explicitNetName); + } + } + + const netPinsMap = new Map(); + const portToNet = new Map(); + const rootToAutoName = new Map(); + let netCounter = 1; + + for (const [portId, sp] of sourcePorts.entries()) { + const pid = portIndex.get(portId); + if (pid === undefined) continue; + const root = uf.find(pid); + let netName = rootNetLabel.get(root) ?? rootToAutoName.get(root); + if (!netName) { + netName = `NET_${netCounter}`; + netCounter += 1; + rootToAutoName.set(root, netName); + } + portToNet.set(portId, netName); + const comp = + typeof sp.source_component_id === "string" + ? sourceComponents.get(sp.source_component_id) + : undefined; + const ref = typeof comp?.name === "string" ? comp.name : "U?"; + const pinNum = + typeof sp.pin_number === "number" || typeof sp.pin_number === "string" + ? String(sp.pin_number) + : typeof sp.name === "string" + ? sp.name + : "1"; + const pinName = typeof sp.name === "string" ? sp.name : undefined; + let list = netPinsMap.get(netName); + if (!list) { + list = []; + netPinsMap.set(netName, list); + } + list.push({ + ref, + pin: pinNum, + ...(pinName !== undefined ? { pinName } : {}), + electricalType: "passive", + }); + } + + const components: ElectronicsComponent[] = []; + let fallbackIdx = 0; + for (const [compId, sc] of sourceComponents.entries()) { + const ref = typeof sc.name === "string" ? sc.name : `C_${fallbackIdx + 1}`; + const value = + typeof sc.display_value === "string" + ? sc.display_value + : typeof sc.resistance === "number" + ? `${sc.resistance}Ω` + : typeof sc.capacitance === "number" + ? `${sc.capacitance}F` + : typeof sc.ftype === "string" + ? sc.ftype + : ref; + const geom = pcbComponents.get(compId) ?? schComponents.get(compId); + const center = geom?.center as { x?: number; y?: number } | undefined; + const cx = typeof center?.x === "number" ? center.x : (fallbackIdx % 4) * 30; + const cy = typeof center?.y === "number" ? center.y : Math.floor(fallbackIdx / 4) * 24; + fallbackIdx += 1; + + const pins: ElectronicsPin[] = []; + let pIdx = 0; + for (const [portId, sp] of sourcePorts.entries()) { + if (sp.source_component_id !== compId) continue; + const pinNum = + typeof sp.pin_number === "number" || typeof sp.pin_number === "string" + ? String(sp.pin_number) + : typeof sp.name === "string" + ? sp.name + : String(pIdx + 1); + const pinName = typeof sp.name === "string" ? sp.name : undefined; + const schP = schPorts.get(portId); + const schCenter = schP?.center as { x?: number; y?: number } | undefined; + const px = typeof schCenter?.x === "number" ? schCenter.x : cx + (pIdx % 2 === 0 ? -6 : 6); + const py = typeof schCenter?.y === "number" ? schCenter.y : cy + Math.floor(pIdx / 2) * 4; + const net = portToNet.get(portId); + pins.push({ + number: pinNum, + ...(pinName !== undefined ? { name: pinName } : {}), + electricalType: "passive", + ...(net !== undefined ? { net } : {}), + x: px, + y: py, + }); + pIdx += 1; + } + + components.push({ + ref, + value, + kind: inferComponentKind(ref, typeof sc.ftype === "string" ? sc.ftype : undefined, value), + x: cx, + y: cy, + rotation: typeof geom?.rotation === "number" ? geom.rotation : 0, + layer: typeof geom?.layer === "string" ? geom.layer : "F.Cu", + pins, + }); + } + + const wires: ElectronicsWireSegment[] = []; + const boardOutline: ElectronicsWireSegment[] = []; + + for (const el of elements) { + if (el.type === "pcb_trace" && Array.isArray(el.route)) { + const route = el.route as ReadonlyArray<{ + x?: number; + y?: number; + layer?: string; + width?: number; + }>; + for (let i = 0; i + 1 < route.length; i += 1) { + const a = route[i]!; + const b = route[i + 1]!; + if ( + typeof a.x === "number" && + typeof a.y === "number" && + typeof b.x === "number" && + typeof b.y === "number" + ) { + wires.push({ + x1: a.x, + y1: a.y, + x2: b.x, + y2: b.y, + layer: a.layer === "bottom" ? "B.Cu" : "F.Cu", + width: typeof a.width === "number" ? a.width : 0.25, + }); + } + } + } else if (el.type === "schematic_trace" && Array.isArray(el.edges)) { + const edges = el.edges as ReadonlyArray<{ + from?: { x?: number; y?: number }; + to?: { x?: number; y?: number }; + }>; + for (const edge of edges) { + if ( + typeof edge.from?.x === "number" && + typeof edge.from?.y === "number" && + typeof edge.to?.x === "number" && + typeof edge.to?.y === "number" + ) { + wires.push({ + x1: edge.from.x, + y1: edge.from.y, + x2: edge.to.x, + y2: edge.to.y, + layer: "wire", + }); + } + } + } else if (el.type === "pcb_board") { + const center = (el.center as { x?: number; y?: number } | undefined) ?? { x: 0, y: 0 }; + const w = typeof el.width === "number" ? el.width : 50; + const h = typeof el.height === "number" ? el.height : 30; + const x1 = (center.x ?? 0) - w / 2; + const y1 = (center.y ?? 0) - h / 2; + const x2 = (center.x ?? 0) + w / 2; + const y2 = (center.y ?? 0) + h / 2; + boardOutline.push( + { x1, y1, x2, y2: y1, layer: "Edge.Cuts", width: 0.15 }, + { x1: x2, y1, x2, y2, layer: "Edge.Cuts", width: 0.15 }, + { x1: x2, y1: y2, x2: x1, y2, layer: "Edge.Cuts", width: 0.15 }, + { x1, y1: y2, x2: x1, y2: y1, layer: "Edge.Cuts", width: 0.15 }, + ); + } + } + + const nets: ElectronicsNet[] = Array.from(netPinsMap.entries()) + .map(([name, pins]) => ({ + name, + isPower: isPowerNetName(name), + isGround: isGroundNetName(name), + pins, + })) + .toSorted((a, b) => a.name.localeCompare(b.name)); + + return { + format: "circuit_json", + filePath, + layers: boardOutline.length > 0 ? ["F.Cu", "B.Cu", "Edge.Cuts"] : ["schematic", "wire"], + bounds: computeBounds({ + components, + wires, + vias: [], + labels: [], + boardOutline, + }), + components, + nets, + wires, + vias: [], + junctions: [], + noConnects: [], + labels: [], + boardOutline, + bom: buildBom(components), + parseWarnings: [], + }; +} + +export function parseElectronicsFile(filePath: string, content: string): ElectronicsCircuitModel { + const format = detectElectronicsFormat(filePath); + if (!format) { + throw new Error( + `Unsupported electronics format for "${filePath}". Supported: .kicad_sch, .kicad_pcb, .cir/.sp/.spice/.net, *.circuit.json.`, + ); + } + switch (format) { + case "kicad_sch": + return parseKiCadSchematic(filePath, content); + case "kicad_pcb": + return parseKiCadPcb(filePath, content); + case "spice": + return parseSpiceNetlist(filePath, content); + case "circuit_json": + return parseCircuitJson(filePath, content); + } +} diff --git a/apps/server/src/electronics/pathTracer.ts b/apps/server/src/electronics/pathTracer.ts new file mode 100644 index 0000000000000..50e93d49f57a9 --- /dev/null +++ b/apps/server/src/electronics/pathTracer.ts @@ -0,0 +1,349 @@ +import type { + ElectronicsCircuitModel, + ElectronicsComponent, + ElectronicsComponentKind, + ElectronicsPathHop, + ElectronicsTracePathResult, +} from "@t3tools/contracts"; + +import { isGroundNetName, parseEngineeringNumber } from "./parsers.ts"; + +const TRAVERSABLE_SERIES_KINDS: ReadonlySet = new Set([ + "resistor", + "inductor", + "fuse", + "switch", + "diode", +]); + +interface ResolvedEndpoint { + readonly query: string; + readonly nets: ReadonlySet; + readonly componentRef?: string; + readonly pinNumber?: string; + readonly warnings: string[]; +} + +function resolveEndpoint(model: ElectronicsCircuitModel, rawQuery: string): ResolvedEndpoint { + const query = rawQuery.trim(); + const warnings: string[] = []; + const nets = new Set(); + + // 1. Exact net match (case-insensitive) + const exactNet = model.nets.find((n) => n.name.toLowerCase() === query.toLowerCase()); + if (exactNet) { + nets.add(exactNet.name); + return { query, nets, warnings }; + } + + // 2. Component.Pin or Component:Pin syntax (e.g. U1.3, U1.VOUT, J1:1) + const dotIdx = query.search(/[.:]/u); + if (dotIdx > 0) { + const refPart = query.slice(0, dotIdx).trim(); + const pinPart = query.slice(dotIdx + 1).trim(); + const comp = model.components.find((c) => c.ref.toLowerCase() === refPart.toLowerCase()); + if (!comp) { + warnings.push(`Component "${refPart}" was not found in ${model.filePath}.`); + return { query, nets, warnings }; + } + const pin = comp.pins.find( + (p) => + p.number.toLowerCase() === pinPart.toLowerCase() || + (p.name !== undefined && p.name.toLowerCase() === pinPart.toLowerCase()), + ); + if (!pin) { + warnings.push(`Pin "${pinPart}" was not found on component ${comp.ref}.`); + return { query, nets, componentRef: comp.ref, warnings }; + } + if (pin.net) { + nets.add(pin.net); + } else { + warnings.push( + `Pin ${comp.ref}.${pin.number}${pin.name ? ` (${pin.name})` : ""} is unconnected.`, + ); + } + return { query, nets, componentRef: comp.ref, pinNumber: pin.number, warnings }; + } + + // 3. Component reference match (all nets touching this component) + const comp = model.components.find((c) => c.ref.toLowerCase() === query.toLowerCase()); + if (comp) { + for (const pin of comp.pins) { + if (pin.net) nets.add(pin.net); + } + if (nets.size === 0) { + warnings.push(`Component ${comp.ref} has no connected nets.`); + } + return { query, nets, componentRef: comp.ref, warnings }; + } + + warnings.push( + `Endpoint "${query}" did not match any net, component, or pin in ${model.filePath}.`, + ); + return { query, nets, warnings }; +} + +function isSeriesTraversable(comp: ElectronicsComponent): boolean { + if (comp.pins.length !== 2) return false; + if (TRAVERSABLE_SERIES_KINDS.has(comp.kind)) return true; + // Also allow 2-pin jumper connectors (JP1 / J_BRIDGE) + if (comp.kind === "connector" && /^JP\d/iu.test(comp.ref)) return true; + return false; +} + +export function traceCircuitPath( + model: ElectronicsCircuitModel, + options: { + readonly from: string; + readonly to?: string; + readonly traversePassives?: boolean; + readonly maxHops?: number; + }, +): ElectronicsTracePathResult { + const traversePassives = options.traversePassives ?? true; + const maxHops = options.maxHops ?? 8; + + const fromResolved = resolveEndpoint(model, options.from); + const warnings = [...fromResolved.warnings]; + + // Single-endpoint inspection mode: return the net(s) and directly connected components + if (options.to === undefined || options.to.trim().length === 0) { + const highlightedNets = Array.from(fromResolved.nets); + const highlightedCompSet = new Set(); + if (fromResolved.componentRef) highlightedCompSet.add(fromResolved.componentRef); + const hops: ElectronicsPathHop[] = []; + for (const netName of highlightedNets) { + hops.push({ kind: "net", name: netName }); + const net = model.nets.find((n) => n.name === netName); + if (net) { + for (const p of net.pins) highlightedCompSet.add(p.ref); + } + } + return { + filePath: model.filePath, + from: options.from, + connected: highlightedNets.length > 0, + ...(highlightedNets.length === 1 ? { directNet: highlightedNets[0]! } : {}), + fromNets: highlightedNets, + toNets: [], + hops, + highlightedNets, + highlightedComponents: Array.from(highlightedCompSet), + warnings, + }; + } + + const toResolved = resolveEndpoint(model, options.to); + warnings.push(...toResolved.warnings); + + const fromNets = Array.from(fromResolved.nets); + const toNets = Array.from(toResolved.nets); + + if (fromNets.length === 0 || toNets.length === 0) { + return { + filePath: model.filePath, + from: options.from, + to: options.to, + connected: false, + fromNets, + toNets, + hops: [], + highlightedNets: [...fromNets, ...toNets], + highlightedComponents: [ + ...(fromResolved.componentRef ? [fromResolved.componentRef] : []), + ...(toResolved.componentRef ? [toResolved.componentRef] : []), + ], + warnings, + }; + } + + // 1. Check direct same-net connectivity + for (const netName of fromNets) { + if (toResolved.nets.has(netName)) { + const highlightedComponents = new Set(); + if (fromResolved.componentRef) highlightedComponents.add(fromResolved.componentRef); + if (toResolved.componentRef) highlightedComponents.add(toResolved.componentRef); + return { + filePath: model.filePath, + from: options.from, + to: options.to, + connected: true, + directNet: netName, + fromNets, + toNets, + hops: [{ kind: "net", name: netName }], + highlightedNets: [netName], + highlightedComponents: Array.from(highlightedComponents), + estimatedResistanceOhms: 0, + warnings, + }; + } + } + + if (!traversePassives) { + warnings.push( + `No direct single-net connection between "${options.from}" and "${options.to}" (passive traversal disabled).`, + ); + return { + filePath: model.filePath, + from: options.from, + to: options.to, + connected: false, + fromNets, + toNets, + hops: [], + highlightedNets: [...fromNets, ...toNets], + highlightedComponents: [ + ...(fromResolved.componentRef ? [fromResolved.componentRef] : []), + ...(toResolved.componentRef ? [toResolved.componentRef] : []), + ], + warnings, + }; + } + + // 2. Build net-to-net adjacency through 2-pin series passives + interface Edge { + readonly comp: ElectronicsComponent; + readonly fromPin: string; + readonly toPin: string; + readonly nextNet: string; + } + + const adj = new Map(); + const addEdge = (net: string, edge: Edge) => { + let list = adj.get(net); + if (!list) { + list = []; + adj.set(net, list); + } + list.push(edge); + }; + + for (const comp of model.components) { + if (!isSeriesTraversable(comp)) continue; + const p1 = comp.pins[0]!; + const p2 = comp.pins[1]!; + if (!p1.net || !p2.net || p1.net === p2.net) continue; + addEdge(p1.net, { comp, fromPin: p1.number, toPin: p2.number, nextNet: p2.net }); + addEdge(p2.net, { comp, fromPin: p2.number, toPin: p1.number, nextNet: p1.net }); + } + + // BFS from all source nets to any target net + interface QueueNode { + readonly net: string; + readonly depth: number; + readonly hops: ElectronicsPathHop[]; + } + + const targetIsGround = toNets.some((n) => isGroundNetName(n)); + const visited = new Set(fromNets); + const queue: QueueNode[] = fromNets.map((net) => ({ + net, + depth: 0, + hops: [{ kind: "net", name: net }], + })); + + let winningHops: ElectronicsPathHop[] | null = null; + while (queue.length > 0) { + const current = queue.shift()!; + if (current.depth >= maxHops) continue; + + for (const edge of adj.get(current.net) ?? []) { + // Do not route through GND as an intermediate node unless GND is the target + if (isGroundNetName(edge.nextNet) && !toResolved.nets.has(edge.nextNet) && !targetIsGround) { + continue; + } + const nextHops: ElectronicsPathHop[] = [ + ...current.hops, + { + kind: "component", + name: edge.comp.ref, + value: edge.comp.value, + fromPin: edge.fromPin, + toPin: edge.toPin, + componentKind: edge.comp.kind, + }, + { kind: "net", name: edge.nextNet }, + ]; + if (toResolved.nets.has(edge.nextNet)) { + winningHops = nextHops; + break; + } + if (!visited.has(edge.nextNet)) { + visited.add(edge.nextNet); + queue.push({ net: edge.nextNet, depth: current.depth + 1, hops: nextHops }); + } + } + if (winningHops) break; + } + + if (!winningHops) { + warnings.push( + `No electrical path found from "${options.from}" to "${options.to}" within ${maxHops} passive hops.`, + ); + return { + filePath: model.filePath, + from: options.from, + to: options.to, + connected: false, + fromNets, + toNets, + hops: [], + highlightedNets: [...fromNets, ...toNets], + highlightedComponents: [ + ...(fromResolved.componentRef ? [fromResolved.componentRef] : []), + ...(toResolved.componentRef ? [toResolved.componentRef] : []), + ], + warnings, + }; + } + + const highlightedNets: string[] = []; + const highlightedComponents = new Set(); + if (fromResolved.componentRef) highlightedComponents.add(fromResolved.componentRef); + if (toResolved.componentRef) highlightedComponents.add(toResolved.componentRef); + + let totalResistanceOhms = 0; + let hasResistiveEstimate = true; + + for (const hop of winningHops) { + if (hop.kind === "net") { + highlightedNets.push(hop.name); + } else { + highlightedComponents.add(hop.name); + if (hop.componentKind === "resistor") { + const val = hop.value ? parseEngineeringNumber(hop.value) : null; + if (val !== null) totalResistanceOhms += val; + else hasResistiveEstimate = false; + } else if (hop.componentKind === "diode") { + warnings.push( + `Path crosses diode ${hop.name} (${hop.fromPin}→${hop.toPin}); verify forward polarity.`, + ); + } else if (hop.componentKind === "switch") { + warnings.push(`Path crosses switch ${hop.name}; connectivity depends on switch state.`); + } + } + } + + if (hasResistiveEstimate && totalResistanceOhms >= 100_000) { + warnings.push( + `High series resistance along path (~${(totalResistanceOhms / 1000).toFixed(1)} kΩ); verify current drive.`, + ); + } + + return { + filePath: model.filePath, + from: options.from, + to: options.to, + connected: true, + fromNets, + toNets, + hops: winningHops, + highlightedNets, + highlightedComponents: Array.from(highlightedComponents), + ...(hasResistiveEstimate + ? { estimatedResistanceOhms: Number(totalResistanceOhms.toFixed(4)) } + : {}), + warnings, + }; +} diff --git a/apps/server/src/electronics/sexpr.ts b/apps/server/src/electronics/sexpr.ts new file mode 100644 index 0000000000000..c30c7a97f77d6 --- /dev/null +++ b/apps/server/src/electronics/sexpr.ts @@ -0,0 +1,132 @@ +/** + * Iterative, depth- and size-bounded KiCad S-expression parser. + * Parses `.kicad_sch` and `.kicad_pcb` files without recursion stack overflows. + */ + +export type SExprNode = string | SExprList; +export interface SExprList extends ReadonlyArray {} + +const MAX_SEXPR_BYTES = 20 * 1024 * 1024; +const MAX_SEXPR_DEPTH = 128; + +export function parseSExpr(input: string): SExprList { + if (input.length > MAX_SEXPR_BYTES) { + throw new Error(`S-expression exceeds maximum supported size (${MAX_SEXPR_BYTES} bytes).`); + } + + const root: SExprNode[] = []; + const stack: SExprNode[][] = [root]; + const len = input.length; + let i = 0; + + while (i < len) { + const ch = input.charCodeAt(i); + // Whitespace + if (ch === 32 || ch === 9 || ch === 10 || ch === 13) { + i += 1; + continue; + } + // Line comment starting with '#' + if (ch === 35) { + while (i < len && input.charCodeAt(i) !== 10) i += 1; + continue; + } + // '(' + if (ch === 40) { + if (stack.length >= MAX_SEXPR_DEPTH) { + throw new Error(`S-expression nesting exceeded limit (${MAX_SEXPR_DEPTH}).`); + } + const next: SExprNode[] = []; + stack[stack.length - 1]!.push(next); + stack.push(next); + i += 1; + continue; + } + // ')' + if (ch === 41) { + if (stack.length <= 1) { + throw new Error(`Unexpected ')' in S-expression at offset ${i}.`); + } + stack.pop(); + i += 1; + continue; + } + // Quoted string '"' + if (ch === 34) { + i += 1; + let str = ""; + let closed = false; + while (i < len) { + const c = input.charCodeAt(i); + if (c === 92 && i + 1 < len) { + // Escape sequence + const escaped = input[i + 1]!; + if (escaped === "n") str += "\n"; + else if (escaped === "r") str += "\r"; + else if (escaped === "t") str += "\t"; + else str += escaped; + i += 2; + continue; + } + if (c === 34) { + i += 1; + closed = true; + break; + } + str += input[i]!; + i += 1; + } + if (!closed) { + throw new Error("Unterminated quoted string in S-expression."); + } + stack[stack.length - 1]!.push(str); + continue; + } + // Atom + const start = i; + while (i < len) { + const c = input.charCodeAt(i); + if (c === 32 || c === 9 || c === 10 || c === 13 || c === 40 || c === 41) { + break; + } + i += 1; + } + stack[stack.length - 1]!.push(input.slice(start, i)); + } + + if (stack.length !== 1) { + throw new Error("Unclosed '(' in S-expression."); + } + return root; +} + +export function isSExprList(node: SExprNode | undefined): node is SExprList { + return Array.isArray(node); +} + +export function findChild(list: SExprList, tag: string): SExprList | undefined { + for (let i = 1; i < list.length; i += 1) { + const child = list[i]; + if (Array.isArray(child) && child[0] === tag) return child; + } + return undefined; +} + +export function findChildren(list: SExprList, tag: string): SExprList[] { + const out: SExprList[] = []; + for (let i = 1; i < list.length; i += 1) { + const child = list[i]; + if (Array.isArray(child) && child[0] === tag) out.push(child); + } + return out; +} + +export function atomString(node: SExprNode | undefined): string | undefined { + return typeof node === "string" ? node : undefined; +} + +export function atomNumber(node: SExprNode | undefined): number | undefined { + if (typeof node !== "string") return undefined; + const parsed = Number(node); + return Number.isFinite(parsed) ? parsed : undefined; +} diff --git a/apps/server/src/electronics/toolchain.ts b/apps/server/src/electronics/toolchain.ts new file mode 100644 index 0000000000000..051a3013d494c --- /dev/null +++ b/apps/server/src/electronics/toolchain.ts @@ -0,0 +1,296 @@ +import type { + ElectronicsCircuitModel, + ElectronicsSimulationKind, + ElectronicsSimulationResult, + ElectronicsToolBinaryStatus, + ElectronicsValidationIssue, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +const PROBE_TIMEOUT = Duration.seconds(5); +const RUN_TIMEOUT = Duration.seconds(20); + +/** + * Executes a single command without a shell and returns captured stdout, or fails cleanly on timeout/error. + */ +const execToolString = Effect.fn("ElectronicsToolchain.execToolString")(function* ( + executable: string, + args: ReadonlyArray, + timeout: Duration.Duration, + cwd?: string, +) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const command = ChildProcess.make(executable, [...args], { + stdin: "ignore", + stderr: "ignore", + ...(cwd !== undefined ? { cwd } : {}), + }); + return yield* spawner.string(command).pipe(Effect.timeout(timeout)); +}); + +export const probeBinary = Effect.fn("ElectronicsToolchain.probeBinary")(function* ( + name: "kicad-cli" | "ngspice", + overridePath?: string, +): Effect.fn.Return { + const executable = overridePath && overridePath.trim().length > 0 ? overridePath.trim() : name; + const args = name === "kicad-cli" ? ["--version"] : ["-v"]; + const output = yield* execToolString(executable, args, PROBE_TIMEOUT).pipe( + Effect.map((raw) => ({ ok: true as const, raw })), + Effect.catch((err) => Effect.succeed({ ok: false as const, err: String(err) })), + ); + if (!output.ok) { + return { + name, + available: false, + ...(overridePath && overridePath.trim().length > 0 ? { path: executable } : {}), + error: output.err.slice(0, 200), + }; + } + const firstLine = output.raw + .split(/\r?\n/u) + .map((line) => line.trim()) + .find((line) => line.length > 0); + return { + name, + available: true, + path: executable, + ...(firstLine !== undefined ? { version: firstLine.slice(0, 120) } : {}), + }; +}); + +interface KiCadViolationRaw { + readonly type?: string; + readonly severity?: string; + readonly description?: string; + readonly items?: ReadonlyArray<{ + readonly description?: string; + readonly pos?: { readonly x?: number; readonly y?: number }; + }>; +} + +function mapKiCadSeverity(raw: string | undefined): "error" | "warning" | "info" { + const lower = (raw ?? "").toLowerCase(); + if (lower === "error") return "error"; + if (lower === "warning") return "warning"; + return "info"; +} + +function parseKiCadJsonViolations( + jsonText: string, + source: "kicad_erc" | "kicad_drc", +): ElectronicsValidationIssue[] { + let parsed: unknown; + try { + parsed = JSON.parse(jsonText); + } catch { + return []; + } + if (typeof parsed !== "object" || parsed === null) return []; + + const violations: KiCadViolationRaw[] = []; + const obj = parsed as { + violations?: KiCadViolationRaw[]; + unconnected_items?: KiCadViolationRaw[]; + sheets?: Array<{ violations?: KiCadViolationRaw[] }>; + }; + + if (Array.isArray(obj.violations)) violations.push(...obj.violations); + if (Array.isArray(obj.unconnected_items)) violations.push(...obj.unconnected_items); + if (Array.isArray(obj.sheets)) { + for (const sheet of obj.sheets) { + if (Array.isArray(sheet.violations)) violations.push(...sheet.violations); + } + } + + return violations.map((v, idx) => { + const pos = v.items?.[0]?.pos; + const detail = v.items + ?.map((i) => i.description) + .filter((d): d is string => typeof d === "string" && d.length > 0) + .slice(0, 2) + .join("; "); + const baseMsg = v.description ?? v.type ?? "KiCad rule violation"; + return { + id: `${source}-${idx + 1}`, + code: v.type ?? source, + severity: mapKiCadSeverity(v.severity), + source, + message: detail ? `${baseMsg} (${detail})` : baseMsg, + refs: [], + ...(typeof pos?.x === "number" ? { x: pos.x } : {}), + ...(typeof pos?.y === "number" ? { y: pos.y } : {}), + }; + }); +} + +export const runKiCadExternalValidation = Effect.fn( + "ElectronicsToolchain.runKiCadExternalValidation", +)(function* (input: { + readonly absolutePath: string; + readonly format: "kicad_sch" | "kicad_pcb"; + readonly kicadCliPath?: string; +}) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const executable = + input.kicadCliPath && input.kicadCliPath.trim().length > 0 + ? input.kicadCliPath.trim() + : "kicad-cli"; + const source = input.format === "kicad_sch" ? ("kicad_erc" as const) : ("kicad_drc" as const); + + return yield* Effect.scoped( + Effect.gen(function* () { + const tmpDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-kicad-" }); + const reportPath = path.join(tmpDir, "report.json"); + const args = + input.format === "kicad_sch" + ? ["sch", "erc", "--format", "json", "--output", reportPath, input.absolutePath] + : ["pcb", "drc", "--format", "json", "--output", reportPath, input.absolutePath]; + + // kicad-cli may exit non-zero when violations exist even though report.json was written. + yield* execToolString(executable, args, RUN_TIMEOUT).pipe(Effect.ignore); + const exists = yield* fs.exists(reportPath); + if (!exists) { + return { + ran: false, + source, + issues: [] as ElectronicsValidationIssue[], + note: `kicad-cli did not produce a JSON ${source === "kicad_erc" ? "ERC" : "DRC"} report.`, + }; + } + const reportText = yield* fs.readFileString(reportPath); + const issues = parseKiCadJsonViolations(reportText, source); + return { + ran: true, + source, + issues, + note: undefined as string | undefined, + }; + }), + ).pipe( + Effect.catch((err) => + Effect.succeed({ + ran: false, + source, + issues: [] as ElectronicsValidationIssue[], + note: `kicad-cli check failed: ${String(err).slice(0, 180)}`, + }), + ), + ); +}); + +export const runNgspiceSimulation = Effect.fn("ElectronicsToolchain.runNgspiceSimulation")( + function* (input: { + readonly model: ElectronicsCircuitModel; + readonly spiceSource: string; + readonly kind: ElectronicsSimulationKind; + readonly ngspicePath?: string; + readonly outputNode?: string; + readonly startFreqHz?: number; + readonly stopFreqHz?: number; + readonly pointsPerDecade?: number; + readonly stopTimeSeconds?: number; + readonly stepTimeSeconds?: number; + }) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const executable = + input.ngspicePath && input.ngspicePath.trim().length > 0 + ? input.ngspicePath.trim() + : "ngspice"; + + return yield* Effect.scoped( + Effect.gen(function* () { + const tmpDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ngspice-" }); + const deckPath = path.join(tmpDir, "deck.cir"); + const stripped = input.spiceSource + .split(/\r?\n/u) + .filter((line) => !/^\s*\.(end|op|ac|tran|dc|control|endc)\b/iu.test(line)) + .join("\n"); + + const targetNode = + input.outputNode ?? input.model.nets.find((n) => !n.isGround)?.name ?? "out"; + + const directive = + input.kind === "dc_op" + ? ".op\n.print op all" + : input.kind === "ac_sweep" + ? `.ac dec ${input.pointsPerDecade ?? 10} ${input.startFreqHz ?? 10} ${input.stopFreqHz ?? 1_000_000}\n.print ac vdb(${targetNode}) vp(${targetNode})` + : `.tran ${input.stepTimeSeconds ?? 5e-5} ${input.stopTimeSeconds ?? 5e-3}\n.print tran v(${targetNode})`; + + const deck = `${stripped}\n${directive}\n.end\n`; + yield* fs.writeFileString(deckPath, deck); + + const stdout = yield* execToolString(executable, ["-b", deckPath], RUN_TIMEOUT); + const nodeVoltages: Array<{ node: string; voltageV: number }> = []; + const points: Array<{ x: number; y: number; phaseDeg?: number }> = []; + + for (const line of stdout.split(/\r?\n/u)) { + const opMatch = /^\s*([A-Za-z0-9_]+)\s+([+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?)\s*$/iu.exec( + line, + ); + if (input.kind === "dc_op" && opMatch) { + const node = opMatch[1]!; + const val = Number(opMatch[2]!); + if (Number.isFinite(val) && node.toLowerCase() !== "index") { + nodeVoltages.push({ node, voltageV: Number(val.toPrecision(6)) }); + } + } + const tableMatch = + /^\s*\d+\s+([+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?)\s+([+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?)(?:\s+([+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?))?/iu.exec( + line, + ); + if (input.kind !== "dc_op" && tableMatch) { + const xVal = Number(tableMatch[1]!); + const yVal = Number(tableMatch[2]!); + const third = tableMatch[3] !== undefined ? Number(tableMatch[3]) : undefined; + if (Number.isFinite(xVal) && Number.isFinite(yVal)) { + points.push({ + x: input.kind === "transient" ? Number((xVal * 1000).toPrecision(5)) : xVal, + y: Number(yVal.toPrecision(5)), + ...(third !== undefined && Number.isFinite(third) + ? { phaseDeg: Number(third.toFixed(2)) } + : {}), + }); + } + } + } + + if (nodeVoltages.length === 0 && points.length === 0) { + return null as ElectronicsSimulationResult | null; + } + + return { + filePath: input.model.filePath, + kind: input.kind, + engine: "ngspice" as const, + xAxisLabel: + input.kind === "ac_sweep" ? "Frequency" : input.kind === "transient" ? "Time" : "Node", + xAxisUnit: input.kind === "ac_sweep" ? "Hz" : input.kind === "transient" ? "ms" : "", + xAxisLog: input.kind === "ac_sweep", + nodeVoltages, + componentReadings: [], + series: + points.length > 0 + ? [ + { + label: input.kind === "ac_sweep" ? `|V(${targetNode})|` : `V(${targetNode})`, + unit: input.kind === "ac_sweep" ? "dB" : "V", + points, + }, + ] + : [], + metrics: [], + notes: [`Simulated using local ngspice (${executable}).`], + simulatedAt: DateTime.formatIso(yield* DateTime.now), + } satisfies ElectronicsSimulationResult; + }), + ).pipe(Effect.orElseSucceed(() => null as ElectronicsSimulationResult | null)); + }, +); diff --git a/apps/server/src/electronics/validator.ts b/apps/server/src/electronics/validator.ts new file mode 100644 index 0000000000000..d09c9edb1086f --- /dev/null +++ b/apps/server/src/electronics/validator.ts @@ -0,0 +1,342 @@ +import * as DateTime from "effect/DateTime"; +import type { + ElectronicsCircuitModel, + ElectronicsValidationIssue, + ElectronicsValidationReport, + ElectronicsValidationSource, +} from "@t3tools/contracts"; + +import { isGroundNetName, isPowerNetName } from "./parsers.ts"; + +function nearPoint(ax: number, ay: number, bx: number, by: number, tol = 0.25): boolean { + return Math.hypot(ax - bx, ay - by) <= tol; +} + +/** + * Deterministic static electrical & layout rule checker. + * Runs in pure TypeScript with zero external binaries required. + */ +export function runBuiltinCircuitValidation(model: ElectronicsCircuitModel): { + readonly issues: ElectronicsValidationIssue[]; + readonly notes: string[]; +} { + const issues: ElectronicsValidationIssue[] = []; + const notes: string[] = []; + let seq = 1; + const nextId = (prefix: string) => `${prefix}-${seq++}`; + + // 1. Duplicate component references + const seenRefs = new Map(); + for (const comp of model.components) { + if (comp.kind === "power_symbol" || comp.ref.startsWith("#")) continue; + const count = (seenRefs.get(comp.ref) ?? 0) + 1; + seenRefs.set(comp.ref, count); + if (count === 2) { + issues.push({ + id: nextId("dup-ref"), + code: "duplicate_reference", + severity: "error", + source: "builtin", + message: `Duplicate component designator "${comp.ref}" found on the sheet/board.`, + refs: [comp.ref], + ...(comp.x !== undefined ? { x: comp.x } : {}), + ...(comp.y !== undefined ? { y: comp.y } : {}), + }); + } + } + + // 2. Power rail shorts (e.g. GND shorted directly to +3V3 or +5V on the same net) + for (const net of model.nets) { + const parts = net.name.split(" / ").map((p) => p.trim()); + const distinctRails = parts.filter((p) => isGroundNetName(p) || isPowerNetName(p)); + if ((net.isPower && net.isGround) || distinctRails.length > 1) { + const firstRef = net.pins[0]?.ref; + const comp = firstRef ? model.components.find((c) => c.ref === firstRef) : undefined; + issues.push({ + id: nextId("rail-short"), + code: "power_rail_short", + severity: "error", + source: "builtin", + message: `Power rail short detected on net "${net.name}": distinct power/ground rails are tied together.`, + net: net.name, + refs: Array.from(new Set(net.pins.map((p) => p.ref))), + ...(comp?.x !== undefined ? { x: comp.x } : {}), + ...(comp?.y !== undefined ? { y: comp.y } : {}), + }); + } + } + + // 3. Output-to-output conflicts and undriven inputs (primarily schematic ERC) + for (const net of model.nets) { + const drivers = net.pins.filter( + (p) => p.electricalType === "output" || p.electricalType === "power_out", + ); + if (drivers.length > 1) { + const firstComp = model.components.find((c) => c.ref === drivers[0]!.ref); + issues.push({ + id: nextId("out-conflict"), + code: "output_conflict", + severity: "error", + source: "builtin", + message: `Multiple output drivers (${drivers.map((d) => `${d.ref}.${d.pin}`).join(", ")}) share net "${net.name}".`, + net: net.name, + refs: Array.from(new Set(drivers.map((d) => d.ref))), + ...(firstComp?.x !== undefined ? { x: firstComp.x } : {}), + ...(firstComp?.y !== undefined ? { y: firstComp.y } : {}), + }); + } + + const inputs = net.pins.filter((p) => p.electricalType === "input"); + const hasDriverOrPassive = net.pins.some( + (p) => + p.electricalType === "output" || + p.electricalType === "power_out" || + p.electricalType === "bidirectional" || + p.electricalType === "tri_state" || + p.electricalType === "passive" || + p.electricalType === "open_collector" || + p.electricalType === "open_emitter", + ); + if (inputs.length > 0 && !hasDriverOrPassive && !net.isPower && !net.isGround) { + const firstComp = model.components.find((c) => c.ref === inputs[0]!.ref); + issues.push({ + id: nextId("undriven"), + code: "undriven_input", + severity: "warning", + source: "builtin", + message: `Input pin(s) ${inputs.map((i) => `${i.ref}.${i.pin}`).join(", ")} on net "${net.name}" have no driver.`, + net: net.name, + refs: Array.from(new Set(inputs.map((i) => i.ref))), + ...(firstComp?.x !== undefined ? { x: firstComp.x } : {}), + ...(firstComp?.y !== undefined ? { y: firstComp.y } : {}), + }); + } + + // 4. Single-pin named nets (catches typos in net labels like SDA vs SDA_1) + if (net.pins.length === 1 && !net.isPower && !net.isGround && !net.name.startsWith("Net-(")) { + const sole = net.pins[0]!; + const comp = model.components.find((c) => c.ref === sole.ref); + const pin = comp?.pins.find((p) => p.number === sole.pin); + issues.push({ + id: nextId("single-pin"), + code: "single_pin_net", + severity: "warning", + source: "builtin", + message: `Named net "${net.name}" only connects to a single pin (${sole.ref}.${sole.pin}); check for a label typo or missing connection.`, + net: net.name, + refs: [sole.ref], + ...(pin?.x !== undefined ? { x: pin.x } : comp?.x !== undefined ? { x: comp.x } : {}), + ...(pin?.y !== undefined ? { y: pin.y } : comp?.y !== undefined ? { y: comp.y } : {}), + }); + } + } + + // 5. Floating / unconnected component pins (excluding explicit no_connects and power symbols) + for (const comp of model.components) { + if (comp.kind === "power_symbol" || comp.ref.startsWith("#")) continue; + for (const pin of comp.pins) { + if (pin.electricalType === "unconnected") continue; + if (!pin.net) { + issues.push({ + id: nextId("floating"), + code: "floating_pin", + severity: pin.electricalType === "power_in" ? "error" : "warning", + source: "builtin", + message: `Pin ${comp.ref}.${pin.number}${pin.name ? ` (${pin.name})` : ""} is unconnected${pin.electricalType === "power_in" ? " (power input)" : ""}.`, + refs: [comp.ref], + ...(pin.x !== undefined ? { x: pin.x } : comp.x !== undefined ? { x: comp.x } : {}), + ...(pin.y !== undefined ? { y: pin.y } : comp.y !== undefined ? { y: comp.y } : {}), + }); + } + } + } + + // 6. Missing ground reference + const realComponents = model.components.filter( + (c) => c.kind !== "power_symbol" && !c.ref.startsWith("#"), + ); + const hasGround = model.nets.some((n) => n.isGround && n.pins.length > 0); + if (realComponents.length > 0 && !hasGround) { + issues.push({ + id: nextId("no-gnd"), + code: "missing_ground", + severity: "warning", + source: "builtin", + message: "No ground reference net (GND / 0 / VSS) was detected in this circuit.", + refs: [], + }); + } + + // 7. Missing decoupling capacitor hint for ICs with power + ground rails + const netByName = new Map(model.nets.map((n) => [n.name, n])); + const capacitors = realComponents.filter((c) => c.kind === "capacitor"); + for (const comp of realComponents) { + if (comp.kind !== "ic") continue; + const powerNets = Array.from( + new Set( + comp.pins + .map((p) => p.net) + .filter( + (n): n is string => Boolean(n) && (netByName.get(n!)?.isPower ?? isPowerNetName(n!)), + ), + ), + ); + const groundNets = Array.from( + new Set( + comp.pins + .map((p) => p.net) + .filter( + (n): n is string => Boolean(n) && (netByName.get(n!)?.isGround ?? isGroundNetName(n!)), + ), + ), + ); + if (powerNets.length === 0 || groundNets.length === 0) continue; + + for (const pNet of powerNets) { + const hasDecoupling = capacitors.some((cap) => { + const capNets = new Set(cap.pins.map((p) => p.net).filter((n): n is string => Boolean(n))); + return capNets.has(pNet) && groundNets.some((g) => capNets.has(g)); + }); + if (!hasDecoupling) { + issues.push({ + id: nextId("decoupling"), + code: "missing_decoupling", + severity: "info", + source: "builtin", + message: `IC ${comp.ref} (${comp.value}) uses power rail "${pNet}" with no decoupling capacitor detected between "${pNet}" and ground.`, + net: pNet, + refs: [comp.ref], + ...(comp.x !== undefined ? { x: comp.x } : {}), + ...(comp.y !== undefined ? { y: comp.y } : {}), + }); + } + } + } + + // 8. PCB copper continuity / unrouted ratsnest check + if (model.format === "kicad_pcb") { + for (const net of model.nets) { + // Collect pad positions belonging to this net + const padPoints: Array<{ x: number; y: number; ref: string }> = []; + for (const comp of model.components) { + for (const pin of comp.pins) { + if (pin.net === net.name && pin.x !== undefined && pin.y !== undefined) { + padPoints.push({ x: pin.x, y: pin.y, ref: comp.ref }); + } + } + } + if (padPoints.length < 2) continue; + const netTracks = model.wires.filter((w) => w.net === net.name); + const netVias = model.vias.filter((v) => v.net === net.name); + + // Build graph over pad indices + track segment indices + via indices + const totalNodes = padPoints.length + netTracks.length + netVias.length; + const parent = Array.from({ length: totalNodes }, (_, idx) => idx); + const find = (a: number): number => { + let cur = a; + while (parent[cur] !== cur) cur = parent[cur]!; + let walk = a; + while (walk !== cur) { + const next = parent[walk]!; + parent[walk] = cur; + walk = next; + } + return cur; + }; + const union = (a: number, b: number) => { + const ra = find(a); + const rb = find(b); + if (ra !== rb) parent[ra] = rb; + }; + + const trackOffset = padPoints.length; + const viaOffset = padPoints.length + netTracks.length; + + // Connect tracks to pads + for (let t = 0; t < netTracks.length; t += 1) { + const seg = netTracks[t]!; + for (let p = 0; p < padPoints.length; p += 1) { + const pad = padPoints[p]!; + if ( + nearPoint(pad.x, pad.y, seg.x1, seg.y1, 0.5) || + nearPoint(pad.x, pad.y, seg.x2, seg.y2, 0.5) + ) { + union(p, trackOffset + t); + } + } + // Connect tracks to other tracks on same layer + for (let t2 = t + 1; t2 < netTracks.length; t2 += 1) { + const seg2 = netTracks[t2]!; + if (seg.layer && seg2.layer && seg.layer !== seg2.layer) continue; + if ( + nearPoint(seg.x1, seg.y1, seg2.x1, seg2.y1) || + nearPoint(seg.x1, seg.y1, seg2.x2, seg2.y2) || + nearPoint(seg.x2, seg.y2, seg2.x1, seg2.y1) || + nearPoint(seg.x2, seg.y2, seg2.x2, seg2.y2) + ) { + union(trackOffset + t, trackOffset + t2); + } + } + // Connect tracks to vias (any layer) + for (let v = 0; v < netVias.length; v += 1) { + const via = netVias[v]!; + if ( + nearPoint(via.x, via.y, seg.x1, seg.y1, 0.4) || + nearPoint(via.x, via.y, seg.x2, seg.y2, 0.4) + ) { + union(trackOffset + t, viaOffset + v); + } + } + } + + const padRoots = new Set(); + for (let p = 0; p < padPoints.length; p += 1) padRoots.add(find(p)); + if (padRoots.size > 1) { + issues.push({ + id: nextId("unrouted"), + code: "unrouted_pcb_net", + severity: "warning", + source: "builtin", + message: `PCB net "${net.name}" has ${padPoints.length} pads split across ${padRoots.size} disconnected copper islands (${netTracks.length} track segment${netTracks.length === 1 ? "" : "s"}).`, + net: net.name, + refs: Array.from(new Set(padPoints.map((p) => p.ref))), + x: padPoints[0]!.x, + y: padPoints[0]!.y, + }); + } + } + } + + return { issues, notes }; +} + +export function assembleValidationReport(input: { + readonly model: ElectronicsCircuitModel; + readonly builtinIssues: ReadonlyArray; + readonly externalIssues: ReadonlyArray; + readonly enginesUsed: ReadonlyArray; + readonly notes: ReadonlyArray; +}): ElectronicsValidationReport { + const issues = [...input.builtinIssues, ...input.externalIssues]; + let errorCount = 0; + let warningCount = 0; + let infoCount = 0; + for (const issue of issues) { + if (issue.severity === "error") errorCount += 1; + else if (issue.severity === "warning") warningCount += 1; + else infoCount += 1; + } + + return { + filePath: input.model.filePath, + format: input.model.format, + passed: errorCount === 0, + errorCount, + warningCount, + infoCount, + enginesUsed: [...input.enginesUsed], + notes: [...input.notes], + issues, + checkedAt: DateTime.formatIso(DateTime.nowUnsafe()), + }; +} diff --git a/apps/server/src/mcp/McpElectronicsToolkit.test.ts b/apps/server/src/mcp/McpElectronicsToolkit.test.ts new file mode 100644 index 0000000000000..cdc2fe061f5f0 --- /dev/null +++ b/apps/server/src/mcp/McpElectronicsToolkit.test.ts @@ -0,0 +1,174 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { + DEFAULT_SERVER_SETTINGS, + EnvironmentId, + ProjectId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import { McpSchema, McpServer } from "effect/ai"; + +import * as ElectronicsService from "../electronics/ElectronicsService.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as McpHttpServer from "./McpHttpServer.ts"; +import * as McpInvocationContext from "./McpInvocationContext.ts"; + +const testClient = McpSchema.McpServerClient.of({ + clientId: 1, + clientCapabilities: {}, + clientInfo: { name: "mcp-electronics-test", version: "1.0.0" }, + protocolVersion: "2025-06-18", + initializePayload: { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "mcp-electronics-test", version: "1.0.0" }, + }, + getClient: Effect.die("unused"), +}); + +const makeMcpTestLayer = ( + workspaceRoot: string, + settingsOverride: Partial = {}, +) => { + const mockSettings = ServerSettings.layerTest(settingsOverride); + const mockSpawner = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => Effect.fail(new Error("ENOENT") as never)), + ); + const mockThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadShell: () => + Effect.succeed({ + id: ThreadId.make("thread-mcp-elec"), + projectId: ProjectId.make("proj-mcp-elec"), + worktreePath: workspaceRoot, + deletedAt: null, + archivedAt: null, + runtimeMode: "full-access", + interactionMode: "default", + linkOrigin: null, + activeRunId: "run-1", + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + pendingBackgroundTasks: [], + } as never), + }); + const mockProjects = Layer.mock(ProjectService.ProjectService)({ + getById: () => Effect.succeedSome({ workspaceRoot } as never), + }); + const electronicsLayer = ElectronicsService.layer.pipe( + Layer.provide(mockSettings), + Layer.provide(mockSpawner), + Layer.provide(NodeServices.layer), + ); + return McpHttpServer.layerElectronicsToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(electronicsLayer), + Layer.provide(mockThreads), + Layer.provide(mockProjects), + Layer.provide(mockSettings), + Layer.provideMerge(NodeServices.layer), + ); +}; + +const scopeForThread = (): McpInvocationContext.McpInvocationScope => ({ + environmentId: EnvironmentId.make("env-test"), + requestNamespace: "provider-session-elec-test", + capabilities: new Set(), + client: undefined, + issuedAt: 1, + thread: { + threadId: ThreadId.make("thread-mcp-elec"), + providerSessionId: "sess-1", + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + }, +}); + +it.effect( + "runs electronics MCP tools end-to-end: list, open, inspect, trace_path, validate, simulate", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-mcp-elec-" }); + yield* fs.writeFileString( + path.join(dir, "rc.cir"), + "* RC Filter\nV1 vin 0 DC 5 AC 1\nR1 vin vout 1k\nC1 vout 0 100n\n.end\n", + ); + + yield* Effect.gen(function* () { + const mcp = yield* McpServer.McpServer; + const callTool = (name: string, args: Record) => + mcp + .callTool({ name, arguments: args }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scopeForThread()), + Effect.provideService(McpSchema.McpServerClient, testClient), + ); + + const textOf = (res: McpSchema.CallToolResult) => + res.content + .map((item) => (item.type === "text" ? item.text : JSON.stringify(item))) + .join("\n"); + + const listRes = yield* callTool("electronics_list", {}); + expect(listRes.isError).toBe(false); + expect(textOf(listRes)).toContain("rc.cir"); + + const openRes = yield* callTool("electronics_open", { + filePath: "rc.cir", + activeTab: "canvas", + }); + expect(openRes.isError).toBe(false); + expect(textOf(openRes)).toContain("spice"); + + const inspectRes = yield* callTool("electronics_inspect", { filePath: "rc.cir" }); + expect(inspectRes.isError).toBe(false); + expect(textOf(inspectRes)).toContain("R1"); + + const traceRes = yield* callTool("electronics_trace_path", { + filePath: "rc.cir", + from: "V1.+", + to: "vout", + }); + expect(traceRes.isError).toBe(false); + expect(textOf(traceRes)).toContain("1000"); + + const valRes = yield* callTool("electronics_validate", { filePath: "rc.cir" }); + expect(valRes.isError).toBe(false); + expect(textOf(valRes)).toContain('"passed":true'); + + const simRes = yield* callTool("electronics_simulate", { + filePath: "rc.cir", + kind: "ac_sweep", + outputNode: "vout", + }); + expect(simRes.isError).toBe(false); + expect(textOf(simRes)).toContain("-3 dB Cutoff"); + }).pipe(Effect.provide(makeMcpTestLayer(dir))); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.effect("blocks electronics MCP tools when enableAgentElectronicsAccess is false", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-mcp-elec-off-" }); + yield* Effect.gen(function* () { + const mcp = yield* McpServer.McpServer; + const res = yield* mcp + .callTool({ name: "electronics_list", arguments: {} }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scopeForThread()), + Effect.provideService(McpSchema.McpServerClient, testClient), + ); + expect(res.isError).toBe(true); + expect(JSON.stringify(res.content)).toContain("turned off"); + }).pipe(Effect.provide(makeMcpTestLayer(dir, { enableAgentElectronicsAccess: false }))); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 4c9d9dca1081a..ff243c267352d 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -92,6 +92,8 @@ import { DeviceScreenshotToolkit, DeviceStandardToolkit, } from "./toolkits/device/tools.ts"; +import * as ElectronicsHandlers from "./toolkits/electronics/handlers.ts"; +import { ElectronicsToolkit } from "./toolkits/electronics/tools.ts"; import * as HtmlHandlers from "./toolkits/html/handlers.ts"; import { MessageToolkit } from "./toolkits/message/tools.ts"; import * as MessageHandlers from "./toolkits/message/handlers.ts"; @@ -1350,6 +1352,11 @@ export const layerDeviceToolkit = Layer.mergeAll( layerDeviceScreenshotRegistration, ); +export const layerElectronicsToolkit = toolkitRegistration( + ElectronicsToolkit, + ElectronicsHandlers.layer, +); + /** * `McpServer` for in-process calls, which provide `McpInvocationContext` * around `callTool` as the auth middleware does for each /mcp request. @@ -1393,6 +1400,7 @@ export const layerTools = Layer.mergeAll( layerPullRequestsToolkit, layerIssuesToolkit, layerDeviceToolkit, + layerElectronicsToolkit, layerHtmlToolkit, layerMessageToolkit, ); diff --git a/apps/server/src/mcp/toolkits/electronics/handlers.ts b/apps/server/src/mcp/toolkits/electronics/handlers.ts new file mode 100644 index 0000000000000..4ac3f515893ab --- /dev/null +++ b/apps/server/src/mcp/toolkits/electronics/handlers.ts @@ -0,0 +1,192 @@ +import { + ElectronicsError, + type ElectronicsToolInspectResult, + type ElectronicsToolListResult, + type ElectronicsToolOpenResult, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; + +import * as ElectronicsService from "../../../electronics/ElectronicsService.ts"; +import { threadWorkspaceRoot } from "../../../project/threadWorkspaceRoot.ts"; +import * as ServerSettings from "../../../serverSettings.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import * as McpToolAccess from "../../McpToolAccess.ts"; +import { ElectronicsToolkit } from "./tools.ts"; + +const requireElectronicsAgentAccess = Effect.gen(function* () { + const scope = yield* McpInvocationContext.McpInvocationContext; + const threadScope = yield* McpInvocationContext.requireThreadScope(scope, "Electronics tools"); + const settingsService = yield* ServerSettings.ServerSettingsService; + const settings = yield* settingsService.getSettings.pipe( + Effect.mapError( + (err) => + new ElectronicsError({ + code: "internal", + message: `Could not read settings: ${err.message}`, + }), + ), + ); + if (!settings.enableElectronicsWorkbench || !settings.enableAgentElectronicsAccess) { + return yield* new ElectronicsError({ + code: "disabled", + message: + "Agent access to Electronics Workbench is turned off. Enable it in Settings → Electronics.", + }); + } + const cwd = yield* threadWorkspaceRoot(threadScope.thread.threadId); + if (!cwd) { + return yield* new ElectronicsError({ + code: "not_found", + message: "This thread does not have an attached workspace root.", + }); + } + return { threadId: threadScope.thread.threadId, cwd }; +}); + +const handlers = { + electronics_list: McpToolAccess.actsAsCaller((input) => + Effect.gen(function* () { + const { threadId, cwd } = yield* requireElectronicsAgentAccess; + const service = yield* ElectronicsService.ElectronicsService; + if (input.refreshToolchain) { + yield* service.getToolchainStatus(true); + } + const listed = yield* service.listFiles(cwd); + const session = yield* service.getThreadSession(threadId); + return { + files: listed.files, + ...(session !== undefined ? { openFilePath: session.filePath } : {}), + toolchain: { + kicadCli: listed.toolchain.kicadCli.available, + ...(listed.toolchain.kicadCli.version !== undefined + ? { kicadVersion: listed.toolchain.kicadCli.version } + : {}), + ngspice: listed.toolchain.ngspice.available, + ...(listed.toolchain.ngspice.version !== undefined + ? { ngspiceVersion: listed.toolchain.ngspice.version } + : {}), + }, + } satisfies ElectronicsToolListResult; + }), + ), + + electronics_open: McpToolAccess.actsAsCaller((input) => + Effect.gen(function* () { + const { threadId, cwd } = yield* requireElectronicsAgentAccess; + const service = yield* ElectronicsService.ElectronicsService; + const model = yield* service.inspect(cwd, input.filePath); + const session = yield* service.openPanel({ + threadId, + cwd, + filePath: input.filePath, + ...(input.activeTab !== undefined ? { activeTab: input.activeTab } : {}), + ...(input.selectedNet !== undefined ? { selectedNet: input.selectedNet } : {}), + }); + return { + filePath: session.filePath, + format: session.format, + activeTab: session.activeTab, + componentCount: model.components.filter((c) => c.kind !== "power_symbol").length, + netCount: model.nets.length, + } satisfies ElectronicsToolOpenResult; + }), + ), + + electronics_inspect: McpToolAccess.actsAsCaller((input) => + Effect.gen(function* () { + const { cwd } = yield* requireElectronicsAgentAccess; + const service = yield* ElectronicsService.ElectronicsService; + const model = yield* service.inspect(cwd, input.filePath); + const nonPower = model.components.filter((c) => c.kind !== "power_symbol"); + return { + filePath: model.filePath, + format: model.format, + ...(model.title !== undefined ? { title: model.title } : {}), + componentCount: nonPower.length, + netCount: model.nets.length, + powerNets: model.nets.filter((n) => n.isPower).map((n) => n.name), + groundNets: model.nets.filter((n) => n.isGround).map((n) => n.name), + components: nonPower.map((c) => ({ + ref: c.ref, + value: c.value, + kind: c.kind, + ...(c.footprint !== undefined ? { footprint: c.footprint } : {}), + pins: c.pins.map((p) => ({ + number: p.number, + ...(p.name !== undefined ? { name: p.name } : {}), + type: p.electricalType, + ...(p.net !== undefined ? { net: p.net } : {}), + })), + })), + nets: model.nets.map((n) => ({ + name: n.name, + isPower: n.isPower, + isGround: n.isGround, + pins: n.pins.map((p) => `${p.ref}.${p.pin}`), + })), + bom: model.bom, + parseWarnings: model.parseWarnings, + } satisfies ElectronicsToolInspectResult; + }), + ), + + electronics_trace_path: McpToolAccess.actsAsCaller((input) => + Effect.gen(function* () { + const { threadId, cwd } = yield* requireElectronicsAgentAccess; + const service = yield* ElectronicsService.ElectronicsService; + return yield* service.tracePath( + { + cwd, + filePath: input.filePath, + from: input.from, + ...(input.to !== undefined ? { to: input.to } : {}), + ...(input.traversePassives !== undefined + ? { traversePassives: input.traversePassives } + : {}), + ...(input.maxHops !== undefined ? { maxHops: input.maxHops } : {}), + }, + threadId, + ); + }), + ), + + electronics_validate: McpToolAccess.actsAsCaller((input) => + Effect.gen(function* () { + const { threadId, cwd } = yield* requireElectronicsAgentAccess; + const service = yield* ElectronicsService.ElectronicsService; + return yield* service.validate( + { + cwd, + filePath: input.filePath, + ...(input.useExternalToolchain !== undefined + ? { useExternalToolchain: input.useExternalToolchain } + : {}), + }, + threadId, + ); + }), + ), + + electronics_simulate: McpToolAccess.actsAsCaller((input) => + Effect.gen(function* () { + const { threadId, cwd } = yield* requireElectronicsAgentAccess; + const service = yield* ElectronicsService.ElectronicsService; + return yield* service.simulate( + { + cwd, + filePath: input.filePath, + ...(input.kind !== undefined ? { kind: input.kind } : {}), + ...(input.outputNode !== undefined ? { outputNode: input.outputNode } : {}), + ...(input.startFreqHz !== undefined ? { startFreqHz: input.startFreqHz } : {}), + ...(input.stopFreqHz !== undefined ? { stopFreqHz: input.stopFreqHz } : {}), + ...(input.stopTimeSeconds !== undefined + ? { stopTimeSeconds: input.stopTimeSeconds } + : {}), + }, + threadId, + ); + }), + ), +} satisfies McpToolAccess.Handlers; + +export const layer = McpToolAccess.toLayer(ElectronicsToolkit, handlers); diff --git a/apps/server/src/mcp/toolkits/electronics/tools.ts b/apps/server/src/mcp/toolkits/electronics/tools.ts new file mode 100644 index 0000000000000..469818dc4c67a --- /dev/null +++ b/apps/server/src/mcp/toolkits/electronics/tools.ts @@ -0,0 +1,154 @@ +import { + ElectronicsError, + ElectronicsPanelTab, + ElectronicsSimulationKind, + ElectronicsSimulationResult, + ElectronicsToolInspectResult, + ElectronicsToolListResult, + ElectronicsToolOpenResult, + ElectronicsTracePathResult, + ElectronicsValidationReport, + OrchestratorMcpFailure, + TrimmedNonEmptyString, +} from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import { McpSchema, Tool, Toolkit } from "effect/ai"; + +import * as ElectronicsService from "../../../electronics/ElectronicsService.ts"; +import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../../../project/ProjectService.ts"; +import * as ServerSettings from "../../../serverSettings.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; + +const dependencies = [ + McpInvocationContext.McpInvocationContext, + ThreadManagementService.ThreadManagementService, + ProjectService.ProjectService, + ServerSettings.ServerSettingsService, + ElectronicsService.ElectronicsService, +]; + +const ElectronicsToolFailure = Schema.Union([ElectronicsError, OrchestratorMcpFailure]); + +const ElectronicsListTool = Tool.make("electronics_list", { + description: + "List workspace circuit files (.kicad_sch, .kicad_pcb, .cir/.spice, *.circuit.json), open panel file, and kicad-cli/ngspice status.", + parameters: Schema.Struct({ + refreshToolchain: Schema.optional(Schema.Boolean), + }), + success: ElectronicsToolListResult, + failure: ElectronicsToolFailure, + dependencies, +}) + .annotate(Tool.Title, "List electronics files") + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + +const ElectronicsOpenTool = Tool.make("electronics_open", { + description: + "Open a circuit file in this thread's Electronics panel so the user sees the same schematic, PCB, or simulation view.", + parameters: Schema.Struct({ + filePath: TrimmedNonEmptyString, + activeTab: Schema.optional(ElectronicsPanelTab), + selectedNet: Schema.optional(Schema.String), + }), + success: ElectronicsToolOpenResult, + failure: ElectronicsToolFailure, + dependencies, +}) + .annotate(Tool.Title, "Open electronics panel") + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + +const ElectronicsInspectTool = Tool.make("electronics_inspect", { + description: + "Parse a KiCad schematic/PCB, SPICE netlist, or Circuit JSON into components, pins, nets, power rails, and BOM.", + parameters: Schema.Struct({ + filePath: TrimmedNonEmptyString, + }), + success: ElectronicsToolInspectResult, + failure: ElectronicsToolFailure, + dependencies, +}) + .annotate(Tool.Title, "Inspect circuit") + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + +const ElectronicsTracePathTool = Tool.make("electronics_trace_path", { + description: + "Validate electrical path between pins, components, or nets (e.g. U1.VOUT to J1.1), directly or through series passives.", + parameters: Schema.Struct({ + filePath: TrimmedNonEmptyString, + from: TrimmedNonEmptyString, + to: Schema.optional(TrimmedNonEmptyString), + traversePassives: Schema.optional(Schema.Boolean), + maxHops: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 16 }))), + }), + success: ElectronicsTracePathResult, + failure: ElectronicsToolFailure, + dependencies, +}) + .annotate(Tool.Title, "Trace circuit path") + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + +const ElectronicsValidateTool = Tool.make("electronics_validate", { + description: + "Run built-in electrical/layout checks (shorts, floating pins, conflicts, unrouted nets) plus kicad-cli ERC/DRC if installed.", + parameters: Schema.Struct({ + filePath: TrimmedNonEmptyString, + useExternalToolchain: Schema.optional(Schema.Boolean), + }), + success: ElectronicsValidationReport, + failure: ElectronicsToolFailure, + dependencies, +}) + .annotate(Tool.Title, "Validate circuit") + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + +const ElectronicsSimulateTool = Tool.make("electronics_simulate", { + description: + "Simulate DC operating point, AC Bode sweep, or transient response via ngspice or built-in linear MNA solver.", + parameters: Schema.Struct({ + filePath: TrimmedNonEmptyString, + kind: Schema.optional(ElectronicsSimulationKind), + outputNode: Schema.optional(TrimmedNonEmptyString), + startFreqHz: Schema.optional(Schema.Number), + stopFreqHz: Schema.optional(Schema.Number), + stopTimeSeconds: Schema.optional(Schema.Number), + }), + success: ElectronicsSimulationResult, + failure: ElectronicsToolFailure, + dependencies, +}) + .annotate(Tool.Title, "Simulate circuit") + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + +export const ElectronicsToolkit = Toolkit.make( + ElectronicsListTool, + ElectronicsOpenTool, + ElectronicsInspectTool, + ElectronicsTracePathTool, + ElectronicsValidateTool, + ElectronicsSimulateTool, +); diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index f02f32d67e764..9c70f07ee63af 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -256,6 +256,15 @@ const RPC_AGGREGATES = { [WS_METHODS.deviceDetail]: "device", [WS_METHODS.deviceAction]: "device", [WS_METHODS.subscribeDeviceState]: "device", + [WS_METHODS.electronicsListFiles]: "electronics", + [WS_METHODS.electronicsInspect]: "electronics", + [WS_METHODS.electronicsTracePath]: "electronics", + [WS_METHODS.electronicsValidate]: "electronics", + [WS_METHODS.electronicsSimulate]: "electronics", + [WS_METHODS.electronicsToolchainStatus]: "electronics", + [WS_METHODS.electronicsOpenPanel]: "electronics", + [WS_METHODS.electronicsClosePanel]: "electronics", + [WS_METHODS.subscribeElectronicsState]: "electronics", [WS_METHODS.subscribeServerConfig]: "server", [WS_METHODS.subscribeServerLifecycle]: "server", [WS_METHODS.subscribeAuthAccess]: "auth", diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index 3b3f1459cb9dd..1104abae8033c 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -11,6 +11,7 @@ import { AssetSigner } from "../assets/AssetSigner.ts"; import { ServerSecretStore } from "../auth/ServerSecretStore.ts"; import { ServerConfig } from "../config.ts"; import { DeviceService } from "../device/DeviceService.ts"; +import { ElectronicsService } from "../electronics/ElectronicsService.ts"; import { ServerEnvironment } from "../environment/ServerEnvironment.ts"; import { GitManager } from "../git/GitManager.ts"; import { GitWorkflowService } from "../git/GitWorkflowService.ts"; @@ -56,6 +57,7 @@ import budget from "./agentContextBudget.json" with { type: "json" }; const toolHandlerServices = Layer.mergeAll( Layer.mock(AssetSigner)({}), Layer.mock(DeviceService)({}), + Layer.mock(ElectronicsService)({}), Layer.mock(DocumentText)({}), Layer.mock(EnvironmentThemeService)({}), Layer.mock(GitVcsDriver)({}), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 139eba175bc8a..1bb26ed08a099 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 59052 + "mcpToolListJsonBytes": 61333 } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d06186beb1988..c9b56017ac8f4 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -102,6 +102,7 @@ import * as PeerThreadRelay from "./peer/PeerThreadRelay.ts"; import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts"; import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts"; import * as DeviceService from "./device/DeviceService.ts"; +import * as ElectronicsService from "./electronics/ElectronicsService.ts"; import * as DeviceHubProxy from "./device/DeviceHubProxy.ts"; import * as PreviewManager from "./preview/Manager.ts"; import * as PortScanner from "./preview/PortScanner.ts"; @@ -554,6 +555,8 @@ const layerDevice = DeviceService.layer.pipe( Layer.provide(NetService.layer), ); +const layerElectronics = ElectronicsService.layer.pipe(Layer.provide(layerServerSettings)); + const layerWorkspaceEntries = WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer)); const layerWorkspaceFileSystem = WorkspaceFileSystem.layer.pipe( @@ -771,7 +774,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( Layer.provideMerge(layerSourceControlProviderRegistry), Layer.provideMerge(layerGit), Layer.provideMerge(layerVcs), - Layer.provideMerge(Layer.mergeAll(layerTerminal, layerPreview, layerDevice)), + Layer.provideMerge(Layer.mergeAll(layerTerminal, layerPreview, layerDevice, layerElectronics)), Layer.provideMerge(layerPersistence), Layer.provideMerge(Layer.mergeAll(Keybindings.layer, UsageLimitSources.layer)), Layer.provideMerge(ProviderRegistry.layer), diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 02ca5170d7ffd..d9c38254b4e56 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -86,6 +86,7 @@ import * as CommandOutputHub from "./orchestration-v2/CommandOutputHub.ts"; import * as ThreadViewers from "./orchestration-v2/ThreadViewers.ts"; import * as CodexInstallation from "./provider/CodexInstallation.ts"; import * as DeviceService from "./device/DeviceService.ts"; +import * as ElectronicsService from "./electronics/ElectronicsService.ts"; import * as DocumentText from "./provider/DocumentText.ts"; import * as DirectEndpoints from "./environment/DirectEndpoints.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; @@ -843,6 +844,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( ThreadViewers.layer, Layer.mock(CodexInstallation.CodexInstallation)({ managedDirectory: "/unused" }), Layer.mock(DeviceService.DeviceService)({}), + Layer.mock(ElectronicsService.ElectronicsService)({}), Layer.mock(EnvironmentTheme.EnvironmentThemeService)({}), Layer.mock(GitWorkflowService.GitWorkflowService)({}), Layer.mock(HostResources.HostResources)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index ddd07fcfad656..8a31000aa5f0f 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -203,6 +203,7 @@ import { makePrepareTerminalLaunch } from "./workspace/restoreMissingWorktree.ts import { terminalOutputStream, withOutputWindow } from "./terminal/OutputProtocol.ts"; import * as ServerBrowser from "./preview/ServerBrowser.ts"; import * as DeviceService from "./device/DeviceService.ts"; +import * as ElectronicsService from "./electronics/ElectronicsService.ts"; import { remoteSshDeviceHosts } from "./device/localSshDeviceHost.ts"; import * as PreviewManager from "./preview/Manager.ts"; import { issueAssetUrl } from "./assets/AssetAccess.ts"; @@ -1501,6 +1502,7 @@ export const layerWsRpc = ( const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService; const pullRequestSync = yield* PullRequestSyncReactor.PullRequestSyncReactor; const deviceService = yield* DeviceService.DeviceService; + const electronicsService = yield* ElectronicsService.ElectronicsService; const deviceHostContext = yield* Effect.context>>(); const orchestrationEngine = yield* Orchestrator.OrchestratorV2; @@ -3408,6 +3410,18 @@ export const layerWsRpc = ( [WS_METHODS.deviceDetail]: (input) => deviceService.detail(input), [WS_METHODS.deviceAction]: (input) => deviceService.action(input), [WS_METHODS.subscribeDeviceState]: (_input) => DeviceService.stateStream(deviceService), + [WS_METHODS.electronicsListFiles]: (input) => electronicsService.listFiles(input.cwd), + [WS_METHODS.electronicsInspect]: (input) => + electronicsService.inspect(input.cwd, input.filePath), + [WS_METHODS.electronicsTracePath]: (input) => electronicsService.tracePath(input), + [WS_METHODS.electronicsValidate]: (input) => electronicsService.validate(input), + [WS_METHODS.electronicsSimulate]: (input) => electronicsService.simulate(input), + [WS_METHODS.electronicsToolchainStatus]: (input) => + electronicsService.getToolchainStatus(input.refresh ?? false), + [WS_METHODS.electronicsOpenPanel]: (input) => electronicsService.openPanel(input), + [WS_METHODS.electronicsClosePanel]: (input) => + electronicsService.closePanel(input.threadId).pipe(Effect.as({})), + [WS_METHODS.subscribeElectronicsState]: (_input) => electronicsService.subscribeState, [WS_METHODS.previewStopLocalServer]: (input) => portDiscovery.stopServer(input), [WS_METHODS.subscribeDiscoveredLocalServers]: (input) => Stream.callback((queue) => diff --git a/apps/web/src/closedViewStore.ts b/apps/web/src/closedViewStore.ts index 6587eb3eddf0d..871f646cd1d93 100644 --- a/apps/web/src/closedViewStore.ts +++ b/apps/web/src/closedViewStore.ts @@ -64,6 +64,7 @@ const isClosedViewEntry = (entry: unknown): entry is ClosedViewEntry => { case "diff": case "files": case "pull-requests": + case "electronics": return surface.id === surface.kind; case "preview": return surface.resourceId === null || typeof surface.resourceId === "string"; diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index ea16d027fcfe9..7fc1a0399fa4f 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2480,6 +2480,7 @@ export default function ChatView(props: ChatViewProps) { const { activateRightPanelSurfaceStable, addDeviceSurfaceStable, + addElectronicsSurfaceStable, addDiffSurfaceStable, addFilesSurfaceStable, addPullRequestSurfaceStable, @@ -4187,6 +4188,7 @@ export default function ChatView(props: ChatViewProps) { onAddPullRequest={addPullRequestSurfaceStable} onAddPullRequests={addPullRequestsSurfaceStable} onAddDevice={addDeviceSurfaceStable} + onAddElectronics={addElectronicsSurfaceStable} onAddSideChat={sideChatsOffered ? openSideChatStable : undefined} browserAvailable={canOperatePreview && browserAvailable} terminalAvailable={activeProject !== null && canOperateTerminal} @@ -4195,6 +4197,7 @@ export default function ChatView(props: ChatViewProps) { pullRequestAvailable={pullRequestSurfaceAvailable} pullRequestsAvailable={linkedItemsSurfaceAvailable} deviceAvailable={activeThreadRef !== null} + electronicsAvailable={activeThreadRef !== null && activeProject !== null} sideChatAvailable={sideChat.available} sideChatDisabledReason={sideChatDisabledReason} > diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 57ed98c49dfca..e4968e8261270 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -41,6 +41,7 @@ import { horizontalListSortingStrategy, SortableContext, useSortable } from "@dn import { CSS } from "@dnd-kit/utilities"; import { Bot, + CircuitBoard, CircleDotIcon, Smartphone, ChevronDown, @@ -157,6 +158,7 @@ export interface RightPanelTabsProps { onAddPullRequest: () => void; onAddPullRequests: () => void; onAddDevice: () => void; + onAddElectronics?: (() => void) | undefined; /** Absent where side chats are not offered. */ onAddSideChat?: (() => void) | undefined; browserAvailable: boolean; @@ -166,6 +168,7 @@ export interface RightPanelTabsProps { pullRequestAvailable: boolean; pullRequestsAvailable: boolean; deviceAvailable: boolean; + electronicsAvailable?: boolean | undefined; sideChatAvailable?: boolean; /** Overrides the default reason while side chats are available but cannot start. */ sideChatDisabledReason?: string | null; @@ -195,6 +198,7 @@ const SURFACE_DISABLED_REASONS = { pullRequest: msg("This thread's branch has no pull request yet."), pullRequests: msg("This thread has no linked items."), device: msg("Devices are only available from a thread."), + electronics: msg("Electronics Workbench is only available when a project is open."), sideChat: msg("Side chats start after the first message."), } as const; @@ -220,6 +224,7 @@ const SURFACE_UNAVAILABLE_HINTS = { pullRequest: msg("No pull request on this branch yet."), pullRequests: msg("No linked items available."), device: msg("Available from a thread."), + electronics: msg("Available when a project is open."), sideChat: msg("Available after the first message."), } as const; @@ -343,6 +348,7 @@ function RightPanelEmptyState(props: { onAddPullRequest: () => void; onAddPullRequests: () => void; onAddDevice: () => void; + onAddElectronics?: (() => void) | undefined; /** Absent where side chats are not offered. */ onAddSideChat?: (() => void) | undefined; browserAvailable: boolean; @@ -352,6 +358,7 @@ function RightPanelEmptyState(props: { pullRequestAvailable: boolean; pullRequestsAvailable: boolean; deviceAvailable: boolean; + electronicsAvailable?: boolean | undefined; sideChatAvailable: boolean; sideChatDisabledReason: string | null; }) { @@ -417,6 +424,21 @@ function RightPanelEmptyState(props: { disabledReason: messages(SURFACE_UNAVAILABLE_HINTS.device), onClick: props.onAddDevice, }, + ...(props.onAddElectronics + ? [ + { + label: msg("Electronics"), + description: msg( + "Inspect schematics/PCBs, trace circuit paths, run ERC/DRC, and simulate SPICE.", + ), + icon: CircuitBoard, + shortcut: "E", + available: props.electronicsAvailable === true, + disabledReason: messages(SURFACE_UNAVAILABLE_HINTS.electronics), + onClick: props.onAddElectronics, + }, + ] + : []), ...(props.onAddSideChat ? [ { @@ -622,6 +644,8 @@ function surfaceTitle( return /^\d+$/.test(surface.key) ? `#${surface.key}` : surface.key; case "device": return surface.title ?? surface.target?.name ?? resolve(msg("Device")); + case "electronics": + return resolve(msg("Electronics")); case "thread": // Until the thread's own title loads. return resolve(msg("Thread")); @@ -732,6 +756,8 @@ function SurfaceIcon({ ) : ( ); + case "electronics": + return ; } } @@ -1259,6 +1285,18 @@ export function RightPanelTabs(props: RightPanelTabsProps) { disabledReason: messages(SURFACE_DISABLED_REASONS.device), onClick: props.onAddDevice, }, + ...(props.onAddElectronics + ? [ + { + label: msg("Electronics"), + icon: CircuitBoard, + shortcut: "E", + available: props.electronicsAvailable === true, + disabledReason: messages(SURFACE_DISABLED_REASONS.electronics), + onClick: props.onAddElectronics, + }, + ] + : []), ...(props.onAddSideChat ? [ { @@ -1692,6 +1730,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { onAddPullRequest={props.onAddPullRequest} onAddPullRequests={props.onAddPullRequests} onAddDevice={props.onAddDevice} + onAddElectronics={props.onAddElectronics} onAddSideChat={props.onAddSideChat} browserAvailable={props.browserAvailable} terminalAvailable={props.terminalAvailable} @@ -1700,6 +1739,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { pullRequestAvailable={props.pullRequestAvailable} pullRequestsAvailable={props.pullRequestsAvailable} deviceAvailable={props.deviceAvailable} + electronicsAvailable={props.electronicsAvailable} sideChatAvailable={props.sideChatAvailable === true} sideChatDisabledReason={props.sideChatDisabledReason ?? null} /> diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 076c78d88d468..db5d52d37e260 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -36,6 +36,11 @@ const DiffPanel = lazy(() => import("../DiffPanel")); const DevicePanel = lazy(() => import("../device/DevicePanel").then((module) => ({ default: module.DevicePanel })), ); +const ElectronicsPanel = lazy(() => + import("../electronics/ElectronicsPanel").then((module) => ({ + default: module.ElectronicsPanel, + })), +); const FilePreviewPanel = lazy(() => import("../files/FilePreviewPanel")); type RightPanelTerminalProps = Omit< @@ -251,6 +256,18 @@ export function RightPanelSurfaceContent(props: { /> ); + case "electronics": + return ( + + + + ); case "files": case "file": { const files = props.files; diff --git a/apps/web/src/components/chat/useRightPanelActions.ts b/apps/web/src/components/chat/useRightPanelActions.ts index 9a5e4c24e7a0c..07c9f62d3f697 100644 --- a/apps/web/src/components/chat/useRightPanelActions.ts +++ b/apps/web/src/components/chat/useRightPanelActions.ts @@ -171,6 +171,11 @@ export function useRightPanelActions(input: RightPanelActionsInput) { useRightPanelStore.getState().open(activeThreadRef, "device"); }; const addDeviceSurfaceStable = useStableCallback(addDeviceSurface); + const addElectronicsSurface = () => { + if (!activeThreadRef || !activeProject) return; + useRightPanelStore.getState().open(activeThreadRef, "electronics"); + }; + const addElectronicsSurfaceStable = useStableCallback(addElectronicsSurface); const openFileSurface = (relativePath: string) => { if (!activeThreadRef || !activeProject) return; useRightPanelStore.getState().openFile(activeThreadRef, relativePath); @@ -348,6 +353,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) { shortcuts, activateRightPanelSurfaceStable, addDeviceSurfaceStable, + addElectronicsSurfaceStable, addDiffSurfaceStable, addFilesSurfaceStable, addPullRequestSurfaceStable, diff --git a/apps/web/src/components/electronics/BomPanel.tsx b/apps/web/src/components/electronics/BomPanel.tsx new file mode 100644 index 0000000000000..e7d12ab08768a --- /dev/null +++ b/apps/web/src/components/electronics/BomPanel.tsx @@ -0,0 +1,106 @@ +import type { ElectronicsBomEntry } from "@t3tools/contracts"; +import { T, useGT } from "gt-react"; +import { SearchIcon } from "lucide-react"; +import { useState } from "react"; + +import { Input } from "../ui/input"; + +export interface BomPanelProps { + readonly bom: ReadonlyArray; + readonly onSelectRef: (ref: string) => void; +} + +export function BomPanel(props: BomPanelProps) { + const { bom, onSelectRef } = props; + const gt = useGT(); + const [query, setQuery] = useState(""); + + const q = query.trim().toLowerCase(); + const filtered = q + ? bom.filter( + (row) => + row.value.toLowerCase().includes(q) || + row.kind.toLowerCase().includes(q) || + (row.footprint?.toLowerCase().includes(q) ?? false) || + row.refs.some((r) => r.toLowerCase().includes(q)), + ) + : bom; + + const totalParts = filtered.reduce((acc, row) => acc + row.quantity, 0); + + return ( +
+
+
+ + setQuery(e.target.value)} + placeholder={gt("Filter BOM by ref, value, footprint…")} + /> +
+ + {gt("{lines} lines · {parts} parts", { lines: filtered.length, parts: totalParts })} + +
+ + {filtered.length === 0 ? ( +
+ No BOM entries found. +
+ ) : ( +
+ + + + + + + + + + + {filtered.map((row) => ( + + + + + + + ))} + +
+ Designators + + Value + + Footprint + + Qty +
+
+ {row.refs.map((ref) => ( + + ))} +
+
{row.value} + {row.footprint ?? "-"} + + {row.quantity} +
+
+ )} +
+ ); +} diff --git a/apps/web/src/components/electronics/CircuitCanvas.tsx b/apps/web/src/components/electronics/CircuitCanvas.tsx new file mode 100644 index 0000000000000..c667212d9c8a7 --- /dev/null +++ b/apps/web/src/components/electronics/CircuitCanvas.tsx @@ -0,0 +1,685 @@ +import type { + ElectronicsCircuitModel, + ElectronicsComponent, + ElectronicsTracePathResult, + ElectronicsValidationIssue, +} from "@t3tools/contracts"; +import { T, useGT } from "gt-react"; +import { CrosshairIcon, LayersIcon, Maximize2Icon, ZoomInIcon, ZoomOutIcon } from "lucide-react"; +import { type MouseEvent, type WheelEvent, useRef, useState } from "react"; + +import { Button } from "../ui/button"; + +export interface CircuitCanvasProps { + readonly model: ElectronicsCircuitModel; + readonly selectedNet: string | null; + readonly selectedRef: string | null; + readonly activeTrace: ElectronicsTracePathResult | null; + readonly validationIssues: ReadonlyArray; + readonly onSelectNet: (net: string | null) => void; + readonly onSelectRef: (ref: string | null) => void; + readonly onStartTraceFrom?: (endpoint: string) => void; +} + +function layerColor(layer: string | undefined, isPcb: boolean): string { + if (!isPcb) return "var(--chart-2, #10b981)"; + if (layer === "F.Cu") return "var(--destructive, #ef4444)"; + if (layer === "B.Cu") return "var(--info, #3b82f6)"; + if (layer === "Edge.Cuts") return "var(--warning, #eab308)"; + return "var(--chart-3, #a855f7)"; +} + +function componentBodySize(comp: ElectronicsComponent, isPcb: boolean): { w: number; h: number } { + if (isPcb) { + if (comp.pins.length >= 2) { + let minX = comp.x ?? 0; + let maxX = comp.x ?? 0; + let minY = comp.y ?? 0; + let maxY = comp.y ?? 0; + for (const p of comp.pins) { + if (p.x !== undefined) { + minX = Math.min(minX, p.x); + maxX = Math.max(maxX, p.x); + } + if (p.y !== undefined) { + minY = Math.min(minY, p.y); + maxY = Math.max(maxY, p.y); + } + } + return { + w: Math.max(2.4, maxX - minX + 1.4), + h: Math.max(1.6, maxY - minY + 1.2), + }; + } + return { w: 3.2, h: 2.0 }; + } + if (comp.kind === "ic") return { w: 12, h: Math.max(10, comp.pins.length * 2.5) }; + if (comp.kind === "power_symbol") return { w: 3.6, h: 3.6 }; + if (comp.kind === "power_source") return { w: 9, h: 9 }; + return { w: 9, h: 6 }; +} + +export function CircuitCanvas(props: CircuitCanvasProps) { + const { + model, + selectedNet, + selectedRef, + activeTrace, + validationIssues, + onSelectNet, + onSelectRef, + onStartTraceFrom, + } = props; + const gt = useGT(); + const svgRef = useRef(null); + const isPcb = model.format === "kicad_pcb" || model.boardOutline.length > 0; + + const [zoom, setZoom] = useState(1); + const [pan, setPan] = useState({ x: 0, y: 0 }); + const [dragging, setDragging] = useState<{ + startX: number; + startY: number; + originX: number; + originY: number; + } | null>(null); + const [hiddenLayers, setHiddenLayers] = useState>(() => new Set()); + const [showLayerMenu, setShowLayerMenu] = useState(false); + + const bounds = model.bounds; + const baseWidth = Math.max(10, bounds.maxX - bounds.minX); + const baseHeight = Math.max(10, bounds.maxY - bounds.minY); + const viewW = baseWidth / zoom; + const viewH = baseHeight / zoom; + const viewX = bounds.minX + (baseWidth - viewW) / 2 - pan.x; + const viewY = bounds.minY + (baseHeight - viewH) / 2 - pan.y; + + const traceNets = new Set(activeTrace?.highlightedNets ?? []); + const traceComps = new Set(activeTrace?.highlightedComponents ?? []); + + const layerSet = new Set(); + for (const l of model.layers) layerSet.add(l); + for (const w of model.wires) { + if (w.layer) layerSet.add(w.layer); + } + const availableLayers = Array.from(layerSet); + + const toggleLayer = (layer: string) => { + setHiddenLayers((prev) => { + const next = new Set(prev); + if (next.has(layer)) next.delete(layer); + else next.add(layer); + return next; + }); + }; + + const resetView = () => { + setZoom(1); + setPan({ x: 0, y: 0 }); + }; + + const handleWheel = (event: WheelEvent) => { + event.preventDefault(); + const factor = event.deltaY < 0 ? 1.18 : 1 / 1.18; + setZoom((prev) => Math.max(0.35, Math.min(12, Number((prev * factor).toFixed(3))))); + }; + + const handleMouseDown = (event: MouseEvent) => { + if (event.button !== 0) return; + setDragging({ + startX: event.clientX, + startY: event.clientY, + originX: pan.x, + originY: pan.y, + }); + }; + + const handleMouseMove = (event: MouseEvent) => { + if (!dragging || !svgRef.current) return; + const rect = svgRef.current.getBoundingClientRect(); + if (rect.width <= 0 || rect.height <= 0) return; + const dx = ((event.clientX - dragging.startX) / rect.width) * viewW; + const dy = ((event.clientY - dragging.startY) / rect.height) * viewH; + setPan({ x: dragging.originX + dx, y: dragging.originY + dy }); + }; + + const handleMouseUp = () => { + if (dragging) setDragging(null); + }; + + const selectedComponent = selectedRef + ? (model.components.find((c) => c.ref === selectedRef) ?? null) + : null; + const selectedNetObj = selectedNet + ? (model.nets.find((n) => n.name === selectedNet) ?? null) + : null; + + const unitScale = Math.max(baseWidth, baseHeight) / 100; + const strokeUnit = Math.max(0.18, unitScale * 0.45); + const fontUnit = Math.max(1.1, unitScale * 2.3); + + return ( +
+
+
+ {isPcb && availableLayers.length > 0 && ( + + )} + + + +
+ + {isPcb && showLayerMenu && ( +
+
+ Layers +
+ {availableLayers.map((layer) => { + const visible = !hiddenLayers.has(layer); + return ( + + ); + })} +
+ )} + + {(selectedNet || activeTrace) && ( +
+ {selectedNet && ( + + + {selectedNet} + + + )} + {activeTrace && ( + + {activeTrace.from} + {activeTrace.to ? ` → ${activeTrace.to}` : ""} + + )} +
+ )} + + + + + + + + { + onSelectNet(null); + onSelectRef(null); + }} + /> + + {!hiddenLayers.has("Edge.Cuts") && + model.boardOutline.map((seg) => ( + + ))} + + {model.wires.map((seg) => { + if (seg.layer && hiddenLayers.has(seg.layer)) return null; + const isSelected = Boolean(seg.net && seg.net === selectedNet); + const isTraced = Boolean(seg.net && traceNets.has(seg.net)); + const baseStroke = seg.width ? Math.max(strokeUnit * 0.7, seg.width) : strokeUnit; + const color = isTraced + ? "var(--warning, #f59e0b)" + : isSelected + ? "var(--primary, #38bdf8)" + : layerColor(seg.layer, isPcb); + return ( + + {(isSelected || isTraced) && ( + + )} + { + e.stopPropagation(); + if (seg.net) onSelectNet(seg.net); + }} + /> + + ); + })} + + {model.vias.map((via) => { + const highlighted = Boolean( + (via.net && via.net === selectedNet) || (via.net && traceNets.has(via.net)), + ); + return ( + { + e.stopPropagation(); + if (via.net) onSelectNet(via.net); + }} + > + + + + ); + })} + + {model.junctions.map((pt) => ( + + ))} + + {model.noConnects.map((pt) => ( + + + + + ))} + + {model.components.map((comp) => { + if (comp.x === undefined || comp.y === undefined) return null; + const { w, h } = componentBodySize(comp, isPcb); + const isSelected = comp.ref === selectedRef; + const isTraced = traceComps.has(comp.ref); + const touchesSelectedNet = + selectedNet !== null && comp.pins.some((p) => p.net === selectedNet); + const borderColor = isTraced + ? "var(--warning, #f59e0b)" + : isSelected + ? "var(--primary, #38bdf8)" + : touchesSelectedNet + ? "var(--chart-2, #10b981)" + : comp.kind === "power_symbol" + ? "var(--destructive, #ef4444)" + : "var(--foreground)"; + + return ( + { + e.stopPropagation(); + onSelectRef(comp.ref); + }} + > + {comp.kind === "power_symbol" ? ( + + ) : ( + + )} + + {comp.pins.map((pin) => { + if (pin.x === undefined || pin.y === undefined) return null; + const pinHighlighted = + (pin.net && pin.net === selectedNet) || (pin.net && traceNets.has(pin.net)); + return ( + { + e.stopPropagation(); + onSelectRef(comp.ref); + if (pin.net) onSelectNet(pin.net); + }} + > + {!isPcb && ( + + )} + + + ); + })} + + + {comp.kind === "power_symbol" ? comp.value : comp.ref} + + {comp.kind !== "power_symbol" && + (() => { + const displayVal = comp.value.slice(0, 14); + const fittedFont = Math.min( + fontUnit * 0.76, + (w * 0.86) / Math.max(3.5, displayVal.length * 0.62), + ); + return ( + + {displayVal} + + ); + })()} + + ); + })} + + {model.labels + .filter((lbl) => lbl.kind !== "power") + .map((lbl) => { + const isHighlighted = lbl.text === selectedNet || traceNets.has(lbl.text); + return ( + { + e.stopPropagation(); + onSelectNet(lbl.text); + }} + > + {lbl.text} + + ); + })} + + {validationIssues.map((issue) => { + if (issue.x === undefined || issue.y === undefined) return null; + const fill = + issue.severity === "error" + ? "var(--destructive, #ef4444)" + : issue.severity === "warning" + ? "var(--warning, #eab308)" + : "var(--info, #3b82f6)"; + return ( + { + e.stopPropagation(); + if (issue.net) onSelectNet(issue.net); + if (issue.refs[0]) onSelectRef(issue.refs[0]); + }} + > + + + {`[${issue.severity.toUpperCase()}] ${issue.message}`} + + + ); + })} + +
+ + {(selectedComponent || selectedNetObj) && ( +
+ {selectedComponent ? ( +
+
+
+ + {selectedComponent.ref} + + {selectedComponent.value} + {selectedComponent.footprint && ( + + {selectedComponent.footprint} + + )} +
+ {onStartTraceFrom && ( + + )} +
+
+ {selectedComponent.pins.map((pin) => ( + + ))} +
+
+ ) : selectedNetObj ? ( +
+
+
+ + {selectedNetObj.name} + + + {gt("{count} connected pins", { count: selectedNetObj.pins.length })} + +
+ {onStartTraceFrom && ( + + )} +
+
+ {selectedNetObj.pins.map((p) => ( + + ))} +
+
+ ) : null} +
+ )} +
+ ); +} diff --git a/apps/web/src/components/electronics/ElectronicsPanel.browser.test.tsx b/apps/web/src/components/electronics/ElectronicsPanel.browser.test.tsx new file mode 100644 index 0000000000000..389f71afe52f3 --- /dev/null +++ b/apps/web/src/components/electronics/ElectronicsPanel.browser.test.tsx @@ -0,0 +1,279 @@ +import "~/index.css"; + +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + type ElectronicsCircuitModel, + type ElectronicsServiceState, + type ElectronicsSimulationResult, + type ElectronicsTracePathResult, + type ElectronicsValidationReport, + EnvironmentId, + ThreadId, +} from "@t3tools/contracts"; +import * as Exit from "effect/Exit"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; + +import { render } from "../../../test/render"; +import { ElectronicsPanel } from "./ElectronicsPanel"; + +const SAMPLE_MODEL: ElectronicsCircuitModel = { + format: "kicad_sch", + filePath: "boards/power.kicad_sch", + title: "Sensor Power & Divider", + layers: ["schematic", "wire"], + bounds: { minX: 0, minY: 0, maxX: 100, maxY: 70 }, + components: [ + { + ref: "U1", + value: "AMS1117-3.3", + kind: "ic", + footprint: "SOT-223", + x: 35, + y: 30, + rotation: 0, + pins: [ + { number: "1", name: "VIN", electricalType: "power_in", net: "+5V", x: 25, y: 30 }, + { number: "2", name: "GND", electricalType: "power_in", net: "GND", x: 35, y: 40 }, + { number: "3", name: "VOUT", electricalType: "power_out", net: "+3V3", x: 45, y: 30 }, + ], + }, + { + ref: "R1", + value: "10k", + kind: "resistor", + footprint: "R_0603", + x: 65, + y: 30, + rotation: 0, + pins: [ + { number: "1", electricalType: "passive", net: "+3V3", x: 58, y: 30 }, + { number: "2", electricalType: "passive", net: "VSENSE", x: 72, y: 30 }, + ], + }, + ], + nets: [ + { + name: "+5V", + isPower: true, + isGround: false, + pins: [{ ref: "U1", pin: "1", pinName: "VIN", electricalType: "power_in" }], + }, + { + name: "+3V3", + isPower: true, + isGround: false, + pins: [ + { ref: "U1", pin: "3", pinName: "VOUT", electricalType: "power_out" }, + { ref: "R1", pin: "1", electricalType: "passive" }, + ], + }, + { + name: "VSENSE", + isPower: false, + isGround: false, + pins: [{ ref: "R1", pin: "2", electricalType: "passive" }], + }, + { + name: "GND", + isPower: false, + isGround: true, + pins: [{ ref: "U1", pin: "2", pinName: "GND", electricalType: "power_in" }], + }, + ], + wires: [{ x1: 45, y1: 30, x2: 58, y2: 30, layer: "wire", net: "+3V3" }], + vias: [], + junctions: [], + noConnects: [], + labels: [{ text: "+3V3", kind: "local", x: 51, y: 28 }], + boardOutline: [], + bom: [ + { value: "AMS1117-3.3", footprint: "SOT-223", kind: "ic", refs: ["U1"], quantity: 1 }, + { value: "10k", footprint: "R_0603", kind: "resistor", refs: ["R1"], quantity: 1 }, + ], + parseWarnings: [], +}; + +const SAMPLE_TRACE: ElectronicsTracePathResult = { + filePath: "boards/power.kicad_sch", + from: "U1.VOUT", + to: "VSENSE", + connected: true, + fromNets: ["+3V3"], + toNets: ["VSENSE"], + hops: [ + { kind: "net", name: "+3V3" }, + { + kind: "component", + name: "R1", + value: "10k", + fromPin: "1", + toPin: "2", + componentKind: "resistor", + }, + { kind: "net", name: "VSENSE" }, + ], + highlightedNets: ["+3V3", "VSENSE"], + highlightedComponents: ["U1", "R1"], + estimatedResistanceOhms: 10000, + warnings: [], +}; + +const SAMPLE_VALIDATION: ElectronicsValidationReport = { + filePath: "boards/power.kicad_sch", + format: "kicad_sch", + passed: true, + errorCount: 0, + warningCount: 1, + infoCount: 1, + enginesUsed: ["builtin"], + notes: [], + issues: [ + { + id: "w-1", + code: "single_pin_net", + severity: "warning", + source: "builtin", + message: 'Named net "VSENSE" only connects to a single pin (R1.2).', + net: "VSENSE", + refs: ["R1"], + x: 72, + y: 30, + }, + { + id: "i-1", + code: "missing_decoupling", + severity: "info", + source: "builtin", + message: 'IC U1 uses power rail "+5V" with no decoupling capacitor detected.', + net: "+5V", + refs: ["U1"], + x: 35, + y: 30, + }, + ], + checkedAt: "2026-11-22T05:00:00.000Z", +}; + +const SAMPLE_SIM: ElectronicsSimulationResult = { + filePath: "boards/power.kicad_sch", + kind: "ac_sweep", + engine: "builtin_mna", + xAxisLabel: "Frequency", + xAxisUnit: "Hz", + xAxisLog: true, + nodeVoltages: [{ node: "VSENSE", voltageV: 1.65 }], + componentReadings: [ + { ref: "R1", value: "10k", voltageDropV: 1.65, currentA: 0.000165, powerW: 0.000272 }, + ], + series: [ + { + label: "|V(VSENSE)|", + unit: "dB", + points: [ + { x: 10, y: 0, phaseDeg: -1 }, + { x: 1590, y: -3.01, phaseDeg: -45 }, + { x: 100000, y: -36, phaseDeg: -89 }, + ], + }, + ], + metrics: [{ name: "-3 dB Cutoff", value: 1591.5, unit: "Hz" }], + notes: [], + simulatedAt: "2026-11-22T05:00:00.000Z", +}; + +const mockState: ElectronicsServiceState = { + toolchain: { + enabled: true, + allowExternalTools: true, + agentAccessEnabled: true, + kicadCli: { name: "kicad-cli", available: false }, + ngspice: { name: "ngspice", available: false }, + checkedAt: "2026-11-22T05:00:00.000Z", + }, + sessions: [], +}; + +vi.mock("~/state/electronics", () => ({ + electronicsEnvironment: { + listFiles: "listFiles", + inspect: "inspect", + tracePath: "tracePath", + validate: "validate", + simulate: "simulate", + }, + useElectronicsState: () => ({ + state: mockState, + loaded: true, + error: null, + refresh: vi.fn(), + }), +})); + +vi.mock("~/state/use-atom-command", () => ({ + useAtomCommand: (cmd: string) => async () => { + switch (cmd) { + case "listFiles": + return Exit.succeed({ + files: [ + { + relativePath: "boards/power.kicad_sch", + name: "power.kicad_sch", + format: "kicad_sch", + sizeBytes: 2048, + }, + ], + toolchain: mockState.toolchain, + }); + case "inspect": + return Exit.succeed(SAMPLE_MODEL); + case "tracePath": + return Exit.succeed(SAMPLE_TRACE); + case "validate": + return Exit.succeed(SAMPLE_VALIDATION); + case "simulate": + return Exit.succeed(SAMPLE_SIM); + default: + return Exit.succeed({}); + } + }, +})); + +describe("ElectronicsPanel", () => { + const threadRef = scopeThreadRef(EnvironmentId.make("env-1"), ThreadId.make("thread-1")); + + it("renders schematic canvas, traces paths, validates ERC issues, simulates Bode sweep, and filters BOM", async () => { + const screen = await render( +
+ +
, + ); + + await expect.element(screen.getByText("Sensor Power & Divider")).toBeVisible(); + await expect.element(screen.getByLabelText("Interactive circuit canvas")).toBeVisible(); + + // Switch to Path Tracer tab and run trace + await userEvent.click(screen.getByRole("button", { name: /Path Tracer/i })); + await userEvent.type(screen.getByPlaceholder(/U1\.VOUT/i), "U1.VOUT"); + await userEvent.type(screen.getByPlaceholder(/R2\.1/i), "VSENSE"); + await userEvent.click(screen.getByRole("button", { name: /Validate Path/i })); + await expect.element(screen.getByText("Path Connected")).toBeVisible(); + await expect.element(screen.getByText(/10\.00 kΩ/i)).toBeVisible(); + + // Switch to Checks tab and run validation + await userEvent.click(screen.getByRole("button", { name: /Checks/i })); + await userEvent.click(screen.getByRole("button", { name: /Run Checks/i })); + await expect.element(screen.getByText("All error checks passed")).toBeVisible(); + await expect.element(screen.getByText(/single_pin_net/i)).toBeVisible(); + + // Switch to Simulate tab and run simulation + await userEvent.click(screen.getByRole("button", { name: /Simulate/i })); + await userEvent.click(screen.getByRole("button", { name: /Run Simulation/i })); + await expect.element(screen.getByText(/1\.59 kHz/i)).toBeVisible(); + + // Switch to BOM tab and verify part entries + await userEvent.click(screen.getByRole("button", { name: /BOM/i })); + await expect.element(screen.getByText("AMS1117-3.3")).toBeVisible(); + await expect.element(screen.getByText("SOT-223")).toBeVisible(); + }); +}); diff --git a/apps/web/src/components/electronics/ElectronicsPanel.tsx b/apps/web/src/components/electronics/ElectronicsPanel.tsx new file mode 100644 index 0000000000000..3bd75ba45b2c0 --- /dev/null +++ b/apps/web/src/components/electronics/ElectronicsPanel.tsx @@ -0,0 +1,532 @@ +import { + type ElectronicsCircuitModel, + type ElectronicsDesignFormat, + type ElectronicsPanelTab, + type ElectronicsSimulationKind, + type ElectronicsSimulationResult, + type ElectronicsTracePathResult, + type ElectronicsValidationIssue, + type ElectronicsValidationReport, + type ElectronicsWorkspaceFile, + type ScopedThreadRef, +} from "@t3tools/contracts"; +import { T, useGT } from "gt-react"; +import { + ActivityIcon, + CircuitBoardIcon, + ListChecksIcon, + PackageIcon, + RefreshCwIcon, + RouteIcon, + ShieldCheckIcon, +} from "lucide-react"; +import { useEffect, useState } from "react"; + +import { Button } from "../ui/button"; +import { Spinner } from "../ui/spinner"; +import { useStableCallback } from "../../hooks/useStableCallback"; +import { electronicsEnvironment, useElectronicsState } from "../../state/electronics"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { BomPanel } from "./BomPanel"; +import { CircuitCanvas } from "./CircuitCanvas"; +import { PathTracerPanel } from "./PathTracerPanel"; +import { SimulationPanel } from "./SimulationPanel"; +import { ValidationPanel } from "./ValidationPanel"; + +export interface ElectronicsPanelProps { + readonly threadRef: ScopedThreadRef; + readonly workspaceRoot: string | undefined; + readonly initialFilePath?: string | undefined; + readonly visible: boolean; +} + +export function ElectronicsPanel(props: ElectronicsPanelProps) { + const { threadRef, workspaceRoot, initialFilePath } = props; + const gt = useGT(); + const { state: serviceState } = useElectronicsState(threadRef.environmentId); + + const listFilesCmd = useStableCallback( + useAtomCommand(electronicsEnvironment.listFiles, { reportFailure: false }), + ); + const inspectCmd = useStableCallback( + useAtomCommand(electronicsEnvironment.inspect, { reportFailure: false }), + ); + const traceCmd = useAtomCommand(electronicsEnvironment.tracePath, { reportFailure: false }); + const validateCmd = useAtomCommand(electronicsEnvironment.validate, { reportFailure: false }); + const simulateCmd = useAtomCommand(electronicsEnvironment.simulate, { reportFailure: false }); + + const formatBadgeLabel = (format: ElectronicsDesignFormat): string => { + switch (format) { + case "kicad_sch": + return gt("KiCad SCH"); + case "kicad_pcb": + return gt("KiCad PCB"); + case "spice": + return gt("SPICE"); + case "circuit_json": + return gt("Circuit JSON"); + } + }; + + const threadSession = + serviceState.sessions.find((s) => s.threadId === threadRef.threadId) ?? null; + + const [files, setFiles] = useState>([]); + const [selectedFile, setSelectedFile] = useState( + initialFilePath ?? threadSession?.filePath ?? "", + ); + const [activeTab, setActiveTab] = useState( + threadSession?.activeTab ?? "canvas", + ); + const [model, setModel] = useState(null); + const [loadingFiles, setLoadingFiles] = useState(false); + const [loadingModel, setLoadingModel] = useState(false); + const [errorMessage, setErrorMessage] = useState(null); + + const [selectedNet, setSelectedNet] = useState(threadSession?.selectedNet ?? null); + const [selectedRef, setSelectedRef] = useState(null); + + const [traceFrom, setTraceFrom] = useState(""); + const [traceTo, setTraceTo] = useState(""); + const [traversePassives, setTraversePassives] = useState(true); + const [traceRunning, setTraceRunning] = useState(false); + const [traceResult, setTraceResult] = useState( + threadSession?.lastTrace ?? null, + ); + + const [validationRunning, setValidationRunning] = useState(false); + const [validationReport, setValidationReport] = useState( + threadSession?.lastValidation ?? null, + ); + + const [simKind, setSimKind] = useState("dc_op"); + const [simOutputNode, setSimOutputNode] = useState(""); + const [simRunning, setSimRunning] = useState(false); + const [simError, setSimError] = useState(null); + const [simResult, setSimResult] = useState( + threadSession?.lastSimulation ?? null, + ); + + const [lastSyncedAt, setLastSyncedAt] = useState(""); + + if (threadSession && threadSession.updatedAt !== lastSyncedAt) { + setLastSyncedAt(threadSession.updatedAt); + if (threadSession.filePath !== selectedFile) { + setSelectedFile(threadSession.filePath); + } + setActiveTab(threadSession.activeTab); + if (threadSession.selectedNet !== undefined) { + setSelectedNet(threadSession.selectedNet); + } + if (threadSession.lastTrace !== undefined) { + setTraceResult(threadSession.lastTrace); + setTraceFrom(threadSession.lastTrace.from); + setTraceTo(threadSession.lastTrace.to ?? ""); + } + if (threadSession.lastValidation !== undefined) { + setValidationReport(threadSession.lastValidation); + } + if (threadSession.lastSimulation !== undefined) { + setSimResult(threadSession.lastSimulation); + setSimKind(threadSession.lastSimulation.kind); + } + } + + const triggerFilesRefresh = () => { + if (!workspaceRoot) return; + setLoadingFiles(true); + void listFilesCmd({ + environmentId: threadRef.environmentId, + input: { cwd: workspaceRoot }, + }).then((result) => { + setLoadingFiles(false); + if (result._tag === "Success") { + setFiles(result.value.files); + setErrorMessage(null); + setSelectedFile((current) => current || result.value.files[0]?.relativePath || ""); + } else { + setErrorMessage(String(result.cause)); + } + }); + }; + + const triggerModelRefresh = () => { + if (!workspaceRoot || !selectedFile) return; + setLoadingModel(true); + void inspectCmd({ + environmentId: threadRef.environmentId, + input: { cwd: workspaceRoot, filePath: selectedFile }, + }).then((result) => { + setLoadingModel(false); + if (result._tag === "Success") { + setModel(result.value); + setErrorMessage(null); + } else { + setModel(null); + setErrorMessage(gt("Unable to parse circuit file.")); + } + }); + }; + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads workspace electronics catalog on mount and workspace switch + useEffect(() => { + if (!workspaceRoot) return; + let active = true; + void listFilesCmd({ + environmentId: threadRef.environmentId, + input: { cwd: workspaceRoot }, + }).then((result) => { + if (!active) return; + setLoadingFiles(false); + if (result._tag === "Success") { + setFiles(result.value.files); + setErrorMessage(null); + setSelectedFile((current) => current || result.value.files[0]?.relativePath || ""); + } else { + setErrorMessage(String(result.cause)); + } + }); + return () => { + active = false; + }; + }, [workspaceRoot, threadRef.environmentId, listFilesCmd]); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- fetches parsed circuit model when user or agent selects a file + useEffect(() => { + if (!workspaceRoot || !selectedFile) return; + let active = true; + void inspectCmd({ + environmentId: threadRef.environmentId, + input: { cwd: workspaceRoot, filePath: selectedFile }, + }).then((result) => { + if (!active) return; + setLoadingModel(false); + if (result._tag === "Success") { + setModel(result.value); + setErrorMessage(null); + } else { + setModel(null); + setErrorMessage(gt("Unable to parse circuit file.")); + } + }); + return () => { + active = false; + }; + }, [selectedFile, workspaceRoot, threadRef.environmentId, inspectCmd, gt]); + + const handleRunTrace = () => { + if (!workspaceRoot || !selectedFile || traceFrom.trim().length === 0) return; + setTraceRunning(true); + void traceCmd({ + environmentId: threadRef.environmentId, + input: { + cwd: workspaceRoot, + filePath: selectedFile, + from: traceFrom.trim(), + ...(traceTo.trim().length > 0 ? { to: traceTo.trim() } : {}), + traversePassives, + }, + }).then((result) => { + setTraceRunning(false); + if (result._tag === "Success") { + setTraceResult(result.value); + if (result.value.highlightedNets[0]) { + setSelectedNet(result.value.highlightedNets[0]); + } + } + }); + }; + + const handleRunValidate = () => { + if (!workspaceRoot || !selectedFile) return; + setValidationRunning(true); + void validateCmd({ + environmentId: threadRef.environmentId, + input: { cwd: workspaceRoot, filePath: selectedFile, useExternalToolchain: true }, + }).then((result) => { + setValidationRunning(false); + if (result._tag === "Success") { + setValidationReport(result.value); + } + }); + }; + + const handleRunSimulate = () => { + if (!workspaceRoot || !selectedFile) return; + setSimRunning(true); + setSimError(null); + void simulateCmd({ + environmentId: threadRef.environmentId, + input: { + cwd: workspaceRoot, + filePath: selectedFile, + kind: simKind, + ...(simOutputNode ? { outputNode: simOutputNode } : {}), + useExternalToolchain: true, + }, + }).then((result) => { + setSimRunning(false); + if (result._tag === "Success") { + setSimResult(result.value); + } else { + setSimError(gt("Simulation failed. Verify the circuit includes a ground node and source.")); + } + }); + }; + + const handleFocusIssue = (issue: ElectronicsValidationIssue) => { + if (issue.net) setSelectedNet(issue.net); + if (issue.refs[0]) setSelectedRef(issue.refs[0]); + setActiveTab("canvas"); + }; + + const handleStartTraceFrom = (endpoint: string) => { + setTraceFrom(endpoint); + setActiveTab("trace"); + }; + + const kicadAvailable = serviceState.toolchain.kicadCli.available; + const ngspiceAvailable = serviceState.toolchain.ngspice.available; + const errorCount = validationReport?.errorCount ?? 0; + const warningCount = validationReport?.warningCount ?? 0; + + return ( +
+
+ + + + + +
+ + kicad-cli + + + ngspice + +
+
+ +
+ {( + [ + { id: "canvas", label: gt("Canvas"), icon: CircuitBoardIcon }, + { id: "trace", label: gt("Path Tracer"), icon: RouteIcon }, + { id: "checks", label: gt("Checks"), icon: ShieldCheckIcon }, + { id: "simulate", label: gt("Simulate"), icon: ActivityIcon }, + { id: "bom", label: gt("BOM"), icon: PackageIcon }, + ] as const + ).map((tab) => { + const Icon = tab.icon; + const active = activeTab === tab.id; + return ( + + ); + })} +
+ + {!workspaceRoot ? ( +
+ +

+ Open a project workspace to inspect schematics, PCBs, and SPICE circuits. +

+
+ ) : loadingModel && !model ? ( +
+ + Parsing circuit… +
+ ) : errorMessage && !model ? ( +
+

{errorMessage}

+ +
+ ) : !model ? ( +
+ +
+

+ No electronics design files found in this workspace +

+

+ + Add a KiCad schematic (.kicad_sch), KiCad PCB (.kicad_pcb), SPICE netlist (.cir / + .spice), or tscircuit Circuit JSON (*.circuit.json) to inspect nets, validate + circuit paths, run ERC/DRC, and simulate waveforms. + +

+
+ +
+ ) : ( + <> +
+ {formatBadgeLabel(model.format)} + · + + {gt("{count} components", { + count: model.components.filter((c) => c.kind !== "power_symbol").length, + })} + + · + {gt("{count} nets", { count: model.nets.length })} + {model.title && ( + <> + · + {model.title} + + )} +
+ + {activeTab === "canvas" && ( + + )} + + {activeTab === "trace" && ( + { + if (net) setSelectedNet(net); + if (ref) setSelectedRef(ref); + setActiveTab("canvas"); + }} + /> + )} + + {activeTab === "checks" && ( + + )} + + {activeTab === "simulate" && ( + + )} + + {activeTab === "bom" && ( + { + setSelectedRef(ref); + setActiveTab("canvas"); + }} + /> + )} + + )} +
+ ); +} diff --git a/apps/web/src/components/electronics/ElectronicsSettings.tsx b/apps/web/src/components/electronics/ElectronicsSettings.tsx new file mode 100644 index 0000000000000..172483f37345b --- /dev/null +++ b/apps/web/src/components/electronics/ElectronicsSettings.tsx @@ -0,0 +1,192 @@ +import { AuthSettingsWriteScope } from "@t3tools/contracts"; +import { T, useGT } from "gt-react"; +import { CheckCircle2Icon, CircuitBoardIcon, RefreshCwIcon, XCircleIcon } from "lucide-react"; +import { useState } from "react"; + +import { Badge } from "../ui/badge"; +import { Button } from "../ui/button"; +import { Input } from "../ui/input"; +import { Switch } from "../ui/switch"; +import { SettingsPageContainer, SettingsRow, SettingsSection } from "../settings/settingsLayout"; +import { useSettingsScope } from "../settings/SettingsScopeContext"; +import { useScopedSettings, useUpdateScopedSettings } from "../settings/useScopedSettings"; +import { electronicsEnvironment, useElectronicsState } from "../../state/electronics"; +import { useEnvironmentScope } from "../../state/session"; +import { useAtomCommand } from "../../state/use-atom-command"; + +export function ElectronicsSettings() { + const gt = useGT(); + const { environment } = useSettingsScope(); + const environmentId = environment?.environmentId ?? null; + const settings = useScopedSettings(); + const updateSettings = useUpdateScopedSettings(); + const canWrite = useEnvironmentScope(environmentId, AuthSettingsWriteScope); + const { state } = useElectronicsState(environmentId); + const probeToolchain = useAtomCommand(electronicsEnvironment.toolchainStatus, { + reportFailure: false, + }); + + const [kicadPathDraft, setKicadPathDraft] = useState(settings.electronicsKicadCliPath); + const [ngspicePathDraft, setNgspicePathDraft] = useState(settings.electronicsNgspicePath); + const [probing, setProbing] = useState(false); + + const handleSavePaths = () => { + updateSettings({ + electronicsKicadCliPath: kicadPathDraft.trim(), + electronicsNgspicePath: ngspicePathDraft.trim(), + }); + }; + + const handleReprobe = () => { + if (!environmentId) return; + setProbing(true); + void probeToolchain({ environmentId, input: { refresh: true } }).then(() => { + setProbing(false); + }); + }; + + return ( + + + { + updateSettings({ enableElectronicsWorkbench: Boolean(checked) }); + }} + /> + } + /> + + { + updateSettings({ enableAgentElectronicsAccess: Boolean(checked) }); + }} + /> + } + /> + + { + updateSettings({ electronicsAllowExternalTools: Boolean(checked) }); + }} + /> + } + /> + + + +
+

+ + Optional binaries detected on this environment. Leave path overrides blank to + auto-detect from PATH. + +

+
+ {[state.toolchain.kicadCli, state.toolchain.ngspice].map((tool) => ( +
+
+
+ + {tool.name} +
+

+ {tool.available + ? (tool.version ?? tool.path ?? gt("Installed")) + : gt("Not detected (built-in TypeScript engine active)")} +

+
+ {tool.available ? ( + + + Ready + + ) : ( + + + Optional + + )} +
+ ))} +
+ +
+ + + +
+ +
+ + +
+
+
+
+ ); +} diff --git a/apps/web/src/components/electronics/PathTracerPanel.tsx b/apps/web/src/components/electronics/PathTracerPanel.tsx new file mode 100644 index 0000000000000..ddb64c99d0e42 --- /dev/null +++ b/apps/web/src/components/electronics/PathTracerPanel.tsx @@ -0,0 +1,200 @@ +import type { ElectronicsCircuitModel, ElectronicsTracePathResult } from "@t3tools/contracts"; +import { T, useGT } from "gt-react"; +import { + AlertTriangleIcon, + ArrowRightIcon, + CheckCircle2Icon, + RouteIcon, + XCircleIcon, +} from "lucide-react"; + +import { Button } from "../ui/button"; +import { Input } from "../ui/input"; + +export interface PathTracerPanelProps { + readonly model: ElectronicsCircuitModel; + readonly fromValue: string; + readonly toValue: string; + readonly traversePassives: boolean; + readonly running: boolean; + readonly result: ElectronicsTracePathResult | null; + readonly onChangeFrom: (value: string) => void; + readonly onChangeTo: (value: string) => void; + readonly onChangeTraversePassives: (value: boolean) => void; + readonly onRunTrace: () => void; + readonly onHighlightOnCanvas: (net: string | null, ref: string | null) => void; +} + +function formatOhms(ohms: number, directLabel: string): string { + if (ohms === 0) return directLabel; + if (ohms >= 1_000_000) return `${(ohms / 1_000_000).toFixed(2)} MΩ`; + if (ohms >= 1_000) return `${(ohms / 1_000).toFixed(2)} kΩ`; + return `${ohms.toFixed(1)} Ω`; +} + +export function PathTracerPanel(props: PathTracerPanelProps) { + const { + model, + fromValue, + toValue, + traversePassives, + running, + result, + onChangeFrom, + onChangeTo, + onChangeTraversePassives, + onRunTrace, + onHighlightOnCanvas, + } = props; + const gt = useGT(); + + const endpointSuggestions: string[] = []; + for (const net of model.nets) endpointSuggestions.push(net.name); + for (const comp of model.components) { + if (comp.kind === "power_symbol") continue; + endpointSuggestions.push(comp.ref); + for (const pin of comp.pins) { + endpointSuggestions.push(`${comp.ref}.${pin.number}`); + if (pin.name && pin.name !== pin.number) { + endpointSuggestions.push(`${comp.ref}.${pin.name}`); + } + } + } + const uniqueSuggestions = Array.from(new Set(endpointSuggestions)).slice(0, 180); + + return ( +
+
+
+ + Circuit Path Validator +
+
+ + +
+ + {uniqueSuggestions.map((opt) => ( + + +
+ + +
+
+ + {result && ( +
+
+
+ {result.connected ? ( + <> + + + Path Connected + + + ) : ( + <> + + + No Path Found + + + )} +
+ {result.estimatedResistanceOhms !== undefined && ( + + {gt("Series R ≈ {value}", { + value: formatOhms(result.estimatedResistanceOhms, gt("0 Ω (direct wire)")), + })} + + )} +
+ + {result.hops.length > 0 && ( +
+ {result.hops.map((hop, pos) => ( +
+ {pos > 0 && } + +
+ ))} +
+ )} + + {result.warnings.length > 0 && ( +
+ {result.warnings.map((w) => ( +
+ + {w} +
+ ))} +
+ )} +
+ )} +
+ ); +} diff --git a/apps/web/src/components/electronics/SimulationPanel.tsx b/apps/web/src/components/electronics/SimulationPanel.tsx new file mode 100644 index 0000000000000..bbc3b0a9eedbe --- /dev/null +++ b/apps/web/src/components/electronics/SimulationPanel.tsx @@ -0,0 +1,368 @@ +import type { + ElectronicsCircuitModel, + ElectronicsSimulationKind, + ElectronicsSimulationResult, +} from "@t3tools/contracts"; +import { T, useGT } from "gt-react"; +import { ActivityIcon, PlayIcon } from "lucide-react"; +import { useState } from "react"; + +import { Button } from "../ui/button"; + +export interface SimulationPanelProps { + readonly model: ElectronicsCircuitModel; + readonly kind: ElectronicsSimulationKind; + readonly outputNode: string; + readonly running: boolean; + readonly error: string | null; + readonly result: ElectronicsSimulationResult | null; + readonly onChangeKind: (kind: ElectronicsSimulationKind) => void; + readonly onChangeOutputNode: (node: string) => void; + readonly onRunSimulate: () => void; +} + +const TRACE_COLORS = [ + "var(--chart-1, #38bdf8)", + "var(--chart-2, #10b981)", + "var(--chart-3, #f59e0b)", + "var(--chart-4, #a855f7)", +]; + +function formatAxisTick(value: number, unit: string): string { + if (unit === "Hz") { + if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`; + if (value >= 1_000) return `${(value / 1_000).toFixed(1)}k`; + return `${value.toFixed(0)}`; + } + return Number(value.toPrecision(3)).toString(); +} + +function formatEngineering(value: number, unit: string): string { + const abs = Math.abs(value); + if (abs === 0) return `0 ${unit}`; + if (abs >= 1e6) return `${(value / 1e6).toPrecision(3)} M${unit}`; + if (abs >= 1e3) return `${(value / 1e3).toPrecision(3)} k${unit}`; + if (abs >= 1) return `${value.toPrecision(4)} ${unit}`; + if (abs >= 1e-3) return `${(value * 1e3).toPrecision(3)} m${unit}`; + if (abs >= 1e-6) return `${(value * 1e6).toPrecision(3)} µ${unit}`; + return `${value.toExponential(2)} ${unit}`; +} + +export function SimulationPanel(props: SimulationPanelProps) { + const { + model, + kind, + outputNode, + running, + error, + result, + onChangeKind, + onChangeOutputNode, + onRunSimulate, + } = props; + const gt = useGT(); + const [hoverIdx, setHoverIdx] = useState(null); + + const nonGroundNets = model.nets.filter((n) => !n.isGround); + + const chartW = 540; + const chartH = 210; + const padL = 48; + const padR = 16; + const padT = 16; + const padB = 28; + const plotW = chartW - padL - padR; + const plotH = chartH - padT - padB; + + const series = result?.series ?? []; + const allPoints = series.flatMap((s) => s.points); + const xLog = result?.xAxisLog ?? false; + + const xMin = allPoints.length > 0 ? Math.min(...allPoints.map((p) => p.x)) : 0; + const xMax = allPoints.length > 0 ? Math.max(...allPoints.map((p) => p.x)) : 1; + const rawYMin = allPoints.length > 0 ? Math.min(...allPoints.map((p) => p.y)) : 0; + const rawYMax = allPoints.length > 0 ? Math.max(...allPoints.map((p) => p.y)) : 1; + const ySpan = Math.max(1e-6, rawYMax - rawYMin); + const yMin = rawYMin - ySpan * 0.08; + const yMax = rawYMax + ySpan * 0.08; + + const mapX = (x: number): number => { + if (xLog && xMin > 0 && xMax > xMin) { + const frac = + (Math.log10(Math.max(xMin, x)) - Math.log10(xMin)) / (Math.log10(xMax) - Math.log10(xMin)); + return padL + frac * plotW; + } + const span = Math.max(1e-9, xMax - xMin); + return padL + ((x - xMin) / span) * plotW; + }; + const mapY = (y: number): number => padT + (1 - (y - yMin) / Math.max(1e-9, yMax - yMin)) * plotH; + + const primarySeries = series[0]; + const hoveredPoint = + hoverIdx !== null && primarySeries ? (primarySeries.points[hoverIdx] ?? null) : null; + + return ( +
+
+ + + + +
+ +
+
+ + {error && ( +
+ {error} +
+ )} + + {result && ( + <> +
+ + {result.engine === "ngspice" ? gt("ngspice") : gt("Built-in MNA Solver")} + + {result.metrics.map((metric) => ( +
+ {metric.name}: + + {formatEngineering(metric.value, metric.unit)} + +
+ ))} +
+ + {series.length > 0 && ( +
+
+
+ + {series.map((s, idx) => ( + + + {s.label} ({s.unit}) + + ))} +
+ {hoveredPoint && ( + + {formatAxisTick(hoveredPoint.x, result.xAxisUnit)} {result.xAxisUnit} ·{" "} + {hoveredPoint.y.toFixed(2)} {primarySeries?.unit} + {hoveredPoint.phaseDeg !== undefined ? ` · ${hoveredPoint.phaseDeg}°` : ""} + + )} +
+ + setHoverIdx(null)} + onMouseMove={(e) => { + if (!primarySeries || primarySeries.points.length === 0) return; + const rect = e.currentTarget.getBoundingClientRect(); + const relX = ((e.clientX - rect.left) / Math.max(1, rect.width)) * chartW; + const frac = Math.max(0, Math.min(1, (relX - padL) / plotW)); + const idx = Math.round(frac * (primarySeries.points.length - 1)); + setHoverIdx(idx); + }} + > + {[0, 0.25, 0.5, 0.75, 1].map((f) => { + const yVal = yMin + f * (yMax - yMin); + const yPos = mapY(yVal); + return ( + + + + {yVal.toFixed(1)} + + + ); + })} + + {[0, 0.25, 0.5, 0.75, 1].map((f) => { + const xVal = + xLog && xMin > 0 ? xMin * Math.pow(xMax / xMin, f) : xMin + f * (xMax - xMin); + const xPos = padL + f * plotW; + return ( + + {formatAxisTick(xVal, result.xAxisUnit)} + + ); + })} + + {series.map((s, idx) => { + const pts = s.points + .map((p) => `${mapX(p.x).toFixed(1)},${mapY(p.y).toFixed(1)}`) + .join(" "); + return ( + + ); + })} + + {hoveredPoint && ( + + + + + )} + +
+ )} + + {result.nodeVoltages.length > 0 && ( +
+
+ DC Node Voltages +
+
+ {result.nodeVoltages.map((nv) => ( +
+ {nv.node} + + {nv.voltageV.toFixed(4)} V + +
+ ))} +
+
+ )} + + {result.componentReadings.length > 0 && ( +
+ + + + + + + + + + + + {result.componentReadings.map((row) => ( + + + + + + + + ))} + +
+ Ref + + Value + + ΔV + + Current + + Power +
{row.ref}{row.value}{row.voltageDropV.toFixed(3)} V + {formatEngineering(row.currentA, "A")} + + {formatEngineering(row.powerW, "W")} +
+
+ )} + + {result.notes.length > 0 && ( +
+ {result.notes.map((n) => ( +

{n}

+ ))} +
+ )} + + )} +
+ ); +} diff --git a/apps/web/src/components/electronics/ValidationPanel.tsx b/apps/web/src/components/electronics/ValidationPanel.tsx new file mode 100644 index 0000000000000..9cfdaccb5fec5 --- /dev/null +++ b/apps/web/src/components/electronics/ValidationPanel.tsx @@ -0,0 +1,169 @@ +import type { + ElectronicsValidationIssue, + ElectronicsValidationReport, + ElectronicsValidationSeverity, +} from "@t3tools/contracts"; +import { T, useGT } from "gt-react"; +import { + AlertCircleIcon, + AlertTriangleIcon, + CheckCircle2Icon, + InfoIcon, + RefreshCwIcon, +} from "lucide-react"; +import { useState } from "react"; + +import { Button } from "../ui/button"; + +export interface ValidationPanelProps { + readonly report: ElectronicsValidationReport | null; + readonly running: boolean; + readonly onRunValidate: () => void; + readonly onFocusIssue: (issue: ElectronicsValidationIssue) => void; +} + +export function ValidationPanel(props: ValidationPanelProps) { + const { report, running, onRunValidate, onFocusIssue } = props; + const gt = useGT(); + const [filter, setFilter] = useState<"all" | ElectronicsValidationSeverity>("all"); + + const filteredIssues = !report + ? [] + : filter === "all" + ? report.issues + : report.issues.filter((i) => i.severity === filter); + + return ( +
+
+
+ {report ? ( + <> + {report.passed ? ( + + + All error checks passed + + ) : ( + + + {gt("{count} error(s) found", { count: report.errorCount })} + + )} + + · {gt("{count} warnings", { count: report.warningCount })} ·{" "} + {gt("{count} info", { count: report.infoCount })} + + + ) : ( + + Run ERC/DRC and static circuit validation to inspect electrical rules. + + )} +
+ + +
+ + {report && ( + <> +
+
+ {(["all", "error", "warning", "info"] as const).map((sev) => ( + + ))} +
+
+ {report.enginesUsed.map((eng) => ( + + {eng === "builtin" + ? gt("Built-in") + : eng === "kicad_erc" + ? gt("KiCad ERC") + : gt("KiCad DRC")} + + ))} +
+
+ + {filteredIssues.length === 0 ? ( +
+ No diagnostics match the selected filter. +
+ ) : ( +
+ {filteredIssues.map((issue) => ( + + ))} +
+ )} + + {report.notes.length > 0 && ( +
+ {report.notes.map((note) => ( +

{note}

+ ))} +
+ )} + + )} +
+ ); +} diff --git a/apps/web/src/components/preview/agentOpenedPreviews.ts b/apps/web/src/components/preview/agentOpenedPreviews.ts index 8255cc48a551d..8f760fc1b885a 100644 --- a/apps/web/src/components/preview/agentOpenedPreviews.ts +++ b/apps/web/src/components/preview/agentOpenedPreviews.ts @@ -5,6 +5,7 @@ import { } from "@t3tools/client-runtime/environment"; import type { DeviceServiceState, + ElectronicsServiceState, EnvironmentId, PreviewSessionSnapshot, ScopedThreadRef, @@ -27,6 +28,7 @@ import { useRightPanelStore } from "../../rightPanelStore"; import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../../rightPanelLayout"; import { appAtomRegistry } from "../../rpc/atomRegistry"; import { deviceEnvironment } from "../../state/device"; +import { electronicsEnvironment } from "../../state/electronics"; import { readEnvironmentSupportsServerBrowser } from "../../state/entities"; import { environmentSummaries } from "../../state/presentation"; @@ -217,8 +219,27 @@ export function resetDeviceSessionBaselinesForTests(): void { deviceSessionBaselines.clear(); } +const electronicsSessionBaselines = new Map>(); + +function applyElectronicsSnapshot( + environmentId: EnvironmentId, + state: ElectronicsServiceState, +): void { + const previous = electronicsSessionBaselines.get(environmentId); + const next = new Map(); + for (const session of state.sessions) { + next.set(session.threadId, session.updatedAt); + if (previous !== undefined && previous.get(session.threadId) !== session.updatedAt) { + useRightPanelStore + .getState() + .open(scopeThreadRef(environmentId, session.threadId), "electronics"); + } + } + electronicsSessionBaselines.set(environmentId, next); +} + function watchEnvironmentDevices(environmentId: EnvironmentId): () => void { - return appAtomRegistry.subscribe( + const stopDevices = appAtomRegistry.subscribe( deviceEnvironment.state({ environmentId, input: {} }), (result) => { const state = AsyncResult.getOrElse(result, () => null); @@ -230,6 +251,20 @@ function watchEnvironmentDevices(environmentId: EnvironmentId): () => void { }, { immediate: true }, ); + const stopElectronics = appAtomRegistry.subscribe( + electronicsEnvironment.state({ environmentId, input: {} }), + (result) => { + const state = AsyncResult.getOrElse(result, () => null); + if (state === null) return; + applyElectronicsSnapshot(environmentId, state); + }, + { immediate: true }, + ); + return () => { + stopDevices(); + stopElectronics(); + electronicsSessionBaselines.delete(environmentId); + }; } /** diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx index 10bc07c123dd8..c4b4d26d054c2 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -13,6 +13,7 @@ import { BotIcon, createLucideIcon, CalendarClockIcon, + CircuitBoardIcon, FileDiffIcon, FolderTreeIcon, GitBranchIcon, @@ -105,6 +106,7 @@ const SETTINGS_SECTION_ICONS: Readonly< "/settings/threads": MessagesSquareIcon, "/settings/browser": GlobeIcon, "/settings/devices": SmartphoneIcon, + "/settings/electronics": CircuitBoardIcon, "/settings/scheduled-tasks": CalendarClockIcon, "/settings/source-control": GitBranchIcon, "/settings/worktrees": FolderTreeIcon, diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index d91d6da4a42d7..b811e5e742c2f 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -31,6 +31,7 @@ export type SettingsPath = | "/settings/threads" | "/settings/browser" | "/settings/devices" + | "/settings/electronics" | "/settings/scheduled-tasks" | "/settings/source-control" | "/settings/worktrees" @@ -107,6 +108,7 @@ export const SETTINGS_SECTION_LABELS: Readonly> = { "/settings/threads": msg("Threads"), "/settings/browser": msg("Browser"), "/settings/devices": msg("Devices"), + "/settings/electronics": msg("Electronics"), "/settings/scheduled-tasks": msg("Scheduled tasks"), "/settings/source-control": msg("Source control & issues"), "/settings/worktrees": msg("Worktrees"), @@ -157,6 +159,7 @@ const ALL_SETTINGS_NAV_GROUPS: ReadonlyArray = [ "/settings/threads", "/settings/browser", "/settings/devices", + "/settings/electronics", "/settings/scheduled-tasks", ], }, @@ -1102,6 +1105,24 @@ export const SETTINGS_SEARCH_ITEMS = [ scope: "project-defaults", searchTerms: [msg("allow disable enable open drive preview tools sessions project override")], }, + { + id: "electronics-workbench-enabled", + title: msg("Electronics Workbench"), + to: "/settings/electronics", + targetId: "electronics-workbench-enabled", + scope: "environment", + searchTerms: [ + msg("electronics kicad spice pcb schematic circuit erc drc ngspice simulation path"), + ], + }, + { + id: "electronics-agent-access", + title: msg("Allow agent MCP access (Electronics)"), + to: "/settings/electronics", + targetId: "electronics-agent-access", + scope: "environment", + searchTerms: [msg("electronics mcp agent kicad spice validate simulate trace")], + }, { id: "device-sources", title: msg("Device sources"), @@ -1510,6 +1531,7 @@ const SETTINGS_CATEGORY_SCOPES: Readonly ChatSettingsRoute, } as any) +const ChatSettingsElectronicsRoute = ChatSettingsElectronicsRouteImport.update({ + id: '/electronics', + path: '/electronics', + getParentRoute: () => ChatSettingsRoute, +} as any) const ChatSettingsDiffsRoute = ChatSettingsDiffsRouteImport.update({ id: '/diffs', path: '/diffs', @@ -316,6 +322,7 @@ export interface FileRoutesByFullPath { '/settings/devices': typeof ChatSettingsDevicesRoute '/settings/diagnostics': typeof ChatSettingsDiagnosticsRoute '/settings/diffs': typeof ChatSettingsDiffsRoute + '/settings/electronics': typeof ChatSettingsElectronicsRoute '/settings/general': typeof ChatSettingsGeneralRoute '/settings/integrations': typeof ChatSettingsIntegrationsRoute '/settings/keybindings': typeof ChatSettingsKeybindingsRoute @@ -362,6 +369,7 @@ export interface FileRoutesByTo { '/settings/devices': typeof ChatSettingsDevicesRoute '/settings/diagnostics': typeof ChatSettingsDiagnosticsRoute '/settings/diffs': typeof ChatSettingsDiffsRoute + '/settings/electronics': typeof ChatSettingsElectronicsRoute '/settings/general': typeof ChatSettingsGeneralRoute '/settings/integrations': typeof ChatSettingsIntegrationsRoute '/settings/keybindings': typeof ChatSettingsKeybindingsRoute @@ -410,6 +418,7 @@ export interface FileRoutesById { '/_chat/settings/devices': typeof ChatSettingsDevicesRoute '/_chat/settings/diagnostics': typeof ChatSettingsDiagnosticsRoute '/_chat/settings/diffs': typeof ChatSettingsDiffsRoute + '/_chat/settings/electronics': typeof ChatSettingsElectronicsRoute '/_chat/settings/general': typeof ChatSettingsGeneralRoute '/_chat/settings/integrations': typeof ChatSettingsIntegrationsRoute '/_chat/settings/keybindings': typeof ChatSettingsKeybindingsRoute @@ -458,6 +467,7 @@ export interface FileRouteTypes { | '/settings/devices' | '/settings/diagnostics' | '/settings/diffs' + | '/settings/electronics' | '/settings/general' | '/settings/integrations' | '/settings/keybindings' @@ -504,6 +514,7 @@ export interface FileRouteTypes { | '/settings/devices' | '/settings/diagnostics' | '/settings/diffs' + | '/settings/electronics' | '/settings/general' | '/settings/integrations' | '/settings/keybindings' @@ -551,6 +562,7 @@ export interface FileRouteTypes { | '/_chat/settings/devices' | '/_chat/settings/diagnostics' | '/_chat/settings/diffs' + | '/_chat/settings/electronics' | '/_chat/settings/general' | '/_chat/settings/integrations' | '/_chat/settings/keybindings' @@ -802,6 +814,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ChatSettingsGeneralRouteImport parentRoute: typeof ChatSettingsRoute } + '/_chat/settings/electronics': { + id: '/_chat/settings/electronics' + path: '/electronics' + fullPath: '/settings/electronics' + preLoaderRoute: typeof ChatSettingsElectronicsRouteImport + parentRoute: typeof ChatSettingsRoute + } '/_chat/settings/diffs': { id: '/_chat/settings/diffs' path: '/diffs' @@ -915,6 +934,7 @@ interface ChatSettingsRouteChildren { ChatSettingsDevicesRoute: typeof ChatSettingsDevicesRoute ChatSettingsDiagnosticsRoute: typeof ChatSettingsDiagnosticsRoute ChatSettingsDiffsRoute: typeof ChatSettingsDiffsRoute + ChatSettingsElectronicsRoute: typeof ChatSettingsElectronicsRoute ChatSettingsGeneralRoute: typeof ChatSettingsGeneralRoute ChatSettingsIntegrationsRoute: typeof ChatSettingsIntegrationsRoute ChatSettingsKeybindingsRoute: typeof ChatSettingsKeybindingsRoute @@ -945,6 +965,7 @@ const ChatSettingsRouteChildren: ChatSettingsRouteChildren = { ChatSettingsDevicesRoute: ChatSettingsDevicesRoute, ChatSettingsDiagnosticsRoute: ChatSettingsDiagnosticsRoute, ChatSettingsDiffsRoute: ChatSettingsDiffsRoute, + ChatSettingsElectronicsRoute: ChatSettingsElectronicsRoute, ChatSettingsGeneralRoute: ChatSettingsGeneralRoute, ChatSettingsIntegrationsRoute: ChatSettingsIntegrationsRoute, ChatSettingsKeybindingsRoute: ChatSettingsKeybindingsRoute, diff --git a/apps/web/src/routes/_chat.settings.electronics.tsx b/apps/web/src/routes/_chat.settings.electronics.tsx new file mode 100644 index 0000000000000..d60131787f55a --- /dev/null +++ b/apps/web/src/routes/_chat.settings.electronics.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from "@tanstack/react-router"; +import { ElectronicsSettings } from "../components/electronics/ElectronicsSettings"; + +export const Route = createFileRoute("/_chat/settings/electronics")({ + component: ElectronicsSettings, +}); diff --git a/apps/web/src/state/electronics.ts b/apps/web/src/state/electronics.ts new file mode 100644 index 0000000000000..9f265c06818d1 --- /dev/null +++ b/apps/web/src/state/electronics.ts @@ -0,0 +1,39 @@ +import { createElectronicsEnvironmentAtoms } from "@t3tools/client-runtime/state/electronics"; +import type { ElectronicsServiceState, EnvironmentId } from "@t3tools/contracts"; +import { useMessages } from "gt-react"; + +import { connectionAtomRuntime } from "../connection/runtime"; +import { useEnvironmentQuery } from "./query"; + +export const electronicsEnvironment = createElectronicsEnvironmentAtoms(connectionAtomRuntime); + +const EMPTY_ELECTRONICS_STATE: ElectronicsServiceState = { + toolchain: { + enabled: true, + allowExternalTools: true, + agentAccessEnabled: true, + kicadCli: { name: "kicad-cli", available: false }, + ngspice: { name: "ngspice", available: false }, + checkedAt: "", + }, + sessions: [], +}; + +export function useElectronicsState(environmentId: EnvironmentId | null): { + readonly state: ElectronicsServiceState; + readonly loaded: boolean; + readonly error: string | null; + readonly refresh: () => void; +} { + const resolve = useMessages(); + const query = useEnvironmentQuery( + environmentId === null ? null : electronicsEnvironment.state({ environmentId, input: {} }), + resolve, + ); + return { + state: query.data ?? EMPTY_ELECTRONICS_STATE, + loaded: query.data !== null, + error: query.error, + refresh: query.refresh, + }; +} diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index fee70319c71de..0a816879055f4 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -295,6 +295,10 @@ "types": "./src/state/deviceHubAccess.ts", "default": "./src/state/deviceHubAccess.ts" }, + "./state/electronics": { + "types": "./src/state/electronics.ts", + "default": "./src/state/electronics.ts" + }, "./state/previewTunnel": { "types": "./src/state/previewTunnel.ts", "default": "./src/state/previewTunnel.ts" diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index 11588aa329ee0..0f22279e0f219 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -77,6 +77,7 @@ export type EnvironmentSubscriptionRpcTag = | typeof WS_METHODS.subscribePreviewEvents | typeof WS_METHODS.subscribeDiscoveredLocalServers | typeof WS_METHODS.subscribeDeviceState + | typeof WS_METHODS.subscribeElectronicsState | typeof WS_METHODS.subscribeResourceTelemetry | typeof WS_METHODS.pullRequestsSubscribeRefreshes | typeof WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes diff --git a/packages/client-runtime/src/state/electronics.ts b/packages/client-runtime/src/state/electronics.ts new file mode 100644 index 0000000000000..66150cf203dee --- /dev/null +++ b/packages/client-runtime/src/state/electronics.ts @@ -0,0 +1,51 @@ +import { WS_METHODS } from "@t3tools/contracts"; +import type { Atom } from "effect/reactivity"; + +import type { EnvironmentRegistry } from "../connection/registry.ts"; +import { + createEnvironmentRpcCommand, + createEnvironmentRpcSubscriptionAtomFamily, +} from "./runtime.ts"; + +export function createElectronicsEnvironmentAtoms( + runtime: Atom.AtomRuntime, +) { + return { + state: createEnvironmentRpcSubscriptionAtomFamily(runtime, { + label: "environment-data:electronics:state", + tag: WS_METHODS.subscribeElectronicsState, + }), + listFiles: createEnvironmentRpcCommand(runtime, { + label: "environment-data:electronics:list-files", + tag: WS_METHODS.electronicsListFiles, + }), + inspect: createEnvironmentRpcCommand(runtime, { + label: "environment-data:electronics:inspect", + tag: WS_METHODS.electronicsInspect, + }), + tracePath: createEnvironmentRpcCommand(runtime, { + label: "environment-data:electronics:trace-path", + tag: WS_METHODS.electronicsTracePath, + }), + validate: createEnvironmentRpcCommand(runtime, { + label: "environment-data:electronics:validate", + tag: WS_METHODS.electronicsValidate, + }), + simulate: createEnvironmentRpcCommand(runtime, { + label: "environment-data:electronics:simulate", + tag: WS_METHODS.electronicsSimulate, + }), + toolchainStatus: createEnvironmentRpcCommand(runtime, { + label: "environment-data:electronics:toolchain-status", + tag: WS_METHODS.electronicsToolchainStatus, + }), + openPanel: createEnvironmentRpcCommand(runtime, { + label: "environment-data:electronics:open-panel", + tag: WS_METHODS.electronicsOpenPanel, + }), + closePanel: createEnvironmentRpcCommand(runtime, { + label: "environment-data:electronics:close-panel", + tag: WS_METHODS.electronicsClosePanel, + }), + }; +} diff --git a/packages/contracts/src/electronics.ts b/packages/contracts/src/electronics.ts new file mode 100644 index 0000000000000..18f2125b424a0 --- /dev/null +++ b/packages/contracts/src/electronics.ts @@ -0,0 +1,464 @@ +import * as Schema from "effect/Schema"; + +import { ThreadId, TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts"; + +export const ElectronicsDesignFormat = Schema.Literals([ + "kicad_sch", + "kicad_pcb", + "spice", + "circuit_json", +]); +export type ElectronicsDesignFormat = typeof ElectronicsDesignFormat.Type; + +export const ElectronicsPinElectricalType = Schema.Literals([ + "input", + "output", + "bidirectional", + "tri_state", + "passive", + "power_in", + "power_out", + "open_collector", + "open_emitter", + "unconnected", + "unspecified", +]); +export type ElectronicsPinElectricalType = typeof ElectronicsPinElectricalType.Type; + +export const ElectronicsComponentKind = Schema.Literals([ + "resistor", + "capacitor", + "inductor", + "diode", + "transistor", + "ic", + "connector", + "power_source", + "power_symbol", + "switch", + "fuse", + "crystal", + "other", +]); +export type ElectronicsComponentKind = typeof ElectronicsComponentKind.Type; + +export const ElectronicsPoint = Schema.Struct({ + x: Schema.Number, + y: Schema.Number, +}); +export type ElectronicsPoint = typeof ElectronicsPoint.Type; + +export const ElectronicsPin = Schema.Struct({ + number: Schema.String, + name: Schema.optional(Schema.String), + electricalType: ElectronicsPinElectricalType, + net: Schema.optional(Schema.String), + x: Schema.optional(Schema.Number), + y: Schema.optional(Schema.Number), +}); +export type ElectronicsPin = typeof ElectronicsPin.Type; + +export const ElectronicsComponent = Schema.Struct({ + ref: Schema.String, + value: Schema.String, + kind: ElectronicsComponentKind, + libId: Schema.optional(Schema.String), + footprint: Schema.optional(Schema.String), + x: Schema.optional(Schema.Number), + y: Schema.optional(Schema.Number), + rotation: Schema.optional(Schema.Number), + layer: Schema.optional(Schema.String), + pins: Schema.Array(ElectronicsPin), +}); +export type ElectronicsComponent = typeof ElectronicsComponent.Type; + +export const ElectronicsNetPinRef = Schema.Struct({ + ref: Schema.String, + pin: Schema.String, + pinName: Schema.optional(Schema.String), + electricalType: ElectronicsPinElectricalType, +}); +export type ElectronicsNetPinRef = typeof ElectronicsNetPinRef.Type; + +export const ElectronicsNet = Schema.Struct({ + name: Schema.String, + code: Schema.optional(Schema.Int), + isPower: Schema.Boolean, + isGround: Schema.Boolean, + pins: Schema.Array(ElectronicsNetPinRef), +}); +export type ElectronicsNet = typeof ElectronicsNet.Type; + +export const ElectronicsWireSegment = Schema.Struct({ + x1: Schema.Number, + y1: Schema.Number, + x2: Schema.Number, + y2: Schema.Number, + layer: Schema.optional(Schema.String), + width: Schema.optional(Schema.Number), + net: Schema.optional(Schema.String), +}); +export type ElectronicsWireSegment = typeof ElectronicsWireSegment.Type; + +export const ElectronicsVia = Schema.Struct({ + x: Schema.Number, + y: Schema.Number, + size: Schema.Number, + drill: Schema.optional(Schema.Number), + net: Schema.optional(Schema.String), +}); +export type ElectronicsVia = typeof ElectronicsVia.Type; + +export const ElectronicsLabelMarker = Schema.Struct({ + text: Schema.String, + kind: Schema.Literals(["local", "global", "hierarchical", "power"]), + x: Schema.Number, + y: Schema.Number, +}); +export type ElectronicsLabelMarker = typeof ElectronicsLabelMarker.Type; + +export const ElectronicsBomEntry = Schema.Struct({ + value: Schema.String, + footprint: Schema.optional(Schema.String), + libId: Schema.optional(Schema.String), + kind: ElectronicsComponentKind, + refs: Schema.Array(Schema.String), + quantity: Schema.Int, +}); +export type ElectronicsBomEntry = typeof ElectronicsBomEntry.Type; + +export const ElectronicsBounds = Schema.Struct({ + minX: Schema.Number, + minY: Schema.Number, + maxX: Schema.Number, + maxY: Schema.Number, +}); +export type ElectronicsBounds = typeof ElectronicsBounds.Type; + +export const ElectronicsCircuitModel = Schema.Struct({ + format: ElectronicsDesignFormat, + filePath: Schema.String, + title: Schema.optional(Schema.String), + layers: Schema.Array(Schema.String), + bounds: ElectronicsBounds, + components: Schema.Array(ElectronicsComponent), + nets: Schema.Array(ElectronicsNet), + wires: Schema.Array(ElectronicsWireSegment), + vias: Schema.Array(ElectronicsVia), + junctions: Schema.Array(ElectronicsPoint), + noConnects: Schema.Array(ElectronicsPoint), + labels: Schema.Array(ElectronicsLabelMarker), + boardOutline: Schema.Array(ElectronicsWireSegment), + bom: Schema.Array(ElectronicsBomEntry), + parseWarnings: Schema.Array(Schema.String), +}); +export type ElectronicsCircuitModel = typeof ElectronicsCircuitModel.Type; + +export const ElectronicsPathHop = Schema.Struct({ + kind: Schema.Literals(["net", "component"]), + name: Schema.String, + value: Schema.optional(Schema.String), + fromPin: Schema.optional(Schema.String), + toPin: Schema.optional(Schema.String), + componentKind: Schema.optional(ElectronicsComponentKind), +}); +export type ElectronicsPathHop = typeof ElectronicsPathHop.Type; + +export const ElectronicsTracePathResult = Schema.Struct({ + filePath: Schema.String, + from: Schema.String, + to: Schema.optional(Schema.String), + connected: Schema.Boolean, + directNet: Schema.optional(Schema.String), + fromNets: Schema.Array(Schema.String), + toNets: Schema.Array(Schema.String), + hops: Schema.Array(ElectronicsPathHop), + highlightedNets: Schema.Array(Schema.String), + highlightedComponents: Schema.Array(Schema.String), + estimatedResistanceOhms: Schema.optional(Schema.Number), + warnings: Schema.Array(Schema.String), +}); +export type ElectronicsTracePathResult = typeof ElectronicsTracePathResult.Type; + +export const ElectronicsValidationSeverity = Schema.Literals(["error", "warning", "info"]); +export type ElectronicsValidationSeverity = typeof ElectronicsValidationSeverity.Type; + +export const ElectronicsValidationSource = Schema.Literals(["builtin", "kicad_erc", "kicad_drc"]); +export type ElectronicsValidationSource = typeof ElectronicsValidationSource.Type; + +export const ElectronicsValidationIssue = Schema.Struct({ + id: Schema.String, + code: Schema.String, + severity: ElectronicsValidationSeverity, + source: ElectronicsValidationSource, + message: Schema.String, + net: Schema.optional(Schema.String), + refs: Schema.Array(Schema.String), + x: Schema.optional(Schema.Number), + y: Schema.optional(Schema.Number), +}); +export type ElectronicsValidationIssue = typeof ElectronicsValidationIssue.Type; + +export const ElectronicsValidationReport = Schema.Struct({ + filePath: Schema.String, + format: ElectronicsDesignFormat, + passed: Schema.Boolean, + errorCount: Schema.Int, + warningCount: Schema.Int, + infoCount: Schema.Int, + enginesUsed: Schema.Array(ElectronicsValidationSource), + notes: Schema.Array(Schema.String), + issues: Schema.Array(ElectronicsValidationIssue), + checkedAt: Schema.String, +}); +export type ElectronicsValidationReport = typeof ElectronicsValidationReport.Type; + +export const ElectronicsSimulationKind = Schema.Literals(["dc_op", "ac_sweep", "transient"]); +export type ElectronicsSimulationKind = typeof ElectronicsSimulationKind.Type; + +export const ElectronicsSimulationEngine = Schema.Literals(["ngspice", "builtin_mna"]); +export type ElectronicsSimulationEngine = typeof ElectronicsSimulationEngine.Type; + +export const ElectronicsSimulationNodeVoltage = Schema.Struct({ + node: Schema.String, + voltageV: Schema.Number, +}); +export type ElectronicsSimulationNodeVoltage = typeof ElectronicsSimulationNodeVoltage.Type; + +export const ElectronicsSimulationComponentReading = Schema.Struct({ + ref: Schema.String, + value: Schema.String, + voltageDropV: Schema.Number, + currentA: Schema.Number, + powerW: Schema.Number, +}); +export type ElectronicsSimulationComponentReading = + typeof ElectronicsSimulationComponentReading.Type; + +export const ElectronicsSimulationTraceSeries = Schema.Struct({ + label: Schema.String, + unit: Schema.String, + points: Schema.Array( + Schema.Struct({ + x: Schema.Number, + y: Schema.Number, + phaseDeg: Schema.optional(Schema.Number), + }), + ), +}); +export type ElectronicsSimulationTraceSeries = typeof ElectronicsSimulationTraceSeries.Type; + +export const ElectronicsSimulationMetric = Schema.Struct({ + name: Schema.String, + value: Schema.Number, + unit: Schema.String, +}); +export type ElectronicsSimulationMetric = typeof ElectronicsSimulationMetric.Type; + +export const ElectronicsSimulationResult = Schema.Struct({ + filePath: Schema.String, + kind: ElectronicsSimulationKind, + engine: ElectronicsSimulationEngine, + xAxisLabel: Schema.String, + xAxisUnit: Schema.String, + xAxisLog: Schema.Boolean, + nodeVoltages: Schema.Array(ElectronicsSimulationNodeVoltage), + componentReadings: Schema.Array(ElectronicsSimulationComponentReading), + series: Schema.Array(ElectronicsSimulationTraceSeries), + metrics: Schema.Array(ElectronicsSimulationMetric), + notes: Schema.Array(Schema.String), + simulatedAt: Schema.String, +}); +export type ElectronicsSimulationResult = typeof ElectronicsSimulationResult.Type; + +export const ElectronicsToolBinaryStatus = Schema.Struct({ + name: Schema.Literals(["kicad-cli", "ngspice"]), + available: Schema.Boolean, + path: Schema.optional(Schema.String), + version: Schema.optional(Schema.String), + error: Schema.optional(Schema.String), +}); +export type ElectronicsToolBinaryStatus = typeof ElectronicsToolBinaryStatus.Type; + +export const ElectronicsToolchainStatus = Schema.Struct({ + enabled: Schema.Boolean, + allowExternalTools: Schema.Boolean, + agentAccessEnabled: Schema.Boolean, + kicadCli: ElectronicsToolBinaryStatus, + ngspice: ElectronicsToolBinaryStatus, + checkedAt: Schema.String, +}); +export type ElectronicsToolchainStatus = typeof ElectronicsToolchainStatus.Type; + +export const ElectronicsWorkspaceFile = Schema.Struct({ + relativePath: Schema.String, + name: Schema.String, + format: ElectronicsDesignFormat, + sizeBytes: Schema.Int, +}); +export type ElectronicsWorkspaceFile = typeof ElectronicsWorkspaceFile.Type; + +export const ElectronicsPanelTab = Schema.Literals([ + "canvas", + "trace", + "checks", + "simulate", + "bom", +]); +export type ElectronicsPanelTab = typeof ElectronicsPanelTab.Type; + +export const ElectronicsThreadSession = Schema.Struct({ + threadId: ThreadId, + filePath: Schema.String, + format: ElectronicsDesignFormat, + activeTab: ElectronicsPanelTab, + selectedNet: Schema.optional(Schema.String), + lastTrace: Schema.optional(ElectronicsTracePathResult), + lastValidation: Schema.optional(ElectronicsValidationReport), + lastSimulation: Schema.optional(ElectronicsSimulationResult), + openedAt: Schema.String, + updatedAt: Schema.String, +}); +export type ElectronicsThreadSession = typeof ElectronicsThreadSession.Type; + +export const ElectronicsServiceState = Schema.Struct({ + toolchain: ElectronicsToolchainStatus, + sessions: Schema.Array(ElectronicsThreadSession), +}); +export type ElectronicsServiceState = typeof ElectronicsServiceState.Type; + +export class ElectronicsError extends Schema.TaggedError()("ElectronicsError", { + code: Schema.Literals([ + "disabled", + "not_found", + "invalid_path", + "unsupported_format", + "parse_failed", + "simulation_failed", + "toolchain_unavailable", + "internal", + ]), + message: Schema.String, +}) {} + +// RPC payloads +export const ElectronicsListFilesInput = Schema.Struct({ + cwd: TrimmedNonEmptyString, +}); +export type ElectronicsListFilesInput = typeof ElectronicsListFilesInput.Type; + +export const ElectronicsListFilesResult = Schema.Struct({ + files: Schema.Array(ElectronicsWorkspaceFile), + toolchain: ElectronicsToolchainStatus, +}); +export type ElectronicsListFilesResult = typeof ElectronicsListFilesResult.Type; + +export const ElectronicsInspectInput = Schema.Struct({ + cwd: TrimmedNonEmptyString, + filePath: TrimmedNonEmptyString, +}); +export type ElectronicsInspectInput = typeof ElectronicsInspectInput.Type; + +export const ElectronicsTracePathInput = Schema.Struct({ + cwd: TrimmedNonEmptyString, + filePath: TrimmedNonEmptyString, + from: TrimmedNonEmptyString, + to: Schema.optional(TrimmedNonEmptyString), + traversePassives: Schema.optional(Schema.Boolean), + maxHops: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 16 }))), +}); +export type ElectronicsTracePathInput = typeof ElectronicsTracePathInput.Type; + +export const ElectronicsValidateInput = Schema.Struct({ + cwd: TrimmedNonEmptyString, + filePath: TrimmedNonEmptyString, + useExternalToolchain: Schema.optional(Schema.Boolean), +}); +export type ElectronicsValidateInput = typeof ElectronicsValidateInput.Type; + +export const ElectronicsSimulateInput = Schema.Struct({ + cwd: TrimmedNonEmptyString, + filePath: TrimmedNonEmptyString, + kind: Schema.optional(ElectronicsSimulationKind), + outputNode: Schema.optional(TrimmedNonEmptyString), + startFreqHz: Schema.optional(Schema.Number), + stopFreqHz: Schema.optional(Schema.Number), + pointsPerDecade: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 2, maximum: 50 }))), + stopTimeSeconds: Schema.optional(Schema.Number), + stepTimeSeconds: Schema.optional(Schema.Number), + useExternalToolchain: Schema.optional(Schema.Boolean), +}); +export type ElectronicsSimulateInput = typeof ElectronicsSimulateInput.Type; + +export const ElectronicsOpenPanelInput = Schema.Struct({ + threadId: ThreadId, + cwd: TrimmedNonEmptyString, + filePath: TrimmedNonEmptyString, + activeTab: Schema.optional(ElectronicsPanelTab), + selectedNet: Schema.optional(TrimmedString), +}); +export type ElectronicsOpenPanelInput = typeof ElectronicsOpenPanelInput.Type; + +export const ElectronicsClosePanelInput = Schema.Struct({ + threadId: ThreadId, +}); +export type ElectronicsClosePanelInput = typeof ElectronicsClosePanelInput.Type; + +// Compact MCP tool schemas +export const ElectronicsToolListResult = Schema.Struct({ + files: Schema.Array(ElectronicsWorkspaceFile), + openFilePath: Schema.optional(Schema.String), + toolchain: Schema.Struct({ + kicadCli: Schema.Boolean, + kicadVersion: Schema.optional(Schema.String), + ngspice: Schema.Boolean, + ngspiceVersion: Schema.optional(Schema.String), + }), +}); +export type ElectronicsToolListResult = typeof ElectronicsToolListResult.Type; + +export const ElectronicsToolInspectResult = Schema.Struct({ + filePath: Schema.String, + format: ElectronicsDesignFormat, + title: Schema.optional(Schema.String), + componentCount: Schema.Int, + netCount: Schema.Int, + powerNets: Schema.Array(Schema.String), + groundNets: Schema.Array(Schema.String), + components: Schema.Array( + Schema.Struct({ + ref: Schema.String, + value: Schema.String, + kind: ElectronicsComponentKind, + footprint: Schema.optional(Schema.String), + pins: Schema.Array( + Schema.Struct({ + number: Schema.String, + name: Schema.optional(Schema.String), + type: ElectronicsPinElectricalType, + net: Schema.optional(Schema.String), + }), + ), + }), + ), + nets: Schema.Array( + Schema.Struct({ + name: Schema.String, + isPower: Schema.Boolean, + isGround: Schema.Boolean, + pins: Schema.Array(Schema.String), + }), + ), + bom: Schema.Array(ElectronicsBomEntry), + parseWarnings: Schema.Array(Schema.String), +}); +export type ElectronicsToolInspectResult = typeof ElectronicsToolInspectResult.Type; + +export const ElectronicsToolOpenResult = Schema.Struct({ + filePath: Schema.String, + format: ElectronicsDesignFormat, + activeTab: ElectronicsPanelTab, + componentCount: Schema.Int, + netCount: Schema.Int, +}); +export type ElectronicsToolOpenResult = typeof ElectronicsToolOpenResult.Type; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index d7af43291a061..4fcac041ad455 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -62,6 +62,7 @@ export * from "./mcpApps.ts"; export * from "./browserImport.ts"; export * from "./browserProfile.ts"; export * from "./device.ts"; +export * from "./electronics.ts"; export * from "./preview.ts"; export * from "./previewAutomation.ts"; export * from "./previewCapture.ts"; diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index e30bf9af2937c..158a67db1551e 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -465,6 +465,24 @@ import { } from "./sourceControl.ts"; import { VcsError } from "./vcs.ts"; import { Project, ProjectMutation, ProjectMutationError } from "./project.ts"; +import { + ElectronicsCircuitModel, + ElectronicsClosePanelInput, + ElectronicsError, + ElectronicsInspectInput, + ElectronicsListFilesInput, + ElectronicsListFilesResult, + ElectronicsOpenPanelInput, + ElectronicsServiceState, + ElectronicsSimulateInput, + ElectronicsSimulationResult, + ElectronicsThreadSession, + ElectronicsToolchainStatus, + ElectronicsTracePathInput, + ElectronicsTracePathResult, + ElectronicsValidateInput, + ElectronicsValidationReport, +} from "./electronics.ts"; export const WS_METHODS = { projectsListEntries: "projects.listEntries", @@ -563,6 +581,16 @@ export const WS_METHODS = { deviceDetail: "device.detail", deviceAction: "device.action", + electronicsListFiles: "electronics.listFiles", + electronicsInspect: "electronics.inspect", + electronicsTracePath: "electronics.tracePath", + electronicsValidate: "electronics.validate", + electronicsSimulate: "electronics.simulate", + electronicsToolchainStatus: "electronics.toolchainStatus", + electronicsOpenPanel: "electronics.openPanel", + electronicsClosePanel: "electronics.closePanel", + subscribeElectronicsState: "electronics.subscribeState", + serverProbe: "server.probe", serverGetConfig: "server.getConfig", serverGetNpmRelease: "server.getNpmRelease", @@ -2365,6 +2393,63 @@ const WsSubscribeResourceTelemetryRpc = Rpc.make(WS_METHODS.subscribeResourceTel stream: true, }); +const WsElectronicsListFilesRpc = Rpc.make(WS_METHODS.electronicsListFiles, { + payload: ElectronicsListFilesInput, + success: ElectronicsListFilesResult, + error: Schema.Union([ElectronicsError, EnvironmentAuthorizationError]), +}); + +const WsElectronicsInspectRpc = Rpc.make(WS_METHODS.electronicsInspect, { + payload: ElectronicsInspectInput, + success: ElectronicsCircuitModel, + error: Schema.Union([ElectronicsError, EnvironmentAuthorizationError]), +}); + +const WsElectronicsTracePathRpc = Rpc.make(WS_METHODS.electronicsTracePath, { + payload: ElectronicsTracePathInput, + success: ElectronicsTracePathResult, + error: Schema.Union([ElectronicsError, EnvironmentAuthorizationError]), +}); + +const WsElectronicsValidateRpc = Rpc.make(WS_METHODS.electronicsValidate, { + payload: ElectronicsValidateInput, + success: ElectronicsValidationReport, + error: Schema.Union([ElectronicsError, EnvironmentAuthorizationError]), +}); + +const WsElectronicsSimulateRpc = Rpc.make(WS_METHODS.electronicsSimulate, { + payload: ElectronicsSimulateInput, + success: ElectronicsSimulationResult, + error: Schema.Union([ElectronicsError, EnvironmentAuthorizationError]), +}); + +const WsElectronicsToolchainStatusRpc = Rpc.make(WS_METHODS.electronicsToolchainStatus, { + payload: Schema.Struct({ + refresh: Schema.optional(Schema.Boolean), + }), + success: ElectronicsToolchainStatus, + error: Schema.Union([ElectronicsError, EnvironmentAuthorizationError]), +}); + +const WsElectronicsOpenPanelRpc = Rpc.make(WS_METHODS.electronicsOpenPanel, { + payload: ElectronicsOpenPanelInput, + success: ElectronicsThreadSession, + error: Schema.Union([ElectronicsError, EnvironmentAuthorizationError]), +}); + +const WsElectronicsClosePanelRpc = Rpc.make(WS_METHODS.electronicsClosePanel, { + payload: ElectronicsClosePanelInput, + success: Schema.Struct({}), + error: Schema.Union([ElectronicsError, EnvironmentAuthorizationError]), +}); + +const WsSubscribeElectronicsStateRpc = Rpc.make(WS_METHODS.subscribeElectronicsState, { + payload: Schema.Struct({}), + success: ElectronicsServiceState, + error: EnvironmentAuthorizationError, + stream: true, +}); + export class RpcScopeAuthorization extends RpcMiddleware.Service()( "t3/contracts/RpcScopeAuthorization", { error: EnvironmentAuthorizationError }, @@ -2591,6 +2676,15 @@ export const WsRpcGroup = RpcGroup.make( WsDeviceDetailRpc, WsDeviceActionRpc, WsSubscribeDeviceStateRpc, + WsElectronicsListFilesRpc, + WsElectronicsInspectRpc, + WsElectronicsTracePathRpc, + WsElectronicsValidateRpc, + WsElectronicsSimulateRpc, + WsElectronicsToolchainStatusRpc, + WsElectronicsOpenPanelRpc, + WsElectronicsClosePanelRpc, + WsSubscribeElectronicsStateRpc, WsSubscribeServerConfigRpc, WsSubscribeServerLifecycleRpc, WsSubscribeAuthAccessRpc, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index b0726b07174c9..0de4844253830 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1463,6 +1463,16 @@ export const ServerSettings = Schema.Struct({ simlockDeviceHosts: SimlockDeviceHostConfigs.pipe(Schema.withDecodingDefault(Effect.succeed([]))), /** Alpha: Simlock device hosts. Off, the server ignores `simlockDeviceHosts`. */ simlockDeviceHostsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + /** Electronics Workbench panel, pure-TS parser/path validator, and optional KiCad/ngspice toolchain. */ + enableElectronicsWorkbench: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + enableAgentElectronicsAccess: Schema.Boolean.pipe( + Schema.withDecodingDefault(Effect.succeed(true)), + ), + electronicsAllowExternalTools: Schema.Boolean.pipe( + Schema.withDecodingDefault(Effect.succeed(true)), + ), + electronicsKicadCliPath: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))), + electronicsNgspicePath: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))), sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)), ), @@ -1918,6 +1928,11 @@ export const ServerSettingsPatch = Schema.Struct({ easDeviceHosts: Schema.optionalKey(EasDeviceHostConfigs), simlockDeviceHosts: Schema.optionalKey(SimlockDeviceHostConfigs), simlockDeviceHostsEnabled: Schema.optionalKey(Schema.Boolean), + enableElectronicsWorkbench: Schema.optionalKey(Schema.Boolean), + enableAgentElectronicsAccess: Schema.optionalKey(Schema.Boolean), + electronicsAllowExternalTools: Schema.optionalKey(Schema.Boolean), + electronicsKicadCliPath: Schema.optionalKey(TrimmedString), + electronicsNgspicePath: Schema.optionalKey(TrimmedString), sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)), compactIdleThreads: Schema.optionalKey(LegacyCompactIdleThreads), idleCompaction: Schema.optionalKey(IdleCompactionMode),