diff --git a/docs/changelog.md b/docs/changelog.md index 52d818c..b46be9d 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -4,6 +4,14 @@ All notable changes to the EasyEDA Pro MCP server and browser extension are docu For packaged `.eext` and `.mcpb` downloads and checksums, see [GitHub Releases](https://github.com/VLab-Software/easyeda_mcp/releases). +## `1.4.1` (Extension `0.5.1`) + +- feat: reconcile single-page snapshots with native Protel2 netlists +- fix: serialize native wire readback as plain JSON +- fix: track mutation deadlines and reconcile late completion +- fix: decode native wire segment groups without artificial diagonals +- fix: preserve schematic wire geometry and net identity + ## `1.4.0` (Extension `0.5.0`) - feat(spice): simulation feasibility assessment, component audit and SPICE netlist generation (Phase 5.5) diff --git a/docs/tools.md b/docs/tools.md index b062a85..2cf10db 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -263,6 +263,23 @@ Builds a normalized snapshot of the active schematic: components, pins, wires, l --- +**Native connectivity:** with `allPages: false`, the extension attempts +`sch_ManufactureData.getNetlistFile("mcp-native-connectivity", "Protel2")` and reads the returned +File in memory. It does not save an export or modify the schematic. The read has a 3-second budget +and a 2 MB limit. Only supported Protel2 component and net records are parsed. + +The `nativeNetlist` result reports `status`, `format`, `matchedPins`, `conflicts`, and an optional +`reason`. Pins matched by an exact, project-unique designator and pin number use +`netSource: "native_netlist"`. Native membership takes precedence over geometric inference; +disagreements produce warnings. Conflicting native memberships remain unknown. + +An absent member does not prove disconnection: exports may omit components. Missing APIs, +unsupported files, timeouts, duplicate designators, and unmatched pins retain explicit geometric +fallback. Multi-page snapshots currently do not apply native membership because page-local IDs +and duplicate references need a separate scoped reconciliation. This integration requires a real +editor check after reloading the rebuilt extension; parsing tests alone do not establish export +compatibility with every EasyEDA version. + ### `easyeda_get_schematic_nets` **Scope:** Schematic RPC (`readOnlyHint: true`, `idempotentHint: true`, default timeout: `30000` ms) @@ -1346,6 +1363,24 @@ Executes a mutating EasyEDA Pro action only after human confirmation is verified - **`params`** (`object`, _optional_): Required for `editDrcRules` (`{ "editId": "" }`) and `mutation` (`{ "mutationId": "" }`). - **`timeoutMs`** (`number`, _optional_, default: `60000`): RPC timeout in ms. +For staged mutations (`action: "mutation"`), the extension also tracks a 45-second execution deadline, +independent of the RPC timeout. A deadline returns `status: "unknown"`, not proof of cancellation. +Query `easyeda_get_mutation_result` with the same mutation ID; never replay an uncertain write. +The result includes `phase`, execution timestamps, and `execution` diagnostics (`timeoutMs`, +`elapsedMs`, `lockHeld`, and recovery guidance). Busy errors include the active mutation record. + +The original operation remains observed after the deadline. Late completion runs readback and +updates the retained result; late rejection preserves uncertainty and releases the lock. A completed write whose readback fails validation or serialization remains `unknown`, with the +original error and mutation ID available for inspection; it is not evidence that the write failed. +Wire rename readback stores explicit plain state fields and verifies the returned net name. +A pending +executor retains its lock because the native SDK write cannot be cancelled by a JavaScript timeout. +If it never settles, reload the extension and inspect the document before preparing another write. +A stalled read-only lifecycle readback releases its lock at the deadline; its eventual completion +cannot unlock another mutation. Executors that perform their own writes and readback internally +are conservatively treated as pending writes until the entire executor settles. + + ::: code-group ```json [Apply Prepared DRC Edit] diff --git a/extension/extension.json b/extension/extension.json index 1d12a01..eecf5fa 100644 --- a/extension/extension.json +++ b/extension/extension.json @@ -3,7 +3,7 @@ "uuid": "easyedamcpbridge202605240001abcd", "displayName": "EasyEDA MCP Bridge", "description": "Independent local WebSocket bridge that lets an MCP server inspect and assist the active EasyEDA Pro project.", - "version": "0.5.0", + "version": "0.5.1", "publisher": "vlabsoft", "engines": { "eda": "^2.3.0" diff --git a/extension/src/handlers/nativeNetlist.test.ts b/extension/src/handlers/nativeNetlist.test.ts new file mode 100644 index 0000000..0be12e7 --- /dev/null +++ b/extension/src/handlers/nativeNetlist.test.ts @@ -0,0 +1,80 @@ +import { collectSchematicSnapshot } from "./schematicHandlers.js"; +import { describe, expect, it, vi } from "vitest"; +import { collectNativeNetlist } from "./nativeNetlist.js"; + +describe("native netlist collection", () => { + it("reads the File in memory, requests Protel2 and detects duplicate project references", async () => { + const getNetlistFile = vi.fn(async () => ({ size: 12, text: async () => "(\nGND\nU1-1\n)" })); + const result = await collectNativeNetlist( + { + sch_ManufactureData: { getNetlistFile }, + sch_PrimitiveComponent: { + getAll: async () => [ + { componentType: "part", designator: "U1" }, + { componentType: "part", designator: "U1" } + ] + } + }, + false + ); + expect(getNetlistFile).toHaveBeenCalledWith("mcp-native-connectivity", "Protel2"); + expect(result).toMatchObject({ status: "available", ambiguousDesignators: ["U1"] }); + }); + it("does not claim support when the API or page scope is unavailable", async () => { + expect((await collectNativeNetlist({}, false)).status).toBe("unavailable"); + const getNetlistFile = vi.fn(); + expect((await collectNativeNetlist({ sch_ManufactureData: { getNetlistFile } }, true)).status).toBe("unavailable"); + expect(getNetlistFile).not.toHaveBeenCalled(); + }); + it("reports a read failure without changing the editor", async () => { + const result = await collectNativeNetlist( + { + sch_ManufactureData: { + getNetlistFile: async () => { + throw new Error("export failed"); + } + } + }, + false + ); + expect(result).toMatchObject({ status: "error", reason: "export failed" }); + }); + it("integrates native membership into the current-page snapshot", async () => { + const component = { primitiveId: "u", componentType: "part", designator: "U15" }; + const api = () => ({ + dmt_SelectControl: { getCurrentDocumentInfo: async () => ({ uuid: "sheet", documentType: 1 }) }, + sch_PrimitiveComponent: { + getAll: async () => [component], + getAllPinsByPrimitiveId: async () => [{ pinNumber: "5", pinName: "V+" }] + }, + sch_ManufactureData: { getNetlistFile: async () => ({ text: async () => "(\n3V3_LAB\nU15-5\n)" }) } + }); + const snapshot = await collectSchematicSnapshot(api, { allPages: false, includeRaw: false }); + expect(snapshot.pins[0]).toMatchObject({ net: "3V3_LAB", netSource: "native_netlist" }); + expect(snapshot.nativeNetlist).toMatchObject({ status: "available", matchedPins: 1 }); + }); + + it("bounds a hung native read and observes late rejection", async () => { + vi.useFakeTimers(); + try { + let reject!: (error: Error) => void; + const pending = collectNativeNetlist( + { + sch_ManufactureData: { + getNetlistFile: () => + new Promise((_, fail) => { + reject = fail; + }) + } + }, + false + ); + await vi.advanceTimersByTimeAsync(3000); + expect((await pending).status).toBe("error"); + reject(new Error("late SDK rejection")); + await vi.advanceTimersByTimeAsync(0); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/extension/src/handlers/nativeNetlist.ts b/extension/src/handlers/nativeNetlist.ts new file mode 100644 index 0000000..ad40f73 --- /dev/null +++ b/extension/src/handlers/nativeNetlist.ts @@ -0,0 +1,55 @@ +import type { NativeNetlistData } from "../../../src/schematic/nativeNetlist.js"; +import type { EasyEdaApi } from "../types.js"; + +export async function collectNativeNetlist(eda: EasyEdaApi, allPages: boolean): Promise { + const base = { format: "Protel2" as const }; + if (allPages) + return { + ...base, + status: "unavailable", + reason: "Native mapping currently requires a single-page snapshot to avoid page-local ID collisions" + }; + if (!eda.sch_ManufactureData?.getNetlistFile) + return { ...base, status: "unavailable", reason: "sch_ManufactureData.getNetlistFile is unavailable" }; + let timer: ReturnType | undefined; + try { + const read = (async (): Promise => { + const file = await eda.sch_ManufactureData.getNetlistFile("mcp-native-connectivity", "Protel2"); + if (!file || typeof file.text !== "function") + return { ...base, status: "unsupported", reason: "Native API did not return a readable File" }; + if (typeof file.size === "number" && file.size > 2_000_000) + return { ...base, status: "unsupported", reason: "Native netlist exceeds 2 MB" }; + const text: unknown = await file.text(); + if (typeof text !== "string") return { ...base, status: "unsupported", reason: "Netlist content is not text" }; + // Establish uniqueness across the project before matching references from an export. + const components = await eda.sch_PrimitiveComponent.getAll(undefined, true); + if (!Array.isArray(components)) throw new Error("Cannot establish project designator uniqueness"); + const counts = new Map(); + for (const c of components) + if (c.componentType === "part" && typeof c.designator === "string") + counts.set(c.designator, (counts.get(c.designator) ?? 0) + 1); + return { + ...base, + status: "available", + text, + ambiguousDesignators: [...counts].filter(([, count]) => count > 1).map(([name]) => name) + }; + })(); + const timeout = new Promise((resolve) => { + timer = setTimeout( + () => + resolve({ + ...base, + status: "error", + reason: "Native netlist read timed out after 3000 ms; geometric fallback used" + }), + 3000 + ); + }); + return await Promise.race([read, timeout]); + } catch (error) { + return { ...base, status: "error", reason: error instanceof Error ? error.message : String(error) }; + } finally { + if (timer !== undefined) clearTimeout(timer); + } +} diff --git a/extension/src/handlers/schematicHandlers.ts b/extension/src/handlers/schematicHandlers.ts index 1ca3c7a..0d27568 100644 --- a/extension/src/handlers/schematicHandlers.ts +++ b/extension/src/handlers/schematicHandlers.ts @@ -1,3 +1,4 @@ +import { collectNativeNetlist } from "./nativeNetlist.js"; import { assertSnapshotFresh, buildSchematicSnapshot, @@ -66,8 +67,11 @@ export async function collectSchematicSnapshot( pinsByComponent, wires: await optionalCall(() => (eda.sch_PrimitiveWire?.getAll ? eda.sch_PrimitiveWire.getAll() : [])), texts: await optionalCall(() => (eda.sch_PrimitiveText?.getAll ? eda.sch_PrimitiveText.getAll() : [])), - includeRaw: options.includeRaw + includeRaw: options.includeRaw, + nativeNetlist: await collectNativeNetlist(eda, options.allPages) }; + const afterInfo = await eda.dmt_SelectControl.getCurrentDocumentInfo(); + assertDocumentTargetMatch(target, extractDocumentIdentity(afterInfo, undefined, "native_api")); return buildSchematicSnapshot(rawData); } diff --git a/extension/src/mutation/schematicWireMutations.test.ts b/extension/src/mutation/schematicWireMutations.test.ts index 341ec4a..33402ff 100644 --- a/extension/src/mutation/schematicWireMutations.test.ts +++ b/extension/src/mutation/schematicWireMutations.test.ts @@ -335,3 +335,75 @@ describe("Schematic Wire & Net Label Mutations", () => { }); }); }); + +describe("native wire rename readback", () => { + function fixture(options: { ignoreWrite?: boolean; invalidReadback?: boolean } = {}) { + class NativeWire { + primitiveId = "native-wire"; + net = "TEST_USB_GND"; + line = [240, 620, 300, 620]; + // These native members must never be copied into the lifecycle record. + nativeMetadata = new Map([["editor", "native"]]); + getState_PrimitiveId() { + return this.primitiveId; + } + getState_Net() { + return this.net; + } + getState_Line() { + return options.invalidReadback && this.net === "GND" ? [NaN] : this.line; + } + } + const wire = new NativeWire(); + const modify = vi.fn(async (_id: string, properties: Record) => { + if (!options.ignoreWrite) wire.net = String(properties.net); + }); + const api = () => ({ + dmt_SelectControl: { getCurrentDocumentInfo: async () => ({ uuid: "rename-sheet", documentType: 1 }) }, + sch_PrimitiveWire: { get: async () => wire, getAll: async () => [wire], modify } + }); + return { api, wire, modify }; + } + + it("confirms a native class instance as plain JSON after renaming once", async () => { + const { api, modify } = fixture(); + const prepared = await prepareSchematicWireMutation(api, { + action: "modifyWire", + wireId: "native-wire", + net: "GND" + }); + const result: any = await createActionHandlers(api, new DrcRules(api)).confirmedAction({ + action: "mutation", + confirmation: prepared.confirmation, + params: { mutationId: prepared.mutationId } + }); + expect(result.status).toBe("applied"); + expect(result.after).toMatchObject({ + wire: { primitiveId: "native-wire", net: "GND", line: [240, 620, 300, 620] }, + verified: true + }); + expect((result.after as any).wire.nativeMetadata).toBeUndefined(); + expect(modify).toHaveBeenCalledTimes(1); + }); + + it.each([{ ignoreWrite: true }, { invalidReadback: true }])( + "preserves uncertainty when native readback fails: %j", + async (options) => { + const { api, modify } = fixture(options); + const prepared = await prepareSchematicWireMutation(api, { + action: "modifyWire", + wireId: "native-wire", + net: "GND" + }); + const result: any = await createActionHandlers(api, new DrcRules(api)).confirmedAction({ + action: "mutation", + confirmation: prepared.confirmation, + params: { mutationId: prepared.mutationId } + }); + expect(result.status).toBe("unknown"); + expect(result.error).toMatch(/readback/); + expect(result.execution).toMatchObject({ lockHeld: false }); + expect(modify).toHaveBeenCalledTimes(1); + } + ); +}); diff --git a/extension/src/mutation/schematicWireMutations.ts b/extension/src/mutation/schematicWireMutations.ts index afa907b..c762864 100644 --- a/extension/src/mutation/schematicWireMutations.ts +++ b/extension/src/mutation/schematicWireMutations.ts @@ -2,7 +2,7 @@ import { apiError, ensureApi, isNumber, isRecord, numeric, optionalCall, toArray import { assertDocumentTargetMatch, extractDocumentIdentity } from "../identity.js"; import { extensionMutations } from "./mutationManager.js"; import type { EasyEdaApi } from "../types.js"; -import type { MutationRecord } from "../../../src/mutation/contracts.js"; +import { canonicalJson, type MutationRecord } from "../../../src/mutation/contracts.js"; export type NormalizedPoint = { x: number; y: number }; @@ -94,17 +94,35 @@ export async function findTouchingConnections( return touching; } +// SDK primitives are class instances. Only explicit state belongs in a mutation record. +export function wireReadbackData(wire: Record): Record { + const state = (method: string, field: string): unknown => { + const getter = wire[method]; + return typeof getter === "function" ? getter.call(wire) : wire[field]; + }; + return JSON.parse( + canonicalJson({ + primitiveId: state("getState_PrimitiveId", "primitiveId") ?? wire.id ?? wire.uuid, + line: state("getState_Line", "line"), + net: state("getState_Net", "net"), + color: state("getState_Color", "color"), + lineWidth: state("getState_LineWidth", "lineWidth"), + lineType: state("getState_LineType", "lineType") + }) + ); +} + export async function findWireById(api: () => EasyEdaApi, wireId: string): Promise> { const eda = api(); if (eda.sch_PrimitiveWire?.get) { const wire = await optionalCall(() => eda.sch_PrimitiveWire.get(wireId)); - if (isRecord(wire)) return wire; + if (isRecord(wire)) return wireReadbackData(wire); } ensureApi("sch_PrimitiveWire", "getAll", eda); const all = toArray(await eda.sch_PrimitiveWire.getAll()); for (const w of all) { if (isRecord(w) && String(w.primitiveId ?? w.id ?? w.uuid ?? "") === wireId) { - return w; + return wireReadbackData(w); } } throw apiError("wire_not_found", `Schematic wire with id "${wireId}" was not found.`); @@ -422,20 +440,33 @@ export async function executeSchematicWireMutation( ensureApi("sch_PrimitiveWire", "modify", eda); await eda.sch_PrimitiveWire.modify(op.wireId, op.properties); - const wire = await findWireById(api, op.wireId); - const points = op.properties.coordinates ? extractPointsFromFlat(op.properties.coordinates) : []; - const affectedConnections = points.length > 0 ? await findTouchingConnections(api, points) : []; - - return { - executed: true, - readback: { - wireId: op.wireId, - properties: op.properties, - wire, - affectedConnections, - verified: true + try { + const wire = await findWireById(api, op.wireId); + if (op.properties.net !== undefined && wire.net !== op.properties.net) { + throw apiError("readback_verification_failed", `Wire ${op.wireId} net does not match the requested name.`, { + expected: op.properties.net, + actual: wire.net + }); } - }; + const points = op.properties.coordinates ? extractPointsFromFlat(op.properties.coordinates) : []; + const affectedConnections = points.length > 0 ? await findTouchingConnections(api, points) : []; + + return { + executed: true, + readback: { + wireId: op.wireId, + properties: op.properties, + wire, + affectedConnections, + verified: true + } + }; + } catch (error) { + throw apiError( + "write_readback_unknown", + `Wire modification completed but readback failed: ${error instanceof Error ? error.message : String(error)}` + ); + } } if (op.action === "deleteWire") { diff --git a/package-lock.json b/package-lock.json index 3307405..239de0e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@vlabsoftware/easyeda-pro-mcp", - "version": "1.4.0", + "version": "1.4.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@vlabsoftware/easyeda-pro-mcp", - "version": "1.4.0", + "version": "1.4.1", "license": "MIT", "dependencies": { "@modelcontextprotocol/server": "^2.4.0", diff --git a/package.json b/package.json index cad650e..b4e2ac5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@vlabsoftware/easyeda-pro-mcp", - "version": "1.4.0", + "version": "1.4.1", "mcpName": "io.github.VLab-Software/easyeda-pro-mcp", "description": "Independent open-source MCP server and EasyEDA Pro extension bridge for live PCB project assistance.", "main": "dist/index.js", diff --git a/server.json b/server.json index 3fba1b0..db074c5 100644 --- a/server.json +++ b/server.json @@ -6,12 +6,12 @@ "url": "https://github.com/VLab-Software/easyeda_mcp", "source": "github" }, - "version": "1.4.0", + "version": "1.4.1", "packages": [ { "registryType": "npm", "identifier": "@vlabsoftware/easyeda-pro-mcp", - "version": "1.4.0", + "version": "1.4.1", "transport": { "type": "stdio" }, diff --git a/src/mcp/tools/schematicTools.ts b/src/mcp/tools/schematicTools.ts index 46c48e3..e07adf6 100644 --- a/src/mcp/tools/schematicTools.ts +++ b/src/mcp/tools/schematicTools.ts @@ -108,7 +108,7 @@ export function registerSchematicTools(server: McpServer, bridge: EditorClient): name: "easyeda_schematic_snapshot", title: "Get EasyEDA Pro schematic snapshot", description: - "Returns a structured snapshot of the active schematic: components, pins, nets, wires, labels, and confidence metadata.", + "Returns components, pins, nets, wires, labels and provenance. Single-page reads attempt native Protel2 netlist membership and explicitly report geometric fallback.", method: "schematicSnapshot", inputSchema: { includeRaw: z diff --git a/src/mutation/MutationLifecycle.test.ts b/src/mutation/MutationLifecycle.test.ts index aa2940f..743f238 100644 --- a/src/mutation/MutationLifecycle.test.ts +++ b/src/mutation/MutationLifecycle.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import type { DocumentIdentity } from "../protocol/identity.js"; import { MutationLifecycle } from "./MutationLifecycle.js"; @@ -205,6 +205,42 @@ describe("MutationLifecycle", () => { expect(record.error).toContain("Bridge connection lost"); }); + it("keeps a completed write uncertain when its readback cannot be serialized", async () => { + const lifecycle = new MutationLifecycle(); + const prepared = lifecycle.prepare({ + domain: "schematic", + action: "modifyWire", + target: baseTarget, + operation: {}, + before: {}, + requestedAfter: {}, + scope: "sheet" + }); + const execute = vi.fn(async () => true); + const result = await lifecycle.apply({ + mutationId: prepared.mutationId, + confirmation: prepared.confirmation, + currentTarget: baseTarget, + currentBefore: {}, + execute, + readback: async () => new Map() + }); + expect(result.status).toBe("unknown"); + expect(result.error).toMatch(/Write completed but readback/); + expect(result.execution?.lockHeld).toBe(false); + await expect( + lifecycle.apply({ + mutationId: prepared.mutationId, + confirmation: prepared.confirmation, + currentTarget: baseTarget, + currentBefore: {}, + execute, + readback: async () => ({}) + }) + ).rejects.toThrow(); + expect(execute).toHaveBeenCalledTimes(1); + }); + it("expires mutations after TTL", () => { const lifecycle = new MutationLifecycle(); const prepared = lifecycle.prepare({ @@ -222,3 +258,159 @@ describe("MutationLifecycle", () => { expect(record.status).toBe("expired"); }); }); + +describe("mutation execution deadlines", () => { + const target: DocumentIdentity = { documentId: "sheet", documentType: "schematic", tabId: "tab" }; + function setup() { + const lifecycle = new MutationLifecycle(100); + const options = { + domain: "schematic", + action: "addNetLabel", + target, + operation: {}, + before: {}, + requestedAfter: {}, + scope: "sheet" + }; + const prepared = lifecycle.prepare(options); + return { + lifecycle, + options, + prepared, + apply: { + mutationId: prepared.mutationId, + confirmation: prepared.confirmation, + currentTarget: target, + currentBefore: {} + } + }; + } + + it("reports a hung write as unknown, retains its lock and forbids replay", async () => { + vi.useFakeTimers(); + try { + const { lifecycle, options, prepared, apply } = setup(); + const execute = vi.fn(() => new Promise(() => {})); + const resultPromise = lifecycle.apply({ ...apply, execute, readback: async () => ({}) }); + await vi.advanceTimersByTimeAsync(100); + const result = await resultPromise; + expect(result).toMatchObject({ + status: "unknown", + phase: "execute", + execution: { lockHeld: true, timeoutMs: 100 } + }); + expect(result.timedOutAt).toBeDefined(); + expect(() => lifecycle.prepare(options)).toThrow(/still pending/); + try { + lifecycle.prepare(options); + } catch (error) { + expect((error as { details: unknown }).details).toMatchObject({ + mutationId: prepared.mutationId, + status: "unknown" + }); + } + await expect(lifecycle.apply({ ...apply, execute, readback: async () => ({}) })).rejects.toThrow(); + expect(execute).toHaveBeenCalledTimes(1); + } finally { + vi.useRealTimers(); + } + }); + + it("automatically reconciles late completion and releases the lock", async () => { + vi.useFakeTimers(); + try { + const { lifecycle, options, prepared, apply } = setup(); + let finish!: (value: boolean) => void; + const resultPromise = lifecycle.apply({ + ...apply, + execute: () => + new Promise((resolve) => { + finish = resolve; + }), + readback: async () => ({ verified: true }) + }); + await vi.advanceTimersByTimeAsync(100); + expect((await resultPromise).status).toBe("unknown"); + finish(true); + await vi.advanceTimersByTimeAsync(0); + expect(lifecycle.get(prepared.mutationId)).toMatchObject({ + status: "applied", + phase: "settled", + after: { verified: true }, + execution: { lockHeld: false } + }); + expect(lifecycle.get(prepared.mutationId).error).toBeUndefined(); + expect(() => lifecycle.prepare(options)).not.toThrow(); + } finally { + vi.useRealTimers(); + } + }); + + it("observes late rejection without an unhandled rejection or a permanent lock", async () => { + vi.useFakeTimers(); + try { + const { lifecycle, options, prepared, apply } = setup(); + let reject!: (error: Error) => void; + const resultPromise = lifecycle.apply({ + ...apply, + execute: () => + new Promise((_, fail) => { + reject = fail; + }), + readback: async () => ({}) + }); + await vi.advanceTimersByTimeAsync(100); + await resultPromise; + reject(new Error("SDK failed late")); + await vi.advanceTimersByTimeAsync(0); + expect(lifecycle.get(prepared.mutationId)).toMatchObject({ + status: "unknown", + phase: "settled", + execution: { lockHeld: false } + }); + expect(() => lifecycle.prepare(options)).not.toThrow(); + } finally { + vi.useRealTimers(); + } + }); + + it("releases a stalled readback without unlocking a newer write on late completion", async () => { + vi.useFakeTimers(); + try { + const { lifecycle, options, prepared, apply } = setup(); + let finishRead!: (value: unknown) => void; + const first = lifecycle.apply({ + ...apply, + execute: async () => true, + readback: () => + new Promise((resolve) => { + finishRead = resolve; + }) + }); + await vi.advanceTimersByTimeAsync(100); + expect(await first).toMatchObject({ status: "unknown", phase: "readback", execution: { lockHeld: false } }); + const next = lifecycle.prepare(options); + let finishWrite!: (value: boolean) => void; + const second = lifecycle.apply({ + ...apply, + mutationId: next.mutationId, + confirmation: next.confirmation, + execute: () => + new Promise((resolve) => { + finishWrite = resolve; + }), + readback: async () => ({}) + }); + finishRead({ verified: true }); + await vi.advanceTimersByTimeAsync(0); + expect(lifecycle.get(prepared.mutationId).status).toBe("applied"); + expect(lifecycle.get(next.mutationId).execution?.lockHeld).toBe(true); + expect(() => lifecycle.prepare(options)).toThrow(); + finishWrite(true); + await second; + expect(() => lifecycle.prepare(options)).not.toThrow(); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/src/mutation/MutationLifecycle.ts b/src/mutation/MutationLifecycle.ts index bc3e3ad..fa3bcea 100644 --- a/src/mutation/MutationLifecycle.ts +++ b/src/mutation/MutationLifecycle.ts @@ -31,6 +31,21 @@ export type ApplyMutationOptions = { export class MutationLifecycle { private mutations = new Map>(); private busy = false; + private activeMutationId?: string; + + constructor(private readonly executionTimeoutMs = 45_000) { + if (!Number.isFinite(executionTimeoutMs) || executionTimeoutMs <= 0) { + throw new Error("Mutation execution timeout must be positive and finite"); + } + } + + private busyError(): Error & { code: string; details: unknown } { + const active = this.activeMutationId ? this.mutations.get(this.activeMutationId) : undefined; + return Object.assign(new Error("Another mutation is still pending; query its result without replaying it"), { + code: "mutation_busy", + details: active ? this.public(active) : undefined + }); + } private generation = 0; getGeneration(): number { @@ -50,9 +65,7 @@ export class MutationLifecycle { options: PrepareMutationOptions ): MutationRecord { if (this.busy) { - const error = new Error("Another mutation is currently in progress") as Error & { code: string }; - error.code = "mutation_busy"; - throw error; + throw this.busyError(); } const mutationId = @@ -182,9 +195,7 @@ export class MutationLifecycle { } if (this.busy) { - const error = new Error("Another mutation is currently in progress") as Error & { code: string }; - error.code = "mutation_busy"; - throw error; + throw this.busyError(); } // Verify target matches @@ -203,40 +214,82 @@ export class MutationLifecycle { } this.busy = true; + this.activeMutationId = record.mutationId; record.status = "running"; - - try { - const execResult = await options.execute(); - if (execResult === false) { - record.status = "failed"; - record.error = "Mutation executor returned false"; - const error = new Error("Mutation execution returned false; outcome unverified") as Error & { - code: string; - }; - error.code = "write_unverified"; + record.startedAt = new Date().toISOString(); + record.phase = "execute"; + + // Keep observing the original promise after the caller's deadline. A timeout + // cannot cancel an SDK write, so never release its lock or replay the write. + const completion = (async () => { + try { + const execResult = await options.execute(); + if (execResult === false) { + record.status = "failed"; + record.error = "Mutation executor returned false"; + const error = new Error("Mutation execution returned false; outcome unverified") as Error & { + code: string; + }; + error.code = "write_unverified"; + throw error; + } + + // Check target again after write + if (options.readbackTarget) { + assertDocumentTargetMatch(record.target, options.readbackTarget, { + requireTabMatch: true, + requirePageMatch: true + }); + } + + record.phase = "readback"; + const readbackData = await options.readback(); + record.after = copy(readbackData); + record.status = "applied"; + delete record.error; + return this.public(record); + } catch (error) { + if (record.phase === "readback" || (error as { code?: string })?.code === "write_readback_unknown") { + record.status = "unknown"; + record.error = `Write completed but readback could not be confirmed: ${error instanceof Error ? error.message : String(error)}`; + return this.public(record); + } + if (record.status === "running") { + record.status = "failed"; + record.error = error instanceof Error ? error.message : String(error); + } else if (record.status === "unknown") { + record.error = `Outcome remains uncertain after executor rejection: ${error instanceof Error ? error.message : String(error)}`; + } throw error; + } finally { + record.phase = "settled"; + record.settledAt = new Date().toISOString(); + if (this.activeMutationId === record.mutationId) { + this.busy = false; + this.activeMutationId = undefined; + } } - - // Check target again after write - if (options.readbackTarget) { - assertDocumentTargetMatch(record.target, options.readbackTarget, { - requireTabMatch: true, - requirePageMatch: true - }); - } - - const readbackData = await options.readback(); - record.after = copy(readbackData); - record.status = "applied"; + })(); + + let timer: ReturnType | undefined; + const deadline = new Promise>((resolve) => { + timer = setTimeout(() => { + record.status = "unknown"; + record.timedOutAt = new Date().toISOString(); + record.error = "Execution deadline exceeded; the original operation is still being observed. Do not replay it."; + // A pending read-only readback cannot perform another write. + if (record.phase === "readback" && this.activeMutationId === record.mutationId) { + this.busy = false; + this.activeMutationId = undefined; + } + resolve(this.public(record)); + }, this.executionTimeoutMs); + }); + try { + await Promise.race([completion, deadline]); return this.public(record); - } catch (error) { - if (record.status === "running") { - record.status = "failed"; - record.error = error instanceof Error ? error.message : String(error); - } - throw error; } finally { - this.busy = false; + if (timer !== undefined) clearTimeout(timer); } } @@ -256,6 +309,17 @@ export class MutationLifecycle { return copy({ ...record, status: record.status === "prepared" && Date.now() > Date.parse(record.expiresAt) ? "expired" : record.status, + execution: { + timeoutMs: this.executionTimeoutMs, + elapsedMs: record.startedAt + ? Math.max(0, (record.settledAt ? Date.parse(record.settledAt) : Date.now()) - Date.parse(record.startedAt)) + : 0, + lockHeld: this.busy && this.activeMutationId === record.mutationId, + recovery: + this.busy && this.activeMutationId === record.mutationId + ? "Query this mutation; the lock releases automatically when the original executor settles. If it never settles, reload the extension and inspect the document before any retry." + : "No execution lock held. Inspect the result before preparing another operation." + }, documentSaved: false as const }); } diff --git a/src/mutation/contracts.ts b/src/mutation/contracts.ts index 5f83e10..fe64236 100644 --- a/src/mutation/contracts.ts +++ b/src/mutation/contracts.ts @@ -54,6 +54,11 @@ export type MutationRecord, TData = unknown expiresAt: string; after?: TData; error?: string; + startedAt?: string; + timedOutAt?: string; + settledAt?: string; + phase?: "execute" | "readback" | "settled"; + execution?: { timeoutMs: number; elapsedMs: number; lockHeld: boolean; recovery: string }; documentSaved: false; }; diff --git a/src/schematic/connectivity.ts b/src/schematic/connectivity.ts index 7eee91b..2729298 100644 --- a/src/schematic/connectivity.ts +++ b/src/schematic/connectivity.ts @@ -1,3 +1,4 @@ +import { applyNativeNetlist } from "./nativeNetlist.js"; import { extractSegments, formatPin, @@ -302,6 +303,8 @@ export function buildSchematicSnapshot(raw: RawSchematicData): SchematicSnapshot ...(raw.texts ?? []).flatMap((text) => normalizeTextLabel(text, includeRaw)) ]; const resolved = resolveConnectivity(pins, wires, labels); + const native = applyNativeNetlist(resolved.pins, raw.nativeNetlist); + resolved.pins = native.pins; const nets = buildNets(resolved.pins, resolved.wires, labels); const warnings: string[] = []; @@ -311,7 +314,7 @@ export function buildSchematicSnapshot(raw: RawSchematicData): SchematicSnapshot if (wires.length === 0) { warnings.push("No schematic wires were returned by EasyEDA Pro; wire-based checks may be incomplete."); } - warnings.push(...resolved.warnings); + warnings.push(...resolved.warnings, ...native.warnings); const completeness: DataCompleteness = raw.completeness ?? @@ -326,6 +329,7 @@ export function buildSchematicSnapshot(raw: RawSchematicData): SchematicSnapshot return { snapshotId, + nativeNetlist: native.report, target: raw.target, capturedAt, source, diff --git a/src/schematic/nativeNetlist.test.ts b/src/schematic/nativeNetlist.test.ts new file mode 100644 index 0000000..e5f307e --- /dev/null +++ b/src/schematic/nativeNetlist.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from "vitest"; +import { applyNativeNetlist, parseProtel2 } from "./nativeNetlist.js"; +import { buildSchematicSnapshot } from "./analysis.js"; +import type { SchematicPin } from "./types.js"; + +const text = "[\nUSB2\nUSB-C\nConnector\n]\n(\nUSB_D+\nUSB2-A6\nUSB2-B6\n)\n(\nUSB_D-\nUSB2-A7\nUSB2-B7\n)"; +const pin: SchematicPin = { + componentDesignator: "USB2", + pinNumber: "A6", + net: "WRONG", + nodeId: "net:WRONG", + connected: true, + position: {} +}; + +describe("native Protel2 membership", () => { + it("parses component records, CRLF and polarity-sensitive net names", () => { + const nets = parseProtel2("\uFEFF" + text.replace(/\n/g, "\r\n")); + expect(nets.get("USB_D+")).toEqual(["USB2-A6", "USB2-B6"]); + expect(nets.get("USB_D-")).toEqual(["USB2-A7", "USB2-B7"]); + }); + it.each(["", "not a netlist", "(\nNET\nU1-1", "(\n)\n", "(\nNET\ninvalid-memberless\n[\n)"])( + "rejects unsupported or incomplete data: %j", + (bad) => { + expect(() => parseProtel2(bad)).toThrow(); + } + ); + it("prefers native pin membership and reports a disagreement", () => { + const result = applyNativeNetlist([pin], { status: "available", format: "Protel2", text }); + expect(result.pins[0]).toMatchObject({ net: "USB_D+", nodeId: "net:USB_D+", netSource: "native_netlist" }); + expect(result.report).toMatchObject({ matchedPins: 1, conflicts: 1 }); + expect(result.warnings[0]).toMatch(/disagreement/); + }); + it("does not interpret absent pins as disconnected or match duplicate references", () => { + for (const data of [{ text: "(\nGND\nOTHER-1\n)" }, { text, ambiguousDesignators: ["USB2"] }]) { + const result = applyNativeNetlist([pin], { ...data, status: "available", format: "Protel2" }); + expect(result.pins[0]).toEqual(pin); + expect(result.report.matchedPins).toBe(0); + } + }); + it("leaves contradictory native memberships unknown", () => { + const result = applyNativeNetlist([pin], { + status: "available", + format: "Protel2", + text: "(\nA\nUSB2-A6\n)\n(\nB\nUSB2-A6\n)" + }); + expect(result.pins[0]).toMatchObject({ netSource: "unknown" }); + expect(result.pins[0].net).toBeUndefined(); + expect(result.pins[0].nodeId).toBeUndefined(); + expect(result.report.conflicts).toBe(1); + }); + it("keeps geometric data when parsing fails", () => { + const result = applyNativeNetlist([pin], { status: "available", format: "Protel2", text: "ZIP or unknown format" }); + expect(result.report.status).toBe("unsupported"); + expect(result.pins[0]).toEqual(pin); + }); + it("builds native pin nets without any image or wire geometry", () => { + const snapshot = buildSchematicSnapshot({ + components: [{ primitiveId: "usb", designator: "USB2", componentType: "part" }], + pinsByComponent: { + usb: [ + { pinNumber: "A6", pinName: "D+" }, + { pinNumber: "A7", pinName: "D-" } + ] + }, + nativeNetlist: { status: "available", format: "Protel2", text } + }); + expect(snapshot.pins.map((p) => p.net)).toEqual(["USB_D+", "USB_D-"]); + expect(snapshot.nativeNetlist?.matchedPins).toBe(2); + expect(snapshot.nets.map((n) => n.name)).toEqual(["USB_D-", "USB_D+"]); + }); +}); diff --git a/src/schematic/nativeNetlist.ts b/src/schematic/nativeNetlist.ts new file mode 100644 index 0000000..f8cf3f5 --- /dev/null +++ b/src/schematic/nativeNetlist.ts @@ -0,0 +1,133 @@ +import type { SchematicPin } from "./types.js"; +import { netNodeId } from "./normalization.js"; + +export type NativeNetlistData = { + status: "available" | "unavailable" | "unsupported" | "error"; + format: "Protel2"; + text?: string; + reason?: string; + ambiguousDesignators?: string[]; +}; + +// Protel2 uses [component records] and (net name, reference-pin records). +// Reject unknown syntax rather than treating an unparsed file as an empty circuit. +export function parseProtel2(text: string): Map { + if (text.length > 2_000_000) throw new Error("Native netlist exceeds 2 MB"); + const result = new Map(); + const lines = text + .replace(/^\uFEFF/, "") + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean); + let mode: "component" | "net" | undefined; + let name: string | undefined; + let records = 0; + for (const line of lines) { + if (!mode) { + if (line === "[") mode = "component"; + else if (line === "(") { + mode = "net"; + name = undefined; + } else throw new Error("Unsupported Protel2 record"); + } else if ((mode === "component" && line === "]") || (mode === "net" && line === ")")) { + if (mode === "net" && !name) throw new Error("Empty net record"); + mode = undefined; + records++; + } else if (["[", "]", "(", ")"].includes(line)) { + throw new Error("Malformed Protel2 nesting"); + } else if (mode === "net") { + if (!name) { + name = line; + if (!result.has(name)) result.set(name, []); + } else { + if (!line.includes("-")) throw new Error("Unsupported net member"); + result.get(name)!.push(line); + } + } + } + if (mode || !records) throw new Error("Incomplete or unrecognized Protel2 netlist"); + return result; +} + +export function applyNativeNetlist(pins: SchematicPin[], data?: NativeNetlistData) { + const report = { + status: data?.status ?? "unavailable", + format: "Protel2" as const, + matchedPins: 0, + conflicts: 0, + reason: data?.reason + }; + const warnings: string[] = []; + if (!data || data.status !== "available" || data.text === undefined) { + warnings.push(`Native netlist unavailable: ${data?.reason ?? "not collected"}. Connectivity may be inferred.`); + return { pins, report, warnings }; + } + let nets: Map; + try { + nets = parseProtel2(data.text); + } catch (error) { + report.status = "unsupported"; + report.reason = error instanceof Error ? error.message : String(error); + warnings.push(`Native netlist was not used: ${report.reason}.`); + return { pins, report, warnings }; + } + const byMember = new Map>(); + for (const [net, members] of nets) + for (const member of members) { + const names = byMember.get(member) ?? new Set(); + names.add(net); + byMember.set(member, names); + } + const ambiguous = new Set(data.ambiguousDesignators); + const mapped = pins.map((pin) => { + if (!pin.componentDesignator || !pin.pinNumber || ambiguous.has(pin.componentDesignator)) return pin; + const names = byMember.get(`${pin.componentDesignator}-${pin.pinNumber}`); + if (!names?.size) return pin; // Absence does not prove a pin is disconnected. + if (names.size !== 1) { + report.conflicts++; + warnings.push( + `Native netlist has multiple nets for ${pin.componentDesignator}#${pin.pinNumber}; mapping skipped.` + ); + return { + ...pin, + net: undefined, + nodeId: undefined, + connected: undefined, + netSource: "unknown" as const, + connectivityEvidence: { + source: "unknown" as const, + confidence: "low" as const, + reason: "Conflicting native net membership" + } + }; + } + const net = [...names][0]; + report.matchedPins++; + if (pin.net && pin.net !== net) { + report.conflicts++; + warnings.push( + `Native/geometry disagreement for ${pin.componentDesignator}#${pin.pinNumber}: native=${net}, inferred=${pin.net}. Native membership used.` + ); + } + return { + ...pin, + net, + nodeId: netNodeId(net), + connected: true, + netSource: "native_netlist" as const, + connectivityEvidence: { + source: "native_netlist" as const, + confidence: "high" as const, + net, + nodeId: netNodeId(net), + reason: "Exact unique designator and pin match in native Protel2 netlist" + } + }; + }); + if (ambiguous.size) warnings.push("Native mapping skipped for duplicate project designators."); + if (!report.matchedPins) + warnings.push( + "Native netlist contains no unambiguous matches for the collected pins; geometry remains a fallback." + ); + return { pins: mapped, report, warnings }; +} diff --git a/src/schematic/normalization.test.ts b/src/schematic/normalization.test.ts new file mode 100644 index 0000000..6a6f360 --- /dev/null +++ b/src/schematic/normalization.test.ts @@ -0,0 +1,134 @@ +import { describe, expect, it } from "vitest"; +import { buildSchematicSnapshot, verifyConnections } from "./analysis.js"; +import { extractSegments, netNodeId } from "./normalization.js"; + +describe("schematic wire geometry", () => { + it("reads all legs of flat and nested polylines", () => { + const expected = [ + { start: { x: 0, y: 0 }, end: { x: 10, y: 0 } }, + { start: { x: 10, y: 0 }, end: { x: 10, y: 20 } } + ]; + expect(extractSegments([0, 0, 10, 0, 10, 20])).toEqual(expected); + expect(extractSegments([[0, 0, 10, 0, 10, 20]])).toEqual(expected); + expect( + extractSegments([ + [0, 0], + [10, 0], + [10, 20] + ]) + ).toEqual(expected); + expect( + extractSegments([ + { x: 0, y: 0 }, + { x: 10, y: 0 }, + { x: 10, y: 20 } + ]) + ).toEqual(expected); + }); + + it("does not bridge independent paths or malformed coordinates", () => { + expect( + extractSegments([ + [0, 0, 10, 0], + [20, 0, 30, 0] + ]) + ).toHaveLength(2); + expect( + extractSegments([ + [0, 0], + [10, 0, 20, 0], + [30, 0] + ]) + ).toHaveLength(1); + expect(extractSegments([{ x: 0, y: 0 }, {}, { x: 30, y: 0 }])).toEqual([]); + for (const invalid of [ + [0, 0, 10], + [0, 0, NaN, 10], + [0, 0, Infinity, 10], + [0, 0, "10", 10] + ]) { + expect(extractSegments(invalid)).toEqual([]); + } + }); + + it("resolves charger pins and branches from flat wire coordinates", () => { + const snapshot = buildSchematicSnapshot({ + components: [{ primitiveId: "u5", designator: "U5", componentType: "part" }], + pinsByComponent: { + u5: [ + { pinNumber: "3", pinName: "BAT", x: 360, y: 390 }, + { pinNumber: "4", pinName: "VCC", x: 480, y: 390 }, + { pinNumber: "2", pinName: "GND", x: 360, y: 410 } + ] + }, + wires: [ + { primitiveId: "bat", net: "VBAT_LIPO", line: [350, 390, 320, 390, 350, 390, 360, 390] }, + { primitiveId: "vcc", net: "VBUS", line: [480, 390, 500, 390] }, + { primitiveId: "gnd", net: "GND", line: [310, 410, 360, 410, 310, 410, 310, 350] } + ] + }); + expect(snapshot.pins.map((pin) => pin.net)).toEqual(["VBAT_LIPO", "VBUS", "GND"]); + expect(snapshot.pins.every((pin) => pin.connected)).toBe(true); + }); + + it("keeps native PROG readback separate from STDBY without inventing a diagonal", () => { + const snapshot = buildSchematicSnapshot({ + components: [ + { primitiveId: "u5", designator: "U5", componentType: "part" }, + { primitiveId: "r7", designator: "R7", componentType: "part" } + ], + pinsByComponent: { + u5: [ + { pinNumber: "6", pinName: "PROG", x: 480, y: 430 }, + { pinNumber: "5", pinName: "STDBY", x: 480, y: 410 } + ], + r7: [{ pinNumber: "2", pinName: "2", x: 520, y: 390 }] + }, + wires: [ + { primitiveId: "e6440", net: "", line: [520, 430, 520, 390, 480, 430, 520, 430] }, + { primitiveId: "e5061", net: "STDBY", line: [500, 410, 480, 410] } + ] + }); + expect(snapshot.pins[0].net).toBeUndefined(); + expect(snapshot.pins[0].connected).toBe(true); + expect(snapshot.pins[0].nodeId).toBe(snapshot.pins[2].nodeId); + expect(snapshot.pins[0].nodeId).not.toBe(snapshot.pins[1].nodeId); + expect(snapshot.pins[1].net).toBe("STDBY"); + const result = verifyConnections(snapshot, [ + { + type: "same_node", + left: { component: "U5", pin: "6" }, + right: { component: "U5", pin: "5" } + } + ]); + expect(result.checks[0].status).not.toBe("pass"); + }); +}); + +describe("schematic net identity", () => { + it("preserves punctuation and exact names", () => { + const names = ["USB_D+", "USB_D-", "USB_D", "+3V3", "3V3", "BATT_GND", "BATT-GND", "电源+", "电源-"]; + expect(new Set(names.map(netNodeId)).size).toBe(names.length); + }); + + it("does not report opposite USB signals on the same node", () => { + const snapshot = buildSchematicSnapshot({ + components: [{ primitiveId: "usb", designator: "USB1", componentType: "part" }], + pinsByComponent: { + usb: [ + { pinNumber: "1", pinName: "D+", net: "USB_D+" }, + { pinNumber: "2", pinName: "D-", net: "USB_D-" } + ] + } + }); + const result = verifyConnections(snapshot, [ + { + type: "same_node", + left: { component: "USB1", pin: "1" }, + right: { component: "USB1", pin: "2" } + } + ]); + expect(snapshot.pins[0].nodeId).not.toBe(snapshot.pins[1].nodeId); + expect(result.checks[0].status).toBe("fail"); + }); +}); diff --git a/src/schematic/normalization.ts b/src/schematic/normalization.ts index 1a8553b..3ee18a1 100644 --- a/src/schematic/normalization.ts +++ b/src/schematic/normalization.ts @@ -80,25 +80,34 @@ export function extractSegments(value: unknown): Segment[] { return []; } const segments: Segment[] = []; - const points: Required[] = []; + // EasyEDA returns both flat polylines and arrays of independent polylines. + // Never join the end of one independent path to the start of another. + if (value.some((item) => typeof item === "number")) { + if (value.length < 4 || value.length % 2 !== 0 || !value.every((item) => numberValue(item) !== undefined)) { + return []; + } + for (let index = 2; index < value.length; index += 2) { + segments.push({ + start: { x: value[index - 2], y: value[index - 1] }, + end: { x: value[index], y: value[index + 1] } + }); + } + return segments; + } + let previousPoint: Required | undefined; for (const item of value) { if (Array.isArray(item) && item.length >= 4) { - const start = requiredPosition({ x: numberValue(item[0]), y: numberValue(item[1]) }); - const end = requiredPosition({ x: numberValue(item[2]), y: numberValue(item[3]) }); - if (start && end) { - segments.push({ start, end }); - } + previousPoint = undefined; + segments.push(...extractSegments(item)); continue; } const point = Array.isArray(item) ? requiredPosition({ x: numberValue(item[0]), y: numberValue(item[1]) }) : requiredPosition({ x: numberValue(asRecord(item).x), y: numberValue(asRecord(item).y) }); - if (point) { - points.push(point); + if (point && previousPoint) { + segments.push({ start: previousPoint, end: point }); } - } - for (let index = 1; index < points.length; index += 1) { - segments.push({ start: points[index - 1], end: points[index] }); + previousPoint = point; } return segments; } @@ -204,7 +213,8 @@ export function pinEvidence(pin: SchematicPin): Record { } export function netNodeId(net: string): string { - return `net:${canonicalNet(net)}`; + // Keep significant punctuation: USB_D+ and USB_D- are different nodes. + return `net:${net}`; } export function normalizeComponent(raw: unknown, includeRaw: boolean): SchematicComponent { @@ -265,11 +275,22 @@ export function normalizePin( export function normalizeWire(raw: unknown, includeRaw: boolean): SchematicWire { const item = asRecord(raw); + const line = item.line; + const geometry = line ?? item.points ?? item.geometry; + // Native Wire.line readback packs independent segments as x1,y1,x2,y2. + // Joining consecutive segments introduces artificial paths between their ends. + const normalizedGeometry = + Array.isArray(line) && + line.length > 0 && + line.length % 4 === 0 && + line.every((coordinate: unknown) => numberValue(coordinate) !== undefined) + ? Array.from({ length: line.length / 4 }, (_, index) => line.slice(index * 4, index * 4 + 4)) + : geometry; return { primitiveId: stringValue(item.primitiveId ?? item.id ?? item.uuid), net: normalizeNetName(item.net ?? item.netName), - geometry: item.line ?? item.points ?? item.geometry, - endpoints: inferEndpoints(item.line ?? item.points ?? item.geometry), + geometry: normalizedGeometry, + endpoints: inferEndpoints(normalizedGeometry), raw: includeRaw ? compactRaw(item) : undefined }; } diff --git a/src/schematic/types.ts b/src/schematic/types.ts index 96cade6..5be37d1 100644 --- a/src/schematic/types.ts +++ b/src/schematic/types.ts @@ -1,3 +1,4 @@ +import type { NativeNetlistData } from "./nativeNetlist.js"; import type { DataCompleteness, DataSource, DocumentIdentity } from "../protocol/identity.js"; export type Confidence = "high" | "partial" | "low"; @@ -7,7 +8,7 @@ export type Position = { y?: number; }; -export type ConnectivitySource = "direct" | "wire_inferred" | "label_inferred" | "unknown"; +export type ConnectivitySource = "direct" | "native_netlist" | "wire_inferred" | "label_inferred" | "unknown"; export type ConnectivityEvidence = { source: ConnectivitySource; @@ -79,6 +80,13 @@ export type SchematicNet = { }; export type SchematicSnapshot = { + nativeNetlist?: { + status: NativeNetlistData["status"]; + format: "Protel2"; + matchedPins: number; + conflicts: number; + reason?: string; + }; snapshotId?: string; target?: DocumentIdentity; capturedAt?: string; @@ -102,6 +110,7 @@ export type SchematicSnapshot = { }; export type RawSchematicData = { + nativeNetlist?: NativeNetlistData; snapshotId?: string; target?: DocumentIdentity; capturedAt?: string; diff --git a/src/version.ts b/src/version.ts index 1d0ad93..c3ff56a 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,3 +1,3 @@ export const MCP_SERVER_NAME = "easyeda-pro-mcp"; -export const MCP_SERVER_VERSION = "1.4.0"; -export const EXTENSION_VERSION = "0.5.0"; +export const MCP_SERVER_VERSION = "1.4.1"; +export const EXTENSION_VERSION = "0.5.1";