From 1d631adeda7407efc3ac700731140dc8848a2294 Mon Sep 17 00:00:00 2001 From: i2cjak Date: Mon, 23 Nov 2026 02:35:04 -0500 Subject: [PATCH 1/2] Sidebar: crew band, inbox with status labels and snooze, a bench of recent projects (hub, GPUI, Web) Forty projects buried the bots and rooms a screen below the list, and Active held nearly every project. - Crew band above the list, never scrolled: Bub, the bots as one strip, the rooms as #name. - Needs you, Running (every project's, one list) and Snoozed (ThreadSnoozed, folded) as two-line rows: title, then the status as a word (label/tone), the project and the age. No status dots. A stop settles in one press; a row snoozes for 1 hour, tomorrow or a week. - Recent: the eight projects the person was in last (sidebar.visit.), by name; the rest fold into All projects, then Quiet. A hardware project carries a board glyph. Co-Authored-By: Claude Fable 5.2 --- docs/ALWAYS-ON.md | 12 + native/gpui/src/screens/sections.rs | 11 +- native/gpui/src/screens/siderow.rs | 51 ++ native/gpui/src/ui.rs | 122 ++-- native/host/src/data/budget_tests.rs | 4 + native/host/src/present/sections.rs | 128 +++- native/host/src/present/sections_tests.rs | 88 ++- native/host/src/state/policy.rs | 4 +- native/host/src/state/visible.rs | 9 + test/sidebar/d.sh | 2 +- test/sidebar/rig.sh | 8 +- test/sidebar/seed43.py | 52 ++ web/dist/assets/app.js | 36 +- web/dist/assets/pair.js | 2 +- web/dist/assets/style.css | 354 ++++++++- web/dist/manifest.json | 32 +- web/src/app.ts | 18 + web/src/shell.css | 354 ++++++++- web/src/sidebar.ts | 828 +++++++++++++++++----- web/test/sidebar.test.ts | 49 ++ 20 files changed, 1862 insertions(+), 302 deletions(-) create mode 100644 test/sidebar/seed43.py create mode 100644 web/test/sidebar.test.ts diff --git a/docs/ALWAYS-ON.md b/docs/ALWAYS-ON.md index a676912649..649c9699c0 100644 --- a/docs/ALWAYS-ON.md +++ b/docs/ALWAYS-ON.md @@ -171,6 +171,18 @@ Setup's sub-step shows each row as Signed in / Sign in there / Not on that machi A setting, off by default (Settings, Appearance, "Group projects", `sidebar.groups`): off, the rest stays in Active, newest first, and only a group the person made (Move to group, New group…) is a section. 6. **Quiet:** nothing for 2 weeks; auto-collapsed, never deleted, searchable. +- **D12, revised Nov 23 (the crew band, the inbox, the bench):** with forty projects the bots and rooms were a screen below the list, and + "Active" held nearly every project. Now, top to bottom: + 1. **The crew band**, above the list and never scrolled with it: Bub, the bots as one strip of cats (name and note under the pointer, a red + mark on one that waits), the rooms as `#name`, each with its `+`. + 2. **Needs you**, then **Running** (every project's running threads in one list, not repeated under their projects), then **Snoozed** + (folded; `ThreadSnoozed`, the row's clock offers 1 hour, Tomorrow, 1 week; an open ask is never snoozed away). A row is two lines: its + title, then its status as a word (`label`, `tone`: Approve, Input, Sign in, Failed, Stopped, Working, Waiting, Done), its project and its + age. No status dots: a word reads at a glance. A stop settles in one press (`settle`). + 3. **Pinned** projects, then **Recent**: the eight projects the person was in last (`sidebar.visit.`, written when a thread or the + project's page is opened, at most once in ten minutes; never visited: by last activity), so a board reopened daily stays at hand with no + agent activity and a merged software project sinks by itself. A hardware project (KiCad files) carries a board glyph (`hasBoard`). + 4. **All projects** (the rest, by name, one folded line), then **Quiet**. - **A project's page:** running, then needs you, then recent, with done threads behind "Done (n)". - **Ctrl+K** jumps to any project or thread on any machine (registry-backed). - Same on GPUI, iOS and Android: the hub presents it (present/screen.rs sections), the clients draw sections generically. diff --git a/native/gpui/src/screens/sections.rs b/native/gpui/src/screens/sections.rs index 7dfb3fa03d..1795fdb9b6 100644 --- a/native/gpui/src/screens/sections.rs +++ b/native/gpui/src/screens/sections.rs @@ -97,11 +97,15 @@ fn project(this: &Backplane, cx: &mut Context, light: bool, p: &Value .child(twisty) .child(crate::screens::badge::mark(light, p)) .child(div().flex_1().min_w_0().overflow_hidden().whitespace_nowrap().text_ellipsis().child(string(p, "title"))) + // a hardware project (a board or schematic in it): a faint board glyph, so the bench reads hardware and software apart at a glance + .children((p["hasBoard"] == true).then(|| crate::art::icon("circuit-board", 12., c("faint")))) .children((!dots.is_empty()).then(|| div().flex().gap_1().items_center().children(dots))) // its threads with no row here (finished ones): a faint count, so none seems lost; they are on its page .children((rest > 0).then(|| crate::ui::with_rect(div().id(SharedString::from(format!("prest-{pid}"))), { let p = pid.clone(); move || format!("project-rest:{p}") }).text_size(crate::scale::tpx(11.)).text_color(c("faint")) .tooltip(crate::keys::tip_raw(&tf("gpui.sections.rest", &[("n", rest.into())]), "", light)).child(rest.to_string()))) - .children((running > 0).then(|| div().text_size(crate::scale::tpx(11.)).text_color(c("accent")).child(tf("gpui.sections.running", &[("n", running.into())])))) + // what of it runs (its rows are in Running): a count in the running colour, outlined as the Working label is + .children((running > 0).then(|| div().id(SharedString::from(format!("prun-{pid}"))).px(px(4.)).h(px(16.)).flex().items_center().border_1().border_color(c("accent")).text_size(crate::scale::tpx(10.)).text_color(c("accent")) + .tooltip(crate::keys::tip_raw(&tf("gpui.sections.running", &[("n", running.into())]), "", light)).child(running.to_string()))) // what of it waits on the person (its rows are in Needs you, folded or not) .children((needs_n > 0).then(|| div().px(px(5.)).h(px(16.)).flex().items_center().bg(c("bad")).text_size(crate::scale::tpx(10.)).text_color(c("bg")).child(needs_n.to_string()))) .when(pinned, |d| d.child(crate::ui::ic(light, "pin", 12., "dim"))) @@ -144,7 +148,10 @@ impl Backplane { // no project name after the title: the sidebar is narrow and the title is what the person reads (sub " ": an Active-view row, so no tree chevron and no drag) // a stop says so by its dot alone (the right column is the title's); an ask keeps its red word (approval, question) let mut t = t.clone(); if matches!(t["want"].as_str(), Some("failed" | "stopped")) { t["want"] = serde_json::json!(""); } - rows.push(self.side_thread(cx, light, &t, "", " ", t["off"] == true, ctl)); + // Running lists every project's work in one place, so each row names its project (faint, after the title) + let sub = string(&t, "project"); + if t["settle"].as_str().map_or(false, |v| !v.is_empty()) { let v = string(&t, "settle"); ctl.push(CtlEntry { id: format!("settle:{}", v.rsplit('|').next().unwrap_or("")), label: "Settle".into() /* i18n-ok: a ctl label */, ctl: Ctl::Node("row-settle".into(), v) }); } + rows.push(self.side_thread(cx, light, &t, "", if sub.is_empty() { " " } else { &sub }, t["off"] == true, ctl)); } } _ => { diff --git a/native/gpui/src/screens/siderow.rs b/native/gpui/src/screens/siderow.rs index 06194d6a46..22332ce9a5 100644 --- a/native/gpui/src/screens/siderow.rs +++ b/native/gpui/src/screens/siderow.rs @@ -117,6 +117,57 @@ pub fn pin_button_as(cx: &mut Context, light: bool, t: &Value, group: .into_any_element() } +/// A row's status label (the hub's `label` and `tone`): a short word in its tone's colour, filled when it asks the person (Approve, Input, +/// Sign in), outlined otherwise. Read at a glance where a 6 px dot was not. `None` for a row with nothing to say. +pub struct Pill { text: String, token: &'static str, filled: bool, light: bool } +pub fn pill(light: bool, t: &Value) -> Option { + let text = string(t, "label"); if text.is_empty() { return None } + let token = pill_token(t["tone"].as_str().unwrap_or("")); + Some(Pill { filled: t["word"] == "needs", text, token, light }) +} +/// The colour token of a label's tone. +pub fn pill_token(tone: &str) -> &'static str { match tone { "bad" => "bad", "run" => "accent", "wait" => "waiting", "ok" => "ok", _ => "dim" } } +pub trait PillEl { fn clone_el(&self) -> Option; } +impl PillEl for Option { + fn clone_el(&self) -> Option { + let p = self.as_ref()?; let col = theme::color(p.light, p.token); + Some(div().flex_shrink_0().h(px(15.)).px(px(4.)).flex().items_center().text_size(crate::scale::tpx(10.)).line_height(px(13.)).border_1().border_color(col) + .when(p.filled, |d| d.bg(col).text_color(theme::color(p.light, "bg"))).when(!p.filled, |d| d.text_color(col)) + .child(crate::i18n::trs(&p.text)).into_any_element()) + } +} +/// Snooze, under the pointer: a clock that opens the hub's spans (`snooze`: 1 hour, Tomorrow, 1 week); on a snoozed row (`wake`) it wakes it in +/// one press. None for a row that can do neither. +pub fn snooze_button(cx: &mut Context, light: bool, t: &Value, group: SharedString) -> Option { + let (wake, opts) = (string(t, "wake"), t["snooze"].as_array().cloned().unwrap_or_default()); + if wake.is_empty() && opts.is_empty() { return None } + let c = |n: &str| theme::color(light, n); + let id = string(t, "id"); let raw = id.rsplit('|').next().unwrap_or("").to_string(); + /* i18n-ok: the menu's words, drawn through trs */ let tip = crate::i18n::trs(if wake.is_empty() { "Snooze" } else { "Wake" }); + Some(crate::ui::with_rect(div().id(SharedString::from(format!("snooze-{id}"))), move || format!("snooze:{raw}")).flex_shrink_0().w(px(16.)).h(px(16.)).flex().items_center().justify_center().cursor_pointer() + .invisible().group_hover(group, |s| s.visible()).hover(|s| s.bg(c("line"))) + .tooltip(crate::keys::tip(&tip, "", light)) + .child(crate::art::icon(if wake.is_empty() { "clock" } else { "bell" }, 12., c("dim"))) + .on_click(cx.listener(move |this, e: &ClickEvent, _, cx| { cx.stop_propagation(); + if !wake.is_empty() { let _ = this.tx.try_send(Command::Action("row-snooze".into(), wake.clone())); cx.notify(); return } + /* i18n-ok: menu labels, drawn through trs */ let items = opts.iter().map(|o| crate::screens::ctxmenu::Item { label: format!("Snooze {}", string(o, "label").to_lowercase()), action: "row-snooze".into(), value: string(o, "value"), confirm: false, note: String::new() }).collect(); + this.ctx_open(e.position(), items, cx); })) + .into_any_element()) +} + +/// Settle in one press: a check on a row the hub says can be settled (`settle`: its id), shown under the pointer. None for any other row. +pub fn settle_button(cx: &mut Context, light: bool, t: &Value, group: SharedString) -> Option { + let value = string(t, "settle"); if value.is_empty() { return None } + let c = |n: &str| theme::color(light, n); + let raw = value.rsplit('|').next().unwrap_or("").to_string(); + Some(crate::ui::with_rect(div().id(SharedString::from(format!("settle-{value}"))), move || format!("settle:{raw}")).flex_shrink_0().w(px(16.)).h(px(16.)).flex().items_center().justify_center().cursor_pointer() + .invisible().group_hover(group, |s| s.visible()).hover(|s| s.bg(c("line"))) + /* i18n-ok: the context menu's word, drawn through trs */ .tooltip(crate::keys::tip(&crate::i18n::trs("Settle"), "", light)) + .child(crate::art::icon("check", 12., c("dim"))) + .on_click(cx.listener(move |this, _, _, cx| { let _ = this.tx.try_send(Command::Action("row-settle".into(), value.clone())); cx.stop_propagation(); cx.notify(); })) + .into_any_element()) +} + pub fn strip_projects(data: &Value) -> Vec<(String, String, &Value)> { data["projects"].as_array().into_iter().flatten().map(|p| { let id = string(p, "id"); (id.rsplit('|').next().unwrap_or("").to_string(), string(p, "title"), p) }).filter(|(id, _, _)| !id.is_empty()).collect() } diff --git a/native/gpui/src/ui.rs b/native/gpui/src/ui.rs index d6fce1a720..afc62c513e 100644 --- a/native/gpui/src/ui.rs +++ b/native/gpui/src/ui.rs @@ -1,4 +1,5 @@ //! The window: layout and colours follow the web client (src/web/style.css tokens). +use crate::screens::siderow::PillEl; use crate::script::{Ctl, CtlEntry}; use crate::{art, hub::Command, string, theme, Backplane, Send}; use crate::i18n::{tf, trs}; @@ -373,8 +374,17 @@ impl Backplane { /* i18n-ok: a ctl label */ if kids > 0 && tree { ctl.push(CtlEntry { id: format!("tree:{raw}"), label: format!("{} subthreads", kids), ctl: Ctl::Node("thread-tree".into(), format!("{id}|{}", if open { 0 } else { 1 })) }); } let pin_group = SharedString::from(format!("row-{id}")); let pin = crate::screens::siderow::pin_button(cx, light, t, pin_group.clone()); + // the hub's status label (`label`, `tone`): drawn as a word where the dot was. A row of the lists across projects (Needs you, Running, + // Snoozed: `sub`) has two lines: its title, then its label, its project and its age + let pill = crate::screens::siderow::pill(light, t); + let labelled = t["label"].is_string(); + let inbox = labelled && !sub.is_empty(); + let gutter = if inbox { 10. } else { gutter }; + { let (snz, wake) = (&t["snooze"], string(t, "wake")); + if !wake.is_empty() { ctl.push(CtlEntry { id: format!("wake:{raw}"), label: "Wake".into() /* i18n-ok: a ctl label */, ctl: Ctl::Node("row-snooze".into(), wake) }); } + for o in snz.as_array().into_iter().flatten() { ctl.push(CtlEntry { id: format!("snooze:{raw}:{}", string(o, "label")), label: format!("Snooze {}", string(o, "label")) /* i18n-ok: a ctl label */, ctl: Ctl::Node("row-snooze".into(), string(o, "value")) }); } } { let (action, value) = crate::screens::siderow::pin_press(t); ctl.push(CtlEntry { id: format!("pin:{raw}"), label: action.into(), ctl: Ctl::Node(action.into(), value) }); } - with_rect(div().id(SharedString::from(format!("thread-{id}"))), || format!("thread:{raw}")).group(pin_group).flex().items_center().gap_2().pr_3().h(crate::scale::tpx(32.)).when(faded || t["off"] == true, |d| d.opacity(0.55)) + with_rect(div().id(SharedString::from(format!("thread-{id}"))), || format!("thread:{raw}")).group(pin_group).relative().flex().items_center().gap_2().pr_3().h(crate::scale::tpx(if inbox { 42. } else { 32. })).when(faded || t["off"] == true, |d| d.opacity(0.55)) // a row under its project: no bar and no block when open (the person, 2026-11-15); its L says where it is .border_l_2().border_color(if selected && !under { c("accent") } else { transparent_black().into() }) .bg(if selected && !under { c("raise") } else { transparent_black().into() }).hover(|s| s.bg(c("raise"))).cursor_pointer() @@ -387,14 +397,29 @@ impl Backplane { // as the project's own; the open one's L a shade brighter .child(toggle.map_or_else(|| div().w(px(gutter)).h_full().flex_shrink_0().relative().when(under, |d| { let l = c(if selected { "dim" } else { "line" }); d.child(div().absolute().left(px(36.)).top_0().w(px(1.)).h(relative(0.5)).bg(l)) - .child(div().absolute().left(px(36.)).top(relative(0.5)).w(px(11.)).h(px(1.)).bg(l)) }).into_any_element(), |t| t.into_any_element())).child(crate::screens::siderow::dot(light, t)).child(if crate::screens::siderow::renaming(&self.data, &id, "thread") { crate::screens::siderow::field(light, &self.screens.fields, &id) } else { div().flex_1().min_w_0().overflow_hidden().whitespace_nowrap().flex().gap_2().relative().child(div().min_w_0().overflow_hidden().text_ellipsis().child(string(t, "title"))).children((!sub.is_empty()).then(|| div().flex_shrink_0().max_w(px(80.)).overflow_hidden().text_ellipsis().text_size(crate::scale::tpx(11.)).text_color(c("faint")).child(sub.to_string()))) + .child(div().absolute().left(px(36.)).top(relative(0.5)).w(px(11.)).h(px(1.)).bg(l)) }).into_any_element(), |t| t.into_any_element())).children((!labelled).then(|| crate::screens::siderow::dot(light, t))).child(if crate::screens::siderow::renaming(&self.data, &id, "thread") { crate::screens::siderow::field(light, &self.screens.fields, &id) } else if inbox { + let (proj, ago) = (sub.trim().to_string(), trs(&string(t, "ago"))); + div().flex_1().min_w_0().flex().flex_col().justify_center().gap(px(1.)).relative() + .child(div().w_full().overflow_hidden().whitespace_nowrap().text_ellipsis().line_height(crate::scale::tpx(18.)).child(string(t, "title"))) + .child(div().flex().items_center().gap(px(6.)).min_w_0().overflow_hidden().whitespace_nowrap().text_size(crate::scale::tpx(11.)).line_height(crate::scale::tpx(16.)).text_color(c("faint")) + .children(pill.clone_el()) + .children((!proj.is_empty()).then(|| div().min_w_0().overflow_hidden().text_ellipsis().text_color(c("dim")).child(proj))) + .child(div().flex_shrink_0().child(ago))) + .children(crate::screens::hints::digit_of(&self.screens.hold_threads, &id).map(|n| crate::screens::hints::over_end(crate::screens::hints::digit(light, n)))).into_any_element() + } else { div().flex_1().min_w_0().overflow_hidden().whitespace_nowrap().flex().gap_2().relative().child(div().min_w_0().overflow_hidden().text_ellipsis().child(string(t, "title"))).children((!sub.is_empty()).then(|| div().flex_shrink_0().max_w(px(80.)).overflow_hidden().text_ellipsis().text_size(crate::scale::tpx(11.)).text_color(c("faint")).child(sub.to_string()))) // held Ctrl: this row's Ctrl+digit; held Alt, in the Active view: its project's Alt+digit; over the title's end, so nothing moves (screens/hints.rs) .children(crate::screens::hints::digit_of(&self.screens.hold_threads, &id).or_else(|| (!sub.is_empty()).then(|| crate::screens::hints::digit_of(&self.screens.hold_projects, pid)).flatten()).map(|n| crate::screens::hints::over_end(crate::screens::hints::digit(light, n)))).into_any_element() }) - .child(pin) // the pin: always on a pinned row, on hover on the others + .children(crate::screens::siderow::settle_button(cx, light, t, SharedString::from(format!("row-{id}")))) // Settle in one press, under the pointer (the hub's `settle`: a stop that asks nothing) + // under the pointer: Snooze (a span from its menu; Wake on a snoozed row), Settle in one press (the hub's `settle`: a stop that asks + // nothing), the pin (always on a pinned row). On a two-line row they lie over the title's end, so they take no width from it + .child({ let g = SharedString::from(format!("row-{id}")); + let acts = div().flex().items_center().gap_1().children(crate::screens::siderow::snooze_button(cx, light, t, g.clone())).children(crate::screens::siderow::settle_button(cx, light, t, g.clone())).child(pin); + if inbox { let raise = c("raise"); acts.absolute().right(px(8.)).top(px(4.)).px(px(2.)).group_hover(g, move |s| s.bg(raise)) } else { acts.flex_shrink_0() } }) .children(crate::screens::badge::machine_mark(light, &t["mark"], false, &id)) // (another machine's thread: its name, dim; none for this machine's) - .child({ let want = string(t, "want"); // a red row says what it wants where its age goes (0.14 Side.want, r01) + .children((labelled && !inbox).then(|| pill.clone_el()).flatten()) // under its project: the label before its age + .children((!inbox).then(|| { let want = if labelled { String::new() } else { string(t, "want") }; // a red row says what it wants where its age goes (0.14 Side.want, r01); the label says it now if want.is_empty() { div().text_size(crate::scale::tpx(11.)).text_color(c("faint")).child(if kids > 0 && !under && string(t, "agents").is_empty() { format!("{kids}") } else { trs(&string(t, "ago")) }) } - else { div().text_size(crate::scale::tpx(11.)).text_color(c(if want == "failed" { "dim" } else { "bad" })).child(trs(&want)) } }).into_any_element() + else { div().text_size(crate::scale::tpx(11.)).text_color(c(if want == "failed" { "dim" } else { "bad" })).child(trs(&want)) } })).into_any_element() } } @@ -581,15 +606,59 @@ impl Backplane { // always on: listening is shown at the top of the sidebar whenever it is on if let Some(r) = crate::screens::voice::always_row(cx, light, &self.screens.voice, self.screens.voice.always_wanted) { rows.push(r); } let mut ctl: Vec = Vec::new(); + // the crew band (Bub, the bots in one strip, the rooms as chips): above the list and never scrolled with it, so forty projects cannot bury it + let mut crew: Vec = Vec::new(); for ((bname, mood, note, _, bid, bsel), rig) in uber_data.iter().zip(uber_rigs.iter()) { let note_color = match mood.as_str() { "wait" | "error" => c("bad"), "work" | "talk" => c("accent"), _ => c("faint") }; ctl.push(CtlEntry { id: format!("bot:{bname}"), label: bname.clone(), ctl: Ctl::Node("bot".into(), bid.clone()) }); let bid2 = bid.clone(); - rows.push(with_rect(div().id(SharedString::from(format!("bot-{bid}"))), || format!("bot:{bname}")).flex().items_center().gap_3().px_3().py(px(10.)).border_b_1().border_color(c("line")).cursor_pointer().when(*bsel, |d| d.bg(c("raise"))).hover(|s| s.bg(c("raise"))) + crew.push(with_rect(div().id(SharedString::from(format!("bot-{bid}"))), || format!("bot:{bname}")).flex().items_center().gap_2().px_3().h(px(44.)).border_l_2().border_color(if *bsel { c("accent") } else { transparent_black().into() }).cursor_pointer().when(*bsel, |d| d.bg(c("raise"))).hover(|s| s.bg(c("raise"))) .on_click(cx.listener(move |this, _, _, cx| this.go("bot", bid2.clone(), cx))) - .child(art::cat(rig.clone(), mood, 56., started, if art::rects_on() { format!("cat:{bname}") } else { String::new() })) - .child(div().flex().flex_col().min_w_0().line_height(crate::scale::tpx(22.)).child(div().text_size(crate::scale::tpx(16.)).overflow_hidden().whitespace_nowrap().child(bname.clone())) - .child(div().flex().gap_2().items_center().child(div().text_size(crate::scale::tpx(11.)).text_color(note_color).child(trs(note))).children(marks.get(bid).and_then(|m| crate::screens::badge::machine_mark(light, m, false, bid))))).into_any_element()); + .child(art::cat(rig.clone(), mood, 36., started, if art::rects_on() { format!("cat:{bname}") } else { String::new() })) + .child(div().flex_shrink_0().text_size(crate::scale::tpx(14.)).whitespace_nowrap().child(bname.clone())) + .child(div().flex_1().min_w_0().overflow_hidden().whitespace_nowrap().text_ellipsis().text_size(crate::scale::tpx(11.)).text_color(note_color).child(trs(note))) + .children(marks.get(bid).and_then(|m| crate::screens::badge::machine_mark(light, m, false, bid))).into_any_element()); + } + { + // the bots: one strip of cats (a bot's name and what it does under the pointer; a red mark on one that waits or failed), then + + let mut strip: Vec = Vec::new(); + for ((bname, mood, note, _, bid, bsel), rig) in bot_data.iter().zip(bot_rigs.iter()) { + ctl.push(CtlEntry { id: format!("bot:{bname}"), label: bname.clone(), ctl: Ctl::Node("bot".into(), bid.clone()) }); + let bid2 = bid.clone(); + let wants = matches!(mood.as_str(), "wait" | "error"); let busy = matches!(mood.as_str(), "work" | "talk"); + /* i18n-ok: a name and a note already translated */ let tip = if note.is_empty() { bname.clone() } else { format!("{bname} · {}", trs(note)) }; + strip.push(with_rect(div().id(SharedString::from(format!("bot-{bid}"))), || format!("bot:{bname}")).relative().flex_shrink_0().size(px(32.)).flex().items_center().justify_center().cursor_pointer() + .border_b_2().border_color(if *bsel { c("accent") } else if wants { c("bad") } else if busy { c("accent") } else { transparent_black().into() }) + .when(*bsel, |d| d.bg(c("raise"))).hover(|s| s.bg(c("raise"))) + .tooltip(crate::keys::tip_raw(&tip, "", light)) + .on_click(cx.listener(move |this, _, _, cx| this.go("bot", bid2.clone(), cx))) + .when_some(row_menus.get(bid).cloned(), |d, menu| d.on_mouse_down(MouseButton::Right, cx.listener(move |this, e: &MouseDownEvent, _, cx| { let items = crate::screens::ctxmenu::section_items(&menu); if !items.is_empty() { this.ctx_open(e.position, items, cx); } }))) + .child(art::cat(rig.clone(), mood, 26., started, if art::rects_on() { format!("cat:{bname}") } else { String::new() })) + .children(wants.then(|| div().absolute().top(px(2.)).right(px(2.)).size(px(6.)).bg(c("bad")))) + .children(marks.get(bid).map(|_| div().absolute().bottom(px(3.)).right(px(2.)).size(px(5.)).rounded_full().bg(c("dim")))).into_any_element()); + } + /* i18n-ok: ui: ids the drivers press */ ctl.push(CtlEntry { id: "ui:New bot".into(), label: "New bot".into(), ctl: Ctl::Node("bot-new".into(), String::new()) }); + /* i18n-ok: a ui: id the drivers press */ strip.push(with_rect(div().id("ui:New bot"), || "ui:New bot".to_string()).flex_shrink_0().size(px(32.)).flex().items_center().justify_center().cursor_pointer().hover(|s| s.bg(c("raise"))).tooltip(crate::keys::tip("New bot", "", light)) + .on_click(cx.listener(|this, _, _, cx| { let _ = this.tx.try_send(Command::Action("bot-new".into(), String::new())); cx.notify(); })).child(ic(light, "plus", 14., "dim")).into_any_element()); + crew.push(div().id("crew-bots").flex().flex_wrap().items_center().px(px(6.)).children(strip).into_any_element()); + // the rooms: chips (#name and its members), wrapping, three lines at most (the rest scroll within the band), then + + let mut chips: Vec = Vec::new(); + for r in self.data["rooms"].as_array().into_iter().flatten() { + let (rid, rname, sel) = (string(r, "id"), string(r, "name"), r["sel"].as_bool().unwrap_or(false)); + ctl.push(CtlEntry { id: format!("room:{rname}"), label: rname.clone(), ctl: Ctl::Node("room".into(), rid.clone()) }); + let rid2 = rid.clone(); + chips.push(with_rect(div().id(SharedString::from(format!("room-{rid}"))), || format!("room:{rname}")).flex_shrink_0().max_w(px(150.)).h(px(22.)).px(px(5.)).flex().items_center().cursor_pointer().text_size(crate::scale::tpx(12.)) + .border_b_1().border_color(if sel { c("accent") } else { transparent_black().into() }).when(sel, |d| d.bg(c("raise"))).hover(|s| s.bg(c("raise"))) + /* i18n-ok: a room name and a count */ .tooltip(crate::keys::tip_raw(&format!("#{rname} · {}", r["members"]), "", light)) + .on_click(cx.listener(move |this, _, _, cx| this.go("room", rid2.clone(), cx))) + .when_some(row_menus.get(&rid).cloned(), |d, menu| d.on_mouse_down(MouseButton::Right, cx.listener(move |this, e: &MouseDownEvent, _, cx| { let items = crate::screens::ctxmenu::section_items(&menu); if !items.is_empty() { this.ctx_open(e.position, items, cx); } }))) + .child(div().text_color(c("faint")).child("#")).child(div().min_w_0().overflow_hidden().whitespace_nowrap().text_ellipsis().text_color(if sel { c("text") } else { c("dim") }).child(rname.clone())) + .children(crate::screens::badge::machine_mark(light, &r["mark"], false, &rid)).into_any_element()); + } + /* i18n-ok: ui: ids the drivers press */ ctl.push(CtlEntry { id: "ui:New room".into(), label: "New room".into(), ctl: Ctl::Node("room-new".into(), String::new()) }); + /* i18n-ok: a ui: id the drivers press */ chips.push(with_rect(div().id("ui:New room"), || "ui:New room".to_string()).flex_shrink_0().h(px(22.)).px(px(4.)).flex().items_center().gap_1().cursor_pointer().text_size(crate::scale::tpx(12.)).text_color(c("faint")).hover(|s| s.bg(c("raise"))).tooltip(crate::keys::tip("New room", "", light)) + .on_click(cx.listener(|this, _, _, cx| { let _ = this.tx.try_send(Command::Action("room-new".into(), String::new())); cx.notify(); })).child(ic(light, "plus", 14., "dim")).into_any_element()); + crew.push(div().id("crew-rooms").flex().flex_wrap().items_center().px(px(7.)).pb(px(6.)).max_h(px(3. * 22. + 6.)).overflow_y_scroll().children(chips).into_any_element()); } if let Some((line, bad)) = home_away_line(&self.data["home"]) { rows.push(div().id("home-away-row").px_3().py_1().border_b_1().border_color(c("line")).bg(c("panel")).text_size(crate::scale::tpx(11.)).text_color(if bad { c("bad") } else { c("dim") }).child(line).into_any_element()); @@ -697,39 +766,10 @@ impl Backplane { .child(ic(light, if open { "chevron-down" } else { "chevron-right" }, 14., "dim")).child(tf(if open { "gpui.b.older.open" } else { "gpui.b.older" }, &[("n", n.into())])) .on_click(cx.listener(|this, _, _, cx| { let _ = this.tx.try_send(Command::Action("side-older".into(), String::new())); cx.notify(); })).into_any_element()); } - /* i18n-ok: compared below; drawn through trs */ for name in ["BOTS", "ROOMS"] { - /* i18n-ok: ui: ids */ let (plus_id, plus_action) = if name == "BOTS" { ("ui:New bot", "bot-new") } else { ("ui:New room", "room-new") }; - ctl.push(CtlEntry { id: plus_id.into(), label: plus_id.trim_start_matches("ui:").into(), ctl: Ctl::Node(plus_action.into(), String::new()) }); - rows.push(div().flex().justify_between().px_3().pt_4().text_size(crate::scale::tpx(11.)).text_color(c("dim")).child(trs(name)) - .child(with_rect(div().id(plus_id), || plus_id.to_string()).cursor_pointer().on_click(cx.listener(move |this, _, _, cx| { let _ = this.tx.try_send(Command::Action(plus_action.into(), String::new())); cx.notify(); })).child(ic(light, "plus", 16., "dim"))).into_any_element()); - if name == "BOTS" { - for ((bname, mood, note, _, bid, bsel), rig) in bot_data.iter().zip(bot_rigs.iter()) { - let note_color = match mood.as_str() { "wait" | "error" => c("bad"), "work" | "talk" => c("accent"), _ => c("faint") }; - ctl.push(CtlEntry { id: format!("bot:{bname}"), label: bname.clone(), ctl: Ctl::Node("bot".into(), bid.clone()) }); - let bid2 = bid.clone(); - rows.push(with_rect(div().id(SharedString::from(format!("bot-{bid}"))), || format!("bot:{bname}")).flex().items_center().gap_2().px_3().py(px(3.)).cursor_pointer().when(*bsel, |d| d.bg(c("raise"))).hover(|s| s.bg(c("raise"))) - .on_click(cx.listener(move |this, _, _, cx| this.go("bot", bid2.clone(), cx))) - .when_some(row_menus.get(bid).cloned(), |d, menu| d.on_mouse_down(MouseButton::Right, cx.listener(move |this, e: &MouseDownEvent, _, cx| { let items = crate::screens::ctxmenu::section_items(&menu); if !items.is_empty() { this.ctx_open(e.position, items, cx); } }))) - .child(art::cat(rig.clone(), mood, 28., started, if art::rects_on() { format!("cat:{bname}") } else { String::new() })) - .child(div().flex().flex_col().min_w_0().line_height(crate::scale::tpx(18.)).child(div().overflow_hidden().whitespace_nowrap().child(bname.clone())) - .child(div().flex().gap_2().items_center().child(div().text_size(crate::scale::tpx(11.)).text_color(note_color).child(trs(note))).children(marks.get(bid).and_then(|m| crate::screens::badge::machine_mark(light, m, false, bid))))).into_any_element()); - } - } else { - for r in self.data["rooms"].as_array().into_iter().flatten() { - let (rid, rname, sel) = (string(r, "id"), string(r, "name"), r["sel"].as_bool().unwrap_or(false)); - ctl.push(CtlEntry { id: format!("room:{rname}"), label: rname.clone(), ctl: Ctl::Node("room".into(), rid.clone()) }); - let rid2 = rid.clone(); - rows.push(with_rect(div().id(SharedString::from(format!("room-{rid}"))), || format!("room:{rname}")).flex().items_center().gap_2().px_3().py_1().cursor_pointer().when(sel, |d| d.bg(c("raise"))).hover(|s| s.bg(c("raise"))) - .on_click(cx.listener(move |this, _, _, cx| this.go("room", rid2.clone(), cx))) - .when_some(row_menus.get(&rid).cloned(), |d, menu| d.on_mouse_down(MouseButton::Right, cx.listener(move |this, e: &MouseDownEvent, _, cx| { let items = crate::screens::ctxmenu::section_items(&menu); if !items.is_empty() { this.ctx_open(e.position, items, cx); } }))) - .child(div().text_color(c("faint")).child("#")).child(div().flex_1().overflow_hidden().whitespace_nowrap().child(rname.clone())) - .children(crate::screens::badge::machine_mark(light, &r["mark"], false, &rid)) - .child(div().text_size(crate::scale::tpx(11.)).text_color(c("faint")).child(format!("{}", r["members"]))).into_any_element()); - } - } - } self.screens.parts.side_ctl = ctl; - /* i18n-ok: a key context */ div().id("sidebar").size_full().overflow_y_scroll().track_focus(&self.screens.side_focus).key_context("Sidebar").children(rows).into_any_element() + /* i18n-ok: a key context */ div().id("sidebar").size_full().flex().flex_col().track_focus(&self.screens.side_focus).key_context("Sidebar") + .child(div().id("crew").flex_none().flex().flex_col().border_b_1().border_color(c("line")).children(crew)) + .child(div().id("sidebar-list").flex_1().min_h_0().overflow_y_scroll().pb_3().children(rows)).into_any_element() } /// The viewer's page, a part of the window (part.rs): a board or schematic is drawn again only when the page itself changed, not for /// a hover in the sidebar or the caret's blink. diff --git a/native/host/src/data/budget_tests.rs b/native/host/src/data/budget_tests.rs index f366890f5b..de85332bfc 100644 --- a/native/host/src/data/budget_tests.rs +++ b/native/host/src/data/budget_tests.rs @@ -21,6 +21,10 @@ fn home_log() -> String { line(json!({"$":"MessagePosted","thread":th,"msg":format!("m{t}-{i}a"),"role":"assistant","text":format!("Step {i}: the 3V3 rail is routed, DRC reports no errors, and the decoupling capacitors sit next to their pins."),"at":at})); at += 1; } } + // the person was in t000's and t001's projects just now (present/sections.rs `bench_rank`): opening their threads here is no new visit, so going + // between them changes nothing of the sidebar (a first visit moves a project onto the bench, once) + { let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()); + for p in ["p0", "p1"] { line(json!({"$":"SettingSet","key":format!("sidebar.visit.{p}"),"value":now.to_string(),"at":at})); at += 1; } } line(json!({"$":"AskOpened","id":"q81","thread":"t002","kind":"approval","tool":"Bash","detail":"make flash","options":"","at":at})); at += 1; line(json!({"$":"AskOpened","id":"q82","thread":"t003","kind":"approval","tool":"Bash","detail":"make flash","options":"","at":at})); l diff --git a/native/host/src/present/sections.rs b/native/host/src/present/sections.rs index 6a1c03118c..bf7b8314af 100644 --- a/native/host/src/present/sections.rs +++ b/native/host/src/present/sections.rs @@ -5,7 +5,10 @@ //! a sign-in), or stopped abnormally (failed, interrupted, cut by a restart or held by a usage limit) until the person looks at it or settles it. //! A pinned thread always shows. Everything else is reachable from the project page and Ctrl+K (`jump`), never from the sidebar. //! -//! D12, the order: Bub; Needs you (every machine, gone when empty); Pinned projects; Active (a visible thread or activity in the last +//! D12 as revised 2026-11-23 (docs/ALWAYS-ON.md): Bub; Needs you; Running (every project's, one list); Snoozed (folded); Pinned projects; Recent (id +//! `active`: the BENCH projects the person was in last, `sidebar.visit.`); the person's groups; All projects (the rest, folded); Quiet. +//! Every thread row says its status as a word (`label`, `tone`), can be snoozed (`snooze`) and, stopped, settled in one press (`settle`). +//! Before that: Bub; Needs you (every machine, gone when empty); Pinned projects; Active (a visible thread or activity in the last //! ACTIVE days, newest first); Groups (the rest, by git owner then folder, named by Haiku or the person, folded by default); Quiet (nothing for //! QUIET, folded, never deleted, searchable); Archived (the projects the person put away, folded, last). The automatic groups are a setting, off by default (`sidebar.groups`, `groups_on`): without them //! the rest stays in Active, and only a group the person made is a section. @@ -28,6 +31,8 @@ const UNDER: usize = 8; /// rows of the project page's Recent and Done lists, and of the Ctrl+K list const PAGE: usize = 60; const JUMP: usize = 600; +/// projects in Recent (the bench): the ones the person was in last. The rest are one fold below, All projects. +pub const BENCH: usize = 8; // the status vocabulary and D11's rule are the state's own (state/visible.rs: the digest and probe binaries fold the look and cut marks too) pub use crate::state::visible::*; @@ -110,7 +115,36 @@ fn thread_row(hub: &str, now: u64, p: &MergedProject, f: &Th) -> Value { "project":p.name,"projectKey":p.key,"off":off,"nav":if off { String::new() } else { qid(hub,&t.id) }, // another machine's thread can be hidden here (its menu's first item on the desktop, a long press on the phones) "hide":hide_of(hub,t),"lead":if hide_of(hub,t).is_empty() { json!([]) } else { json!([{"label":"Hide","action":"thread-hide","value":hide_of(hub,t),"tone":"settle","options":[]}]) }, - "menu":thread_menu(hub,f)}) + "label":badge(f.word,want(t,f.word)).0,"tone":badge(f.word,want(t,f.word)).1,"snooze":snooze_of(hub,f), + "settle":settle_of(hub,f),"menu":thread_menu(hub,f)}) +} +/// A row's status as a word and its tone (`bad`, `run`, `wait`, `ok`): every client draws it as a label beside the title, where a coloured dot +/// alone said almost nothing at a glance (the person, 2026-11-23). ("", "") for a thread with nothing to say (idle). +pub fn badge(word: &str, want: &str) -> (&'static str, &'static str) { + match (word, want) { + ("needs", "approval") => ("Approve", "bad"), ("needs", "sign-in") => ("Sign in", "bad"), ("needs", _) => ("Input", "bad"), + ("failed", _) => ("Failed", "bad"), ("cut" | "interrupted", _) => ("Stopped", "bad"), + ("running", _) => ("Working", "run"), ("monitoring" | "limit", _) => ("Waiting", "wait"), ("done", _) => ("Done", "ok"), + _ => ("", ""), + } +} +/// Whether a thread is snoozed now (`ThreadSnoozed`, state `snooze_until`): a thread of this machine, until its time. An open ask is never +/// snoozed away (it is answered); a new turn or ask wakes the thread (commands/plan.rs). +fn snoozed(f: &Th, now: u64) -> bool { f.word != "needs" && f.t.machine.is_empty() && snooze_end(f) > now } +fn snooze_end(f: &Th) -> u64 { f.t.src.and_then(|s| s.snooze_until.get(&f.t.id).copied()).unwrap_or(0) } +/// The spans a row can be snoozed for (action `row-snooze`, each option's value): a thread of this machine with no open ask. Empty for any other. +fn snooze_of(hub: &str, f: &Th) -> Value { + let t = f.t; + if !t.machine.is_empty() || t.src.is_none() || t.archived || f.word == "needs" { return json!([]) } + let q = qid(hub, &t.id); + json!([{"label":"1 hour","value":format!("{q}|1h")},{"label":"Tomorrow","value":format!("{q}|tomorrow")},{"label":"1 week","value":format!("{q}|1w")}]) +} +/// The thread a row settles in one press (its id; "" for none): a thread of this machine that stopped and asks nothing. One that runs is not settled +/// from under its turn, and an open ask is answered, not put away. +fn settle_of(hub: &str, f: &Th) -> String { + let t = f.t; + if !t.machine.is_empty() || t.src.is_none() || t.archived || f.settled || live(f.word) || f.word == "needs" { return String::new() } + qid(hub, &t.id) } /// A thread row's menu (right click on the desktop, long press on the phones), for a thread of this machine: Pin or Unpin (a pinned thread is a /// fixed row under its project, and the clock never settles it), Settle or Unsettle (Archive was folded into Settle). `id` is the `thread.act` action a phone sends; @@ -334,8 +368,8 @@ fn put_away(f: &Th) -> bool { f.t.archived || f.t.src.and_then(|s| s.threads.get fn project_row(st: &State, c: &Ctx, p: &MergedProject, ths: &[Th], gid: &str, groups: &Groups) -> Value { let mut r = super::merged::row_json(p); // what runs: a turn running (one that also asks the person counts here and in Needs you), work it owns, a turn held for a reset - let running = ths.iter().filter(|f| matches!(f.word, "running" | "monitoring" | "limit") || (f.word == "needs" && f.t.src.map_or(false, |s| s.threads.get(&f.t.id).map_or(false, |x| x.turn == Turn::Running)))).count(); - let needs = ths.iter().filter(|f| f.needs).count(); + let running = ths.iter().filter(|f| !snoozed(f, c.now)).filter(|f| matches!(f.word, "running" | "monitoring" | "limit") || (f.word == "needs" && f.t.src.map_or(false, |s| s.threads.get(&f.t.id).map_or(false, |x| x.turn == Turn::Running)))).count(); + let needs = ths.iter().filter(|f| f.needs && !snoozed(f, c.now)).count(); let q = c.query; let every = !attention_only(st); let on_show = |f: &Th| !c.selected.is_empty() && f.t.id == c.selected; @@ -343,15 +377,16 @@ fn project_row(st: &State, c: &Ctx, p: &MergedProject, ths: &[Th], gid: &str, gr // Settings' "Only threads that need attention" off: every thread of it the person has not put away, its asks too (they are also in // Needs you), as in 0.15; a delegated child or a swarm's member still hangs under its parent or its swarm let mut shown: Vec<&Th> = if every && q.is_empty() { ths.iter().filter(|f| (!f.kid && !put_away(f)) || on_show(f)).collect() } - else { ths.iter().filter(|f| if q.is_empty() { !f.needs && ((f.show && !f.kid) || on_show(f)) } else { crate::sidebar::word_hit(&f.t.title, q) }).collect() }; + else { ths.iter().filter(|f| if q.is_empty() { (!f.needs || snoozed(f, c.now)) && ((f.show && !f.kid && !snoozed(f, c.now)) || on_show(f)) } else { crate::sidebar::word_hit(&f.t.title, q) }).collect() }; // a pinned thread is a fixed row of its project: first, where it was pinned, whatever runs or stops below it (and never cut by UNDER) if q.is_empty() { shown.sort_by_key(|f| pin_rank(f)); } - // At most its two pins and one other: the thread that runs (the newest live one), else the one on show, else the newest stop that - // still wants a look. Nothing folds: the rows under a project are few and fixed, so there is no chevron (the person, 2026-11-15: "the + // At most its two pins and one other: the one on show, else the newest stop that still wants a look. Nothing folds: the rows under a project are few and fixed, so there is no chevron (the person, 2026-11-15: "the // max number of threads viewable under a project are 2 pinned plus one active ... it should not be collapsible anyway") if q.is_empty() && !every { let mut other: Vec<&Th> = shown.iter().filter(|f| !f.t.pinned).copied().collect(); - other.sort_by_key(|f| (!crate::state::visible::live(f.word), f.t.id != c.selected, std::cmp::Reverse(f.t.activity))); + // what runs is a row of Running (`build`), not repeated here: under a project, its pins, the thread on show, else its newest stop + other.retain(|f| !live(f.word) || on_show(f)); + other.sort_by_key(|f| (f.t.id != c.selected, std::cmp::Reverse(f.t.activity))); let pins: Vec<&Th> = shown.iter().filter(|f| f.t.pinned).take(crate::commands::plan::PINS).copied().collect(); shown = pins.into_iter().chain(other.into_iter().take(1)).collect(); } @@ -370,7 +405,10 @@ fn project_row(st: &State, c: &Ctx, p: &MergedProject, ths: &[Th], gid: &str, gr let sw = swarms_of(p, c); r["running"] = json!(running + sw.iter().filter(|x| x.1 == "running").count()); r["needsCount"] = json!(needs + sw.iter().filter(|x| x.1 != "running").count()); - let live: Vec = sw.into_iter().filter(|x| x.1 == "running").map(|x| x.0).collect(); + // a running swarm is a row of Running while only what needs attention is listed; with every thread listed it stays under its project + let live: Vec = if every { sw.into_iter().filter(|x| x.1 == "running").map(|x| x.0).collect() } else { vec![] }; + r["hasBoard"] = json!(p.here.is_some() && hardware(&p.folder)); r["hasSchematic"] = r["hasBoard"].clone(); + // no fold while only what needs attention is listed (an older client draws a chevron only for a `fold` action with rows to hide: none); // with every thread listed, a chevron folds them away (its counts stay, and its asks are in Needs you) if every && q.is_empty() && under > 0 { r["fold"] = json!("project-fold"); r["folded"] = json!(folded); r["under"] = json!(under); } @@ -386,6 +424,18 @@ fn project_row(st: &State, c: &Ctx, p: &MergedProject, ths: &[Th], gid: &str, gr r["dots"] = json!(p.machines.iter().map(|m| json!({"name":m["name"],"short":m["short"],"here":m["here"],"dim":m["dim"],"note":m["note"]})).collect::>()); r } +/// When the person was last in a project (opened its page or a thread of it: `sidebar.visit.`, state/visible.rs `visit`), s; 0 for never. +fn visited_at(st: &State, p: &MergedProject) -> u64 { p.here.as_ref().map_or(0, |id| num(st, &format!("sidebar.visit.{id}"))) } +/// The bench's order: by the person's last visit; a project never visited (every one, at the upgrade) by its last activity. +fn bench_rank(st: &State, p: &MergedProject) -> u64 { match visited_at(st, p) { 0 => p.last_activity, v => v } } +/// `kicad::canonical::hardware` of a project's folder, remembered for five minutes: the sidebar asks for every project at every picture. +fn hardware(folder: &str) -> bool { + static HW: std::sync::OnceLock>> = std::sync::OnceLock::new(); + if folder.is_empty() { return false } + let m = HW.get_or_init(Default::default); + if let Some((at, v)) = m.lock().unwrap().get(folder) { if at.elapsed() < std::time::Duration::from_secs(300) { return *v } } + let v = crate::files::kicad::canonical::hardware(folder); m.lock().unwrap().insert(folder.to_string(), (std::time::Instant::now(), v)); v +} fn fold_section(id: &str, title: &str, rows: Vec, c: &Ctx, extra: Value) -> Value { let open = c.open.contains(&format!("sec:{id}")) || !c.query.is_empty() || rows.iter().any(|r| r["threads"].as_array().map_or(false, |t| t.iter().any(|x| x["id"] == json!(qid(c.hub, c.selected))))); let mut s = json!({"id":id,"kind":"projects","title":title,"count":rows.len(),"fold":true,"open":open,"toggle":format!("sec:{id}"),"rows":if open { rows } else { vec![] }}); @@ -400,7 +450,7 @@ pub fn build(st: &State, rows: &[MergedProject], bub: &Value, c: &Ctx) -> Value if bub.is_object() { out.push(json!({"id":"bub","kind":"bub","title":"","rows":[bub]})); } // Needs you: every machine's, approvals first, then questions, then stops, newest first within each let mut needs: Vec<(u8, u64, Value)> = vec![]; - for (p, ths) in rows.iter().zip(&facts_of) { for f in ths.iter().filter(|f| f.needs) { + for (p, ths) in rows.iter().zip(&facts_of) { for f in ths.iter().filter(|f| f.needs && !snoozed(f, c.now)) { if !c.query.is_empty() && !hit(&f.t.title, c.query) && !hit(&p.name, c.query) { continue } let r = thread_row(c.hub, c.now, p, f); let rank = match r["want"].as_str().unwrap_or("") { "approval" => 0, "question" | "sign-in" => 1, "failed" => 2, _ => 3 }; @@ -427,8 +477,36 @@ pub fn build(st: &State, rows: &[MergedProject], bub: &Value, c: &Ctx) -> Value } } } needs.sort_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1))); if !needs.is_empty() { out.push(json!({"id":"needs","kind":"threads","title":"Needs you","count":needs.len(),"rows":needs.into_iter().map(|x| x.2).collect::>()})); } - // the projects: pinned, active, by group, quiet + // Running: what works now, every project's in one list (the newest first), each row naming its project. With every thread listed + // (`sidebar.attention` off) they stay under their projects, as before + if attention_only(st) { + let mut running: Vec<(u64, Value)> = vec![]; + for (p, ths) in rows.iter().zip(&facts_of) { + for f in ths.iter().filter(|f| !f.needs && f.show && !f.kid && live(f.word) && !snoozed(f, c.now)) { + if !c.query.is_empty() && !hit(&f.t.title, c.query) && !hit(&p.name, c.query) { continue } + running.push((f.t.activity, thread_row(c.hub, c.now, p, f))); + } + for (r, w) in swarms_of(p, c) { if w != "running" { continue } + if !c.query.is_empty() && !hit(text_of(&r, "title"), c.query) && !hit(&p.name, c.query) { continue } + running.push((r["activity"].as_u64().unwrap_or(0), r)); } + } + running.sort_by(|a, b| b.0.cmp(&a.0)); + if !running.is_empty() { out.push(json!({"id":"running","kind":"threads","title":"Running","count":running.len(),"rows":running.into_iter().map(|x| x.1).collect::>()})); } + } + // Snoozed: what the person put off (a stop, or work they do not want to watch), soonest to wake first; folded, and gone when empty + { let mut snz: Vec<(u64, Value)> = vec![]; + for (p, ths) in rows.iter().zip(&facts_of) { for f in ths.iter().filter(|f| snoozed(f, c.now) && !f.kid && (f.show || f.needs)) { + if !c.query.is_empty() && !hit(&f.t.title, c.query) && !hit(&p.name, c.query) { continue } + let mut r = thread_row(c.hub, c.now, p, f); let until = snooze_end(f); + r["wake"] = json!(format!("{}|off", qid(c.hub, &f.t.id))); r["until"] = json!(until); r["ago"] = json!(crate::sidebar::ago(until, c.now)); r["snooze"] = json!([]); r["settle"] = json!(""); + snz.push((until, r)); } } + snz.sort_by(|a, b| a.0.cmp(&b.0)); + if !snz.is_empty() { + let open = c.open.contains("sec:snoozed") || !c.query.is_empty(); + out.push(json!({"id":"snoozed","kind":"threads","title":"Snoozed","count":snz.len(),"fold":true,"open":open,"toggle":"sec:snoozed","rows":if open { snz.into_iter().map(|x| x.1).collect::>() } else { vec![] }})); } } + // the projects: pinned, the bench (Recent), by group, all the rest, quiet let (mut pinned, mut active, mut quiet): (Vec<(u64, Value)>, Vec<(u64, Value)>, Vec) = (vec![], vec![], vec![]); + let mut rest: Vec<(String, Value)> = vec![]; let mut groups: Vec<(String, String, Vec)> = vec![]; let all = Groups::of(st, rows); let held = rows.iter().zip(&facts_of).find(|(_, ths)| ths.iter().any(|f| f.t.id == c.selected)).map(|(p, _)| p.key.clone()).unwrap_or_default(); @@ -437,23 +515,32 @@ pub fn build(st: &State, rows: &[MergedProject], bub: &Value, c: &Ctx) -> Value let gid = all.of_project(st, p); let row = project_row(st, c, p, ths, &gid, &all); let pin = pinned_at(st, &p.key); - let shows = ths.iter().any(|f| f.show && !f.kid) || row["swarms"].as_array().map_or(false, |a| !a.is_empty()) || row["needsCount"].as_u64().unwrap_or(0) > 0; + let shows = ths.iter().any(|f| f.show && !f.kid && !snoozed(f, c.now)) || row["swarms"].as_array().map_or(false, |a| !a.is_empty()) || row["needsCount"].as_u64().unwrap_or(0) > 0; if pin > 0 { pinned.push((pin, row)); continue } // made quiet: in Quiet at once, until something new happens in it (its asks are in Needs you all the same; the section opens by // itself while the open thread is listed under it, `fold_section`) if made_quiet(st, p) { quiet.push(row); continue } - if shows || p.last_activity + ACTIVE > c.now || p.key == held { active.push((p.last_activity, row)); continue } - if p.last_activity + QUIET <= c.now { quiet.push(row); continue } - // in no group (groups are off, the default): it stays in the one list, below what is newer - if gid.is_empty() { active.push((p.last_activity, row)); continue } + // the project of the open thread is always on the bench (the person is in it now) + if p.key == held { active.push((u64::MAX, row)); continue } + if !shows && bench_rank(st, p) + QUIET <= c.now && p.last_activity + QUIET <= c.now { quiet.push(row); continue } + // a project of a group the person made (or of the automatic groups, when on) is in its group + // (one with something to show, or one the person was in within ACTIVE, is on the bench all the same) + if gid.is_empty() || shows || bench_rank(st, p) + ACTIVE > c.now { active.push((bench_rank(st, p), row)); continue } match groups.iter_mut().find(|g| g.0 == gid) { Some(g) => g.2.push(row), None => groups.push((gid.clone(), all.name(st, &gid), vec![row])) } } pinned.sort_by(|a, b| a.0.cmp(&b.0)); active.sort_by(|a, b| b.0.cmp(&a.0)); if !pinned.is_empty() { out.push(json!({"id":"pinned","kind":"projects","title":"Pinned","count":pinned.len(),"rows":pinned.into_iter().map(|x| x.1).collect::>()})); } - out.push(json!({"id":"active","kind":"projects","title":"Active","count":active.len(),"rows":active.into_iter().map(|x| x.1).collect::>()})); + // the bench holds BENCH: the rest fold into All projects, by name (a search lists every hit where it is) + for (_, row) in active.split_off(active.len().min(BENCH)) { rest.push((text_of(&row, "title").to_lowercase(), row)); } + rest.sort_by(|a, b| a.0.cmp(&b.0)); + // which projects are on the bench follows the person's visits; where each stands on it does not: by name, so opening a thread of another + // project moves no row under the pointer and a project is found where it was + active.sort_by(|a, b| text_of(&a.1, "title").to_lowercase().cmp(&text_of(&b.1, "title").to_lowercase())); + out.push(json!({"id":"active","kind":"projects","title":"Recent","count":active.len(),"rows":active.into_iter().map(|x| x.1).collect::>()})); groups.sort_by(|a, b| a.1.to_lowercase().cmp(&b.1.to_lowercase())); for (gid, name, rs) in groups { out.push(fold_section(&format!("group:{gid}"), &name, rs, c, json!({"group":gid,"rename":true}))); } + if !rest.is_empty() { out.push(fold_section("all", "All projects", rest.into_iter().map(|x| x.1).collect(), c, json!({}))); } if !quiet.is_empty() { out.push(fold_section("quiet", "Quiet", quiet, c, json!({"hint":"Nothing for two weeks, or made quiet"}))); } json!(out) } @@ -524,8 +611,11 @@ pub fn act(st: &State, rows: &[MergedProject], action: &str, value: &str, drafts let known = |key: &str| rows.iter().any(|p| p.key == key); match action { // a section's fold (Groups, Quiet, Archived), the project page's Done (n) and its Older (m) - "side-section" => { if !(value.starts_with("sec:group:") || value == "sec:quiet" || value == "sec:archived" || value == "page-done" || value == "page-older") { return None } Some(Act { open_toggle: Some(value.into()), ..none() }) } - "project-page" => { if !value.is_empty() && !known(value) { return None } Some(Act { page: Some(value.into()), ..none() }) } + "side-section" => { if !(value.starts_with("sec:group:") || value == "sec:quiet" || value == "sec:all" || value == "sec:snoozed" || value == "sec:archived" || value == "page-done" || value == "page-older") { return None } Some(Act { open_toggle: Some(value.into()), ..none() }) } + "project-page" => { if !value.is_empty() && !known(value) { return None } + // opening a project's page is a visit: it comes to the top of the bench (`bench_rank`) + let sets = rows.iter().find(|p| p.key == value).and_then(|p| p.here.as_ref()).filter(|id| crate::state::visible::visit_due(st, id, now)).map(|id| vec![(format!("sidebar.visit.{id}"), now.to_string())]).unwrap_or_default(); + Some(Act { page: Some(value.into()), sets, ..none() }) } // another machine's thread, hidden here until something new happens there (`hidden_at`); a local thread has Settle and Archive "thread-hide" => { let id = value.rsplit_once('|').map_or(value, |(_, r)| r); diff --git a/native/host/src/present/sections_tests.rs b/native/host/src/present/sections_tests.rs index e674f840bd..abc8c5039e 100644 --- a/native/host/src/present/sections_tests.rs +++ b/native/host/src/present/sections_tests.rs @@ -102,21 +102,24 @@ fn one(evs: &[Value]) -> State { let mut v = vec![pc("p1", "Proj", "/nowhere/pro let under = |s: &State| { let rows = merged_projects(s, &[], &|_| false, &|_| String::new(), "desk", &[]); let v = build(s, &rows, &Value::Null, &ctx(&HashSet::new())); sec(&v, "active")["rows"][0]["threads"].clone() }; let names = |u: &Value| u.as_array().unwrap().iter().map(|r| r["title"].as_str().unwrap().to_string()).collect::>(); let u = under(&one(&evs)); - assert_eq!(names(&u), ["T t3", "T t1", "T t2"], "the pins first, as pinned; the running one (newest) after them"); + assert_eq!(names(&u), ["T t3", "T t1"], "the pins first, as pinned; the running one is a row of Running"); + let running = { let s = one(&evs); let rows = merged_projects(&s, &[], &|_| false, &|_| String::new(), "desk", &[]); sec(&build(&s, &rows, &Value::Null, &ctx(&HashSet::new())), "running")["rows"].clone() }; + assert_eq!(names(&running), ["T t2"]); assert_eq!(running[0]["project"], "Proj"); assert_eq!(running[0]["settle"], "", "a thread that runs is not settled from under its turn"); + assert_eq!(u[0]["settle"], "h|t3", "a finished one settles in one press"); let menu = |r: &Value| r["menu"].as_array().unwrap().iter().map(|m| (m["id"].as_str().unwrap().to_string(), m["action"].as_str().unwrap().to_string(), m["value"].as_str().unwrap().to_string())).collect::>(); assert_eq!(menu(&u[0]), [("unpin".into(), "row-unpin".into(), "h|t3".into()), ("settle".into(), "row-settle".into(), "h|t3".into())], "no Archive: it is Settle"); - assert_eq!(menu(&u[2])[0].0, "pin"); assert_eq!(u[0]["menu"][0]["label"], "Unpin"); assert_eq!(u[2]["menu"][0]["label"], "Pin"); + assert_eq!(menu(&running[0])[0].0, "pin"); assert_eq!(u[0]["menu"][0]["label"], "Unpin"); assert_eq!(running[0]["menu"][0]["label"], "Pin"); // no fold: a project's rows are few and fixed (two pins, one other), so no chevron; an old fold setting changes nothing { let s = one(&evs); let key = merged_projects(&s, &[], &|_| false, &|_| String::new(), "desk", &[])[0].key.clone(); let mut f = evs.clone(); f.push(json!({"$":"SettingSet","key":format!("sidebar.fold.{key}"),"value":"1","at":NOW-1})); let s = one(&f); let rows = merged_projects(&s, &[], &|_| false, &|_| String::new(), "desk", &[]); let v = build(&s, &rows, &Value::Null, &ctx(&HashSet::new())); - let p = &sec(&v, "active")["rows"][0]; assert_eq!((p["fold"].as_str(), p["folded"].as_bool(), p["under"].as_u64()), (Some(""), Some(false), Some(0))); assert_eq!(names(&p["threads"]), ["T t3", "T t1", "T t2"]); } - // ten more running threads, all newer: still the two pins and one running thread, the newest + let p = &sec(&v, "active")["rows"][0]; assert_eq!((p["fold"].as_str(), p["folded"].as_bool(), p["under"].as_u64()), (Some(""), Some(false), Some(0))); assert_eq!(names(&p["threads"]), ["T t3", "T t1"]); } + // ten more running threads, all newer: still the two pins alone (what runs is in Running) for i in 0..10 { let id = format!("r{i}"); evs.push(tc(&id, "p1", NOW - 9)); evs.push(turn(&id, "running", NOW - 5)); } - let u = under(&one(&evs)); assert_eq!(u.as_array().unwrap().len(), 3); assert_eq!(names(&u)[..2], ["T t3", "T t1"]); + let u = under(&one(&evs)); assert_eq!(names(&u), ["T t3", "T t1"]); // settled by hand, a thread gives up its pin (the state's law) and leaves; unpinned and done, the other leaves too. The page's Done row offers Pin and Unsettle evs.truncate(7); evs.push(json!({"$":"ThreadSettled","id":"t3","manual":true,"at":NOW-20})); evs.push(pin("t1", false, NOW - 20)); - let s = one(&evs); assert_eq!(names(&under(&s)), ["T t2"]); + let s = one(&evs); assert!(names(&under(&s)).is_empty()); let rows = merged_projects(&s, &[], &|_| false, &|_| String::new(), "desk", &[]); let open = HashSet::new(); let pg = page(&s, &rows, &rows[0].key, &ctx(&open), true); let done = pg["sections"].as_array().unwrap().iter().find(|x| x["id"] == "done").unwrap(); let t3 = done["rows"].as_array().unwrap().iter().find(|r| r["title"] == "T t3").unwrap(); assert_eq!((t3["menu"][0]["id"].as_str(), t3["menu"][1]["id"].as_str()), (Some("pin"), Some("unsettle"))); @@ -148,7 +151,7 @@ fn world() -> State { assert!(!groups_on(&s) && groups_on(&world())); let v = build(&s, &rows, &Value::Null, &ctx(&HashSet::new())); assert_eq!(ids(&v), ["needs", "active", "quiet"], "no group section"); - assert_eq!(titles(sec(&v, "active")), ["Alive", "Recent", "Grouped", "Failing"], "the grouped one is in the list, by its last activity like the rest"); + assert_eq!(titles(sec(&v, "active")), ["Alive", "Failing", "Grouped", "Recent"], "the grouped one is in the list, by name like the rest"); assert!(groups_due(&s, &rows).is_empty(), "nothing asks Haiku for a name"); let g = sec(&v, "active")["rows"].as_array().unwrap().iter().find(|r| r["title"] == "Grouped").unwrap().clone(); assert_eq!(g["group"], ""); let sub = |r: &Value| r["menu"].as_array().unwrap().iter().find(|i| i["id"] == "move").unwrap()["sub"].as_array().unwrap().iter().map(|i| i["label"].as_str().unwrap().to_string()).collect::>(); @@ -171,8 +174,8 @@ fn world() -> State { // Needs you: the approval, then the failure (twenty days old, never looked at) assert_eq!(titles(sec(&v, "needs")), ["T ta", "T tf"]); assert_eq!(sec(&v, "needs")["rows"][0]["want"], "approval"); assert_eq!(sec(&v, "needs")["rows"][1]["want"], "failed"); - // Active: a project with a visible thread (Alive runs, Failing's failure shows) or activity within three days, newest first - assert_eq!(titles(sec(&v, "active")), ["Alive", "Recent", "Failing"], "{v}"); + // Recent: a project with a visible thread (Alive runs, Failing's failure shows) or activity within three days; on the bench by name + assert_eq!(titles(sec(&v, "active")), ["Alive", "Failing", "Recent"], "{v}"); let alive = &sec(&v, "active")["rows"][0]; assert_eq!(alive["running"], 1); assert_eq!(alive["needsCount"], 1); assert!(alive["threads"].as_array().unwrap().is_empty(), "its thread is in Needs you, not repeated under it"); // a group folds by default with its count, and Quiet too @@ -213,7 +216,7 @@ fn world() -> State { let v = build(&s, &rows, &Value::Null, &ctx(&HashSet::new())); let alive = &sec(&v, "active")["rows"][0]; assert_eq!((alive["fold"].as_str(), alive["folded"].as_bool(), alive["under"].as_u64(), alive["rest"].as_u64()), (Some(""), Some(false), Some(0), Some(0)), "{alive}"); - assert_eq!(titles_of(&alive["threads"]), ["T tc"], "one other thread: the newest running one"); + assert!(titles_of(&alive["threads"]).is_empty(), "what runs is in Running"); assert_eq!(titles(sec(&v, "running")), ["T tc", "T tb"], "the newest first"); assert_eq!((alive["running"].as_u64(), alive["needsCount"].as_u64()), (Some(3), Some(1)), "its counts stay on the row"); assert_eq!(titles(sec(&v, "needs"))[0], "T ta", "a thread of it that asks the person is in Needs you"); // a search still lists every hit under it @@ -458,7 +461,8 @@ fn menu_ids(m: &Value) -> Vec { m.as_array().unwrap().iter().map(|i| i[" let rows2 = merged_projects(&s2, &[], &|_| false, &|_| String::new(), "desk", &[]); let v2 = build(&s2, &rows2, &Value::Null, &ctx(&HashSet::new())); assert!(sec(&v2, "needs").is_null()); - let p2 = &sec(&v2, "active")["rows"][0]; assert_eq!(p2["swarms"][0]["nav"], "@room:r1"); assert_eq!(p2["swarms"][0]["members"], 2); assert!(p2["running"].as_u64().unwrap() >= 1); + let p2 = &sec(&v2, "active")["rows"][0]; assert!(p2["swarms"].as_array().unwrap().is_empty(), "not repeated under its project"); assert!(p2["running"].as_u64().unwrap() >= 1); + let r2 = &sec(&v2, "running")["rows"][0]; assert_eq!(r2["nav"], "@room:r1"); assert_eq!(r2["members"], 2); // a guard's pause asks the person; a member's ask does too for evs in [vec![room("r1", "paused", "circular")], vec![room("r1", "", ""), ask("q", "a", "question")]] { let mut e = vec![pc("p1", "P", "/n/p", 1), tc("a", "p1", 2), tc("b", "p1", 3)]; e.extend(evs); @@ -475,14 +479,15 @@ fn menu_ids(m: &Value) -> Vec { m.as_array().unwrap().iter().map(|i| i[" } // ---- finished threads: counted on the project's row, and the one on show listed under it ----------------------------------- -#[test] fn the_one_row_besides_the_pins_is_the_running_thread_else_the_open_one() { +#[test] fn the_one_row_besides_the_pins_is_the_open_thread_and_what_runs_is_in_running() { let s = one(&[tc("t2", "p1", NOW - 80), tc("t3", "p1", NOW - 70), turn("t1", "completed", NOW - 50), turn("t2", "completed", NOW - 40), json!({"$":"ThreadSettled","id":"t2","manual":true,"at":NOW-30}), turn("t3", "running", NOW - 20)]); let rows = merged_projects(&s, &[], &|_| false, &|_| String::new(), "desk", &[]); let open = HashSet::new(); let row = |s: &State, sel: &'static str| { let rows = merged_projects(s, &[], &|_| false, &|_| String::new(), "desk", &[]); let c = Ctx { selected: sel, ..ctx(&open) }; sec(&build(s, &rows, &Value::Null, &c), "active")["rows"][0].clone() }; let _ = rows; - let r = row(&s, ""); assert_eq!((titles_of(&r["threads"]), r["rest"].as_u64()), (vec!["T t3".to_string()], Some(0)), "the running one; no count of the rest"); - assert_eq!(titles_of(&row(&s, "t2")["threads"]), ["T t3"], "the running one wins over the one on show"); + let r = row(&s, ""); assert_eq!((titles_of(&r["threads"]), r["rest"].as_u64(), r["running"].as_u64()), (vec![], Some(0), Some(1)), "the running one is in Running, counted here; no count of the rest"); + assert_eq!(titles_of(&row(&s, "t2")["threads"]), ["T t2"], "the one on show has the row"); + assert_eq!(titles_of(&row(&s, "t3")["threads"]), ["T t3"], "the running one too, while it is the one on show"); // nothing runs: the thread on show has the row, and leaves when another is opened let s = one(&[tc("t2", "p1", NOW - 80), turn("t1", "completed", NOW - 50), turn("t2", "completed", NOW - 40), json!({"$":"ThreadSettled","id":"t2","manual":true,"at":NOW-30})]); assert_eq!(titles_of(&row(&s, "t2")["threads"]), ["T t2"]); @@ -504,7 +509,7 @@ fn menu_ids(m: &Value) -> Vec { m.as_array().unwrap().iter().map(|i| i[" let s = one(&evs); assert!(attention_only(&s), "on unless the person turns it off"); let v = view(&s, ""); let p = &sec(&v, "active")["rows"][0]; - assert_eq!(titles_of(&p["threads"]), ["T t8", "T t3"], "the pin and the running one"); + assert_eq!(titles_of(&p["threads"]), ["T t8"], "the pin"); assert_eq!(titles_of(&sec(&v, "running")["rows"]), ["T t3"], "what runs is in Running"); assert_eq!(titles_of(&sec(&v, "needs")["rows"]), ["T t7"]); assert_eq!(p["fold"], "", "no chevron"); let mut off = evs.clone(); off.push(set(ATTENTION, "off", NOW - 1)); @@ -634,3 +639,56 @@ fn menu_ids(m: &Value) -> Vec { m.as_array().unwrap().iter().map(|i| i[" assert!(!jmp_str.contains("Bub: Launch:") && !jmp_str.contains("mailcoord-"), "no mailroom runs in Ctrl+K: {jmp_str}"); assert!(jmp_str.contains("User thread") && jmp_str.contains("Test runner")); } + +// ---- the bench: Recent holds the projects the person was in last, the rest fold into All projects ---------------------------------- +#[test] fn recent_holds_the_last_visited_projects_and_the_rest_fold_into_all_projects() { + // twelve projects, each with one finished thread, the higher the number the newer its activity + let mut evs = vec![]; for i in 0..12u64 { let (p, t) = (format!("q{i:02}"), format!("u{i:02}")); evs.push(pc(&p, &format!("N{i:02}"), &format!("/n/q{i:02}"), NOW - 5 * DAY)); evs.push(tc(&t, &p, NOW - 4 * DAY + i)); evs.push(turn(&t, "completed", NOW - 4 * DAY + i)); } + let s = st(&evs); let rows = merged_projects(&s, &[], &|_| false, &|_| String::new(), "desk", &[]); + let v = build(&s, &rows, &Value::Null, &ctx(&HashSet::new())); + assert_eq!(ids(&v), ["active", "all"]); assert_eq!(sec(&v, "active")["title"], "Recent"); + assert_eq!(titles(sec(&v, "active")), ["N04", "N05", "N06", "N07", "N08", "N09", "N10", "N11"], "never visited: the BENCH newest by activity; on the bench by name, so no row moves as the person goes between them"); + assert_eq!((sec(&v, "all")["count"].as_u64(), sec(&v, "all")["open"].as_bool(), sec(&v, "all")["rows"].as_array().unwrap().len()), (Some(4), Some(false), 0), "the rest: one folded line"); + // opened: by name + let open: HashSet = ["sec:all".to_string()].into(); + assert_eq!(titles(sec(&build(&s, &rows, &Value::Null, &ctx(&open)), "all")), ["N00", "N01", "N02", "N03"]); + assert_eq!(act(&s, &rows, "side-section", "sec:all", &json!({}), NOW).unwrap().open_toggle.as_deref(), Some("sec:all")); + // a visit (its page opened, or a thread of it) brings an old one to the top, whatever the agents did since + let key = rows.iter().find(|p| p.name == "N01").unwrap().key.clone(); + let a = act(&s, &rows, "project-page", &key, &json!({}), NOW).unwrap(); assert_eq!(a.sets, vec![("sidebar.visit.q01".to_string(), NOW.to_string())]); + let mut s2 = st(&evs); s2.apply(&set("sidebar.visit.q01", &NOW.to_string(), NOW)); + let rows2 = merged_projects(&s2, &[], &|_| false, &|_| String::new(), "desk", &[]); + assert_eq!(titles(sec(&build(&s2, &rows2, &Value::Null, &ctx(&HashSet::new())), "active")), ["N01", "N05", "N06", "N07", "N08", "N09", "N10", "N11"], "it took the oldest one's place"); + assert!(act(&s2, &rows2, "project-page", &key, &json!({}), NOW + 60).unwrap().sets.is_empty(), "at most one visit line in ten minutes"); + assert_eq!(crate::state::visible::visit(&s2, "u02", NOW)[0]["key"], "sidebar.visit.q02"); assert!(crate::state::visible::visit(&s2, "u01", NOW + 60).is_empty()); + // the open thread's project is on the bench, wherever it was + let none = HashSet::new(); let c = Ctx { selected: "u00", ..ctx(&none) }; + assert_eq!(titles(sec(&build(&s, &rows, &Value::Null, &c), "active")), ["N00", "N05", "N06", "N07", "N08", "N09", "N10", "N11"]); + // a search lists every hit: All projects opens by itself + let c = Ctx { query: "N02", ..ctx(&none) }; let v = build(&s, &rows, &Value::Null, &c); + assert_eq!(titles(sec(&v, "active")), ["N02"]); +} + +// ---- status labels and snoozing (the person, 2026-11-23) ---------------------------------------------------------------------------------- +#[test] fn a_row_says_its_status_in_a_word_and_a_snoozed_thread_waits_in_its_own_fold() { + assert_eq!([badge("needs", "approval"), badge("needs", "question"), badge("needs", "sign-in"), badge("failed", "failed"), badge("cut", "stopped"), badge("running", ""), badge("monitoring", ""), badge("done", ""), badge("idle", "")], + [("Approve", "bad"), ("Input", "bad"), ("Sign in", "bad"), ("Failed", "bad"), ("Stopped", "bad"), ("Working", "run"), ("Waiting", "wait"), ("Done", "ok"), ("", "")]); + let snz = |id: &str, until: u64| json!({"$":"ThreadSnoozed","id":id,"until":until,"at":NOW-5}); + let evs = vec![tc("t2", "p1", NOW - 80), tc("t3", "p1", NOW - 70), turn("t1", "failed", NOW - 60), turn("t2", "running", NOW - 50), ask("q3", "t3", "question")]; + let view = |s: &State, open: &HashSet| { let rows = merged_projects(s, &[], &|_| false, &|_| String::new(), "desk", &[]); build(s, &rows, &Value::Null, &ctx(open)) }; + let none = HashSet::new(); let v = view(&one(&evs), &none); + assert_eq!(ids(&v), ["needs", "running", "active"]); + let n = &sec(&v, "needs")["rows"]; assert_eq!((n[0]["label"].as_str(), n[0]["tone"].as_str()), (Some("Input"), Some("bad"))); assert_eq!((n[1]["label"].as_str(), n[1]["settle"].as_str()), (Some("Failed"), Some("h|t1"))); + assert_eq!(n[0]["snooze"], json!([]), "an open ask is answered, not snoozed"); assert_eq!(n[1]["snooze"][0], json!({"label":"1 hour","value":"h|t1|1h"})); + let r = &sec(&v, "running")["rows"][0]; assert_eq!((r["label"].as_str(), r["tone"].as_str(), r["snooze"].as_array().map(Vec::len)), (Some("Working"), Some("run"), Some(3))); + // snoozed: the stop and the running one leave their lists for one folded line; the ask stays whatever its snooze + let mut e2 = evs.clone(); e2.extend([snz("t1", NOW + 3600), snz("t2", NOW + 7200), snz("t3", NOW + 3600)]); + let s2 = one(&e2); let v = view(&s2, &none); + assert_eq!(ids(&v), ["needs", "snoozed", "active"]); assert_eq!(titles(sec(&v, "needs")), ["T t3"]); + let z = sec(&v, "snoozed"); assert_eq!((z["count"].as_u64(), z["fold"].as_bool(), z["open"].as_bool(), z["rows"].as_array().map(Vec::len)), (Some(2), Some(true), Some(false), Some(0))); + let p = &sec(&v, "active")["rows"][0]; assert_eq!((p["running"].as_u64(), p["needsCount"].as_u64()), (Some(0), Some(1)), "a snoozed thread is not counted on its project"); + let open: HashSet = ["sec:snoozed".to_string()].into(); let v = view(&s2, &open); let z = sec(&v, "snoozed"); + assert_eq!(titles(z), ["T t1", "T t2"], "soonest to wake first"); assert_eq!((z["rows"][0]["wake"].as_str(), z["rows"][0]["ago"].as_str()), (Some("h|t1|off"), Some("1h"))); + // its time passed: back where it was + let mut e3 = evs.clone(); e3.push(snz("t1", NOW - 1)); assert_eq!(ids(&view(&one(&e3), &none)), ["needs", "running", "active"]); +} diff --git a/native/host/src/state/policy.rs b/native/host/src/state/policy.rs index 2c3c01a8a7..d8bfe153bb 100644 --- a/native/host/src/state/policy.rs +++ b/native/host/src/state/policy.rs @@ -17,7 +17,7 @@ use std::sync::{Mutex, MutexGuard}; /// seen counts...). A policy that starts reading another family adds its prefix here. const KEEP: &[&str] = &["settle.", "autosettle.", "launch.", "launched.", "thread.parent.", "bg.", "watch.", "order.wait.", "wake.", "wakes.", "lock.", "locks.", "secret.ask.", "liveness.", "star.nudge.", "restart.retry", "provider.resume.", "thread.config.hold.", "watchdog.", "alert.", "summary.", "notify.", "push.webhook", "told.", "project.dormant.", - "order.enabled", "order.estimates", "account.thread.", "allowance.", "sidebar.pin.", "sidebar.fold.", "sidebar.keys.moved.", "sidebar.archived.", "sidebar.group.", "sidebar.hide.", "sidebar.looked.", "sidebar.cut.", "auth.wait.", "carry.wait.", "room.need.", "room.member.", "accounts.inventory", "fork.", "usage.", "effort.", "speed.", "buy."]; // fork.: the source thread id, a thread screen's "back" button; the action dispatcher's facts (Fab.at / Fab.want, Accounts.named): tiny values, one account key per thread + "order.enabled", "order.estimates", "account.thread.", "allowance.", "sidebar.pin.", "sidebar.visit.", "sidebar.fold.", "sidebar.keys.moved.", "sidebar.archived.", "sidebar.group.", "sidebar.hide.", "sidebar.looked.", "sidebar.cut.", "auth.wait.", "carry.wait.", "room.need.", "room.member.", "accounts.inventory", "fork.", "usage.", "effort.", "speed.", "buy."]; // fork.: the source thread id, a thread screen's "back" button; the action dispatcher's facts (Fab.at / Fab.want, Accounts.named): tiny values, one account key per thread // A thread screen must see its refusal gate's configuration even in the lean copy. Exact global keys keep their values; // per-thread keys keep only presence, never the possibly large body. stopped./failed. remain outside this allowlist. const GATE_EXACT: &[&str] = &["files.max.mb", "person.tz", "person.tz.device", "tz.machine", "think", "agent.thinking", "permissions.default"]; @@ -249,7 +249,7 @@ impl Policy { } pub fn read(&self, thread: &str, now_s: u64) -> Vec { let g = self.lock(); - if g.booting.is_some() { vec![] } else { let mut v = autosettle::read(&g.core.st, thread, now_s); v.extend(crate::state::visible::look(&g.core.st, thread, now_s)); v } + if g.booting.is_some() { vec![] } else { let mut v = autosettle::read(&g.core.st, thread, now_s); v.extend(crate::state::visible::look(&g.core.st, thread, now_s)); v.extend(crate::state::visible::visit(&g.core.st, thread, now_s)); v } } } diff --git a/native/host/src/state/visible.rs b/native/host/src/state/visible.rs index 252929be0b..4e5a9ddd25 100644 --- a/native/host/src/state/visible.rs +++ b/native/host/src/state/visible.rs @@ -128,6 +128,15 @@ pub fn look(st: &State, id: &str, now: u64) -> Vec { if !abnormal(status(st, id)) || !own(st, id) || num(st, &format!("sidebar.looked.{id}")) >= t.activity.max(1) { return vec![] } vec![json!({"$":"SettingSet","key":format!("sidebar.looked.{id}"),"value":now.max(t.activity).to_string(),"at":now})] } +/// A visit is written at most once in ten minutes for a project (`sidebar.visit.`): the bench orders by it, and a log line for +/// every thread opened would be noise. +pub fn visit_due(st: &State, project: &str, now: u64) -> bool { !project.is_empty() && num(st, &format!("sidebar.visit.{project}")) + 600 <= now } +/// Events a viewer's view.open of a thread adds for the bench (state/policy.rs `read`): the person was in its project now. +pub fn visit(st: &State, id: &str, now: u64) -> Vec { + let Some(t) = st.threads.get(id) else { return vec![] }; + if !visit_due(st, &t.project, now) { return vec![] } + vec![json!({"$":"SettingSet","key":format!("sidebar.visit.{}", t.project),"value":now.to_string(),"at":now})] +} /// What a committed change leaves for the sidebar (state/policy.rs `derive`): a turn that starts ends a restart's cut mark. pub fn meta(st: &State, e: &Value) -> Vec { if e["$"] != "TurnChanged" || e["state"] != "running" { return vec![] } diff --git a/test/sidebar/d.sh b/test/sidebar/d.sh index a720867fd0..c7aad9046e 100644 --- a/test/sidebar/d.sh +++ b/test/sidebar/d.sh @@ -1,5 +1,5 @@ # Source this: functions that drive the sidebar rig with real X input. -R=$HOME/.cache/bp-tmp/sb; . $R/env; export DISPLAY=$DISP; XI=$(git rev-parse --show-toplevel 2>/dev/null)/test/cef/xinput.py; [ -f "$XI" ] || XI=${WT:-.}/test/cef/xinput.py +R=${RIG:-$HOME/.cache/bp-tmp/sb}; . $R/env; export DISPLAY=$DISP; XI=$(git rev-parse --show-toplevel 2>/dev/null)/test/cef/xinput.py; [ -f "$XI" ] || XI=${WT:-.}/test/cef/xinput.py SH=${SH:-$(git rev-parse --show-toplevel 2>/dev/null)/build/gpui/shots/sidebar}; mkdir -p $SH # the centre of a control's rect in the latest controls metric (exit 1 when absent) at() { python3 -I -c ' diff --git a/test/sidebar/rig.sh b/test/sidebar/rig.sh index b22f58d221..5acc0e02ca 100755 --- a/test/sidebar/rig.sh +++ b/test/sidebar/rig.sh @@ -3,14 +3,14 @@ # Drive it with d.sh (real X mouse and keys through test/cef/xinput.py; targets from the client's `controls` rect metric). set -u WT=${WT:-$(cd "$(dirname "$0")/../.." && pwd)}; MAIN=${MAIN:-${WT%%/.backplane/worktrees/*}} # the checkout that holds build/gpui/xvfb -HUBBIN=$WT/native/host/target/fast/backplane-hub; CLIENT=$WT/native/gpui/target/fast/backplane-gpui; ASSETS=$(ls -d $HOME/.backplane-gpui-dev/builds/*/assets | tail -1) -R=$HOME/.cache/bp-tmp/sb; X=$MAIN/build/gpui/xvfb; HERE=$(dirname "$(readlink -f "$0")") +HUBBIN=${HUBBIN:-$WT/native/host/target/fast/backplane-hub}; CLIENT=${CLIENT:-$WT/native/gpui/target/fast/backplane-gpui}; ASSETS=$(ls -d $HOME/.backplane-gpui-dev/builds/*/assets | tail -1) +R=${RIG:-$HOME/.cache/bp-tmp/sb}; X=${XVFB_ROOT:-$MAIN/build/gpui/xvfb}; HERE=$(dirname "$(readlink -f "$0")") DN=$(for d in $(seq 151 199); do [ -e /tmp/.X11-unix/X$d ] || [ -e /tmp/.X$d-lock ] || { echo $d; break; }; done); DISP=:$DN PORT=$(python3 -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1])') rm -rf $R; mkdir -p $R/home $R/proj $R/bin $R/fakehome/.cache $R/fakehome/Documents/boards printf '#!/bin/sh\nexec %s %s "$@"\n' "$(command -v bun || echo /home/h/.bun/bin/bun)" "$WT/test/tools/claude_standin.ts" > $R/bin/claude; chmod +x $R/bin/claude for n in codex grok muse; do printf '#!/bin/sh\nexit 1\n' > $R/bin/$n; chmod +x $R/bin/$n; done -python3 -I $HERE/seed.py $R +python3 -I $HERE/${SEED:-seed.py} $R echo "DISP=$DISP PORT=$PORT R=$R" > $R/env; cat $R/env pids=() cleanup() { for p in "${pids[@]}"; do kill $p 2>/dev/null; done; sleep 1; } @@ -24,7 +24,7 @@ printf "ipc-socket $R/i3.sock\nfont pango:monospace 8\nnew_window none\ndefault_ i3 -c $R/i3.conf > $R/i3.log 2>&1 & pids+=($!); sleep 1 start_client() { VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/lvp_icd.json LP_NUM_THREADS=2 LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe BACKPLANE_GPUI_ASSETS=$ASSETS BACKPLANE_GPUI_RECTS=1 \ - $CLIENT --url http://127.0.0.1:$PORT --token-file $R/home/token --theme dark > $R/client.log 2>&1 & cpid=$!; echo $cpid > $R/client.pid + $CLIENT --url http://127.0.0.1:$PORT --token-file $R/home/token --theme ${THEME:-dark} > $R/client.log 2>&1 & cpid=$!; echo $cpid > $R/client.pid } start_client for i in $(seq 1 10800); do [ -e $R/stop ] && break; kill -0 $cpid 2>/dev/null || { [ -e $R/restart-client ] && { rm -f $R/restart-client; mv $R/client.log $R/client.$i.log; start_client; } ; }; sleep 1; done diff --git a/test/sidebar/seed43.py b/test/sidebar/seed43.py new file mode 100644 index 0000000000..bd2adc9cc7 --- /dev/null +++ b/test/sidebar/seed43.py @@ -0,0 +1,52 @@ +# A realistic big hub for the sidebar rig (SEED=seed43.py rig.sh): 43 hardware and software projects, the uberbot, bots, rooms, +# and threads that need the person, run, stopped, are pinned or settled. +import json, sys, time, os +R = sys.argv[1]; N = int(time.time()); D = 86400; H = 3600 +ev = [{"$":"SettingSet","key":k,"value":v,"at":N-90*D} for k, v in [("restart.continue","off"),("onboard.done","1"),("onboard.uber","1")]] +HW = ["STM32N657_SoM", "Orbital Feed Actuator", "OpenUWP Thermostat", "HaLow Baby Monitor", "Boost_12V_48V_480W", "Hubble_DK", "LoRa Gateway Rev C", "BLDC Driver 60V", + "USB-PD Sink 100W", "Flex Sensor Array", "nRF54 Tag", "PoE Splitter", "E-Ink Badge", "CAN Isolator", "Reflow Controller", "RP2350 Stamp", "GaN Half Bridge", + "Buck 5V 3A", "Stepper Hat", "Audio DAC I2S", "Solar MPPT 20A", "Thermal Camera Carrier", "Battery Fuel Gauge"] +SW = ["Backplane", "PinPlanner", "i2cjak.com", "kistack", "fabsrv", "pcbparts", "netlist-diff", "bom-lint", "step2glb", "gerber-view", "uwp-firmware", "halow-fw", + "tag-fw", "orbital-fw", "docs-site", "bench-scripts", "kicad-plugins", "symbol-gen", "label-printer", "ci-runners"] +def proj(pid, title, at, hw): + root = f"{R}/proj/{pid}"; os.makedirs(root, exist_ok=True) + if hw: # a KiCad project: the hub's design detection reads the folder + for ext in ("kicad_pro", "kicad_pcb", "kicad_sch"): open(f"{root}/{pid}.{ext}", "w").write("") + ev.append({"$":"ProjectCreated","id":pid,"title":title,"root":root,"at":at}) +def th(tid, pid, title, at): ev.append({"$":"ThreadCreated","id":tid,"project":pid,"title":title,"env":"local","branch":"","worktree":"","provider":"claude","model":"","at":at}) +def settle(tid, at): ev.append({"$":"ThreadSettled","id":tid,"manual":True,"at":at}) +names = [] +for i in range(max(len(HW), len(SW))): + if i < len(HW): names.append((HW[i], True)) + if i < len(SW): names.append((SW[i], False)) +for i, (name, hw) in enumerate(names): + pid = f"p{i:02d}"; age = [0, 0, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13][i % 17] + (i // 17) * 9 + proj(pid, name, N-(age+30)*D, hw) + th(f"t{i:02d}a", pid, ["Route the power stage", "Fix the build", "BOM review", "Bring-up notes", "Rev B changes"][i % 5], N-(age+2)*D) + settle(f"t{i:02d}a", N-age*D-H) + th(f"t{i:02d}b", pid, ["Footprint check", "Refactor the parser", "Order rev A", "DRC cleanup", "Release 0.3"][i % 5], N-(age+1)*D) + settle(f"t{i:02d}b", N-age*D-2*H) +# what needs the person, runs, stopped, is pinned +th("n1", "p00", "Swap the PMIC for one in stock?", N-2*H); ev.append({"$":"AskOpened","id":"a1","thread":"n1","kind":"question","tool":"AskUserQuestion","detail":"TPS65219 or DA9063?","options":"","at":N-900}) +th("n2", "p01", "Clean the build cache", N-3*H); ev.append({"$":"AskOpened","id":"a2","thread":"n2","kind":"approval","tool":"Bash","detail":"rm -rf target","options":"","at":N-300}) +th("n3", "p04", "Thermal sim of the inductor", N-5*H); ev.append({"$":"TurnChanged","thread":"n3","state":"failed","at":N-H}) +th("r1", "p02", "Length-match the DDR bus", N-40*60); th("r2", "p03", "Port the settings page", N-25*60); th("r3", "p06", "Antenna keep-out pass", N-10*60) +for t in ("r1", "r2", "r3"): ev.append({"$":"TurnChanged","thread":t,"state":"running","at":N-300}) +th("k1", "p02", "Rev B errata", N-6*D); ev.append({"$":"ThreadPinned","id":"k1","pinned":True,"at":N-6*D}) +# marks that outlast the hub's start (it closes open asks and cuts running turns of a log it did not write): a sign-in that waits, turns the +# restart carries on (running), a usage hold (waiting), a snoozed stop, and the person's visits (the bench's order) +def sset(k, v, at=N-10): ev.append({"$":"SettingSet","key":k,"value":v,"at":at}) +sset("auth.wait.n2", "1") +for t in ("r1", "r2"): sset(f"carry.wait.{t}", "1") +sset("provider.resume.r3", "1") +th("z1", "p05", "Lighthouse audit", N-8*H); ev.append({"$":"TurnChanged","thread":"z1","state":"failed","at":N-7*H}); ev.append({"$":"ThreadSnoozed","id":"z1","until":N+20*H,"at":N-6*H}) +for i, pid in enumerate(["p00", "p02", "p01", "p06", "p04", "p10", "p03"]): sset(f"sidebar.visit.{pid}", str(N-(i+1)*H-i*D//2)) +sset("sidebar.pin." + os.environ.get("PINKEY", "none"), str(N-9*D)) +# the uberbot, bots, rooms +def bot(bid, name, look, at): th("t"+bid, "", name, at); ev.append({"$":"BotSet","id":bid,"name":name,"thread":"t"+bid,"look":look,"persona":"","at":at}) +bot("b1", "Bub", 306440, N-80*D); ev.append({"$":"UberSet","bot":"b1","uid":"u1","at":N-80*D}) +for i, n in enumerate(["Ada", "Scout", "Pebble", "Mailroom", "Fabwatch", "Calendar"]): bot(f"b{i+2}", n, 304951+i*977, N-(60-i)*D) +for i, (n, m) in enumerate([("bring-up", 4), ("fab-orders", 3), ("firmware", 5), ("standup", 7), ("thermostat", 2)]): + ev.append({"$":"RoomSet","id":f"r{i+1}","name":n,"members":"\n".join(f"bot:b{j+1}" for j in range(m)),"ephemeral":False,"closed":False,"kind":"","project":"","goal":"","by":"","state":"","reason":"","at":N-(20-i)*D}) +ev.sort(key=lambda e: e["at"]) +open(R + "/home/events.jsonl", "w").write("".join(json.dumps(e, separators=(",", ":")) + "\n" for e in ev)) diff --git a/web/dist/assets/app.js b/web/dist/assets/app.js index b23c6bef6f..e52b3f1ced 100644 --- a/web/dist/assets/app.js +++ b/web/dist/assets/app.js @@ -1,15 +1,15 @@ -function _t(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 Rn(e){return e==="done"||e==="failed"||e==="cancelled"}function jn(e,t){if(!e||e.id!==t.id)return!0;let n=Rn(e.state),i=Rn(t.state);if(n!==i)return i;return(t.ended??0)>=(e.ended??0)}function Hn(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var gt={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.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","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","model.col.agent":"Agent","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:","secret.you":"You","settings.lang":"Language","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.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","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","model.col.agent":"Agente","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:","secret.you":"Tú","settings.lang":"Idioma","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.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":"分割表示には基板と回路図が必要です","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":"ピン留めを解除","model.col.agent":"エージェント","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":"返信先:","secret.you":"あなた","settings.lang":"言語","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 Dn(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 ft=bs(),qt=new Set,Kt=new Map;for(let[e,t]of Object.entries(gt.en||{}))if(typeof t==="string"&&!Kt.has(t))Kt.set(t,e);function bs(){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 Fn(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=ft}Fn();function Bt(e){return qt.add(e),()=>{qt.delete(e)}}function $n(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!==ft;if(ft=n,Fn(),i)for(let s of qt)s(ft);return i}function b(e,t,n){let s=(gt[ft]||gt.en||{})[e]??gt.en?.[e]??t??e;return Dn(s,n)}function pe(e){if(!e)return"";let t=Kt.get(e);if(!t)return e;return b(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 gs(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function fs(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class zt{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=b("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",b("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",(a)=>{if(a.key==="Enter"){a.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 r=J("div","bp-ap-foot");this.actBtn=Fe("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),r.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,r)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(J("div","bp-fb-empty",b("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=b("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",b("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(fs(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(gs(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 Jt{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","",b("sidebar.add.project","Add project")),s=Fe("×","icon",()=>this.close());s.title=b("common.close","Close"),s.setAttribute("aria-label",b("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",(r)=>{if(r.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=b("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",b("gpui.e.open.folder","Open folder")),e("clone",b("web.clone.tab","Clone from git")))}renderFolder(){let e=new zt(this.host.hub,(t)=>b("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=b("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",b("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",(u)=>this.repoKey(u)),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"),r=J("input");r.type="checkbox",r.checked=this.wantThread,r.setAttribute("data-testid","clone-thread"),r.addEventListener("change",()=>{this.wantThread=r.checked}),s.append(r,J("span","",b("web.clone.start.thread","Start a thread")));let a=[n,this.signinEl,this.destEl,s];if(this.firstText)a.push(J("div","bp-ap-first bp-dim",b("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 c=J("div","bp-ap-foot");this.cloneBtn=Fe(b("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),c.append(this.cloneBtn),a.push(o,c),t.append(...a),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,r)=>{let a=Fe("","bp-ap-sug"+(r===this.suggestIdx?" active":""));a.setAttribute("data-testid","clone-suggestion"),a.addEventListener("mousedown",(c)=>c.preventDefault()),a.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",b("web.clone.private","private")));if(a.append(o),s.description)a.append(J("div","bp-ap-sug-desc",s.description));i.push(a)}),n.length===0&&t){if(t.loading)i.push(J("div","bp-ap-sug-note",b("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 r=Fe(b("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});r.addEventListener("mousedown",(a)=>a.preventDefault()),r.setAttribute("data-testid","clone-signin-btn"),s.append(r)}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 a=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 c=Fe(b("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});c.setAttribute("data-testid","clone-change-folder"),a.append(o,c),n.push(a);let u=J("label","bp-ap-name");u.append(J("span","bp-ap-lbl",b("web.clone.folder.name","Folder name")));let l=J("input","bp-input");if(l.type="text",l.spellcheck=!1,l.value=this.nameText,l.setAttribute("data-testid","clone-name"),l.addEventListener("input",()=>{this.nameText=l.value,this.nameTouched=l.value.trim()!=="",this.startErr="",this.askDest(250)}),l.addEventListener("keydown",(p)=>{if(p.key==="Enter"&&this.canStart())p.preventDefault(),this.startClone()}),u.append(l),n.push(u),!t.ok&&t.error)n.push(this.errLine(pe(t.error)));else if(t.same)n.push(J("div","bp-ap-note bp-dim",b("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",r=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let a=e.querySelector('[data-testid="clone-name"]');if(a){if(a.focus(),r!==null)a.setSelectionRange(r,r)}}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(b("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new zt(this.host.hub,(i)=>b("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=_t();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=_t(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let r=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(r)}catch(r){let a=pe(r instanceof Error?r.message:String(r));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(a)}}apply(e){if(!e||e.id!==this.jobId)return;if(!jn(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&&Hn(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"?b("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?b("web.clone.stopped","Stopped cloning {repo}",{repo:i}):b("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),r=[J("div","bp-ap-job-title",s)];if(t.state==="running"){let a=J("div","bp-ap-phase",pe(t.phase||""));a.setAttribute("data-testid","clone-phase");let o=J("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),c=J("div","bp-ap-bar-fill");if(typeof t.pct==="number")c.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(c),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(r.push(a,o),t.detail)r.push(J("div","bp-ap-detail bp-dim",t.detail));let u=J("div","bp-ap-foot"),l=Fe(b("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((p)=>this.apply(p)).catch(()=>{})});l.setAttribute("data-testid","clone-cancel"),u.append(l),r.push(u)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let u=J("div","bp-ap-err",pe(t.error));u.setAttribute("data-testid","clone-error"),r.push(u)}let a=J("div","bp-ap-foot"),o=Fe(b("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(a.append(o),t.signin){let u=Fe(b("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});u.setAttribute("data-testid","clone-signin-btn"),a.append(u)}let c=Fe(b("web.clone.retry","Try again"),"primary",()=>{this.retry(t,c)});c.setAttribute("data-testid","clone-retry"),a.append(c),r.push(a)}else if(t.state==="done"){let a=t.notes??[];if(a.length>0){let l=J("ul","bp-ap-notes");l.setAttribute("data-testid","clone-notes");for(let p of a)l.appendChild(J("li","",pe(p)));r.push(l)}let o=J("div","bp-ap-foot"),c=t.thread?b("web.clone.open.thread","Open the thread"):b("web.clone.open.project","Open the project"),u=Fe(c,"primary",()=>this.goTo(t));u.setAttribute("data-testid","clone-open"),o.append(u),r.push(o)}e.replaceChildren(...r)}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",b("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(J("div","",b("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 r=Fe(this.copied?b("web.clone.copied","Copied"):b("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,r),n.push(i),t.url){let a=J("a","bp-ap-link",t.url);a.href=t.url,a.target="_blank",a.rel="noopener noreferrer",a.setAttribute("data-testid","clone-signin-url"),n.push(a)}}else if(t.state==="done")n.push(J("div","bp-ok",b("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 vs(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function vt(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 r=s[0];if(r.startsWith("`")&&r.endsWith("`")){let a=document.createElement("code");a.className="bp-code-inline",a.textContent=r.slice(1,-1),e.appendChild(a)}else if(r.startsWith("**")&&r.endsWith("**")){let a=document.createElement("strong");a.textContent=r.slice(2,-2),e.appendChild(a)}else if(r.startsWith("*")&&r.endsWith("*")){let a=document.createElement("em");a.textContent=r.slice(1,-1),e.appendChild(a)}else if(r.startsWith("[")){let a=s[2]??"",o=vs(s[3]??"");if(o){let c=document.createElement("a");c.href=o,c.target="_blank",c.rel="noopener noreferrer",c.textContent=a,e.appendChild(c)}else e.appendChild(document.createTextNode(a))}i=n.lastIndex}if(i=(e.ended??0)}function $n(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var vt={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","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","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.lang":"Language","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","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","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.lang":"Idioma","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":"分割表示には基板と回路図が必要です","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":"エージェント","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.lang":"言語","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 Gn(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 yt=ys(),Kt=new Set,Jt=new Map;for(let[e,t]of Object.entries(vt.en||{}))if(typeof t==="string"&&!Jt.has(t))Jt.set(t,e);function ys(){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 On(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=yt}On();function jt(e){return Kt.add(e),()=>{Kt.delete(e)}}function Vn(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!==yt;if(yt=n,On(),i)for(let s of Kt)s(yt);return i}function b(e,t,n){let s=(vt[yt]||vt.en||{})[e]??vt.en?.[e]??t??e;return Gn(s,n)}function pe(e){if(!e)return"";let t=Jt.get(e);if(!t)return e;return b(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 ws(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function Es(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class Yt{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=b("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",b("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",(a)=>{if(a.key==="Enter"){a.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 r=J("div","bp-ap-foot");this.actBtn=Fe("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),r.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,r)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(J("div","bp-fb-empty",b("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=b("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",b("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(Es(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(ws(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 Xt{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","",b("sidebar.add.project","Add project")),s=Fe("×","icon",()=>this.close());s.title=b("common.close","Close"),s.setAttribute("aria-label",b("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",(r)=>{if(r.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=b("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",b("gpui.e.open.folder","Open folder")),e("clone",b("web.clone.tab","Clone from git")))}renderFolder(){let e=new Yt(this.host.hub,(t)=>b("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=b("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",b("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",(m)=>this.repoKey(m)),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"),r=J("input");r.type="checkbox",r.checked=this.wantThread,r.setAttribute("data-testid","clone-thread"),r.addEventListener("change",()=>{this.wantThread=r.checked}),s.append(r,J("span","",b("web.clone.start.thread","Start a thread")));let a=[n,this.signinEl,this.destEl,s];if(this.firstText)a.push(J("div","bp-ap-first bp-dim",b("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 c=J("div","bp-ap-foot");this.cloneBtn=Fe(b("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),c.append(this.cloneBtn),a.push(o,c),t.append(...a),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,r)=>{let a=Fe("","bp-ap-sug"+(r===this.suggestIdx?" active":""));a.setAttribute("data-testid","clone-suggestion"),a.addEventListener("mousedown",(c)=>c.preventDefault()),a.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",b("web.clone.private","private")));if(a.append(o),s.description)a.append(J("div","bp-ap-sug-desc",s.description));i.push(a)}),n.length===0&&t){if(t.loading)i.push(J("div","bp-ap-sug-note",b("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 r=Fe(b("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});r.addEventListener("mousedown",(a)=>a.preventDefault()),r.setAttribute("data-testid","clone-signin-btn"),s.append(r)}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 a=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 c=Fe(b("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});c.setAttribute("data-testid","clone-change-folder"),a.append(o,c),n.push(a);let m=J("label","bp-ap-name");m.append(J("span","bp-ap-lbl",b("web.clone.folder.name","Folder name")));let d=J("input","bp-input");if(d.type="text",d.spellcheck=!1,d.value=this.nameText,d.setAttribute("data-testid","clone-name"),d.addEventListener("input",()=>{this.nameText=d.value,this.nameTouched=d.value.trim()!=="",this.startErr="",this.askDest(250)}),d.addEventListener("keydown",(p)=>{if(p.key==="Enter"&&this.canStart())p.preventDefault(),this.startClone()}),m.append(d),n.push(m),!t.ok&&t.error)n.push(this.errLine(pe(t.error)));else if(t.same)n.push(J("div","bp-ap-note bp-dim",b("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",r=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let a=e.querySelector('[data-testid="clone-name"]');if(a){if(a.focus(),r!==null)a.setSelectionRange(r,r)}}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(b("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new Yt(this.host.hub,(i)=>b("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=qt();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=qt(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let r=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(r)}catch(r){let a=pe(r instanceof Error?r.message:String(r));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(a)}}apply(e){if(!e||e.id!==this.jobId)return;if(!Fn(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&&$n(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"?b("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?b("web.clone.stopped","Stopped cloning {repo}",{repo:i}):b("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),r=[J("div","bp-ap-job-title",s)];if(t.state==="running"){let a=J("div","bp-ap-phase",pe(t.phase||""));a.setAttribute("data-testid","clone-phase");let o=J("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),c=J("div","bp-ap-bar-fill");if(typeof t.pct==="number")c.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(c),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(r.push(a,o),t.detail)r.push(J("div","bp-ap-detail bp-dim",t.detail));let m=J("div","bp-ap-foot"),d=Fe(b("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((p)=>this.apply(p)).catch(()=>{})});d.setAttribute("data-testid","clone-cancel"),m.append(d),r.push(m)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let m=J("div","bp-ap-err",pe(t.error));m.setAttribute("data-testid","clone-error"),r.push(m)}let a=J("div","bp-ap-foot"),o=Fe(b("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(a.append(o),t.signin){let m=Fe(b("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});m.setAttribute("data-testid","clone-signin-btn"),a.append(m)}let c=Fe(b("web.clone.retry","Try again"),"primary",()=>{this.retry(t,c)});c.setAttribute("data-testid","clone-retry"),a.append(c),r.push(a)}else if(t.state==="done"){let a=t.notes??[];if(a.length>0){let d=J("ul","bp-ap-notes");d.setAttribute("data-testid","clone-notes");for(let p of a)d.appendChild(J("li","",pe(p)));r.push(d)}let o=J("div","bp-ap-foot"),c=t.thread?b("web.clone.open.thread","Open the thread"):b("web.clone.open.project","Open the project"),m=Fe(c,"primary",()=>this.goTo(t));m.setAttribute("data-testid","clone-open"),o.append(m),r.push(o)}e.replaceChildren(...r)}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",b("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(J("div","",b("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 r=Fe(this.copied?b("web.clone.copied","Copied"):b("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,r),n.push(i),t.url){let a=J("a","bp-ap-link",t.url);a.href=t.url,a.target="_blank",a.rel="noopener noreferrer",a.setAttribute("data-testid","clone-signin-url"),n.push(a)}}else if(t.state==="done")n.push(J("div","bp-ok",b("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 Cs(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function wt(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 r=s[0];if(r.startsWith("`")&&r.endsWith("`")){let a=document.createElement("code");a.className="bp-code-inline",a.textContent=r.slice(1,-1),e.appendChild(a)}else if(r.startsWith("**")&&r.endsWith("**")){let a=document.createElement("strong");a.textContent=r.slice(2,-2),e.appendChild(a)}else if(r.startsWith("*")&&r.endsWith("*")){let a=document.createElement("em");a.textContent=r.slice(1,-1),e.appendChild(a)}else if(r.startsWith("[")){let a=s[2]??"",o=Cs(s[3]??"");if(o){let c=document.createElement("a");c.href=o,c.target="_blank",c.rel="noopener noreferrer",c.textContent=a,e.appendChild(c)}else e.appendChild(document.createTextNode(a))}i=n.lastIndex}if(i{navigator.clipboard?.writeText(l).then(()=>{y.textContent="✓",window.setTimeout(()=>{y.textContent=m},1200)}).catch(()=>{})}),d.append(g,y);let h=document.createElement("pre"),f=document.createElement("code");f.textContent=l,h.appendChild(f),p.append(d,h),t.appendChild(p);continue}if(!s.trim()){i++;continue}let r=/^(#{1,4})\s+(.+)$/.exec(s);if(r){let c=document.createElement(`h${Math.min(4,r[1].length+1)}`);c.className="bp-md-h",vt(c,r[2]),t.appendChild(c),i++;continue}if(s.startsWith("> ")){let c=document.createElement("blockquote");c.className="bp-md-quote";let u=[];while(i "))u.push(n[i].slice(2)),i++;vt(c,u.join(` -`)),t.appendChild(c);continue}if(/^\s*[-*]\s+/.test(s)){let c=document.createElement("ul");c.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))a.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let c=0;c0)o.appendChild(document.createElement("br"));vt(o,a[c])}t.appendChild(o)}return t}var Gn="http://www.w3.org/2000/svg";function wt(e){let t=document.createElementNS(Gn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),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(Gn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Xt(e){return e<10000000000?e*1000:e}function ys(e){if(!e)return"";return new Date(Xt(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function ws(e){if(!Number.isFinite(e)||e<=0||e>3600000)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 Yt(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class Zt{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;noProvider=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;planExpanded=new Set;planRevisingId="";planReviseDrafts=new Map;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=b("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{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",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=b("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 r=document.createElement("button");r.type="button",r.textContent=b("tools.retry","Retry"),r.addEventListener("click",n),i.append(s,r),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=b("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((r)=>!Yt(r)),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((r)=>r.id)),s=e.filter((r)=>!Yt(r)&&!i.has(r.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(Yt(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((a)=>a.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 r=this.liveNodes.get(e);if(r){if(r.replaceChildren(yt(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 a=document.createElement("span");a.className="bp-dim",a.textContent=pe(this.noProvider.text),n.appendChild(a)}let s=document.createElement("div");s.className="bp-banner-actions";let r=document.createElement("button");r.type="button",r.className="primary",r.setAttribute("data-testid","no-provider-accounts-btn"),r.textContent=pe(this.noProvider.button),r.addEventListener("click",()=>this.cb.onOpenAccounts?.()),s.appendChild(r),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||b("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 r=document.createElement("button");if(r.type="button",s.primary)r.className="primary";r.textContent=s.label,r.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(r)}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(yt(this.btwNote.a)),n.append(i,s);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,r),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 r=b("common.copy","Copy"),a=document.createElement("span");a.textContent=r,s.append(wt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),a),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{a.textContent="✓",window.setTimeout(()=>{a.textContent=r},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let c=document.createElement("span");c.textContent=b("reply.action","Reply"),o.append(wt(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),c),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let u=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),l=document.createElement("span");l.className="bp-entry-time";let p=ys(e.at);if(t)l.textContent=p,i.append(s,...u?[o]:[],l);else{let d=n&&e.at?ws(Xt(e.at)-Xt(n)):"",g=p?d?b("web.chat.finished.dur","Finished {time} · {dur}",{time:p,dur:d}):b("web.chat.finished","Finished {time}",{time:p}):"";l.textContent=e.live?b("web.chat.streaming","Streaming…"):g,i.append(l,s,...u?[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 r=document.createElement("div");r.className="bp-empty-state",r.textContent=b("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(r),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let r=document.createElement("div");r.className="bp-empty-state",r.textContent=b("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(r),this.listEl.replaceChildren(i);return}let s=0;for(let r of this.entries){if(r.kind==="user"&&r.at)s=r.at;let a=document.createElement("article");if(a.className=`bp-entry bp-entry-${r.kind}`+(r.live?" is-live":""),a.setAttribute("data-entry-id",r.id),r.kind==="tool"&&r.tool){let l=document.createElement("div");l.className=`bp-tool-pill bp-tool-${r.tool.state||"done"}`;let p=document.createElement("span");if(p.className="bp-tool-name",p.textContent=r.tool.name,l.appendChild(p),r.tool.summary){let d=document.createElement("span");d.className="bp-tool-summary",d.textContent=r.tool.summary,l.appendChild(d)}a.appendChild(l),i.appendChild(a);continue}if(r.kind==="ask"&&r.ask){let l=r.ask;if(l.kind==="plan"){a.appendChild(this.renderPlanAsk(l)),i.appendChild(a);continue}let p=document.createElement("div");p.className="bp-ask-card",p.setAttribute("data-testid",`ask-${l.id}`);let d=document.createElement("div");if(d.className="bp-ask-q",d.textContent=l.question,p.appendChild(d),l.state==="open"){let g=document.createElement("div");if(g.className="bp-ask-opts",l.options&&l.options.length>0)for(let y of l.options){let m=document.createElement("button");m.type="button",m.textContent=y.label,m.addEventListener("click",()=>this.cb.onAnswerAsk(l.id,y.id)),g.appendChild(m)}else{let y=document.createElement("input");y.type="text",y.className="bp-input",y.placeholder=b("web.chat.answer.placeholder","Type answer…");let m=document.createElement("button");m.type="button",m.className="primary",m.textContent=b("web.chat.answer.btn","Answer"),m.addEventListener("click",()=>{if(y.value.trim())this.cb.onAnswerAsk(l.id,y.value.trim())}),g.append(y,m)}p.appendChild(g)}else{let g=document.createElement("div");g.className="bp-ask-answered",g.textContent=b("web.chat.answered","Answered: {answer}",{answer:l.answered??""}),p.appendChild(g)}a.appendChild(p),i.appendChild(a);continue}let o=Boolean(r.text&&r.text.trim().length>0),c=Boolean(r.images&&r.images.length>0),u=Boolean(r.attachments&&r.attachments.length>0);if(!o&&!c&&!u&&!r.live)continue;if(r.replyTo?.quote){let l=document.createElement("div");l.className="bp-reply-quote",l.textContent=b("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:r.replyTo.quote});let p=r.replyTo.id;l.setAttribute("role","button"),l.tabIndex=0,l.setAttribute("data-testid","entry-reply-quote");let d=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(p);else this.goTo(p)};l.addEventListener("click",d),l.addEventListener("keydown",(g)=>{if(g.key==="Enter"||g.key===" ")g.preventDefault(),d()}),a.appendChild(l)}if(o||r.live){let l=document.createElement("div");if(l.className="bp-entry-body",r.kind==="user")l.textContent=r.text;else l.appendChild(yt(r.text||""));if(r.live)this.liveNodes.set(r.id,l);a.appendChild(l)}if(u&&r.attachments){let l=document.createElement("div");l.className="bp-entry-images";for(let p of r.attachments)if(p.previewUrl){let d=document.createElement("img");d.className="bp-reply-img",d.src=p.previewUrl,d.alt=p.name||"attachment",l.appendChild(d)}else if(p.path||p.name){let d=document.createElement("span");d.className="bp-tool-pill",d.textContent=p.name||p.path||"image",l.appendChild(d)}if(l.childElementCount>0)a.appendChild(l)}if(r.images&&r.images.length>0){let l=document.createElement("div");l.className="bp-entry-images";for(let p of r.images){let d=document.createElement("img");d.className="bp-reply-img",d.alt=p;let g=`${r.id}|${p}`,y=this.imageCache.get(g);if(y)d.src=y;else this.cb.onLoadImage(r.id,p).then((m)=>{if(!m)return;let h=m.url??(m.mime&&m.data?`data:${m.mime};base64,${m.data}`:"");if(!h)return;this.imageCache.set(g,h),d.src=h});l.appendChild(d)}a.appendChild(l)}a.appendChild(this.makeEntryActions(r,r.kind==="user",r.kind==="assistant"?s:void 0)),i.appendChild(a)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let r=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(r){if(r.focus({preventScroll:!0}),t.start!==null&&t.end!==null)r.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 r=wt(["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"]);r.classList.add("bp-plan-head-ic");let a=document.createElement("span");if(a.className="bp-plan-title",a.textContent=!e.head||e.head==="Proposed plan"?b("ask.plan","Proposed plan"):pe(e.head),s.append(r,a),e.state==="open"){let l=document.createElement("span");l.className="bp-plan-badge",l.textContent=b("gpui.ask.plan.ready","Ready for review"),s.appendChild(l)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn";let p=b("common.copy","Copy"),d=document.createElement("span");d.textContent=p,l.append(wt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),d),l.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{l.classList.add("copied"),d.textContent=b("web.clone.copied","Copied"),window.setTimeout(()=>{l.classList.remove("copied"),d.textContent=p},1200)}).catch(()=>{})}),s.appendChild(l)}let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn",c.setAttribute("data-testid","plan-expand"),c.textContent=t?b("gpui.c.term.collapse","Collapse"):b("gpui.c.term.expand","Expand"),c.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let l=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=l}),s.appendChild(c),i.appendChild(s);let u=document.createElement("div");if(u.className="bp-plan-body"+(t?" is-expanded":""),u.setAttribute("data-testid","plan-body"),u.appendChild(yt(e.question||"")),i.appendChild(u),e.state==="open"){let l=document.createElement("div");l.className="bp-plan-actions";let p=e.options?.find((m)=>m.id==="implement"||m.id.endsWith("|implement")),d=document.createElement("button");if(d.type="button",d.className="primary",d.setAttribute("data-testid","plan-implement"),d.textContent=p?.label&&p.label!=="Implement"?pe(p.label):b("approval.implement","Implement"),d.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,p?.id??"implement")}),l.appendChild(d),e.revise!==!1){let m=document.createElement("button");m.type="button",m.className="bp-plan-revise-btn"+(n?" active":""),m.setAttribute("data-testid","plan-revise"),m.append(wt(["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(b("gpui.ask.plan.revise","Revise"))),m.addEventListener("click",()=>{let h=this.planRevisingId!==e.id;this.planRevisingId=h?e.id:"";let f=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=f,h)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),l.appendChild(m)}let g=e.options?.find((m)=>m.id==="dismiss"||m.id.endsWith("|dismiss")),y=document.createElement("button");if(y.type="button",y.className="bp-plan-dismiss-btn",y.setAttribute("data-testid","plan-dismiss"),y.textContent=g?.label&&g.label!=="Dismiss"?pe(g.label):b("approval.dismiss","Dismiss"),y.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,g?.id??"dismiss")}),l.appendChild(y),i.appendChild(l),n){let m=document.createElement("div");m.className="bp-plan-revise",m.setAttribute("data-testid","plan-revise-drawer");let h=document.createElement("textarea");h.rows=2,h.className="bp-input bp-plan-revise-input",h.placeholder=b("gpui.ask.plan.reviseph","What should change in the plan?"),h.value=this.planReviseDrafts.get(e.id)??"";let f=document.createElement("button");f.type="button",f.className="bp-plan-revise-send",f.setAttribute("data-testid","plan-revise-send"),f.textContent=b("gpui.ask.plan.sendrev","Send revision"),f.disabled=h.value.trim().length===0;let w=()=>{let M=h.value.trim();if(!M)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${M}`)},C=()=>{this.closePlanRevise()};m.addEventListener("keydown",(M)=>{if(M.key==="Escape")M.preventDefault(),M.stopPropagation(),C()}),h.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,h.value),f.disabled=h.value.trim().length===0}),h.addEventListener("keydown",(M)=>{if(M.key==="Enter"&&!M.shiftKey)M.preventDefault(),w()}),f.addEventListener("click",w);let A=document.createElement("button");A.type="button",A.className="bp-btn-ghost",A.textContent=b("common.cancel","Cancel"),A.addEventListener("click",C),m.append(h,f,A),i.appendChild(m)}}else{let l=document.createElement("div");l.className="bp-ask-answered",l.textContent=b("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(l)}return i}}var On="http://www.w3.org/2000/svg",Vn=4,Un=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function It(e){let t=document.createElementNS(On,"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(On,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Qt(){return It(["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 Wn(){return It(["M6 4l14 8-14 8z"])}function Es(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class en{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=b("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 r=document.createElement("div");r.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"),r.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(Qt()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=b("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 a=document.createElement("div");a.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",a.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(a,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=b("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",b("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(It(["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=b("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",b("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(It(["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=b("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=b("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(r,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",(c)=>{let u=c.clipboardData?.items;if(!u)return;let l=[];for(let p=0;p0)c.preventDefault(),this.addFiles(l)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(c)=>{if(this.popupMode!=="none"){let u=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(c.key==="ArrowDown"){c.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,u),this.renderPopup();return}if(c.key==="ArrowUp"){c.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,u))%Math.max(1,u),this.renderPopup();return}if(c.key==="Tab"||c.key==="Enter"&&!c.shiftKey&&this.shouldCompleteOnEnter()){c.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(c.key==="Escape"){c.preventDefault(),this.closePopup();return}}if(c.key==="Tab"&&c.shiftKey&&this.planMode!==null){c.preventDefault(),this.cb.onCyclePlanMode?.();return}if(c.key==="Enter"&&!c.shiftKey)c.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=Es(t);if(this.providerMarkEl.textContent=i.glyph,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=b("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 r=`${b("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=r,this.planChipBtn.setAttribute("aria-label",r),this.planChipIconHost.replaceChildren(s?Wn():Qt()),this.planChipLbl.textContent=s?b("gpui.planmode.chip.building","Building"):t==="pending"?b("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?b("gpui.planmode.chip.once","Plan · 1t"):b("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?b("gpui.mgmt.plan.tab","Plan"):b("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 a=document.createElement("span");a.className="bp-plan-bar-ic",a.appendChild(s?Wn():Qt());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?b("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?b("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?b("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?b("gpui.planmode.bar.pending","Proposed plan awaits review below"):b("gpui.planmode.bar.executing","Building the approved plan");let c=[a,o];if(t==="armed"||t==="planning"){let u=document.createElement("div");u.className="bp-plan-scopes";let l=(p,d,g,y)=>{let m=document.createElement("button");return m.type="button",m.className="bp-plan-scope-btn"+(d?" active":""),m.textContent=p,m.disabled=!this.enabled,m.setAttribute("data-testid",y),m.addEventListener("click",()=>this.cb.onSetPlanMode?.(g)),m};u.append(l(b("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),l(b("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),l(b("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),c.push(u)}this.planBarEl.replaceChildren(...c)}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 r=document.createElement("span");if(r.className="bp-reply-strip-line",r.textContent=b("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,r),t)i.addEventListener("click",t);let a=document.createElement("button");a.type="button",a.className="icon bp-reply-strip-drop",a.textContent="×";let o=b("reply.cancel","Cancel reply");if(a.title=o,a.setAttribute("aria-label",o),a.setAttribute("data-testid","composer-reply-drop"),n)a.addEventListener("click",n);this.replyEl.replaceChildren(i,a),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} +`),i=0;while(i{navigator.clipboard?.writeText(d).then(()=>{v.textContent="✓",window.setTimeout(()=>{v.textContent=u},1200)}).catch(()=>{})}),l.append(h,v);let g=document.createElement("pre"),f=document.createElement("code");f.textContent=d,g.appendChild(f),p.append(l,g),t.appendChild(p);continue}if(!s.trim()){i++;continue}let r=/^(#{1,4})\s+(.+)$/.exec(s);if(r){let c=document.createElement(`h${Math.min(4,r[1].length+1)}`);c.className="bp-md-h",wt(c,r[2]),t.appendChild(c),i++;continue}if(s.startsWith("> ")){let c=document.createElement("blockquote");c.className="bp-md-quote";let m=[];while(i "))m.push(n[i].slice(2)),i++;wt(c,m.join(` +`)),t.appendChild(c);continue}if(/^\s*[-*]\s+/.test(s)){let c=document.createElement("ul");c.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))a.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let c=0;c0)o.appendChild(document.createElement("br"));wt(o,a[c])}t.appendChild(o)}return t}var Un="http://www.w3.org/2000/svg";function Ct(e){let t=document.createElementNS(Un,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),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(Un,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Zt(e){return e<10000000000?e*1000:e}function xs(e){if(!e)return"";return new Date(Zt(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function ks(e){if(!Number.isFinite(e)||e<=0||e>3600000)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 Qt(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class en{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;noProvider=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;planExpanded=new Set;planRevisingId="";planReviseDrafts=new Map;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=b("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{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",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=b("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 r=document.createElement("button");r.type="button",r.textContent=b("tools.retry","Retry"),r.addEventListener("click",n),i.append(s,r),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=b("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((r)=>!Qt(r)),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((r)=>r.id)),s=e.filter((r)=>!Qt(r)&&!i.has(r.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(Qt(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((a)=>a.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 r=this.liveNodes.get(e);if(r){if(r.replaceChildren(Et(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 a=document.createElement("span");a.className="bp-dim",a.textContent=pe(this.noProvider.text),n.appendChild(a)}let s=document.createElement("div");s.className="bp-banner-actions";let r=document.createElement("button");r.type="button",r.className="primary",r.setAttribute("data-testid","no-provider-accounts-btn"),r.textContent=pe(this.noProvider.button),r.addEventListener("click",()=>this.cb.onOpenAccounts?.()),s.appendChild(r),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||b("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 r=document.createElement("button");if(r.type="button",s.primary)r.className="primary";r.textContent=s.label,r.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(r)}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(Et(this.btwNote.a)),n.append(i,s);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,r),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 r=b("common.copy","Copy"),a=document.createElement("span");a.textContent=r,s.append(Ct(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),a),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{a.textContent="✓",window.setTimeout(()=>{a.textContent=r},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let c=document.createElement("span");c.textContent=b("reply.action","Reply"),o.append(Ct(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),c),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let m=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),d=document.createElement("span");d.className="bp-entry-time";let p=xs(e.at);if(t)d.textContent=p,i.append(s,...m?[o]:[],d);else{let l=n&&e.at?ks(Zt(e.at)-Zt(n)):"",h=p?l?b("web.chat.finished.dur","Finished {time} · {dur}",{time:p,dur:l}):b("web.chat.finished","Finished {time}",{time:p}):"";d.textContent=e.live?b("web.chat.streaming","Streaming…"):h,i.append(d,s,...m?[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 r=document.createElement("div");r.className="bp-empty-state",r.textContent=b("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(r),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let r=document.createElement("div");r.className="bp-empty-state",r.textContent=b("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(r),this.listEl.replaceChildren(i);return}let s=0;for(let r of this.entries){if(r.kind==="user"&&r.at)s=r.at;let a=document.createElement("article");if(a.className=`bp-entry bp-entry-${r.kind}`+(r.live?" is-live":""),a.setAttribute("data-entry-id",r.id),r.kind==="tool"&&r.tool){let d=document.createElement("div");d.className=`bp-tool-pill bp-tool-${r.tool.state||"done"}`;let p=document.createElement("span");if(p.className="bp-tool-name",p.textContent=r.tool.name,d.appendChild(p),r.tool.summary){let l=document.createElement("span");l.className="bp-tool-summary",l.textContent=r.tool.summary,d.appendChild(l)}a.appendChild(d),i.appendChild(a);continue}if(r.kind==="ask"&&r.ask){let d=r.ask;if(d.kind==="plan"){a.appendChild(this.renderPlanAsk(d)),i.appendChild(a);continue}let p=document.createElement("div");p.className="bp-ask-card",p.setAttribute("data-testid",`ask-${d.id}`);let l=document.createElement("div");if(l.className="bp-ask-q",l.textContent=d.question,p.appendChild(l),d.state==="open"){let h=document.createElement("div");if(h.className="bp-ask-opts",d.options&&d.options.length>0)for(let v of d.options){let u=document.createElement("button");u.type="button",u.textContent=v.label,u.addEventListener("click",()=>this.cb.onAnswerAsk(d.id,v.id)),h.appendChild(u)}else{let v=document.createElement("input");v.type="text",v.className="bp-input",v.placeholder=b("web.chat.answer.placeholder","Type answer…");let u=document.createElement("button");u.type="button",u.className="primary",u.textContent=b("web.chat.answer.btn","Answer"),u.addEventListener("click",()=>{if(v.value.trim())this.cb.onAnswerAsk(d.id,v.value.trim())}),h.append(v,u)}p.appendChild(h)}else{let h=document.createElement("div");h.className="bp-ask-answered",h.textContent=b("web.chat.answered","Answered: {answer}",{answer:d.answered??""}),p.appendChild(h)}a.appendChild(p),i.appendChild(a);continue}let o=Boolean(r.text&&r.text.trim().length>0),c=Boolean(r.images&&r.images.length>0),m=Boolean(r.attachments&&r.attachments.length>0);if(!o&&!c&&!m&&!r.live)continue;if(r.replyTo?.quote){let d=document.createElement("div");d.className="bp-reply-quote",d.textContent=b("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:r.replyTo.quote});let p=r.replyTo.id;d.setAttribute("role","button"),d.tabIndex=0,d.setAttribute("data-testid","entry-reply-quote");let l=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(p);else this.goTo(p)};d.addEventListener("click",l),d.addEventListener("keydown",(h)=>{if(h.key==="Enter"||h.key===" ")h.preventDefault(),l()}),a.appendChild(d)}if(o||r.live){let d=document.createElement("div");if(d.className="bp-entry-body",r.kind==="user")d.textContent=r.text;else d.appendChild(Et(r.text||""));if(r.live)this.liveNodes.set(r.id,d);a.appendChild(d)}if(m&&r.attachments){let d=document.createElement("div");d.className="bp-entry-images";for(let p of r.attachments)if(p.previewUrl){let l=document.createElement("img");l.className="bp-reply-img",l.src=p.previewUrl,l.alt=p.name||"attachment",d.appendChild(l)}else if(p.path||p.name){let l=document.createElement("span");l.className="bp-tool-pill",l.textContent=p.name||p.path||"image",d.appendChild(l)}if(d.childElementCount>0)a.appendChild(d)}if(r.images&&r.images.length>0){let d=document.createElement("div");d.className="bp-entry-images";for(let p of r.images){let l=document.createElement("img");l.className="bp-reply-img",l.alt=p;let h=`${r.id}|${p}`,v=this.imageCache.get(h);if(v)l.src=v;else this.cb.onLoadImage(r.id,p).then((u)=>{if(!u)return;let g=u.url??(u.mime&&u.data?`data:${u.mime};base64,${u.data}`:"");if(!g)return;this.imageCache.set(h,g),l.src=g});d.appendChild(l)}a.appendChild(d)}a.appendChild(this.makeEntryActions(r,r.kind==="user",r.kind==="assistant"?s:void 0)),i.appendChild(a)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let r=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(r){if(r.focus({preventScroll:!0}),t.start!==null&&t.end!==null)r.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 r=Ct(["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"]);r.classList.add("bp-plan-head-ic");let a=document.createElement("span");if(a.className="bp-plan-title",a.textContent=!e.head||e.head==="Proposed plan"?b("ask.plan","Proposed plan"):pe(e.head),s.append(r,a),e.state==="open"){let d=document.createElement("span");d.className="bp-plan-badge",d.textContent=b("gpui.ask.plan.ready","Ready for review"),s.appendChild(d)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let d=document.createElement("button");d.type="button",d.className="bp-plan-head-btn";let p=b("common.copy","Copy"),l=document.createElement("span");l.textContent=p,d.append(Ct(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),l),d.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{d.classList.add("copied"),l.textContent=b("web.clone.copied","Copied"),window.setTimeout(()=>{d.classList.remove("copied"),l.textContent=p},1200)}).catch(()=>{})}),s.appendChild(d)}let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn",c.setAttribute("data-testid","plan-expand"),c.textContent=t?b("gpui.c.term.collapse","Collapse"):b("gpui.c.term.expand","Expand"),c.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let d=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=d}),s.appendChild(c),i.appendChild(s);let m=document.createElement("div");if(m.className="bp-plan-body"+(t?" is-expanded":""),m.setAttribute("data-testid","plan-body"),m.appendChild(Et(e.question||"")),i.appendChild(m),e.state==="open"){let d=document.createElement("div");d.className="bp-plan-actions";let p=e.options?.find((u)=>u.id==="implement"||u.id.endsWith("|implement")),l=document.createElement("button");if(l.type="button",l.className="primary",l.setAttribute("data-testid","plan-implement"),l.textContent=p?.label&&p.label!=="Implement"?pe(p.label):b("approval.implement","Implement"),l.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,p?.id??"implement")}),d.appendChild(l),e.revise!==!1){let u=document.createElement("button");u.type="button",u.className="bp-plan-revise-btn"+(n?" active":""),u.setAttribute("data-testid","plan-revise"),u.append(Ct(["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(b("gpui.ask.plan.revise","Revise"))),u.addEventListener("click",()=>{let g=this.planRevisingId!==e.id;this.planRevisingId=g?e.id:"";let f=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=f,g)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),d.appendChild(u)}let h=e.options?.find((u)=>u.id==="dismiss"||u.id.endsWith("|dismiss")),v=document.createElement("button");if(v.type="button",v.className="bp-plan-dismiss-btn",v.setAttribute("data-testid","plan-dismiss"),v.textContent=h?.label&&h.label!=="Dismiss"?pe(h.label):b("approval.dismiss","Dismiss"),v.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,h?.id??"dismiss")}),d.appendChild(v),i.appendChild(d),n){let u=document.createElement("div");u.className="bp-plan-revise",u.setAttribute("data-testid","plan-revise-drawer");let g=document.createElement("textarea");g.rows=2,g.className="bp-input bp-plan-revise-input",g.placeholder=b("gpui.ask.plan.reviseph","What should change in the plan?"),g.value=this.planReviseDrafts.get(e.id)??"";let f=document.createElement("button");f.type="button",f.className="bp-plan-revise-send",f.setAttribute("data-testid","plan-revise-send"),f.textContent=b("gpui.ask.plan.sendrev","Send revision"),f.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()};u.addEventListener("keydown",(N)=>{if(N.key==="Escape")N.preventDefault(),N.stopPropagation(),x()}),g.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,g.value),f.disabled=g.value.trim().length===0}),g.addEventListener("keydown",(N)=>{if(N.key==="Enter"&&!N.shiftKey)N.preventDefault(),w()}),f.addEventListener("click",w);let S=document.createElement("button");S.type="button",S.className="bp-btn-ghost",S.textContent=b("common.cancel","Cancel"),S.addEventListener("click",x),u.append(g,f,S),i.appendChild(u)}}else{let d=document.createElement("div");d.className="bp-ask-answered",d.textContent=b("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(d)}return i}}var Wn="http://www.w3.org/2000/svg",_n=4,zn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Ht(e){let t=document.createElementNS(Wn,"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(Wn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function tn(){return Ht(["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 qn(){return Ht(["M6 4l14 8-14 8z"])}function As(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class nn{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=b("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 r=document.createElement("div");r.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"),r.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(tn()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=b("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 a=document.createElement("div");a.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",a.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(a,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=b("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",b("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(Ht(["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=b("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",b("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(Ht(["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=b("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=b("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(r,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",(c)=>{let m=c.clipboardData?.items;if(!m)return;let d=[];for(let p=0;p0)c.preventDefault(),this.addFiles(d)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(c)=>{if(this.popupMode!=="none"){let m=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(c.key==="ArrowDown"){c.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,m),this.renderPopup();return}if(c.key==="ArrowUp"){c.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,m))%Math.max(1,m),this.renderPopup();return}if(c.key==="Tab"||c.key==="Enter"&&!c.shiftKey&&this.shouldCompleteOnEnter()){c.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(c.key==="Escape"){c.preventDefault(),this.closePopup();return}}if(c.key==="Tab"&&c.shiftKey&&this.planMode!==null){c.preventDefault(),this.cb.onCyclePlanMode?.();return}if(c.key==="Enter"&&!c.shiftKey)c.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=As(t);if(this.providerMarkEl.textContent=i.glyph,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=b("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 r=`${b("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=r,this.planChipBtn.setAttribute("aria-label",r),this.planChipIconHost.replaceChildren(s?qn():tn()),this.planChipLbl.textContent=s?b("gpui.planmode.chip.building","Building"):t==="pending"?b("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?b("gpui.planmode.chip.once","Plan · 1t"):b("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?b("gpui.mgmt.plan.tab","Plan"):b("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 a=document.createElement("span");a.className="bp-plan-bar-ic",a.appendChild(s?qn():tn());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?b("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?b("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?b("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?b("gpui.planmode.bar.pending","Proposed plan awaits review below"):b("gpui.planmode.bar.executing","Building the approved plan");let c=[a,o];if(t==="armed"||t==="planning"){let m=document.createElement("div");m.className="bp-plan-scopes";let d=(p,l,h,v)=>{let u=document.createElement("button");return u.type="button",u.className="bp-plan-scope-btn"+(l?" active":""),u.textContent=p,u.disabled=!this.enabled,u.setAttribute("data-testid",v),u.addEventListener("click",()=>this.cb.onSetPlanMode?.(h)),u};m.append(d(b("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),d(b("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),d(b("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),c.push(m)}this.planBarEl.replaceChildren(...c)}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 r=document.createElement("span");if(r.className="bp-reply-strip-line",r.textContent=b("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,r),t)i.addEventListener("click",t);let a=document.createElement("button");a.type="button",a.className="icon bp-reply-strip-drop",a.textContent="×";let o=b("reply.cancel","Cancel reply");if(a.title=o,a.setAttribute("aria-label",o),a.setAttribute("data-testid","composer-reply-drop"),n)a.addEventListener("click",n);this.replyEl.replaceChildren(i,a),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=b("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=b("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",b("web.composer.attach","Attach image")),this.voiceBtn.title=b("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",b("web.composer.voice","Voice dictation")),this.sendBtn.textContent=b("composer.send","Send"),this.stopBtn.textContent=b("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 r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.desc||t.label,i.append(s,r),i.addEventListener("mousedown",(a)=>{a.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 r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.detail||t.label,i.append(s,r),i.addEventListener("mousedown",(a)=>{a.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),r=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=r+s,this.textarea.selectionStart=this.textarea.selectionEnd=r.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!Un.has(t.type)){this.showError(b("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=Vn){this.showError(b("web.composer.maximages","At most {max} images per message.",{max:Vn}));break}let n=await new Promise((s,r)=>{let a=new FileReader;a.onload=()=>s(String(a.result||"")),a.onerror=()=>r(Error("read failed")),a.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 r=document.createElement("button");r.type="button",r.className="icon bp-attach-rm",r.textContent="×",r.title=b("common.remove","Remove"),r.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,r),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 _n(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 xs=new Set(["bom","checks","life","plan","fab"]);function Rt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&xs.has(t.id))}function Xn(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 jt(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=a}return i}function at(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 ot(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 Cs=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),ks=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Zn(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let a of i)if(Cs.has(a))return a;let s=i[0]??"",r=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(ks.has(r)){let a=s.split("-");if(a.length>=2&&/^\d+$/.test(a[1]))return`${a[0]}-${a[1]}`;return a[0]}return i.slice(0,2).join("_")}function Qn(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 ${at(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${at(n)}`,tone:"warn"};return{text:at(n),tone:"ok"}}function ei(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((r)=>r==="dnp"&&Boolean(i.dnp)||s.includes(r))})}function ti(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function nn(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 Ht(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 ni(e){return e.state==="routed"||e.state==="verified"}function ii(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 si(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 ri(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,r=0;if(typeof e.total!=="number"){for(let a of e.layers??[])for(let o of a.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")r+=1;else if(o.state==="approved")n+=1}else if(e.routing)r=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:r,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function ai(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 oi(e){return e==="extra"?"costs-more limits":"base-price limits"}function sn(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function li(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function rn(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var qn=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],Kn=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function ci(e){let t=2166136261;for(let n=0;n>>0;return t}function Et(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 qn[ci(i)%qn.length]}function lt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return Kn[ci(e)%Kn.length]}function di(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),r=Math.max(1,Math.abs(e[3]-e[1])),a=Math.max(20,t-i*2),o=Math.max(20,n-i*2),c=Math.max(0.05,Math.min(200,Math.min(a/s,o/r)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:c,fitted:c,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 Dt(e,t,n,i,s){let r=Math.max(0.0001,e.scale);return[e.cx+(t-i*0.5)/r,e.cy+(n-s*0.5)/r]}function pi(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 mi(e,t,n,i,s,r){let a=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),c=Math.max(a,Math.min(o,e.scale*t)),[u,l]=Dt(e,n,i,s,r);return{...e,cx:u-(n-s*0.5)/c,cy:l-(i-r*0.5)/c,scale:c,touched:!0}}function ui(e,t,n,i){let s=e.map((a)=>[a[0],a[1]]);if(s.length===0)return[n];let r=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(r,0,[n[0],n[1]]),s}function an(e,t,n){let i=n?3:2;if(e.length<=i||t<0||t>=e.length)return null;let s=e.map((r)=>[r[0],r[1]]);return s.splice(t,1),s}function As(e,t,n,i,s,r){let a=s-n,o=r-i,c=a*a+o*o;if(c<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let u=Math.max(0,Math.min(1,((e-n)*a+(t-i)*o)/c)),l=n+u*a,p=i+u*o;return(e-l)*(e-l)+(t-p)*(t-p)}function zn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==u>t&&e<(c-a)*(t-o)/(u-o+0.000000000001)+a)i=!i}return i}function on(e,t){return Math.max(5,Math.min(32,e*t))}function Ft(e,t,n,i,s,r,a,o,c){if(i){for(let d of e){if(d.layer!==n||d.id!==i||d.locked)continue;let g=d.path??[];for(let y=0;y=3)for(let y=0;y=0;d--){let g=t[d];if(g.layer!==n)continue;let y=g.outline??[];if(!zn(l,p,y))continue;if(!(g.holes??[]).some((h)=>zn(l,p,h)))return{kind:"region",id:g.id}}return null}function ct(e){let t=null,n=null,i=[];for(let r of e){if(!r.layer)continue;i.push(r.layer);let a=r.items??[],o=a.filter((u)=>u.kind==="corridor").length,c=a.filter((u)=>u.kind==="plane").length;if((o>0||r.role==="signal")&&(!t||o>t.count))t={count:o,layer:r.layer};if((c>0||r.role==="power"||r.role==="plane")&&(!n||c>n.count))n={count:c,layer:r.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let r of i){if(s.length>=2)break;if(!s.includes(r))s.push(r)}return s}function Jn(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 a=1;a=s&&o>0.000000001){let c=(s-r)/o;return[e[a-1][0]+(e[a][0]-e[a-1][0])*c,e[a-1][1]+(e[a][1]-e[a-1][1])*c]}r+=o}return e[e.length-1]}function it(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 hi(e,t,n){if(e==="split"&&n.length>0)return t.filter((i)=>n.includes(i.layer));return t}function tn(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function Yn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==u>t&&e<(c-a)*(t-o)/(u-o+0.000000000001)+a)i=!i}return i}function bi(e,t){if(e.length<3)return null;let n=1/0,i=1/0,s=-1/0,r=-1/0,a=0,o=0;for(let u of e)n=Math.min(n,u[0]),i=Math.min(i,u[1]),s=Math.max(s,u[0]),r=Math.max(r,u[1]),a+=u[0],o+=u[1];let c=[[(n+s)*0.5,(i+r)*0.5],[a/e.length,o/e.length]];for(let u of[0.5,0.25,0.75,0.125,0.875])for(let l of[0.5,0.25,0.75,0.125,0.875])c.push([n+(s-n)*l,i+(r-i)*u]);for(let u of c)if(Yn(u[0],u[1],e)&&!t.some((l)=>Yn(u[0],u[1],l)))return u;return null}function gi(e,t,n,i,s,r){let a=[];for(let l of e){let p=l.nets??0,d=l.path??[];if(p<=0||d.length<2)continue;let g=0;for(let y=1;y{let d=l.sel||l.hov?1:0,g=p.sel||p.hov?1:0;if(g!==d)return g-d;if(p.nets!==l.nets)return p.nets-l.nets;return l.b.id.localeCompare(p.b.id)});let o=[],c=[],u=(l,p,d,g,y)=>[l-d*0.5-y,p-g*0.5-y,l+d*0.5+y,p+g*0.5+y];for(let l of a){let p=l.b.name||"",d=String(l.nets),g=p?`${p} · ${l.nets}`:d,y=(l.sel||l.hov||l.pxLen>=95)&&p?[g,d]:[d],m=null,h=(w,C)=>Math.max(C*0.5+3,Math.min(Math.max(C*0.5+3,n-C*0.5-3),w)),f=(w,C)=>Math.max(C*0.5+3,Math.min(Math.max(C*0.5+3,i-C*0.5-3),w));e:for(let w of y){let C=Math.max(16,w.length*5.9+10),A=15;for(let M of[0.5,0.35,0.65,0.22,0.78]){let P=Jn(l.pts,M);if(!P)continue;let[T,B]=Ve(t,P[0],P[1],n,i),R=h(T,C),O=f(B,15),H=u(R,O,C,15,2);if(!o.some((ae)=>tn(H,ae))){m={id:l.b.id,text:w,cx:R,cy:O,pw:C,ph:15,col:l.col,sel:l.sel};break e}}}if(!m){let w=Jn(l.pts,0.5);if(w){let[C,A]=Ve(t,w[0],w[1],n,i),M=Math.max(16,d.length*6.5+8),P=15,T=h(C,M);for(let B of[-18,18]){let R=f(A+B,15);if(!o.some((O)=>tn(u(T,R,M,15,2),O))){m={id:l.b.id,text:d,cx:T,cy:R,pw:M,ph:15,col:l.col,sel:l.sel};break}}}}if(m)o.push(u(m.cx,m.cy,m.pw,m.ph,2)),c.push(m)}return c}function fi(e,t,n,i,s,r=[]){let a=new Set(s),o=[];for(let l of e){if(!l.r||!l.b||l.b.length!==4)continue;let[p,d]=Ve(t,l.b[0],l.b[1],n,i),[g,y]=Ve(t,l.b[2],l.b[3],n,i),m=Math.abs(g-p),h=Math.abs(y-d);if(m<13||h<9)continue;let f=(p+g)*0.5,w=(d+y)*0.5;if(f<8||f>n-8||w<8||w>i-8)continue;o.push({text:l.r,cx:f,cy:w,bw:l.r.length*5.8+4,bh:11,score:m*h+(a.has(l.r)?1e4:0)})}o.sort((l,p)=>p.score-l.score);let c=[...r],u=[];for(let l of o){let p=[l.cx-l.bw*0.5,l.cy-l.bh*0.5,l.cx+l.bw*0.5,l.cy+l.bh*0.5];if(!c.some((g)=>tn(p,g)))c.push(p),u.push({text:l.text,cx:l.cx,cy:l.cy})}return u}function vi(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 $t(e,t){if(!t||t.length===0)return e;let n=new Map;for(let r of e)if(r.layer)n.set(r.layer,r);let i=[],s=new Set;for(let r of t){if(!r.layer)continue;s.add(r.layer);let a=n.get(r.layer);if(a)i.push(a);else i.push({layer:r.layer,index:r.index,title:r.title||`L${r.index} · ${r.layer}`,subtitle:r.subtitle||"",role:r.role,status:"proposed",done:0,approved:0,total:0,items:[]})}for(let r of e)if(r.layer&&!s.has(r.layer))i.push(r);return i}function yi(e,t,n,i,s,r,a,o){return e===t&&n===i&&s===r&&(o===void 0||a>=o)}var wi="#111917",Ls="#16201d",Ss="rgba(212, 224, 219, 0.92)",Ps="rgba(61, 80, 73, 0.72)",Ns="rgba(82, 107, 97, 0.85)";var Ei="#f59e0b",Ms="#eef5f2",xi="#ef4444";function st(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),r=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(r))return`rgba(${i}, ${s}, ${r}, ${t})`}return`rgba(20, 184, 166, ${t})`}function Ts(e,t,n){let i=0.14,s=0.45,r=0.85,a=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,r=0.91;break;case"edited":i=0.2,s=0.56,r=0.95;break;case"routed":case"verified":i=0.08,s=0.26,r=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,r=0.27;break;case"blocked":i=0.18,s=0.48,r=0.88,a=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),r=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:r,bad:a}}function Bs(e,t,n){let i=0.27,s=0.83,r=!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,r=!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:r}}function Is(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 ln{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=$t(e.layers,e.copperLayers);if(t.length===0)return[];if(e.gridMode==="all")return t;if(e.gridMode==="single"){let s=e.shownLayers.find((a)=>t.some((o)=>o.layer===a))??ct(t)[0]??t[0]?.layer,r=t.find((a)=>a.layer===s);return r?[r]:[]}let n=e.shownLayers.length>0&&e.shownLayers.every((s)=>t.some((r)=>r.layer===s))?e.shownLayers.slice(0,2):ct(t),i=[];for(let s of n){let r=t.find((a)=>a.layer===s);if(r)i.push(r)}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 r=this.buildCard(s);this.cards.set(s.layer,r),this.root.appendChild(r.el)}}else for(let s of n){let r=this.cards.get(s.layer);if(r)this.syncCardHeaderAndLegend(r,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 di(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"),r=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((w)=>w.kind==="plane");s.className="bp-plan-card-bar "+(r?"pwr":"sig");let a=document.createElement("span");a.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn bp-plan-mini-btn",c.textContent="✓",c.title=b("gpui.mgmt.plan.layer","Approve layer"),c.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let u=document.createElement("button");u.type="button",u.className="bp-mgmt-btn bp-plan-mini-btn",u.textContent="✗",u.title=b("gpui.mgmt.plan.rejectlayer","Reject layer"),u.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,a,o,c,u);let l=document.createElement("div");l.className="bp-plan-card-sub",n.append(i,l);let p=document.createElement("div");p.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 g=document.createElement("div");g.className="bp-plan-hover-hud bp-hidden",p.append(d,g);let y=document.createElement("div");y.className="bp-plan-legend bp-hidden",t.append(n,p,y);let m=d.getContext("2d"),h=new ResizeObserver(()=>this.scheduleDraw());h.observe(p),this.attachPointerListeners(d,e.layer);let f={layer:e.layer,el:t,canvas:d,ctx:m,legendEl:y,okBtn:c,noBtn:u,statusEl:o,titleEl:a,subtitleEl:l,hoverHudEl:g,ro:h};return this.syncCardHeaderAndLegend(f,e),f}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=it(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=Is(t);e.statusEl.className=`bp-plan-card-status tone-${s.tone==="warn"?"dim":s.tone}`,e.statusEl.textContent=i.length>0?b(s.key,s.label):"",e.statusEl.classList.toggle("bp-hidden",i.length===0);let r=i.some((o)=>o.state==="proposed"||o.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!r);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!r);let a=(this.state?.regions??[]).filter((o)=>o.layer===t.layer);if(a.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let o=document.createDocumentFragment();for(let c of a){let u=document.createElement("button");u.type="button";let l=this.state?.selectedId===c.id;u.className="bp-plan-legend-chip"+(l?" active":"");let p=document.createElement("span");p.className="bp-plan-legend-sw",p.style.background=Et(c.net||c.id,c.color||"");let d=document.createElement("span");d.textContent=c.net||c.id,u.append(p,d),u.addEventListener("click",()=>{this.cb.onSelect(c.id),this.cb.onFocusItem(c.id)}),o.appendChild(u)}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 r=e.getBoundingClientRect(),a=i.clientX-r.left,o=i.clientY-r.top,c=Math.max(1,r.width),u=Math.max(1,r.height),l=this.getCam(t,c,u),p=Ft(s.bands,s.regions,t,s.selectedId,l,c,u,a,o);if(i.button===2){if(p?.kind==="vertex"){let d=this.getItemPts(p.id,p.isPlane),g=an(d,p.idx,p.isPlane);if(g)this.selectedVertex=null,this.cb.onCommitFields(p.id,{[p.isPlane?"outline":"path"]:g})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},p?.kind==="vertex"){let d=this.getItemPts(p.id,p.isPlane),g=d.map((y)=>[y[0],y[1]]);this.selectedVertex={id:p.id,idx:p.idx},this.drag={layer:t,kind:"vertex",id:p.id,isPlane:p.isPlane,idx:p.idx,pts:d.map((y)=>[y[0],y[1]]),origPts:g,moved:!1},this.scheduleDraw()}else if(p?.kind==="midpoint"){let d=this.getItemPts(p.id,p.isPlane),g=d.map((h)=>[h[0],h[1]]),y=ui(d,p.segIdx,p.pos,p.isPlane),m=p.isPlane&&p.segIdx+1>=d.length?y.length-1:Math.min(p.segIdx+1,y.length-1);this.selectedVertex={id:p.id,idx:m},this.patchLocalItem(p.id,p.isPlane,y),this.drag={layer:t,kind:"vertex",id:p.id,isPlane:p.isPlane,idx:m,pts:y,origPts:g,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:a,lastY:o}}),e.addEventListener("pointermove",(i)=>{let s=this.state;if(!s)return;let r=e.getBoundingClientRect(),a=i.clientX-r.left,o=i.clientY-r.top,c=Math.max(1,r.width),u=Math.max(1,r.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let A=this.getCam(t,c,u);this.setCam(t,pi(A,a-this.drag.lastX,o-this.drag.lastY)),this.drag.lastX=a,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 m=this.getCam(t,c,u),[h,f]=Dt(m,a,o,c,u),w=[Math.round(h*1000)/1000,Math.round(f*1000)/1000];this.drag.moved=!0,this.drag.pts[this.drag.idx]=w;let C=this.drag.pts.map((A)=>[A[0],A[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,C),this.scheduleDraw();return}let l=this.getCam(t,c,u),p=Ft(s.bands,s.regions,t,s.selectedId,l,c,u,a,o),d=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",g=this.hover?.hit.kind??"",y=p?p.id:"";if(this.hover=p?{layer:t,hit:p}:null,e.style.cursor=p?"pointer":"crosshair",d!==y||(p?.kind??"")!==g)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((r)=>[r[0],r[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,r=this.drag,a=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(i.pointerId))e.releasePointerCapture(i.pointerId);if(r&&r.kind==="vertex"&&r.layer===t){if(r.moved)this.cb.onCommitFields(r.id,{[r.isPlane?"outline":"path"]:r.pts});else this.cb.onDragEnd?.(),this.scheduleDraw();return}if(s&&a&&Math.hypot(i.clientX-a.x,i.clientY-a.y)<4.5){let o=e.getBoundingClientRect(),c=i.clientX-o.left,u=i.clientY-o.top,l=Math.max(1,o.width),p=Math.max(1,o.height),d=this.getCam(t,l,p),g=Ft(s.bands,s.regions,t,s.selectedId,d,l,p,c,u);if(g&&(g.kind==="band"||g.kind==="region")){this.cb.onSelect(g.id),this.cb.onFocusItem(g.id);return}if(!g&&s.selectedId){this.cb.onSelect("");return}}this.cb.onDragEnd?.()}),e.addEventListener("wheel",(i)=>{i.preventDefault();let s=e.getBoundingClientRect(),r=i.clientX-s.left,a=i.clientY-s.top,o=Math.max(1,s.width),c=Math.max(1,s.height),u=this.getCam(t,o,c),l=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,mi(u,l,r,a,o,c)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((r)=>r.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((r)=>r.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),r=n.regions.find((o)=>o.id===i),a="";if(s)a=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(r)a=r.reference?`${r.net||i} · ${r.reference}`:r.net||i;if(!a)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=a}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((a)=>a.id===t.selectedId),i=t.regions.find((a)=>a.id===t.selectedId),s=Boolean(n?.locked??i?.locked),r=e.key.toLowerCase();if(r==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(r==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(r==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(r==="w"&&n&&!s){e.preventDefault();let a=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+a))*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 a=Boolean(i),o=this.getItemPts(t.selectedId,a),c=an(o,this.selectedVertex.idx,a);if(c)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[a?"outline":"path"]:c})}}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)),r=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${r}px`;let a=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*a),c=Math.round(r*a);if(n.canvas.width!==o||n.canvas.height!==c)n.canvas.width=o,n.canvas.height=c;n.ctx.setTransform(a,0,0,a,0,0),this.drawLayer(n.ctx,n.layer,s,r,e)}}drawLayer(e,t,n,i,s){let r=this.getCam(t,n,i),a=(m,h)=>Ve(r,m,h,n,i);e.fillStyle=wi,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((m)=>m.length>=3);if(e.fillStyle=Ls,o.length>0){e.beginPath();for(let m of o){for(let h=0;hm.layer===t),u=this.hover?.layer===t?this.hover.hit:null;for(let m of c){let h=m.outline??[];if(h.length<3)continue;let f=s.selectedId===m.id,w=u?.id===m.id,C=Bs(m.state||"proposed",f,w),A=Et(m.net||m.id,m.color||"");e.beginPath();for(let P=0;PB)B=H;if(ae>R)R=ae}if(Math.abs(B-P)>=38&&Math.abs(R-T)>=18){let O=bi(h,m.holes??[]);if(O){let[H,ae]=a(O[0],O[1]);e.fillStyle=st(A,f?0.91:0.67),e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(M,H,ae)}}}}if(e.strokeStyle=Ss,e.lineWidth=1.25,e.lineCap="round",e.lineJoin="round",o.length>0){e.beginPath();for(let m of o){for(let h=0;hm.layer===t),d=gi(p,r,n,i,s.selectedId,u?.id??""),g=d.map((m)=>[m.cx-m.pw*0.5-1,m.cy-m.ph*0.5-1,m.cx+m.pw*0.5+1,m.cy+m.ph*0.5+1]),y=[];for(let m of p){for(let h of m.from??[])y.push(h);for(let h of m.to??[])y.push(h)}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 m of fi(l,r,n,i,y,g))e.fillText(m.text,m.cx,m.cy);for(let m of p){let h=m.guides??[];if(h.length===0)continue;let f=s.selectedId===m.id||u?.id===m.id,w=lt(m.name||m.id,m.color||"");e.strokeStyle=st(w,f?0.38:0.17),e.lineWidth=f?1:0.7,e.beginPath();for(let C of h){let[A,M]=a(C[0],C[1]),[P,T]=a(C[2],C[3]);e.moveTo(A,M),e.lineTo(P,T)}e.stroke()}for(let m of p){let h=m.path??[];if(h.length<2)continue;let f=s.selectedId===m.id,w=u?.id===m.id,C=Ts(m.state||"proposed",f,w),A=lt(m.name||m.id,m.color||""),M=on(m.width??1.5,r.scale),P=()=>{e.beginPath();for(let T=0;T{let w=f?h.length:Math.max(0,h.length-1);for(let C=0;Cn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return Rt(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,r]of Object.entries(n.data))if(r&&typeof r==="object")this.infos.set(`mgmt.${s}.${i}`,r)}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=Rt(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 a of t){let o=document.createElement("button");o.type="button";let c=this.openPanel===a.id;o.className="bp-mgmt-tab"+(c?" active":""),o.setAttribute("data-testid",`mgmt-tab-${a.id}`),o.setAttribute("aria-pressed",c?"true":"false");let u=document.createElement("span");u.textContent=pe(a.label),o.appendChild(u);let l=this.getPanelData(a.id),p=Xn(l);if(p){let d=document.createElement("span");d.className=`bp-mgmt-badge bp-tone-${p.tone}`,d.textContent=p.text,o.appendChild(d)}o.addEventListener("click",()=>this.togglePanel(a.id)),i.appendChild(o)}if(n.appendChild(i),this.openPanel){let a=document.createElement("button");a.type="button",a.className="icon bp-mgmt-close",a.textContent="×",a.title=b("gpui.mgmt.close","Close the panel"),a.setAttribute("aria-label",b("gpui.mgmt.close","Close the panel")),a.setAttribute("data-testid","mgmt-close"),a.addEventListener("click",()=>this.closePanel()),n.appendChild(a)}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)),r=document.createDocumentFragment();if(this.errorMsg){let a=document.createElement("div");a.className="bp-mgmt-note bp-tone-bad",a.textContent=this.errorMsg,r.appendChild(a)}switch(this.openPanel){case"bom":r.appendChild(this.renderBom());break;case"checks":r.appendChild(this.renderChecks());break;case"life":r.appendChild(this.renderLife());break;case"plan":r.appendChild(this.renderPlan());break;case"fab":r.appendChild(this.renderFab());break}if(this.panelEl.replaceChildren(r),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 r=document.createElement("span"),a=t.source==="kicad";if(r.className="bp-mgmt-pill"+(a?" accent":""),r.textContent=a?"live":"saved",i.append(s,r),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let u=document.createElement("span");u.className="bp-dim",u.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${ot(t.cost)}/board`:`${ot(t.cost)}/board`,i.appendChild(u)}if(t.paused){let u=document.createElement("span");u.className="bp-mgmt-faint",u.textContent="Stock check paused",i.appendChild(u)}if(e.appendChild(i),t.stock_note){let u=document.createElement("div");u.className="bp-mgmt-note bp-mgmt-faint",u.textContent=pe(t.stock_note),e.appendChild(u)}let o=this.bomEditingId?n.find((u)=>u.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let u=document.createElement("div");u.className="bp-mgmt-filter-row";let l=document.createElement("input");l.type="text",l.className="bp-mgmt-filter",l.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",l.value=this.bomFilter,l.setAttribute("data-testid","mgmt-bom-filter"),l.addEventListener("input",()=>{this.bomFilter=l.value,this.renderBomRows(c,n)}),u.appendChild(l),e.appendChild(u)}let c=document.createElement("div");return c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(c,n),e.appendChild(c),e}renderBomRows(e,t){let n=ei(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((r)=>Boolean(r.mpn)||Boolean(r.fab)),s=document.createDocumentFragment();for(let r of n){let a=Array.isArray(r.refs)?r.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===r.id?" active":"")+(r.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${r.id}`);let c=document.createElement("div");c.className="bp-mgmt-row-line";let u=document.createElement("span");if(u.className="bp-mgmt-strong bp-mgmt-flex1",u.textContent=jt(a,24),c.appendChild(u),r.dnp){let m=document.createElement("span");m.className="bp-mgmt-pill",m.textContent=b("gpui.mgmt.bom.dnp","DNP"),c.appendChild(m)}else{let m=Qn(r.stock);if(m){let h=document.createElement("span");h.className=`bp-tone-${m.tone}`,h.textContent=m.text,c.appendChild(h)}}let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn",l.textContent="Edit",l.addEventListener("click",(m)=>{m.stopPropagation(),this.bomEditGen++,this.bomEditingId=r.id,this.bomEditDraft=r.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),c.appendChild(l);let p=document.createElement("div");p.className="bp-mgmt-row-sub";let d=[`${r.qty??a.length}×`,r.value??"",Zn(r.footprint??"")].filter(Boolean).join(" · "),g=document.createElement("span");g.className="bp-dim",g.textContent=d;let y=document.createElement("span");if(y.className="bp-mgmt-flex1",r.mpn)y.textContent=r.mpn;else if(i&&!r.dnp)y.className+=" bp-tone-warn",y.textContent=b("gpui.mgmt.bom.nompn","no MPN");if(p.append(g,y),!r.dnp&&typeof r.stock?.price==="number"){let m=document.createElement("span");m.className="bp-dim",m.textContent=ot(r.stock.price),p.appendChild(m)}if(!r.dnp&&r.stock?.class){let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent=pe(r.stock.class),p.appendChild(m)}o.append(c,p),o.addEventListener("click",()=>{this.bomSelectedId=r.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=jt(n,30);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,r);let a=document.createElement("input");a.type="text",a.className="bp-mgmt-filter",a.placeholder="MPN",a.value=this.bomEditDraft,a.addEventListener("input",()=>{this.bomEditDraft=a.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),c=async(d,g=!1)=>{let y=o();this.bomEditStatus="Writing…",this.render();try{let m=await this.cb.hub.rpc("mgmt.bom.edit",d);if(!sn(y,o()))return;this.bomLastUndo=!g&&(m.changed??0)>0?{project:d.project,editId:y.editId,refs:d.refs.slice(),field:d.field,was:typeof m.was==="string"?m.was:d.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=g?"Restored":(m.changed??0)===0?"No change":m.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(m){if(!sn(y,o()))return;this.bomEditStatus=m instanceof Error?m.message:"Could not save edit"}this.render()},u=document.createElement("div");u.className="bp-mgmt-btn-row";let l=document.createElement("button");l.type="button",l.className="primary bp-mgmt-btn",l.textContent="Save MPN",l.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let p=document.createElement("button");if(p.type="button",p.className="bp-mgmt-btn",p.textContent=e.dnp?"Clear DNP":"Mark DNP",p.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),u.append(l,p),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let d=this.bomLastUndo,g=document.createElement("button");g.type="button",g.className="bp-mgmt-btn",g.textContent="Undo",g.addEventListener("click",()=>{c(li(d),!0)}),u.appendChild(g)}if(t.append(i,a,u),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(),r=(d)=>t.sources?.[d]?.judged===!0,a=document.createElement("div");a.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=b("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),a.appendChild(o);for(let d of i){let g=document.createElement("button");g.type="button",g.className="bp-mgmt-btn"+(this.checksSource===d?" active":""),g.textContent=s(d)+(r(d)?" · judged":""),g.addEventListener("click",()=>{this.checksSource=this.checksSource===d?"":d,this.render()}),a.appendChild(g)}let c=document.createElement("span");c.className="bp-mgmt-flex1";let u=document.createElement("button");if(u.type="button",u.className="bp-mgmt-btn",u.textContent=b("gpui.mgmt.checks.run","Run"),u.addEventListener("click",()=>{let d=this.watchGen,g=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:g}).then(()=>{if(d!==this.watchGen||g!==this.project)return;this.checksStatus="",this.render()}).catch((y)=>{if(d!==this.watchGen||g!==this.project)return;this.checksStatus=y instanceof Error?y.message:"Could not run checks",this.render()})}),a.append(c,u),e.appendChild(a),this.checksStatus){let d=document.createElement("div");d.className="bp-mgmt-note bp-dim",d.textContent=this.checksStatus,e.appendChild(d)}let l=document.createElement("div");l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-checks-rows");let p=ti(n,this.checksSource);if(p.length===0)l.appendChild(this.makeEmpty("No check findings."));else for(let d of p){let g=d.severity==="error"?"bad":d.severity==="warning"?"warn":"faint",y=document.createElement("div");y.className="bp-mgmt-group-head";let m=document.createElement("span");m.className=`bp-mgmt-dot bp-tone-bg-${g}`;let h=document.createElement("span");h.className="bp-mgmt-flex1",h.textContent=`${s(d.source)} · ${d.rule}`;let f=document.createElement("span");f.className=`bp-tone-${g}`,f.textContent=String(d.n),y.append(m,h,f),l.appendChild(y);for(let w of d.rows??[]){let C=document.createElement("div");C.className="bp-mgmt-row"+(this.checksSelectedId===w.id?" active":"");let A=document.createElement("div");if(A.textContent=pe(w.title??""),C.appendChild(A),w.names||this.checksSelectedId===w.id){let M=document.createElement("div");M.className="bp-mgmt-row-sub";let P=document.createElement("span");if(P.className="bp-dim bp-mgmt-flex1",P.textContent=w.names??"",M.appendChild(P),this.checksSelectedId===w.id){let T=document.createElement("button");T.type="button",T.className="bp-mgmt-btn accent",T.textContent=b("gpui.mgmt.checks.fix","Fix with agent"),T.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((O)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!rn(R,H))return;if(O.text)this.cb.onSendText(O.text),this.checksStatus="Sent to agent",this.render()}).catch((O)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!rn(R,H))return;this.checksStatus=O instanceof Error?O.message:"Could not send finding",this.render()})}),M.appendChild(T)}C.appendChild(M)}C.addEventListener("click",()=>{this.checksSelectedId=w.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:w.id}).catch(()=>{}),this.render()}),l.appendChild(C)}}return e.appendChild(l),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 c of["active","nrnd","eol"]){let u=i[c]??0,l=nn(c),p=document.createElement("span");p.className=u>0?`bp-tone-${l.tone}`:"bp-mgmt-faint",p.textContent=`${l.label} ${u}`,n.appendChild(p)}if((i.unknown??0)>0){let c=document.createElement("span");c.className="bp-mgmt-faint",c.textContent=`${i.unknown} unknown`,n.appendChild(c)}if(t.since){let c=document.createElement("span");c.className="bp-mgmt-flex1";let u=document.createElement("span");u.className="bp-mgmt-faint",u.textContent=`since ${Ht(t.since)} (${t.samples??0})`,n.append(c,u)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let r=t.bom?.cost??[],a=t.bom?.instock??[],o=t.bom?.lines??0;if(r.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 c=r[r.length-1],u=a[a.length-1],l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=`Parts/board: ${ot(c[1])} · ${Math.round(u?.[1]??0)}/${o} lines in stock (${Ht(c[0])})`,s.appendChild(l)}for(let c of t.parts??[]){let u=this.lifeSelectedKey===c.key,l=nn(c.lifecycle??"unknown"),p=document.createElement("div");p.className="bp-mgmt-row"+(u?" active":"");let d=document.createElement("div");d.className="bp-mgmt-row-line";let g=document.createElement("span");g.className="bp-mgmt-strong",g.textContent=jt(c.refs??[],14);let y=document.createElement("span");y.className="bp-mgmt-flex1 bp-dim",y.textContent=c.mpn||c.key;let m=document.createElement("span");if(m.className=`bp-tone-${l.tone}`,m.textContent=l.label,d.append(g,y,m),typeof c.stock==="number"){let h=document.createElement("span");h.className="bp-dim",h.textContent=at(c.stock),d.appendChild(h)}if(p.appendChild(d),u){let h=document.createElement("div");if(h.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)h.textContent=b("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let f=this.lifePartSamples[this.lifePartSamples.length-1];h.textContent=`${this.lifePartSamples.length} samples · latest ${f.at?Ht(f.at):""}`+(typeof f.stock==="number"?` · stock ${at(f.stock)}`:"")+(typeof f.price==="number"?` · ${ot(f.price)}`:"")}else h.textContent=b("gpui.mgmt.life.nopart","No reading of this part yet.");p.appendChild(h)}p.addEventListener("click",()=>{if(this.lifeSelectedKey===c.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=c.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:c.key}).then((h)=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(h.samples)?h.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(p)}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(b("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(E,k)=>{let j=this.watchGen,N=this.project;this.planStatus="",this.cb.hub.rpc(E,{pro:N,...k}).catch((K)=>{if(j!==this.watchGen||N!==this.project)return;this.planOptimistic.clear(),this.planStatus=K instanceof Error?K.message:b("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,N=t.revision??0;this.cb.hub.rpc("plan.get",{pro:j,board:!0}).then((K)=>{let te=vi(K);if(!te)return;let D=typeof te.revision==="number"?te.revision:N;if(!yi(E,this.watchGen,k,this.planHydrateGen,j,this.project,D,this.planHydratedRev))return;this.planHydratedRev=D,this.planHydratedKey=`${j}:${D}`,this.planHydratedBoard=te.board??null,this.planHydratedDraw=te.draw??null,this.render()}).catch(()=>{})}let s=t.on===!0,r=document.createElement("div");r.className="bp-plan-header";let a=document.createElement("div");a.className="bp-plan-toggle";let o=document.createElement("span");o.className="bp-mgmt-strong",o.textContent=b("gpui.mgmt.plan.before","Plan before routing"),o.title=s?b("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."):b("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."),a.appendChild(o);let c=t.awaiting??0,u=t.blocked??0,l=t.done??0,p=t.total??0,d=t.revision??0,g=t.empty?[]:ri(t),y=g.reduce((E,k)=>E+k.count,0);if(!t.empty){let E=si(t),k=document.createElement("span");if(k.className=`bp-plan-status-badge tone-${E.tone}`,k.textContent=b(E.key,E.label),a.appendChild(k),d>0){let N=document.createElement("span");N.className="bp-dim",N.textContent=`v${d}`,a.appendChild(N)}let j=document.createElement("span");if(j.className="bp-plan-header-counts bp-mgmt-flex1 "+(c>0?"bp-tone-warn":u>0?"bp-tone-bad":"bp-dim"),j.textContent=p>0?`${l}/${p} ${b("gpui.mgmt.plan.done","done")}`:c>0?b("web.plan.awaiting","{n} awaiting approval",{n:c}):b("gpui.mgmt.plan.nothing","Nothing awaits your approval"),a.appendChild(j),!t.live){let N=document.createElement("span");N.className="bp-mgmt-pill",N.textContent=b("gpui.mgmt.plan.saved","saved plan"),a.appendChild(N)}}else{let E=document.createElement("span");E.className="bp-mgmt-flex1",a.appendChild(E)}let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn bp-plan-chip-btn"+(s?" active":""),m.setAttribute("data-testid","mgmt-plan-on"),m.setAttribute("aria-pressed",s?"true":"false"),m.textContent=b("gpui.bots.recall.on","On"),m.addEventListener("click",()=>n("plan.enable",{on:!0}));let h=document.createElement("button");if(h.type="button",h.className="bp-mgmt-btn bp-plan-chip-btn"+(!s?" active":""),h.setAttribute("data-testid","mgmt-plan-off"),h.setAttribute("aria-pressed",!s?"true":"false"),h.textContent=b("gpui.bots.recall.off","Off"),h.addEventListener("click",()=>n("plan.enable",{on:!1})),a.append(m,h),r.appendChild(a),y>0){let E=document.createElement("div");E.className="bp-plan-segbar";for(let k of g){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)}r.appendChild(E)}e.appendChild(r);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=b("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=b("gpui.mgmt.plan.noboard","No routing plan for this board.");let j=document.createElement("div");return j.className="bp-mgmt-faint",j.textContent=b("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),E.append(k,j),e.appendChild(E),e}let f=t.stackup_summary??"",w=Array.isArray(t.impedances)?t.impedances:[],C=Boolean(f)||w.length>0,A=document.createElement("div");if(A.className="bp-mgmt-head",c>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=b("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=b("gpui.mgmt.plan.stop","Stop routing"),E.addEventListener("click",()=>n("plan.stop",{})),A.appendChild(E)}if(t.live&&l>0){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-verify"),E.textContent=b("gpui.mgmt.plan.verify","Verify"),E.addEventListener("click",()=>n("plan.verify",{})),A.appendChild(E)}let M=document.createElement("span");if(M.className="bp-mgmt-flex1",A.appendChild(M),C){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=`${b("gpui.mgmt.plan.stackup.short","Stackup")} ${this.planStackupOpen?"▾":"▸"}`,E.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),A.appendChild(E)}let P=document.createElement("button");P.type="button",P.className="bp-mgmt-btn",P.setAttribute("data-testid","mgmt-plan-hide"),P.textContent=this.planHideDone?b("gpui.mgmt.plan.show","Show done"):b("gpui.mgmt.plan.hide","Hide done"),P.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),A.appendChild(P),e.appendChild(A);let T=Array.isArray(t.asks)?t.asks:[];if(T.length>0){let E=T.map((te)=>te.what||"").filter(Boolean).join(", "),k=T[0]?.note||"",j=document.createElement("div");j.className="bp-plan-elsewhere";let N=document.createElement("div");N.className="bp-plan-ask-col";let K=document.createElement("div");if(K.className="bp-tone-warn",K.textContent=E?b("gpui.mgmt.plan.requested","Approval requested: {what}",{what:E}):b("gpui.mgmt.plan.reqplain","Approval requested"),N.appendChild(K),k){let te=document.createElement("div");te.className="bp-dim",te.textContent=k,N.appendChild(te)}j.appendChild(N),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"?b("gpui.mgmt.plan.refused","KiCad refused"):pe(this.planStatus);let j=document.createElement("button");j.type="button",j.className="icon",j.textContent="×",j.title=b("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?b("gpui.mgmt.plan.keysnote",k):pe(t.keys_note),e.appendChild(E)}if(C&&this.planStackupOpen){let E=document.createElement("div");if(E.className="bp-plan-stackup-body",E.setAttribute("data-testid","mgmt-plan-stackup-body"),f){let k=document.createElement("div");k.className="bp-dim",k.textContent=f,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,N)=>{let K=document.createElement("button");return K.type="button",K.className="bp-mgmt-btn bp-plan-chip-btn"+(k?" active":""),K.setAttribute("data-testid",j),K.setAttribute("aria-pressed",k?"true":"false"),K.textContent=E,K.addEventListener("click",N),K},R=document.createElement("div");if(R.className="bp-plan-viewbar",R.append(B(b("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),B(b("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),B(b("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=b("gpui.mgmt.plan.fit","Fit"),j.addEventListener("click",()=>this.planCanvas?.fitAll()),R.append(E,B(b("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),B(b("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),B(b("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),k,B(b("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),j)}let O=document.createElement("span");O.className="bp-mgmt-flex1";let H=document.createElement("button");H.type="button",H.className="bp-mgmt-btn bp-plan-mini-btn",H.setAttribute("data-testid","mgmt-plan-expand"),H.textContent=this.planExpanded?b("gpui.mgmt.plan.compact","Compact"):b("gpui.mgmt.plan.expand","Expand"),H.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),R.append(O,H),e.appendChild(R);let ae=Boolean(this.planHydratedBoard)&&this.planHydratedKey.startsWith(`${this.project}:`)&&(this.planHydratedKey===i||this.planHydratedRev!==void 0&&this.planHydratedRev>=(t.revision??0)),ue=ae&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},oe=ae&&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}}),Le=(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}}),Ne=[],he=(t.layers??[]).map((E)=>{let k=[];for(let j of E.items??[]){let N=this.planOptimistic.get(j.id);if(!N){k.push(j);continue}let K={...j,width:typeof N.width==="number"?N.width:j.width,locked:typeof N.locked==="boolean"?N.locked:j.locked,edited:!0,state:j.state==="proposed"?"edited":j.state};if(typeof N.layer==="string"&&N.layer!==E.layer)Ne.push({target:N.layer,item:K});else k.push(K)}return{...E,items:k}});for(let E of Ne){let k=he.find((j)=>j.layer===E.target);if(k)k.items=[...k.items??[],E.item]}let be=$t(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))??ct(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):ct(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),N=(k.items??[]).length,K=it(k.layer,t.copper_layers,be)||k.title||k.layer,te=N>0?`${K} · ${N}`:K,D=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(N===0&&!j)D.classList.add("empty-layer");E.appendChild(D)}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 N=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:E,fields:k}],...N!==void 0?{base:N}:{}})};if(this.planCommitFields=le,this.planSelectedId){let E="",k=null;for(let j of he){let N=(j.items??[]).find((K)=>K.id===this.planSelectedId);if(N){E=j.layer,k=N;break}}if(k){let j=it(E,t.copper_layers,be),N=document.createElement("div");N.className="bp-plan-inspector",N.setAttribute("data-testid","mgmt-plan-inspector");let K=document.createElement("div");K.className="bp-plan-ins-row";let te=document.createElement("span");te.className="bp-plan-ins-sw",te.style.background=k.kind==="corridor"?lt(k.name||k.id,k.color||""):Et(k.name||k.id,k.color||"");let D=document.createElement("span");D.className="bp-mgmt-strong",D.textContent=k.name||k.id;let z=document.createElement("span");if(z.className="bp-dim",z.textContent=j,K.append(te,D,z),k.edited||k.state==="edited"){let Y=document.createElement("span");Y.className="bp-plan-ins-pill warn",Y.textContent=b("gpui.mgmt.plan.edited","Edited"),K.appendChild(Y)}if(k.locked){let Y=document.createElement("span");Y.className="bp-plan-ins-pill",Y.textContent=b("gpui.mgmt.plan.locked","Locked"),K.appendChild(Y)}let je=document.createElement("span");je.className="bp-mgmt-flex1",K.appendChild(je);let Se=document.createElement("button");if(Se.type="button",Se.className="bp-mgmt-btn bp-plan-mini-btn",Se.setAttribute("data-testid","mgmt-plan-lock"),Se.textContent=k.locked?b("gpui.mgmt.plan.unlock","Unlock"):b("gpui.mgmt.plan.lock","Lock"),Se.addEventListener("click",()=>le(k.id,{locked:!k.locked})),K.appendChild(Se),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=b("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=b("gpui.mgmt.plan.reject","Reject"),ve.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[k.id],approve:!1})),K.append(Y,ve)}let me=document.createElement("button");me.type="button",me.className="bp-mgmt-btn bp-plan-mini-btn",me.setAttribute("data-testid","mgmt-plan-note-toggle"),me.textContent=b("gpui.mgmt.plan.addnote","Add note"),me.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let Me=document.createElement("button");if(Me.type="button",Me.className="icon",Me.textContent="×",Me.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.render()}),K.append(me,Me),N.appendChild(K),!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=b("gpui.mgmt.plan.width","Width");let He=document.createElement("button");He.type="button",He.className="bp-mgmt-btn bp-plan-mini-btn",He.setAttribute("data-testid","mgmt-plan-w-down"),He.textContent="-",He.addEventListener("click",()=>{let Ue=Math.round(Math.max(0.15,ie-0.25)*100)/100;le(k.id,{width:Ue})});let re=document.createElement("span");re.className="bp-plan-ins-val",re.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,He,re,ge,_e)}let ve=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((ie)=>ie.layer):he.map((ie)=>ie.layer);if(ve.length>0){let ie=document.createElement("span");ie.className="bp-dim",ie.textContent=b("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(N.appendChild(Y),this.planMoveLayerOpen&&ve.length>0){let ie=document.createElement("div");ie.className="bp-plan-ins-row";for(let ke of ve){let He=it(ke,t.copper_layers,be);ie.appendChild(B(He,ke===E,`mgmt-plan-move-${ke}`,()=>{if(this.planMoveLayerOpen=!1,ke!==E)le(k.id,{layer:ke});else this.render()}))}N.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=b("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=b("gpui.mgmt.plan.addnote","Add note"),Y.append(ve,ie),Y.addEventListener("submit",(ke)=>{ke.preventDefault();let He=ve.value.trim();if(!He)return;ve.value="",this.planNoteOpen=!1;let re=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:k.id,text:He}],...re!==void 0?{base:re}:{}})}),N.appendChild(Y)}if(this.planViewMode!=="list"&&!k.locked){let Y=document.createElement("div");Y.className="bp-plan-hint",Y.textContent=b("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),N.appendChild(Y)}e.appendChild(N)}}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=b("gpui.mgmt.plan.done","done"),ce=hi(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=b("gpui.mgmt.plan.noitems","No corridors or planes on this layer"),ne.appendChild(E)}for(let E of ce){let k=E.items??[],j=it(E.layer,t.copper_layers,be)||E.layer;if(this.planViewMode==="split"){if(ce.length>1){let N=document.createElement("div");N.className="bp-plan-split-divider";let K=E.role==="power"||E.role==="plane",te=document.createElement("span");te.className="bp-plan-card-bar "+(K?"pwr":"sig");let D=document.createElement("span");D.className="bp-mgmt-strong",D.textContent=j;let z=document.createElement("span");z.className="bp-dim",z.textContent=`${E.done??0}/${k.length} ${X}`,N.append(te,D,z),ne.appendChild(N)}}else{let N=document.createElement("div");N.className="bp-mgmt-group-head bp-plan-layer-head";let K=document.createElement("div");K.className="bp-mgmt-row-line";let te=document.createElement("span");te.className="bp-mgmt-strong",te.textContent=j;let D=document.createElement("span");if(D.className="bp-dim bp-mgmt-flex1",D.textContent=`${E.role?`${E.role} · `:""}${E.done??0}/${k.length} ${X}`,K.append(te,D),E.status!=="approved"&&k.length>0){let z=document.createElement("button");z.type="button",z.className="bp-mgmt-btn",z.textContent=b("gpui.mgmt.plan.layer","Approve layer"),z.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=b("gpui.mgmt.plan.reject","Reject"),je.addEventListener("click",()=>n("plan.approve",{layer:E.layer,ids:[],approve:!1})),K.append(z,je)}if(N.appendChild(K),E.stackup){let z=document.createElement("div");z.className="bp-plan-layer-stackup",z.textContent=E.stackup,N.appendChild(z)}ne.appendChild(N)}for(let N of k){if(this.planHideDone&&ni(N))continue;let K=this.planSelectedId===N.id,te=document.createElement("div");te.className="bp-mgmt-row bp-plan-row"+(K?" active":""),te.setAttribute("data-testid",`mgmt-plan-row-${N.id}`);let D=document.createElement("div");D.className="bp-mgmt-row-line";let z=document.createElement("span");z.className=`bp-plan-swatch bp-plan-st-${N.state||"proposed"}`,z.style.setProperty("--swatch-color",N.color||"#8a8a8a");let je=document.createElement("span");je.className="bp-mgmt-flex1"+(N.state==="blocked"||N.state==="failed"?" bp-tone-bad":N.state==="edited"?" bp-tone-warn":N.state==="rejected"||N.state==="routed"||N.state==="verified"?" bp-dim":""),je.textContent=`${N.name||N.id}${N.locked?" \uD83D\uDD12":""}`;let Se=[];if(N.kind==="plane"){if(N.reference)Se.push(b("gpui.mgmt.plan.reference","over {layer}",{layer:N.reference}))}else{let Y=N.nets??0;Se.push(Y===1?b("web.plan.net.one","1 net"):b("web.plan.nets","{n} nets",{n:Y}))}if(typeof N.width==="number"&&Number.isFinite(N.width))Se.push(`${N.width.toFixed(2)}mm`);if(N.impedance)Se.push(N.impedance);let me=Se.join(" · "),Me=document.createElement("span");if(Me.className="bp-plan-mark "+(N.state==="blocked"||N.state==="failed"?"bp-tone-bad":N.state==="verified"||N.state==="routed"?"bp-tone-ok":N.state==="approved"?"bp-tone-accent":"bp-dim"),Me.textContent=ii(N),D.append(z,je,Me),N.state==="proposed"||N.state==="edited"){let Y=document.createElement("button");Y.type="button",Y.className="bp-mgmt-btn",Y.textContent="✓",Y.title=b("gpui.mgmt.plan.layer","Approve layer"),Y.addEventListener("click",(ie)=>{ie.stopPropagation(),n("plan.approve",{layer:"",ids:[N.id],approve:!0})});let ve=document.createElement("button");ve.type="button",ve.className="bp-mgmt-btn",ve.textContent="✗",ve.title=b("gpui.mgmt.plan.reject","Reject"),ve.addEventListener("click",(ie)=>{ie.stopPropagation(),n("plan.approve",{layer:"",ids:[N.id],approve:!1})}),D.append(Y,ve)}if(te.appendChild(D),me){let Y=document.createElement("div");Y.className="bp-mgmt-row-sub bp-plan-detail bp-dim",Y.textContent=me,te.appendChild(Y)}if(N.state==="routing"&&typeof N.total==="number"&&N.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((N.routed??0)/N.total*100)));ve.style.width=`${ie}%`,Y.appendChild(ve),te.appendChild(Y)}if(N.problem_text){let Y=document.createElement("div");Y.className="bp-plan-problem",Y.textContent=N.problem_text,te.appendChild(Y)}te.addEventListener("click",()=>{this.planSelectedId=N.id,n("plan.focus",{id:N.id}),this.render()}),ne.appendChild(te)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new ln({onSelect:(N)=>{if(this.planSelectedId=N,!N)this.planNoteOpen=!1;this.render()},onFocusItem:(N)=>{n("plan.focus",{id:N})},onDragEnd:()=>{if(this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onCommitFields:(N,K)=>{(this.planCommitFields??le)(N,K)},onApproveLayer:(N,K)=>{n("plan.approve",{layer:N,ids:[],approve:K})},onQuickApprove:(N,K)=>{n("plan.approve",{layer:"",ids:N,approve:K})}});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:ue,bands:we,regions:Le,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=b("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,C={})=>{let A=this.watchGen,M=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:M,action:w,...C}).catch((P)=>{if(A!==this.watchGen||M!==this.project)return;this.fabStatus=P instanceof Error?P.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=b("gpui.mgmt.fab.thefab","The fab");let r=document.createElement("span");r.className="bp-dim bp-mgmt-flex1",r.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${oi(t.tier??"")}`;let a=document.createElement("button");if(a.type="button",a.className="bp-mgmt-btn",a.textContent=b("gpui.mgmt.fab.refresh","Refresh"),a.addEventListener("click",()=>n("refresh")),i.append(s,r,a),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 c=t.review,u=document.createElement("div");u.className="bp-mgmt-row";let l=document.createElement("div");l.className="bp-mgmt-row-line";let p=document.createElement("span"),d=(c?.counts?.error??0)>0;if(p.className="bp-mgmt-flex1 "+(d?"bp-tone-bad":"bp-dim"),p.textContent=c?.running?"Reviewing the design…":c?.at==null?"No design review yet":`${c.counts?.error??0} must-fix · ${c.counts?.warning??0} should-fix · ${c.counts?.info??0} notes${c.scope?` (${c.scope})`:""}`,l.appendChild(p),c?.at!=null){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.findings","Findings"),w.addEventListener("click",()=>this.togglePanel("checks")),l.appendChild(w)}if(!c?.running){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.reviewbtn","Review"),w.addEventListener("click",()=>n("review")),l.appendChild(w)}if(c?.judge){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.judge","Datasheets"),w.addEventListener("click",()=>{if(c.judge)this.cb.onSendText(c.judge)}),l.appendChild(w)}u.appendChild(l),o.appendChild(u);let g=ai(t.drc?.state??""),y=document.createElement("div");y.className="bp-mgmt-row";let m=document.createElement("div");m.className="bp-mgmt-row-line";let h=document.createElement("span");if(h.className="bp-mgmt-flex1 "+(g.button?"bp-tone-warn":"bp-dim"),h.textContent=g.text,m.appendChild(h),g.button){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=g.button,w.addEventListener("click",()=>n("drc")),m.appendChild(w)}y.appendChild(m),o.appendChild(y);for(let w of t.conflicts??[]){let C=document.createElement("div");C.className="bp-mgmt-row bp-tone-bad",C.textContent=w,o.appendChild(C)}for(let w of t.suggestions??[]){let C=document.createElement("div");C.className="bp-mgmt-row";let A=document.createElement("div");A.className="bp-mgmt-row-line";let M=document.createElement("span");M.className="bp-mgmt-flex1 bp-tone-warn",M.textContent=`${w.label||w.key}: board ${w.project??"?"} mm, fab ${w.fab??"?"} mm`;let P=document.createElement("button");P.type="button",P.className="bp-mgmt-btn",P.textContent=b("gpui.mgmt.fab.apply","Apply"),P.addEventListener("click",()=>n("apply",{key:w.key})),A.append(M,P),C.appendChild(A),o.appendChild(C)}if(t.stackup?.chosen){let w=document.createElement("div");w.className="bp-mgmt-row";let C=document.createElement("div");C.className="bp-mgmt-row-line";let A=t.stackup.by==="proposed",M=document.createElement("span");if(M.className="bp-mgmt-flex1 "+(A?"bp-tone-warn":"bp-dim"),M.textContent=`${A?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,C.appendChild(M),A){let P=t.stackup.chosen,T=document.createElement("button");T.type="button",T.className="bp-mgmt-btn",T.textContent=b("gpui.mgmt.fab.use","Use"),T.addEventListener("click",()=>n("stackup",{id:P})),C.appendChild(T)}w.appendChild(C),o.appendChild(w)}if(Array.isArray(t.changed)&&t.changed.length>0){let w=document.createElement("div");w.className="bp-mgmt-row";let C=document.createElement("div");C.className="bp-mgmt-row-line";let A=document.createElement("span");A.className="bp-mgmt-flex1 bp-tone-warn",A.textContent=b("gpui.mgmt.fab.changed","Changed since you last looked");let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=b("gpui.mgmt.fab.seen","Seen"),M.addEventListener("click",()=>n("seen")),C.append(A,M),w.appendChild(C);for(let P of t.changed.slice(0,12)){let T=document.createElement("div");T.className="bp-mgmt-faint",T.textContent=P,w.appendChild(T)}o.appendChild(w)}let f=Array.isArray(t.limits)?t.limits:[];if(f.length>0){let w=document.createElement("div");w.className="bp-mgmt-group-head";let C=document.createElement("span");C.className="bp-mgmt-flex1",C.textContent=b("gpui.mgmt.fab.limit","Limit");let A=document.createElement("span");A.className="bp-mgmt-col",A.textContent=b("gpui.mgmt.fab.free","Base price");let M=document.createElement("span");M.className="bp-mgmt-col",M.textContent=b("gpui.mgmt.fab.extra","Costs more");let P=document.createElement("span");P.className="bp-mgmt-col bp-mgmt-col-read",P.textContent=b("gpui.mgmt.fab.readcol","Read"),w.append(C,A,M,P),o.appendChild(w);for(let B of f){let R=document.createElement("div");R.className="bp-mgmt-row";let O=document.createElement("div");O.className="bp-mgmt-row-line";let H=document.createElement("span");H.className="bp-mgmt-flex1"+(B.changed?" bp-tone-warn":B.inherited?" bp-dim":""),H.textContent=`${B.changed?"• ":""}${B.label??""}`;let ae=document.createElement("span");ae.className="bp-mgmt-col",ae.textContent=B.free?.text||"—";let ue=document.createElement("span");ue.className="bp-mgmt-col bp-dim",ue.textContent=B.extra?.text||"—";let oe=B.free&&typeof B.free==="object"?B.free:B.extra,we=oe?.fetched??"",Le=Boolean(we)&&oe?.confidence!=="published",Ne=we?Le?`${we}*`:we:"—",he=oe?.source??"",be;if(he.startsWith("https://")&&we){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=Ne,be=I}else{let I=document.createElement("span");I.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",I.textContent=Ne,be=I}O.append(H,ae,ue,be),R.appendChild(O),o.appendChild(R)}let T=document.createElement("div");T.className="bp-mgmt-note bp-mgmt-faint",T.textContent=b("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(T)}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 Rs={trs:(e)=>e,t:(e,t)=>t},js=new Set(["/settle"]);function Ci(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((a)=>a.startsWith(n)))return 2;let r=0;for(let a=0;a0||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 Ai(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 Li(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 Si(e,t=Rs){let{t:n,trs:i}=t,s=[],r=new Map;for(let o of e.projects)r.set(o.id,o.title||o.id);let a=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!a&&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(a)s.push({label:a.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:a.pinned?"unpin":"pin"}}),s.push({label:a.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:a.settled?"unsettle":"settle"}}),s.push({label:a.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:a.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(a)for(let o of e.commands){if(!o.word)continue;let c=js.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:c}})}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:c,want:u}=ki(o);s.push({label:o.title||"Untitled thread",place:o.project?r.get(o.project)??"":"",kind:"thread",urgency:c,want:u,dotClass:Ai(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 Pi(e,t,n,i=[],s=10,r=14){let a=t.trim(),o=a.length===0,c=e.slice();if(n?.threads&&n.threads.length>0){let d=new Map;for(let y of i)d.set(y.id,y.title||y.id);let g=new Set;for(let y of c)if(y.action.type==="thread")g.add(y.action.id);for(let y of n.threads){if(!y.id||g.has(y.id))continue;g.add(y.id);let{urgency:m,want:h}=ki(y);c.push({label:y.title||"Untitled thread",place:y.project?d.get(y.project)??"":"",kind:"thread",urgency:m,want:h,dotClass:Ai(y),action:{type:"thread",id:y.id}})}}let u=[];for(let d=0;d0)u.push({score:h,index:d,item:g})}u.sort((d,g)=>{if(o){let h=(g.item.urgency??0)-(d.item.urgency??0);if(h!==0)return h}if(g.score!==d.score)return g.score-d.score;let y=d.item.kind==="thread"?0:1,m=g.item.kind==="thread"?0:1;if(y!==m)return y-m;return d.index-g.index});let l=new Set,p=[];for(let d of u){let g=`${d.item.label}\x00${d.item.place}\x00${d.item.kind}`;if(l.has(g))continue;if(l.add(g),p.push(d.item),p.length>=s)break}if(n?.messages&&n.messages.length>0&&p.length{if(a.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(a)=>{if(a.key==="Escape")a.preventDefault(),a.stopPropagation(),this.close();else if(a.key==="ArrowDown"){if(a.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(a.key==="ArrowUp"){if(a.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(a.key==="Enter")a.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=r,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=Si(t,{t:b,trs:pe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=Pi(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 a=document.createElement("div");a.className="bp-palette-empty",a.textContent=b("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(a);return}let s=document.createDocumentFragment(),r=null;for(let a=0;a0)u.appendChild(document.createTextNode(o.label.slice(0,d)));let y=document.createElement("strong");if(y.className="bp-palette-mark",y.textContent=o.label.slice(d,g),u.appendChild(y),g{if(this.activeIdx!==a)this.activeIdx=a,this.updateActiveClass()}),c.addEventListener("click",()=>this.runAt(a)),a===this.activeIdx)r=c;s.appendChild(c)}if(this.listEl.replaceChildren(s),e&&r)r.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return r}render(){let e=this.items.filter((a)=>a.group!=="tools"),t=this.items.filter((a)=>a.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let a of e){if(i!==void 0&&a.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=a.group,n.appendChild(this.renderButton(a))}let s=()=>{let a=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let a=document.createElement("div");a.className="bp-rail-tools";for(let o of t)a.appendChild(this.renderButton(o));r.appendChild(a)}this.el.replaceChildren(r)}}var Fs=new Set(["resume","raise","retry","move","signin"]);function Bi(e){if(!e||typeof e!=="object")return null;let t=e,n=(r)=>typeof r==="string"?r:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((r)=>Boolean(r)&&typeof r==="object").map((r)=>({label:n(r.label),act:n(r.act),room:n(r.room),thread:n(r.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function Gt(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(Fs.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 Ii(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}class un{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;forceProviders=!1;providersEl=null;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";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${b("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",b("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}async openToAccounts(){this.forceProviders=!0,await this.open(),this.providersEl?.scrollIntoView({block:"nearest"})}close(){this.openState=!1,this.forceProviders=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${b("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",b("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment();this.providersEl=null;let t=this.cb.onGetNoProvider?.()??null;if(t||this.forceProviders){let l=document.createElement("section");l.className="bp-set-section",l.setAttribute("data-testid","settings-providers");let p=document.createElement("div");p.className="bp-set-head",p.textContent=b("web.settings.providers","AI providers");let d=document.createElement("div");d.className="bp-set-row";let g=document.createElement("div");g.className="bp-set-info";let y=document.createElement("div");y.textContent=t?pe(t.head):b("provider.notice.head","No AI provider connected");let m=document.createElement("div");m.className="bp-dim",m.textContent=b("web.settings.providers.browser","Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."),g.append(y,m);let h=document.createElement("div");h.className="bp-set-btns";let f=document.createElement("a");f.className="bp-link-btn primary",f.href=t?.url||"backplane://settings/accounts",f.setAttribute("data-testid","settings-open-accounts"),f.textContent=t?pe(t.button):b("provider.notice.button","Open Settings → Accounts"),h.appendChild(f),d.append(g,h),l.append(p,d),this.providersEl=l,e.appendChild(l)}let n=this.cb.onGetHome?.()??null;if(n){let l=document.createElement("section");l.className="bp-set-section",l.setAttribute("data-testid","settings-home");let p=document.createElement("div");p.className="bp-set-head",p.textContent=b("home.machine","Home machine");let d=document.createElement("div");d.className="bp-set-row";let g=document.createElement("div");g.className="bp-set-info";let y=document.createElement("div"),m=n.kind==="local"?`${n.name||"This machine"} (this machine)`:n.kind==="boat"?`${n.name||"Boat"} (Boat)`:n.name||"Linked machine";y.textContent=m,g.appendChild(y);let h=document.createElement("div");if(h.className="bp-dim",n.moving?.state==="moving")h.textContent=n.moving.step?b("home.moving.step","Moving home to {to}: {step}").replace("{to}",n.moving.to).replace("{step}",n.moving.step):b("home.moving","Moving home to {to}…").replace("{to}",n.moving.to);else if(n.moving?.state==="failed")h.textContent=n.moving.note?b("home.move.failed.note","Home move failed: {note}").replace("{note}",n.moving.note):b("home.move.failed","Home move failed");else if(!n.online)h.textContent=n.queuedCount>0?b("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",n.name||"home").replace("{n}",String(n.queuedCount)):b("home.away","Home ({name}) is away").replace("{name}",n.name||"home");else h.textContent="Online";if(g.appendChild(h),d.appendChild(g),n.canMoveHere&&this.cb.onMoveHomeHere){let f=document.createElement("button");f.type="button",f.className="primary",f.textContent=b("home.move.here","Make this machine the home"),f.setAttribute("data-testid","home-move-here-btn"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),d.appendChild(f)}l.append(p,d),e.appendChild(l)}let i=document.createElement("section");i.className="bp-set-section";let s=document.createElement("div");s.className="bp-set-head",s.textContent="This browser";let r=document.createElement("div");r.className="bp-set-row";let a=document.createElement("span");a.className="bp-dim",a.textContent="Sign out and revoke this browser's session cookie.";let o=document.createElement("button");o.type="button",o.className="primary stop",o.textContent=b("agy.signout","Sign out"),o.setAttribute("data-testid","logout-btn"),o.addEventListener("click",()=>{o.disabled=!0,this.cb.onLogout().catch(()=>{a.setAttribute("role","alert"),a.textContent=b("web.logout.failed","Could not confirm sign-out. Try again."),o.disabled=!1})}),r.append(a,o),i.append(s,r),e.appendChild(i);let c=document.createElement("section");c.className="bp-set-section";let u=document.createElement("div");u.className="bp-set-head",u.textContent="Paired devices",c.appendChild(u);try{let l=await this.cb.onLoadDevices();if(l.length===0){let p=document.createElement("div");p.className="bp-dim",p.textContent="No devices listed.",c.appendChild(p)}else for(let p of l){let d=document.createElement("div");d.className="bp-set-row";let g=document.createElement("div");g.className="bp-set-info";let y=document.createElement("div");if(y.textContent=p.title||p.head||"",g.appendChild(y),p.text||p.detail){let m=document.createElement("div");m.className="bp-dim",m.textContent=p.text||p.detail||"",g.appendChild(m)}if(d.appendChild(g),p.buttons?.length){let m=document.createElement("div");m.className="bp-set-btns";for(let h of p.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||b("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(h.action,h.value).finally(()=>{this.refresh()})}),m.appendChild(f)}d.appendChild(m)}c.appendChild(d)}}catch(l){let p=document.createElement("div");p.className="bp-dim";let d=l instanceof Error&&l.message?l.message:"Not available from a browser";p.textContent=`${d} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,c.appendChild(p)}e.appendChild(c),this.bodyEl.replaceChildren(e)}}function Ee(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function xt(e,t,n=!1){let i=Ee("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function hn(e){return Ee("pre","bp-context-code",e)}function $s(e){return Ee("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,pe(e))}function Ot(e,t){let n=Ee("div","bp-context-row");return n.append(Ee("strong",void 0,e),$s(t)),n}class bn{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,xt(b("common.refresh","Refresh"),()=>{this.load()}),xt(b("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=b("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=b("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=[b("thread.context.instructions","Instructions"),b("thread.context.system","System Prompt"),b("thread.context.skills","Skills"),b("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=xt(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",b("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(Ot(t.path,t.status),Ee("small","bp-dim",b("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,hn(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=xt(b("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=b("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(Ee("p","bp-dim",b("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[[b("thread.context.base","Backplane"),e.sections.base],[b("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[b("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(Ee("h3",void 0,i),hn(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(Ot(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",b("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=Ee("article","bp-context-card");n.append(Ot(t.path,t.state));for(let s of t.servers){let r=s.url||[s.command,...s.args].map((a)=>JSON.stringify(a)).join(" ");if(n.append(Ot(s.name,s.status),hn(r)),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"?b("thread.context.trust","Trust and enable"):i==="disable"?b("thread.context.disable","Disable"):b("thread.context.enable","Enable"),r=xt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");r.disabled=this.busy;let a=Ee("div","bp-context-actions");a.append(r),n.append(a)}this.body.append(n)}}}var Ri="http://www.w3.org/2000/svg";function ji(){let e=document.createElementNS(Ri,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(Ri,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function Gs(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Hi(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`}class gn{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;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 r=document.createElement("button");r.type="button",r.className="icon bp-side-collapse",r.textContent="‹",r.title="Collapse sidebar",r.setAttribute("aria-label","Collapse sidebar"),r.setAttribute("data-testid","sidebar-collapse"),r.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,r);let a=document.createElement("div");a.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=b("sidebar.search.projects","Search projects");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 c=document.createElement("button");c.type="button",c.className="icon bp-side-add",c.textContent="+",c.title=b("thread.new","New thread"),c.setAttribute("aria-label",b("thread.new","New thread")),c.setAttribute("data-testid","sidebar-new-thread"),c.addEventListener("click",()=>{let l=this.firstProjectId();if(l)this.cb.onNewThread(l)}),a.append(this.filterInput,c),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.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let u=document.createElement("div");u.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"),u.appendChild(this.connEl),this.el.append(n,a,this.homeBanner,this.listEl,u)}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?b("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):b("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?b("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):b("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 r=new Date(e.awaySince);s=`${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=b("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=b("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=b("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=b("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=b("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}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=b("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(r)=>{r.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let p=document.createElement("span");p.className="bp-tree-branch",p.setAttribute("aria-hidden","true"),n.appendChild(p)}let i=document.createElement("span");i.className=`bp-dot ${Gs(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let p=document.createElement("span");if(p.className="bp-badge-need",p.textContent=e.want==="approval"?"!":"•",e.say)p.title=e.say;n.appendChild(p)}else if(e.ago){let p=document.createElement("span");if(p.className="bp-thread-age",p.textContent=e.ago,e.pinned)p.title=b("tools.pinned","Pinned");n.appendChild(p)}let r=e.nav||e.id;if(!e.off&&r&&!r.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(r));let a=e.kind==="swarm"?Bi(e.need):null;if(!a)return n;let o=document.createElement("div");o.className="bp-need-wrap";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=a.line,u.title=a.line,c.appendChild(u);for(let p of a.actions){if(!Gt(p,Boolean(this.cb.hasRoomView)))continue;let d=document.createElement("button");d.type="button",d.className="bp-need-btn",d.textContent=p.label,d.setAttribute("data-testid",`need-${p.act}-${e.id}`),d.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,d.addEventListener("click",(g)=>{g.stopPropagation();let y=this.cb.onNeedAct;if(!y)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),y(p).catch((m)=>{this.needErr.set(e.id,m instanceof Error?m.message:String(m))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),c.appendChild(d)}o.append(n,c);let l=this.needErr.get(e.id);if(l){let p=document.createElement("div");p.className="bp-need-err"+(t?" nested":""),p.textContent=l,o.appendChild(p)}return o}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let a of n)if(a.kind==="threads")for(let o of a.rows)i.add(o.id);else if(a.kind==="projects")for(let o of a.rows)for(let c of o.threads??[])i.add(c.id);let s=this.selectedThreadId?this.threads.find((a)=>a.id===this.selectedThreadId)??null:null,r=!1;for(let a of n)if(a.kind==="projects"&&a.rows.length>0)r=!0;for(let a of n){if(a.kind==="bub")continue;if(a.kind==="threads"){let o=a.rows.filter((l)=>{if(!t)return!0;return`${l.title} ${l.project??""}`.toLowerCase().includes(t)});if(o.length===0)continue;let c=document.createElement("section");c.className="bp-side-section",c.setAttribute("data-section-id",a.id);let u=document.createElement("div");u.className="bp-side-section-head",u.textContent=a.title.toUpperCase(),c.appendChild(u);for(let l of o)c.appendChild(this.renderSectionThreadRow(l,!1));e.appendChild(c);continue}if(a.kind==="projects"){let o=a.rows.filter((l)=>{if(!t)return!0;if((l.title||l.id).toLowerCase().includes(t))return!0;if((l.threads??[]).some((p)=>p.title.toLowerCase().includes(t)))return!0;if((l.swarms??[]).some((p)=>p.title.toLowerCase().includes(t)))return!0;return!1}),c=Boolean(a.fold&&a.toggle);if(t&&o.length===0)continue;if(!c&&a.id!=="active"&&o.length===0)continue;let u=document.createElement("section");if(u.className="bp-side-section",u.setAttribute("data-section-id",a.id),c){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let p=a.count??o.length,d=a.open?"▾":"▸";if(l.textContent=`${a.title.toUpperCase()} (${p}) ${d}`,a.hint)l.title=a.hint;l.addEventListener("click",()=>{if(a.toggle)this.cb.onToggleSection?.(a.toggle)}),u.appendChild(l)}else u.appendChild(this.projectsHead(a.title.toUpperCase()));if(!c||a.open||Boolean(t)){if(a.id==="active"&&!r&&!t){let l=document.createElement("div");l.className="bp-side-empty",l.textContent="No projects yet.",u.appendChild(l)}for(let l of o){let p=document.createElement("div");if(p.className="bp-proj-group"+(l.off?" bp-dim":""),p.setAttribute("data-project-id",l.id),l.nav||l.key)p.setAttribute("data-project-key",l.nav||l.key||"");let d=document.createElement("div");d.className="bp-proj-head";let g=document.createElement("button");g.type="button",g.className="bp-proj-toggle";let y=ji();if(l.css)y.style.color=l.css;let m=document.createElement("span");if(m.className="bp-proj-name",m.textContent=l.title||l.id,g.append(y,m),l.fold==="project-fold"&&l.nav)g.addEventListener("click",()=>this.cb.onToggleProjectFold?.(l.nav));let h=document.createElement("button");if(h.type="button",h.className="icon bp-proj-add",h.title=b("thread.new","New thread"),h.textContent="+",h.setAttribute("data-testid",`new-thread-${l.id}`),l.off)h.disabled=!0;if(h.addEventListener("click",(f)=>{f.stopPropagation(),this.cb.onNewThread(l.id)}),d.append(g,h),p.appendChild(d),!l.folded||Boolean(t)){let f=Boolean(t)&&(l.title||l.id).toLowerCase().includes(t);for(let w of l.swarms??[]){if(t&&!f&&!w.title.toLowerCase().includes(t))continue;p.appendChild(this.renderSectionThreadRow(w,!0))}for(let w of l.threads??[]){if(t&&!f&&!w.title.toLowerCase().includes(t))continue;p.appendChild(this.renderSectionThreadRow(w,!0))}if(s&&s.project===l.id&&!i.has(s.id)&&(!t||f||s.title.toLowerCase().includes(t)))p.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:Hi(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}u.appendChild(p)}}e.appendChild(u)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let r=document.createElement("section");r.className="bp-proj-group",r.setAttribute("data-project-id",i.id);let a=document.createElement("div");a.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let c=this.collapsedProjects.has(i.id)&&!t,u=ji();if(i.css)u.style.color=i.css;let l=document.createElement("span");l.className="bp-proj-name",l.textContent=i.title||i.id,o.append(u,l),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let p=document.createElement("button");if(p.type="button",p.className="icon bp-proj-add",p.title=b("thread.new","New thread"),p.textContent="+",p.setAttribute("data-testid",`new-thread-${i.id}`),p.addEventListener("click",(d)=>{d.stopPropagation(),this.cb.onNewThread(i.id)}),a.append(o,p),r.appendChild(a),!c)for(let d of s)r.appendChild(this.renderSectionThreadRow({id:d.id,title:d.title,status:d.status,state:d.state,ago:Hi(d.updatedAt),pinned:d.pinned,nav:d.id},!0));e.appendChild(r)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=b("tour.title.bots","Bots").toUpperCase();let r=document.createElement("span");r.className="bp-side-sec-plus",r.textContent="+",r.setAttribute("aria-hidden","true"),i.append(s,r),n.appendChild(i);for(let l of this.bots){let p=document.createElement("div");p.className="bp-thread-row"+(l.thread===this.selectedThreadId?" active":"");let d=document.createElement("span");if(d.className="bp-dot bp-dot-idle",l.color)d.style.backgroundColor=l.color;let g=document.createElement("div");g.className="bp-thread-title",g.textContent=`@${l.name}`,p.append(d,g),p.addEventListener("click",()=>this.cb.onSelectBot(l)),n.appendChild(p)}e.appendChild(n);let a=document.createElement("section");a.className="bp-proj-group";let o=document.createElement("div");o.className="bp-side-section-head bp-side-section-row";let c=document.createElement("span");c.textContent=b("bots.rooms","Rooms").toUpperCase();let u=document.createElement("span");u.className="bp-side-sec-plus",u.textContent="+",u.setAttribute("aria-hidden","true"),o.append(c,u),a.appendChild(o);for(let l of this.rooms){let p=document.createElement("div");p.className="bp-thread-row";let d=document.createElement("div");d.className="bp-thread-title",d.textContent=`#${l.name}`,p.appendChild(d),a.appendChild(p)}e.appendChild(a)}this.listEl.replaceChildren(e)}}function Os(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function Ct(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function Vs(e,t){if(t===16000){let r=new Int16Array(e.length);for(let a=0;a0?c/u:0));s[r]=l<0?l*32768:l*32767}return s}class fn{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){Ct(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(Ct(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(Ct(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?Os(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(Ct(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 r=this.stopDrain.then(async()=>{if(t&&i){let a=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(a.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=r,await r}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),r=String(e.ins??""),a=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,a-s),c=i.slice(0,o)+r+i.slice(a);this.mark=o+r.length,this.cb.setDraft(c)}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),r=i.createScriptProcessor(4096,1,1);r.onaudioprocess=(a)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=Vs(a.inputBuffer.getChannelData(0),i.sampleRate);for(let c=0;c=3200){let c=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(c.buffer),!1,t)}},s.connect(r),r.connect(i.destination),this.audioCtx=i,this.processor=r}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 r=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!r.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${r.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;Ct(this.stream),this.stream=null}}var Di=[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],Fi=[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],$i=[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],Gi=[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],Us=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function kt(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[c]++,c>i)i=c}}let s=new Int32Array(16),r=0;for(let o=1;o<=15;o++)s[o]=r,r+=n[o];let a=new Int32Array(r);for(let o=0;o0)a[s[c]++]=o}return{counts:n,symbols:a,maxBits:i}}var Ws=(()=>{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),kt(e,288)})(),_s=(()=>{let e=new Uint8Array(32);return e.fill(5),kt(e,32)})();class vn{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,r=(p)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=p,s-=p,d},a=(p)=>{let d=0,g=0,y=0;for(let m=1;m<=p.maxBits;m++){d|=r(1);let h=p.counts[m];if(d-h{let d=c+p;if(d>t)throw Error("inflated frame exceeds limit");if(d<=o.length)return;let g=o.length;while(g{u(1),o[c++]=p,this.win[this.winPos]=p,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let p=r(1),d=r(2);if(d===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let g=e[n]|e[n+1]<<8,y=e[n+2]|e[n+3]<<8;if(n+=4,(g^65535)!==y)throw Error("invalid stored block length");if(n+g>e.length)throw Error("truncated stored payload");u(g);for(let m=0;m=e.length)break}else if(d===1||d===2){let g=Ws,y=_s;if(d===2){let m=r(5)+257,h=r(5)+1,f=r(4)+4,w=new Uint8Array(19);for(let T=0;TA)throw Error("code length overflow");for(let O=0;OA)throw Error("code length overflow");P+=B}else if(T===18){let B=r(7)+11;if(P+B>A)throw Error("code length overflow");P+=B}else throw Error("invalid code length symbol")}g=kt(M,m),y=kt(M.subarray(m),h)}while(!0){let m=a(g);if(m<256)l(m);else if(m===256)break;else{let h=m-257;if(h>=Di.length)throw Error("invalid length symbol");let f=Di[h]+(Fi[h]?r(Fi[h]):0),w=a(y);if(w>=$i.length)throw Error("invalid distance symbol");let C=$i[w]+(Gi[w]?r(Gi[w]):0);u(f);let A=this.winPos-C&32767;for(let M=0;M{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 r=this.nextId++,a=window.setTimeout(()=>{this.pending.delete(r),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(r,{resolve:i,reject:s,timer:a}),this.ws.send(JSON.stringify({id:r,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 r;try{r=JSON.parse(s)}catch{return}if(r.t==="hub.restarting")this.restarting={reason:String(r.reason??""),build:String(r.build??""),text:String(r.text??""),at:Date.now()};if(r.t==="hello")this.restarting=null,this.hello=r,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new vn:null,this.reconnectDelay=500,this.setState("connected");else if(r.t==="reply"&&typeof r.id==="number"){let a=this.pending.get(r.id);if(a)if(this.pending.delete(r.id),window.clearTimeout(a.timer),r.ok)a.resolve(r.result??{});else{let o=r.error,c=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed",u=typeof r.errorCode==="string"?r.errorCode:void 0,l=typeof r.machine==="string"?r.machine:void 0,p=typeof r.thread==="string"?r.thread:void 0;a.reject(new At(c,{code:u,machine:l,thread:p}))}return}for(let a of this.frameListeners)a(r)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let r;try{r=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(r.length>0&&r[0]===123)i(this.textDecoder.decode(r));else{let a=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);for(let o of this.binaryListeners)o(a)}return}for(let r of this.binaryListeners)r(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 qs=new TextDecoder;function Oi(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 Vi(e){let t=0,n=0;function i(a){if(a<=23)return a;if(a===24){if(t>=e.length)return null;return e[t++]}if(a===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(a===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(a){if(n++,a>32||n>400000||t>=e.length)return null;let o=e[t++],c=o>>5,u=i(o&31);if(u===null)return null;switch(c){case 0:return u;case 1:return-1-u;case 2:{if(t+u>e.length)return null;let l=e.subarray(t,t+u);return t+=u,l}case 3:{if(t+u>e.length)return null;let l=qs.decode(e.subarray(t,t+u));return t+=u,l}case 4:{if(u>e.length)return null;let l=Array(u);for(let p=0;p=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 Wi(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[m]==="number"?e[m]:h,n=t("l",0),i=t("c",0),s=t("a",255)/255,r=t("m",1),a=t("w",0),o=a/2,c=r===0&&a!==0,u=e.d instanceof Uint8Array?e.d:new Uint8Array(0),l=new Ui(u),p=[],d=[],g=0,y=0;while(l.more()){let m=l.nextU32(),h=p.length,f=1/0,w=1/0,C=-1/0,A=-1/0;if(r===2)g=g+l.nextI32()|0,y=y+l.nextI32()|0,p.push(g,y),f=C=g,w=A=y;else{let P=Math.min(l.nextU32(),1048576);for(let T=0;TC)C=g;if(yA)A=y}}let M=(p.length-h)/2;if(M>0){let P=r===2||M===1?2:r===0?0:1,T=r===0?0:o;d.push({info:m,x0:f-T,y0:w-T,x1:C+T,y1:A+T,at:h,n:M,kind:P})}}return{layer:n,color:i,alpha:s,mode:r,r:o,own:c,pts:new Float32Array(p),pieces:d}}function _i(e,t,n){let i=(a)=>Array.isArray(a)&&a.length>=4?[Number(a[0])||0,Number(a[1])||0,Number(a[2])||0,Number(a[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],r=[];for(let a=0;a=0&&o0){n.delete(o.h),n.set(o.h,c);while(n.size>1024){let u=n.keys().next().value;if(u!==void 0)n.delete(u);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:r}}function qi(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),r=n.naturalWidth*s,a=n.naturalHeight*s,o=n.left+(n.width-r)/2,c=i?n.top:n.top+(n.height-a)/2,u=(e-o)/r,l=(t-c)/a;if(u<0||u>1||l<0||l>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(u*1000))),y:Math.max(0,Math.min(1000,Math.round(l*1000)))}}var Ki=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function zi(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class wn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function Ji(e,t,n){let i=!0,s=!1,r=!1,a="",o=!1,c=!1,u=-1,l=null,p=new wn,d=document.createElement("div");d.className="bp-pane bp-browser-pane",d.setAttribute("data-testid","pane-browser");let g=document.createElement("div");g.className="bp-pane-bar bp-browser-nav";function y(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 m=y("←","browser-back","Back"),h=y("→","browser-forward","Forward"),f=y("↻","browser-reload","Reload"),w=document.createElement("form");w.className="bp-browser-url-form";let C=document.createElement("input");C.type="text",C.className="bp-browser-input",C.placeholder="https://…",C.autocomplete="off",C.spellcheck=!1,C.setAttribute("data-testid","browser-url");let A=y("Go","browser-go","Navigate");A.type="submit",w.append(C,A);let M=y("Take over","browser-takeover");M.classList.add("is-primary"),g.append(m,h,f,w,M);let P=document.createElement("div");P.className="bp-browser-drive-bar",P.hidden=!0;let T=document.createElement("div");T.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=y("Send","browser-type-send");T.append(B,R);let O=document.createElement("div");O.className="bp-browser-quick-keys";for(let[X,ce]of Ki){let E=y(X,`browser-key-${ce}`);E.addEventListener("click",()=>he("press",{key:ce})),O.append(E)}P.append(T,O);let H=document.createElement("div");H.className="bp-browser-err",H.setAttribute("data-testid","browser-error"),H.hidden=!0;let ae=document.createElement("div");ae.className="bp-browser-stage",ae.setAttribute("data-testid","browser-stage");let ue=document.createElement("img");ue.className="bp-browser-img",ue.alt="Hub browser screen",ue.draggable=!1,ue.hidden=!0,ue.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…",ae.append(ue,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(g,P,H,ae,we),e.replaceChildren(d);function Le(X){H.textContent=X,H.hidden=!X}function Ne(){P.hidden=!s,we.hidden=!s,M.textContent=s?"Hand back":"Take over",M.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),M.classList.toggle("is-on",s),ue.classList.toggle("is-driving",s)}function he(X,ce={},E){p.enqueue(async()=>{if(!i)return;Le("");try{if(await t.hub.rpc("browser",{thread:n,op:X,...ce}),!i)return;E?.(),le()}catch(k){if(!i)return;Le(k instanceof Error?k.message:String(k))}})}function be(X){he("toolbar",{command:X},()=>{s=!0,Ne()})}m.addEventListener("click",()=>be("back")),h.addEventListener("click",()=>be("forward")),f.addEventListener("click",()=>be("reload")),w.addEventListener("submit",(X)=>{X.preventDefault();let ce=zi(C.value);if(!ce)return;if(C.value=ce,!s)he("takeover",{},()=>{s=!0,Ne()});he("navigate",{url:ce},()=>{s=!0,Ne()})}),M.addEventListener("click",()=>{if(s)he("handback",{},()=>{s=!1,Ne()});else he("takeover",{},()=>{s=!0,Ne(),B.focus()})});function I(){let X=B.value;if(!X)return;B.value="",he("type",{text:X})}R.addEventListener("click",I),B.addEventListener("keydown",(X)=>{if(!s)return;if(X.key==="Enter"){if(X.preventDefault(),B.value)I();he("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(),he("press",{key:X.key})}),ue.addEventListener("click",(X)=>{if(!s||!r)return;let ce=ue.getBoundingClientRect(),E=qi(X.clientX,X.clientY,{left:ce.left,top:ce.top,width:ce.width,height:ce.height,naturalWidth:ue.naturalWidth,naturalHeight:ue.naturalHeight});if(!E)return;he("click",E)}),ue.addEventListener("wheel",(X)=>{if(!s||!r)return;X.preventDefault();let ce=Math.round(X.deltaX),E=Math.round(X.deltaY);if(ce===0&&E===0)return;he("scroll",{dx:ce,dy:E})},{passive:!1});async function le(){if(!i)return;if(o){c=!0;return}o=!0;try{do{c=!1,l=new AbortController;let X=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:l.signal});if(!i)return;if(X.ok){let ce=await X.blob();if(!i)return;let E=URL.createObjectURL(ce),k=a;if(a=E,ue.src=E,ue.hidden=!1,oe.hidden=!0,r=!0,k)URL.revokeObjectURL(k)}else if(!r)ue.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&c)}catch{if(!i)return;if(!r)ue.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}finally{l=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===u)return;u=X.n}le()}});return le(),{destroy(){if(i=!1,ne(),l?.abort(),a)URL.revokeObjectURL(a),a=""}}}function q(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Vt(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 Xi(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function zs(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function Yi(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 Js(e){let t=Xi(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 Zi(e,t,n,i){let s=!0,r="",a="",o=q("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let c=q("div","bp-pane-bar"),u=q("div","bp-files-crumbs"),l=q("button","bp-v-btn","Refresh");l.type="button",l.addEventListener("click",()=>void h(r)),c.append(u,l);let p=q("div","bp-files-split"),d=q("div","bp-files-list");d.setAttribute("data-testid","files-list");let g=q("div","bp-files-preview");g.setAttribute("data-testid","files-preview"),g.append(q("div","bp-pane-empty","Select a file to preview")),p.append(d,g),o.append(c,p),e.replaceChildren(o);function y(){u.replaceChildren();let f=q("button","bp-crumb-btn","project");if(f.type="button",f.addEventListener("click",()=>void h("")),u.append(f),!r)return;let w=r.split("/").filter(Boolean),C="";for(let A of w){C=C?`${C}/${A}`:A;let M=C;u.append(q("span","bp-vh-sep","/"));let P=q("button","bp-crumb-btn",A);P.type="button",P.addEventListener("click",()=>void h(M)),u.append(P)}}async function m(f,w,C){a=f,g.replaceChildren();let A=q("div","bp-files-prev-head");A.append(q("span","bp-files-prev-name",f));let M=q("div","bp-files-prev-acts"),P=Js(w);if(P){let O=q("button","bp-v-btn is-primary",`Open in ${P}`);O.type="button",O.setAttribute("data-testid","files-open-viewer"),O.addEventListener("click",()=>i(P,f)),M.append(O)}let T=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(f)}`,B=q("a","bp-v-btn","Download");B.href=T,B.download=w,M.append(B),A.append(M),g.append(A);let R=Xi(w);if(zs(R)){let O=q("div","bp-files-img-wrap"),H=document.createElement("img");H.className="bp-files-img",H.alt=w,H.src=T,O.append(H),g.append(O);return}if(C>524288&&!Yi(R)){g.append(q("div","bp-pane-empty",`Binary file (${Vt(C)}). Use Download to save.`));return}if(Yi(R)||C<=65536){let O=q("div","bp-pane-empty","Loading…");g.append(O);try{let H=await fetch(T,{credentials:"same-origin"});if(!s||a!==f)return;if(!H.ok){O.textContent=`Could not load file (${H.status})`;return}if((H.headers.get("content-type")||"").startsWith("image/")){O.remove();let ne=document.createElement("img");ne.className="bp-files-img",ne.alt=w,ne.src=T,g.append(ne);return}let ue=262144,oe=[],we=0,Le=!1;if(H.body){let ne=H.body.getReader();try{while(!0){let{done:X,value:ce}=await ne.read();if(X||!ce)break;if(we+ce.byteLength>ue){let E=ue-we;if(E>0)oe.push(ce.subarray(0,E)),we+=E;Le=!0,await ne.cancel();break}oe.push(ce),we+=ce.byteLength}}finally{ne.releaseLock()}}if(!s||a!==f)return;let Ne=new Uint8Array(we),he=0;for(let ne of oe)Ne.set(ne,he),he+=ne.byteLength;let be=!1;for(let ne=0;neA.dir===M.dir?A.name.localeCompare(M.name):A.dir?-1:1),d.replaceChildren(),f){let A=q("button","bp-file-row is-dir");A.type="button",A.append(q("span","bp-file-icon","↰"),q("span","bp-file-name",".."));let M=f.includes("/")?f.slice(0,f.lastIndexOf("/")):"";A.addEventListener("click",()=>void h(M)),d.append(A)}if(C.length===0){d.append(q("div","bp-pane-empty","Empty folder"));return}for(let A of C){let M=f?`${f}/${A.name}`:A.name,P=q("button","bp-file-row"+(A.dir?" is-dir":"")+(M===a?" is-sel":""));P.type="button",P.setAttribute("data-testid",`file-row-${A.name}`),P.append(q("span","bp-file-icon",A.dir?"▸":"·"),q("span","bp-file-name",A.name),q("span","bp-file-size",A.dir?"":Vt(A.size))),P.addEventListener("click",()=>{if(A.dir)h(M);else d.querySelectorAll(".bp-file-row.is-sel").forEach((T)=>T.classList.remove("is-sel")),P.classList.add("is-sel"),m(M,A.name,A.size)}),d.append(P)}}catch(w){if(!s)return;d.replaceChildren(q("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return h(""),{destroy(){s=!1}}}function Qi(e,t,n){let i=!0,s=q("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let r=q("div","bp-pane-bar"),a=q("span","bp-diff-summary","Loading diff…"),o=q("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void u()),r.append(a,o);let c=q("div","bp-diff-body");c.setAttribute("data-testid","diff-body"),s.append(r,c),e.replaceChildren(s);async function u(){a.textContent="Loading diff…",c.replaceChildren();try{let l=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(l?.nogit){a.textContent="Not a git repository",c.append(q("div","bp-pane-empty","This project is not a git repository."));return}let p=typeof l?.diff==="string"?l.diff:"";if(!p.trim()){a.textContent="Clean working tree",c.append(q("div","bp-pane-empty","No uncommitted changes."));return}let d=p.split(` -`),g=0,y=0,m=0,h=document.createDocumentFragment(),f=q("div","bp-diff-file");for(let w of d){if(w.startsWith("diff --git ")){if(f.childNodes.length>0)h.append(f);f=q("div","bp-diff-file"),g++;let C=w.match(/ b\/(.+)$/);f.append(q("div","bp-diff-file-head",C?C[1]:w));continue}if(w.startsWith("index ")||w.startsWith("--- ")||w.startsWith("+++ "))f.append(q("div","bp-diff-line is-meta",w));else if(w.startsWith("@@"))f.append(q("div","bp-diff-line is-hunk",w));else if(w.startsWith("+"))y++,f.append(q("div","bp-diff-line is-add",w));else if(w.startsWith("-"))m++,f.append(q("div","bp-diff-line is-del",w));else f.append(q("div","bp-diff-line",w))}if(f.childNodes.length>0)h.append(f);a.textContent=`${g||1} file${g===1?"":"s"} · +${y} -${m}`,c.append(h)}catch(l){if(!i)return;a.textContent="Diff unavailable",c.append(q("div","bp-pane-empty",l instanceof Error?l.message:String(l)))}}return u(),{destroy(){i=!1}}}function es(e,t,n){let i=!0,s="checks",r=q("div","bp-pane bp-review-pane");r.setAttribute("data-testid","pane-review");let a=q("div","bp-pane-bar"),o=q("div","bp-review-tabs"),c=q("button","bp-v-btn is-on","Checks"),u=q("button","bp-v-btn","BOM"),l=q("button","bp-v-btn","Comments");c.type=u.type=l.type="button",o.append(c,u,l);let p=q("button","bp-v-btn","Refresh");p.type="button",p.addEventListener("click",()=>void m()),a.append(o,p);let d=q("div","bp-review-body");d.setAttribute("data-testid","review-body"),r.append(a,d),e.replaceChildren(r);function g(h){s=h,c.classList.toggle("is-on",s==="checks"),u.classList.toggle("is-on",s==="bom"),l.classList.toggle("is-on",s==="comments"),m()}c.addEventListener("click",()=>g("checks")),u.addEventListener("click",()=>g("bom")),l.addEventListener("click",()=>g("comments"));function y(h){let f=q("div","bp-review-md"),w=h.split(` -`),C=0;while(C{T.preventDefault();let B=M.value.trim();if(!B)return;P.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:B}).then(()=>{M.value="",P.disabled=!1,m()},()=>{P.disabled=!1})}),d.append(A),C.length===0){d.append(q("div","bp-pane-empty","No review comments yet."));return}for(let T of C){let B=q("div","bp-review-comment"+(T.resolved?" is-resolved":"")),R=[T.by||"review",T.file,T.layer,T.item].filter(Boolean).join(" · ");B.append(q("div","bp-review-comment-meta",R),q("div","bp-review-comment-text",T.text)),d.append(B)}return}let h=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let f=h?.report||{};if(d.replaceChildren(),f.line||f.gate){let w=q("div","bp-review-gate",[f.gate,f.line].filter(Boolean).join(" · "));d.append(w)}if(f.err)d.append(q("div","bp-review-err",f.err));if(Array.isArray(f.tasks)&&f.tasks.length>0){let w=q("div","bp-review-tasks");f.tasks.forEach((C,A)=>{let M=q("label","bp-review-task"),P=document.createElement("input");P.type="checkbox",P.checked=!!(C.done??C.checked);let T=typeof C.index==="number"?C.index:A;P.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:T}).then(()=>void m(),()=>{})}),M.append(P,q("span",void 0,C.text||C.label||`Item ${A+1}`)),w.append(M)}),d.append(w)}if(f.md&&f.md.trim())d.append(y(f.md));else if(!f.err&&(!f.tasks||f.tasks.length===0))d.append(q("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(h){if(!i)return;d.replaceChildren(q("div","bp-pane-empty",h instanceof Error?h.message:String(h)))}}return m(),{destroy(){i=!1}}}function ts(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 En{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,r=Math.max(i-t,1000),a=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),c=Math.max(o.width,200),u=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(c/r,u/a)*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),r=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==r)this.canvas.width=s,this.canvas.height=r;let a=this.ctx;a.setTransform(i,0,0,i,0,0),a.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",a.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 c=t*0.5,u=n*0.5,l=this.scale,p=this.cx,d=this.cy,g=p-c/l,y=p+c/l,m=d-u/l,h=d+u/l,{off:f,dim:w,lift:C}=this.masks,A=[],M=[];for(let T=0;T>>B&1)===1)continue;if(B===C)M.push(T);else A.push(T)}let P=A.concat(M);a.lineCap="round",a.lineJoin="round";for(let T=0;T>>R.layer&1)===1,H=R.alpha*(O?0.25:1);if(H<=0.01)continue;this.drawChunk(a,R,H,g,m,y,h,p,d,l,c,u)}if(this.highlights.size>0){a.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",a.fillRect(0,0,t,n);let T=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let B=0;Br||h.y1a)continue;if(h.n<3)continue;let f=(d[h.at]-o)*u+l,w=(d[h.at+1]-c)*u+p;e.moveTo(f,w);for(let C=1;C0)e.fill()}else if(t.mode===2){let y=Math.max(0.75,t.r*u);e.fillStyle=g,e.beginPath();let m=0;for(let h=0;hr||f.y1a)continue;let w=(d[f.at]-o)*u+l,C=(d[f.at+1]-c)*u+p;e.moveTo(w+y,C),e.arc(w,C,y,0,Math.PI*2),m++}if(m>0)e.fill()}else{e.strokeStyle=g,e.lineWidth=Math.max(1,t.r*2*u),e.beginPath();let y=0;for(let m=0;mr||h.y1a)continue;let f=(d[h.at]-o)*u+l,w=(d[h.at+1]-c)*u+p;if(h.n===1)e.moveTo(f,w),e.lineTo(f+0.01,w);else{e.moveTo(f,w);for(let C=1;C0)e.stroke()}}drawLitPieces(e,t,n,i,s,r,a,o,c,u,l,p,d){let g=t.pts,y=ts(t.color,t.alpha);for(let m=0;ma||h.y1o)continue;let f=(g[h.at]-c)*l+p,w=(g[h.at+1]-u)*l+d;if(h.kind===2){let C=Math.max(1.5,t.r*l);e.fillStyle=y,e.beginPath(),e.arc(f,w,C,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(h.kind===0&&h.n>=3){e.fillStyle=y,e.beginPath(),e.moveTo(f,w);for(let C=1;C=0;l--){let p=n.chunks[l];if(p.layer<32&&(u>>>p.layer&1)===1)continue;for(let d=0;dg.x1+a||rg.y1+a)continue;let y=(g.x1-g.x0+1)*(g.y1-g.y0+1);if(y{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,r=(t.y+n.y)*0.5,a=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*a)),c=this.canvas.getBoundingClientRect(),u=this.pinchStart.midX-c.left-c.width*0.5,l=this.pinchStart.midY-c.top-c.height*0.5,p=s-c.left-c.width*0.5,d=r-c.top-c.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+u/this.pinchStart.scale-p/o,this.cy=this.pinchStart.cy+l/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,r=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/r,this.cy+=i/this.scale-i/r,this.scale=r,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 ns=[{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 is(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 xn(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` -`),r=(s[0]||"").split("\t");if(r[0]!=="git"||r[2]!==n)return!1;let a=s[1]||r.slice(4).join("\t");if(!a)return!1;let o=a.replace(/\\/g,"/"),c=i.replace(/\\/g,"/");if(c.startsWith("/")||/^[A-Za-z]:\//.test(c))return o===c;return o===c||o.endsWith(`/${c}`)}class Cn{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 Ys=`#version 300 es +`)){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 r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.desc||t.label,i.append(s,r),i.addEventListener("mousedown",(a)=>{a.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 r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.detail||t.label,i.append(s,r),i.addEventListener("mousedown",(a)=>{a.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),r=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=r+s,this.textarea.selectionStart=this.textarea.selectionEnd=r.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!zn.has(t.type)){this.showError(b("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=_n){this.showError(b("web.composer.maximages","At most {max} images per message.",{max:_n}));break}let n=await new Promise((s,r)=>{let a=new FileReader;a.onload=()=>s(String(a.result||"")),a.onerror=()=>r(Error("read failed")),a.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 r=document.createElement("button");r.type="button",r.className="icon bp-attach-rm",r.textContent="×",r.title=b("common.remove","Remove"),r.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,r),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 Kn(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 Ss=new Set(["bom","checks","life","plan","fab"]);function Dt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&Ss.has(t.id))}function ei(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 Ft(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=a}return i}function lt(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 ct(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 Ls=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),Ps=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function ti(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let a of i)if(Ls.has(a))return a;let s=i[0]??"",r=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(Ps.has(r)){let a=s.split("-");if(a.length>=2&&/^\d+$/.test(a[1]))return`${a[0]}-${a[1]}`;return a[0]}return i.slice(0,2).join("_")}function ni(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 ${lt(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${lt(n)}`,tone:"warn"};return{text:lt(n),tone:"ok"}}function ii(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((r)=>r==="dnp"&&Boolean(i.dnp)||s.includes(r))})}function si(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function rn(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 $t(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 ri(e){return e.state==="routed"||e.state==="verified"}function ai(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 oi(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 li(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,r=0;if(typeof e.total!=="number"){for(let a of e.layers??[])for(let o of a.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")r+=1;else if(o.state==="approved")n+=1}else if(e.routing)r=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:r,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 di(e){return e==="extra"?"costs-more limits":"base-price limits"}function an(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function pi(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function on(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var Jn=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],Yn=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function mi(e){let t=2166136261;for(let n=0;n>>0;return t}function xt(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 Jn[mi(i)%Jn.length]}function dt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return Yn[mi(e)%Yn.length]}function ui(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),r=Math.max(1,Math.abs(e[3]-e[1])),a=Math.max(20,t-i*2),o=Math.max(20,n-i*2),c=Math.max(0.05,Math.min(200,Math.min(a/s,o/r)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:c,fitted:c,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 Gt(e,t,n,i,s){let r=Math.max(0.0001,e.scale);return[e.cx+(t-i*0.5)/r,e.cy+(n-s*0.5)/r]}function hi(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 bi(e,t,n,i,s,r){let a=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),c=Math.max(a,Math.min(o,e.scale*t)),[m,d]=Gt(e,n,i,s,r);return{...e,cx:m-(n-s*0.5)/c,cy:d-(i-r*0.5)/c,scale:c,touched:!0}}function gi(e,t,n,i){let s=e.map((a)=>[a[0],a[1]]);if(s.length===0)return[n];let r=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(r,0,[n[0],n[1]]),s}function ln(e,t,n){let i=n?3:2;if(e.length<=i||t<0||t>=e.length)return null;let s=e.map((r)=>[r[0],r[1]]);return s.splice(t,1),s}function Ns(e,t,n,i,s,r){let a=s-n,o=r-i,c=a*a+o*o;if(c<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let m=Math.max(0,Math.min(1,((e-n)*a+(t-i)*o)/c)),d=n+m*a,p=i+m*o;return(e-d)*(e-d)+(t-p)*(t-p)}function Xn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==m>t&&e<(c-a)*(t-o)/(m-o+0.000000000001)+a)i=!i}return i}function cn(e,t){return Math.max(5,Math.min(32,e*t))}function Ot(e,t,n,i,s,r,a,o,c){if(i){for(let l of e){if(l.layer!==n||l.id!==i||l.locked)continue;let h=l.path??[];for(let v=0;v=3)for(let v=0;v=0;l--){let h=t[l];if(h.layer!==n)continue;let v=h.outline??[];if(!Xn(d,p,v))continue;if(!(h.holes??[]).some((g)=>Xn(d,p,g)))return{kind:"region",id:h.id}}return null}function pt(e){let t=null,n=null,i=[];for(let r of e){if(!r.layer)continue;i.push(r.layer);let a=r.items??[],o=a.filter((m)=>m.kind==="corridor").length,c=a.filter((m)=>m.kind==="plane").length;if((o>0||r.role==="signal")&&(!t||o>t.count))t={count:o,layer:r.layer};if((c>0||r.role==="power"||r.role==="plane")&&(!n||c>n.count))n={count:c,layer:r.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let r of i){if(s.length>=2)break;if(!s.includes(r))s.push(r)}return s}function Qn(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 a=1;a=s&&o>0.000000001){let c=(s-r)/o;return[e[a-1][0]+(e[a][0]-e[a-1][0])*c,e[a-1][1]+(e[a][1]-e[a-1][1])*c]}r+=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 fi(e,t,n){if(e==="split"&&n.length>0)return t.filter((i)=>n.includes(i.layer));return t}function sn(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function Zn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==m>t&&e<(c-a)*(t-o)/(m-o+0.000000000001)+a)i=!i}return i}function vi(e,t){if(e.length<3)return null;let n=1/0,i=1/0,s=-1/0,r=-1/0,a=0,o=0;for(let m of e)n=Math.min(n,m[0]),i=Math.min(i,m[1]),s=Math.max(s,m[0]),r=Math.max(r,m[1]),a+=m[0],o+=m[1];let c=[[(n+s)*0.5,(i+r)*0.5],[a/e.length,o/e.length]];for(let m of[0.5,0.25,0.75,0.125,0.875])for(let d of[0.5,0.25,0.75,0.125,0.875])c.push([n+(s-n)*d,i+(r-i)*m]);for(let m of c)if(Zn(m[0],m[1],e)&&!t.some((d)=>Zn(m[0],m[1],d)))return m;return null}function yi(e,t,n,i,s,r){let a=[];for(let d of e){let p=d.nets??0,l=d.path??[];if(p<=0||l.length<2)continue;let h=0;for(let v=1;v{let l=d.sel||d.hov?1:0,h=p.sel||p.hov?1:0;if(h!==l)return h-l;if(p.nets!==d.nets)return p.nets-d.nets;return d.b.id.localeCompare(p.b.id)});let o=[],c=[],m=(d,p,l,h,v)=>[d-l*0.5-v,p-h*0.5-v,d+l*0.5+v,p+h*0.5+v];for(let d of a){let p=d.b.name||"",l=String(d.nets),h=p?`${p} · ${d.nets}`:l,v=(d.sel||d.hov||d.pxLen>=95)&&p?[h,l]:[l],u=null,g=(w,x)=>Math.max(x*0.5+3,Math.min(Math.max(x*0.5+3,n-x*0.5-3),w)),f=(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 v){let x=Math.max(16,w.length*5.9+10),S=15;for(let N of[0.5,0.35,0.65,0.22,0.78]){let A=Qn(d.pts,N);if(!A)continue;let[M,T]=Ve(t,A[0],A[1],n,i),R=g(M,x),V=f(T,15),H=m(R,V,x,15,2);if(!o.some((ae)=>sn(H,ae))){u={id:d.b.id,text:w,cx:R,cy:V,pw:x,ph:15,col:d.col,sel:d.sel};break e}}}if(!u){let w=Qn(d.pts,0.5);if(w){let[x,S]=Ve(t,w[0],w[1],n,i),N=Math.max(16,l.length*6.5+8),A=15,M=g(x,N);for(let T of[-18,18]){let R=f(S+T,15);if(!o.some((V)=>sn(m(M,R,N,15,2),V))){u={id:d.b.id,text:l,cx:M,cy:R,pw:N,ph:15,col:d.col,sel:d.sel};break}}}}if(u)o.push(m(u.cx,u.cy,u.pw,u.ph,2)),c.push(u)}return c}function wi(e,t,n,i,s,r=[]){let a=new Set(s),o=[];for(let d of e){if(!d.r||!d.b||d.b.length!==4)continue;let[p,l]=Ve(t,d.b[0],d.b[1],n,i),[h,v]=Ve(t,d.b[2],d.b[3],n,i),u=Math.abs(h-p),g=Math.abs(v-l);if(u<13||g<9)continue;let f=(p+h)*0.5,w=(l+v)*0.5;if(f<8||f>n-8||w<8||w>i-8)continue;o.push({text:d.r,cx:f,cy:w,bw:d.r.length*5.8+4,bh:11,score:u*g+(a.has(d.r)?1e4:0)})}o.sort((d,p)=>p.score-d.score);let c=[...r],m=[];for(let d of o){let p=[d.cx-d.bw*0.5,d.cy-d.bh*0.5,d.cx+d.bw*0.5,d.cy+d.bh*0.5];if(!c.some((h)=>sn(p,h)))c.push(p),m.push({text:d.text,cx:d.cx,cy:d.cy})}return m}function Ei(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 Vt(e,t){if(!t||t.length===0)return e;let n=new Map;for(let r of e)if(r.layer)n.set(r.layer,r);let i=[],s=new Set;for(let r of t){if(!r.layer)continue;s.add(r.layer);let a=n.get(r.layer);if(a)i.push(a);else i.push({layer:r.layer,index:r.index,title:r.title||`L${r.index} · ${r.layer}`,subtitle:r.subtitle||"",role:r.role,status:"proposed",done:0,approved:0,total:0,items:[]})}for(let r of e)if(r.layer&&!s.has(r.layer))i.push(r);return i}function Ci(e,t,n,i,s,r,a,o){return e===t&&n===i&&s===r&&(o===void 0||a>=o)}var xi="#111917",Ms="#16201d",Bs="rgba(212, 224, 219, 0.92)",Ts="rgba(61, 80, 73, 0.72)",Is="rgba(82, 107, 97, 0.85)";var ki="#f59e0b",Rs="#eef5f2",Ai="#ef4444";function rt(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),r=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(r))return`rgba(${i}, ${s}, ${r}, ${t})`}return`rgba(20, 184, 166, ${t})`}function js(e,t,n){let i=0.14,s=0.45,r=0.85,a=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,r=0.91;break;case"edited":i=0.2,s=0.56,r=0.95;break;case"routed":case"verified":i=0.08,s=0.26,r=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,r=0.27;break;case"blocked":i=0.18,s=0.48,r=0.88,a=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),r=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:r,bad:a}}function Hs(e,t,n){let i=0.27,s=0.83,r=!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,r=!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:r}}function Ds(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 dn{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=Vt(e.layers,e.copperLayers);if(t.length===0)return[];if(e.gridMode==="all")return t;if(e.gridMode==="single"){let s=e.shownLayers.find((a)=>t.some((o)=>o.layer===a))??pt(t)[0]??t[0]?.layer,r=t.find((a)=>a.layer===s);return r?[r]:[]}let n=e.shownLayers.length>0&&e.shownLayers.every((s)=>t.some((r)=>r.layer===s))?e.shownLayers.slice(0,2):pt(t),i=[];for(let s of n){let r=t.find((a)=>a.layer===s);if(r)i.push(r)}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 r=this.buildCard(s);this.cards.set(s.layer,r),this.root.appendChild(r.el)}}else for(let s of n){let r=this.cards.get(s.layer);if(r)this.syncCardHeaderAndLegend(r,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 ui(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"),r=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((w)=>w.kind==="plane");s.className="bp-plan-card-bar "+(r?"pwr":"sig");let a=document.createElement("span");a.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn bp-plan-mini-btn",c.textContent="✓",c.title=b("gpui.mgmt.plan.layer","Approve layer"),c.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn bp-plan-mini-btn",m.textContent="✗",m.title=b("gpui.mgmt.plan.rejectlayer","Reject layer"),m.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,a,o,c,m);let d=document.createElement("div");d.className="bp-plan-card-sub",n.append(i,d);let p=document.createElement("div");p.className="bp-plan-card-canvas-wrap";let l=document.createElement("canvas");l.className="bp-plan-card-canvas",l.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let h=document.createElement("div");h.className="bp-plan-hover-hud bp-hidden",p.append(l,h);let v=document.createElement("div");v.className="bp-plan-legend bp-hidden",t.append(n,p,v);let u=l.getContext("2d"),g=new ResizeObserver(()=>this.scheduleDraw());g.observe(p),this.attachPointerListeners(l,e.layer);let f={layer:e.layer,el:t,canvas:l,ctx:u,legendEl:v,okBtn:c,noBtn:m,statusEl:o,titleEl:a,subtitleEl:d,hoverHudEl:h,ro:g};return this.syncCardHeaderAndLegend(f,e),f}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=Ds(t);e.statusEl.className=`bp-plan-card-status tone-${s.tone==="warn"?"dim":s.tone}`,e.statusEl.textContent=i.length>0?b(s.key,s.label):"",e.statusEl.classList.toggle("bp-hidden",i.length===0);let r=i.some((o)=>o.state==="proposed"||o.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!r);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!r);let a=(this.state?.regions??[]).filter((o)=>o.layer===t.layer);if(a.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let o=document.createDocumentFragment();for(let c of a){let m=document.createElement("button");m.type="button";let d=this.state?.selectedId===c.id;m.className="bp-plan-legend-chip"+(d?" active":"");let p=document.createElement("span");p.className="bp-plan-legend-sw",p.style.background=xt(c.net||c.id,c.color||"");let l=document.createElement("span");l.textContent=c.net||c.id,m.append(p,l),m.addEventListener("click",()=>{this.cb.onSelect(c.id),this.cb.onFocusItem(c.id)}),o.appendChild(m)}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 r=e.getBoundingClientRect(),a=i.clientX-r.left,o=i.clientY-r.top,c=Math.max(1,r.width),m=Math.max(1,r.height),d=this.getCam(t,c,m),p=Ot(s.bands,s.regions,t,s.selectedId,d,c,m,a,o);if(i.button===2){if(p?.kind==="vertex"){let l=this.getItemPts(p.id,p.isPlane),h=ln(l,p.idx,p.isPlane);if(h)this.selectedVertex=null,this.cb.onCommitFields(p.id,{[p.isPlane?"outline":"path"]:h})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},p?.kind==="vertex"){let l=this.getItemPts(p.id,p.isPlane),h=l.map((v)=>[v[0],v[1]]);this.selectedVertex={id:p.id,idx:p.idx},this.drag={layer:t,kind:"vertex",id:p.id,isPlane:p.isPlane,idx:p.idx,pts:l.map((v)=>[v[0],v[1]]),origPts:h,moved:!1},this.scheduleDraw()}else if(p?.kind==="midpoint"){let l=this.getItemPts(p.id,p.isPlane),h=l.map((g)=>[g[0],g[1]]),v=gi(l,p.segIdx,p.pos,p.isPlane),u=p.isPlane&&p.segIdx+1>=l.length?v.length-1:Math.min(p.segIdx+1,v.length-1);this.selectedVertex={id:p.id,idx:u},this.patchLocalItem(p.id,p.isPlane,v),this.drag={layer:t,kind:"vertex",id:p.id,isPlane:p.isPlane,idx:u,pts:v,origPts:h,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:a,lastY:o}}),e.addEventListener("pointermove",(i)=>{let s=this.state;if(!s)return;let r=e.getBoundingClientRect(),a=i.clientX-r.left,o=i.clientY-r.top,c=Math.max(1,r.width),m=Math.max(1,r.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let S=this.getCam(t,c,m);this.setCam(t,hi(S,a-this.drag.lastX,o-this.drag.lastY)),this.drag.lastX=a,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 u=this.getCam(t,c,m),[g,f]=Gt(u,a,o,c,m),w=[Math.round(g*1000)/1000,Math.round(f*1000)/1000];this.drag.moved=!0,this.drag.pts[this.drag.idx]=w;let x=this.drag.pts.map((S)=>[S[0],S[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,x),this.scheduleDraw();return}let d=this.getCam(t,c,m),p=Ot(s.bands,s.regions,t,s.selectedId,d,c,m,a,o),l=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",h=this.hover?.hit.kind??"",v=p?p.id:"";if(this.hover=p?{layer:t,hit:p}:null,e.style.cursor=p?"pointer":"crosshair",l!==v||(p?.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((r)=>[r[0],r[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,r=this.drag,a=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(i.pointerId))e.releasePointerCapture(i.pointerId);if(r&&r.kind==="vertex"&&r.layer===t){if(r.moved)this.cb.onCommitFields(r.id,{[r.isPlane?"outline":"path"]:r.pts});else this.cb.onDragEnd?.(),this.scheduleDraw();return}if(s&&a&&Math.hypot(i.clientX-a.x,i.clientY-a.y)<4.5){let o=e.getBoundingClientRect(),c=i.clientX-o.left,m=i.clientY-o.top,d=Math.max(1,o.width),p=Math.max(1,o.height),l=this.getCam(t,d,p),h=Ot(s.bands,s.regions,t,s.selectedId,l,d,p,c,m);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(),r=i.clientX-s.left,a=i.clientY-s.top,o=Math.max(1,s.width),c=Math.max(1,s.height),m=this.getCam(t,o,c),d=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,bi(m,d,r,a,o,c)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((r)=>r.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((r)=>r.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),r=n.regions.find((o)=>o.id===i),a="";if(s)a=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(r)a=r.reference?`${r.net||i} · ${r.reference}`:r.net||i;if(!a)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=a}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((a)=>a.id===t.selectedId),i=t.regions.find((a)=>a.id===t.selectedId),s=Boolean(n?.locked??i?.locked),r=e.key.toLowerCase();if(r==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(r==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(r==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(r==="w"&&n&&!s){e.preventDefault();let a=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+a))*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 a=Boolean(i),o=this.getItemPts(t.selectedId,a),c=ln(o,this.selectedVertex.idx,a);if(c)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[a?"outline":"path"]:c})}}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)),r=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${r}px`;let a=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*a),c=Math.round(r*a);if(n.canvas.width!==o||n.canvas.height!==c)n.canvas.width=o,n.canvas.height=c;n.ctx.setTransform(a,0,0,a,0,0),this.drawLayer(n.ctx,n.layer,s,r,e)}}drawLayer(e,t,n,i,s){let r=this.getCam(t,n,i),a=(u,g)=>Ve(r,u,g,n,i);e.fillStyle=xi,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((u)=>u.length>=3);if(e.fillStyle=Ms,o.length>0){e.beginPath();for(let u of o){for(let g=0;gu.layer===t),m=this.hover?.layer===t?this.hover.hit:null;for(let u of c){let g=u.outline??[];if(g.length<3)continue;let f=s.selectedId===u.id,w=m?.id===u.id,x=Hs(u.state||"proposed",f,w),S=xt(u.net||u.id,u.color||"");e.beginPath();for(let A=0;AT)T=H;if(ae>R)R=ae}if(Math.abs(T-A)>=38&&Math.abs(R-M)>=18){let V=vi(g,u.holes??[]);if(V){let[H,ae]=a(V[0],V[1]);e.fillStyle=rt(S,f?0.91:0.67),e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(N,H,ae)}}}}if(e.strokeStyle=Bs,e.lineWidth=1.25,e.lineCap="round",e.lineJoin="round",o.length>0){e.beginPath();for(let u of o){for(let g=0;gu.layer===t),l=yi(p,r,n,i,s.selectedId,m?.id??""),h=l.map((u)=>[u.cx-u.pw*0.5-1,u.cy-u.ph*0.5-1,u.cx+u.pw*0.5+1,u.cy+u.ph*0.5+1]),v=[];for(let u of p){for(let g of u.from??[])v.push(g);for(let g of u.to??[])v.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 u of wi(d,r,n,i,v,h))e.fillText(u.text,u.cx,u.cy);for(let u of p){let g=u.guides??[];if(g.length===0)continue;let f=s.selectedId===u.id||m?.id===u.id,w=dt(u.name||u.id,u.color||"");e.strokeStyle=rt(w,f?0.38:0.17),e.lineWidth=f?1:0.7,e.beginPath();for(let x of g){let[S,N]=a(x[0],x[1]),[A,M]=a(x[2],x[3]);e.moveTo(S,N),e.lineTo(A,M)}e.stroke()}for(let u of p){let g=u.path??[];if(g.length<2)continue;let f=s.selectedId===u.id,w=m?.id===u.id,x=js(u.state||"proposed",f,w),S=dt(u.name||u.id,u.color||""),N=cn(u.width??1.5,r.scale),A=()=>{e.beginPath();for(let M=0;M{let w=f?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 Dt(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,r]of Object.entries(n.data))if(r&&typeof r==="object")this.infos.set(`mgmt.${s}.${i}`,r)}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=Dt(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 a of t){let o=document.createElement("button");o.type="button";let c=this.openPanel===a.id;o.className="bp-mgmt-tab"+(c?" active":""),o.setAttribute("data-testid",`mgmt-tab-${a.id}`),o.setAttribute("aria-pressed",c?"true":"false");let m=document.createElement("span");m.textContent=pe(a.label),o.appendChild(m);let d=this.getPanelData(a.id),p=ei(d);if(p){let l=document.createElement("span");l.className=`bp-mgmt-badge bp-tone-${p.tone}`,l.textContent=p.text,o.appendChild(l)}o.addEventListener("click",()=>this.togglePanel(a.id)),i.appendChild(o)}if(n.appendChild(i),this.openPanel){let a=document.createElement("button");a.type="button",a.className="icon bp-mgmt-close",a.textContent="×",a.title=b("gpui.mgmt.close","Close the panel"),a.setAttribute("aria-label",b("gpui.mgmt.close","Close the panel")),a.setAttribute("data-testid","mgmt-close"),a.addEventListener("click",()=>this.closePanel()),n.appendChild(a)}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)),r=document.createDocumentFragment();if(this.errorMsg){let a=document.createElement("div");a.className="bp-mgmt-note bp-tone-bad",a.textContent=this.errorMsg,r.appendChild(a)}switch(this.openPanel){case"bom":r.appendChild(this.renderBom());break;case"checks":r.appendChild(this.renderChecks());break;case"life":r.appendChild(this.renderLife());break;case"plan":r.appendChild(this.renderPlan());break;case"fab":r.appendChild(this.renderFab());break}if(this.panelEl.replaceChildren(r),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 r=document.createElement("span"),a=t.source==="kicad";if(r.className="bp-mgmt-pill"+(a?" accent":""),r.textContent=a?"live":"saved",i.append(s,r),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let m=document.createElement("span");m.className="bp-dim",m.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${ct(t.cost)}/board`:`${ct(t.cost)}/board`,i.appendChild(m)}if(t.paused){let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent="Stock check paused",i.appendChild(m)}if(e.appendChild(i),t.stock_note){let m=document.createElement("div");m.className="bp-mgmt-note bp-mgmt-faint",m.textContent=pe(t.stock_note),e.appendChild(m)}let o=this.bomEditingId?n.find((m)=>m.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let m=document.createElement("div");m.className="bp-mgmt-filter-row";let d=document.createElement("input");d.type="text",d.className="bp-mgmt-filter",d.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",d.value=this.bomFilter,d.setAttribute("data-testid","mgmt-bom-filter"),d.addEventListener("input",()=>{this.bomFilter=d.value,this.renderBomRows(c,n)}),m.appendChild(d),e.appendChild(m)}let c=document.createElement("div");return c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(c,n),e.appendChild(c),e}renderBomRows(e,t){let n=ii(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((r)=>Boolean(r.mpn)||Boolean(r.fab)),s=document.createDocumentFragment();for(let r of n){let a=Array.isArray(r.refs)?r.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===r.id?" active":"")+(r.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${r.id}`);let c=document.createElement("div");c.className="bp-mgmt-row-line";let m=document.createElement("span");if(m.className="bp-mgmt-strong bp-mgmt-flex1",m.textContent=Ft(a,24),c.appendChild(m),r.dnp){let u=document.createElement("span");u.className="bp-mgmt-pill",u.textContent=b("gpui.mgmt.bom.dnp","DNP"),c.appendChild(u)}else{let u=ni(r.stock);if(u){let g=document.createElement("span");g.className=`bp-tone-${u.tone}`,g.textContent=u.text,c.appendChild(g)}}let d=document.createElement("button");d.type="button",d.className="bp-mgmt-btn",d.textContent="Edit",d.addEventListener("click",(u)=>{u.stopPropagation(),this.bomEditGen++,this.bomEditingId=r.id,this.bomEditDraft=r.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),c.appendChild(d);let p=document.createElement("div");p.className="bp-mgmt-row-sub";let l=[`${r.qty??a.length}×`,r.value??"",ti(r.footprint??"")].filter(Boolean).join(" · "),h=document.createElement("span");h.className="bp-dim",h.textContent=l;let v=document.createElement("span");if(v.className="bp-mgmt-flex1",r.mpn)v.textContent=r.mpn;else if(i&&!r.dnp)v.className+=" bp-tone-warn",v.textContent=b("gpui.mgmt.bom.nompn","no MPN");if(p.append(h,v),!r.dnp&&typeof r.stock?.price==="number"){let u=document.createElement("span");u.className="bp-dim",u.textContent=ct(r.stock.price),p.appendChild(u)}if(!r.dnp&&r.stock?.class){let u=document.createElement("span");u.className="bp-mgmt-faint",u.textContent=pe(r.stock.class),p.appendChild(u)}o.append(c,p),o.addEventListener("click",()=>{this.bomSelectedId=r.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=Ft(n,30);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,r);let a=document.createElement("input");a.type="text",a.className="bp-mgmt-filter",a.placeholder="MPN",a.value=this.bomEditDraft,a.addEventListener("input",()=>{this.bomEditDraft=a.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),c=async(l,h=!1)=>{let v=o();this.bomEditStatus="Writing…",this.render();try{let u=await this.cb.hub.rpc("mgmt.bom.edit",l);if(!an(v,o()))return;this.bomLastUndo=!h&&(u.changed??0)>0?{project:l.project,editId:v.editId,refs:l.refs.slice(),field:l.field,was:typeof u.was==="string"?u.was:l.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=h?"Restored":(u.changed??0)===0?"No change":u.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(u){if(!an(v,o()))return;this.bomEditStatus=u instanceof Error?u.message:"Could not save edit"}this.render()},m=document.createElement("div");m.className="bp-mgmt-btn-row";let d=document.createElement("button");d.type="button",d.className="primary bp-mgmt-btn",d.textContent="Save MPN",d.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let p=document.createElement("button");if(p.type="button",p.className="bp-mgmt-btn",p.textContent=e.dnp?"Clear DNP":"Mark DNP",p.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),m.append(d,p),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let l=this.bomLastUndo,h=document.createElement("button");h.type="button",h.className="bp-mgmt-btn",h.textContent="Undo",h.addEventListener("click",()=>{c(pi(l),!0)}),m.appendChild(h)}if(t.append(i,a,m),this.bomEditStatus){let l=document.createElement("div");l.className="bp-mgmt-faint",l.textContent=this.bomEditStatus,t.appendChild(l)}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((l)=>l.source).filter(Boolean))),s=(l)=>t.sources?.[l]?.label||l.toUpperCase(),r=(l)=>t.sources?.[l]?.judged===!0,a=document.createElement("div");a.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=b("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),a.appendChild(o);for(let l of i){let h=document.createElement("button");h.type="button",h.className="bp-mgmt-btn"+(this.checksSource===l?" active":""),h.textContent=s(l)+(r(l)?" · judged":""),h.addEventListener("click",()=>{this.checksSource=this.checksSource===l?"":l,this.render()}),a.appendChild(h)}let c=document.createElement("span");c.className="bp-mgmt-flex1";let m=document.createElement("button");if(m.type="button",m.className="bp-mgmt-btn",m.textContent=b("gpui.mgmt.checks.run","Run"),m.addEventListener("click",()=>{let l=this.watchGen,h=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:h}).then(()=>{if(l!==this.watchGen||h!==this.project)return;this.checksStatus="",this.render()}).catch((v)=>{if(l!==this.watchGen||h!==this.project)return;this.checksStatus=v instanceof Error?v.message:"Could not run checks",this.render()})}),a.append(c,m),e.appendChild(a),this.checksStatus){let l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=this.checksStatus,e.appendChild(l)}let d=document.createElement("div");d.className="bp-mgmt-rows",d.setAttribute("data-testid","mgmt-checks-rows");let p=si(n,this.checksSource);if(p.length===0)d.appendChild(this.makeEmpty("No check findings."));else for(let l of p){let h=l.severity==="error"?"bad":l.severity==="warning"?"warn":"faint",v=document.createElement("div");v.className="bp-mgmt-group-head";let u=document.createElement("span");u.className=`bp-mgmt-dot bp-tone-bg-${h}`;let g=document.createElement("span");g.className="bp-mgmt-flex1",g.textContent=`${s(l.source)} · ${l.rule}`;let f=document.createElement("span");f.className=`bp-tone-${h}`,f.textContent=String(l.n),v.append(u,g,f),d.appendChild(v);for(let w of l.rows??[]){let x=document.createElement("div");x.className="bp-mgmt-row"+(this.checksSelectedId===w.id?" active":"");let S=document.createElement("div");if(S.textContent=pe(w.title??""),x.appendChild(S),w.names||this.checksSelectedId===w.id){let N=document.createElement("div");N.className="bp-mgmt-row-sub";let A=document.createElement("span");if(A.className="bp-dim bp-mgmt-flex1",A.textContent=w.names??"",N.appendChild(A),this.checksSelectedId===w.id){let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn accent",M.textContent=b("gpui.mgmt.checks.fix","Fix with agent"),M.addEventListener("click",(T)=>{T.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 H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!on(R,H))return;if(V.text)this.cb.onSendText(V.text),this.checksStatus="Sent to agent",this.render()}).catch((V)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!on(R,H))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()}),d.appendChild(x)}}return e.appendChild(d),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 c of["active","nrnd","eol"]){let m=i[c]??0,d=rn(c),p=document.createElement("span");p.className=m>0?`bp-tone-${d.tone}`:"bp-mgmt-faint",p.textContent=`${d.label} ${m}`,n.appendChild(p)}if((i.unknown??0)>0){let c=document.createElement("span");c.className="bp-mgmt-faint",c.textContent=`${i.unknown} unknown`,n.appendChild(c)}if(t.since){let c=document.createElement("span");c.className="bp-mgmt-flex1";let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent=`since ${$t(t.since)} (${t.samples??0})`,n.append(c,m)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let r=t.bom?.cost??[],a=t.bom?.instock??[],o=t.bom?.lines??0;if(r.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 c=r[r.length-1],m=a[a.length-1],d=document.createElement("div");d.className="bp-mgmt-note bp-dim",d.textContent=`Parts/board: ${ct(c[1])} · ${Math.round(m?.[1]??0)}/${o} lines in stock (${$t(c[0])})`,s.appendChild(d)}for(let c of t.parts??[]){let m=this.lifeSelectedKey===c.key,d=rn(c.lifecycle??"unknown"),p=document.createElement("div");p.className="bp-mgmt-row"+(m?" active":"");let l=document.createElement("div");l.className="bp-mgmt-row-line";let h=document.createElement("span");h.className="bp-mgmt-strong",h.textContent=Ft(c.refs??[],14);let v=document.createElement("span");v.className="bp-mgmt-flex1 bp-dim",v.textContent=c.mpn||c.key;let u=document.createElement("span");if(u.className=`bp-tone-${d.tone}`,u.textContent=d.label,l.append(h,v,u),typeof c.stock==="number"){let g=document.createElement("span");g.className="bp-dim",g.textContent=lt(c.stock),l.appendChild(g)}if(p.appendChild(l),m){let g=document.createElement("div");if(g.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)g.textContent=b("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let f=this.lifePartSamples[this.lifePartSamples.length-1];g.textContent=`${this.lifePartSamples.length} samples · latest ${f.at?$t(f.at):""}`+(typeof f.stock==="number"?` · stock ${lt(f.stock)}`:"")+(typeof f.price==="number"?` · ${ct(f.price)}`:"")}else g.textContent=b("gpui.mgmt.life.nopart","No reading of this part yet.");p.appendChild(g)}p.addEventListener("click",()=>{if(this.lifeSelectedKey===c.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=c.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:c.key}).then((g)=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(g.samples)?g.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(p)}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(b("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(E,k)=>{let j=this.watchGen,B=this.project;this.planStatus="",this.cb.hub.rpc(E,{pro:B,...k}).catch((q)=>{if(j!==this.watchGen||B!==this.project)return;this.planOptimistic.clear(),this.planStatus=q instanceof Error?q.message:b("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,B=t.revision??0;this.cb.hub.rpc("plan.get",{pro:j,board:!0}).then((q)=>{let te=Ei(q);if(!te)return;let D=typeof te.revision==="number"?te.revision:B;if(!Ci(E,this.watchGen,k,this.planHydrateGen,j,this.project,D,this.planHydratedRev))return;this.planHydratedRev=D,this.planHydratedKey=`${j}:${D}`,this.planHydratedBoard=te.board??null,this.planHydratedDraw=te.draw??null,this.render()}).catch(()=>{})}let s=t.on===!0,r=document.createElement("div");r.className="bp-plan-header";let a=document.createElement("div");a.className="bp-plan-toggle";let o=document.createElement("span");o.className="bp-mgmt-strong",o.textContent=b("gpui.mgmt.plan.before","Plan before routing"),o.title=s?b("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."):b("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."),a.appendChild(o);let c=t.awaiting??0,m=t.blocked??0,d=t.done??0,p=t.total??0,l=t.revision??0,h=t.empty?[]:li(t),v=h.reduce((E,k)=>E+k.count,0);if(!t.empty){let E=oi(t),k=document.createElement("span");if(k.className=`bp-plan-status-badge tone-${E.tone}`,k.textContent=b(E.key,E.label),a.appendChild(k),l>0){let B=document.createElement("span");B.className="bp-dim",B.textContent=`v${l}`,a.appendChild(B)}let j=document.createElement("span");if(j.className="bp-plan-header-counts bp-mgmt-flex1 "+(c>0?"bp-tone-warn":m>0?"bp-tone-bad":"bp-dim"),j.textContent=p>0?`${d}/${p} ${b("gpui.mgmt.plan.done","done")}`:c>0?b("web.plan.awaiting","{n} awaiting approval",{n:c}):b("gpui.mgmt.plan.nothing","Nothing awaits your approval"),a.appendChild(j),!t.live){let B=document.createElement("span");B.className="bp-mgmt-pill",B.textContent=b("gpui.mgmt.plan.saved","saved plan"),a.appendChild(B)}}else{let E=document.createElement("span");E.className="bp-mgmt-flex1",a.appendChild(E)}let u=document.createElement("button");u.type="button",u.className="bp-mgmt-btn bp-plan-chip-btn"+(s?" active":""),u.setAttribute("data-testid","mgmt-plan-on"),u.setAttribute("aria-pressed",s?"true":"false"),u.textContent=b("gpui.bots.recall.on","On"),u.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=b("gpui.bots.recall.off","Off"),g.addEventListener("click",()=>n("plan.enable",{on:!1})),a.append(u,g),r.appendChild(a),v>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)}r.appendChild(E)}e.appendChild(r);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=b("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=b("gpui.mgmt.plan.noboard","No routing plan for this board.");let j=document.createElement("div");return j.className="bp-mgmt-faint",j.textContent=b("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),E.append(k,j),e.appendChild(E),e}let f=t.stackup_summary??"",w=Array.isArray(t.impedances)?t.impedances:[],x=Boolean(f)||w.length>0,S=document.createElement("div");if(S.className="bp-mgmt-head",c>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=b("gpui.mgmt.plan.all","Approve all"),E.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),S.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=b("gpui.mgmt.plan.stop","Stop routing"),E.addEventListener("click",()=>n("plan.stop",{})),S.appendChild(E)}if(t.live&&d>0){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-verify"),E.textContent=b("gpui.mgmt.plan.verify","Verify"),E.addEventListener("click",()=>n("plan.verify",{})),S.appendChild(E)}let N=document.createElement("span");if(N.className="bp-mgmt-flex1",S.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=`${b("gpui.mgmt.plan.stackup.short","Stackup")} ${this.planStackupOpen?"▾":"▸"}`,E.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),S.appendChild(E)}let A=document.createElement("button");A.type="button",A.className="bp-mgmt-btn",A.setAttribute("data-testid","mgmt-plan-hide"),A.textContent=this.planHideDone?b("gpui.mgmt.plan.show","Show done"):b("gpui.mgmt.plan.hide","Hide done"),A.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),S.appendChild(A),e.appendChild(S);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 B=document.createElement("div");B.className="bp-plan-ask-col";let q=document.createElement("div");if(q.className="bp-tone-warn",q.textContent=E?b("gpui.mgmt.plan.requested","Approval requested: {what}",{what:E}):b("gpui.mgmt.plan.reqplain","Approval requested"),B.appendChild(q),k){let te=document.createElement("div");te.className="bp-dim",te.textContent=k,B.appendChild(te)}j.appendChild(B),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"?b("gpui.mgmt.plan.refused","KiCad refused"):pe(this.planStatus);let j=document.createElement("button");j.type="button",j.className="icon",j.textContent="×",j.title=b("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?b("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"),f){let k=document.createElement("div");k.className="bp-dim",k.textContent=f,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 T=(E,k,j,B)=>{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",B),q},R=document.createElement("div");if(R.className="bp-plan-viewbar",R.append(T(b("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),T(b("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),T(b("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=b("gpui.mgmt.plan.fit","Fit"),j.addEventListener("click",()=>this.planCanvas?.fitAll()),R.append(E,T(b("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),T(b("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),T(b("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),k,T(b("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 H=document.createElement("button");H.type="button",H.className="bp-mgmt-btn bp-plan-mini-btn",H.setAttribute("data-testid","mgmt-plan-expand"),H.textContent=this.planExpanded?b("gpui.mgmt.plan.compact","Compact"):b("gpui.mgmt.plan.expand","Expand"),H.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),R.append(V,H),e.appendChild(R);let ae=Boolean(this.planHydratedBoard)&&this.planHydratedKey.startsWith(`${this.project}:`)&&(this.planHydratedKey===i||this.planHydratedRev!==void 0&&this.planHydratedRev>=(t.revision??0)),ue=ae&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},oe=ae&&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}}),Se=(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 B=this.planOptimistic.get(j.id);if(!B){k.push(j);continue}let q={...j,width:typeof B.width==="number"?B.width:j.width,locked:typeof B.locked==="boolean"?B.locked:j.locked,edited:!0,state:j.state==="proposed"?"edited":j.state};if(typeof B.layer==="string"&&B.layer!==E.layer)Me.push({target:B.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=Vt(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))??pt(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):pt(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),B=(k.items??[]).length,q=st(k.layer,t.copper_layers,be)||k.title||k.layer,te=B>0?`${q} · ${B}`:q,D=T(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(B===0&&!j)D.classList.add("empty-layer");E.appendChild(D)}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 B=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:E,fields:k}],...B!==void 0?{base:B}:{}})};if(this.planCommitFields=le,this.planSelectedId){let E="",k=null;for(let j of he){let B=(j.items??[]).find((q)=>q.id===this.planSelectedId);if(B){E=j.layer,k=B;break}}if(k){let j=st(E,t.copper_layers,be),B=document.createElement("div");B.className="bp-plan-inspector",B.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"?dt(k.name||k.id,k.color||""):xt(k.name||k.id,k.color||"");let D=document.createElement("span");D.className="bp-mgmt-strong",D.textContent=k.name||k.id;let K=document.createElement("span");if(K.className="bp-dim",K.textContent=j,q.append(te,D,K),k.edited||k.state==="edited"){let Y=document.createElement("span");Y.className="bp-plan-ins-pill warn",Y.textContent=b("gpui.mgmt.plan.edited","Edited"),q.appendChild(Y)}if(k.locked){let Y=document.createElement("span");Y.className="bp-plan-ins-pill",Y.textContent=b("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?b("gpui.mgmt.plan.unlock","Unlock"):b("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=b("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=b("gpui.mgmt.plan.reject","Reject"),ve.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[k.id],approve:!1})),q.append(Y,ve)}let me=document.createElement("button");me.type="button",me.className="bp-mgmt-btn bp-plan-mini-btn",me.setAttribute("data-testid","mgmt-plan-note-toggle"),me.textContent=b("gpui.mgmt.plan.addnote","Add note"),me.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(me,Pe),B.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=b("gpui.mgmt.plan.width","Width");let He=document.createElement("button");He.type="button",He.className="bp-mgmt-btn bp-plan-mini-btn",He.setAttribute("data-testid","mgmt-plan-w-down"),He.textContent="-",He.addEventListener("click",()=>{let Ue=Math.round(Math.max(0.15,ie-0.25)*100)/100;le(k.id,{width:Ue})});let re=document.createElement("span");re.className="bp-plan-ins-val",re.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,He,re,ge,_e)}let ve=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((ie)=>ie.layer):he.map((ie)=>ie.layer);if(ve.length>0){let ie=document.createElement("span");ie.className="bp-dim",ie.textContent=b("gpui.mgmt.plan.layer.short","Layer"),Y.appendChild(ie),Y.appendChild(T(`${j} ${this.planMoveLayerOpen?"▴":"▾"}`,this.planMoveLayerOpen,"mgmt-plan-move-toggle",()=>{this.planMoveLayerOpen=!this.planMoveLayerOpen,this.render()}))}if(B.appendChild(Y),this.planMoveLayerOpen&&ve.length>0){let ie=document.createElement("div");ie.className="bp-plan-ins-row";for(let ke of ve){let He=st(ke,t.copper_layers,be);ie.appendChild(T(He,ke===E,`mgmt-plan-move-${ke}`,()=>{if(this.planMoveLayerOpen=!1,ke!==E)le(k.id,{layer:ke});else this.render()}))}B.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=b("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=b("gpui.mgmt.plan.addnote","Add note"),Y.append(ve,ie),Y.addEventListener("submit",(ke)=>{ke.preventDefault();let He=ve.value.trim();if(!He)return;ve.value="",this.planNoteOpen=!1;let re=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:k.id,text:He}],...re!==void 0?{base:re}:{}})}),B.appendChild(Y)}if(this.planViewMode!=="list"&&!k.locked){let Y=document.createElement("div");Y.className="bp-plan-hint",Y.textContent=b("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),B.appendChild(Y)}e.appendChild(B)}}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=b("gpui.mgmt.plan.done","done"),ce=fi(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=b("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 B=document.createElement("div");B.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 D=document.createElement("span");D.className="bp-mgmt-strong",D.textContent=j;let K=document.createElement("span");K.className="bp-dim",K.textContent=`${E.done??0}/${k.length} ${X}`,B.append(te,D,K),ne.appendChild(B)}}else{let B=document.createElement("div");B.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 D=document.createElement("span");if(D.className="bp-dim bp-mgmt-flex1",D.textContent=`${E.role?`${E.role} · `:""}${E.done??0}/${k.length} ${X}`,q.append(te,D),E.status!=="approved"&&k.length>0){let K=document.createElement("button");K.type="button",K.className="bp-mgmt-btn",K.textContent=b("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=b("gpui.mgmt.plan.reject","Reject"),je.addEventListener("click",()=>n("plan.approve",{layer:E.layer,ids:[],approve:!1})),q.append(K,je)}if(B.appendChild(q),E.stackup){let K=document.createElement("div");K.className="bp-plan-layer-stackup",K.textContent=E.stackup,B.appendChild(K)}ne.appendChild(B)}for(let B of k){if(this.planHideDone&&ri(B))continue;let q=this.planSelectedId===B.id,te=document.createElement("div");te.className="bp-mgmt-row bp-plan-row"+(q?" active":""),te.setAttribute("data-testid",`mgmt-plan-row-${B.id}`);let D=document.createElement("div");D.className="bp-mgmt-row-line";let K=document.createElement("span");K.className=`bp-plan-swatch bp-plan-st-${B.state||"proposed"}`,K.style.setProperty("--swatch-color",B.color||"#8a8a8a");let je=document.createElement("span");je.className="bp-mgmt-flex1"+(B.state==="blocked"||B.state==="failed"?" bp-tone-bad":B.state==="edited"?" bp-tone-warn":B.state==="rejected"||B.state==="routed"||B.state==="verified"?" bp-dim":""),je.textContent=`${B.name||B.id}${B.locked?" \uD83D\uDD12":""}`;let Le=[];if(B.kind==="plane"){if(B.reference)Le.push(b("gpui.mgmt.plan.reference","over {layer}",{layer:B.reference}))}else{let Y=B.nets??0;Le.push(Y===1?b("web.plan.net.one","1 net"):b("web.plan.nets","{n} nets",{n:Y}))}if(typeof B.width==="number"&&Number.isFinite(B.width))Le.push(`${B.width.toFixed(2)}mm`);if(B.impedance)Le.push(B.impedance);let me=Le.join(" · "),Pe=document.createElement("span");if(Pe.className="bp-plan-mark "+(B.state==="blocked"||B.state==="failed"?"bp-tone-bad":B.state==="verified"||B.state==="routed"?"bp-tone-ok":B.state==="approved"?"bp-tone-accent":"bp-dim"),Pe.textContent=ai(B),D.append(K,je,Pe),B.state==="proposed"||B.state==="edited"){let Y=document.createElement("button");Y.type="button",Y.className="bp-mgmt-btn",Y.textContent="✓",Y.title=b("gpui.mgmt.plan.layer","Approve layer"),Y.addEventListener("click",(ie)=>{ie.stopPropagation(),n("plan.approve",{layer:"",ids:[B.id],approve:!0})});let ve=document.createElement("button");ve.type="button",ve.className="bp-mgmt-btn",ve.textContent="✗",ve.title=b("gpui.mgmt.plan.reject","Reject"),ve.addEventListener("click",(ie)=>{ie.stopPropagation(),n("plan.approve",{layer:"",ids:[B.id],approve:!1})}),D.append(Y,ve)}if(te.appendChild(D),me){let Y=document.createElement("div");Y.className="bp-mgmt-row-sub bp-plan-detail bp-dim",Y.textContent=me,te.appendChild(Y)}if(B.state==="routing"&&typeof B.total==="number"&&B.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((B.routed??0)/B.total*100)));ve.style.width=`${ie}%`,Y.appendChild(ve),te.appendChild(Y)}if(B.problem_text){let Y=document.createElement("div");Y.className="bp-plan-problem",Y.textContent=B.problem_text,te.appendChild(Y)}te.addEventListener("click",()=>{this.planSelectedId=B.id,n("plan.focus",{id:B.id}),this.render()}),ne.appendChild(te)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new dn({onSelect:(B)=>{if(this.planSelectedId=B,!B)this.planNoteOpen=!1;this.render()},onFocusItem:(B)=>{n("plan.focus",{id:B})},onDragEnd:()=>{if(this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onCommitFields:(B,q)=>{(this.planCommitFields??le)(B,q)},onApproveLayer:(B,q)=>{n("plan.approve",{layer:B,ids:[],approve:q})},onQuickApprove:(B,q)=>{n("plan.approve",{layer:"",ids:B,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:ue,bands:we,regions:Se,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=b("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 S=this.watchGen,N=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:N,action:w,...x}).catch((A)=>{if(S!==this.watchGen||N!==this.project)return;this.fabStatus=A instanceof Error?A.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=b("gpui.mgmt.fab.thefab","The fab");let r=document.createElement("span");r.className="bp-dim bp-mgmt-flex1",r.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${di(t.tier??"")}`;let a=document.createElement("button");if(a.type="button",a.className="bp-mgmt-btn",a.textContent=b("gpui.mgmt.fab.refresh","Refresh"),a.addEventListener("click",()=>n("refresh")),i.append(s,r,a),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 c=t.review,m=document.createElement("div");m.className="bp-mgmt-row";let d=document.createElement("div");d.className="bp-mgmt-row-line";let p=document.createElement("span"),l=(c?.counts?.error??0)>0;if(p.className="bp-mgmt-flex1 "+(l?"bp-tone-bad":"bp-dim"),p.textContent=c?.running?"Reviewing the design…":c?.at==null?"No design review yet":`${c.counts?.error??0} must-fix · ${c.counts?.warning??0} should-fix · ${c.counts?.info??0} notes${c.scope?` (${c.scope})`:""}`,d.appendChild(p),c?.at!=null){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.findings","Findings"),w.addEventListener("click",()=>this.togglePanel("checks")),d.appendChild(w)}if(!c?.running){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.reviewbtn","Review"),w.addEventListener("click",()=>n("review")),d.appendChild(w)}if(c?.judge){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.judge","Datasheets"),w.addEventListener("click",()=>{if(c.judge)this.cb.onSendText(c.judge)}),d.appendChild(w)}m.appendChild(d),o.appendChild(m);let h=ci(t.drc?.state??""),v=document.createElement("div");v.className="bp-mgmt-row";let u=document.createElement("div");u.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,u.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")),u.appendChild(w)}v.appendChild(u),o.appendChild(v);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 S=document.createElement("div");S.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 A=document.createElement("button");A.type="button",A.className="bp-mgmt-btn",A.textContent=b("gpui.mgmt.fab.apply","Apply"),A.addEventListener("click",()=>n("apply",{key:w.key})),S.append(N,A),x.appendChild(S),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 S=t.stackup.by==="proposed",N=document.createElement("span");if(N.className="bp-mgmt-flex1 "+(S?"bp-tone-warn":"bp-dim"),N.textContent=`${S?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,x.appendChild(N),S){let A=t.stackup.chosen,M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=b("gpui.mgmt.fab.use","Use"),M.addEventListener("click",()=>n("stackup",{id:A})),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 S=document.createElement("span");S.className="bp-mgmt-flex1 bp-tone-warn",S.textContent=b("gpui.mgmt.fab.changed","Changed since you last looked");let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.textContent=b("gpui.mgmt.fab.seen","Seen"),N.addEventListener("click",()=>n("seen")),x.append(S,N),w.appendChild(x);for(let A of t.changed.slice(0,12)){let M=document.createElement("div");M.className="bp-mgmt-faint",M.textContent=A,w.appendChild(M)}o.appendChild(w)}let f=Array.isArray(t.limits)?t.limits:[];if(f.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=b("gpui.mgmt.fab.limit","Limit");let S=document.createElement("span");S.className="bp-mgmt-col",S.textContent=b("gpui.mgmt.fab.free","Base price");let N=document.createElement("span");N.className="bp-mgmt-col",N.textContent=b("gpui.mgmt.fab.extra","Costs more");let A=document.createElement("span");A.className="bp-mgmt-col bp-mgmt-col-read",A.textContent=b("gpui.mgmt.fab.readcol","Read"),w.append(x,S,N,A),o.appendChild(w);for(let T of f){let R=document.createElement("div");R.className="bp-mgmt-row";let V=document.createElement("div");V.className="bp-mgmt-row-line";let H=document.createElement("span");H.className="bp-mgmt-flex1"+(T.changed?" bp-tone-warn":T.inherited?" bp-dim":""),H.textContent=`${T.changed?"• ":""}${T.label??""}`;let ae=document.createElement("span");ae.className="bp-mgmt-col",ae.textContent=T.free?.text||"—";let ue=document.createElement("span");ue.className="bp-mgmt-col bp-dim",ue.textContent=T.extra?.text||"—";let oe=T.free&&typeof T.free==="object"?T.free:T.extra,we=oe?.fetched??"",Se=Boolean(we)&&oe?.confidence!=="published",Me=we?Se?`${we}*`:we:"—",he=oe?.source??"",be;if(he.startsWith("https://")&&we){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}V.append(H,ae,ue,be),R.appendChild(V),o.appendChild(R)}let M=document.createElement("div");M.className="bp-mgmt-note bp-mgmt-faint",M.textContent=b("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 Fs={trs:(e)=>e,t:(e,t)=>t},$s=new Set(["/settle"]);function Si(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((a)=>a.startsWith(n)))return 2;let r=0;for(let a=0;a0||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 Pi(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 Ni(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 Mi(e,t=Fs){let{t:n,trs:i}=t,s=[],r=new Map;for(let o of e.projects)r.set(o.id,o.title||o.id);let a=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!a&&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(a)s.push({label:a.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:a.pinned?"unpin":"pin"}}),s.push({label:a.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:a.settled?"unsettle":"settle"}}),s.push({label:a.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:a.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(a)for(let o of e.commands){if(!o.word)continue;let c=$s.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:c}})}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:c,want:m}=Li(o);s.push({label:o.title||"Untitled thread",place:o.project?r.get(o.project)??"":"",kind:"thread",urgency:c,want:m,dotClass:Pi(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 Bi(e,t,n,i=[],s=10,r=14){let a=t.trim(),o=a.length===0,c=e.slice();if(n?.threads&&n.threads.length>0){let l=new Map;for(let v of i)l.set(v.id,v.title||v.id);let h=new Set;for(let v of c)if(v.action.type==="thread")h.add(v.action.id);for(let v of n.threads){if(!v.id||h.has(v.id))continue;h.add(v.id);let{urgency:u,want:g}=Li(v);c.push({label:v.title||"Untitled thread",place:v.project?l.get(v.project)??"":"",kind:"thread",urgency:u,want:g,dotClass:Pi(v),action:{type:"thread",id:v.id}})}}let m=[];for(let l=0;l0)m.push({score:g,index:l,item:h})}m.sort((l,h)=>{if(o){let g=(h.item.urgency??0)-(l.item.urgency??0);if(g!==0)return g}if(h.score!==l.score)return h.score-l.score;let v=l.item.kind==="thread"?0:1,u=h.item.kind==="thread"?0:1;if(v!==u)return v-u;return l.index-h.index});let d=new Set,p=[];for(let l of m){let h=`${l.item.label}\x00${l.item.place}\x00${l.item.kind}`;if(d.has(h))continue;if(d.add(h),p.push(l.item),p.length>=s)break}if(n?.messages&&n.messages.length>0&&p.length{if(a.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(a)=>{if(a.key==="Escape")a.preventDefault(),a.stopPropagation(),this.close();else if(a.key==="ArrowDown"){if(a.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(a.key==="ArrowUp"){if(a.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(a.key==="Enter")a.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=r,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=Mi(t,{t:b,trs:pe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=Bi(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 a=document.createElement("div");a.className="bp-palette-empty",a.textContent=b("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(a);return}let s=document.createDocumentFragment(),r=null;for(let a=0;a0)m.appendChild(document.createTextNode(o.label.slice(0,l)));let v=document.createElement("strong");if(v.className="bp-palette-mark",v.textContent=o.label.slice(l,h),m.appendChild(v),h{if(this.activeIdx!==a)this.activeIdx=a,this.updateActiveClass()}),c.addEventListener("click",()=>this.runAt(a)),a===this.activeIdx)r=c;s.appendChild(c)}if(this.listEl.replaceChildren(s),e&&r)r.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return r}render(){let e=this.items.filter((a)=>a.group!=="tools"),t=this.items.filter((a)=>a.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let a of e){if(i!==void 0&&a.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=a.group,n.appendChild(this.renderButton(a))}let s=()=>{let a=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let a=document.createElement("div");a.className="bp-rail-tools";for(let o of t)a.appendChild(this.renderButton(o));r.appendChild(a)}this.el.replaceChildren(r)}}var Vs=new Set(["resume","raise","retry","move","signin"]);function ji(e){if(!e||typeof e!=="object")return null;let t=e,n=(r)=>typeof r==="string"?r:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((r)=>Boolean(r)&&typeof r==="object").map((r)=>({label:n(r.label),act:n(r.act),room:n(r.room),thread:n(r.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function Ut(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(Vs.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 Hi(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}class bn{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;forceProviders=!1;providersEl=null;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";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${b("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",b("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}async openToAccounts(){this.forceProviders=!0,await this.open(),this.providersEl?.scrollIntoView({block:"nearest"})}close(){this.openState=!1,this.forceProviders=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${b("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",b("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment();this.providersEl=null;let t=this.cb.onGetNoProvider?.()??null;if(t||this.forceProviders){let d=document.createElement("section");d.className="bp-set-section",d.setAttribute("data-testid","settings-providers");let p=document.createElement("div");p.className="bp-set-head",p.textContent=b("web.settings.providers","AI providers");let l=document.createElement("div");l.className="bp-set-row";let h=document.createElement("div");h.className="bp-set-info";let v=document.createElement("div");v.textContent=t?pe(t.head):b("provider.notice.head","No AI provider connected");let u=document.createElement("div");u.className="bp-dim",u.textContent=b("web.settings.providers.browser","Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."),h.append(v,u);let g=document.createElement("div");g.className="bp-set-btns";let f=document.createElement("a");f.className="bp-link-btn primary",f.href=t?.url||"backplane://settings/accounts",f.setAttribute("data-testid","settings-open-accounts"),f.textContent=t?pe(t.button):b("provider.notice.button","Open Settings → Accounts"),g.appendChild(f),l.append(h,g),d.append(p,l),this.providersEl=d,e.appendChild(d)}let n=this.cb.onGetHome?.()??null;if(n){let d=document.createElement("section");d.className="bp-set-section",d.setAttribute("data-testid","settings-home");let p=document.createElement("div");p.className="bp-set-head",p.textContent=b("home.machine","Home machine");let l=document.createElement("div");l.className="bp-set-row";let h=document.createElement("div");h.className="bp-set-info";let v=document.createElement("div"),u=n.kind==="local"?`${n.name||"This machine"} (this machine)`:n.kind==="boat"?`${n.name||"Boat"} (Boat)`:n.name||"Linked machine";v.textContent=u,h.appendChild(v);let g=document.createElement("div");if(g.className="bp-dim",n.moving?.state==="moving")g.textContent=n.moving.step?b("home.moving.step","Moving home to {to}: {step}").replace("{to}",n.moving.to).replace("{step}",n.moving.step):b("home.moving","Moving home to {to}…").replace("{to}",n.moving.to);else if(n.moving?.state==="failed")g.textContent=n.moving.note?b("home.move.failed.note","Home move failed: {note}").replace("{note}",n.moving.note):b("home.move.failed","Home move failed");else if(!n.online)g.textContent=n.queuedCount>0?b("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",n.name||"home").replace("{n}",String(n.queuedCount)):b("home.away","Home ({name}) is away").replace("{name}",n.name||"home");else g.textContent="Online";if(h.appendChild(g),l.appendChild(h),n.canMoveHere&&this.cb.onMoveHomeHere){let f=document.createElement("button");f.type="button",f.className="primary",f.textContent=b("home.move.here","Make this machine the home"),f.setAttribute("data-testid","home-move-here-btn"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),l.appendChild(f)}d.append(p,l),e.appendChild(d)}let i=document.createElement("section");i.className="bp-set-section";let s=document.createElement("div");s.className="bp-set-head",s.textContent="This browser";let r=document.createElement("div");r.className="bp-set-row";let a=document.createElement("span");a.className="bp-dim",a.textContent="Sign out and revoke this browser's session cookie.";let o=document.createElement("button");o.type="button",o.className="primary stop",o.textContent=b("agy.signout","Sign out"),o.setAttribute("data-testid","logout-btn"),o.addEventListener("click",()=>{o.disabled=!0,this.cb.onLogout().catch(()=>{a.setAttribute("role","alert"),a.textContent=b("web.logout.failed","Could not confirm sign-out. Try again."),o.disabled=!1})}),r.append(a,o),i.append(s,r),e.appendChild(i);let c=document.createElement("section");c.className="bp-set-section";let m=document.createElement("div");m.className="bp-set-head",m.textContent="Paired devices",c.appendChild(m);try{let d=await this.cb.onLoadDevices();if(d.length===0){let p=document.createElement("div");p.className="bp-dim",p.textContent="No devices listed.",c.appendChild(p)}else for(let p of d){let l=document.createElement("div");l.className="bp-set-row";let h=document.createElement("div");h.className="bp-set-info";let v=document.createElement("div");if(v.textContent=p.title||p.head||"",h.appendChild(v),p.text||p.detail){let u=document.createElement("div");u.className="bp-dim",u.textContent=p.text||p.detail||"",h.appendChild(u)}if(l.appendChild(h),p.buttons?.length){let u=document.createElement("div");u.className="bp-set-btns";for(let g of p.buttons){let f=document.createElement("button");if(f.type="button",g.primary)f.className="primary";if(g.danger)f.className="primary stop";f.textContent=g.label||b("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(g.action,g.value).finally(()=>{this.refresh()})}),u.appendChild(f)}l.appendChild(u)}c.appendChild(l)}}catch(d){let p=document.createElement("div");p.className="bp-dim";let l=d instanceof Error&&d.message?d.message:"Not available from a browser";p.textContent=`${l} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,c.appendChild(p)}e.appendChild(c),this.bodyEl.replaceChildren(e)}}function Ee(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function kt(e,t,n=!1){let i=Ee("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function gn(e){return Ee("pre","bp-context-code",e)}function Us(e){return Ee("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,pe(e))}function Wt(e,t){let n=Ee("div","bp-context-row");return n.append(Ee("strong",void 0,e),Us(t)),n}class fn{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,kt(b("common.refresh","Refresh"),()=>{this.load()}),kt(b("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=b("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=b("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=[b("thread.context.instructions","Instructions"),b("thread.context.system","System Prompt"),b("thread.context.skills","Skills"),b("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=kt(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",b("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(Wt(t.path,t.status),Ee("small","bp-dim",b("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,gn(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=kt(b("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=b("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(Ee("p","bp-dim",b("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[[b("thread.context.base","Backplane"),e.sections.base],[b("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[b("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(Ee("h3",void 0,i),gn(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(Wt(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",b("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=Ee("article","bp-context-card");n.append(Wt(t.path,t.state));for(let s of t.servers){let r=s.url||[s.command,...s.args].map((a)=>JSON.stringify(a)).join(" ");if(n.append(Wt(s.name,s.status),gn(r)),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"?b("thread.context.trust","Trust and enable"):i==="disable"?b("thread.context.disable","Disable"):b("thread.context.enable","Enable"),r=kt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");r.disabled=this.busy;let a=Ee("div","bp-context-actions");a.append(r),n.append(a)}this.body.append(n)}}}function Ws(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 Di="http://www.w3.org/2000/svg";function at(e,t=14,n=""){let i=document.createElementNS(Di,"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 r=document.createElementNS(Di,"path");r.setAttribute("d",s),i.appendChild(r)}return i}function Fi(){return at(["M3 6h6l2 2h10v11H3z"],14,"bp-folder-icon")}function $i(e=14,t="bp-folder-icon bp-hw-icon"){return at(["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 _s(e=13){return at(["M6 6h12v12H6z","M9 2v4","M15 2v4","M9 18v4","M15 18v4","M2 9h4","M2 15h4","M18 9h4","M18 15h4"],e)}function zs(e=15){return at(["M4 10V4l4 3h8l4-3v6l-2 9H6z","M9 13h1","M14 13h1","M11 16h2"],e,"bp-cat-glyph")}function qs(e=11){return at(["M4 12l5 5 11-11"],e)}function Ks(e=11){return at(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M12 6v6l4 2"],e)}function Js(e=11){return at(["M12 17v5","M8 4h8l-1 5 3 3v2H6v-2l3-3z"],e,"bp-pin-icon")}function Gi(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 Ys(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 vn(e){if(e==="wait"||e==="error")return"bp-mood-wait";if(e==="work"||e==="talk")return"bp-mood-work";return"bp-mood-idle"}function Qe(e){let t=e.lastIndexOf("|");return t>=0?e.slice(t+1):e}class yn{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 r=document.createElement("button");r.type="button",r.className="icon bp-side-collapse",r.textContent="‹",r.title="Collapse sidebar",r.setAttribute("aria-label","Collapse sidebar"),r.setAttribute("data-testid","sidebar-collapse"),r.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,r);let a=document.createElement("div");a.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=b("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 c=document.createElement("button");c.type="button",c.className="icon bp-side-add",c.textContent="+",c.title=b("thread.new","New thread"),c.setAttribute("aria-label",b("thread.new","New thread")),c.setAttribute("data-testid","sidebar-new-thread"),c.addEventListener("click",()=>{let d=this.firstProjectId();if(d)this.cb.onNewThread(d)}),a.append(this.filterInput,c),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 m=document.createElement("div");m.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"),m.appendChild(this.connEl),this.el.append(n,a,this.homeBanner,this.crewEl,this.listEl,m)}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?b("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):b("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?b("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):b("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 r=new Date(e.awaySince);s=`${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=b("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=b("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=b("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=b("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=b("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((c)=>c.uber),n=this.bots.filter((c)=>!c.uber&&(!e||c.name.toLowerCase().includes(e))),i=this.rooms.filter((c)=>!e||c.name.toLowerCase().includes(e)),s=Boolean(t&&(!e||t.name.toLowerCase().includes(e))),r=n.length>0||Boolean(this.cb.onNewBot)&&!e,a=i.length>0||Boolean(this.cb.onNewRoom)&&!e;if(!s&&!r&&!a){this.crewEl.classList.add("bp-hidden"),this.crewEl.replaceChildren();return}let o=document.createDocumentFragment();if(s&&t){let c=document.createElement("button");c.type="button",c.className="bp-crew-uber"+(t.thread===this.selectedThreadId?" active":""),c.setAttribute("data-testid",`crew-uber-${t.id}`);let m=document.createElement("span");if(m.className=`bp-crew-uber-avatar ${vn(t.mood)}`,t.color)m.style.color=t.color;m.appendChild(zs(14));let d=document.createElement("span");d.className="bp-crew-uber-meta";let p=document.createElement("span");if(p.className="bp-crew-uber-name",p.textContent=t.name,d.appendChild(p),t.note){let l=document.createElement("span");l.className=`bp-crew-uber-note ${vn(t.mood)}`,l.textContent=t.note,d.appendChild(l)}if(c.append(m,d),t.mood==="wait"||t.mood==="error"){let l=document.createElement("span");l.className="bp-status-pill bp-pill-bad",l.textContent="? Input",c.appendChild(l)}c.addEventListener("click",()=>this.cb.onSelectBot(t)),o.appendChild(c)}if(r){let c=document.createElement("div");c.className="bp-crew-bots",c.setAttribute("data-testid","crew-bots");let m=document.createElement("span");m.className="bp-crew-lbl",m.textContent=b("tour.title.bots","Bots").toUpperCase(),c.appendChild(m);let d=document.createElement("div");d.className="bp-crew-bot-tiles";for(let p of n){let l=document.createElement("button");if(l.type="button",l.className=`bp-crew-bot-tile ${vn(p.mood)}`+(p.thread===this.selectedThreadId?" active":""),l.title=p.note?`@${p.name} — ${p.note}`:`@${p.name}`,l.setAttribute("aria-label",`@${p.name}`),l.setAttribute("data-testid",`crew-bot-${p.id}`),p.color)l.style.setProperty("--bot-c",p.color);let h=document.createElement("span");if(h.className="bp-crew-bot-init",h.textContent=Ys(p.name),l.appendChild(h),p.mood==="wait"||p.mood==="error"){let v=document.createElement("span");v.className="bp-crew-bot-wait",l.appendChild(v)}l.addEventListener("click",()=>this.cb.onSelectBot(p)),d.appendChild(l)}if(this.cb.onNewBot&&!e){let p=document.createElement("button");p.type="button",p.className="bp-crew-bot-tile bp-crew-add",p.textContent="+",p.title=b("bots.new","New bot"),p.setAttribute("aria-label",b("bots.new","New bot")),p.setAttribute("data-testid","crew-new-bot"),p.addEventListener("click",()=>this.cb.onNewBot?.()),d.appendChild(p)}c.appendChild(d),o.appendChild(c)}if(a){let c=document.createElement("div");c.className="bp-crew-rooms",c.setAttribute("data-testid","crew-rooms");for(let m of i){let d=document.createElement("button");d.type="button",d.className="bp-crew-room-chip",d.setAttribute("data-testid",`crew-room-${m.id}`);let p=document.createElement("span");p.className="bp-dim",p.textContent="#";let l=document.createElement("span");if(l.textContent=m.name,d.append(p,l),m.members!==void 0&&m.members>0){let h=document.createElement("span");h.className="bp-crew-room-cnt",h.textContent=String(m.members),d.appendChild(h)}d.title=m.members?`#${m.name} (${m.members})`:`#${m.name}`,d.addEventListener("click",()=>this.cb.onSelectRoom?.(m)),c.appendChild(d)}if(this.cb.onNewRoom&&!e){let m=document.createElement("button");m.type="button",m.className="bp-crew-room-chip bp-crew-add",m.textContent="+",m.title=b("rooms.new","New room"),m.setAttribute("aria-label",b("rooms.new","New room")),m.setAttribute("data-testid","crew-new-room"),m.addEventListener("click",()=>this.cb.onNewRoom?.()),c.appendChild(m)}o.appendChild(c)}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=b("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(r)=>{r.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 r=document.createElement("button");r.type="button",r.className="bp-row-act-btn bp-wake-btn",r.textContent=b("menu.wake","Wake"),r.title=b("menu.wake","Wake snoozed thread"),r.setAttribute("data-testid",`wake-row-${e.id}`),r.addEventListener("click",(a)=>{a.stopPropagation(),this.cb.onSnoozeRow?.(e.wake)}),s.appendChild(r)}if(t&&e.snooze){let r=document.createElement("button");r.type="button",r.className="bp-row-act-btn bp-snooze-btn",r.title=b("menu.snooze","Snooze thread"),r.setAttribute("aria-label",b("menu.snooze","Snooze thread")),r.setAttribute("data-testid",`snooze-row-${e.id}`),r.appendChild(Ks(11)),r.addEventListener("click",(a)=>{a.stopPropagation(),this.snoozeMenuRowId=this.snoozeMenuRowId===e.id?"":e.id,this.render()}),s.appendChild(r)}if(i&&e.settle){let r=document.createElement("button");r.type="button",r.className="bp-row-act-btn bp-settle-btn",r.title=b("menu.settle","Settle"),r.setAttribute("aria-label",b("menu.settle","Settle")),r.setAttribute("data-testid",`settle-row-${e.id}`),r.appendChild(qs(11)),r.addEventListener("click",(a)=>{a.stopPropagation(),this.cb.onThreadAct(Qe(e.settle),"settle")}),s.appendChild(r)}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||Qe(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=Ws(e),r=this.renderRowActions(e);if(n){let d=document.createElement("div");d.className="bp-inbox-main";let p=document.createElement("div");p.className="bp-inbox-top";let l=document.createElement("div");if(l.className="bp-thread-title",l.textContent=e.title||"Untitled thread",p.appendChild(l),r)p.appendChild(r);let h=document.createElement("div");if(h.className="bp-inbox-meta",s)h.appendChild(this.renderStatusPill(s,e.say));if(e.project){let v=document.createElement("span");v.className="bp-inbox-proj",v.textContent=e.project,h.appendChild(v)}if(e.ago){let v=document.createElement("span");if(v.className="bp-thread-age",v.textContent=e.ago,e.pinned)v.title=b("tools.pinned","Pinned");h.appendChild(v)}d.append(p,h),i.appendChild(d)}else{if(t){let p=document.createElement("span");p.className="bp-tree-branch",p.setAttribute("aria-hidden","true"),i.appendChild(p)}if(s)i.appendChild(this.renderStatusPill(s,e.say));let d=document.createElement("div");if(d.className="bp-thread-title",d.textContent=e.title||"Untitled thread",i.appendChild(d),r)i.appendChild(r);if(e.ago){let p=document.createElement("span");if(p.className="bp-thread-age",p.textContent=e.ago,e.pinned)p.title=b("tools.pinned","Pinned");i.appendChild(p)}}let a=e.nav||e.id;if(!e.off&&a&&!a.startsWith("@room:"))i.addEventListener("click",()=>this.cb.onSelectThread(Qe(a)));let o=this.snoozeMenuRowId===e.id&&Array.isArray(e.snooze)&&e.snooze.length>0,c=e.kind==="swarm"?ji(e.need):null;if(!c&&!o)return i;let m=document.createElement("div");if(m.className="bp-need-wrap",m.appendChild(i),o&&e.snooze){let d=document.createElement("div");d.className="bp-snooze-bar"+(t?" nested":""),d.setAttribute("data-testid",`snooze-bar-${e.id}`);let p=document.createElement("span");p.className="bp-dim",p.textContent="Snooze:",d.appendChild(p);for(let l of e.snooze){let h=document.createElement("button");h.type="button",h.className="bp-snooze-opt",h.textContent=l.label,h.addEventListener("click",(v)=>{v.stopPropagation(),this.snoozeMenuRowId="",this.cb.onSnoozeRow?.(l.value),this.render()}),d.appendChild(h)}m.appendChild(d)}if(c){let d=document.createElement("div");d.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),d.setAttribute("data-testid",`need-${e.id}`);let p=document.createElement("span");p.className="bp-need-line",p.textContent=c.line,p.title=c.line,d.appendChild(p);for(let h of c.actions){if(!Ut(h,Boolean(this.cb.hasRoomView)))continue;let v=document.createElement("button");v.type="button",v.className="bp-need-btn",v.textContent=h.label,v.setAttribute("data-testid",`need-${h.act}-${e.id}`),v.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,v.addEventListener("click",(u)=>{u.stopPropagation();let g=this.cb.onNeedAct;if(!g)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),g(h).catch((f)=>{this.needErr.set(e.id,f instanceof Error?f.message:String(f))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),d.appendChild(v)}m.appendChild(d);let l=this.needErr.get(e.id);if(l){let h=document.createElement("div");h.className="bp-need-err"+(t?" nested":""),h.textContent=l,m.appendChild(h)}}return m}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let a of n)if(a.kind==="threads")for(let o of a.rows)i.add(o.id),i.add(Qe(o.id));else if(a.kind==="projects")for(let o of a.rows)for(let c of o.threads??[])i.add(c.id),i.add(Qe(c.id));let s=this.selectedThreadId?this.threads.find((a)=>a.id===this.selectedThreadId)??null:null,r=!1;for(let a of n)if(a.kind==="projects"&&(a.rows.length>0||(a.count??0)>0))r=!0;for(let a of n){if(a.kind==="bub")continue;if(a.kind==="threads"){let o=Boolean(a.fold&&a.toggle),c=a.rows.filter((d)=>{if(!t)return!0;return`${d.title} ${d.project??""}`.toLowerCase().includes(t)});if(!o&&c.length===0)continue;if(o&&t&&c.length===0)continue;if(o&&!t&&(a.count??c.length)===0)continue;let m=document.createElement("section");if(m.className=`bp-side-section bp-side-inbox bp-sec-${a.id}`,m.setAttribute("data-section-id",a.id),o){let d=document.createElement("button");d.type="button",d.className="bp-side-section-head bp-side-section-toggle";let p=t?c.length:a.count??c.length,l=a.open||Boolean(t)?"▾":"▸";if(d.textContent=`${l} ${a.title.toUpperCase()} (${p})`,a.hint)d.title=a.hint;d.setAttribute("data-testid",`section-toggle-${a.id}`),d.addEventListener("click",()=>{if(a.toggle)this.cb.onToggleSection?.(a.toggle)}),m.appendChild(d)}else{let d=document.createElement("div");d.className="bp-side-section-head"+(a.id==="needs"?" bp-head-needs":a.id==="running"?" bp-head-running":""),d.textContent=`${a.title.toUpperCase()} ${c.length}`,m.appendChild(d)}if(!o||Boolean(a.open)||Boolean(t))for(let d of c)m.appendChild(this.renderSectionThreadRow(d,!1,!0));e.appendChild(m);continue}if(a.kind==="projects"){let o=a.rows,c=o.filter((l)=>{if(!t)return!0;if((l.title||l.id).toLowerCase().includes(t))return!0;if((l.threads??[]).some((h)=>h.title.toLowerCase().includes(t)))return!0;if((l.swarms??[]).some((h)=>h.title.toLowerCase().includes(t)))return!0;return!1}),m=Boolean(a.fold&&a.toggle);if(t&&c.length===0)continue;if(!m&&a.id!=="active"&&c.length===0)continue;let d=document.createElement("section");if(d.className=`bp-side-section bp-sec-${a.id}`,d.setAttribute("data-section-id",a.id),m){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let h=t?c.length:a.count??c.length,v=a.open||Boolean(t)?"▾":"▸";if(l.textContent=`${v} ${a.title.toUpperCase()} (${h})`,a.hint)l.title=a.hint;l.setAttribute("data-testid",`section-toggle-${a.id}`),l.addEventListener("click",()=>{if(a.toggle)this.cb.onToggleSection?.(a.toggle)}),d.appendChild(l)}else d.appendChild(this.projectsHead(a.title.toUpperCase()));if(!m||Boolean(a.open)||Boolean(t)){if(a.id==="all"&&!t){let l=o.some((v)=>v.hasBoard||v.hasSchematic),h=o.some((v)=>!v.hasBoard&&!v.hasSchematic);if(l&&h){let v=document.createElement("div");v.className="bp-proj-filter",v.setAttribute("data-testid","all-projects-filter");let u=[{id:"all",label:"All"},{id:"hw",label:"Boards"},{id:"sw",label:"Code"}];for(let g of u){let f=document.createElement("button");f.type="button",f.className="bp-proj-filter-btn"+(this.allFilter===g.id?" active":""),f.textContent=g.label,f.addEventListener("click",()=>{this.allFilter=g.id,this.render()}),v.appendChild(f)}if(d.appendChild(v),this.allFilter==="hw")c=c.filter((g)=>g.hasBoard||g.hasSchematic);else if(this.allFilter==="sw")c=c.filter((g)=>!g.hasBoard&&!g.hasSchematic)}}if(a.id==="active"&&!r&&!t){let l=document.createElement("div");l.className="bp-side-empty",l.textContent="No projects yet.",d.appendChild(l)}for(let l of c){let h=document.createElement("div");if(h.className="bp-proj-group"+(l.off||a.id==="quiet"?" bp-dim":""),h.setAttribute("data-project-id",l.id),l.nav||l.key)h.setAttribute("data-project-key",l.nav||l.key||"");let v=document.createElement("div");v.className="bp-proj-head";let u=document.createElement("button");u.type="button",u.className="bp-proj-toggle";let f=Boolean(l.hasBoard||l.hasSchematic)?$i(14):Fi();if(l.css)f.style.color=l.css;let w=document.createElement("span");if(w.className="bp-proj-name",w.textContent=l.title||l.id,u.append(f,w),l.fold==="project-fold"&&l.nav)u.addEventListener("click",()=>this.cb.onToggleProjectFold?.(l.nav));let x=document.createElement("div");if(x.className="bp-proj-meta",(l.needsCount??0)>0){let A=document.createElement("span");A.className="bp-proj-badge-need",A.textContent=String(l.needsCount),A.title=`${l.needsCount} needing you`,x.appendChild(A)}if((l.running??0)>0){let A=document.createElement("span");A.className="bp-proj-badge-run",A.textContent=String(l.running),A.title=`${l.running} running`,x.appendChild(A)}if(l.pinned&&a.id!=="pinned")x.appendChild(Js(11));let S=document.createElement("div");if(S.className="bp-proj-acts",!l.off&&this.cb.onQuickOpenViewer){if(l.hasBoard){let A=document.createElement("button");A.type="button",A.className="bp-proj-quick",A.title=b("viewer.board","Open Board"),A.setAttribute("aria-label",`Open Board (${l.title})`),A.setAttribute("data-testid",`quick-board-${l.id}`),A.appendChild($i(13,"")),A.addEventListener("click",(M)=>{M.stopPropagation(),this.cb.onQuickOpenViewer?.(Qe(l.id),"board")}),S.appendChild(A)}if(l.hasSchematic){let A=document.createElement("button");A.type="button",A.className="bp-proj-quick",A.title=b("viewer.schematic","Open Schematic"),A.setAttribute("aria-label",`Open Schematic (${l.title})`),A.setAttribute("data-testid",`quick-sch-${l.id}`),A.appendChild(_s(13)),A.addEventListener("click",(M)=>{M.stopPropagation(),this.cb.onQuickOpenViewer?.(Qe(l.id),"schematic")}),S.appendChild(A)}}let N=document.createElement("button");if(N.type="button",N.className="icon bp-proj-add",N.title=b("thread.new","New thread"),N.textContent="+",N.setAttribute("data-testid",`new-thread-${l.id}`),l.off)N.disabled=!0;if(N.addEventListener("click",(A)=>{A.stopPropagation(),this.cb.onNewThread(Qe(l.id))}),S.appendChild(N),v.append(u,x,S),h.appendChild(v),!l.folded||Boolean(t)){let A=Boolean(t)&&(l.title||l.id).toLowerCase().includes(t);for(let M of l.swarms??[]){if(t&&!A&&!M.title.toLowerCase().includes(t))continue;h.appendChild(this.renderSectionThreadRow(M,!0))}for(let M of l.threads??[]){if(t&&!A&&!M.title.toLowerCase().includes(t))continue;h.appendChild(this.renderSectionThreadRow(M,!0))}if(s&&s.project===Qe(l.id)&&!i.has(s.id)&&(!t||A||s.title.toLowerCase().includes(t)))h.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:Gi(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}d.appendChild(h)}}e.appendChild(d)}}}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 r=document.createElement("section");r.className="bp-proj-group",r.setAttribute("data-project-id",i.id);let a=document.createElement("div");a.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let c=this.collapsedProjects.has(i.id)&&!e,m=Fi();if(i.css)m.style.color=i.css;let d=document.createElement("span");d.className="bp-proj-name",d.textContent=i.title||i.id,o.append(m,d),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let p=document.createElement("button");if(p.type="button",p.className="icon bp-proj-add",p.title=b("thread.new","New thread"),p.textContent="+",p.setAttribute("data-testid",`new-thread-${i.id}`),p.addEventListener("click",(l)=>{l.stopPropagation(),this.cb.onNewThread(i.id)}),a.append(o,p),r.appendChild(a),!c)for(let l of s)r.appendChild(this.renderSectionThreadRow({id:l.id,title:l.title,status:l.status,state:l.state,ago:Gi(l.updatedAt),pinned:l.pinned,nav:l.id},!0));t.appendChild(r)}}this.listEl.replaceChildren(t)}}function Xs(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function At(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function Qs(e,t){if(t===16000){let r=new Int16Array(e.length);for(let a=0;a0?c/m:0));s[r]=d<0?d*32768:d*32767}return s}class wn{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){At(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(At(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(At(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?Xs(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(At(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 r=this.stopDrain.then(async()=>{if(t&&i){let a=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(a.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=r,await r}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),r=String(e.ins??""),a=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,a-s),c=i.slice(0,o)+r+i.slice(a);this.mark=o+r.length,this.cb.setDraft(c)}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),r=i.createScriptProcessor(4096,1,1);r.onaudioprocess=(a)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=Qs(a.inputBuffer.getChannelData(0),i.sampleRate);for(let c=0;c=3200){let c=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(c.buffer),!1,t)}},s.connect(r),r.connect(i.destination),this.audioCtx=i,this.processor=r}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 r=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!r.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${r.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;At(this.stream),this.stream=null}}var Oi=[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],Vi=[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],Ui=[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],Wi=[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],Zs=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function St(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[c]++,c>i)i=c}}let s=new Int32Array(16),r=0;for(let o=1;o<=15;o++)s[o]=r,r+=n[o];let a=new Int32Array(r);for(let o=0;o0)a[s[c]++]=o}return{counts:n,symbols:a,maxBits:i}}var er=(()=>{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),St(e,288)})(),tr=(()=>{let e=new Uint8Array(32);return e.fill(5),St(e,32)})();class En{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,r=(p)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=p,s-=p,l},a=(p)=>{let l=0,h=0,v=0;for(let u=1;u<=p.maxBits;u++){l|=r(1);let g=p.counts[u];if(l-g{let l=c+p;if(l>t)throw Error("inflated frame exceeds limit");if(l<=o.length)return;let h=o.length;while(h{m(1),o[c++]=p,this.win[this.winPos]=p,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let p=r(1),l=r(2);if(l===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let h=e[n]|e[n+1]<<8,v=e[n+2]|e[n+3]<<8;if(n+=4,(h^65535)!==v)throw Error("invalid stored block length");if(n+h>e.length)throw Error("truncated stored payload");m(h);for(let u=0;u=e.length)break}else if(l===1||l===2){let h=er,v=tr;if(l===2){let u=r(5)+257,g=r(5)+1,f=r(4)+4,w=new Uint8Array(19);for(let M=0;MS)throw Error("code length overflow");for(let V=0;VS)throw Error("code length overflow");A+=T}else if(M===18){let T=r(7)+11;if(A+T>S)throw Error("code length overflow");A+=T}else throw Error("invalid code length symbol")}h=St(N,u),v=St(N.subarray(u),g)}while(!0){let u=a(h);if(u<256)d(u);else if(u===256)break;else{let g=u-257;if(g>=Oi.length)throw Error("invalid length symbol");let f=Oi[g]+(Vi[g]?r(Vi[g]):0),w=a(v);if(w>=Ui.length)throw Error("invalid distance symbol");let x=Ui[w]+(Wi[w]?r(Wi[w]):0);m(f);let S=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 r=this.nextId++,a=window.setTimeout(()=>{this.pending.delete(r),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(r,{resolve:i,reject:s,timer:a}),this.ws.send(JSON.stringify({id:r,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 r;try{r=JSON.parse(s)}catch{return}if(r.t==="hub.restarting")this.restarting={reason:String(r.reason??""),build:String(r.build??""),text:String(r.text??""),at:Date.now()};if(r.t==="hello")this.restarting=null,this.hello=r,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new En:null,this.reconnectDelay=500,this.setState("connected");else if(r.t==="reply"&&typeof r.id==="number"){let a=this.pending.get(r.id);if(a)if(this.pending.delete(r.id),window.clearTimeout(a.timer),r.ok)a.resolve(r.result??{});else{let o=r.error,c=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed",m=typeof r.errorCode==="string"?r.errorCode:void 0,d=typeof r.machine==="string"?r.machine:void 0,p=typeof r.thread==="string"?r.thread:void 0;a.reject(new Lt(c,{code:m,machine:d,thread:p}))}return}for(let a of this.frameListeners)a(r)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let r;try{r=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(r.length>0&&r[0]===123)i(this.textDecoder.decode(r));else{let a=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);for(let o of this.binaryListeners)o(a)}return}for(let r of this.binaryListeners)r(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 nr=new TextDecoder;function _i(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 zi(e){let t=0,n=0;function i(a){if(a<=23)return a;if(a===24){if(t>=e.length)return null;return e[t++]}if(a===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(a===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(a){if(n++,a>32||n>400000||t>=e.length)return null;let o=e[t++],c=o>>5,m=i(o&31);if(m===null)return null;switch(c){case 0:return m;case 1:return-1-m;case 2:{if(t+m>e.length)return null;let d=e.subarray(t,t+m);return t+=m,d}case 3:{if(t+m>e.length)return null;let d=nr.decode(e.subarray(t,t+m));return t+=m,d}case 4:{if(m>e.length)return null;let d=Array(m);for(let p=0;p=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 Ki(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[u]==="number"?e[u]:g,n=t("l",0),i=t("c",0),s=t("a",255)/255,r=t("m",1),a=t("w",0),o=a/2,c=r===0&&a!==0,m=e.d instanceof Uint8Array?e.d:new Uint8Array(0),d=new qi(m),p=[],l=[],h=0,v=0;while(d.more()){let u=d.nextU32(),g=p.length,f=1/0,w=1/0,x=-1/0,S=-1/0;if(r===2)h=h+d.nextI32()|0,v=v+d.nextI32()|0,p.push(h,v),f=x=h,w=S=v;else{let A=Math.min(d.nextU32(),1048576);for(let M=0;Mx)x=h;if(vS)S=v}}let N=(p.length-g)/2;if(N>0){let A=r===2||N===1?2:r===0?0:1,M=r===0?0:o;l.push({info:u,x0:f-M,y0:w-M,x1:x+M,y1:S+M,at:g,n:N,kind:A})}}return{layer:n,color:i,alpha:s,mode:r,r:o,own:c,pts:new Float32Array(p),pieces:l}}function Ji(e,t,n){let i=(a)=>Array.isArray(a)&&a.length>=4?[Number(a[0])||0,Number(a[1])||0,Number(a[2])||0,Number(a[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],r=[];for(let a=0;a=0&&o0){n.delete(o.h),n.set(o.h,c);while(n.size>1024){let m=n.keys().next().value;if(m!==void 0)n.delete(m);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:r}}function Yi(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),r=n.naturalWidth*s,a=n.naturalHeight*s,o=n.left+(n.width-r)/2,c=i?n.top:n.top+(n.height-a)/2,m=(e-o)/r,d=(t-c)/a;if(m<0||m>1||d<0||d>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(m*1000))),y:Math.max(0,Math.min(1000,Math.round(d*1000)))}}var Xi=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function Qi(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class xn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function Zi(e,t,n){let i=!0,s=!1,r=!1,a="",o=!1,c=!1,m=-1,d=null,p=new xn,l=document.createElement("div");l.className="bp-pane bp-browser-pane",l.setAttribute("data-testid","pane-browser");let h=document.createElement("div");h.className="bp-pane-bar bp-browser-nav";function v(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 u=v("←","browser-back","Back"),g=v("→","browser-forward","Forward"),f=v("↻","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 S=v("Go","browser-go","Navigate");S.type="submit",w.append(x,S);let N=v("Take over","browser-takeover");N.classList.add("is-primary"),h.append(u,g,f,w,N);let A=document.createElement("div");A.className="bp-browser-drive-bar",A.hidden=!0;let M=document.createElement("div");M.className="bp-browser-keys-row";let T=document.createElement("input");T.type="text",T.className="bp-browser-input",T.placeholder="Type text or press Enter/Tab/Arrows…",T.autocomplete="off",T.spellcheck=!1,T.setAttribute("data-testid","browser-keys");let R=v("Send","browser-type-send");M.append(T,R);let V=document.createElement("div");V.className="bp-browser-quick-keys";for(let[X,ce]of Xi){let E=v(X,`browser-key-${ce}`);E.addEventListener("click",()=>he("press",{key:ce})),V.append(E)}A.append(M,V);let H=document.createElement("div");H.className="bp-browser-err",H.setAttribute("data-testid","browser-error"),H.hidden=!0;let ae=document.createElement("div");ae.className="bp-browser-stage",ae.setAttribute("data-testid","browser-stage");let ue=document.createElement("img");ue.className="bp-browser-img",ue.alt="Hub browser screen",ue.draggable=!1,ue.hidden=!0,ue.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…",ae.append(ue,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,l.append(h,A,H,ae,we),e.replaceChildren(l);function Se(X){H.textContent=X,H.hidden=!X}function Me(){A.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),ue.classList.toggle("is-driving",s)}function he(X,ce={},E){p.enqueue(async()=>{if(!i)return;Se("");try{if(await t.hub.rpc("browser",{thread:n,op:X,...ce}),!i)return;E?.(),le()}catch(k){if(!i)return;Se(k instanceof Error?k.message:String(k))}})}function be(X){he("toolbar",{command:X},()=>{s=!0,Me()})}u.addEventListener("click",()=>be("back")),g.addEventListener("click",()=>be("forward")),f.addEventListener("click",()=>be("reload")),w.addEventListener("submit",(X)=>{X.preventDefault();let ce=Qi(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(),T.focus()})});function I(){let X=T.value;if(!X)return;T.value="",he("type",{text:X})}R.addEventListener("click",I),T.addEventListener("keydown",(X)=>{if(!s)return;if(X.key==="Enter"){if(X.preventDefault(),T.value)I();he("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"&&T.value==="")X.preventDefault(),he("press",{key:X.key})}),ue.addEventListener("click",(X)=>{if(!s||!r)return;let ce=ue.getBoundingClientRect(),E=Yi(X.clientX,X.clientY,{left:ce.left,top:ce.top,width:ce.width,height:ce.height,naturalWidth:ue.naturalWidth,naturalHeight:ue.naturalHeight});if(!E)return;he("click",E)}),ue.addEventListener("wheel",(X)=>{if(!s||!r)return;X.preventDefault();let ce=Math.round(X.deltaX),E=Math.round(X.deltaY);if(ce===0&&E===0)return;he("scroll",{dx:ce,dy:E})},{passive:!1});async function le(){if(!i)return;if(o){c=!0;return}o=!0;try{do{c=!1,d=new AbortController;let X=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:d.signal});if(!i)return;if(X.ok){let ce=await X.blob();if(!i)return;let E=URL.createObjectURL(ce),k=a;if(a=E,ue.src=E,ue.hidden=!1,oe.hidden=!0,r=!0,k)URL.revokeObjectURL(k)}else if(!r)ue.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&c)}catch{if(!i)return;if(!r)ue.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}finally{d=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===m)return;m=X.n}le()}});return le(),{destroy(){if(i=!1,ne(),d?.abort(),a)URL.revokeObjectURL(a),a=""}}}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 _t(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 ts(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function sr(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function es(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 rr(e){let t=ts(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 ns(e,t,n,i){let s=!0,r="",a="",o=z("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let c=z("div","bp-pane-bar"),m=z("div","bp-files-crumbs"),d=z("button","bp-v-btn","Refresh");d.type="button",d.addEventListener("click",()=>void g(r)),c.append(m,d);let p=z("div","bp-files-split"),l=z("div","bp-files-list");l.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")),p.append(l,h),o.append(c,p),e.replaceChildren(o);function v(){m.replaceChildren();let f=z("button","bp-crumb-btn","project");if(f.type="button",f.addEventListener("click",()=>void g("")),m.append(f),!r)return;let w=r.split("/").filter(Boolean),x="";for(let S of w){x=x?`${x}/${S}`:S;let N=x;m.append(z("span","bp-vh-sep","/"));let A=z("button","bp-crumb-btn",S);A.type="button",A.addEventListener("click",()=>void g(N)),m.append(A)}}async function u(f,w,x){a=f,h.replaceChildren();let S=z("div","bp-files-prev-head");S.append(z("span","bp-files-prev-name",f));let N=z("div","bp-files-prev-acts"),A=rr(w);if(A){let V=z("button","bp-v-btn is-primary",`Open in ${A}`);V.type="button",V.setAttribute("data-testid","files-open-viewer"),V.addEventListener("click",()=>i(A,f)),N.append(V)}let M=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(f)}`,T=z("a","bp-v-btn","Download");T.href=M,T.download=w,N.append(T),S.append(N),h.append(S);let R=ts(w);if(sr(R)){let V=z("div","bp-files-img-wrap"),H=document.createElement("img");H.className="bp-files-img",H.alt=w,H.src=M,V.append(H),h.append(V);return}if(x>524288&&!es(R)){h.append(z("div","bp-pane-empty",`Binary file (${_t(x)}). Use Download to save.`));return}if(es(R)||x<=65536){let V=z("div","bp-pane-empty","Loading…");h.append(V);try{let H=await fetch(M,{credentials:"same-origin"});if(!s||a!==f)return;if(!H.ok){V.textContent=`Could not load file (${H.status})`;return}if((H.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 ue=262144,oe=[],we=0,Se=!1;if(H.body){let ne=H.body.getReader();try{while(!0){let{done:X,value:ce}=await ne.read();if(X||!ce)break;if(we+ce.byteLength>ue){let E=ue-we;if(E>0)oe.push(ce.subarray(0,E)),we+=E;Se=!0,await ne.cancel();break}oe.push(ce),we+=ce.byteLength}}finally{ne.releaseLock()}}if(!s||a!==f)return;let Me=new Uint8Array(we),he=0;for(let ne of oe)Me.set(ne,he),he+=ne.byteLength;let be=!1;for(let ne=0;neS.dir===N.dir?S.name.localeCompare(N.name):S.dir?-1:1),l.replaceChildren(),f){let S=z("button","bp-file-row is-dir");S.type="button",S.append(z("span","bp-file-icon","↰"),z("span","bp-file-name",".."));let N=f.includes("/")?f.slice(0,f.lastIndexOf("/")):"";S.addEventListener("click",()=>void g(N)),l.append(S)}if(x.length===0){l.append(z("div","bp-pane-empty","Empty folder"));return}for(let S of x){let N=f?`${f}/${S.name}`:S.name,A=z("button","bp-file-row"+(S.dir?" is-dir":"")+(N===a?" is-sel":""));A.type="button",A.setAttribute("data-testid",`file-row-${S.name}`),A.append(z("span","bp-file-icon",S.dir?"▸":"·"),z("span","bp-file-name",S.name),z("span","bp-file-size",S.dir?"":_t(S.size))),A.addEventListener("click",()=>{if(S.dir)g(N);else l.querySelectorAll(".bp-file-row.is-sel").forEach((M)=>M.classList.remove("is-sel")),A.classList.add("is-sel"),u(N,S.name,S.size)}),l.append(A)}}catch(w){if(!s)return;l.replaceChildren(z("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return g(""),{destroy(){s=!1}}}function is(e,t,n){let i=!0,s=z("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let r=z("div","bp-pane-bar"),a=z("span","bp-diff-summary","Loading diff…"),o=z("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void m()),r.append(a,o);let c=z("div","bp-diff-body");c.setAttribute("data-testid","diff-body"),s.append(r,c),e.replaceChildren(s);async function m(){a.textContent="Loading diff…",c.replaceChildren();try{let d=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(d?.nogit){a.textContent="Not a git repository",c.append(z("div","bp-pane-empty","This project is not a git repository."));return}let p=typeof d?.diff==="string"?d.diff:"";if(!p.trim()){a.textContent="Clean working tree",c.append(z("div","bp-pane-empty","No uncommitted changes."));return}let l=p.split(` +`),h=0,v=0,u=0,g=document.createDocumentFragment(),f=z("div","bp-diff-file");for(let w of l){if(w.startsWith("diff --git ")){if(f.childNodes.length>0)g.append(f);f=z("div","bp-diff-file"),h++;let x=w.match(/ b\/(.+)$/);f.append(z("div","bp-diff-file-head",x?x[1]:w));continue}if(w.startsWith("index ")||w.startsWith("--- ")||w.startsWith("+++ "))f.append(z("div","bp-diff-line is-meta",w));else if(w.startsWith("@@"))f.append(z("div","bp-diff-line is-hunk",w));else if(w.startsWith("+"))v++,f.append(z("div","bp-diff-line is-add",w));else if(w.startsWith("-"))u++,f.append(z("div","bp-diff-line is-del",w));else f.append(z("div","bp-diff-line",w))}if(f.childNodes.length>0)g.append(f);a.textContent=`${h||1} file${h===1?"":"s"} · +${v} -${u}`,c.append(g)}catch(d){if(!i)return;a.textContent="Diff unavailable",c.append(z("div","bp-pane-empty",d instanceof Error?d.message:String(d)))}}return m(),{destroy(){i=!1}}}function ss(e,t,n){let i=!0,s="checks",r=z("div","bp-pane bp-review-pane");r.setAttribute("data-testid","pane-review");let a=z("div","bp-pane-bar"),o=z("div","bp-review-tabs"),c=z("button","bp-v-btn is-on","Checks"),m=z("button","bp-v-btn","BOM"),d=z("button","bp-v-btn","Comments");c.type=m.type=d.type="button",o.append(c,m,d);let p=z("button","bp-v-btn","Refresh");p.type="button",p.addEventListener("click",()=>void u()),a.append(o,p);let l=z("div","bp-review-body");l.setAttribute("data-testid","review-body"),r.append(a,l),e.replaceChildren(r);function h(g){s=g,c.classList.toggle("is-on",s==="checks"),m.classList.toggle("is-on",s==="bom"),d.classList.toggle("is-on",s==="comments"),u()}c.addEventListener("click",()=>h("checks")),m.addEventListener("click",()=>h("bom")),d.addEventListener("click",()=>h("comments"));function v(g){let f=z("div","bp-review-md"),w=g.split(` +`),x=0;while(x{M.preventDefault();let T=N.value.trim();if(!T)return;A.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:T}).then(()=>{N.value="",A.disabled=!1,u()},()=>{A.disabled=!1})}),l.append(S),x.length===0){l.append(z("div","bp-pane-empty","No review comments yet."));return}for(let M of x){let T=z("div","bp-review-comment"+(M.resolved?" is-resolved":"")),R=[M.by||"review",M.file,M.layer,M.item].filter(Boolean).join(" · ");T.append(z("div","bp-review-comment-meta",R),z("div","bp-review-comment-text",M.text)),l.append(T)}return}let g=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let f=g?.report||{};if(l.replaceChildren(),f.line||f.gate){let w=z("div","bp-review-gate",[f.gate,f.line].filter(Boolean).join(" · "));l.append(w)}if(f.err)l.append(z("div","bp-review-err",f.err));if(Array.isArray(f.tasks)&&f.tasks.length>0){let w=z("div","bp-review-tasks");f.tasks.forEach((x,S)=>{let N=z("label","bp-review-task"),A=document.createElement("input");A.type="checkbox",A.checked=!!(x.done??x.checked);let M=typeof x.index==="number"?x.index:S;A.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:M}).then(()=>void u(),()=>{})}),N.append(A,z("span",void 0,x.text||x.label||`Item ${S+1}`)),w.append(N)}),l.append(w)}if(f.md&&f.md.trim())l.append(v(f.md));else if(!f.err&&(!f.tasks||f.tasks.length===0))l.append(z("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(g){if(!i)return;l.replaceChildren(z("div","bp-pane-empty",g instanceof Error?g.message:String(g)))}}return u(),{destroy(){i=!1}}}function rs(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 kn{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,r=Math.max(i-t,1000),a=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),c=Math.max(o.width,200),m=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(c/r,m/a)*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),r=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==r)this.canvas.width=s,this.canvas.height=r;let a=this.ctx;a.setTransform(i,0,0,i,0,0),a.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",a.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 c=t*0.5,m=n*0.5,d=this.scale,p=this.cx,l=this.cy,h=p-c/d,v=p+c/d,u=l-m/d,g=l+m/d,{off:f,dim:w,lift:x}=this.masks,S=[],N=[];for(let M=0;M>>T&1)===1)continue;if(T===x)N.push(M);else S.push(M)}let A=S.concat(N);a.lineCap="round",a.lineJoin="round";for(let M=0;M>>R.layer&1)===1,H=R.alpha*(V?0.25:1);if(H<=0.01)continue;this.drawChunk(a,R,H,h,u,v,g,p,l,d,c,m)}if(this.highlights.size>0){a.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",a.fillRect(0,0,t,n);let M=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let T=0;Tr||g.y1a)continue;if(g.n<3)continue;let f=(l[g.at]-o)*m+d,w=(l[g.at+1]-c)*m+p;e.moveTo(f,w);for(let x=1;x0)e.fill()}else if(t.mode===2){let v=Math.max(0.75,t.r*m);e.fillStyle=h,e.beginPath();let u=0;for(let g=0;gr||f.y1a)continue;let w=(l[f.at]-o)*m+d,x=(l[f.at+1]-c)*m+p;e.moveTo(w+v,x),e.arc(w,x,v,0,Math.PI*2),u++}if(u>0)e.fill()}else{e.strokeStyle=h,e.lineWidth=Math.max(1,t.r*2*m),e.beginPath();let v=0;for(let u=0;ur||g.y1a)continue;let f=(l[g.at]-o)*m+d,w=(l[g.at+1]-c)*m+p;if(g.n===1)e.moveTo(f,w),e.lineTo(f+0.01,w);else{e.moveTo(f,w);for(let x=1;x0)e.stroke()}}drawLitPieces(e,t,n,i,s,r,a,o,c,m,d,p,l){let h=t.pts,v=rs(t.color,t.alpha);for(let u=0;ua||g.y1o)continue;let f=(h[g.at]-c)*d+p,w=(h[g.at+1]-m)*d+l;if(g.kind===2){let x=Math.max(1.5,t.r*d);e.fillStyle=v,e.beginPath(),e.arc(f,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=v,e.beginPath(),e.moveTo(f,w);for(let x=1;x=0;d--){let p=n.chunks[d];if(p.layer<32&&(m>>>p.layer&1)===1)continue;for(let l=0;lh.x1+a||rh.y1+a)continue;let v=(h.x1-h.x0+1)*(h.y1-h.y0+1);if(v{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,r=(t.y+n.y)*0.5,a=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*a)),c=this.canvas.getBoundingClientRect(),m=this.pinchStart.midX-c.left-c.width*0.5,d=this.pinchStart.midY-c.top-c.height*0.5,p=s-c.left-c.width*0.5,l=r-c.top-c.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+m/this.pinchStart.scale-p/o,this.cy=this.pinchStart.cy+d/this.pinchStart.scale-l/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,r=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/r,this.cy+=i/this.scale-i/r,this.scale=r,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 as=[{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 os(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 An(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` +`),r=(s[0]||"").split("\t");if(r[0]!=="git"||r[2]!==n)return!1;let a=s[1]||r.slice(4).join("\t");if(!a)return!1;let o=a.replace(/\\/g,"/"),c=i.replace(/\\/g,"/");if(c.startsWith("/")||/^[A-Za-z]:\//.test(c))return o===c;return o===c||o.endsWith(`/${c}`)}class Sn{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 ar=`#version 300 es precision highp float; out vec2 vUv; void main() { @@ -18,7 +18,7 @@ void main() { vUv = vec2(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5)); gl_Position = vec4(x, y, 0.0, 1.0); } -`,Xs=`#version 300 es +`,or=`#version 300 es precision highp float; in vec2 vUv; uniform vec3 uBgTop; @@ -35,7 +35,7 @@ void main() { vec3 lin = mix(uBgTop, uBgBot, clamp(vUv.y, 0.0, 1.0)); outColor = vec4(linearToSrgb(clamp(lin, 0.0, 1.0)), 1.0); } -`,Zs=`#version 300 es +`,lr=`#version 300 es precision highp float; layout(location = 0) in vec3 aPos; layout(location = 1) in vec3 aNrm; @@ -53,7 +53,7 @@ void main() { vCol = aCol; gl_Position = uMvp * vec4(aPos, 1.0); } -`,Qs=`#version 300 es +`,cr=`#version 300 es precision highp float; in vec3 vPos; in vec3 vNrm; @@ -149,8 +149,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 qe(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var er=[qe(77),qe(83),qe(94)],tr=[qe(53),qe(58),qe(67)],nr=[qe(245),qe(246),qe(248)],ir=[qe(225),qe(228),qe(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 rs(e,t,n){let i=ss(e,e.VERTEX_SHADER,t),s=ss(e,e.FRAGMENT_SHADER,n),r=e.createProgram();if(!r)throw Error("createProgram failed");if(e.attachShader(r,i),e.attachShader(r,s),e.linkProgram(r),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(r,e.LINK_STATUS)){let a=e.getProgramInfoLog(r)||"program link error";throw e.deleteProgram(r),Error(a)}return r}function sr(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 rr(e,t,n,i){let s=1/Math.tan(e*0.5),r=1/(n-i),a=new Float32Array(16);return a[0]=s/t,a[5]=s,a[10]=(i+n)*r,a[11]=-1,a[14]=2*i*n*r,a}function as(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function os(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 kn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class An{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=rs(n,Ys,Xs),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=rs(n,Zs,Qs),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=Wi(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,r=[n.buffer,i.buffer];if(s)r.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},r)}}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)r++;else a++;let o=r>0?new Float32Array(r*9):null,c=r>0?new Float32Array(r*9):null,u=r>0?new Float32Array(r*12):null,l=a>0?new Float32Array(a*9):null,p=a>0?new Float32Array(a*9):null,d=a>0?new Float32Array(a*12):null,g=0,y=0;for(let f=0;f>>24&255,A=1-C/255,M=(w>>>16&255)/255,P=(w>>>8&255)/255,T=(w&255)/255,B=f*9;if(C===0&&o&&c&&u){let R=g*9;for(let H=0;H<9;H++)o[R+H]=e[B+H],c[R+H]=t[B+H];let O=g*12;for(let H=0;H<3;H++)u[O+H*4]=M,u[O+H*4+1]=P,u[O+H*4+2]=T,u[O+H*4+3]=1;g++}else if(l&&p&&d){let R=y*9;for(let H=0;H<9;H++)l[R+H]=e[B+H],p[R+H]=t[B+H];let O=y*12;for(let H=0;H<3;H++)d[O+H*4]=M,d[O+H*4+1]=P,d[O+H*4+2]=T,d[O+H*4+3]=A;y++}}let m=o&&c&&u?this.createSubBatch(o,c,u,r*3):null,h=l&&p&&d?this.createSubBatch(l,p,d,a*3):null;if(!m&&!h)return null;return{opaque:m,translucent:h,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}=is(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)),r=Math.min(window.devicePixelRatio||1,2),a=Math.round(i*r),o=Math.round(s*r);if(this.canvas.width!==a||this.canvas.height!==o)this.canvas.width=a,this.canvas.height=o;if(t.viewport(0,0,a,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?nr:er,O=this.lightTheme?ir:tr;t.uniform3f(this.uBgTop,R[0],R[1],R[2]),t.uniform3f(this.uBgBot,O[0],O[1],O[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let c=Math.cos(this.pitch),u=Math.sin(this.pitch),l=Math.cos(this.yaw),p=Math.sin(this.yaw),d=[this.target[0]+this.dist*c*p,this.target[1]-this.dist*c*l,this.target[2]+this.dist*u],g=as([this.target[0]-d[0],this.target[1]-d[1],this.target[2]-d[2]]),y=Math.abs(g[2])>0.99?[0,1,0]:[0,0,1],m=as(os(g,y)),h=os(m,g),f=new Float32Array([m[0],h[0],-g[0],0,m[1],h[1],-g[1],0,m[2],h[2],-g[2],0,-kn(m,d),-kn(h,d),kn(g,d),1]),w=Math.max(0.05,this.dist*0.01),C=Math.max(this.dist*10,this.radius*20),A=rr(35*Math.PI/180,a/o,w,C),M=sr(A,f);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,M),t.uniform3f(this.uEye,d[0],d[1],d[2]),t.uniform3f(this.uRight,m[0],m[1],m[2]),t.uniform3f(this.uUp,h[0],h[1],h[2]),t.uniform3f(this.uFwd,g[0],g[1],g[2]);let P=!1,T=[],B=[];for(let R of this.partBatches){let O=e-R.fadeStartMs,H=R.fadeStartMs===0?1:Math.min(1,Math.max(0,O/300));if(H<1){if(P=!0,H>0)B.push({batch:R,fade:H})}else T.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 T)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 T)this.drawSubBatch(R.translucent);for(let{batch:R,fade:O}of B)t.uniform1f(this.uFade,O),this.drawSubBatch(R.opaque),this.drawSubBatch(R.translucent);return t.depthMask(!0),t.bindVertexArray(null),P}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,r]=Array.from(this.pointers.values()),a=Math.hypot(r.x-s.x,r.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/a)));this.pinchDist=a,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,r=Math.cos(this.yaw),a=Math.sin(this.yaw);this.target[0]-=n*r*s,this.target[1]-=n*a*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 ls=64,ar=16777216;function or(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 Lt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function cs(e){switch(e){case"board":return b("viewer.board","Board");case"schematic":return b("viewer.schematic","Schematic");case"3d":return b("viewer.solid","3D");case"gerbers":return b("gpui.gerbers","Gerbers");case"mech":return b("viewer.mech","Mech");case"files":return b("viewer.files","Files");case"diff":return b("viewer.diff","Diff");case"review":return b("viewer.review","Review");case"browser":return b("bots.tab.browser","Browser");case"terminal":return b("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function Ln(e){return e==="board"||e==="schematic"||e==="gerbers"}function lr(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function Sn(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 r=document.createElement("span");r.className="bp-vh-sep",r.textContent="·",r.hidden=!0;let a=document.createElement("span");a.className="bp-vh-file",a.hidden=!0,i.append(s,r,a);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let c=document.createElement("div");c.className="bp-solid-bar",c.setAttribute("data-testid","solid-presets-bar"),c.hidden=!0;let u=document.createElement("div");u.className="bp-v-banner",u.hidden=!0;let l=document.createElement("div");l.className="bp-v-stage-wrap";let p=document.createElement("div");p.className="bp-v-stage";let d=document.createElement("div");d.className="bp-v-overlay",d.hidden=!0;let g=document.createElement("div");g.className="bp-v-layers",g.hidden=!0;let y=document.createElement("div");y.className="bp-v-info",y.hidden=!0,l.append(p,d,g,y);let m=document.createElement("div");m.className="bp-history-bar",m.setAttribute("data-testid","viewer-history-bar"),m.hidden=!0,e.replaceChildren(n,c,u,l,m);let h="",f="",w=0,C=!1,A=new Set,M=[],P=0,T=new Map,B=new Map,R={},O=[],H="",ae="",ue=!1,oe=!1,we=0,Le=!1,Ne=0,he="",be=0,I=null,le=null,ne=null,X=null,ce=null,E=new Cn,k=0,j=!1,N="",K="",te="",D="";document.addEventListener("click",(F)=>{if(!j)return;if(F.target instanceof Node&&m.contains(F.target))return;j=!1,me()}),document.addEventListener("keydown",(F)=>{if(j&&F.key==="Escape")j=!1,me()});function z(){if(k)window.clearInterval(k),k=0;E.playing=!1}function je(){let F=f==="3d"||f==="mech";if(c.hidden=!F,!F)return;if(c.childElementCount>0)return;for(let _ of ns){let V=document.createElement("button");V.type="button",V.className="bp-v-btn",V.textContent=_.label,V.setAttribute("data-testid",`solid-view-${_.id}`),V.addEventListener("click",()=>{ne?.setView(_.id)}),c.append(V)}let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent="Snap view",U.setAttribute("data-testid","solid-snap"),U.addEventListener("click",()=>{if(!ne)return;ne.snapPng().then((_)=>{if(!_)return;let V=URL.createObjectURL(_),G=document.createElement("a");G.href=V;let Z=(He()||f||"view").replace(/[^a-zA-Z0-9._-]/g,"_");G.download=`${Z}-snap.png`,G.click(),setTimeout(()=>URL.revokeObjectURL(V),1000)})}),c.append(U)}async function Se(){if(!h||f!=="board"&&f!=="schematic")return;me();let F=E.compareRequest();if(!F){N="",K="",te="",D="",await $e(!1);return}let U=`${f}|${F.commit}|${F.bits}|${ae}`;if(U===D&&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(),T.clear(),Ye(),C=!0,N="",K=F.commit,te="",D=U;try{let V=ae||(f==="schematic"?R.sch:R.pcb)||"";if(!V){let Ce=await t.hub.rpc("viewer.files",{thread:h});if(_!==w)return;R=Ce||{},re(),V=(f==="schematic"?R.sch:R.pcb)||""}if(!V)throw Error(`Unable to resolve ${f} file path for compare`);let G=await t.hub.rpc("viewer.compare",{thread:h,kind:f,commit:F.commit,bits:F.bits,...ae?{path:ae}:{}});if(_!==w)return;let Z=typeof G?.root==="string"?G.root:"",ee=f==="schematic"?"1":"0";N=Z?`${ee}|${Z}|diff -`:`${ee}|`,K=F.commit,te=V.startsWith("/")||/^[A-Za-z]:[\\/]/.test(V)||!Z?V:`${Z.replace(/\/+$/,"")}/${V.replace(/^\/+/,"")}`,C=!1;let xe=M;Ye();for(let Ce of xe)if(Ce.kind==="bin")Ge(Ce.buf);else We(Ce.key,Ce.none,Ce.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(V){if(_!==w)return;C=!1,N="",K="",te="",D="",Ye(),ke(V instanceof Error?V.message:String(V),!0)}}function me(){let F=f==="board"||f==="schematic";if(m.hidden=!F,!F)return;let U=document.createElement("div");U.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(z(),E.step(1))Se()});let V=document.createElement("button");V.type="button",V.className="bp-v-btn"+(E.playing?" is-on":""),V.textContent=E.playing?"⏸":"▶",V.title=E.playing?"Pause history":"Play history",V.disabled=E.refs.length===0,V.setAttribute("data-testid","history-play"),V.addEventListener("click",()=>{if(E.playing){z(),me();return}if(E.refs.length===0)return;if(E.playing=!0,E.isLive())E.index=E.refs.length-1,Se();else me();k=window.setInterval(()=>{if(!E.playing||f!=="board"&&f!=="schematic"){z(),me();return}if(E.step(-1))Se();else z(),me()},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(z(),E.step(-1))Se()});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(z(),E.goLive())ke("",!1),Se()});let ee=document.createElement("span");ee.className="bp-history-label",ee.setAttribute("data-testid","history-label");let xe=E.activeRef();ee.textContent=xe?xe.label||xe.commit.slice(0,7):E.refs.length>0?`Live (${E.refs.length} saved)`:"Live",U.append(_,V,G,Z,ee);let Ce=document.createElement("div");Ce.className="bp-history-group";let Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(E.highlightEdits?" is-on":""),Pe.textContent="Highlight edits",Pe.disabled=E.refs.length===0,Pe.setAttribute("data-testid","history-highlight"),Pe.addEventListener("click",()=>{z(),E.toggleHighlight(),Se()});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=xe?`Compare: ${xe.label||xe.commit.slice(0,7)} ▾`:"Compare ▾",ye.addEventListener("click",(Te)=>{Te.stopPropagation(),j=!j,me()}),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 Ke=(Ie,mt,Mt)=>{let ze=document.createElement("button");ze.type="button",ze.className="bp-history-menu-item"+(Mt?" is-active":""),ze.setAttribute("role","menuitem"),ze.setAttribute("data-commit",mt),ze.textContent=Ie,ze.addEventListener("click",()=>{if(j=!1,z(),E.selectCommit(mt)){if(E.isLive())ke("",!1);Se()}else me()}),Te.append(ze)};Ke("Live (working tree)","",E.isLive());for(let Ie of E.refs)Ke(Ie.label||Ie.commit.slice(0,7),Ie.commit,xe?.commit===Ie.commit);Re.append(Te)}Ce.append(Pe,Re),m.replaceChildren(U,Ce)}async function Me(F){if(!F)return;try{let U=await t.hub.rpc("viewer.refs",{thread:F});if(F!==h)return;E.setRefs(Array.isArray(U?.refs)?U.refs:[]),me()}catch{if(F!==h)return;E.setRefs([]),me()}}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,U="",_=!1){if(F==="none"){d.hidden=!0,d.replaceChildren();return}d.hidden=!1,d.className=`bp-v-overlay is-${F}`;let V=document.createElement("div");V.className="bp-v-state-card";let G=document.createElement("div");if(G.className="bp-v-state-msg",G.textContent=U,V.append(G),_){let Z=document.createElement("button");Z.type="button",Z.className="bp-v-btn is-primary",Z.textContent=b("tools.retry","Retry"),Z.addEventListener("click",()=>void $e(!0)),V.append(Z)}d.replaceChildren(V)}function ke(F,U){u.textContent=F,u.hidden=!F,u.classList.toggle("is-warn",U)}function He(){if(ae)return Lt(ae);if(f==="board"||f==="3d")return Lt(R.pcb);if(f==="schematic")return Lt(R.sch);if(f==="mech")return Lt(H);return""}function re(){s.textContent=cs(f);let F=He();if(r.hidden=!F,a.hidden=!F,a.textContent=F,o.replaceChildren(),f==="mech"&&O.length>1){let _=document.createElement("select");_.className="bp-v-select",_.setAttribute("aria-label",b("viewer.mech","Mech"));for(let V of O){let G=document.createElement("option");G.value=V,G.textContent=Lt(V),G.selected=V===H,_.append(G)}_.addEventListener("change",()=>{H=_.value,re(),$e(!1)}),o.append(_)}if(Ln(f)){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(Le?" is-on":""),_.textContent=I?.layerHead||"Layers",_.setAttribute("data-testid","viewer-layers-btn"),_.addEventListener("click",()=>{if(Le=!Le,g.hidden=!Le,_.classList.toggle("is-on",Le),Le)_e("","")}),o.append(_)}if(f==="board"||f==="schematic"||f==="3d"||f==="mech"||f==="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((f==="board"||f==="schematic")&&t.hub.hasFeature("follow")){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(ue&&!oe?" is-on":""),_.textContent=ue?oe?b("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",_.setAttribute("data-testid","viewer-follow-btn"),_.addEventListener("click",()=>void tt()),o.append(_)}let U=document.createElement("button");U.type="button",U.className="bp-v-btn bp-v-close",U.textContent="✕",U.title=b("common.close","Close"),U.setAttribute("aria-label",b("common.close","Close")),U.setAttribute("data-testid","viewer-close-btn"),U.addEventListener("click",()=>t.closeViewer()),o.append(U)}function ge(){if(!I){g.replaceChildren();return}let F=document.createDocumentFragment(),U=document.createElement("div");U.className="bp-v-layers-head";let _=document.createElement("span");if(_.textContent=I.layerHead||"Layers",U.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","")),U.append(ee)}if(F.append(U),I.layerModes){let ee=document.createElement("div");ee.className="bp-v-layers-modes",["All","Dim","Only"].forEach((xe,Ce)=>{let Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(I?.layerMode===Ce?" is-on":""),Pe.textContent=xe,Pe.addEventListener("click",()=>void _e("mode",String(Ce))),ee.append(Pe)}),F.append(ee)}let V=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 xe=V.get(ee.layer);if(xe===void 0)continue;let Ce=document.createElement("div");Ce.className="bp-v-layer-row"+(ee.active?" is-focus":"");let Pe=document.createElement("input");Pe.type="checkbox",Pe.checked=ee.on!==!1,Pe.addEventListener("change",()=>void _e("toggle",String(ee.layer)));let Re=document.createElement("span");Re.className="bp-v-layer-swatch";let ye=xe>>>16&255,Te=xe>>>8&255,Ke=xe&255;Re.style.background=ee.on!==!1?`rgb(${ye},${Te},${Ke})`:`rgba(${ye},${Te},${Ke},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))),Ce.append(Pe,Re,Ie),Z.append(Ce)}F.append(Z),g.replaceChildren(F)}async function _e(F,U){if(!Ln(f))return;let _=w;try{let V=await t.hub.rpc("viewer.layers",{kind:f,present:be,off:Ne,focus:he,...F?{action:F,value:U}:{}});if(_!==w||!V)return;Ne=Number(V.own)||0,he=typeof V.focus==="string"?V.focus:"",I=V;let G={off:Number(V.off)||0,dim:Number(V.dim)||0,lift:typeof V.lift==="number"?V.lift:255};if(le?.setLayers(G),re(),Le)ge()}catch{}}async function Ue(){if(!ue||oe||!h||!t.hub.hasFeature("follow"))return;oe=!0,re();try{await t.hub.rpc("viewer.follow",{thread:h,action:"pause"})}catch{}}async function tt(){if(!h||!t.hub.hasFeature("follow"))return;let F=!ue?"on":oe?"resume":"off";try{let U=await t.hub.rpc("viewer.follow",{thread:h,action:F});if(ue=!!U.on,oe=!!U.paused,re(),U.on&&!U.paused&&U.focus&&Array.isArray(U.focus.box)&&U.focus.box.length===4&&(U.seq||0)>we)we=U.seq||we,le?.zoomToBoxMm([U.focus.box[0],U.focus.box[1],U.focus.box[2],U.focus.box[3]])}catch{}}function de(){y.hidden=!0,y.replaceChildren(),le?.setHighlights([])}function dt(F){let U=F.split(";").filter(Boolean),_=U.shift()||F,V=[],G="",Z="";for(let Re of U){if(Re.startsWith("g="))continue;let ye=Re.indexOf("=");if(ye>0){let Te=Re.slice(0,ye),Ke=Re.slice(ye+1);if((Te==="ref"||Te==="symbol")&&!G)G=Ke;if(Te==="net"&&!Z)Z=Ke;V.push([Te,Ke])}else V.push([Re,""])}let ee=document.createElement("div");ee.className="bp-v-info-head";let xe=document.createElement("span");xe.className="bp-v-info-title",xe.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),ee.append(xe,Ce);let Pe=document.createElement("div");Pe.className="bp-v-info-rows";for(let[Re,ye]of V){let Te=document.createElement("span");Te.className="bp-v-info-chip",Te.textContent=ye?`${Re}: ${ye}`:Re,Pe.append(Te)}return y.replaceChildren(ee,...V.length>0?[Pe]:[]),y.hidden=!1,{ref:G||void 0,net:Z||void 0}}async function Je(F){if(!F){de();return}let U=Array.from(A)[0]||"";if(!U)return;let _=w;try{let V=await t.hub.rpc("viewer.info",{key:U,at:F.at,idx:F.idx});if(_!==w)return;let G=typeof V.info==="string"?V.info:"";if(!G){de();return}let{ref:Z,net:ee}=dt(G),xe=[];if(Z)xe.push(["ref",Z]);if(ee)xe.push(["net",ee]);let Ce=[[F.at,F.idx]];for(let[Pe,Re]of xe){let ye=await t.hub.rpc("viewer.probe",{key:U,name:Pe,value:Re});if(_!==w)return;if(Array.isArray(ye.matches))for(let Te of ye.matches)Ce.push(Te)}le?.setHighlights(Ce)}catch{de()}}function pt(){X?.destroy(),X=null,ce?.destroy(),ce=null,le?.destroy(),le=null,ne?.destroy(),ne=null,p.replaceChildren(),Le=!1,g.hidden=!0,y.hidden=!0,y.replaceChildren(),ke("",!1),ie("none")}function Ye(){M=[],P=0}async function $e(F){if(!h||!f)return;let U=++w;if(A.clear(),C=!1,Ye(),pt(),re(),je(),me(),(f==="board"||f==="schematic")&&h)Me(h);if(lr(f)){if(t.hub.rpc("viewer.watch",{thread:h,kind:""}).catch(()=>{}),f==="files")X=Zi(p,t,h,(G,Z)=>{if(f=G,ae=Z,G==="mech")H=Z;$e(!1)});else if(f==="diff")X=Qi(p,t,h);else if(f==="review")X=es(p,t,h);else if(f==="browser")X=Ji(p,t,h);else if(f==="terminal")ie("loading","Loading terminal…"),import("/assets/terminal.js").then((Z)=>{if(U!==w)return;if(ie("none"),Z?.mountTerminalPane)ce=Z.mountTerminalPane(p,t,h,Y());else ie("error","Terminal chunk missing",!0)},(Z)=>{if(U!==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:h});if(U!==w)return;R=G||{},re()}catch{}if(f==="gerbers"&&R.hasGerbers===!1){ie("empty","No Gerbers in this project",!1);return}let _=Y();if(f==="3d"||f==="mech")ne=new An(p,{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(f==="board"||f==="schematic"||f==="gerbers")le=new En(p,{onPick:(G)=>void Je(G),onUserMove:()=>void Ue()}),le.setTheme(_);else{ie("empty",`${cs(f)} is not available in this viewer`,!1);return}let V={thread:h};if(F)V.force=!0;if(f==="mech"){if(O.length===0)try{let G=await t.hub.rpc("mech.list",{thread:h});if(U!==w)return;if(O=Array.isArray(G.parts)?G.parts:[],!H)H=G.primary||O[0]||"";re()}catch(G){if(U!==w)return;ie("error",G instanceof Error?G.message:String(G),!0);return}if(!H){ie("empty",b("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}V.kind="3d",V.path=H}else{if(V.kind=f,ae&&(f==="board"||f==="schematic"))V.path=ae;if(f==="3d"&&!F&&ne){let G=ne.keptToken();if(G)V.kept=G}if((f==="board"||f==="schematic"||f==="gerbers")&&!F&&t.hub.hasFeature("keptChunks"))V.keptChunks=Array.from(B.keys())}C=!0,N="",K="",te="",D="";try{let G=await t.hub.rpc("viewer.watch",V);if(U!==w)return;A=new Set(Array.isArray(G.keys)?G.keys:[]),C=!1;let Z=M;Ye();for(let ee of Z)if(ee.kind==="bin")Ge(ee.buf);else We(ee.key,ee.none,ee.retryable)}catch(G){if(U!==w)return;C=!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,U,_){if(C){if(M.length{if(F.t==="plot"&&typeof F.none==="string"&&typeof F.key==="string")We(F.key,F.none,F.retryable===!0)}),Oe=Bt(()=>{if(f)re()}),Nt=(F)=>{if(F.key==="Escape"&&f&&!y.hidden)de()};return window.addEventListener("keydown",Nt),{open(F,U){if(U!==h){if(h=U,R={},O=[],H="",T.clear(),ue=!1,oe=!1,we=0,Ne=0,he="",be=0,I=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:U}).then((_)=>{if(U!==h)return;if(ue=!!_.on,oe=!!_.paused,we=Number(_.seq)||0,f)re()}).catch(()=>{})}if(F!==f)z(),E.goLive(),Ne=0,he="",be=0,I=null;f=F,ae="",$e(!1)},reconcileHas(F){if(f&&!or(f,F))t.closeViewer()},close(){if(w++,C=!1,z(),j=!1,N="",K="",te="",D="",E.goLive(),c.hidden=!0,m.hidden=!0,Ye(),h)t.hub.rpc("viewer.watch",{thread:h,kind:""}).catch(()=>{});f="",A.clear(),pt()}}}var ds="http://www.w3.org/2000/svg";function St(e){let t=document.createElementNS(ds,"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(ds,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function cr(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 ps(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}function ms(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function dr(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function us(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}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 r=document.createElement("span");r.className="bp-brand-name bp-hide-phone",r.textContent="Backplane";let a=document.createElement("span");a.className="bp-crumb-sep bp-hide-phone",a.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let c=document.createElement("span");c.className="bp-crumb-sep bp-hide-phone",c.textContent="/";let u=document.createElement("span");u.className="bp-crumb-thread",u.setAttribute("data-testid","thread-title");let l=document.createElement("span");l.className="bp-plan-top-badge bp-hidden",l.setAttribute("data-testid","plan-top-badge"),i.append(s,r,a,o,c,u,l);let p=document.createElement("div");p.className="bp-top-state bp-hide-phone bp-hidden";let d=document.createElement("span");d.className="bp-top-state-lbl",d.textContent="STATE";let g=document.createElement("span");g.className="bp-dot bp-dot-idle";let y=document.createElement("span");y.className="bp-top-state-word",p.append(d,g,y);let m=document.createElement("div");m.className="bp-top-acts bp-hide-phone bp-hidden";let h=document.createElement("button");h.type="button",h.className="bp-btn-ghost bp-top-act";let f=document.createElement("span");f.textContent=b("menu.pin","Pin"),h.append(St(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),f);let w=document.createElement("button");w.type="button",w.className="bp-btn-ghost bp-top-act";let C=document.createElement("span");C.textContent=b("menu.settle","Settle"),w.append(St(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),C);let A=document.createElement("div");A.className="bp-menu-wrap";let M=document.createElement("button");M.type="button",M.className="bp-btn-ghost bp-top-act",M.textContent="▾",M.title="Thread menu",M.setAttribute("aria-label","Thread menu"),M.setAttribute("data-testid","thread-menu-btn");let P=document.createElement("div");P.className="bp-popover bp-hidden",P.setAttribute("data-testid","thread-menu"),A.append(M,P),m.append(h,w,A);let T=document.createElement("div");T.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=b("gpui.improvements","Improvements"),B.append(St(["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 O=document.createElement("button");O.type="button",O.className="bp-cmd-box bp-hide-tablet",O.textContent="> Jump or run a command";let H=document.createElement("button");H.type="button",H.className="icon bp-top-icon",H.title="Search",H.setAttribute("aria-label","Search"),H.appendChild(St(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let ae=document.createElement("button");ae.type="button",ae.className="icon bp-top-icon",ae.title=b("palette.settings","Settings"),ae.setAttribute("aria-label",b("palette.settings","Settings")),ae.setAttribute("data-testid","settings-btn"),ae.appendChild(St(["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"])),T.append(B,O,H,ae),t.append(n,i,p,m,T);let ue=document.createElement("div");ue.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 Le=document.createElement("div");Le.className="bp-right-area bp-hidden",Le.setAttribute("data-testid","right-area");let Ne=document.createElement("div");Ne.className="bp-right-top";let he=document.createElement("section");he.className="bp-viewer-pane bp-hidden",he.setAttribute("data-testid","viewer-pane"),Ne.appendChild(he),Le.appendChild(Ne);let be=document.createElement("nav");be.className="bp-rail",be.setAttribute("aria-label","Viewer rail"),be.setAttribute("data-testid","viewer-rail"),ue.append(oe,we,Le,be),e.append(t,ue);let I=new yn,le=null,ne=new Set,X=0,ce=null,E=[],k=[],j=[],N=[],K=[],te=[],D="",z=0,je=0,Se=null,me=null,Me="",Y=null,ve=20,ie={},ke=new Map;function He(v,x){ke.delete(v),ke.set(v,x);while(ke.size>ve){let L=ke.keys().next().value;if(L!==void 0)ke.delete(L);else break}}let re=new gn(oe,{onSelectThread:(v)=>{if(v===D&&Se!==null){oe.classList.remove("bp-sidebar-open");return}Ie(v)},onNewThread:(v)=>{Ut(v)},onSelectBot:(v)=>{Ie(v.thread)},onThreadAct:(v,x)=>{Ze(v,x)},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 x=Gt(v,!1);if(!x)return;if(x.kind==="thread"){Ie(x.id);return}if(x.kind!=="call")return;let L=Ii(await I.rpc(x.method,x.params));if(L?.kind==="thread")Ie(L.id);ye()},hasRoomView:!1,onAddProject:()=>We.open({mode:"folder"})}),ge=new Zt(we,{onLoadOlder:()=>{ze()},onGoToEntry:(v)=>{Mt(v)},onOpenAccounts:()=>{F()},onAnswerAsk:(v,x)=>{I.rpc("ask.answer",{ask:v,answer:x}).catch((L)=>{de.showError(L instanceof Error?L.message:"Could not send answer")})},onToggleReview:(v)=>{if(!D)return;let x=z;I.rpc("thread.review",{thread:D,on:v}).then((L)=>{if(x===z)ge.setReview(L.review??null)}).catch(()=>{})},onUnansweredAction:(v,x)=>{if(!D)return;if(v==="again"||v==="thread-again")I.rpc("thread.again",{thread:D,value:x}).catch(()=>{});else I.rpc("thread.act",{thread:D,action:v,value:x}).catch(()=>{})},onReplyEntry:(v)=>{if(!I.hasFeature("reply")){let x=(v.text||"").split(` -`)[0]?.slice(0,100)??"";if(x)de.prependDraft(`> ${x} -`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;ut({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,x)=>{try{let L={entry:v,path:x};if(I.hasFeature("blobs"))L.metaOnly=!0;let S=await I.rpc("message.image",L);if(S.blob&&S.blob.startsWith("/blob/"))return{url:S.blob};if(S.mime&&S.data)return{mime:S.mime,data:S.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,x){if(!D)return;let L=z,S=D;I.rpc(v,x).then((W)=>{if(L!==z||D!==S)return;if(W.thread){let Q=k.findIndex((fe)=>fe.id===W.thread.id);if(Q>=0)k[Q]=W.thread;else k.unshift(W.thread);re.setData(E,k,j,N),ge.updateThreadMeta(W.thread),G(),de.setState(!0,W.thread.state==="working")}}).catch((W)=>{if(L===z&&D===S)de.showError(W instanceof Error?W.message:"Could not change Plan mode")})}let tt,de=new en(we,{onSend:(v,x)=>{Nn(v,x)},onRunCommand:(v)=>{Mn(v)},onInterrupt:()=>{if(D)I.rpc("turn.interrupt",{thread:D}).catch(()=>{})},onQueryMentions:async(v,x)=>{try{return(await I.rpc("mentions.list",{q:v,kind:x,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{tt.toggle()},onCyclePlanMode:()=>{let v=k.find((L)=>L.id===D)??null,x=_e(v);if(!x||!D)return;if(x.interaction!=="plan")Ue("thread.planonce",{thread:D,on:!0});else if(x.once)Ue("thread.pick",{thread:D,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:D,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!D)return;if(v==="once")Ue("thread.planonce",{thread:D,on:!0});else if(v==="always")Ue("thread.pick",{thread:D,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:D,action:"interaction",value:"default"})}});tt=new fn(I,{getThreadId:()=>D,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 dt(){let v=Me!=="",x=Je.isOpen();Le.classList.toggle("bp-hidden",!v&&!x),Le.classList.toggle("bp-has-viewer",v),Le.classList.toggle("bp-has-mgmt",x)}let Je=new cn(Ne,Le,{hub:I,getThreadId:()=>D,getThreadGen:()=>z,onSendText:(v)=>{Nn(v)},onOpenChange:()=>dt()});function pt(v){let x=window.prompt("Rename thread",v.title||"");if(!x||!x.trim())return;I.rpc("thread.act",{thread:v.id,action:"rename",title:x.trim()}).then((L)=>{if(L.thread)k=k.map((S)=>S.id===L.thread.id?L.thread:S),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(!D&&v.id!=="terminal")break;if(Me===v.id)Z();else ee(v.id);break;case"thread-act":if(D)Ze(D,v.action);break;case"new-thread":Ut(v.projectId);break;case"rename":{let x=k.find((L)=>L.id===D);if(x)pt(x);break}case"prev-thread":case"next-thread":{let x=k.filter((Q)=>!Q.archived&&!Q.swarm);if(x.length<2)break;let L=x.findIndex((Q)=>Q.id===D),S=v.type==="next-thread"?1:-1,W=x[(L<0?0:L+S+x.length)%x.length];if(W)Ie(W.id);break}case"command":if(v.runDirectly)Mn(v.word);else de.setDraft(`${v.word} `),de.focus();break;case"improvements":V();break;case"settings":Oe.open();break;case"sidebar":oe.classList.toggle("bp-sidebar-open"),oe.classList.toggle("bp-sidebar-collapsed");break}}let $e=new dn(e,{getState:()=>({selectedThreadId:D,threads:k,projects:E,bots:j,railItems:K,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 Jt(e,{hub:I,onProjectAdded:(v)=>{if(ye(),v.id)Ut(v.id)},onCloneDone:(v)=>{if(ye(),v.thread)Ie(v.thread)}}),Ge=new mn(be,(v)=>{if(v==="commands"){$e.open();return}if(!D)return;if(Me===v)Z();else ee(v)}),nt=null,Pt=null,Oe=new un(e,{onLoadDevices:async()=>(await I.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,x)=>{await I.rpc("devices.page.act",{action:v,value:x})},onGetHome:()=>nt,onMoveHomeHere:async()=>{await I.rpc("home.move",{to:"back"})},onGetNoProvider:()=>Pt,onLogout:()=>_n(()=>{I.disconnect(),window.location.replace("/")})});function Nt(v){if(Pt=v,ge.setNoProvider(v),Oe.isOpen())Oe.refresh()}function F(){Oe.openToAccounts()}function U(v,x){let L=v instanceof Error?v.message:x,S=v instanceof At?v:null,W=S?.code,Q=S?.machine,fe=W==="no_provider_remote"&&Q?b("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,Ni(L,W)?{label:b("provider.notice.button","Open Settings → Accounts"),onClick:F}:void 0)}h.addEventListener("click",()=>{let v=k.find((x)=>x.id===D);if(v)Ze(v.id,v.pinned?"unpin":"pin")}),w.addEventListener("click",()=>{let v=k.find((x)=>x.id===D);if(v)Ze(v.id,v.settled?"unsettle":"settle")});let _=new bn(e,(v,x)=>x?I.rpc("thread.context.mcp",{thread:v,...x}):I.rpc("thread.context",{thread:v}));M.addEventListener("click",(v)=>{v.stopPropagation();let x=k.find((W)=>W.id===D);if(!x)return;if(!P.classList.contains("bp-hidden")){P.classList.add("bp-hidden");return}let L=[{label:"Rename…",run:()=>pt(x)},{label:x.pinned?b("menu.unpin","Unpin"):b("menu.pin","Pin"),run:()=>{Ze(x.id,x.pinned?"unpin":"pin")}},{label:x.settled?b("phone.unsettle","Unsettle"):b("menu.settle","Settle"),run:()=>{Ze(x.id,x.settled?"unsettle":"settle")}},{label:x.archived?"Unarchive":"Archive",run:()=>{Ze(x.id,x.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Ze(x.id,"delete")}}];if(I.hasFeature("threadContext"))L.unshift({label:b("thread.context.title","Context & Prompt"),run:()=>_.open(x.id)});let S=document.createDocumentFragment();for(let W of L){let Q=document.createElement("button");Q.type="button",Q.className="bp-popover-item"+(W.danger?" danger":""),Q.textContent=W.label,Q.addEventListener("click",()=>{P.classList.add("bp-hidden"),W.run()}),S.appendChild(Q)}P.replaceChildren(S),P.classList.remove("bp-hidden")}),document.addEventListener("click",()=>P.classList.add("bp-hidden"));async function V(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let x=document.createElement("div");x.className="bp-modal";let L=document.createElement("div");L.className="bp-modal-head";let S=document.createElement("h2");S.textContent=b("gpui.improvements","Improvements");let W=document.createElement("button");W.type="button",W.className="icon",W.textContent="×",W.addEventListener("click",()=>v.remove()),L.append(S,W);let Q=document.createElement("div");Q.className="bp-modal-body",Q.textContent="Loading…",x.append(L,Q),v.appendChild(x),v.addEventListener("click",(fe)=>{if(fe.target===v)v.remove()}),e.appendChild(v);try{let fe=await I.rpc("improvements.projects",{}),De=fe.projects??[];if(De.length===0){Q.textContent="No projects available for Improvements.";return}let Qe=document.createDocumentFragment();for(let Ae of De){let se=document.createElement("div");se.className="bp-set-row";let Xe=document.createElement("div");Xe.className="bp-set-info",Xe.textContent=Ae.title||Ae.name||Ae.id;let et=document.createElement("button");et.type="button",et.className=Ae.id===fe.project?"primary":"",et.textContent=Ae.id===fe.project?"Active":"Select",et.addEventListener("click",()=>{I.rpc("improvements.project",{project:Ae.id}).then(()=>v.remove()).catch(()=>{})}),se.append(Xe,et),Qe.appendChild(se)}Q.replaceChildren(Qe)}catch(fe){Q.textContent=fe instanceof Error?fe.message:"Could not load Improvements."}}B.addEventListener("click",()=>{V()}),O.addEventListener("click",()=>$e.open()),H.addEventListener("click",()=>$e.open()),ae.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((S)=>S.id===D)??null,x=v?E.find((S)=>S.id===v.project):void 0;o.textContent=x?.title??"",a.classList.toggle("bp-hidden",!x),c.classList.toggle("bp-hidden",!v),u.textContent=v?v.title||"Untitled thread":"";let L=_e(v);if(de.setPlanMode(L),!L||L.phase==="off")l.classList.add("bp-hidden"),l.classList.remove("is-exec"),l.textContent="";else l.classList.remove("bp-hidden"),l.classList.toggle("is-exec",L.phase==="executing"),l.title=b("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),l.textContent=L.phase==="armed"&&L.once?b("gpui.planmode.top.once","Plan (1 turn)"):L.phase==="armed"?b("gpui.mgmt.plan.tab","Plan"):L.phase==="planning"?b("gpui.planmode.top.planning","Planning"):L.phase==="pending"?b("gpui.planmode.top.pending","Review plan"):b("gpui.planmode.top.executing","Building plan");if(p.classList.toggle("bp-hidden",!v),m.classList.toggle("bp-hidden",!v),v){g.className=`bp-dot ${cr(v)}`,y.textContent=v.status||v.state||"idle",f.textContent=v.pinned?b("menu.unpin","Unpin"):b("menu.pin","Pin"),C.textContent=v.settled?b("phone.unsettle","Unsettle"):b("menu.settle","Settle");let S=v;de.setModelChip(v.chip||v.model||"default",v.provider,S.ctxPct??S.contextPct),de.setMemory(v.memory)}else de.setModelChip("default"),de.setMemory(null)}function Z(v=!0){if(je++,Me="",Ge.setActive(""),he.classList.add("bp-hidden"),Y?.close(),dt(),v&&D&&I.getState()==="connected")I.rpc("viewer.watch",{thread:D,kind:""}).catch(()=>{})}function ee(v){if(je++,Me=v,Ge.setActive(v),he.classList.remove("bp-hidden"),dt(),!Y&&typeof Sn==="function")Y=Sn(he,{hub:I,getThreadId:()=>D,closeViewer:()=>Z(!0)});if(Y)Y.open(v,D);else{let x=document.createElement("div");x.className="bp-viewer-placeholder";let L=document.createElement("div");L.className="bp-viewer-bar";let S=document.createElement("span");S.textContent=v.toUpperCase();let W=document.createElement("button");W.type="button",W.className="icon",W.textContent="×",W.addEventListener("click",()=>Z(!0)),L.append(S,W);let Q=document.createElement("div");Q.className="bp-dim bp-viewer-msg",Q.textContent=`Viewer pane (${v}).`,x.append(L,Q),he.replaceChildren(x)}}async function xe(v,x){if(!v||!I.hasFeature("rail")){if(x===z)K=[],Ge.setItems([]);return}let L=++je;try{let S=await I.rpc("viewer.rail",{thread:v,page:Me});if(x!==z||L!==je)return;let W=Array.isArray(S.rail)?S.rail:Array.isArray(S.items)?S.items:[];if(K=W,Ge.setItems(W),S.has){if(Y?.reconcileHas?.(S.has),Me&&!ps(S.has,Me))Z(!0)}}catch{if(x===z&&L===je)K=[],Ge.setItems([])}}function Ce(v){for(let x of v)if(x.kind==="threads"){for(let L of x.rows)if(!L.off&&(L.nav||L.id)&&!(L.nav||"").startsWith("@room:"))return L.nav||L.id}else if(x.kind==="projects"){for(let L of x.rows)for(let S of L.threads??[])if(!S.off&&(S.nav||S.id)&&!(S.nav||"").startsWith("@room:"))return S.nav||S.id}return""}function Pe(v,x){for(let L of v)if(L.kind==="threads"){if(L.rows.some((S)=>(S.nav||S.id)===x))return!0}else if(L.kind==="projects"){for(let S of L.rows)if((S.threads??[]).some((W)=>(W.nav||W.id)===x))return!0}return!1}function Re(v){let x=[];for(let L of v){if(L.kind!=="projects")continue;for(let S of L.rows)x.push({id:S.id,title:S.title,css:S.css,color:S.color})}if(x.length>0)E=x}async function ye(){if(!I.hasFeature("sections"))return!1;let v=++X;try{let x=await I.rpc("sidebar.sections",{open:Array.from(ne)});if(v!==X)return!0;let L=Array.isArray(x.sections)?x.sections:[];return le=L,Re(L),re.setData(E,k,j,N),re.setSections(L,j,N),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 Ke(){if(Se=null,I.hasFeature("bots"))try{let x=await I.rpc("bots.list",{});j=x.bots??[],N=x.rooms??[]}catch{}if(I.hasFeature("shell")){let x=await I.rpc("shell.sync",{have:ie,settled:25}),L=new Set(x.removed??[]),S=new Set((x.projects??[]).map((W)=>W.id));if(L.size>0||S.size>0)E=[...E.filter((W)=>!L.has(W.id)&&!S.has(W.id)),...x.projects??[]],k=[...k.filter((W)=>!L.has(W.project)&&!S.has(W.project)),...x.threads??[]];else if(Array.isArray(x.threads)&&x.threads.length>0){let W=new Map(k.map((Q)=>[Q.id,Q]));for(let Q of x.threads)W.set(Q.id,Q);k=Array.from(W.values())}if(x.sections!==void 0){let W=Array.isArray(x.sections)?x.sections:Array.isArray(x.sections?.sections)?x.sections.sections:null;if(W)le=W,Re(W)}if(x.h)ie=x.h;re.setData(E,k,j,N),re.setSections(le,j,N)}else if(I.hasFeature("sections")){let[x,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??[],x&&Array.isArray(x.sections)){let S=x.sections;if(!S.some((Q)=>Q.kind==="projects"&&Q.rows.length>0)){let Q=S.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))S=fe.sections}}le=S,Re(S),re.setData(E,k,j,N),re.setSections(S,j,N)}else le=null,E=(await I.rpc("projects.list",{limit:100})).projects??[],re.setSections(null,j,N),re.setData(E,k,j,N);await I.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{le=null;let[x,L]=await Promise.all([I.rpc("projects.list",{limit:100}),I.rpc("threads.list",{limit:200,archived:!1})]);E=x.projects??[],k=L.threads??[],re.setSections(null,j,N),re.setData(E,k,j,N),await I.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=D;if(!v){let x="";try{x=localStorage.getItem("bp.lastThread")||""}catch{}if(x&&(le&&Pe(le,x)||k.some((L)=>L.id===x)))v=x;else if(le)v=Ce(le);if(!v)v=(k.find((S)=>!S.archived&&!S.swarm&&!S.settled)??k.find((S)=>!S.archived&&!S.swarm))?.id??""}if(v&&(le&&Pe(le,v)||k.some((x)=>x.id===v)))await Ie(v);else D="",K=[],Ge.setItems([]),de.setState(!1,!1),G()}async function Ie(v){if(D&&D!==v){tt.cancel();let Ae=ge.getEntries();if(Ae.length>0){let se=ke.get(D);He(D,{entries:Ae,ids:se?.ids??Ae.map((Xe)=>Xe.id),olderCursor:me,review:se?.review??null,unanswered:se?.unanswered??null,rail:se?.rail??K,hashes:se?.hashes??{}})}}let x=++z;je++,ut(null);let L=Se;if(Se=null,L!==null)I.rpc("unsubscribe",{sub:L}).catch(()=>{});D=v;let S=ke.get(v);me=S?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}re.setSelected(v),oe.classList.remove("bp-sidebar-open"),G();let W=k.find((Ae)=>Ae.id===v)??null;if(S)ge.setThread(W,S.entries,Boolean(S.olderCursor),S.review,S.unanswered),K=S.rail,Ge.setItems(S.rail);else ge.setLoading(W),K=[],Ge.setItems([]);if(de.setState(!0,W?.state==="working"),I.hasFeature("open")){let Ae={};if(S){for(let[Be,bt]of Object.entries(S.hashes))Ae[Be]=bt;for(let Be of S.entries)if(Be.h)Ae[Be.id]=Be.h}let se;try{se=await I.rpc("thread.open",{thread:v,limit:40,have:Ae})}catch(Be){if(x===z){let bt=Be instanceof Error&&Be.message?Be.message:"Could not load messages.";ge.setError(W,bt,()=>{Ie(v)})}return}if(x!==z){if(se.sub!==void 0&&se.sub!==null)I.rpc("unsubscribe",{sub:se.sub}).catch(()=>{});return}if(Se=se.sub??null,se.thread){W=se.thread;let Be=k.findIndex((bt)=>bt.id===se.thread.id);if(Be>=0)k[Be]=se.thread;else k.unshift(se.thread);G(),de.setState(!0,W.state==="working")}if("next"in se)me=se.next??null;let Xe=new Map;if(S)for(let Be of S.entries)Xe.set(Be.id,Be);for(let Be of se.entries??[])Xe.set(Be.id,Be);let et=se.ids??S?.ids??(se.entries??[]).map((Be)=>Be.id),Bn=et.map((Be)=>Xe.get(Be)).filter((Be)=>Boolean(Be)),ht=S?.rail??[];if(se.rail!==void 0){if(Array.isArray(se.rail))ht=se.rail;else if(ht=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),Me&&!ps(se.rail.has,Me))Z(!0)}}K=ht,Ge.setItems(ht);let Wt=S?.review??null;if(I.hasFeature("reviewmode"))try{let Be=await I.rpc("thread.review",{thread:v});if(x!==z)return;Wt=Be.review??null}catch{}if(x!==z)return;let In="unanswered"in se?se.unanswered??null:S?.unanswered??null,hs=se.h??S?.hashes??{};if(He(v,{entries:Bn,ids:et,olderCursor:me,review:Wt,unanswered:In,rail:ht,hashes:hs}),ge.setThread(W,Bn,Boolean(me),Wt,In),mt(v,x),Me)ee(Me);return}let Q;try{Q=await I.rpc("thread.entries",{thread:v,limit:40})}catch(Ae){if(x===z){let se=Ae instanceof Error&&Ae.message?Ae.message:"Could not load messages.";ge.setError(W,se,()=>{Ie(v)})}return}if(x!==z)return;if(Q.thread){let Ae=k.findIndex((se)=>se.id===Q.thread.id);if(Ae>=0)k[Ae]=Q.thread;else k.unshift(Q.thread);G()}me=Q.next??null;let fe=null;if(I.hasFeature("reviewmode"))try{let Ae=await I.rpc("thread.review",{thread:v});if(x!==z)return;fe=Ae.review??null}catch{}if(x!==z)return;let De=Q.entries??[],Qe=Q.unanswered??null;He(v,{entries:De,ids:De.map((Ae)=>Ae.id),olderCursor:me,review:fe,unanswered:Qe,rail:S?.rail??[],hashes:S?.hashes??{}}),ge.setThread(W,De,Boolean(me),fe,Qe);try{let se=(await I.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(se!==null){if(x!==z){I.rpc("unsubscribe",{sub:se}).catch(()=>{});return}Se=se}}catch{}if(x!==z)return;if(xe(v,x),mt(v,x),Me)ee(Me)}async function mt(v,x){if(!v||!I.hasFeature("mgmt")){if(x===z)Je.clear();return}let L=k.find((W)=>W.id===v),S=L?.project?E.find((W)=>W.id===L.project)?.root??"":"";if(!S&&I.hasFeature("viewers"))try{let W=await I.rpc("viewer.files",{thread:v});if(x!==z)return;S=W.pcb||W.sch||W.root||""}catch{}if(x!==z)return;if(S)await Je.watchProject(S);else Je.clear()}async function Mt(v){let x=z;for(let L=0;L<25&&x===z;L++){if(ge.goTo(v))return;if(!me)return;let S=me;if(await ze(),me===S)return}}async function ze(){if(!D||!me){ge.clearLoadingOlder();return}let v=z,x=D,L=me;try{let S=await I.rpc("thread.entries",{thread:x,limit:40,before:L});if(v!==z||D!==x)return;me=S.next??null,ge.prependEntries(S.entries??[],Boolean(me))}catch{if(v===z)ge.clearLoadingOlder()}}async function Ut(v){try{let x=await I.rpc("thread.create",{project:v});if(x.thread)k=[x.thread,...k.filter((L)=>L.id!==x.thread.id)],re.setData(E,k,j,N),ye(),await Ie(x.thread.id),de.focus()}catch(x){U(x,"Could not create thread")}}let rt=null;function Pn(v){return(v.split(` -`).map((x)=>x.trim()).find((x)=>x.length>0)??"").slice(0,200)}function ut(v){rt=v,de.setReply(v?{who:v.role==="user"?b("secret.you","You"):b("model.col.agent","Agent"),line:Pn(v.text)}:null,()=>{if(rt)Mt(rt.id)},()=>ut(null))}async function Nn(v,x=[]){if(!D)return;let L=z,S=D,W=dr(),Q=`local-${W}`,fe=rt&&v.trim()&&I.hasFeature("reply")?rt:null;if(fe)ut(null);ge.upsertEntry({id:Q,kind:"user",text:v,at:Date.now(),clientId:W,...fe?{replyTo:{id:fe.id,quote:Pn(fe.text)}}:{},attachments:x.map((De)=>({name:De.name,mime:De.mime,previewUrl:`data:${De.mime};base64,${De.data}`}))});try{let De={thread:S,text:v,clientId:W};if(x.length>0)De.attachments=x;if(fe)De.replyTo={id:fe.id,text:fe.text};let Qe=await I.rpc("message.send",De);if(L!==z||D!==S)return;if(Qe.entry)ge.upsertEntry(Qe.entry)}catch(De){if(L===z&&D===S){if(ge.removeEntry(Q),de.setDraft(v),fe&&!rt)ut(fe);U(De,"Failed to send message")}}}async function Mn(v){if(!D)return;let x=z,L=D;try{let S=await I.rpc("composer.run",{thread:L,text:v});if(x!==z||D!==L)return;if(S.error)de.setDraft(v),U(new At(S.error,{code:S.errorCode,machine:S.machine}),S.error);else if(S.kind==="btw"&&typeof S.a==="string")ge.showBtw(S.q??"",S.a);else if(S.kind==="edit"&&typeof S.text==="string")de.setDraft(S.text);else if(S.kind==="project")We.open({mode:"folder"});else if(S.kind==="clone")We.open({mode:"clone",repo:S.repo??"",text:S.text??""})}catch(S){if(x===z&&D===L)de.setDraft(v),U(S,"Command refused")}}async function Ze(v,x){try{let L=await I.rpc("thread.act",{thread:v,action:x});if(L.thread){if(k=k.map((S)=>S.id===L.thread.id?L.thread:S),re.setData(E,k,j,N),L.thread.id===D)ge.updateThreadMeta(L.thread),G()}ye()}catch(L){de.showError(L instanceof Error?L.message:`Action "${x}" not allowed`)}}function Tn(v,x){if(!v||!v.text||x-v.at>=300000)return"";let L=v.build.split("-").pop()??"";if(v.reason==="build"&&L)return b("hub.restarting.build",v.text,{build:L});if(v.reason==="stop")return b("hub.stopped",v.text);return b("hub.restarting",v.text)}function Tt(v){if(v==="connected")re.setConnStatus(b("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&Tn(I.restarting,Date.now()))re.setConnStatus(Tn(I.restarting,Date.now()),"");else if(v==="reconnecting")re.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")re.setConnStatus(b("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else re.setConnStatus("Connecting…","")}Bt(()=>{Tt(I.getState()),R.textContent=b("gpui.improvements","Improvements"),ae.title=b("palette.settings","Settings"),ae.setAttribute("aria-label",b("palette.settings","Settings")),G(),re.refreshLocale(),ge.refreshLocale(),de.refreshLocale(),Ge.render(),Oe.refreshLocale(),We.refreshLocale()}),I.onState((v,x)=>{if(v==="connected"&&x){if(x.locale)$n(x.locale);if(x.theme)ms(x.theme);if(x.name)re.setHostName(x.name);if(nt=x.home??null,re.setHome(nt),Nt(pn(x.noProvider)),Oe.isOpen())Oe.refresh();Tt(v);let L=typeof x.hubBack==="string"?String(x.hubBack):"";if(L)try{let S=JSON.parse(L);if(S.reason==="crash")re.setConnStatus(b("hub.back.crash",S.text??""),"bp-warn"),window.setTimeout(()=>Tt(I.getState()),6000)}catch{}if(de.setFeatures(I.hasFeature("images"),I.hasFeature("voice")),Array.isArray(x.commands))te=x.commands,de.setCommands(te);else te=[];Ke(),We.reconcile()}else tt.cancel(),Tt(v)}),I.onFrame((v)=>{if(v.t==="voice"){tt.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"))Nt(pn(L["provider.notice"]));Je.handleInfo(L);return}if(v.t!=="d")return;let x=v;if(x.k==="clone"||x.k==="clone.repos"||x.k==="clone.signin"){We.handleFrame(x);return}switch(x.k){case"project":{let L=x.project;if(!L)break;let S=E.findIndex((W)=>W.id===L.id);if(S>=0)E[S]=L;else E.unshift(L);re.setData(E,k,j,N),G(),Te();break}case"thread":{let L=x.thread;if(!L)break;let S=k.findIndex((W)=>W.id===L.id);if(S>=0)k[S]=L;else k.unshift(L);if(re.setData(E,k,j,N),L.id===D)ge.updateThreadMeta(L),G(),de.setState(!0,L.state==="working");Te();break}case"thread.removed":{let L=String(x.id??"");k=k.filter((S)=>S.id!==L),re.setData(E,k,j,N),Te();break}case"entry":{if(x.thread===D&&x.entry)ge.upsertEntry(x.entry);break}case"text":{if(x.thread===D)ge.appendLiveText(String(x.entry??""),String(x.append??""),Number(x.at??Date.now()));break}case"turn":{if(x.thread===D){let L=String(x.state??"idle");de.setState(!0,L==="working"),xe(D,z)}Te();break}case"btw":{if(x.thread===D)ge.showBtw(String(x.q??""),String(x.a??""));break}case"unanswered":{if(x.thread===D)ge.setUnanswered(x.unanswered??null);break}case"theme":{if(typeof x.theme==="string")ms(x.theme);break}case"home":{if(nt=x.home??null,re.setHome(nt),Oe.isOpen())Oe.refresh();break}default:break}}),window.addEventListener("keydown",(v)=>{let x=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(x==="k"||v.shiftKey&&x==="p"))if(v.preventDefault(),$e.isOpen())$e.close();else $e.open();else if(v.key==="Escape"){if($e.isOpen())$e.close();else if(We.isOpen())We.escape();else if(Oe.isOpen())Oe.close();else if(ge.closePlanRevise());else if(Je.isOpen())Je.closePanel()}}),I.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",us);else us(); +`;function ze(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var dr=[ze(77),ze(83),ze(94)],pr=[ze(53),ze(58),ze(67)],mr=[ze(245),ze(246),ze(248)],ur=[ze(225),ze(228),ze(233)];function ls(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 cs(e,t,n){let i=ls(e,e.VERTEX_SHADER,t),s=ls(e,e.FRAGMENT_SHADER,n),r=e.createProgram();if(!r)throw Error("createProgram failed");if(e.attachShader(r,i),e.attachShader(r,s),e.linkProgram(r),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(r,e.LINK_STATUS)){let a=e.getProgramInfoLog(r)||"program link error";throw e.deleteProgram(r),Error(a)}return r}function hr(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 br(e,t,n,i){let s=1/Math.tan(e*0.5),r=1/(n-i),a=new Float32Array(16);return a[0]=s/t,a[5]=s,a[10]=(i+n)*r,a[11]=-1,a[14]=2*i*n*r,a}function ds(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 Ln(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class Pn{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=cs(n,ar,or),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=cs(n,lr,cr),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=Ki(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,r=[n.buffer,i.buffer];if(s)r.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},r)}}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)r++;else a++;let o=r>0?new Float32Array(r*9):null,c=r>0?new Float32Array(r*9):null,m=r>0?new Float32Array(r*12):null,d=a>0?new Float32Array(a*9):null,p=a>0?new Float32Array(a*9):null,l=a>0?new Float32Array(a*12):null,h=0,v=0;for(let f=0;f>>24&255,S=1-x/255,N=(w>>>16&255)/255,A=(w>>>8&255)/255,M=(w&255)/255,T=f*9;if(x===0&&o&&c&&m){let R=h*9;for(let H=0;H<9;H++)o[R+H]=e[T+H],c[R+H]=t[T+H];let V=h*12;for(let H=0;H<3;H++)m[V+H*4]=N,m[V+H*4+1]=A,m[V+H*4+2]=M,m[V+H*4+3]=1;h++}else if(d&&p&&l){let R=v*9;for(let H=0;H<9;H++)d[R+H]=e[T+H],p[R+H]=t[T+H];let V=v*12;for(let H=0;H<3;H++)l[V+H*4]=N,l[V+H*4+1]=A,l[V+H*4+2]=M,l[V+H*4+3]=S;v++}}let u=o&&c&&m?this.createSubBatch(o,c,m,r*3):null,g=d&&p&&l?this.createSubBatch(d,p,l,a*3):null;if(!u&&!g)return null;return{opaque:u,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}=os(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)),r=Math.min(window.devicePixelRatio||1,2),a=Math.round(i*r),o=Math.round(s*r);if(this.canvas.width!==a||this.canvas.height!==o)this.canvas.width=a,this.canvas.height=o;if(t.viewport(0,0,a,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?mr:dr,V=this.lightTheme?ur:pr;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 c=Math.cos(this.pitch),m=Math.sin(this.pitch),d=Math.cos(this.yaw),p=Math.sin(this.yaw),l=[this.target[0]+this.dist*c*p,this.target[1]-this.dist*c*d,this.target[2]+this.dist*m],h=ds([this.target[0]-l[0],this.target[1]-l[1],this.target[2]-l[2]]),v=Math.abs(h[2])>0.99?[0,1,0]:[0,0,1],u=ds(ps(h,v)),g=ps(u,h),f=new Float32Array([u[0],g[0],-h[0],0,u[1],g[1],-h[1],0,u[2],g[2],-h[2],0,-Ln(u,l),-Ln(g,l),Ln(h,l),1]),w=Math.max(0.05,this.dist*0.01),x=Math.max(this.dist*10,this.radius*20),S=br(35*Math.PI/180,a/o,w,x),N=hr(S,f);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,N),t.uniform3f(this.uEye,l[0],l[1],l[2]),t.uniform3f(this.uRight,u[0],u[1],u[2]),t.uniform3f(this.uUp,g[0],g[1],g[2]),t.uniform3f(this.uFwd,h[0],h[1],h[2]);let A=!1,M=[],T=[];for(let R of this.partBatches){let V=e-R.fadeStartMs,H=R.fadeStartMs===0?1:Math.min(1,Math.max(0,V/300));if(H<1){if(A=!0,H>0)T.push({batch:R,fade:H})}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 T)t.uniform1f(this.uFade,V),this.drawSubBatch(R.opaque),this.drawSubBatch(R.translucent);return t.depthMask(!0),t.bindVertexArray(null),A}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,r]=Array.from(this.pointers.values()),a=Math.hypot(r.x-s.x,r.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/a)));this.pinchDist=a,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,r=Math.cos(this.yaw),a=Math.sin(this.yaw);this.target[0]-=n*r*s,this.target[1]-=n*a*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 ms=64,gr=16777216;function fr(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 Pt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function us(e){switch(e){case"board":return b("viewer.board","Board");case"schematic":return b("viewer.schematic","Schematic");case"3d":return b("viewer.solid","3D");case"gerbers":return b("gpui.gerbers","Gerbers");case"mech":return b("viewer.mech","Mech");case"files":return b("viewer.files","Files");case"diff":return b("viewer.diff","Diff");case"review":return b("viewer.review","Review");case"browser":return b("bots.tab.browser","Browser");case"terminal":return b("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function Nn(e){return e==="board"||e==="schematic"||e==="gerbers"}function vr(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function Mn(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 r=document.createElement("span");r.className="bp-vh-sep",r.textContent="·",r.hidden=!0;let a=document.createElement("span");a.className="bp-vh-file",a.hidden=!0,i.append(s,r,a);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let c=document.createElement("div");c.className="bp-solid-bar",c.setAttribute("data-testid","solid-presets-bar"),c.hidden=!0;let m=document.createElement("div");m.className="bp-v-banner",m.hidden=!0;let d=document.createElement("div");d.className="bp-v-stage-wrap";let p=document.createElement("div");p.className="bp-v-stage";let l=document.createElement("div");l.className="bp-v-overlay",l.hidden=!0;let h=document.createElement("div");h.className="bp-v-layers",h.hidden=!0;let v=document.createElement("div");v.className="bp-v-info",v.hidden=!0,d.append(p,l,h,v);let u=document.createElement("div");u.className="bp-history-bar",u.setAttribute("data-testid","viewer-history-bar"),u.hidden=!0,e.replaceChildren(n,c,m,d,u);let g="",f="",w=0,x=!1,S=new Set,N=[],A=0,M=new Map,T=new Map,R={},V=[],H="",ae="",ue=!1,oe=!1,we=0,Se=!1,Me=0,he="",be=0,I=null,le=null,ne=null,X=null,ce=null,E=new Sn,k=0,j=!1,B="",q="",te="",D="";document.addEventListener("click",(F)=>{if(!j)return;if(F.target instanceof Node&&u.contains(F.target))return;j=!1,me()}),document.addEventListener("keydown",(F)=>{if(j&&F.key==="Escape")j=!1,me()});function K(){if(k)window.clearInterval(k),k=0;E.playing=!1}function je(){let F=f==="3d"||f==="mech";if(c.hidden=!F,!F)return;if(c.childElementCount>0)return;for(let _ of as){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)}),c.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 Q=(He()||f||"view").replace(/[^a-zA-Z0-9._-]/g,"_");G.download=`${Q}-snap.png`,G.click(),setTimeout(()=>URL.revokeObjectURL(U),1000)})}),c.append(W)}async function Le(){if(!g||f!=="board"&&f!=="schematic")return;me();let F=E.compareRequest();if(!F){B="",q="",te="",D="",await Ge(!1);return}let W=`${f}|${F.commit}|${F.bits}|${ae}`;if(W===D&&S.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;S.clear(),M.clear(),Ye(),x=!0,B="",q=F.commit,te="",D=W;try{let U=ae||(f==="schematic"?R.sch:R.pcb)||"";if(!U){let xe=await t.hub.rpc("viewer.files",{thread:g});if(_!==w)return;R=xe||{},re(),U=(f==="schematic"?R.sch:R.pcb)||""}if(!U)throw Error(`Unable to resolve ${f} file path for compare`);let G=await t.hub.rpc("viewer.compare",{thread:g,kind:f,commit:F.commit,bits:F.bits,...ae?{path:ae}:{}});if(_!==w)return;let Q=typeof G?.root==="string"?G.root:"",ee=f==="schematic"?"1":"0";B=Q?`${ee}|${Q}|diff +`:`${ee}|`,q=F.commit,te=U.startsWith("/")||/^[A-Za-z]:[\\/]/.test(U)||!Q?U:`${Q.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,B="",q="",te="",D="",Ye(),ke(U instanceof Error?U.message:String(U),!0)}}function me(){let F=f==="board"||f==="schematic";if(u.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(),me();return}if(E.refs.length===0)return;if(E.playing=!0,E.isLive())E.index=E.refs.length-1,Le();else me();k=window.setInterval(()=>{if(!E.playing||f!=="board"&&f!=="schematic"){K(),me();return}if(E.step(-1))Le();else K(),me()},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 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,Q,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",(Be)=>{Be.stopPropagation(),j=!j,me()}),Re.append(ye),j&&E.refs.length>0){let Be=document.createElement("div");Be.className="bp-history-menu",Be.setAttribute("role","menu"),Be.setAttribute("data-testid","history-compare-menu");let qe=(Ie,ht,Tt)=>{let Ke=document.createElement("button");Ke.type="button",Ke.className="bp-history-menu-item"+(Tt?" is-active":""),Ke.setAttribute("role","menuitem"),Ke.setAttribute("data-commit",ht),Ke.textContent=Ie,Ke.addEventListener("click",()=>{if(j=!1,K(),E.selectCommit(ht)){if(E.isLive())ke("",!1);Le()}else me()}),Be.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(Be)}xe.append(Ne,Re),u.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:[]),me()}catch{if(F!==g)return;E.setRefs([]),me()}}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"){l.hidden=!0,l.replaceChildren();return}l.hidden=!1,l.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 Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn is-primary",Q.textContent=b("tools.retry","Retry"),Q.addEventListener("click",()=>void Ge(!0)),U.append(Q)}l.replaceChildren(U)}function ke(F,W){m.textContent=F,m.hidden=!F,m.classList.toggle("is-warn",W)}function He(){if(ae)return Pt(ae);if(f==="board"||f==="3d")return Pt(R.pcb);if(f==="schematic")return Pt(R.sch);if(f==="mech")return Pt(H);return""}function re(){s.textContent=us(f);let F=He();if(r.hidden=!F,a.hidden=!F,a.textContent=F,o.replaceChildren(),f==="mech"&&V.length>1){let _=document.createElement("select");_.className="bp-v-select",_.setAttribute("aria-label",b("viewer.mech","Mech"));for(let U of V){let G=document.createElement("option");G.value=U,G.textContent=Pt(U),G.selected=U===H,_.append(G)}_.addEventListener("change",()=>{H=_.value,re(),Ge(!1)}),o.append(_)}if(Nn(f)){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(Se?" is-on":""),_.textContent=I?.layerHead||"Layers",_.setAttribute("data-testid","viewer-layers-btn"),_.addEventListener("click",()=>{if(Se=!Se,h.hidden=!Se,_.classList.toggle("is-on",Se),Se)_e("","")}),o.append(_)}if(f==="board"||f==="schematic"||f==="3d"||f==="mech"||f==="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((f==="board"||f==="schematic")&&t.hub.hasFeature("follow")){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(ue&&!oe?" is-on":""),_.textContent=ue?oe?b("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=b("common.close","Close"),W.setAttribute("aria-label",b("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||[]),Q=document.createElement("div");Q.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,Be=Ce>>>8&255,qe=Ce&255;Re.style.background=ee.on!==!1?`rgb(${ye},${Be},${qe})`:`rgba(${ye},${Be},${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),Q.append(xe)}F.append(Q),h.replaceChildren(F)}async function _e(F,W){if(!Nn(f))return;let _=w;try{let U=await t.hub.rpc("viewer.layers",{kind:f,present:be,off:Me,focus:he,...F?{action:F,value:W}:{}});if(_!==w||!U)return;Me=Number(U.own)||0,he=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),re(),Se)ge()}catch{}}async function Ue(){if(!ue||oe||!g||!t.hub.hasFeature("follow"))return;oe=!0,re();try{await t.hub.rpc("viewer.follow",{thread:g,action:"pause"})}catch{}}async function nt(){if(!g||!t.hub.hasFeature("follow"))return;let F=!ue?"on":oe?"resume":"off";try{let W=await t.hub.rpc("viewer.follow",{thread:g,action:F});if(ue=!!W.on,oe=!!W.paused,re(),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(){v.hidden=!0,v.replaceChildren(),le?.setHighlights([])}function mt(F){let W=F.split(";").filter(Boolean),_=W.shift()||F,U=[],G="",Q="";for(let Re of W){if(Re.startsWith("g="))continue;let ye=Re.indexOf("=");if(ye>0){let Be=Re.slice(0,ye),qe=Re.slice(ye+1);if((Be==="ref"||Be==="symbol")&&!G)G=qe;if(Be==="net"&&!Q)Q=qe;U.push([Be,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 Be=document.createElement("span");Be.className="bp-v-info-chip",Be.textContent=ye?`${Re}: ${ye}`:Re,Ne.append(Be)}return v.replaceChildren(ee,...U.length>0?[Ne]:[]),v.hidden=!1,{ref:G||void 0,net:Q||void 0}}async function Je(F){if(!F){de();return}let W=Array.from(S)[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:Q,net:ee}=mt(G),Ce=[];if(Q)Ce.push(["ref",Q]);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 Be of ye.matches)xe.push(Be)}le?.setHighlights(xe)}catch{de()}}function ut(){X?.destroy(),X=null,ce?.destroy(),ce=null,le?.destroy(),le=null,ne?.destroy(),ne=null,p.replaceChildren(),Se=!1,h.hidden=!0,v.hidden=!0,v.replaceChildren(),ke("",!1),ie("none")}function Ye(){N=[],A=0}async function Ge(F){if(!g||!f)return;let W=++w;if(S.clear(),x=!1,Ye(),ut(),re(),je(),me(),(f==="board"||f==="schematic")&&g)Pe(g);if(vr(f)){if(t.hub.rpc("viewer.watch",{thread:g,kind:""}).catch(()=>{}),f==="files")X=ns(p,t,g,(G,Q)=>{if(f=G,ae=Q,G==="mech")H=Q;Ge(!1)});else if(f==="diff")X=is(p,t,g);else if(f==="review")X=ss(p,t,g);else if(f==="browser")X=Zi(p,t,g);else if(f==="terminal")ie("loading","Loading terminal…"),import("/assets/terminal.js").then((Q)=>{if(W!==w)return;if(ie("none"),Q?.mountTerminalPane)ce=Q.mountTerminalPane(p,t,g,Y());else ie("error","Terminal chunk missing",!0)},(Q)=>{if(W!==w)return;ie("error",Q instanceof Error?Q.message:String(Q),!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||{},re()}catch{}if(f==="gerbers"&&R.hasGerbers===!1){ie("empty","No Gerbers in this project",!1);return}let _=Y();if(f==="3d"||f==="mech")ne=new Pn(p,{onStatus:(G,Q)=>{if(Q)ie("none"),ke(G,!1);else if(G)ie("loading",G);else ie("none"),ke("",!1)},onUserMove:()=>void Ue()}),ne.setTheme(_);else if(f==="board"||f==="schematic"||f==="gerbers")le=new kn(p,{onPick:(G)=>void Je(G),onUserMove:()=>void Ue()}),le.setTheme(_);else{ie("empty",`${us(f)} is not available in this viewer`,!1);return}let U={thread:g};if(F)U.force=!0;if(f==="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:[],!H)H=G.primary||V[0]||"";re()}catch(G){if(W!==w)return;ie("error",G instanceof Error?G.message:String(G),!0);return}if(!H){ie("empty",b("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}U.kind="3d",U.path=H}else{if(U.kind=f,ae&&(f==="board"||f==="schematic"))U.path=ae;if(f==="3d"&&!F&&ne){let G=ne.keptToken();if(G)U.kept=G}if((f==="board"||f==="schematic"||f==="gerbers")&&!F&&t.hub.hasFeature("keptChunks"))U.keptChunks=Array.from(T.keys())}x=!0,B="",q="",te="",D="";try{let G=await t.hub.rpc("viewer.watch",U);if(W!==w)return;S=new Set(Array.isArray(G.keys)?G.keys:[]),x=!1;let Q=N;Ye();for(let ee of Q)if(ee.kind==="bin")$e(ee.buf);else We(ee.key,ee.none,ee.retryable)}catch(G){if(W!==w)return;x=!1,S.clear(),Ye();let Q=G instanceof Error?G.message:String(G),ee=/no gerbers|not in this project|another machine/i.test(Q);ie(ee?"empty":"error",Q,!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=jt(()=>{if(f)re()}),Bt=(F)=>{if(F.key==="Escape"&&f&&!v.hidden)de()};return window.addEventListener("keydown",Bt),{open(F,W){if(W!==g){if(g=W,R={},V=[],H="",M.clear(),ue=!1,oe=!1,we=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(ue=!!_.on,oe=!!_.paused,we=Number(_.seq)||0,f)re()}).catch(()=>{})}if(F!==f)K(),E.goLive(),Me=0,he="",be=0,I=null;f=F,ae="",Ge(!1)},reconcileHas(F){if(f&&!fr(f,F))t.closeViewer()},close(){if(w++,x=!1,K(),j=!1,B="",q="",te="",D="",E.goLive(),c.hidden=!0,u.hidden=!0,Ye(),g)t.hub.rpc("viewer.watch",{thread:g,kind:""}).catch(()=>{});f="",S.clear(),ut()}}}var hs="http://www.w3.org/2000/svg";function Nt(e){let t=document.createElementNS(hs,"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(hs,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function yr(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}function gs(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function wr(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function fs(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}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 r=document.createElement("span");r.className="bp-brand-name bp-hide-phone",r.textContent="Backplane";let a=document.createElement("span");a.className="bp-crumb-sep bp-hide-phone",a.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let c=document.createElement("span");c.className="bp-crumb-sep bp-hide-phone",c.textContent="/";let m=document.createElement("span");m.className="bp-crumb-thread",m.setAttribute("data-testid","thread-title");let d=document.createElement("span");d.className="bp-plan-top-badge bp-hidden",d.setAttribute("data-testid","plan-top-badge"),i.append(s,r,a,o,c,m,d);let p=document.createElement("div");p.className="bp-top-state bp-hide-phone bp-hidden";let l=document.createElement("span");l.className="bp-top-state-lbl",l.textContent="STATE";let h=document.createElement("span");h.className="bp-dot bp-dot-idle";let v=document.createElement("span");v.className="bp-top-state-word",p.append(l,h,v);let u=document.createElement("div");u.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 f=document.createElement("span");f.textContent=b("menu.pin","Pin"),g.append(Nt(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),f);let w=document.createElement("button");w.type="button",w.className="bp-btn-ghost bp-top-act";let x=document.createElement("span");x.textContent=b("menu.settle","Settle"),w.append(Nt(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),x);let S=document.createElement("div");S.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 A=document.createElement("div");A.className="bp-popover bp-hidden",A.setAttribute("data-testid","thread-menu"),S.append(N,A),u.append(g,w,S);let M=document.createElement("div");M.className="bp-top-right";let T=document.createElement("button");T.type="button",T.className="bp-btn-ghost bp-top-act bp-hide-tablet",T.setAttribute("data-testid","improvements-btn");let R=document.createElement("span");R.textContent=b("gpui.improvements","Improvements"),T.append(Nt(["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 H=document.createElement("button");H.type="button",H.className="icon bp-top-icon",H.title="Search",H.setAttribute("aria-label","Search"),H.appendChild(Nt(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let ae=document.createElement("button");ae.type="button",ae.className="icon bp-top-icon",ae.title=b("palette.settings","Settings"),ae.setAttribute("aria-label",b("palette.settings","Settings")),ae.setAttribute("data-testid","settings-btn"),ae.appendChild(Nt(["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(T,V,H,ae),t.append(n,i,p,u,M);let ue=document.createElement("div");ue.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 Se=document.createElement("div");Se.className="bp-right-area bp-hidden",Se.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),Se.appendChild(Me);let be=document.createElement("nav");be.className="bp-rail",be.setAttribute("aria-label","Viewer rail"),be.setAttribute("data-testid","viewer-rail"),ue.append(oe,we,Se,be),e.append(t,ue);let I=new Cn,le=null,ne=new Set,X=0,ce=null,E=[],k=[],j=[],B=[],q=[],te=[],D="",K=0,je=0,Le=null,me=null,Pe="",Y=null,ve=20,ie={},ke=new Map;function He(y,C){ke.delete(y),ke.set(y,C);while(ke.size>ve){let L=ke.keys().next().value;if(L!==void 0)ke.delete(L);else break}}let re=new yn(oe,{onSelectThread:(y)=>{if(y===D&&Le!==null){oe.classList.remove("bp-sidebar-open");return}Ie(y)},onNewThread:(y)=>{It(y)},onSelectBot:(y)=>{Ie(y.thread)},onQuickOpenViewer:(y,C)=>{let L=k.find((O)=>O.project===y&&!O.archived&&!O.swarm);(async()=>{if(L)await Ie(L.id);else await It(y);if(D)Pe=C,$e.setActive(C),Y?.open(C,D)})()},onThreadAct:(y,C)=>{Ze(y,C)},onSnoozeRow:(y)=>{I.rpc("sidebar.act",{action:"row-snooze",value:y}).then(()=>ye()).catch(()=>{})},onToggleSection:(y)=>{if(ne.has(y))ne.delete(y);else ne.add(y);ye()},onToggleProjectFold:(y)=>{I.rpc("sidebar.act",{action:"project-fold",value:y}).then(()=>ye()).catch(()=>{})},onCollapseSidebar:()=>{oe.classList.remove("bp-sidebar-open"),oe.classList.add("bp-sidebar-collapsed")},onNeedAct:async(y)=>{let C=Ut(y,!1);if(!C)return;if(C.kind==="thread"){Ie(C.id);return}if(C.kind!=="call")return;let L=Hi(await I.rpc(C.method,C.params));if(L?.kind==="thread")Ie(L.id);ye()},hasRoomView:!1,onAddProject:()=>We.open({mode:"folder"})}),ge=new en(we,{onLoadOlder:()=>{Ke()},onGoToEntry:(y)=>{Tt(y)},onOpenAccounts:()=>{F()},onAnswerAsk:(y,C)=>{I.rpc("ask.answer",{ask:y,answer:C}).catch((L)=>{de.showError(L instanceof Error?L.message:"Could not send answer")})},onToggleReview:(y)=>{if(!D)return;let C=K;I.rpc("thread.review",{thread:D,on:y}).then((L)=>{if(C===K)ge.setReview(L.review??null)}).catch(()=>{})},onUnansweredAction:(y,C)=>{if(!D)return;if(y==="again"||y==="thread-again")I.rpc("thread.again",{thread:D,value:C}).catch(()=>{});else I.rpc("thread.act",{thread:D,action:y,value:C}).catch(()=>{})},onReplyEntry:(y)=>{if(!I.hasFeature("reply")){let C=(y.text||"").split(` +`)[0]?.slice(0,100)??"";if(C)de.prependDraft(`> ${C} +`);return}if(!y.text||!y.text.trim()||y.live||y.id.startsWith("local-"))return;bt({id:y.id,text:y.text,role:y.kind==="user"?"user":"assistant"})},onLoadImage:async(y,C)=>{try{let L={entry:y,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(y){if(!y)return null;if(y.planMode)return y.planMode;if(y.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function Ue(y,C){if(!D)return;let L=K,P=D;I.rpc(y,C).then((O)=>{if(L!==K||D!==P)return;if(O.thread){let Z=k.findIndex((fe)=>fe.id===O.thread.id);if(Z>=0)k[Z]=O.thread;else k.unshift(O.thread);re.setData(E,k,j,B),ge.updateThreadMeta(O.thread),G(),de.setState(!0,O.thread.state==="working")}}).catch((O)=>{if(L===K&&D===P)de.showError(O instanceof Error?O.message:"Could not change Plan mode")})}let nt,de=new nn(we,{onSend:(y,C)=>{Tn(y,C)},onRunCommand:(y)=>{In(y)},onInterrupt:()=>{if(D)I.rpc("turn.interrupt",{thread:D}).catch(()=>{})},onQueryMentions:async(y,C)=>{try{return(await I.rpc("mentions.list",{q:y,kind:C,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{nt.toggle()},onCyclePlanMode:()=>{let y=k.find((L)=>L.id===D)??null,C=_e(y);if(!C||!D)return;if(C.interaction!=="plan")Ue("thread.planonce",{thread:D,on:!0});else if(C.once)Ue("thread.pick",{thread:D,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:D,action:"interaction",value:"default"})},onSetPlanMode:(y)=>{if(!D)return;if(y==="once")Ue("thread.planonce",{thread:D,on:!0});else if(y==="always")Ue("thread.pick",{thread:D,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:D,action:"interaction",value:"default"})}});nt=new wn(I,{getThreadId:()=>D,getDraft:()=>de.getDraft(),getCaret:()=>de.getCaret(),setDraft:(y)=>de.setDraft(y),setRecording:(y)=>de.setVoiceRecording(y),setLevel:(y)=>de.setVoiceLevel(y),showError:(y)=>de.showError(y)});function mt(){let y=Pe!=="",C=Je.isOpen();Se.classList.toggle("bp-hidden",!y&&!C),Se.classList.toggle("bp-has-viewer",y),Se.classList.toggle("bp-has-mgmt",C)}let Je=new pn(Me,Se,{hub:I,getThreadId:()=>D,getThreadGen:()=>K,onSendText:(y)=>{Tn(y)},onOpenChange:()=>mt()});function ut(y){let C=window.prompt("Rename thread",y.title||"");if(!C||!C.trim())return;I.rpc("thread.act",{thread:y.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(y){switch(y.type){case"thread":Ie(y.id);break;case"rail":if(!D&&y.id!=="terminal")break;if(Pe===y.id)Q();else ee(y.id);break;case"thread-act":if(D)Ze(D,y.action);break;case"new-thread":It(y.projectId);break;case"rename":{let C=k.find((L)=>L.id===D);if(C)ut(C);break}case"prev-thread":case"next-thread":{let C=k.filter((Z)=>!Z.archived&&!Z.swarm);if(C.length<2)break;let L=C.findIndex((Z)=>Z.id===D),P=y.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(y.runDirectly)In(y.word);else de.setDraft(`${y.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 mn(e,{getState:()=>({selectedThreadId:D,threads:k,projects:E,bots:j,railItems:q,commands:te}),onSearch:async(y)=>{if(!I.hasFeature("search"))return{threads:[],projects:[],messages:[]};return I.rpc("search",{q:y,limit:20})},onExecute:Ye}),We=new Xt(e,{hub:I,onProjectAdded:(y)=>{if(ye(),y.id)It(y.id)},onCloneDone:(y)=>{if(ye(),y.thread)Ie(y.thread)}}),$e=new hn(be,(y)=>{if(y==="commands"){Ge.open();return}if(!D)return;if(Pe===y)Q();else ee(y)}),it=null,Mt=null,Oe=new bn(e,{onLoadDevices:async()=>(await I.rpc("devices.page",{})).rows??[],onDevicesAct:async(y,C)=>{await I.rpc("devices.page.act",{action:y,value:C})},onGetHome:()=>it,onMoveHomeHere:async()=>{await I.rpc("home.move",{to:"back"})},onGetNoProvider:()=>Mt,onLogout:()=>Kn(()=>{I.disconnect(),window.location.replace("/")})});function Bt(y){if(Mt=y,ge.setNoProvider(y),Oe.isOpen())Oe.refresh()}function F(){Oe.openToAccounts()}function W(y,C){let L=y instanceof Error?y.message:C,P=y instanceof Lt?y:null,O=P?.code,Z=P?.machine,fe=O==="no_provider_remote"&&Z?b("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}",Z):L;de.showError(fe,Ti(L,O)?{label:b("provider.notice.button","Open Settings → Accounts"),onClick:F}:void 0)}g.addEventListener("click",()=>{let y=k.find((C)=>C.id===D);if(y)Ze(y.id,y.pinned?"unpin":"pin")}),w.addEventListener("click",()=>{let y=k.find((C)=>C.id===D);if(y)Ze(y.id,y.settled?"unsettle":"settle")});let _=new fn(e,(y,C)=>C?I.rpc("thread.context.mcp",{thread:y,...C}):I.rpc("thread.context",{thread:y}));N.addEventListener("click",(y)=>{y.stopPropagation();let C=k.find((O)=>O.id===D);if(!C)return;if(!A.classList.contains("bp-hidden")){A.classList.add("bp-hidden");return}let L=[{label:"Rename…",run:()=>ut(C)},{label:C.pinned?b("menu.unpin","Unpin"):b("menu.pin","Pin"),run:()=>{Ze(C.id,C.pinned?"unpin":"pin")}},{label:C.settled?b("phone.unsettle","Unsettle"):b("menu.settle","Settle"),run:()=>{Ze(C.id,C.settled?"unsettle":"settle")}},{label:C.archived?"Unarchive":"Archive",run:()=>{Ze(C.id,C.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Ze(C.id,"delete")}}];if(I.hasFeature("threadContext"))L.unshift({label:b("thread.context.title","Context & Prompt"),run:()=>_.open(C.id)});let P=document.createDocumentFragment();for(let O of L){let Z=document.createElement("button");Z.type="button",Z.className="bp-popover-item"+(O.danger?" danger":""),Z.textContent=O.label,Z.addEventListener("click",()=>{A.classList.add("bp-hidden"),O.run()}),P.appendChild(Z)}A.replaceChildren(P),A.classList.remove("bp-hidden")}),document.addEventListener("click",()=>A.classList.add("bp-hidden"));async function U(){let y=document.createElement("div");y.className="bp-modal-backdrop",y.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=b("gpui.improvements","Improvements");let O=document.createElement("button");O.type="button",O.className="icon",O.textContent="×",O.addEventListener("click",()=>y.remove()),L.append(P,O);let Z=document.createElement("div");Z.className="bp-modal-body",Z.textContent="Loading…",C.append(L,Z),y.appendChild(C),y.addEventListener("click",(fe)=>{if(fe.target===y)y.remove()}),e.appendChild(y);try{let fe=await I.rpc("improvements.projects",{}),De=fe.projects??[];if(De.length===0){Z.textContent="No projects available for Improvements.";return}let et=document.createDocumentFragment();for(let Ae of De){let se=document.createElement("div");se.className="bp-set-row";let Xe=document.createElement("div");Xe.className="bp-set-info",Xe.textContent=Ae.title||Ae.name||Ae.id;let tt=document.createElement("button");tt.type="button",tt.className=Ae.id===fe.project?"primary":"",tt.textContent=Ae.id===fe.project?"Active":"Select",tt.addEventListener("click",()=>{I.rpc("improvements.project",{project:Ae.id}).then(()=>y.remove()).catch(()=>{})}),se.append(Xe,tt),et.appendChild(se)}Z.replaceChildren(et)}catch(fe){Z.textContent=fe instanceof Error?fe.message:"Could not load Improvements."}}T.addEventListener("click",()=>{U()}),V.addEventListener("click",()=>Ge.open()),H.addEventListener("click",()=>Ge.open()),ae.addEventListener("click",()=>{Oe.open()}),n.addEventListener("click",()=>{oe.classList.toggle("bp-sidebar-open"),oe.classList.toggle("bp-sidebar-collapsed")});function G(){let y=k.find((P)=>P.id===D)??null,C=y?E.find((P)=>P.id===y.project):void 0;o.textContent=C?.title??"",a.classList.toggle("bp-hidden",!C),c.classList.toggle("bp-hidden",!y),m.textContent=y?y.title||"Untitled thread":"";let L=_e(y);if(de.setPlanMode(L),!L||L.phase==="off")d.classList.add("bp-hidden"),d.classList.remove("is-exec"),d.textContent="";else d.classList.remove("bp-hidden"),d.classList.toggle("is-exec",L.phase==="executing"),d.title=b("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),d.textContent=L.phase==="armed"&&L.once?b("gpui.planmode.top.once","Plan (1 turn)"):L.phase==="armed"?b("gpui.mgmt.plan.tab","Plan"):L.phase==="planning"?b("gpui.planmode.top.planning","Planning"):L.phase==="pending"?b("gpui.planmode.top.pending","Review plan"):b("gpui.planmode.top.executing","Building plan");if(p.classList.toggle("bp-hidden",!y),u.classList.toggle("bp-hidden",!y),y){h.className=`bp-dot ${yr(y)}`,v.textContent=y.status||y.state||"idle",f.textContent=y.pinned?b("menu.unpin","Unpin"):b("menu.pin","Pin"),x.textContent=y.settled?b("phone.unsettle","Unsettle"):b("menu.settle","Settle");let P=y;de.setModelChip(y.chip||y.model||"default",y.provider,P.ctxPct??P.contextPct),de.setMemory(y.memory)}else de.setModelChip("default"),de.setMemory(null)}function Q(y=!0){if(je++,Pe="",$e.setActive(""),he.classList.add("bp-hidden"),Y?.close(),mt(),y&&D&&I.getState()==="connected")I.rpc("viewer.watch",{thread:D,kind:""}).catch(()=>{})}function ee(y){if(je++,Pe=y,$e.setActive(y),he.classList.remove("bp-hidden"),mt(),!Y&&typeof Mn==="function")Y=Mn(he,{hub:I,getThreadId:()=>D,closeViewer:()=>Q(!0)});if(Y)Y.open(y,D);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=y.toUpperCase();let O=document.createElement("button");O.type="button",O.className="icon",O.textContent="×",O.addEventListener("click",()=>Q(!0)),L.append(P,O);let Z=document.createElement("div");Z.className="bp-dim bp-viewer-msg",Z.textContent=`Viewer pane (${y}).`,C.append(L,Z),he.replaceChildren(C)}}async function Ce(y,C){if(!y||!I.hasFeature("rail")){if(C===K)q=[],$e.setItems([]);return}let L=++je;try{let P=await I.rpc("viewer.rail",{thread:y,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))Q(!0)}}catch{if(C===K&&L===je)q=[],$e.setItems([])}}function xe(y){for(let C of y)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(y,C){for(let L of y)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(y){let C=[];for(let L of y){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 y=++X;try{let C=await I.rpc("sidebar.sections",{open:Array.from(ne)});if(y!==X)return!0;let L=Array.isArray(C.sections)?C.sections:[];return le=L,Re(L),re.setData(E,k,j,B),re.setSections(L,j,B),G(),!0}catch{return!1}}function Be(){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??[],B=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((Z)=>[Z.id,Z]));for(let Z of C.threads)O.set(Z.id,Z);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;re.setData(E,k,j,B),re.setSections(le,j,B)}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((Z)=>Z.kind==="projects"&&Z.rows.length>0)){let Z=P.find((fe)=>fe.kind==="projects"&&fe.fold&&fe.toggle&&(fe.count??0)>0);if(Z?.toggle&&!ne.has(Z.toggle)){ne.add(Z.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),re.setData(E,k,j,B),re.setSections(P,j,B)}else le=null,E=(await I.rpc("projects.list",{limit:100})).projects??[],re.setSections(null,j,B),re.setData(E,k,j,B);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??[],re.setSections(null,j,B),re.setData(E,k,j,B),await I.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let y=D;if(!y){let C="";try{C=localStorage.getItem("bp.lastThread")||""}catch{}if(C&&(le&&Ne(le,C)||k.some((L)=>L.id===C)))y=C;else if(le)y=xe(le);if(!y)y=(k.find((P)=>!P.archived&&!P.swarm&&!P.settled)??k.find((P)=>!P.archived&&!P.swarm))?.id??""}if(y&&(le&&Ne(le,y)||k.some((C)=>C.id===y)))await Ie(y);else D="",q=[],$e.setItems([]),de.setState(!1,!1),G()}async function Ie(y){if(D&&D!==y){nt.cancel();let Ae=ge.getEntries();if(Ae.length>0){let se=ke.get(D);He(D,{entries:Ae,ids:se?.ids??Ae.map((Xe)=>Xe.id),olderCursor:me,review:se?.review??null,unanswered:se?.unanswered??null,rail:se?.rail??q,hashes:se?.hashes??{}})}}let C=++K;je++,bt(null);let L=Le;if(Le=null,L!==null)I.rpc("unsubscribe",{sub:L}).catch(()=>{});D=y;let P=ke.get(y);me=P?.olderCursor??null;try{localStorage.setItem("bp.lastThread",y)}catch{}re.setSelected(y),oe.classList.remove("bp-sidebar-open"),G();let O=k.find((Ae)=>Ae.id===y)??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 Ae={};if(P){for(let[Te,ft]of Object.entries(P.hashes))Ae[Te]=ft;for(let Te of P.entries)if(Te.h)Ae[Te.id]=Te.h}let se;try{se=await I.rpc("thread.open",{thread:y,limit:40,have:Ae})}catch(Te){if(C===K){let ft=Te instanceof Error&&Te.message?Te.message:"Could not load messages.";ge.setError(O,ft,()=>{Ie(y)})}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 Te=k.findIndex((ft)=>ft.id===se.thread.id);if(Te>=0)k[Te]=se.thread;else k.unshift(se.thread);G(),de.setState(!0,O.state==="working")}if("next"in se)me=se.next??null;let Xe=new Map;if(P)for(let Te of P.entries)Xe.set(Te.id,Te);for(let Te of se.entries??[])Xe.set(Te.id,Te);let tt=se.ids??P?.ids??(se.entries??[]).map((Te)=>Te.id),jn=tt.map((Te)=>Xe.get(Te)).filter((Te)=>Boolean(Te)),gt=P?.rail??[];if(se.rail!==void 0){if(Array.isArray(se.rail))gt=se.rail;else if(gt=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=gt,$e.setItems(gt);let zt=P?.review??null;if(I.hasFeature("reviewmode"))try{let Te=await I.rpc("thread.review",{thread:y});if(C!==K)return;zt=Te.review??null}catch{}if(C!==K)return;let Hn="unanswered"in se?se.unanswered??null:P?.unanswered??null,vs=se.h??P?.hashes??{};if(He(y,{entries:jn,ids:tt,olderCursor:me,review:zt,unanswered:Hn,rail:gt,hashes:vs}),ge.setThread(O,jn,Boolean(me),zt,Hn),ht(y,C),Pe)ee(Pe);return}let Z;try{Z=await I.rpc("thread.entries",{thread:y,limit:40})}catch(Ae){if(C===K){let se=Ae instanceof Error&&Ae.message?Ae.message:"Could not load messages.";ge.setError(O,se,()=>{Ie(y)})}return}if(C!==K)return;if(Z.thread){let Ae=k.findIndex((se)=>se.id===Z.thread.id);if(Ae>=0)k[Ae]=Z.thread;else k.unshift(Z.thread);G()}me=Z.next??null;let fe=null;if(I.hasFeature("reviewmode"))try{let Ae=await I.rpc("thread.review",{thread:y});if(C!==K)return;fe=Ae.review??null}catch{}if(C!==K)return;let De=Z.entries??[],et=Z.unanswered??null;He(y,{entries:De,ids:De.map((Ae)=>Ae.id),olderCursor:me,review:fe,unanswered:et,rail:P?.rail??[],hashes:P?.hashes??{}}),ge.setThread(O,De,Boolean(me),fe,et);try{let se=(await I.rpc("subscribe",{topic:"thread",thread:y})).sub??null;if(se!==null){if(C!==K){I.rpc("unsubscribe",{sub:se}).catch(()=>{});return}Le=se}}catch{}if(C!==K)return;if(Ce(y,C),ht(y,C),Pe)ee(Pe)}async function ht(y,C){if(!y||!I.hasFeature("mgmt")){if(C===K)Je.clear();return}let L=k.find((O)=>O.id===y),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:y});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 Tt(y){let C=K;for(let L=0;L<25&&C===K;L++){if(ge.goTo(y))return;if(!me)return;let P=me;if(await Ke(),me===P)return}}async function Ke(){if(!D||!me){ge.clearLoadingOlder();return}let y=K,C=D,L=me;try{let P=await I.rpc("thread.entries",{thread:C,limit:40,before:L});if(y!==K||D!==C)return;me=P.next??null,ge.prependEntries(P.entries??[],Boolean(me))}catch{if(y===K)ge.clearLoadingOlder()}}async function It(y){try{let C=await I.rpc("thread.create",{project:y});if(C.thread)k=[C.thread,...k.filter((L)=>L.id!==C.thread.id)],re.setData(E,k,j,B),ye(),await Ie(C.thread.id),de.focus()}catch(C){W(C,"Could not create thread")}}let ot=null;function Bn(y){return(y.split(` +`).map((C)=>C.trim()).find((C)=>C.length>0)??"").slice(0,200)}function bt(y){ot=y,de.setReply(y?{who:y.role==="user"?b("secret.you","You"):b("model.col.agent","Agent"),line:Bn(y.text)}:null,()=>{if(ot)Tt(ot.id)},()=>bt(null))}async function Tn(y,C=[]){if(!D)return;let L=K,P=D,O=wr(),Z=`local-${O}`,fe=ot&&y.trim()&&I.hasFeature("reply")?ot:null;if(fe)bt(null);ge.upsertEntry({id:Z,kind:"user",text:y,at:Date.now(),clientId:O,...fe?{replyTo:{id:fe.id,quote:Bn(fe.text)}}:{},attachments:C.map((De)=>({name:De.name,mime:De.mime,previewUrl:`data:${De.mime};base64,${De.data}`}))});try{let De={thread:P,text:y,clientId:O};if(C.length>0)De.attachments=C;if(fe)De.replyTo={id:fe.id,text:fe.text};let et=await I.rpc("message.send",De);if(L!==K||D!==P)return;if(et.entry)ge.upsertEntry(et.entry)}catch(De){if(L===K&&D===P){if(ge.removeEntry(Z),de.setDraft(y),fe&&!ot)bt(fe);W(De,"Failed to send message")}}}async function In(y){if(!D)return;let C=K,L=D;try{let P=await I.rpc("composer.run",{thread:L,text:y});if(C!==K||D!==L)return;if(P.error)de.setDraft(y),W(new Lt(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&&D===L)de.setDraft(y),W(P,"Command refused")}}async function Ze(y,C){try{let L=await I.rpc("thread.act",{thread:y,action:C});if(L.thread){if(k=k.map((P)=>P.id===L.thread.id?L.thread:P),re.setData(E,k,j,B),L.thread.id===D)ge.updateThreadMeta(L.thread),G()}ye()}catch(L){de.showError(L instanceof Error?L.message:`Action "${C}" not allowed`)}}function Rn(y,C){if(!y||!y.text||C-y.at>=300000)return"";let L=y.build.split("-").pop()??"";if(y.reason==="build"&&L)return b("hub.restarting.build",y.text,{build:L});if(y.reason==="stop")return b("hub.stopped",y.text);return b("hub.restarting",y.text)}function Rt(y){if(y==="connected")re.setConnStatus(b("gpui.acct.connected","Connected"),"bp-ok");else if(y==="reconnecting"&&Rn(I.restarting,Date.now()))re.setConnStatus(Rn(I.restarting,Date.now()),"");else if(y==="reconnecting")re.setConnStatus("Reconnecting…","bp-warn");else if(y==="revoked")re.setConnStatus(b("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else re.setConnStatus("Connecting…","")}jt(()=>{Rt(I.getState()),R.textContent=b("gpui.improvements","Improvements"),ae.title=b("palette.settings","Settings"),ae.setAttribute("aria-label",b("palette.settings","Settings")),G(),re.refreshLocale(),ge.refreshLocale(),de.refreshLocale(),$e.render(),Oe.refreshLocale(),We.refreshLocale()}),I.onState((y,C)=>{if(y==="connected"&&C){if(C.locale)Vn(C.locale);if(C.theme)gs(C.theme);if(C.name)re.setHostName(C.name);if(it=C.home??null,re.setHome(it),Bt(un(C.noProvider)),Oe.isOpen())Oe.refresh();Rt(y);let L=typeof C.hubBack==="string"?String(C.hubBack):"";if(L)try{let P=JSON.parse(L);if(P.reason==="crash")re.setConnStatus(b("hub.back.crash",P.text??""),"bp-warn"),window.setTimeout(()=>Rt(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(),Rt(y)}),I.onFrame((y)=>{if(y.t==="voice"){nt.handleFrame(y);return}if(y.t==="info"&&y.info&&typeof y.info==="object"){let L=y.info;if(Object.prototype.hasOwnProperty.call(L,"provider.notice"))Bt(un(L["provider.notice"]));Je.handleInfo(L);return}if(y.t!=="d")return;let C=y;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);re.setData(E,k,j,B),G(),Be();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(re.setData(E,k,j,B),L.id===D)ge.updateThreadMeta(L),G(),de.setState(!0,L.state==="working");Be();break}case"thread.removed":{let L=String(C.id??"");k=k.filter((P)=>P.id!==L),re.setData(E,k,j,B),Be();break}case"entry":{if(C.thread===D&&C.entry)ge.upsertEntry(C.entry);break}case"text":{if(C.thread===D)ge.appendLiveText(String(C.entry??""),String(C.append??""),Number(C.at??Date.now()));break}case"turn":{if(C.thread===D){let L=String(C.state??"idle");de.setState(!0,L==="working"),Ce(D,K)}Be();break}case"btw":{if(C.thread===D)ge.showBtw(String(C.q??""),String(C.a??""));break}case"unanswered":{if(C.thread===D)ge.setUnanswered(C.unanswered??null);break}case"theme":{if(typeof C.theme==="string")gs(C.theme);break}case"home":{if(it=C.home??null,re.setHome(it),Oe.isOpen())Oe.refresh();break}default:break}}),window.addEventListener("keydown",(y)=>{let C=y.key.toLowerCase();if((y.ctrlKey||y.metaKey)&&(C==="k"||y.shiftKey&&C==="p"))if(y.preventDefault(),Ge.isOpen())Ge.close();else Ge.open();else if(y.key==="Escape"){if(Ge.isOpen())Ge.close();else if(We.isOpen())We.escape();else if(Oe.isOpen())Oe.close();else if(ge.closePlanRevise());else if(Je.isOpen())Je.closePanel()}}),I.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",fs);else fs(); diff --git a/web/dist/assets/pair.js b/web/dist/assets/pair.js index c2a7d581e5..db0d012865 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.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","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","model.col.agent":"Agent","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:","secret.you":"You","settings.lang":"Language","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.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","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","model.col.agent":"Agente","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:","secret.you":"Tú","settings.lang":"Idioma","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.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":"分割表示には基板と回路図が必要です","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":"ピン留めを解除","model.col.agent":"エージェント","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":"返信先:","secret.you":"あなた","settings.lang":"言語","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]]],F=new Uint8Array(512),_=new Uint8Array(256);{let a=1;for(let t=0;t<255;t++)if(F[t]=a,_[a]=t,a<<=1,a&256)a^=285;for(let t=255;t<512;t++)F[t]=F[t-255]}function J(a,t){return a===0||t===0?0:F[_[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,j]=s,w=d-u*f,g=[],E=(e,i)=>{for(let n=i-1;n>=0;n--)g.push(e>>>n&1)};E(4,4),E(t.length,8);for(let e of t)E(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-(S&7)&1,S++;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 D=c("common.copy","Copy");P.textContent=D,P.addEventListener("click",()=>{navigator.clipboard?.writeText(o).then(()=>{P.textContent=c("web.clone.copied","Copied"),window.setTimeout(()=>{P.textContent=D},1200)}).catch(()=>{})}),x.append(v,y,P);let z=document.createDocumentFragment();z.appendChild(x);let K=X(o);if(K){let G=document.createElement("div");G.className="bp-pair-qr",G.setAttribute("data-testid","pair-qr"),G.appendChild(K),z.appendChild(G)}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,E,C,p),a.appendChild(t);let A=null,b=null,N=null,S=0,I=0,R=150,e=1000;function i(){if(S++,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"),E.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=I-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!==S)return;if(I>0&&Date.now()>=I){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!==S)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!==S)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!==S)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!==S)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 D=c("web.pair.failed","Pairing request failed ({status})",{status:o.status});try{let z=await o.json();if(z.error)D=z.error}catch{}if(o.status===429)D=c("web.pair.ratelimited","Too many pairing attempts. Wait a moment and try again.");n(D,!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();I=x.expiresAt?x.expiresAt<10000000000?x.expiresAt*1000:x.expiresAt:y+(x.expiresIn?x.expiresIn*1000:120000),i();let P=S;e=1000,R=x.pollMs&&x.pollMs>=100?x.pollMs:150,M.textContent=re(v),f.classList.add("bp-hidden"),E.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(); +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","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","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.lang":"Language","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","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","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.lang":"Idioma","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":"分割表示には基板と回路図が必要です","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":"エージェント","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.lang":"言語","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]]],F=new Uint8Array(512),_=new Uint8Array(256);{let a=1;for(let t=0;t<255;t++)if(F[t]=a,_[a]=t,a<<=1,a&256)a^=285;for(let t=255;t<512;t++)F[t]=F[t-255]}function J(a,t){return a===0||t===0?0:F[_[a]+_[t]]}function ne(a){let t=new Uint8Array([1]);for(let s=0;s{let m=e-o*n;return Math.ceil((12+t.length*8)/8)<=m});if(!s)return null;let[r,d,u,f,j]=s,w=d-u*f,g=[],N=(e,o)=>{for(let n=o-1;n>=0;n--)g.push(e>>>n&1)};N(4,4),N(t.length,8);for(let e of t)N(e,8);for(let e=0;e<4&&g.length{if(e<0||o<0||e>=p||o>=p)return;H[e*p+o]=n?1:0,A[e*p+o]=1},E=(e,o)=>{for(let n=-1;n<=7;n++)for(let m=-1;m<=7;m++){let k=e+n,l=o+m,i=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,i)}};E(0,0),E(0,p-7),E(p-7,0);for(let e=8;e=1;e-=2){if(e===6)e=5;let o=(e+1&2)===0;for(let n=0;n>>3]>>>7-(S&7)&1,S++;let i=(m+l&1)===0?h^1:h;H[m*p+l]=i}}}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=ie(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 i=h.startsWith("https://")?h:`https://${h}`;if(!i.startsWith("https://")||i.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=i,y.setAttribute("data-testid","pair-address");let P=document.createElement("button");P.type="button",P.className="bp-pair-copy";let D=c("common.copy","Copy");P.textContent=D,P.addEventListener("click",()=>{navigator.clipboard?.writeText(i).then(()=>{P.textContent=c("web.clone.copied","Copied"),window.setTimeout(()=>{P.textContent=D},1200)}).catch(()=>{})}),x.append(v,y,P);let z=document.createDocumentFragment();z.appendChild(x);let K=X(i);if(K){let G=document.createElement("div");G.className="bp-pair-qr",G.setAttribute("data-testid","pair-qr"),G.appendChild(K),z.appendChild(G)}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,N,C,p),a.appendChild(t);let A=null,b=null,E=null,S=0,I=0,R=150,e=1000;function o(){if(S++,E)E.abort(),E=null;if(A!==null)window.clearTimeout(A),A=null;if(b!==null)window.clearInterval(b),b=null}function n(l="",h=!1){o(),f.classList.remove("bp-hidden"),N.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=I-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!==S)return;if(I>0&&Date.now()>=I){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let h=new AbortController;E=h;try{let i=await fetch("/auth/web/poll",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:"{}",signal:h.signal});if(l!==S)return;if(e=1000,i.status===202){A=window.setTimeout(()=>{k(l)},150);return}if(i.status===200||i.status===204){let v={};if(i.status===200)try{v=await i.json()}catch{}if(l!==S)return;let y=(v.state||v.status||"").toLowerCase();if(i.status===204||v.approved===!0||y==="approved"||y==="ok"){o(),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(i.status===429){let v=Number(i.headers.get("Retry-After")||"5"),y=Math.max(2000,(Number.isFinite(v)?v:5)*1000);A=window.setTimeout(()=>{k(l)},y);return}if(i.status===401||i.status===403||i.status===404||i.status===410){let v="";try{let y=await i.json();v=(y.state||y.status||y.error||"").toLowerCase()}catch{}if(l!==S)return;if(v==="denied"||v==="rejected"||i.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!==S)return;let i=e;e=Math.min(1e4,Math.round(e*1.8)),A=window.setTimeout(()=>{k(l)},i)}finally{if(E===h)E=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 i=await fetch("/auth/web/request",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:h})});if(!i.ok){let D=c("web.pair.failed","Pairing request failed ({status})",{status:i.status});try{let z=await i.json();if(z.error)D=z.error}catch{}if(i.status===429)D=c("web.pair.ratelimited","Too many pairing attempts. Wait a moment and try again.");n(D,!0);return}let x=await i.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();I=x.expiresAt?x.expiresAt<10000000000?x.expiresAt*1000:x.expiresAt:y+(x.expiresIn?x.expiresIn*1000:120000),o();let P=S;e=1000,R=x.pollMs&&x.pollMs>=100?x.pollMs:150,M.textContent=re(v),f.classList.add("bp-hidden"),N.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/assets/style.css b/web/dist/assets/style.css index bc519082e0..dc300045fd 100644 --- a/web/dist/assets/style.css +++ b/web/dist/assets/style.css @@ -334,15 +334,148 @@ button.primary.stop { .bp-side-add:hover { color: var(--text); border-color: var(--faint); } .bp-side-section-row { display: flex; align-items: center; justify-content: space-between; } .bp-side-sec-plus { font-size: 13px; font-weight: 400; color: var(--faint); } -.bp-side-list { flex: 1; overflow-y: auto; padding: 6px 0; } +.bp-side-list { flex: 1; overflow-y: auto; padding: 4px 0 8px; } .bp-side-empty { padding: 12px 14px; color: var(--dim); font-size: 12px; } + +/* ---- Sticky Crew Band (Bub + Bots + Rooms, never scrolls away) ---- */ +.bp-crew-band { + flex-shrink: 0; + display: flex; + flex-direction: column; + gap: 5px; + padding: 5px 10px 6px; + border-bottom: 1px solid var(--rule); + background: var(--bg); +} +.bp-crew-uber { + display: flex; + align-items: center; + gap: 7px; + width: 100%; + padding: 3px 5px; + background: transparent; + border: 1px solid transparent; + border-left: 2px solid transparent; + color: var(--text); + text-align: left; + cursor: pointer; +} +.bp-crew-uber:hover { background: var(--raise); } +.bp-crew-uber.active { background: var(--panel); border-left-color: var(--accent); } +.bp-crew-uber-avatar { + width: 22px; + height: 22px; + flex-shrink: 0; + display: inline-flex; + align-items: center; + justify-content: center; + background: var(--panel); + border: 1px solid var(--line); + color: var(--accent); +} +.bp-crew-uber-avatar.bp-mood-work { border-color: var(--accent); } +.bp-crew-uber-avatar.bp-mood-wait { border-color: var(--bad); } +.bp-crew-uber-meta { + flex: 1; + min-width: 0; + display: flex; + align-items: baseline; + gap: 6px; + overflow: hidden; +} +.bp-crew-uber-name { font-size: 13px; font-weight: 600; color: var(--text); white-space: nowrap; } +.bp-crew-uber-note { + font-size: 11px; + color: var(--faint); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.bp-crew-uber-note.bp-mood-work { color: var(--accent); } +.bp-crew-uber-note.bp-mood-wait { color: var(--bad); } + +.bp-crew-bots { + display: flex; + align-items: center; + gap: 6px; + padding: 0 2px; +} +.bp-crew-lbl { + font-size: 9px; + font-weight: 600; + letter-spacing: 0.08em; + color: var(--faint); + flex-shrink: 0; +} +.bp-crew-bot-tiles { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 4px; + min-width: 0; +} +.bp-crew-bot-tile { + position: relative; + width: 22px; + height: 22px; + padding: 0; + display: inline-flex; + align-items: center; + justify-content: center; + background: var(--panel); + border: 1px solid var(--line); + color: var(--bot-c, var(--text)); + font-size: 9.5px; + font-weight: 700; + letter-spacing: -0.02em; + cursor: pointer; +} +.bp-crew-bot-tile:hover { background: var(--raise); border-color: var(--faint); } +.bp-crew-bot-tile.active { border-color: var(--accent); background: var(--raise); } +.bp-crew-bot-tile.bp-mood-work { border-color: var(--accent); } +.bp-crew-bot-tile.bp-mood-wait { border-color: var(--bad); } +.bp-crew-bot-wait { + position: absolute; + top: -2px; + right: -2px; + width: 6px; + height: 6px; + background: var(--bad); +} +.bp-crew-add { color: var(--dim); font-size: 13px; font-weight: 400; } +.bp-crew-add:hover { color: var(--text); } + +.bp-crew-rooms { + display: flex; + flex-wrap: wrap; + gap: 4px; + padding: 0 2px; +} +.bp-crew-room-chip { + display: inline-flex; + align-items: center; + gap: 3px; + padding: 1px 5px; + font-size: 10.5px; + line-height: 1.3; + background: var(--panel); + border: 1px solid var(--line); + color: var(--text); + cursor: pointer; + max-width: 100%; +} +.bp-crew-room-chip:hover { background: var(--raise); border-color: var(--faint); } +.bp-crew-room-cnt { font-size: 9.5px; color: var(--faint); margin-left: 1px; } + .bp-side-section-head { - padding: 10px 12px 4px; + padding: 7px 12px 2px; font-size: 10px; font-weight: 600; color: var(--faint); letter-spacing: 0.08em; } +.bp-head-needs { color: var(--bad); } +.bp-head-running { color: var(--accent); } .bp-side-section-toggle { display: block; width: 100%; @@ -352,13 +485,30 @@ button.primary.stop { cursor: pointer; } .bp-side-section-toggle:hover { color: var(--text); } -.bp-proj-group { margin-bottom: 4px; } +.bp-proj-filter { + display: flex; + gap: 4px; + padding: 3px 12px 5px; +} +.bp-proj-filter-btn { + background: transparent; + border: 1px solid var(--line); + color: var(--dim); + font-size: 10px; + padding: 1px 7px; + cursor: pointer; +} +.bp-proj-filter-btn:hover { color: var(--text); border-color: var(--faint); } +.bp-proj-filter-btn.active { background: var(--panel); color: var(--text); border-color: var(--accent); } + +.bp-proj-group { margin-bottom: 2px; } .bp-proj-head { display: flex; align-items: center; - padding: 4px 8px 4px 14px; + padding: 3px 8px 3px 12px; gap: 4px; } +.bp-proj-head:hover { background: var(--raise); } .bp-proj-toggle { flex: 1; min-width: 0; @@ -371,20 +521,192 @@ button.primary.stop { text-align: left; color: var(--text); font-weight: 500; + cursor: pointer; } .bp-proj-toggle:hover { color: var(--accent); } .bp-folder-icon { flex-shrink: 0; color: var(--ok); } .bp-proj-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.bp-proj-add { font-size: 15px; line-height: 1; padding: 2px 6px; color: var(--dim); } +.bp-proj-meta { + display: inline-flex; + align-items: center; + gap: 4px; + flex-shrink: 0; +} +.bp-proj-badge-need { + background: var(--bad); + color: var(--on-accent); + font-size: 10px; + font-weight: 700; + padding: 0 4px; + line-height: 15px; +} +.bp-proj-badge-run { + color: var(--accent); + font-size: 10px; + font-weight: 600; + padding: 0 2px; +} +.bp-pin-icon { color: var(--faint); flex-shrink: 0; } +.bp-proj-acts { + display: inline-flex; + align-items: center; + gap: 2px; + flex-shrink: 0; +} +button.bp-proj-quick { + display: none; + align-items: center; + justify-content: center; + padding: 2px 3px; + color: var(--dim); + background: transparent; + border: 0; + cursor: pointer; +} +.bp-proj-head:hover button.bp-proj-quick, +.bp-proj-head:focus-within button.bp-proj-quick { display: inline-flex; } +button.bp-proj-quick:hover { color: var(--accent); } +.bp-proj-add { + font-size: 14px; + line-height: 1; + padding: 1px 4px; + color: var(--dim); + opacity: 0.4; +} +.bp-proj-head:hover .bp-proj-add, +.bp-proj-head:focus-within .bp-proj-add { opacity: 1; color: var(--text); } .bp-thread-row { display: flex; align-items: center; - gap: 7px; - padding: 5px 10px 5px 22px; + gap: 6px; + padding: 3px 10px 3px 14px; cursor: pointer; border-left: 2px solid transparent; } +.bp-thread-row.bp-inbox-row { + padding: 4px 10px 4px 12px; + align-items: stretch; +} +.bp-inbox-main { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 2px; +} +.bp-inbox-top { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; +} +.bp-inbox-meta { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; +} +.bp-inbox-proj { + flex: 1; + min-width: 0; + font-size: 10.5px; + color: var(--dim); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +/* Explicit scannable icon+word status pills (replacing cryptic tiny dots) */ +.bp-status-pill { + display: inline-flex; + align-items: center; + gap: 3px; + padding: 0 5px; + height: 16px; + font-size: 10px; + font-weight: 600; + line-height: 1; + letter-spacing: 0.01em; + white-space: nowrap; + flex-shrink: 0; + border: 1px solid transparent; +} +.bp-pill-bad { + background: var(--bad); + color: var(--on-accent); + border-color: var(--bad); +} +.bp-pill-bad-out { + background: transparent; + color: var(--bad); + border-color: var(--bad); +} +.bp-pill-run { + background: color-mix(in srgb, var(--accent) 16%, transparent); + color: var(--accent); + border-color: color-mix(in srgb, var(--accent) 45%, transparent); +} +.bp-pill-wait { + background: color-mix(in srgb, var(--warn, #e5a93c) 16%, transparent); + color: var(--warn, #e5a93c); + border-color: color-mix(in srgb, var(--warn, #e5a93c) 45%, transparent); +} +.bp-pill-ok { + background: color-mix(in srgb, var(--ok) 15%, transparent); + color: var(--ok); + border-color: color-mix(in srgb, var(--ok) 40%, transparent); +} +.bp-pill-dim { + background: var(--panel); + color: var(--dim); + border-color: var(--line); +} + +.bp-row-acts { + display: none; + align-items: center; + gap: 3px; + flex-shrink: 0; +} +.bp-thread-row:hover .bp-row-acts, +.bp-thread-row:focus-within .bp-row-acts { display: inline-flex; } +.bp-row-act-btn { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 1px 4px; + height: 18px; + background: var(--panel); + border: 1px solid var(--line); + color: var(--dim); + font-size: 10px; + cursor: pointer; +} +.bp-row-act-btn:hover { color: var(--text); border-color: var(--faint); } +.bp-settle-btn:hover { color: var(--ok); border-color: var(--ok); } +.bp-snooze-btn:hover { color: var(--accent); border-color: var(--accent); } +.bp-wake-btn { padding: 0 6px; font-weight: 600; } + +.bp-snooze-bar { + display: flex; + align-items: center; + gap: 4px; + padding: 3px 10px 5px 14px; + font-size: 10.5px; + background: var(--panel); + border-bottom: 1px solid var(--line); +} +.bp-snooze-bar.nested { padding-left: 34px; } +.bp-snooze-opt { + background: var(--bg); + border: 1px solid var(--line); + color: var(--text); + font-size: 10px; + padding: 1px 6px; + cursor: pointer; +} +.bp-snooze-opt:hover { border-color: var(--accent); color: var(--accent); } .bp-thread-row.nested { padding-left: 34px; } .bp-thread-row:hover { background: var(--raise); } .bp-thread-row.active { background: var(--panel); border-left-color: var(--accent); } @@ -397,18 +719,36 @@ button.primary.stop { flex-shrink: 0; } .bp-dot { width: 6px; height: 6px; border-radius: 50%; flex-shrink: 0; } +.bp-dot-sq { border-radius: 0; } .bp-dot-work { background: var(--st-work); } +.bp-dot-wait { background: var(--warn, #e5a93c); } .bp-dot-done { background: var(--st-done); } .bp-dot-need { background: var(--st-need); } +.bp-dot-hollow { background: transparent !important; border: 1.5px solid var(--st-need); box-sizing: border-box; } .bp-dot-idle { background: var(--st-idle); } .bp-thread-title { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text); } .bp-thread-age { font-size: 11px; color: var(--faint); flex-shrink: 0; } +.bp-settle-btn { + display: none; + align-items: center; + justify-content: center; + padding: 2px 4px; + background: var(--panel); + border: 1px solid var(--line); + color: var(--dim); + cursor: pointer; + flex-shrink: 0; +} +.bp-thread-row:hover .bp-settle-btn, +.bp-thread-row:focus-within .bp-settle-btn { display: inline-flex; } +.bp-settle-btn:hover { color: var(--ok); border-color: var(--ok); } .bp-badge-need { background: var(--bad); color: var(--on-accent); font-size: 10px; font-weight: 700; padding: 1px 5px; + flex-shrink: 0; } .bp-need { display: flex; align-items: center; gap: 6px; padding: 0 10px 5px 35px; } .bp-need.nested { padding-left: 47px; } diff --git a/web/dist/manifest.json b/web/dist/manifest.json index 0d370b320d..ef348e11f5 100644 --- a/web/dist/manifest.json +++ b/web/dist/manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "totalAssetGzipBytes": 204945, + "totalAssetGzipBytes": 208816, "styleTokensSha256": "a4fed1b1c7bc676acc328907343eb5dcf87e426383d05617c632e48c0c3f2b80", "i18nKeys": [ "agy.signout", @@ -9,6 +9,7 @@ "approval.dismiss", "approval.implement", "ask.plan", + "bots.new", "bots.rooms", "bots.tab.browser", "common.cancel", @@ -158,7 +159,9 @@ "ios.hub.address.field", "menu.pin", "menu.settle", + "menu.snooze", "menu.unpin", + "menu.wake", "model.col.agent", "notify.settled", "palette.archive", @@ -178,6 +181,7 @@ "reply.action", "reply.cancel", "reply.to", + "rooms.new", "secret.you", "settings.lang", "sheet.rename", @@ -274,10 +278,10 @@ "web.settings.providers", "web.settings.providers.browser" ], - "i18nSubsetSha256": "1e3903ee550528a5ebc0c6b57a5b20c6f882fb39bdb7d47c0859cc9fad28658c", + "i18nSubsetSha256": "793a000eb9d84d3f5a9b55032d5594e3be3404de25114af9144e4d39c6d4a810", "inputs": { "web/src/addproject.ts": "06a7ff3e13cd78d993ebca7f638d5d623da06c0099186ad534bae8f184dbe44f", - "web/src/app.ts": "9cd9a49cc844b2fd48e5026c02abb59e6b358fd04405812cf0ecc62c031cf497", + "web/src/app.ts": "4114b0fb1d9dd7e47db8222471213a64a9b60529c388196f0c79d08f15ca39c8", "web/src/chat.ts": "27730f5adfcbb51eecf2f3a7cbd75562c964105dbb6a131697898977432c7892", "web/src/clone-model.ts": "d265df49436e14f415bbeb2a271ffa3552f9163be62bdc0158cecc10c3cdae45", "web/src/composer.ts": "f351b271d59ae560ae57360a8a301fc7df7d4d3adbe2c8933577fd7201399dc0", @@ -298,8 +302,8 @@ "web/src/qr.ts": "04b634557884b8f512a7b03ad9638c1c15a299ffaea0103d1bdeec6338d9b9d3", "web/src/rail.ts": "5fb391094992578cb6f54d35d53559951a584c43fcfc2ee6f4f2cc3897acfe46", "web/src/settings.ts": "4ec089580e4d2f04fb28462cb49cc164893c114af154d849c21ad5448a520433", - "web/src/shell.css": "a029915be277456b83f1cb11f2cae2db131294fb469bd535e9c14764fbc73762", - "web/src/sidebar.ts": "0c326c895375f8a2718ec424b07ca59006d7bc0938f05fe8e3e231ffb6af375f", + "web/src/shell.css": "ab269695b4c8486dfbbf54ad7372944da2b8d39fcd00ae58a7829f1d79ff69d7", + "web/src/sidebar.ts": "cc22668cddd8d039389fdd9637141c840d6ab8985de06a4268bb536d3a9588c1", "web/src/swarm-need.ts": "503bbf5ffe0389f068847571c792321b0ad5c8d26a18c73b8e41c0a8989e227f", "web/src/thread-context.ts": "b9fbd5b3ef0b1357b5a4444a1e9a0ac0606afe1c8a5377c4777752e918af0ac2", "web/src/viewers/browser-input.ts": "2be7672b8bfaded19f385ef56196793b9125130bffee7ac70afd493a3a91a9ab", @@ -327,9 +331,9 @@ }, "outputs": { "assets/app.js": { - "bytes": 346991, - "gzipBytes": 97681, - "sha256": "c6179c60edbcfad8f39144b4fcc09d57ffbf6ddef039b22f55d18acc751a2889" + "bytes": 357939, + "gzipBytes": 100335, + "sha256": "4744062db05b0ef354adacf4f312e3da4821574a4757373cf3479d035499e853" }, "assets/favicon-light.svg": { "bytes": 1207, @@ -347,14 +351,14 @@ "sha256": "123b6a27f255d339b505c8fd83609674f0bddf9b46c0e907fce23befa96b1eec" }, "assets/pair.js": { - "bytes": 53636, - "gzipBytes": 16213, - "sha256": "790192a8e58e5806615ed6ffeeb521e812bb44aaeca6e4e51c00f048a86f3cc7" + "bytes": 53857, + "gzipBytes": 16286, + "sha256": "98b8a10c361338be615496f81432ad026af087e7fffa6b85f5165a7e87fc3aa7" }, "assets/style.css": { - "bytes": 73359, - "gzipBytes": 12752, - "sha256": "93c3d1c33c2955966d5323f10950331c2c69e78c1ca65c70142c1fa1324867ad" + "bytes": 81620, + "gzipBytes": 13896, + "sha256": "5f5158b755ac3ac0646f7d6d7c5ebd5906a0e57170bd0ebbd190ae6097ec1257" }, "assets/terminal.js": { "bytes": 296616, diff --git a/web/src/app.ts b/web/src/app.ts index 01afa32957..354a51d747 100644 --- a/web/src/app.ts +++ b/web/src/app.ts @@ -322,7 +322,25 @@ function mountApp(): void { }, onNewThread: (projectId) => { void createThread(projectId); }, onSelectBot: (bot) => { void openThread(bot.thread); }, + onQuickOpenViewer: (projectId, kind) => { + const existing = threads.find((th) => th.project === projectId && !th.archived && !th.swarm); + const go = async (): Promise => { + if (existing) await openThread(existing.id); + else await createThread(projectId); + if (selectedThreadId) { + activeRailKind = kind; + rail.setActive(kind); + viewerController?.open(kind, selectedThreadId); + } + }; + void go(); + }, onThreadAct: (id, action) => { void runThreadAct(id, action); }, + onSnoozeRow: (value) => { + void hub.rpc("sidebar.act", { action: "row-snooze", value }) + .then(() => refreshSections()) + .catch(() => {}); + }, onToggleSection: (toggle) => { if (openSectionFolds.has(toggle)) openSectionFolds.delete(toggle); else openSectionFolds.add(toggle); diff --git a/web/src/shell.css b/web/src/shell.css index f458a0ce50..ea478a936b 100644 --- a/web/src/shell.css +++ b/web/src/shell.css @@ -241,15 +241,148 @@ button.primary.stop { .bp-side-add:hover { color: var(--text); border-color: var(--faint); } .bp-side-section-row { display: flex; align-items: center; justify-content: space-between; } .bp-side-sec-plus { font-size: 13px; font-weight: 400; color: var(--faint); } -.bp-side-list { flex: 1; overflow-y: auto; padding: 6px 0; } +.bp-side-list { flex: 1; overflow-y: auto; padding: 4px 0 8px; } .bp-side-empty { padding: 12px 14px; color: var(--dim); font-size: 12px; } + +/* ---- Sticky Crew Band (Bub + Bots + Rooms, never scrolls away) ---- */ +.bp-crew-band { + flex-shrink: 0; + display: flex; + flex-direction: column; + gap: 5px; + padding: 5px 10px 6px; + border-bottom: 1px solid var(--rule); + background: var(--bg); +} +.bp-crew-uber { + display: flex; + align-items: center; + gap: 7px; + width: 100%; + padding: 3px 5px; + background: transparent; + border: 1px solid transparent; + border-left: 2px solid transparent; + color: var(--text); + text-align: left; + cursor: pointer; +} +.bp-crew-uber:hover { background: var(--raise); } +.bp-crew-uber.active { background: var(--panel); border-left-color: var(--accent); } +.bp-crew-uber-avatar { + width: 22px; + height: 22px; + flex-shrink: 0; + display: inline-flex; + align-items: center; + justify-content: center; + background: var(--panel); + border: 1px solid var(--line); + color: var(--accent); +} +.bp-crew-uber-avatar.bp-mood-work { border-color: var(--accent); } +.bp-crew-uber-avatar.bp-mood-wait { border-color: var(--bad); } +.bp-crew-uber-meta { + flex: 1; + min-width: 0; + display: flex; + align-items: baseline; + gap: 6px; + overflow: hidden; +} +.bp-crew-uber-name { font-size: 13px; font-weight: 600; color: var(--text); white-space: nowrap; } +.bp-crew-uber-note { + font-size: 11px; + color: var(--faint); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.bp-crew-uber-note.bp-mood-work { color: var(--accent); } +.bp-crew-uber-note.bp-mood-wait { color: var(--bad); } + +.bp-crew-bots { + display: flex; + align-items: center; + gap: 6px; + padding: 0 2px; +} +.bp-crew-lbl { + font-size: 9px; + font-weight: 600; + letter-spacing: 0.08em; + color: var(--faint); + flex-shrink: 0; +} +.bp-crew-bot-tiles { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 4px; + min-width: 0; +} +.bp-crew-bot-tile { + position: relative; + width: 22px; + height: 22px; + padding: 0; + display: inline-flex; + align-items: center; + justify-content: center; + background: var(--panel); + border: 1px solid var(--line); + color: var(--bot-c, var(--text)); + font-size: 9.5px; + font-weight: 700; + letter-spacing: -0.02em; + cursor: pointer; +} +.bp-crew-bot-tile:hover { background: var(--raise); border-color: var(--faint); } +.bp-crew-bot-tile.active { border-color: var(--accent); background: var(--raise); } +.bp-crew-bot-tile.bp-mood-work { border-color: var(--accent); } +.bp-crew-bot-tile.bp-mood-wait { border-color: var(--bad); } +.bp-crew-bot-wait { + position: absolute; + top: -2px; + right: -2px; + width: 6px; + height: 6px; + background: var(--bad); +} +.bp-crew-add { color: var(--dim); font-size: 13px; font-weight: 400; } +.bp-crew-add:hover { color: var(--text); } + +.bp-crew-rooms { + display: flex; + flex-wrap: wrap; + gap: 4px; + padding: 0 2px; +} +.bp-crew-room-chip { + display: inline-flex; + align-items: center; + gap: 3px; + padding: 1px 5px; + font-size: 10.5px; + line-height: 1.3; + background: var(--panel); + border: 1px solid var(--line); + color: var(--text); + cursor: pointer; + max-width: 100%; +} +.bp-crew-room-chip:hover { background: var(--raise); border-color: var(--faint); } +.bp-crew-room-cnt { font-size: 9.5px; color: var(--faint); margin-left: 1px; } + .bp-side-section-head { - padding: 10px 12px 4px; + padding: 7px 12px 2px; font-size: 10px; font-weight: 600; color: var(--faint); letter-spacing: 0.08em; } +.bp-head-needs { color: var(--bad); } +.bp-head-running { color: var(--accent); } .bp-side-section-toggle { display: block; width: 100%; @@ -259,13 +392,30 @@ button.primary.stop { cursor: pointer; } .bp-side-section-toggle:hover { color: var(--text); } -.bp-proj-group { margin-bottom: 4px; } +.bp-proj-filter { + display: flex; + gap: 4px; + padding: 3px 12px 5px; +} +.bp-proj-filter-btn { + background: transparent; + border: 1px solid var(--line); + color: var(--dim); + font-size: 10px; + padding: 1px 7px; + cursor: pointer; +} +.bp-proj-filter-btn:hover { color: var(--text); border-color: var(--faint); } +.bp-proj-filter-btn.active { background: var(--panel); color: var(--text); border-color: var(--accent); } + +.bp-proj-group { margin-bottom: 2px; } .bp-proj-head { display: flex; align-items: center; - padding: 4px 8px 4px 14px; + padding: 3px 8px 3px 12px; gap: 4px; } +.bp-proj-head:hover { background: var(--raise); } .bp-proj-toggle { flex: 1; min-width: 0; @@ -278,20 +428,192 @@ button.primary.stop { text-align: left; color: var(--text); font-weight: 500; + cursor: pointer; } .bp-proj-toggle:hover { color: var(--accent); } .bp-folder-icon { flex-shrink: 0; color: var(--ok); } .bp-proj-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.bp-proj-add { font-size: 15px; line-height: 1; padding: 2px 6px; color: var(--dim); } +.bp-proj-meta { + display: inline-flex; + align-items: center; + gap: 4px; + flex-shrink: 0; +} +.bp-proj-badge-need { + background: var(--bad); + color: var(--on-accent); + font-size: 10px; + font-weight: 700; + padding: 0 4px; + line-height: 15px; +} +.bp-proj-badge-run { + color: var(--accent); + font-size: 10px; + font-weight: 600; + padding: 0 2px; +} +.bp-pin-icon { color: var(--faint); flex-shrink: 0; } +.bp-proj-acts { + display: inline-flex; + align-items: center; + gap: 2px; + flex-shrink: 0; +} +button.bp-proj-quick { + display: none; + align-items: center; + justify-content: center; + padding: 2px 3px; + color: var(--dim); + background: transparent; + border: 0; + cursor: pointer; +} +.bp-proj-head:hover button.bp-proj-quick, +.bp-proj-head:focus-within button.bp-proj-quick { display: inline-flex; } +button.bp-proj-quick:hover { color: var(--accent); } +.bp-proj-add { + font-size: 14px; + line-height: 1; + padding: 1px 4px; + color: var(--dim); + opacity: 0.4; +} +.bp-proj-head:hover .bp-proj-add, +.bp-proj-head:focus-within .bp-proj-add { opacity: 1; color: var(--text); } .bp-thread-row { display: flex; align-items: center; - gap: 7px; - padding: 5px 10px 5px 22px; + gap: 6px; + padding: 3px 10px 3px 14px; cursor: pointer; border-left: 2px solid transparent; } +.bp-thread-row.bp-inbox-row { + padding: 4px 10px 4px 12px; + align-items: stretch; +} +.bp-inbox-main { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 2px; +} +.bp-inbox-top { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; +} +.bp-inbox-meta { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; +} +.bp-inbox-proj { + flex: 1; + min-width: 0; + font-size: 10.5px; + color: var(--dim); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +/* Explicit scannable icon+word status pills (replacing cryptic tiny dots) */ +.bp-status-pill { + display: inline-flex; + align-items: center; + gap: 3px; + padding: 0 5px; + height: 16px; + font-size: 10px; + font-weight: 600; + line-height: 1; + letter-spacing: 0.01em; + white-space: nowrap; + flex-shrink: 0; + border: 1px solid transparent; +} +.bp-pill-bad { + background: var(--bad); + color: var(--on-accent); + border-color: var(--bad); +} +.bp-pill-bad-out { + background: transparent; + color: var(--bad); + border-color: var(--bad); +} +.bp-pill-run { + background: color-mix(in srgb, var(--accent) 16%, transparent); + color: var(--accent); + border-color: color-mix(in srgb, var(--accent) 45%, transparent); +} +.bp-pill-wait { + background: color-mix(in srgb, var(--warn, #e5a93c) 16%, transparent); + color: var(--warn, #e5a93c); + border-color: color-mix(in srgb, var(--warn, #e5a93c) 45%, transparent); +} +.bp-pill-ok { + background: color-mix(in srgb, var(--ok) 15%, transparent); + color: var(--ok); + border-color: color-mix(in srgb, var(--ok) 40%, transparent); +} +.bp-pill-dim { + background: var(--panel); + color: var(--dim); + border-color: var(--line); +} + +.bp-row-acts { + display: none; + align-items: center; + gap: 3px; + flex-shrink: 0; +} +.bp-thread-row:hover .bp-row-acts, +.bp-thread-row:focus-within .bp-row-acts { display: inline-flex; } +.bp-row-act-btn { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 1px 4px; + height: 18px; + background: var(--panel); + border: 1px solid var(--line); + color: var(--dim); + font-size: 10px; + cursor: pointer; +} +.bp-row-act-btn:hover { color: var(--text); border-color: var(--faint); } +.bp-settle-btn:hover { color: var(--ok); border-color: var(--ok); } +.bp-snooze-btn:hover { color: var(--accent); border-color: var(--accent); } +.bp-wake-btn { padding: 0 6px; font-weight: 600; } + +.bp-snooze-bar { + display: flex; + align-items: center; + gap: 4px; + padding: 3px 10px 5px 14px; + font-size: 10.5px; + background: var(--panel); + border-bottom: 1px solid var(--line); +} +.bp-snooze-bar.nested { padding-left: 34px; } +.bp-snooze-opt { + background: var(--bg); + border: 1px solid var(--line); + color: var(--text); + font-size: 10px; + padding: 1px 6px; + cursor: pointer; +} +.bp-snooze-opt:hover { border-color: var(--accent); color: var(--accent); } .bp-thread-row.nested { padding-left: 34px; } .bp-thread-row:hover { background: var(--raise); } .bp-thread-row.active { background: var(--panel); border-left-color: var(--accent); } @@ -304,18 +626,36 @@ button.primary.stop { flex-shrink: 0; } .bp-dot { width: 6px; height: 6px; border-radius: 50%; flex-shrink: 0; } +.bp-dot-sq { border-radius: 0; } .bp-dot-work { background: var(--st-work); } +.bp-dot-wait { background: var(--warn, #e5a93c); } .bp-dot-done { background: var(--st-done); } .bp-dot-need { background: var(--st-need); } +.bp-dot-hollow { background: transparent !important; border: 1.5px solid var(--st-need); box-sizing: border-box; } .bp-dot-idle { background: var(--st-idle); } .bp-thread-title { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text); } .bp-thread-age { font-size: 11px; color: var(--faint); flex-shrink: 0; } +.bp-settle-btn { + display: none; + align-items: center; + justify-content: center; + padding: 2px 4px; + background: var(--panel); + border: 1px solid var(--line); + color: var(--dim); + cursor: pointer; + flex-shrink: 0; +} +.bp-thread-row:hover .bp-settle-btn, +.bp-thread-row:focus-within .bp-settle-btn { display: inline-flex; } +.bp-settle-btn:hover { color: var(--ok); border-color: var(--ok); } .bp-badge-need { background: var(--bad); color: var(--on-accent); font-size: 10px; font-weight: 700; padding: 1px 5px; + flex-shrink: 0; } .bp-need { display: flex; align-items: center; gap: 6px; padding: 0 10px 5px 35px; } .bp-need.nested { padding-left: 47px; } diff --git a/web/src/sidebar.ts b/web/src/sidebar.ts index 488bea4811..82594ea86a 100644 --- a/web/src/sidebar.ts +++ b/web/src/sidebar.ts @@ -1,7 +1,11 @@ -// Left sidebar matching GPUI native-chat.png: -// "This computer" header, "Search projects" input, ACTIVE section with folder icons -// and indented thread rows with status dots + relative age, BOTS & ROOMS sections, -// and bottom-left Connected status footer. +// Left sidebar: Crew / Inbox / Bench layout matching GPUI: +// - Top header ("This computer" + search + quick add) +// - Sticky Crew band (never scrolls): Uberbot (Bub), compact bot avatar strip, wrapping room chips +// - Scrollable Inbox (Needs you + Running + foldable Snoozed) with unmistakable icon+word status pills, +// project context, and hover 1-click Snooze (1h / Tomorrow / 1w) & Settle +// - Scrollable Bench (Pinned + Recent MRU projects with hw/sw icons, live badges, hover quick-open) +// - Foldable All projects (alphabetical, optional All/Boards/Code filter) & Quiet +// - Bottom Connected status footer import { t } from "./i18n"; import { needPress, parseNeed, type NeedAction } from "./swarm-need"; import type { HomeInfo } from "./ws"; @@ -54,11 +58,19 @@ export interface BotItem { thread: string; color?: string; uber?: boolean; + mood?: string; + note?: string; } export interface RoomItem { id: string; name: string; + members?: number; +} + +export interface SnoozeOption { + label: string; + value: string; } export interface SectionThreadRow { @@ -67,6 +79,10 @@ export interface SectionThreadRow { word?: string; say?: string; want?: string; + /** Explicit status pill word from hub (Approve, Input, Sign in, Failed, Stopped, Working, Waiting, Done). */ + label?: string; + /** Explicit status pill tone from hub (bad | run | wait | ok | ""). */ + tone?: string; status?: string; state?: string; ago?: string; @@ -77,6 +93,12 @@ export interface SectionThreadRow { off?: boolean; nav?: string; kind?: string; + /** Thread id for 1-click settle when eligible (hub `settle` field). */ + settle?: string; + /** Snooze duration choices when eligible (hub `snooze` field; send `row-snooze` with `value`). */ + snooze?: SnoozeOption[]; + /** Wake value for a snoozed row (`|off`, send `row-snooze`). */ + wake?: string; /** a swarm row's need (swarm-need.ts): null when nothing waits on the person */ need?: unknown; } @@ -89,6 +111,8 @@ export interface SectionProjectRow { css?: string; color?: string; pinned?: boolean; + hasBoard?: boolean; + hasSchematic?: boolean; threads?: SectionThreadRow[]; swarms?: SectionThreadRow[]; more?: number; @@ -116,7 +140,13 @@ export interface SidebarCallbacks { onSelectThread: (threadId: string) => void; onNewThread: (projectId: string) => void; onSelectBot: (bot: BotItem) => void; + onSelectRoom?: (room: RoomItem) => void; + onNewBot?: () => void; + onNewRoom?: () => void; + onQuickOpenViewer?: (projectId: string, kind: "board" | "schematic") => void; onThreadAct: (threadId: string, action: string) => void; + /** Snooze or wake a thread row (`row-snooze` action with hub-provided value). */ + onSnoozeRow?: (value: string) => void; onToggleSection?: (toggle: string) => void; onToggleProjectFold?: (projectKey: string) => void; onCollapseSidebar?: () => void; @@ -128,34 +158,129 @@ export interface SidebarCallbacks { onAddProject?: () => void; } +export interface StatusPill { + icon: string; + label: string; + tone: "bad" | "bad-out" | "run" | "wait" | "ok" | "dim"; +} + +/** Resolve an explicit, scannable icon+word status pill from hub `label`/`tone` or `word`/`want`. */ +export function statusPillOf(row: Pick): StatusPill | null { + if (row.wake) return { icon: "◷", label: "Snoozed", tone: "dim" }; + + const rawLabel = (row.label ?? "").trim(); + const rawTone = (row.tone ?? "").trim(); + if (rawLabel) { + const low = rawLabel.toLowerCase(); + const icon = + low === "approve" || low === "sign in" ? "!" : + low === "input" ? "?" : + low === "failed" || low === "stopped" ? "×" : + low === "working" || low === "running" ? "▸" : + low === "waiting" ? "◌" : + low === "done" ? "✓" : "•"; + const tone: StatusPill["tone"] = + rawTone === "bad" ? (low === "failed" || low === "stopped" ? "bad-out" : "bad") : + rawTone === "run" ? "run" : + rawTone === "wait" ? "wait" : + rawTone === "ok" ? "ok" : "dim"; + return { icon, label: rawLabel, tone }; + } + + const w = row.word || ""; + if (w === "needs") { + if (row.want === "approval") return { icon: "!", label: "Approve", tone: "bad" }; + if (row.want === "sign-in") return { icon: "!", label: "Sign in", tone: "bad" }; + return { icon: "?", label: "Input", tone: "bad" }; + } + if (w === "failed" || row.status === "failed" || row.state === "fail") return { icon: "×", label: "Failed", tone: "bad-out" }; + if (w === "cut" || w === "interrupted") return { icon: "×", label: "Stopped", tone: "bad-out" }; + if (w === "running" || row.status === "active" || row.status === "working" || row.state === "run") return { icon: "▸", label: "Working", tone: "run" }; + if (w === "monitoring" || w === "limit" || row.status === "waiting") return { icon: "◌", label: "Waiting", tone: "wait" }; + if (w === "done" || row.status === "finished") return { icon: "✓", label: "Done", tone: "ok" }; + return null; +} + const SVG_NS = "http://www.w3.org/2000/svg"; -function makeFolderIcon(): SVGSVGElement { +function makeSvgIcon(paths: string[], size = 14, className = ""): SVGSVGElement { const svg = document.createElementNS(SVG_NS, "svg"); svg.setAttribute("viewBox", "0 0 24 24"); - svg.setAttribute("width", "14"); - svg.setAttribute("height", "14"); + svg.setAttribute("width", String(size)); + svg.setAttribute("height", String(size)); svg.setAttribute("fill", "none"); svg.setAttribute("stroke", "currentColor"); svg.setAttribute("stroke-width", "1.75"); + svg.setAttribute("stroke-linecap", "square"); + svg.setAttribute("stroke-linejoin", "miter"); svg.setAttribute("aria-hidden", "true"); - svg.classList.add("bp-folder-icon"); - const p = document.createElementNS(SVG_NS, "path"); - p.setAttribute("d", "M3 6h6l2 2h10v11H3z"); - svg.appendChild(p); + if (className) svg.classList.add(...className.split(" ")); + for (const d of paths) { + const p = document.createElementNS(SVG_NS, "path"); + p.setAttribute("d", d); + svg.appendChild(p); + } return svg; } -function statusClassFromWords(status?: string, word?: string, state?: string, waiting?: number): string { - const s = status || word || state || ""; - if (s === "active" || s === "working" || s === "running" || s === "run") return "bp-dot-work"; - if (s === "finished" || s === "done") return "bp-dot-done"; - if (s === "waiting" || s === "asking" || s === "blocked" || s === "needs" || s === "failed" || s === "fail" || s === "cut" || s === "interrupted" || s === "limit" || s === "monitoring" || (waiting ?? 0) > 0) return "bp-dot-need"; - return "bp-dot-idle"; +function makeFolderIcon(): SVGSVGElement { + return makeSvgIcon(["M3 6h6l2 2h10v11H3z"], 14, "bp-folder-icon"); +} + +function makeBoardIcon(size = 14, className = "bp-folder-icon bp-hw-icon"): SVGSVGElement { + return makeSvgIcon( + [ + "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", + ], + size, + className, + ); +} + +function makeSchematicIcon(size = 13): SVGSVGElement { + return makeSvgIcon( + [ + "M6 6h12v12H6z", + "M9 2v4", + "M15 2v4", + "M9 18v4", + "M15 18v4", + "M2 9h4", + "M2 15h4", + "M18 9h4", + "M18 15h4", + ], + size, + ); } -function statusClass(th: ThreadItem): string { - return statusClassFromWords(th.status, undefined, th.state, th.waiting); +function makeCatGlyph(size = 15): SVGSVGElement { + return makeSvgIcon( + [ + "M4 10V4l4 3h8l4-3v6l-2 9H6z", + "M9 13h1", + "M14 13h1", + "M11 16h2", + ], + size, + "bp-cat-glyph", + ); +} + +function makeCheckIcon(size = 11): SVGSVGElement { + return makeSvgIcon(["M4 12l5 5 11-11"], size); +} + +function makeClockIcon(size = 11): SVGSVGElement { + return makeSvgIcon(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z", "M12 6v6l4 2"], size); +} + +function makePinIcon(size = 11): SVGSVGElement { + return makeSvgIcon(["M12 17v5", "M8 4h8l-1 5 3 3v2H6v-2l3-3z"], size, "bp-pin-icon"); } function formatAge(ts: number): string { @@ -168,15 +293,36 @@ function formatAge(ts: number): string { return `${Math.floor(diffSec / 86400)}d`; } +function botInitials(name: string): string { + const clean = name.replace(/^@/, "").trim(); + if (!clean) return "?"; + const parts = clean.split(/[\s_-]+/).filter(Boolean); + if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase(); + return clean.slice(0, 2).toUpperCase(); +} + +function moodClass(mood?: string): string { + if (mood === "wait" || mood === "error") return "bp-mood-wait"; + if (mood === "work" || mood === "talk") return "bp-mood-work"; + return "bp-mood-idle"; +} + +function rawThreadId(qid: string): string { + const idx = qid.lastIndexOf("|"); + return idx >= 0 ? qid.slice(idx + 1) : qid; +} + export class SidebarView { private el: HTMLElement; private hostLabel: HTMLElement; private homeBanner: HTMLElement; + private crewEl: HTMLElement; private filterInput: HTMLInputElement; private listEl: HTMLElement; private connEl: HTMLElement; private filterText = ""; - private showSettled = new Set(); + private allFilter: "all" | "hw" | "sw" = "all"; + private snoozeMenuRowId = ""; private collapsedProjects = new Set(); private addShown = false; @@ -223,7 +369,7 @@ export class SidebarView { this.filterInput = document.createElement("input"); this.filterInput.type = "search"; this.filterInput.className = "bp-input bp-side-search"; - const ph = t("sidebar.search.projects", "Search projects"); + const ph = t("sidebar.search.projects", "Search projects, threads…"); this.filterInput.placeholder = ph; this.filterInput.setAttribute("aria-label", ph); this.filterInput.setAttribute("data-testid", "sidebar-filter"); @@ -253,6 +399,11 @@ export class SidebarView { this.homeBanner.style.fontSize = "11px"; this.homeBanner.style.borderBottom = "1px solid var(--line, #2a2a2a)"; + // Sticky Crew band: Bub + Bots strip + Rooms strip (never scrolls away) + 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"); @@ -265,7 +416,7 @@ export class SidebarView { this.connEl.setAttribute("data-testid", "conn-status"); footer.appendChild(this.connEl); - this.el.append(hostRow, head, this.homeBanner, this.listEl, footer); + this.el.append(hostRow, head, this.homeBanner, this.crewEl, this.listEl, footer); } public setHome(home: HomeInfo | null): void { @@ -361,12 +512,154 @@ export class SidebarView { } public refreshLocale(): void { - const ph = t("sidebar.search.projects", "Search projects"); + const ph = t("sidebar.search.projects", "Search projects, threads…"); this.filterInput.placeholder = ph; this.filterInput.setAttribute("aria-label", ph); this.render(); } + private renderCrewBand(q: string): void { + const uber = this.bots.find((b) => b.uber); + const otherBots = this.bots.filter((b) => !b.uber && (!q || b.name.toLowerCase().includes(q))); + const rooms = this.rooms.filter((r) => !q || r.name.toLowerCase().includes(q)); + const showUber = Boolean(uber && (!q || uber.name.toLowerCase().includes(q))); + const hasBotsRow = otherBots.length > 0 || (Boolean(this.cb.onNewBot) && !q); + const hasRoomsRow = rooms.length > 0 || (Boolean(this.cb.onNewRoom) && !q); + + if (!showUber && !hasBotsRow && !hasRoomsRow) { + this.crewEl.classList.add("bp-hidden"); + this.crewEl.replaceChildren(); + return; + } + + const frag = document.createDocumentFragment(); + + if (showUber && uber) { + const row = document.createElement("button"); + row.type = "button"; + row.className = "bp-crew-uber" + (uber.thread === this.selectedThreadId ? " active" : ""); + row.setAttribute("data-testid", `crew-uber-${uber.id}`); + const avatar = document.createElement("span"); + avatar.className = `bp-crew-uber-avatar ${moodClass(uber.mood)}`; + if (uber.color) avatar.style.color = uber.color; + avatar.appendChild(makeCatGlyph(14)); + + const meta = document.createElement("span"); + meta.className = "bp-crew-uber-meta"; + const name = document.createElement("span"); + name.className = "bp-crew-uber-name"; + name.textContent = uber.name; + meta.appendChild(name); + if (uber.note) { + const note = document.createElement("span"); + note.className = `bp-crew-uber-note ${moodClass(uber.mood)}`; + note.textContent = uber.note; + meta.appendChild(note); + } + + row.append(avatar, meta); + if (uber.mood === "wait" || uber.mood === "error") { + const badge = document.createElement("span"); + badge.className = "bp-status-pill bp-pill-bad"; + badge.textContent = "? Input"; + row.appendChild(badge); + } + row.addEventListener("click", () => this.cb.onSelectBot(uber)); + frag.appendChild(row); + } + + if (hasBotsRow) { + const strip = document.createElement("div"); + strip.className = "bp-crew-bots"; + strip.setAttribute("data-testid", "crew-bots"); + + const lbl = document.createElement("span"); + lbl.className = "bp-crew-lbl"; + lbl.textContent = t("tour.title.bots", "Bots").toUpperCase(); + strip.appendChild(lbl); + + const tiles = document.createElement("div"); + tiles.className = "bp-crew-bot-tiles"; + for (const bot of otherBots) { + const tile = document.createElement("button"); + tile.type = "button"; + tile.className = `bp-crew-bot-tile ${moodClass(bot.mood)}` + (bot.thread === this.selectedThreadId ? " active" : ""); + tile.title = bot.note ? `@${bot.name} — ${bot.note}` : `@${bot.name}`; + tile.setAttribute("aria-label", `@${bot.name}`); + tile.setAttribute("data-testid", `crew-bot-${bot.id}`); + if (bot.color) tile.style.setProperty("--bot-c", bot.color); + + const init = document.createElement("span"); + init.className = "bp-crew-bot-init"; + init.textContent = botInitials(bot.name); + tile.appendChild(init); + + if (bot.mood === "wait" || bot.mood === "error") { + const waitDot = document.createElement("span"); + waitDot.className = "bp-crew-bot-wait"; + tile.appendChild(waitDot); + } + tile.addEventListener("click", () => this.cb.onSelectBot(bot)); + tiles.appendChild(tile); + } + if (this.cb.onNewBot && !q) { + const add = document.createElement("button"); + add.type = "button"; + add.className = "bp-crew-bot-tile bp-crew-add"; + add.textContent = "+"; + add.title = t("bots.new", "New bot"); + add.setAttribute("aria-label", t("bots.new", "New bot")); + add.setAttribute("data-testid", "crew-new-bot"); + add.addEventListener("click", () => this.cb.onNewBot?.()); + tiles.appendChild(add); + } + strip.appendChild(tiles); + frag.appendChild(strip); + } + + if (hasRoomsRow) { + const strip = document.createElement("div"); + strip.className = "bp-crew-rooms"; + strip.setAttribute("data-testid", "crew-rooms"); + for (const room of rooms) { + const chip = document.createElement("button"); + chip.type = "button"; + chip.className = "bp-crew-room-chip"; + chip.setAttribute("data-testid", `crew-room-${room.id}`); + const hash = document.createElement("span"); + hash.className = "bp-dim"; + hash.textContent = "#"; + const name = document.createElement("span"); + name.textContent = room.name; + chip.append(hash, name); + if (room.members !== undefined && room.members > 0) { + const cnt = document.createElement("span"); + cnt.className = "bp-crew-room-cnt"; + cnt.textContent = String(room.members); + chip.appendChild(cnt); + } + chip.title = room.members ? `#${room.name} (${room.members})` : `#${room.name}`; + chip.addEventListener("click", () => this.cb.onSelectRoom?.(room)); + strip.appendChild(chip); + } + if (this.cb.onNewRoom && !q) { + const add = document.createElement("button"); + add.type = "button"; + add.className = "bp-crew-room-chip bp-crew-add"; + add.textContent = "+"; + add.title = t("rooms.new", "New room"); + add.setAttribute("aria-label", t("rooms.new", "New room")); + add.setAttribute("data-testid", "crew-new-room"); + add.addEventListener("click", () => this.cb.onNewRoom?.()); + strip.appendChild(add); + } + frag.appendChild(strip); + } + + this.crewEl.classList.remove("bp-hidden"); + this.crewEl.replaceChildren(frag); + } + /** A projects heading with Add project's + at its right (the first projects heading only). */ private projectsHead(title: string): HTMLElement { const head = document.createElement("div"); @@ -395,89 +688,220 @@ export class SidebarView { return head; } - private renderSectionThreadRow(row: SectionThreadRow, showTreeBranch: boolean): HTMLElement { + private renderStatusPill(pill: StatusPill, say?: string): HTMLElement { + const el = document.createElement("span"); + el.className = `bp-status-pill bp-pill-${pill.tone}`; + el.textContent = `${pill.icon} ${pill.label}`; + if (say) el.title = say; + return el; + } + + private renderRowActions(row: SectionThreadRow): HTMLElement | null { + if (row.off) return null; + const hasSnooze = Array.isArray(row.snooze) && row.snooze.length > 0 && Boolean(this.cb.onSnoozeRow); + const hasWake = Boolean(row.wake) && Boolean(this.cb.onSnoozeRow); + const hasSettle = Boolean(row.settle); + if (!hasSnooze && !hasWake && !hasSettle) return null; + + const acts = document.createElement("span"); + acts.className = "bp-row-acts"; + + if (hasWake && row.wake) { + const wakeBtn = document.createElement("button"); + wakeBtn.type = "button"; + wakeBtn.className = "bp-row-act-btn bp-wake-btn"; + wakeBtn.textContent = t("menu.wake", "Wake"); + wakeBtn.title = t("menu.wake", "Wake snoozed thread"); + wakeBtn.setAttribute("data-testid", `wake-row-${row.id}`); + wakeBtn.addEventListener("click", (e) => { + e.stopPropagation(); + this.cb.onSnoozeRow?.(row.wake!); + }); + acts.appendChild(wakeBtn); + } + + if (hasSnooze && row.snooze) { + const snBtn = document.createElement("button"); + snBtn.type = "button"; + snBtn.className = "bp-row-act-btn bp-snooze-btn"; + snBtn.title = t("menu.snooze", "Snooze thread"); + snBtn.setAttribute("aria-label", t("menu.snooze", "Snooze thread")); + snBtn.setAttribute("data-testid", `snooze-row-${row.id}`); + snBtn.appendChild(makeClockIcon(11)); + snBtn.addEventListener("click", (e) => { + e.stopPropagation(); + this.snoozeMenuRowId = this.snoozeMenuRowId === row.id ? "" : row.id; + this.render(); + }); + acts.appendChild(snBtn); + } + + if (hasSettle && row.settle) { + const settleBtn = document.createElement("button"); + settleBtn.type = "button"; + settleBtn.className = "bp-row-act-btn bp-settle-btn"; + settleBtn.title = t("menu.settle", "Settle"); + settleBtn.setAttribute("aria-label", t("menu.settle", "Settle")); + settleBtn.setAttribute("data-testid", `settle-row-${row.id}`); + settleBtn.appendChild(makeCheckIcon(11)); + settleBtn.addEventListener("click", (e) => { + e.stopPropagation(); + this.cb.onThreadAct(rawThreadId(row.settle!), "settle"); + }); + acts.appendChild(settleBtn); + } + + return acts; + } + + private renderSectionThreadRow(row: SectionThreadRow, showTreeBranch: boolean, isInbox = false): HTMLElement { const el = document.createElement("div"); el.className = "bp-thread-row" + - (row.id === this.selectedThreadId ? " active" : "") + + (isInbox ? " bp-inbox-row" : "") + + (row.id === this.selectedThreadId || rawThreadId(row.id) === this.selectedThreadId ? " active" : "") + (row.off ? " bp-dim" : ""); el.setAttribute("data-thread-id", row.id); el.setAttribute("data-testid", `thread-row-${row.id}`); - if (showTreeBranch) { - const branch = document.createElement("span"); - branch.className = "bp-tree-branch"; - branch.setAttribute("aria-hidden", "true"); - el.appendChild(branch); - } + const pill = statusPillOf(row); + const acts = this.renderRowActions(row); + + if (isInbox) { + // 2-line Inbox row: + // Line 1: Full-width Title + hover Snooze/Wake/Settle actions + // Line 2: Explicit [Status Pill] + Project name + right-aligned age + const main = document.createElement("div"); + main.className = "bp-inbox-main"; + + const line1 = document.createElement("div"); + line1.className = "bp-inbox-top"; + const title = document.createElement("div"); + title.className = "bp-thread-title"; + title.textContent = row.title || "Untitled thread"; + line1.appendChild(title); + if (acts) line1.appendChild(acts); + + const line2 = document.createElement("div"); + line2.className = "bp-inbox-meta"; + if (pill) line2.appendChild(this.renderStatusPill(pill, row.say)); + if (row.project) { + const proj = document.createElement("span"); + proj.className = "bp-inbox-proj"; + proj.textContent = row.project; + line2.appendChild(proj); + } + if (row.ago) { + const age = document.createElement("span"); + age.className = "bp-thread-age"; + age.textContent = row.ago; + if (row.pinned) age.title = t("tools.pinned", "Pinned"); + line2.appendChild(age); + } + + main.append(line1, line2); + el.appendChild(main); + } else { + // Nested Bench project row: optional tree branch + explicit compact status pill + title + hover actions + age + if (showTreeBranch) { + const branch = document.createElement("span"); + branch.className = "bp-tree-branch"; + branch.setAttribute("aria-hidden", "true"); + el.appendChild(branch); + } + if (pill) el.appendChild(this.renderStatusPill(pill, row.say)); + + const title = document.createElement("div"); + title.className = "bp-thread-title"; + title.textContent = row.title || "Untitled thread"; + el.appendChild(title); + + if (acts) el.appendChild(acts); - const dot = document.createElement("span"); - dot.className = `bp-dot ${statusClassFromWords(row.status, row.word, row.state)}`; - - const title = document.createElement("div"); - title.className = "bp-thread-title"; - title.textContent = row.title || "Untitled thread"; - - el.append(dot, title); - - if (row.word === "needs") { - const badge = document.createElement("span"); - badge.className = "bp-badge-need"; - badge.textContent = row.want === "approval" ? "!" : "•"; - if (row.say) badge.title = row.say; - el.appendChild(badge); - } else if (row.ago) { - const age = document.createElement("span"); - age.className = "bp-thread-age"; - age.textContent = row.ago; - if (row.pinned) age.title = t("tools.pinned", "Pinned"); - el.appendChild(age); + if (row.ago) { + const age = document.createElement("span"); + age.className = "bp-thread-age"; + age.textContent = row.ago; + if (row.pinned) age.title = t("tools.pinned", "Pinned"); + el.appendChild(age); + } } const target = row.nav || row.id; if (!row.off && target && !target.startsWith("@room:")) { - el.addEventListener("click", () => this.cb.onSelectThread(target)); + el.addEventListener("click", () => this.cb.onSelectThread(rawThreadId(target))); } + + const showSnoozeBar = this.snoozeMenuRowId === row.id && Array.isArray(row.snooze) && row.snooze.length > 0; const need = row.kind === "swarm" ? parseNeed(row.need) : null; - if (!need) return el; - // a swarm's need: its line under the row and a button per action + if (!need && !showSnoozeBar) return el; + const wrap = document.createElement("div"); wrap.className = "bp-need-wrap"; - const line = document.createElement("div"); - line.className = "bp-need" + (showTreeBranch ? " nested" : "") + (row.off ? " bp-dim" : ""); - line.setAttribute("data-testid", `need-${row.id}`); - const text = document.createElement("span"); - text.className = "bp-need-line"; - text.textContent = need.line; - text.title = need.line; - line.appendChild(text); - for (const a of need.actions) { - if (!needPress(a, Boolean(this.cb.hasRoomView))) continue; - const b = document.createElement("button"); - b.type = "button"; - b.className = "bp-need-btn"; - b.textContent = a.label; - b.setAttribute("data-testid", `need-${a.act}-${row.id}`); - b.disabled = Boolean(row.off) || this.needBusy.has(row.id) || !this.cb.onNeedAct; - b.addEventListener("click", (e) => { - e.stopPropagation(); - const act = this.cb.onNeedAct; - if (!act) return; - this.needErr.delete(row.id); - this.needBusy.add(row.id); - this.render(); - act(a) - .catch((err: unknown) => { this.needErr.set(row.id, err instanceof Error ? err.message : String(err)); }) - .finally(() => { this.needBusy.delete(row.id); this.render(); }); - }); - line.appendChild(b); + wrap.appendChild(el); + + // Inline Snooze duration picker (1 hour · Tomorrow · 1 week) + if (showSnoozeBar && row.snooze) { + const bar = document.createElement("div"); + bar.className = "bp-snooze-bar" + (showTreeBranch ? " nested" : ""); + bar.setAttribute("data-testid", `snooze-bar-${row.id}`); + const lbl = document.createElement("span"); + lbl.className = "bp-dim"; + lbl.textContent = "Snooze:"; + bar.appendChild(lbl); + for (const opt of row.snooze) { + const b = document.createElement("button"); + b.type = "button"; + b.className = "bp-snooze-opt"; + b.textContent = opt.label; + b.addEventListener("click", (e) => { + e.stopPropagation(); + this.snoozeMenuRowId = ""; + this.cb.onSnoozeRow?.(opt.value); + this.render(); + }); + bar.appendChild(b); + } + wrap.appendChild(bar); } - wrap.append(el, line); - const err = this.needErr.get(row.id); - if (err) { - const e = document.createElement("div"); - e.className = "bp-need-err" + (showTreeBranch ? " nested" : ""); - e.textContent = err; - wrap.appendChild(e); + + if (need) { + const line = document.createElement("div"); + line.className = "bp-need" + (showTreeBranch ? " nested" : "") + (row.off ? " bp-dim" : ""); + line.setAttribute("data-testid", `need-${row.id}`); + const text = document.createElement("span"); + text.className = "bp-need-line"; + text.textContent = need.line; + text.title = need.line; + line.appendChild(text); + for (const a of need.actions) { + if (!needPress(a, Boolean(this.cb.hasRoomView))) continue; + const b = document.createElement("button"); + b.type = "button"; + b.className = "bp-need-btn"; + b.textContent = a.label; + b.setAttribute("data-testid", `need-${a.act}-${row.id}`); + b.disabled = Boolean(row.off) || this.needBusy.has(row.id) || !this.cb.onNeedAct; + b.addEventListener("click", (e) => { + e.stopPropagation(); + const act = this.cb.onNeedAct; + if (!act) return; + this.needErr.delete(row.id); + this.needBusy.add(row.id); + this.render(); + act(a) + .catch((err: unknown) => { this.needErr.set(row.id, err instanceof Error ? err.message : String(err)); }) + .finally(() => { this.needBusy.delete(row.id); this.render(); }); + }); + line.appendChild(b); + } + wrap.appendChild(line); + const err = this.needErr.get(row.id); + if (err) { + const e = document.createElement("div"); + e.className = "bp-need-err" + (showTreeBranch ? " nested" : ""); + e.textContent = err; + wrap.appendChild(e); + } } return wrap; } @@ -487,10 +911,16 @@ export class SidebarView { const listedThreadIds = new Set(); for (const sec of sections) { if (sec.kind === "threads") { - for (const r of sec.rows as SectionThreadRow[]) listedThreadIds.add(r.id); + for (const r of sec.rows as SectionThreadRow[]) { + listedThreadIds.add(r.id); + listedThreadIds.add(rawThreadId(r.id)); + } } else if (sec.kind === "projects") { for (const p of sec.rows as SectionProjectRow[]) { - for (const th of p.threads ?? []) listedThreadIds.add(th.id); + for (const th of p.threads ?? []) { + listedThreadIds.add(th.id); + listedThreadIds.add(rawThreadId(th.id)); + } } } } @@ -500,37 +930,59 @@ export class SidebarView { let anyProjectRows = false; for (const sec of sections) { - if (sec.kind === "projects" && sec.rows.length > 0) anyProjectRows = true; + if (sec.kind === "projects" && (sec.rows.length > 0 || (sec.count ?? 0) > 0)) anyProjectRows = true; } for (const sec of sections) { if (sec.kind === "bub") continue; if (sec.kind === "threads") { + const isFoldable = Boolean(sec.fold && sec.toggle); const rows = (sec.rows as SectionThreadRow[]).filter((r) => { if (!q) return true; return `${r.title} ${r.project ?? ""}`.toLowerCase().includes(q); }); - if (rows.length === 0) continue; + if (!isFoldable && rows.length === 0) continue; + if (isFoldable && q && rows.length === 0) continue; + if (isFoldable && !q && (sec.count ?? rows.length) === 0) continue; const secWrap = document.createElement("section"); - secWrap.className = "bp-side-section"; + secWrap.className = `bp-side-section bp-side-inbox bp-sec-${sec.id}`; secWrap.setAttribute("data-section-id", sec.id); - const head = document.createElement("div"); - head.className = "bp-side-section-head"; - head.textContent = sec.title.toUpperCase(); - secWrap.appendChild(head); + if (isFoldable) { + const headBtn = document.createElement("button"); + headBtn.type = "button"; + headBtn.className = "bp-side-section-head bp-side-section-toggle"; + const count = q ? rows.length : (sec.count ?? rows.length); + const arrow = sec.open || Boolean(q) ? "▾" : "▸"; + headBtn.textContent = `${arrow} ${sec.title.toUpperCase()} (${count})`; + if (sec.hint) headBtn.title = sec.hint; + headBtn.setAttribute("data-testid", `section-toggle-${sec.id}`); + headBtn.addEventListener("click", () => { + if (sec.toggle) this.cb.onToggleSection?.(sec.toggle); + }); + secWrap.appendChild(headBtn); + } else { + const head = document.createElement("div"); + head.className = "bp-side-section-head" + + (sec.id === "needs" ? " bp-head-needs" : sec.id === "running" ? " bp-head-running" : ""); + head.textContent = `${sec.title.toUpperCase()} ${rows.length}`; + secWrap.appendChild(head); + } - for (const r of rows) { - secWrap.appendChild(this.renderSectionThreadRow(r, false)); + if (!isFoldable || Boolean(sec.open) || Boolean(q)) { + for (const r of rows) { + secWrap.appendChild(this.renderSectionThreadRow(r, false, true)); + } } frag.appendChild(secWrap); continue; } if (sec.kind === "projects") { - const projRows = (sec.rows as SectionProjectRow[]).filter((p) => { + const rawRows = sec.rows as SectionProjectRow[]; + let projRows = rawRows.filter((p) => { if (!q) return true; if ((p.title || p.id).toLowerCase().includes(q)) return true; if ((p.threads ?? []).some((th) => th.title.toLowerCase().includes(q))) return true; @@ -543,17 +995,18 @@ export class SidebarView { if (!isFoldable && sec.id !== "active" && projRows.length === 0) continue; const secWrap = document.createElement("section"); - secWrap.className = "bp-side-section"; + secWrap.className = `bp-side-section bp-sec-${sec.id}`; secWrap.setAttribute("data-section-id", sec.id); if (isFoldable) { const headBtn = document.createElement("button"); headBtn.type = "button"; headBtn.className = "bp-side-section-head bp-side-section-toggle"; - const count = sec.count ?? projRows.length; - const arrow = sec.open ? "▾" : "▸"; - headBtn.textContent = `${sec.title.toUpperCase()} (${count}) ${arrow}`; + const count = q ? projRows.length : (sec.count ?? projRows.length); + const arrow = sec.open || Boolean(q) ? "▾" : "▸"; + headBtn.textContent = `${arrow} ${sec.title.toUpperCase()} (${count})`; if (sec.hint) headBtn.title = sec.hint; + headBtn.setAttribute("data-testid", `section-toggle-${sec.id}`); headBtn.addEventListener("click", () => { if (sec.toggle) this.cb.onToggleSection?.(sec.toggle); }); @@ -562,7 +1015,37 @@ export class SidebarView { secWrap.appendChild(this.projectsHead(sec.title.toUpperCase())); } - if (!isFoldable || sec.open || Boolean(q)) { + const isOpen = !isFoldable || Boolean(sec.open) || Boolean(q); + if (isOpen) { + if (sec.id === "all" && !q) { + const hasHw = rawRows.some((p) => p.hasBoard || p.hasSchematic); + const hasSw = rawRows.some((p) => !p.hasBoard && !p.hasSchematic); + if (hasHw && hasSw) { + const bar = document.createElement("div"); + bar.className = "bp-proj-filter"; + bar.setAttribute("data-testid", "all-projects-filter"); + const opts: Array<{ id: "all" | "hw" | "sw"; label: string }> = [ + { id: "all", label: "All" }, + { id: "hw", label: "Boards" }, + { id: "sw", label: "Code" }, + ]; + for (const opt of opts) { + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "bp-proj-filter-btn" + (this.allFilter === opt.id ? " active" : ""); + btn.textContent = opt.label; + btn.addEventListener("click", () => { + this.allFilter = opt.id; + this.render(); + }); + bar.appendChild(btn); + } + secWrap.appendChild(bar); + if (this.allFilter === "hw") projRows = projRows.filter((p) => p.hasBoard || p.hasSchematic); + else if (this.allFilter === "sw") projRows = projRows.filter((p) => !p.hasBoard && !p.hasSchematic); + } + } + if (sec.id === "active" && !anyProjectRows && !q) { const empty = document.createElement("div"); empty.className = "bp-side-empty"; @@ -572,7 +1055,7 @@ export class SidebarView { for (const proj of projRows) { const group = document.createElement("div"); - group.className = "bp-proj-group" + (proj.off ? " bp-dim" : ""); + group.className = "bp-proj-group" + (proj.off || sec.id === "quiet" ? " bp-dim" : ""); group.setAttribute("data-project-id", proj.id); if (proj.nav || proj.key) group.setAttribute("data-project-key", proj.nav || proj.key || ""); @@ -582,16 +1065,70 @@ export class SidebarView { const toggle = document.createElement("button"); toggle.type = "button"; toggle.className = "bp-proj-toggle"; - const folder = makeFolderIcon(); - if (proj.css) folder.style.color = proj.css; + const isHw = Boolean(proj.hasBoard || proj.hasSchematic); + const icon = isHw ? makeBoardIcon(14) : makeFolderIcon(); + if (proj.css) icon.style.color = proj.css; const nameSpan = document.createElement("span"); nameSpan.className = "bp-proj-name"; nameSpan.textContent = proj.title || proj.id; - toggle.append(folder, nameSpan); + toggle.append(icon, nameSpan); if (proj.fold === "project-fold" && proj.nav) { toggle.addEventListener("click", () => this.cb.onToggleProjectFold?.(proj.nav!)); } + const meta = document.createElement("div"); + meta.className = "bp-proj-meta"; + if ((proj.needsCount ?? 0) > 0) { + const nb = document.createElement("span"); + nb.className = "bp-proj-badge-need"; + nb.textContent = String(proj.needsCount); + nb.title = `${proj.needsCount} needing you`; + meta.appendChild(nb); + } + if ((proj.running ?? 0) > 0) { + const rb = document.createElement("span"); + rb.className = "bp-proj-badge-run"; + rb.textContent = String(proj.running); + rb.title = `${proj.running} running`; + meta.appendChild(rb); + } + if (proj.pinned && sec.id !== "pinned") { + meta.appendChild(makePinIcon(11)); + } + + const acts = document.createElement("div"); + acts.className = "bp-proj-acts"; + if (!proj.off && this.cb.onQuickOpenViewer) { + if (proj.hasBoard) { + const bBtn = document.createElement("button"); + bBtn.type = "button"; + bBtn.className = "bp-proj-quick"; + bBtn.title = t("viewer.board", "Open Board"); + bBtn.setAttribute("aria-label", `Open Board (${proj.title})`); + bBtn.setAttribute("data-testid", `quick-board-${proj.id}`); + bBtn.appendChild(makeBoardIcon(13, "")); + bBtn.addEventListener("click", (e) => { + e.stopPropagation(); + this.cb.onQuickOpenViewer?.(rawThreadId(proj.id), "board"); + }); + acts.appendChild(bBtn); + } + if (proj.hasSchematic) { + const sBtn = document.createElement("button"); + sBtn.type = "button"; + sBtn.className = "bp-proj-quick"; + sBtn.title = t("viewer.schematic", "Open Schematic"); + sBtn.setAttribute("aria-label", `Open Schematic (${proj.title})`); + sBtn.setAttribute("data-testid", `quick-sch-${proj.id}`); + sBtn.appendChild(makeSchematicIcon(13)); + sBtn.addEventListener("click", (e) => { + e.stopPropagation(); + this.cb.onQuickOpenViewer?.(rawThreadId(proj.id), "schematic"); + }); + acts.appendChild(sBtn); + } + } + const addBtn = document.createElement("button"); addBtn.type = "button"; addBtn.className = "icon bp-proj-add"; @@ -601,10 +1138,11 @@ export class SidebarView { if (proj.off) addBtn.disabled = true; addBtn.addEventListener("click", (e) => { e.stopPropagation(); - this.cb.onNewThread(proj.id); + this.cb.onNewThread(rawThreadId(proj.id)); }); + acts.appendChild(addBtn); - header.append(toggle, addBtn); + header.append(toggle, meta, acts); group.appendChild(header); if (!proj.folded || Boolean(q)) { @@ -617,12 +1155,9 @@ export class SidebarView { if (q && !projNameMatches && !th.title.toLowerCase().includes(q)) continue; group.appendChild(this.renderSectionThreadRow(th, true)); } - // Mirror GPUI's `on_show` rule (`sections.rs:340-341`): since `data/1` `sidebar.sections` - // passes `selected: ""`, keep the currently selected thread visible under its project - // without altering the order of hub-returned rows. if ( selectedMeta && - selectedMeta.project === proj.id && + selectedMeta.project === rawThreadId(proj.id) && !listedThreadIds.has(selectedMeta.id) && (!q || projNameMatches || selectedMeta.title.toLowerCase().includes(q)) ) { @@ -649,9 +1184,12 @@ export class SidebarView { public render(): void { this.addShown = false; - const frag = document.createDocumentFragment(); const q = this.filterText; + this.renderCrewBand(q); + + const frag = document.createDocumentFragment(); + if (this.sections !== null) { this.renderHubSections(frag, q); } else { @@ -667,7 +1205,7 @@ export class SidebarView { byProject.set(th.project, list); } - frag.appendChild(this.projectsHead("ACTIVE")); + frag.appendChild(this.projectsHead("RECENT")); if (this.projects.length === 0 && this.threads.length === 0) { const empty = document.createElement("div"); @@ -735,58 +1273,6 @@ export class SidebarView { } } - if (!q) { - const botSec = document.createElement("section"); - botSec.className = "bp-proj-group bp-bots-group"; - const botHead = document.createElement("div"); - botHead.className = "bp-side-section-head bp-side-section-row"; - const botLbl = document.createElement("span"); - botLbl.textContent = t("tour.title.bots", "Bots").toUpperCase(); - const botAdd = document.createElement("span"); - botAdd.className = "bp-side-sec-plus"; - botAdd.textContent = "+"; - botAdd.setAttribute("aria-hidden", "true"); - botHead.append(botLbl, botAdd); - botSec.appendChild(botHead); - for (const bot of this.bots) { - const row = document.createElement("div"); - row.className = "bp-thread-row" + (bot.thread === this.selectedThreadId ? " active" : ""); - const dot = document.createElement("span"); - dot.className = "bp-dot bp-dot-idle"; - if (bot.color) dot.style.backgroundColor = bot.color; - const name = document.createElement("div"); - name.className = "bp-thread-title"; - name.textContent = `@${bot.name}`; - row.append(dot, name); - row.addEventListener("click", () => this.cb.onSelectBot(bot)); - botSec.appendChild(row); - } - frag.appendChild(botSec); - - const roomSec = document.createElement("section"); - roomSec.className = "bp-proj-group"; - const roomHead = document.createElement("div"); - roomHead.className = "bp-side-section-head bp-side-section-row"; - const roomLbl = document.createElement("span"); - roomLbl.textContent = t("bots.rooms", "Rooms").toUpperCase(); - const roomAdd = document.createElement("span"); - roomAdd.className = "bp-side-sec-plus"; - roomAdd.textContent = "+"; - roomAdd.setAttribute("aria-hidden", "true"); - roomHead.append(roomLbl, roomAdd); - roomSec.appendChild(roomHead); - for (const room of this.rooms) { - const row = document.createElement("div"); - row.className = "bp-thread-row"; - const name = document.createElement("div"); - name.className = "bp-thread-title"; - name.textContent = `#${room.name}`; - row.appendChild(name); - roomSec.appendChild(row); - } - frag.appendChild(roomSec); - } - this.listEl.replaceChildren(frag); } } diff --git a/web/test/sidebar.test.ts b/web/test/sidebar.test.ts new file mode 100644 index 0000000000..c19f62aad9 --- /dev/null +++ b/web/test/sidebar.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, mock, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; + +mock.module("virtual:i18n", () => ({ CATALOGS: {} })); +const { statusPillOf } = await import("../src/sidebar"); + +const root = join(import.meta.dir, ".."); +const sidebarSrc = readFileSync(join(root, "src/sidebar.ts"), "utf8"); +const shellCss = readFileSync(join(root, "src/shell.css"), "utf8"); + +describe("SidebarView Crew / Inbox / Bench + Status Pills + Snooze", () => { + test("statusPillOf produces unmistakable icon+word pills from hub label/tone and word/want", () => { + expect(statusPillOf({ label: "Approve", tone: "bad" })).toEqual({ icon: "!", label: "Approve", tone: "bad" }); + expect(statusPillOf({ label: "Input", tone: "bad" })).toEqual({ icon: "?", label: "Input", tone: "bad" }); + expect(statusPillOf({ label: "Failed", tone: "bad" })).toEqual({ icon: "×", label: "Failed", tone: "bad-out" }); + expect(statusPillOf({ label: "Working", tone: "run" })).toEqual({ icon: "▸", label: "Working", tone: "run" }); + expect(statusPillOf({ label: "Waiting", tone: "wait" })).toEqual({ icon: "◌", label: "Waiting", tone: "wait" }); + expect(statusPillOf({ label: "Done", tone: "ok" })).toEqual({ icon: "✓", label: "Done", tone: "ok" }); + expect(statusPillOf({ wake: "t1|off" })).toEqual({ icon: "◷", label: "Snoozed", tone: "dim" }); + // Fallback without hub label/tone + expect(statusPillOf({ word: "needs", want: "question" })).toEqual({ icon: "?", label: "Input", tone: "bad" }); + expect(statusPillOf({ word: "running" })).toEqual({ icon: "▸", label: "Working", tone: "run" }); + expect(statusPillOf({ word: "done" })).toEqual({ icon: "✓", label: "Done", tone: "ok" }); + expect(statusPillOf({ word: "idle" })).toBeNull(); + }); + + test("Crew band is mounted outside scrollable list and never appended after projects", () => { + expect(sidebarSrc).toContain('this.crewEl.className = "bp-crew-band bp-hidden"'); + expect(sidebarSrc).toContain("this.el.append(hostRow, head, this.homeBanner, this.crewEl, this.listEl, footer)"); + expect(sidebarSrc).not.toContain("bp-bots-group"); + }); + + test("Supports Running + foldable Snoozed sections, hover Snooze/Wake/Settle, and hardware icons", () => { + expect(sidebarSrc).toContain('sec.id === "running"'); + expect(sidebarSrc).toContain("row.snooze"); + expect(sidebarSrc).toContain("row.wake"); + expect(sidebarSrc).toContain("this.cb.onSnoozeRow?.(opt.value)"); + expect(sidebarSrc).toContain("const hasSettle = Boolean(row.settle);"); + expect(sidebarSrc).toContain("proj.hasBoard || proj.hasSchematic"); + expect(sidebarSrc).toContain('data-testid", "all-projects-filter"'); + }); + + test("Quick-open hardware buttons stay hidden at rest and reveal on hover", () => { + expect(shellCss).toContain("button.bp-proj-quick {\n display: none;"); + expect(shellCss).toContain(".bp-proj-head:hover button.bp-proj-quick"); + expect(sidebarSrc).not.toContain('className = "icon bp-proj-quick"'); + }); +}); From 5180b29d79be6387cdf8006a6b51ac500490921e Mon Sep 17 00:00:00 2001 From: i2cjak Date: Mon, 23 Nov 2026 02:36:37 -0500 Subject: [PATCH 2/2] Sidebar: no visit mark for the chats with no project Co-Authored-By: Claude Fable 5.2 --- native/host/src/state/visible.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/host/src/state/visible.rs b/native/host/src/state/visible.rs index 4e5a9ddd25..261d7ccd30 100644 --- a/native/host/src/state/visible.rs +++ b/native/host/src/state/visible.rs @@ -130,7 +130,7 @@ pub fn look(st: &State, id: &str, now: u64) -> Vec { } /// A visit is written at most once in ten minutes for a project (`sidebar.visit.`): the bench orders by it, and a log line for /// every thread opened would be noise. -pub fn visit_due(st: &State, project: &str, now: u64) -> bool { !project.is_empty() && num(st, &format!("sidebar.visit.{project}")) + 600 <= now } +pub fn visit_due(st: &State, project: &str, now: u64) -> bool { !project.is_empty() && project != "scratch" /* sidebar::SCRATCH: the chats with no project */ && num(st, &format!("sidebar.visit.{project}")) + 600 <= now } /// Events a viewer's view.open of a thread adds for the bench (state/policy.rs `read`): the person was in its project now. pub fn visit(st: &State, id: &str, now: u64) -> Vec { let Some(t) = st.threads.get(id) else { return vec![] };