From 55e3a9ecf37a47577ab198d186ad5cdb16558a6e Mon Sep 17 00:00:00 2001 From: Codex Astra Date: Wed, 9 Sep 2026 16:31:57 -0500 Subject: [PATCH] Support revisioned sheet sizes and reject stale native views --- docs/AUTHORING-DEVELOPMENT.md | 7 ++++ src/author.rs | 63 ++++++++++++++++++++++++++++++++++- src/author_server.rs | 2 +- src/author_ui.js | 9 ++--- 4 files changed, 75 insertions(+), 6 deletions(-) diff --git a/docs/AUTHORING-DEVELOPMENT.md b/docs/AUTHORING-DEVELOPMENT.md index faa9d64..d88f8bf 100644 --- a/docs/AUTHORING-DEVELOPMENT.md +++ b/docs/AUTHORING-DEVELOPMENT.md @@ -95,3 +95,10 @@ Model paths in the footprint exports use `${KIPRJMOD}/models//` w `set_label_net {endpoint,net}` explicitly changes an existing pin-attached label's electrical net while preserving its anchor and text angle. Unlike `style_label`, this is an electrical edit: merging with an existing named net is intentional and requires native ERC/connectivity review. The Text layout panel exposes a separate Change net control. Undo restores the prior assignment. Empty/control-character names are rejected. + + +### Page size and native-view freshness + +`set_paper {paper:"A3"}` changes the landscape sheet format through the same revisioned transaction as UI edits. Supported formats are A4, A3, A2, A1 and A0. Existing documents without a paper field retain A4 and unchanged native export bytes. Paper changes preserve circuit geometry, survive save/restore and can be undone. The Sheet control exposes the operation; this does not add multi-sheet support or automatic page/body/text collision checking. + +Every live-state update clears native attribution. A native response only mounts if its requested revision, report revision and view request generation still match the current view. Switching to live preview or accepting an SSE update invalidates an in-flight native response, preventing late replies from replacing current content. diff --git a/src/author.rs b/src/author.rs index 433027e..6146696 100644 --- a/src/author.rs +++ b/src/author.rs @@ -179,6 +179,8 @@ pub struct Label { pub struct Document { pub id: String, pub name: String, + #[serde(default = "default_paper")] + pub paper: String, pub libraries: BTreeMap, pub components: BTreeMap, pub connections: Vec, @@ -199,6 +201,9 @@ pub struct Project { #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)] pub enum Operation { + SetPaper { + paper: String, + }, AddLibrary { key: String, symbol: String, @@ -402,6 +407,9 @@ fn coords(x: f64, y: f64, r: u16) -> Result<()> { }; Ok(()) } +fn default_paper() -> String { + "A4".into() +} impl Project { pub fn new(name: &str) -> Self { Self { @@ -409,6 +417,7 @@ impl Project { document: Document { id: Uuid::new_v4().to_string(), name: name.into(), + paper: default_paper(), libraries: BTreeMap::new(), components: BTreeMap::new(), connections: vec![], @@ -480,6 +489,9 @@ impl Project { impl Document { fn apply(&mut self, op: &Operation) -> Result<()> { match op { + Operation::SetPaper { paper } => { + self.paper = paper.clone(); + } Operation::AddLibrary { key, symbol } => { asset_key(key)?; if self.libraries.contains_key(key) { @@ -656,6 +668,9 @@ impl Document { Ok(out) } fn validate(&self) -> Result<()> { + if !["A4", "A3", "A2", "A1", "A0"].contains(&self.paper.as_str()) { + bail!("unsupported_paper: choose A4, A3, A2, A1 or A0 landscape") + } for (key, lib) in &self.libraries { asset_key(key)?; if let Some(fp) = &lib.footprint { @@ -841,7 +856,7 @@ impl Document { pub fn export_kicad(&self) -> Result { self.validate()?; let root = id(&self.id, "sheet"); - let mut out=format!("(kicad_sch (version 20250114) (generator \"adom-schematic\") (uuid {root}) (paper \"A4\")\n(title_block (title {}))\n(lib_symbols\n",q(&self.name)); + let mut out=format!("(kicad_sch (version 20250114) (generator \"adom-schematic\") (uuid {root}) (paper {})\n(title_block (title {}))\n(lib_symbols\n",q(&self.paper),q(&self.name)); for (key, lib) in &self.libraries { let a = exported_library(key, lib, true)?; out += &a.emit(); @@ -1005,6 +1020,52 @@ mod tests { .unwrap() } #[test] + fn paper_migration_persistence_and_undo_preserve_circuit() { + let p = placed(); + let mut legacy = serde_json::to_value(&p).unwrap(); + legacy["document"].as_object_mut().unwrap().remove("paper"); + let restored: Project = serde_json::from_value(legacy).unwrap(); + assert_eq!( + restored.document.export_kicad().unwrap(), + p.document.export_kicad().unwrap() + ); + let before = p.document.pin_inventory().unwrap(); + let q = p + .stage(&tx( + &p, + "a3", + vec![Operation::SetPaper { paper: "A3".into() }], + )) + .unwrap(); + assert_eq!(q.document.pin_inventory().unwrap(), before); + assert!(q + .document + .export_kicad() + .unwrap() + .contains("(paper \"A3\")")); + let folder = std::env::temp_dir().join(format!("adom-paper-{}", Uuid::new_v4())); + q.persist(&folder).unwrap(); + let saved = Project::restore(&folder).unwrap(); + assert_eq!(saved.document.paper, "A3"); + let undone = saved + .stage(&tx(&saved, "undo-paper", vec![Operation::Undo])) + .unwrap(); + assert_eq!( + undone.document.export_kicad().unwrap(), + p.document.export_kicad().unwrap() + ); + assert!(p + .stage(&tx( + &p, + "bad-paper", + vec![Operation::SetPaper { + paper: "arbitrary".into() + }] + )) + .is_err()); + std::fs::remove_dir_all(folder).unwrap(); + } + #[test] fn library_fields_and_outward_labels_follow_rotation() { let mut p = placed(); p.document.labels.push(Label { diff --git a/src/author_server.rs b/src/author_server.rs index 4b30d32..9bed37a 100644 --- a/src/author_server.rs +++ b/src/author_server.rs @@ -37,7 +37,7 @@ fn snapshot(p: &Project, owner: &str) -> Result { inner ); Ok( - json!({"name":p.document.name,"svg":svg,"meta":serde_json::from_str::(&crate::kicad_sch::meta_json(&sch)?)?,"author":{"revision":p.revision,"documentId":p.document.id,"aiThread":owner,"libraries":p.document.libraries.keys().collect::>(),"footprintBindings":p.document.libraries.iter().filter_map(|(k,l)|l.footprint.as_ref().map(|f|(k.clone(),f.source_sha256.clone()))).collect::>(),"components":p.document.components,"pins":p.document.pin_inventory()?,"contactIssues":p.document.contact_issues()?,"connections":p.document.connections,"labels":p.document.labels,"status":"Development authoring slice; circuit/ERC and native parity pending","hints":["Use expectedRevision and operationId for every edit; read state on conflicts.","Endpoints are stable reference/pin identities; moving a component updates connected wire endpoints.","Local Rust preview is not a native KiCad render or ERC result.","Inspect contactIssues for unintended pin or wire contacts. Body clearance and native netlist equivalence remain separate checks."]}}), + json!({"name":p.document.name,"svg":svg,"meta":serde_json::from_str::(&crate::kicad_sch::meta_json(&sch)?)?,"author":{"revision":p.revision,"paper":p.document.paper,"documentId":p.document.id,"aiThread":owner,"libraries":p.document.libraries.keys().collect::>(),"footprintBindings":p.document.libraries.iter().filter_map(|(k,l)|l.footprint.as_ref().map(|f|(k.clone(),f.source_sha256.clone()))).collect::>(),"components":p.document.components,"pins":p.document.pin_inventory()?,"contactIssues":p.document.contact_issues()?,"connections":p.document.connections,"labels":p.document.labels,"status":"Development authoring slice; circuit/ERC and native parity pending","hints":["Use expectedRevision and operationId for every edit; read state on conflicts.","Endpoints are stable reference/pin identities; moving a component updates connected wire endpoints.","Local Rust preview is not a native KiCad render or ERC result.","Inspect contactIssues for unintended pin or wire contacts. Body clearance and native netlist equivalence remain separate checks."]}}), ) } fn error(e: impl std::fmt::Display) -> Value { diff --git a/src/author_ui.js b/src/author_ui.js index 5ca5131..d62458e 100644 --- a/src/author_ui.js +++ b/src/author_ui.js @@ -1,14 +1,15 @@ /* The same authoring transaction endpoint serves human controls and the CLI. */ (async()=>{ const initial=await fetch('state').then(r=>r.json());if(!initial.author)return; - let latest=initial.author;const style=document.createElement('style');style.textContent=` + let latest=initial.author;let renderEpoch=0;const style=document.createElement('style');style.textContent=` body.author #svgbox{top:var(--author-canvas-top,152px)!important}body.author #side{display:none!important}#authorBar{position:absolute;top:44px;left:0;right:0;min-height:92px;z-index:10;padding:6px 12px;background:var(--panel,#15202b);border-bottom:1px solid var(--edge,#39434d);font:12px sans-serif;color:var(--ink,#eee)} #authorBar .row{display:flex;gap:6px;align-items:center;flex-wrap:wrap;margin:4px 0}#authorBar input,#authorBar select,#authorBar button{font:inherit;background:var(--bg,#18232e);color:inherit;border:1px solid var(--edge,#40505d);border-radius:4px;padding:4px}#authorBar input[type=number]{width:48px}#authorBar .ref{width:44px}#authorStatus{color:var(--muted,#abb7c2)}#authorBar a{color:var(--accent,#73caca)} `;document.head.append(style);document.body.classList.add('author'); - const bar=document.createElement('section');bar.id='authorBar';bar.innerHTML=`
Development circuit • not releasedKiCad file
Library links
Project files JSON
Fields and net labels
Change net edits electrical connectivity. Field placement and angles keep nets unchanged.
`;document.body.append(bar);new ResizeObserver(()=>document.body.style.setProperty('--author-canvas-top',`${44+bar.getBoundingClientRect().height}px`)).observe(bar); + const bar=document.createElement('section');bar.id='authorBar';bar.innerHTML=`
Development circuit • not releasedKiCad file
Sheet
Library links
Project files JSON
Fields and net labels
Change net edits electrical connectivity. Field placement and angles keep nets unchanged.
`;document.body.append(bar);new ResizeObserver(()=>document.body.style.setProperty('--author-canvas-top',`${44+bar.getBoundingClientRect().height}px`)).observe(bar); const $=s=>document.getElementById(s);function options(el,rows){const old=el.value;el.replaceChildren(...rows.map(([v,t])=>{const o=document.createElement('option');o.value=v;o.textContent=t;return o}));if(rows.some(([v])=>v===old))el.value=old;} - function update(s){if(!s.author)return;latest=s.author;window.AdomAuthorSnapshot=s;window.AdomAuthorState=latest;window.AdomSch.mount(s.svg,s.meta);$('authorRevision').textContent=`${s.name} · revision ${latest.revision}`;options($('authorLib'),latest.libraries.map(k=>[k,k]));options($('authorBindKey'),latest.libraries.map(k=>[k,k]));$('authorLinkStatus').textContent=`${Object.keys(latest.footprintBindings||{}).length}/${latest.libraries.length} footprints linked`;const pins=latest.pins.map(p=>[JSON.stringify(p.endpoint),`${p.endpoint.reference}.${p.endpoint.pin}`]);options($('authorFrom'),pins);options($('authorTo'),pins);options($('authorFieldRef'),Object.keys(latest.components).map(r=>[r,r]));options($('authorLabelPin'),latest.labels.map(l=>[JSON.stringify(l.endpoint),`${l.endpoint.reference}.${l.endpoint.pin}: ${l.net}`]));requestAnimationFrame(()=>requestAnimationFrame(()=>fetch('author/ack',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({revision:latest.revision,componentCount:latest.pins.length?Object.keys(latest.components).length:0,paintedAt:new Date().toISOString()})})));} + function update(s){if(!s.author)return;latest=s.author;renderEpoch++;$('authorPaper').value=latest.paper||'A4';$('authorStatus').textContent='Live Rust preview • native checks separate';window.AdomAuthorSnapshot=s;window.AdomAuthorState=latest;window.AdomSch.mount(s.svg,s.meta);$('authorRevision').textContent=`${s.name} · revision ${latest.revision}`;options($('authorLib'),latest.libraries.map(k=>[k,k]));options($('authorBindKey'),latest.libraries.map(k=>[k,k]));$('authorLinkStatus').textContent=`${Object.keys(latest.footprintBindings||{}).length}/${latest.libraries.length} footprints linked`;const pins=latest.pins.map(p=>[JSON.stringify(p.endpoint),`${p.endpoint.reference}.${p.endpoint.pin}`]);options($('authorFrom'),pins);options($('authorTo'),pins);options($('authorFieldRef'),Object.keys(latest.components).map(r=>[r,r]));options($('authorLabelPin'),latest.labels.map(l=>[JSON.stringify(l.endpoint),`${l.endpoint.reference}.${l.endpoint.pin}: ${l.net}`]));requestAnimationFrame(()=>requestAnimationFrame(()=>fetch('author/ack',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({revision:latest.revision,componentCount:latest.pins.length?Object.keys(latest.components).length:0,paintedAt:new Date().toISOString()})})));} async function transact(operations){const r=await fetch('author/transaction',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({aiThread:'Schematic UI',expectedRevision:latest.revision,operationId:crypto.randomUUID(),operations})});const s=await r.json();if(!s.ok){window.AdomSch.toast(s.error,'error');return}window.AdomSch.toast(`Saved revision ${s.revision}`,'success');} + $('authorPaperApply').onclick=()=>transact([{op:'set_paper',paper:$('authorPaper').value}]); $('authorPlace').onclick=()=>transact([{op:'place',component:{reference:$('authorRef').value,library:$('authorLib').value,value:$('authorLib').value,x:Number($('authorX').value),y:Number($('authorY').value),rotation:0}}]); $('authorConnect').onclick=()=>{if(!$('authorFrom').value||!$('authorTo').value)return;transact([{op:'connect',connection:{id:crypto.randomUUID(),from:JSON.parse($('authorFrom').value),to:JSON.parse($('authorTo').value)}}]);}; $('authorBind').onclick=async()=>{const file=$('authorBindFile').files[0];if(!file){window.AdomSch.toast('Choose the exact component footprint file','error');return;}await transact([{op:'bind_footprint',key:$('authorBindKey').value,footprint:await file.text()}]);}; @@ -18,7 +19,7 @@ function fieldSelection(){const f=latest.components[$('authorFieldRef').value]?.fields?.[$('authorFieldName').value];if(f){$('authorFieldX').value=f.x;$('authorFieldY').value=f.y;$('authorFieldAngle').value=f.rotation;}} $('authorFieldRef').onchange=fieldSelection;$('authorFieldName').onchange=fieldSelection; $('authorLabelPin').onchange=()=>{const l=latest.labels.find(l=>JSON.stringify(l.endpoint)===$('authorLabelPin').value);if(l){$('authorLabelNet').value=l.net;if(l.angle!==undefined)$('authorLabelAngle').value=l.angle;}}; - $('authorNative').onclick=async()=>{const r=await fetch('author/native');const v=await r.json();if(!v.ok){window.AdomSch.toast(v.error,'error');return}window.AdomSch.mount(v.svg,v.meta);$('authorStatus').textContent=`KiCad ${v.report.kicadVersion} service render • revision ${v.report.revision} • ${v.report.violationCount} ERC findings`;}; + $('authorNative').onclick=async()=>{const epoch=++renderEpoch;const revision=latest.revision;const r=await fetch('author/native');const v=await r.json();if(!v.ok){window.AdomSch.toast(v.error,'error');return}if(epoch!==renderEpoch||revision!==latest.revision||v.report.revision!==latest.revision){window.AdomSch.toast('Native response is stale; inspect the current revision','error');return}window.AdomSch.mount(v.svg,v.meta);$('authorStatus').textContent=`KiCad ${v.report.kicadVersion} service render • revision ${v.report.revision} • ${v.report.violationCount} ERC findings`;}; $('authorLocal').onclick=()=>{update({name:initial.name,author:latest,...window.AdomAuthorSnapshot});$('authorStatus').textContent='Live Rust preview • native checks separate';}; $('authorUndo').onclick=()=>transact([{op:'undo'}]);update(initial);const events=new EventSource('events');events.addEventListener('state',e=>update(JSON.parse(e.data)));events.onerror=()=>{$('authorStatus').textContent='Reconnecting… saved document retained';};events.onopen=()=>{$('authorStatus').textContent='Live • development circuit • ERC pending';}; })().catch(e=>console.error('Authoring UI:',e)); -- 2.43.0