← All Pull Requests

0.14.1: --render-board pushes to the named page; the Manager reads pages by owner-qualified ref #1

Merged not released yet opened by AdityaAngajala
Merges owner-qualified-refs → master

What this fixes

Two places dropped the owner from a page reference before talking to the wiki. Both work while only one owner has a given slug. Once a second owner has a page with the same slug, the bare slug is ambiguous: the wiki answers 409, or the Manager acts on another owner's page.

1. --render-board <owner>/<slug> pushed by bare slug

render_and_upload took slug.rsplit('/').next() before running adom-wiki repo push. The push argv now comes from render_push_args(), which passes the reference through unchanged: <owner>/<slug> stays qualified, a bare slug stays bare, a pg_ id passes through. The reads in the same command already used the reference unchanged. This was the only adom-wiki call that takes a page reference; the other one is whoami --json.

2. The Manager read dependency pages by bare slug

deps_of() stripped the owner from every package.json dependency (barrett-land/cl05b104ko5nnnc became cl05b104ko5nnnc) before the Manager read those pages. The gallery did the same: list_components dropped the listing's owner, so boards opened by bare slug, and circuit BOM rows stripped the owner from a component's page.

Server (src/main.rs):

  • manifest_deps() keeps each dependency reference as written.
  • /api/board and /api/project return {slug, ref} for each dependency.
  • /api/components items carry ref (<owner>/<slug>, from the listing's owner field), and tags_of_cached matches a ref against it.
  • /board-svg and /board-view read pcb or sch from the right of the path, so <owner>/<slug> works there. The other routes already took the rest of the path.
  • Names built from a slug use the slug part (page_slug()): the MPN in up(), the <slug>.glb fallback, the embed temp folder, and the default project folder and project library name in project delivery.

UI (src/manage.html, src/viewer3d.html):

  • Gallery rows and cards, library rows, BOM rows, board dependencies and project boards open pages by ref.
  • bySlug also indexes each listed page under its ref.
  • Wiki links and the wiki 3D viewer take the owner from the ref. The board-eda fetch and the viewer3d GLB URL encode each part of the ref and keep the /.

Also in this PR

  • skills/publish-board/SKILL.md said to use the bare slug for repo push. It now says <owner>/<slug> for repo push and for --render-board. That folder is in .adomignore, so it does not ship.
  • Version 0.14.1 in package.json, page.json, Cargo.toml, Cargo.lock and the UI boot diagnostic.
  • bin/adom-project-manager is rebuilt from this source (x86-64, needs GLIBC_2.39, the same floor as the 0.14.0 binary).

How it was checked

  • cargo test: 10 unit tests pass. Three cover the push argv (owner-qualified, bare, pg_ id). Seven cover dependency refs, the slug part and MPN, index matching, and board-path parsing.
  • Push argv, using the real binaries with a fake curl and adom-wiki on PATH, so nothing reached the network:
    • 0.14.0, --render-board aditya/usb3-ethernet ran adom-wiki repo push usb3-ethernet --files render/manifest.json ...
    • 0.14.1, same input, ran adom-wiki repo push aditya/usb3-ethernet --files render/manifest.json .... A bare usb3-ethernet stays bare.
  • Dependency reads, running both binaries as servers against a fake wiki. In it the bare slug part-a is ambiguous, only ownera/part-a resolves, and board ownerb/board-x depends on ownera/part-a:
    • 0.14.0: /api/board/ownerb/board-x returned part-a. /api/part/part-a read pages/part-a/files and failed.
    • 0.14.1: it returned {"ref": "ownera/part-a", "slug": "part-a"}. /api/part/ownera/part-a read that owner's page and loaded the part.
  • Live, 0.14.1 against wiki.adom.inc (GET only, public pages):
    • adom/bme690-molecule lists barrett-land/cl05b104ko5nnnc with its owner, and the part view loads it from that owner's page.
    • The legacy library expansion still works on adom/usb3-to-ethernet-dataonly-molecule (28 components through barrett-land/...-library).
    • board-media, board-eda, board-upaxis, board-svg (pcb and sch), board-glb, board-hero, glb and symbol-names all answered 200 for owner-qualified refs.
    • In a browser, the UI opened the board by ref, listed its dependencies with owners, and opened the part.
  • Not checked: the symbol, footprint and interactive board/schematic embeds. adom-symbol, adom-footprint, adom-2dboard and adom-schematic were not installed where this ran. The server log shows those routes parsed the ref and staged the files before the missing tool failed.

Not in this PR

The Manager's component list pages through /api/v1/pages with offset, and the wiki now refuses offset >= 1000 (USE_CURSOR). With 117,452 component pages, /api/components stops at the 1,000 most recently updated ones, and right now those include no public boards, so the gallery shows none. It needs the cursor paging the wiki asks for. That is a separate change.

🤖 Generated with Claude Code

Diff Skip to comments

Cargo.lock+1−1
@@ -4,7 +4,7 @@ version = 4  [[package]] name = "adom-project-manager"-version = "0.14.0"+version = "0.14.1" dependencies = [  "altium-codec",  "anyhow",
Cargo.toml+1−1
@@ -1,6 +1,6 @@ [package] name = "adom-project-manager"-version = "0.14.0"+version = "0.14.1" edition = "2021" description = "Adom Project Manager — the central hub for navigating wiki boards, molecules, and libraries into Hydrogen: browse your wiki boards/projects, view symbol + footprint + 3D and the footprint layer stackup, add components to your KiCad/Altium libraries, and deliver self-contained KiCad projects. Built on adom-lbr." 
bin/adom-project-manager
⋯ 1 unchanged line ⋯
package.json+1−1
@@ -1,6 +1,6 @@ {   "slug": "adom-project-manager",-  "version": "0.14.0",+  "version": "0.14.1",   "type": "app",   "description": "Adom Project Manager — the central hub for navigating wiki boards, molecules and libraries into Hydrogen: browse your wiki boards/projects (Personal / Organization / Public), view symbol + footprint + 3D and the per-EDA footprint layer stackup, explore the board and schematic in INTERACTIVE cross-probing viewers (click a net, hover a part for stock and price), add components to your KiCad/Altium libraries, and deliver self-contained KiCad projects. Built on adom-lbr. (Formerly Adom Project Manager / adom-project-manager.)",   "dependencies": {
page.json+1−1
@@ -1,6 +1,6 @@ {   "slug": "adom-project-manager",-  "version": "0.14.0",+  "version": "0.14.1",   "type": "app",   "description": "Adom Project Manager — the central hub for navigating wiki boards, molecules and libraries into Hydrogen: browse your wiki boards/projects (Personal / Organization / Public), view symbol + footprint + 3D and the per-EDA footprint layer stackup, explore the board and schematic in INTERACTIVE cross-probing viewers (click a net, hover a part for stock and price), add components to your KiCad/Altium libraries, and deliver self-contained KiCad projects. Built on adom-lbr. (Formerly Adom Project Manager / adom-project-manager.)",   "dependencies": {
skills/publish-board/SKILL.md+8−5
@@ -115,10 +115,10 @@ issue #7) so the pipeline delivers the JSON automatically; do it here until then After the board files are published, regenerate the pre-rendered assets so the Manager loads the board instantly (no live render) and the wiki 3D preview is fresh: ```-adom-project-manager --render-board <board-slug>+adom-project-manager --render-board <owner>/<board-slug> ``` This renders the 3D GLB + PCB SVG + per-sheet schematic SVGs and pushes them to the-page's `render/` folder (with a `manifest.json`). The Manager serves `render/`+`render/` folder of that owner's page (with a `manifest.json`). The Manager serves `render/` directly when present and only falls back to live rendering when it's absent. **Stale `render/` = the board shows its OLD 3D/PCB/schematic after an edit**, so never skip this after changing `.kicad_pcb`/`.kicad_sch`/models.@@ -129,9 +129,12 @@ its 3D + schematic + PCB render, and the component list matches the board.  ## Gotchas (learned the hard way) -- **repo push ref**: the component namespace is a single shared namespace. Use the-  **bare slug** for `repo push <slug>`; `pkg publish` needs `--org <org>` if the-  slug is owned by an org (a `409 already exists … owned by <org>` tells you which).+- **repo push ref**: two owners can each have a page with the same slug. Use the+  **owner-qualified ref** for `repo push <owner>/<slug>` and for+  `--render-board <owner>/<slug>`. A bare slug resolves only while one owner has+  that slug; once a second owner has it, the push fails as ambiguous. `pkg publish`+  needs `--org <org>` if the slug is owned by an org (a `409 already exists …+  owned by <org>` tells you which). - **Dependency graph vs file**: the Manager reads the `package.json` FILE (so   `repo push` is enough for it), but the wiki's dependency-graph UI comes from   `pkg publish` — re-publish (bump the version) to update the graph.
src/main.rs+205−52
@@ -21,8 +21,9 @@ use tiny_http::{Header, Method, Response, Server};  fn main() {     // `serve`: the dock-facing launcher — idempotent, version-aware, self-backgrounding-    // (see serve_cmd). `--render-board <slug>`: regenerate + upload the page's render/-    // assets, then exit (used by the publish flow). Otherwise serve in the foreground+    // (see serve_cmd). `--render-board <owner>/<slug>`: regenerate + upload that page's+    // render/ assets, then exit (used by the publish flow). A bare slug also works+    // while only one owner has a page with that slug. Otherwise serve in the foreground     // on `--port <n>` (default 8785).     let mut port: Option<u16> = None;     let mut serve = false;@@ -466,6 +467,8 @@ fn finish_serve(port: u16, version: &str, started: bool) { /// Render a board's GLB + PCB SVG + schematic SVGs live and publish them to the /// page's `render/` folder (with a manifest), so the Manager can serve them /// instantly. Run on every board publish/update to keep the assets fresh.+/// `slug` is the page reference as given (`<owner>/<slug>`, bare slug or `pg_` id);+/// the reads and the upload both use it unchanged. fn render_and_upload(slug: &str) -> bool {     eprintln!("rendering {slug} …");     let (sheets, pcb_svg, glb) = render_board_media(slug);@@ -541,16 +544,13 @@ fn render_and_upload(slug: &str) -> bool {      // Push TARGETED paths (not the whole render/ dir) so previously-archived     // render/<version>/ folders on the page are not clobbered.-    let bare = slug.rsplit('/').next().unwrap_or(slug);     let mut files: Vec<String> = vec!["render/manifest.json".into()];     if glb.is_some() { files.push("render/board.glb".into()); }     if pcb_svg.is_some() { files.push("render/pcb.svg".into()); }     for i in 0..sheets.len() { files.push(format!("render/sheet-{i:03}.svg")); }     if changed { files.push(format!("render/{version}")); }-    let mut args: Vec<String> = vec!["repo".into(), "push".into(), bare.into(), "--files".into()];-    args.extend(files);-    args.push("-m".into());-    args.push(format!("render assets{}", if changed { format!(" + archive v{version}") } else { String::new() }));+    let message = format!("render assets{}", if changed { format!(" + archive v{version}") } else { String::new() });+    let args = render_push_args(slug, files, message);     let ok = Command::new("adom-wiki").args(&args).current_dir(&work)         .status().map(|s| s.success()).unwrap_or(false);     let msg = if !ok { "upload FAILED".to_string() }@@ -560,6 +560,20 @@ fn render_and_upload(slug: &str) -> bool {     ok } +/// The `adom-wiki repo push` argv that uploads a board's render assets.+///+/// `page` is the page reference exactly as the caller gave it: `<owner>/<slug>`,+/// a bare slug, or a `pg_` id. It is passed through unchanged, so an+/// owner-qualified reference always pushes to that owner's page, and a bare slug+/// keeps the CLI's own bare-slug resolution.+fn render_push_args(page: &str, files: Vec<String>, message: String) -> Vec<String> {+    let mut args: Vec<String> = vec!["repo".into(), "push".into(), page.into(), "--files".into()];+    args.extend(files);+    args.push("-m".into());+    args.push(message);+    args+}+ const WIKI: &str = "https://wiki.adom.inc"; // Hosted headless KiCad 10 (service-kicad), renders board SVG/GLB server-side, // so board views need no local kicad-cli and no desktop bridge.@@ -878,13 +892,14 @@ fn route(method: &Method, url: &str, body: &str) -> Response<Cursor<Vec<u8>>> {             }         }         (Method::Get, p) if p.starts_with("/board-svg/") => {-            // forms: /board-svg/<slug>/pcb  or  /board-svg/<slug>/sch/<idx>  [?v=<version>]+            // forms: /board-svg/<page>/pcb  or  /board-svg/<page>/sch/<idx>  [?v=<version>]+            // (<page> = <owner>/<slug> or a bare slug)             let (path, ver) = split_ver(url);-            let segs: Vec<&str> = path["/board-svg/".len()..].splitn(3, '/').collect();-            let slug = segs.first().copied().unwrap_or("");-            let sub = |dir: &str| match segs.get(1).copied() {+            let (slug, kind, idx) = split_board_path(&path["/board-svg/".len()..]);+            let sheet_idx = idx.and_then(|i| i.parse::<usize>().ok());+            let sub = |dir: &str| match kind {                 Some("pcb") => Some(format!("{dir}pcb.svg")),-                Some("sch") => segs.get(2).and_then(|i| i.parse::<usize>().ok()).map(|i| format!("{dir}sheet-{i:03}.svg")),+                Some("sch") => sheet_idx.map(|i| format!("{dir}sheet-{i:03}.svg")),                 _ => None,             };             // a selected PAST version → serve from its render/<version>/ archive;@@ -892,9 +907,9 @@ fn route(method: &Method, url: &str, body: &str) -> Response<Cursor<Vec<u8>>> {             let svg = ver.as_ref()                 .and_then(|v| sub(&format!("render/{v}/")))                 .and_then(|f| wiki_bytes(slug, &f)).and_then(|b| String::from_utf8(b).ok())-                .or_else(|| cached_board(slug).and_then(|(sheets, pcb, _)| match segs.get(1).copied() {+                .or_else(|| cached_board(slug).and_then(|(sheets, pcb, _)| match kind {                     Some("pcb") => pcb,-                    Some("sch") => segs.get(2).and_then(|i| i.parse::<usize>().ok()).and_then(|i| sheets.get(i).map(|(_, s)| s.clone())),+                    Some("sch") => sheet_idx.and_then(|i| sheets.get(i).map(|(_, s)| s.clone())),                     _ => None,                 }))                 .or_else(|| sub("render/").and_then(|f| wiki_bytes(slug, &f)).and_then(|b| String::from_utf8(b).ok()));@@ -911,11 +926,11 @@ fn route(method: &Method, url: &str, body: &str) -> Response<Cursor<Vec<u8>>> {         }         (Method::Get, p) if p.starts_with("/board-view/") => {             // Interactive PCB / schematic view via adom-2dboard / adom-schematic.-            // forms: /board-view/<slug>/pcb  or  /board-view/<slug>/sch  [?v=<version>]+            // forms: /board-view/<page>/pcb  or  /board-view/<page>/sch  [?v=<version>]+            // (<page> = <owner>/<slug> or a bare slug)             let (path, ver) = split_ver(url);-            let segs: Vec<&str> = path["/board-view/".len()..].splitn(2, '/').collect();-            let slug = segs.first().copied().unwrap_or("");-            let kind = match segs.get(1).copied() { Some("pcb") => "pcb", Some("sch") => "sch", _ => "" };+            let (slug, kind, _) = split_board_path(&path["/board-view/".len()..]);+            let kind = kind.unwrap_or("");             // ?sheet=<file>: render a specific hierarchical child sheet instead of the root             let sheet = url.split_once('?').and_then(|(_, q)| q.split('&')                 .find_map(|kv| kv.strip_prefix("sheet="))).map(|s| pct(s))@@ -1084,7 +1099,7 @@ fn page_model_glb(slug: &str) -> Option<Vec<u8>> {         }     }     // 3) The <slug>.glb convention (last resort).-    wiki_bytes(slug, &format!("{slug}.glb"))+    wiki_bytes(slug, &format!("{}.glb", page_slug(slug))) }  // Read the up-axis a molecule GLB declares in its glTF header. step2glb --molecule@@ -1117,9 +1132,38 @@ fn split_ver(p: &str) -> (&str, Option<String>) {     } } -/// Uppercase-MPN filename stem for a slug (files are named `<MPN>.ext`).+/// The slug part of a page reference: `<owner>/<slug>` gives `<slug>`, and a bare+/// slug is returned as is. Use it wherever a name is built from the slug (files,+/// folders, MPNs, links that add the owner themselves); wiki reads and writes take+/// the whole reference.+fn page_slug(page: &str) -> &str {+    page.rsplit('/').next().unwrap_or(page)+}++/// Split a board asset path `<page>/pcb`, `<page>/sch` or `<page>/sch/<n>` into+/// (page, kind, sheet number). `<page>` may itself contain `/` (`<owner>/<slug>`), so+/// the kind is read from the right. A path with no recognised kind gives+/// `(path, None, None)`.+fn split_board_path(path: &str) -> (&str, Option<&'static str>, Option<&str>) {+    if let Some(page) = path.strip_suffix("/pcb") {+        return (page, Some("pcb"), None);+    }+    if let Some(page) = path.strip_suffix("/sch") {+        return (page, Some("sch"), None);+    }+    if let Some((head, n)) = path.rsplit_once('/') {+        if let Some(page) = head.strip_suffix("/sch") {+            if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) {+                return (page, Some("sch"), Some(n));+            }+        }+    }+    (path, None, None)+}++/// Uppercase-MPN filename stem for a page reference (files are named `<MPN>.ext`). fn up(slug: &str) -> String {-    slug.to_uppercase()+    page_slug(slug).to_uppercase() }  /// List component pages from the wiki API (fast + reliable; `adompkg` is dead).@@ -1155,6 +1199,12 @@ fn list_components() -> Value {                 Some(s) => serde_json::from_str::<Value>(s).unwrap_or_else(|_| json!([])),                 None => t.clone(),             }).unwrap_or_else(|| json!([]));+            // the page's own reference: `owner` is the URL owner (org for org pages);+            // `author_name` below is a display name and can't address the page.+            let page_ref = match pg.get("owner").and_then(|s| s.as_str()).filter(|s| !s.is_empty()) {+                Some(o) => format!("{o}/{slug}"),+                None => slug.clone(),+            };             let owner = pg.get("author_name").and_then(|s| s.as_str()).unwrap_or("").to_string();             let org = pg.get("org_name").and_then(|s| s.as_str()).unwrap_or("").to_string();             let is_starred = pg.get("starred").and_then(|s| s.as_bool()).unwrap_or(false);@@ -1167,7 +1217,7 @@ fn list_components() -> Value {                 .or_else(|| pg.get("updated_at").and_then(|s| s.as_str()))                 .or_else(|| pg.get("created_at").and_then(|s| s.as_str()))                 .unwrap_or("").to_string();-            items.push(json!({"slug": slug, "title": title, "brief": brief, "tags": tags, "owner": owner, "org": org, "starred": is_starred, "visibility": visibility, "version": version, "score": score, "updated": updated}));+            items.push(json!({"slug": slug, "ref": page_ref, "title": title, "brief": brief, "tags": tags, "owner": owner, "org": org, "starred": is_starred, "visibility": visibility, "version": version, "score": score, "updated": updated}));         }         offset += n;         let total = v.get("total").and_then(|t| t.as_u64()).unwrap_or(0) as usize;@@ -1226,7 +1276,7 @@ fn part_embed(slug: &str, kind: &str) -> Option<String> {     }     let mpn = up(slug);     let (part, _) = load_part(slug, &mpn).ok()?;-    let dir = std::env::temp_dir().join(format!("pm-embed-{slug}"));+    let dir = std::env::temp_dir().join(format!("pm-embed-{}", slug.replace(['/', ' '], "_")));     std::fs::create_dir_all(&dir).ok()?;     let (text, ext, tool) = match kind {         "symbol" => (export_kicad_symbol(&part.symbol), "kicad_sym", "adom-symbol"),@@ -1296,35 +1346,47 @@ fn get_part(slug: &str) -> Value { /// A board/molecule's component dependencies, the other wiki components it's /// built from. Read from the board's **`package.json` `dependencies`** (the same /// npm-style manifest the wiki dependency graph is built from, so the two agree).-/// Values may be `{slug: ver}`, `[slug,…]`, or `[{slug|ref|name}, …]`; owner-/// prefixes (`adom/foo`) are stripped to the slug.-/// A page's package.json dependencies as bare slugs (owner prefix stripped).+/// Each dependency is a page reference as the manifest writes it: `<owner>/<slug>`+/// keeps its owner, so the page read is that owner's page; a bare slug stays bare. fn deps_of(slug: &str) -> Vec<String> {-    let bare = |k: &str| k.rsplit('/').next().unwrap_or(k).trim().to_string();-    if let Some(txt) = wiki_text(slug, "package.json") {-        if let Ok(v) = serde_json::from_str::<Value>(&txt) {-            return match v.get("dependencies") {-                Some(Value::Object(m)) => m.keys().map(|k| bare(k)).collect(),-                Some(Value::Array(a)) => a-                    .iter()-                    .filter_map(|d| {-                        d.as_str().map(|s| s.to_string()).or_else(|| {-                            d.get("slug").or_else(|| d.get("ref")).or_else(|| d.get("name")).and_then(|x| x.as_str()).map(|s| s.to_string())-                        })-                    })-                    .map(|s| bare(&s))-                    .collect(),-                _ => vec![],-            };-        }-    }-    vec![]+    wiki_text(slug, "package.json")+        .and_then(|txt| serde_json::from_str::<Value>(&txt).ok())+        .map(|v| manifest_deps(&v))+        .unwrap_or_default()+}++/// The page references in a parsed `package.json`'s `dependencies`. Values may be+/// `{ref: ver}` (returned in key order), `[ref,…]` or `[{slug|ref|name}, …]` (returned+/// in array order). Each reference is trimmed and otherwise kept exactly as written;+/// empty ones are dropped.+fn manifest_deps(manifest: &Value) -> Vec<String> {+    let refs: Vec<String> = match manifest.get("dependencies") {+        Some(Value::Object(m)) => m.keys().cloned().collect(),+        Some(Value::Array(a)) => a+            .iter()+            .filter_map(|d| {+                d.as_str().map(|s| s.to_string()).or_else(|| {+                    d.get("slug").or_else(|| d.get("ref")).or_else(|| d.get("name")).and_then(|x| x.as_str()).map(|s| s.to_string())+                })+            })+            .collect(),+        _ => vec![],+    };+    refs.iter().map(|r| r.trim().to_string()).filter(|r| !r.is_empty()).collect()+}++/// Does a component-index item (from `list_components`) name the page `page`?+/// An owner-qualified reference matches the item's `ref` (`<owner>/<slug>`); a bare+/// slug matches the item's `slug`.+fn index_item_is(item: &Value, page: &str) -> bool {+    let field = if page.contains('/') { "ref" } else { "slug" };+    item.get(field).and_then(|s| s.as_str()) == Some(page) }  /// A page's tags, read from the already-fetched component index. PEEKS the cache /// only — it never triggers `list_components()`'s ~8s wiki crawl, so a caller that /// runs before the gallery has loaded just gets an empty list and falls back to-/// whatever cheaper test it has.+/// whatever cheaper test it has. `slug` is a page reference (`<owner>/<slug>` or bare). fn tags_of_cached(slug: &str) -> Vec<String> {     let txt = match LIST_CACHE.lock().unwrap().as_ref() {         Some(s) => s.clone(),@@ -1336,7 +1398,7 @@ fn tags_of_cached(slug: &str) -> Vec<String> {     };     v.get("components")         .and_then(|c| c.as_array())-        .and_then(|arr| arr.iter().find(|it| it.get("slug").and_then(|s| s.as_str()) == Some(slug)))+        .and_then(|arr| arr.iter().find(|it| index_item_is(it, slug)))         .and_then(|it| it.get("tags"))         .and_then(|t| t.as_array())         .map(|a| a.iter().filter_map(|x| x.as_str()).map(|s| s.to_lowercase()).collect())@@ -1420,7 +1482,7 @@ fn board_deps(slug: &str) -> Value {             components.push(d);         }     }-    let items: Vec<Value> = components.into_iter().map(|s| json!({"slug": s})).collect();+    let items: Vec<Value> = components.into_iter().map(|s| dep_item(&s)).collect();     // No resolved component pages? fall back to the block-model BOM (circuit pages).     let bom = if items.is_empty() { circuit_bom(slug) } else { vec![] };     // the page's git commit history (the wiki's Activity tab)@@ -1432,11 +1494,17 @@ fn board_deps(slug: &str) -> Value {         "hints": ["board → components (its own dependencies); a legacy '-library' dep is expanded one hop"] }) } +/// One dependency as the UI receives it: `ref` is the page reference to address+/// the page by (owner kept when the manifest gave one), `slug` its slug part.+fn dep_item(page: &str) -> Value {+    json!({"slug": page_slug(page), "ref": page})+}+ /// A PROJECT's direct board dependencies, a page tagged `project` depends on /// boards (not components), so unlike `board_deps` these are NOT expanded. The /// Manager lists them, and clicking one opens it as a normal board. fn project_boards(slug: &str) -> Value {-    let boards: Vec<Value> = deps_of(slug).into_iter().map(|s| json!({"slug": s})).collect();+    let boards: Vec<Value> = deps_of(slug).into_iter().map(|s| dep_item(&s)).collect();     let log = curl(&format!("{WIKI}/api/v1/pages/{slug}/log"))         .and_then(|b| serde_json::from_slice::<Value>(&b).ok())         .and_then(|v| v.get("log").cloned())@@ -2395,7 +2463,7 @@ fn list_kicad_mods(dir: &str) -> Vec<String> { /// library, re-point every `lib_id`/footprint reference to it, and write the /// project-local sym/fp-lib-tables. Then deliver everything to `dest`. fn fetch_project_files(board: &str, dest: &str, project_only: bool) -> (String, Vec<String>) {-    let dest = if dest.trim().is_empty() { format!("{}{}{board}", kicad_dir("Projects"), sep()) } else { dest.trim().to_string() };+    let dest = if dest.trim().is_empty() { format!("{}{}{}", kicad_dir("Projects"), sep(), page_slug(board)) } else { dest.trim().to_string() };     let work = format!("{SCRATCH}/proj-{}", board.replace(['/', ' '], "_"));     let _ = std::fs::remove_dir_all(&work);     let _ = std::fs::create_dir_all(&work);@@ -2457,7 +2525,7 @@ fn fetch_project_files(board: &str, dest: &str, project_only: bool) -> (String,     if project_only {         // self-contain: run the Python helper, which rewrites files in `work`,         // creates <board>.kicad_sym / .pretty / lib-tables, and reports the split.-        let libnick = board.replace(['/', ' '], "_");+        let libnick = page_slug(board).replace(['/', ' '], "_");         let script = format!("{work}/_selfcontain.py");         let _ = std::fs::write(&script, PYTHON_SELFCONTAIN);         let out = Command::new("python3")@@ -3721,7 +3789,7 @@ fn components_in_libs(slugs: &[String]) -> Vec<(String, String, String, String)> /// project lib), KEPT (already there), and which library symbols would be REMOVED /// (in the lib, no longer on the board). `exists` = the project lib was found. fn project_diff(board: &str, dest: &str) -> Value {-    let libnick = board.replace(['/', ' '], "_");+    let libnick = page_slug(board).replace(['/', ' '], "_");     let s = sep();     let mut lib_path = format!("{}{s}{libnick}.kicad_sym", dest.trim_end_matches(['/', '\\']));     // if it's not at the given destination, search the user's Documents for it@@ -4072,3 +4140,88 @@ const LOADER_GIF: &[u8] = include_bytes!("loader.gif"); // points at is the same file the server hands the page as /favicon.svg. const NEWBIE_PANEL_JS: &str = include_str!("newbie-panel.js"); const FAVICON_SVG: &str = include_str!("../docs/img/dock-project-manager.svg");++#[cfg(test)]+mod tests {+    use super::{dep_item, index_item_is, manifest_deps, page_slug, render_push_args, split_board_path, up};+    use serde_json::json;++    fn files() -> Vec<String> {+        vec!["render/manifest.json".into(), "render/board.glb".into()]+    }++    #[test]+    fn owner_qualified_ref_pushes_to_that_owner() {+        let args = render_push_args("ownera/usb3-ethernet", files(), "render assets".into());+        assert_eq!(+            args,+            ["repo", "push", "ownera/usb3-ethernet", "--files", "render/manifest.json", "render/board.glb", "-m", "render assets"]+        );+    }++    #[test]+    fn bare_slug_stays_bare() {+        let args = render_push_args("usb3-ethernet", files(), "render assets".into());+        assert_eq!(args[2], "usb3-ethernet");+    }++    #[test]+    fn page_id_passes_through() {+        let args = render_push_args("pg_0123abcd", files(), "render assets".into());+        assert_eq!(args[2], "pg_0123abcd");+    }++    #[test]+    fn manifest_deps_keep_owners() {+        let m = json!({"dependencies": {"ownera/cl21a476": "^1.0.0", "ownerb/cl21a476": "^1.0.0", "lqm18pnr47": "^1.0.0"}});+        let mut deps = manifest_deps(&m);+        deps.sort();+        assert_eq!(deps, ["lqm18pnr47", "ownera/cl21a476", "ownerb/cl21a476"]);+    }++    #[test]+    fn manifest_deps_array_forms() {+        let m = json!({"dependencies": ["ownera/part-a", {"slug": "ownerb/part-b"}, {"ref": "part-c"}, {"name": " ownera/part-d "}, "", 7]});+        assert_eq!(manifest_deps(&m), ["ownera/part-a", "ownerb/part-b", "part-c", "ownera/part-d"]);+    }++    #[test]+    fn manifest_without_deps_is_empty() {+        assert!(manifest_deps(&json!({"version": "1.0.0"})).is_empty());+        assert!(manifest_deps(&json!({"dependencies": "nonsense"})).is_empty());+    }++    #[test]+    fn page_slug_and_mpn_use_the_slug_part() {+        assert_eq!(page_slug("ownera/cl21a476"), "cl21a476");+        assert_eq!(page_slug("cl21a476"), "cl21a476");+        assert_eq!(up("ownera/cl21a476"), "CL21A476");+        assert_eq!(up("cl21a476"), "CL21A476");+    }++    #[test]+    fn dep_item_carries_ref_and_slug() {+        assert_eq!(dep_item("ownera/part-a"), json!({"slug": "part-a", "ref": "ownera/part-a"}));+        assert_eq!(dep_item("part-a"), json!({"slug": "part-a", "ref": "part-a"}));+    }++    #[test]+    fn index_items_match_by_ref_or_slug() {+        let a = json!({"slug": "part-a", "ref": "ownera/part-a"});+        let b = json!({"slug": "part-a", "ref": "ownerb/part-a"});+        assert!(index_item_is(&a, "ownera/part-a"));+        assert!(!index_item_is(&b, "ownera/part-a"));+        assert!(index_item_is(&a, "part-a") && index_item_is(&b, "part-a"));+    }++    #[test]+    fn board_paths_take_owner_qualified_pages() {+        assert_eq!(split_board_path("ownera/board-x/pcb"), ("ownera/board-x", Some("pcb"), None));+        assert_eq!(split_board_path("ownera/board-x/sch"), ("ownera/board-x", Some("sch"), None));+        assert_eq!(split_board_path("ownera/board-x/sch/2"), ("ownera/board-x", Some("sch"), Some("2")));+        assert_eq!(split_board_path("board-x/pcb"), ("board-x", Some("pcb"), None));+        assert_eq!(split_board_path("board-x/sch/0"), ("board-x", Some("sch"), Some("0")));+        assert_eq!(split_board_path("board-x"), ("board-x", None, None));+        assert_eq!(split_board_path("board-x/sch/x"), ("board-x/sch/x", None, None));+    }+}
src/manage.html+32−18
@@ -632,6 +632,20 @@ const COLORS={Silkscreen:'#d8b4fe',Courtyard:'#4ade80','Fabrication / Assembly': // Board-centric navigation: Boards (tagged board/molecule) ▸ a board's component // dependencies ▸ the symbol/footprint/3D viewer. let all=[], bySlug={}, boardSlug=null, curDeps=[], curBom=[], me='', pubQuery='', orgs=[], boardTab='mine';+// Pages are addressed by REFERENCE: `<owner>/<slug>` when the owner is known, else a+// bare slug. bySlug holds each listed page under its bare slug and under its ref.+// pageSlug: the slug part. pageOwner: the owner part ('' for a bare slug).+// pagePath: the reference as a URL path, each part encoded.+const pageSlug=r=>String(r).split('/').pop();+const pageOwner=r=>{const s=String(r),i=s.lastIndexOf('/');return i<0?'':s.slice(0,i);};+const pagePath=r=>String(r).split('/').map(encodeURIComponent).join('/');+// The page's wiki URL: an owner-qualified reference names its page directly; a bare+// slug falls back to the listed org/author.+function wikiPageUrl(ref,c){+  if(pageOwner(ref)) return 'https://wiki.adom.inc/'+pagePath(ref);+  const o=(c&&(c.org||c.owner))||'';+  return o?`https://wiki.adom.inc/${o}/${encodeURIComponent(ref)}`:'';+} // canonical header subject zone: the currently-open board + its meta function setSubject(name, slug){   const n=document.getElementById('hdr-name'), m=document.getElementById('hdr-meta');@@ -742,7 +756,7 @@ function nbInit(){    // Set LAST, and record what failed, so a diagnosis never has to be inferred   // from which regions happen to be painted.-  window.__pmBoot={complete:true,failed:fails,version:'0.14.0',+  window.__pmBoot={complete:true,failed:fails,version:'0.14.1',                    panelMounted:!!window.__pmPanelMounted,ledTimer:!!window.__pmLedTimer};   if(fails.length) toast('Part of this dashboard failed to start: '+fails.join('; '),'error'); }@@ -963,7 +977,7 @@ async function loadList(fresh){   if(!fresh){ startLoader(); rowsEl().innerHTML='<div class="row" style="color:#8b93a3;cursor:default">loading boards from wiki…</div>'; }   try{     const r=await fetch('api/components'+(fresh?'?refresh=1':'')).then(r=>r.json());-    all=r.components||[]; me=r.me||''; orgs=r.orgs||[]; bySlug={}; all.forEach(c=>bySlug[c.slug]=c);+    all=r.components||[]; me=r.me||''; orgs=r.orgs||[]; bySlug={}; all.forEach(c=>{bySlug[c.slug]=c; if(c.ref)bySlug[c.ref]=c;});     fetch('api/env').then(r=>r.json()).then(e=>{ if(e&&e.os) env=e; }).catch(()=>{});     loadLibraries();     render();@@ -1043,7 +1057,7 @@ function galleryCard(c){   const hero=card.querySelector('.g-hero');   hero.onerror=()=>{ hero.style.display='none'; };   // 404/no hero → kind-colored monogram shows through   hero.src='board-hero/'+c.slug;-  card.onclick=()=>isProject(c)?openProject(c.slug):openBoard(c.slug);+  card.onclick=()=>isProject(c)?openProject(c.ref||c.slug):openBoard(c.ref||c.slug);   // clicking the author name pivots the wall to that person's boards (not the card open)   if(c.owner){ const ow=card.querySelector('.g-owner'); ow.onclick=(e)=>{ e.stopPropagation(); viewUser(c.owner); }; }   return card;@@ -1260,7 +1274,7 @@ function edaTags(list){return (list||[]).map(e=>`<span class="tag eda ${e}">${ED function loadEda(slug){   const fill=list=>document.querySelectorAll('.eda[data-eda="'+CSS.escape(slug)+'"]').forEach(el=>{el.outerHTML=edaTags(list);});   if(edaCache[slug]!==undefined){fill(edaCache[slug]);return;}-  fetch('api/board-eda/'+encodeURIComponent(slug)).then(r=>r.json()).then(d=>{edaCache[slug]=d.eda||[];fill(edaCache[slug]);}).catch(()=>{});+  fetch('api/board-eda/'+pagePath(slug)).then(r=>r.json()).then(d=>{edaCache[slug]=d.eda||[];fill(edaCache[slug]);}).catch(()=>{}); } // In-app folder browser: navigates the user's filesystem via the bridge and calls // onPick(absolutePath) with the real path when the user selects a folder.@@ -1319,7 +1333,7 @@ function boardRow(c){   const visClass=vis==='private'?'private':(vis==='public'||vis==='open')?'public':'';   const visTag=vis?`<span class="tag vis ${visClass}">${vis==='open'?'public':vis}</span>`:'';   d.innerHTML=`<div class="mpn">${star}${c.title||c.slug}</div><div class="sub">${c.slug}${c.owner?`<span class="auth">${c.owner}</span>`:''}</div><div class="row-tags"><span class="tag kind ${kind}">${kind}</span>${edaSpan}${visTag}</div>`;-  d.onclick=()=>isProject(c)?openProject(c.slug):openBoard(c.slug);+  d.onclick=()=>isProject(c)?openProject(c.ref||c.slug):openBoard(c.ref||c.slug);   // If this board/molecule/project has its own (non-standalone) library, add a   // "Library" expander that reveals it inline instead of listing it separately.   const libs=librariesFor(c.slug);@@ -1347,7 +1361,7 @@ function toggleLibChild(row,btn,libs){     // embedded library row mirrors a normal board row: purple "library" kind tag FIRST,     // then its eda/visibility tags, all on one line.     lr.innerHTML=`<div class="mpn">${l.title||l.slug}</div><div class="sub">${l.slug}${l.owner?`<span class="auth">${l.owner}</span>`:''}</div><div class="row-tags"><span class="tag kind library">library</span>${other}</div>`;-    lr.onclick=(ev)=>{ ev.stopPropagation(); openBoard(l.slug); };+    lr.onclick=(ev)=>{ ev.stopPropagation(); openBoard(l.ref||l.slug); };     wrap.appendChild(lr);   });   row.after(wrap); btn.classList.add('open');@@ -1431,7 +1445,7 @@ async function openBoard(slug){   rowsEl().innerHTML='<div class="row" style="color:#8b93a3;cursor:default">loading dependencies…</div>';   try{ const r=await fetch('api/board/'+slug).then(r=>r.json());     if(boardSlug!==slug)return; // navigated back/away while loading, don't paint stale parts-    curDeps=(r.deps||[]).map(d=>d.slug); curBom=(r.bom||[]); fillBoardInfo(slug,r.log); }+    curDeps=(r.deps||[]).map(d=>d.ref||d.slug); curBom=(r.bom||[]); fillBoardInfo(slug,r.log); }   catch(e){ if(boardSlug!==slug)return; curDeps=[]; curBom=[]; }   if(boardSlug!==slug)return;   renderDeps();@@ -1442,8 +1456,7 @@ function renderBoardOverview(slug){   const c=bySlug[slug]||{slug};   const _vis=(c.visibility||'').toLowerCase();   const _visTag=_vis?`<span class="tag vis ${_vis==='private'?'private':(_vis==='public'||_vis==='open')?'public':''}">${_vis==='open'?'public':_vis}</span>`:'';-  const _wowner=c.org||c.owner||'';-  const _wikiUrl=_wowner?`https://wiki.adom.inc/${_wowner}/${encodeURIComponent(slug)}`:'';+  const _wikiUrl=wikiPageUrl(slug,c);   const _wikiBtn=_wikiUrl?`<a class="wikibtn" href="${_wikiUrl}" target="_blank" rel="noopener" title="open this page on the Adom wiki">Open on wiki ↗</a>`:'';   const view=document.getElementById('view');   view.classList.remove('split');@@ -1586,10 +1599,11 @@ function wikiViewer3d(slug){   // the viewer then can't derive the model and the pane errors out. Always pass the page's   // own owner (org for org pages, else the author), and NEVER an ownerless lookup. Pass the   // slug verbatim — never append "-board" (many board slugs already end in it).+  // An owner-qualified reference carries its own owner, which wins over the listing's.   const c=bySlug[slug]||{};-  const owner=c.org||c.owner;+  const owner=pageOwner(slug)||c.org||c.owner;   if(!owner){ return '<div class="bo-na">3D not available</div>'; }  // no owner ⇒ don't send a lookup that can't resolve-  const src=`https://wiki.adom.inc/viewer/3d/${encodeURIComponent(owner)}/component/${encodeURIComponent(slug)}`;+  const src=`https://wiki.adom.inc/viewer/3d/${encodeURIComponent(owner)}/component/${encodeURIComponent(pageSlug(slug))}`;   return `<iframe class="bo-embed" style="background:#0d0f14;border:0" src="${src}" allow="fullscreen" onload="this.nextElementSibling&&this.nextElementSibling.remove()"></iframe><div class="vload ov"><img src="loader.gif" alt=""></div>`; } function selectVersion(v){@@ -1755,7 +1769,7 @@ function renderDeps(){   const cats=Object.keys(groups).sort((a,b)=>{const ia=TYPE_ORDER.indexOf(a),ib=TYPE_ORDER.indexOf(b);return (ia<0?99:ia)-(ib<0?99:ib)||a.localeCompare(b);});   cats.forEach(cat=>{     const h=document.createElement('div');h.className='cathead';h.textContent=`${cat} · ${groups[cat].length}`;el.appendChild(h);-    groups[cat].forEach(x=>{const on=bySlug[x.slug];el.appendChild(makeRow(x.slug,x.c.title||x.slug,on?x.slug:x.slug+' · not on wiki',openPart,null,true));});+    groups[cat].forEach(x=>{const on=bySlug[x.slug];el.appendChild(makeRow(x.slug,x.c.title||pageSlug(x.slug),on?x.slug:x.slug+' · not on wiki',openPart,null,true));});   });   updateToolbar(); }@@ -1785,7 +1799,7 @@ async function openProject(slug){   rowsEl().innerHTML='<div class="row" style="color:#8b93a3;cursor:default">loading boards…</div>';   try{ const r=await fetch('api/project/'+slug).then(r=>r.json());     if(projectSlug!==slug)return;-    projectBoards=(r.boards||[]).map(d=>d.slug);+    projectBoards=(r.boards||[]).map(d=>d.ref||d.slug);     fillProjectInfo(slug,r.log);   }catch(e){ if(projectSlug!==slug)return; projectBoards=[]; }   if(projectSlug!==slug)return;@@ -1839,7 +1853,7 @@ function renderBom(el,q){     const refs=(p.refs&&p.refs.length)?` <span class="bom-refs">${p.refs.join(', ')}</span>`:'';     const meta=[p.lcsc?`LCSC ${p.lcsc}`:'',p.footprint||''].filter(Boolean).join(' · ');     d.innerHTML=`<div class="mpn">${qty}${title}${refs}</div><div class="sub">${meta}${p.page?'':' · not on wiki'}</div>`;-    if(p.page){ d.onclick=()=>openBoard(p.page.split('/').pop()); } else { d.style.cursor='default'; }+    if(p.page){ d.onclick=()=>openBoard(p.page); } else { d.style.cursor='default'; }     el.appendChild(d);   }); }@@ -1884,8 +1898,8 @@ async function openPart(slug,el){       <td><span class="swatch" style="background:${COLORS[l.role]||'#888'}"></span>${l.role}<span style="color:#8b93a3"> ×${l.count}</span></td>       <td><span class="badge">${l.kicad}</span></td>       <td><span class="badge">${l.altium}</span></td></tr>`).join('');-  const wc=bySlug[slug]||{}; const wowner=wc.org||wc.owner||'';-  const wikiUrl=wowner?`https://wiki.adom.inc/${wowner}/${encodeURIComponent(slug)}`:'';+  const wc=bySlug[slug]||{};+  const wikiUrl=wikiPageUrl(slug,wc);   v.innerHTML=`     <h2 class="title">${p.mpn} <small>· ${p.pins} pins · ${p.pads} pads</small>${wikiUrl?`<a class="wikibtn" href="${wikiUrl}" target="_blank" rel="noopener">Open on wiki ↗</a>`:''}</h2>     <div class="cols">@@ -2177,11 +2191,11 @@ function openAddProj(){   // deliver-to: a "Browse files" button pops a native folder dialog on the user's   // machine (via the bridge); once picked it shows the path. Then / + project name.   document.getElementById('modal-dest').innerHTML=`<label>Deliver project to</label><div class="destrow"><button type="button" id="destbrowse" class="browsebtn" title="choose a folder on your computer">Browse files</button><span class="destsep">${env.sep}</span><input id="destname" spellcheck="false" autocomplete="off" placeholder="project folder name"></div>`;-  const destname=document.getElementById('destname'); destname.value=boardSlug;+  const destname=document.getElementById('destname'); destname.value=pageSlug(boardSlug);   let chosenDir=''; const browse=document.getElementById('destbrowse');   const destPath=()=>chosenDir?chosenDir.replace(/[\/\\]+$/,'')+env.sep+destname.value.trim():'';   // project directory to diff against: the browsed folder, else the default Projects dir, + the name-  const projPath=()=>((chosenDir||destFolders()[0]||'').replace(/[\/\\]+$/,''))+env.sep+(destname.value.trim()||boardSlug);+  const projPath=()=>((chosenDir||destFolders()[0]||'').replace(/[\/\\]+$/,''))+env.sep+(destname.value.trim()||pageSlug(boardSlug));   const draw=()=>{     const editable=mode==='personal';     curPlan=buildPlan(slugs,mode==='project',projName);
src/viewer3d.html+2−1
@@ -62,7 +62,8 @@         }       }catch(e){}       // Model comes from Project Manager's own authenticated route (same-origin).-      var glbUrl='board-glb/'+encodeURIComponent(slug)+(v?('?v='+encodeURIComponent(v)):'');+      // `slug` is a page reference (<owner>/<slug> or bare): encode each part, keep the '/'.+      var glbUrl='board-glb/'+slug.split('/').map(encodeURIComponent).join('/')+(v?('?v='+encodeURIComponent(v)):'');       try{         // zUp:true for our pipeline GLBs (step2glb --molecule stamps Z-up); ?up=y flips it         // for a raw Y-up export. Matches the wiki viewer's zUp:true default.

Comments

No comments yet.

Log in to comment.