diff --git a/i18n/en.msg b/i18n/en.msg index 77d061d621..dfd59d4421 100644 --- a/i18n/en.msg +++ b/i18n/en.msg @@ -2238,6 +2238,9 @@ gpui.c.kicad.exit.full.screen = Exit full screen gpui.c.kicad.the.editor.takes.the.whole = The editor takes the whole window; only this row stays gpui.c.kicad.closing = KiCad is closing. The editor opens again once it has closed. gpui.c.kicad.closing.ask = KiCad is waiting for an answer before it closes: "{title}". Its window may be behind another one. +gpui.c.solid.load.big = Load it anyway +gpui.c.solid.loading.big = Loading it anyway… +gpui.c.solid.big.next = Loading it may take a while and a lot of memory. # ---- gpui-d: setup, pairing, hubs, palette, picker, projects, composer, menus ---- gpui.assets.missing = Assets missing in {dir}: {files} diff --git a/i18n/es.msg b/i18n/es.msg index a0e2962ef9..bd6709d8a1 100644 --- a/i18n/es.msg +++ b/i18n/es.msg @@ -2239,6 +2239,9 @@ gpui.c.kicad.exit.full.screen = Salir de pantalla completa gpui.c.kicad.the.editor.takes.the.whole = El editor ocupa toda la ventana; solo queda esta fila gpui.c.kicad.closing = KiCad se está cerrando. El editor vuelve a abrirse cuando termine de cerrarse. gpui.c.kicad.closing.ask = KiCad espera una respuesta antes de cerrarse: «{title}». Su ventana puede estar detrás de otra. +gpui.c.solid.load.big = Cargarlo de todos modos +gpui.c.solid.loading.big = Cargándolo de todos modos… +gpui.c.solid.big.next = Cargarlo puede tardar y usar mucha memoria. # ---- gpui-d: setup, pairing, hubs, palette, picker, projects, composer, menus ---- gpui.assets.missing = Faltan recursos en {dir}: {files} diff --git a/i18n/ja.msg b/i18n/ja.msg index e2c59c7903..173df45ff1 100644 --- a/i18n/ja.msg +++ b/i18n/ja.msg @@ -2261,6 +2261,9 @@ gpui.c.kicad.exit.full.screen = 全画面を終了 gpui.c.kicad.the.editor.takes.the.whole = エディタがウィンドウ全体を使います。この行だけが残ります gpui.c.kicad.closing = KiCad を閉じています。閉じ終わるとエディタがもう一度開きます。 gpui.c.kicad.closing.ask = KiCad は閉じる前に応答を待っています:「{title}」。そのウィンドウが別のウィンドウの後ろにあるかもしれません。 +gpui.c.solid.load.big = それでも読み込む +gpui.c.solid.loading.big = それでも読み込み中… +gpui.c.solid.big.next = 読み込みには時間と多くのメモリがかかることがあります。 # ---- gpui-d: setup, pairing, hubs, palette, picker, projects, composer, menus ---- gpui.assets.missing = {dir} にアセットがありません: {files} diff --git a/native/gpui/src/screens/glue.rs b/native/gpui/src/screens/glue.rs index 296d336551..ce0cccc5d7 100644 --- a/native/gpui/src/screens/glue.rs +++ b/native/gpui/src/screens/glue.rs @@ -343,6 +343,8 @@ impl Backplane { } } // zoomed in on a STEP: its solids there meshed finer by the hub, the model replaced when they are + // "Load it anyway": a model the hub refused for its size, read past the limit + crate::viewers::solid::SolidEvent::LoadBig(key) => { let _ = this.tx.try_send(Command::Rpc("kicad.big".into(), super::settings::Secret(serde_json::json!({"key": key})), "big")); } crate::viewers::solid::SolidEvent::Refine(key, at, r) => { let _ = this.tx.try_send(Command::Rpc("kicad.refine".into(), super::settings::Secret(serde_json::json!({"key": key, "at": at, "r": r})), "refine")); } // a part clicked on the board's model: the board's probe, lit on the schematic and the board as a tap there is crate::viewers::solid::SolidEvent::Pick(r) => super::plotview::probe_part(this, r), diff --git a/native/gpui/src/viewers/solid.rs b/native/gpui/src/viewers/solid.rs index 86163eac56..474f34d76f 100644 --- a/native/gpui/src/viewers/solid.rs +++ b/native/gpui/src/viewers/solid.rs @@ -251,8 +251,9 @@ pub fn read_frame(b: &[u8]) -> Option> { Some(out) } #[derive(Debug, PartialEq)] -pub enum SolidFrame { Model(String, Mesh), /// why there is no model (the hub's `none`) and its `retryable` flag, the previous model stays - Note(String, String, Option), Bad(String), +pub enum SolidFrame { Model(String, Mesh), /// why there is no model (the hub's `none`), its `retryable` flag and its `big` one (refused for its + /// size, so the page offers "Load it anyway"); the previous model stays + Note(String, String, Option, bool), Bad(String), /// the parts of the model start again: `of` instances will come Parts(String, u32), /// one part model at its instances (placed), and how many instances have now come @@ -284,7 +285,7 @@ pub fn parse_frame(b: &[u8]) -> Option { if !is_solid_key(&key) { return None } if let Some(Item::Text(why)) = get("none") { let retryable = match get("retryable") { Some(Item::Bool(b)) => Some(*b), _ => None }; - return Some(SolidFrame::Note(key, why.clone(), retryable)) + return Some(SolidFrame::Note(key, why.clone(), retryable, matches!(get("big"), Some(Item::Bool(true))))) } if let Some(Item::Text(text)) = get("stage") { let ms = |k: &str| match get(k) { Some(Item::Int(v)) if *v > 0 => *v as u64, _ => 0 }; @@ -486,7 +487,7 @@ impl Scene { self.key = key; self.parts.clear(); self.done = 0; self.of = of; *reset = true; Ok(true) } SolidFrame::Part(key, m, done) => { if key != self.key { return Ok(false) } self.parts.push(Arc::new(m)); self.done = done.min(self.of.max(done)); Ok(true) } - SolidFrame::Note(key, why, retryable) => { if key != self.key { *self = Scene { key: key.clone(), ..Default::default() } } Err(SolidFrame::Note(key, why, retryable)) } + SolidFrame::Note(key, why, retryable, big) => { if key != self.key { *self = Scene { key: key.clone(), ..Default::default() } } Err(SolidFrame::Note(key, why, retryable, big)) } other => Err(other), } } @@ -603,7 +604,8 @@ pub fn stage_line(text: &str, secs: u64, about_ms: u64) -> String { } /// What the page asks of the window: the model of this source made again (its Retry, after the hub could not make it). /// `Refine`: the person zoomed in on a STEP: its solids near `at` (the model's millimetres) within `r`, meshed finer (kicad.refine). -pub enum SolidEvent { Retry(String), Refine(String, [f32; 3], f32), /** a click on a board's model: the reference of the part under it, "" the board or nothing */ Pick(String) } +/// `LoadBig`: the person asked for a model the hub refused for its size, read past the limit (kicad.big). +pub enum SolidEvent { Retry(String), Refine(String, [f32; 3], f32), LoadBig(String), /** a click on a board's model: the reference of the part under it, "" the board or nothing */ Pick(String) } impl EventEmitter for SolidPage {} /// Whether a source's model can be refined: a STEP's (the Mech tab's parts; a board's model is made at its finest already). pub fn refinable(key: &str) -> bool { @@ -871,7 +873,7 @@ pub struct SolidPage { /** the page's keys (0.14's: f/Home fit, 0-6 views, arrows turn, shift+arrows move, +/- zoom), taken when the model is pressed; the wheel's burst, to settle after it */ focus: FocusHandle, wheel: u64, /** what the hub said it is doing for a model (Stage), shown with its time running; whether a second's tick is running for it */ stage: Option, ticking: bool, /** the share of DRAFT_PIXELS a picture in motion gets, from how long the last ones took (draft_scale) */ draft_scale: f32, - /** the hub could not make this source's model (its Note): the page offers Retry when retryable */ failed: bool, retryable: Option, /** last Retry press time (1 s client cooldown) */ last_retry: Option, + /** the hub could not make this source's model (its Note): the page offers Retry when retryable */ failed: bool, retryable: Option, /** refused for its size: the page offers "Load it anyway" */ big: bool, /** last Retry press time (1 s client cooldown) */ last_retry: Option, pub note: String, /** the canvas supplies its own controls in Split */ pub inline_controls: bool, worker: Worker, size: Arc> /* panel width, height, scale factor, origin x, y (logical px) */, /** runs in normal clients too (one relaxed atomic per qualifying paint); measures the GPUI paint callback with non-zero bounds, not GPU presentation */ painted: Arc, painted_gen: Arc, pub stats: Stats, @@ -884,7 +886,7 @@ impl SolidPage { if weak.update(cx, |this, cx| this.apply(msg, cx)).is_err() { break } } }).detach(); - SolidPage { source_rev: 0, seen_source: None, source_subscription: None, press_btn: None, press: None, names_probe: true, core: SolidCore::new(), drag: None, fading: false, focus: cx.focus_handle(), wheel: 0, stage: None, ticking: false, draft_scale: 1.0, failed: false, retryable: None, last_retry: None, note: "No 3D model yet".into(), /* i18n-ok: the note is drawn through note_words */ inline_controls: true, worker: Worker::spawn(tx), + SolidPage { source_rev: 0, seen_source: None, source_subscription: None, press_btn: None, press: None, names_probe: true, core: SolidCore::new(), drag: None, fading: false, focus: cx.focus_handle(), wheel: 0, stage: None, ticking: false, draft_scale: 1.0, failed: false, retryable: None, big: false, last_retry: None, note: "No 3D model yet".into(), /* i18n-ok: the note is drawn through note_words */ inline_controls: true, worker: Worker::spawn(tx), size: Arc::new(Mutex::new([0.0, 0.0, 1.0, 0.0, 0.0])), painted: Arc::new(AtomicU64::new(0)), painted_gen: Arc::new(AtomicU64::new(0)), stats: Stats::default() } } /// The background to draw on (the setting resolved by the window): a change draws the picture again at once, the camera untouched. @@ -904,6 +906,7 @@ impl SolidPage { let changed = self.core.mirror_layers(&src.core, (w, h)); self.failed = src.failed; self.retryable = src.retryable; + self.big = src.big; self.note.clone_from(&src.note); let stage = src.stage.clone(); if self.stage != stage { self.set_stage(stage, cx); } @@ -995,20 +998,21 @@ impl SolidPage { self.stage = None; stage_cleared = true; } - if res.clear_failed { self.failed = false; self.retryable = None; } + if res.clear_failed { self.failed = false; self.retryable = None; self.big = false; } if res.clear_note { self.note.clear(); } if res.should_render { self.ask_render(self.drag.is_some()); } if res.notify || stage_cleared { cx.notify(); } } Msg::Mesh(SolidFrame::Model(..) | SolidFrame::Parts(..) | SolidFrame::Part(..)) => {} // the worker makes these a Scene - Msg::Mesh(SolidFrame::Note(key, why, retryable)) => { // why there is no model; the same source's previous model stays shown + Msg::Mesh(SolidFrame::Note(key, why, retryable, big)) => { // why there is no model; the same source's previous model stays shown self.core.apply_note(key); self.stage = None; self.failed = !why.is_empty() && !crate::screens::panestate::is_empty_none(&why); self.retryable = retryable; + self.big = self.failed && big; self.note = if self.core.mesh.is_some() { format!("{why}{PREVIOUS_SHOWN}") } else { why }; cx.notify(); } - Msg::Mesh(SolidFrame::Bad(e)) => { self.failed = true; self.retryable = Some(true); self.note = e; self.set_stage(None, cx); } + Msg::Mesh(SolidFrame::Bad(e)) => { self.failed = true; self.retryable = Some(true); self.big = false; self.note = e; self.set_stage(None, cx); } Msg::Mesh(SolidFrame::Stage(key, text, ms, about)) => { if key == self.core.key && !text.is_empty() { self.failed = false; } if text.is_empty() && self.stage.as_ref().is_some_and(|s| s.key != key) { return } // another source's end: not this one's stage @@ -1116,6 +1120,25 @@ impl SolidPage { let k = this.core.key.clone(); cx.emit(SolidEvent::Retry(k)); })) } + /// "Load it anyway", for a model the hub refused for its size: it is read past the limit (kicad.big); the page says so until the hub's + /// own stage comes (bounded at 15 s, as a Retry). + fn load_big_button(&self, cx: &mut Context) -> impl IntoElement { + div().id("solid-load-big").px_2().py_1().text_size(crate::scale::tpx(12.)).border_1().border_color(rgb(0x3a4456)).child(trs("Load it anyway")) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .text_color(rgb(0xc8ced9)).bg(rgba(0x1d2430dd)).cursor_pointer().hover(|d| d.bg(rgba(0x2a3548ee))) + .on_click(cx.listener(|this, _, _, cx| { + if this.core.key.is_empty() { return } + let k = this.core.key.clone(); this.big = false; + /* i18n-ok: stage_line draws through trs */ this.set_stage(Some(Stage { key: k.clone(), text: "Loading it anyway…".into(), since: std::time::Instant::now(), about: 0, retrying: true }), cx); + cx.emit(SolidEvent::LoadBig(k)); cx.notify(); + })) + } + /// What the page offers under a failed model's note: "Load it anyway" for one refused for its size, else Retry when retryable. + fn failed_action(&self, st_retry: bool, cx: &mut Context) -> Option { + if self.core.key.is_empty() || !self.failed { return None } + if self.big { return Some(self.load_big_button(cx).into_any_element()) } + st_retry.then(|| self.retry_button(cx).into_any_element()) + } /// Snap view: the picture on screen as a PNG in `dir` (never over a file); the path, or why not. pub fn snap(&mut self, dir: &std::path::Path) -> Result { /* i18n-ok: a reason inside the translated "Snap view failed" */ let img = self.core.image.clone().ok_or("no picture yet")?; @@ -1236,9 +1259,10 @@ impl Render for SolidPage { _ if making_other || (self.core.image.is_none() && !stage.is_empty()) => div().id("solid-stage").size_full().child(crate::screens::panestate::view_on_backdrop(self.core.back, &crate::screens::panestate::PaneState::loading(stage.clone()), None)).into_any_element(), Some(i) => img(i.clone()).size_full().object_fit(ObjectFit::Fill).into_any_element(), None => { - let st = crate::screens::panestate::classify_solid_note(&self.note, self.failed && !self.core.key.is_empty(), self.retryable); - let retry = st.retry.then(|| self.retry_button(cx).into_any_element()); - crate::screens::panestate::view_on_backdrop(self.core.back, &st, retry) + let mut st = crate::screens::panestate::classify_solid_note(&self.note, self.failed && !self.core.key.is_empty(), self.retryable); + let action = self.failed_action(st.retry, cx); + if self.big && action.is_some() { st.retry = true; st.next = trs("Loading it may take a while and a lot of memory."); } + crate::screens::panestate::view_on_backdrop(self.core.back, &st, action) } }; let tools = (self.inline_controls && self.core.mesh.is_some() && !making_other).then(|| { @@ -1247,7 +1271,7 @@ impl Render for SolidPage { div().id("solid-page").size_full().overflow_hidden().relative().track_focus(&self.focus).key_context("Viewer").child(body).child(probe).children(tools) .on_key_down(cx.listener(|this, e: &KeyDownEvent, _, cx| if this.on_key(e, cx) { cx.stop_propagation() })) .when(self.core.image.is_some() && !making_other && !self.note.is_empty(), |d| d.child(div().absolute().bottom_2().left_2().px_2().flex().items_center().gap_2().text_size(crate::scale::tpx(12.)).text_color(rgb(0x8a93a3)).child(note_words(&self.note)) - .when(self.failed && self.retryable.unwrap_or_else(|| crate::screens::panestate::is_retryable_none(&self.note)) && !self.core.key.is_empty(), |d| d.child(self.retry_button(cx))))) + .children(self.failed_action(self.retryable.unwrap_or_else(|| crate::screens::panestate::is_retryable_none(&self.note)), cx)))) .when(self.core.image.is_some() && !making_other && (!stage.is_empty() || !self.parts_progress().is_empty()), |d| d.child(div().id("solid-parts").absolute().bottom_2().right_2().px_2().text_size(crate::scale::tpx(12.)).text_color(rgb(0x8a93a3)).child(if stage.is_empty() { trs(&self.parts_progress()) } else { stage.clone() }))) .on_mouse_down(MouseButton::Left, cx.listener(|this, e: &MouseDownEvent, window, cx| this.mouse_down(e, window, cx))) .on_mouse_down(crate::mousecfg::BUTTONS[1], cx.listener(|this, e: &MouseDownEvent, window, cx| this.mouse_down(e, window, cx))) @@ -1503,9 +1527,11 @@ mod tests { let mut f = vec![0xa3]; text(&mut f, "key"); text(&mut f, "2|board"); text(&mut f, "n"); f.push(12); text(&mut f, "mesh"); f.push(0x59); f.extend((bytes.len() as u16).to_be_bytes()); f.extend(&bytes); match parse_frame(&f) { Some(SolidFrame::Model(k, m)) => { assert_eq!(k, "2|board"); assert_eq!(m.tris.len(), 12) } other => panic!("{other:?}") } let mut n = vec![0xa2]; text(&mut n, "key"); text(&mut n, "3|board"); text(&mut n, "none"); text(&mut n, "no model for this board"); - assert_eq!(parse_frame(&n), Some(SolidFrame::Note("3|board".into(), "no model for this board".into(), None))); + assert_eq!(parse_frame(&n), Some(SolidFrame::Note("3|board".into(), "no model for this board".into(), None, false))); let mut nr = vec![0xa3]; text(&mut nr, "key"); text(&mut nr, "3|board"); text(&mut nr, "none"); text(&mut nr, "boom"); text(&mut nr, "retryable"); nr.push(0xf5); - assert_eq!(parse_frame(&nr), Some(SolidFrame::Note("3|board".into(), "boom".into(), Some(true)))); + assert_eq!(parse_frame(&nr), Some(SolidFrame::Note("3|board".into(), "boom".into(), Some(true), false))); + let mut nb = vec![0xa4]; text(&mut nb, "key"); text(&mut nb, "2|board"); text(&mut nb, "none"); text(&mut nb, "too big"); text(&mut nb, "retryable"); nb.push(0xf4); text(&mut nb, "big"); nb.push(0xf5); + assert_eq!(parse_frame(&nb), Some(SolidFrame::Note("2|board".into(), "too big".into(), Some(false), true)), "a model refused for its size offers Load it anyway"); let mut other = f.clone(); other[6] = b'1'; assert!(parse_frame(&other).is_none()); assert!(parse_frame(&[0xff, 0x00]).is_none()); // a tag wraps ONE value: tag 6 over the map's text key must not eat the next item diff --git a/native/host/src/bin/bp-plot.rs b/native/host/src/bin/bp-plot.rs index c52401a107..e32fd3cd56 100644 --- a/native/host/src/bin/bp-plot.rs +++ b/native/host/src/bin/bp-plot.rs @@ -64,7 +64,9 @@ fn main() { } let kind: u32 = k.parse().unwrap_or(0); if kind >= 2 { - let g = solidread::read(kind, file, &std::env::var("BACKPLANE_KICAD_CLI").unwrap_or_default(), &tools(), a.get(2).map_or("", String::as_str)); + // BACKPLANE_PLOT_ASKED: the person asked for this model past the size limit (the hub's kicad.big) + let asked = std::env::var("BACKPLANE_PLOT_ASKED").map_or(false, |v| v == "1"); + let g = solidread::read_streaming(kind, file, &std::env::var("BACKPLANE_KICAD_CLI").unwrap_or_default(), &tools(), a.get(2).map_or("", String::as_str), None, asked, None); let Some(p) = g.plot else { eprintln!("{}", g.text); std::process::exit(g.code) }; std::io::stdout().write_all(&plotgen::lines(&p)).unwrap(); println!(); diff --git a/native/host/src/kicad/solid.rs b/native/host/src/kicad/solid.rs index 3b3079d1b9..515f9d7bc4 100644 --- a/native/host/src/kicad/solid.rs +++ b/native/host/src/kicad/solid.rs @@ -14,8 +14,20 @@ pub fn fits_for(size: u64, step: bool) -> bool { size <= if step { MOST_STEP } e /// The most triangles a STEP's model goes out with: a phone takes (64 << 20) / 84 for a model, and a frame of about 10 bytes a triangle /// stays under the hub's 8 MB outbox. A model within it is sent exactly as meshed. pub const STEP_TRIS: usize = 600_000; +/// The biggest GLB the hub reads when the person asked for a model past its limit (`kicad.big`, the page's "Load it anyway"). The GLB +/// reader's own bounds (glb::MOST_TRIS) still hold, and what goes out is thinned to `STEP_TRIS` like a STEP's. +pub const MOST_ASKED: u64 = 512 << 20; +/// Whether a model's GLB of `size` bytes is read: `fits_for`, or up to MOST_ASKED once the person asked for it. +pub fn fits_asked(size: u64, step: bool, asked: bool) -> bool { size <= if asked { MOST_ASKED } else if step { MOST_STEP } else { MOST } } +/// The words every refusal of a model for its size starts with (the hub marks such a refusal `big` for the page's "Load it anyway"). +pub const BIG_WORDS: &str = "This 3D model is too big to show here"; /// Solid.big: what a refused model says (its size in whole megabytes, rounded up) -pub fn big(size: u64) -> String { format!("This 3D model is too big to show here ({} MB; the hub reads models up to {} MB)", (size + 1048575) >> 20, MOST >> 20) } +pub fn big(size: u64) -> String { big_past(size, MOST) } +/// What a model refused for its size says, with the limit it was held to (a STEP's mesh, or one the person asked for, has a higher one). +pub fn big_for(size: u64, step: bool, asked: bool) -> String { big_past(size, if asked { MOST_ASKED } else if step { MOST_STEP } else { MOST }) } +fn big_past(size: u64, most: u64) -> String { format!("{BIG_WORDS} ({} MB; the hub reads models up to {} MB)", (size + 1048575) >> 20, most >> 20) } +/// Whether a refusal is one for the model's size. +pub fn is_big(why: &str) -> bool { why.starts_with(BIG_WORDS) } /// Mech.upright: CAD parts are Z up, the viewer's world is Y up: (x, y, z) goes to (x, z, -y) pub fn upright(ts: &mut [Tri3]) { for t in ts { for v in [&mut t.a, &mut t.b, &mut t.c] { *v = [v[0], v[2], -v[1]] } } } @@ -112,6 +124,9 @@ mod tests { assert!(thin(model.clone()).len() < 120, "the old grid (a 4000th of 2 m: 0.5 mm) kept {} of the 6 mm rim's 200", thin(model.clone()).len()); let f = fit(model.clone(), 199); assert!(f.len() <= 199 && f.len() > 150, "over it: the finest grid that fits ({})", f.len()); assert!(fits_for(MOST_STEP, true) && !fits_for(MOST + 1, false) && fits_for(MOST, false)); + assert!(fits_asked(MOST + 1, false, true) && fits_asked(MOST_ASKED, false, true) && !fits_asked(MOST_ASKED + 1, true, true) && !fits_asked(MOST + 1, false, false)); + assert_eq!(big_for(73 << 20, true, false), "This 3D model is too big to show here (73 MB; the hub reads models up to 64 MB)"); + assert!(is_big(&big_for(MOST_ASKED + 1, false, true)) && !is_big("3D export failed: x")); } #[test] fn faces_go_as_runs_and_none_when_they_are_not_one_a_triangle() { assert_eq!(face_runs(&[0, 0, 0, 1, 2, 2], 6), vec![3, 1, 2]); diff --git a/native/host/src/kicad/solidread.rs b/native/host/src/kicad/solidread.rs index daf6b66027..2344b1f348 100644 --- a/native/host/src/kicad/solidread.rs +++ b/native/host/src/kicad/solidread.rs @@ -130,7 +130,8 @@ pub fn plot_of(bytes: &[u8], step: bool) -> Result { if step { solid::metres(&mut ts); solid::upright(&mut ts) } // a part from STEP stands Z up, in metres // a STEP is sent as meshed while it fits (the grid of `thin` made small holes in big assemblies jagged), with its B-rep faces when // its mesher said them and nothing was thinned; a board as always - let ts = if step { solid::fit(ts, solid::STEP_TRIS) } else { solid::thin(ts) }; + // (a board's thinned model within STEP_TRIS too: one read past its size limit on the person's word goes out in one frame) + let ts = if step { solid::fit(ts, solid::STEP_TRIS) } else { solid::fit(solid::thin(ts), solid::STEP_TRIS) }; let runs = if step { solid::face_runs(&faces, ts.len()) } else { vec![] }; let mut so = solid::of(&ts); if let Some(s) = so.as_mut() { s.faces = runs } Ok(solid::plot(so)) @@ -144,10 +145,11 @@ pub fn warm(path: &str, tools: &[Mesher]) -> bool { export(true, false, false, path, &out, "", tools, stepglb::NORMAL, None).code == 0 } /// Pv.child.solid: what `--plot KIND FILE INFOS` does for a 3D model. The note (parts without a model) goes to `infos`, as the child left it. -pub fn read(kind: u32, path: &str, cli: &str, tools: &[Mesher], infos: &str) -> Got { read_streaming(kind, path, cli, tools, infos, None, None) } +pub fn read(kind: u32, path: &str, cli: &str, tools: &[Mesher], infos: &str) -> Got { read_streaming(kind, path, cli, tools, infos, None, false, None) } /// `read`, a STEP not meshed yet streaming its parts to `on` while it is (a cached one, a board or a GLB says nothing there). `fine`: a -/// STEP refined around that box (its solids there meshed finer: `stepglb::Detail::refined`), kept as a mesh of its own. -pub fn read_streaming(kind: u32, path: &str, cli: &str, tools: &[Mesher], infos: &str, fine: Option<[f64; 6]>, on: Option<&mut dyn FnMut(Streamed)>) -> Got { +/// STEP refined around that box (its solids there meshed finer: `stepglb::Detail::refined`), kept as a mesh of its own. `asked`: the +/// person asked for this model past the size limit (`solid::fits_asked`). +pub fn read_streaming(kind: u32, path: &str, cli: &str, tools: &[Mesher], infos: &str, fine: Option<[f64; 6]>, asked: bool, on: Option<&mut dyn FnMut(Streamed)>) -> Got { let (isglb, step) = (path.ends_with(".glb"), is_step(path)); let out = glb_at(kind, path, fine); let detail = fine.map_or(stepglb::NORMAL, stepglb::Detail::refined); @@ -155,8 +157,8 @@ pub fn read_streaming(kind: u32, path: &str, cli: &str, tools: &[Mesher], infos: if r.code != 0 { return fail(format!("3D export failed: {}", r.out.trim().chars().take(600).collect::())) } plotgen::write_infos(infos, &missing_note(&r.out)); let size = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0); - if !solid::fits_for(size, step) { return fail(solid::big(size)) } - match plot_of(&std::fs::read(&out).unwrap_or_default(), step) { Ok(p) => Got { code: 0, text: String::new(), plot: Some(p) }, Err(_) => fail(solid::big(size)) } + if !solid::fits_asked(size, step, asked) { return fail(solid::big_for(size, step, asked)) } + match plot_of(&std::fs::read(&out).unwrap_or_default(), step) { Ok(p) => Got { code: 0, text: String::new(), plot: Some(p) }, Err(_) => fail(solid::big_for(size, step, asked)) } } #[cfg(test)] @@ -226,7 +228,7 @@ mod tests { std::env::set_var("XDG_CACHE_HOME", d.join("cache")); // its own models cache: nothing made before is read let tools = [Mesher::Step2glb(tool)]; let infos = d.join("i").to_string_lossy().into_owned(); let rim = |fine: Option<[f64; 6]>| -> usize { - let g = read_streaming(2, &src.to_string_lossy(), "", &tools, &infos, fine, None); + let g = read_streaming(2, &src.to_string_lossy(), "", &tools, &infos, fine, false, None); assert_eq!(g.code, 0, "{}", g.text); let ts = glb::tris(&std::fs::read(glb_at(2, &src.to_string_lossy(), fine)).unwrap()).unwrap(); let mut pts: Vec<(i64, i64)> = ts.iter().flat_map(|t| [t.a, t.b, t.c]).filter(|p| (p[2] - 10.0).abs() < 1e-4 && ((p[0] * p[0] + p[1] * p[1]).sqrt() - 3.0).abs() < 1e-3) @@ -251,6 +253,7 @@ mod tests { let big = vec![0u8; solid::MOST as usize + 1]; std::fs::write(&f, &big).unwrap(); let p = f.to_string_lossy(); let g = read(2, &p, "", &[], &infos); assert_eq!((g.code, g.text.as_str()), (3, "This 3D model is too big to show here (13 MB; the hub reads models up to 12 MB)")); + let g = read_streaming(2, &p, "", &[], &infos, None, true, None); assert_eq!(g.code, 0, "asked for: read past the limit ({})", g.text); std::fs::write(&f, b"not a model").unwrap(); let g = read(2, &p, "", &[], &infos); assert_eq!(g.code, 0); let pl = g.plot.unwrap(); assert_eq!((pl.solid, pl.thick), (None, 0)); } diff --git a/native/host/src/kicad/watch.rs b/native/host/src/kicad/watch.rs index 04567f35ed..fc3f069d77 100644 --- a/native/host/src/kicad/watch.rs +++ b/native/host/src/kicad/watch.rs @@ -76,7 +76,7 @@ pub fn stage_text(kind: u32, file: &str, native: bool, cached: bool, tools: &[st pub fn is_retryable_err(why: &str) -> bool { if why.is_empty() || why.starts_with("@bp.file-missing:") { return false } let low = why.to_ascii_lowercase(); - !["too large", "not found", "no such file", "does not exist", "unsupported", "permission denied"].iter().any(|p| low.contains(p)) + !["too large", "too big", "not found", "no such file", "does not exist", "unsupported", "permission denied"].iter().any(|p| low.contains(p)) } pub fn key(kind: u32, root: &str, path: &str) -> String { format!("{kind}|{root}|{path}") } /// An Altium board file (.PcbDoc, any case): read by altium/pcb.rs @@ -88,7 +88,8 @@ pub fn fnv(s: &str) -> u32 { s.chars().fold(2166136261u32, |h, c| (h ^ c as u32) #[derive(Default)] /// `parts`: a board model's part frames so far (the one that starts them first), `stop` its stream's (set when another replaces it) /// `focus`: a STEP the person zoomed in on, refined around this box (kicad.refine): read at that detail from then on -struct Src { kind: u32, root: String, file: String, stamp: Option, busy: bool, plot: Option>, again: bool, parts: Vec>>, stop: Option>, focus: Option<[f64; 6]> } +/// `asked`: the person asked for this model past the size limit (kicad.big, "Load it anyway"): read up to `solid::MOST_ASKED` from then on +struct Src { kind: u32, root: String, file: String, stamp: Option, busy: bool, plot: Option>, again: bool, parts: Vec>>, stop: Option>, focus: Option<[f64; 6]>, asked: bool } /// `kept`: the id (`plot::mesh_id`) of the model the client already holds from an earlier visit; that model is not sent again /// `parts_at`: how many of its source's part frames this watcher has been sent struct Sub { key: String, held: Vec, mesh: Vec, fresh: bool, base: String, kept: u64, kept_chunks: std::collections::HashSet, with_chunk_hashes: bool, parts_at: usize } @@ -467,6 +468,18 @@ impl Plots { self.read(hub, ky); Ok(true) } + /// kicad.big: a client asked for a 3D model it watches that was refused for its size ("Load it anyway"). The source is read again up to + /// `solid::MOST_ASKED`, and stays so while it is watched. Ok(false): it was asked for already. Err: not a 3D model this client watches. + pub fn ask_big(self: &Arc, hub: &Arc, client: u64, ky: &str) -> Result { + { let mut st = self.st.lock().unwrap(); + if !st.subs.get(&client).map_or(false, |v| v.iter().any(|s| s.key == ky)) { return Err("that model is not on show here") } + let Some(s) = st.srcs.get_mut(ky) else { return Err("that model is not on show here") }; + if !solid_kind(s.kind) { return Err("only a 3D model is loaded past its size") } + if s.asked { return Ok(false) } + s.asked = true; } + self.read(hub, ky); + Ok(true) + } /// A board model's parts, streamed: the plan's frames go onto the source as they are made and out to its watchers. A newer model's /// stream stops this one (its flag), and so does the source leaving. fn start_parts(self: &Arc, hub: &Arc, ky: &str, file: &str, rev: String, made: Arc<(pcb3d::stream::Plan, u64)>) { @@ -590,7 +603,7 @@ impl Plots { } fn read(self: &Arc, hub: &Arc, ky: &str) { - let (kind, root, file) = { let mut st = self.st.lock().unwrap(); let Some(s) = st.srcs.get_mut(ky) else { return }; if s.busy { s.again = true; return } s.busy = true; (s.kind, s.root.clone(), s.file.clone()) }; + let (kind, root, file, asked) = { let mut st = self.st.lock().unwrap(); let Some(s) = st.srcs.get_mut(ky) else { return }; if s.busy { s.again = true; return } s.busy = true; (s.kind, s.root.clone(), s.file.clone(), s.asked) }; let (me, hub, ky) = (self.clone(), hub.clone(), ky.to_string()); tokio::spawn(async move { let t0 = std::time::Instant::now(); @@ -603,7 +616,8 @@ impl Plots { // always made here (altium/board3d.rs reads the .PcbDoc itself: no KiCad, no kicad-cli) let native3d = solid3 && !file.starts_with("diff\n") && (is_altium_board(&file) || (file.ends_with(".kicad_pcb") && Self::board3d_native(&hub).await)); let known = if solid3 && !native3d { solidread::known(kind, &file) } else { 0 }; - let _one = if solid3 && !native3d && solid::fits_for(known, solidread::is_step(&file)) { + let fits = solid::fits_asked(known, solidread::is_step(&file), asked); + let _one = if solid3 && !native3d && fits { let g = match me.solid.try_lock() { Ok(g) => g, Err(_) => { say("Waiting for another 3D model to finish…"); me.solid.lock().await } }; Some(g) } else { None }; @@ -612,7 +626,7 @@ impl Plots { let before = if is_version(&file) { Stamp::default() } else { stamp_in(&file, rt) }; let mut parts = None; let out = if native3d { me.run_board3d(&hub, kind, &file, &ky).await.map(|r| match r { Ok((p, plan)) => { parts = plan; (0, String::new(), Some(p)) } Err(e) => (3, e, None) }) } - else if !solid::fits_for(known, solidread::is_step(&file)) { Some((3, solid::big(known), None)) } else if native() { me.run_native(&hub, kind, &root, &file, &ky).await } else { me.run_child(kind, &root, &file, &ky).await.map(|(c, t)| (c, t, None)) }; + else if !fits { Some((3, solid::big_for(known, solidread::is_step(&file), asked), None)) } else if native() { me.run_native(&hub, kind, &root, &file, &ky, asked).await } else { me.run_child(kind, &root, &file, &ky, asked).await.map(|(c, t)| (c, t, None)) }; let after = if is_version(&file) { Stamp::default() } else { stamp_in(&file, rt) }; let (code, text, made) = match out { Some((c, t, m)) => if before != after { (2, String::new(), None) } else { (c, t, m) }, None => (1, "cannot run the plot reader".into(), None) }; let mut again = false; @@ -635,8 +649,11 @@ impl Plots { (None, _) => { // Pv.fail: every watcher told why, and holding nothing let why: String = text.trim().chars().take(200).collect(); let retryable = is_retryable_err(&why); + // a model refused for its size, not asked for yet: `big`, the page offers "Load it anyway" (kicad.big) + let mut frame = json!({"t":"plot","key":ky,"none":why,"retryable":retryable}); + if solid3 && !asked && solid::is_big(&why) { frame["big"] = json!(true) } let mut st = me.st.lock().unwrap(); let mut gone = vec![]; - for (c, subs) in st.subs.iter_mut() { for s in subs.iter_mut().filter(|s| s.key == ky) { s.held.clear(); if !hub.push(*c, json!({"t":"plot","key":ky,"none":why,"retryable":retryable})) { gone.push(*c) } } } + for (c, subs) in st.subs.iter_mut() { for s in subs.iter_mut().filter(|s| s.key == ky) { s.held.clear(); if !hub.push(*c, frame.clone()) { gone.push(*c) } } } drop(st); for c in gone { me.stop(c) } } } if matches!(code, 0 | 2) && (ky.starts_with("2|") || ky.starts_with("3|")) { me.note(&hub, &ky, None) } // Pv.handle PGot @@ -646,7 +663,7 @@ impl Plots { } /// `Pv.child` in this process (kicad/plotread.rs, kicad/solidread.rs): the plot, its info file written, and the child's exit code and /// message. A panic in a reader is an unread file, never the hub's end; a big file's memory goes back when it is done. - async fn run_native(self: &Arc, hub: &Arc, kind: u32, root: &str, file: &str, ky: &str) -> Option<(i32, String, Option)> { + async fn run_native(self: &Arc, hub: &Arc, kind: u32, root: &str, file: &str, ky: &str, asked: bool) -> Option<(i32, String, Option)> { let (f, infos) = (file.to_string(), self.infos(ky)); if solid_kind(kind) { let (cli, home) = (super::ipc::runtime(hub).await.cli, self.home.clone()); @@ -671,9 +688,9 @@ impl Plots { emit(plot::part_frame_faces(&ky, &format!("step{n}"), count, &mesh, &[IDENTITY], &[], done, &faces)) } }; - solidread::read_streaming(kind, &f, &cli, &tools, &i, None, Some(&mut on)) + solidread::read_streaming(kind, &f, &cli, &tools, &i, None, asked, Some(&mut on)) } - None => solidread::read_streaming(kind, &f, &cli, &tools, &i, focus, None), + None => solidread::read_streaming(kind, &f, &cli, &tools, &i, focus, asked, None), })); let o = match r { Ok(g) => (g.code, g.text, g.plot), Err(_) => (3, plotgen::UNREAD.to_string(), None) }; #[cfg(all(target_os = "linux", target_env = "gnu"))] unsafe { libc::malloc_trim(0); } @@ -693,9 +710,10 @@ impl Plots { o }).await.ok() } - async fn run_child(&self, kind: u32, root: &str, file: &str, ky: &str) -> Option<(i32, String)> { + async fn run_child(&self, kind: u32, root: &str, file: &str, ky: &str, asked: bool) -> Option<(i32, String)> { let mut c = if solid_kind(kind) { let mut c = crate::proc::tokio_cmd(crate::proc::Kind::Local, "nice"); c.args(["-n", "10"]).arg(&self.bin); c } else { crate::proc::tokio_cmd(crate::proc::Kind::Local, &self.bin) }; if !root.is_empty() { c.env("BACKPLANE_PLOT_ROOT", root); } + if asked { c.env("BACKPLANE_PLOT_ASKED", "1"); } c.arg("--plot").arg(kind.to_string()).arg(file).arg(self.infos(ky)).stdin(std::process::Stdio::null()).kill_on_drop(false); let o = c.output().await.ok()?; let code = o.status.code().unwrap_or(1); @@ -858,7 +876,7 @@ pub fn viewer_snapshot(thread: &str) -> (u64, u64, Value) { vs().lock().unwrap() pub struct KicadRpc(pub Arc); impl RpcHandler for KicadRpc { - fn methods(&self) -> &'static [&'static str] { &["kicad.watch", "kicad.watch.set", "kicad.refine", "kicad.info", "kicad.warm", "kicad.probe", "kicad.open", "kicad.install", "viewer.state", "history.steps"] } + fn methods(&self) -> &'static [&'static str] { &["kicad.watch", "kicad.watch.set", "kicad.refine", "kicad.big", "kicad.info", "kicad.warm", "kicad.probe", "kicad.open", "kicad.install", "viewer.state", "history.steps"] } fn call<'a>(&'a self, hub: &'a Arc, who: &'a Caller, id: &'a Value, method: &'a str, p: &'a Value) -> Fut<'a, Vec> { Box::pin(async move { let s = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or("").to_string(); @@ -928,6 +946,11 @@ impl RpcHandler for KicadRpc { Err(why) => vec![json!({"t":"reply","id":id,"ok":false,"error":why})], } } + // "Load it anyway": a 3D model refused for its size, read past the limit (Plots::ask_big) + "kicad.big" => match self.0.ask_big(hub, who.client, &s("key")) { + Ok(started) => vec![json!({"t":"reply","id":id,"ok":true,"result":{"started":started}})], + Err(why) => vec![json!({"t":"reply","id":id,"ok":false,"error":why})], + }, "kicad.warm" => { // the saved versions before and after a step, plotted ahead let (kind, root) = (s("kind"), s("root")); for path in [s("before"), s("after")] { @@ -1331,7 +1354,7 @@ mod tests { let plots = Plots::new(&home); let ky = "2|/p/mech/lid.step|".to_string(); let mut out = hub.attach(7); { let mut st = plots.st.lock().unwrap(); - st.srcs.insert(ky.clone(), Src { kind: 2, root: "/p".into(), file: "/p/mech/lid.step".into(), stamp: None, busy: true, plot: None, again: false, parts: vec![], stop: None, focus: None }); + st.srcs.insert(ky.clone(), Src { kind: 2, root: "/p".into(), file: "/p/mech/lid.step".into(), stamp: None, busy: true, plot: None, again: false, parts: vec![], stop: None, focus: None, asked: false }); st.subs.insert(7, vec![Sub { key: ky.clone(), held: vec![], mesh: vec![], fresh: true, base: String::new(), kept: 0, kept_chunks: Default::default(), with_chunk_hashes: false, parts_at: 0 }]); } let raw = |out: &mut crate::hub::Outbox| { let mut v = vec![]; while let Ok(o) = out.try_recv() { if let Out::Raw(b) = o { v.push(String::from_utf8_lossy(&b).into_owned()) } } v }; let old = plots.step_stream(&ky); diff --git a/web/dist/assets/app.js b/web/dist/assets/app.js index 7a528a7e85..cabf49ef40 100644 --- a/web/dist/assets/app.js +++ b/web/dist/assets/app.js @@ -1,15 +1,15 @@ -function nn(e=Date.now(),t=Math.random){let n=Math.floor(t()*1099511627776).toString(36);return`w${e}-${n}`.replace(/[^A-Za-z0-9_-]/g,"").slice(0,64)}function Yn(e){return e==="done"||e==="failed"||e==="cancelled"}function Xn(e,t){if(!e||e.id!==t.id)return!0;let n=Yn(e.state),i=Yn(t.state);if(n!==i)return i;return(t.ended??0)>=(e.ended??0)}function Zn(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var Ct={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.new":"New bot","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","gpui.settings.group.agents":"Agents and tools","gpui.settings.group.general":"General","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","menu.wake":"Wake","model.col.agent":"Agent","native.pair.connect":"Connect","native.thread.model":"Model","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.senderr.remote":"No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","rooms.new":"New room","secret.you":"You","settings.appearance":"Appearance","settings.lang":"Language","settings.lang.auto":"Automatic","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Theme","settings.theme.dark":"Dark","settings.theme.light":"Light","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets","web.settings.providers":"AI providers","web.settings.providers.browser":"Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.new":"Nuevo bot","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.short":"Capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.noitems":"Sin corredores ni planos en esta capa","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup.short":"Apilamiento","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","gpui.settings.group.agents":"Agentes y herramientas","gpui.settings.group.general":"General","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","menu.wake":"Despertar","model.col.agent":"Agente","native.pair.connect":"Conectar","native.thread.model":"Modelo","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.senderr.remote":"No hay ningún proveedor de IA conectado en {machine}. Abre Configuración → Cuentas en {machine} para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","rooms.new":"Nueva sala","secret.you":"Tú","settings.appearance":"Apariencia","settings.lang":"Idioma","settings.lang.auto":"Automático","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Tema","settings.theme.dark":"Oscuro","settings.theme.light":"Claro","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes","web.settings.providers":"Proveedores de IA","web.settings.providers.browser":"Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas."},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.new":"新しいボット","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.short":"レイヤー","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.noitems":"このレイヤーにコリドーまたはプレーンがありません","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup.short":"スタックアップ","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","gpui.settings.group.agents":"エージェントとツール","gpui.settings.group.general":"一般","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","menu.wake":"再開","model.col.agent":"エージェント","native.pair.connect":"接続","native.thread.model":"モデル","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.senderr.remote":"{machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","rooms.new":"新しいルーム","secret.you":"あなた","settings.appearance":"外観","settings.lang":"言語","settings.lang.auto":"自動","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"テーマ","settings.theme.dark":"ダーク","settings.theme.light":"ライト","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット","web.settings.providers":"AI プロバイダー","web.settings.providers.browser":"Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。"}};function Qn(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var xt=Fs(),sn=new Set,an=new Map;for(let[e,t]of Object.entries(Ct.en||{}))if(typeof t==="string"&&!an.has(t))an.set(t,e);function Fs(){let e=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(e.startsWith("ja"))return"ja";if(e.startsWith("es"))return"es";return"en"}function ei(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=xt}ei();function Ot(e){return sn.add(e),()=>{sn.delete(e)}}function ct(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==xt;if(xt=n,ei(),i)for(let s of sn)s(xt);return i}function m(e,t,n){let s=(Ct[xt]||Ct.en||{})[e]??Ct.en?.[e]??t??e;return Qn(s,n)}function pe(e){if(!e)return"";let t=an.get(e);if(!t)return e;return m(t,e)}function J(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Fe(e,t="",n){let i=J("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function $s(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function Gs(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class rn{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=J("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=J("div","bp-fb-head");this.upBtn=Fe("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=m("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",m("web.clone.up","Up")),this.pathInput=J("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(r)=>{if(r.key==="Enter"){r.preventDefault();let o=this.pathInput.value.trim();if(o)this.go(o)}}),s.append(this.upBtn,this.pathInput),this.listEl=J("div","bp-fb-list"),this.errEl=J("div","bp-ap-err bp-hidden");let a=J("div","bp-ap-foot");this.actBtn=Fe("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),a.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,a)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(J("div","bp-fb-empty",m("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(pe(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=m("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(J("div","bp-fb-empty",m("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=Fe("","bp-fb-row",()=>{this.go(Gs(this.path,n))});i.append(J("span","bp-fb-icon","▸"),J("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel($s(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(pe(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class on{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=J("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=J("div","bp-modal bp-ap"),n=J("div","bp-modal-head"),i=J("h2","",m("sidebar.add.project","Add project")),s=Fe("×","icon",()=>this.close());s.title=m("common.close","Close"),s.setAttribute("aria-label",m("common.close","Close")),n.append(i,s),this.tabsEl=J("div","bp-ap-tabs"),this.bodyEl=J("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(a)=>{if(a.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=m("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=Fe(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",m("gpui.e.open.folder","Open folder")),e("clone",m("web.clone.tab","Clone from git")))}renderFolder(){let e=new rn(this.host.hub,(t)=>m("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=J("div","bp-ap-form"),n=J("div","bp-ap-repo"),i=J("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=m("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",m("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(p)=>this.repoKey(p)),this.repoInput=i,this.suggestEl=J("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=J("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=J("label","bp-ap-check"),a=J("input");a.type="checkbox",a.checked=this.wantThread,a.setAttribute("data-testid","clone-thread"),a.addEventListener("change",()=>{this.wantThread=a.checked}),s.append(a,J("span","",m("web.clone.start.thread","Start a thread")));let r=[n,this.signinEl,this.destEl,s];if(this.firstText)r.push(J("div","bp-ap-first bp-dim",m("web.clone.first","First message: {text}",{text:this.firstText})));let o=J("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let l=J("div","bp-ap-foot");this.cloneBtn=Fe(m("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),l.append(this.cloneBtn),r.push(o,l),t.append(...r),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,a)=>{let r=Fe("","bp-ap-sug"+(a===this.suggestIdx?" active":""));r.setAttribute("data-testid","clone-suggestion"),r.addEventListener("mousedown",(l)=>l.preventDefault()),r.addEventListener("click",()=>this.pickRepo(s));let o=J("div","bp-ap-sug-top");if(o.append(J("span","bp-ap-sug-name",s.name)),s.private)o.append(J("span","bp-ap-tag",m("web.clone.private","private")));if(r.append(o),s.description)r.append(J("div","bp-ap-sug-desc",s.description));i.push(r)}),n.length===0&&t){if(t.loading)i.push(J("div","bp-ap-sug-note",m("web.clone.loading","Loading…")));else if(t.hint){let s=J("div","bp-ap-sug-note");if(s.append(J("span","",pe(t.hint))),t.state==="signedout"){let a=Fe(m("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});a.addEventListener("mousedown",(r)=>r.preventDefault()),a.setAttribute("data-testid","clone-signin-btn"),s.append(a)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(pe(t.error)))}else if(t){let r=J("div","bp-ap-where"),o=J("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let l=Fe(m("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});l.setAttribute("data-testid","clone-change-folder"),r.append(o,l),n.push(r);let p=J("label","bp-ap-name");p.append(J("span","bp-ap-lbl",m("web.clone.folder.name","Folder name")));let c=J("input","bp-input");if(c.type="text",c.spellcheck=!1,c.value=this.nameText,c.setAttribute("data-testid","clone-name"),c.addEventListener("input",()=>{this.nameText=c.value,this.nameTouched=c.value.trim()!=="",this.startErr="",this.askDest(250)}),c.addEventListener("keydown",(u)=>{if(u.key==="Enter"&&this.canStart())u.preventDefault(),this.startClone()}),p.append(c),n.push(p),!t.ok&&t.error)n.push(this.errLine(pe(t.error)));else if(t.same)n.push(J("div","bp-ap-note bp-dim",m("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",a=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let r=e.querySelector('[data-testid="clone-name"]');if(r){if(r.focus(),a!==null)r.setSelectionRange(a,a)}}this.updateCloneBtn()}errLine(e){let t=J("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=Fe(m("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new rn(this.host.hub,(i)=>m("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=nn();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=pe(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=nn(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let a=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(a)}catch(a){let r=pe(a instanceof Error?a.message:String(a));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let o=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(o&&o.id===i){this.apply(o);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(r)}}apply(e){if(!e||e.id!==this.jobId)return;if(!Xn(this.job,e))return;if(this.job=e,this.copied=!1,this.isOpen()&&this.mode==="clone")if(this.jobEl&&this.jobEl.isConnected)this.renderJob();else this.render();this.maybeGo(e)}maybeGo(e){if(this.isOpen()&&e.id===this.jobId&&Zn(e))this.goTo(e)}renderJobView(){this.jobEl=J("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?m("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?m("web.clone.stopped","Stopped cloning {repo}",{repo:i}):m("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),a=[J("div","bp-ap-job-title",s)];if(t.state==="running"){let r=J("div","bp-ap-phase",pe(t.phase||""));r.setAttribute("data-testid","clone-phase");let o=J("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),l=J("div","bp-ap-bar-fill");if(typeof t.pct==="number")l.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(l),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(a.push(r,o),t.detail)a.push(J("div","bp-ap-detail bp-dim",t.detail));let p=J("div","bp-ap-foot"),c=Fe(m("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((u)=>this.apply(u)).catch(()=>{})});c.setAttribute("data-testid","clone-cancel"),p.append(c),a.push(p)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let p=J("div","bp-ap-err",pe(t.error));p.setAttribute("data-testid","clone-error"),a.push(p)}let r=J("div","bp-ap-foot"),o=Fe(m("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(r.append(o),t.signin){let p=Fe(m("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});p.setAttribute("data-testid","clone-signin-btn"),r.append(p)}let l=Fe(m("web.clone.retry","Try again"),"primary",()=>{this.retry(t,l)});l.setAttribute("data-testid","clone-retry"),r.append(l),a.push(r)}else if(t.state==="done"){let r=t.notes??[];if(r.length>0){let c=J("ul","bp-ap-notes");c.setAttribute("data-testid","clone-notes");for(let u of r)c.appendChild(J("li","",pe(u)));a.push(c)}let o=J("div","bp-ap-foot"),l=t.thread?m("web.clone.open.thread","Open the thread"):m("web.clone.open.project","Open the project"),p=Fe(l,"primary",()=>this.goTo(t));p.setAttribute("data-testid","clone-open"),o.append(p),a.push(o)}e.replaceChildren(...a)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=J("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(J("div","bp-dim",m("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(J("div","",m("web.clone.signin.enter","Enter this code on GitHub:")));let i=J("div","bp-ap-code-row"),s=J("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let a=Fe(this.copied?m("web.clone.copied","Copied"):m("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,a),n.push(i),t.url){let r=J("a","bp-ap-link",t.url);r.href=t.url,r.target="_blank",r.rel="noopener noreferrer",r.setAttribute("data-testid","clone-signin-url"),n.push(r)}}else if(t.state==="done")n.push(J("div","bp-ok",m("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(J("div","bp-ap-err",pe(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function Os(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function kt(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let a=s[0];if(a.startsWith("`")&&a.endsWith("`")){let r=document.createElement("code");r.className="bp-code-inline",r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("**")&&a.endsWith("**")){let r=document.createElement("strong");r.textContent=a.slice(2,-2),e.appendChild(r)}else if(a.startsWith("*")&&a.endsWith("*")){let r=document.createElement("em");r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("[")){let r=s[2]??"",o=Os(s[3]??"");if(o){let l=document.createElement("a");l.href=o,l.target="_blank",l.rel="noopener noreferrer",l.textContent=r,e.appendChild(l)}else e.appendChild(document.createTextNode(r))}i=n.lastIndex}if(i=(e.ended??0)}function Zn(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var Ct={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.new":"New bot","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.solid.big.next":"Loading it may take a while and a lot of memory.","gpui.c.solid.load.big":"Load it anyway","gpui.c.solid.loading.big":"Loading it anyway…","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","gpui.settings.group.agents":"Agents and tools","gpui.settings.group.general":"General","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","menu.wake":"Wake","model.col.agent":"Agent","native.pair.connect":"Connect","native.thread.model":"Model","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.senderr.remote":"No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","rooms.new":"New room","secret.you":"You","settings.appearance":"Appearance","settings.lang":"Language","settings.lang.auto":"Automatic","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Theme","settings.theme.dark":"Dark","settings.theme.light":"Light","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets","web.settings.providers":"AI providers","web.settings.providers.browser":"Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.new":"Nuevo bot","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.solid.big.next":"Cargarlo puede tardar y usar mucha memoria.","gpui.c.solid.load.big":"Cargarlo de todos modos","gpui.c.solid.loading.big":"Cargándolo de todos modos…","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.short":"Capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.noitems":"Sin corredores ni planos en esta capa","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup.short":"Apilamiento","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","gpui.settings.group.agents":"Agentes y herramientas","gpui.settings.group.general":"General","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","menu.wake":"Despertar","model.col.agent":"Agente","native.pair.connect":"Conectar","native.thread.model":"Modelo","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.senderr.remote":"No hay ningún proveedor de IA conectado en {machine}. Abre Configuración → Cuentas en {machine} para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","rooms.new":"Nueva sala","secret.you":"Tú","settings.appearance":"Apariencia","settings.lang":"Idioma","settings.lang.auto":"Automático","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Tema","settings.theme.dark":"Oscuro","settings.theme.light":"Claro","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes","web.settings.providers":"Proveedores de IA","web.settings.providers.browser":"Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas."},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.new":"新しいボット","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.solid.big.next":"読み込みには時間と多くのメモリがかかることがあります。","gpui.c.solid.load.big":"それでも読み込む","gpui.c.solid.loading.big":"それでも読み込み中…","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.short":"レイヤー","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.noitems":"このレイヤーにコリドーまたはプレーンがありません","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup.short":"スタックアップ","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","gpui.settings.group.agents":"エージェントとツール","gpui.settings.group.general":"一般","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","menu.wake":"再開","model.col.agent":"エージェント","native.pair.connect":"接続","native.thread.model":"モデル","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.senderr.remote":"{machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","rooms.new":"新しいルーム","secret.you":"あなた","settings.appearance":"外観","settings.lang":"言語","settings.lang.auto":"自動","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"テーマ","settings.theme.dark":"ダーク","settings.theme.light":"ライト","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット","web.settings.providers":"AI プロバイダー","web.settings.providers.browser":"Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。"}};function Qn(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var xt=Fs(),sn=new Set,an=new Map;for(let[e,t]of Object.entries(Ct.en||{}))if(typeof t==="string"&&!an.has(t))an.set(t,e);function Fs(){let e=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(e.startsWith("ja"))return"ja";if(e.startsWith("es"))return"es";return"en"}function ei(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=xt}ei();function Ot(e){return sn.add(e),()=>{sn.delete(e)}}function ct(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==xt;if(xt=n,ei(),i)for(let s of sn)s(xt);return i}function h(e,t,n){let s=(Ct[xt]||Ct.en||{})[e]??Ct.en?.[e]??t??e;return Qn(s,n)}function pe(e){if(!e)return"";let t=an.get(e);if(!t)return e;return h(t,e)}function J(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Fe(e,t="",n){let i=J("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function $s(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function Gs(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class rn{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=J("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=J("div","bp-fb-head");this.upBtn=Fe("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=h("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",h("web.clone.up","Up")),this.pathInput=J("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(r)=>{if(r.key==="Enter"){r.preventDefault();let o=this.pathInput.value.trim();if(o)this.go(o)}}),s.append(this.upBtn,this.pathInput),this.listEl=J("div","bp-fb-list"),this.errEl=J("div","bp-ap-err bp-hidden");let a=J("div","bp-ap-foot");this.actBtn=Fe("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),a.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,a)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(J("div","bp-fb-empty",h("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(pe(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=h("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(J("div","bp-fb-empty",h("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=Fe("","bp-fb-row",()=>{this.go(Gs(this.path,n))});i.append(J("span","bp-fb-icon","▸"),J("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel($s(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(pe(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class on{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=J("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=J("div","bp-modal bp-ap"),n=J("div","bp-modal-head"),i=J("h2","",h("sidebar.add.project","Add project")),s=Fe("×","icon",()=>this.close());s.title=h("common.close","Close"),s.setAttribute("aria-label",h("common.close","Close")),n.append(i,s),this.tabsEl=J("div","bp-ap-tabs"),this.bodyEl=J("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(a)=>{if(a.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=h("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=Fe(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",h("gpui.e.open.folder","Open folder")),e("clone",h("web.clone.tab","Clone from git")))}renderFolder(){let e=new rn(this.host.hub,(t)=>h("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=J("div","bp-ap-form"),n=J("div","bp-ap-repo"),i=J("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=h("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",h("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(p)=>this.repoKey(p)),this.repoInput=i,this.suggestEl=J("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=J("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=J("label","bp-ap-check"),a=J("input");a.type="checkbox",a.checked=this.wantThread,a.setAttribute("data-testid","clone-thread"),a.addEventListener("change",()=>{this.wantThread=a.checked}),s.append(a,J("span","",h("web.clone.start.thread","Start a thread")));let r=[n,this.signinEl,this.destEl,s];if(this.firstText)r.push(J("div","bp-ap-first bp-dim",h("web.clone.first","First message: {text}",{text:this.firstText})));let o=J("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let l=J("div","bp-ap-foot");this.cloneBtn=Fe(h("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),l.append(this.cloneBtn),r.push(o,l),t.append(...r),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,a)=>{let r=Fe("","bp-ap-sug"+(a===this.suggestIdx?" active":""));r.setAttribute("data-testid","clone-suggestion"),r.addEventListener("mousedown",(l)=>l.preventDefault()),r.addEventListener("click",()=>this.pickRepo(s));let o=J("div","bp-ap-sug-top");if(o.append(J("span","bp-ap-sug-name",s.name)),s.private)o.append(J("span","bp-ap-tag",h("web.clone.private","private")));if(r.append(o),s.description)r.append(J("div","bp-ap-sug-desc",s.description));i.push(r)}),n.length===0&&t){if(t.loading)i.push(J("div","bp-ap-sug-note",h("web.clone.loading","Loading…")));else if(t.hint){let s=J("div","bp-ap-sug-note");if(s.append(J("span","",pe(t.hint))),t.state==="signedout"){let a=Fe(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});a.addEventListener("mousedown",(r)=>r.preventDefault()),a.setAttribute("data-testid","clone-signin-btn"),s.append(a)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(pe(t.error)))}else if(t){let r=J("div","bp-ap-where"),o=J("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let l=Fe(h("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});l.setAttribute("data-testid","clone-change-folder"),r.append(o,l),n.push(r);let p=J("label","bp-ap-name");p.append(J("span","bp-ap-lbl",h("web.clone.folder.name","Folder name")));let c=J("input","bp-input");if(c.type="text",c.spellcheck=!1,c.value=this.nameText,c.setAttribute("data-testid","clone-name"),c.addEventListener("input",()=>{this.nameText=c.value,this.nameTouched=c.value.trim()!=="",this.startErr="",this.askDest(250)}),c.addEventListener("keydown",(u)=>{if(u.key==="Enter"&&this.canStart())u.preventDefault(),this.startClone()}),p.append(c),n.push(p),!t.ok&&t.error)n.push(this.errLine(pe(t.error)));else if(t.same)n.push(J("div","bp-ap-note bp-dim",h("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",a=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let r=e.querySelector('[data-testid="clone-name"]');if(r){if(r.focus(),a!==null)r.setSelectionRange(a,a)}}this.updateCloneBtn()}errLine(e){let t=J("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=Fe(h("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new rn(this.host.hub,(i)=>h("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=nn();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=pe(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=nn(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let a=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(a)}catch(a){let r=pe(a instanceof Error?a.message:String(a));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let o=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(o&&o.id===i){this.apply(o);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(r)}}apply(e){if(!e||e.id!==this.jobId)return;if(!Xn(this.job,e))return;if(this.job=e,this.copied=!1,this.isOpen()&&this.mode==="clone")if(this.jobEl&&this.jobEl.isConnected)this.renderJob();else this.render();this.maybeGo(e)}maybeGo(e){if(this.isOpen()&&e.id===this.jobId&&Zn(e))this.goTo(e)}renderJobView(){this.jobEl=J("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?h("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?h("web.clone.stopped","Stopped cloning {repo}",{repo:i}):h("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),a=[J("div","bp-ap-job-title",s)];if(t.state==="running"){let r=J("div","bp-ap-phase",pe(t.phase||""));r.setAttribute("data-testid","clone-phase");let o=J("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),l=J("div","bp-ap-bar-fill");if(typeof t.pct==="number")l.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(l),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(a.push(r,o),t.detail)a.push(J("div","bp-ap-detail bp-dim",t.detail));let p=J("div","bp-ap-foot"),c=Fe(h("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((u)=>this.apply(u)).catch(()=>{})});c.setAttribute("data-testid","clone-cancel"),p.append(c),a.push(p)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let p=J("div","bp-ap-err",pe(t.error));p.setAttribute("data-testid","clone-error"),a.push(p)}let r=J("div","bp-ap-foot"),o=Fe(h("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(r.append(o),t.signin){let p=Fe(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});p.setAttribute("data-testid","clone-signin-btn"),r.append(p)}let l=Fe(h("web.clone.retry","Try again"),"primary",()=>{this.retry(t,l)});l.setAttribute("data-testid","clone-retry"),r.append(l),a.push(r)}else if(t.state==="done"){let r=t.notes??[];if(r.length>0){let c=J("ul","bp-ap-notes");c.setAttribute("data-testid","clone-notes");for(let u of r)c.appendChild(J("li","",pe(u)));a.push(c)}let o=J("div","bp-ap-foot"),l=t.thread?h("web.clone.open.thread","Open the thread"):h("web.clone.open.project","Open the project"),p=Fe(l,"primary",()=>this.goTo(t));p.setAttribute("data-testid","clone-open"),o.append(p),a.push(o)}e.replaceChildren(...a)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=J("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(J("div","bp-dim",h("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(J("div","",h("web.clone.signin.enter","Enter this code on GitHub:")));let i=J("div","bp-ap-code-row"),s=J("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let a=Fe(this.copied?h("web.clone.copied","Copied"):h("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,a),n.push(i),t.url){let r=J("a","bp-ap-link",t.url);r.href=t.url,r.target="_blank",r.rel="noopener noreferrer",r.setAttribute("data-testid","clone-signin-url"),n.push(r)}}else if(t.state==="done")n.push(J("div","bp-ok",h("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(J("div","bp-ap-err",pe(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function Os(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function kt(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let a=s[0];if(a.startsWith("`")&&a.endsWith("`")){let r=document.createElement("code");r.className="bp-code-inline",r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("**")&&a.endsWith("**")){let r=document.createElement("strong");r.textContent=a.slice(2,-2),e.appendChild(r)}else if(a.startsWith("*")&&a.endsWith("*")){let r=document.createElement("em");r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("[")){let r=s[2]??"",o=Os(s[3]??"");if(o){let l=document.createElement("a");l.href=o,l.target="_blank",l.rel="noopener noreferrer",l.textContent=r,e.appendChild(l)}else e.appendChild(document.createTextNode(r))}i=n.lastIndex}if(i{navigator.clipboard?.writeText(c).then(()=>{f.textContent="✓",window.setTimeout(()=>{f.textContent=b},1200)}).catch(()=>{})}),d.append(h,f);let g=document.createElement("pre"),y=document.createElement("code");y.textContent=c,g.appendChild(y),u.append(d,g),t.appendChild(u);continue}if(!s.trim()){i++;continue}let a=/^(#{1,4})\s+(.+)$/.exec(s);if(a){let l=document.createElement(`h${Math.min(4,a[1].length+1)}`);l.className="bp-md-h",kt(l,a[2]),t.appendChild(l),i++;continue}if(s.startsWith("> ")){let l=document.createElement("blockquote");l.className="bp-md-quote";let p=[];while(i "))p.push(n[i].slice(2)),i++;kt(l,p.join(` -`)),t.appendChild(l);continue}if(/^\s*[-*]\s+/.test(s)){let l=document.createElement("ul");l.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))r.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let l=0;l0)o.appendChild(document.createElement("br"));kt(o,r[l])}t.appendChild(o)}return t}var Vs=new Set(["(","[",'"',"'","`"]);function Us(e){return/[\p{L}\p{N}\-_\/+\[]/u.test(e)}function Ws(e){return/[\p{L}\p{N}\-_\/]/u.test(e)}function _s(e){return/[\p{L}\p{N}]/u.test(e)}function ti(e,t){if(!e)return[];let n=(t??[]).filter((a)=>a.kind==="model"&&a.word&&a.label);if(n.length===0)return[{kind:"text",text:e}];let i=[],s=0;while(sr)a=c,r=u,o=l;break}p=c+1}}if(o===null)break;if(a>s)i.push({kind:"text",text:e.slice(s,a)});i.push({kind:"model",word:o.word,label:o.label}),s=r}if(s3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function Ks(e,t){let n=document.createDocumentFragment(),i=ti(e,t),s=m("native.thread.model","Model").toLowerCase();for(let a of i){if(a.kind==="text"){n.appendChild(document.createTextNode(a.text));continue}let r=document.createElement("span");r.className="bp-ref-chip bp-ref-model",r.title=a.word,r.setAttribute("data-ref-word",a.word);let o=document.createElement("span");o.className="bp-ref-sigil",o.textContent="&";let l=document.createElement("span");l.className="bp-ref-label",l.textContent=a.label;let p=document.createElement("span");p.className="bp-ref-kind",p.textContent=s,r.append(o,l,p),n.appendChild(r)}return n}function Js(e){e.addEventListener("copy",(t)=>{let n=typeof window<"u"?window.getSelection():null;if(!n||n.rangeCount===0||n.isCollapsed)return;let i=n.getRangeAt(0);if(!e.contains(i.commonAncestorContainer))return;let s=i.commonAncestorContainer,o=(s.nodeType===Node.ELEMENT_NODE?s:s.parentElement)?.closest(".bp-ref-chip[data-ref-word]")?.getAttribute("data-ref-word"),l;if(o)l=o;else{let p=i.cloneContents(),c=p.querySelectorAll(".bp-ref-chip[data-ref-word]");if(c.length===0)return;for(let d of c){let h=d.getAttribute("data-ref-word")||d.textContent||"";d.replaceWith(document.createTextNode(h))}let u=p.querySelectorAll(".bp-entry");for(let d=1;d{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",Js(this.scrollEl),this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=m("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let a=document.createElement("button");a.type="button",a.textContent=m("tools.retry","Retry"),a.addEventListener("click",n),i.append(s,a),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=m("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((a)=>!ln(a)),this.hasMore=n,this.loadingOlder=!1,this.review=i,this.unanswered=s,this.btwNote=null,this.renderBanners(),this.renderEntries(!0)}updateThreadMeta(e){if(!this.thread||this.thread.id!==e.id)return;this.thread=e}setReview(e){this.review=e,this.renderBanners()}setUnanswered(e){this.unanswered=e,this.renderBanners()}setNoProvider(e){this.noProvider=e,this.renderBanners()}showBtw(e,t){this.btwNote={q:e,a:t},this.renderBanners()}prependEntries(e,t){this.loadingOlder=!1;let n=this.scrollEl.scrollHeight,i=new Set(this.entries.map((a)=>a.id)),s=e.filter((a)=>!ln(a)&&!i.has(a.id));this.entries=[...s,...this.entries],this.hasMore=t,this.renderEntries(!1),this.scrollEl.scrollTop+=this.scrollEl.scrollHeight-n}clearLoadingOlder(){this.loadingOlder=!1}upsertEntry(e){if(ln(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((r)=>r.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let a=this.liveNodes.get(e);if(a){if(a.replaceChildren(St(s.text)),i)this.scrollToBottom()}else this.renderEntries(i)}isNearBottom(){let e=this.scrollEl;return e.scrollHeight-e.scrollTop-e.clientHeight<80}scrollToBottom(){this.pinnedToBottom=!0,this.scrollEl.scrollTop=this.scrollEl.scrollHeight}renderBanners(){let e=document.createDocumentFragment();if(this.noProvider&&!this.thread?.id.includes("~")){let t=document.createElement("div");t.className="bp-banner bp-no-provider",t.setAttribute("data-testid","no-provider-banner");let n=document.createElement("div");n.className="bp-no-provider-body";let i=document.createElement("strong");if(i.textContent=pe(this.noProvider.head),n.appendChild(i),this.noProvider.text){let r=document.createElement("span");r.className="bp-dim",r.textContent=pe(this.noProvider.text),n.appendChild(r)}let s=document.createElement("div");s.className="bp-banner-actions";let a=document.createElement("button");a.type="button",a.className="primary",a.setAttribute("data-testid","no-provider-accounts-btn"),a.textContent=pe(this.noProvider.button),a.addEventListener("click",()=>this.cb.onOpenAccounts?.()),s.appendChild(a),t.append(n,s),e.appendChild(t)}if(this.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||m("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let a=document.createElement("button");if(a.type="button",s.primary)a.className="primary";a.textContent=s.label,a.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(a)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(St(this.btwNote.a)),n.append(i,s);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,a),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let a=m("common.copy","Copy"),r=document.createElement("span");r.textContent=a,s.append(At(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),r),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{r.textContent="✓",window.setTimeout(()=>{r.textContent=a},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let l=document.createElement("span");l.textContent=m("reply.action","Reply"),o.append(At(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),l),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let p=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),c=document.createElement("span");c.className="bp-entry-time";let u=zs(e.at);if(t)c.textContent=u,i.append(s,...p?[o]:[],c);else{let d=n&&e.at?qs(cn(e.at)-cn(n)):"",h=u?d?m("web.chat.finished.dur","Finished {time} · {dur}",{time:u,dur:d}):m("web.chat.finished","Finished {time}",{time:u}):"";c.textContent=e.live?m("web.chat.streaming","Streaming…"):h,i.append(c,s,...p?[o]:[])}return i}closePlanRevise(){let e=this.planRevisingId;if(!e)return!1;this.planRevisingId="";let t=this.scrollEl.scrollTop;return this.renderEntries(!1),this.scrollEl.scrollTop=t,this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e)}"] [data-testid="plan-revise"]`)?.focus(),!0}renderEntries(e){let t=null,n=typeof document<"u"?document.activeElement:null;if(n instanceof HTMLTextAreaElement&&n.classList.contains("bp-plan-revise-input")&&this.listEl.contains(n)&&this.planRevisingId)this.planReviseDrafts.set(this.planRevisingId,n.value),t={askId:this.planRevisingId,start:n.selectionStart,end:n.selectionEnd,dir:n.selectionDirection};this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let i=document.createDocumentFragment();if(!this.thread){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=m("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(a),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=m("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(a),this.listEl.replaceChildren(i);return}let s=0;for(let a of this.entries){if(a.kind==="user"&&a.at)s=a.at;let r=document.createElement("article");if(r.className=`bp-entry bp-entry-${a.kind}`+(a.live?" is-live":""),r.setAttribute("data-entry-id",a.id),a.kind==="tool"&&a.tool){let c=document.createElement("div");c.className=`bp-tool-pill bp-tool-${a.tool.state||"done"}`;let u=document.createElement("span");if(u.className="bp-tool-name",u.textContent=a.tool.name,c.appendChild(u),a.tool.summary){let d=document.createElement("span");d.className="bp-tool-summary",d.textContent=a.tool.summary,c.appendChild(d)}r.appendChild(c),i.appendChild(r);continue}if(a.kind==="ask"&&a.ask){let c=a.ask;if(c.kind==="plan"){r.appendChild(this.renderPlanAsk(c)),i.appendChild(r);continue}let u=document.createElement("div");u.className="bp-ask-card",u.setAttribute("data-testid",`ask-${c.id}`);let d=document.createElement("div");if(d.className="bp-ask-q",d.textContent=c.question,u.appendChild(d),c.state==="open"){let h=document.createElement("div");if(h.className="bp-ask-opts",c.options&&c.options.length>0)for(let f of c.options){let b=document.createElement("button");b.type="button",b.textContent=f.label,b.addEventListener("click",()=>this.cb.onAnswerAsk(c.id,f.id)),h.appendChild(b)}else{let f=document.createElement("input");f.type="text",f.className="bp-input",f.placeholder=m("web.chat.answer.placeholder","Type answer…");let b=document.createElement("button");b.type="button",b.className="primary",b.textContent=m("web.chat.answer.btn","Answer"),b.addEventListener("click",()=>{if(f.value.trim())this.cb.onAnswerAsk(c.id,f.value.trim())}),h.append(f,b)}u.appendChild(h)}else{let h=document.createElement("div");h.className="bp-ask-answered",h.textContent=m("web.chat.answered","Answered: {answer}",{answer:c.answered??""}),u.appendChild(h)}r.appendChild(u),i.appendChild(r);continue}let o=Boolean(a.text&&a.text.trim().length>0),l=Boolean(a.images&&a.images.length>0),p=Boolean(a.attachments&&a.attachments.length>0);if(!o&&!l&&!p&&!a.live)continue;if(a.replyTo?.quote){let c=document.createElement("div");c.className="bp-reply-quote",c.textContent=m("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:a.replyTo.quote});let u=a.replyTo.id;c.setAttribute("role","button"),c.tabIndex=0,c.setAttribute("data-testid","entry-reply-quote");let d=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(u);else this.goTo(u)};c.addEventListener("click",d),c.addEventListener("keydown",(h)=>{if(h.key==="Enter"||h.key===" ")h.preventDefault(),d()}),r.appendChild(c)}if(o||a.live){let c=document.createElement("div");if(c.className="bp-entry-body",a.kind==="user")c.appendChild(Ks(a.text||"",a.refs));else c.appendChild(St(a.text||""));if(a.live)this.liveNodes.set(a.id,c);r.appendChild(c)}if(p&&a.attachments){let c=document.createElement("div");c.className="bp-entry-images";for(let u of a.attachments)if(u.previewUrl){let d=document.createElement("img");d.className="bp-reply-img",d.src=u.previewUrl,d.alt=u.name||"attachment",c.appendChild(d)}else if(u.path||u.name){let d=document.createElement("span");d.className="bp-tool-pill",d.textContent=u.name||u.path||"image",c.appendChild(d)}if(c.childElementCount>0)r.appendChild(c)}if(a.images&&a.images.length>0){let c=document.createElement("div");c.className="bp-entry-images";for(let u of a.images){let d=document.createElement("img");d.className="bp-reply-img",d.alt=u;let h=`${a.id}|${u}`,f=this.imageCache.get(h);if(f)d.src=f;else this.cb.onLoadImage(a.id,u).then((b)=>{if(!b)return;let g=b.url??(b.mime&&b.data?`data:${b.mime};base64,${b.data}`:"");if(!g)return;this.imageCache.set(h,g),d.src=g});c.appendChild(d)}r.appendChild(c)}r.appendChild(this.makeEntryActions(a,a.kind==="user",a.kind==="assistant"?s:void 0)),i.appendChild(r)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let a=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(a){if(a.focus({preventScroll:!0}),t.start!==null&&t.end!==null)a.setSelectionRange(t.start,t.end,t.dir??void 0)}}if(e&&!t)this.scrollToBottom()}renderPlanAsk(e){let t=this.planExpanded.has(e.id),n=e.state==="open"&&this.planRevisingId===e.id,i=document.createElement("div");i.className="bp-ask-card bp-ask-plan",i.setAttribute("data-testid",`ask-${e.id}`);let s=document.createElement("div");s.className="bp-plan-head";let a=At(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"]);a.classList.add("bp-plan-head-ic");let r=document.createElement("span");if(r.className="bp-plan-title",r.textContent=!e.head||e.head==="Proposed plan"?m("ask.plan","Proposed plan"):pe(e.head),s.append(a,r),e.state==="open"){let c=document.createElement("span");c.className="bp-plan-badge",c.textContent=m("gpui.ask.plan.ready","Ready for review"),s.appendChild(c)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn";let u=m("common.copy","Copy"),d=document.createElement("span");d.textContent=u,c.append(At(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),d),c.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{c.classList.add("copied"),d.textContent=m("web.clone.copied","Copied"),window.setTimeout(()=>{c.classList.remove("copied"),d.textContent=u},1200)}).catch(()=>{})}),s.appendChild(c)}let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn",l.setAttribute("data-testid","plan-expand"),l.textContent=t?m("gpui.c.term.collapse","Collapse"):m("gpui.c.term.expand","Expand"),l.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let c=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=c}),s.appendChild(l),i.appendChild(s);let p=document.createElement("div");if(p.className="bp-plan-body"+(t?" is-expanded":""),p.setAttribute("data-testid","plan-body"),p.appendChild(St(e.question||"")),i.appendChild(p),e.state==="open"){let c=document.createElement("div");c.className="bp-plan-actions";let u=e.options?.find((b)=>b.id==="implement"||b.id.endsWith("|implement")),d=document.createElement("button");if(d.type="button",d.className="primary",d.setAttribute("data-testid","plan-implement"),d.textContent=u?.label&&u.label!=="Implement"?pe(u.label):m("approval.implement","Implement"),d.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,u?.id??"implement")}),c.appendChild(d),e.revise!==!1){let b=document.createElement("button");b.type="button",b.className="bp-plan-revise-btn"+(n?" active":""),b.setAttribute("data-testid","plan-revise"),b.append(At(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(m("gpui.ask.plan.revise","Revise"))),b.addEventListener("click",()=>{let g=this.planRevisingId!==e.id;this.planRevisingId=g?e.id:"";let y=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=y,g)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),c.appendChild(b)}let h=e.options?.find((b)=>b.id==="dismiss"||b.id.endsWith("|dismiss")),f=document.createElement("button");if(f.type="button",f.className="bp-plan-dismiss-btn",f.setAttribute("data-testid","plan-dismiss"),f.textContent=h?.label&&h.label!=="Dismiss"?pe(h.label):m("approval.dismiss","Dismiss"),f.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,h?.id??"dismiss")}),c.appendChild(f),i.appendChild(c),n){let b=document.createElement("div");b.className="bp-plan-revise",b.setAttribute("data-testid","plan-revise-drawer");let g=document.createElement("textarea");g.rows=2,g.className="bp-input bp-plan-revise-input",g.placeholder=m("gpui.ask.plan.reviseph","What should change in the plan?"),g.value=this.planReviseDrafts.get(e.id)??"";let y=document.createElement("button");y.type="button",y.className="bp-plan-revise-send",y.setAttribute("data-testid","plan-revise-send"),y.textContent=m("gpui.ask.plan.sendrev","Send revision"),y.disabled=g.value.trim().length===0;let w=()=>{let N=g.value.trim();if(!N)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${N}`)},x=()=>{this.closePlanRevise()};b.addEventListener("keydown",(N)=>{if(N.key==="Escape")N.preventDefault(),N.stopPropagation(),x()}),g.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,g.value),y.disabled=g.value.trim().length===0}),g.addEventListener("keydown",(N)=>{if(N.key==="Enter"&&!N.shiftKey)N.preventDefault(),w()}),y.addEventListener("click",w);let A=document.createElement("button");A.type="button",A.className="bp-btn-ghost",A.textContent=m("common.cancel","Cancel"),A.addEventListener("click",x),b.append(g,y,A),i.appendChild(b)}}else{let c=document.createElement("div");c.className="bp-ask-answered",c.textContent=m("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(c)}return i}}var ii={claude:{viewBox:"0 0 24 24",d:"m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z"},codex:{viewBox:"0 0 256 260",d:"M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87l51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921l51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272l-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695l-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69l-1.535-.922l-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87l-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58L128.067 97.3l28.188 16.218v32.434l-28.086 16.218l-28.188-16.218l-.052-32.434Z"},grok:{viewBox:"0 0 24 24",d:"M9.497 15.122 L16.811 9.491 C17.169 9.215 17.682 9.323 17.852 9.751 C18.752 12.013 18.35 14.73 16.561 16.596 C14.772 18.462 12.283 18.871 10.007 17.939 L7.522 19.139 C11.087 21.68 15.416 21.052 18.121 18.229 C20.267 15.991 20.931 12.941 20.31 10.19 L20.315 10.196 C19.414 6.155 20.537 4.54 22.837 1.237 C22.891 1.159 22.946 1.08 23 1 L19.974 4.156 L19.974 4.146 L9.495 15.124 M7.987 16.49 C5.429 13.941 5.87 9.996 8.053 7.721 C9.667 6.037 12.313 5.35 14.622 6.361 L17.102 5.166 C16.655 4.829 16.082 4.467 15.425 4.213 C12.455 2.938 8.9 3.573 6.485 6.088 C4.163 8.51 3.433 12.234 4.687 15.411 C5.624 17.786 4.088 19.466 2.541 21.162 C1.993 21.763 1.443 22.364 1 23 L7.985 16.492"},muse:{viewBox:"0 0 24 24",d:"M10.73.032c-1.333 0-2.032 1.016-2.032 2.285 0 2.223 2.127 4.953 4.318 4.953 1.301 0 2-.953 2-2.254 0-2.254-2.095-4.984-4.286-4.984m8.413 2.984c-1.968 0-3.397 2.73-3.397 4.825 0 1.556.794 3.016 2.254 3.016 2 0 3.365-2.762 3.365-4.794 0-1.523-.762-3.047-2.222-3.047M4.857 4.159c-1.968 0-3.778 1.016-3.778 2.54 0 1.65 2.16 2.793 4.254 2.793 1.873 0 3.778-.92 3.778-2.508 0-1.682-2.159-2.825-4.254-2.825m-.222 6.476C2.413 10.635 0 13.175 0 15.397c0 1.301.825 2.159 2.095 2.159 2.19 0 4.603-2.508 4.603-4.794 0-1.27-.761-2.127-2.063-2.127m16.667.698c-2.223 0-5.016 1.62-5.016 3.651 0 1.238 1.047 2.19 2.698 2.19 2.159 0 5.016-1.587 5.016-3.682 0-1.302-1.08-2.159-2.698-2.159M7.619 16c-1.524 0-2.38 1.746-2.38 3.429 0 2.063 1.269 4.54 3.047 4.54 1.524 0 2.38-1.81 2.38-3.461C10.667 18.57 9.46 16 7.62 16m6.571 1.016c-1.333 0-2.476.667-2.476 2.032 0 2.095 2.667 4.063 4.92 4.063 1.366 0 2.54-.73 2.54-2.063 0-2.032-2.698-4.032-4.984-4.032"},antigravity:{viewBox:"0 0 24 24",d:"M20.197 20.618 C21.318 21.459 23 20.898 21.459 19.357 C16.834 14.873 17.815 2.541 12.07 2.541 C6.325 2.541 7.306 14.873 2.682 19.357 C1 21.038 2.822 21.459 3.943 20.618 C8.287 17.675 8.006 12.49 12.07 12.49 C16.134 12.49 15.853 17.675 20.197 20.618 Z"},opencode:{viewBox:"0 0 24 24",d:"M22 24H2V0h20zM17 4.8H7v14.4h10z"},pi:{viewBox:"0 0 24 24",d:"M0 0v24h6v-6h6v-6H6V6h6v6h6V0Zm18 12v12h6V12Z"},omp:{viewBox:"0 0 24 24",d:"M1.44 3.86 L22.56 3.86 C23 3.86 23 3.86 23 4.3 L23 6.06 C23 6.5 23 6.5 22.56 6.5 L1.44 6.5 C1 6.5 1 6.5 1 6.06 L1 4.3 C1 3.86 1 3.86 1.44 3.86 Z M4.74 6.5 L6.5 6.5 C6.94 6.5 6.94 6.5 6.94 6.94 L6.94 19.7 C6.94 20.14 6.94 20.14 6.5 20.14 L4.74 20.14 C4.3 20.14 4.3 20.14 4.3 19.7 L4.3 6.94 C4.3 6.5 4.3 6.5 4.74 6.5 Z M15.74 6.5 L17.5 6.5 C17.94 6.5 17.94 6.5 17.94 6.94 L17.94 13.32 C17.94 13.76 17.94 13.76 17.5 13.76 L15.74 13.76 C15.3 13.76 15.3 13.76 15.3 13.32 L15.3 6.94 C15.3 6.5 15.3 6.5 15.74 6.5 Z M15.08 14.64 L18.16 14.64 C18.82 14.64 18.82 14.64 18.82 15.3 L18.82 17.5 C18.82 18.16 18.82 18.16 18.16 18.16 L15.08 18.16 C14.42 18.16 14.42 18.16 14.42 17.5 L14.42 15.3 C14.42 14.64 14.42 14.64 15.08 14.64 Z"}};var Vt="http://www.w3.org/2000/svg",si=4,ai=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Ut(e){let t=document.createElementNS(Vt,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","15"),t.setAttribute("height","15"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Vt,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function pn(){return Ut(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"])}function ri(){return Ut(["M6 4l14 8-14 8z"])}function Ys(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{mark:"claude",glyph:"A",color:"#d97757",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{mark:"codex",glyph:"O",color:"#10a37f",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity")||t==="agy")return{mark:"antigravity",glyph:"G",color:"#4285f4",title:"Antigravity"};if(t.includes("grok"))return{mark:"grok",glyph:"X",color:"#6b7280",title:"Grok"};if(t.includes("muse"))return{mark:"muse",glyph:"M",color:"#8b5cf6",title:"Muse"};if(t.includes("opencode"))return{mark:"opencode",glyph:"C",color:"#2563eb",title:"OpenCode"};if(t.includes("omp")||t.includes("oh-my-pi"))return{mark:"omp",glyph:"Ω",color:"#c026d3",title:"Oh My Pi"};if(t==="pi"||t.startsWith("pi/")||t.startsWith("@pi"))return{mark:"pi",glyph:"π",color:"#db2777",title:"Pi"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}function Xs(e){let t=ii[e];if(!t||!t.d)return null;let n=document.createElementNS(Vt,"svg");n.setAttribute("viewBox",t.viewBox||"0 0 24 24"),n.setAttribute("width","14"),n.setAttribute("height","14"),n.setAttribute("fill","currentColor"),n.setAttribute("aria-hidden","true");let i=document.createElementNS(Vt,"path");return i.setAttribute("d",t.d),n.appendChild(i),n}class un{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=m("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let a=document.createElement("div");a.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),a.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.planChipBtn=document.createElement("button"),this.planChipBtn.type="button",this.planChipBtn.className="bp-plan-chip bp-hidden",this.planChipBtn.setAttribute("data-testid","composer-plan-chip"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planChipIconHost=document.createElement("span"),this.planChipIconHost.className="bp-plan-chip-ic",this.planChipIconHost.appendChild(pn()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=m("gpui.mgmt.plan.tab","Plan"),this.planChipBtn.append(this.planChipIconHost,this.planChipLbl),this.planChipBtn.addEventListener("click",()=>this.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let r=document.createElement("div");r.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",r.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(r,this.memoryText);let o=document.createElement("div");o.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=m("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",m("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(Ut(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=m("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",m("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(Ut(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=m("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=m("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),o.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(a,this.planChipBtn,this.memoryEl,o),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(l)=>{let p=l.clipboardData?.items;if(!p)return;let c=[];for(let u=0;u0)l.preventDefault(),this.addFiles(c)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(l)=>{if(this.popupMode!=="none"){let p=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(l.key==="ArrowDown"){l.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,p),this.renderPopup();return}if(l.key==="ArrowUp"){l.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,p))%Math.max(1,p),this.renderPopup();return}if(l.key==="Tab"||l.key==="Enter"&&!l.shiftKey&&this.shouldCompleteOnEnter()){l.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(l.key==="Escape"){l.preventDefault(),this.closePopup();return}}if(l.key==="Tab"&&l.shiftKey&&this.planMode!==null){l.preventDefault(),this.cb.onCyclePlanMode?.();return}if(l.key==="Enter"&&!l.shiftKey)l.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=Ys(t),s=i.mark?Xs(i.mark):null;if(s)this.providerMarkEl.replaceChildren(s);else this.providerMarkEl.textContent=i.glyph;if(this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` -`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=m("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let a=`${m("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=a,this.planChipBtn.setAttribute("aria-label",a),this.planChipIconHost.replaceChildren(s?ri():pn()),this.planChipLbl.textContent=s?m("gpui.planmode.chip.building","Building"):t==="pending"?m("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?m("gpui.planmode.chip.once","Plan · 1t"):m("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?m("gpui.mgmt.plan.tab","Plan"):m("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let r=document.createElement("span");r.className="bp-plan-bar-ic",r.appendChild(s?ri():pn());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?m("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?m("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?m("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?m("gpui.planmode.bar.pending","Proposed plan awaits review below"):m("gpui.planmode.bar.executing","Building the approved plan");let l=[r,o];if(t==="armed"||t==="planning"){let p=document.createElement("div");p.className="bp-plan-scopes";let c=(u,d,h,f)=>{let b=document.createElement("button");return b.type="button",b.className="bp-plan-scope-btn"+(d?" active":""),b.textContent=u,b.disabled=!this.enabled,b.setAttribute("data-testid",f),b.addEventListener("click",()=>this.cb.onSetPlanMode?.(h)),b};p.append(c(m("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),c(m("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),c(m("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),l.push(p)}this.planBarEl.replaceChildren(...l)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let a=document.createElement("span");if(a.className="bp-reply-strip-line",a.textContent=m("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,a),t)i.addEventListener("click",t);let r=document.createElement("button");r.type="button",r.className="icon bp-reply-strip-drop",r.textContent="×";let o=m("reply.cancel","Cancel reply");if(r.title=o,r.setAttribute("aria-label",o),r.setAttribute("data-testid","composer-reply-drop"),n)r.addEventListener("click",n);this.replyEl.replaceChildren(i,r),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} -${t}`:e,this.autoGrow(),this.textarea.focus()}showError(e,t){let n=document.createElement("span");if(n.textContent=pe(e),t){let i=document.createElement("button");i.type="button",i.className="bp-composer-err-act",i.setAttribute("data-testid","composer-err-accounts"),i.textContent=t.label,i.addEventListener("click",t.onClick),this.errorEl.replaceChildren(n,i)}else this.errorEl.replaceChildren(n);this.errorEl.classList.remove("bp-hidden")}clearError(){this.errorEl.replaceChildren(),this.errorEl.classList.add("bp-hidden")}focus(){this.textarea.focus()}refreshLocale(){this.textarea.placeholder=m("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=m("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",m("web.composer.attach","Attach image")),this.voiceBtn.title=m("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",m("web.composer.voice","Voice dictation")),this.sendBtn.textContent=m("composer.send","Send"),this.stopBtn.textContent=m("composer.stop","Stop"),this.setPlanMode(this.planMode)}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` -`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.desc||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.detail||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),a=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=a+s,this.textarea.selectionStart=this.textarea.selectionEnd=a.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!ai.has(t.type)){this.showError(m("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=si){this.showError(m("web.composer.maximages","At most {max} images per message.",{max:si}));break}let n=await new Promise((s,a)=>{let r=new FileReader;r.onload=()=>s(String(r.result||"")),r.onerror=()=>a(Error("read failed")),r.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let a=document.createElement("button");a.type="button",a.className="icon bp-attach-rm",a.textContent="×",a.title=m("common.remove","Remove"),a.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,a),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function oi(e,t=fetch){let n=await t("/auth/web/logout",{method:"POST",credentials:"same-origin",redirect:"error",headers:{"Content-Type":"application/json"},body:"{}"});if(n.status!==200||(await n.json()).state!=="revoked")throw Error("Logout was not confirmed");e()}var Zs=new Set(["bom","checks","life","plan","fab"]);function Wt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&Zs.has(t.id))}function hi(e){let t=e?.badge?.n??0;if(!Number.isFinite(t)||t<=0)return null;return{text:t>99?"99+":String(Math.floor(t)),tone:e?.badge?.tone==="bad"?"bad":"warn"}}function _t(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=r}return i}function dt(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function pt(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var Qs=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),ea=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function mi(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let r of i)if(Qs.has(r))return r;let s=i[0]??"",a=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(ea.has(a)){let r=s.split("-");if(r.length>=2&&/^\d+$/.test(r[1]))return`${r[0]}-${r[1]}`;return r[0]}return i.slice(0,2).join("_")}function bi(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${dt(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${dt(n)}`,tone:"warn"};return{text:dt(n),tone:"ok"}}function gi(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((a)=>a==="dnp"&&Boolean(i.dnp)||s.includes(a))})}function fi(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function mn(e){if(e==="active")return{label:"Active",tone:"ok"};if(e==="nrnd")return{label:"NRND",tone:"warn"};if(e==="eol")return{label:"EOL",tone:"bad"};return{label:"Unknown",tone:"faint"}}function zt(e){if(!Number.isFinite(e)||e<=0)return"";let t=new Date(e*1000),n=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0");return`${n}-${i}-${s}`}function vi(e){return e.state==="routed"||e.state==="verified"}function yi(e){switch(e.state){case"approved":return"✓";case"edited":return"✎";case"verified":return"✓✓";case"routed":return"100%";case"rejected":case"failed":return"✗";case"routing":return typeof e.routed==="number"&&typeof e.total==="number"&&e.total>0?`${e.routed}/${e.total}`:"…";case"blocked":return`⚠ ${Math.max(1,e.problems??1)}`;default:return""}}function wi(e){switch(e.status){case"blocked":return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};case"routing":return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};case"awaiting":return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};case"verified":return{key:"gpui.mgmt.plan.st.verified",label:"Verified",tone:"ok"};case"routed":return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};case"ready":return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};case"partial":return{key:"gpui.mgmt.plan.st.partial",label:"Partial",tone:"warn"};case"rejected":return{key:"gpui.mgmt.plan.st.rejected",label:"Rejected",tone:"bad"};default:if((e.blocked??0)>0)return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(e.routing)return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if((e.awaiting??0)>0)return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}}function Ei(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,a=0;if(typeof e.total!=="number"){for(let r of e.layers??[])for(let o of r.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")a+=1;else if(o.state==="approved")n+=1}else if(e.routing)a=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:a,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function Ci(e){switch(e){case"current":return{text:"The fab's limits are in the DRC rules",button:null};case"stale":return{text:"The DRC rules have older fab limits",button:"Update"};case"none":return{text:"The fab's limits are not in the DRC rules",button:"Write"};default:return{text:"No KiCad project for DRC rules",button:null}}}function xi(e){return e==="extra"?"costs-more limits":"base-price limits"}function bn(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function ki(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function gn(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var li=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],ci=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function Si(e){let t=2166136261;for(let n=0;n>>0;return t}function Lt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#5a7a9a"&&n!=="#8a8a8a")return t;let i=e.toUpperCase();if(i.includes("3V3A")||i.includes("AVDD")||i.includes("VDDA"))return"#38bdf8";if(i.includes("1V8")||i.includes("1.8V"))return"#c084fc";if(i.includes("2V5")||i.includes("2.5V"))return"#a3e635";if(i.includes("3V3")||i.includes("3.3V")||i.includes("VCC"))return"#f59e0b";if(i.includes("5V")||i.startsWith("+5"))return"#ef4444";if(i.includes("12V")||i.includes("24V"))return"#f97316";if(i.includes("VBAT")||i.includes("VIN"))return"#ec4899";if(i.includes("GND"))return"#2dd4bf";return li[Si(i)%li.length]}function ut(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return ci[Si(e)%ci.length]}function Ai(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),a=Math.max(1,Math.abs(e[3]-e[1])),r=Math.max(20,t-i*2),o=Math.max(20,n-i*2),l=Math.max(0.05,Math.min(200,Math.min(r/s,o/a)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:l,fitted:l,touched:!1}}function Ve(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function qt(e,t,n,i,s){let a=Math.max(0.0001,e.scale);return[e.cx+(t-i*0.5)/a,e.cy+(n-s*0.5)/a]}function Li(e,t,n){let i=Math.max(0.0001,e.scale);return{...e,cx:e.cx-t/i,cy:e.cy-n/i,touched:!0}}function Pi(e,t,n,i,s,a){let r=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),l=Math.max(r,Math.min(o,e.scale*t)),[p,c]=qt(e,n,i,s,a);return{...e,cx:p-(n-s*0.5)/l,cy:c-(i-a*0.5)/l,scale:l,touched:!0}}function Ni(e,t,n,i){let s=e.map((r)=>[r[0],r[1]]);if(s.length===0)return[n];let a=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(a,0,[n[0],n[1]]),s}function fn(e,t,n){let i=n?3:2;if(e.length<=i||t<0||t>=e.length)return null;let s=e.map((a)=>[a[0],a[1]]);return s.splice(t,1),s}function ta(e,t,n,i,s,a){let r=s-n,o=a-i,l=r*r+o*o;if(l<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let p=Math.max(0,Math.min(1,((e-n)*r+(t-i)*o)/l)),c=n+p*r,u=i+p*o;return(e-c)*(e-c)+(t-u)*(t-u)}function di(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,a=n.length-1;st!==p>t&&e<(l-r)*(t-o)/(p-o+0.000000000001)+r)i=!i}return i}function vn(e,t){return Math.max(5,Math.min(32,e*t))}function Kt(e,t,n,i,s,a,r,o,l){if(i){for(let d of e){if(d.layer!==n||d.id!==i||d.locked)continue;let h=d.path??[];for(let f=0;f=3)for(let f=0;f=0;d--){let h=t[d];if(h.layer!==n)continue;let f=h.outline??[];if(!di(c,u,f))continue;if(!(h.holes??[]).some((g)=>di(c,u,g)))return{kind:"region",id:h.id}}return null}function ht(e){let t=null,n=null,i=[];for(let a of e){if(!a.layer)continue;i.push(a.layer);let r=a.items??[],o=r.filter((p)=>p.kind==="corridor").length,l=r.filter((p)=>p.kind==="plane").length;if((o>0||a.role==="signal")&&(!t||o>t.count))t={count:o,layer:a.layer};if((l>0||a.role==="power"||a.role==="plane")&&(!n||l>n.count))n={count:l,layer:a.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let a of i){if(s.length>=2)break;if(!s.includes(a))s.push(a)}return s}function pi(e,t){if(!e||e.length===0)return null;if(e.length===1)return e[0];let n=Math.max(0,Math.min(1,t)),i=0;for(let r=1;r=s&&o>0.000000001){let l=(s-a)/o;return[e[r-1][0]+(e[r][0]-e[r-1][0])*l,e[r-1][1]+(e[r][1]-e[r-1][1])*l]}a+=o}return e[e.length-1]}function st(e,t,n){for(let i of t??[])if(i.layer===e&&i.title)return i.title;for(let i of n??[])if(i.layer===e&&i.title)return i.title;return e}function Mi(e,t,n){if(e==="split"&&n.length>0)return t.filter((i)=>n.includes(i.layer));return t}function hn(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function ui(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,a=n.length-1;st!==p>t&&e<(l-r)*(t-o)/(p-o+0.000000000001)+r)i=!i}return i}function Ti(e,t){if(e.length<3)return null;let n=1/0,i=1/0,s=-1/0,a=-1/0,r=0,o=0;for(let p of e)n=Math.min(n,p[0]),i=Math.min(i,p[1]),s=Math.max(s,p[0]),a=Math.max(a,p[1]),r+=p[0],o+=p[1];let l=[[(n+s)*0.5,(i+a)*0.5],[r/e.length,o/e.length]];for(let p of[0.5,0.25,0.75,0.125,0.875])for(let c of[0.5,0.25,0.75,0.125,0.875])l.push([n+(s-n)*c,i+(a-i)*p]);for(let p of l)if(ui(p[0],p[1],e)&&!t.some((c)=>ui(p[0],p[1],c)))return p;return null}function Bi(e,t,n,i,s,a){let r=[];for(let c of e){let u=c.nets??0,d=c.path??[];if(u<=0||d.length<2)continue;let h=0;for(let f=1;f{let d=c.sel||c.hov?1:0,h=u.sel||u.hov?1:0;if(h!==d)return h-d;if(u.nets!==c.nets)return u.nets-c.nets;return c.b.id.localeCompare(u.b.id)});let o=[],l=[],p=(c,u,d,h,f)=>[c-d*0.5-f,u-h*0.5-f,c+d*0.5+f,u+h*0.5+f];for(let c of r){let u=c.b.name||"",d=String(c.nets),h=u?`${u} · ${c.nets}`:d,f=(c.sel||c.hov||c.pxLen>=95)&&u?[h,d]:[d],b=null,g=(w,x)=>Math.max(x*0.5+3,Math.min(Math.max(x*0.5+3,n-x*0.5-3),w)),y=(w,x)=>Math.max(x*0.5+3,Math.min(Math.max(x*0.5+3,i-x*0.5-3),w));e:for(let w of f){let x=Math.max(16,w.length*5.9+10),A=15;for(let N of[0.5,0.35,0.65,0.22,0.78]){let S=pi(c.pts,N);if(!S)continue;let[M,B]=Ve(t,S[0],S[1],n,i),R=g(M,x),V=y(B,15),D=p(R,V,x,15,2);if(!o.some((re)=>hn(D,re))){b={id:c.b.id,text:w,cx:R,cy:V,pw:x,ph:15,col:c.col,sel:c.sel};break e}}}if(!b){let w=pi(c.pts,0.5);if(w){let[x,A]=Ve(t,w[0],w[1],n,i),N=Math.max(16,d.length*6.5+8),S=15,M=g(x,N);for(let B of[-18,18]){let R=y(A+B,15);if(!o.some((V)=>hn(p(M,R,N,15,2),V))){b={id:c.b.id,text:d,cx:M,cy:R,pw:N,ph:15,col:c.col,sel:c.sel};break}}}}if(b)o.push(p(b.cx,b.cy,b.pw,b.ph,2)),l.push(b)}return l}function Ii(e,t,n,i,s,a=[]){let r=new Set(s),o=[];for(let c of e){if(!c.r||!c.b||c.b.length!==4)continue;let[u,d]=Ve(t,c.b[0],c.b[1],n,i),[h,f]=Ve(t,c.b[2],c.b[3],n,i),b=Math.abs(h-u),g=Math.abs(f-d);if(b<13||g<9)continue;let y=(u+h)*0.5,w=(d+f)*0.5;if(y<8||y>n-8||w<8||w>i-8)continue;o.push({text:c.r,cx:y,cy:w,bw:c.r.length*5.8+4,bh:11,score:b*g+(r.has(c.r)?1e4:0)})}o.sort((c,u)=>u.score-c.score);let l=[...a],p=[];for(let c of o){let u=[c.cx-c.bw*0.5,c.cy-c.bh*0.5,c.cx+c.bw*0.5,c.cy+c.bh*0.5];if(!l.some((h)=>hn(u,h)))l.push(u),p.push({text:c.text,cx:c.cx,cy:c.cy})}return p}function Ri(e){if(!e||typeof e!=="object")return null;let t=e;if(t.panel&&typeof t.panel==="object")return t.panel;if(t.result&&typeof t.result==="object"){let n=t.result.panel;if(n&&typeof n==="object")return n}return null}function Jt(e,t){if(!t||t.length===0)return e;let n=new Map;for(let a of e)if(a.layer)n.set(a.layer,a);let i=[],s=new Set;for(let a of t){if(!a.layer)continue;s.add(a.layer);let r=n.get(a.layer);if(r)i.push(r);else i.push({layer:a.layer,index:a.index,title:a.title||`L${a.index} · ${a.layer}`,subtitle:a.subtitle||"",role:a.role,status:"proposed",done:0,approved:0,total:0,items:[]})}for(let a of e)if(a.layer&&!s.has(a.layer))i.push(a);return i}function ji(e,t,n,i,s,a,r,o){return e===t&&n===i&&s===a&&(o===void 0||r>=o)}var Di="#111917",na="#16201d",ia="rgba(212, 224, 219, 0.92)",sa="rgba(61, 80, 73, 0.72)",aa="rgba(82, 107, 97, 0.85)";var Hi="#f59e0b",ra="#eef5f2",Fi="#ef4444";function at(e,t){let n=e.trim().replace(/^#/,"");if(n.length===6){let i=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),a=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(a))return`rgba(${i}, ${s}, ${a}, ${t})`}return`rgba(20, 184, 166, ${t})`}function oa(e,t,n){let i=0.14,s=0.45,a=0.85,r=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,a=0.91;break;case"edited":i=0.2,s=0.56,a=0.95;break;case"routed":case"verified":i=0.08,s=0.26,a=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,a=0.27;break;case"blocked":i=0.18,s=0.48,a=0.88,r=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),a=1;else if(n)i=Math.min(0.28,i+0.06),s=Math.min(0.63,s+0.07);return{glow:i,body:s,core:a,bad:r}}function la(e,t,n){let i=0.27,s=0.83,a=!1;switch(e){case"approved":case"routing":i=0.36,s=0.91;break;case"edited":i=0.38,s=0.95;break;case"routed":case"verified":i=0.16,s=0.54;break;case"rejected":case"failed":i=0.08,s=0.27;break;case"blocked":i=0.31,s=0.94,a=!0;break}if(t)i=Math.min(0.53,i+0.12),s=1;else if(n)i=Math.min(0.45,i+0.06),s=Math.min(1,s+0.1);return{fill:i,edge:s,bad:a}}function ca(e){let t=e.items??[];if(t.some((n)=>n.state==="blocked"||n.state==="failed"))return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(t.some((n)=>n.state==="routing"))return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if(t.some((n)=>n.state==="proposed"||n.state==="edited"))return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};if(t.length>0&&t.every((n)=>n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};if(t.length>0&&t.every((n)=>n.state==="approved"||n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}class yn{root;cb;state=null;cards=new Map;renderedLayerKey="";sharedCam=null;layerCams=new Map;hover=null;selectedVertex=null;drag=null;downPos=null;rafPending=0;constructor(e){this.cb=e,this.root=document.createElement("div"),this.root.className="bp-plan-canvas-grid",this.root.tabIndex=0,this.root.setAttribute("data-testid","mgmt-plan-canvas-grid"),this.root.addEventListener("keydown",(t)=>this.onKeyDown(t))}isDragging(){return this.drag!==null}fitAll(){this.sharedCam=null,this.layerCams.clear(),this.scheduleDraw()}destroy(){if(this.rafPending)cancelAnimationFrame(this.rafPending),this.rafPending=0;for(let e of this.cards.values())e.ro.disconnect();this.cards.clear(),this.root.replaceChildren()}visibleLayers(e){let t=Jt(e.layers,e.copperLayers);if(t.length===0)return[];if(e.gridMode==="all")return t;if(e.gridMode==="single"){let s=e.shownLayers.find((r)=>t.some((o)=>o.layer===r))??ht(t)[0]??t[0]?.layer,a=t.find((r)=>r.layer===s);return a?[a]:[]}let n=e.shownLayers.length>0&&e.shownLayers.every((s)=>t.some((a)=>a.layer===s))?e.shownLayers.slice(0,2):ht(t),i=[];for(let s of n){let a=t.find((r)=>r.layer===s);if(a)i.push(a)}return i.length>0?i:t.slice(0,2)}update(e,t){this.state=e;let n=this.visibleLayers(e);this.root.classList.toggle("two-cols",t&&n.length>1);let i=n.map((s)=>s.layer).join("|");if(i!==this.renderedLayerKey){this.renderedLayerKey=i;for(let s of this.cards.values())s.ro.disconnect();this.cards.clear(),this.root.replaceChildren();for(let s of n){let a=this.buildCard(s);this.cards.set(s.layer,a),this.root.appendChild(a.el)}}else for(let s of n){let a=this.cards.get(s.layer);if(a)this.syncCardHeaderAndLegend(a,s)}this.scheduleDraw()}effectiveBbox(e){let t=e.bbox;if(!t||t.length!==4||Math.abs(t[2]-t[0])<0.5||Math.abs(t[3]-t[1])<0.5)return[0,0,100,70];return t}getCam(e,t,n){let i=this.state,s=i?.syncZoom?this.sharedCam:this.layerCams.get(e)??null;if(s&&s.touched)return s;return Ai(i?this.effectiveBbox(i.board):[0,0,100,70],t,n,14)}setCam(e,t){if(this.state?.syncZoom)this.sharedCam=t;else this.layerCams.set(e,t)}buildCard(e){let t=document.createElement("section");t.className="bp-plan-card",t.setAttribute("data-testid",`mgmt-plan-card-${e.layer}`);let n=document.createElement("div");n.className="bp-plan-card-head";let i=document.createElement("div");i.className="bp-plan-card-head-top";let s=document.createElement("span"),a=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((w)=>w.kind==="plane");s.className="bp-plan-card-bar "+(a?"pwr":"sig");let r=document.createElement("span");r.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn bp-plan-mini-btn",l.textContent="✓",l.title=m("gpui.mgmt.plan.layer","Approve layer"),l.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let p=document.createElement("button");p.type="button",p.className="bp-mgmt-btn bp-plan-mini-btn",p.textContent="✗",p.title=m("gpui.mgmt.plan.rejectlayer","Reject layer"),p.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,r,o,l,p);let c=document.createElement("div");c.className="bp-plan-card-sub",n.append(i,c);let u=document.createElement("div");u.className="bp-plan-card-canvas-wrap";let d=document.createElement("canvas");d.className="bp-plan-card-canvas",d.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let h=document.createElement("div");h.className="bp-plan-hover-hud bp-hidden",u.append(d,h);let f=document.createElement("div");f.className="bp-plan-legend bp-hidden",t.append(n,u,f);let b=d.getContext("2d"),g=new ResizeObserver(()=>this.scheduleDraw());g.observe(u),this.attachPointerListeners(d,e.layer);let y={layer:e.layer,el:t,canvas:d,ctx:b,legendEl:f,okBtn:l,noBtn:p,statusEl:o,titleEl:r,subtitleEl:c,hoverHudEl:h,ro:g};return this.syncCardHeaderAndLegend(y,e),y}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=st(t.layer,this.state?.copperLayers,this.state?.layers)||t.title||t.layer;let n=t.subtitle||t.stackup||"";e.subtitleEl.textContent=n,e.subtitleEl.classList.toggle("bp-hidden",!n);let i=t.items??[],s=ca(t);e.statusEl.className=`bp-plan-card-status tone-${s.tone==="warn"?"dim":s.tone}`,e.statusEl.textContent=i.length>0?m(s.key,s.label):"",e.statusEl.classList.toggle("bp-hidden",i.length===0);let a=i.some((o)=>o.state==="proposed"||o.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!a);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!a);let r=(this.state?.regions??[]).filter((o)=>o.layer===t.layer);if(r.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let o=document.createDocumentFragment();for(let l of r){let p=document.createElement("button");p.type="button";let c=this.state?.selectedId===l.id;p.className="bp-plan-legend-chip"+(c?" active":"");let u=document.createElement("span");u.className="bp-plan-legend-sw",u.style.background=Lt(l.net||l.id,l.color||"");let d=document.createElement("span");d.textContent=l.net||l.id,p.append(u,d),p.addEventListener("click",()=>{this.cb.onSelect(l.id),this.cb.onFocusItem(l.id)}),o.appendChild(p)}e.legendEl.replaceChildren(o)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(i)=>i.preventDefault()),e.addEventListener("dblclick",()=>this.fitAll()),e.addEventListener("pointerdown",(i)=>{let s=this.state;if(!s)return;this.root.focus({preventScroll:!0});let a=e.getBoundingClientRect(),r=i.clientX-a.left,o=i.clientY-a.top,l=Math.max(1,a.width),p=Math.max(1,a.height),c=this.getCam(t,l,p),u=Kt(s.bands,s.regions,t,s.selectedId,c,l,p,r,o);if(i.button===2){if(u?.kind==="vertex"){let d=this.getItemPts(u.id,u.isPlane),h=fn(d,u.idx,u.isPlane);if(h)this.selectedVertex=null,this.cb.onCommitFields(u.id,{[u.isPlane?"outline":"path"]:h})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},u?.kind==="vertex"){let d=this.getItemPts(u.id,u.isPlane),h=d.map((f)=>[f[0],f[1]]);this.selectedVertex={id:u.id,idx:u.idx},this.drag={layer:t,kind:"vertex",id:u.id,isPlane:u.isPlane,idx:u.idx,pts:d.map((f)=>[f[0],f[1]]),origPts:h,moved:!1},this.scheduleDraw()}else if(u?.kind==="midpoint"){let d=this.getItemPts(u.id,u.isPlane),h=d.map((g)=>[g[0],g[1]]),f=Ni(d,u.segIdx,u.pos,u.isPlane),b=u.isPlane&&u.segIdx+1>=d.length?f.length-1:Math.min(u.segIdx+1,f.length-1);this.selectedVertex={id:u.id,idx:b},this.patchLocalItem(u.id,u.isPlane,f),this.drag={layer:t,kind:"vertex",id:u.id,isPlane:u.isPlane,idx:b,pts:f,origPts:h,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:r,lastY:o}}),e.addEventListener("pointermove",(i)=>{let s=this.state;if(!s)return;let a=e.getBoundingClientRect(),r=i.clientX-a.left,o=i.clientY-a.top,l=Math.max(1,a.width),p=Math.max(1,a.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let A=this.getCam(t,l,p);this.setCam(t,Li(A,r-this.drag.lastX,o-this.drag.lastY)),this.drag.lastX=r,this.drag.lastY=o,this.scheduleDraw();return}if(this.downPos&&Math.hypot(i.clientX-this.downPos.x,i.clientY-this.downPos.y)<1.5&&!this.drag.moved)return;let b=this.getCam(t,l,p),[g,y]=qt(b,r,o,l,p),w=[Math.round(g*1000)/1000,Math.round(y*1000)/1000];this.drag.moved=!0,this.drag.pts[this.drag.idx]=w;let x=this.drag.pts.map((A)=>[A[0],A[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,x),this.scheduleDraw();return}let c=this.getCam(t,l,p),u=Kt(s.bands,s.regions,t,s.selectedId,c,l,p,r,o),d=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",h=this.hover?.hit.kind??"",f=u?u.id:"";if(this.hover=u?{layer:t,hit:u}:null,e.style.cursor=u?"pointer":"crosshair",d!==f||(u?.kind??"")!==h)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()});let n=()=>{let i=this.drag;if(!i||i.layer!==t)return;if(this.drag=null,this.downPos=null,i.kind==="vertex"&&i.moved){let s=i.origPts.map((a)=>[a[0],a[1]]);this.patchLocalItem(i.id,i.isPlane,s)}this.cb.onDragEnd?.(),this.scheduleDraw()};e.addEventListener("pointercancel",n),e.addEventListener("lostpointercapture",n),e.addEventListener("pointerup",(i)=>{let s=this.state,a=this.drag,r=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(i.pointerId))e.releasePointerCapture(i.pointerId);if(a&&a.kind==="vertex"&&a.layer===t){if(a.moved)this.cb.onCommitFields(a.id,{[a.isPlane?"outline":"path"]:a.pts});else this.cb.onDragEnd?.(),this.scheduleDraw();return}if(s&&r&&Math.hypot(i.clientX-r.x,i.clientY-r.y)<4.5){let o=e.getBoundingClientRect(),l=i.clientX-o.left,p=i.clientY-o.top,c=Math.max(1,o.width),u=Math.max(1,o.height),d=this.getCam(t,c,u),h=Kt(s.bands,s.regions,t,s.selectedId,d,c,u,l,p);if(h&&(h.kind==="band"||h.kind==="region")){this.cb.onSelect(h.id),this.cb.onFocusItem(h.id);return}if(!h&&s.selectedId){this.cb.onSelect("");return}}this.cb.onDragEnd?.()}),e.addEventListener("wheel",(i)=>{i.preventDefault();let s=e.getBoundingClientRect(),a=i.clientX-s.left,r=i.clientY-s.top,o=Math.max(1,s.width),l=Math.max(1,s.height),p=this.getCam(t,o,l),c=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,Pi(p,c,a,r,o,l)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((a)=>a.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((a)=>a.id===e);if(s){if(s.path=n,s.edited=!0,s.state==="proposed")s.state="edited"}}}getItemPts(e,t){let n=this.state;if(!n)return[];if(t)return(n.regions.find((i)=>i.id===e)?.outline??[]).map((i)=>[i[0],i[1]]);return(n.bands.find((i)=>i.id===e)?.path??[]).map((i)=>[i[0],i[1]])}syncHoverHud(e){let t=this.cards.get(e),n=this.state;if(!t||!n)return;if(!this.hover||this.hover.layer!==e){t.hoverHudEl.classList.add("bp-hidden"),t.hoverHudEl.textContent="";return}let i=this.hover.hit.id,s=n.bands.find((o)=>o.id===i),a=n.regions.find((o)=>o.id===i),r="";if(s)r=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(a)r=a.reference?`${a.net||i} · ${a.reference}`:a.net||i;if(!r)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=r}onKeyDown(e){let t=this.state;if(!t)return;if(e.key==="0"||e.key==="Home"){e.preventDefault(),this.fitAll();return}if(e.key==="Escape"){this.selectedVertex=null,this.cb.onSelect("");return}if(!t.selectedId)return;let n=t.bands.find((r)=>r.id===t.selectedId),i=t.regions.find((r)=>r.id===t.selectedId),s=Boolean(n?.locked??i?.locked),a=e.key.toLowerCase();if(a==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(a==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(a==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(a==="w"&&n&&!s){e.preventDefault();let r=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+r))*100)/100;this.cb.onCommitFields(t.selectedId,{width:o})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let r=Boolean(i),o=this.getItemPts(t.selectedId,r),l=fn(o,this.selectedVertex.idx,r);if(l)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[r?"outline":"path"]:l})}}scheduleDraw(){if(this.rafPending)return;this.rafPending=requestAnimationFrame(()=>{this.rafPending=0,this.drawAll()})}drawAll(){let e=this.state;if(!e)return;let t=Math.max(0.45,Math.min(1.25,Math.abs(this.effectiveBbox(e.board)[3]-this.effectiveBbox(e.board)[1])/Math.max(1,Math.abs(this.effectiveBbox(e.board)[2]-this.effectiveBbox(e.board)[0]))));for(let n of this.cards.values()){let i=n.canvas.parentElement;if(!i)continue;let s=Math.max(120,Math.round(i.clientWidth)),a=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${a}px`;let r=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*r),l=Math.round(a*r);if(n.canvas.width!==o||n.canvas.height!==l)n.canvas.width=o,n.canvas.height=l;n.ctx.setTransform(r,0,0,r,0,0),this.drawLayer(n.ctx,n.layer,s,a,e)}}drawLayer(e,t,n,i,s){let a=this.getCam(t,n,i),r=(b,g)=>Ve(a,b,g,n,i);e.fillStyle=Di,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((b)=>b.length>=3);if(e.fillStyle=na,o.length>0){e.beginPath();for(let b of o){for(let g=0;gb.layer===t),p=this.hover?.layer===t?this.hover.hit:null;for(let b of l){let g=b.outline??[];if(g.length<3)continue;let y=s.selectedId===b.id,w=p?.id===b.id,x=la(b.state||"proposed",y,w),A=Lt(b.net||b.id,b.color||"");e.beginPath();for(let S=0;SB)B=D;if(re>R)R=re}if(Math.abs(B-S)>=38&&Math.abs(R-M)>=18){let V=Ti(g,b.holes??[]);if(V){let[D,re]=r(V[0],V[1]);e.fillStyle=at(A,y?0.91:0.67),e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(N,D,re)}}}}if(e.strokeStyle=ia,e.lineWidth=1.25,e.lineCap="round",e.lineJoin="round",o.length>0){e.beginPath();for(let b of o){for(let g=0;gb.layer===t),d=Bi(u,a,n,i,s.selectedId,p?.id??""),h=d.map((b)=>[b.cx-b.pw*0.5-1,b.cy-b.ph*0.5-1,b.cx+b.pw*0.5+1,b.cy+b.ph*0.5+1]),f=[];for(let b of u){for(let g of b.from??[])f.push(g);for(let g of b.to??[])f.push(g)}e.fillStyle="rgba(143, 163, 155, 0.72)",e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let b of Ii(c,a,n,i,f,h))e.fillText(b.text,b.cx,b.cy);for(let b of u){let g=b.guides??[];if(g.length===0)continue;let y=s.selectedId===b.id||p?.id===b.id,w=ut(b.name||b.id,b.color||"");e.strokeStyle=at(w,y?0.38:0.17),e.lineWidth=y?1:0.7,e.beginPath();for(let x of g){let[A,N]=r(x[0],x[1]),[S,M]=r(x[2],x[3]);e.moveTo(A,N),e.lineTo(S,M)}e.stroke()}for(let b of u){let g=b.path??[];if(g.length<2)continue;let y=s.selectedId===b.id,w=p?.id===b.id,x=oa(b.state||"proposed",y,w),A=ut(b.name||b.id,b.color||""),N=vn(b.width??1.5,a.scale),S=()=>{e.beginPath();for(let M=0;M{let w=y?g.length:Math.max(0,g.length-1);for(let x=0;xn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return Wt(this.getStateInfo())}isOpen(){return this.openPanel!==""}closePanel(){if(!this.openPanel)return;if(this.openPanel="",this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:""}).catch(()=>{});this.render()}clear(){this.watchGen++,this.bomEditGen++,this.askedProject="",this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydrateGen++,this.planHydratedRev=void 0,this.planRenderDeferred=!1,this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.render()}async watchProject(e){if(!e||!this.cb.hub.hasFeature("mgmt")){this.clear();return}if(e===this.askedProject&&this.digest){this.render();return}let t=++this.watchGen;if(this.askedProject=e,this.project!==e)this.bomEditGen++,this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomSelectedId="",this.bomEditingId="",this.bomEditStatus="",this.bomLastUndo=null,this.checksSelectedId="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydrateGen++,this.planHydratedRev=void 0,this.planRenderDeferred=!1,this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.lifeSelectedKey="",this.lifePartSamples=null,this.render();try{let n=await this.cb.hub.rpc("mgmt.watch",{project:e});if(t!==this.watchGen)return;let i=typeof n.digest==="string"?n.digest:"";if(!i){this.render();return}if(this.digest=i,this.project=typeof n.project==="string"&&n.project?n.project:e,n.state&&typeof n.state==="object")this.infos.set(`mgmt.state.${i}`,n.state);if(n.data&&typeof n.data==="object"){for(let[s,a]of Object.entries(n.data))if(a&&typeof a==="object")this.infos.set(`mgmt.${s}.${i}`,a)}this.errorMsg="",this.render()}catch{if(t===this.watchGen)this.render()}}handleInfo(e){let t=!1;for(let[n,i]of Object.entries(e)){if(!n.startsWith("mgmt.")&&!n.startsWith("kicad.checks."))continue;if(i===""||i===null||i===void 0){if(this.infos.delete(n))t=!0;continue}if(typeof i==="string")try{let s=JSON.parse(i);if(s&&typeof s==="object")this.infos.set(n,s),t=!0}catch{}else if(typeof i==="object")this.infos.set(n,i),t=!0}if(t)this.render()}getStateInfo(){if(!this.digest)return null;return this.infos.get(`mgmt.state.${this.digest}`)??null}getPanelData(e){if(!this.digest)return null;return this.infos.get(`mgmt.${e}.${this.digest}`)??null}togglePanel(e){let t=this.openPanel===e?"":e;if(this.openPanel=t,this.errorMsg="",this.render(),this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:t}).catch((n)=>{this.errorMsg=n instanceof Error?n.message:"Could not update panel",this.render()})}render(){if(this.openPanel==="plan"&&this.planCanvas?.isDragging()){this.planRenderDeferred=!0;return}this.planRenderDeferred=!1;let e=this.getStateInfo(),t=Wt(e);if(!this.digest||t.length===0){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let r of t){let o=document.createElement("button");o.type="button";let l=this.openPanel===r.id;o.className="bp-mgmt-tab"+(l?" active":""),o.setAttribute("data-testid",`mgmt-tab-${r.id}`),o.setAttribute("aria-pressed",l?"true":"false");let p=document.createElement("span");p.textContent=pe(r.label),o.appendChild(p);let c=this.getPanelData(r.id),u=hi(c);if(u){let d=document.createElement("span");d.className=`bp-mgmt-badge bp-tone-${u.tone}`,d.textContent=u.text,o.appendChild(d)}o.addEventListener("click",()=>this.togglePanel(r.id)),i.appendChild(o)}if(n.appendChild(i),this.openPanel){let r=document.createElement("button");r.type="button",r.className="icon bp-mgmt-close",r.textContent="×",r.title=m("gpui.mgmt.close","Close the panel"),r.setAttribute("aria-label",m("gpui.mgmt.close","Close the panel")),r.setAttribute("data-testid","mgmt-close"),r.addEventListener("click",()=>this.closePanel()),n.appendChild(r)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}if(this.openPanel!=="plan")this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded");else this.panelEl.classList.toggle("bp-plan-expanded",this.planExpanded);this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=this.openPanel==="plan"&&this.planCanvas!==null&&document.activeElement instanceof HTMLElement&&this.panelEl.contains(document.activeElement)&&(document.activeElement===this.planCanvas.root||this.planCanvas.root.contains(document.activeElement)),a=document.createDocumentFragment();if(this.errorMsg){let r=document.createElement("div");r.className="bp-mgmt-note bp-tone-bad",r.textContent=this.errorMsg,a.appendChild(r)}switch(this.openPanel){case"bom":a.appendChild(this.renderBom());break;case"checks":a.appendChild(this.renderChecks());break;case"life":a.appendChild(this.renderLife());break;case"plan":a.appendChild(this.renderPlan());break;case"fab":a.appendChild(this.renderFab());break}if(this.panelEl.replaceChildren(a),s)this.planCanvas?.root.focus({preventScroll:!0})}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let a=document.createElement("span"),r=t.source==="kicad";if(a.className="bp-mgmt-pill"+(r?" accent":""),a.textContent=r?"live":"saved",i.append(s,a),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let p=document.createElement("span");p.className="bp-dim",p.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${pt(t.cost)}/board`:`${pt(t.cost)}/board`,i.appendChild(p)}if(t.paused){let p=document.createElement("span");p.className="bp-mgmt-faint",p.textContent="Stock check paused",i.appendChild(p)}if(e.appendChild(i),t.stock_note){let p=document.createElement("div");p.className="bp-mgmt-note bp-mgmt-faint",p.textContent=pe(t.stock_note),e.appendChild(p)}let o=this.bomEditingId?n.find((p)=>p.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let p=document.createElement("div");p.className="bp-mgmt-filter-row";let c=document.createElement("input");c.type="text",c.className="bp-mgmt-filter",c.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",c.value=this.bomFilter,c.setAttribute("data-testid","mgmt-bom-filter"),c.addEventListener("input",()=>{this.bomFilter=c.value,this.renderBomRows(l,n)}),p.appendChild(c),e.appendChild(p)}let l=document.createElement("div");return l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(l,n),e.appendChild(l),e}renderBomRows(e,t){let n=gi(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((a)=>Boolean(a.mpn)||Boolean(a.fab)),s=document.createDocumentFragment();for(let a of n){let r=Array.isArray(a.refs)?a.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===a.id?" active":"")+(a.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${a.id}`);let l=document.createElement("div");l.className="bp-mgmt-row-line";let p=document.createElement("span");if(p.className="bp-mgmt-strong bp-mgmt-flex1",p.textContent=_t(r,24),l.appendChild(p),a.dnp){let b=document.createElement("span");b.className="bp-mgmt-pill",b.textContent=m("gpui.mgmt.bom.dnp","DNP"),l.appendChild(b)}else{let b=bi(a.stock);if(b){let g=document.createElement("span");g.className=`bp-tone-${b.tone}`,g.textContent=b.text,l.appendChild(g)}}let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn",c.textContent="Edit",c.addEventListener("click",(b)=>{b.stopPropagation(),this.bomEditGen++,this.bomEditingId=a.id,this.bomEditDraft=a.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),l.appendChild(c);let u=document.createElement("div");u.className="bp-mgmt-row-sub";let d=[`${a.qty??r.length}×`,a.value??"",mi(a.footprint??"")].filter(Boolean).join(" · "),h=document.createElement("span");h.className="bp-dim",h.textContent=d;let f=document.createElement("span");if(f.className="bp-mgmt-flex1",a.mpn)f.textContent=a.mpn;else if(i&&!a.dnp)f.className+=" bp-tone-warn",f.textContent=m("gpui.mgmt.bom.nompn","no MPN");if(u.append(h,f),!a.dnp&&typeof a.stock?.price==="number"){let b=document.createElement("span");b.className="bp-dim",b.textContent=pt(a.stock.price),u.appendChild(b)}if(!a.dnp&&a.stock?.class){let b=document.createElement("span");b.className="bp-mgmt-faint",b.textContent=pe(a.stock.class),u.appendChild(b)}o.append(l,u),o.addEventListener("click",()=>{this.bomSelectedId=a.id,this.renderBomRows(e,t)}),s.appendChild(o)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=_t(n,30);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,a);let r=document.createElement("input");r.type="text",r.className="bp-mgmt-filter",r.placeholder="MPN",r.value=this.bomEditDraft,r.addEventListener("input",()=>{this.bomEditDraft=r.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),l=async(d,h=!1)=>{let f=o();this.bomEditStatus="Writing…",this.render();try{let b=await this.cb.hub.rpc("mgmt.bom.edit",d);if(!bn(f,o()))return;this.bomLastUndo=!h&&(b.changed??0)>0?{project:d.project,editId:f.editId,refs:d.refs.slice(),field:d.field,was:typeof b.was==="string"?b.was:d.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=h?"Restored":(b.changed??0)===0?"No change":b.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(b){if(!bn(f,o()))return;this.bomEditStatus=b instanceof Error?b.message:"Could not save edit"}this.render()},p=document.createElement("div");p.className="bp-mgmt-btn-row";let c=document.createElement("button");c.type="button",c.className="primary bp-mgmt-btn",c.textContent="Save MPN",c.addEventListener("click",()=>{l({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let u=document.createElement("button");if(u.type="button",u.className="bp-mgmt-btn",u.textContent=e.dnp?"Clear DNP":"Mark DNP",u.addEventListener("click",()=>{l({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),p.append(c,u),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let d=this.bomLastUndo,h=document.createElement("button");h.type="button",h.className="bp-mgmt-btn",h.textContent="Undo",h.addEventListener("click",()=>{l(ki(d),!0)}),p.appendChild(h)}if(t.append(i,r,p),this.bomEditStatus){let d=document.createElement("div");d.className="bp-mgmt-faint",d.textContent=this.bomEditStatus,t.appendChild(d)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((d)=>d.source).filter(Boolean))),s=(d)=>t.sources?.[d]?.label||d.toUpperCase(),a=(d)=>t.sources?.[d]?.judged===!0,r=document.createElement("div");r.className="bp-mgmt-head bp-mgmt-scroll-x";let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),o.textContent=m("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),r.appendChild(o);for(let d of i){let h=document.createElement("button");h.type="button",h.className="bp-mgmt-btn"+(this.checksSource===d?" active":""),h.textContent=s(d)+(a(d)?" · judged":""),h.addEventListener("click",()=>{this.checksSource=this.checksSource===d?"":d,this.render()}),r.appendChild(h)}let l=document.createElement("span");l.className="bp-mgmt-flex1";let p=document.createElement("button");if(p.type="button",p.className="bp-mgmt-btn",p.textContent=m("gpui.mgmt.checks.run","Run"),p.addEventListener("click",()=>{let d=this.watchGen,h=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:h}).then(()=>{if(d!==this.watchGen||h!==this.project)return;this.checksStatus="",this.render()}).catch((f)=>{if(d!==this.watchGen||h!==this.project)return;this.checksStatus=f instanceof Error?f.message:"Could not run checks",this.render()})}),r.append(l,p),e.appendChild(r),this.checksStatus){let d=document.createElement("div");d.className="bp-mgmt-note bp-dim",d.textContent=this.checksStatus,e.appendChild(d)}let c=document.createElement("div");c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-checks-rows");let u=fi(n,this.checksSource);if(u.length===0)c.appendChild(this.makeEmpty("No check findings."));else for(let d of u){let h=d.severity==="error"?"bad":d.severity==="warning"?"warn":"faint",f=document.createElement("div");f.className="bp-mgmt-group-head";let b=document.createElement("span");b.className=`bp-mgmt-dot bp-tone-bg-${h}`;let g=document.createElement("span");g.className="bp-mgmt-flex1",g.textContent=`${s(d.source)} · ${d.rule}`;let y=document.createElement("span");y.className=`bp-tone-${h}`,y.textContent=String(d.n),f.append(b,g,y),c.appendChild(f);for(let w of d.rows??[]){let x=document.createElement("div");x.className="bp-mgmt-row"+(this.checksSelectedId===w.id?" active":"");let A=document.createElement("div");if(A.textContent=pe(w.title??""),x.appendChild(A),w.names||this.checksSelectedId===w.id){let N=document.createElement("div");N.className="bp-mgmt-row-sub";let S=document.createElement("span");if(S.className="bp-dim bp-mgmt-flex1",S.textContent=w.names??"",N.appendChild(S),this.checksSelectedId===w.id){let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn accent",M.textContent=m("gpui.mgmt.checks.fix","Fix with agent"),M.addEventListener("click",(B)=>{B.stopPropagation();let R={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:R.project,id:w.id}).then((V)=>{let D={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!gn(R,D))return;if(V.text)this.cb.onSendText(V.text),this.checksStatus="Sent to agent",this.render()}).catch((V)=>{let D={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!gn(R,D))return;this.checksStatus=V instanceof Error?V.message:"Could not send finding",this.render()})}),N.appendChild(M)}x.appendChild(N)}x.addEventListener("click",()=>{this.checksSelectedId=w.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:w.id}).catch(()=>{}),this.render()}),c.appendChild(x)}}return e.appendChild(c),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let l of["active","nrnd","eol"]){let p=i[l]??0,c=mn(l),u=document.createElement("span");u.className=p>0?`bp-tone-${c.tone}`:"bp-mgmt-faint",u.textContent=`${c.label} ${p}`,n.appendChild(u)}if((i.unknown??0)>0){let l=document.createElement("span");l.className="bp-mgmt-faint",l.textContent=`${i.unknown} unknown`,n.appendChild(l)}if(t.since){let l=document.createElement("span");l.className="bp-mgmt-flex1";let p=document.createElement("span");p.className="bp-mgmt-faint",p.textContent=`since ${zt(t.since)} (${t.samples??0})`,n.append(l,p)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let a=t.bom?.cost??[],r=t.bom?.instock??[],o=t.bom?.lines??0;if(a.length===0)s.appendChild(this.makeEmpty(o===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let l=a[a.length-1],p=r[r.length-1],c=document.createElement("div");c.className="bp-mgmt-note bp-dim",c.textContent=`Parts/board: ${pt(l[1])} · ${Math.round(p?.[1]??0)}/${o} lines in stock (${zt(l[0])})`,s.appendChild(c)}for(let l of t.parts??[]){let p=this.lifeSelectedKey===l.key,c=mn(l.lifecycle??"unknown"),u=document.createElement("div");u.className="bp-mgmt-row"+(p?" active":"");let d=document.createElement("div");d.className="bp-mgmt-row-line";let h=document.createElement("span");h.className="bp-mgmt-strong",h.textContent=_t(l.refs??[],14);let f=document.createElement("span");f.className="bp-mgmt-flex1 bp-dim",f.textContent=l.mpn||l.key;let b=document.createElement("span");if(b.className=`bp-tone-${c.tone}`,b.textContent=c.label,d.append(h,f,b),typeof l.stock==="number"){let g=document.createElement("span");g.className="bp-dim",g.textContent=dt(l.stock),d.appendChild(g)}if(u.appendChild(d),p){let g=document.createElement("div");if(g.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)g.textContent=m("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let y=this.lifePartSamples[this.lifePartSamples.length-1];g.textContent=`${this.lifePartSamples.length} samples · latest ${y.at?zt(y.at):""}`+(typeof y.stock==="number"?` · stock ${dt(y.stock)}`:"")+(typeof y.price==="number"?` · ${pt(y.price)}`:"")}else g.textContent=m("gpui.mgmt.life.nopart","No reading of this part yet.");u.appendChild(g)}u.addEventListener("click",()=>{if(this.lifeSelectedKey===l.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=l.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:l.key}).then((g)=>{if(this.lifeSelectedKey!==l.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(g.samples)?g.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==l.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(u)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(m("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(E,k)=>{let j=this.watchGen,T=this.project;this.planStatus="",this.cb.hub.rpc(E,{pro:T,...k}).catch((q)=>{if(j!==this.watchGen||T!==this.project)return;this.planOptimistic.clear(),this.planStatus=q instanceof Error?q.message:m("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydrateAskedKey!==i&&this.project){this.planHydrateAskedKey=i;let E=this.watchGen,k=++this.planHydrateGen,j=this.project,T=t.revision??0;this.cb.hub.rpc("plan.get",{pro:j,board:!0}).then((q)=>{let te=Ri(q);if(!te)return;let H=typeof te.revision==="number"?te.revision:T;if(!ji(E,this.watchGen,k,this.planHydrateGen,j,this.project,H,this.planHydratedRev))return;this.planHydratedRev=H,this.planHydratedKey=`${j}:${H}`,this.planHydratedBoard=te.board??null,this.planHydratedDraw=te.draw??null,this.render()}).catch(()=>{})}let s=t.on===!0,a=document.createElement("div");a.className="bp-plan-header";let r=document.createElement("div");r.className="bp-plan-toggle";let o=document.createElement("span");o.className="bp-mgmt-strong",o.textContent=m("gpui.mgmt.plan.before","Plan before routing"),o.title=s?m("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):m("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here."),r.appendChild(o);let l=t.awaiting??0,p=t.blocked??0,c=t.done??0,u=t.total??0,d=t.revision??0,h=t.empty?[]:Ei(t),f=h.reduce((E,k)=>E+k.count,0);if(!t.empty){let E=wi(t),k=document.createElement("span");if(k.className=`bp-plan-status-badge tone-${E.tone}`,k.textContent=m(E.key,E.label),r.appendChild(k),d>0){let T=document.createElement("span");T.className="bp-dim",T.textContent=`v${d}`,r.appendChild(T)}let j=document.createElement("span");if(j.className="bp-plan-header-counts bp-mgmt-flex1 "+(l>0?"bp-tone-warn":p>0?"bp-tone-bad":"bp-dim"),j.textContent=u>0?`${c}/${u} ${m("gpui.mgmt.plan.done","done")}`:l>0?m("web.plan.awaiting","{n} awaiting approval",{n:l}):m("gpui.mgmt.plan.nothing","Nothing awaits your approval"),r.appendChild(j),!t.live){let T=document.createElement("span");T.className="bp-mgmt-pill",T.textContent=m("gpui.mgmt.plan.saved","saved plan"),r.appendChild(T)}}else{let E=document.createElement("span");E.className="bp-mgmt-flex1",r.appendChild(E)}let b=document.createElement("button");b.type="button",b.className="bp-mgmt-btn bp-plan-chip-btn"+(s?" active":""),b.setAttribute("data-testid","mgmt-plan-on"),b.setAttribute("aria-pressed",s?"true":"false"),b.textContent=m("gpui.bots.recall.on","On"),b.addEventListener("click",()=>n("plan.enable",{on:!0}));let g=document.createElement("button");if(g.type="button",g.className="bp-mgmt-btn bp-plan-chip-btn"+(!s?" active":""),g.setAttribute("data-testid","mgmt-plan-off"),g.setAttribute("aria-pressed",!s?"true":"false"),g.textContent=m("gpui.bots.recall.off","Off"),g.addEventListener("click",()=>n("plan.enable",{on:!1})),r.append(b,g),a.appendChild(r),f>0){let E=document.createElement("div");E.className="bp-plan-segbar";for(let k of h){if(k.count<=0)continue;let j=document.createElement("div");j.className=`bp-plan-seg bp-tone-bg-${k.tone}`,j.style.flexGrow=String(k.count),E.appendChild(j)}a.appendChild(E)}e.appendChild(a);for(let E of t.elsewhere??[]){let k=document.createElement("div");k.className="bp-plan-elsewhere";let j=document.createElement("span");j.className="bp-tone-warn bp-mgmt-flex1",j.textContent=m("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:E.name||E.rel||""}),k.appendChild(j),e.appendChild(k)}if(t.empty){let E=document.createElement("div");E.className="bp-mgmt-note";let k=document.createElement("div");k.className="bp-dim",k.textContent=m("gpui.mgmt.plan.noboard","No routing plan for this board.");let j=document.createElement("div");return j.className="bp-mgmt-faint",j.textContent=m("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),E.append(k,j),e.appendChild(E),e}let y=t.stackup_summary??"",w=Array.isArray(t.impedances)?t.impedances:[],x=Boolean(y)||w.length>0,A=document.createElement("div");if(A.className="bp-mgmt-head",l>0){let E=document.createElement("button");E.type="button",E.className="primary bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-approve-all"),E.textContent=m("gpui.mgmt.plan.all","Approve all"),E.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),A.appendChild(E)}if(t.routing){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-stop"),E.textContent=m("gpui.mgmt.plan.stop","Stop routing"),E.addEventListener("click",()=>n("plan.stop",{})),A.appendChild(E)}if(t.live&&c>0){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-verify"),E.textContent=m("gpui.mgmt.plan.verify","Verify"),E.addEventListener("click",()=>n("plan.verify",{})),A.appendChild(E)}let N=document.createElement("span");if(N.className="bp-mgmt-flex1",A.appendChild(N),x){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn bp-plan-chip-btn"+(this.planStackupOpen?" active":""),E.setAttribute("data-testid","mgmt-plan-stackup-toggle"),E.setAttribute("aria-expanded",this.planStackupOpen?"true":"false"),E.textContent=`${m("gpui.mgmt.plan.stackup.short","Stackup")} ${this.planStackupOpen?"▾":"▸"}`,E.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),A.appendChild(E)}let S=document.createElement("button");S.type="button",S.className="bp-mgmt-btn",S.setAttribute("data-testid","mgmt-plan-hide"),S.textContent=this.planHideDone?m("gpui.mgmt.plan.show","Show done"):m("gpui.mgmt.plan.hide","Hide done"),S.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),A.appendChild(S),e.appendChild(A);let M=Array.isArray(t.asks)?t.asks:[];if(M.length>0){let E=M.map((te)=>te.what||"").filter(Boolean).join(", "),k=M[0]?.note||"",j=document.createElement("div");j.className="bp-plan-elsewhere";let T=document.createElement("div");T.className="bp-plan-ask-col";let q=document.createElement("div");if(q.className="bp-tone-warn",q.textContent=E?m("gpui.mgmt.plan.requested","Approval requested: {what}",{what:E}):m("gpui.mgmt.plan.reqplain","Approval requested"),T.appendChild(q),k){let te=document.createElement("div");te.className="bp-dim",te.textContent=k,T.appendChild(te)}j.appendChild(T),e.appendChild(j)}if(this.planStatus){let E=document.createElement("div");E.className="bp-mgmt-note bp-plan-err bp-tone-bad";let k=document.createElement("span");k.className="bp-mgmt-flex1",k.textContent=this.planStatus==="KiCad refused"?m("gpui.mgmt.plan.refused","KiCad refused"):pe(this.planStatus);let j=document.createElement("button");j.type="button",j.className="icon",j.textContent="×",j.title=m("common.close","Close"),j.addEventListener("click",()=>{this.planStatus="",this.render()}),E.append(k,j),e.appendChild(E)}if(t.keys_note){let E=document.createElement("div");E.className="bp-mgmt-note bp-dim";let k="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";E.textContent=t.keys_note===k?m("gpui.mgmt.plan.keysnote",k):pe(t.keys_note),e.appendChild(E)}if(x&&this.planStackupOpen){let E=document.createElement("div");if(E.className="bp-plan-stackup-body",E.setAttribute("data-testid","mgmt-plan-stackup-body"),y){let k=document.createElement("div");k.className="bp-dim",k.textContent=y,E.appendChild(k)}for(let k of w){let j=document.createElement("div");j.className="bp-mgmt-faint",j.textContent=`· ${k}`,E.appendChild(j)}e.appendChild(E)}let B=(E,k,j,T)=>{let q=document.createElement("button");return q.type="button",q.className="bp-mgmt-btn bp-plan-chip-btn"+(k?" active":""),q.setAttribute("data-testid",j),q.setAttribute("aria-pressed",k?"true":"false"),q.textContent=E,q.addEventListener("click",T),q},R=document.createElement("div");if(R.className="bp-plan-viewbar",R.append(B(m("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),B(m("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),B(m("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let E=document.createElement("span");E.className="bp-plan-sep";let k=document.createElement("span");k.className="bp-plan-sep";let j=document.createElement("button");j.type="button",j.className="bp-mgmt-btn bp-plan-mini-btn",j.setAttribute("data-testid","mgmt-plan-fit"),j.textContent=m("gpui.mgmt.plan.fit","Fit"),j.addEventListener("click",()=>this.planCanvas?.fitAll()),R.append(E,B(m("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),B(m("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),B(m("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),k,B(m("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),j)}let V=document.createElement("span");V.className="bp-mgmt-flex1";let D=document.createElement("button");D.type="button",D.className="bp-mgmt-btn bp-plan-mini-btn",D.setAttribute("data-testid","mgmt-plan-expand"),D.textContent=this.planExpanded?m("gpui.mgmt.plan.compact","Compact"):m("gpui.mgmt.plan.expand","Expand"),D.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),R.append(V,D),e.appendChild(R);let re=Boolean(this.planHydratedBoard)&&this.planHydratedKey.startsWith(`${this.project}:`)&&(this.planHydratedKey===i||this.planHydratedRev!==void 0&&this.planHydratedRev>=(t.revision??0)),he=re&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},oe=re&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},we=(oe.bands??[]).map((E)=>{let k=this.planOptimistic.get(E.id);if(!k)return{...E};return{...E,...k,edited:!0,state:E.state==="proposed"?"edited":E.state}}),Ae=(oe.regions??[]).map((E)=>{let k=this.planOptimistic.get(E.id);if(!k)return{...E};return{...E,...k,edited:!0,state:E.state==="proposed"?"edited":E.state}}),Me=[],me=(t.layers??[]).map((E)=>{let k=[];for(let j of E.items??[]){let T=this.planOptimistic.get(j.id);if(!T){k.push(j);continue}let q={...j,width:typeof T.width==="number"?T.width:j.width,locked:typeof T.locked==="boolean"?T.locked:j.locked,edited:!0,state:j.state==="proposed"?"edited":j.state};if(typeof T.layer==="string"&&T.layer!==E.layer)Me.push({target:T.layer,item:q});else k.push(q)}return{...E,items:k}});for(let E of Me){let k=me.find((j)=>j.layer===E.target);if(k)k.items=[...k.items??[],E.item]}let be=Jt(me,t.copper_layers),I=this.planGridMode==="all"?be.map((E)=>E.layer):this.planGridMode==="single"?[this.planShownLayers.find((E)=>be.some((k)=>k.layer===E))??ht(be)[0]??be[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((E)=>be.some((k)=>k.layer===E))?this.planShownLayers.slice(0,2):ht(be);if(this.planViewMode!=="list"&&this.planGridMode!=="all"&&be.length>1){let E=document.createElement("div");E.className="bp-plan-layerbar";for(let k of be){let j=I.includes(k.layer),T=(k.items??[]).length,q=st(k.layer,t.copper_layers,be)||k.title||k.layer,te=T>0?`${q} · ${T}`:q,H=B(te,j,`mgmt-plan-layerpill-${k.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[k.layer];else if(this.planGridMode==="pair"){if(!I.includes(k.layer))this.planShownLayers=I.length>=2?[I[0],k.layer]:[...I,k.layer]}else this.planGridMode="single",this.planShownLayers=[k.layer];this.render()});if(T===0&&!j)H.classList.add("empty-layer");E.appendChild(H)}e.appendChild(E)}let le=(E,k)=>{let j=this.planOptimistic.get(E)??{};if(this.planOptimistic.set(E,{...j,...k}),typeof k.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[k.layer];else if(this.planGridMode==="pair"&&!I.includes(k.layer))this.planShownLayers=I.length>=2?[I[0],k.layer]:[...I,k.layer]}let T=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:E,fields:k}],...T!==void 0?{base:T}:{}})};if(this.planCommitFields=le,this.planSelectedId){let E="",k=null;for(let j of me){let T=(j.items??[]).find((q)=>q.id===this.planSelectedId);if(T){E=j.layer,k=T;break}}if(k){let j=st(E,t.copper_layers,be),T=document.createElement("div");T.className="bp-plan-inspector",T.setAttribute("data-testid","mgmt-plan-inspector");let q=document.createElement("div");q.className="bp-plan-ins-row";let te=document.createElement("span");te.className="bp-plan-ins-sw",te.style.background=k.kind==="corridor"?ut(k.name||k.id,k.color||""):Lt(k.name||k.id,k.color||"");let H=document.createElement("span");H.className="bp-mgmt-strong",H.textContent=k.name||k.id;let K=document.createElement("span");if(K.className="bp-dim",K.textContent=j,q.append(te,H,K),k.edited||k.state==="edited"){let Y=document.createElement("span");Y.className="bp-plan-ins-pill warn",Y.textContent=m("gpui.mgmt.plan.edited","Edited"),q.appendChild(Y)}if(k.locked){let Y=document.createElement("span");Y.className="bp-plan-ins-pill",Y.textContent=m("gpui.mgmt.plan.locked","Locked"),q.appendChild(Y)}let je=document.createElement("span");je.className="bp-mgmt-flex1",q.appendChild(je);let Le=document.createElement("button");if(Le.type="button",Le.className="bp-mgmt-btn bp-plan-mini-btn",Le.setAttribute("data-testid","mgmt-plan-lock"),Le.textContent=k.locked?m("gpui.mgmt.plan.unlock","Unlock"):m("gpui.mgmt.plan.lock","Lock"),Le.addEventListener("click",()=>le(k.id,{locked:!k.locked})),q.appendChild(Le),k.state==="proposed"||k.state==="edited"){let Y=document.createElement("button");Y.type="button",Y.className="primary bp-mgmt-btn bp-plan-mini-btn",Y.textContent=m("android.hub.machines.approve","Approve"),Y.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[k.id],approve:!0}));let ve=document.createElement("button");ve.type="button",ve.className="bp-mgmt-btn bp-plan-mini-btn",ve.textContent=m("gpui.mgmt.plan.reject","Reject"),ve.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[k.id],approve:!1})),q.append(Y,ve)}let ue=document.createElement("button");ue.type="button",ue.className="bp-mgmt-btn bp-plan-mini-btn",ue.setAttribute("data-testid","mgmt-plan-note-toggle"),ue.textContent=m("gpui.mgmt.plan.addnote","Add note"),ue.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let Pe=document.createElement("button");if(Pe.type="button",Pe.className="icon",Pe.textContent="×",Pe.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.render()}),q.append(ue,Pe),T.appendChild(q),!k.locked){let Y=document.createElement("div");if(Y.className="bp-plan-ins-row",k.kind==="corridor"){let ie=typeof k.width==="number"?k.width:1.5,ke=document.createElement("span");ke.className="bp-dim",ke.textContent=m("gpui.mgmt.plan.width","Width");let De=document.createElement("button");De.type="button",De.className="bp-mgmt-btn bp-plan-mini-btn",De.setAttribute("data-testid","mgmt-plan-w-down"),De.textContent="-",De.addEventListener("click",()=>{let Ue=Math.round(Math.max(0.15,ie-0.25)*100)/100;le(k.id,{width:Ue})});let ae=document.createElement("span");ae.className="bp-plan-ins-val",ae.textContent=`${ie.toFixed(2)}mm`;let ge=document.createElement("button");ge.type="button",ge.className="bp-mgmt-btn bp-plan-mini-btn",ge.setAttribute("data-testid","mgmt-plan-w-up"),ge.textContent="+",ge.addEventListener("click",()=>{let Ue=Math.round(Math.min(25,ie+0.25)*100)/100;le(k.id,{width:Ue})});let _e=document.createElement("span");_e.className="bp-plan-sep",Y.append(ke,De,ae,ge,_e)}let ve=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((ie)=>ie.layer):me.map((ie)=>ie.layer);if(ve.length>0){let ie=document.createElement("span");ie.className="bp-dim",ie.textContent=m("gpui.mgmt.plan.layer.short","Layer"),Y.appendChild(ie),Y.appendChild(B(`${j} ${this.planMoveLayerOpen?"▴":"▾"}`,this.planMoveLayerOpen,"mgmt-plan-move-toggle",()=>{this.planMoveLayerOpen=!this.planMoveLayerOpen,this.render()}))}if(T.appendChild(Y),this.planMoveLayerOpen&&ve.length>0){let ie=document.createElement("div");ie.className="bp-plan-ins-row";for(let ke of ve){let De=st(ke,t.copper_layers,be);ie.appendChild(B(De,ke===E,`mgmt-plan-move-${ke}`,()=>{if(this.planMoveLayerOpen=!1,ke!==E)le(k.id,{layer:ke});else this.render()}))}T.appendChild(ie)}}if(this.planNoteOpen){let Y=document.createElement("form");Y.className="bp-plan-note-form";let ve=document.createElement("input");ve.type="text",ve.className="bp-plan-note-input",ve.setAttribute("data-testid","mgmt-plan-note-input"),ve.placeholder=m("gpui.mgmt.plan.note.placeholder","Steering note for router…");let ie=document.createElement("button");ie.type="submit",ie.className="primary bp-mgmt-btn bp-plan-mini-btn",ie.setAttribute("data-testid","mgmt-plan-note-submit"),ie.textContent=m("gpui.mgmt.plan.addnote","Add note"),Y.append(ve,ie),Y.addEventListener("submit",(ke)=>{ke.preventDefault();let De=ve.value.trim();if(!De)return;ve.value="",this.planNoteOpen=!1;let ae=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:k.id,text:De}],...ae!==void 0?{base:ae}:{}})}),T.appendChild(Y)}if(this.planViewMode!=="list"&&!k.locked){let Y=document.createElement("div");Y.className="bp-plan-hint",Y.textContent=m("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),T.appendChild(Y)}e.appendChild(T)}}let ne=document.createElement("div");ne.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),ne.setAttribute("data-testid","mgmt-plan-rows");let X=m("gpui.mgmt.plan.done","done"),ce=Mi(this.planViewMode,me,I);if(this.planViewMode==="split"&&ce.length===0){let E=document.createElement("div");E.className="bp-dim",E.style.padding="6px 8px",E.style.fontSize="11px",E.textContent=m("gpui.mgmt.plan.noitems","No corridors or planes on this layer"),ne.appendChild(E)}for(let E of ce){let k=E.items??[],j=st(E.layer,t.copper_layers,be)||E.layer;if(this.planViewMode==="split"){if(ce.length>1){let T=document.createElement("div");T.className="bp-plan-split-divider";let q=E.role==="power"||E.role==="plane",te=document.createElement("span");te.className="bp-plan-card-bar "+(q?"pwr":"sig");let H=document.createElement("span");H.className="bp-mgmt-strong",H.textContent=j;let K=document.createElement("span");K.className="bp-dim",K.textContent=`${E.done??0}/${k.length} ${X}`,T.append(te,H,K),ne.appendChild(T)}}else{let T=document.createElement("div");T.className="bp-mgmt-group-head bp-plan-layer-head";let q=document.createElement("div");q.className="bp-mgmt-row-line";let te=document.createElement("span");te.className="bp-mgmt-strong",te.textContent=j;let H=document.createElement("span");if(H.className="bp-dim bp-mgmt-flex1",H.textContent=`${E.role?`${E.role} · `:""}${E.done??0}/${k.length} ${X}`,q.append(te,H),E.status!=="approved"&&k.length>0){let K=document.createElement("button");K.type="button",K.className="bp-mgmt-btn",K.textContent=m("gpui.mgmt.plan.layer","Approve layer"),K.addEventListener("click",()=>n("plan.approve",{layer:E.layer,ids:[],approve:!0}));let je=document.createElement("button");je.type="button",je.className="bp-mgmt-btn",je.textContent=m("gpui.mgmt.plan.reject","Reject"),je.addEventListener("click",()=>n("plan.approve",{layer:E.layer,ids:[],approve:!1})),q.append(K,je)}if(T.appendChild(q),E.stackup){let K=document.createElement("div");K.className="bp-plan-layer-stackup",K.textContent=E.stackup,T.appendChild(K)}ne.appendChild(T)}for(let T of k){if(this.planHideDone&&vi(T))continue;let q=this.planSelectedId===T.id,te=document.createElement("div");te.className="bp-mgmt-row bp-plan-row"+(q?" active":""),te.setAttribute("data-testid",`mgmt-plan-row-${T.id}`);let H=document.createElement("div");H.className="bp-mgmt-row-line";let K=document.createElement("span");K.className=`bp-plan-swatch bp-plan-st-${T.state||"proposed"}`,K.style.setProperty("--swatch-color",T.color||"#8a8a8a");let je=document.createElement("span");je.className="bp-mgmt-flex1"+(T.state==="blocked"||T.state==="failed"?" bp-tone-bad":T.state==="edited"?" bp-tone-warn":T.state==="rejected"||T.state==="routed"||T.state==="verified"?" bp-dim":""),je.textContent=`${T.name||T.id}${T.locked?" \uD83D\uDD12":""}`;let Le=[];if(T.kind==="plane"){if(T.reference)Le.push(m("gpui.mgmt.plan.reference","over {layer}",{layer:T.reference}))}else{let Y=T.nets??0;Le.push(Y===1?m("web.plan.net.one","1 net"):m("web.plan.nets","{n} nets",{n:Y}))}if(typeof T.width==="number"&&Number.isFinite(T.width))Le.push(`${T.width.toFixed(2)}mm`);if(T.impedance)Le.push(T.impedance);let ue=Le.join(" · "),Pe=document.createElement("span");if(Pe.className="bp-plan-mark "+(T.state==="blocked"||T.state==="failed"?"bp-tone-bad":T.state==="verified"||T.state==="routed"?"bp-tone-ok":T.state==="approved"?"bp-tone-accent":"bp-dim"),Pe.textContent=yi(T),H.append(K,je,Pe),T.state==="proposed"||T.state==="edited"){let Y=document.createElement("button");Y.type="button",Y.className="bp-mgmt-btn",Y.textContent="✓",Y.title=m("gpui.mgmt.plan.layer","Approve layer"),Y.addEventListener("click",(ie)=>{ie.stopPropagation(),n("plan.approve",{layer:"",ids:[T.id],approve:!0})});let ve=document.createElement("button");ve.type="button",ve.className="bp-mgmt-btn",ve.textContent="✗",ve.title=m("gpui.mgmt.plan.reject","Reject"),ve.addEventListener("click",(ie)=>{ie.stopPropagation(),n("plan.approve",{layer:"",ids:[T.id],approve:!1})}),H.append(Y,ve)}if(te.appendChild(H),ue){let Y=document.createElement("div");Y.className="bp-mgmt-row-sub bp-plan-detail bp-dim",Y.textContent=ue,te.appendChild(Y)}if(T.state==="routing"&&typeof T.total==="number"&&T.total>0){let Y=document.createElement("div");Y.className="bp-plan-microbar";let ve=document.createElement("div");ve.className="bp-plan-microbar-fill";let ie=Math.max(0,Math.min(100,Math.round((T.routed??0)/T.total*100)));ve.style.width=`${ie}%`,Y.appendChild(ve),te.appendChild(Y)}if(T.problem_text){let Y=document.createElement("div");Y.className="bp-plan-problem",Y.textContent=T.problem_text,te.appendChild(Y)}te.addEventListener("click",()=>{this.planSelectedId=T.id,n("plan.focus",{id:T.id}),this.render()}),ne.appendChild(te)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new yn({onSelect:(T)=>{if(this.planSelectedId=T,!T)this.planNoteOpen=!1;this.render()},onFocusItem:(T)=>{n("plan.focus",{id:T})},onDragEnd:()=>{if(this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onCommitFields:(T,q)=>{(this.planCommitFields??le)(T,q)},onApproveLayer:(T,q)=>{n("plan.approve",{layer:T,ids:[],approve:q})},onQuickApprove:(T,q)=>{n("plan.approve",{layer:"",ids:T,approve:q})}});let E=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,k=this.planExpanded||this.panelEl.clientWidth>=540||E;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:I,selectedId:this.planSelectedId,board:he,bands:we,regions:Ae,layers:be,copperLayers:t.copper_layers},k);let j=document.createElement("div");j.className="bp-plan-canvas-scroll",j.appendChild(this.planCanvas.root),e.appendChild(j)}if(this.planViewMode!=="canvas")e.appendChild(ne);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let E=document.createElement("div");E.className="bp-plan-footer",E.textContent=m("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(E)}return e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let w=document.createElement("div");return w.className="bp-mgmt-note bp-tone-warn",w.textContent=t.error,e.appendChild(w),e}let n=(w,x={})=>{let A=this.watchGen,N=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:N,action:w,...x}).catch((S)=>{if(A!==this.watchGen||N!==this.project)return;this.fabStatus=S instanceof Error?S.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=m("gpui.mgmt.fab.thefab","The fab");let a=document.createElement("span");a.className="bp-dim bp-mgmt-flex1",a.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${xi(t.tier??"")}`;let r=document.createElement("button");if(r.type="button",r.className="bp-mgmt-btn",r.textContent=m("gpui.mgmt.fab.refresh","Refresh"),r.addEventListener("click",()=>n("refresh")),i.append(s,a,r),e.appendChild(i),this.fabStatus){let w=document.createElement("div");w.className="bp-mgmt-note bp-tone-bad",w.textContent=this.fabStatus,e.appendChild(w)}let o=document.createElement("div");o.className="bp-mgmt-rows",o.setAttribute("data-testid","mgmt-fab-rows");let l=t.review,p=document.createElement("div");p.className="bp-mgmt-row";let c=document.createElement("div");c.className="bp-mgmt-row-line";let u=document.createElement("span"),d=(l?.counts?.error??0)>0;if(u.className="bp-mgmt-flex1 "+(d?"bp-tone-bad":"bp-dim"),u.textContent=l?.running?"Reviewing the design…":l?.at==null?"No design review yet":`${l.counts?.error??0} must-fix · ${l.counts?.warning??0} should-fix · ${l.counts?.info??0} notes${l.scope?` (${l.scope})`:""}`,c.appendChild(u),l?.at!=null){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=m("gpui.mgmt.fab.findings","Findings"),w.addEventListener("click",()=>this.togglePanel("checks")),c.appendChild(w)}if(!l?.running){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=m("gpui.mgmt.fab.reviewbtn","Review"),w.addEventListener("click",()=>n("review")),c.appendChild(w)}if(l?.judge){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=m("gpui.mgmt.fab.judge","Datasheets"),w.addEventListener("click",()=>{if(l.judge)this.cb.onSendText(l.judge)}),c.appendChild(w)}p.appendChild(c),o.appendChild(p);let h=Ci(t.drc?.state??""),f=document.createElement("div");f.className="bp-mgmt-row";let b=document.createElement("div");b.className="bp-mgmt-row-line";let g=document.createElement("span");if(g.className="bp-mgmt-flex1 "+(h.button?"bp-tone-warn":"bp-dim"),g.textContent=h.text,b.appendChild(g),h.button){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h.button,w.addEventListener("click",()=>n("drc")),b.appendChild(w)}f.appendChild(b),o.appendChild(f);for(let w of t.conflicts??[]){let x=document.createElement("div");x.className="bp-mgmt-row bp-tone-bad",x.textContent=w,o.appendChild(x)}for(let w of t.suggestions??[]){let x=document.createElement("div");x.className="bp-mgmt-row";let A=document.createElement("div");A.className="bp-mgmt-row-line";let N=document.createElement("span");N.className="bp-mgmt-flex1 bp-tone-warn",N.textContent=`${w.label||w.key}: board ${w.project??"?"} mm, fab ${w.fab??"?"} mm`;let S=document.createElement("button");S.type="button",S.className="bp-mgmt-btn",S.textContent=m("gpui.mgmt.fab.apply","Apply"),S.addEventListener("click",()=>n("apply",{key:w.key})),A.append(N,S),x.appendChild(A),o.appendChild(x)}if(t.stackup?.chosen){let w=document.createElement("div");w.className="bp-mgmt-row";let x=document.createElement("div");x.className="bp-mgmt-row-line";let A=t.stackup.by==="proposed",N=document.createElement("span");if(N.className="bp-mgmt-flex1 "+(A?"bp-tone-warn":"bp-dim"),N.textContent=`${A?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,x.appendChild(N),A){let S=t.stackup.chosen,M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=m("gpui.mgmt.fab.use","Use"),M.addEventListener("click",()=>n("stackup",{id:S})),x.appendChild(M)}w.appendChild(x),o.appendChild(w)}if(Array.isArray(t.changed)&&t.changed.length>0){let w=document.createElement("div");w.className="bp-mgmt-row";let x=document.createElement("div");x.className="bp-mgmt-row-line";let A=document.createElement("span");A.className="bp-mgmt-flex1 bp-tone-warn",A.textContent=m("gpui.mgmt.fab.changed","Changed since you last looked");let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.textContent=m("gpui.mgmt.fab.seen","Seen"),N.addEventListener("click",()=>n("seen")),x.append(A,N),w.appendChild(x);for(let S of t.changed.slice(0,12)){let M=document.createElement("div");M.className="bp-mgmt-faint",M.textContent=S,w.appendChild(M)}o.appendChild(w)}let y=Array.isArray(t.limits)?t.limits:[];if(y.length>0){let w=document.createElement("div");w.className="bp-mgmt-group-head";let x=document.createElement("span");x.className="bp-mgmt-flex1",x.textContent=m("gpui.mgmt.fab.limit","Limit");let A=document.createElement("span");A.className="bp-mgmt-col",A.textContent=m("gpui.mgmt.fab.free","Base price");let N=document.createElement("span");N.className="bp-mgmt-col",N.textContent=m("gpui.mgmt.fab.extra","Costs more");let S=document.createElement("span");S.className="bp-mgmt-col bp-mgmt-col-read",S.textContent=m("gpui.mgmt.fab.readcol","Read"),w.append(x,A,N,S),o.appendChild(w);for(let B of y){let R=document.createElement("div");R.className="bp-mgmt-row";let V=document.createElement("div");V.className="bp-mgmt-row-line";let D=document.createElement("span");D.className="bp-mgmt-flex1"+(B.changed?" bp-tone-warn":B.inherited?" bp-dim":""),D.textContent=`${B.changed?"• ":""}${B.label??""}`;let re=document.createElement("span");re.className="bp-mgmt-col",re.textContent=B.free?.text||"—";let he=document.createElement("span");he.className="bp-mgmt-col bp-dim",he.textContent=B.extra?.text||"—";let oe=B.free&&typeof B.free==="object"?B.free:B.extra,we=oe?.fetched??"",Ae=Boolean(we)&&oe?.confidence!=="published",Me=we?Ae?`${we}*`:we:"—",me=oe?.source??"",be;if(me.startsWith("https://")&&we){let I=document.createElement("a");I.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",I.href=me,I.target="_blank",I.rel="noopener noreferrer",I.textContent=Me,be=I}else{let I=document.createElement("span");I.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",I.textContent=Me,be=I}V.append(D,re,he,be),R.appendChild(V),o.appendChild(R)}let M=document.createElement("div");M.className="bp-mgmt-note bp-mgmt-faint",M.textContent=m("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(M)}return e.appendChild(o),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var da={trs:(e)=>e,t:(e,t)=>t},pa=new Set(["/settle"]);function $i(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((r)=>r.startsWith(n)))return 2;let a=0;for(let r=0;r0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function Oi(e){let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Vi(e,t){let n=t.trim().split(/\s+/)[0]?.toLowerCase()??"";if(!n)return null;let i=e.toLowerCase();if(i.length!==e.length)return null;let s=i.indexOf(n);if(s<0)return null;return[s,s+n.length]}function Ui(e,t=da){let{t:n,trs:i}=t,s=[],a=new Map;for(let o of e.projects)a.set(o.id,o.title||o.id);let r=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!r&&o.id!=="terminal")continue;s.push({label:i(o.label),place:o.id==="terminal"?"":"viewer",kind:"action",shortcut:o.key?o.key.toUpperCase():void 0,action:{type:"rail",id:o.id}})}if(r)s.push({label:r.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:r.pinned?"unpin":"pin"}}),s.push({label:r.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:r.settled?"unsettle":"settle"}}),s.push({label:r.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:r.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(r)for(let o of e.commands){if(!o.word)continue;let l=pa.has(o.word.toLowerCase());s.push({label:o.label?`${o.word} — ${o.label}`:o.word,place:o.desc||"command",kind:"command",action:{type:"command",word:o.word,runDirectly:l}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let o of e.projects)s.push({label:`New thread in ${o.title||o.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:o.id}});for(let o of e.threads){let{urgency:l,want:p}=Gi(o);s.push({label:o.title||"Untitled thread",place:o.project?a.get(o.project)??"":"",kind:"thread",urgency:l,want:p,dotClass:Oi(o),action:{type:"thread",id:o.id}})}for(let o of e.bots){if(!o.name||!o.thread)continue;s.push({label:o.name,place:"",kind:"bot",action:{type:"thread",id:o.thread}})}return s}function Wi(e,t,n,i=[],s=10,a=14){let r=t.trim(),o=r.length===0,l=e.slice();if(n?.threads&&n.threads.length>0){let d=new Map;for(let f of i)d.set(f.id,f.title||f.id);let h=new Set;for(let f of l)if(f.action.type==="thread")h.add(f.action.id);for(let f of n.threads){if(!f.id||h.has(f.id))continue;h.add(f.id);let{urgency:b,want:g}=Gi(f);l.push({label:f.title||"Untitled thread",place:f.project?d.get(f.project)??"":"",kind:"thread",urgency:b,want:g,dotClass:Oi(f),action:{type:"thread",id:f.id}})}}let p=[];for(let d=0;d0)p.push({score:g,index:d,item:h})}p.sort((d,h)=>{if(o){let g=(h.item.urgency??0)-(d.item.urgency??0);if(g!==0)return g}if(h.score!==d.score)return h.score-d.score;let f=d.item.kind==="thread"?0:1,b=h.item.kind==="thread"?0:1;if(f!==b)return f-b;return d.index-h.index});let c=new Set,u=[];for(let d of p){let h=`${d.item.label}\x00${d.item.place}\x00${d.item.kind}`;if(c.has(h))continue;if(c.add(h),u.push(d.item),u.length>=s)break}if(n?.messages&&n.messages.length>0&&u.length{if(r.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(r)=>{if(r.key==="Escape")r.preventDefault(),r.stopPropagation(),this.close();else if(r.key==="ArrowDown"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(r.key==="ArrowUp"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(r.key==="Enter")r.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=a,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=Ui(t,{t:m,trs:pe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=Wi(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let r=document.createElement("div");r.className="bp-palette-empty",r.textContent=m("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(r);return}let s=document.createDocumentFragment(),a=null;for(let r=0;r0)p.appendChild(document.createTextNode(o.label.slice(0,d)));let f=document.createElement("strong");if(f.className="bp-palette-mark",f.textContent=o.label.slice(d,h),p.appendChild(f),h{if(this.activeIdx!==r)this.activeIdx=r,this.updateActiveClass()}),l.addEventListener("click",()=>this.runAt(r)),r===this.activeIdx)a=l;s.appendChild(l)}if(this.listEl.replaceChildren(s),e&&a)a.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return a}render(){let e=this.items.filter((r)=>r.group!=="tools"),t=this.items.filter((r)=>r.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let r of e){if(i!==void 0&&r.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=r.group,n.appendChild(this.renderButton(r))}let s=()=>{let r=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let r=document.createElement("div");r.className="bp-rail-tools";for(let o of t)r.appendChild(this.renderButton(o));a.appendChild(r)}this.el.replaceChildren(a)}}var ma=new Set(["resume","raise","retry","move","signin"]);function Ki(e){if(!e||typeof e!=="object")return null;let t=e,n=(a)=>typeof a==="string"?a:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((a)=>Boolean(a)&&typeof a==="object").map((a)=>({label:n(a.label),act:n(a.act),room:n(a.room),thread:n(a.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function Yt(e,t){if(e.act==="board")return t&&e.room?{kind:"board",room:e.room}:null;if(e.act==="open")return e.thread?{kind:"thread",id:e.thread}:null;if(ma.has(e.act)){let n={room:e.room,action:e.act};if(e.thread)n.thread=e.thread;return{kind:"call",method:"swarm.act",params:n}}return null}function Ji(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}var Sn=[{id:"general",label:"General"},{id:"ai",label:"Agents and tools"},{id:"connect",label:"Connect"}],mt=[{id:"appearance",group:"general",title:"Appearance",subtitle:"Kept in this browser only. Never sent to the hub.",icon:"sun",keywords:["theme","dark","light","auto","color","language","locale","english","espanol","japanese"]},{id:"providers",group:"ai",title:"AI providers",subtitle:"Account sign-ins live in the desktop or mobile app.",icon:"cpu",keywords:["accounts","claude","codex","antigravity","grok","openai","anthropic","signin","login","model"]},{id:"devices",group:"connect",title:"Devices & browser",subtitle:"This browser session and paired devices on this hub.",icon:"link",keywords:["sign out","logout","session","cookie","revoke","paired","phone","browser","pair"]},{id:"home",group:"connect",title:"Home machine",subtitle:"Which machine hosts your always-on hub and bots.",icon:"globe",keywords:["host","boat","move","online","away","queued","linked"]}];function Yi(e){if(e==="dark"||e==="light"||e==="auto")return e;return"auto"}function Xi(e){if(e==="en"||e==="es"||e==="ja"||e==="auto")return e;return"auto"}function Pt(e,t){if(e==="dark"||e==="light")return e;return t==="light"?"light":"dark"}function Zi(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean)}function kn(e,t){if(t.length===0)return!0;let n=e.toLowerCase();return t.every((i)=>n.includes(i))}function Qi(e,t){let n=Zi(t);if(n.length===0)return[];return e.filter((i)=>{let s=[i.groupLabel,i.pageTitle,i.rowTitle,i.rowDetail,...i.keywords??[]].join(" ");return kn(s,n)})}function An(e,t,n){let i=Zi(n);if(i.length===0)return e.map((r)=>({page:r,hits:[]}));let s=new Map(Sn.map((r)=>[r.id,r.label])),a=[];for(let r of e){let l=t.filter((c)=>c.pageId===r.id).filter((c)=>kn([c.rowTitle,c.rowDetail,c.pageTitle,c.groupLabel,...c.keywords??[]].join(" "),i));if(kn([s.get(r.group)??"",r.title,r.subtitle,...r.keywords].join(" "),i)||l.length>0){let c=[];for(let u of l){if(!c.includes(u.rowTitle))c.push(u.rowTitle);if(c.length>=2)break}a.push({page:r,hits:c})}}return a}function ba(e){let n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("width","15"),n.setAttribute("height","15"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.75"),n.setAttribute("stroke-linecap","square"),n.setAttribute("stroke-linejoin","miter"),n.setAttribute("aria-hidden","true");let i=(s,a)=>{let r=document.createElementNS("http://www.w3.org/2000/svg",s);for(let[o,l]of Object.entries(a))r.setAttribute(o,l);n.appendChild(r)};switch(e){case"sun":i("circle",{cx:"12",cy:"12",r:"4"}),i("path",{d:"M12 2v2m0 16v2M4.93 4.93l1.41 1.41m11.32 11.32 1.41 1.41M2 12h2m16 0h2M4.93 19.07l1.41-1.41m11.32-11.32 1.41-1.41"});break;case"cpu":i("rect",{x:"5",y:"5",width:"14",height:"14"}),i("rect",{x:"9",y:"9",width:"6",height:"6"}),i("path",{d:"M9 2v3m6-3v3M9 19v3m6-3v3M2 9h3m-3 6h3M19 9h3m-3 6h3"});break;case"link":i("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),i("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"});break;case"globe":i("circle",{cx:"12",cy:"12",r:"10"}),i("path",{d:"M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"});break}return n}function ga(){let t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("aria-hidden","true");let n=document.createElementNS("http://www.w3.org/2000/svg","circle");n.setAttribute("cx","11"),n.setAttribute("cy","11"),n.setAttribute("r","7");let i=document.createElementNS("http://www.w3.org/2000/svg","path");return i.setAttribute("d","m20 20-3.5-3.5"),t.append(n,i),t}function Xt(e,t){switch(e){case"general":return m("gpui.settings.group.general",t);case"ai":return m("gpui.settings.group.agents",t);case"connect":return m("native.pair.connect",t)}}function rt(e,t){switch(e){case"appearance":return m("settings.appearance",t);case"providers":return m("web.settings.providers",t);case"devices":return t;case"home":return m("home.machine",t)}}class Ln{backdrop;titleEl;badgeEl;closeBtn;navListEl;searchInput;searchClearBtn;paneEl;cb;openState=!1;activePage="appearance";forceProviders=!1;query="";searchBrowseAll=!1;devicesLoaded=!1;devicesLoading=!1;devicesRows=[];devicesError="";loadGen=0;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal bp-settings-modal",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.setAttribute("aria-labelledby","bp-settings-title");let i=document.createElement("div");i.className="bp-modal-head";let s=document.createElement("div");s.className="bp-settings-head-title",this.titleEl=document.createElement("h2"),this.titleEl.id="bp-settings-title",this.titleEl.textContent=m("palette.settings","Settings"),this.badgeEl=document.createElement("span"),this.badgeEl.className="bp-settings-badge",this.badgeEl.textContent="Browser",s.append(this.titleEl,this.badgeEl),this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",m("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(s,this.closeBtn);let a=document.createElement("div");a.className="bp-settings-body";let r=document.createElement("aside");r.className="bp-settings-nav";let o=document.createElement("div");o.className="bp-settings-search";let l=document.createElement("span");l.className="bp-settings-search-icon",l.appendChild(ga()),this.searchInput=document.createElement("input"),this.searchInput.type="text",this.searchInput.className="bp-settings-search-input",this.searchInput.placeholder="Search settings…",this.searchInput.setAttribute("aria-label","Search settings"),this.searchInput.setAttribute("data-testid","settings-search"),this.searchClearBtn=document.createElement("button"),this.searchClearBtn.type="button",this.searchClearBtn.className="bp-settings-search-clear bp-hidden",this.searchClearBtn.textContent="×",this.searchClearBtn.title="Clear search",this.searchClearBtn.setAttribute("aria-label","Clear search"),o.append(l,this.searchInput,this.searchClearBtn),this.navListEl=document.createElement("nav"),this.navListEl.className="bp-settings-nav-list",this.navListEl.setAttribute("aria-label","Settings sections"),r.append(o,this.navListEl),this.paneEl=document.createElement("div"),this.paneEl.className="bp-settings-pane",a.append(r,this.paneEl),n.append(i,a),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(p)=>{if(p.target===this.backdrop)this.close()}),this.searchInput.addEventListener("input",()=>{this.query=this.searchInput.value,this.searchBrowseAll=this.query.trim().length>0,this.syncSearchClear(),this.render()}),this.searchInput.addEventListener("keydown",(p)=>{if(p.key==="Enter"){let c=An(mt,this.buildSearchItems(),this.query);if(c.length>0)p.preventDefault(),this.activePage=c[0].page.id,this.searchBrowseAll=!1,this.render()}else if(p.key==="Escape"&&this.query.trim().length>0)p.preventDefault(),p.stopPropagation(),this.clearSearch()}),this.searchClearBtn.addEventListener("click",()=>{this.clearSearch(),this.searchInput.focus()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}handleEscape(){if(!this.openState)return;if(this.query.trim().length>0)this.clearSearch(),this.searchInput.focus();else this.close()}async open(e){if(this.openState=!0,e)this.activePage=e;this.backdrop.classList.remove("bp-hidden"),this.render(),this.loadDevices(),window.setTimeout(()=>{if(this.openState)this.searchInput.focus()},0)}async openToAccounts(){this.forceProviders=!0,this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),await this.open("providers")}close(){this.openState=!1,this.forceProviders=!1,this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=m("palette.settings","Settings"),this.closeBtn.setAttribute("aria-label",m("common.close","Close")),this.openState)this.render()}async refresh(){if(!this.openState)return;this.render(),await this.loadDevices()}clearSearch(){this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),this.render()}syncSearchClear(){this.searchClearBtn.classList.toggle("bp-hidden",this.query.length===0)}async loadDevices(){let e=++this.loadGen;if(this.devicesLoading=!this.devicesLoaded,this.devicesLoading&&this.openState)this.renderPane();try{let t=await this.cb.onLoadDevices();if(e!==this.loadGen)return;this.devicesRows=t,this.devicesError="",this.devicesLoaded=!0}catch(t){if(e!==this.loadGen)return;let n=t instanceof Error&&t.message?t.message:"Not available from a browser";this.devicesError=`${n} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,this.devicesRows=[],this.devicesLoaded=!0}finally{if(e===this.loadGen){if(this.devicesLoading=!1,this.openState)this.render()}}}buildSearchItems(){let e=this.cb.onGetHome?.()??null,t=this.cb.onGetNoProvider?.()??null,n=Xt("general","General"),i=Xt("ai","Agents and tools"),s=Xt("connect","Connect"),a=rt("appearance","Appearance"),r=rt("providers","AI providers"),o=rt("devices","Devices & browser"),l=rt("home","Home machine"),p=[{pageId:"appearance",pageTitle:a,groupLabel:n,rowTitle:m("settings.theme","Theme"),rowDetail:"Auto (follow hub), Dark, or Light in this browser.",keywords:["theme","dark","light","auto","appearance","colors"]},{pageId:"appearance",pageTitle:a,groupLabel:n,rowTitle:m("settings.lang","Language"),rowDetail:"Interface language for this browser.",keywords:["locale","english","espanol","japanese","language"]},{pageId:"providers",pageTitle:r,groupLabel:i,rowTitle:t?pe(t.head):"Provider connections",rowDetail:"Connect Claude, Codex, Antigravity, or other AI providers in Settings → Accounts.",keywords:["accounts","claude","codex","antigravity","grok","openai","signin"]},{pageId:"devices",pageTitle:o,groupLabel:s,rowTitle:"This browser",rowDetail:"Sign out and revoke this browser's session cookie.",keywords:["logout","sign out","session","cookie"]},{pageId:"devices",pageTitle:o,groupLabel:s,rowTitle:"Paired devices",rowDetail:this.devicesRows.map((c)=>`${c.title||c.head||""} ${c.detail||c.text||""}`).join(" ")||"Paired phones and browsers on this hub.",keywords:["phone","pair","revoke","browser"]},{pageId:"home",pageTitle:l,groupLabel:s,rowTitle:e?.name?`${e.name}`:l,rowDetail:"Which machine hosts your always-on hub and bots.",keywords:["boat","move","online","away","queued","machine"]}];for(let c of this.devicesRows){let u=c.title||c.head||"";if(u)p.push({pageId:"devices",pageTitle:o,groupLabel:s,rowTitle:u,rowDetail:c.detail||c.text||"",keywords:["paired","device"]})}return p}render(){this.renderNav(),this.renderPane()}renderNav(){let e=document.createDocumentFragment(),t=An(mt,this.buildSearchItems(),this.query),n=this.cb.onGetNoProvider?.()??null,i=this.cb.onGetHome?.()??null;if(t.length===0){let a=document.createElement("div");a.className="bp-settings-nav-empty",a.setAttribute("data-testid","settings-nav-empty"),a.textContent="No matching settings",e.appendChild(a),this.navListEl.replaceChildren(e);return}let s="";for(let a of t){let r=a.page;if(r.group!==s){s=r.group;let d=Sn.find((h)=>h.id===r.group);if(d){let h=document.createElement("div");h.className="bp-settings-group",h.textContent=Xt(d.id,d.label),e.appendChild(h)}}let o=document.createElement("button");o.type="button";let l=!this.searchBrowseAll&&r.id===this.activePage;o.className="bp-settings-nav-item"+(l?" active":""),o.setAttribute("data-testid",`settings-nav-${r.id}`);let p=document.createElement("div");p.className="bp-settings-nav-row";let c=document.createElement("span");c.className="bp-settings-nav-icon",c.appendChild(ba(r.icon));let u=document.createElement("span");if(u.className="bp-settings-nav-label",u.textContent=rt(r.id,r.title),p.append(c,u),r.id==="providers"&&(n||this.forceProviders)){let d=document.createElement("span");d.className="bp-settings-nav-dot warn",d.title="Action needed",p.appendChild(d)}else if(r.id==="home"&&i){let d=document.createElement("span");d.className="bp-settings-nav-dot "+(i.moving?.state==="failed"?"bad":i.online?"ok":"warn"),p.appendChild(d)}if(o.appendChild(p),a.hits.length>0)for(let d of a.hits){let h=document.createElement("div");h.className="bp-settings-hit",h.textContent=d,o.appendChild(h)}o.addEventListener("click",()=>{this.activePage=r.id,this.searchBrowseAll=!1,this.render()}),e.appendChild(o)}this.navListEl.replaceChildren(e)}renderPane(){let e=document.createDocumentFragment(),t=this.query.trim();if(t&&this.searchBrowseAll){this.renderSearchResults(e,t),this.paneEl.replaceChildren(e);return}let n=mt.find((r)=>r.id===this.activePage)??mt[0],i=document.createElement("div");i.className="bp-settings-pane-head";let s=document.createElement("h3");s.textContent=rt(n.id,n.title);let a=document.createElement("div");switch(a.className="bp-settings-pane-sub",a.textContent=n.subtitle,i.append(s,a),e.appendChild(i),n.id){case"appearance":this.renderAppearancePage(e);break;case"providers":this.renderProvidersPage(e);break;case"devices":this.renderDevicesPage(e);break;case"home":this.renderHomePage(e);break}this.paneEl.replaceChildren(e)}renderSearchResults(e,t){let n=Qi(this.buildSearchItems(),t),i=document.createElement("div");i.className="bp-settings-pane-head";let s=document.createElement("h3");s.textContent="Search results";let a=document.createElement("div");if(a.className="bp-settings-pane-sub",a.textContent=n.length===0?`No settings match "${t}".`:`${n.length} matching ${n.length===1?"setting":"settings"} for "${t}"`,i.append(s,a),e.appendChild(i),n.length===0){let o=document.createElement("div");o.className="bp-settings-empty",o.textContent="Try searching for theme, language, providers, sign out, devices, or home.",e.appendChild(o);return}let r=Array.from(new Set(n.map((o)=>o.pageId)));for(let o of r){let l=mt.find((h)=>h.id===o);if(!l)continue;let p=document.createElement("div");p.className="bp-settings-search-sec";let c=document.createElement("div");c.className="bp-settings-subhead",c.textContent=rt(l.id,l.title);let u=document.createElement("button");u.type="button",u.className="bp-settings-search-open",u.textContent="Open page ›",u.addEventListener("click",()=>{this.activePage=o,this.searchBrowseAll=!1,this.render()}),p.append(c,u),e.appendChild(p);let d=new Set(n.filter((h)=>h.pageId===o).map((h)=>h.rowTitle));if(o==="appearance")this.renderAppearancePage(e,d);else if(o==="providers")this.renderProvidersPage(e);else if(o==="devices")this.renderDevicesPage(e,d);else if(o==="home")this.renderHomePage(e)}}renderAppearancePage(e,t){let n=this.cb.onGetThemePref?.()??"auto",i=this.cb.onGetHubTheme?.()??"dark",s=Pt(n,i),a=this.cb.onGetLocalePref?.()??"auto",r=m("settings.theme","Theme"),o=m("settings.lang","Language");if(!t||t.has(r)){let l=m("settings.theme.dark","Dark"),p=m("settings.theme.light","Light"),c=n==="auto"?`Following hub theme (${i==="light"?p:l}). Stored in this browser only.`:`Using ${s==="light"?p:l} in this browser. Select Auto to follow the hub.`;e.appendChild(this.makeSegmentedRow(r,c,[{value:"auto",label:"Auto"},{value:"dark",label:l},{value:"light",label:p}],n,"settings-theme",(u)=>{this.cb.onSetThemePref?.(u),this.render()}))}if(!t||t.has(o))e.appendChild(this.makeSegmentedRow(o,"Interface language for this browser. Automatic follows the hub or browser language.",[{value:"auto",label:m("settings.lang.auto","Automatic")},{value:"en",label:m("settings.lang.en","English")},{value:"es",label:m("settings.lang.es","Español")},{value:"ja",label:m("settings.lang.ja","日本語")}],a,"settings-locale",(l)=>{this.cb.onSetLocalePref?.(l),this.render()}))}makeSegmentedRow(e,t,n,i,s,a){let r=document.createElement("div");r.className="bp-settings-row";let o=document.createElement("div");o.className="bp-settings-row-info";let l=document.createElement("div");l.className="bp-settings-row-title",l.textContent=e;let p=document.createElement("div");p.className="bp-settings-row-detail",p.textContent=t,o.append(l,p);let c=document.createElement("div");c.className="bp-chip-group",c.setAttribute("role","group"),c.setAttribute("aria-label",e);for(let u of n){let d=document.createElement("button");d.type="button";let h=u.value===i;d.className="bp-chip"+(h?" active":""),d.textContent=u.label,d.setAttribute("aria-pressed",h?"true":"false"),d.setAttribute("data-testid",`${s}-${u.value}`),d.addEventListener("click",()=>a(u.value)),c.appendChild(d)}return r.append(o,c),r}renderProvidersPage(e){let t=this.cb.onGetNoProvider?.()??null,n=document.createElement("section");if(n.className="bp-settings-section",n.setAttribute("data-testid","settings-providers"),t||this.forceProviders){let i=document.createElement("div");i.className="bp-settings-notice warn";let s=document.createElement("div");s.className="bp-settings-row-info";let a=document.createElement("div");a.className="bp-settings-row-title",a.textContent=t?pe(t.head):m("provider.notice.head","No AI provider connected");let r=document.createElement("div");r.className="bp-settings-row-detail",r.textContent=m("web.settings.providers.browser","Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."),s.append(a,r);let o=document.createElement("div");o.className="bp-set-btns";let l=document.createElement("a");l.className="bp-link-btn primary",l.href=t?.url||"backplane://settings/accounts",l.setAttribute("data-testid","settings-open-accounts"),l.textContent=t?pe(t.button):m("provider.notice.button","Open Settings → Accounts"),o.appendChild(l),i.append(s,o),n.appendChild(i)}else{let i=document.createElement("div");i.className="bp-settings-row";let s=document.createElement("div");s.className="bp-settings-row-info";let a=document.createElement("div");a.className="bp-settings-row-title-wrap";let r=document.createElement("span");r.className="bp-settings-row-title",r.textContent="Provider connections";let o=document.createElement("span");o.className="bp-status-pill ok",o.textContent=m("gpui.acct.connected","Connected"),a.append(r,o);let l=document.createElement("div");l.className="bp-settings-row-detail",l.textContent="Provider sign-ins, fallback order, API keys, and usage limits are managed in the Backplane desktop or mobile app.",s.append(a,l);let p=document.createElement("div");p.className="bp-set-btns";let c=document.createElement("a");c.className="bp-link-btn",c.href="backplane://settings/accounts",c.setAttribute("data-testid","settings-open-accounts"),c.textContent=m("provider.notice.button","Open Settings → Accounts"),p.appendChild(c),i.append(s,p),n.appendChild(i)}e.appendChild(n)}renderDevicesPage(e,t){let n=!t||t.has("This browser"),i=!t||t.has("Paired devices")||this.devicesRows.some((r)=>t.has(r.title||r.head||""));if(n){let r=document.createElement("div");r.className="bp-settings-subhead",r.textContent="This browser",e.appendChild(r);let o=document.createElement("div");o.className="bp-settings-row";let l=document.createElement("div");l.className="bp-settings-row-info";let p=document.createElement("div");p.className="bp-settings-row-title",p.textContent="Browser session";let c=document.createElement("div");c.className="bp-settings-row-detail",c.textContent="Sign out and revoke this browser's session cookie.",l.append(p,c);let u=document.createElement("button");u.type="button",u.className="primary stop",u.textContent=m("agy.signout","Sign out"),u.setAttribute("data-testid","logout-btn"),u.addEventListener("click",()=>{u.disabled=!0,this.cb.onLogout().catch(()=>{c.setAttribute("role","alert"),c.className="bp-settings-row-detail bp-bad",c.textContent=m("web.logout.failed","Could not confirm sign-out. Try again."),u.disabled=!1})}),o.append(l,u),e.appendChild(o)}if(!i)return;let s=document.createElement("div");if(s.className="bp-settings-subhead",s.textContent="Paired devices",e.appendChild(s),this.devicesLoading){let r=document.createElement("div");r.className="bp-settings-empty",r.textContent="Loading paired devices…",e.appendChild(r);return}if(this.devicesError){let r=document.createElement("div");r.className="bp-settings-notice bad";let o=document.createElement("div");o.className="bp-settings-row-detail",o.textContent=this.devicesError,r.appendChild(o),e.appendChild(r);return}let a=!t||t.has("Paired devices")?this.devicesRows:this.devicesRows.filter((r)=>t.has(r.title||r.head||""));if(a.length===0){let r=document.createElement("div");r.className="bp-settings-empty",r.textContent="No paired devices listed.",e.appendChild(r)}else for(let r of a){let o=document.createElement("div");o.className="bp-settings-row";let l=document.createElement("div");l.className="bp-settings-row-info";let p=document.createElement("div");p.className="bp-settings-row-title-wrap";let c=document.createElement("span");c.className="bp-settings-row-title",c.textContent=r.title||r.head||"",p.appendChild(c);let u=r.detail||r.text||"";if(u){let d=document.createElement("span"),h=u.toLowerCase();d.className="bp-status-pill "+(h.includes("this browser")?"accent":"neutral"),d.textContent=u,p.appendChild(d)}if(l.appendChild(p),o.appendChild(l),r.buttons?.length){let d=document.createElement("div");d.className="bp-set-btns";for(let h of r.buttons){let f=document.createElement("button");if(f.type="button",h.primary)f.className="primary";if(h.danger)f.className="primary stop";f.textContent=h.label||m("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(h.action,h.value).finally(()=>{this.refresh()})}),d.appendChild(f)}o.appendChild(d)}e.appendChild(o)}if(!t){let r=document.createElement("div");r.className="bp-settings-footnote",r.textContent="Pair new browsers or phones, configure Tailscale HTTPS forwarding, or revoke access in desktop or mobile Settings → Devices.",e.appendChild(r)}}renderHomePage(e){let t=this.cb.onGetHome?.()??null,n=document.createElement("section");if(n.className="bp-settings-section",n.setAttribute("data-testid","settings-home"),!t){let d=document.createElement("div");d.className="bp-settings-empty",d.textContent="Single-hub mode — this hub is running locally without linked home machines.",n.appendChild(d),e.appendChild(n);return}let i=document.createElement("div");i.className="bp-settings-row";let s=document.createElement("div");s.className="bp-settings-row-info";let a=document.createElement("div");a.className="bp-settings-row-title-wrap";let r=document.createElement("span");r.className="bp-settings-row-title",r.textContent=t.name||(t.kind==="boat"?"Boat":"This machine"),a.appendChild(r);let o=document.createElement("span");o.className="bp-status-pill neutral",o.textContent=t.kind==="local"?"This machine":t.kind==="boat"?"Boat":"Linked machine",a.appendChild(o);let l=document.createElement("span"),p="Online",c="ok";if(t.moving?.state==="moving")p="Moving",c="accent";else if(t.moving?.state==="failed")p="Move failed",c="bad";else if(!t.online)p="Away",c="warn";l.className=`bp-status-pill ${c}`,l.textContent=p,a.appendChild(l);let u=document.createElement("div");if(u.className="bp-settings-row-detail",t.moving?.state==="moving")u.textContent=t.moving.step?m("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):m("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")u.textContent=t.moving.note?m("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):m("home.move.failed","Home move failed");else if(!t.online)u.textContent=t.queuedCount>0?m("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):m("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else u.textContent="Your active home hub is online and serving threads and bots.";if(s.append(a,u),i.appendChild(s),t.canMoveHere&&this.cb.onMoveHomeHere){let d=document.createElement("button");d.type="button",d.className="primary",d.textContent=m("home.move.here","Make this machine the home"),d.setAttribute("data-testid","home-move-here-btn"),d.addEventListener("click",()=>{d.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),i.appendChild(d)}n.appendChild(i),e.appendChild(n)}}function Ee(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Nt(e,t,n=!1){let i=Ee("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function Pn(e){return Ee("pre","bp-context-code",e)}function fa(e){return Ee("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,pe(e))}function Zt(e,t){let n=Ee("div","bp-context-row");return n.append(Ee("strong",void 0,e),fa(t)),n}class Nn{fetchContext;dialog=Ee("dialog","bp-context");title=Ee("h2");cwd=Ee("div","bp-context-path");tabs=Ee("div","bp-context-tabs");body=Ee("div","bp-context-body");notice=Ee("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=Ee("div","bp-context-head"),i=Ee("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,Nt(m("common.refresh","Refresh"),()=>{this.load()}),Nt(m("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=m("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=m("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[m("thread.context.instructions","Instructions"),m("thread.context.system","System Prompt"),m("thread.context.skills","Skills"),m("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=Nt(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(Ee("p","bp-dim",m("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=Ee("details","bp-context-card"),i=Ee("summary");if(i.append(Zt(t.path,t.status),Ee("small","bp-dim",m("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,Pn(t.preview)),t.note)n.append(Ee("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=Ee("div","bp-context-row"),n=Nt(m("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=m("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(Ee("p","bp-dim",m("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[m("thread.context.base","Backplane"),e.sections.base],[m("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[m("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(Ee("h3",void 0,i),Pn(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(Ee("h3",void 0,pe(t)));for(let i of n){let s=Ee("article","bp-context-card");s.append(Zt(i.name,i.status),Ee("p",void 0,i.description),Ee("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),Ee("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(Ee("p","bp-dim",m("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=Ee("article","bp-context-card");n.append(Zt(t.path,t.state));for(let s of t.servers){let a=s.url||[s.command,...s.args].map((r)=>JSON.stringify(r)).join(" ");if(n.append(Zt(s.name,s.status),Pn(a)),s.cwd)n.append(Ee("small","bp-context-path",s.cwd))}if(t.error)n.append(Ee("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?m("thread.context.trust","Trust and enable"):i==="disable"?m("thread.context.disable","Disable"):m("thread.context.enable","Enable"),a=Nt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");a.disabled=this.busy;let r=Ee("div","bp-context-actions");r.append(a),n.append(r)}this.body.append(n)}}}function va(e){if(e.wake)return{icon:"◷",label:"Snoozed",tone:"dim"};let t=(e.label??"").trim(),n=(e.tone??"").trim();if(t){let s=t.toLowerCase();return{icon:s==="approve"||s==="sign in"?"!":s==="input"?"?":s==="failed"||s==="stopped"?"×":s==="working"||s==="running"?"▸":s==="waiting"?"◌":s==="done"?"✓":"•",label:t,tone:n==="bad"?s==="failed"||s==="stopped"?"bad-out":"bad":n==="run"?"run":n==="wait"?"wait":n==="ok"?"ok":"dim"}}let i=e.word||"";if(i==="needs"){if(e.want==="approval")return{icon:"!",label:"Approve",tone:"bad"};if(e.want==="sign-in")return{icon:"!",label:"Sign in",tone:"bad"};return{icon:"?",label:"Input",tone:"bad"}}if(i==="failed"||e.status==="failed"||e.state==="fail")return{icon:"×",label:"Failed",tone:"bad-out"};if(i==="cut"||i==="interrupted")return{icon:"×",label:"Stopped",tone:"bad-out"};if(i==="running"||e.status==="active"||e.status==="working"||e.state==="run")return{icon:"▸",label:"Working",tone:"run"};if(i==="monitoring"||i==="limit"||e.status==="waiting")return{icon:"◌",label:"Waiting",tone:"wait"};if(i==="done"||e.status==="finished")return{icon:"✓",label:"Done",tone:"ok"};return null}var es="http://www.w3.org/2000/svg";function ot(e,t=14,n=""){let i=document.createElementNS(es,"svg");if(i.setAttribute("viewBox","0 0 24 24"),i.setAttribute("width",String(t)),i.setAttribute("height",String(t)),i.setAttribute("fill","none"),i.setAttribute("stroke","currentColor"),i.setAttribute("stroke-width","1.75"),i.setAttribute("stroke-linecap","square"),i.setAttribute("stroke-linejoin","miter"),i.setAttribute("aria-hidden","true"),n)i.classList.add(...n.split(" "));for(let s of e){let a=document.createElementNS(es,"path");a.setAttribute("d",s),i.appendChild(a)}return i}function ts(){return ot(["M3 6h6l2 2h10v11H3z"],14,"bp-folder-icon")}function ns(e=14,t="bp-folder-icon bp-hw-icon"){return ot(["M3 3h18v18H3z","M9 3v6h6","M9 21v-6","M15 9a2 2 0 1 0 0-4 2 2 0 0 0 0 4z","M9 15a2 2 0 1 0 0-4 2 2 0 0 0 0 4z"],e,t)}function ya(e=13){return ot(["M6 6h12v12H6z","M9 2v4","M15 2v4","M9 18v4","M15 18v4","M2 9h4","M2 15h4","M18 9h4","M18 15h4"],e)}function wa(e=15){return ot(["M4 10V4l4 3h8l4-3v6l-2 9H6z","M9 13h1","M14 13h1","M11 16h2"],e,"bp-cat-glyph")}function Ea(e=11){return ot(["M4 12l5 5 11-11"],e)}function Ca(e=11){return ot(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M12 6v6l4 2"],e)}function xa(e=11){return ot(["M12 17v5","M8 4h8l-1 5 3 3v2H6v-2l3-3z"],e,"bp-pin-icon")}function is(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}function ka(e){let t=e.replace(/^@/,"").trim();if(!t)return"?";let n=t.split(/[\s_-]+/).filter(Boolean);if(n.length>=2)return(n[0][0]+n[1][0]).toUpperCase();return t.slice(0,2).toUpperCase()}function Mn(e){if(e==="wait"||e==="error")return"bp-mood-wait";if(e==="work"||e==="talk")return"bp-mood-work";return"bp-mood-idle"}function Ze(e){let t=e.lastIndexOf("|");return t>=0?e.slice(t+1):e}class Tn{el;hostLabel;homeBanner;crewEl;filterInput;listEl;connEl;filterText="";allFilter="all";snoozeMenuRowId="";collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let a=document.createElement("button");a.type="button",a.className="icon bp-side-collapse",a.textContent="‹",a.title="Collapse sidebar",a.setAttribute("aria-label","Collapse sidebar"),a.setAttribute("data-testid","sidebar-collapse"),a.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,a);let r=document.createElement("div");r.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=m("sidebar.search.projects","Search projects, threads…");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let l=document.createElement("button");l.type="button",l.className="icon bp-side-add",l.textContent="+",l.title=m("thread.new","New thread"),l.setAttribute("aria-label",m("thread.new","New thread")),l.setAttribute("data-testid","sidebar-new-thread"),l.addEventListener("click",()=>{let c=this.firstProjectId();if(c)this.cb.onNewThread(c)}),r.append(this.filterInput,l),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.crewEl=document.createElement("div"),this.crewEl.className="bp-crew-band bp-hidden",this.crewEl.setAttribute("data-testid","sidebar-crew"),this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let p=document.createElement("div");p.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),p.appendChild(this.connEl),this.el.append(n,r,this.homeBanner,this.crewEl,this.listEl,p)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?m("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):m("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?m("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):m("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let a=new Date(e.awaySince);s=`${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=m("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=m("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=m("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=m("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=m("sidebar.search.projects","Search projects, threads…");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}renderCrewBand(e){let t=this.bots.find((l)=>l.uber),n=this.bots.filter((l)=>!l.uber&&(!e||l.name.toLowerCase().includes(e))),i=this.rooms.filter((l)=>!e||l.name.toLowerCase().includes(e)),s=Boolean(t&&(!e||t.name.toLowerCase().includes(e))),a=n.length>0||Boolean(this.cb.onNewBot)&&!e,r=i.length>0||Boolean(this.cb.onNewRoom)&&!e;if(!s&&!a&&!r){this.crewEl.classList.add("bp-hidden"),this.crewEl.replaceChildren();return}let o=document.createDocumentFragment();if(s&&t){let l=document.createElement("button");l.type="button",l.className="bp-crew-uber"+(t.thread===this.selectedThreadId?" active":""),l.setAttribute("data-testid",`crew-uber-${t.id}`);let p=document.createElement("span");if(p.className=`bp-crew-uber-avatar ${Mn(t.mood)}`,t.color)p.style.color=t.color;p.appendChild(wa(14));let c=document.createElement("span");c.className="bp-crew-uber-meta";let u=document.createElement("span");if(u.className="bp-crew-uber-name",u.textContent=t.name,c.appendChild(u),t.note){let d=document.createElement("span");d.className=`bp-crew-uber-note ${Mn(t.mood)}`,d.textContent=t.note,c.appendChild(d)}if(l.append(p,c),t.mood==="wait"||t.mood==="error"){let d=document.createElement("span");d.className="bp-status-pill bp-pill-bad",d.textContent="? Input",l.appendChild(d)}l.addEventListener("click",()=>this.cb.onSelectBot(t)),o.appendChild(l)}if(a){let l=document.createElement("div");l.className="bp-crew-bots",l.setAttribute("data-testid","crew-bots");let p=document.createElement("span");p.className="bp-crew-lbl",p.textContent=m("tour.title.bots","Bots").toUpperCase(),l.appendChild(p);let c=document.createElement("div");c.className="bp-crew-bot-tiles";for(let u of n){let d=document.createElement("button");if(d.type="button",d.className=`bp-crew-bot-tile ${Mn(u.mood)}`+(u.thread===this.selectedThreadId?" active":""),d.title=u.note?`@${u.name} — ${u.note}`:`@${u.name}`,d.setAttribute("aria-label",`@${u.name}`),d.setAttribute("data-testid",`crew-bot-${u.id}`),u.color)d.style.setProperty("--bot-c",u.color);let h=document.createElement("span");if(h.className="bp-crew-bot-init",h.textContent=ka(u.name),d.appendChild(h),u.mood==="wait"||u.mood==="error"){let f=document.createElement("span");f.className="bp-crew-bot-wait",d.appendChild(f)}d.addEventListener("click",()=>this.cb.onSelectBot(u)),c.appendChild(d)}if(this.cb.onNewBot&&!e){let u=document.createElement("button");u.type="button",u.className="bp-crew-bot-tile bp-crew-add",u.textContent="+",u.title=m("bots.new","New bot"),u.setAttribute("aria-label",m("bots.new","New bot")),u.setAttribute("data-testid","crew-new-bot"),u.addEventListener("click",()=>this.cb.onNewBot?.()),c.appendChild(u)}l.appendChild(c),o.appendChild(l)}if(r){let l=document.createElement("div");l.className="bp-crew-rooms",l.setAttribute("data-testid","crew-rooms");for(let p of i){let c=document.createElement("button");c.type="button",c.className="bp-crew-room-chip",c.setAttribute("data-testid",`crew-room-${p.id}`);let u=document.createElement("span");u.className="bp-dim",u.textContent="#";let d=document.createElement("span");if(d.textContent=p.name,c.append(u,d),p.members!==void 0&&p.members>0){let h=document.createElement("span");h.className="bp-crew-room-cnt",h.textContent=String(p.members),c.appendChild(h)}c.title=p.members?`#${p.name} (${p.members})`:`#${p.name}`,c.addEventListener("click",()=>this.cb.onSelectRoom?.(p)),l.appendChild(c)}if(this.cb.onNewRoom&&!e){let p=document.createElement("button");p.type="button",p.className="bp-crew-room-chip bp-crew-add",p.textContent="+",p.title=m("rooms.new","New room"),p.setAttribute("aria-label",m("rooms.new","New room")),p.setAttribute("data-testid","crew-new-room"),p.addEventListener("click",()=>this.cb.onNewRoom?.()),l.appendChild(p)}o.appendChild(l)}this.crewEl.classList.remove("bp-hidden"),this.crewEl.replaceChildren(o)}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=m("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(a)=>{a.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderStatusPill(e,t){let n=document.createElement("span");if(n.className=`bp-status-pill bp-pill-${e.tone}`,n.textContent=`${e.icon} ${e.label}`,t)n.title=t;return n}renderRowActions(e){if(e.off)return null;let t=Array.isArray(e.snooze)&&e.snooze.length>0&&Boolean(this.cb.onSnoozeRow),n=Boolean(e.wake)&&Boolean(this.cb.onSnoozeRow),i=Boolean(e.settle);if(!t&&!n&&!i)return null;let s=document.createElement("span");if(s.className="bp-row-acts",n&&e.wake){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-wake-btn",a.textContent=m("menu.wake","Wake"),a.title=m("menu.wake","Wake snoozed thread"),a.setAttribute("data-testid",`wake-row-${e.id}`),a.addEventListener("click",(r)=>{r.stopPropagation(),this.cb.onSnoozeRow?.(e.wake)}),s.appendChild(a)}if(t&&e.snooze){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-snooze-btn",a.title=m("menu.snooze","Snooze thread"),a.setAttribute("aria-label",m("menu.snooze","Snooze thread")),a.setAttribute("data-testid",`snooze-row-${e.id}`),a.appendChild(Ca(11)),a.addEventListener("click",(r)=>{r.stopPropagation(),this.snoozeMenuRowId=this.snoozeMenuRowId===e.id?"":e.id,this.render()}),s.appendChild(a)}if(i&&e.settle){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-settle-btn",a.title=m("menu.settle","Settle"),a.setAttribute("aria-label",m("menu.settle","Settle")),a.setAttribute("data-testid",`settle-row-${e.id}`),a.appendChild(Ea(11)),a.addEventListener("click",(r)=>{r.stopPropagation(),this.cb.onThreadAct(Ze(e.settle),"settle")}),s.appendChild(a)}return s}renderSectionThreadRow(e,t,n=!1){let i=document.createElement("div");i.className="bp-thread-row"+(n?" bp-inbox-row":"")+(e.id===this.selectedThreadId||Ze(e.id)===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),i.setAttribute("data-thread-id",e.id),i.setAttribute("data-testid",`thread-row-${e.id}`);let s=va(e),a=this.renderRowActions(e);if(n){let c=document.createElement("div");c.className="bp-inbox-main";let u=document.createElement("div");u.className="bp-inbox-top";let d=document.createElement("div");if(d.className="bp-thread-title",d.textContent=e.title||"Untitled thread",u.appendChild(d),a)u.appendChild(a);let h=document.createElement("div");if(h.className="bp-inbox-meta",s)h.appendChild(this.renderStatusPill(s,e.say));if(e.project){let f=document.createElement("span");f.className="bp-inbox-proj",f.textContent=e.project,h.appendChild(f)}if(e.ago){let f=document.createElement("span");if(f.className="bp-thread-age",f.textContent=e.ago,e.pinned)f.title=m("tools.pinned","Pinned");h.appendChild(f)}c.append(u,h),i.appendChild(c)}else{if(t){let u=document.createElement("span");u.className="bp-tree-branch",u.setAttribute("aria-hidden","true"),i.appendChild(u)}if(s)i.appendChild(this.renderStatusPill(s,e.say));let c=document.createElement("div");if(c.className="bp-thread-title",c.textContent=e.title||"Untitled thread",i.appendChild(c),a)i.appendChild(a);if(e.ago){let u=document.createElement("span");if(u.className="bp-thread-age",u.textContent=e.ago,e.pinned)u.title=m("tools.pinned","Pinned");i.appendChild(u)}}let r=e.nav||e.id;if(!e.off&&r&&!r.startsWith("@room:"))i.addEventListener("click",()=>this.cb.onSelectThread(Ze(r)));let o=this.snoozeMenuRowId===e.id&&Array.isArray(e.snooze)&&e.snooze.length>0,l=e.kind==="swarm"?Ki(e.need):null;if(!l&&!o)return i;let p=document.createElement("div");if(p.className="bp-need-wrap",p.appendChild(i),o&&e.snooze){let c=document.createElement("div");c.className="bp-snooze-bar"+(t?" nested":""),c.setAttribute("data-testid",`snooze-bar-${e.id}`);let u=document.createElement("span");u.className="bp-dim",u.textContent="Snooze:",c.appendChild(u);for(let d of e.snooze){let h=document.createElement("button");h.type="button",h.className="bp-snooze-opt",h.textContent=d.label,h.addEventListener("click",(f)=>{f.stopPropagation(),this.snoozeMenuRowId="",this.cb.onSnoozeRow?.(d.value),this.render()}),c.appendChild(h)}p.appendChild(c)}if(l){let c=document.createElement("div");c.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),c.setAttribute("data-testid",`need-${e.id}`);let u=document.createElement("span");u.className="bp-need-line",u.textContent=l.line,u.title=l.line,c.appendChild(u);for(let h of l.actions){if(!Yt(h,Boolean(this.cb.hasRoomView)))continue;let f=document.createElement("button");f.type="button",f.className="bp-need-btn",f.textContent=h.label,f.setAttribute("data-testid",`need-${h.act}-${e.id}`),f.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,f.addEventListener("click",(b)=>{b.stopPropagation();let g=this.cb.onNeedAct;if(!g)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),g(h).catch((y)=>{this.needErr.set(e.id,y instanceof Error?y.message:String(y))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),c.appendChild(f)}p.appendChild(c);let d=this.needErr.get(e.id);if(d){let h=document.createElement("div");h.className="bp-need-err"+(t?" nested":""),h.textContent=d,p.appendChild(h)}}return p}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let r of n)if(r.kind==="threads")for(let o of r.rows)i.add(o.id),i.add(Ze(o.id));else if(r.kind==="projects")for(let o of r.rows)for(let l of o.threads??[])i.add(l.id),i.add(Ze(l.id));let s=this.selectedThreadId?this.threads.find((r)=>r.id===this.selectedThreadId)??null:null,a=!1;for(let r of n)if(r.kind==="projects"&&(r.rows.length>0||(r.count??0)>0))a=!0;for(let r of n){if(r.kind==="bub")continue;if(r.kind==="threads"){let o=Boolean(r.fold&&r.toggle),l=r.rows.filter((c)=>{if(!t)return!0;return`${c.title} ${c.project??""}`.toLowerCase().includes(t)});if(!o&&l.length===0)continue;if(o&&t&&l.length===0)continue;if(o&&!t&&(r.count??l.length)===0)continue;let p=document.createElement("section");if(p.className=`bp-side-section bp-side-inbox bp-sec-${r.id}`,p.setAttribute("data-section-id",r.id),o){let c=document.createElement("button");c.type="button",c.className="bp-side-section-head bp-side-section-toggle";let u=t?l.length:r.count??l.length,d=r.open||Boolean(t)?"▾":"▸";if(c.textContent=`${d} ${r.title.toUpperCase()} (${u})`,r.hint)c.title=r.hint;c.setAttribute("data-testid",`section-toggle-${r.id}`),c.addEventListener("click",()=>{if(r.toggle)this.cb.onToggleSection?.(r.toggle)}),p.appendChild(c)}else{let c=document.createElement("div");c.className="bp-side-section-head"+(r.id==="needs"?" bp-head-needs":r.id==="running"?" bp-head-running":""),c.textContent=`${r.title.toUpperCase()} ${l.length}`,p.appendChild(c)}if(!o||Boolean(r.open)||Boolean(t))for(let c of l)p.appendChild(this.renderSectionThreadRow(c,!1,!0));e.appendChild(p);continue}if(r.kind==="projects"){let o=r.rows,l=o.filter((d)=>{if(!t)return!0;if((d.title||d.id).toLowerCase().includes(t))return!0;if((d.threads??[]).some((h)=>h.title.toLowerCase().includes(t)))return!0;if((d.swarms??[]).some((h)=>h.title.toLowerCase().includes(t)))return!0;return!1}),p=Boolean(r.fold&&r.toggle);if(t&&l.length===0)continue;if(!p&&r.id!=="active"&&l.length===0)continue;let c=document.createElement("section");if(c.className=`bp-side-section bp-sec-${r.id}`,c.setAttribute("data-section-id",r.id),p){let d=document.createElement("button");d.type="button",d.className="bp-side-section-head bp-side-section-toggle";let h=t?l.length:r.count??l.length,f=r.open||Boolean(t)?"▾":"▸";if(d.textContent=`${f} ${r.title.toUpperCase()} (${h})`,r.hint)d.title=r.hint;d.setAttribute("data-testid",`section-toggle-${r.id}`),d.addEventListener("click",()=>{if(r.toggle)this.cb.onToggleSection?.(r.toggle)}),c.appendChild(d)}else c.appendChild(this.projectsHead(r.title.toUpperCase()));if(!p||Boolean(r.open)||Boolean(t)){if(r.id==="all"&&!t){let d=o.some((f)=>f.hasBoard||f.hasSchematic),h=o.some((f)=>!f.hasBoard&&!f.hasSchematic);if(d&&h){let f=document.createElement("div");f.className="bp-proj-filter",f.setAttribute("data-testid","all-projects-filter");let b=[{id:"all",label:"All"},{id:"hw",label:"Boards"},{id:"sw",label:"Code"}];for(let g of b){let y=document.createElement("button");y.type="button",y.className="bp-proj-filter-btn"+(this.allFilter===g.id?" active":""),y.textContent=g.label,y.addEventListener("click",()=>{this.allFilter=g.id,this.render()}),f.appendChild(y)}if(c.appendChild(f),this.allFilter==="hw")l=l.filter((g)=>g.hasBoard||g.hasSchematic);else if(this.allFilter==="sw")l=l.filter((g)=>!g.hasBoard&&!g.hasSchematic)}}if(r.id==="active"&&!a&&!t){let d=document.createElement("div");d.className="bp-side-empty",d.textContent="No projects yet.",c.appendChild(d)}for(let d of l){let h=document.createElement("div");if(h.className="bp-proj-group"+(d.off||r.id==="quiet"?" bp-dim":""),h.setAttribute("data-project-id",d.id),d.nav||d.key)h.setAttribute("data-project-key",d.nav||d.key||"");let f=document.createElement("div");f.className="bp-proj-head";let b=document.createElement("button");b.type="button",b.className="bp-proj-toggle";let y=Boolean(d.hasBoard||d.hasSchematic)?ns(14):ts();if(d.css)y.style.color=d.css;let w=document.createElement("span");if(w.className="bp-proj-name",w.textContent=d.title||d.id,b.append(y,w),d.fold==="project-fold"&&d.nav)b.addEventListener("click",()=>this.cb.onToggleProjectFold?.(d.nav));let x=document.createElement("div");if(x.className="bp-proj-meta",(d.needsCount??0)>0){let S=document.createElement("span");S.className="bp-proj-badge-need",S.textContent=String(d.needsCount),S.title=`${d.needsCount} needing you`,x.appendChild(S)}if((d.running??0)>0){let S=document.createElement("span");S.className="bp-proj-badge-run",S.textContent=String(d.running),S.title=`${d.running} running`,x.appendChild(S)}if(d.pinned&&r.id!=="pinned")x.appendChild(xa(11));let A=document.createElement("div");if(A.className="bp-proj-acts",!d.off&&this.cb.onQuickOpenViewer){if(d.hasBoard){let S=document.createElement("button");S.type="button",S.className="bp-proj-quick",S.title=m("viewer.board","Open Board"),S.setAttribute("aria-label",`Open Board (${d.title})`),S.setAttribute("data-testid",`quick-board-${d.id}`),S.appendChild(ns(13,"")),S.addEventListener("click",(M)=>{M.stopPropagation(),this.cb.onQuickOpenViewer?.(Ze(d.id),"board")}),A.appendChild(S)}if(d.hasSchematic){let S=document.createElement("button");S.type="button",S.className="bp-proj-quick",S.title=m("viewer.schematic","Open Schematic"),S.setAttribute("aria-label",`Open Schematic (${d.title})`),S.setAttribute("data-testid",`quick-sch-${d.id}`),S.appendChild(ya(13)),S.addEventListener("click",(M)=>{M.stopPropagation(),this.cb.onQuickOpenViewer?.(Ze(d.id),"schematic")}),A.appendChild(S)}}let N=document.createElement("button");if(N.type="button",N.className="icon bp-proj-add",N.title=m("thread.new","New thread"),N.textContent="+",N.setAttribute("data-testid",`new-thread-${d.id}`),d.off)N.disabled=!0;if(N.addEventListener("click",(S)=>{S.stopPropagation(),this.cb.onNewThread(Ze(d.id))}),A.appendChild(N),f.append(b,x,A),h.appendChild(f),!d.folded||Boolean(t)){let S=Boolean(t)&&(d.title||d.id).toLowerCase().includes(t);for(let M of d.swarms??[]){if(t&&!S&&!M.title.toLowerCase().includes(t))continue;h.appendChild(this.renderSectionThreadRow(M,!0))}for(let M of d.threads??[]){if(t&&!S&&!M.title.toLowerCase().includes(t))continue;h.appendChild(this.renderSectionThreadRow(M,!0))}if(s&&s.project===Ze(d.id)&&!i.has(s.id)&&(!t||S||s.title.toLowerCase().includes(t)))h.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:is(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}c.appendChild(h)}}e.appendChild(c)}}}render(){this.addShown=!1;let e=this.filterText;this.renderCrewBand(e);let t=document.createDocumentFragment();if(this.sections!==null)this.renderHubSections(t,e);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(e){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(e))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(t.appendChild(this.projectsHead("RECENT")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",t.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(e&&s.length===0&&!i.title.toLowerCase().includes(e))continue;let a=document.createElement("section");a.className="bp-proj-group",a.setAttribute("data-project-id",i.id);let r=document.createElement("div");r.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let l=this.collapsedProjects.has(i.id)&&!e,p=ts();if(i.css)p.style.color=i.css;let c=document.createElement("span");c.className="bp-proj-name",c.textContent=i.title||i.id,o.append(p,c),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let u=document.createElement("button");if(u.type="button",u.className="icon bp-proj-add",u.title=m("thread.new","New thread"),u.textContent="+",u.setAttribute("data-testid",`new-thread-${i.id}`),u.addEventListener("click",(d)=>{d.stopPropagation(),this.cb.onNewThread(i.id)}),r.append(o,u),a.appendChild(r),!l)for(let d of s)a.appendChild(this.renderSectionThreadRow({id:d.id,title:d.title,status:d.status,state:d.state,ago:is(d.updatedAt),pinned:d.pinned,nav:d.id},!0));t.appendChild(a)}}this.listEl.replaceChildren(t)}}function Sa(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function Mt(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function Aa(e,t){if(t===16000){let a=new Int16Array(e.length);for(let r=0;r0?l/p:0));s[a]=c<0?c*32768:c*32767}return s}class Bn{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){Mt(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(Mt(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(Mt(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?Sa(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(Mt(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let a=this.stopDrain.then(async()=>{if(t&&i){let r=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(r.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=a,await a}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),a=String(e.ins??""),r=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,r-s),l=i.slice(0,o)+a+i.slice(r);this.mark=o+a.length,this.cb.setDraft(l)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),a=i.createScriptProcessor(4096,1,1);a.onaudioprocess=(r)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=Aa(r.inputBuffer.getChannelData(0),i.sampleRate);for(let l=0;l=3200){let l=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(l.buffer),!1,t)}},s.connect(a),a.connect(i.destination),this.audioCtx=i,this.processor=a}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let a=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!a.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${a.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;Mt(this.stream),this.stream=null}}var ss=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],as=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],rs=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],os=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],La=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function Tt(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[l]++,l>i)i=l}}let s=new Int32Array(16),a=0;for(let o=1;o<=15;o++)s[o]=a,a+=n[o];let r=new Int32Array(a);for(let o=0;o0)r[s[l]++]=o}return{counts:n,symbols:r,maxBits:i}}var Pa=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),Tt(e,288)})(),Na=(()=>{let e=new Uint8Array(32);return e.fill(5),Tt(e,32)})();class In{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,a=(u)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=u,s-=u,d},r=(u)=>{let d=0,h=0,f=0;for(let b=1;b<=u.maxBits;b++){d|=a(1);let g=u.counts[b];if(d-g{let d=l+u;if(d>t)throw Error("inflated frame exceeds limit");if(d<=o.length)return;let h=o.length;while(h{p(1),o[l++]=u,this.win[this.winPos]=u,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let u=a(1),d=a(2);if(d===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let h=e[n]|e[n+1]<<8,f=e[n+2]|e[n+3]<<8;if(n+=4,(h^65535)!==f)throw Error("invalid stored block length");if(n+h>e.length)throw Error("truncated stored payload");p(h);for(let b=0;b=e.length)break}else if(d===1||d===2){let h=Pa,f=Na;if(d===2){let b=a(5)+257,g=a(5)+1,y=a(4)+4,w=new Uint8Array(19);for(let M=0;MA)throw Error("code length overflow");for(let V=0;VA)throw Error("code length overflow");S+=B}else if(M===18){let B=a(7)+11;if(S+B>A)throw Error("code length overflow");S+=B}else throw Error("invalid code length symbol")}h=Tt(N,b),f=Tt(N.subarray(b),g)}while(!0){let b=r(h);if(b<256)c(b);else if(b===256)break;else{let g=b-257;if(g>=ss.length)throw Error("invalid length symbol");let y=ss[g]+(as[g]?a(as[g]):0),w=r(f);if(w>=rs.length)throw Error("invalid distance symbol");let x=rs[w]+(os[w]?a(os[w]):0);p(y);let A=this.winPos-x&32767;for(let N=0;N{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let a=this.nextId++,r=window.setTimeout(()=>{this.pending.delete(a),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(a,{resolve:i,reject:s,timer:r}),this.ws.send(JSON.stringify({id:a,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let a;try{a=JSON.parse(s)}catch{return}if(a.t==="hub.restarting")this.restarting={reason:String(a.reason??""),build:String(a.build??""),text:String(a.text??""),at:Date.now()};if(a.t==="hello")this.restarting=null,this.hello=a,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new In:null,this.reconnectDelay=500,this.setState("connected");else if(a.t==="reply"&&typeof a.id==="number"){let r=this.pending.get(a.id);if(r)if(this.pending.delete(a.id),window.clearTimeout(r.timer),a.ok)r.resolve(a.result??{});else{let o=a.error,l=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed",p=typeof a.errorCode==="string"?a.errorCode:void 0,c=typeof a.machine==="string"?a.machine:void 0,u=typeof a.thread==="string"?a.thread:void 0;r.reject(new Bt(l,{code:p,machine:c,thread:u}))}return}for(let r of this.frameListeners)r(a)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let a;try{a=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(a.length>0&&a[0]===123)i(this.textDecoder.decode(a));else{let r=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);for(let o of this.binaryListeners)o(r)}return}for(let a of this.binaryListeners)a(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Ma=new TextDecoder;function ls(e){return e.length>7&&e[0]>=160&&e[0]<=183&&e[1]===1&&e[2]===100&&e[3]===112&&e[4]===108&&e[5]===111&&e[6]===116}function cs(e){let t=0,n=0;function i(r){if(r<=23)return r;if(r===24){if(t>=e.length)return null;return e[t++]}if(r===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(r===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(r){if(n++,r>32||n>400000||t>=e.length)return null;let o=e[t++],l=o>>5,p=i(o&31);if(p===null)return null;switch(l){case 0:return p;case 1:return-1-p;case 2:{if(t+p>e.length)return null;let c=e.subarray(t,t+p);return t+=p,c}case 3:{if(t+p>e.length)return null;let c=Ma.decode(e.subarray(t,t+p));return t+=p,c}case 4:{if(p>e.length)return null;let c=Array(p);for(let u=0;u=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function ps(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[b]==="number"?e[b]:g,n=t("l",0),i=t("c",0),s=t("a",255)/255,a=t("m",1),r=t("w",0),o=r/2,l=a===0&&r!==0,p=e.d instanceof Uint8Array?e.d:new Uint8Array(0),c=new ds(p),u=[],d=[],h=0,f=0;while(c.more()){let b=c.nextU32(),g=u.length,y=1/0,w=1/0,x=-1/0,A=-1/0;if(a===2)h=h+c.nextI32()|0,f=f+c.nextI32()|0,u.push(h,f),y=x=h,w=A=f;else{let S=Math.min(c.nextU32(),1048576);for(let M=0;Mx)x=h;if(fA)A=f}}let N=(u.length-g)/2;if(N>0){let S=a===2||N===1?2:a===0?0:1,M=a===0?0:o;d.push({info:b,x0:y-M,y0:w-M,x1:x+M,y1:A+M,at:g,n:N,kind:S})}}return{layer:n,color:i,alpha:s,mode:a,r:o,own:l,pts:new Float32Array(u),pieces:d}}function us(e,t,n){let i=(r)=>Array.isArray(r)&&r.length>=4?[Number(r[0])||0,Number(r[1])||0,Number(r[2])||0,Number(r[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],a=[];for(let r=0;r=0&&o0){n.delete(o.h),n.set(o.h,l);while(n.size>1024){let p=n.keys().next().value;if(p!==void 0)n.delete(p);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:a}}function hs(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),a=n.naturalWidth*s,r=n.naturalHeight*s,o=n.left+(n.width-a)/2,l=i?n.top:n.top+(n.height-r)/2,p=(e-o)/a,c=(t-l)/r;if(p<0||p>1||c<0||c>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(p*1000))),y:Math.max(0,Math.min(1000,Math.round(c*1000)))}}var ms=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function bs(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class jn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function gs(e,t,n){let i=!0,s=!1,a=!1,r="",o=!1,l=!1,p=-1,c=null,u=new jn,d=document.createElement("div");d.className="bp-pane bp-browser-pane",d.setAttribute("data-testid","pane-browser");let h=document.createElement("div");h.className="bp-pane-bar bp-browser-nav";function f(X,ce,E){let k=document.createElement("button");if(k.type="button",k.className="bp-v-btn",k.textContent=X,k.setAttribute("data-testid",ce),E)k.title=E;return k}let b=f("←","browser-back","Back"),g=f("→","browser-forward","Forward"),y=f("↻","browser-reload","Reload"),w=document.createElement("form");w.className="bp-browser-url-form";let x=document.createElement("input");x.type="text",x.className="bp-browser-input",x.placeholder="https://…",x.autocomplete="off",x.spellcheck=!1,x.setAttribute("data-testid","browser-url");let A=f("Go","browser-go","Navigate");A.type="submit",w.append(x,A);let N=f("Take over","browser-takeover");N.classList.add("is-primary"),h.append(b,g,y,w,N);let S=document.createElement("div");S.className="bp-browser-drive-bar",S.hidden=!0;let M=document.createElement("div");M.className="bp-browser-keys-row";let B=document.createElement("input");B.type="text",B.className="bp-browser-input",B.placeholder="Type text or press Enter/Tab/Arrows…",B.autocomplete="off",B.spellcheck=!1,B.setAttribute("data-testid","browser-keys");let R=f("Send","browser-type-send");M.append(B,R);let V=document.createElement("div");V.className="bp-browser-quick-keys";for(let[X,ce]of ms){let E=f(X,`browser-key-${ce}`);E.addEventListener("click",()=>me("press",{key:ce})),V.append(E)}S.append(M,V);let D=document.createElement("div");D.className="bp-browser-err",D.setAttribute("data-testid","browser-error"),D.hidden=!0;let re=document.createElement("div");re.className="bp-browser-stage",re.setAttribute("data-testid","browser-stage");let he=document.createElement("img");he.className="bp-browser-img",he.alt="Hub browser screen",he.draggable=!1,he.hidden=!0,he.setAttribute("data-testid","browser-frame");let oe=document.createElement("div");oe.className="bp-pane-empty",oe.setAttribute("data-testid","browser-empty"),oe.textContent="Loading browser screen…",re.append(he,oe);let we=document.createElement("div");we.className="bp-browser-hint",we.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",we.hidden=!0,d.append(h,S,D,re,we),e.replaceChildren(d);function Ae(X){D.textContent=X,D.hidden=!X}function Me(){S.hidden=!s,we.hidden=!s,N.textContent=s?"Hand back":"Take over",N.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),N.classList.toggle("is-on",s),he.classList.toggle("is-driving",s)}function me(X,ce={},E){u.enqueue(async()=>{if(!i)return;Ae("");try{if(await t.hub.rpc("browser",{thread:n,op:X,...ce}),!i)return;E?.(),le()}catch(k){if(!i)return;Ae(k instanceof Error?k.message:String(k))}})}function be(X){me("toolbar",{command:X},()=>{s=!0,Me()})}b.addEventListener("click",()=>be("back")),g.addEventListener("click",()=>be("forward")),y.addEventListener("click",()=>be("reload")),w.addEventListener("submit",(X)=>{X.preventDefault();let ce=bs(x.value);if(!ce)return;if(x.value=ce,!s)me("takeover",{},()=>{s=!0,Me()});me("navigate",{url:ce},()=>{s=!0,Me()})}),N.addEventListener("click",()=>{if(s)me("handback",{},()=>{s=!1,Me()});else me("takeover",{},()=>{s=!0,Me(),B.focus()})});function I(){let X=B.value;if(!X)return;B.value="",me("type",{text:X})}R.addEventListener("click",I),B.addEventListener("keydown",(X)=>{if(!s)return;if(X.key==="Enter"){if(X.preventDefault(),B.value)I();me("press",{key:"Enter"});return}if(X.key==="Tab"||X.key==="Escape"||X.key==="ArrowUp"||X.key==="ArrowDown"||X.key==="ArrowLeft"||X.key==="ArrowRight"||X.key==="Backspace"&&B.value==="")X.preventDefault(),me("press",{key:X.key})}),he.addEventListener("click",(X)=>{if(!s||!a)return;let ce=he.getBoundingClientRect(),E=hs(X.clientX,X.clientY,{left:ce.left,top:ce.top,width:ce.width,height:ce.height,naturalWidth:he.naturalWidth,naturalHeight:he.naturalHeight});if(!E)return;me("click",E)}),he.addEventListener("wheel",(X)=>{if(!s||!a)return;X.preventDefault();let ce=Math.round(X.deltaX),E=Math.round(X.deltaY);if(ce===0&&E===0)return;me("scroll",{dx:ce,dy:E})},{passive:!1});async function le(){if(!i)return;if(o){l=!0;return}o=!0;try{do{l=!1,c=new AbortController;let X=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:c.signal});if(!i)return;if(X.ok){let ce=await X.blob();if(!i)return;let E=URL.createObjectURL(ce),k=r;if(r=E,he.src=E,he.hidden=!1,oe.hidden=!0,a=!0,k)URL.revokeObjectURL(k)}else if(!a)he.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&l)}catch{if(!i)return;if(!a)he.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}finally{c=null,o=!1}}let ne=t.hub.onFrame((X)=>{if(!i)return;if(X.t==="shot"&&X.bot===n){if(typeof X.n==="number"){if(X.n===p)return;p=X.n}le()}});return le(),{destroy(){if(i=!1,ne(),c?.abort(),r)URL.revokeObjectURL(r),r=""}}}function z(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Qt(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;if(e<1048576)return`${Math.round(e/1024)} KB`;return`${(e/1048576).toFixed(1)} MB`}function vs(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function Ba(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function fs(e){return["txt","md","markdown","json","toml","yaml","yml","xml","csv","tsv","rs","ts","tsx","js","mjs","cjs","jsx","css","html","htm","sh","bash","py","c","h","cc","cpp","hpp","go","java","kt","swift","rb","lua","sql","ini","cfg","conf","env","gitignore","lock","log","gbr","gtl","gbl","gts","gbs","gto","gbo","gm1","drl","pos","net","kicad_pro","kicad_prl","kicad_dru","kicad_sym","kicad_mod","kicad_wks"].includes(e)}function Ia(e){let t=vs(e);if(t==="kicad_pcb")return"board";if(t==="kicad_sch")return"schematic";if(t==="step"||t==="stp"||t==="glb")return"mech";return null}function ys(e,t,n,i){let s=!0,a="",r="",o=z("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let l=z("div","bp-pane-bar"),p=z("div","bp-files-crumbs"),c=z("button","bp-v-btn","Refresh");c.type="button",c.addEventListener("click",()=>void g(a)),l.append(p,c);let u=z("div","bp-files-split"),d=z("div","bp-files-list");d.setAttribute("data-testid","files-list");let h=z("div","bp-files-preview");h.setAttribute("data-testid","files-preview"),h.append(z("div","bp-pane-empty","Select a file to preview")),u.append(d,h),o.append(l,u),e.replaceChildren(o);function f(){p.replaceChildren();let y=z("button","bp-crumb-btn","project");if(y.type="button",y.addEventListener("click",()=>void g("")),p.append(y),!a)return;let w=a.split("/").filter(Boolean),x="";for(let A of w){x=x?`${x}/${A}`:A;let N=x;p.append(z("span","bp-vh-sep","/"));let S=z("button","bp-crumb-btn",A);S.type="button",S.addEventListener("click",()=>void g(N)),p.append(S)}}async function b(y,w,x){r=y,h.replaceChildren();let A=z("div","bp-files-prev-head");A.append(z("span","bp-files-prev-name",y));let N=z("div","bp-files-prev-acts"),S=Ia(w);if(S){let V=z("button","bp-v-btn is-primary",`Open in ${S}`);V.type="button",V.setAttribute("data-testid","files-open-viewer"),V.addEventListener("click",()=>i(S,y)),N.append(V)}let M=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(y)}`,B=z("a","bp-v-btn","Download");B.href=M,B.download=w,N.append(B),A.append(N),h.append(A);let R=vs(w);if(Ba(R)){let V=z("div","bp-files-img-wrap"),D=document.createElement("img");D.className="bp-files-img",D.alt=w,D.src=M,V.append(D),h.append(V);return}if(x>524288&&!fs(R)){h.append(z("div","bp-pane-empty",`Binary file (${Qt(x)}). Use Download to save.`));return}if(fs(R)||x<=65536){let V=z("div","bp-pane-empty","Loading…");h.append(V);try{let D=await fetch(M,{credentials:"same-origin"});if(!s||r!==y)return;if(!D.ok){V.textContent=`Could not load file (${D.status})`;return}if((D.headers.get("content-type")||"").startsWith("image/")){V.remove();let ne=document.createElement("img");ne.className="bp-files-img",ne.alt=w,ne.src=M,h.append(ne);return}let he=262144,oe=[],we=0,Ae=!1;if(D.body){let ne=D.body.getReader();try{while(!0){let{done:X,value:ce}=await ne.read();if(X||!ce)break;if(we+ce.byteLength>he){let E=he-we;if(E>0)oe.push(ce.subarray(0,E)),we+=E;Ae=!0,await ne.cancel();break}oe.push(ce),we+=ce.byteLength}}finally{ne.releaseLock()}}if(!s||r!==y)return;let Me=new Uint8Array(we),me=0;for(let ne of oe)Me.set(ne,me),me+=ne.byteLength;let be=!1;for(let ne=0;neA.dir===N.dir?A.name.localeCompare(N.name):A.dir?-1:1),d.replaceChildren(),y){let A=z("button","bp-file-row is-dir");A.type="button",A.append(z("span","bp-file-icon","↰"),z("span","bp-file-name",".."));let N=y.includes("/")?y.slice(0,y.lastIndexOf("/")):"";A.addEventListener("click",()=>void g(N)),d.append(A)}if(x.length===0){d.append(z("div","bp-pane-empty","Empty folder"));return}for(let A of x){let N=y?`${y}/${A.name}`:A.name,S=z("button","bp-file-row"+(A.dir?" is-dir":"")+(N===r?" is-sel":""));S.type="button",S.setAttribute("data-testid",`file-row-${A.name}`),S.append(z("span","bp-file-icon",A.dir?"▸":"·"),z("span","bp-file-name",A.name),z("span","bp-file-size",A.dir?"":Qt(A.size))),S.addEventListener("click",()=>{if(A.dir)g(N);else d.querySelectorAll(".bp-file-row.is-sel").forEach((M)=>M.classList.remove("is-sel")),S.classList.add("is-sel"),b(N,A.name,A.size)}),d.append(S)}}catch(w){if(!s)return;d.replaceChildren(z("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return g(""),{destroy(){s=!1}}}function ws(e,t,n){let i=!0,s=z("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let a=z("div","bp-pane-bar"),r=z("span","bp-diff-summary","Loading diff…"),o=z("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void p()),a.append(r,o);let l=z("div","bp-diff-body");l.setAttribute("data-testid","diff-body"),s.append(a,l),e.replaceChildren(s);async function p(){r.textContent="Loading diff…",l.replaceChildren();try{let c=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(c?.nogit){r.textContent="Not a git repository",l.append(z("div","bp-pane-empty","This project is not a git repository."));return}let u=typeof c?.diff==="string"?c.diff:"";if(!u.trim()){r.textContent="Clean working tree",l.append(z("div","bp-pane-empty","No uncommitted changes."));return}let d=u.split(` -`),h=0,f=0,b=0,g=document.createDocumentFragment(),y=z("div","bp-diff-file");for(let w of d){if(w.startsWith("diff --git ")){if(y.childNodes.length>0)g.append(y);y=z("div","bp-diff-file"),h++;let x=w.match(/ b\/(.+)$/);y.append(z("div","bp-diff-file-head",x?x[1]:w));continue}if(w.startsWith("index ")||w.startsWith("--- ")||w.startsWith("+++ "))y.append(z("div","bp-diff-line is-meta",w));else if(w.startsWith("@@"))y.append(z("div","bp-diff-line is-hunk",w));else if(w.startsWith("+"))f++,y.append(z("div","bp-diff-line is-add",w));else if(w.startsWith("-"))b++,y.append(z("div","bp-diff-line is-del",w));else y.append(z("div","bp-diff-line",w))}if(y.childNodes.length>0)g.append(y);r.textContent=`${h||1} file${h===1?"":"s"} · +${f} -${b}`,l.append(g)}catch(c){if(!i)return;r.textContent="Diff unavailable",l.append(z("div","bp-pane-empty",c instanceof Error?c.message:String(c)))}}return p(),{destroy(){i=!1}}}function Es(e,t,n){let i=!0,s="checks",a=z("div","bp-pane bp-review-pane");a.setAttribute("data-testid","pane-review");let r=z("div","bp-pane-bar"),o=z("div","bp-review-tabs"),l=z("button","bp-v-btn is-on","Checks"),p=z("button","bp-v-btn","BOM"),c=z("button","bp-v-btn","Comments");l.type=p.type=c.type="button",o.append(l,p,c);let u=z("button","bp-v-btn","Refresh");u.type="button",u.addEventListener("click",()=>void b()),r.append(o,u);let d=z("div","bp-review-body");d.setAttribute("data-testid","review-body"),a.append(r,d),e.replaceChildren(a);function h(g){s=g,l.classList.toggle("is-on",s==="checks"),p.classList.toggle("is-on",s==="bom"),c.classList.toggle("is-on",s==="comments"),b()}l.addEventListener("click",()=>h("checks")),p.addEventListener("click",()=>h("bom")),c.addEventListener("click",()=>h("comments"));function f(g){let y=z("div","bp-review-md"),w=g.split(` -`),x=0;while(x{M.preventDefault();let B=N.value.trim();if(!B)return;S.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:B}).then(()=>{N.value="",S.disabled=!1,b()},()=>{S.disabled=!1})}),d.append(A),x.length===0){d.append(z("div","bp-pane-empty","No review comments yet."));return}for(let M of x){let B=z("div","bp-review-comment"+(M.resolved?" is-resolved":"")),R=[M.by||"review",M.file,M.layer,M.item].filter(Boolean).join(" · ");B.append(z("div","bp-review-comment-meta",R),z("div","bp-review-comment-text",M.text)),d.append(B)}return}let g=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let y=g?.report||{};if(d.replaceChildren(),y.line||y.gate){let w=z("div","bp-review-gate",[y.gate,y.line].filter(Boolean).join(" · "));d.append(w)}if(y.err)d.append(z("div","bp-review-err",y.err));if(Array.isArray(y.tasks)&&y.tasks.length>0){let w=z("div","bp-review-tasks");y.tasks.forEach((x,A)=>{let N=z("label","bp-review-task"),S=document.createElement("input");S.type="checkbox",S.checked=!!(x.done??x.checked);let M=typeof x.index==="number"?x.index:A;S.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:M}).then(()=>void b(),()=>{})}),N.append(S,z("span",void 0,x.text||x.label||`Item ${A+1}`)),w.append(N)}),d.append(w)}if(y.md&&y.md.trim())d.append(f(y.md));else if(!y.err&&(!y.tasks||y.tasks.length===0))d.append(z("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(g){if(!i)return;d.replaceChildren(z("div","bp-pane-empty",g instanceof Error?g.message:String(g)))}}return b(),{destroy(){i=!1}}}function Cs(e,t){let n=e>>>16&255,i=e>>>8&255,s=e&255;return t>=0.999?`rgb(${n},${i},${s})`:`rgba(${n},${i},${s},${t.toFixed(3)})`}class Dn{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,a=Math.max(i-t,1000),r=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),l=Math.max(o.width,200),p=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(l/a,p/r)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),a=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==a)this.canvas.width=s,this.canvas.height=a;let r=this.ctx;r.setTransform(i,0,0,i,0,0),r.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",r.fillRect(0,0,t,n);let o=this.frame;if(!o)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let l=t*0.5,p=n*0.5,c=this.scale,u=this.cx,d=this.cy,h=u-l/c,f=u+l/c,b=d-p/c,g=d+p/c,{off:y,dim:w,lift:x}=this.masks,A=[],N=[];for(let M=0;M>>B&1)===1)continue;if(B===x)N.push(M);else A.push(M)}let S=A.concat(N);r.lineCap="round",r.lineJoin="round";for(let M=0;M>>R.layer&1)===1,D=R.alpha*(V?0.25:1);if(D<=0.01)continue;this.drawChunk(r,R,D,h,b,f,g,u,d,c,l,p)}if(this.highlights.size>0){r.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",r.fillRect(0,0,t,n);let M=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let B=0;Ba||g.y1r)continue;if(g.n<3)continue;let y=(d[g.at]-o)*p+c,w=(d[g.at+1]-l)*p+u;e.moveTo(y,w);for(let x=1;x0)e.fill()}else if(t.mode===2){let f=Math.max(0.75,t.r*p);e.fillStyle=h,e.beginPath();let b=0;for(let g=0;ga||y.y1r)continue;let w=(d[y.at]-o)*p+c,x=(d[y.at+1]-l)*p+u;e.moveTo(w+f,x),e.arc(w,x,f,0,Math.PI*2),b++}if(b>0)e.fill()}else{e.strokeStyle=h,e.lineWidth=Math.max(1,t.r*2*p),e.beginPath();let f=0;for(let b=0;ba||g.y1r)continue;let y=(d[g.at]-o)*p+c,w=(d[g.at+1]-l)*p+u;if(g.n===1)e.moveTo(y,w),e.lineTo(y+0.01,w);else{e.moveTo(y,w);for(let x=1;x0)e.stroke()}}drawLitPieces(e,t,n,i,s,a,r,o,l,p,c,u,d){let h=t.pts,f=Cs(t.color,t.alpha);for(let b=0;br||g.y1o)continue;let y=(h[g.at]-l)*c+u,w=(h[g.at+1]-p)*c+d;if(g.kind===2){let x=Math.max(1.5,t.r*c);e.fillStyle=f,e.beginPath(),e.arc(y,w,x,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(g.kind===0&&g.n>=3){e.fillStyle=f,e.beginPath(),e.moveTo(y,w);for(let x=1;x=0;c--){let u=n.chunks[c];if(u.layer<32&&(p>>>u.layer&1)===1)continue;for(let d=0;dh.x1+r||ah.y1+r)continue;let f=(h.x1-h.x0+1)*(h.y1-h.y0+1);if(f{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,a=(t.y+n.y)*0.5,r=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*r)),l=this.canvas.getBoundingClientRect(),p=this.pinchStart.midX-l.left-l.width*0.5,c=this.pinchStart.midY-l.top-l.height*0.5,u=s-l.left-l.width*0.5,d=a-l.top-l.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+p/this.pinchStart.scale-u/o,this.cy=this.pinchStart.cy+c/this.pinchStart.scale-d/o,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,a=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/a,this.cy+=i/this.scale-i/a,this.scale=a,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var xs=[{id:"fit",label:"Fit"},{id:"iso",label:"Iso"},{id:"top",label:"Top"},{id:"bottom",label:"Bottom"},{id:"front",label:"Front"},{id:"right",label:"Right"},{id:"back",label:"Back"},{id:"left",label:"Left"}];function ks(e){switch(e){case"top":return{yaw:0,pitch:Math.PI*0.499};case"bottom":return{yaw:0,pitch:-Math.PI*0.499};case"front":return{yaw:0,pitch:0};case"right":return{yaw:Math.PI*0.5,pitch:0};case"back":return{yaw:Math.PI,pitch:0};case"left":return{yaw:-Math.PI*0.5,pitch:0};case"iso":case"fit":default:return{yaw:0.6,pitch:0.7}}}function Hn(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` +`),u=document.createElement("div");u.className="bp-code-block";let d=document.createElement("div");d.className="bp-code-head";let m=document.createElement("span");m.className="bp-code-lang",m.textContent=l||"code";let f=document.createElement("button");f.type="button",f.className="bp-btn-ghost bp-code-copy";let b=h("common.copy","Copy");f.textContent=b,f.addEventListener("click",()=>{navigator.clipboard?.writeText(c).then(()=>{f.textContent="✓",window.setTimeout(()=>{f.textContent=b},1200)}).catch(()=>{})}),d.append(m,f);let g=document.createElement("pre"),y=document.createElement("code");y.textContent=c,g.appendChild(y),u.append(d,g),t.appendChild(u);continue}if(!s.trim()){i++;continue}let a=/^(#{1,4})\s+(.+)$/.exec(s);if(a){let l=document.createElement(`h${Math.min(4,a[1].length+1)}`);l.className="bp-md-h",kt(l,a[2]),t.appendChild(l),i++;continue}if(s.startsWith("> ")){let l=document.createElement("blockquote");l.className="bp-md-quote";let p=[];while(i "))p.push(n[i].slice(2)),i++;kt(l,p.join(` +`)),t.appendChild(l);continue}if(/^\s*[-*]\s+/.test(s)){let l=document.createElement("ul");l.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))r.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let l=0;l0)o.appendChild(document.createElement("br"));kt(o,r[l])}t.appendChild(o)}return t}var Vs=new Set(["(","[",'"',"'","`"]);function Us(e){return/[\p{L}\p{N}\-_\/+\[]/u.test(e)}function Ws(e){return/[\p{L}\p{N}\-_\/]/u.test(e)}function _s(e){return/[\p{L}\p{N}]/u.test(e)}function ti(e,t){if(!e)return[];let n=(t??[]).filter((a)=>a.kind==="model"&&a.word&&a.label);if(n.length===0)return[{kind:"text",text:e}];let i=[],s=0;while(sr)a=c,r=u,o=l;break}p=c+1}}if(o===null)break;if(a>s)i.push({kind:"text",text:e.slice(s,a)});i.push({kind:"model",word:o.word,label:o.label}),s=r}if(s3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function Ks(e,t){let n=document.createDocumentFragment(),i=ti(e,t),s=h("native.thread.model","Model").toLowerCase();for(let a of i){if(a.kind==="text"){n.appendChild(document.createTextNode(a.text));continue}let r=document.createElement("span");r.className="bp-ref-chip bp-ref-model",r.title=a.word,r.setAttribute("data-ref-word",a.word);let o=document.createElement("span");o.className="bp-ref-sigil",o.textContent="&";let l=document.createElement("span");l.className="bp-ref-label",l.textContent=a.label;let p=document.createElement("span");p.className="bp-ref-kind",p.textContent=s,r.append(o,l,p),n.appendChild(r)}return n}function Js(e){e.addEventListener("copy",(t)=>{let n=typeof window<"u"?window.getSelection():null;if(!n||n.rangeCount===0||n.isCollapsed)return;let i=n.getRangeAt(0);if(!e.contains(i.commonAncestorContainer))return;let s=i.commonAncestorContainer,o=(s.nodeType===Node.ELEMENT_NODE?s:s.parentElement)?.closest(".bp-ref-chip[data-ref-word]")?.getAttribute("data-ref-word"),l;if(o)l=o;else{let p=i.cloneContents(),c=p.querySelectorAll(".bp-ref-chip[data-ref-word]");if(c.length===0)return;for(let d of c){let m=d.getAttribute("data-ref-word")||d.textContent||"";d.replaceWith(document.createTextNode(m))}let u=p.querySelectorAll(".bp-entry");for(let d=1;d{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",Js(this.scrollEl),this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=h("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let a=document.createElement("button");a.type="button",a.textContent=h("tools.retry","Retry"),a.addEventListener("click",n),i.append(s,a),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=h("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((a)=>!ln(a)),this.hasMore=n,this.loadingOlder=!1,this.review=i,this.unanswered=s,this.btwNote=null,this.renderBanners(),this.renderEntries(!0)}updateThreadMeta(e){if(!this.thread||this.thread.id!==e.id)return;this.thread=e}setReview(e){this.review=e,this.renderBanners()}setUnanswered(e){this.unanswered=e,this.renderBanners()}setNoProvider(e){this.noProvider=e,this.renderBanners()}showBtw(e,t){this.btwNote={q:e,a:t},this.renderBanners()}prependEntries(e,t){this.loadingOlder=!1;let n=this.scrollEl.scrollHeight,i=new Set(this.entries.map((a)=>a.id)),s=e.filter((a)=>!ln(a)&&!i.has(a.id));this.entries=[...s,...this.entries],this.hasMore=t,this.renderEntries(!1),this.scrollEl.scrollTop+=this.scrollEl.scrollHeight-n}clearLoadingOlder(){this.loadingOlder=!1}upsertEntry(e){if(ln(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((r)=>r.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let a=this.liveNodes.get(e);if(a){if(a.replaceChildren(St(s.text)),i)this.scrollToBottom()}else this.renderEntries(i)}isNearBottom(){let e=this.scrollEl;return e.scrollHeight-e.scrollTop-e.clientHeight<80}scrollToBottom(){this.pinnedToBottom=!0,this.scrollEl.scrollTop=this.scrollEl.scrollHeight}renderBanners(){let e=document.createDocumentFragment();if(this.noProvider&&!this.thread?.id.includes("~")){let t=document.createElement("div");t.className="bp-banner bp-no-provider",t.setAttribute("data-testid","no-provider-banner");let n=document.createElement("div");n.className="bp-no-provider-body";let i=document.createElement("strong");if(i.textContent=pe(this.noProvider.head),n.appendChild(i),this.noProvider.text){let r=document.createElement("span");r.className="bp-dim",r.textContent=pe(this.noProvider.text),n.appendChild(r)}let s=document.createElement("div");s.className="bp-banner-actions";let a=document.createElement("button");a.type="button",a.className="primary",a.setAttribute("data-testid","no-provider-accounts-btn"),a.textContent=pe(this.noProvider.button),a.addEventListener("click",()=>this.cb.onOpenAccounts?.()),s.appendChild(a),t.append(n,s),e.appendChild(t)}if(this.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||h("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let a=document.createElement("button");if(a.type="button",s.primary)a.className="primary";a.textContent=s.label,a.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(a)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(St(this.btwNote.a)),n.append(i,s);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,a),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let a=h("common.copy","Copy"),r=document.createElement("span");r.textContent=a,s.append(At(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),r),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{r.textContent="✓",window.setTimeout(()=>{r.textContent=a},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let l=document.createElement("span");l.textContent=h("reply.action","Reply"),o.append(At(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),l),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let p=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),c=document.createElement("span");c.className="bp-entry-time";let u=zs(e.at);if(t)c.textContent=u,i.append(s,...p?[o]:[],c);else{let d=n&&e.at?qs(cn(e.at)-cn(n)):"",m=u?d?h("web.chat.finished.dur","Finished {time} · {dur}",{time:u,dur:d}):h("web.chat.finished","Finished {time}",{time:u}):"";c.textContent=e.live?h("web.chat.streaming","Streaming…"):m,i.append(c,s,...p?[o]:[])}return i}closePlanRevise(){let e=this.planRevisingId;if(!e)return!1;this.planRevisingId="";let t=this.scrollEl.scrollTop;return this.renderEntries(!1),this.scrollEl.scrollTop=t,this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e)}"] [data-testid="plan-revise"]`)?.focus(),!0}renderEntries(e){let t=null,n=typeof document<"u"?document.activeElement:null;if(n instanceof HTMLTextAreaElement&&n.classList.contains("bp-plan-revise-input")&&this.listEl.contains(n)&&this.planRevisingId)this.planReviseDrafts.set(this.planRevisingId,n.value),t={askId:this.planRevisingId,start:n.selectionStart,end:n.selectionEnd,dir:n.selectionDirection};this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let i=document.createDocumentFragment();if(!this.thread){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=h("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(a),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=h("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(a),this.listEl.replaceChildren(i);return}let s=0;for(let a of this.entries){if(a.kind==="user"&&a.at)s=a.at;let r=document.createElement("article");if(r.className=`bp-entry bp-entry-${a.kind}`+(a.live?" is-live":""),r.setAttribute("data-entry-id",a.id),a.kind==="tool"&&a.tool){let c=document.createElement("div");c.className=`bp-tool-pill bp-tool-${a.tool.state||"done"}`;let u=document.createElement("span");if(u.className="bp-tool-name",u.textContent=a.tool.name,c.appendChild(u),a.tool.summary){let d=document.createElement("span");d.className="bp-tool-summary",d.textContent=a.tool.summary,c.appendChild(d)}r.appendChild(c),i.appendChild(r);continue}if(a.kind==="ask"&&a.ask){let c=a.ask;if(c.kind==="plan"){r.appendChild(this.renderPlanAsk(c)),i.appendChild(r);continue}let u=document.createElement("div");u.className="bp-ask-card",u.setAttribute("data-testid",`ask-${c.id}`);let d=document.createElement("div");if(d.className="bp-ask-q",d.textContent=c.question,u.appendChild(d),c.state==="open"){let m=document.createElement("div");if(m.className="bp-ask-opts",c.options&&c.options.length>0)for(let f of c.options){let b=document.createElement("button");b.type="button",b.textContent=f.label,b.addEventListener("click",()=>this.cb.onAnswerAsk(c.id,f.id)),m.appendChild(b)}else{let f=document.createElement("input");f.type="text",f.className="bp-input",f.placeholder=h("web.chat.answer.placeholder","Type answer…");let b=document.createElement("button");b.type="button",b.className="primary",b.textContent=h("web.chat.answer.btn","Answer"),b.addEventListener("click",()=>{if(f.value.trim())this.cb.onAnswerAsk(c.id,f.value.trim())}),m.append(f,b)}u.appendChild(m)}else{let m=document.createElement("div");m.className="bp-ask-answered",m.textContent=h("web.chat.answered","Answered: {answer}",{answer:c.answered??""}),u.appendChild(m)}r.appendChild(u),i.appendChild(r);continue}let o=Boolean(a.text&&a.text.trim().length>0),l=Boolean(a.images&&a.images.length>0),p=Boolean(a.attachments&&a.attachments.length>0);if(!o&&!l&&!p&&!a.live)continue;if(a.replyTo?.quote){let c=document.createElement("div");c.className="bp-reply-quote",c.textContent=h("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:a.replyTo.quote});let u=a.replyTo.id;c.setAttribute("role","button"),c.tabIndex=0,c.setAttribute("data-testid","entry-reply-quote");let d=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(u);else this.goTo(u)};c.addEventListener("click",d),c.addEventListener("keydown",(m)=>{if(m.key==="Enter"||m.key===" ")m.preventDefault(),d()}),r.appendChild(c)}if(o||a.live){let c=document.createElement("div");if(c.className="bp-entry-body",a.kind==="user")c.appendChild(Ks(a.text||"",a.refs));else c.appendChild(St(a.text||""));if(a.live)this.liveNodes.set(a.id,c);r.appendChild(c)}if(p&&a.attachments){let c=document.createElement("div");c.className="bp-entry-images";for(let u of a.attachments)if(u.previewUrl){let d=document.createElement("img");d.className="bp-reply-img",d.src=u.previewUrl,d.alt=u.name||"attachment",c.appendChild(d)}else if(u.path||u.name){let d=document.createElement("span");d.className="bp-tool-pill",d.textContent=u.name||u.path||"image",c.appendChild(d)}if(c.childElementCount>0)r.appendChild(c)}if(a.images&&a.images.length>0){let c=document.createElement("div");c.className="bp-entry-images";for(let u of a.images){let d=document.createElement("img");d.className="bp-reply-img",d.alt=u;let m=`${a.id}|${u}`,f=this.imageCache.get(m);if(f)d.src=f;else this.cb.onLoadImage(a.id,u).then((b)=>{if(!b)return;let g=b.url??(b.mime&&b.data?`data:${b.mime};base64,${b.data}`:"");if(!g)return;this.imageCache.set(m,g),d.src=g});c.appendChild(d)}r.appendChild(c)}r.appendChild(this.makeEntryActions(a,a.kind==="user",a.kind==="assistant"?s:void 0)),i.appendChild(r)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let a=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(a){if(a.focus({preventScroll:!0}),t.start!==null&&t.end!==null)a.setSelectionRange(t.start,t.end,t.dir??void 0)}}if(e&&!t)this.scrollToBottom()}renderPlanAsk(e){let t=this.planExpanded.has(e.id),n=e.state==="open"&&this.planRevisingId===e.id,i=document.createElement("div");i.className="bp-ask-card bp-ask-plan",i.setAttribute("data-testid",`ask-${e.id}`);let s=document.createElement("div");s.className="bp-plan-head";let a=At(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"]);a.classList.add("bp-plan-head-ic");let r=document.createElement("span");if(r.className="bp-plan-title",r.textContent=!e.head||e.head==="Proposed plan"?h("ask.plan","Proposed plan"):pe(e.head),s.append(a,r),e.state==="open"){let c=document.createElement("span");c.className="bp-plan-badge",c.textContent=h("gpui.ask.plan.ready","Ready for review"),s.appendChild(c)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn";let u=h("common.copy","Copy"),d=document.createElement("span");d.textContent=u,c.append(At(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),d),c.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{c.classList.add("copied"),d.textContent=h("web.clone.copied","Copied"),window.setTimeout(()=>{c.classList.remove("copied"),d.textContent=u},1200)}).catch(()=>{})}),s.appendChild(c)}let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn",l.setAttribute("data-testid","plan-expand"),l.textContent=t?h("gpui.c.term.collapse","Collapse"):h("gpui.c.term.expand","Expand"),l.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let c=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=c}),s.appendChild(l),i.appendChild(s);let p=document.createElement("div");if(p.className="bp-plan-body"+(t?" is-expanded":""),p.setAttribute("data-testid","plan-body"),p.appendChild(St(e.question||"")),i.appendChild(p),e.state==="open"){let c=document.createElement("div");c.className="bp-plan-actions";let u=e.options?.find((b)=>b.id==="implement"||b.id.endsWith("|implement")),d=document.createElement("button");if(d.type="button",d.className="primary",d.setAttribute("data-testid","plan-implement"),d.textContent=u?.label&&u.label!=="Implement"?pe(u.label):h("approval.implement","Implement"),d.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,u?.id??"implement")}),c.appendChild(d),e.revise!==!1){let b=document.createElement("button");b.type="button",b.className="bp-plan-revise-btn"+(n?" active":""),b.setAttribute("data-testid","plan-revise"),b.append(At(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(h("gpui.ask.plan.revise","Revise"))),b.addEventListener("click",()=>{let g=this.planRevisingId!==e.id;this.planRevisingId=g?e.id:"";let y=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=y,g)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),c.appendChild(b)}let m=e.options?.find((b)=>b.id==="dismiss"||b.id.endsWith("|dismiss")),f=document.createElement("button");if(f.type="button",f.className="bp-plan-dismiss-btn",f.setAttribute("data-testid","plan-dismiss"),f.textContent=m?.label&&m.label!=="Dismiss"?pe(m.label):h("approval.dismiss","Dismiss"),f.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,m?.id??"dismiss")}),c.appendChild(f),i.appendChild(c),n){let b=document.createElement("div");b.className="bp-plan-revise",b.setAttribute("data-testid","plan-revise-drawer");let g=document.createElement("textarea");g.rows=2,g.className="bp-input bp-plan-revise-input",g.placeholder=h("gpui.ask.plan.reviseph","What should change in the plan?"),g.value=this.planReviseDrafts.get(e.id)??"";let y=document.createElement("button");y.type="button",y.className="bp-plan-revise-send",y.setAttribute("data-testid","plan-revise-send"),y.textContent=h("gpui.ask.plan.sendrev","Send revision"),y.disabled=g.value.trim().length===0;let w=()=>{let N=g.value.trim();if(!N)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${N}`)},x=()=>{this.closePlanRevise()};b.addEventListener("keydown",(N)=>{if(N.key==="Escape")N.preventDefault(),N.stopPropagation(),x()}),g.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,g.value),y.disabled=g.value.trim().length===0}),g.addEventListener("keydown",(N)=>{if(N.key==="Enter"&&!N.shiftKey)N.preventDefault(),w()}),y.addEventListener("click",w);let A=document.createElement("button");A.type="button",A.className="bp-btn-ghost",A.textContent=h("common.cancel","Cancel"),A.addEventListener("click",x),b.append(g,y,A),i.appendChild(b)}}else{let c=document.createElement("div");c.className="bp-ask-answered",c.textContent=h("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(c)}return i}}var ii={claude:{viewBox:"0 0 24 24",d:"m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z"},codex:{viewBox:"0 0 256 260",d:"M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87l51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921l51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272l-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695l-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69l-1.535-.922l-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87l-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58L128.067 97.3l28.188 16.218v32.434l-28.086 16.218l-28.188-16.218l-.052-32.434Z"},grok:{viewBox:"0 0 24 24",d:"M9.497 15.122 L16.811 9.491 C17.169 9.215 17.682 9.323 17.852 9.751 C18.752 12.013 18.35 14.73 16.561 16.596 C14.772 18.462 12.283 18.871 10.007 17.939 L7.522 19.139 C11.087 21.68 15.416 21.052 18.121 18.229 C20.267 15.991 20.931 12.941 20.31 10.19 L20.315 10.196 C19.414 6.155 20.537 4.54 22.837 1.237 C22.891 1.159 22.946 1.08 23 1 L19.974 4.156 L19.974 4.146 L9.495 15.124 M7.987 16.49 C5.429 13.941 5.87 9.996 8.053 7.721 C9.667 6.037 12.313 5.35 14.622 6.361 L17.102 5.166 C16.655 4.829 16.082 4.467 15.425 4.213 C12.455 2.938 8.9 3.573 6.485 6.088 C4.163 8.51 3.433 12.234 4.687 15.411 C5.624 17.786 4.088 19.466 2.541 21.162 C1.993 21.763 1.443 22.364 1 23 L7.985 16.492"},muse:{viewBox:"0 0 24 24",d:"M10.73.032c-1.333 0-2.032 1.016-2.032 2.285 0 2.223 2.127 4.953 4.318 4.953 1.301 0 2-.953 2-2.254 0-2.254-2.095-4.984-4.286-4.984m8.413 2.984c-1.968 0-3.397 2.73-3.397 4.825 0 1.556.794 3.016 2.254 3.016 2 0 3.365-2.762 3.365-4.794 0-1.523-.762-3.047-2.222-3.047M4.857 4.159c-1.968 0-3.778 1.016-3.778 2.54 0 1.65 2.16 2.793 4.254 2.793 1.873 0 3.778-.92 3.778-2.508 0-1.682-2.159-2.825-4.254-2.825m-.222 6.476C2.413 10.635 0 13.175 0 15.397c0 1.301.825 2.159 2.095 2.159 2.19 0 4.603-2.508 4.603-4.794 0-1.27-.761-2.127-2.063-2.127m16.667.698c-2.223 0-5.016 1.62-5.016 3.651 0 1.238 1.047 2.19 2.698 2.19 2.159 0 5.016-1.587 5.016-3.682 0-1.302-1.08-2.159-2.698-2.159M7.619 16c-1.524 0-2.38 1.746-2.38 3.429 0 2.063 1.269 4.54 3.047 4.54 1.524 0 2.38-1.81 2.38-3.461C10.667 18.57 9.46 16 7.62 16m6.571 1.016c-1.333 0-2.476.667-2.476 2.032 0 2.095 2.667 4.063 4.92 4.063 1.366 0 2.54-.73 2.54-2.063 0-2.032-2.698-4.032-4.984-4.032"},antigravity:{viewBox:"0 0 24 24",d:"M20.197 20.618 C21.318 21.459 23 20.898 21.459 19.357 C16.834 14.873 17.815 2.541 12.07 2.541 C6.325 2.541 7.306 14.873 2.682 19.357 C1 21.038 2.822 21.459 3.943 20.618 C8.287 17.675 8.006 12.49 12.07 12.49 C16.134 12.49 15.853 17.675 20.197 20.618 Z"},opencode:{viewBox:"0 0 24 24",d:"M22 24H2V0h20zM17 4.8H7v14.4h10z"},pi:{viewBox:"0 0 24 24",d:"M0 0v24h6v-6h6v-6H6V6h6v6h6V0Zm18 12v12h6V12Z"},omp:{viewBox:"0 0 24 24",d:"M1.44 3.86 L22.56 3.86 C23 3.86 23 3.86 23 4.3 L23 6.06 C23 6.5 23 6.5 22.56 6.5 L1.44 6.5 C1 6.5 1 6.5 1 6.06 L1 4.3 C1 3.86 1 3.86 1.44 3.86 Z M4.74 6.5 L6.5 6.5 C6.94 6.5 6.94 6.5 6.94 6.94 L6.94 19.7 C6.94 20.14 6.94 20.14 6.5 20.14 L4.74 20.14 C4.3 20.14 4.3 20.14 4.3 19.7 L4.3 6.94 C4.3 6.5 4.3 6.5 4.74 6.5 Z M15.74 6.5 L17.5 6.5 C17.94 6.5 17.94 6.5 17.94 6.94 L17.94 13.32 C17.94 13.76 17.94 13.76 17.5 13.76 L15.74 13.76 C15.3 13.76 15.3 13.76 15.3 13.32 L15.3 6.94 C15.3 6.5 15.3 6.5 15.74 6.5 Z M15.08 14.64 L18.16 14.64 C18.82 14.64 18.82 14.64 18.82 15.3 L18.82 17.5 C18.82 18.16 18.82 18.16 18.16 18.16 L15.08 18.16 C14.42 18.16 14.42 18.16 14.42 17.5 L14.42 15.3 C14.42 14.64 14.42 14.64 15.08 14.64 Z"}};var Vt="http://www.w3.org/2000/svg",si=4,ai=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Ut(e){let t=document.createElementNS(Vt,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","15"),t.setAttribute("height","15"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Vt,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function pn(){return Ut(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"])}function ri(){return Ut(["M6 4l14 8-14 8z"])}function Ys(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{mark:"claude",glyph:"A",color:"#d97757",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{mark:"codex",glyph:"O",color:"#10a37f",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity")||t==="agy")return{mark:"antigravity",glyph:"G",color:"#4285f4",title:"Antigravity"};if(t.includes("grok"))return{mark:"grok",glyph:"X",color:"#6b7280",title:"Grok"};if(t.includes("muse"))return{mark:"muse",glyph:"M",color:"#8b5cf6",title:"Muse"};if(t.includes("opencode"))return{mark:"opencode",glyph:"C",color:"#2563eb",title:"OpenCode"};if(t.includes("omp")||t.includes("oh-my-pi"))return{mark:"omp",glyph:"Ω",color:"#c026d3",title:"Oh My Pi"};if(t==="pi"||t.startsWith("pi/")||t.startsWith("@pi"))return{mark:"pi",glyph:"π",color:"#db2777",title:"Pi"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}function Xs(e){let t=ii[e];if(!t||!t.d)return null;let n=document.createElementNS(Vt,"svg");n.setAttribute("viewBox",t.viewBox||"0 0 24 24"),n.setAttribute("width","14"),n.setAttribute("height","14"),n.setAttribute("fill","currentColor"),n.setAttribute("aria-hidden","true");let i=document.createElementNS(Vt,"path");return i.setAttribute("d",t.d),n.appendChild(i),n}class un{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=h("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let a=document.createElement("div");a.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),a.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.planChipBtn=document.createElement("button"),this.planChipBtn.type="button",this.planChipBtn.className="bp-plan-chip bp-hidden",this.planChipBtn.setAttribute("data-testid","composer-plan-chip"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planChipIconHost=document.createElement("span"),this.planChipIconHost.className="bp-plan-chip-ic",this.planChipIconHost.appendChild(pn()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=h("gpui.mgmt.plan.tab","Plan"),this.planChipBtn.append(this.planChipIconHost,this.planChipLbl),this.planChipBtn.addEventListener("click",()=>this.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let r=document.createElement("div");r.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",r.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(r,this.memoryText);let o=document.createElement("div");o.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=h("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",h("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(Ut(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=h("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",h("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(Ut(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=h("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=h("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),o.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(a,this.planChipBtn,this.memoryEl,o),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(l)=>{let p=l.clipboardData?.items;if(!p)return;let c=[];for(let u=0;u0)l.preventDefault(),this.addFiles(c)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(l)=>{if(this.popupMode!=="none"){let p=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(l.key==="ArrowDown"){l.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,p),this.renderPopup();return}if(l.key==="ArrowUp"){l.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,p))%Math.max(1,p),this.renderPopup();return}if(l.key==="Tab"||l.key==="Enter"&&!l.shiftKey&&this.shouldCompleteOnEnter()){l.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(l.key==="Escape"){l.preventDefault(),this.closePopup();return}}if(l.key==="Tab"&&l.shiftKey&&this.planMode!==null){l.preventDefault(),this.cb.onCyclePlanMode?.();return}if(l.key==="Enter"&&!l.shiftKey)l.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=Ys(t),s=i.mark?Xs(i.mark):null;if(s)this.providerMarkEl.replaceChildren(s);else this.providerMarkEl.textContent=i.glyph;if(this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` +`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=h("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let a=`${h("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=a,this.planChipBtn.setAttribute("aria-label",a),this.planChipIconHost.replaceChildren(s?ri():pn()),this.planChipLbl.textContent=s?h("gpui.planmode.chip.building","Building"):t==="pending"?h("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?h("gpui.planmode.chip.once","Plan · 1t"):h("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?h("gpui.mgmt.plan.tab","Plan"):h("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let r=document.createElement("span");r.className="bp-plan-bar-ic",r.appendChild(s?ri():pn());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?h("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?h("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?h("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?h("gpui.planmode.bar.pending","Proposed plan awaits review below"):h("gpui.planmode.bar.executing","Building the approved plan");let l=[r,o];if(t==="armed"||t==="planning"){let p=document.createElement("div");p.className="bp-plan-scopes";let c=(u,d,m,f)=>{let b=document.createElement("button");return b.type="button",b.className="bp-plan-scope-btn"+(d?" active":""),b.textContent=u,b.disabled=!this.enabled,b.setAttribute("data-testid",f),b.addEventListener("click",()=>this.cb.onSetPlanMode?.(m)),b};p.append(c(h("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),c(h("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),c(h("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),l.push(p)}this.planBarEl.replaceChildren(...l)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let a=document.createElement("span");if(a.className="bp-reply-strip-line",a.textContent=h("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,a),t)i.addEventListener("click",t);let r=document.createElement("button");r.type="button",r.className="icon bp-reply-strip-drop",r.textContent="×";let o=h("reply.cancel","Cancel reply");if(r.title=o,r.setAttribute("aria-label",o),r.setAttribute("data-testid","composer-reply-drop"),n)r.addEventListener("click",n);this.replyEl.replaceChildren(i,r),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} +${t}`:e,this.autoGrow(),this.textarea.focus()}showError(e,t){let n=document.createElement("span");if(n.textContent=pe(e),t){let i=document.createElement("button");i.type="button",i.className="bp-composer-err-act",i.setAttribute("data-testid","composer-err-accounts"),i.textContent=t.label,i.addEventListener("click",t.onClick),this.errorEl.replaceChildren(n,i)}else this.errorEl.replaceChildren(n);this.errorEl.classList.remove("bp-hidden")}clearError(){this.errorEl.replaceChildren(),this.errorEl.classList.add("bp-hidden")}focus(){this.textarea.focus()}refreshLocale(){this.textarea.placeholder=h("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=h("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",h("web.composer.attach","Attach image")),this.voiceBtn.title=h("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",h("web.composer.voice","Voice dictation")),this.sendBtn.textContent=h("composer.send","Send"),this.stopBtn.textContent=h("composer.stop","Stop"),this.setPlanMode(this.planMode)}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` +`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.desc||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.detail||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),a=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=a+s,this.textarea.selectionStart=this.textarea.selectionEnd=a.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!ai.has(t.type)){this.showError(h("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=si){this.showError(h("web.composer.maximages","At most {max} images per message.",{max:si}));break}let n=await new Promise((s,a)=>{let r=new FileReader;r.onload=()=>s(String(r.result||"")),r.onerror=()=>a(Error("read failed")),r.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let a=document.createElement("button");a.type="button",a.className="icon bp-attach-rm",a.textContent="×",a.title=h("common.remove","Remove"),a.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,a),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function oi(e,t=fetch){let n=await t("/auth/web/logout",{method:"POST",credentials:"same-origin",redirect:"error",headers:{"Content-Type":"application/json"},body:"{}"});if(n.status!==200||(await n.json()).state!=="revoked")throw Error("Logout was not confirmed");e()}var Zs=new Set(["bom","checks","life","plan","fab"]);function Wt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&Zs.has(t.id))}function mi(e){let t=e?.badge?.n??0;if(!Number.isFinite(t)||t<=0)return null;return{text:t>99?"99+":String(Math.floor(t)),tone:e?.badge?.tone==="bad"?"bad":"warn"}}function _t(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=r}return i}function dt(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function pt(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var Qs=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),ea=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function hi(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let r of i)if(Qs.has(r))return r;let s=i[0]??"",a=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(ea.has(a)){let r=s.split("-");if(r.length>=2&&/^\d+$/.test(r[1]))return`${r[0]}-${r[1]}`;return r[0]}return i.slice(0,2).join("_")}function bi(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${dt(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${dt(n)}`,tone:"warn"};return{text:dt(n),tone:"ok"}}function gi(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((a)=>a==="dnp"&&Boolean(i.dnp)||s.includes(a))})}function fi(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function hn(e){if(e==="active")return{label:"Active",tone:"ok"};if(e==="nrnd")return{label:"NRND",tone:"warn"};if(e==="eol")return{label:"EOL",tone:"bad"};return{label:"Unknown",tone:"faint"}}function zt(e){if(!Number.isFinite(e)||e<=0)return"";let t=new Date(e*1000),n=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0");return`${n}-${i}-${s}`}function vi(e){return e.state==="routed"||e.state==="verified"}function yi(e){switch(e.state){case"approved":return"✓";case"edited":return"✎";case"verified":return"✓✓";case"routed":return"100%";case"rejected":case"failed":return"✗";case"routing":return typeof e.routed==="number"&&typeof e.total==="number"&&e.total>0?`${e.routed}/${e.total}`:"…";case"blocked":return`⚠ ${Math.max(1,e.problems??1)}`;default:return""}}function wi(e){switch(e.status){case"blocked":return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};case"routing":return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};case"awaiting":return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};case"verified":return{key:"gpui.mgmt.plan.st.verified",label:"Verified",tone:"ok"};case"routed":return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};case"ready":return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};case"partial":return{key:"gpui.mgmt.plan.st.partial",label:"Partial",tone:"warn"};case"rejected":return{key:"gpui.mgmt.plan.st.rejected",label:"Rejected",tone:"bad"};default:if((e.blocked??0)>0)return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(e.routing)return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if((e.awaiting??0)>0)return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}}function Ei(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,a=0;if(typeof e.total!=="number"){for(let r of e.layers??[])for(let o of r.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")a+=1;else if(o.state==="approved")n+=1}else if(e.routing)a=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:a,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function Ci(e){switch(e){case"current":return{text:"The fab's limits are in the DRC rules",button:null};case"stale":return{text:"The DRC rules have older fab limits",button:"Update"};case"none":return{text:"The fab's limits are not in the DRC rules",button:"Write"};default:return{text:"No KiCad project for DRC rules",button:null}}}function xi(e){return e==="extra"?"costs-more limits":"base-price limits"}function bn(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function ki(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function gn(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var li=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],ci=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function Si(e){let t=2166136261;for(let n=0;n>>0;return t}function Lt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#5a7a9a"&&n!=="#8a8a8a")return t;let i=e.toUpperCase();if(i.includes("3V3A")||i.includes("AVDD")||i.includes("VDDA"))return"#38bdf8";if(i.includes("1V8")||i.includes("1.8V"))return"#c084fc";if(i.includes("2V5")||i.includes("2.5V"))return"#a3e635";if(i.includes("3V3")||i.includes("3.3V")||i.includes("VCC"))return"#f59e0b";if(i.includes("5V")||i.startsWith("+5"))return"#ef4444";if(i.includes("12V")||i.includes("24V"))return"#f97316";if(i.includes("VBAT")||i.includes("VIN"))return"#ec4899";if(i.includes("GND"))return"#2dd4bf";return li[Si(i)%li.length]}function ut(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return ci[Si(e)%ci.length]}function Ai(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),a=Math.max(1,Math.abs(e[3]-e[1])),r=Math.max(20,t-i*2),o=Math.max(20,n-i*2),l=Math.max(0.05,Math.min(200,Math.min(r/s,o/a)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:l,fitted:l,touched:!1}}function Ve(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function qt(e,t,n,i,s){let a=Math.max(0.0001,e.scale);return[e.cx+(t-i*0.5)/a,e.cy+(n-s*0.5)/a]}function Li(e,t,n){let i=Math.max(0.0001,e.scale);return{...e,cx:e.cx-t/i,cy:e.cy-n/i,touched:!0}}function Pi(e,t,n,i,s,a){let r=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),l=Math.max(r,Math.min(o,e.scale*t)),[p,c]=qt(e,n,i,s,a);return{...e,cx:p-(n-s*0.5)/l,cy:c-(i-a*0.5)/l,scale:l,touched:!0}}function Ni(e,t,n,i){let s=e.map((r)=>[r[0],r[1]]);if(s.length===0)return[n];let a=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(a,0,[n[0],n[1]]),s}function fn(e,t,n){let i=n?3:2;if(e.length<=i||t<0||t>=e.length)return null;let s=e.map((a)=>[a[0],a[1]]);return s.splice(t,1),s}function ta(e,t,n,i,s,a){let r=s-n,o=a-i,l=r*r+o*o;if(l<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let p=Math.max(0,Math.min(1,((e-n)*r+(t-i)*o)/l)),c=n+p*r,u=i+p*o;return(e-c)*(e-c)+(t-u)*(t-u)}function di(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,a=n.length-1;st!==p>t&&e<(l-r)*(t-o)/(p-o+0.000000000001)+r)i=!i}return i}function vn(e,t){return Math.max(5,Math.min(32,e*t))}function Kt(e,t,n,i,s,a,r,o,l){if(i){for(let d of e){if(d.layer!==n||d.id!==i||d.locked)continue;let m=d.path??[];for(let f=0;f=3)for(let f=0;f=0;d--){let m=t[d];if(m.layer!==n)continue;let f=m.outline??[];if(!di(c,u,f))continue;if(!(m.holes??[]).some((g)=>di(c,u,g)))return{kind:"region",id:m.id}}return null}function mt(e){let t=null,n=null,i=[];for(let a of e){if(!a.layer)continue;i.push(a.layer);let r=a.items??[],o=r.filter((p)=>p.kind==="corridor").length,l=r.filter((p)=>p.kind==="plane").length;if((o>0||a.role==="signal")&&(!t||o>t.count))t={count:o,layer:a.layer};if((l>0||a.role==="power"||a.role==="plane")&&(!n||l>n.count))n={count:l,layer:a.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let a of i){if(s.length>=2)break;if(!s.includes(a))s.push(a)}return s}function pi(e,t){if(!e||e.length===0)return null;if(e.length===1)return e[0];let n=Math.max(0,Math.min(1,t)),i=0;for(let r=1;r=s&&o>0.000000001){let l=(s-a)/o;return[e[r-1][0]+(e[r][0]-e[r-1][0])*l,e[r-1][1]+(e[r][1]-e[r-1][1])*l]}a+=o}return e[e.length-1]}function st(e,t,n){for(let i of t??[])if(i.layer===e&&i.title)return i.title;for(let i of n??[])if(i.layer===e&&i.title)return i.title;return e}function Mi(e,t,n){if(e==="split"&&n.length>0)return t.filter((i)=>n.includes(i.layer));return t}function mn(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function ui(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,a=n.length-1;st!==p>t&&e<(l-r)*(t-o)/(p-o+0.000000000001)+r)i=!i}return i}function Ti(e,t){if(e.length<3)return null;let n=1/0,i=1/0,s=-1/0,a=-1/0,r=0,o=0;for(let p of e)n=Math.min(n,p[0]),i=Math.min(i,p[1]),s=Math.max(s,p[0]),a=Math.max(a,p[1]),r+=p[0],o+=p[1];let l=[[(n+s)*0.5,(i+a)*0.5],[r/e.length,o/e.length]];for(let p of[0.5,0.25,0.75,0.125,0.875])for(let c of[0.5,0.25,0.75,0.125,0.875])l.push([n+(s-n)*c,i+(a-i)*p]);for(let p of l)if(ui(p[0],p[1],e)&&!t.some((c)=>ui(p[0],p[1],c)))return p;return null}function Bi(e,t,n,i,s,a){let r=[];for(let c of e){let u=c.nets??0,d=c.path??[];if(u<=0||d.length<2)continue;let m=0;for(let f=1;f{let d=c.sel||c.hov?1:0,m=u.sel||u.hov?1:0;if(m!==d)return m-d;if(u.nets!==c.nets)return u.nets-c.nets;return c.b.id.localeCompare(u.b.id)});let o=[],l=[],p=(c,u,d,m,f)=>[c-d*0.5-f,u-m*0.5-f,c+d*0.5+f,u+m*0.5+f];for(let c of r){let u=c.b.name||"",d=String(c.nets),m=u?`${u} · ${c.nets}`:d,f=(c.sel||c.hov||c.pxLen>=95)&&u?[m,d]:[d],b=null,g=(w,x)=>Math.max(x*0.5+3,Math.min(Math.max(x*0.5+3,n-x*0.5-3),w)),y=(w,x)=>Math.max(x*0.5+3,Math.min(Math.max(x*0.5+3,i-x*0.5-3),w));e:for(let w of f){let x=Math.max(16,w.length*5.9+10),A=15;for(let N of[0.5,0.35,0.65,0.22,0.78]){let S=pi(c.pts,N);if(!S)continue;let[M,B]=Ve(t,S[0],S[1],n,i),R=g(M,x),U=y(B,15),D=p(R,U,x,15,2);if(!o.some((re)=>mn(D,re))){b={id:c.b.id,text:w,cx:R,cy:U,pw:x,ph:15,col:c.col,sel:c.sel};break e}}}if(!b){let w=pi(c.pts,0.5);if(w){let[x,A]=Ve(t,w[0],w[1],n,i),N=Math.max(16,d.length*6.5+8),S=15,M=g(x,N);for(let B of[-18,18]){let R=y(A+B,15);if(!o.some((U)=>mn(p(M,R,N,15,2),U))){b={id:c.b.id,text:d,cx:M,cy:R,pw:N,ph:15,col:c.col,sel:c.sel};break}}}}if(b)o.push(p(b.cx,b.cy,b.pw,b.ph,2)),l.push(b)}return l}function Ii(e,t,n,i,s,a=[]){let r=new Set(s),o=[];for(let c of e){if(!c.r||!c.b||c.b.length!==4)continue;let[u,d]=Ve(t,c.b[0],c.b[1],n,i),[m,f]=Ve(t,c.b[2],c.b[3],n,i),b=Math.abs(m-u),g=Math.abs(f-d);if(b<13||g<9)continue;let y=(u+m)*0.5,w=(d+f)*0.5;if(y<8||y>n-8||w<8||w>i-8)continue;o.push({text:c.r,cx:y,cy:w,bw:c.r.length*5.8+4,bh:11,score:b*g+(r.has(c.r)?1e4:0)})}o.sort((c,u)=>u.score-c.score);let l=[...a],p=[];for(let c of o){let u=[c.cx-c.bw*0.5,c.cy-c.bh*0.5,c.cx+c.bw*0.5,c.cy+c.bh*0.5];if(!l.some((m)=>mn(u,m)))l.push(u),p.push({text:c.text,cx:c.cx,cy:c.cy})}return p}function Ri(e){if(!e||typeof e!=="object")return null;let t=e;if(t.panel&&typeof t.panel==="object")return t.panel;if(t.result&&typeof t.result==="object"){let n=t.result.panel;if(n&&typeof n==="object")return n}return null}function Jt(e,t){if(!t||t.length===0)return e;let n=new Map;for(let a of e)if(a.layer)n.set(a.layer,a);let i=[],s=new Set;for(let a of t){if(!a.layer)continue;s.add(a.layer);let r=n.get(a.layer);if(r)i.push(r);else i.push({layer:a.layer,index:a.index,title:a.title||`L${a.index} · ${a.layer}`,subtitle:a.subtitle||"",role:a.role,status:"proposed",done:0,approved:0,total:0,items:[]})}for(let a of e)if(a.layer&&!s.has(a.layer))i.push(a);return i}function ji(e,t,n,i,s,a,r,o){return e===t&&n===i&&s===a&&(o===void 0||r>=o)}var Di="#111917",na="#16201d",ia="rgba(212, 224, 219, 0.92)",sa="rgba(61, 80, 73, 0.72)",aa="rgba(82, 107, 97, 0.85)";var Hi="#f59e0b",ra="#eef5f2",Fi="#ef4444";function at(e,t){let n=e.trim().replace(/^#/,"");if(n.length===6){let i=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),a=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(a))return`rgba(${i}, ${s}, ${a}, ${t})`}return`rgba(20, 184, 166, ${t})`}function oa(e,t,n){let i=0.14,s=0.45,a=0.85,r=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,a=0.91;break;case"edited":i=0.2,s=0.56,a=0.95;break;case"routed":case"verified":i=0.08,s=0.26,a=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,a=0.27;break;case"blocked":i=0.18,s=0.48,a=0.88,r=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),a=1;else if(n)i=Math.min(0.28,i+0.06),s=Math.min(0.63,s+0.07);return{glow:i,body:s,core:a,bad:r}}function la(e,t,n){let i=0.27,s=0.83,a=!1;switch(e){case"approved":case"routing":i=0.36,s=0.91;break;case"edited":i=0.38,s=0.95;break;case"routed":case"verified":i=0.16,s=0.54;break;case"rejected":case"failed":i=0.08,s=0.27;break;case"blocked":i=0.31,s=0.94,a=!0;break}if(t)i=Math.min(0.53,i+0.12),s=1;else if(n)i=Math.min(0.45,i+0.06),s=Math.min(1,s+0.1);return{fill:i,edge:s,bad:a}}function ca(e){let t=e.items??[];if(t.some((n)=>n.state==="blocked"||n.state==="failed"))return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(t.some((n)=>n.state==="routing"))return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if(t.some((n)=>n.state==="proposed"||n.state==="edited"))return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};if(t.length>0&&t.every((n)=>n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};if(t.length>0&&t.every((n)=>n.state==="approved"||n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}class yn{root;cb;state=null;cards=new Map;renderedLayerKey="";sharedCam=null;layerCams=new Map;hover=null;selectedVertex=null;drag=null;downPos=null;rafPending=0;constructor(e){this.cb=e,this.root=document.createElement("div"),this.root.className="bp-plan-canvas-grid",this.root.tabIndex=0,this.root.setAttribute("data-testid","mgmt-plan-canvas-grid"),this.root.addEventListener("keydown",(t)=>this.onKeyDown(t))}isDragging(){return this.drag!==null}fitAll(){this.sharedCam=null,this.layerCams.clear(),this.scheduleDraw()}destroy(){if(this.rafPending)cancelAnimationFrame(this.rafPending),this.rafPending=0;for(let e of this.cards.values())e.ro.disconnect();this.cards.clear(),this.root.replaceChildren()}visibleLayers(e){let t=Jt(e.layers,e.copperLayers);if(t.length===0)return[];if(e.gridMode==="all")return t;if(e.gridMode==="single"){let s=e.shownLayers.find((r)=>t.some((o)=>o.layer===r))??mt(t)[0]??t[0]?.layer,a=t.find((r)=>r.layer===s);return a?[a]:[]}let n=e.shownLayers.length>0&&e.shownLayers.every((s)=>t.some((a)=>a.layer===s))?e.shownLayers.slice(0,2):mt(t),i=[];for(let s of n){let a=t.find((r)=>r.layer===s);if(a)i.push(a)}return i.length>0?i:t.slice(0,2)}update(e,t){this.state=e;let n=this.visibleLayers(e);this.root.classList.toggle("two-cols",t&&n.length>1);let i=n.map((s)=>s.layer).join("|");if(i!==this.renderedLayerKey){this.renderedLayerKey=i;for(let s of this.cards.values())s.ro.disconnect();this.cards.clear(),this.root.replaceChildren();for(let s of n){let a=this.buildCard(s);this.cards.set(s.layer,a),this.root.appendChild(a.el)}}else for(let s of n){let a=this.cards.get(s.layer);if(a)this.syncCardHeaderAndLegend(a,s)}this.scheduleDraw()}effectiveBbox(e){let t=e.bbox;if(!t||t.length!==4||Math.abs(t[2]-t[0])<0.5||Math.abs(t[3]-t[1])<0.5)return[0,0,100,70];return t}getCam(e,t,n){let i=this.state,s=i?.syncZoom?this.sharedCam:this.layerCams.get(e)??null;if(s&&s.touched)return s;return Ai(i?this.effectiveBbox(i.board):[0,0,100,70],t,n,14)}setCam(e,t){if(this.state?.syncZoom)this.sharedCam=t;else this.layerCams.set(e,t)}buildCard(e){let t=document.createElement("section");t.className="bp-plan-card",t.setAttribute("data-testid",`mgmt-plan-card-${e.layer}`);let n=document.createElement("div");n.className="bp-plan-card-head";let i=document.createElement("div");i.className="bp-plan-card-head-top";let s=document.createElement("span"),a=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((w)=>w.kind==="plane");s.className="bp-plan-card-bar "+(a?"pwr":"sig");let r=document.createElement("span");r.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn bp-plan-mini-btn",l.textContent="✓",l.title=h("gpui.mgmt.plan.layer","Approve layer"),l.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let p=document.createElement("button");p.type="button",p.className="bp-mgmt-btn bp-plan-mini-btn",p.textContent="✗",p.title=h("gpui.mgmt.plan.rejectlayer","Reject layer"),p.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,r,o,l,p);let c=document.createElement("div");c.className="bp-plan-card-sub",n.append(i,c);let u=document.createElement("div");u.className="bp-plan-card-canvas-wrap";let d=document.createElement("canvas");d.className="bp-plan-card-canvas",d.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let m=document.createElement("div");m.className="bp-plan-hover-hud bp-hidden",u.append(d,m);let f=document.createElement("div");f.className="bp-plan-legend bp-hidden",t.append(n,u,f);let b=d.getContext("2d"),g=new ResizeObserver(()=>this.scheduleDraw());g.observe(u),this.attachPointerListeners(d,e.layer);let y={layer:e.layer,el:t,canvas:d,ctx:b,legendEl:f,okBtn:l,noBtn:p,statusEl:o,titleEl:r,subtitleEl:c,hoverHudEl:m,ro:g};return this.syncCardHeaderAndLegend(y,e),y}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=st(t.layer,this.state?.copperLayers,this.state?.layers)||t.title||t.layer;let n=t.subtitle||t.stackup||"";e.subtitleEl.textContent=n,e.subtitleEl.classList.toggle("bp-hidden",!n);let i=t.items??[],s=ca(t);e.statusEl.className=`bp-plan-card-status tone-${s.tone==="warn"?"dim":s.tone}`,e.statusEl.textContent=i.length>0?h(s.key,s.label):"",e.statusEl.classList.toggle("bp-hidden",i.length===0);let a=i.some((o)=>o.state==="proposed"||o.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!a);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!a);let r=(this.state?.regions??[]).filter((o)=>o.layer===t.layer);if(r.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let o=document.createDocumentFragment();for(let l of r){let p=document.createElement("button");p.type="button";let c=this.state?.selectedId===l.id;p.className="bp-plan-legend-chip"+(c?" active":"");let u=document.createElement("span");u.className="bp-plan-legend-sw",u.style.background=Lt(l.net||l.id,l.color||"");let d=document.createElement("span");d.textContent=l.net||l.id,p.append(u,d),p.addEventListener("click",()=>{this.cb.onSelect(l.id),this.cb.onFocusItem(l.id)}),o.appendChild(p)}e.legendEl.replaceChildren(o)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(i)=>i.preventDefault()),e.addEventListener("dblclick",()=>this.fitAll()),e.addEventListener("pointerdown",(i)=>{let s=this.state;if(!s)return;this.root.focus({preventScroll:!0});let a=e.getBoundingClientRect(),r=i.clientX-a.left,o=i.clientY-a.top,l=Math.max(1,a.width),p=Math.max(1,a.height),c=this.getCam(t,l,p),u=Kt(s.bands,s.regions,t,s.selectedId,c,l,p,r,o);if(i.button===2){if(u?.kind==="vertex"){let d=this.getItemPts(u.id,u.isPlane),m=fn(d,u.idx,u.isPlane);if(m)this.selectedVertex=null,this.cb.onCommitFields(u.id,{[u.isPlane?"outline":"path"]:m})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},u?.kind==="vertex"){let d=this.getItemPts(u.id,u.isPlane),m=d.map((f)=>[f[0],f[1]]);this.selectedVertex={id:u.id,idx:u.idx},this.drag={layer:t,kind:"vertex",id:u.id,isPlane:u.isPlane,idx:u.idx,pts:d.map((f)=>[f[0],f[1]]),origPts:m,moved:!1},this.scheduleDraw()}else if(u?.kind==="midpoint"){let d=this.getItemPts(u.id,u.isPlane),m=d.map((g)=>[g[0],g[1]]),f=Ni(d,u.segIdx,u.pos,u.isPlane),b=u.isPlane&&u.segIdx+1>=d.length?f.length-1:Math.min(u.segIdx+1,f.length-1);this.selectedVertex={id:u.id,idx:b},this.patchLocalItem(u.id,u.isPlane,f),this.drag={layer:t,kind:"vertex",id:u.id,isPlane:u.isPlane,idx:b,pts:f,origPts:m,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:r,lastY:o}}),e.addEventListener("pointermove",(i)=>{let s=this.state;if(!s)return;let a=e.getBoundingClientRect(),r=i.clientX-a.left,o=i.clientY-a.top,l=Math.max(1,a.width),p=Math.max(1,a.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let A=this.getCam(t,l,p);this.setCam(t,Li(A,r-this.drag.lastX,o-this.drag.lastY)),this.drag.lastX=r,this.drag.lastY=o,this.scheduleDraw();return}if(this.downPos&&Math.hypot(i.clientX-this.downPos.x,i.clientY-this.downPos.y)<1.5&&!this.drag.moved)return;let b=this.getCam(t,l,p),[g,y]=qt(b,r,o,l,p),w=[Math.round(g*1000)/1000,Math.round(y*1000)/1000];this.drag.moved=!0,this.drag.pts[this.drag.idx]=w;let x=this.drag.pts.map((A)=>[A[0],A[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,x),this.scheduleDraw();return}let c=this.getCam(t,l,p),u=Kt(s.bands,s.regions,t,s.selectedId,c,l,p,r,o),d=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",m=this.hover?.hit.kind??"",f=u?u.id:"";if(this.hover=u?{layer:t,hit:u}:null,e.style.cursor=u?"pointer":"crosshair",d!==f||(u?.kind??"")!==m)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()});let n=()=>{let i=this.drag;if(!i||i.layer!==t)return;if(this.drag=null,this.downPos=null,i.kind==="vertex"&&i.moved){let s=i.origPts.map((a)=>[a[0],a[1]]);this.patchLocalItem(i.id,i.isPlane,s)}this.cb.onDragEnd?.(),this.scheduleDraw()};e.addEventListener("pointercancel",n),e.addEventListener("lostpointercapture",n),e.addEventListener("pointerup",(i)=>{let s=this.state,a=this.drag,r=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(i.pointerId))e.releasePointerCapture(i.pointerId);if(a&&a.kind==="vertex"&&a.layer===t){if(a.moved)this.cb.onCommitFields(a.id,{[a.isPlane?"outline":"path"]:a.pts});else this.cb.onDragEnd?.(),this.scheduleDraw();return}if(s&&r&&Math.hypot(i.clientX-r.x,i.clientY-r.y)<4.5){let o=e.getBoundingClientRect(),l=i.clientX-o.left,p=i.clientY-o.top,c=Math.max(1,o.width),u=Math.max(1,o.height),d=this.getCam(t,c,u),m=Kt(s.bands,s.regions,t,s.selectedId,d,c,u,l,p);if(m&&(m.kind==="band"||m.kind==="region")){this.cb.onSelect(m.id),this.cb.onFocusItem(m.id);return}if(!m&&s.selectedId){this.cb.onSelect("");return}}this.cb.onDragEnd?.()}),e.addEventListener("wheel",(i)=>{i.preventDefault();let s=e.getBoundingClientRect(),a=i.clientX-s.left,r=i.clientY-s.top,o=Math.max(1,s.width),l=Math.max(1,s.height),p=this.getCam(t,o,l),c=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,Pi(p,c,a,r,o,l)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((a)=>a.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((a)=>a.id===e);if(s){if(s.path=n,s.edited=!0,s.state==="proposed")s.state="edited"}}}getItemPts(e,t){let n=this.state;if(!n)return[];if(t)return(n.regions.find((i)=>i.id===e)?.outline??[]).map((i)=>[i[0],i[1]]);return(n.bands.find((i)=>i.id===e)?.path??[]).map((i)=>[i[0],i[1]])}syncHoverHud(e){let t=this.cards.get(e),n=this.state;if(!t||!n)return;if(!this.hover||this.hover.layer!==e){t.hoverHudEl.classList.add("bp-hidden"),t.hoverHudEl.textContent="";return}let i=this.hover.hit.id,s=n.bands.find((o)=>o.id===i),a=n.regions.find((o)=>o.id===i),r="";if(s)r=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(a)r=a.reference?`${a.net||i} · ${a.reference}`:a.net||i;if(!r)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=r}onKeyDown(e){let t=this.state;if(!t)return;if(e.key==="0"||e.key==="Home"){e.preventDefault(),this.fitAll();return}if(e.key==="Escape"){this.selectedVertex=null,this.cb.onSelect("");return}if(!t.selectedId)return;let n=t.bands.find((r)=>r.id===t.selectedId),i=t.regions.find((r)=>r.id===t.selectedId),s=Boolean(n?.locked??i?.locked),a=e.key.toLowerCase();if(a==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(a==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(a==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(a==="w"&&n&&!s){e.preventDefault();let r=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+r))*100)/100;this.cb.onCommitFields(t.selectedId,{width:o})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let r=Boolean(i),o=this.getItemPts(t.selectedId,r),l=fn(o,this.selectedVertex.idx,r);if(l)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[r?"outline":"path"]:l})}}scheduleDraw(){if(this.rafPending)return;this.rafPending=requestAnimationFrame(()=>{this.rafPending=0,this.drawAll()})}drawAll(){let e=this.state;if(!e)return;let t=Math.max(0.45,Math.min(1.25,Math.abs(this.effectiveBbox(e.board)[3]-this.effectiveBbox(e.board)[1])/Math.max(1,Math.abs(this.effectiveBbox(e.board)[2]-this.effectiveBbox(e.board)[0]))));for(let n of this.cards.values()){let i=n.canvas.parentElement;if(!i)continue;let s=Math.max(120,Math.round(i.clientWidth)),a=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${a}px`;let r=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*r),l=Math.round(a*r);if(n.canvas.width!==o||n.canvas.height!==l)n.canvas.width=o,n.canvas.height=l;n.ctx.setTransform(r,0,0,r,0,0),this.drawLayer(n.ctx,n.layer,s,a,e)}}drawLayer(e,t,n,i,s){let a=this.getCam(t,n,i),r=(b,g)=>Ve(a,b,g,n,i);e.fillStyle=Di,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((b)=>b.length>=3);if(e.fillStyle=na,o.length>0){e.beginPath();for(let b of o){for(let g=0;gb.layer===t),p=this.hover?.layer===t?this.hover.hit:null;for(let b of l){let g=b.outline??[];if(g.length<3)continue;let y=s.selectedId===b.id,w=p?.id===b.id,x=la(b.state||"proposed",y,w),A=Lt(b.net||b.id,b.color||"");e.beginPath();for(let S=0;SB)B=D;if(re>R)R=re}if(Math.abs(B-S)>=38&&Math.abs(R-M)>=18){let U=Ti(g,b.holes??[]);if(U){let[D,re]=r(U[0],U[1]);e.fillStyle=at(A,y?0.91:0.67),e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(N,D,re)}}}}if(e.strokeStyle=ia,e.lineWidth=1.25,e.lineCap="round",e.lineJoin="round",o.length>0){e.beginPath();for(let b of o){for(let g=0;gb.layer===t),d=Bi(u,a,n,i,s.selectedId,p?.id??""),m=d.map((b)=>[b.cx-b.pw*0.5-1,b.cy-b.ph*0.5-1,b.cx+b.pw*0.5+1,b.cy+b.ph*0.5+1]),f=[];for(let b of u){for(let g of b.from??[])f.push(g);for(let g of b.to??[])f.push(g)}e.fillStyle="rgba(143, 163, 155, 0.72)",e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let b of Ii(c,a,n,i,f,m))e.fillText(b.text,b.cx,b.cy);for(let b of u){let g=b.guides??[];if(g.length===0)continue;let y=s.selectedId===b.id||p?.id===b.id,w=ut(b.name||b.id,b.color||"");e.strokeStyle=at(w,y?0.38:0.17),e.lineWidth=y?1:0.7,e.beginPath();for(let x of g){let[A,N]=r(x[0],x[1]),[S,M]=r(x[2],x[3]);e.moveTo(A,N),e.lineTo(S,M)}e.stroke()}for(let b of u){let g=b.path??[];if(g.length<2)continue;let y=s.selectedId===b.id,w=p?.id===b.id,x=oa(b.state||"proposed",y,w),A=ut(b.name||b.id,b.color||""),N=vn(b.width??1.5,a.scale),S=()=>{e.beginPath();for(let M=0;M{let w=y?g.length:Math.max(0,g.length-1);for(let x=0;xn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return Wt(this.getStateInfo())}isOpen(){return this.openPanel!==""}closePanel(){if(!this.openPanel)return;if(this.openPanel="",this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:""}).catch(()=>{});this.render()}clear(){this.watchGen++,this.bomEditGen++,this.askedProject="",this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydrateGen++,this.planHydratedRev=void 0,this.planRenderDeferred=!1,this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.render()}async watchProject(e){if(!e||!this.cb.hub.hasFeature("mgmt")){this.clear();return}if(e===this.askedProject&&this.digest){this.render();return}let t=++this.watchGen;if(this.askedProject=e,this.project!==e)this.bomEditGen++,this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomSelectedId="",this.bomEditingId="",this.bomEditStatus="",this.bomLastUndo=null,this.checksSelectedId="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydrateGen++,this.planHydratedRev=void 0,this.planRenderDeferred=!1,this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.lifeSelectedKey="",this.lifePartSamples=null,this.render();try{let n=await this.cb.hub.rpc("mgmt.watch",{project:e});if(t!==this.watchGen)return;let i=typeof n.digest==="string"?n.digest:"";if(!i){this.render();return}if(this.digest=i,this.project=typeof n.project==="string"&&n.project?n.project:e,n.state&&typeof n.state==="object")this.infos.set(`mgmt.state.${i}`,n.state);if(n.data&&typeof n.data==="object"){for(let[s,a]of Object.entries(n.data))if(a&&typeof a==="object")this.infos.set(`mgmt.${s}.${i}`,a)}this.errorMsg="",this.render()}catch{if(t===this.watchGen)this.render()}}handleInfo(e){let t=!1;for(let[n,i]of Object.entries(e)){if(!n.startsWith("mgmt.")&&!n.startsWith("kicad.checks."))continue;if(i===""||i===null||i===void 0){if(this.infos.delete(n))t=!0;continue}if(typeof i==="string")try{let s=JSON.parse(i);if(s&&typeof s==="object")this.infos.set(n,s),t=!0}catch{}else if(typeof i==="object")this.infos.set(n,i),t=!0}if(t)this.render()}getStateInfo(){if(!this.digest)return null;return this.infos.get(`mgmt.state.${this.digest}`)??null}getPanelData(e){if(!this.digest)return null;return this.infos.get(`mgmt.${e}.${this.digest}`)??null}togglePanel(e){let t=this.openPanel===e?"":e;if(this.openPanel=t,this.errorMsg="",this.render(),this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:t}).catch((n)=>{this.errorMsg=n instanceof Error?n.message:"Could not update panel",this.render()})}render(){if(this.openPanel==="plan"&&this.planCanvas?.isDragging()){this.planRenderDeferred=!0;return}this.planRenderDeferred=!1;let e=this.getStateInfo(),t=Wt(e);if(!this.digest||t.length===0){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let r of t){let o=document.createElement("button");o.type="button";let l=this.openPanel===r.id;o.className="bp-mgmt-tab"+(l?" active":""),o.setAttribute("data-testid",`mgmt-tab-${r.id}`),o.setAttribute("aria-pressed",l?"true":"false");let p=document.createElement("span");p.textContent=pe(r.label),o.appendChild(p);let c=this.getPanelData(r.id),u=mi(c);if(u){let d=document.createElement("span");d.className=`bp-mgmt-badge bp-tone-${u.tone}`,d.textContent=u.text,o.appendChild(d)}o.addEventListener("click",()=>this.togglePanel(r.id)),i.appendChild(o)}if(n.appendChild(i),this.openPanel){let r=document.createElement("button");r.type="button",r.className="icon bp-mgmt-close",r.textContent="×",r.title=h("gpui.mgmt.close","Close the panel"),r.setAttribute("aria-label",h("gpui.mgmt.close","Close the panel")),r.setAttribute("data-testid","mgmt-close"),r.addEventListener("click",()=>this.closePanel()),n.appendChild(r)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}if(this.openPanel!=="plan")this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded");else this.panelEl.classList.toggle("bp-plan-expanded",this.planExpanded);this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=this.openPanel==="plan"&&this.planCanvas!==null&&document.activeElement instanceof HTMLElement&&this.panelEl.contains(document.activeElement)&&(document.activeElement===this.planCanvas.root||this.planCanvas.root.contains(document.activeElement)),a=document.createDocumentFragment();if(this.errorMsg){let r=document.createElement("div");r.className="bp-mgmt-note bp-tone-bad",r.textContent=this.errorMsg,a.appendChild(r)}switch(this.openPanel){case"bom":a.appendChild(this.renderBom());break;case"checks":a.appendChild(this.renderChecks());break;case"life":a.appendChild(this.renderLife());break;case"plan":a.appendChild(this.renderPlan());break;case"fab":a.appendChild(this.renderFab());break}if(this.panelEl.replaceChildren(a),s)this.planCanvas?.root.focus({preventScroll:!0})}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let a=document.createElement("span"),r=t.source==="kicad";if(a.className="bp-mgmt-pill"+(r?" accent":""),a.textContent=r?"live":"saved",i.append(s,a),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let p=document.createElement("span");p.className="bp-dim",p.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${pt(t.cost)}/board`:`${pt(t.cost)}/board`,i.appendChild(p)}if(t.paused){let p=document.createElement("span");p.className="bp-mgmt-faint",p.textContent="Stock check paused",i.appendChild(p)}if(e.appendChild(i),t.stock_note){let p=document.createElement("div");p.className="bp-mgmt-note bp-mgmt-faint",p.textContent=pe(t.stock_note),e.appendChild(p)}let o=this.bomEditingId?n.find((p)=>p.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let p=document.createElement("div");p.className="bp-mgmt-filter-row";let c=document.createElement("input");c.type="text",c.className="bp-mgmt-filter",c.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",c.value=this.bomFilter,c.setAttribute("data-testid","mgmt-bom-filter"),c.addEventListener("input",()=>{this.bomFilter=c.value,this.renderBomRows(l,n)}),p.appendChild(c),e.appendChild(p)}let l=document.createElement("div");return l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(l,n),e.appendChild(l),e}renderBomRows(e,t){let n=gi(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((a)=>Boolean(a.mpn)||Boolean(a.fab)),s=document.createDocumentFragment();for(let a of n){let r=Array.isArray(a.refs)?a.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===a.id?" active":"")+(a.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${a.id}`);let l=document.createElement("div");l.className="bp-mgmt-row-line";let p=document.createElement("span");if(p.className="bp-mgmt-strong bp-mgmt-flex1",p.textContent=_t(r,24),l.appendChild(p),a.dnp){let b=document.createElement("span");b.className="bp-mgmt-pill",b.textContent=h("gpui.mgmt.bom.dnp","DNP"),l.appendChild(b)}else{let b=bi(a.stock);if(b){let g=document.createElement("span");g.className=`bp-tone-${b.tone}`,g.textContent=b.text,l.appendChild(g)}}let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn",c.textContent="Edit",c.addEventListener("click",(b)=>{b.stopPropagation(),this.bomEditGen++,this.bomEditingId=a.id,this.bomEditDraft=a.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),l.appendChild(c);let u=document.createElement("div");u.className="bp-mgmt-row-sub";let d=[`${a.qty??r.length}×`,a.value??"",hi(a.footprint??"")].filter(Boolean).join(" · "),m=document.createElement("span");m.className="bp-dim",m.textContent=d;let f=document.createElement("span");if(f.className="bp-mgmt-flex1",a.mpn)f.textContent=a.mpn;else if(i&&!a.dnp)f.className+=" bp-tone-warn",f.textContent=h("gpui.mgmt.bom.nompn","no MPN");if(u.append(m,f),!a.dnp&&typeof a.stock?.price==="number"){let b=document.createElement("span");b.className="bp-dim",b.textContent=pt(a.stock.price),u.appendChild(b)}if(!a.dnp&&a.stock?.class){let b=document.createElement("span");b.className="bp-mgmt-faint",b.textContent=pe(a.stock.class),u.appendChild(b)}o.append(l,u),o.addEventListener("click",()=>{this.bomSelectedId=a.id,this.renderBomRows(e,t)}),s.appendChild(o)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=_t(n,30);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,a);let r=document.createElement("input");r.type="text",r.className="bp-mgmt-filter",r.placeholder="MPN",r.value=this.bomEditDraft,r.addEventListener("input",()=>{this.bomEditDraft=r.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),l=async(d,m=!1)=>{let f=o();this.bomEditStatus="Writing…",this.render();try{let b=await this.cb.hub.rpc("mgmt.bom.edit",d);if(!bn(f,o()))return;this.bomLastUndo=!m&&(b.changed??0)>0?{project:d.project,editId:f.editId,refs:d.refs.slice(),field:d.field,was:typeof b.was==="string"?b.was:d.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=m?"Restored":(b.changed??0)===0?"No change":b.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(b){if(!bn(f,o()))return;this.bomEditStatus=b instanceof Error?b.message:"Could not save edit"}this.render()},p=document.createElement("div");p.className="bp-mgmt-btn-row";let c=document.createElement("button");c.type="button",c.className="primary bp-mgmt-btn",c.textContent="Save MPN",c.addEventListener("click",()=>{l({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let u=document.createElement("button");if(u.type="button",u.className="bp-mgmt-btn",u.textContent=e.dnp?"Clear DNP":"Mark DNP",u.addEventListener("click",()=>{l({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),p.append(c,u),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let d=this.bomLastUndo,m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn",m.textContent="Undo",m.addEventListener("click",()=>{l(ki(d),!0)}),p.appendChild(m)}if(t.append(i,r,p),this.bomEditStatus){let d=document.createElement("div");d.className="bp-mgmt-faint",d.textContent=this.bomEditStatus,t.appendChild(d)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((d)=>d.source).filter(Boolean))),s=(d)=>t.sources?.[d]?.label||d.toUpperCase(),a=(d)=>t.sources?.[d]?.judged===!0,r=document.createElement("div");r.className="bp-mgmt-head bp-mgmt-scroll-x";let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),o.textContent=h("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),r.appendChild(o);for(let d of i){let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn"+(this.checksSource===d?" active":""),m.textContent=s(d)+(a(d)?" · judged":""),m.addEventListener("click",()=>{this.checksSource=this.checksSource===d?"":d,this.render()}),r.appendChild(m)}let l=document.createElement("span");l.className="bp-mgmt-flex1";let p=document.createElement("button");if(p.type="button",p.className="bp-mgmt-btn",p.textContent=h("gpui.mgmt.checks.run","Run"),p.addEventListener("click",()=>{let d=this.watchGen,m=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:m}).then(()=>{if(d!==this.watchGen||m!==this.project)return;this.checksStatus="",this.render()}).catch((f)=>{if(d!==this.watchGen||m!==this.project)return;this.checksStatus=f instanceof Error?f.message:"Could not run checks",this.render()})}),r.append(l,p),e.appendChild(r),this.checksStatus){let d=document.createElement("div");d.className="bp-mgmt-note bp-dim",d.textContent=this.checksStatus,e.appendChild(d)}let c=document.createElement("div");c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-checks-rows");let u=fi(n,this.checksSource);if(u.length===0)c.appendChild(this.makeEmpty("No check findings."));else for(let d of u){let m=d.severity==="error"?"bad":d.severity==="warning"?"warn":"faint",f=document.createElement("div");f.className="bp-mgmt-group-head";let b=document.createElement("span");b.className=`bp-mgmt-dot bp-tone-bg-${m}`;let g=document.createElement("span");g.className="bp-mgmt-flex1",g.textContent=`${s(d.source)} · ${d.rule}`;let y=document.createElement("span");y.className=`bp-tone-${m}`,y.textContent=String(d.n),f.append(b,g,y),c.appendChild(f);for(let w of d.rows??[]){let x=document.createElement("div");x.className="bp-mgmt-row"+(this.checksSelectedId===w.id?" active":"");let A=document.createElement("div");if(A.textContent=pe(w.title??""),x.appendChild(A),w.names||this.checksSelectedId===w.id){let N=document.createElement("div");N.className="bp-mgmt-row-sub";let S=document.createElement("span");if(S.className="bp-dim bp-mgmt-flex1",S.textContent=w.names??"",N.appendChild(S),this.checksSelectedId===w.id){let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn accent",M.textContent=h("gpui.mgmt.checks.fix","Fix with agent"),M.addEventListener("click",(B)=>{B.stopPropagation();let R={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:R.project,id:w.id}).then((U)=>{let D={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!gn(R,D))return;if(U.text)this.cb.onSendText(U.text),this.checksStatus="Sent to agent",this.render()}).catch((U)=>{let D={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!gn(R,D))return;this.checksStatus=U instanceof Error?U.message:"Could not send finding",this.render()})}),N.appendChild(M)}x.appendChild(N)}x.addEventListener("click",()=>{this.checksSelectedId=w.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:w.id}).catch(()=>{}),this.render()}),c.appendChild(x)}}return e.appendChild(c),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let l of["active","nrnd","eol"]){let p=i[l]??0,c=hn(l),u=document.createElement("span");u.className=p>0?`bp-tone-${c.tone}`:"bp-mgmt-faint",u.textContent=`${c.label} ${p}`,n.appendChild(u)}if((i.unknown??0)>0){let l=document.createElement("span");l.className="bp-mgmt-faint",l.textContent=`${i.unknown} unknown`,n.appendChild(l)}if(t.since){let l=document.createElement("span");l.className="bp-mgmt-flex1";let p=document.createElement("span");p.className="bp-mgmt-faint",p.textContent=`since ${zt(t.since)} (${t.samples??0})`,n.append(l,p)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let a=t.bom?.cost??[],r=t.bom?.instock??[],o=t.bom?.lines??0;if(a.length===0)s.appendChild(this.makeEmpty(o===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let l=a[a.length-1],p=r[r.length-1],c=document.createElement("div");c.className="bp-mgmt-note bp-dim",c.textContent=`Parts/board: ${pt(l[1])} · ${Math.round(p?.[1]??0)}/${o} lines in stock (${zt(l[0])})`,s.appendChild(c)}for(let l of t.parts??[]){let p=this.lifeSelectedKey===l.key,c=hn(l.lifecycle??"unknown"),u=document.createElement("div");u.className="bp-mgmt-row"+(p?" active":"");let d=document.createElement("div");d.className="bp-mgmt-row-line";let m=document.createElement("span");m.className="bp-mgmt-strong",m.textContent=_t(l.refs??[],14);let f=document.createElement("span");f.className="bp-mgmt-flex1 bp-dim",f.textContent=l.mpn||l.key;let b=document.createElement("span");if(b.className=`bp-tone-${c.tone}`,b.textContent=c.label,d.append(m,f,b),typeof l.stock==="number"){let g=document.createElement("span");g.className="bp-dim",g.textContent=dt(l.stock),d.appendChild(g)}if(u.appendChild(d),p){let g=document.createElement("div");if(g.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)g.textContent=h("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let y=this.lifePartSamples[this.lifePartSamples.length-1];g.textContent=`${this.lifePartSamples.length} samples · latest ${y.at?zt(y.at):""}`+(typeof y.stock==="number"?` · stock ${dt(y.stock)}`:"")+(typeof y.price==="number"?` · ${pt(y.price)}`:"")}else g.textContent=h("gpui.mgmt.life.nopart","No reading of this part yet.");u.appendChild(g)}u.addEventListener("click",()=>{if(this.lifeSelectedKey===l.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=l.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:l.key}).then((g)=>{if(this.lifeSelectedKey!==l.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(g.samples)?g.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==l.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(u)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(h("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(E,k)=>{let j=this.watchGen,T=this.project;this.planStatus="",this.cb.hub.rpc(E,{pro:T,...k}).catch((q)=>{if(j!==this.watchGen||T!==this.project)return;this.planOptimistic.clear(),this.planStatus=q instanceof Error?q.message:h("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydrateAskedKey!==i&&this.project){this.planHydrateAskedKey=i;let E=this.watchGen,k=++this.planHydrateGen,j=this.project,T=t.revision??0;this.cb.hub.rpc("plan.get",{pro:j,board:!0}).then((q)=>{let ne=Ri(q);if(!ne)return;let H=typeof ne.revision==="number"?ne.revision:T;if(!ji(E,this.watchGen,k,this.planHydrateGen,j,this.project,H,this.planHydratedRev))return;this.planHydratedRev=H,this.planHydratedKey=`${j}:${H}`,this.planHydratedBoard=ne.board??null,this.planHydratedDraw=ne.draw??null,this.render()}).catch(()=>{})}let s=t.on===!0,a=document.createElement("div");a.className="bp-plan-header";let r=document.createElement("div");r.className="bp-plan-toggle";let o=document.createElement("span");o.className="bp-mgmt-strong",o.textContent=h("gpui.mgmt.plan.before","Plan before routing"),o.title=s?h("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):h("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here."),r.appendChild(o);let l=t.awaiting??0,p=t.blocked??0,c=t.done??0,u=t.total??0,d=t.revision??0,m=t.empty?[]:Ei(t),f=m.reduce((E,k)=>E+k.count,0);if(!t.empty){let E=wi(t),k=document.createElement("span");if(k.className=`bp-plan-status-badge tone-${E.tone}`,k.textContent=h(E.key,E.label),r.appendChild(k),d>0){let T=document.createElement("span");T.className="bp-dim",T.textContent=`v${d}`,r.appendChild(T)}let j=document.createElement("span");if(j.className="bp-plan-header-counts bp-mgmt-flex1 "+(l>0?"bp-tone-warn":p>0?"bp-tone-bad":"bp-dim"),j.textContent=u>0?`${c}/${u} ${h("gpui.mgmt.plan.done","done")}`:l>0?h("web.plan.awaiting","{n} awaiting approval",{n:l}):h("gpui.mgmt.plan.nothing","Nothing awaits your approval"),r.appendChild(j),!t.live){let T=document.createElement("span");T.className="bp-mgmt-pill",T.textContent=h("gpui.mgmt.plan.saved","saved plan"),r.appendChild(T)}}else{let E=document.createElement("span");E.className="bp-mgmt-flex1",r.appendChild(E)}let b=document.createElement("button");b.type="button",b.className="bp-mgmt-btn bp-plan-chip-btn"+(s?" active":""),b.setAttribute("data-testid","mgmt-plan-on"),b.setAttribute("aria-pressed",s?"true":"false"),b.textContent=h("gpui.bots.recall.on","On"),b.addEventListener("click",()=>n("plan.enable",{on:!0}));let g=document.createElement("button");if(g.type="button",g.className="bp-mgmt-btn bp-plan-chip-btn"+(!s?" active":""),g.setAttribute("data-testid","mgmt-plan-off"),g.setAttribute("aria-pressed",!s?"true":"false"),g.textContent=h("gpui.bots.recall.off","Off"),g.addEventListener("click",()=>n("plan.enable",{on:!1})),r.append(b,g),a.appendChild(r),f>0){let E=document.createElement("div");E.className="bp-plan-segbar";for(let k of m){if(k.count<=0)continue;let j=document.createElement("div");j.className=`bp-plan-seg bp-tone-bg-${k.tone}`,j.style.flexGrow=String(k.count),E.appendChild(j)}a.appendChild(E)}e.appendChild(a);for(let E of t.elsewhere??[]){let k=document.createElement("div");k.className="bp-plan-elsewhere";let j=document.createElement("span");j.className="bp-tone-warn bp-mgmt-flex1",j.textContent=h("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:E.name||E.rel||""}),k.appendChild(j),e.appendChild(k)}if(t.empty){let E=document.createElement("div");E.className="bp-mgmt-note";let k=document.createElement("div");k.className="bp-dim",k.textContent=h("gpui.mgmt.plan.noboard","No routing plan for this board.");let j=document.createElement("div");return j.className="bp-mgmt-faint",j.textContent=h("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),E.append(k,j),e.appendChild(E),e}let y=t.stackup_summary??"",w=Array.isArray(t.impedances)?t.impedances:[],x=Boolean(y)||w.length>0,A=document.createElement("div");if(A.className="bp-mgmt-head",l>0){let E=document.createElement("button");E.type="button",E.className="primary bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-approve-all"),E.textContent=h("gpui.mgmt.plan.all","Approve all"),E.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),A.appendChild(E)}if(t.routing){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-stop"),E.textContent=h("gpui.mgmt.plan.stop","Stop routing"),E.addEventListener("click",()=>n("plan.stop",{})),A.appendChild(E)}if(t.live&&c>0){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-verify"),E.textContent=h("gpui.mgmt.plan.verify","Verify"),E.addEventListener("click",()=>n("plan.verify",{})),A.appendChild(E)}let N=document.createElement("span");if(N.className="bp-mgmt-flex1",A.appendChild(N),x){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn bp-plan-chip-btn"+(this.planStackupOpen?" active":""),E.setAttribute("data-testid","mgmt-plan-stackup-toggle"),E.setAttribute("aria-expanded",this.planStackupOpen?"true":"false"),E.textContent=`${h("gpui.mgmt.plan.stackup.short","Stackup")} ${this.planStackupOpen?"▾":"▸"}`,E.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),A.appendChild(E)}let S=document.createElement("button");S.type="button",S.className="bp-mgmt-btn",S.setAttribute("data-testid","mgmt-plan-hide"),S.textContent=this.planHideDone?h("gpui.mgmt.plan.show","Show done"):h("gpui.mgmt.plan.hide","Hide done"),S.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),A.appendChild(S),e.appendChild(A);let M=Array.isArray(t.asks)?t.asks:[];if(M.length>0){let E=M.map((ne)=>ne.what||"").filter(Boolean).join(", "),k=M[0]?.note||"",j=document.createElement("div");j.className="bp-plan-elsewhere";let T=document.createElement("div");T.className="bp-plan-ask-col";let q=document.createElement("div");if(q.className="bp-tone-warn",q.textContent=E?h("gpui.mgmt.plan.requested","Approval requested: {what}",{what:E}):h("gpui.mgmt.plan.reqplain","Approval requested"),T.appendChild(q),k){let ne=document.createElement("div");ne.className="bp-dim",ne.textContent=k,T.appendChild(ne)}j.appendChild(T),e.appendChild(j)}if(this.planStatus){let E=document.createElement("div");E.className="bp-mgmt-note bp-plan-err bp-tone-bad";let k=document.createElement("span");k.className="bp-mgmt-flex1",k.textContent=this.planStatus==="KiCad refused"?h("gpui.mgmt.plan.refused","KiCad refused"):pe(this.planStatus);let j=document.createElement("button");j.type="button",j.className="icon",j.textContent="×",j.title=h("common.close","Close"),j.addEventListener("click",()=>{this.planStatus="",this.render()}),E.append(k,j),e.appendChild(E)}if(t.keys_note){let E=document.createElement("div");E.className="bp-mgmt-note bp-dim";let k="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";E.textContent=t.keys_note===k?h("gpui.mgmt.plan.keysnote",k):pe(t.keys_note),e.appendChild(E)}if(x&&this.planStackupOpen){let E=document.createElement("div");if(E.className="bp-plan-stackup-body",E.setAttribute("data-testid","mgmt-plan-stackup-body"),y){let k=document.createElement("div");k.className="bp-dim",k.textContent=y,E.appendChild(k)}for(let k of w){let j=document.createElement("div");j.className="bp-mgmt-faint",j.textContent=`· ${k}`,E.appendChild(j)}e.appendChild(E)}let B=(E,k,j,T)=>{let q=document.createElement("button");return q.type="button",q.className="bp-mgmt-btn bp-plan-chip-btn"+(k?" active":""),q.setAttribute("data-testid",j),q.setAttribute("aria-pressed",k?"true":"false"),q.textContent=E,q.addEventListener("click",T),q},R=document.createElement("div");if(R.className="bp-plan-viewbar",R.append(B(h("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),B(h("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),B(h("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let E=document.createElement("span");E.className="bp-plan-sep";let k=document.createElement("span");k.className="bp-plan-sep";let j=document.createElement("button");j.type="button",j.className="bp-mgmt-btn bp-plan-mini-btn",j.setAttribute("data-testid","mgmt-plan-fit"),j.textContent=h("gpui.mgmt.plan.fit","Fit"),j.addEventListener("click",()=>this.planCanvas?.fitAll()),R.append(E,B(h("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),B(h("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),B(h("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),k,B(h("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),j)}let U=document.createElement("span");U.className="bp-mgmt-flex1";let D=document.createElement("button");D.type="button",D.className="bp-mgmt-btn bp-plan-mini-btn",D.setAttribute("data-testid","mgmt-plan-expand"),D.textContent=this.planExpanded?h("gpui.mgmt.plan.compact","Compact"):h("gpui.mgmt.plan.expand","Expand"),D.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),R.append(U,D),e.appendChild(R);let re=Boolean(this.planHydratedBoard)&&this.planHydratedKey.startsWith(`${this.project}:`)&&(this.planHydratedKey===i||this.planHydratedRev!==void 0&&this.planHydratedRev>=(t.revision??0)),me=re&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},oe=re&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},Ee=(oe.bands??[]).map((E)=>{let k=this.planOptimistic.get(E.id);if(!k)return{...E};return{...E,...k,edited:!0,state:E.state==="proposed"?"edited":E.state}}),Ae=(oe.regions??[]).map((E)=>{let k=this.planOptimistic.get(E.id);if(!k)return{...E};return{...E,...k,edited:!0,state:E.state==="proposed"?"edited":E.state}}),Me=[],he=(t.layers??[]).map((E)=>{let k=[];for(let j of E.items??[]){let T=this.planOptimistic.get(j.id);if(!T){k.push(j);continue}let q={...j,width:typeof T.width==="number"?T.width:j.width,locked:typeof T.locked==="boolean"?T.locked:j.locked,edited:!0,state:j.state==="proposed"?"edited":j.state};if(typeof T.layer==="string"&&T.layer!==E.layer)Me.push({target:T.layer,item:q});else k.push(q)}return{...E,items:k}});for(let E of Me){let k=he.find((j)=>j.layer===E.target);if(k)k.items=[...k.items??[],E.item]}let be=Jt(he,t.copper_layers),I=this.planGridMode==="all"?be.map((E)=>E.layer):this.planGridMode==="single"?[this.planShownLayers.find((E)=>be.some((k)=>k.layer===E))??mt(be)[0]??be[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((E)=>be.some((k)=>k.layer===E))?this.planShownLayers.slice(0,2):mt(be);if(this.planViewMode!=="list"&&this.planGridMode!=="all"&&be.length>1){let E=document.createElement("div");E.className="bp-plan-layerbar";for(let k of be){let j=I.includes(k.layer),T=(k.items??[]).length,q=st(k.layer,t.copper_layers,be)||k.title||k.layer,ne=T>0?`${q} · ${T}`:q,H=B(ne,j,`mgmt-plan-layerpill-${k.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[k.layer];else if(this.planGridMode==="pair"){if(!I.includes(k.layer))this.planShownLayers=I.length>=2?[I[0],k.layer]:[...I,k.layer]}else this.planGridMode="single",this.planShownLayers=[k.layer];this.render()});if(T===0&&!j)H.classList.add("empty-layer");E.appendChild(H)}e.appendChild(E)}let le=(E,k)=>{let j=this.planOptimistic.get(E)??{};if(this.planOptimistic.set(E,{...j,...k}),typeof k.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[k.layer];else if(this.planGridMode==="pair"&&!I.includes(k.layer))this.planShownLayers=I.length>=2?[I[0],k.layer]:[...I,k.layer]}let T=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:E,fields:k}],...T!==void 0?{base:T}:{}})};if(this.planCommitFields=le,this.planSelectedId){let E="",k=null;for(let j of he){let T=(j.items??[]).find((q)=>q.id===this.planSelectedId);if(T){E=j.layer,k=T;break}}if(k){let j=st(E,t.copper_layers,be),T=document.createElement("div");T.className="bp-plan-inspector",T.setAttribute("data-testid","mgmt-plan-inspector");let q=document.createElement("div");q.className="bp-plan-ins-row";let ne=document.createElement("span");ne.className="bp-plan-ins-sw",ne.style.background=k.kind==="corridor"?ut(k.name||k.id,k.color||""):Lt(k.name||k.id,k.color||"");let H=document.createElement("span");H.className="bp-mgmt-strong",H.textContent=k.name||k.id;let K=document.createElement("span");if(K.className="bp-dim",K.textContent=j,q.append(ne,H,K),k.edited||k.state==="edited"){let Y=document.createElement("span");Y.className="bp-plan-ins-pill warn",Y.textContent=h("gpui.mgmt.plan.edited","Edited"),q.appendChild(Y)}if(k.locked){let Y=document.createElement("span");Y.className="bp-plan-ins-pill",Y.textContent=h("gpui.mgmt.plan.locked","Locked"),q.appendChild(Y)}let je=document.createElement("span");je.className="bp-mgmt-flex1",q.appendChild(je);let Le=document.createElement("button");if(Le.type="button",Le.className="bp-mgmt-btn bp-plan-mini-btn",Le.setAttribute("data-testid","mgmt-plan-lock"),Le.textContent=k.locked?h("gpui.mgmt.plan.unlock","Unlock"):h("gpui.mgmt.plan.lock","Lock"),Le.addEventListener("click",()=>le(k.id,{locked:!k.locked})),q.appendChild(Le),k.state==="proposed"||k.state==="edited"){let Y=document.createElement("button");Y.type="button",Y.className="primary bp-mgmt-btn bp-plan-mini-btn",Y.textContent=h("android.hub.machines.approve","Approve"),Y.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[k.id],approve:!0}));let ye=document.createElement("button");ye.type="button",ye.className="bp-mgmt-btn bp-plan-mini-btn",ye.textContent=h("gpui.mgmt.plan.reject","Reject"),ye.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[k.id],approve:!1})),q.append(Y,ye)}let ue=document.createElement("button");ue.type="button",ue.className="bp-mgmt-btn bp-plan-mini-btn",ue.setAttribute("data-testid","mgmt-plan-note-toggle"),ue.textContent=h("gpui.mgmt.plan.addnote","Add note"),ue.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let Pe=document.createElement("button");if(Pe.type="button",Pe.className="icon",Pe.textContent="×",Pe.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.render()}),q.append(ue,Pe),T.appendChild(q),!k.locked){let Y=document.createElement("div");if(Y.className="bp-plan-ins-row",k.kind==="corridor"){let te=typeof k.width==="number"?k.width:1.5,ke=document.createElement("span");ke.className="bp-dim",ke.textContent=h("gpui.mgmt.plan.width","Width");let De=document.createElement("button");De.type="button",De.className="bp-mgmt-btn bp-plan-mini-btn",De.setAttribute("data-testid","mgmt-plan-w-down"),De.textContent="-",De.addEventListener("click",()=>{let Ue=Math.round(Math.max(0.15,te-0.25)*100)/100;le(k.id,{width:Ue})});let ae=document.createElement("span");ae.className="bp-plan-ins-val",ae.textContent=`${te.toFixed(2)}mm`;let fe=document.createElement("button");fe.type="button",fe.className="bp-mgmt-btn bp-plan-mini-btn",fe.setAttribute("data-testid","mgmt-plan-w-up"),fe.textContent="+",fe.addEventListener("click",()=>{let Ue=Math.round(Math.min(25,te+0.25)*100)/100;le(k.id,{width:Ue})});let _e=document.createElement("span");_e.className="bp-plan-sep",Y.append(ke,De,ae,fe,_e)}let ye=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((te)=>te.layer):he.map((te)=>te.layer);if(ye.length>0){let te=document.createElement("span");te.className="bp-dim",te.textContent=h("gpui.mgmt.plan.layer.short","Layer"),Y.appendChild(te),Y.appendChild(B(`${j} ${this.planMoveLayerOpen?"▴":"▾"}`,this.planMoveLayerOpen,"mgmt-plan-move-toggle",()=>{this.planMoveLayerOpen=!this.planMoveLayerOpen,this.render()}))}if(T.appendChild(Y),this.planMoveLayerOpen&&ye.length>0){let te=document.createElement("div");te.className="bp-plan-ins-row";for(let ke of ye){let De=st(ke,t.copper_layers,be);te.appendChild(B(De,ke===E,`mgmt-plan-move-${ke}`,()=>{if(this.planMoveLayerOpen=!1,ke!==E)le(k.id,{layer:ke});else this.render()}))}T.appendChild(te)}}if(this.planNoteOpen){let Y=document.createElement("form");Y.className="bp-plan-note-form";let ye=document.createElement("input");ye.type="text",ye.className="bp-plan-note-input",ye.setAttribute("data-testid","mgmt-plan-note-input"),ye.placeholder=h("gpui.mgmt.plan.note.placeholder","Steering note for router…");let te=document.createElement("button");te.type="submit",te.className="primary bp-mgmt-btn bp-plan-mini-btn",te.setAttribute("data-testid","mgmt-plan-note-submit"),te.textContent=h("gpui.mgmt.plan.addnote","Add note"),Y.append(ye,te),Y.addEventListener("submit",(ke)=>{ke.preventDefault();let De=ye.value.trim();if(!De)return;ye.value="",this.planNoteOpen=!1;let ae=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:k.id,text:De}],...ae!==void 0?{base:ae}:{}})}),T.appendChild(Y)}if(this.planViewMode!=="list"&&!k.locked){let Y=document.createElement("div");Y.className="bp-plan-hint",Y.textContent=h("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),T.appendChild(Y)}e.appendChild(T)}}let ie=document.createElement("div");ie.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),ie.setAttribute("data-testid","mgmt-plan-rows");let Z=h("gpui.mgmt.plan.done","done"),ce=Mi(this.planViewMode,he,I);if(this.planViewMode==="split"&&ce.length===0){let E=document.createElement("div");E.className="bp-dim",E.style.padding="6px 8px",E.style.fontSize="11px",E.textContent=h("gpui.mgmt.plan.noitems","No corridors or planes on this layer"),ie.appendChild(E)}for(let E of ce){let k=E.items??[],j=st(E.layer,t.copper_layers,be)||E.layer;if(this.planViewMode==="split"){if(ce.length>1){let T=document.createElement("div");T.className="bp-plan-split-divider";let q=E.role==="power"||E.role==="plane",ne=document.createElement("span");ne.className="bp-plan-card-bar "+(q?"pwr":"sig");let H=document.createElement("span");H.className="bp-mgmt-strong",H.textContent=j;let K=document.createElement("span");K.className="bp-dim",K.textContent=`${E.done??0}/${k.length} ${Z}`,T.append(ne,H,K),ie.appendChild(T)}}else{let T=document.createElement("div");T.className="bp-mgmt-group-head bp-plan-layer-head";let q=document.createElement("div");q.className="bp-mgmt-row-line";let ne=document.createElement("span");ne.className="bp-mgmt-strong",ne.textContent=j;let H=document.createElement("span");if(H.className="bp-dim bp-mgmt-flex1",H.textContent=`${E.role?`${E.role} · `:""}${E.done??0}/${k.length} ${Z}`,q.append(ne,H),E.status!=="approved"&&k.length>0){let K=document.createElement("button");K.type="button",K.className="bp-mgmt-btn",K.textContent=h("gpui.mgmt.plan.layer","Approve layer"),K.addEventListener("click",()=>n("plan.approve",{layer:E.layer,ids:[],approve:!0}));let je=document.createElement("button");je.type="button",je.className="bp-mgmt-btn",je.textContent=h("gpui.mgmt.plan.reject","Reject"),je.addEventListener("click",()=>n("plan.approve",{layer:E.layer,ids:[],approve:!1})),q.append(K,je)}if(T.appendChild(q),E.stackup){let K=document.createElement("div");K.className="bp-plan-layer-stackup",K.textContent=E.stackup,T.appendChild(K)}ie.appendChild(T)}for(let T of k){if(this.planHideDone&&vi(T))continue;let q=this.planSelectedId===T.id,ne=document.createElement("div");ne.className="bp-mgmt-row bp-plan-row"+(q?" active":""),ne.setAttribute("data-testid",`mgmt-plan-row-${T.id}`);let H=document.createElement("div");H.className="bp-mgmt-row-line";let K=document.createElement("span");K.className=`bp-plan-swatch bp-plan-st-${T.state||"proposed"}`,K.style.setProperty("--swatch-color",T.color||"#8a8a8a");let je=document.createElement("span");je.className="bp-mgmt-flex1"+(T.state==="blocked"||T.state==="failed"?" bp-tone-bad":T.state==="edited"?" bp-tone-warn":T.state==="rejected"||T.state==="routed"||T.state==="verified"?" bp-dim":""),je.textContent=`${T.name||T.id}${T.locked?" \uD83D\uDD12":""}`;let Le=[];if(T.kind==="plane"){if(T.reference)Le.push(h("gpui.mgmt.plan.reference","over {layer}",{layer:T.reference}))}else{let Y=T.nets??0;Le.push(Y===1?h("web.plan.net.one","1 net"):h("web.plan.nets","{n} nets",{n:Y}))}if(typeof T.width==="number"&&Number.isFinite(T.width))Le.push(`${T.width.toFixed(2)}mm`);if(T.impedance)Le.push(T.impedance);let ue=Le.join(" · "),Pe=document.createElement("span");if(Pe.className="bp-plan-mark "+(T.state==="blocked"||T.state==="failed"?"bp-tone-bad":T.state==="verified"||T.state==="routed"?"bp-tone-ok":T.state==="approved"?"bp-tone-accent":"bp-dim"),Pe.textContent=yi(T),H.append(K,je,Pe),T.state==="proposed"||T.state==="edited"){let Y=document.createElement("button");Y.type="button",Y.className="bp-mgmt-btn",Y.textContent="✓",Y.title=h("gpui.mgmt.plan.layer","Approve layer"),Y.addEventListener("click",(te)=>{te.stopPropagation(),n("plan.approve",{layer:"",ids:[T.id],approve:!0})});let ye=document.createElement("button");ye.type="button",ye.className="bp-mgmt-btn",ye.textContent="✗",ye.title=h("gpui.mgmt.plan.reject","Reject"),ye.addEventListener("click",(te)=>{te.stopPropagation(),n("plan.approve",{layer:"",ids:[T.id],approve:!1})}),H.append(Y,ye)}if(ne.appendChild(H),ue){let Y=document.createElement("div");Y.className="bp-mgmt-row-sub bp-plan-detail bp-dim",Y.textContent=ue,ne.appendChild(Y)}if(T.state==="routing"&&typeof T.total==="number"&&T.total>0){let Y=document.createElement("div");Y.className="bp-plan-microbar";let ye=document.createElement("div");ye.className="bp-plan-microbar-fill";let te=Math.max(0,Math.min(100,Math.round((T.routed??0)/T.total*100)));ye.style.width=`${te}%`,Y.appendChild(ye),ne.appendChild(Y)}if(T.problem_text){let Y=document.createElement("div");Y.className="bp-plan-problem",Y.textContent=T.problem_text,ne.appendChild(Y)}ne.addEventListener("click",()=>{this.planSelectedId=T.id,n("plan.focus",{id:T.id}),this.render()}),ie.appendChild(ne)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new yn({onSelect:(T)=>{if(this.planSelectedId=T,!T)this.planNoteOpen=!1;this.render()},onFocusItem:(T)=>{n("plan.focus",{id:T})},onDragEnd:()=>{if(this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onCommitFields:(T,q)=>{(this.planCommitFields??le)(T,q)},onApproveLayer:(T,q)=>{n("plan.approve",{layer:T,ids:[],approve:q})},onQuickApprove:(T,q)=>{n("plan.approve",{layer:"",ids:T,approve:q})}});let E=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,k=this.planExpanded||this.panelEl.clientWidth>=540||E;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:I,selectedId:this.planSelectedId,board:me,bands:Ee,regions:Ae,layers:be,copperLayers:t.copper_layers},k);let j=document.createElement("div");j.className="bp-plan-canvas-scroll",j.appendChild(this.planCanvas.root),e.appendChild(j)}if(this.planViewMode!=="canvas")e.appendChild(ie);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let E=document.createElement("div");E.className="bp-plan-footer",E.textContent=h("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(E)}return e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let w=document.createElement("div");return w.className="bp-mgmt-note bp-tone-warn",w.textContent=t.error,e.appendChild(w),e}let n=(w,x={})=>{let A=this.watchGen,N=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:N,action:w,...x}).catch((S)=>{if(A!==this.watchGen||N!==this.project)return;this.fabStatus=S instanceof Error?S.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=h("gpui.mgmt.fab.thefab","The fab");let a=document.createElement("span");a.className="bp-dim bp-mgmt-flex1",a.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${xi(t.tier??"")}`;let r=document.createElement("button");if(r.type="button",r.className="bp-mgmt-btn",r.textContent=h("gpui.mgmt.fab.refresh","Refresh"),r.addEventListener("click",()=>n("refresh")),i.append(s,a,r),e.appendChild(i),this.fabStatus){let w=document.createElement("div");w.className="bp-mgmt-note bp-tone-bad",w.textContent=this.fabStatus,e.appendChild(w)}let o=document.createElement("div");o.className="bp-mgmt-rows",o.setAttribute("data-testid","mgmt-fab-rows");let l=t.review,p=document.createElement("div");p.className="bp-mgmt-row";let c=document.createElement("div");c.className="bp-mgmt-row-line";let u=document.createElement("span"),d=(l?.counts?.error??0)>0;if(u.className="bp-mgmt-flex1 "+(d?"bp-tone-bad":"bp-dim"),u.textContent=l?.running?"Reviewing the design…":l?.at==null?"No design review yet":`${l.counts?.error??0} must-fix · ${l.counts?.warning??0} should-fix · ${l.counts?.info??0} notes${l.scope?` (${l.scope})`:""}`,c.appendChild(u),l?.at!=null){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.findings","Findings"),w.addEventListener("click",()=>this.togglePanel("checks")),c.appendChild(w)}if(!l?.running){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.reviewbtn","Review"),w.addEventListener("click",()=>n("review")),c.appendChild(w)}if(l?.judge){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.judge","Datasheets"),w.addEventListener("click",()=>{if(l.judge)this.cb.onSendText(l.judge)}),c.appendChild(w)}p.appendChild(c),o.appendChild(p);let m=Ci(t.drc?.state??""),f=document.createElement("div");f.className="bp-mgmt-row";let b=document.createElement("div");b.className="bp-mgmt-row-line";let g=document.createElement("span");if(g.className="bp-mgmt-flex1 "+(m.button?"bp-tone-warn":"bp-dim"),g.textContent=m.text,b.appendChild(g),m.button){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=m.button,w.addEventListener("click",()=>n("drc")),b.appendChild(w)}f.appendChild(b),o.appendChild(f);for(let w of t.conflicts??[]){let x=document.createElement("div");x.className="bp-mgmt-row bp-tone-bad",x.textContent=w,o.appendChild(x)}for(let w of t.suggestions??[]){let x=document.createElement("div");x.className="bp-mgmt-row";let A=document.createElement("div");A.className="bp-mgmt-row-line";let N=document.createElement("span");N.className="bp-mgmt-flex1 bp-tone-warn",N.textContent=`${w.label||w.key}: board ${w.project??"?"} mm, fab ${w.fab??"?"} mm`;let S=document.createElement("button");S.type="button",S.className="bp-mgmt-btn",S.textContent=h("gpui.mgmt.fab.apply","Apply"),S.addEventListener("click",()=>n("apply",{key:w.key})),A.append(N,S),x.appendChild(A),o.appendChild(x)}if(t.stackup?.chosen){let w=document.createElement("div");w.className="bp-mgmt-row";let x=document.createElement("div");x.className="bp-mgmt-row-line";let A=t.stackup.by==="proposed",N=document.createElement("span");if(N.className="bp-mgmt-flex1 "+(A?"bp-tone-warn":"bp-dim"),N.textContent=`${A?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,x.appendChild(N),A){let S=t.stackup.chosen,M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=h("gpui.mgmt.fab.use","Use"),M.addEventListener("click",()=>n("stackup",{id:S})),x.appendChild(M)}w.appendChild(x),o.appendChild(w)}if(Array.isArray(t.changed)&&t.changed.length>0){let w=document.createElement("div");w.className="bp-mgmt-row";let x=document.createElement("div");x.className="bp-mgmt-row-line";let A=document.createElement("span");A.className="bp-mgmt-flex1 bp-tone-warn",A.textContent=h("gpui.mgmt.fab.changed","Changed since you last looked");let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.textContent=h("gpui.mgmt.fab.seen","Seen"),N.addEventListener("click",()=>n("seen")),x.append(A,N),w.appendChild(x);for(let S of t.changed.slice(0,12)){let M=document.createElement("div");M.className="bp-mgmt-faint",M.textContent=S,w.appendChild(M)}o.appendChild(w)}let y=Array.isArray(t.limits)?t.limits:[];if(y.length>0){let w=document.createElement("div");w.className="bp-mgmt-group-head";let x=document.createElement("span");x.className="bp-mgmt-flex1",x.textContent=h("gpui.mgmt.fab.limit","Limit");let A=document.createElement("span");A.className="bp-mgmt-col",A.textContent=h("gpui.mgmt.fab.free","Base price");let N=document.createElement("span");N.className="bp-mgmt-col",N.textContent=h("gpui.mgmt.fab.extra","Costs more");let S=document.createElement("span");S.className="bp-mgmt-col bp-mgmt-col-read",S.textContent=h("gpui.mgmt.fab.readcol","Read"),w.append(x,A,N,S),o.appendChild(w);for(let B of y){let R=document.createElement("div");R.className="bp-mgmt-row";let U=document.createElement("div");U.className="bp-mgmt-row-line";let D=document.createElement("span");D.className="bp-mgmt-flex1"+(B.changed?" bp-tone-warn":B.inherited?" bp-dim":""),D.textContent=`${B.changed?"• ":""}${B.label??""}`;let re=document.createElement("span");re.className="bp-mgmt-col",re.textContent=B.free?.text||"—";let me=document.createElement("span");me.className="bp-mgmt-col bp-dim",me.textContent=B.extra?.text||"—";let oe=B.free&&typeof B.free==="object"?B.free:B.extra,Ee=oe?.fetched??"",Ae=Boolean(Ee)&&oe?.confidence!=="published",Me=Ee?Ae?`${Ee}*`:Ee:"—",he=oe?.source??"",be;if(he.startsWith("https://")&&Ee){let I=document.createElement("a");I.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",I.href=he,I.target="_blank",I.rel="noopener noreferrer",I.textContent=Me,be=I}else{let I=document.createElement("span");I.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",I.textContent=Me,be=I}U.append(D,re,me,be),R.appendChild(U),o.appendChild(R)}let M=document.createElement("div");M.className="bp-mgmt-note bp-mgmt-faint",M.textContent=h("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(M)}return e.appendChild(o),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var da={trs:(e)=>e,t:(e,t)=>t},pa=new Set(["/settle"]);function $i(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((r)=>r.startsWith(n)))return 2;let a=0;for(let r=0;r0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function Oi(e){let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Vi(e,t){let n=t.trim().split(/\s+/)[0]?.toLowerCase()??"";if(!n)return null;let i=e.toLowerCase();if(i.length!==e.length)return null;let s=i.indexOf(n);if(s<0)return null;return[s,s+n.length]}function Ui(e,t=da){let{t:n,trs:i}=t,s=[],a=new Map;for(let o of e.projects)a.set(o.id,o.title||o.id);let r=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!r&&o.id!=="terminal")continue;s.push({label:i(o.label),place:o.id==="terminal"?"":"viewer",kind:"action",shortcut:o.key?o.key.toUpperCase():void 0,action:{type:"rail",id:o.id}})}if(r)s.push({label:r.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:r.pinned?"unpin":"pin"}}),s.push({label:r.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:r.settled?"unsettle":"settle"}}),s.push({label:r.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:r.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(r)for(let o of e.commands){if(!o.word)continue;let l=pa.has(o.word.toLowerCase());s.push({label:o.label?`${o.word} — ${o.label}`:o.word,place:o.desc||"command",kind:"command",action:{type:"command",word:o.word,runDirectly:l}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let o of e.projects)s.push({label:`New thread in ${o.title||o.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:o.id}});for(let o of e.threads){let{urgency:l,want:p}=Gi(o);s.push({label:o.title||"Untitled thread",place:o.project?a.get(o.project)??"":"",kind:"thread",urgency:l,want:p,dotClass:Oi(o),action:{type:"thread",id:o.id}})}for(let o of e.bots){if(!o.name||!o.thread)continue;s.push({label:o.name,place:"",kind:"bot",action:{type:"thread",id:o.thread}})}return s}function Wi(e,t,n,i=[],s=10,a=14){let r=t.trim(),o=r.length===0,l=e.slice();if(n?.threads&&n.threads.length>0){let d=new Map;for(let f of i)d.set(f.id,f.title||f.id);let m=new Set;for(let f of l)if(f.action.type==="thread")m.add(f.action.id);for(let f of n.threads){if(!f.id||m.has(f.id))continue;m.add(f.id);let{urgency:b,want:g}=Gi(f);l.push({label:f.title||"Untitled thread",place:f.project?d.get(f.project)??"":"",kind:"thread",urgency:b,want:g,dotClass:Oi(f),action:{type:"thread",id:f.id}})}}let p=[];for(let d=0;d0)p.push({score:g,index:d,item:m})}p.sort((d,m)=>{if(o){let g=(m.item.urgency??0)-(d.item.urgency??0);if(g!==0)return g}if(m.score!==d.score)return m.score-d.score;let f=d.item.kind==="thread"?0:1,b=m.item.kind==="thread"?0:1;if(f!==b)return f-b;return d.index-m.index});let c=new Set,u=[];for(let d of p){let m=`${d.item.label}\x00${d.item.place}\x00${d.item.kind}`;if(c.has(m))continue;if(c.add(m),u.push(d.item),u.length>=s)break}if(n?.messages&&n.messages.length>0&&u.length{if(r.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(r)=>{if(r.key==="Escape")r.preventDefault(),r.stopPropagation(),this.close();else if(r.key==="ArrowDown"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(r.key==="ArrowUp"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(r.key==="Enter")r.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=a,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=Ui(t,{t:h,trs:pe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=Wi(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let r=document.createElement("div");r.className="bp-palette-empty",r.textContent=h("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(r);return}let s=document.createDocumentFragment(),a=null;for(let r=0;r0)p.appendChild(document.createTextNode(o.label.slice(0,d)));let f=document.createElement("strong");if(f.className="bp-palette-mark",f.textContent=o.label.slice(d,m),p.appendChild(f),m{if(this.activeIdx!==r)this.activeIdx=r,this.updateActiveClass()}),l.addEventListener("click",()=>this.runAt(r)),r===this.activeIdx)a=l;s.appendChild(l)}if(this.listEl.replaceChildren(s),e&&a)a.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return a}render(){let e=this.items.filter((r)=>r.group!=="tools"),t=this.items.filter((r)=>r.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let r of e){if(i!==void 0&&r.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=r.group,n.appendChild(this.renderButton(r))}let s=()=>{let r=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let r=document.createElement("div");r.className="bp-rail-tools";for(let o of t)r.appendChild(this.renderButton(o));a.appendChild(r)}this.el.replaceChildren(a)}}var ha=new Set(["resume","raise","retry","move","signin"]);function Ki(e){if(!e||typeof e!=="object")return null;let t=e,n=(a)=>typeof a==="string"?a:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((a)=>Boolean(a)&&typeof a==="object").map((a)=>({label:n(a.label),act:n(a.act),room:n(a.room),thread:n(a.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function Yt(e,t){if(e.act==="board")return t&&e.room?{kind:"board",room:e.room}:null;if(e.act==="open")return e.thread?{kind:"thread",id:e.thread}:null;if(ha.has(e.act)){let n={room:e.room,action:e.act};if(e.thread)n.thread=e.thread;return{kind:"call",method:"swarm.act",params:n}}return null}function Ji(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}var Sn=[{id:"general",label:"General"},{id:"ai",label:"Agents and tools"},{id:"connect",label:"Connect"}],ht=[{id:"appearance",group:"general",title:"Appearance",subtitle:"Kept in this browser only. Never sent to the hub.",icon:"sun",keywords:["theme","dark","light","auto","color","language","locale","english","espanol","japanese"]},{id:"providers",group:"ai",title:"AI providers",subtitle:"Account sign-ins live in the desktop or mobile app.",icon:"cpu",keywords:["accounts","claude","codex","antigravity","grok","openai","anthropic","signin","login","model"]},{id:"devices",group:"connect",title:"Devices & browser",subtitle:"This browser session and paired devices on this hub.",icon:"link",keywords:["sign out","logout","session","cookie","revoke","paired","phone","browser","pair"]},{id:"home",group:"connect",title:"Home machine",subtitle:"Which machine hosts your always-on hub and bots.",icon:"globe",keywords:["host","boat","move","online","away","queued","linked"]}];function Yi(e){if(e==="dark"||e==="light"||e==="auto")return e;return"auto"}function Xi(e){if(e==="en"||e==="es"||e==="ja"||e==="auto")return e;return"auto"}function Pt(e,t){if(e==="dark"||e==="light")return e;return t==="light"?"light":"dark"}function Zi(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean)}function kn(e,t){if(t.length===0)return!0;let n=e.toLowerCase();return t.every((i)=>n.includes(i))}function Qi(e,t){let n=Zi(t);if(n.length===0)return[];return e.filter((i)=>{let s=[i.groupLabel,i.pageTitle,i.rowTitle,i.rowDetail,...i.keywords??[]].join(" ");return kn(s,n)})}function An(e,t,n){let i=Zi(n);if(i.length===0)return e.map((r)=>({page:r,hits:[]}));let s=new Map(Sn.map((r)=>[r.id,r.label])),a=[];for(let r of e){let l=t.filter((c)=>c.pageId===r.id).filter((c)=>kn([c.rowTitle,c.rowDetail,c.pageTitle,c.groupLabel,...c.keywords??[]].join(" "),i));if(kn([s.get(r.group)??"",r.title,r.subtitle,...r.keywords].join(" "),i)||l.length>0){let c=[];for(let u of l){if(!c.includes(u.rowTitle))c.push(u.rowTitle);if(c.length>=2)break}a.push({page:r,hits:c})}}return a}function ba(e){let n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("width","15"),n.setAttribute("height","15"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.75"),n.setAttribute("stroke-linecap","square"),n.setAttribute("stroke-linejoin","miter"),n.setAttribute("aria-hidden","true");let i=(s,a)=>{let r=document.createElementNS("http://www.w3.org/2000/svg",s);for(let[o,l]of Object.entries(a))r.setAttribute(o,l);n.appendChild(r)};switch(e){case"sun":i("circle",{cx:"12",cy:"12",r:"4"}),i("path",{d:"M12 2v2m0 16v2M4.93 4.93l1.41 1.41m11.32 11.32 1.41 1.41M2 12h2m16 0h2M4.93 19.07l1.41-1.41m11.32-11.32 1.41-1.41"});break;case"cpu":i("rect",{x:"5",y:"5",width:"14",height:"14"}),i("rect",{x:"9",y:"9",width:"6",height:"6"}),i("path",{d:"M9 2v3m6-3v3M9 19v3m6-3v3M2 9h3m-3 6h3M19 9h3m-3 6h3"});break;case"link":i("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),i("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"});break;case"globe":i("circle",{cx:"12",cy:"12",r:"10"}),i("path",{d:"M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"});break}return n}function ga(){let t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("aria-hidden","true");let n=document.createElementNS("http://www.w3.org/2000/svg","circle");n.setAttribute("cx","11"),n.setAttribute("cy","11"),n.setAttribute("r","7");let i=document.createElementNS("http://www.w3.org/2000/svg","path");return i.setAttribute("d","m20 20-3.5-3.5"),t.append(n,i),t}function Xt(e,t){switch(e){case"general":return h("gpui.settings.group.general",t);case"ai":return h("gpui.settings.group.agents",t);case"connect":return h("native.pair.connect",t)}}function rt(e,t){switch(e){case"appearance":return h("settings.appearance",t);case"providers":return h("web.settings.providers",t);case"devices":return t;case"home":return h("home.machine",t)}}class Ln{backdrop;titleEl;badgeEl;closeBtn;navListEl;searchInput;searchClearBtn;paneEl;cb;openState=!1;activePage="appearance";forceProviders=!1;query="";searchBrowseAll=!1;devicesLoaded=!1;devicesLoading=!1;devicesRows=[];devicesError="";loadGen=0;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal bp-settings-modal",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.setAttribute("aria-labelledby","bp-settings-title");let i=document.createElement("div");i.className="bp-modal-head";let s=document.createElement("div");s.className="bp-settings-head-title",this.titleEl=document.createElement("h2"),this.titleEl.id="bp-settings-title",this.titleEl.textContent=h("palette.settings","Settings"),this.badgeEl=document.createElement("span"),this.badgeEl.className="bp-settings-badge",this.badgeEl.textContent="Browser",s.append(this.titleEl,this.badgeEl),this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(s,this.closeBtn);let a=document.createElement("div");a.className="bp-settings-body";let r=document.createElement("aside");r.className="bp-settings-nav";let o=document.createElement("div");o.className="bp-settings-search";let l=document.createElement("span");l.className="bp-settings-search-icon",l.appendChild(ga()),this.searchInput=document.createElement("input"),this.searchInput.type="text",this.searchInput.className="bp-settings-search-input",this.searchInput.placeholder="Search settings…",this.searchInput.setAttribute("aria-label","Search settings"),this.searchInput.setAttribute("data-testid","settings-search"),this.searchClearBtn=document.createElement("button"),this.searchClearBtn.type="button",this.searchClearBtn.className="bp-settings-search-clear bp-hidden",this.searchClearBtn.textContent="×",this.searchClearBtn.title="Clear search",this.searchClearBtn.setAttribute("aria-label","Clear search"),o.append(l,this.searchInput,this.searchClearBtn),this.navListEl=document.createElement("nav"),this.navListEl.className="bp-settings-nav-list",this.navListEl.setAttribute("aria-label","Settings sections"),r.append(o,this.navListEl),this.paneEl=document.createElement("div"),this.paneEl.className="bp-settings-pane",a.append(r,this.paneEl),n.append(i,a),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(p)=>{if(p.target===this.backdrop)this.close()}),this.searchInput.addEventListener("input",()=>{this.query=this.searchInput.value,this.searchBrowseAll=this.query.trim().length>0,this.syncSearchClear(),this.render()}),this.searchInput.addEventListener("keydown",(p)=>{if(p.key==="Enter"){let c=An(ht,this.buildSearchItems(),this.query);if(c.length>0)p.preventDefault(),this.activePage=c[0].page.id,this.searchBrowseAll=!1,this.render()}else if(p.key==="Escape"&&this.query.trim().length>0)p.preventDefault(),p.stopPropagation(),this.clearSearch()}),this.searchClearBtn.addEventListener("click",()=>{this.clearSearch(),this.searchInput.focus()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}handleEscape(){if(!this.openState)return;if(this.query.trim().length>0)this.clearSearch(),this.searchInput.focus();else this.close()}async open(e){if(this.openState=!0,e)this.activePage=e;this.backdrop.classList.remove("bp-hidden"),this.render(),this.loadDevices(),window.setTimeout(()=>{if(this.openState)this.searchInput.focus()},0)}async openToAccounts(){this.forceProviders=!0,this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),await this.open("providers")}close(){this.openState=!1,this.forceProviders=!1,this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=h("palette.settings","Settings"),this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.openState)this.render()}async refresh(){if(!this.openState)return;this.render(),await this.loadDevices()}clearSearch(){this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),this.render()}syncSearchClear(){this.searchClearBtn.classList.toggle("bp-hidden",this.query.length===0)}async loadDevices(){let e=++this.loadGen;if(this.devicesLoading=!this.devicesLoaded,this.devicesLoading&&this.openState)this.renderPane();try{let t=await this.cb.onLoadDevices();if(e!==this.loadGen)return;this.devicesRows=t,this.devicesError="",this.devicesLoaded=!0}catch(t){if(e!==this.loadGen)return;let n=t instanceof Error&&t.message?t.message:"Not available from a browser";this.devicesError=`${n} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,this.devicesRows=[],this.devicesLoaded=!0}finally{if(e===this.loadGen){if(this.devicesLoading=!1,this.openState)this.render()}}}buildSearchItems(){let e=this.cb.onGetHome?.()??null,t=this.cb.onGetNoProvider?.()??null,n=Xt("general","General"),i=Xt("ai","Agents and tools"),s=Xt("connect","Connect"),a=rt("appearance","Appearance"),r=rt("providers","AI providers"),o=rt("devices","Devices & browser"),l=rt("home","Home machine"),p=[{pageId:"appearance",pageTitle:a,groupLabel:n,rowTitle:h("settings.theme","Theme"),rowDetail:"Auto (follow hub), Dark, or Light in this browser.",keywords:["theme","dark","light","auto","appearance","colors"]},{pageId:"appearance",pageTitle:a,groupLabel:n,rowTitle:h("settings.lang","Language"),rowDetail:"Interface language for this browser.",keywords:["locale","english","espanol","japanese","language"]},{pageId:"providers",pageTitle:r,groupLabel:i,rowTitle:t?pe(t.head):"Provider connections",rowDetail:"Connect Claude, Codex, Antigravity, or other AI providers in Settings → Accounts.",keywords:["accounts","claude","codex","antigravity","grok","openai","signin"]},{pageId:"devices",pageTitle:o,groupLabel:s,rowTitle:"This browser",rowDetail:"Sign out and revoke this browser's session cookie.",keywords:["logout","sign out","session","cookie"]},{pageId:"devices",pageTitle:o,groupLabel:s,rowTitle:"Paired devices",rowDetail:this.devicesRows.map((c)=>`${c.title||c.head||""} ${c.detail||c.text||""}`).join(" ")||"Paired phones and browsers on this hub.",keywords:["phone","pair","revoke","browser"]},{pageId:"home",pageTitle:l,groupLabel:s,rowTitle:e?.name?`${e.name}`:l,rowDetail:"Which machine hosts your always-on hub and bots.",keywords:["boat","move","online","away","queued","machine"]}];for(let c of this.devicesRows){let u=c.title||c.head||"";if(u)p.push({pageId:"devices",pageTitle:o,groupLabel:s,rowTitle:u,rowDetail:c.detail||c.text||"",keywords:["paired","device"]})}return p}render(){this.renderNav(),this.renderPane()}renderNav(){let e=document.createDocumentFragment(),t=An(ht,this.buildSearchItems(),this.query),n=this.cb.onGetNoProvider?.()??null,i=this.cb.onGetHome?.()??null;if(t.length===0){let a=document.createElement("div");a.className="bp-settings-nav-empty",a.setAttribute("data-testid","settings-nav-empty"),a.textContent="No matching settings",e.appendChild(a),this.navListEl.replaceChildren(e);return}let s="";for(let a of t){let r=a.page;if(r.group!==s){s=r.group;let d=Sn.find((m)=>m.id===r.group);if(d){let m=document.createElement("div");m.className="bp-settings-group",m.textContent=Xt(d.id,d.label),e.appendChild(m)}}let o=document.createElement("button");o.type="button";let l=!this.searchBrowseAll&&r.id===this.activePage;o.className="bp-settings-nav-item"+(l?" active":""),o.setAttribute("data-testid",`settings-nav-${r.id}`);let p=document.createElement("div");p.className="bp-settings-nav-row";let c=document.createElement("span");c.className="bp-settings-nav-icon",c.appendChild(ba(r.icon));let u=document.createElement("span");if(u.className="bp-settings-nav-label",u.textContent=rt(r.id,r.title),p.append(c,u),r.id==="providers"&&(n||this.forceProviders)){let d=document.createElement("span");d.className="bp-settings-nav-dot warn",d.title="Action needed",p.appendChild(d)}else if(r.id==="home"&&i){let d=document.createElement("span");d.className="bp-settings-nav-dot "+(i.moving?.state==="failed"?"bad":i.online?"ok":"warn"),p.appendChild(d)}if(o.appendChild(p),a.hits.length>0)for(let d of a.hits){let m=document.createElement("div");m.className="bp-settings-hit",m.textContent=d,o.appendChild(m)}o.addEventListener("click",()=>{this.activePage=r.id,this.searchBrowseAll=!1,this.render()}),e.appendChild(o)}this.navListEl.replaceChildren(e)}renderPane(){let e=document.createDocumentFragment(),t=this.query.trim();if(t&&this.searchBrowseAll){this.renderSearchResults(e,t),this.paneEl.replaceChildren(e);return}let n=ht.find((r)=>r.id===this.activePage)??ht[0],i=document.createElement("div");i.className="bp-settings-pane-head";let s=document.createElement("h3");s.textContent=rt(n.id,n.title);let a=document.createElement("div");switch(a.className="bp-settings-pane-sub",a.textContent=n.subtitle,i.append(s,a),e.appendChild(i),n.id){case"appearance":this.renderAppearancePage(e);break;case"providers":this.renderProvidersPage(e);break;case"devices":this.renderDevicesPage(e);break;case"home":this.renderHomePage(e);break}this.paneEl.replaceChildren(e)}renderSearchResults(e,t){let n=Qi(this.buildSearchItems(),t),i=document.createElement("div");i.className="bp-settings-pane-head";let s=document.createElement("h3");s.textContent="Search results";let a=document.createElement("div");if(a.className="bp-settings-pane-sub",a.textContent=n.length===0?`No settings match "${t}".`:`${n.length} matching ${n.length===1?"setting":"settings"} for "${t}"`,i.append(s,a),e.appendChild(i),n.length===0){let o=document.createElement("div");o.className="bp-settings-empty",o.textContent="Try searching for theme, language, providers, sign out, devices, or home.",e.appendChild(o);return}let r=Array.from(new Set(n.map((o)=>o.pageId)));for(let o of r){let l=ht.find((m)=>m.id===o);if(!l)continue;let p=document.createElement("div");p.className="bp-settings-search-sec";let c=document.createElement("div");c.className="bp-settings-subhead",c.textContent=rt(l.id,l.title);let u=document.createElement("button");u.type="button",u.className="bp-settings-search-open",u.textContent="Open page ›",u.addEventListener("click",()=>{this.activePage=o,this.searchBrowseAll=!1,this.render()}),p.append(c,u),e.appendChild(p);let d=new Set(n.filter((m)=>m.pageId===o).map((m)=>m.rowTitle));if(o==="appearance")this.renderAppearancePage(e,d);else if(o==="providers")this.renderProvidersPage(e);else if(o==="devices")this.renderDevicesPage(e,d);else if(o==="home")this.renderHomePage(e)}}renderAppearancePage(e,t){let n=this.cb.onGetThemePref?.()??"auto",i=this.cb.onGetHubTheme?.()??"dark",s=Pt(n,i),a=this.cb.onGetLocalePref?.()??"auto",r=h("settings.theme","Theme"),o=h("settings.lang","Language");if(!t||t.has(r)){let l=h("settings.theme.dark","Dark"),p=h("settings.theme.light","Light"),c=n==="auto"?`Following hub theme (${i==="light"?p:l}). Stored in this browser only.`:`Using ${s==="light"?p:l} in this browser. Select Auto to follow the hub.`;e.appendChild(this.makeSegmentedRow(r,c,[{value:"auto",label:"Auto"},{value:"dark",label:l},{value:"light",label:p}],n,"settings-theme",(u)=>{this.cb.onSetThemePref?.(u),this.render()}))}if(!t||t.has(o))e.appendChild(this.makeSegmentedRow(o,"Interface language for this browser. Automatic follows the hub or browser language.",[{value:"auto",label:h("settings.lang.auto","Automatic")},{value:"en",label:h("settings.lang.en","English")},{value:"es",label:h("settings.lang.es","Español")},{value:"ja",label:h("settings.lang.ja","日本語")}],a,"settings-locale",(l)=>{this.cb.onSetLocalePref?.(l),this.render()}))}makeSegmentedRow(e,t,n,i,s,a){let r=document.createElement("div");r.className="bp-settings-row";let o=document.createElement("div");o.className="bp-settings-row-info";let l=document.createElement("div");l.className="bp-settings-row-title",l.textContent=e;let p=document.createElement("div");p.className="bp-settings-row-detail",p.textContent=t,o.append(l,p);let c=document.createElement("div");c.className="bp-chip-group",c.setAttribute("role","group"),c.setAttribute("aria-label",e);for(let u of n){let d=document.createElement("button");d.type="button";let m=u.value===i;d.className="bp-chip"+(m?" active":""),d.textContent=u.label,d.setAttribute("aria-pressed",m?"true":"false"),d.setAttribute("data-testid",`${s}-${u.value}`),d.addEventListener("click",()=>a(u.value)),c.appendChild(d)}return r.append(o,c),r}renderProvidersPage(e){let t=this.cb.onGetNoProvider?.()??null,n=document.createElement("section");if(n.className="bp-settings-section",n.setAttribute("data-testid","settings-providers"),t||this.forceProviders){let i=document.createElement("div");i.className="bp-settings-notice warn";let s=document.createElement("div");s.className="bp-settings-row-info";let a=document.createElement("div");a.className="bp-settings-row-title",a.textContent=t?pe(t.head):h("provider.notice.head","No AI provider connected");let r=document.createElement("div");r.className="bp-settings-row-detail",r.textContent=h("web.settings.providers.browser","Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."),s.append(a,r);let o=document.createElement("div");o.className="bp-set-btns";let l=document.createElement("a");l.className="bp-link-btn primary",l.href=t?.url||"backplane://settings/accounts",l.setAttribute("data-testid","settings-open-accounts"),l.textContent=t?pe(t.button):h("provider.notice.button","Open Settings → Accounts"),o.appendChild(l),i.append(s,o),n.appendChild(i)}else{let i=document.createElement("div");i.className="bp-settings-row";let s=document.createElement("div");s.className="bp-settings-row-info";let a=document.createElement("div");a.className="bp-settings-row-title-wrap";let r=document.createElement("span");r.className="bp-settings-row-title",r.textContent="Provider connections";let o=document.createElement("span");o.className="bp-status-pill ok",o.textContent=h("gpui.acct.connected","Connected"),a.append(r,o);let l=document.createElement("div");l.className="bp-settings-row-detail",l.textContent="Provider sign-ins, fallback order, API keys, and usage limits are managed in the Backplane desktop or mobile app.",s.append(a,l);let p=document.createElement("div");p.className="bp-set-btns";let c=document.createElement("a");c.className="bp-link-btn",c.href="backplane://settings/accounts",c.setAttribute("data-testid","settings-open-accounts"),c.textContent=h("provider.notice.button","Open Settings → Accounts"),p.appendChild(c),i.append(s,p),n.appendChild(i)}e.appendChild(n)}renderDevicesPage(e,t){let n=!t||t.has("This browser"),i=!t||t.has("Paired devices")||this.devicesRows.some((r)=>t.has(r.title||r.head||""));if(n){let r=document.createElement("div");r.className="bp-settings-subhead",r.textContent="This browser",e.appendChild(r);let o=document.createElement("div");o.className="bp-settings-row";let l=document.createElement("div");l.className="bp-settings-row-info";let p=document.createElement("div");p.className="bp-settings-row-title",p.textContent="Browser session";let c=document.createElement("div");c.className="bp-settings-row-detail",c.textContent="Sign out and revoke this browser's session cookie.",l.append(p,c);let u=document.createElement("button");u.type="button",u.className="primary stop",u.textContent=h("agy.signout","Sign out"),u.setAttribute("data-testid","logout-btn"),u.addEventListener("click",()=>{u.disabled=!0,this.cb.onLogout().catch(()=>{c.setAttribute("role","alert"),c.className="bp-settings-row-detail bp-bad",c.textContent=h("web.logout.failed","Could not confirm sign-out. Try again."),u.disabled=!1})}),o.append(l,u),e.appendChild(o)}if(!i)return;let s=document.createElement("div");if(s.className="bp-settings-subhead",s.textContent="Paired devices",e.appendChild(s),this.devicesLoading){let r=document.createElement("div");r.className="bp-settings-empty",r.textContent="Loading paired devices…",e.appendChild(r);return}if(this.devicesError){let r=document.createElement("div");r.className="bp-settings-notice bad";let o=document.createElement("div");o.className="bp-settings-row-detail",o.textContent=this.devicesError,r.appendChild(o),e.appendChild(r);return}let a=!t||t.has("Paired devices")?this.devicesRows:this.devicesRows.filter((r)=>t.has(r.title||r.head||""));if(a.length===0){let r=document.createElement("div");r.className="bp-settings-empty",r.textContent="No paired devices listed.",e.appendChild(r)}else for(let r of a){let o=document.createElement("div");o.className="bp-settings-row";let l=document.createElement("div");l.className="bp-settings-row-info";let p=document.createElement("div");p.className="bp-settings-row-title-wrap";let c=document.createElement("span");c.className="bp-settings-row-title",c.textContent=r.title||r.head||"",p.appendChild(c);let u=r.detail||r.text||"";if(u){let d=document.createElement("span"),m=u.toLowerCase();d.className="bp-status-pill "+(m.includes("this browser")?"accent":"neutral"),d.textContent=u,p.appendChild(d)}if(l.appendChild(p),o.appendChild(l),r.buttons?.length){let d=document.createElement("div");d.className="bp-set-btns";for(let m of r.buttons){let f=document.createElement("button");if(f.type="button",m.primary)f.className="primary";if(m.danger)f.className="primary stop";f.textContent=m.label||h("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(m.action,m.value).finally(()=>{this.refresh()})}),d.appendChild(f)}o.appendChild(d)}e.appendChild(o)}if(!t){let r=document.createElement("div");r.className="bp-settings-footnote",r.textContent="Pair new browsers or phones, configure Tailscale HTTPS forwarding, or revoke access in desktop or mobile Settings → Devices.",e.appendChild(r)}}renderHomePage(e){let t=this.cb.onGetHome?.()??null,n=document.createElement("section");if(n.className="bp-settings-section",n.setAttribute("data-testid","settings-home"),!t){let d=document.createElement("div");d.className="bp-settings-empty",d.textContent="Single-hub mode — this hub is running locally without linked home machines.",n.appendChild(d),e.appendChild(n);return}let i=document.createElement("div");i.className="bp-settings-row";let s=document.createElement("div");s.className="bp-settings-row-info";let a=document.createElement("div");a.className="bp-settings-row-title-wrap";let r=document.createElement("span");r.className="bp-settings-row-title",r.textContent=t.name||(t.kind==="boat"?"Boat":"This machine"),a.appendChild(r);let o=document.createElement("span");o.className="bp-status-pill neutral",o.textContent=t.kind==="local"?"This machine":t.kind==="boat"?"Boat":"Linked machine",a.appendChild(o);let l=document.createElement("span"),p="Online",c="ok";if(t.moving?.state==="moving")p="Moving",c="accent";else if(t.moving?.state==="failed")p="Move failed",c="bad";else if(!t.online)p="Away",c="warn";l.className=`bp-status-pill ${c}`,l.textContent=p,a.appendChild(l);let u=document.createElement("div");if(u.className="bp-settings-row-detail",t.moving?.state==="moving")u.textContent=t.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")u.textContent=t.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):h("home.move.failed","Home move failed");else if(!t.online)u.textContent=t.queuedCount>0?h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):h("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else u.textContent="Your active home hub is online and serving threads and bots.";if(s.append(a,u),i.appendChild(s),t.canMoveHere&&this.cb.onMoveHomeHere){let d=document.createElement("button");d.type="button",d.className="primary",d.textContent=h("home.move.here","Make this machine the home"),d.setAttribute("data-testid","home-move-here-btn"),d.addEventListener("click",()=>{d.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),i.appendChild(d)}n.appendChild(i),e.appendChild(n)}}function xe(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Nt(e,t,n=!1){let i=xe("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function Pn(e){return xe("pre","bp-context-code",e)}function fa(e){return xe("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,pe(e))}function Zt(e,t){let n=xe("div","bp-context-row");return n.append(xe("strong",void 0,e),fa(t)),n}class Nn{fetchContext;dialog=xe("dialog","bp-context");title=xe("h2");cwd=xe("div","bp-context-path");tabs=xe("div","bp-context-tabs");body=xe("div","bp-context-body");notice=xe("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=xe("div","bp-context-head"),i=xe("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,Nt(h("common.refresh","Refresh"),()=>{this.load()}),Nt(h("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=h("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=h("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[h("thread.context.instructions","Instructions"),h("thread.context.system","System Prompt"),h("thread.context.skills","Skills"),h("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=Nt(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(xe("p","bp-dim",h("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=xe("details","bp-context-card"),i=xe("summary");if(i.append(Zt(t.path,t.status),xe("small","bp-dim",h("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,Pn(t.preview)),t.note)n.append(xe("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=xe("div","bp-context-row"),n=Nt(h("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=h("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(xe("p","bp-dim",h("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[h("thread.context.base","Backplane"),e.sections.base],[h("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[h("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(xe("h3",void 0,i),Pn(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(xe("h3",void 0,pe(t)));for(let i of n){let s=xe("article","bp-context-card");s.append(Zt(i.name,i.status),xe("p",void 0,i.description),xe("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),xe("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(xe("p","bp-dim",h("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=xe("article","bp-context-card");n.append(Zt(t.path,t.state));for(let s of t.servers){let a=s.url||[s.command,...s.args].map((r)=>JSON.stringify(r)).join(" ");if(n.append(Zt(s.name,s.status),Pn(a)),s.cwd)n.append(xe("small","bp-context-path",s.cwd))}if(t.error)n.append(xe("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?h("thread.context.trust","Trust and enable"):i==="disable"?h("thread.context.disable","Disable"):h("thread.context.enable","Enable"),a=Nt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");a.disabled=this.busy;let r=xe("div","bp-context-actions");r.append(a),n.append(r)}this.body.append(n)}}}function va(e){if(e.wake)return{icon:"◷",label:"Snoozed",tone:"dim"};let t=(e.label??"").trim(),n=(e.tone??"").trim();if(t){let s=t.toLowerCase();return{icon:s==="approve"||s==="sign in"?"!":s==="input"?"?":s==="failed"||s==="stopped"?"×":s==="working"||s==="running"?"▸":s==="waiting"?"◌":s==="done"?"✓":"•",label:t,tone:n==="bad"?s==="failed"||s==="stopped"?"bad-out":"bad":n==="run"?"run":n==="wait"?"wait":n==="ok"?"ok":"dim"}}let i=e.word||"";if(i==="needs"){if(e.want==="approval")return{icon:"!",label:"Approve",tone:"bad"};if(e.want==="sign-in")return{icon:"!",label:"Sign in",tone:"bad"};return{icon:"?",label:"Input",tone:"bad"}}if(i==="failed"||e.status==="failed"||e.state==="fail")return{icon:"×",label:"Failed",tone:"bad-out"};if(i==="cut"||i==="interrupted")return{icon:"×",label:"Stopped",tone:"bad-out"};if(i==="running"||e.status==="active"||e.status==="working"||e.state==="run")return{icon:"▸",label:"Working",tone:"run"};if(i==="monitoring"||i==="limit"||e.status==="waiting")return{icon:"◌",label:"Waiting",tone:"wait"};if(i==="done"||e.status==="finished")return{icon:"✓",label:"Done",tone:"ok"};return null}var es="http://www.w3.org/2000/svg";function ot(e,t=14,n=""){let i=document.createElementNS(es,"svg");if(i.setAttribute("viewBox","0 0 24 24"),i.setAttribute("width",String(t)),i.setAttribute("height",String(t)),i.setAttribute("fill","none"),i.setAttribute("stroke","currentColor"),i.setAttribute("stroke-width","1.75"),i.setAttribute("stroke-linecap","square"),i.setAttribute("stroke-linejoin","miter"),i.setAttribute("aria-hidden","true"),n)i.classList.add(...n.split(" "));for(let s of e){let a=document.createElementNS(es,"path");a.setAttribute("d",s),i.appendChild(a)}return i}function ts(){return ot(["M3 6h6l2 2h10v11H3z"],14,"bp-folder-icon")}function ns(e=14,t="bp-folder-icon bp-hw-icon"){return ot(["M3 3h18v18H3z","M9 3v6h6","M9 21v-6","M15 9a2 2 0 1 0 0-4 2 2 0 0 0 0 4z","M9 15a2 2 0 1 0 0-4 2 2 0 0 0 0 4z"],e,t)}function ya(e=13){return ot(["M6 6h12v12H6z","M9 2v4","M15 2v4","M9 18v4","M15 18v4","M2 9h4","M2 15h4","M18 9h4","M18 15h4"],e)}function wa(e=15){return ot(["M4 10V4l4 3h8l4-3v6l-2 9H6z","M9 13h1","M14 13h1","M11 16h2"],e,"bp-cat-glyph")}function Ea(e=11){return ot(["M4 12l5 5 11-11"],e)}function Ca(e=11){return ot(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M12 6v6l4 2"],e)}function xa(e=11){return ot(["M12 17v5","M8 4h8l-1 5 3 3v2H6v-2l3-3z"],e,"bp-pin-icon")}function is(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}function ka(e){let t=e.replace(/^@/,"").trim();if(!t)return"?";let n=t.split(/[\s_-]+/).filter(Boolean);if(n.length>=2)return(n[0][0]+n[1][0]).toUpperCase();return t.slice(0,2).toUpperCase()}function Mn(e){if(e==="wait"||e==="error")return"bp-mood-wait";if(e==="work"||e==="talk")return"bp-mood-work";return"bp-mood-idle"}function Ze(e){let t=e.lastIndexOf("|");return t>=0?e.slice(t+1):e}class Tn{el;hostLabel;homeBanner;crewEl;filterInput;listEl;connEl;filterText="";allFilter="all";snoozeMenuRowId="";collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let a=document.createElement("button");a.type="button",a.className="icon bp-side-collapse",a.textContent="‹",a.title="Collapse sidebar",a.setAttribute("aria-label","Collapse sidebar"),a.setAttribute("data-testid","sidebar-collapse"),a.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,a);let r=document.createElement("div");r.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=h("sidebar.search.projects","Search projects, threads…");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let l=document.createElement("button");l.type="button",l.className="icon bp-side-add",l.textContent="+",l.title=h("thread.new","New thread"),l.setAttribute("aria-label",h("thread.new","New thread")),l.setAttribute("data-testid","sidebar-new-thread"),l.addEventListener("click",()=>{let c=this.firstProjectId();if(c)this.cb.onNewThread(c)}),r.append(this.filterInput,l),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.crewEl=document.createElement("div"),this.crewEl.className="bp-crew-band bp-hidden",this.crewEl.setAttribute("data-testid","sidebar-crew"),this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let p=document.createElement("div");p.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),p.appendChild(this.connEl),this.el.append(n,r,this.homeBanner,this.crewEl,this.listEl,p)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):h("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let a=new Date(e.awaySince);s=`${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=h("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=h("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=h("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=h("sidebar.search.projects","Search projects, threads…");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}renderCrewBand(e){let t=this.bots.find((l)=>l.uber),n=this.bots.filter((l)=>!l.uber&&(!e||l.name.toLowerCase().includes(e))),i=this.rooms.filter((l)=>!e||l.name.toLowerCase().includes(e)),s=Boolean(t&&(!e||t.name.toLowerCase().includes(e))),a=n.length>0||Boolean(this.cb.onNewBot)&&!e,r=i.length>0||Boolean(this.cb.onNewRoom)&&!e;if(!s&&!a&&!r){this.crewEl.classList.add("bp-hidden"),this.crewEl.replaceChildren();return}let o=document.createDocumentFragment();if(s&&t){let l=document.createElement("button");l.type="button",l.className="bp-crew-uber"+(t.thread===this.selectedThreadId?" active":""),l.setAttribute("data-testid",`crew-uber-${t.id}`);let p=document.createElement("span");if(p.className=`bp-crew-uber-avatar ${Mn(t.mood)}`,t.color)p.style.color=t.color;p.appendChild(wa(14));let c=document.createElement("span");c.className="bp-crew-uber-meta";let u=document.createElement("span");if(u.className="bp-crew-uber-name",u.textContent=t.name,c.appendChild(u),t.note){let d=document.createElement("span");d.className=`bp-crew-uber-note ${Mn(t.mood)}`,d.textContent=t.note,c.appendChild(d)}if(l.append(p,c),t.mood==="wait"||t.mood==="error"){let d=document.createElement("span");d.className="bp-status-pill bp-pill-bad",d.textContent="? Input",l.appendChild(d)}l.addEventListener("click",()=>this.cb.onSelectBot(t)),o.appendChild(l)}if(a){let l=document.createElement("div");l.className="bp-crew-bots",l.setAttribute("data-testid","crew-bots");let p=document.createElement("span");p.className="bp-crew-lbl",p.textContent=h("tour.title.bots","Bots").toUpperCase(),l.appendChild(p);let c=document.createElement("div");c.className="bp-crew-bot-tiles";for(let u of n){let d=document.createElement("button");if(d.type="button",d.className=`bp-crew-bot-tile ${Mn(u.mood)}`+(u.thread===this.selectedThreadId?" active":""),d.title=u.note?`@${u.name} — ${u.note}`:`@${u.name}`,d.setAttribute("aria-label",`@${u.name}`),d.setAttribute("data-testid",`crew-bot-${u.id}`),u.color)d.style.setProperty("--bot-c",u.color);let m=document.createElement("span");if(m.className="bp-crew-bot-init",m.textContent=ka(u.name),d.appendChild(m),u.mood==="wait"||u.mood==="error"){let f=document.createElement("span");f.className="bp-crew-bot-wait",d.appendChild(f)}d.addEventListener("click",()=>this.cb.onSelectBot(u)),c.appendChild(d)}if(this.cb.onNewBot&&!e){let u=document.createElement("button");u.type="button",u.className="bp-crew-bot-tile bp-crew-add",u.textContent="+",u.title=h("bots.new","New bot"),u.setAttribute("aria-label",h("bots.new","New bot")),u.setAttribute("data-testid","crew-new-bot"),u.addEventListener("click",()=>this.cb.onNewBot?.()),c.appendChild(u)}l.appendChild(c),o.appendChild(l)}if(r){let l=document.createElement("div");l.className="bp-crew-rooms",l.setAttribute("data-testid","crew-rooms");for(let p of i){let c=document.createElement("button");c.type="button",c.className="bp-crew-room-chip",c.setAttribute("data-testid",`crew-room-${p.id}`);let u=document.createElement("span");u.className="bp-dim",u.textContent="#";let d=document.createElement("span");if(d.textContent=p.name,c.append(u,d),p.members!==void 0&&p.members>0){let m=document.createElement("span");m.className="bp-crew-room-cnt",m.textContent=String(p.members),c.appendChild(m)}c.title=p.members?`#${p.name} (${p.members})`:`#${p.name}`,c.addEventListener("click",()=>this.cb.onSelectRoom?.(p)),l.appendChild(c)}if(this.cb.onNewRoom&&!e){let p=document.createElement("button");p.type="button",p.className="bp-crew-room-chip bp-crew-add",p.textContent="+",p.title=h("rooms.new","New room"),p.setAttribute("aria-label",h("rooms.new","New room")),p.setAttribute("data-testid","crew-new-room"),p.addEventListener("click",()=>this.cb.onNewRoom?.()),l.appendChild(p)}o.appendChild(l)}this.crewEl.classList.remove("bp-hidden"),this.crewEl.replaceChildren(o)}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=h("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(a)=>{a.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderStatusPill(e,t){let n=document.createElement("span");if(n.className=`bp-status-pill bp-pill-${e.tone}`,n.textContent=`${e.icon} ${e.label}`,t)n.title=t;return n}renderRowActions(e){if(e.off)return null;let t=Array.isArray(e.snooze)&&e.snooze.length>0&&Boolean(this.cb.onSnoozeRow),n=Boolean(e.wake)&&Boolean(this.cb.onSnoozeRow),i=Boolean(e.settle);if(!t&&!n&&!i)return null;let s=document.createElement("span");if(s.className="bp-row-acts",n&&e.wake){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-wake-btn",a.textContent=h("menu.wake","Wake"),a.title=h("menu.wake","Wake snoozed thread"),a.setAttribute("data-testid",`wake-row-${e.id}`),a.addEventListener("click",(r)=>{r.stopPropagation(),this.cb.onSnoozeRow?.(e.wake)}),s.appendChild(a)}if(t&&e.snooze){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-snooze-btn",a.title=h("menu.snooze","Snooze thread"),a.setAttribute("aria-label",h("menu.snooze","Snooze thread")),a.setAttribute("data-testid",`snooze-row-${e.id}`),a.appendChild(Ca(11)),a.addEventListener("click",(r)=>{r.stopPropagation(),this.snoozeMenuRowId=this.snoozeMenuRowId===e.id?"":e.id,this.render()}),s.appendChild(a)}if(i&&e.settle){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-settle-btn",a.title=h("menu.settle","Settle"),a.setAttribute("aria-label",h("menu.settle","Settle")),a.setAttribute("data-testid",`settle-row-${e.id}`),a.appendChild(Ea(11)),a.addEventListener("click",(r)=>{r.stopPropagation(),this.cb.onThreadAct(Ze(e.settle),"settle")}),s.appendChild(a)}return s}renderSectionThreadRow(e,t,n=!1){let i=document.createElement("div");i.className="bp-thread-row"+(n?" bp-inbox-row":"")+(e.id===this.selectedThreadId||Ze(e.id)===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),i.setAttribute("data-thread-id",e.id),i.setAttribute("data-testid",`thread-row-${e.id}`);let s=va(e),a=this.renderRowActions(e);if(n){let c=document.createElement("div");c.className="bp-inbox-main";let u=document.createElement("div");u.className="bp-inbox-top";let d=document.createElement("div");if(d.className="bp-thread-title",d.textContent=e.title||"Untitled thread",u.appendChild(d),a)u.appendChild(a);let m=document.createElement("div");if(m.className="bp-inbox-meta",s)m.appendChild(this.renderStatusPill(s,e.say));if(e.project){let f=document.createElement("span");f.className="bp-inbox-proj",f.textContent=e.project,m.appendChild(f)}if(e.ago){let f=document.createElement("span");if(f.className="bp-thread-age",f.textContent=e.ago,e.pinned)f.title=h("tools.pinned","Pinned");m.appendChild(f)}c.append(u,m),i.appendChild(c)}else{if(t){let u=document.createElement("span");u.className="bp-tree-branch",u.setAttribute("aria-hidden","true"),i.appendChild(u)}if(s)i.appendChild(this.renderStatusPill(s,e.say));let c=document.createElement("div");if(c.className="bp-thread-title",c.textContent=e.title||"Untitled thread",i.appendChild(c),a)i.appendChild(a);if(e.ago){let u=document.createElement("span");if(u.className="bp-thread-age",u.textContent=e.ago,e.pinned)u.title=h("tools.pinned","Pinned");i.appendChild(u)}}let r=e.nav||e.id;if(!e.off&&r&&!r.startsWith("@room:"))i.addEventListener("click",()=>this.cb.onSelectThread(Ze(r)));let o=this.snoozeMenuRowId===e.id&&Array.isArray(e.snooze)&&e.snooze.length>0,l=e.kind==="swarm"?Ki(e.need):null;if(!l&&!o)return i;let p=document.createElement("div");if(p.className="bp-need-wrap",p.appendChild(i),o&&e.snooze){let c=document.createElement("div");c.className="bp-snooze-bar"+(t?" nested":""),c.setAttribute("data-testid",`snooze-bar-${e.id}`);let u=document.createElement("span");u.className="bp-dim",u.textContent="Snooze:",c.appendChild(u);for(let d of e.snooze){let m=document.createElement("button");m.type="button",m.className="bp-snooze-opt",m.textContent=d.label,m.addEventListener("click",(f)=>{f.stopPropagation(),this.snoozeMenuRowId="",this.cb.onSnoozeRow?.(d.value),this.render()}),c.appendChild(m)}p.appendChild(c)}if(l){let c=document.createElement("div");c.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),c.setAttribute("data-testid",`need-${e.id}`);let u=document.createElement("span");u.className="bp-need-line",u.textContent=l.line,u.title=l.line,c.appendChild(u);for(let m of l.actions){if(!Yt(m,Boolean(this.cb.hasRoomView)))continue;let f=document.createElement("button");f.type="button",f.className="bp-need-btn",f.textContent=m.label,f.setAttribute("data-testid",`need-${m.act}-${e.id}`),f.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,f.addEventListener("click",(b)=>{b.stopPropagation();let g=this.cb.onNeedAct;if(!g)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),g(m).catch((y)=>{this.needErr.set(e.id,y instanceof Error?y.message:String(y))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),c.appendChild(f)}p.appendChild(c);let d=this.needErr.get(e.id);if(d){let m=document.createElement("div");m.className="bp-need-err"+(t?" nested":""),m.textContent=d,p.appendChild(m)}}return p}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let r of n)if(r.kind==="threads")for(let o of r.rows)i.add(o.id),i.add(Ze(o.id));else if(r.kind==="projects")for(let o of r.rows)for(let l of o.threads??[])i.add(l.id),i.add(Ze(l.id));let s=this.selectedThreadId?this.threads.find((r)=>r.id===this.selectedThreadId)??null:null,a=!1;for(let r of n)if(r.kind==="projects"&&(r.rows.length>0||(r.count??0)>0))a=!0;for(let r of n){if(r.kind==="bub")continue;if(r.kind==="threads"){let o=Boolean(r.fold&&r.toggle),l=r.rows.filter((c)=>{if(!t)return!0;return`${c.title} ${c.project??""}`.toLowerCase().includes(t)});if(!o&&l.length===0)continue;if(o&&t&&l.length===0)continue;if(o&&!t&&(r.count??l.length)===0)continue;let p=document.createElement("section");if(p.className=`bp-side-section bp-side-inbox bp-sec-${r.id}`,p.setAttribute("data-section-id",r.id),o){let c=document.createElement("button");c.type="button",c.className="bp-side-section-head bp-side-section-toggle";let u=t?l.length:r.count??l.length,d=r.open||Boolean(t)?"▾":"▸";if(c.textContent=`${d} ${r.title.toUpperCase()} (${u})`,r.hint)c.title=r.hint;c.setAttribute("data-testid",`section-toggle-${r.id}`),c.addEventListener("click",()=>{if(r.toggle)this.cb.onToggleSection?.(r.toggle)}),p.appendChild(c)}else{let c=document.createElement("div");c.className="bp-side-section-head"+(r.id==="needs"?" bp-head-needs":r.id==="running"?" bp-head-running":""),c.textContent=`${r.title.toUpperCase()} ${l.length}`,p.appendChild(c)}if(!o||Boolean(r.open)||Boolean(t))for(let c of l)p.appendChild(this.renderSectionThreadRow(c,!1,!0));e.appendChild(p);continue}if(r.kind==="projects"){let o=r.rows,l=o.filter((d)=>{if(!t)return!0;if((d.title||d.id).toLowerCase().includes(t))return!0;if((d.threads??[]).some((m)=>m.title.toLowerCase().includes(t)))return!0;if((d.swarms??[]).some((m)=>m.title.toLowerCase().includes(t)))return!0;return!1}),p=Boolean(r.fold&&r.toggle);if(t&&l.length===0)continue;if(!p&&r.id!=="active"&&l.length===0)continue;let c=document.createElement("section");if(c.className=`bp-side-section bp-sec-${r.id}`,c.setAttribute("data-section-id",r.id),p){let d=document.createElement("button");d.type="button",d.className="bp-side-section-head bp-side-section-toggle";let m=t?l.length:r.count??l.length,f=r.open||Boolean(t)?"▾":"▸";if(d.textContent=`${f} ${r.title.toUpperCase()} (${m})`,r.hint)d.title=r.hint;d.setAttribute("data-testid",`section-toggle-${r.id}`),d.addEventListener("click",()=>{if(r.toggle)this.cb.onToggleSection?.(r.toggle)}),c.appendChild(d)}else c.appendChild(this.projectsHead(r.title.toUpperCase()));if(!p||Boolean(r.open)||Boolean(t)){if(r.id==="all"&&!t){let d=o.some((f)=>f.hasBoard||f.hasSchematic),m=o.some((f)=>!f.hasBoard&&!f.hasSchematic);if(d&&m){let f=document.createElement("div");f.className="bp-proj-filter",f.setAttribute("data-testid","all-projects-filter");let b=[{id:"all",label:"All"},{id:"hw",label:"Boards"},{id:"sw",label:"Code"}];for(let g of b){let y=document.createElement("button");y.type="button",y.className="bp-proj-filter-btn"+(this.allFilter===g.id?" active":""),y.textContent=g.label,y.addEventListener("click",()=>{this.allFilter=g.id,this.render()}),f.appendChild(y)}if(c.appendChild(f),this.allFilter==="hw")l=l.filter((g)=>g.hasBoard||g.hasSchematic);else if(this.allFilter==="sw")l=l.filter((g)=>!g.hasBoard&&!g.hasSchematic)}}if(r.id==="active"&&!a&&!t){let d=document.createElement("div");d.className="bp-side-empty",d.textContent="No projects yet.",c.appendChild(d)}for(let d of l){let m=document.createElement("div");if(m.className="bp-proj-group"+(d.off||r.id==="quiet"?" bp-dim":""),m.setAttribute("data-project-id",d.id),d.nav||d.key)m.setAttribute("data-project-key",d.nav||d.key||"");let f=document.createElement("div");f.className="bp-proj-head";let b=document.createElement("button");b.type="button",b.className="bp-proj-toggle";let y=Boolean(d.hasBoard||d.hasSchematic)?ns(14):ts();if(d.css)y.style.color=d.css;let w=document.createElement("span");if(w.className="bp-proj-name",w.textContent=d.title||d.id,b.append(y,w),d.fold==="project-fold"&&d.nav)b.addEventListener("click",()=>this.cb.onToggleProjectFold?.(d.nav));let x=document.createElement("div");if(x.className="bp-proj-meta",(d.needsCount??0)>0){let S=document.createElement("span");S.className="bp-proj-badge-need",S.textContent=String(d.needsCount),S.title=`${d.needsCount} needing you`,x.appendChild(S)}if((d.running??0)>0){let S=document.createElement("span");S.className="bp-proj-badge-run",S.textContent=String(d.running),S.title=`${d.running} running`,x.appendChild(S)}if(d.pinned&&r.id!=="pinned")x.appendChild(xa(11));let A=document.createElement("div");if(A.className="bp-proj-acts",!d.off&&this.cb.onQuickOpenViewer){if(d.hasBoard){let S=document.createElement("button");S.type="button",S.className="bp-proj-quick",S.title=h("viewer.board","Open Board"),S.setAttribute("aria-label",`Open Board (${d.title})`),S.setAttribute("data-testid",`quick-board-${d.id}`),S.appendChild(ns(13,"")),S.addEventListener("click",(M)=>{M.stopPropagation(),this.cb.onQuickOpenViewer?.(Ze(d.id),"board")}),A.appendChild(S)}if(d.hasSchematic){let S=document.createElement("button");S.type="button",S.className="bp-proj-quick",S.title=h("viewer.schematic","Open Schematic"),S.setAttribute("aria-label",`Open Schematic (${d.title})`),S.setAttribute("data-testid",`quick-sch-${d.id}`),S.appendChild(ya(13)),S.addEventListener("click",(M)=>{M.stopPropagation(),this.cb.onQuickOpenViewer?.(Ze(d.id),"schematic")}),A.appendChild(S)}}let N=document.createElement("button");if(N.type="button",N.className="icon bp-proj-add",N.title=h("thread.new","New thread"),N.textContent="+",N.setAttribute("data-testid",`new-thread-${d.id}`),d.off)N.disabled=!0;if(N.addEventListener("click",(S)=>{S.stopPropagation(),this.cb.onNewThread(Ze(d.id))}),A.appendChild(N),f.append(b,x,A),m.appendChild(f),!d.folded||Boolean(t)){let S=Boolean(t)&&(d.title||d.id).toLowerCase().includes(t);for(let M of d.swarms??[]){if(t&&!S&&!M.title.toLowerCase().includes(t))continue;m.appendChild(this.renderSectionThreadRow(M,!0))}for(let M of d.threads??[]){if(t&&!S&&!M.title.toLowerCase().includes(t))continue;m.appendChild(this.renderSectionThreadRow(M,!0))}if(s&&s.project===Ze(d.id)&&!i.has(s.id)&&(!t||S||s.title.toLowerCase().includes(t)))m.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:is(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}c.appendChild(m)}}e.appendChild(c)}}}render(){this.addShown=!1;let e=this.filterText;this.renderCrewBand(e);let t=document.createDocumentFragment();if(this.sections!==null)this.renderHubSections(t,e);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(e){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(e))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(t.appendChild(this.projectsHead("RECENT")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",t.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(e&&s.length===0&&!i.title.toLowerCase().includes(e))continue;let a=document.createElement("section");a.className="bp-proj-group",a.setAttribute("data-project-id",i.id);let r=document.createElement("div");r.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let l=this.collapsedProjects.has(i.id)&&!e,p=ts();if(i.css)p.style.color=i.css;let c=document.createElement("span");c.className="bp-proj-name",c.textContent=i.title||i.id,o.append(p,c),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let u=document.createElement("button");if(u.type="button",u.className="icon bp-proj-add",u.title=h("thread.new","New thread"),u.textContent="+",u.setAttribute("data-testid",`new-thread-${i.id}`),u.addEventListener("click",(d)=>{d.stopPropagation(),this.cb.onNewThread(i.id)}),r.append(o,u),a.appendChild(r),!l)for(let d of s)a.appendChild(this.renderSectionThreadRow({id:d.id,title:d.title,status:d.status,state:d.state,ago:is(d.updatedAt),pinned:d.pinned,nav:d.id},!0));t.appendChild(a)}}this.listEl.replaceChildren(t)}}function Sa(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function Mt(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function Aa(e,t){if(t===16000){let a=new Int16Array(e.length);for(let r=0;r0?l/p:0));s[a]=c<0?c*32768:c*32767}return s}class Bn{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){Mt(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(Mt(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(Mt(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?Sa(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(Mt(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let a=this.stopDrain.then(async()=>{if(t&&i){let r=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(r.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=a,await a}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),a=String(e.ins??""),r=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,r-s),l=i.slice(0,o)+a+i.slice(r);this.mark=o+a.length,this.cb.setDraft(l)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),a=i.createScriptProcessor(4096,1,1);a.onaudioprocess=(r)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=Aa(r.inputBuffer.getChannelData(0),i.sampleRate);for(let l=0;l=3200){let l=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(l.buffer),!1,t)}},s.connect(a),a.connect(i.destination),this.audioCtx=i,this.processor=a}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let a=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!a.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${a.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;Mt(this.stream),this.stream=null}}var ss=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],as=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],rs=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],os=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],La=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function Tt(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[l]++,l>i)i=l}}let s=new Int32Array(16),a=0;for(let o=1;o<=15;o++)s[o]=a,a+=n[o];let r=new Int32Array(a);for(let o=0;o0)r[s[l]++]=o}return{counts:n,symbols:r,maxBits:i}}var Pa=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),Tt(e,288)})(),Na=(()=>{let e=new Uint8Array(32);return e.fill(5),Tt(e,32)})();class In{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,a=(u)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=u,s-=u,d},r=(u)=>{let d=0,m=0,f=0;for(let b=1;b<=u.maxBits;b++){d|=a(1);let g=u.counts[b];if(d-g{let d=l+u;if(d>t)throw Error("inflated frame exceeds limit");if(d<=o.length)return;let m=o.length;while(m{p(1),o[l++]=u,this.win[this.winPos]=u,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let u=a(1),d=a(2);if(d===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let m=e[n]|e[n+1]<<8,f=e[n+2]|e[n+3]<<8;if(n+=4,(m^65535)!==f)throw Error("invalid stored block length");if(n+m>e.length)throw Error("truncated stored payload");p(m);for(let b=0;b=e.length)break}else if(d===1||d===2){let m=Pa,f=Na;if(d===2){let b=a(5)+257,g=a(5)+1,y=a(4)+4,w=new Uint8Array(19);for(let M=0;MA)throw Error("code length overflow");for(let U=0;UA)throw Error("code length overflow");S+=B}else if(M===18){let B=a(7)+11;if(S+B>A)throw Error("code length overflow");S+=B}else throw Error("invalid code length symbol")}m=Tt(N,b),f=Tt(N.subarray(b),g)}while(!0){let b=r(m);if(b<256)c(b);else if(b===256)break;else{let g=b-257;if(g>=ss.length)throw Error("invalid length symbol");let y=ss[g]+(as[g]?a(as[g]):0),w=r(f);if(w>=rs.length)throw Error("invalid distance symbol");let x=rs[w]+(os[w]?a(os[w]):0);p(y);let A=this.winPos-x&32767;for(let N=0;N{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let a=this.nextId++,r=window.setTimeout(()=>{this.pending.delete(a),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(a,{resolve:i,reject:s,timer:r}),this.ws.send(JSON.stringify({id:a,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let a;try{a=JSON.parse(s)}catch{return}if(a.t==="hub.restarting")this.restarting={reason:String(a.reason??""),build:String(a.build??""),text:String(a.text??""),at:Date.now()};if(a.t==="hello")this.restarting=null,this.hello=a,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new In:null,this.reconnectDelay=500,this.setState("connected");else if(a.t==="reply"&&typeof a.id==="number"){let r=this.pending.get(a.id);if(r)if(this.pending.delete(a.id),window.clearTimeout(r.timer),a.ok)r.resolve(a.result??{});else{let o=a.error,l=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed",p=typeof a.errorCode==="string"?a.errorCode:void 0,c=typeof a.machine==="string"?a.machine:void 0,u=typeof a.thread==="string"?a.thread:void 0;r.reject(new Bt(l,{code:p,machine:c,thread:u}))}return}for(let r of this.frameListeners)r(a)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let a;try{a=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(a.length>0&&a[0]===123)i(this.textDecoder.decode(a));else{let r=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);for(let o of this.binaryListeners)o(r)}return}for(let a of this.binaryListeners)a(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Ma=new TextDecoder;function ls(e){return e.length>7&&e[0]>=160&&e[0]<=183&&e[1]===1&&e[2]===100&&e[3]===112&&e[4]===108&&e[5]===111&&e[6]===116}function cs(e){let t=0,n=0;function i(r){if(r<=23)return r;if(r===24){if(t>=e.length)return null;return e[t++]}if(r===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(r===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(r){if(n++,r>32||n>400000||t>=e.length)return null;let o=e[t++],l=o>>5,p=i(o&31);if(p===null)return null;switch(l){case 0:return p;case 1:return-1-p;case 2:{if(t+p>e.length)return null;let c=e.subarray(t,t+p);return t+=p,c}case 3:{if(t+p>e.length)return null;let c=Ma.decode(e.subarray(t,t+p));return t+=p,c}case 4:{if(p>e.length)return null;let c=Array(p);for(let u=0;u=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function ps(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[b]==="number"?e[b]:g,n=t("l",0),i=t("c",0),s=t("a",255)/255,a=t("m",1),r=t("w",0),o=r/2,l=a===0&&r!==0,p=e.d instanceof Uint8Array?e.d:new Uint8Array(0),c=new ds(p),u=[],d=[],m=0,f=0;while(c.more()){let b=c.nextU32(),g=u.length,y=1/0,w=1/0,x=-1/0,A=-1/0;if(a===2)m=m+c.nextI32()|0,f=f+c.nextI32()|0,u.push(m,f),y=x=m,w=A=f;else{let S=Math.min(c.nextU32(),1048576);for(let M=0;Mx)x=m;if(fA)A=f}}let N=(u.length-g)/2;if(N>0){let S=a===2||N===1?2:a===0?0:1,M=a===0?0:o;d.push({info:b,x0:y-M,y0:w-M,x1:x+M,y1:A+M,at:g,n:N,kind:S})}}return{layer:n,color:i,alpha:s,mode:a,r:o,own:l,pts:new Float32Array(u),pieces:d}}function us(e,t,n){let i=(r)=>Array.isArray(r)&&r.length>=4?[Number(r[0])||0,Number(r[1])||0,Number(r[2])||0,Number(r[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],a=[];for(let r=0;r=0&&o0){n.delete(o.h),n.set(o.h,l);while(n.size>1024){let p=n.keys().next().value;if(p!==void 0)n.delete(p);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:a}}function ms(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),a=n.naturalWidth*s,r=n.naturalHeight*s,o=n.left+(n.width-a)/2,l=i?n.top:n.top+(n.height-r)/2,p=(e-o)/a,c=(t-l)/r;if(p<0||p>1||c<0||c>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(p*1000))),y:Math.max(0,Math.min(1000,Math.round(c*1000)))}}var hs=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function bs(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class jn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function gs(e,t,n){let i=!0,s=!1,a=!1,r="",o=!1,l=!1,p=-1,c=null,u=new jn,d=document.createElement("div");d.className="bp-pane bp-browser-pane",d.setAttribute("data-testid","pane-browser");let m=document.createElement("div");m.className="bp-pane-bar bp-browser-nav";function f(Z,ce,E){let k=document.createElement("button");if(k.type="button",k.className="bp-v-btn",k.textContent=Z,k.setAttribute("data-testid",ce),E)k.title=E;return k}let b=f("←","browser-back","Back"),g=f("→","browser-forward","Forward"),y=f("↻","browser-reload","Reload"),w=document.createElement("form");w.className="bp-browser-url-form";let x=document.createElement("input");x.type="text",x.className="bp-browser-input",x.placeholder="https://…",x.autocomplete="off",x.spellcheck=!1,x.setAttribute("data-testid","browser-url");let A=f("Go","browser-go","Navigate");A.type="submit",w.append(x,A);let N=f("Take over","browser-takeover");N.classList.add("is-primary"),m.append(b,g,y,w,N);let S=document.createElement("div");S.className="bp-browser-drive-bar",S.hidden=!0;let M=document.createElement("div");M.className="bp-browser-keys-row";let B=document.createElement("input");B.type="text",B.className="bp-browser-input",B.placeholder="Type text or press Enter/Tab/Arrows…",B.autocomplete="off",B.spellcheck=!1,B.setAttribute("data-testid","browser-keys");let R=f("Send","browser-type-send");M.append(B,R);let U=document.createElement("div");U.className="bp-browser-quick-keys";for(let[Z,ce]of hs){let E=f(Z,`browser-key-${ce}`);E.addEventListener("click",()=>he("press",{key:ce})),U.append(E)}S.append(M,U);let D=document.createElement("div");D.className="bp-browser-err",D.setAttribute("data-testid","browser-error"),D.hidden=!0;let re=document.createElement("div");re.className="bp-browser-stage",re.setAttribute("data-testid","browser-stage");let me=document.createElement("img");me.className="bp-browser-img",me.alt="Hub browser screen",me.draggable=!1,me.hidden=!0,me.setAttribute("data-testid","browser-frame");let oe=document.createElement("div");oe.className="bp-pane-empty",oe.setAttribute("data-testid","browser-empty"),oe.textContent="Loading browser screen…",re.append(me,oe);let Ee=document.createElement("div");Ee.className="bp-browser-hint",Ee.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",Ee.hidden=!0,d.append(m,S,D,re,Ee),e.replaceChildren(d);function Ae(Z){D.textContent=Z,D.hidden=!Z}function Me(){S.hidden=!s,Ee.hidden=!s,N.textContent=s?"Hand back":"Take over",N.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),N.classList.toggle("is-on",s),me.classList.toggle("is-driving",s)}function he(Z,ce={},E){u.enqueue(async()=>{if(!i)return;Ae("");try{if(await t.hub.rpc("browser",{thread:n,op:Z,...ce}),!i)return;E?.(),le()}catch(k){if(!i)return;Ae(k instanceof Error?k.message:String(k))}})}function be(Z){he("toolbar",{command:Z},()=>{s=!0,Me()})}b.addEventListener("click",()=>be("back")),g.addEventListener("click",()=>be("forward")),y.addEventListener("click",()=>be("reload")),w.addEventListener("submit",(Z)=>{Z.preventDefault();let ce=bs(x.value);if(!ce)return;if(x.value=ce,!s)he("takeover",{},()=>{s=!0,Me()});he("navigate",{url:ce},()=>{s=!0,Me()})}),N.addEventListener("click",()=>{if(s)he("handback",{},()=>{s=!1,Me()});else he("takeover",{},()=>{s=!0,Me(),B.focus()})});function I(){let Z=B.value;if(!Z)return;B.value="",he("type",{text:Z})}R.addEventListener("click",I),B.addEventListener("keydown",(Z)=>{if(!s)return;if(Z.key==="Enter"){if(Z.preventDefault(),B.value)I();he("press",{key:"Enter"});return}if(Z.key==="Tab"||Z.key==="Escape"||Z.key==="ArrowUp"||Z.key==="ArrowDown"||Z.key==="ArrowLeft"||Z.key==="ArrowRight"||Z.key==="Backspace"&&B.value==="")Z.preventDefault(),he("press",{key:Z.key})}),me.addEventListener("click",(Z)=>{if(!s||!a)return;let ce=me.getBoundingClientRect(),E=ms(Z.clientX,Z.clientY,{left:ce.left,top:ce.top,width:ce.width,height:ce.height,naturalWidth:me.naturalWidth,naturalHeight:me.naturalHeight});if(!E)return;he("click",E)}),me.addEventListener("wheel",(Z)=>{if(!s||!a)return;Z.preventDefault();let ce=Math.round(Z.deltaX),E=Math.round(Z.deltaY);if(ce===0&&E===0)return;he("scroll",{dx:ce,dy:E})},{passive:!1});async function le(){if(!i)return;if(o){l=!0;return}o=!0;try{do{l=!1,c=new AbortController;let Z=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:c.signal});if(!i)return;if(Z.ok){let ce=await Z.blob();if(!i)return;let E=URL.createObjectURL(ce),k=r;if(r=E,me.src=E,me.hidden=!1,oe.hidden=!0,a=!0,k)URL.revokeObjectURL(k)}else if(!a)me.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&l)}catch{if(!i)return;if(!a)me.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}finally{c=null,o=!1}}let ie=t.hub.onFrame((Z)=>{if(!i)return;if(Z.t==="shot"&&Z.bot===n){if(typeof Z.n==="number"){if(Z.n===p)return;p=Z.n}le()}});return le(),{destroy(){if(i=!1,ie(),c?.abort(),r)URL.revokeObjectURL(r),r=""}}}function z(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Qt(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;if(e<1048576)return`${Math.round(e/1024)} KB`;return`${(e/1048576).toFixed(1)} MB`}function vs(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function Ba(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function fs(e){return["txt","md","markdown","json","toml","yaml","yml","xml","csv","tsv","rs","ts","tsx","js","mjs","cjs","jsx","css","html","htm","sh","bash","py","c","h","cc","cpp","hpp","go","java","kt","swift","rb","lua","sql","ini","cfg","conf","env","gitignore","lock","log","gbr","gtl","gbl","gts","gbs","gto","gbo","gm1","drl","pos","net","kicad_pro","kicad_prl","kicad_dru","kicad_sym","kicad_mod","kicad_wks"].includes(e)}function Ia(e){let t=vs(e);if(t==="kicad_pcb")return"board";if(t==="kicad_sch")return"schematic";if(t==="step"||t==="stp"||t==="glb")return"mech";return null}function ys(e,t,n,i){let s=!0,a="",r="",o=z("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let l=z("div","bp-pane-bar"),p=z("div","bp-files-crumbs"),c=z("button","bp-v-btn","Refresh");c.type="button",c.addEventListener("click",()=>void g(a)),l.append(p,c);let u=z("div","bp-files-split"),d=z("div","bp-files-list");d.setAttribute("data-testid","files-list");let m=z("div","bp-files-preview");m.setAttribute("data-testid","files-preview"),m.append(z("div","bp-pane-empty","Select a file to preview")),u.append(d,m),o.append(l,u),e.replaceChildren(o);function f(){p.replaceChildren();let y=z("button","bp-crumb-btn","project");if(y.type="button",y.addEventListener("click",()=>void g("")),p.append(y),!a)return;let w=a.split("/").filter(Boolean),x="";for(let A of w){x=x?`${x}/${A}`:A;let N=x;p.append(z("span","bp-vh-sep","/"));let S=z("button","bp-crumb-btn",A);S.type="button",S.addEventListener("click",()=>void g(N)),p.append(S)}}async function b(y,w,x){r=y,m.replaceChildren();let A=z("div","bp-files-prev-head");A.append(z("span","bp-files-prev-name",y));let N=z("div","bp-files-prev-acts"),S=Ia(w);if(S){let U=z("button","bp-v-btn is-primary",`Open in ${S}`);U.type="button",U.setAttribute("data-testid","files-open-viewer"),U.addEventListener("click",()=>i(S,y)),N.append(U)}let M=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(y)}`,B=z("a","bp-v-btn","Download");B.href=M,B.download=w,N.append(B),A.append(N),m.append(A);let R=vs(w);if(Ba(R)){let U=z("div","bp-files-img-wrap"),D=document.createElement("img");D.className="bp-files-img",D.alt=w,D.src=M,U.append(D),m.append(U);return}if(x>524288&&!fs(R)){m.append(z("div","bp-pane-empty",`Binary file (${Qt(x)}). Use Download to save.`));return}if(fs(R)||x<=65536){let U=z("div","bp-pane-empty","Loading…");m.append(U);try{let D=await fetch(M,{credentials:"same-origin"});if(!s||r!==y)return;if(!D.ok){U.textContent=`Could not load file (${D.status})`;return}if((D.headers.get("content-type")||"").startsWith("image/")){U.remove();let ie=document.createElement("img");ie.className="bp-files-img",ie.alt=w,ie.src=M,m.append(ie);return}let me=262144,oe=[],Ee=0,Ae=!1;if(D.body){let ie=D.body.getReader();try{while(!0){let{done:Z,value:ce}=await ie.read();if(Z||!ce)break;if(Ee+ce.byteLength>me){let E=me-Ee;if(E>0)oe.push(ce.subarray(0,E)),Ee+=E;Ae=!0,await ie.cancel();break}oe.push(ce),Ee+=ce.byteLength}}finally{ie.releaseLock()}}if(!s||r!==y)return;let Me=new Uint8Array(Ee),he=0;for(let ie of oe)Me.set(ie,he),he+=ie.byteLength;let be=!1;for(let ie=0;ieA.dir===N.dir?A.name.localeCompare(N.name):A.dir?-1:1),d.replaceChildren(),y){let A=z("button","bp-file-row is-dir");A.type="button",A.append(z("span","bp-file-icon","↰"),z("span","bp-file-name",".."));let N=y.includes("/")?y.slice(0,y.lastIndexOf("/")):"";A.addEventListener("click",()=>void g(N)),d.append(A)}if(x.length===0){d.append(z("div","bp-pane-empty","Empty folder"));return}for(let A of x){let N=y?`${y}/${A.name}`:A.name,S=z("button","bp-file-row"+(A.dir?" is-dir":"")+(N===r?" is-sel":""));S.type="button",S.setAttribute("data-testid",`file-row-${A.name}`),S.append(z("span","bp-file-icon",A.dir?"▸":"·"),z("span","bp-file-name",A.name),z("span","bp-file-size",A.dir?"":Qt(A.size))),S.addEventListener("click",()=>{if(A.dir)g(N);else d.querySelectorAll(".bp-file-row.is-sel").forEach((M)=>M.classList.remove("is-sel")),S.classList.add("is-sel"),b(N,A.name,A.size)}),d.append(S)}}catch(w){if(!s)return;d.replaceChildren(z("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return g(""),{destroy(){s=!1}}}function ws(e,t,n){let i=!0,s=z("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let a=z("div","bp-pane-bar"),r=z("span","bp-diff-summary","Loading diff…"),o=z("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void p()),a.append(r,o);let l=z("div","bp-diff-body");l.setAttribute("data-testid","diff-body"),s.append(a,l),e.replaceChildren(s);async function p(){r.textContent="Loading diff…",l.replaceChildren();try{let c=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(c?.nogit){r.textContent="Not a git repository",l.append(z("div","bp-pane-empty","This project is not a git repository."));return}let u=typeof c?.diff==="string"?c.diff:"";if(!u.trim()){r.textContent="Clean working tree",l.append(z("div","bp-pane-empty","No uncommitted changes."));return}let d=u.split(` +`),m=0,f=0,b=0,g=document.createDocumentFragment(),y=z("div","bp-diff-file");for(let w of d){if(w.startsWith("diff --git ")){if(y.childNodes.length>0)g.append(y);y=z("div","bp-diff-file"),m++;let x=w.match(/ b\/(.+)$/);y.append(z("div","bp-diff-file-head",x?x[1]:w));continue}if(w.startsWith("index ")||w.startsWith("--- ")||w.startsWith("+++ "))y.append(z("div","bp-diff-line is-meta",w));else if(w.startsWith("@@"))y.append(z("div","bp-diff-line is-hunk",w));else if(w.startsWith("+"))f++,y.append(z("div","bp-diff-line is-add",w));else if(w.startsWith("-"))b++,y.append(z("div","bp-diff-line is-del",w));else y.append(z("div","bp-diff-line",w))}if(y.childNodes.length>0)g.append(y);r.textContent=`${m||1} file${m===1?"":"s"} · +${f} -${b}`,l.append(g)}catch(c){if(!i)return;r.textContent="Diff unavailable",l.append(z("div","bp-pane-empty",c instanceof Error?c.message:String(c)))}}return p(),{destroy(){i=!1}}}function Es(e,t,n){let i=!0,s="checks",a=z("div","bp-pane bp-review-pane");a.setAttribute("data-testid","pane-review");let r=z("div","bp-pane-bar"),o=z("div","bp-review-tabs"),l=z("button","bp-v-btn is-on","Checks"),p=z("button","bp-v-btn","BOM"),c=z("button","bp-v-btn","Comments");l.type=p.type=c.type="button",o.append(l,p,c);let u=z("button","bp-v-btn","Refresh");u.type="button",u.addEventListener("click",()=>void b()),r.append(o,u);let d=z("div","bp-review-body");d.setAttribute("data-testid","review-body"),a.append(r,d),e.replaceChildren(a);function m(g){s=g,l.classList.toggle("is-on",s==="checks"),p.classList.toggle("is-on",s==="bom"),c.classList.toggle("is-on",s==="comments"),b()}l.addEventListener("click",()=>m("checks")),p.addEventListener("click",()=>m("bom")),c.addEventListener("click",()=>m("comments"));function f(g){let y=z("div","bp-review-md"),w=g.split(` +`),x=0;while(x{M.preventDefault();let B=N.value.trim();if(!B)return;S.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:B}).then(()=>{N.value="",S.disabled=!1,b()},()=>{S.disabled=!1})}),d.append(A),x.length===0){d.append(z("div","bp-pane-empty","No review comments yet."));return}for(let M of x){let B=z("div","bp-review-comment"+(M.resolved?" is-resolved":"")),R=[M.by||"review",M.file,M.layer,M.item].filter(Boolean).join(" · ");B.append(z("div","bp-review-comment-meta",R),z("div","bp-review-comment-text",M.text)),d.append(B)}return}let g=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let y=g?.report||{};if(d.replaceChildren(),y.line||y.gate){let w=z("div","bp-review-gate",[y.gate,y.line].filter(Boolean).join(" · "));d.append(w)}if(y.err)d.append(z("div","bp-review-err",y.err));if(Array.isArray(y.tasks)&&y.tasks.length>0){let w=z("div","bp-review-tasks");y.tasks.forEach((x,A)=>{let N=z("label","bp-review-task"),S=document.createElement("input");S.type="checkbox",S.checked=!!(x.done??x.checked);let M=typeof x.index==="number"?x.index:A;S.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:M}).then(()=>void b(),()=>{})}),N.append(S,z("span",void 0,x.text||x.label||`Item ${A+1}`)),w.append(N)}),d.append(w)}if(y.md&&y.md.trim())d.append(f(y.md));else if(!y.err&&(!y.tasks||y.tasks.length===0))d.append(z("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(g){if(!i)return;d.replaceChildren(z("div","bp-pane-empty",g instanceof Error?g.message:String(g)))}}return b(),{destroy(){i=!1}}}function Cs(e,t){let n=e>>>16&255,i=e>>>8&255,s=e&255;return t>=0.999?`rgb(${n},${i},${s})`:`rgba(${n},${i},${s},${t.toFixed(3)})`}class Dn{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,a=Math.max(i-t,1000),r=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),l=Math.max(o.width,200),p=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(l/a,p/r)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),a=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==a)this.canvas.width=s,this.canvas.height=a;let r=this.ctx;r.setTransform(i,0,0,i,0,0),r.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",r.fillRect(0,0,t,n);let o=this.frame;if(!o)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let l=t*0.5,p=n*0.5,c=this.scale,u=this.cx,d=this.cy,m=u-l/c,f=u+l/c,b=d-p/c,g=d+p/c,{off:y,dim:w,lift:x}=this.masks,A=[],N=[];for(let M=0;M>>B&1)===1)continue;if(B===x)N.push(M);else A.push(M)}let S=A.concat(N);r.lineCap="round",r.lineJoin="round";for(let M=0;M>>R.layer&1)===1,D=R.alpha*(U?0.25:1);if(D<=0.01)continue;this.drawChunk(r,R,D,m,b,f,g,u,d,c,l,p)}if(this.highlights.size>0){r.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",r.fillRect(0,0,t,n);let M=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let B=0;Ba||g.y1r)continue;if(g.n<3)continue;let y=(d[g.at]-o)*p+c,w=(d[g.at+1]-l)*p+u;e.moveTo(y,w);for(let x=1;x0)e.fill()}else if(t.mode===2){let f=Math.max(0.75,t.r*p);e.fillStyle=m,e.beginPath();let b=0;for(let g=0;ga||y.y1r)continue;let w=(d[y.at]-o)*p+c,x=(d[y.at+1]-l)*p+u;e.moveTo(w+f,x),e.arc(w,x,f,0,Math.PI*2),b++}if(b>0)e.fill()}else{e.strokeStyle=m,e.lineWidth=Math.max(1,t.r*2*p),e.beginPath();let f=0;for(let b=0;ba||g.y1r)continue;let y=(d[g.at]-o)*p+c,w=(d[g.at+1]-l)*p+u;if(g.n===1)e.moveTo(y,w),e.lineTo(y+0.01,w);else{e.moveTo(y,w);for(let x=1;x0)e.stroke()}}drawLitPieces(e,t,n,i,s,a,r,o,l,p,c,u,d){let m=t.pts,f=Cs(t.color,t.alpha);for(let b=0;br||g.y1o)continue;let y=(m[g.at]-l)*c+u,w=(m[g.at+1]-p)*c+d;if(g.kind===2){let x=Math.max(1.5,t.r*c);e.fillStyle=f,e.beginPath(),e.arc(y,w,x,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(g.kind===0&&g.n>=3){e.fillStyle=f,e.beginPath(),e.moveTo(y,w);for(let x=1;x=0;c--){let u=n.chunks[c];if(u.layer<32&&(p>>>u.layer&1)===1)continue;for(let d=0;dm.x1+r||am.y1+r)continue;let f=(m.x1-m.x0+1)*(m.y1-m.y0+1);if(f{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,a=(t.y+n.y)*0.5,r=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*r)),l=this.canvas.getBoundingClientRect(),p=this.pinchStart.midX-l.left-l.width*0.5,c=this.pinchStart.midY-l.top-l.height*0.5,u=s-l.left-l.width*0.5,d=a-l.top-l.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+p/this.pinchStart.scale-u/o,this.cy=this.pinchStart.cy+c/this.pinchStart.scale-d/o,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,a=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/a,this.cy+=i/this.scale-i/a,this.scale=a,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var xs=[{id:"fit",label:"Fit"},{id:"iso",label:"Iso"},{id:"top",label:"Top"},{id:"bottom",label:"Bottom"},{id:"front",label:"Front"},{id:"right",label:"Right"},{id:"back",label:"Back"},{id:"left",label:"Left"}];function ks(e){switch(e){case"top":return{yaw:0,pitch:Math.PI*0.499};case"bottom":return{yaw:0,pitch:-Math.PI*0.499};case"front":return{yaw:0,pitch:0};case"right":return{yaw:Math.PI*0.5,pitch:0};case"back":return{yaw:Math.PI,pitch:0};case"left":return{yaw:-Math.PI*0.5,pitch:0};case"iso":case"fit":default:return{yaw:0.6,pitch:0.7}}}function Hn(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` `),a=(s[0]||"").split("\t");if(a[0]!=="git"||a[2]!==n)return!1;let r=s[1]||a.slice(4).join("\t");if(!r)return!1;let o=r.replace(/\\/g,"/"),l=i.replace(/\\/g,"/");if(l.startsWith("/")||/^[A-Za-z]:\//.test(l))return o===l;return o===l||o.endsWith(`/${l}`)}class Fn{refs=[];index=-1;lastCommit="";highlightEdits=!1;playing=!1;setRefs(e){if(this.refs=e,this.index>=e.length)this.index=-1,this.highlightEdits=!1}isLive(){return this.index<0||this.index>=this.refs.length}activeRef(){return this.isLive()?null:this.refs[this.index]}step(e){if(this.refs.length===0)return!1;let t=this.index;if(e>0)this.index=Math.min(this.refs.length-1,this.index+1);else this.index=Math.max(-1,this.index-1);if(this.index===-1)this.playing=!1,this.highlightEdits=!1;else this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0;return this.index!==t}selectCommit(e){if(!e)return this.goLive();let t=this.refs.findIndex((i)=>i.commit===e);if(t<0)return!1;let n=this.index!==t||!this.highlightEdits;return this.index=t,this.lastCommit=e,this.highlightEdits=!0,n}goLive(){let e=this.index!==-1||this.playing||this.highlightEdits;return this.index=-1,this.playing=!1,this.highlightEdits=!1,e}toggleHighlight(){if(this.highlightEdits)return this.goLive(),!1;if(this.refs.length===0)return!1;let e=this.lastCommit?this.refs.findIndex((t)=>t.commit===this.lastCommit):0;return this.index=e>=0?e:0,this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0,!0}compareRequest(){let e=this.activeRef();if(!e||!this.highlightEdits)return null;return{commit:e.commit,bits:0}}}var Ra=`#version 300 es precision highp float; out vec2 vUv; @@ -150,8 +150,8 @@ void main() { rgb = rgb / (vec3(1.0) + max(rgb - vec3(0.8), vec3(0.0)) * 0.28); outColor = vec4(linearToSrgb(clamp(rgb, 0.0, 1.0)), alpha * uFade); } -`;function ze(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var Fa=[ze(77),ze(83),ze(94)],$a=[ze(53),ze(58),ze(67)],Ga=[ze(245),ze(246),ze(248)],Oa=[ze(225),ze(228),ze(233)];function Ss(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function As(e,t,n){let i=Ss(e,e.VERTEX_SHADER,t),s=Ss(e,e.FRAGMENT_SHADER,n),a=e.createProgram();if(!a)throw Error("createProgram failed");if(e.attachShader(a,i),e.attachShader(a,s),e.linkProgram(a),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(a,e.LINK_STATUS)){let r=e.getProgramInfoLog(a)||"program link error";throw e.deleteProgram(a),Error(r)}return a}function Va(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function Ua(e,t,n,i){let s=1/Math.tan(e*0.5),a=1/(n-i),r=new Float32Array(16);return r[0]=s/t,r[5]=s,r[10]=(i+n)*a,r[11]=-1,r[14]=2*i*n*a,r}function Ls(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function Ps(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function $n(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class Gn{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=As(n,Ra,ja),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=As(n,Da,Ha),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=ps(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,a=[n.buffer,i.buffer];if(s)a.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},a)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)a++;else r++;let o=a>0?new Float32Array(a*9):null,l=a>0?new Float32Array(a*9):null,p=a>0?new Float32Array(a*12):null,c=r>0?new Float32Array(r*9):null,u=r>0?new Float32Array(r*9):null,d=r>0?new Float32Array(r*12):null,h=0,f=0;for(let y=0;y>>24&255,A=1-x/255,N=(w>>>16&255)/255,S=(w>>>8&255)/255,M=(w&255)/255,B=y*9;if(x===0&&o&&l&&p){let R=h*9;for(let D=0;D<9;D++)o[R+D]=e[B+D],l[R+D]=t[B+D];let V=h*12;for(let D=0;D<3;D++)p[V+D*4]=N,p[V+D*4+1]=S,p[V+D*4+2]=M,p[V+D*4+3]=1;h++}else if(c&&u&&d){let R=f*9;for(let D=0;D<9;D++)c[R+D]=e[B+D],u[R+D]=t[B+D];let V=f*12;for(let D=0;D<3;D++)d[V+D*4]=N,d[V+D*4+1]=S,d[V+D*4+2]=M,d[V+D*4+3]=A;f++}}let b=o&&l&&p?this.createSubBatch(o,l,p,a*3):null,g=c&&u&&d?this.createSubBatch(c,u,d,r*3):null;if(!b&&!g)return null;return{opaque:b,translucent:g,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=ks(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),a=Math.min(window.devicePixelRatio||1,2),r=Math.round(i*a),o=Math.round(s*a);if(this.canvas.width!==r||this.canvas.height!==o)this.canvas.width=r,this.canvas.height=o;if(t.viewport(0,0,r,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let R=this.lightTheme?Ga:Fa,V=this.lightTheme?Oa:$a;t.uniform3f(this.uBgTop,R[0],R[1],R[2]),t.uniform3f(this.uBgBot,V[0],V[1],V[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let l=Math.cos(this.pitch),p=Math.sin(this.pitch),c=Math.cos(this.yaw),u=Math.sin(this.yaw),d=[this.target[0]+this.dist*l*u,this.target[1]-this.dist*l*c,this.target[2]+this.dist*p],h=Ls([this.target[0]-d[0],this.target[1]-d[1],this.target[2]-d[2]]),f=Math.abs(h[2])>0.99?[0,1,0]:[0,0,1],b=Ls(Ps(h,f)),g=Ps(b,h),y=new Float32Array([b[0],g[0],-h[0],0,b[1],g[1],-h[1],0,b[2],g[2],-h[2],0,-$n(b,d),-$n(g,d),$n(h,d),1]),w=Math.max(0.05,this.dist*0.01),x=Math.max(this.dist*10,this.radius*20),A=Ua(35*Math.PI/180,r/o,w,x),N=Va(A,y);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,N),t.uniform3f(this.uEye,d[0],d[1],d[2]),t.uniform3f(this.uRight,b[0],b[1],b[2]),t.uniform3f(this.uUp,g[0],g[1],g[2]),t.uniform3f(this.uFwd,h[0],h[1],h[2]);let S=!1,M=[],B=[];for(let R of this.partBatches){let V=e-R.fadeStartMs,D=R.fadeStartMs===0?1:Math.min(1,Math.max(0,V/300));if(D<1){if(S=!0,D>0)B.push({batch:R,fade:D})}else M.push(R)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let R of M)this.drawSubBatch(R.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let R of M)this.drawSubBatch(R.translucent);for(let{batch:R,fade:V}of B)t.uniform1f(this.uFade,V),this.drawSubBatch(R.opaque),this.drawSubBatch(R.translucent);return t.depthMask(!0),t.bindVertexArray(null),S}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,a]=Array.from(this.pointers.values()),r=Math.hypot(a.x-s.x,a.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/r)));this.pinchDist=r,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,a=Math.cos(this.yaw),r=Math.sin(this.yaw);this.target[0]-=n*a*s,this.target[1]-=n*r*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var Ns=64,Wa=16777216;function _a(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function It(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Ms(e){switch(e){case"board":return m("viewer.board","Board");case"schematic":return m("viewer.schematic","Schematic");case"3d":return m("viewer.solid","3D");case"gerbers":return m("gpui.gerbers","Gerbers");case"mech":return m("viewer.mech","Mech");case"files":return m("viewer.files","Files");case"diff":return m("viewer.diff","Diff");case"review":return m("viewer.review","Review");case"browser":return m("bots.tab.browser","Browser");case"terminal":return m("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function On(e){return e==="board"||e==="schematic"||e==="gerbers"}function za(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function Vn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let a=document.createElement("span");a.className="bp-vh-sep",a.textContent="·",a.hidden=!0;let r=document.createElement("span");r.className="bp-vh-file",r.hidden=!0,i.append(s,a,r);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let l=document.createElement("div");l.className="bp-solid-bar",l.setAttribute("data-testid","solid-presets-bar"),l.hidden=!0;let p=document.createElement("div");p.className="bp-v-banner",p.hidden=!0;let c=document.createElement("div");c.className="bp-v-stage-wrap";let u=document.createElement("div");u.className="bp-v-stage";let d=document.createElement("div");d.className="bp-v-overlay",d.hidden=!0;let h=document.createElement("div");h.className="bp-v-layers",h.hidden=!0;let f=document.createElement("div");f.className="bp-v-info",f.hidden=!0,c.append(u,d,h,f);let b=document.createElement("div");b.className="bp-history-bar",b.setAttribute("data-testid","viewer-history-bar"),b.hidden=!0,e.replaceChildren(n,l,p,c,b);let g="",y="",w=0,x=!1,A=new Set,N=[],S=0,M=new Map,B=new Map,R={},V=[],D="",re="",he=!1,oe=!1,we=0,Ae=!1,Me=0,me="",be=0,I=null,le=null,ne=null,X=null,ce=null,E=new Fn,k=0,j=!1,T="",q="",te="",H="";document.addEventListener("click",(F)=>{if(!j)return;if(F.target instanceof Node&&b.contains(F.target))return;j=!1,ue()}),document.addEventListener("keydown",(F)=>{if(j&&F.key==="Escape")j=!1,ue()});function K(){if(k)window.clearInterval(k),k=0;E.playing=!1}function je(){let F=y==="3d"||y==="mech";if(l.hidden=!F,!F)return;if(l.childElementCount>0)return;for(let _ of xs){let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent=_.label,U.setAttribute("data-testid",`solid-view-${_.id}`),U.addEventListener("click",()=>{ne?.setView(_.id)}),l.append(U)}let W=document.createElement("button");W.type="button",W.className="bp-v-btn",W.textContent="Snap view",W.setAttribute("data-testid","solid-snap"),W.addEventListener("click",()=>{if(!ne)return;ne.snapPng().then((_)=>{if(!_)return;let U=URL.createObjectURL(_),G=document.createElement("a");G.href=U;let Z=(De()||y||"view").replace(/[^a-zA-Z0-9._-]/g,"_");G.download=`${Z}-snap.png`,G.click(),setTimeout(()=>URL.revokeObjectURL(U),1000)})}),l.append(W)}async function Le(){if(!g||y!=="board"&&y!=="schematic")return;ue();let F=E.compareRequest();if(!F){T="",q="",te="",H="",await Ge(!1);return}let W=`${y}|${F.commit}|${F.bits}|${re}`;if(W===H&&A.size>0){ke(E.highlightEdits?`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)}`,!1);return}let _=++w;A.clear(),M.clear(),Ye(),x=!0,T="",q=F.commit,te="",H=W;try{let U=re||(y==="schematic"?R.sch:R.pcb)||"";if(!U){let xe=await t.hub.rpc("viewer.files",{thread:g});if(_!==w)return;R=xe||{},ae(),U=(y==="schematic"?R.sch:R.pcb)||""}if(!U)throw Error(`Unable to resolve ${y} file path for compare`);let G=await t.hub.rpc("viewer.compare",{thread:g,kind:y,commit:F.commit,bits:F.bits,...re?{path:re}:{}});if(_!==w)return;let Z=typeof G?.root==="string"?G.root:"",ee=y==="schematic"?"1":"0";T=Z?`${ee}|${Z}|diff -`:`${ee}|`,q=F.commit,te=U.startsWith("/")||/^[A-Za-z]:[\\/]/.test(U)||!Z?U:`${Z.replace(/\/+$/,"")}/${U.replace(/^\/+/,"")}`,x=!1;let Ce=N;Ye();for(let xe of Ce)if(xe.kind==="bin")$e(xe.buf);else We(xe.key,xe.none,xe.retryable);ke(E.highlightEdits?`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${E.activeRef()?.label||F.commit.slice(0,7)}`,!1)}catch(U){if(_!==w)return;x=!1,T="",q="",te="",H="",Ye(),ke(U instanceof Error?U.message:String(U),!0)}}function ue(){let F=y==="board"||y==="schematic";if(b.hidden=!F,!F)return;let W=document.createElement("div");W.className="bp-history-group";let _=document.createElement("button");_.type="button",_.className="bp-v-btn",_.textContent="<",_.title="Older snapshot",_.disabled=E.refs.length===0||E.index>=E.refs.length-1,_.setAttribute("data-testid","history-prev"),_.addEventListener("click",()=>{if(K(),E.step(1))Le()});let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(E.playing?" is-on":""),U.textContent=E.playing?"⏸":"▶",U.title=E.playing?"Pause history":"Play history",U.disabled=E.refs.length===0,U.setAttribute("data-testid","history-play"),U.addEventListener("click",()=>{if(E.playing){K(),ue();return}if(E.refs.length===0)return;if(E.playing=!0,E.isLive())E.index=E.refs.length-1,Le();else ue();k=window.setInterval(()=>{if(!E.playing||y!=="board"&&y!=="schematic"){K(),ue();return}if(E.step(-1))Le();else K(),ue()},1400)});let G=document.createElement("button");G.type="button",G.className="bp-v-btn",G.textContent=">",G.title="Newer snapshot",G.disabled=E.isLive(),G.setAttribute("data-testid","history-next"),G.addEventListener("click",()=>{if(K(),E.step(-1))Le()});let Z=document.createElement("button");Z.type="button",Z.className="bp-v-btn"+(E.isLive()?" is-on":""),Z.textContent="Live",Z.setAttribute("data-testid","history-live"),Z.addEventListener("click",()=>{if(K(),E.goLive())ke("",!1),Le()});let ee=document.createElement("span");ee.className="bp-history-label",ee.setAttribute("data-testid","history-label");let Ce=E.activeRef();ee.textContent=Ce?Ce.label||Ce.commit.slice(0,7):E.refs.length>0?`Live (${E.refs.length} saved)`:"Live",W.append(_,U,G,Z,ee);let xe=document.createElement("div");xe.className="bp-history-group";let Ne=document.createElement("button");Ne.type="button",Ne.className="bp-v-btn"+(E.highlightEdits?" is-on":""),Ne.textContent="Highlight edits",Ne.disabled=E.refs.length===0,Ne.setAttribute("data-testid","history-highlight"),Ne.addEventListener("click",()=>{K(),E.toggleHighlight(),Le()});let Re=document.createElement("div");Re.className="bp-history-menu-wrap";let ye=document.createElement("button");if(ye.type="button",ye.className="bp-v-btn"+(j||!E.isLive()?" is-on":""),ye.disabled=E.refs.length===0,ye.setAttribute("data-testid","history-compare"),ye.setAttribute("aria-haspopup","menu"),ye.setAttribute("aria-expanded",String(j)),ye.textContent=Ce?`Compare: ${Ce.label||Ce.commit.slice(0,7)} ▾`:"Compare ▾",ye.addEventListener("click",(Te)=>{Te.stopPropagation(),j=!j,ue()}),Re.append(ye),j&&E.refs.length>0){let Te=document.createElement("div");Te.className="bp-history-menu",Te.setAttribute("role","menu"),Te.setAttribute("data-testid","history-compare-menu");let qe=(Ie,vt,Ft)=>{let Ke=document.createElement("button");Ke.type="button",Ke.className="bp-history-menu-item"+(Ft?" is-active":""),Ke.setAttribute("role","menuitem"),Ke.setAttribute("data-commit",vt),Ke.textContent=Ie,Ke.addEventListener("click",()=>{if(j=!1,K(),E.selectCommit(vt)){if(E.isLive())ke("",!1);Le()}else ue()}),Te.append(Ke)};qe("Live (working tree)","",E.isLive());for(let Ie of E.refs)qe(Ie.label||Ie.commit.slice(0,7),Ie.commit,Ce?.commit===Ie.commit);Re.append(Te)}xe.append(Ne,Re),b.replaceChildren(W,xe)}async function Pe(F){if(!F)return;try{let W=await t.hub.rpc("viewer.refs",{thread:F});if(F!==g)return;E.setRefs(Array.isArray(W?.refs)?W.refs:[]),ue()}catch{if(F!==g)return;E.setRefs([]),ue()}}function Y(){return document.documentElement.classList.contains("light")}let ve=new MutationObserver(()=>{let F=Y();le?.setTheme(F),ne?.setTheme(F),ce?.setTheme(F)});ve.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function ie(F,W="",_=!1){if(F==="none"){d.hidden=!0,d.replaceChildren();return}d.hidden=!1,d.className=`bp-v-overlay is-${F}`;let U=document.createElement("div");U.className="bp-v-state-card";let G=document.createElement("div");if(G.className="bp-v-state-msg",G.textContent=W,U.append(G),_){let Z=document.createElement("button");Z.type="button",Z.className="bp-v-btn is-primary",Z.textContent=m("tools.retry","Retry"),Z.addEventListener("click",()=>void Ge(!0)),U.append(Z)}d.replaceChildren(U)}function ke(F,W){p.textContent=F,p.hidden=!F,p.classList.toggle("is-warn",W)}function De(){if(re)return It(re);if(y==="board"||y==="3d")return It(R.pcb);if(y==="schematic")return It(R.sch);if(y==="mech")return It(D);return""}function ae(){s.textContent=Ms(y);let F=De();if(a.hidden=!F,r.hidden=!F,r.textContent=F,o.replaceChildren(),y==="mech"&&V.length>1){let _=document.createElement("select");_.className="bp-v-select",_.setAttribute("aria-label",m("viewer.mech","Mech"));for(let U of V){let G=document.createElement("option");G.value=U,G.textContent=It(U),G.selected=U===D,_.append(G)}_.addEventListener("change",()=>{D=_.value,ae(),Ge(!1)}),o.append(_)}if(On(y)){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(Ae?" is-on":""),_.textContent=I?.layerHead||"Layers",_.setAttribute("data-testid","viewer-layers-btn"),_.addEventListener("click",()=>{if(Ae=!Ae,h.hidden=!Ae,_.classList.toggle("is-on",Ae),Ae)_e("","")}),o.append(_)}if(y==="board"||y==="schematic"||y==="3d"||y==="mech"||y==="gerbers"){let _=document.createElement("button");_.type="button",_.className="bp-v-btn",_.textContent="Fit",_.setAttribute("data-testid","viewer-fit-btn"),_.addEventListener("click",()=>{le?.fit(),ne?.fit()}),o.append(_)}if((y==="board"||y==="schematic")&&t.hub.hasFeature("follow")){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(he&&!oe?" is-on":""),_.textContent=he?oe?m("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",_.setAttribute("data-testid","viewer-follow-btn"),_.addEventListener("click",()=>void nt()),o.append(_)}let W=document.createElement("button");W.type="button",W.className="bp-v-btn bp-v-close",W.textContent="✕",W.title=m("common.close","Close"),W.setAttribute("aria-label",m("common.close","Close")),W.setAttribute("data-testid","viewer-close-btn"),W.addEventListener("click",()=>t.closeViewer()),o.append(W)}function ge(){if(!I){h.replaceChildren();return}let F=document.createDocumentFragment(),W=document.createElement("div");W.className="bp-v-layers-head";let _=document.createElement("span");if(_.textContent=I.layerHead||"Layers",W.append(_),I.layerReset){let ee=document.createElement("button");ee.type="button",ee.className="bp-v-btn",ee.textContent="Reset",ee.addEventListener("click",()=>void _e("reset","")),W.append(ee)}if(F.append(W),I.layerModes){let ee=document.createElement("div");ee.className="bp-v-layers-modes",["All","Dim","Only"].forEach((Ce,xe)=>{let Ne=document.createElement("button");Ne.type="button",Ne.className="bp-v-btn"+(I?.layerMode===xe?" is-on":""),Ne.textContent=Ce,Ne.addEventListener("click",()=>void _e("mode",String(xe))),ee.append(Ne)}),F.append(ee)}let U=le?.presentColors()??new Map,G=(I.layerList||[]).concat(I.layerMarks||[]),Z=document.createElement("div");Z.className="bp-v-layers-list";for(let ee of G){let Ce=U.get(ee.layer);if(Ce===void 0)continue;let xe=document.createElement("div");xe.className="bp-v-layer-row"+(ee.active?" is-focus":"");let Ne=document.createElement("input");Ne.type="checkbox",Ne.checked=ee.on!==!1,Ne.addEventListener("change",()=>void _e("toggle",String(ee.layer)));let Re=document.createElement("span");Re.className="bp-v-layer-swatch";let ye=Ce>>>16&255,Te=Ce>>>8&255,qe=Ce&255;Re.style.background=ee.on!==!1?`rgb(${ye},${Te},${qe})`:`rgba(${ye},${Te},${qe},0.2)`;let Ie=document.createElement("button");Ie.type="button",Ie.className="bp-v-layer-name",Ie.textContent=ee.name,Ie.addEventListener("click",()=>void _e("pick",String(ee.layer))),xe.append(Ne,Re,Ie),Z.append(xe)}F.append(Z),h.replaceChildren(F)}async function _e(F,W){if(!On(y))return;let _=w;try{let U=await t.hub.rpc("viewer.layers",{kind:y,present:be,off:Me,focus:me,...F?{action:F,value:W}:{}});if(_!==w||!U)return;Me=Number(U.own)||0,me=typeof U.focus==="string"?U.focus:"",I=U;let G={off:Number(U.off)||0,dim:Number(U.dim)||0,lift:typeof U.lift==="number"?U.lift:255};if(le?.setLayers(G),ae(),Ae)ge()}catch{}}async function Ue(){if(!he||oe||!g||!t.hub.hasFeature("follow"))return;oe=!0,ae();try{await t.hub.rpc("viewer.follow",{thread:g,action:"pause"})}catch{}}async function nt(){if(!g||!t.hub.hasFeature("follow"))return;let F=!he?"on":oe?"resume":"off";try{let W=await t.hub.rpc("viewer.follow",{thread:g,action:F});if(he=!!W.on,oe=!!W.paused,ae(),W.on&&!W.paused&&W.focus&&Array.isArray(W.focus.box)&&W.focus.box.length===4&&(W.seq||0)>we)we=W.seq||we,le?.zoomToBoxMm([W.focus.box[0],W.focus.box[1],W.focus.box[2],W.focus.box[3]])}catch{}}function de(){f.hidden=!0,f.replaceChildren(),le?.setHighlights([])}function gt(F){let W=F.split(";").filter(Boolean),_=W.shift()||F,U=[],G="",Z="";for(let Re of W){if(Re.startsWith("g="))continue;let ye=Re.indexOf("=");if(ye>0){let Te=Re.slice(0,ye),qe=Re.slice(ye+1);if((Te==="ref"||Te==="symbol")&&!G)G=qe;if(Te==="net"&&!Z)Z=qe;U.push([Te,qe])}else U.push([Re,""])}let ee=document.createElement("div");ee.className="bp-v-info-head";let Ce=document.createElement("span");Ce.className="bp-v-info-title",Ce.textContent=_;let xe=document.createElement("button");xe.type="button",xe.className="bp-v-info-x",xe.textContent="×",xe.setAttribute("aria-label","Clear selection"),xe.addEventListener("click",de),ee.append(Ce,xe);let Ne=document.createElement("div");Ne.className="bp-v-info-rows";for(let[Re,ye]of U){let Te=document.createElement("span");Te.className="bp-v-info-chip",Te.textContent=ye?`${Re}: ${ye}`:Re,Ne.append(Te)}return f.replaceChildren(ee,...U.length>0?[Ne]:[]),f.hidden=!1,{ref:G||void 0,net:Z||void 0}}async function Je(F){if(!F){de();return}let W=Array.from(A)[0]||"";if(!W)return;let _=w;try{let U=await t.hub.rpc("viewer.info",{key:W,at:F.at,idx:F.idx});if(_!==w)return;let G=typeof U.info==="string"?U.info:"";if(!G){de();return}let{ref:Z,net:ee}=gt(G),Ce=[];if(Z)Ce.push(["ref",Z]);if(ee)Ce.push(["net",ee]);let xe=[[F.at,F.idx]];for(let[Ne,Re]of Ce){let ye=await t.hub.rpc("viewer.probe",{key:W,name:Ne,value:Re});if(_!==w)return;if(Array.isArray(ye.matches))for(let Te of ye.matches)xe.push(Te)}le?.setHighlights(xe)}catch{de()}}function ft(){X?.destroy(),X=null,ce?.destroy(),ce=null,le?.destroy(),le=null,ne?.destroy(),ne=null,u.replaceChildren(),Ae=!1,h.hidden=!0,f.hidden=!0,f.replaceChildren(),ke("",!1),ie("none")}function Ye(){N=[],S=0}async function Ge(F){if(!g||!y)return;let W=++w;if(A.clear(),x=!1,Ye(),ft(),ae(),je(),ue(),(y==="board"||y==="schematic")&&g)Pe(g);if(za(y)){if(t.hub.rpc("viewer.watch",{thread:g,kind:""}).catch(()=>{}),y==="files")X=ys(u,t,g,(G,Z)=>{if(y=G,re=Z,G==="mech")D=Z;Ge(!1)});else if(y==="diff")X=ws(u,t,g);else if(y==="review")X=Es(u,t,g);else if(y==="browser")X=gs(u,t,g);else if(y==="terminal")ie("loading","Loading terminal…"),import("/assets/terminal.js").then((Z)=>{if(W!==w)return;if(ie("none"),Z?.mountTerminalPane)ce=Z.mountTerminalPane(u,t,g,Y());else ie("error","Terminal chunk missing",!0)},(Z)=>{if(W!==w)return;ie("error",Z instanceof Error?Z.message:String(Z),!0)});return}if(ie("loading","Loading…"),!R.root)try{let G=await t.hub.rpc("viewer.files",{thread:g});if(W!==w)return;R=G||{},ae()}catch{}if(y==="gerbers"&&R.hasGerbers===!1){ie("empty","No Gerbers in this project",!1);return}let _=Y();if(y==="3d"||y==="mech")ne=new Gn(u,{onStatus:(G,Z)=>{if(Z)ie("none"),ke(G,!1);else if(G)ie("loading",G);else ie("none"),ke("",!1)},onUserMove:()=>void Ue()}),ne.setTheme(_);else if(y==="board"||y==="schematic"||y==="gerbers")le=new Dn(u,{onPick:(G)=>void Je(G),onUserMove:()=>void Ue()}),le.setTheme(_);else{ie("empty",`${Ms(y)} is not available in this viewer`,!1);return}let U={thread:g};if(F)U.force=!0;if(y==="mech"){if(V.length===0)try{let G=await t.hub.rpc("mech.list",{thread:g});if(W!==w)return;if(V=Array.isArray(G.parts)?G.parts:[],!D)D=G.primary||V[0]||"";ae()}catch(G){if(W!==w)return;ie("error",G instanceof Error?G.message:String(G),!0);return}if(!D){ie("empty",m("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}U.kind="3d",U.path=D}else{if(U.kind=y,re&&(y==="board"||y==="schematic"))U.path=re;if(y==="3d"&&!F&&ne){let G=ne.keptToken();if(G)U.kept=G}if((y==="board"||y==="schematic"||y==="gerbers")&&!F&&t.hub.hasFeature("keptChunks"))U.keptChunks=Array.from(B.keys())}x=!0,T="",q="",te="",H="";try{let G=await t.hub.rpc("viewer.watch",U);if(W!==w)return;A=new Set(Array.isArray(G.keys)?G.keys:[]),x=!1;let Z=N;Ye();for(let ee of Z)if(ee.kind==="bin")$e(ee.buf);else We(ee.key,ee.none,ee.retryable)}catch(G){if(W!==w)return;x=!1,A.clear(),Ye();let Z=G instanceof Error?G.message:String(G),ee=/no gerbers|not in this project|another machine/i.test(Z);ie(ee?"empty":"error",Z,!ee)}}function We(F,W,_){if(x){if(N.length{if(F.t==="plot"&&typeof F.none==="string"&&typeof F.key==="string")We(F.key,F.none,F.retryable===!0)}),Oe=Ot(()=>{if(y)ae()}),Ht=(F)=>{if(F.key==="Escape"&&y&&!f.hidden)de()};return window.addEventListener("keydown",Ht),{open(F,W){if(W!==g){if(g=W,R={},V=[],D="",M.clear(),he=!1,oe=!1,we=0,Me=0,me="",be=0,I=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:W}).then((_)=>{if(W!==g)return;if(he=!!_.on,oe=!!_.paused,we=Number(_.seq)||0,y)ae()}).catch(()=>{})}if(F!==y)K(),E.goLive(),Me=0,me="",be=0,I=null;y=F,re="",Ge(!1)},reconcileHas(F){if(y&&!_a(y,F))t.closeViewer()},close(){if(w++,x=!1,K(),j=!1,T="",q="",te="",H="",E.goLive(),l.hidden=!0,b.hidden=!0,Ye(),g)t.hub.rpc("viewer.watch",{thread:g,kind:""}).catch(()=>{});y="",A.clear(),ft()}}}var Ts="http://www.w3.org/2000/svg";function Rt(e){let t=document.createElementNS(Ts,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Ts,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function qa(e){if(!e)return"bp-dot-idle";let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Bs(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}var jt="dark",en=(()=>{try{return Yi(localStorage.getItem("bp.theme.pref"))}catch{return"auto"}})(),Un=null,bt=(()=>{try{return Xi(localStorage.getItem("bp.locale"))}catch{return"auto"}})();function Ds(){let e=Pt(en,jt);document.documentElement.classList.toggle("light",e==="light");try{localStorage.setItem("bp.theme",e)}catch{}}function Is(e){if(!e)return;jt=e==="light"?"light":"dark",Ds()}function Rs(){if(bt!=="auto")ct(bt);else if(Un)ct(Un);else if(typeof navigator<"u"&&navigator.language){if(!ct(navigator.language))ct("en")}}function Ka(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function js(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")jt="light";if(Pt(en,jt)==="light")document.documentElement.classList.add("light");if(bt!=="auto")ct(bt)}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let a=document.createElement("span");a.className="bp-brand-name bp-hide-phone",a.textContent="Backplane";let r=document.createElement("span");r.className="bp-crumb-sep bp-hide-phone",r.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let l=document.createElement("span");l.className="bp-crumb-sep bp-hide-phone",l.textContent="/";let p=document.createElement("span");p.className="bp-crumb-thread",p.setAttribute("data-testid","thread-title");let c=document.createElement("span");c.className="bp-plan-top-badge bp-hidden",c.setAttribute("data-testid","plan-top-badge"),i.append(s,a,r,o,l,p,c);let u=document.createElement("div");u.className="bp-top-state bp-hide-phone bp-hidden";let d=document.createElement("span");d.className="bp-top-state-lbl",d.textContent="STATE";let h=document.createElement("span");h.className="bp-dot bp-dot-idle";let f=document.createElement("span");f.className="bp-top-state-word",u.append(d,h,f);let b=document.createElement("div");b.className="bp-top-acts bp-hide-phone bp-hidden";let g=document.createElement("button");g.type="button",g.className="bp-btn-ghost bp-top-act";let y=document.createElement("span");y.textContent=m("menu.pin","Pin"),g.append(Rt(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),y);let w=document.createElement("button");w.type="button",w.className="bp-btn-ghost bp-top-act";let x=document.createElement("span");x.textContent=m("menu.settle","Settle"),w.append(Rt(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),x);let A=document.createElement("div");A.className="bp-menu-wrap";let N=document.createElement("button");N.type="button",N.className="bp-btn-ghost bp-top-act",N.textContent="▾",N.title="Thread menu",N.setAttribute("aria-label","Thread menu"),N.setAttribute("data-testid","thread-menu-btn");let S=document.createElement("div");S.className="bp-popover bp-hidden",S.setAttribute("data-testid","thread-menu"),A.append(N,S),b.append(g,w,A);let M=document.createElement("div");M.className="bp-top-right";let B=document.createElement("button");B.type="button",B.className="bp-btn-ghost bp-top-act bp-hide-tablet",B.setAttribute("data-testid","improvements-btn");let R=document.createElement("span");R.textContent=m("gpui.improvements","Improvements"),B.append(Rt(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),R);let V=document.createElement("button");V.type="button",V.className="bp-cmd-box bp-hide-tablet",V.textContent="> Jump or run a command";let D=document.createElement("button");D.type="button",D.className="icon bp-top-icon",D.title="Search",D.setAttribute("aria-label","Search"),D.appendChild(Rt(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let re=document.createElement("button");re.type="button",re.className="icon bp-top-icon",re.title=m("palette.settings","Settings"),re.setAttribute("aria-label",m("palette.settings","Settings")),re.setAttribute("data-testid","settings-btn"),re.appendChild(Rt(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),M.append(B,V,D,re),t.append(n,i,u,b,M);let he=document.createElement("div");he.className="bp-body";let oe=document.createElement("aside");oe.className="bp-sidebar",oe.setAttribute("data-testid","sidebar");let we=document.createElement("main");we.className="bp-center";let Ae=document.createElement("div");Ae.className="bp-right-area bp-hidden",Ae.setAttribute("data-testid","right-area");let Me=document.createElement("div");Me.className="bp-right-top";let me=document.createElement("section");me.className="bp-viewer-pane bp-hidden",me.setAttribute("data-testid","viewer-pane"),Me.appendChild(me),Ae.appendChild(Me);let be=document.createElement("nav");be.className="bp-rail",be.setAttribute("aria-label","Viewer rail"),be.setAttribute("data-testid","viewer-rail"),he.append(oe,we,Ae,be),e.append(t,he);let I=new Rn,le=null,ne=new Set,X=0,ce=null,E=[],k=[],j=[],T=[],q=[],te=[],H="",K=0,je=0,Le=null,ue=null,Pe="",Y=null,ve=20,ie={},ke=new Map;function De(v,C){ke.delete(v),ke.set(v,C);while(ke.size>ve){let L=ke.keys().next().value;if(L!==void 0)ke.delete(L);else break}}let ae=new Tn(oe,{onSelectThread:(v)=>{if(v===H&&Le!==null){oe.classList.remove("bp-sidebar-open");return}Ie(v)},onNewThread:(v)=>{$t(v)},onSelectBot:(v)=>{Ie(v.thread)},onQuickOpenViewer:(v,C)=>{let L=k.find((O)=>O.project===v&&!O.archived&&!O.swarm);(async()=>{if(L)await Ie(L.id);else await $t(v);if(H)Pe=C,$e.setActive(C),Y?.open(C,H)})()},onThreadAct:(v,C)=>{Qe(v,C)},onSnoozeRow:(v)=>{I.rpc("sidebar.act",{action:"row-snooze",value:v}).then(()=>ye()).catch(()=>{})},onToggleSection:(v)=>{if(ne.has(v))ne.delete(v);else ne.add(v);ye()},onToggleProjectFold:(v)=>{I.rpc("sidebar.act",{action:"project-fold",value:v}).then(()=>ye()).catch(()=>{})},onCollapseSidebar:()=>{oe.classList.remove("bp-sidebar-open"),oe.classList.add("bp-sidebar-collapsed")},onNeedAct:async(v)=>{let C=Yt(v,!1);if(!C)return;if(C.kind==="thread"){Ie(C.id);return}if(C.kind!=="call")return;let L=Ji(await I.rpc(C.method,C.params));if(L?.kind==="thread")Ie(L.id);ye()},hasRoomView:!1,onAddProject:()=>We.open({mode:"folder"})}),ge=new dn(we,{onLoadOlder:()=>{Ke()},onGoToEntry:(v)=>{Ft(v)},onOpenAccounts:()=>{F()},onAnswerAsk:(v,C)=>{I.rpc("ask.answer",{ask:v,answer:C}).catch((L)=>{de.showError(L instanceof Error?L.message:"Could not send answer")})},onToggleReview:(v)=>{if(!H)return;let C=K;I.rpc("thread.review",{thread:H,on:v}).then((L)=>{if(C===K)ge.setReview(L.review??null)}).catch(()=>{})},onUnansweredAction:(v,C)=>{if(!H)return;if(v==="again"||v==="thread-again")I.rpc("thread.again",{thread:H,value:C}).catch(()=>{});else I.rpc("thread.act",{thread:H,action:v,value:C}).catch(()=>{})},onReplyEntry:(v)=>{if(!I.hasFeature("reply")){let C=(v.text||"").split(` +`;function ze(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var Fa=[ze(77),ze(83),ze(94)],$a=[ze(53),ze(58),ze(67)],Ga=[ze(245),ze(246),ze(248)],Oa=[ze(225),ze(228),ze(233)];function Ss(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function As(e,t,n){let i=Ss(e,e.VERTEX_SHADER,t),s=Ss(e,e.FRAGMENT_SHADER,n),a=e.createProgram();if(!a)throw Error("createProgram failed");if(e.attachShader(a,i),e.attachShader(a,s),e.linkProgram(a),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(a,e.LINK_STATUS)){let r=e.getProgramInfoLog(a)||"program link error";throw e.deleteProgram(a),Error(r)}return a}function Va(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function Ua(e,t,n,i){let s=1/Math.tan(e*0.5),a=1/(n-i),r=new Float32Array(16);return r[0]=s/t,r[5]=s,r[10]=(i+n)*a,r[11]=-1,r[14]=2*i*n*a,r}function Ls(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function Ps(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function $n(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class Gn{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=As(n,Ra,ja),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=As(n,Da,Ha),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=ps(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,a=[n.buffer,i.buffer];if(s)a.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},a)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)a++;else r++;let o=a>0?new Float32Array(a*9):null,l=a>0?new Float32Array(a*9):null,p=a>0?new Float32Array(a*12):null,c=r>0?new Float32Array(r*9):null,u=r>0?new Float32Array(r*9):null,d=r>0?new Float32Array(r*12):null,m=0,f=0;for(let y=0;y>>24&255,A=1-x/255,N=(w>>>16&255)/255,S=(w>>>8&255)/255,M=(w&255)/255,B=y*9;if(x===0&&o&&l&&p){let R=m*9;for(let D=0;D<9;D++)o[R+D]=e[B+D],l[R+D]=t[B+D];let U=m*12;for(let D=0;D<3;D++)p[U+D*4]=N,p[U+D*4+1]=S,p[U+D*4+2]=M,p[U+D*4+3]=1;m++}else if(c&&u&&d){let R=f*9;for(let D=0;D<9;D++)c[R+D]=e[B+D],u[R+D]=t[B+D];let U=f*12;for(let D=0;D<3;D++)d[U+D*4]=N,d[U+D*4+1]=S,d[U+D*4+2]=M,d[U+D*4+3]=A;f++}}let b=o&&l&&p?this.createSubBatch(o,l,p,a*3):null,g=c&&u&&d?this.createSubBatch(c,u,d,r*3):null;if(!b&&!g)return null;return{opaque:b,translucent:g,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=ks(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),a=Math.min(window.devicePixelRatio||1,2),r=Math.round(i*a),o=Math.round(s*a);if(this.canvas.width!==r||this.canvas.height!==o)this.canvas.width=r,this.canvas.height=o;if(t.viewport(0,0,r,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let R=this.lightTheme?Ga:Fa,U=this.lightTheme?Oa:$a;t.uniform3f(this.uBgTop,R[0],R[1],R[2]),t.uniform3f(this.uBgBot,U[0],U[1],U[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let l=Math.cos(this.pitch),p=Math.sin(this.pitch),c=Math.cos(this.yaw),u=Math.sin(this.yaw),d=[this.target[0]+this.dist*l*u,this.target[1]-this.dist*l*c,this.target[2]+this.dist*p],m=Ls([this.target[0]-d[0],this.target[1]-d[1],this.target[2]-d[2]]),f=Math.abs(m[2])>0.99?[0,1,0]:[0,0,1],b=Ls(Ps(m,f)),g=Ps(b,m),y=new Float32Array([b[0],g[0],-m[0],0,b[1],g[1],-m[1],0,b[2],g[2],-m[2],0,-$n(b,d),-$n(g,d),$n(m,d),1]),w=Math.max(0.05,this.dist*0.01),x=Math.max(this.dist*10,this.radius*20),A=Ua(35*Math.PI/180,r/o,w,x),N=Va(A,y);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,N),t.uniform3f(this.uEye,d[0],d[1],d[2]),t.uniform3f(this.uRight,b[0],b[1],b[2]),t.uniform3f(this.uUp,g[0],g[1],g[2]),t.uniform3f(this.uFwd,m[0],m[1],m[2]);let S=!1,M=[],B=[];for(let R of this.partBatches){let U=e-R.fadeStartMs,D=R.fadeStartMs===0?1:Math.min(1,Math.max(0,U/300));if(D<1){if(S=!0,D>0)B.push({batch:R,fade:D})}else M.push(R)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let R of M)this.drawSubBatch(R.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let R of M)this.drawSubBatch(R.translucent);for(let{batch:R,fade:U}of B)t.uniform1f(this.uFade,U),this.drawSubBatch(R.opaque),this.drawSubBatch(R.translucent);return t.depthMask(!0),t.bindVertexArray(null),S}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,a]=Array.from(this.pointers.values()),r=Math.hypot(a.x-s.x,a.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/r)));this.pinchDist=r,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,a=Math.cos(this.yaw),r=Math.sin(this.yaw);this.target[0]-=n*a*s,this.target[1]-=n*r*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var Ns=64,Wa=16777216;function _a(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function It(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Ms(e){switch(e){case"board":return h("viewer.board","Board");case"schematic":return h("viewer.schematic","Schematic");case"3d":return h("viewer.solid","3D");case"gerbers":return h("gpui.gerbers","Gerbers");case"mech":return h("viewer.mech","Mech");case"files":return h("viewer.files","Files");case"diff":return h("viewer.diff","Diff");case"review":return h("viewer.review","Review");case"browser":return h("bots.tab.browser","Browser");case"terminal":return h("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function On(e){return e==="board"||e==="schematic"||e==="gerbers"}function za(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function Vn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let a=document.createElement("span");a.className="bp-vh-sep",a.textContent="·",a.hidden=!0;let r=document.createElement("span");r.className="bp-vh-file",r.hidden=!0,i.append(s,a,r);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let l=document.createElement("div");l.className="bp-solid-bar",l.setAttribute("data-testid","solid-presets-bar"),l.hidden=!0;let p=document.createElement("div");p.className="bp-v-banner",p.hidden=!0;let c=document.createElement("div");c.className="bp-v-stage-wrap";let u=document.createElement("div");u.className="bp-v-stage";let d=document.createElement("div");d.className="bp-v-overlay",d.hidden=!0;let m=document.createElement("div");m.className="bp-v-layers",m.hidden=!0;let f=document.createElement("div");f.className="bp-v-info",f.hidden=!0,c.append(u,d,m,f);let b=document.createElement("div");b.className="bp-history-bar",b.setAttribute("data-testid","viewer-history-bar"),b.hidden=!0,e.replaceChildren(n,l,p,c,b);let g="",y="",w=0,x=!1,A=new Set,N=[],S=0,M=new Map,B=new Map,R={},U=[],D="",re="",me=!1,oe=!1,Ee=0,Ae=!1,Me=0,he="",be=0,I=null,le=null,ie=null,Z=null,ce=null,E=new Fn,k=0,j=!1,T="",q="",ne="",H="";document.addEventListener("click",(F)=>{if(!j)return;if(F.target instanceof Node&&b.contains(F.target))return;j=!1,ue()}),document.addEventListener("keydown",(F)=>{if(j&&F.key==="Escape")j=!1,ue()});function K(){if(k)window.clearInterval(k),k=0;E.playing=!1}function je(){let F=y==="3d"||y==="mech";if(l.hidden=!F,!F)return;if(l.childElementCount>0)return;for(let _ of xs){let O=document.createElement("button");O.type="button",O.className="bp-v-btn",O.textContent=_.label,O.setAttribute("data-testid",`solid-view-${_.id}`),O.addEventListener("click",()=>{ie?.setView(_.id)}),l.append(O)}let W=document.createElement("button");W.type="button",W.className="bp-v-btn",W.textContent="Snap view",W.setAttribute("data-testid","solid-snap"),W.addEventListener("click",()=>{if(!ie)return;ie.snapPng().then((_)=>{if(!_)return;let O=URL.createObjectURL(_),G=document.createElement("a");G.href=O;let Q=(De()||y||"view").replace(/[^a-zA-Z0-9._-]/g,"_");G.download=`${Q}-snap.png`,G.click(),setTimeout(()=>URL.revokeObjectURL(O),1000)})}),l.append(W)}async function Le(){if(!g||y!=="board"&&y!=="schematic")return;ue();let F=E.compareRequest();if(!F){T="",q="",ne="",H="",await Ge(!1);return}let W=`${y}|${F.commit}|${F.bits}|${re}`;if(W===H&&A.size>0){ke(E.highlightEdits?`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)}`,!1);return}let _=++w;A.clear(),M.clear(),Ye(),x=!0,T="",q=F.commit,ne="",H=W;try{let O=re||(y==="schematic"?R.sch:R.pcb)||"";if(!O){let Ce=await t.hub.rpc("viewer.files",{thread:g});if(_!==w)return;R=Ce||{},ae(),O=(y==="schematic"?R.sch:R.pcb)||""}if(!O)throw Error(`Unable to resolve ${y} file path for compare`);let G=await t.hub.rpc("viewer.compare",{thread:g,kind:y,commit:F.commit,bits:F.bits,...re?{path:re}:{}});if(_!==w)return;let Q=typeof G?.root==="string"?G.root:"",X=y==="schematic"?"1":"0";T=Q?`${X}|${Q}|diff +`:`${X}|`,q=F.commit,ne=O.startsWith("/")||/^[A-Za-z]:[\\/]/.test(O)||!Q?O:`${Q.replace(/\/+$/,"")}/${O.replace(/^\/+/,"")}`,x=!1;let ge=N;Ye();for(let Ce of ge)if(Ce.kind==="bin")$e(Ce.buf);else We(Ce.key,Ce.none,Ce.retryable,Ce.big);ke(E.highlightEdits?`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${E.activeRef()?.label||F.commit.slice(0,7)}`,!1)}catch(O){if(_!==w)return;x=!1,T="",q="",ne="",H="",Ye(),ke(O instanceof Error?O.message:String(O),!0)}}function ue(){let F=y==="board"||y==="schematic";if(b.hidden=!F,!F)return;let W=document.createElement("div");W.className="bp-history-group";let _=document.createElement("button");_.type="button",_.className="bp-v-btn",_.textContent="<",_.title="Older snapshot",_.disabled=E.refs.length===0||E.index>=E.refs.length-1,_.setAttribute("data-testid","history-prev"),_.addEventListener("click",()=>{if(K(),E.step(1))Le()});let O=document.createElement("button");O.type="button",O.className="bp-v-btn"+(E.playing?" is-on":""),O.textContent=E.playing?"⏸":"▶",O.title=E.playing?"Pause history":"Play history",O.disabled=E.refs.length===0,O.setAttribute("data-testid","history-play"),O.addEventListener("click",()=>{if(E.playing){K(),ue();return}if(E.refs.length===0)return;if(E.playing=!0,E.isLive())E.index=E.refs.length-1,Le();else ue();k=window.setInterval(()=>{if(!E.playing||y!=="board"&&y!=="schematic"){K(),ue();return}if(E.step(-1))Le();else K(),ue()},1400)});let G=document.createElement("button");G.type="button",G.className="bp-v-btn",G.textContent=">",G.title="Newer snapshot",G.disabled=E.isLive(),G.setAttribute("data-testid","history-next"),G.addEventListener("click",()=>{if(K(),E.step(-1))Le()});let Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn"+(E.isLive()?" is-on":""),Q.textContent="Live",Q.setAttribute("data-testid","history-live"),Q.addEventListener("click",()=>{if(K(),E.goLive())ke("",!1),Le()});let X=document.createElement("span");X.className="bp-history-label",X.setAttribute("data-testid","history-label");let ge=E.activeRef();X.textContent=ge?ge.label||ge.commit.slice(0,7):E.refs.length>0?`Live (${E.refs.length} saved)`:"Live",W.append(_,O,G,Q,X);let Ce=document.createElement("div");Ce.className="bp-history-group";let Ne=document.createElement("button");Ne.type="button",Ne.className="bp-v-btn"+(E.highlightEdits?" is-on":""),Ne.textContent="Highlight edits",Ne.disabled=E.refs.length===0,Ne.setAttribute("data-testid","history-highlight"),Ne.addEventListener("click",()=>{K(),E.toggleHighlight(),Le()});let Re=document.createElement("div");Re.className="bp-history-menu-wrap";let we=document.createElement("button");if(we.type="button",we.className="bp-v-btn"+(j||!E.isLive()?" is-on":""),we.disabled=E.refs.length===0,we.setAttribute("data-testid","history-compare"),we.setAttribute("aria-haspopup","menu"),we.setAttribute("aria-expanded",String(j)),we.textContent=ge?`Compare: ${ge.label||ge.commit.slice(0,7)} ▾`:"Compare ▾",we.addEventListener("click",(Te)=>{Te.stopPropagation(),j=!j,ue()}),Re.append(we),j&&E.refs.length>0){let Te=document.createElement("div");Te.className="bp-history-menu",Te.setAttribute("role","menu"),Te.setAttribute("data-testid","history-compare-menu");let qe=(Ie,vt,Ft)=>{let Ke=document.createElement("button");Ke.type="button",Ke.className="bp-history-menu-item"+(Ft?" is-active":""),Ke.setAttribute("role","menuitem"),Ke.setAttribute("data-commit",vt),Ke.textContent=Ie,Ke.addEventListener("click",()=>{if(j=!1,K(),E.selectCommit(vt)){if(E.isLive())ke("",!1);Le()}else ue()}),Te.append(Ke)};qe("Live (working tree)","",E.isLive());for(let Ie of E.refs)qe(Ie.label||Ie.commit.slice(0,7),Ie.commit,ge?.commit===Ie.commit);Re.append(Te)}Ce.append(Ne,Re),b.replaceChildren(W,Ce)}async function Pe(F){if(!F)return;try{let W=await t.hub.rpc("viewer.refs",{thread:F});if(F!==g)return;E.setRefs(Array.isArray(W?.refs)?W.refs:[]),ue()}catch{if(F!==g)return;E.setRefs([]),ue()}}function Y(){return document.documentElement.classList.contains("light")}let ye=new MutationObserver(()=>{let F=Y();le?.setTheme(F),ie?.setTheme(F),ce?.setTheme(F)});ye.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function te(F,W="",_=!1,O=""){if(F==="none"){d.hidden=!0,d.replaceChildren();return}d.hidden=!1,d.className=`bp-v-overlay is-${F}`;let G=document.createElement("div");G.className="bp-v-state-card";let Q=document.createElement("div");if(Q.className="bp-v-state-msg",Q.textContent=W,G.append(Q),_){let X=document.createElement("button");X.type="button",X.className="bp-v-btn is-primary",X.textContent=h("tools.retry","Retry"),X.addEventListener("click",()=>void Ge(!0)),G.append(X)}if(O){let X=document.createElement("div");X.className="bp-v-state-msg",X.textContent=h("gpui.c.solid.big.next","Loading it may take a while and a lot of memory.");let ge=document.createElement("button");ge.type="button",ge.className="bp-v-btn is-primary",ge.textContent=h("gpui.c.solid.load.big","Load it anyway"),ge.addEventListener("click",()=>{te("loading",h("gpui.c.solid.loading.big","Loading it anyway…")),t.hub.rpc("kicad.big",{key:O}).catch(()=>te("error",W,!1,O))}),G.append(X,ge)}d.replaceChildren(G)}function ke(F,W){p.textContent=F,p.hidden=!F,p.classList.toggle("is-warn",W)}function De(){if(re)return It(re);if(y==="board"||y==="3d")return It(R.pcb);if(y==="schematic")return It(R.sch);if(y==="mech")return It(D);return""}function ae(){s.textContent=Ms(y);let F=De();if(a.hidden=!F,r.hidden=!F,r.textContent=F,o.replaceChildren(),y==="mech"&&U.length>1){let _=document.createElement("select");_.className="bp-v-select",_.setAttribute("aria-label",h("viewer.mech","Mech"));for(let O of U){let G=document.createElement("option");G.value=O,G.textContent=It(O),G.selected=O===D,_.append(G)}_.addEventListener("change",()=>{D=_.value,ae(),Ge(!1)}),o.append(_)}if(On(y)){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(Ae?" is-on":""),_.textContent=I?.layerHead||"Layers",_.setAttribute("data-testid","viewer-layers-btn"),_.addEventListener("click",()=>{if(Ae=!Ae,m.hidden=!Ae,_.classList.toggle("is-on",Ae),Ae)_e("","")}),o.append(_)}if(y==="board"||y==="schematic"||y==="3d"||y==="mech"||y==="gerbers"){let _=document.createElement("button");_.type="button",_.className="bp-v-btn",_.textContent="Fit",_.setAttribute("data-testid","viewer-fit-btn"),_.addEventListener("click",()=>{le?.fit(),ie?.fit()}),o.append(_)}if((y==="board"||y==="schematic")&&t.hub.hasFeature("follow")){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(me&&!oe?" is-on":""),_.textContent=me?oe?h("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",_.setAttribute("data-testid","viewer-follow-btn"),_.addEventListener("click",()=>void nt()),o.append(_)}let W=document.createElement("button");W.type="button",W.className="bp-v-btn bp-v-close",W.textContent="✕",W.title=h("common.close","Close"),W.setAttribute("aria-label",h("common.close","Close")),W.setAttribute("data-testid","viewer-close-btn"),W.addEventListener("click",()=>t.closeViewer()),o.append(W)}function fe(){if(!I){m.replaceChildren();return}let F=document.createDocumentFragment(),W=document.createElement("div");W.className="bp-v-layers-head";let _=document.createElement("span");if(_.textContent=I.layerHead||"Layers",W.append(_),I.layerReset){let X=document.createElement("button");X.type="button",X.className="bp-v-btn",X.textContent="Reset",X.addEventListener("click",()=>void _e("reset","")),W.append(X)}if(F.append(W),I.layerModes){let X=document.createElement("div");X.className="bp-v-layers-modes",["All","Dim","Only"].forEach((ge,Ce)=>{let Ne=document.createElement("button");Ne.type="button",Ne.className="bp-v-btn"+(I?.layerMode===Ce?" is-on":""),Ne.textContent=ge,Ne.addEventListener("click",()=>void _e("mode",String(Ce))),X.append(Ne)}),F.append(X)}let O=le?.presentColors()??new Map,G=(I.layerList||[]).concat(I.layerMarks||[]),Q=document.createElement("div");Q.className="bp-v-layers-list";for(let X of G){let ge=O.get(X.layer);if(ge===void 0)continue;let Ce=document.createElement("div");Ce.className="bp-v-layer-row"+(X.active?" is-focus":"");let Ne=document.createElement("input");Ne.type="checkbox",Ne.checked=X.on!==!1,Ne.addEventListener("change",()=>void _e("toggle",String(X.layer)));let Re=document.createElement("span");Re.className="bp-v-layer-swatch";let we=ge>>>16&255,Te=ge>>>8&255,qe=ge&255;Re.style.background=X.on!==!1?`rgb(${we},${Te},${qe})`:`rgba(${we},${Te},${qe},0.2)`;let Ie=document.createElement("button");Ie.type="button",Ie.className="bp-v-layer-name",Ie.textContent=X.name,Ie.addEventListener("click",()=>void _e("pick",String(X.layer))),Ce.append(Ne,Re,Ie),Q.append(Ce)}F.append(Q),m.replaceChildren(F)}async function _e(F,W){if(!On(y))return;let _=w;try{let O=await t.hub.rpc("viewer.layers",{kind:y,present:be,off:Me,focus:he,...F?{action:F,value:W}:{}});if(_!==w||!O)return;Me=Number(O.own)||0,he=typeof O.focus==="string"?O.focus:"",I=O;let G={off:Number(O.off)||0,dim:Number(O.dim)||0,lift:typeof O.lift==="number"?O.lift:255};if(le?.setLayers(G),ae(),Ae)fe()}catch{}}async function Ue(){if(!me||oe||!g||!t.hub.hasFeature("follow"))return;oe=!0,ae();try{await t.hub.rpc("viewer.follow",{thread:g,action:"pause"})}catch{}}async function nt(){if(!g||!t.hub.hasFeature("follow"))return;let F=!me?"on":oe?"resume":"off";try{let W=await t.hub.rpc("viewer.follow",{thread:g,action:F});if(me=!!W.on,oe=!!W.paused,ae(),W.on&&!W.paused&&W.focus&&Array.isArray(W.focus.box)&&W.focus.box.length===4&&(W.seq||0)>Ee)Ee=W.seq||Ee,le?.zoomToBoxMm([W.focus.box[0],W.focus.box[1],W.focus.box[2],W.focus.box[3]])}catch{}}function de(){f.hidden=!0,f.replaceChildren(),le?.setHighlights([])}function gt(F){let W=F.split(";").filter(Boolean),_=W.shift()||F,O=[],G="",Q="";for(let Re of W){if(Re.startsWith("g="))continue;let we=Re.indexOf("=");if(we>0){let Te=Re.slice(0,we),qe=Re.slice(we+1);if((Te==="ref"||Te==="symbol")&&!G)G=qe;if(Te==="net"&&!Q)Q=qe;O.push([Te,qe])}else O.push([Re,""])}let X=document.createElement("div");X.className="bp-v-info-head";let ge=document.createElement("span");ge.className="bp-v-info-title",ge.textContent=_;let Ce=document.createElement("button");Ce.type="button",Ce.className="bp-v-info-x",Ce.textContent="×",Ce.setAttribute("aria-label","Clear selection"),Ce.addEventListener("click",de),X.append(ge,Ce);let Ne=document.createElement("div");Ne.className="bp-v-info-rows";for(let[Re,we]of O){let Te=document.createElement("span");Te.className="bp-v-info-chip",Te.textContent=we?`${Re}: ${we}`:Re,Ne.append(Te)}return f.replaceChildren(X,...O.length>0?[Ne]:[]),f.hidden=!1,{ref:G||void 0,net:Q||void 0}}async function Je(F){if(!F){de();return}let W=Array.from(A)[0]||"";if(!W)return;let _=w;try{let O=await t.hub.rpc("viewer.info",{key:W,at:F.at,idx:F.idx});if(_!==w)return;let G=typeof O.info==="string"?O.info:"";if(!G){de();return}let{ref:Q,net:X}=gt(G),ge=[];if(Q)ge.push(["ref",Q]);if(X)ge.push(["net",X]);let Ce=[[F.at,F.idx]];for(let[Ne,Re]of ge){let we=await t.hub.rpc("viewer.probe",{key:W,name:Ne,value:Re});if(_!==w)return;if(Array.isArray(we.matches))for(let Te of we.matches)Ce.push(Te)}le?.setHighlights(Ce)}catch{de()}}function ft(){Z?.destroy(),Z=null,ce?.destroy(),ce=null,le?.destroy(),le=null,ie?.destroy(),ie=null,u.replaceChildren(),Ae=!1,m.hidden=!0,f.hidden=!0,f.replaceChildren(),ke("",!1),te("none")}function Ye(){N=[],S=0}async function Ge(F){if(!g||!y)return;let W=++w;if(A.clear(),x=!1,Ye(),ft(),ae(),je(),ue(),(y==="board"||y==="schematic")&&g)Pe(g);if(za(y)){if(t.hub.rpc("viewer.watch",{thread:g,kind:""}).catch(()=>{}),y==="files")Z=ys(u,t,g,(G,Q)=>{if(y=G,re=Q,G==="mech")D=Q;Ge(!1)});else if(y==="diff")Z=ws(u,t,g);else if(y==="review")Z=Es(u,t,g);else if(y==="browser")Z=gs(u,t,g);else if(y==="terminal")te("loading","Loading terminal…"),import("/assets/terminal.js").then((Q)=>{if(W!==w)return;if(te("none"),Q?.mountTerminalPane)ce=Q.mountTerminalPane(u,t,g,Y());else te("error","Terminal chunk missing",!0)},(Q)=>{if(W!==w)return;te("error",Q instanceof Error?Q.message:String(Q),!0)});return}if(te("loading","Loading…"),!R.root)try{let G=await t.hub.rpc("viewer.files",{thread:g});if(W!==w)return;R=G||{},ae()}catch{}if(y==="gerbers"&&R.hasGerbers===!1){te("empty","No Gerbers in this project",!1);return}let _=Y();if(y==="3d"||y==="mech")ie=new Gn(u,{onStatus:(G,Q)=>{if(Q)te("none"),ke(G,!1);else if(G)te("loading",G);else te("none"),ke("",!1)},onUserMove:()=>void Ue()}),ie.setTheme(_);else if(y==="board"||y==="schematic"||y==="gerbers")le=new Dn(u,{onPick:(G)=>void Je(G),onUserMove:()=>void Ue()}),le.setTheme(_);else{te("empty",`${Ms(y)} is not available in this viewer`,!1);return}let O={thread:g};if(F)O.force=!0;if(y==="mech"){if(U.length===0)try{let G=await t.hub.rpc("mech.list",{thread:g});if(W!==w)return;if(U=Array.isArray(G.parts)?G.parts:[],!D)D=G.primary||U[0]||"";ae()}catch(G){if(W!==w)return;te("error",G instanceof Error?G.message:String(G),!0);return}if(!D){te("empty",h("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}O.kind="3d",O.path=D}else{if(O.kind=y,re&&(y==="board"||y==="schematic"))O.path=re;if(y==="3d"&&!F&&ie){let G=ie.keptToken();if(G)O.kept=G}if((y==="board"||y==="schematic"||y==="gerbers")&&!F&&t.hub.hasFeature("keptChunks"))O.keptChunks=Array.from(B.keys())}x=!0,T="",q="",ne="",H="";try{let G=await t.hub.rpc("viewer.watch",O);if(W!==w)return;A=new Set(Array.isArray(G.keys)?G.keys:[]),x=!1;let Q=N;Ye();for(let X of Q)if(X.kind==="bin")$e(X.buf);else We(X.key,X.none,X.retryable,X.big)}catch(G){if(W!==w)return;x=!1,A.clear(),Ye();let Q=G instanceof Error?G.message:String(G),X=/no gerbers|not in this project|another machine/i.test(Q);te(X?"empty":"error",Q,!X)}}function We(F,W,_,O=!1){if(x){if(N.length{if(F.t==="plot"&&typeof F.none==="string"&&typeof F.key==="string")We(F.key,F.none,F.retryable===!0)}),Oe=Ot(()=>{if(y)ae()}),Ht=(F)=>{if(F.key==="Escape"&&y&&!f.hidden)de()};return window.addEventListener("keydown",Ht),{open(F,W){if(W!==g){if(g=W,R={},U=[],D="",M.clear(),me=!1,oe=!1,Ee=0,Me=0,he="",be=0,I=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:W}).then((_)=>{if(W!==g)return;if(me=!!_.on,oe=!!_.paused,Ee=Number(_.seq)||0,y)ae()}).catch(()=>{})}if(F!==y)K(),E.goLive(),Me=0,he="",be=0,I=null;y=F,re="",Ge(!1)},reconcileHas(F){if(y&&!_a(y,F))t.closeViewer()},close(){if(w++,x=!1,K(),j=!1,T="",q="",ne="",H="",E.goLive(),l.hidden=!0,b.hidden=!0,Ye(),g)t.hub.rpc("viewer.watch",{thread:g,kind:""}).catch(()=>{});y="",A.clear(),ft()}}}var Ts="http://www.w3.org/2000/svg";function Rt(e){let t=document.createElementNS(Ts,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Ts,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function qa(e){if(!e)return"bp-dot-idle";let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Bs(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}var jt="dark",en=(()=>{try{return Yi(localStorage.getItem("bp.theme.pref"))}catch{return"auto"}})(),Un=null,bt=(()=>{try{return Xi(localStorage.getItem("bp.locale"))}catch{return"auto"}})();function Ds(){let e=Pt(en,jt);document.documentElement.classList.toggle("light",e==="light");try{localStorage.setItem("bp.theme",e)}catch{}}function Is(e){if(!e)return;jt=e==="light"?"light":"dark",Ds()}function Rs(){if(bt!=="auto")ct(bt);else if(Un)ct(Un);else if(typeof navigator<"u"&&navigator.language){if(!ct(navigator.language))ct("en")}}function Ka(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function js(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")jt="light";if(Pt(en,jt)==="light")document.documentElement.classList.add("light");if(bt!=="auto")ct(bt)}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let a=document.createElement("span");a.className="bp-brand-name bp-hide-phone",a.textContent="Backplane";let r=document.createElement("span");r.className="bp-crumb-sep bp-hide-phone",r.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let l=document.createElement("span");l.className="bp-crumb-sep bp-hide-phone",l.textContent="/";let p=document.createElement("span");p.className="bp-crumb-thread",p.setAttribute("data-testid","thread-title");let c=document.createElement("span");c.className="bp-plan-top-badge bp-hidden",c.setAttribute("data-testid","plan-top-badge"),i.append(s,a,r,o,l,p,c);let u=document.createElement("div");u.className="bp-top-state bp-hide-phone bp-hidden";let d=document.createElement("span");d.className="bp-top-state-lbl",d.textContent="STATE";let m=document.createElement("span");m.className="bp-dot bp-dot-idle";let f=document.createElement("span");f.className="bp-top-state-word",u.append(d,m,f);let b=document.createElement("div");b.className="bp-top-acts bp-hide-phone bp-hidden";let g=document.createElement("button");g.type="button",g.className="bp-btn-ghost bp-top-act";let y=document.createElement("span");y.textContent=h("menu.pin","Pin"),g.append(Rt(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),y);let w=document.createElement("button");w.type="button",w.className="bp-btn-ghost bp-top-act";let x=document.createElement("span");x.textContent=h("menu.settle","Settle"),w.append(Rt(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),x);let A=document.createElement("div");A.className="bp-menu-wrap";let N=document.createElement("button");N.type="button",N.className="bp-btn-ghost bp-top-act",N.textContent="▾",N.title="Thread menu",N.setAttribute("aria-label","Thread menu"),N.setAttribute("data-testid","thread-menu-btn");let S=document.createElement("div");S.className="bp-popover bp-hidden",S.setAttribute("data-testid","thread-menu"),A.append(N,S),b.append(g,w,A);let M=document.createElement("div");M.className="bp-top-right";let B=document.createElement("button");B.type="button",B.className="bp-btn-ghost bp-top-act bp-hide-tablet",B.setAttribute("data-testid","improvements-btn");let R=document.createElement("span");R.textContent=h("gpui.improvements","Improvements"),B.append(Rt(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),R);let U=document.createElement("button");U.type="button",U.className="bp-cmd-box bp-hide-tablet",U.textContent="> Jump or run a command";let D=document.createElement("button");D.type="button",D.className="icon bp-top-icon",D.title="Search",D.setAttribute("aria-label","Search"),D.appendChild(Rt(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let re=document.createElement("button");re.type="button",re.className="icon bp-top-icon",re.title=h("palette.settings","Settings"),re.setAttribute("aria-label",h("palette.settings","Settings")),re.setAttribute("data-testid","settings-btn"),re.appendChild(Rt(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),M.append(B,U,D,re),t.append(n,i,u,b,M);let me=document.createElement("div");me.className="bp-body";let oe=document.createElement("aside");oe.className="bp-sidebar",oe.setAttribute("data-testid","sidebar");let Ee=document.createElement("main");Ee.className="bp-center";let Ae=document.createElement("div");Ae.className="bp-right-area bp-hidden",Ae.setAttribute("data-testid","right-area");let Me=document.createElement("div");Me.className="bp-right-top";let he=document.createElement("section");he.className="bp-viewer-pane bp-hidden",he.setAttribute("data-testid","viewer-pane"),Me.appendChild(he),Ae.appendChild(Me);let be=document.createElement("nav");be.className="bp-rail",be.setAttribute("aria-label","Viewer rail"),be.setAttribute("data-testid","viewer-rail"),me.append(oe,Ee,Ae,be),e.append(t,me);let I=new Rn,le=null,ie=new Set,Z=0,ce=null,E=[],k=[],j=[],T=[],q=[],ne=[],H="",K=0,je=0,Le=null,ue=null,Pe="",Y=null,ye=20,te={},ke=new Map;function De(v,C){ke.delete(v),ke.set(v,C);while(ke.size>ye){let L=ke.keys().next().value;if(L!==void 0)ke.delete(L);else break}}let ae=new Tn(oe,{onSelectThread:(v)=>{if(v===H&&Le!==null){oe.classList.remove("bp-sidebar-open");return}Ie(v)},onNewThread:(v)=>{$t(v)},onSelectBot:(v)=>{Ie(v.thread)},onQuickOpenViewer:(v,C)=>{let L=k.find((V)=>V.project===v&&!V.archived&&!V.swarm);(async()=>{if(L)await Ie(L.id);else await $t(v);if(H)Pe=C,$e.setActive(C),Y?.open(C,H)})()},onThreadAct:(v,C)=>{Qe(v,C)},onSnoozeRow:(v)=>{I.rpc("sidebar.act",{action:"row-snooze",value:v}).then(()=>we()).catch(()=>{})},onToggleSection:(v)=>{if(ie.has(v))ie.delete(v);else ie.add(v);we()},onToggleProjectFold:(v)=>{I.rpc("sidebar.act",{action:"project-fold",value:v}).then(()=>we()).catch(()=>{})},onCollapseSidebar:()=>{oe.classList.remove("bp-sidebar-open"),oe.classList.add("bp-sidebar-collapsed")},onNeedAct:async(v)=>{let C=Yt(v,!1);if(!C)return;if(C.kind==="thread"){Ie(C.id);return}if(C.kind!=="call")return;let L=Ji(await I.rpc(C.method,C.params));if(L?.kind==="thread")Ie(L.id);we()},hasRoomView:!1,onAddProject:()=>We.open({mode:"folder"})}),fe=new dn(Ee,{onLoadOlder:()=>{Ke()},onGoToEntry:(v)=>{Ft(v)},onOpenAccounts:()=>{F()},onAnswerAsk:(v,C)=>{I.rpc("ask.answer",{ask:v,answer:C}).catch((L)=>{de.showError(L instanceof Error?L.message:"Could not send answer")})},onToggleReview:(v)=>{if(!H)return;let C=K;I.rpc("thread.review",{thread:H,on:v}).then((L)=>{if(C===K)fe.setReview(L.review??null)}).catch(()=>{})},onUnansweredAction:(v,C)=>{if(!H)return;if(v==="again"||v==="thread-again")I.rpc("thread.again",{thread:H,value:C}).catch(()=>{});else I.rpc("thread.act",{thread:H,action:v,value:C}).catch(()=>{})},onReplyEntry:(v)=>{if(!I.hasFeature("reply")){let C=(v.text||"").split(` `)[0]?.slice(0,100)??"";if(C)de.prependDraft(`> ${C} -`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;yt({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,C)=>{try{let L={entry:v,path:C};if(I.hasFeature("blobs"))L.metaOnly=!0;let P=await I.rpc("message.image",L);if(P.blob&&P.blob.startsWith("/blob/"))return{url:P.blob};if(P.mime&&P.data)return{mime:P.mime,data:P.data}}catch{}return null}});function _e(v){if(!v)return null;if(v.planMode)return v.planMode;if(v.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function Ue(v,C){if(!H)return;let L=K,P=H;I.rpc(v,C).then((O)=>{if(L!==K||H!==P)return;if(O.thread){let Q=k.findIndex((fe)=>fe.id===O.thread.id);if(Q>=0)k[Q]=O.thread;else k.unshift(O.thread);ae.setData(E,k,j,T),ge.updateThreadMeta(O.thread),G(),de.setState(!0,O.thread.state==="working")}}).catch((O)=>{if(L===K&&H===P)de.showError(O instanceof Error?O.message:"Could not change Plan mode")})}let nt,de=new un(we,{onSend:(v,C)=>{_n(v,C)},onRunCommand:(v)=>{zn(v)},onInterrupt:()=>{if(H)I.rpc("turn.interrupt",{thread:H}).catch(()=>{})},onQueryMentions:async(v,C)=>{try{return(await I.rpc("mentions.list",{q:v,kind:C,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{nt.toggle()},onCyclePlanMode:()=>{let v=k.find((L)=>L.id===H)??null,C=_e(v);if(!C||!H)return;if(C.interaction!=="plan")Ue("thread.planonce",{thread:H,on:!0});else if(C.once)Ue("thread.pick",{thread:H,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:H,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!H)return;if(v==="once")Ue("thread.planonce",{thread:H,on:!0});else if(v==="always")Ue("thread.pick",{thread:H,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:H,action:"interaction",value:"default"})}});nt=new Bn(I,{getThreadId:()=>H,getDraft:()=>de.getDraft(),getCaret:()=>de.getCaret(),setDraft:(v)=>de.setDraft(v),setRecording:(v)=>de.setVoiceRecording(v),setLevel:(v)=>de.setVoiceLevel(v),showError:(v)=>de.showError(v)});function gt(){let v=Pe!=="",C=Je.isOpen();Ae.classList.toggle("bp-hidden",!v&&!C),Ae.classList.toggle("bp-has-viewer",v),Ae.classList.toggle("bp-has-mgmt",C)}let Je=new wn(Me,Ae,{hub:I,getThreadId:()=>H,getThreadGen:()=>K,onSendText:(v)=>{_n(v)},onOpenChange:()=>gt()});function ft(v){let C=window.prompt("Rename thread",v.title||"");if(!C||!C.trim())return;I.rpc("thread.act",{thread:v.id,action:"rename",title:C.trim()}).then((L)=>{if(L.thread)k=k.map((P)=>P.id===L.thread.id?L.thread:P),G(),ye()}).catch((L)=>{de.showError(L instanceof Error?L.message:"Could not rename thread")})}function Ye(v){switch(v.type){case"thread":Ie(v.id);break;case"rail":if(!H&&v.id!=="terminal")break;if(Pe===v.id)Z();else ee(v.id);break;case"thread-act":if(H)Qe(H,v.action);break;case"new-thread":$t(v.projectId);break;case"rename":{let C=k.find((L)=>L.id===H);if(C)ft(C);break}case"prev-thread":case"next-thread":{let C=k.filter((Q)=>!Q.archived&&!Q.swarm);if(C.length<2)break;let L=C.findIndex((Q)=>Q.id===H),P=v.type==="next-thread"?1:-1,O=C[(L<0?0:L+P+C.length)%C.length];if(O)Ie(O.id);break}case"command":if(v.runDirectly)zn(v.word);else de.setDraft(`${v.word} `),de.focus();break;case"improvements":U();break;case"settings":Oe.open();break;case"sidebar":oe.classList.toggle("bp-sidebar-open"),oe.classList.toggle("bp-sidebar-collapsed");break}}let Ge=new En(e,{getState:()=>({selectedThreadId:H,threads:k,projects:E,bots:j,railItems:q,commands:te}),onSearch:async(v)=>{if(!I.hasFeature("search"))return{threads:[],projects:[],messages:[]};return I.rpc("search",{q:v,limit:20})},onExecute:Ye}),We=new on(e,{hub:I,onProjectAdded:(v)=>{if(ye(),v.id)$t(v.id)},onCloneDone:(v)=>{if(ye(),v.thread)Ie(v.thread)}}),$e=new xn(be,(v)=>{if(v==="commands"){Ge.open();return}if(!H)return;if(Pe===v)Z();else ee(v)}),it=null,Dt=null,Oe=new Ln(e,{onLoadDevices:async()=>(await I.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,C)=>{await I.rpc("devices.page.act",{action:v,value:C})},onGetHome:()=>it,onMoveHomeHere:async()=>{await I.rpc("home.move",{to:"back"})},onGetNoProvider:()=>Dt,onGetThemePref:()=>en,onSetThemePref:(v)=>{en=v;try{if(v==="auto")localStorage.removeItem("bp.theme.pref");else localStorage.setItem("bp.theme.pref",v)}catch{}Ds()},onGetHubTheme:()=>jt,onGetLocalePref:()=>bt,onSetLocalePref:(v)=>{bt=v;try{if(v==="auto")localStorage.removeItem("bp.locale");else localStorage.setItem("bp.locale",v)}catch{}Rs()},onLogout:()=>oi(()=>{I.disconnect(),window.location.replace("/")})});function Ht(v){if(Dt=v,ge.setNoProvider(v),Oe.isOpen())Oe.refresh()}function F(){Oe.openToAccounts()}function W(v,C){let L=v instanceof Error?v.message:C,P=v instanceof Bt?v:null,O=P?.code,Q=P?.machine,fe=O==="no_provider_remote"&&Q?m("provider.notice.senderr.remote","No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.").replaceAll("{machine}",Q):L;de.showError(fe,_i(L,O)?{label:m("provider.notice.button","Open Settings → Accounts"),onClick:F}:void 0)}g.addEventListener("click",()=>{let v=k.find((C)=>C.id===H);if(v)Qe(v.id,v.pinned?"unpin":"pin")}),w.addEventListener("click",()=>{let v=k.find((C)=>C.id===H);if(v)Qe(v.id,v.settled?"unsettle":"settle")});let _=new Nn(e,(v,C)=>C?I.rpc("thread.context.mcp",{thread:v,...C}):I.rpc("thread.context",{thread:v}));N.addEventListener("click",(v)=>{v.stopPropagation();let C=k.find((O)=>O.id===H);if(!C)return;if(!S.classList.contains("bp-hidden")){S.classList.add("bp-hidden");return}let L=[{label:"Rename…",run:()=>ft(C)},{label:C.pinned?m("menu.unpin","Unpin"):m("menu.pin","Pin"),run:()=>{Qe(C.id,C.pinned?"unpin":"pin")}},{label:C.settled?m("phone.unsettle","Unsettle"):m("menu.settle","Settle"),run:()=>{Qe(C.id,C.settled?"unsettle":"settle")}},{label:C.archived?"Unarchive":"Archive",run:()=>{Qe(C.id,C.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Qe(C.id,"delete")}}];if(I.hasFeature("threadContext"))L.unshift({label:m("thread.context.title","Context & Prompt"),run:()=>_.open(C.id)});let P=document.createDocumentFragment();for(let O of L){let Q=document.createElement("button");Q.type="button",Q.className="bp-popover-item"+(O.danger?" danger":""),Q.textContent=O.label,Q.addEventListener("click",()=>{S.classList.add("bp-hidden"),O.run()}),P.appendChild(Q)}S.replaceChildren(P),S.classList.remove("bp-hidden")}),document.addEventListener("click",()=>S.classList.add("bp-hidden"));async function U(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let C=document.createElement("div");C.className="bp-modal";let L=document.createElement("div");L.className="bp-modal-head";let P=document.createElement("h2");P.textContent=m("gpui.improvements","Improvements");let O=document.createElement("button");O.type="button",O.className="icon",O.textContent="×",O.addEventListener("click",()=>v.remove()),L.append(P,O);let Q=document.createElement("div");Q.className="bp-modal-body",Q.textContent="Loading…",C.append(L,Q),v.appendChild(C),v.addEventListener("click",(fe)=>{if(fe.target===v)v.remove()}),e.appendChild(v);try{let fe=await I.rpc("improvements.projects",{}),He=fe.projects??[];if(He.length===0){Q.textContent="No projects available for Improvements.";return}let et=document.createDocumentFragment();for(let Se of He){let se=document.createElement("div");se.className="bp-set-row";let Xe=document.createElement("div");Xe.className="bp-set-info",Xe.textContent=Se.title||Se.name||Se.id;let tt=document.createElement("button");tt.type="button",tt.className=Se.id===fe.project?"primary":"",tt.textContent=Se.id===fe.project?"Active":"Select",tt.addEventListener("click",()=>{I.rpc("improvements.project",{project:Se.id}).then(()=>v.remove()).catch(()=>{})}),se.append(Xe,tt),et.appendChild(se)}Q.replaceChildren(et)}catch(fe){Q.textContent=fe instanceof Error?fe.message:"Could not load Improvements."}}B.addEventListener("click",()=>{U()}),V.addEventListener("click",()=>Ge.open()),D.addEventListener("click",()=>Ge.open()),re.addEventListener("click",()=>{Oe.open()}),n.addEventListener("click",()=>{oe.classList.toggle("bp-sidebar-open"),oe.classList.toggle("bp-sidebar-collapsed")});function G(){let v=k.find((P)=>P.id===H)??null,C=v?E.find((P)=>P.id===v.project):void 0;o.textContent=C?.title??"",r.classList.toggle("bp-hidden",!C),l.classList.toggle("bp-hidden",!v),p.textContent=v?v.title||"Untitled thread":"";let L=_e(v);if(de.setPlanMode(L),!L||L.phase==="off")c.classList.add("bp-hidden"),c.classList.remove("is-exec"),c.textContent="";else c.classList.remove("bp-hidden"),c.classList.toggle("is-exec",L.phase==="executing"),c.title=m("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),c.textContent=L.phase==="armed"&&L.once?m("gpui.planmode.top.once","Plan (1 turn)"):L.phase==="armed"?m("gpui.mgmt.plan.tab","Plan"):L.phase==="planning"?m("gpui.planmode.top.planning","Planning"):L.phase==="pending"?m("gpui.planmode.top.pending","Review plan"):m("gpui.planmode.top.executing","Building plan");if(u.classList.toggle("bp-hidden",!v),b.classList.toggle("bp-hidden",!v),v){h.className=`bp-dot ${qa(v)}`,f.textContent=v.status||v.state||"idle",y.textContent=v.pinned?m("menu.unpin","Unpin"):m("menu.pin","Pin"),x.textContent=v.settled?m("phone.unsettle","Unsettle"):m("menu.settle","Settle");let P=v;de.setModelChip(v.chip||v.model||"default",v.provider,P.ctxPct??P.contextPct),de.setMemory(v.memory)}else de.setModelChip("default"),de.setMemory(null)}function Z(v=!0){if(je++,Pe="",$e.setActive(""),me.classList.add("bp-hidden"),Y?.close(),gt(),v&&H&&I.getState()==="connected")I.rpc("viewer.watch",{thread:H,kind:""}).catch(()=>{})}function ee(v){if(je++,Pe=v,$e.setActive(v),me.classList.remove("bp-hidden"),gt(),!Y&&typeof Vn==="function")Y=Vn(me,{hub:I,getThreadId:()=>H,closeViewer:()=>Z(!0)});if(Y)Y.open(v,H);else{let C=document.createElement("div");C.className="bp-viewer-placeholder";let L=document.createElement("div");L.className="bp-viewer-bar";let P=document.createElement("span");P.textContent=v.toUpperCase();let O=document.createElement("button");O.type="button",O.className="icon",O.textContent="×",O.addEventListener("click",()=>Z(!0)),L.append(P,O);let Q=document.createElement("div");Q.className="bp-dim bp-viewer-msg",Q.textContent=`Viewer pane (${v}).`,C.append(L,Q),me.replaceChildren(C)}}async function Ce(v,C){if(!v||!I.hasFeature("rail")){if(C===K)q=[],$e.setItems([]);return}let L=++je;try{let P=await I.rpc("viewer.rail",{thread:v,page:Pe});if(C!==K||L!==je)return;let O=Array.isArray(P.rail)?P.rail:Array.isArray(P.items)?P.items:[];if(q=O,$e.setItems(O),P.has){if(Y?.reconcileHas?.(P.has),Pe&&!Bs(P.has,Pe))Z(!0)}}catch{if(C===K&&L===je)q=[],$e.setItems([])}}function xe(v){for(let C of v)if(C.kind==="threads"){for(let L of C.rows)if(!L.off&&(L.nav||L.id)&&!(L.nav||"").startsWith("@room:"))return L.nav||L.id}else if(C.kind==="projects"){for(let L of C.rows)for(let P of L.threads??[])if(!P.off&&(P.nav||P.id)&&!(P.nav||"").startsWith("@room:"))return P.nav||P.id}return""}function Ne(v,C){for(let L of v)if(L.kind==="threads"){if(L.rows.some((P)=>(P.nav||P.id)===C))return!0}else if(L.kind==="projects"){for(let P of L.rows)if((P.threads??[]).some((O)=>(O.nav||O.id)===C))return!0}return!1}function Re(v){let C=[];for(let L of v){if(L.kind!=="projects")continue;for(let P of L.rows)C.push({id:P.id,title:P.title,css:P.css,color:P.color})}if(C.length>0)E=C}async function ye(){if(!I.hasFeature("sections"))return!1;let v=++X;try{let C=await I.rpc("sidebar.sections",{open:Array.from(ne)});if(v!==X)return!0;let L=Array.isArray(C.sections)?C.sections:[];return le=L,Re(L),ae.setData(E,k,j,T),ae.setSections(L,j,T),G(),!0}catch{return!1}}function Te(){if(!I.hasFeature("sections"))return;if(ce!==null)window.clearTimeout(ce);ce=window.setTimeout(()=>{ce=null,ye()},150)}async function qe(){if(Le=null,I.hasFeature("bots"))try{let C=await I.rpc("bots.list",{});j=C.bots??[],T=C.rooms??[]}catch{}if(I.hasFeature("shell")){let C=await I.rpc("shell.sync",{have:ie,settled:25}),L=new Set(C.removed??[]),P=new Set((C.projects??[]).map((O)=>O.id));if(L.size>0||P.size>0)E=[...E.filter((O)=>!L.has(O.id)&&!P.has(O.id)),...C.projects??[]],k=[...k.filter((O)=>!L.has(O.project)&&!P.has(O.project)),...C.threads??[]];else if(Array.isArray(C.threads)&&C.threads.length>0){let O=new Map(k.map((Q)=>[Q.id,Q]));for(let Q of C.threads)O.set(Q.id,Q);k=Array.from(O.values())}if(C.sections!==void 0){let O=Array.isArray(C.sections)?C.sections:Array.isArray(C.sections?.sections)?C.sections.sections:null;if(O)le=O,Re(O)}if(C.h)ie=C.h;ae.setData(E,k,j,T),ae.setSections(le,j,T)}else if(I.hasFeature("sections")){let[C,L]=await Promise.all([I.rpc("sidebar.sections",{open:Array.from(ne)}).catch(()=>null),I.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(k=L.threads??[],C&&Array.isArray(C.sections)){let P=C.sections;if(!P.some((Q)=>Q.kind==="projects"&&Q.rows.length>0)){let Q=P.find((fe)=>fe.kind==="projects"&&fe.fold&&fe.toggle&&(fe.count??0)>0);if(Q?.toggle&&!ne.has(Q.toggle)){ne.add(Q.toggle);let fe=await I.rpc("sidebar.sections",{open:Array.from(ne)}).catch(()=>null);if(fe&&Array.isArray(fe.sections))P=fe.sections}}le=P,Re(P),ae.setData(E,k,j,T),ae.setSections(P,j,T)}else le=null,E=(await I.rpc("projects.list",{limit:100})).projects??[],ae.setSections(null,j,T),ae.setData(E,k,j,T);await I.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{le=null;let[C,L]=await Promise.all([I.rpc("projects.list",{limit:100}),I.rpc("threads.list",{limit:200,archived:!1})]);E=C.projects??[],k=L.threads??[],ae.setSections(null,j,T),ae.setData(E,k,j,T),await I.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=H;if(!v){let C="";try{C=localStorage.getItem("bp.lastThread")||""}catch{}if(C&&(le&&Ne(le,C)||k.some((L)=>L.id===C)))v=C;else if(le)v=xe(le);if(!v)v=(k.find((P)=>!P.archived&&!P.swarm&&!P.settled)??k.find((P)=>!P.archived&&!P.swarm))?.id??""}if(v&&(le&&Ne(le,v)||k.some((C)=>C.id===v)))await Ie(v);else H="",q=[],$e.setItems([]),de.setState(!1,!1),G()}async function Ie(v){if(H&&H!==v){nt.cancel();let Se=ge.getEntries();if(Se.length>0){let se=ke.get(H);De(H,{entries:Se,ids:se?.ids??Se.map((Xe)=>Xe.id),olderCursor:ue,review:se?.review??null,unanswered:se?.unanswered??null,rail:se?.rail??q,hashes:se?.hashes??{}})}}let C=++K;je++,yt(null);let L=Le;if(Le=null,L!==null)I.rpc("unsubscribe",{sub:L}).catch(()=>{});H=v;let P=ke.get(v);ue=P?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}ae.setSelected(v),oe.classList.remove("bp-sidebar-open"),G();let O=k.find((Se)=>Se.id===v)??null;if(P)ge.setThread(O,P.entries,Boolean(P.olderCursor),P.review,P.unanswered),q=P.rail,$e.setItems(P.rail);else ge.setLoading(O),q=[],$e.setItems([]);if(de.setState(!0,O?.state==="working"),I.hasFeature("open")){let Se={};if(P){for(let[Be,Et]of Object.entries(P.hashes))Se[Be]=Et;for(let Be of P.entries)if(Be.h)Se[Be.id]=Be.h}let se;try{se=await I.rpc("thread.open",{thread:v,limit:40,have:Se})}catch(Be){if(C===K){let Et=Be instanceof Error&&Be.message?Be.message:"Could not load messages.";ge.setError(O,Et,()=>{Ie(v)})}return}if(C!==K){if(se.sub!==void 0&&se.sub!==null)I.rpc("unsubscribe",{sub:se.sub}).catch(()=>{});return}if(Le=se.sub??null,se.thread){O=se.thread;let Be=k.findIndex((Et)=>Et.id===se.thread.id);if(Be>=0)k[Be]=se.thread;else k.unshift(se.thread);G(),de.setState(!0,O.state==="working")}if("next"in se)ue=se.next??null;let Xe=new Map;if(P)for(let Be of P.entries)Xe.set(Be.id,Be);for(let Be of se.entries??[])Xe.set(Be.id,Be);let tt=se.ids??P?.ids??(se.entries??[]).map((Be)=>Be.id),Kn=tt.map((Be)=>Xe.get(Be)).filter((Be)=>Boolean(Be)),wt=P?.rail??[];if(se.rail!==void 0){if(Array.isArray(se.rail))wt=se.rail;else if(wt=Array.isArray(se.rail?.rail)?se.rail.rail:Array.isArray(se.rail?.items)?se.rail.items:[],se.rail?.has){if(Y?.reconcileHas?.(se.rail.has),Pe&&!Bs(se.rail.has,Pe))Z(!0)}}q=wt,$e.setItems(wt);let tn=P?.review??null;if(I.hasFeature("reviewmode"))try{let Be=await I.rpc("thread.review",{thread:v});if(C!==K)return;tn=Be.review??null}catch{}if(C!==K)return;let Jn="unanswered"in se?se.unanswered??null:P?.unanswered??null,Hs=se.h??P?.hashes??{};if(De(v,{entries:Kn,ids:tt,olderCursor:ue,review:tn,unanswered:Jn,rail:wt,hashes:Hs}),ge.setThread(O,Kn,Boolean(ue),tn,Jn),vt(v,C),Pe)ee(Pe);return}let Q;try{Q=await I.rpc("thread.entries",{thread:v,limit:40})}catch(Se){if(C===K){let se=Se instanceof Error&&Se.message?Se.message:"Could not load messages.";ge.setError(O,se,()=>{Ie(v)})}return}if(C!==K)return;if(Q.thread){let Se=k.findIndex((se)=>se.id===Q.thread.id);if(Se>=0)k[Se]=Q.thread;else k.unshift(Q.thread);G()}ue=Q.next??null;let fe=null;if(I.hasFeature("reviewmode"))try{let Se=await I.rpc("thread.review",{thread:v});if(C!==K)return;fe=Se.review??null}catch{}if(C!==K)return;let He=Q.entries??[],et=Q.unanswered??null;De(v,{entries:He,ids:He.map((Se)=>Se.id),olderCursor:ue,review:fe,unanswered:et,rail:P?.rail??[],hashes:P?.hashes??{}}),ge.setThread(O,He,Boolean(ue),fe,et);try{let se=(await I.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(se!==null){if(C!==K){I.rpc("unsubscribe",{sub:se}).catch(()=>{});return}Le=se}}catch{}if(C!==K)return;if(Ce(v,C),vt(v,C),Pe)ee(Pe)}async function vt(v,C){if(!v||!I.hasFeature("mgmt")){if(C===K)Je.clear();return}let L=k.find((O)=>O.id===v),P=L?.project?E.find((O)=>O.id===L.project)?.root??"":"";if(!P&&I.hasFeature("viewers"))try{let O=await I.rpc("viewer.files",{thread:v});if(C!==K)return;P=O.pcb||O.sch||O.root||""}catch{}if(C!==K)return;if(P)await Je.watchProject(P);else Je.clear()}async function Ft(v){let C=K;for(let L=0;L<25&&C===K;L++){if(ge.goTo(v))return;if(!ue)return;let P=ue;if(await Ke(),ue===P)return}}async function Ke(){if(!H||!ue){ge.clearLoadingOlder();return}let v=K,C=H,L=ue;try{let P=await I.rpc("thread.entries",{thread:C,limit:40,before:L});if(v!==K||H!==C)return;ue=P.next??null,ge.prependEntries(P.entries??[],Boolean(ue))}catch{if(v===K)ge.clearLoadingOlder()}}async function $t(v){try{let C=await I.rpc("thread.create",{project:v});if(C.thread)k=[C.thread,...k.filter((L)=>L.id!==C.thread.id)],ae.setData(E,k,j,T),ye(),await Ie(C.thread.id),de.focus()}catch(C){W(C,"Could not create thread")}}let lt=null;function Wn(v){return(v.split(` -`).map((C)=>C.trim()).find((C)=>C.length>0)??"").slice(0,200)}function yt(v){lt=v,de.setReply(v?{who:v.role==="user"?m("secret.you","You"):m("model.col.agent","Agent"),line:Wn(v.text)}:null,()=>{if(lt)Ft(lt.id)},()=>yt(null))}async function _n(v,C=[]){if(!H)return;let L=K,P=H,O=Ka(),Q=`local-${O}`,fe=lt&&v.trim()&&I.hasFeature("reply")?lt:null;if(fe)yt(null);ge.upsertEntry({id:Q,kind:"user",text:v,at:Date.now(),clientId:O,...fe?{replyTo:{id:fe.id,quote:Wn(fe.text)}}:{},attachments:C.map((He)=>({name:He.name,mime:He.mime,previewUrl:`data:${He.mime};base64,${He.data}`}))});try{let He={thread:P,text:v,clientId:O};if(C.length>0)He.attachments=C;if(fe)He.replyTo={id:fe.id,text:fe.text};let et=await I.rpc("message.send",He);if(L!==K||H!==P)return;if(et.entry)ge.upsertEntry(et.entry)}catch(He){if(L===K&&H===P){if(ge.removeEntry(Q),de.setDraft(v),fe&&!lt)yt(fe);W(He,"Failed to send message")}}}async function zn(v){if(!H)return;let C=K,L=H;try{let P=await I.rpc("composer.run",{thread:L,text:v});if(C!==K||H!==L)return;if(P.error)de.setDraft(v),W(new Bt(P.error,{code:P.errorCode,machine:P.machine}),P.error);else if(P.kind==="btw"&&typeof P.a==="string")ge.showBtw(P.q??"",P.a);else if(P.kind==="edit"&&typeof P.text==="string")de.setDraft(P.text);else if(P.kind==="project")We.open({mode:"folder"});else if(P.kind==="clone")We.open({mode:"clone",repo:P.repo??"",text:P.text??""})}catch(P){if(C===K&&H===L)de.setDraft(v),W(P,"Command refused")}}async function Qe(v,C){try{let L=await I.rpc("thread.act",{thread:v,action:C});if(L.thread){if(k=k.map((P)=>P.id===L.thread.id?L.thread:P),ae.setData(E,k,j,T),L.thread.id===H)ge.updateThreadMeta(L.thread),G()}ye()}catch(L){de.showError(L instanceof Error?L.message:`Action "${C}" not allowed`)}}function qn(v,C){if(!v||!v.text||C-v.at>=300000)return"";let L=v.build.split("-").pop()??"";if(v.reason==="build"&&L)return m("hub.restarting.build",v.text,{build:L});if(v.reason==="stop")return m("hub.stopped",v.text);return m("hub.restarting",v.text)}function Gt(v){if(v==="connected")ae.setConnStatus(m("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&qn(I.restarting,Date.now()))ae.setConnStatus(qn(I.restarting,Date.now()),"");else if(v==="reconnecting")ae.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")ae.setConnStatus(m("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else ae.setConnStatus("Connecting…","")}Ot(()=>{Gt(I.getState()),R.textContent=m("gpui.improvements","Improvements"),re.title=m("palette.settings","Settings"),re.setAttribute("aria-label",m("palette.settings","Settings")),G(),ae.refreshLocale(),ge.refreshLocale(),de.refreshLocale(),$e.render(),Oe.refreshLocale(),We.refreshLocale()}),I.onState((v,C)=>{if(v==="connected"&&C){if(C.locale)Un=C.locale,Rs();if(C.theme)Is(C.theme);if(C.name)ae.setHostName(C.name);if(it=C.home??null,ae.setHome(it),Ht(Cn(C.noProvider)),Oe.isOpen())Oe.refresh();Gt(v);let L=typeof C.hubBack==="string"?String(C.hubBack):"";if(L)try{let P=JSON.parse(L);if(P.reason==="crash")ae.setConnStatus(m("hub.back.crash",P.text??""),"bp-warn"),window.setTimeout(()=>Gt(I.getState()),6000)}catch{}if(de.setFeatures(I.hasFeature("images"),I.hasFeature("voice")),Array.isArray(C.commands))te=C.commands,de.setCommands(te);else te=[];qe(),We.reconcile()}else nt.cancel(),Gt(v)}),I.onFrame((v)=>{if(v.t==="voice"){nt.handleFrame(v);return}if(v.t==="info"&&v.info&&typeof v.info==="object"){let L=v.info;if(Object.prototype.hasOwnProperty.call(L,"provider.notice"))Ht(Cn(L["provider.notice"]));Je.handleInfo(L);return}if(v.t!=="d")return;let C=v;if(C.k==="clone"||C.k==="clone.repos"||C.k==="clone.signin"){We.handleFrame(C);return}switch(C.k){case"project":{let L=C.project;if(!L)break;let P=E.findIndex((O)=>O.id===L.id);if(P>=0)E[P]=L;else E.unshift(L);ae.setData(E,k,j,T),G(),Te();break}case"thread":{let L=C.thread;if(!L)break;let P=k.findIndex((O)=>O.id===L.id);if(P>=0)k[P]=L;else k.unshift(L);if(ae.setData(E,k,j,T),L.id===H)ge.updateThreadMeta(L),G(),de.setState(!0,L.state==="working");Te();break}case"thread.removed":{let L=String(C.id??"");k=k.filter((P)=>P.id!==L),ae.setData(E,k,j,T),Te();break}case"entry":{if(C.thread===H&&C.entry)ge.upsertEntry(C.entry);break}case"text":{if(C.thread===H)ge.appendLiveText(String(C.entry??""),String(C.append??""),Number(C.at??Date.now()));break}case"turn":{if(C.thread===H){let L=String(C.state??"idle");de.setState(!0,L==="working"),Ce(H,K)}Te();break}case"btw":{if(C.thread===H)ge.showBtw(String(C.q??""),String(C.a??""));break}case"unanswered":{if(C.thread===H)ge.setUnanswered(C.unanswered??null);break}case"theme":{if(typeof C.theme==="string")Is(C.theme);break}case"home":{if(it=C.home??null,ae.setHome(it),Oe.isOpen())Oe.refresh();break}default:break}}),window.addEventListener("keydown",(v)=>{let C=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(C==="k"||v.shiftKey&&C==="p"))if(v.preventDefault(),Ge.isOpen())Ge.close();else Ge.open();else if(v.key==="Escape"){if(Ge.isOpen())Ge.close();else if(We.isOpen())We.escape();else if(Oe.isOpen())Oe.handleEscape();else if(ge.closePlanRevise());else if(Je.isOpen())Je.closePanel()}}),I.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",js);else js(); +`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;yt({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,C)=>{try{let L={entry:v,path:C};if(I.hasFeature("blobs"))L.metaOnly=!0;let P=await I.rpc("message.image",L);if(P.blob&&P.blob.startsWith("/blob/"))return{url:P.blob};if(P.mime&&P.data)return{mime:P.mime,data:P.data}}catch{}return null}});function _e(v){if(!v)return null;if(v.planMode)return v.planMode;if(v.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function Ue(v,C){if(!H)return;let L=K,P=H;I.rpc(v,C).then((V)=>{if(L!==K||H!==P)return;if(V.thread){let ee=k.findIndex((ve)=>ve.id===V.thread.id);if(ee>=0)k[ee]=V.thread;else k.unshift(V.thread);ae.setData(E,k,j,T),fe.updateThreadMeta(V.thread),G(),de.setState(!0,V.thread.state==="working")}}).catch((V)=>{if(L===K&&H===P)de.showError(V instanceof Error?V.message:"Could not change Plan mode")})}let nt,de=new un(Ee,{onSend:(v,C)=>{_n(v,C)},onRunCommand:(v)=>{zn(v)},onInterrupt:()=>{if(H)I.rpc("turn.interrupt",{thread:H}).catch(()=>{})},onQueryMentions:async(v,C)=>{try{return(await I.rpc("mentions.list",{q:v,kind:C,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{nt.toggle()},onCyclePlanMode:()=>{let v=k.find((L)=>L.id===H)??null,C=_e(v);if(!C||!H)return;if(C.interaction!=="plan")Ue("thread.planonce",{thread:H,on:!0});else if(C.once)Ue("thread.pick",{thread:H,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:H,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!H)return;if(v==="once")Ue("thread.planonce",{thread:H,on:!0});else if(v==="always")Ue("thread.pick",{thread:H,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:H,action:"interaction",value:"default"})}});nt=new Bn(I,{getThreadId:()=>H,getDraft:()=>de.getDraft(),getCaret:()=>de.getCaret(),setDraft:(v)=>de.setDraft(v),setRecording:(v)=>de.setVoiceRecording(v),setLevel:(v)=>de.setVoiceLevel(v),showError:(v)=>de.showError(v)});function gt(){let v=Pe!=="",C=Je.isOpen();Ae.classList.toggle("bp-hidden",!v&&!C),Ae.classList.toggle("bp-has-viewer",v),Ae.classList.toggle("bp-has-mgmt",C)}let Je=new wn(Me,Ae,{hub:I,getThreadId:()=>H,getThreadGen:()=>K,onSendText:(v)=>{_n(v)},onOpenChange:()=>gt()});function ft(v){let C=window.prompt("Rename thread",v.title||"");if(!C||!C.trim())return;I.rpc("thread.act",{thread:v.id,action:"rename",title:C.trim()}).then((L)=>{if(L.thread)k=k.map((P)=>P.id===L.thread.id?L.thread:P),G(),we()}).catch((L)=>{de.showError(L instanceof Error?L.message:"Could not rename thread")})}function Ye(v){switch(v.type){case"thread":Ie(v.id);break;case"rail":if(!H&&v.id!=="terminal")break;if(Pe===v.id)Q();else X(v.id);break;case"thread-act":if(H)Qe(H,v.action);break;case"new-thread":$t(v.projectId);break;case"rename":{let C=k.find((L)=>L.id===H);if(C)ft(C);break}case"prev-thread":case"next-thread":{let C=k.filter((ee)=>!ee.archived&&!ee.swarm);if(C.length<2)break;let L=C.findIndex((ee)=>ee.id===H),P=v.type==="next-thread"?1:-1,V=C[(L<0?0:L+P+C.length)%C.length];if(V)Ie(V.id);break}case"command":if(v.runDirectly)zn(v.word);else de.setDraft(`${v.word} `),de.focus();break;case"improvements":O();break;case"settings":Oe.open();break;case"sidebar":oe.classList.toggle("bp-sidebar-open"),oe.classList.toggle("bp-sidebar-collapsed");break}}let Ge=new En(e,{getState:()=>({selectedThreadId:H,threads:k,projects:E,bots:j,railItems:q,commands:ne}),onSearch:async(v)=>{if(!I.hasFeature("search"))return{threads:[],projects:[],messages:[]};return I.rpc("search",{q:v,limit:20})},onExecute:Ye}),We=new on(e,{hub:I,onProjectAdded:(v)=>{if(we(),v.id)$t(v.id)},onCloneDone:(v)=>{if(we(),v.thread)Ie(v.thread)}}),$e=new xn(be,(v)=>{if(v==="commands"){Ge.open();return}if(!H)return;if(Pe===v)Q();else X(v)}),it=null,Dt=null,Oe=new Ln(e,{onLoadDevices:async()=>(await I.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,C)=>{await I.rpc("devices.page.act",{action:v,value:C})},onGetHome:()=>it,onMoveHomeHere:async()=>{await I.rpc("home.move",{to:"back"})},onGetNoProvider:()=>Dt,onGetThemePref:()=>en,onSetThemePref:(v)=>{en=v;try{if(v==="auto")localStorage.removeItem("bp.theme.pref");else localStorage.setItem("bp.theme.pref",v)}catch{}Ds()},onGetHubTheme:()=>jt,onGetLocalePref:()=>bt,onSetLocalePref:(v)=>{bt=v;try{if(v==="auto")localStorage.removeItem("bp.locale");else localStorage.setItem("bp.locale",v)}catch{}Rs()},onLogout:()=>oi(()=>{I.disconnect(),window.location.replace("/")})});function Ht(v){if(Dt=v,fe.setNoProvider(v),Oe.isOpen())Oe.refresh()}function F(){Oe.openToAccounts()}function W(v,C){let L=v instanceof Error?v.message:C,P=v instanceof Bt?v:null,V=P?.code,ee=P?.machine,ve=V==="no_provider_remote"&&ee?h("provider.notice.senderr.remote","No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.").replaceAll("{machine}",ee):L;de.showError(ve,_i(L,V)?{label:h("provider.notice.button","Open Settings → Accounts"),onClick:F}:void 0)}g.addEventListener("click",()=>{let v=k.find((C)=>C.id===H);if(v)Qe(v.id,v.pinned?"unpin":"pin")}),w.addEventListener("click",()=>{let v=k.find((C)=>C.id===H);if(v)Qe(v.id,v.settled?"unsettle":"settle")});let _=new Nn(e,(v,C)=>C?I.rpc("thread.context.mcp",{thread:v,...C}):I.rpc("thread.context",{thread:v}));N.addEventListener("click",(v)=>{v.stopPropagation();let C=k.find((V)=>V.id===H);if(!C)return;if(!S.classList.contains("bp-hidden")){S.classList.add("bp-hidden");return}let L=[{label:"Rename…",run:()=>ft(C)},{label:C.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),run:()=>{Qe(C.id,C.pinned?"unpin":"pin")}},{label:C.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle"),run:()=>{Qe(C.id,C.settled?"unsettle":"settle")}},{label:C.archived?"Unarchive":"Archive",run:()=>{Qe(C.id,C.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Qe(C.id,"delete")}}];if(I.hasFeature("threadContext"))L.unshift({label:h("thread.context.title","Context & Prompt"),run:()=>_.open(C.id)});let P=document.createDocumentFragment();for(let V of L){let ee=document.createElement("button");ee.type="button",ee.className="bp-popover-item"+(V.danger?" danger":""),ee.textContent=V.label,ee.addEventListener("click",()=>{S.classList.add("bp-hidden"),V.run()}),P.appendChild(ee)}S.replaceChildren(P),S.classList.remove("bp-hidden")}),document.addEventListener("click",()=>S.classList.add("bp-hidden"));async function O(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let C=document.createElement("div");C.className="bp-modal";let L=document.createElement("div");L.className="bp-modal-head";let P=document.createElement("h2");P.textContent=h("gpui.improvements","Improvements");let V=document.createElement("button");V.type="button",V.className="icon",V.textContent="×",V.addEventListener("click",()=>v.remove()),L.append(P,V);let ee=document.createElement("div");ee.className="bp-modal-body",ee.textContent="Loading…",C.append(L,ee),v.appendChild(C),v.addEventListener("click",(ve)=>{if(ve.target===v)v.remove()}),e.appendChild(v);try{let ve=await I.rpc("improvements.projects",{}),He=ve.projects??[];if(He.length===0){ee.textContent="No projects available for Improvements.";return}let et=document.createDocumentFragment();for(let Se of He){let se=document.createElement("div");se.className="bp-set-row";let Xe=document.createElement("div");Xe.className="bp-set-info",Xe.textContent=Se.title||Se.name||Se.id;let tt=document.createElement("button");tt.type="button",tt.className=Se.id===ve.project?"primary":"",tt.textContent=Se.id===ve.project?"Active":"Select",tt.addEventListener("click",()=>{I.rpc("improvements.project",{project:Se.id}).then(()=>v.remove()).catch(()=>{})}),se.append(Xe,tt),et.appendChild(se)}ee.replaceChildren(et)}catch(ve){ee.textContent=ve instanceof Error?ve.message:"Could not load Improvements."}}B.addEventListener("click",()=>{O()}),U.addEventListener("click",()=>Ge.open()),D.addEventListener("click",()=>Ge.open()),re.addEventListener("click",()=>{Oe.open()}),n.addEventListener("click",()=>{oe.classList.toggle("bp-sidebar-open"),oe.classList.toggle("bp-sidebar-collapsed")});function G(){let v=k.find((P)=>P.id===H)??null,C=v?E.find((P)=>P.id===v.project):void 0;o.textContent=C?.title??"",r.classList.toggle("bp-hidden",!C),l.classList.toggle("bp-hidden",!v),p.textContent=v?v.title||"Untitled thread":"";let L=_e(v);if(de.setPlanMode(L),!L||L.phase==="off")c.classList.add("bp-hidden"),c.classList.remove("is-exec"),c.textContent="";else c.classList.remove("bp-hidden"),c.classList.toggle("is-exec",L.phase==="executing"),c.title=h("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),c.textContent=L.phase==="armed"&&L.once?h("gpui.planmode.top.once","Plan (1 turn)"):L.phase==="armed"?h("gpui.mgmt.plan.tab","Plan"):L.phase==="planning"?h("gpui.planmode.top.planning","Planning"):L.phase==="pending"?h("gpui.planmode.top.pending","Review plan"):h("gpui.planmode.top.executing","Building plan");if(u.classList.toggle("bp-hidden",!v),b.classList.toggle("bp-hidden",!v),v){m.className=`bp-dot ${qa(v)}`,f.textContent=v.status||v.state||"idle",y.textContent=v.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),x.textContent=v.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle");let P=v;de.setModelChip(v.chip||v.model||"default",v.provider,P.ctxPct??P.contextPct),de.setMemory(v.memory)}else de.setModelChip("default"),de.setMemory(null)}function Q(v=!0){if(je++,Pe="",$e.setActive(""),he.classList.add("bp-hidden"),Y?.close(),gt(),v&&H&&I.getState()==="connected")I.rpc("viewer.watch",{thread:H,kind:""}).catch(()=>{})}function X(v){if(je++,Pe=v,$e.setActive(v),he.classList.remove("bp-hidden"),gt(),!Y&&typeof Vn==="function")Y=Vn(he,{hub:I,getThreadId:()=>H,closeViewer:()=>Q(!0)});if(Y)Y.open(v,H);else{let C=document.createElement("div");C.className="bp-viewer-placeholder";let L=document.createElement("div");L.className="bp-viewer-bar";let P=document.createElement("span");P.textContent=v.toUpperCase();let V=document.createElement("button");V.type="button",V.className="icon",V.textContent="×",V.addEventListener("click",()=>Q(!0)),L.append(P,V);let ee=document.createElement("div");ee.className="bp-dim bp-viewer-msg",ee.textContent=`Viewer pane (${v}).`,C.append(L,ee),he.replaceChildren(C)}}async function ge(v,C){if(!v||!I.hasFeature("rail")){if(C===K)q=[],$e.setItems([]);return}let L=++je;try{let P=await I.rpc("viewer.rail",{thread:v,page:Pe});if(C!==K||L!==je)return;let V=Array.isArray(P.rail)?P.rail:Array.isArray(P.items)?P.items:[];if(q=V,$e.setItems(V),P.has){if(Y?.reconcileHas?.(P.has),Pe&&!Bs(P.has,Pe))Q(!0)}}catch{if(C===K&&L===je)q=[],$e.setItems([])}}function Ce(v){for(let C of v)if(C.kind==="threads"){for(let L of C.rows)if(!L.off&&(L.nav||L.id)&&!(L.nav||"").startsWith("@room:"))return L.nav||L.id}else if(C.kind==="projects"){for(let L of C.rows)for(let P of L.threads??[])if(!P.off&&(P.nav||P.id)&&!(P.nav||"").startsWith("@room:"))return P.nav||P.id}return""}function Ne(v,C){for(let L of v)if(L.kind==="threads"){if(L.rows.some((P)=>(P.nav||P.id)===C))return!0}else if(L.kind==="projects"){for(let P of L.rows)if((P.threads??[]).some((V)=>(V.nav||V.id)===C))return!0}return!1}function Re(v){let C=[];for(let L of v){if(L.kind!=="projects")continue;for(let P of L.rows)C.push({id:P.id,title:P.title,css:P.css,color:P.color})}if(C.length>0)E=C}async function we(){if(!I.hasFeature("sections"))return!1;let v=++Z;try{let C=await I.rpc("sidebar.sections",{open:Array.from(ie)});if(v!==Z)return!0;let L=Array.isArray(C.sections)?C.sections:[];return le=L,Re(L),ae.setData(E,k,j,T),ae.setSections(L,j,T),G(),!0}catch{return!1}}function Te(){if(!I.hasFeature("sections"))return;if(ce!==null)window.clearTimeout(ce);ce=window.setTimeout(()=>{ce=null,we()},150)}async function qe(){if(Le=null,I.hasFeature("bots"))try{let C=await I.rpc("bots.list",{});j=C.bots??[],T=C.rooms??[]}catch{}if(I.hasFeature("shell")){let C=await I.rpc("shell.sync",{have:te,settled:25}),L=new Set(C.removed??[]),P=new Set((C.projects??[]).map((V)=>V.id));if(L.size>0||P.size>0)E=[...E.filter((V)=>!L.has(V.id)&&!P.has(V.id)),...C.projects??[]],k=[...k.filter((V)=>!L.has(V.project)&&!P.has(V.project)),...C.threads??[]];else if(Array.isArray(C.threads)&&C.threads.length>0){let V=new Map(k.map((ee)=>[ee.id,ee]));for(let ee of C.threads)V.set(ee.id,ee);k=Array.from(V.values())}if(C.sections!==void 0){let V=Array.isArray(C.sections)?C.sections:Array.isArray(C.sections?.sections)?C.sections.sections:null;if(V)le=V,Re(V)}if(C.h)te=C.h;ae.setData(E,k,j,T),ae.setSections(le,j,T)}else if(I.hasFeature("sections")){let[C,L]=await Promise.all([I.rpc("sidebar.sections",{open:Array.from(ie)}).catch(()=>null),I.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(k=L.threads??[],C&&Array.isArray(C.sections)){let P=C.sections;if(!P.some((ee)=>ee.kind==="projects"&&ee.rows.length>0)){let ee=P.find((ve)=>ve.kind==="projects"&&ve.fold&&ve.toggle&&(ve.count??0)>0);if(ee?.toggle&&!ie.has(ee.toggle)){ie.add(ee.toggle);let ve=await I.rpc("sidebar.sections",{open:Array.from(ie)}).catch(()=>null);if(ve&&Array.isArray(ve.sections))P=ve.sections}}le=P,Re(P),ae.setData(E,k,j,T),ae.setSections(P,j,T)}else le=null,E=(await I.rpc("projects.list",{limit:100})).projects??[],ae.setSections(null,j,T),ae.setData(E,k,j,T);await I.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{le=null;let[C,L]=await Promise.all([I.rpc("projects.list",{limit:100}),I.rpc("threads.list",{limit:200,archived:!1})]);E=C.projects??[],k=L.threads??[],ae.setSections(null,j,T),ae.setData(E,k,j,T),await I.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=H;if(!v){let C="";try{C=localStorage.getItem("bp.lastThread")||""}catch{}if(C&&(le&&Ne(le,C)||k.some((L)=>L.id===C)))v=C;else if(le)v=Ce(le);if(!v)v=(k.find((P)=>!P.archived&&!P.swarm&&!P.settled)??k.find((P)=>!P.archived&&!P.swarm))?.id??""}if(v&&(le&&Ne(le,v)||k.some((C)=>C.id===v)))await Ie(v);else H="",q=[],$e.setItems([]),de.setState(!1,!1),G()}async function Ie(v){if(H&&H!==v){nt.cancel();let Se=fe.getEntries();if(Se.length>0){let se=ke.get(H);De(H,{entries:Se,ids:se?.ids??Se.map((Xe)=>Xe.id),olderCursor:ue,review:se?.review??null,unanswered:se?.unanswered??null,rail:se?.rail??q,hashes:se?.hashes??{}})}}let C=++K;je++,yt(null);let L=Le;if(Le=null,L!==null)I.rpc("unsubscribe",{sub:L}).catch(()=>{});H=v;let P=ke.get(v);ue=P?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}ae.setSelected(v),oe.classList.remove("bp-sidebar-open"),G();let V=k.find((Se)=>Se.id===v)??null;if(P)fe.setThread(V,P.entries,Boolean(P.olderCursor),P.review,P.unanswered),q=P.rail,$e.setItems(P.rail);else fe.setLoading(V),q=[],$e.setItems([]);if(de.setState(!0,V?.state==="working"),I.hasFeature("open")){let Se={};if(P){for(let[Be,Et]of Object.entries(P.hashes))Se[Be]=Et;for(let Be of P.entries)if(Be.h)Se[Be.id]=Be.h}let se;try{se=await I.rpc("thread.open",{thread:v,limit:40,have:Se})}catch(Be){if(C===K){let Et=Be instanceof Error&&Be.message?Be.message:"Could not load messages.";fe.setError(V,Et,()=>{Ie(v)})}return}if(C!==K){if(se.sub!==void 0&&se.sub!==null)I.rpc("unsubscribe",{sub:se.sub}).catch(()=>{});return}if(Le=se.sub??null,se.thread){V=se.thread;let Be=k.findIndex((Et)=>Et.id===se.thread.id);if(Be>=0)k[Be]=se.thread;else k.unshift(se.thread);G(),de.setState(!0,V.state==="working")}if("next"in se)ue=se.next??null;let Xe=new Map;if(P)for(let Be of P.entries)Xe.set(Be.id,Be);for(let Be of se.entries??[])Xe.set(Be.id,Be);let tt=se.ids??P?.ids??(se.entries??[]).map((Be)=>Be.id),Kn=tt.map((Be)=>Xe.get(Be)).filter((Be)=>Boolean(Be)),wt=P?.rail??[];if(se.rail!==void 0){if(Array.isArray(se.rail))wt=se.rail;else if(wt=Array.isArray(se.rail?.rail)?se.rail.rail:Array.isArray(se.rail?.items)?se.rail.items:[],se.rail?.has){if(Y?.reconcileHas?.(se.rail.has),Pe&&!Bs(se.rail.has,Pe))Q(!0)}}q=wt,$e.setItems(wt);let tn=P?.review??null;if(I.hasFeature("reviewmode"))try{let Be=await I.rpc("thread.review",{thread:v});if(C!==K)return;tn=Be.review??null}catch{}if(C!==K)return;let Jn="unanswered"in se?se.unanswered??null:P?.unanswered??null,Hs=se.h??P?.hashes??{};if(De(v,{entries:Kn,ids:tt,olderCursor:ue,review:tn,unanswered:Jn,rail:wt,hashes:Hs}),fe.setThread(V,Kn,Boolean(ue),tn,Jn),vt(v,C),Pe)X(Pe);return}let ee;try{ee=await I.rpc("thread.entries",{thread:v,limit:40})}catch(Se){if(C===K){let se=Se instanceof Error&&Se.message?Se.message:"Could not load messages.";fe.setError(V,se,()=>{Ie(v)})}return}if(C!==K)return;if(ee.thread){let Se=k.findIndex((se)=>se.id===ee.thread.id);if(Se>=0)k[Se]=ee.thread;else k.unshift(ee.thread);G()}ue=ee.next??null;let ve=null;if(I.hasFeature("reviewmode"))try{let Se=await I.rpc("thread.review",{thread:v});if(C!==K)return;ve=Se.review??null}catch{}if(C!==K)return;let He=ee.entries??[],et=ee.unanswered??null;De(v,{entries:He,ids:He.map((Se)=>Se.id),olderCursor:ue,review:ve,unanswered:et,rail:P?.rail??[],hashes:P?.hashes??{}}),fe.setThread(V,He,Boolean(ue),ve,et);try{let se=(await I.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(se!==null){if(C!==K){I.rpc("unsubscribe",{sub:se}).catch(()=>{});return}Le=se}}catch{}if(C!==K)return;if(ge(v,C),vt(v,C),Pe)X(Pe)}async function vt(v,C){if(!v||!I.hasFeature("mgmt")){if(C===K)Je.clear();return}let L=k.find((V)=>V.id===v),P=L?.project?E.find((V)=>V.id===L.project)?.root??"":"";if(!P&&I.hasFeature("viewers"))try{let V=await I.rpc("viewer.files",{thread:v});if(C!==K)return;P=V.pcb||V.sch||V.root||""}catch{}if(C!==K)return;if(P)await Je.watchProject(P);else Je.clear()}async function Ft(v){let C=K;for(let L=0;L<25&&C===K;L++){if(fe.goTo(v))return;if(!ue)return;let P=ue;if(await Ke(),ue===P)return}}async function Ke(){if(!H||!ue){fe.clearLoadingOlder();return}let v=K,C=H,L=ue;try{let P=await I.rpc("thread.entries",{thread:C,limit:40,before:L});if(v!==K||H!==C)return;ue=P.next??null,fe.prependEntries(P.entries??[],Boolean(ue))}catch{if(v===K)fe.clearLoadingOlder()}}async function $t(v){try{let C=await I.rpc("thread.create",{project:v});if(C.thread)k=[C.thread,...k.filter((L)=>L.id!==C.thread.id)],ae.setData(E,k,j,T),we(),await Ie(C.thread.id),de.focus()}catch(C){W(C,"Could not create thread")}}let lt=null;function Wn(v){return(v.split(` +`).map((C)=>C.trim()).find((C)=>C.length>0)??"").slice(0,200)}function yt(v){lt=v,de.setReply(v?{who:v.role==="user"?h("secret.you","You"):h("model.col.agent","Agent"),line:Wn(v.text)}:null,()=>{if(lt)Ft(lt.id)},()=>yt(null))}async function _n(v,C=[]){if(!H)return;let L=K,P=H,V=Ka(),ee=`local-${V}`,ve=lt&&v.trim()&&I.hasFeature("reply")?lt:null;if(ve)yt(null);fe.upsertEntry({id:ee,kind:"user",text:v,at:Date.now(),clientId:V,...ve?{replyTo:{id:ve.id,quote:Wn(ve.text)}}:{},attachments:C.map((He)=>({name:He.name,mime:He.mime,previewUrl:`data:${He.mime};base64,${He.data}`}))});try{let He={thread:P,text:v,clientId:V};if(C.length>0)He.attachments=C;if(ve)He.replyTo={id:ve.id,text:ve.text};let et=await I.rpc("message.send",He);if(L!==K||H!==P)return;if(et.entry)fe.upsertEntry(et.entry)}catch(He){if(L===K&&H===P){if(fe.removeEntry(ee),de.setDraft(v),ve&&!lt)yt(ve);W(He,"Failed to send message")}}}async function zn(v){if(!H)return;let C=K,L=H;try{let P=await I.rpc("composer.run",{thread:L,text:v});if(C!==K||H!==L)return;if(P.error)de.setDraft(v),W(new Bt(P.error,{code:P.errorCode,machine:P.machine}),P.error);else if(P.kind==="btw"&&typeof P.a==="string")fe.showBtw(P.q??"",P.a);else if(P.kind==="edit"&&typeof P.text==="string")de.setDraft(P.text);else if(P.kind==="project")We.open({mode:"folder"});else if(P.kind==="clone")We.open({mode:"clone",repo:P.repo??"",text:P.text??""})}catch(P){if(C===K&&H===L)de.setDraft(v),W(P,"Command refused")}}async function Qe(v,C){try{let L=await I.rpc("thread.act",{thread:v,action:C});if(L.thread){if(k=k.map((P)=>P.id===L.thread.id?L.thread:P),ae.setData(E,k,j,T),L.thread.id===H)fe.updateThreadMeta(L.thread),G()}we()}catch(L){de.showError(L instanceof Error?L.message:`Action "${C}" not allowed`)}}function qn(v,C){if(!v||!v.text||C-v.at>=300000)return"";let L=v.build.split("-").pop()??"";if(v.reason==="build"&&L)return h("hub.restarting.build",v.text,{build:L});if(v.reason==="stop")return h("hub.stopped",v.text);return h("hub.restarting",v.text)}function Gt(v){if(v==="connected")ae.setConnStatus(h("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&qn(I.restarting,Date.now()))ae.setConnStatus(qn(I.restarting,Date.now()),"");else if(v==="reconnecting")ae.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")ae.setConnStatus(h("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else ae.setConnStatus("Connecting…","")}Ot(()=>{Gt(I.getState()),R.textContent=h("gpui.improvements","Improvements"),re.title=h("palette.settings","Settings"),re.setAttribute("aria-label",h("palette.settings","Settings")),G(),ae.refreshLocale(),fe.refreshLocale(),de.refreshLocale(),$e.render(),Oe.refreshLocale(),We.refreshLocale()}),I.onState((v,C)=>{if(v==="connected"&&C){if(C.locale)Un=C.locale,Rs();if(C.theme)Is(C.theme);if(C.name)ae.setHostName(C.name);if(it=C.home??null,ae.setHome(it),Ht(Cn(C.noProvider)),Oe.isOpen())Oe.refresh();Gt(v);let L=typeof C.hubBack==="string"?String(C.hubBack):"";if(L)try{let P=JSON.parse(L);if(P.reason==="crash")ae.setConnStatus(h("hub.back.crash",P.text??""),"bp-warn"),window.setTimeout(()=>Gt(I.getState()),6000)}catch{}if(de.setFeatures(I.hasFeature("images"),I.hasFeature("voice")),Array.isArray(C.commands))ne=C.commands,de.setCommands(ne);else ne=[];qe(),We.reconcile()}else nt.cancel(),Gt(v)}),I.onFrame((v)=>{if(v.t==="voice"){nt.handleFrame(v);return}if(v.t==="info"&&v.info&&typeof v.info==="object"){let L=v.info;if(Object.prototype.hasOwnProperty.call(L,"provider.notice"))Ht(Cn(L["provider.notice"]));Je.handleInfo(L);return}if(v.t!=="d")return;let C=v;if(C.k==="clone"||C.k==="clone.repos"||C.k==="clone.signin"){We.handleFrame(C);return}switch(C.k){case"project":{let L=C.project;if(!L)break;let P=E.findIndex((V)=>V.id===L.id);if(P>=0)E[P]=L;else E.unshift(L);ae.setData(E,k,j,T),G(),Te();break}case"thread":{let L=C.thread;if(!L)break;let P=k.findIndex((V)=>V.id===L.id);if(P>=0)k[P]=L;else k.unshift(L);if(ae.setData(E,k,j,T),L.id===H)fe.updateThreadMeta(L),G(),de.setState(!0,L.state==="working");Te();break}case"thread.removed":{let L=String(C.id??"");k=k.filter((P)=>P.id!==L),ae.setData(E,k,j,T),Te();break}case"entry":{if(C.thread===H&&C.entry)fe.upsertEntry(C.entry);break}case"text":{if(C.thread===H)fe.appendLiveText(String(C.entry??""),String(C.append??""),Number(C.at??Date.now()));break}case"turn":{if(C.thread===H){let L=String(C.state??"idle");de.setState(!0,L==="working"),ge(H,K)}Te();break}case"btw":{if(C.thread===H)fe.showBtw(String(C.q??""),String(C.a??""));break}case"unanswered":{if(C.thread===H)fe.setUnanswered(C.unanswered??null);break}case"theme":{if(typeof C.theme==="string")Is(C.theme);break}case"home":{if(it=C.home??null,ae.setHome(it),Oe.isOpen())Oe.refresh();break}default:break}}),window.addEventListener("keydown",(v)=>{let C=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(C==="k"||v.shiftKey&&C==="p"))if(v.preventDefault(),Ge.isOpen())Ge.close();else Ge.open();else if(v.key==="Escape"){if(Ge.isOpen())Ge.close();else if(We.isOpen())We.escape();else if(Oe.isOpen())Oe.handleEscape();else if(fe.closePlanRevise());else if(Je.isOpen())Je.closePanel()}}),I.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",js);else js(); diff --git a/web/dist/assets/pair.js b/web/dist/assets/pair.js index 819be54171..1ea9cde973 100644 --- a/web/dist/assets/pair.js +++ b/web/dist/assets/pair.js @@ -1 +1 @@ -var U={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.new":"New bot","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","gpui.settings.group.agents":"Agents and tools","gpui.settings.group.general":"General","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","menu.wake":"Wake","model.col.agent":"Agent","native.pair.connect":"Connect","native.thread.model":"Model","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.senderr.remote":"No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","rooms.new":"New room","secret.you":"You","settings.appearance":"Appearance","settings.lang":"Language","settings.lang.auto":"Automatic","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Theme","settings.theme.dark":"Dark","settings.theme.light":"Light","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets","web.settings.providers":"AI providers","web.settings.providers.browser":"Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.new":"Nuevo bot","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.short":"Capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.noitems":"Sin corredores ni planos en esta capa","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup.short":"Apilamiento","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","gpui.settings.group.agents":"Agentes y herramientas","gpui.settings.group.general":"General","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","menu.wake":"Despertar","model.col.agent":"Agente","native.pair.connect":"Conectar","native.thread.model":"Modelo","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.senderr.remote":"No hay ningún proveedor de IA conectado en {machine}. Abre Configuración → Cuentas en {machine} para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","rooms.new":"Nueva sala","secret.you":"Tú","settings.appearance":"Apariencia","settings.lang":"Idioma","settings.lang.auto":"Automático","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Tema","settings.theme.dark":"Oscuro","settings.theme.light":"Claro","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes","web.settings.providers":"Proveedores de IA","web.settings.providers.browser":"Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas."},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.new":"新しいボット","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.short":"レイヤー","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.noitems":"このレイヤーにコリドーまたはプレーンがありません","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup.short":"スタックアップ","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","gpui.settings.group.agents":"エージェントとツール","gpui.settings.group.general":"一般","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","menu.wake":"再開","model.col.agent":"エージェント","native.pair.connect":"接続","native.thread.model":"モデル","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.senderr.remote":"{machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","rooms.new":"新しいルーム","secret.you":"あなた","settings.appearance":"外観","settings.lang":"言語","settings.lang.auto":"自動","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"テーマ","settings.theme.dark":"ダーク","settings.theme.light":"ライト","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット","web.settings.providers":"AI プロバイダー","web.settings.providers.browser":"Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。"}};function Q(n,t){if(!t)return n;return n.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(s,r)=>Object.prototype.hasOwnProperty.call(t,r)?String(t[r]):s)}var O=te(),W=new Set,V=new Map;for(let[n,t]of Object.entries(U.en||{}))if(typeof t==="string"&&!V.has(t))V.set(t,n);function te(){let n=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(n.startsWith("ja"))return"ja";if(n.startsWith("es"))return"es";return"en"}function Y(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=O}Y();function me(n){return W.add(n),()=>{W.delete(n)}}function ue(n){if(!n)return!1;let t=n.toLowerCase(),s=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!s)return!1;let r=s!==O;if(O=s,Y(),r)for(let d of W)d(O);return r}function c(n,t,s){let d=(U[O]||U.en||{})[n]??U.en?.[n]??t??n;return Q(d,s)}function ge(n){if(!n)return"";let t=V.get(n);if(!t)return n;return c(t,n)}var ne=[[1,26,7,1,[]],[2,44,10,1,[6,18]],[3,70,15,1,[6,22]],[4,100,20,1,[6,26]],[5,134,26,1,[6,30]],[6,172,18,2,[6,34]]],G=new Uint8Array(512),_=new Uint8Array(256);{let n=1;for(let t=0;t<255;t++)if(G[t]=n,_[n]=t,n<<=1,n&256)n^=285;for(let t=255;t<512;t++)G[t]=G[t-255]}function J(n,t){return n===0||t===0?0:G[_[n]+_[t]]}function ae(n){let t=new Uint8Array([1]);for(let s=0;s{let m=e-i*a;return Math.ceil((12+t.length*8)/8)<=m});if(!s)return null;let[r,d,u,f,E]=s,w=d-u*f,g=[],S=(e,i)=>{for(let a=i-1;a>=0;a--)g.push(e>>>a&1)};S(4,4),S(t.length,8);for(let e of t)S(e,8);for(let e=0;e<4&&g.length{if(e<0||i<0||e>=p||i>=p)return;H[e*p+i]=a?1:0,A[e*p+i]=1},N=(e,i)=>{for(let a=-1;a<=7;a++)for(let m=-1;m<=7;m++){let k=e+a,l=i+m,o=a>=0&&a<=6&&m>=0&&m<=6&&(a===0||a===6||m===0||m===6||a>=2&&a<=4&&m>=2&&m<=4);b(k,l,o)}};N(0,0),N(0,p-7),N(p-7,0);for(let e=8;e=1;e-=2){if(e===6)e=5;let i=(e+1&2)===0;for(let a=0;a>>3]>>>7-(j&7)&1,j++;let o=(m+l&1)===0?h^1:h;H[m*p+l]=o}}}let R=30660;for(let e=0;e<=5;e++)b(8,e,(R>>>14-e&1)===1);b(8,7,(R>>>8&1)===1),b(8,8,(R>>>7&1)===1),b(7,8,(R>>>6&1)===1);for(let e=0;e<=5;e++)b(5-e,8,(R>>>5-e&1)===1);for(let e=0;e<8;e++)b(8,p-1-e,(R>>>e&1)===1);for(let e=0;e<7;e++)b(p-7+e,8,(R>>>14-e&1)===1);return{size:p,modules:H}}function X(n){let t=oe(n);if(!t)return null;let s=2,r=t.size+s*2,d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("viewBox",`0 0 ${r} ${r}`),d.setAttribute("role","img"),d.setAttribute("aria-label",`QR code for ${n}`),d.setAttribute("shape-rendering","crispEdges"),d.classList.add("bp-qr-svg");let u=document.createElementNS("http://www.w3.org/2000/svg","rect");u.setAttribute("width",String(r)),u.setAttribute("height",String(r)),u.setAttribute("fill","#ffffff"),d.appendChild(u);let f="";for(let w=0;w{let h=l.trim();if(!h)return;let o=h.startsWith("https://")?h:`https://${h}`;if(!o.startsWith("https://")||o.length<=8)return;let x=document.createElement("div");x.className="bp-pair-addr-meta";let v=document.createElement("div");v.className="bp-pair-code-label",v.textContent=c("ios.hub.address.field","Hub address");let y=document.createElement("code");y.className="bp-pair-addr-url",y.textContent=o,y.setAttribute("data-testid","pair-address");let P=document.createElement("button");P.type="button",P.className="bp-pair-copy";let I=c("common.copy","Copy");P.textContent=I,P.addEventListener("click",()=>{navigator.clipboard?.writeText(o).then(()=>{P.textContent=c("web.clone.copied","Copied"),window.setTimeout(()=>{P.textContent=I},1200)}).catch(()=>{})}),x.append(v,y,P);let z=document.createDocumentFragment();z.appendChild(x);let K=X(o);if(K){let F=document.createElement("div");F.className="bp-pair-qr",F.setAttribute("data-testid","pair-qr"),F.appendChild(K),z.appendChild(F)}p.replaceChildren(z),p.classList.remove("bp-hidden")};fetch("/auth/web/info",{credentials:"same-origin"}).then(async(l)=>{if(!l.ok)return;let h=await l.json();if(typeof h.address==="string")H(h.address)}).catch(()=>{}),t.append(s,u,f,S,C,p),n.appendChild(t);let A=null,b=null,N=null,j=0,D=0,R=150,e=1000;function i(){if(j++,N)N.abort(),N=null;if(A!==null)window.clearTimeout(A),A=null;if(b!==null)window.clearInterval(b),b=null}function a(l="",h=!1){i(),f.classList.remove("bp-hidden"),S.classList.add("bp-hidden"),g.disabled=!1,C.textContent=l,C.className=h?"bp-pair-status bp-bad":"bp-pair-status"}function m(){let l=D-Date.now();if(l<=0){a(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}B.textContent=c("web.pair.approve.in","Approve on desktop or paired phone · expires in {time}",{time:pe(l)})}async function k(l){if(l!==j)return;if(D>0&&Date.now()>=D){a(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let h=new AbortController;N=h;try{let o=await fetch("/auth/web/poll",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:"{}",signal:h.signal});if(l!==j)return;if(e=1000,o.status===202){A=window.setTimeout(()=>{k(l)},150);return}if(o.status===200||o.status===204){let v={};if(o.status===200)try{v=await o.json()}catch{}if(l!==j)return;let y=(v.state||v.status||"").toLowerCase();if(o.status===204||v.approved===!0||y==="approved"||y==="ok"){i(),C.textContent=c("web.pair.approved","Approved. Opening Backplane…"),C.className="bp-pair-status bp-ok",window.location.replace("/");return}if(y==="denied"||y==="rejected"){a(c("web.pair.denied","Pairing request was denied."),!0);return}if(y==="expired"){a(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}A=window.setTimeout(()=>{k(l)},150);return}if(o.status===429){let v=Number(o.headers.get("Retry-After")||"5"),y=Math.max(2000,(Number.isFinite(v)?v:5)*1000);A=window.setTimeout(()=>{k(l)},y);return}if(o.status===401||o.status===403||o.status===404||o.status===410){let v="";try{let y=await o.json();v=(y.state||y.status||y.error||"").toLowerCase()}catch{}if(l!==j)return;if(v==="denied"||v==="rejected"||o.status===403)a(c("web.pair.denied","Pairing request was denied."),!0);else a(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let x=e;e=Math.min(1e4,Math.round(e*1.8)),A=window.setTimeout(()=>{k(l)},x)}catch{if(l!==j)return;let o=e;e=Math.min(1e4,Math.round(e*1.8)),A=window.setTimeout(()=>{k(l)},o)}finally{if(N===h)N=null}}L.addEventListener("click",()=>{a(c("web.pair.cancelled","Cancelled."))}),f.addEventListener("submit",async(l)=>{l.preventDefault();let h=w.value.trim()||Z();g.disabled=!0,C.textContent=c("web.pair.requesting","Requesting pairing code…"),C.className="bp-pair-status";try{let o=await fetch("/auth/web/request",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:h})});if(!o.ok){let I=c("web.pair.failed","Pairing request failed ({status})",{status:o.status});try{let z=await o.json();if(z.error)I=z.error}catch{}if(o.status===429)I=c("web.pair.ratelimited","Too many pairing attempts. Wait a moment and try again.");a(I,!0);return}let x=await o.json(),v=x.code||x.checkCode||"";if(!v){a(c("web.pair.nocode","Hub did not return a comparison code."),!0);return}let y=Date.now();D=x.expiresAt?x.expiresAt<10000000000?x.expiresAt*1000:x.expiresAt:y+(x.expiresIn?x.expiresIn*1000:120000),i();let P=j;e=1000,R=x.pollMs&&x.pollMs>=100?x.pollMs:150,M.textContent=re(v),f.classList.add("bp-hidden"),S.classList.remove("bp-hidden"),C.textContent="",m(),b=window.setInterval(m,1000),A=window.setTimeout(()=>{k(P)},R)}catch{a(c("web.pair.unreachable","Could not reach the hub. Check your tailnet connection."),!0)}})}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",ee);else ee(); +var U={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.new":"New bot","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.solid.big.next":"Loading it may take a while and a lot of memory.","gpui.c.solid.load.big":"Load it anyway","gpui.c.solid.loading.big":"Loading it anyway…","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","gpui.settings.group.agents":"Agents and tools","gpui.settings.group.general":"General","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","menu.wake":"Wake","model.col.agent":"Agent","native.pair.connect":"Connect","native.thread.model":"Model","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.senderr.remote":"No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","rooms.new":"New room","secret.you":"You","settings.appearance":"Appearance","settings.lang":"Language","settings.lang.auto":"Automatic","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Theme","settings.theme.dark":"Dark","settings.theme.light":"Light","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets","web.settings.providers":"AI providers","web.settings.providers.browser":"Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.new":"Nuevo bot","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.solid.big.next":"Cargarlo puede tardar y usar mucha memoria.","gpui.c.solid.load.big":"Cargarlo de todos modos","gpui.c.solid.loading.big":"Cargándolo de todos modos…","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.short":"Capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.noitems":"Sin corredores ni planos en esta capa","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup.short":"Apilamiento","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","gpui.settings.group.agents":"Agentes y herramientas","gpui.settings.group.general":"General","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","menu.wake":"Despertar","model.col.agent":"Agente","native.pair.connect":"Conectar","native.thread.model":"Modelo","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.senderr.remote":"No hay ningún proveedor de IA conectado en {machine}. Abre Configuración → Cuentas en {machine} para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","rooms.new":"Nueva sala","secret.you":"Tú","settings.appearance":"Apariencia","settings.lang":"Idioma","settings.lang.auto":"Automático","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Tema","settings.theme.dark":"Oscuro","settings.theme.light":"Claro","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes","web.settings.providers":"Proveedores de IA","web.settings.providers.browser":"Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas."},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.new":"新しいボット","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.solid.big.next":"読み込みには時間と多くのメモリがかかることがあります。","gpui.c.solid.load.big":"それでも読み込む","gpui.c.solid.loading.big":"それでも読み込み中…","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.short":"レイヤー","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.noitems":"このレイヤーにコリドーまたはプレーンがありません","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup.short":"スタックアップ","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","gpui.settings.group.agents":"エージェントとツール","gpui.settings.group.general":"一般","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","menu.wake":"再開","model.col.agent":"エージェント","native.pair.connect":"接続","native.thread.model":"モデル","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.senderr.remote":"{machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","rooms.new":"新しいルーム","secret.you":"あなた","settings.appearance":"外観","settings.lang":"言語","settings.lang.auto":"自動","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"テーマ","settings.theme.dark":"ダーク","settings.theme.light":"ライト","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット","web.settings.providers":"AI プロバイダー","web.settings.providers.browser":"Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。"}};function Q(a,t){if(!t)return a;return a.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(s,r)=>Object.prototype.hasOwnProperty.call(t,r)?String(t[r]):s)}var O=te(),W=new Set,V=new Map;for(let[a,t]of Object.entries(U.en||{}))if(typeof t==="string"&&!V.has(t))V.set(t,a);function te(){let a=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(a.startsWith("ja"))return"ja";if(a.startsWith("es"))return"es";return"en"}function Y(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=O}Y();function me(a){return W.add(a),()=>{W.delete(a)}}function ue(a){if(!a)return!1;let t=a.toLowerCase(),s=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!s)return!1;let r=s!==O;if(O=s,Y(),r)for(let d of W)d(O);return r}function c(a,t,s){let d=(U[O]||U.en||{})[a]??U.en?.[a]??t??a;return Q(d,s)}function ge(a){if(!a)return"";let t=V.get(a);if(!t)return a;return c(t,a)}var ae=[[1,26,7,1,[]],[2,44,10,1,[6,18]],[3,70,15,1,[6,22]],[4,100,20,1,[6,26]],[5,134,26,1,[6,30]],[6,172,18,2,[6,34]]],G=new Uint8Array(512),_=new Uint8Array(256);{let a=1;for(let t=0;t<255;t++)if(G[t]=a,_[a]=t,a<<=1,a&256)a^=285;for(let t=255;t<512;t++)G[t]=G[t-255]}function J(a,t){return a===0||t===0?0:G[_[a]+_[t]]}function ne(a){let t=new Uint8Array([1]);for(let s=0;s{let m=e-i*n;return Math.ceil((12+t.length*8)/8)<=m});if(!s)return null;let[r,d,u,f,E]=s,w=d-u*f,g=[],S=(e,i)=>{for(let n=i-1;n>=0;n--)g.push(e>>>n&1)};S(4,4),S(t.length,8);for(let e of t)S(e,8);for(let e=0;e<4&&g.length{if(e<0||i<0||e>=p||i>=p)return;H[e*p+i]=n?1:0,A[e*p+i]=1},N=(e,i)=>{for(let n=-1;n<=7;n++)for(let m=-1;m<=7;m++){let k=e+n,l=i+m,o=n>=0&&n<=6&&m>=0&&m<=6&&(n===0||n===6||m===0||m===6||n>=2&&n<=4&&m>=2&&m<=4);b(k,l,o)}};N(0,0),N(0,p-7),N(p-7,0);for(let e=8;e=1;e-=2){if(e===6)e=5;let i=(e+1&2)===0;for(let n=0;n>>3]>>>7-(j&7)&1,j++;let o=(m+l&1)===0?h^1:h;H[m*p+l]=o}}}let R=30660;for(let e=0;e<=5;e++)b(8,e,(R>>>14-e&1)===1);b(8,7,(R>>>8&1)===1),b(8,8,(R>>>7&1)===1),b(7,8,(R>>>6&1)===1);for(let e=0;e<=5;e++)b(5-e,8,(R>>>5-e&1)===1);for(let e=0;e<8;e++)b(8,p-1-e,(R>>>e&1)===1);for(let e=0;e<7;e++)b(p-7+e,8,(R>>>14-e&1)===1);return{size:p,modules:H}}function X(a){let t=oe(a);if(!t)return null;let s=2,r=t.size+s*2,d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("viewBox",`0 0 ${r} ${r}`),d.setAttribute("role","img"),d.setAttribute("aria-label",`QR code for ${a}`),d.setAttribute("shape-rendering","crispEdges"),d.classList.add("bp-qr-svg");let u=document.createElementNS("http://www.w3.org/2000/svg","rect");u.setAttribute("width",String(r)),u.setAttribute("height",String(r)),u.setAttribute("fill","#ffffff"),d.appendChild(u);let f="";for(let w=0;w{let h=l.trim();if(!h)return;let o=h.startsWith("https://")?h:`https://${h}`;if(!o.startsWith("https://")||o.length<=8)return;let x=document.createElement("div");x.className="bp-pair-addr-meta";let v=document.createElement("div");v.className="bp-pair-code-label",v.textContent=c("ios.hub.address.field","Hub address");let y=document.createElement("code");y.className="bp-pair-addr-url",y.textContent=o,y.setAttribute("data-testid","pair-address");let P=document.createElement("button");P.type="button",P.className="bp-pair-copy";let I=c("common.copy","Copy");P.textContent=I,P.addEventListener("click",()=>{navigator.clipboard?.writeText(o).then(()=>{P.textContent=c("web.clone.copied","Copied"),window.setTimeout(()=>{P.textContent=I},1200)}).catch(()=>{})}),x.append(v,y,P);let z=document.createDocumentFragment();z.appendChild(x);let K=X(o);if(K){let F=document.createElement("div");F.className="bp-pair-qr",F.setAttribute("data-testid","pair-qr"),F.appendChild(K),z.appendChild(F)}p.replaceChildren(z),p.classList.remove("bp-hidden")};fetch("/auth/web/info",{credentials:"same-origin"}).then(async(l)=>{if(!l.ok)return;let h=await l.json();if(typeof h.address==="string")H(h.address)}).catch(()=>{}),t.append(s,u,f,S,C,p),a.appendChild(t);let A=null,b=null,N=null,j=0,D=0,R=150,e=1000;function i(){if(j++,N)N.abort(),N=null;if(A!==null)window.clearTimeout(A),A=null;if(b!==null)window.clearInterval(b),b=null}function n(l="",h=!1){i(),f.classList.remove("bp-hidden"),S.classList.add("bp-hidden"),g.disabled=!1,C.textContent=l,C.className=h?"bp-pair-status bp-bad":"bp-pair-status"}function m(){let l=D-Date.now();if(l<=0){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}B.textContent=c("web.pair.approve.in","Approve on desktop or paired phone · expires in {time}",{time:pe(l)})}async function k(l){if(l!==j)return;if(D>0&&Date.now()>=D){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let h=new AbortController;N=h;try{let o=await fetch("/auth/web/poll",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:"{}",signal:h.signal});if(l!==j)return;if(e=1000,o.status===202){A=window.setTimeout(()=>{k(l)},150);return}if(o.status===200||o.status===204){let v={};if(o.status===200)try{v=await o.json()}catch{}if(l!==j)return;let y=(v.state||v.status||"").toLowerCase();if(o.status===204||v.approved===!0||y==="approved"||y==="ok"){i(),C.textContent=c("web.pair.approved","Approved. Opening Backplane…"),C.className="bp-pair-status bp-ok",window.location.replace("/");return}if(y==="denied"||y==="rejected"){n(c("web.pair.denied","Pairing request was denied."),!0);return}if(y==="expired"){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}A=window.setTimeout(()=>{k(l)},150);return}if(o.status===429){let v=Number(o.headers.get("Retry-After")||"5"),y=Math.max(2000,(Number.isFinite(v)?v:5)*1000);A=window.setTimeout(()=>{k(l)},y);return}if(o.status===401||o.status===403||o.status===404||o.status===410){let v="";try{let y=await o.json();v=(y.state||y.status||y.error||"").toLowerCase()}catch{}if(l!==j)return;if(v==="denied"||v==="rejected"||o.status===403)n(c("web.pair.denied","Pairing request was denied."),!0);else n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let x=e;e=Math.min(1e4,Math.round(e*1.8)),A=window.setTimeout(()=>{k(l)},x)}catch{if(l!==j)return;let o=e;e=Math.min(1e4,Math.round(e*1.8)),A=window.setTimeout(()=>{k(l)},o)}finally{if(N===h)N=null}}L.addEventListener("click",()=>{n(c("web.pair.cancelled","Cancelled."))}),f.addEventListener("submit",async(l)=>{l.preventDefault();let h=w.value.trim()||Z();g.disabled=!0,C.textContent=c("web.pair.requesting","Requesting pairing code…"),C.className="bp-pair-status";try{let o=await fetch("/auth/web/request",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:h})});if(!o.ok){let I=c("web.pair.failed","Pairing request failed ({status})",{status:o.status});try{let z=await o.json();if(z.error)I=z.error}catch{}if(o.status===429)I=c("web.pair.ratelimited","Too many pairing attempts. Wait a moment and try again.");n(I,!0);return}let x=await o.json(),v=x.code||x.checkCode||"";if(!v){n(c("web.pair.nocode","Hub did not return a comparison code."),!0);return}let y=Date.now();D=x.expiresAt?x.expiresAt<10000000000?x.expiresAt*1000:x.expiresAt:y+(x.expiresIn?x.expiresIn*1000:120000),i();let P=j;e=1000,R=x.pollMs&&x.pollMs>=100?x.pollMs:150,M.textContent=re(v),f.classList.add("bp-hidden"),S.classList.remove("bp-hidden"),C.textContent="",m(),b=window.setInterval(m,1000),A=window.setTimeout(()=>{k(P)},R)}catch{n(c("web.pair.unreachable","Could not reach the hub. Check your tailnet connection."),!0)}})}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",ee);else ee(); diff --git a/web/dist/manifest.json b/web/dist/manifest.json index 25e2d45a88..4e5e0e4e91 100644 --- a/web/dist/manifest.json +++ b/web/dist/manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "totalAssetGzipBytes": 219557, + "totalAssetGzipBytes": 220069, "styleTokensSha256": "a4fed1b1c7bc676acc328907343eb5dcf87e426383d05617c632e48c0c3f2b80", "i18nKeys": [ "agy.signout", @@ -33,6 +33,9 @@ "gpui.b.replying.to", "gpui.bots.recall.off", "gpui.bots.recall.on", + "gpui.c.solid.big.next", + "gpui.c.solid.load.big", + "gpui.c.solid.loading.big", "gpui.c.term.collapse", "gpui.c.term.expand", "gpui.commands", @@ -290,7 +293,7 @@ "web.settings.providers", "web.settings.providers.browser" ], - "i18nSubsetSha256": "6cd77cd7f63e03b4e72d44faa754280b501ca4dd1d539c07c919443e92a1d32c", + "i18nSubsetSha256": "6a57c32569a7e901ce73a080de12a870ccf81af34fe7742186d530dc2b808bc4", "inputs": { "web/src/addproject.ts": "06a7ff3e13cd78d993ebca7f638d5d623da06c0099186ad534bae8f184dbe44f", "web/src/app.ts": "1b58e4dcb0aa1890f6ae60b3de713928faea76f083c324362954274600f6495a", @@ -330,7 +333,7 @@ "web/src/viewers/solid3d.ts": "9e82abfe611d41917e70d315cc86047f5a9f99e6cb4df051cdec117078026e21", "web/src/viewers/terminal-state.ts": "316d9c82b63c9d7a73aa3063957b3a2b578ff2ca735a6f32cf290a92cf10ddc2", "web/src/viewers/terminal.ts": "dead59ace15647f726f5d7c4dad0a430fa63c82481c4399f40d17f01e5805099", - "web/src/viewers/viewer-pane.ts": "0021e2ac702c7b4960f685d822b6f3cf4728589b4cca54498556695de7ddb1eb", + "web/src/viewers/viewer-pane.ts": "9a24cd856adf2ce6ca7ec58660bcd8dd1003049d55fc9fe0925c7d6b5585ff14", "web/src/viewers/viewer-tools.ts": "7db4587ad1410cf21364b1121454e0520fd515c82b63916d31a5fdc1443615b4", "web/src/voice.ts": "f401f1d5bd1685c7d7270fc02a8ff16f54bde7ae98aee21b4e802f0357063345", "web/src/ws.ts": "b8d433e2902d91c72563c304bbb8a609e242e4884074399a12f792f0f47db3a4", @@ -353,9 +356,9 @@ }, "outputs": { "assets/app.js": { - "bytes": 387434, - "gzipBytes": 109648, - "sha256": "9472ce7e1d484f0676a00f7a450af77a30aedfa403344cf35748aa1ec1a15a78" + "bytes": 388563, + "gzipBytes": 109984, + "sha256": "a55b7298215fc3e51fef03cfdcd989f2e918f4bf1256faf916314e04dfe657a1" }, "assets/favicon-light.svg": { "bytes": 1207, @@ -373,9 +376,9 @@ "sha256": "123b6a27f255d339b505c8fd83609674f0bddf9b46c0e907fce23befa96b1eec" }, "assets/pair.js": { - "bytes": 55069, - "gzipBytes": 16550, - "sha256": "2091b0df3867fc40b70439d3e2abfaaf86a717eaaa357fb29308e606d0fdc3df" + "bytes": 55633, + "gzipBytes": 16726, + "sha256": "f960233e435ca31cbb87254879bc8d43bf708991da986ee3e10602d084eb32f1" }, "assets/style.css": { "bytes": 90272, diff --git a/web/src/viewers/viewer-pane.ts b/web/src/viewers/viewer-pane.ts index 75df78ff74..cf0111c7ab 100644 --- a/web/src/viewers/viewer-pane.ts +++ b/web/src/viewers/viewer-pane.ts @@ -40,7 +40,7 @@ interface LayersReply { type PendingFrame = | { kind: "bin"; buf: ArrayBuffer } - | { kind: "none"; key: string; none: string; retryable: boolean }; + | { kind: "none"; key: string; none: string; retryable: boolean; big: boolean }; const MAX_PENDING_FRAMES = 64; const MAX_PENDING_BYTES = 16 << 20; @@ -330,7 +330,7 @@ export function mountViewerPane(container: HTMLElement, api: ViewerHostApi): { clearPending(); for (const item of queued) { if (item.kind === "bin") handleBinary(item.buf); - else handlePlotNone(item.key, item.none, item.retryable); + else handlePlotNone(item.key, item.none, item.retryable, item.big); } setBanner( history.highlightEdits @@ -539,7 +539,8 @@ export function mountViewerPane(container: HTMLElement, api: ViewerHostApi): { }); themeObs.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] }); - function setOverlay(mode: "none" | "loading" | "empty" | "error", text = "", retryable = false): void { + // bigKey: a 3D model the hub refused for its size; the card offers "Load it anyway" (kicad.big reads it past the limit) + function setOverlay(mode: "none" | "loading" | "empty" | "error", text = "", retryable = false, bigKey = ""): void { if (mode === "none") { overlayEl.hidden = true; overlayEl.replaceChildren(); @@ -561,6 +562,20 @@ export function mountViewerPane(container: HTMLElement, api: ViewerHostApi): { retryBtn.addEventListener("click", () => void startWatch(true)); card.append(retryBtn); } + if (bigKey) { + const next = document.createElement("div"); + next.className = "bp-v-state-msg"; + next.textContent = t("gpui.c.solid.big.next", "Loading it may take a while and a lot of memory."); + const bigBtn = document.createElement("button"); + bigBtn.type = "button"; + bigBtn.className = "bp-v-btn is-primary"; + bigBtn.textContent = t("gpui.c.solid.load.big", "Load it anyway"); + bigBtn.addEventListener("click", () => { + setOverlay("loading", t("gpui.c.solid.loading.big", "Loading it anyway…")); + void api.hub.rpc("kicad.big", { key: bigKey }).catch(() => setOverlay("error", text, false, bigKey)); + }); + card.append(next, bigBtn); + } overlayEl.replaceChildren(card); } @@ -1043,7 +1058,7 @@ export function mountViewerPane(container: HTMLElement, api: ViewerHostApi): { clearPending(); for (const item of queued) { if (item.kind === "bin") handleBinary(item.buf); - else handlePlotNone(item.key, item.none, item.retryable); + else handlePlotNone(item.key, item.none, item.retryable, item.big); } } catch (err) { if (gen !== watchGen) return; @@ -1056,10 +1071,10 @@ export function mountViewerPane(container: HTMLElement, api: ViewerHostApi): { } } - function handlePlotNone(key: string, none: string, retryable: boolean): void { + function handlePlotNone(key: string, none: string, retryable: boolean, big = false): void { if (watchPending) { if (pendingQueue.length < MAX_PENDING_FRAMES) { - pendingQueue.push({ kind: "none", key, none, retryable }); + pendingQueue.push({ kind: "none", key, none, retryable, big }); } return; } @@ -1073,6 +1088,7 @@ export function mountViewerPane(container: HTMLElement, api: ViewerHostApi): { return; } } + if (big) { setOverlay("error", none, false, key); return; } setOverlay(retryable ? "error" : "empty", none || "Nothing to display", retryable); } @@ -1105,7 +1121,7 @@ export function mountViewerPane(container: HTMLElement, api: ViewerHostApi): { } if (typeof map.none === "string") { - handlePlotNone(key, map.none, map.retryable === 1 || (map.retryable as unknown) === true); + handlePlotNone(key, map.none, map.retryable === 1 || (map.retryable as unknown) === true, (map.big as unknown) === true); return; }